Search is not available for this dataset
text
string
meta
dict
/*************************************************************************** File : MyParser.h Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2006 by Ion Vasilief Email (use @ for *) : ion_vasilief*yahoo.fr Description : Parser class based on muParser ***************************************************************************/ /*************************************************************************** * * * 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 MYPARSER_H #define MYPARSER_H #include <muParser.h> #include <muParserDLL.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <qstringlist.h> using namespace mu; /*!\brief Mathematical parser class based on muParser. * * \section future Future Plans * Eliminate in favour of Script/ScriptingEnv. * This will allow you to use e.g. Python's global variables and functions everywhere. * Before this happens, a cleaner and more generic solution for accessing the current ScriptingEnv * should be implemented (maybe by making it a property of Project; see ApplicationWindow). */ class MyParser : public Parser { public: MyParser(); static QStringList functionsList(); static QString explainFunction(int index); static double bessel_J0(double x) { return gsl_sf_bessel_J0 (x); } static double bessel_J1(double x) { return gsl_sf_bessel_J1 (x); } static double bessel_Jn(double x, double n) { return gsl_sf_bessel_Jn ((int)n, x); } static double bessel_Y0(double x) { return gsl_sf_bessel_Y0 (x); } static double bessel_Y1(double x) { return gsl_sf_bessel_Y1 (x); } static double bessel_Yn(double x, double n) { return gsl_sf_bessel_Yn ((int)n, x); } static double beta(double a, double b) { return gsl_sf_beta (a, b); } static double erf(double x) { return gsl_sf_erf (x); } static double erfc(double x) { return gsl_sf_erfc (x); } static double erfz(double x) { return gsl_sf_erf_Z (x); } static double erfq(double x) { return gsl_sf_erf_Q (x); } static double gamma(double x) { return gsl_sf_gamma (x); } static double gammaln(double x) { return gsl_sf_lngamma (x); } static double hazard(double x) { return gsl_sf_hazard (x); } }; #endif
{ "alphanum_fraction": 0.5280309307, "avg_line_length": 30.175, "ext": "h", "hexsha": "b12e59975144b344bbfde40575818061c21924e4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": [ "IJG" ], "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_licenses": [ "IJG" ], "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_line_length": 98, "max_stars_count": 6, "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": [ "IJG" ], "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/MyParser.h", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "num_tokens": 785, "size": 3621 }
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* aslmirtime.h */ /*---------------------------------------------------------------------------*/ /* */ /* aslmirtime.h: Global includes and defines */ /* */ /* Copyright (C) 2011 Paul Kinchesh */ /* */ /* This file is part of aslmirtime. */ /* */ /* aslmirtime 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. */ /* */ /* aslmirtime 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 aslmirtime. If not, see <http://www.gnu.org/licenses/>. */ /* */ /*---------------------------------------------------------------------------*/ /* */ /*--------------------------------------------------------*/ /*---- Wrap the header to prevent multiple inclusions ----*/ /*--------------------------------------------------------*/ #ifndef _H_aslmirtime_H #define _H_aslmirtime_H /*----------------------------------*/ /*---- Include standard headers ----*/ /*----------------------------------*/ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <sys/param.h> #include <sys/stat.h> #include <stddef.h> #include <sys/time.h> /*-----------------------------*/ /*---- Include GSL Headers ----*/ /*-----------------------------*/ #include <gsl/gsl_multimin.h> /*-------------------------------------------*/ /*---- Make sure __FUNCTION__ is defined ----*/ /*-------------------------------------------*/ #ifndef __FUNCTION__ #define __FUNCTION__ __func__ #endif /*------------------------------------------------------*/ /*---- Floating point comparison macros (as in SGL) ----*/ /*------------------------------------------------------*/ /* EPSILON is the largest allowable deviation due to floating point storage */ #define EPSILON 1e-9 #define FP_LT(A,B) (((A)<(B)) && (fabs((A)-(B))>EPSILON)) /* A less than B */ #define FP_GT(A,B) (((A)>(B)) && (fabs((A)-(B))>EPSILON)) /* A greater than B */ #define FP_EQ(A,B) (fabs((A)-(B))<=EPSILON) /* A equal to B */ #define FP_NEQ(A,B) (!FP_EQ(A,B)) /* A not equal to B */ #define FP_GTE(A,B) (FP_GT(A,B) || FP_EQ(A,B)) /* A greater than or equal to B */ #define FP_LTE(A,B) (FP_LT(A,B) || FP_EQ(A,B)) /* A less than or equal to B */ /*---------------------------------------------------------------*/ /*---- So we can simply include aslmirtime.h in aslmirtime.c ----*/ /*---------------------------------------------------------------*/ #ifdef LOCAL #define EXTERN #else #define EXTERN extern #endif /*-----------------------------------*/ /*---- Functions in aslmirtime.c ----*/ /*-----------------------------------*/ double my_f (const gsl_vector *v, void *params); void my_df (const gsl_vector *v, void *params, gsl_vector *df); void my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *df); void getinput(double **pars,int argc,char *argv[]); int nomem(char *file,const char *function,int line); int usage_terminate(); /*----------------------------*/ /*---- End of header wrap ----*/ /*----------------------------*/ #endif
{ "alphanum_fraction": 0.4048573975, "avg_line_length": 42.3396226415, "ext": "h", "hexsha": "3cbaeac9f431aaef22db1616eb83176abb148376", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "timburrow/openvnmrj-source", "max_forks_repo_path": "src/aslmirtime/aslmirtime.h", "max_issues_count": 128, "max_issues_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "timburrow/openvnmrj-source", "max_issues_repo_path": "src/aslmirtime/aslmirtime.h", "max_line_length": 94, "max_stars_count": 32, "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_path": "src/aslmirtime/aslmirtime.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "num_tokens": 809, "size": 4488 }
/* Copyright [2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef MCAS_HSTORE_HEAP_MC_SHIM_H #define MCAS_HSTORE_HEAP_MC_SHIM_H #include <mm_plugin_itf.h> #include <ccpm/interfaces.h> /* ownership_callback, (IHeap_expandable, region_vector_t) */ #include <common/byte_span.h> #include <common/string_view.h> #include <gsl/span> #include <cstddef> /* size_t */ #include <functional> /* function */ struct heap_mc_shim : public ccpm::IHeap_expandable { private: MM_plugin_wrapper _mm; public: heap_mc_shim(common::string_view path, ccpm::persister *pe, gsl::span<common::byte_span> range, std::function<bool(const void *)> callee_owns); heap_mc_shim(common::string_view path, ccpm::persister *pe); heap_mc_shim(MM_plugin_wrapper &&pw); bool reconstitute( ccpm::region_span regions , ccpm::ownership_callback_t resolver , bool force_init ) override; status_t allocate(void * & ptr , std::size_t bytes , std::size_t alignment ) override; status_t free(void * & ptr , std::size_t bytes ) override; status_t remaining(std::size_t& out_size) const override; ccpm::region_vector_t get_regions() const override; void add_regions(ccpm::region_span regions) override; bool includes(const void *ptr) const override; bool is_crash_consistent() const; }; #endif
{ "alphanum_fraction": 0.7523287671, "avg_line_length": 28.515625, "ext": "h", "hexsha": "1504b3c5b4194cf5002921860d4c0afab4d42b05", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_line_length": 144, "max_stars_count": 60, "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_path": "src/components/store/hstore/src/heap_mc_shim.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 466, "size": 1825 }
#pragma once #include "Cesium3DTilesSelection/BoundingVolume.h" #include "Cesium3DTilesSelection/Library.h" #include "Cesium3DTilesSelection/Tile.h" #include "Cesium3DTilesSelection/TileContext.h" #include "Cesium3DTilesSelection/TileID.h" #include "Cesium3DTilesSelection/TileRefine.h" #include "Cesium3DTilesSelection/TilesetOptions.h" #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <memory> namespace Cesium3DTilesSelection { /** * @brief The information that is passed to a {@link TileContentLoader} to * create a {@link TileContentLoadResult}. * * For many types of tile content, only the `data` field is required. The other * members are used for content that can generate child tiles, like external * tilesets or composite tiles. These members are usually initialized from * the corresponding members of the {@link Tile} that the content belongs to. */ struct CESIUM3DTILESSELECTION_API TileContentLoadInput { /** * @brief Creates a new, uninitialized instance for the given tile. * * The `data`, `contentType` and `url` will have default values, * and have to be initialized before this instance is passed to * one of the loader functions. * * @param pLogger The logger that will be used * @param tile The {@link Tile} that the content belongs to */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger, const Tile& tile); /** * @brief Creates a new instance for the given tile. * * @param pLogger The logger that will be used * @param data The actual data that the tile content will be created from * @param contentType The content type, if the data was received via a * network response * @param url The URL that the data was loaded from * @param tile The {@link Tile} that the content belongs to */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger, const gsl::span<const std::byte>& data, const std::string& contentType, const std::string& url, const Tile& tile); /** * @brief Creates a new instance. * * For many types of tile content, only the `data` field is required. The * other parameters are used for content that can generate child tiles, like * external tilesets or composite tiles. * * @param pLogger The logger that will be used * @param data The actual data that the tile content will be created from * @param contentType The content type, if the data was received via a * network response * @param url The URL that the data was loaded from * @param tileID The {@link TileID} * @param tileBoundingVolume The tile {@link BoundingVolume} * @param tileContentBoundingVolume The tile content {@link BoundingVolume} * @param tileRefine The {@link TileRefine} strategy * @param tileGeometricError The geometric error of the tile * @param tileTransform The tile transform */ TileContentLoadInput( const std::shared_ptr<spdlog::logger> pLogger, const gsl::span<const std::byte>& data, const std::string& contentType, const std::string& url, const TileID& tileID, const BoundingVolume& tileBoundingVolume, const std::optional<BoundingVolume>& tileContentBoundingVolume, TileRefine tileRefine, double tileGeometricError, const glm::dmat4& tileTransform, const TilesetContentOptions& contentOptions); /** * @brief The logger that receives details of loading errors and warnings. */ std::shared_ptr<spdlog::logger> pLogger; /** * @brief The raw input data. * * The {@link TileContentFactory} will try to determine the type of the * data using the first four bytes (i.e. the "magic header"). If this * does not succeed, it will try to determine the type based on the * `contentType` field. */ gsl::span<const std::byte> data; /** * @brief The content type. * * If the data was obtained via a HTTP response, then this will be * the `Content-Type` of that response. The {@link TileContentFactory} * will try to interpret the data based on this content type. * * If the data was not directly obtained from an HTTP response, then * this may be the empty string. */ std::string contentType; /** * @brief The source URL. */ std::string url; /** * @brief The {@link TileID}. */ TileID tileID; /** * @brief The tile {@link BoundingVolume}. */ BoundingVolume tileBoundingVolume; /** * @brief Tile content {@link BoundingVolume}. */ std::optional<BoundingVolume> tileContentBoundingVolume; /** * @brief The {@link TileRefine}. */ TileRefine tileRefine; /** * @brief The geometric error. */ double tileGeometricError; /** * @brief The tile transform */ glm::dmat4 tileTransform; /** * @brief Options for parsing content and creating Gltf models. */ TilesetContentOptions contentOptions; }; } // namespace Cesium3DTilesSelection
{ "alphanum_fraction": 0.6995587645, "avg_line_length": 31.1625, "ext": "h", "hexsha": "a5ff7f8f2ef7c76616e8e18fc843d1b7022e42d0", "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": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "zrkcode/cesium-native", "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "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": "zrkcode/cesium-native", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "5265a65053542fe02928c272762c6b89fa2b29bb", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "zrkcode/cesium-native", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/TileContentLoadInput.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1247, "size": 4986 }
/* * 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. */ // The GSL extra library provides linear algebra functions using a // similar interface to the rest of the GSL library. #ifndef COMMON_C_MATH_GSL_LINALG_EXTRA_H_ #define COMMON_C_MATH_GSL_LINALG_EXTRA_H_ #include <stdint.h> #include <gsl/gsl_blas_types.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #ifdef __cplusplus extern "C" { #endif int32_t GslTriangularSolve(CBLAS_SIDE_t side, CBLAS_UPLO_t uplo, CBLAS_TRANSPOSE_t transpose, const gsl_matrix *T, const gsl_matrix *B, gsl_matrix *X); void GslTrapezoidalToTriangular(const gsl_matrix *R, gsl_matrix *T, gsl_vector *tau); void GslTrapezoidalToTriangularZTMat(const gsl_matrix *T, const gsl_vector *tau, const gsl_matrix *X, gsl_matrix *Zt_X); int32_t GslMatrixDivide(CBLAS_SIDE_t side, const gsl_matrix *A, const gsl_matrix *B, gsl_matrix *X); #ifdef __cplusplus } // extern "C" #endif #endif // COMMON_C_MATH_GSL_LINALG_EXTRA_H_
{ "alphanum_fraction": 0.7057761733, "avg_line_length": 34.625, "ext": "h", "hexsha": "fc8daaa0809ace0890f2c007630324f9b2535eba", "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": "common/c_math/gsl_linalg_extra.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": "common/c_math/gsl_linalg_extra.h", "max_line_length": 80, "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": "common/c_math/gsl_linalg_extra.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": 402, "size": 1662 }
#ifndef __GEMM_DRIVER_H #define __GEMM_DRIVER_H #include "util.h" #include <stddef.h> #include <stdlib.h> #include <string.h> #include <tuple> #include <algorithm> #include <assert.h> #include <iostream> #include <sstream> #include <vector> // openblas #include <cblas.h> #ifndef CEIL #define CEIL(value, divider) ( ((value)-1)/(divider)+1 ) #endif #ifndef CEIL_WRAP #define CEIL_WRAP(value, divider) ( CEIL((value), (divider)) * (divider) ) #endif typedef enum { LAYOUT_ROW_MAJOR = 0, LAYOUT_COL_MAJOR }layout_t; typedef enum { TRANS_NO_TRANS = 0, TRANS_TRANS, TRANS_CONJ_TRANS, TRANS_CONJ_NO_TRANS, }trans_t; typedef enum { IDENT_A_MATRIX = 0, IDENT_B_MATRIX }identifier_t; // cblas helper function static inline CBLAS_ORDER to_blas_layout(layout_t layout){ if(layout == LAYOUT_ROW_MAJOR) return CblasRowMajor; //if(layout == LAYOUT_COL_MAJOR) //TODO: validation return CblasColMajor; } // cblas helper function static inline CBLAS_TRANSPOSE to_blas_transpose(trans_t trans){ switch(trans){ case TRANS_NO_TRANS: return CblasNoTrans; case TRANS_TRANS: return CblasTrans; case TRANS_CONJ_TRANS: return CblasConjTrans; case TRANS_CONJ_NO_TRANS: return CblasConjNoTrans; default: return CblasConjNoTrans; } } static inline const char * to_layout_str(layout_t layout){ if(layout == LAYOUT_ROW_MAJOR) return "CblasRowMajor"; if(layout == LAYOUT_COL_MAJOR) return "CblasColMajor"; return "n/a major"; } static inline const char * to_trans_str(trans_t trans){ if(trans == TRANS_NO_TRANS) return "CblasNoTrans"; if(trans == TRANS_TRANS) return "CblasTrans"; if(trans == TRANS_CONJ_TRANS) return "CblasConjTrans"; if(trans == TRANS_CONJ_NO_TRANS) return "CblasConjNoTrans"; return "n/a trans"; } class gemm_context_t { public: // matrix descriptors layout_t layout; trans_t trans_a; trans_t trans_b; size_t m; size_t n; size_t k; size_t lda; size_t ldb; size_t ldc; double alpha; double beta; // size_t alignment; // used for alloc A/B/C, indeed not so useful // blocking parameters size_t mc; size_t nc; size_t kc; size_t mr; size_t nr; // hw parameters //size_t cpu_id; size_t l1_size; size_t l2_size; size_t l3_size; size_t tlb_entry_l1d; size_t cacheline_size; size_t page_size; std::vector<int> cpu_list; double frequency; // MHz bool cur_use_tuned {false}; // use tuned param from db or default, only a flag void serialize_layout_trans(std::ostream & os){ std::string al, bl, cl; if(layout == LAYOUT_ROW_MAJOR){ cl = "cr"; if(trans_a == TRANS_NO_TRANS || trans_a == TRANS_CONJ_NO_TRANS){ al = "ar"; }else{ al = "ac"; } if(trans_b == TRANS_NO_TRANS || trans_b == TRANS_CONJ_NO_TRANS){ bl = "br"; }else{ bl = "bc"; } }else{ cl = "cc"; if(trans_a == TRANS_NO_TRANS || trans_a == TRANS_CONJ_NO_TRANS){ al = "ac"; }else{ al = "ar"; } if(trans_b == TRANS_NO_TRANS || trans_b == TRANS_CONJ_NO_TRANS){ bl = "bc"; }else{ bl = "br"; } } os<<al<<"-"<<bl<<"-"<<cl; } void deserialize_layout_trans(const std::istream & is){ std::string al, bl, cl; std::stringstream tmp; tmp << is.rdbuf(); std::string s( tmp.str() ); al = s.substr(0, 2); bl = s.substr(3, 2); cl = s.substr(6, 2); if(cl == "cr"){ layout = LAYOUT_ROW_MAJOR; if(al == "ar"){ trans_a = TRANS_NO_TRANS; }else{ trans_a = TRANS_TRANS; } if(bl == "br"){ trans_b = TRANS_NO_TRANS; }else{ trans_b = TRANS_TRANS; } }else if(cl == "cc"){ layout = LAYOUT_COL_MAJOR; if(al == "ar"){ trans_a = TRANS_TRANS; }else{ trans_a = TRANS_NO_TRANS; } if(bl == "br"){ trans_b = TRANS_TRANS; }else{ trans_b = TRANS_NO_TRANS; } } } // TODO: fix more param void serialize(std::ostream & os){ serialize_layout_trans(os); os<<"-"<<m<<"-"<<n<<"-"<<k; } void serialize(std::string & str){ std::ostringstream oss; serialize(oss); str = oss.str(); } void deserialize(std::istream & is){ char _d; deserialize_layout_trans(is); is>>_d>>m>>_d>>n>>_d>>k; } void deserialize(std::string & str){ std::istringstream iss; iss.str(str); deserialize(iss); } }; // https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm class matrix_elem_t { public: size_t operator() (size_t row, size_t col, size_t ldim, layout_t layout, trans_t trans){ if(layout == LAYOUT_ROW_MAJOR){ if(trans == TRANS_NO_TRANS || trans == TRANS_CONJ_NO_TRANS){ assert(ldim>=col); return row * ldim; } else{ assert(ldim>=row); return col * ldim; } }else{ if(trans == TRANS_NO_TRANS || trans == TRANS_CONJ_NO_TRANS){ assert(ldim>=row); return col * ldim; } else{ assert(ldim>=col); return row * ldim; } } } }; template<typename T> class matrix_t{ public: matrix_t(size_t row_, size_t col_, size_t ldim_, layout_t layout_, trans_t trans_, size_t alignment_) { this->row = row_; this->col = col_; this->ldim = ldim_; // TODO ldim should be multiple of alignment! this->layout = layout_; this->trans = trans_; this->alignment = alignment_; size_t elements = matrix_elem_t()(row_, col_, ldim_, layout_, trans_); this->data = (T *) __aligned_malloc(sizeof(T)*elements, alignment_); rand_vector(this->data, elements); } ~matrix_t(){ if(data) __aligned_free(this->data); } size_t dtype_size() const { return sizeof(T); } void __copy(const matrix_t<T> & rhs){ this->row = rhs.row; this->col = rhs.col; this->ldim = rhs.ldim; this->layout = rhs.layout; this->trans = rhs.trans; this->alignment = rhs.alignment; size_t elements = matrix_elem_t()(rhs.row, rhs.col, rhs.ldim, rhs.layout, rhs.trans); this->data = (T *) __aligned_malloc(sizeof(T)*elements, alignment); memcpy(this->data, rhs.data, sizeof(T)*elements); } matrix_t(const matrix_t<T> & rhs){ __copy(rhs); } matrix_t& operator =(const matrix_t<T> & rhs){ __copy(rhs); return *this; } T *data {nullptr}; size_t row; size_t col; size_t ldim; // leading dimension layout_t layout; trans_t trans; size_t alignment; }; //typedef matrix_t<float> matrix_fp32_t; //typedef matrix_t<double> matrix_fp64_t; #endif
{ "alphanum_fraction": 0.5374740664, "avg_line_length": 25.3684210526, "ext": "h", "hexsha": "3e186976e50bd0c47e18e158500e2d0ea779fc61", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-11-09T03:48:31.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-19T14:36:21.000Z", "max_forks_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carlushuang/gemm_opt", "max_forks_repo_path": "src/gemm_driver.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_issues_repo_issues_event_max_datetime": "2020-01-22T11:37:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-18T16:42:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carlushuang/gemm_opt", "max_issues_repo_path": "src/gemm_driver.h", "max_line_length": 93, "max_stars_count": 47, "max_stars_repo_head_hexsha": "810b23ddd3c3da53d98398537154ed1f36ce4c29", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "carlushuang/gemm_opt", "max_stars_repo_path": "src/gemm_driver.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:09:25.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-19T07:14:15.000Z", "num_tokens": 1903, "size": 7712 }
/* Copyright (C) 2004-2007 M. Oliveira, F. Nogueira This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <string_f.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_odeiv.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_multiroots.h> /* This file contains interface routines that allow Fortran 90/95 routines to call GSL routines. The names of these routines are compiler dependent: Fortran 90/95 compilers have different name-mangling schemes. For a description of the routines please refer to the GSL documentation. */ /* Error Handling */ void FC_FUNC_(gsl_strerror, GSL_STRERROR) (int *err, STR_F_TYPE res STR_ARG1) { char *c; c = gsl_strerror(*err); /*TO_F_STR1(c, res);!!not too sure what this does*/ } /* Mathematical Functions */ double FC_FUNC_(gsl_asinh, GSL_ASINH) (const double *x) { return gsl_asinh(*x); } /* Special Functions */ double FC_FUNC_(gsl_sf_bessel_knu_scaled, GSL_SF_BESSEL_KNU_SCALED) (double *nu, double *x) { return gsl_sf_bessel_Knu_scaled(*nu,*x); } /* Vectors and Matrices */ void FC_FUNC_(gsl_vector_alloc, GSL_VECTOR_ALLOC) (int *n, void **v) { *v = (void*) gsl_vector_alloc (*n); } void FC_FUNC_(gsl_vector_free, GSL_VECTOR_FREE) (void **v) { gsl_vector_free ((gsl_vector *)(*v)); } double FC_FUNC_(gsl_vector_get, GSL_VECTOR_GET) (void **v, int *i) { return gsl_vector_get ((gsl_vector *)(*v), *i); } void FC_FUNC_(gsl_vector_set, GSL_VECTOR_SET) (void **v, int *i, double *x) { gsl_vector_set ((gsl_vector *)(*v), *i, *x); } void FC_FUNC_(gsl_matrix_alloc, GSL_MATRIX_ALLOC) (int *n1, int *n2, void **m) { *m = (void*) gsl_matrix_alloc (*n1, *n2); } void FC_FUNC_(gsl_matrix_calloc, GSL_MATRIX_CALLOC) (int *n1, int *n2, void **m) { *m = (void*) gsl_matrix_calloc (*n1, *n2); } void FC_FUNC_(gsl_matrix_free, GSL_MATRIX_FREE) (void **m) { gsl_matrix_free ((gsl_matrix *)(*m)); } double FC_FUNC_(gsl_matrix_get, GSL_MATRIX_GET) (void **m, int *i, int *j) { return gsl_matrix_get ((gsl_matrix *)(*m), *i, *j); } void FC_FUNC_(gsl_matrix_set, GSL_MATRIX_SET) (void **m, int *i, int *j, double *x) { gsl_matrix_set ((gsl_matrix *)(*m), *i, *j, *x); } /* Permutations */ void FC_FUNC_(gsl_permutation_alloc, GSL_PERMUTATION_ALLOC) (int *n, void **p) { *p = (void*) gsl_permutation_alloc (*n); } void FC_FUNC_(gsl_permutation_free, GSL_PERMUTATION_FREE) (void **p) { gsl_permutation_free ((gsl_permutation *)(*p)); } /* Linear Algebra */ int FC_FUNC_(gsl_linalg_lu_decomp, GSL_LINALG_LU_DECOMP) (void **m, void **p, int *signum) { int s,ierr; ierr = gsl_linalg_LU_decomp ((gsl_matrix *)(*m) , (gsl_permutation *)(*p), &s); *signum = s; return (ierr); } int FC_FUNC_(gsl_linalg_lu_invert, GSL_LINALG_LU_INVERT) (void **LU, void **p, void **inverse) { return gsl_linalg_LU_invert ((gsl_matrix *)(*LU),(gsl_permutation *)(*p), (gsl_matrix *)(*inverse)); } int FC_FUNC_(gsl_linalg_lu_solve, GSL_LINALG_LU_SOLVE) (void **LU, void **p, void **b, void **x) { return gsl_linalg_LU_solve ((gsl_matrix *)(*LU), (gsl_permutation *)(*p), (gsl_vector *)(*b), (gsl_vector *)(*x)); } /* Ordinary Differential Equations */ void FC_FUNC_(gsl_odeiv_step_alloc, GSL_ODEIV_STEP_ALLOC) (const int *stepping_func, const int *dim, void **stp) { /* WARNING: This routine has a small modification: the user needs to pass an integer in order to choose the stepping function instead of a variable of type gsl_odeiv_step_type. */ switch(*stepping_func) { case 1 : // Embedded 2nd order Runge-Kutta with 3rd order error estimate *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk2, *dim); break; case 2 : // 4th order (classical) Runge-Kutta *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk4, *dim); break; case 3 : // Embedded 4th order Runge-Kutta-Fehlberg method with 5th order error estimate. This method is a good general-purpose integrator *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rkf45, *dim); break; case 4 : // Embedded 4th order Runge-Kutta Cash-Karp method with 5th order error estimate *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rkck, *dim); break; case 5 : // Embedded 8th order Runge-Kutta Prince-Dormand method with 9th order error estimate *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk8pd, *dim); break; case 6 : // Implicit 2nd order Runge-Kutta at Gaussian points *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk2imp, *dim); break; case 7 : // Implicit 4th order Runge-Kutta at Gaussian points *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_rk4imp, *dim); break; case 8 : // Implicit Bulirsch-Stoer method of Bader and Deuflhard. This algorithm requires the Jacobian *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_bsimp, *dim); break; case 9 : // M=1 implicit Gear method *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_gear1, *dim); break; case 10 : // M=2 implicit Gear method *stp = (void *)gsl_odeiv_step_alloc(gsl_odeiv_step_gear2, *dim); break; } } void FC_FUNC_(gsl_odeiv_step_free, GSL_ODEIV_STEP_FREE) (void **stp) { gsl_odeiv_step_free((gsl_odeiv_step *)(*stp)); } void FC_FUNC_(gsl_odeiv_evolve_alloc, GSL_ODEIV_EVOLVE_ALLOC) (const int *dim, void **evl) { *evl = (void *)gsl_odeiv_evolve_alloc (*dim); } int FC_FUNC_(gsl_odeiv_evolve_reset, GSL_ODEIV_EVOLVE_RESET) (void **evl) { return gsl_odeiv_evolve_reset ((gsl_odeiv_evolve *)(*evl)); } void FC_FUNC_(gsl_odeiv_evolve_free, GSL_ODEIV_EVOLVE_FREE) (void **evl) { gsl_odeiv_evolve_free((gsl_odeiv_evolve *)(*evl)); } void FC_FUNC_(gsl_odeiv_control_standart_new, GSL_ODEIV_CONTROL_STANDART_NEW) (void **ctrl, double *epsabs, double *epsrel, double *ay, double *adydt) { *ctrl = (void*) gsl_odeiv_control_standard_new (*epsabs, *epsrel, *ay, *adydt); } void FC_FUNC_(gsl_odeiv_control_free, GSL_ODEIV_CONTROL_FREE) (void **ctrl) { gsl_odeiv_control_free((gsl_odeiv_control *)(*ctrl)); } /* Interpolation */ void FC_FUNC_(gsl_interp_accel_alloc, GSL_INTERP_ACCEL_ALLOC) (void **acc) { *acc = (void *)gsl_interp_accel_alloc(); } void FC_FUNC_(gsl_spline_alloc, GSL_SPLINE_ALLOC) (void **spl, int *n, short int *opt) { /* WARNING: This routine has a small modification: the user needs to pass an integer in order to choose the interpolation type instead of a variable of type gsl_interp_type. */ switch (*opt) { case 1 : // linear interpolation *spl = (void *)gsl_spline_alloc(gsl_interp_linear, *n); break; case 2 : // polynomial interpolation *spl = (void *)gsl_spline_alloc(gsl_interp_polynomial, *n); break; case 3 : // cubic spline with natural boundary conditions *spl = (void *)gsl_spline_alloc(gsl_interp_cspline, *n); break; case 4 : // cubic spline with periodic boundary conditions *spl = (void *)gsl_spline_alloc(gsl_interp_cspline_periodic, *n); break; case 5 : // Akima spline with natural boundary conditions *spl = (void *)gsl_spline_alloc(gsl_interp_akima, *n); break; case 6 : // Akima spline with periodic boundary conditions *spl = (void *)gsl_spline_alloc(gsl_interp_akima_periodic, *n); break; } } void FC_FUNC_(gsl_spline_init, GSL_SPLINE_INIT) (void **spl, int *n, double *x, double *f) { gsl_spline_init((gsl_spline *)(*spl), x, f, *n); } double FC_FUNC_(gsl_spline_eval, GSL_SPLINE_EVAL) (double *x, void **spl, void **acc) { return gsl_spline_eval((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } double FC_FUNC_(gsl_spline_eval_deriv, GSL_SPLINE_EVAL_DERIV) (double *x, void **spl, void **acc) { return gsl_spline_eval_deriv((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } double FC_FUNC_(gsl_spline_eval_deriv2, GSL_SPLINE_EVAL_DERIV2) (double *x, void **spl, void **acc) { return gsl_spline_eval_deriv2((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc)); } void FC_FUNC_(gsl_spline_free, GSL_SPLINE_FREE) (void **spl) { gsl_spline_free((gsl_spline *)(*spl)); } void FC_FUNC_(gsl_interp_accel_free, GSL_INTERP_ACCEL_FREE) (void **acc) { gsl_interp_accel_free((gsl_interp_accel *)(*acc)); } double FC_FUNC_(gsl_spline_eval_integ, GSL_SPLINE_EVAL_INTEG) (double *a, double *b, void **spl, void **acc) { return gsl_spline_eval_integ((gsl_spline *)(*spl), *a, *b, (gsl_interp_accel *)(*acc)); } /* Multidimensional Root-Finding */ void FC_FUNC_(gsl_multiroot_fsolver_alloc, GSL_MULTIROOT_FSOLVER_ALLOC) (void **s, const int *solver_type, const int *n) { switch(*solver_type) { case 1 : // hybrid algorithm with internal scaling. *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrids, *n); break; case 2 : // hybrid algorithm without internal scaling. *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrid, *n); break; case 3 : // discrete Newton algorithm *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_dnewton, *n); break; case 4 : // Broyden algorithm *s = (void *)gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_broyden, *n); break; } } void FC_FUNC_(gsl_multiroot_fsolver_free, GSL_MULTIROOT_FSOLVER_FREE) (void **s) { gsl_multiroot_fsolver_free((gsl_multiroot_fsolver *)(*s)); }
{ "alphanum_fraction": 0.6998054475, "avg_line_length": 28.7955182073, "ext": "c", "hexsha": "c9e4524532cbf39b90d87426e233782cb7b98884", "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": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cathcart/CCPG", "max_forks_repo_path": "siesta/gsl_interface_c.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "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": "cathcart/CCPG", "max_issues_repo_path": "siesta/gsl_interface_c.c", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "43a72c0ae47b3c3b3975e75f18185a886c143ab1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cathcart/CCPG", "max_stars_repo_path": "siesta/gsl_interface_c.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3195, "size": 10280 }
#include <jni.h> #include "jade_reconstruct_area_PJNI.h" #include <gsl/gsl_linalg.h> #include <stdio.h> JNIEXPORT jdoubleArray JNICALL Java_jade_reconstruct_area_PJNI_matrixExp (JNIEnv *jenv, jobject obj, jdoubleArray arr,jint size){ jdoubleArray ret = (*jenv)->NewDoubleArray(jenv,(jint)( size * size)); double *OutData = (*jenv)->GetDoubleArrayElements(jenv,ret,JNI_FALSE); //double OutData [size*size]; jdouble * at_data = (*jenv)->GetDoubleArrayElements(jenv, arr, NULL); int i,j; double a_data [size*size]; for (i = 0; i < size*size; i++){ a_data[i] = (double)at_data[i]; } gsl_matrix_view m = gsl_matrix_view_array (a_data, (int)size, (int)size); gsl_mode_t mt = 0; gsl_matrix *ma = gsl_matrix_alloc (size,size); gsl_linalg_exponential_ss(&m.matrix, ma, mt);//m input, ma output int x = 0; for(i = 0; i < size; i++){ for(j=0;j<size;j++){ OutData[x] = gsl_matrix_get(ma,i,j); x++; } } //gsl_permutation_free (ma); //(*jenv)->SetDoubleArrayRegion(jenv,ret,(jsize)0,(jsize)size*size,OutData); (*jenv)->ReleaseDoubleArrayElements(jenv,ret,OutData,0); (*jenv)->ReleaseDoubleArrayElements(jenv,arr,at_data,0); gsl_matrix_free (ma); return ret; }
{ "alphanum_fraction": 0.701769166, "avg_line_length": 32.9722222222, "ext": "c", "hexsha": "d5bf6353d1d7c9654fd96d6f9d9dfec21bdef44a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-02T18:31:44.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-06T12:43:53.000Z", "max_forks_repo_head_hexsha": "9e2172084c648f690e8405233771f2a3ead8475d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yashondhi/PIA2", "max_forks_repo_path": "pia/phyutility/src/jade/lib/jade_reconstruct_area_PJNI.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9e2172084c648f690e8405233771f2a3ead8475d", "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": "yashondhi/PIA2", "max_issues_repo_path": "pia/phyutility/src/jade/lib/jade_reconstruct_area_PJNI.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "9e2172084c648f690e8405233771f2a3ead8475d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yashondhi/PIA2", "max_stars_repo_path": "pia/phyutility/src/jade/lib/jade_reconstruct_area_PJNI.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 382, "size": 1187 }
#include <stdlib.h> #include <string.h> #include <math.h> #include <complex.h> #include <float.h> #ifdef _MACOSX #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include <gsl/gsl_sf_legendre.h> #include "util.h" #include "spbessel.h" /* Use the modified Gram-Schmidt process to compute (in place) the portion of * the n-dimensional vector v orthogonal to each of the nv vectors s. The * projection * of the vector onto each of the basis vectors is stored in the * length-nv array c. */ int cmgs (complex double *v, complex double *c, complex double *s, int n, int nv) { int i, j, k; complex double *sv, cv; for (i = 0, sv = s; i < nv; ++i, sv += n) { c[i] = 0; k = 0; do { cv = pardot (sv, v, n); c[i] += cv; #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] -= cv * sv[j]; } while (cabs(cv / c[i]) > IMGS_TOL && ++k < IMGS_ITS); } return n; } complex double pardot (complex double *x, complex double *y, int n) { complex double dp; /* Compute the local portion. */ cblas_zdotc_sub (n, x, 1, y, 1, &dp); return dp; } /* The MSE between two vectors. */ double rmserror (complex double *v, complex double *r, int n) { double err = 0, errd = 0, e; int i; for (i = 0; i < n; ++i) { e = cabs (v[i] - r[i]); err += e * e; e = cabs (r[i]); errd += e * e; } return sqrt (err / errd); } /* Open a file or die. */ FILE *critopen (char *fname, char *mode) { FILE *fptr; fptr = fopen (fname, mode); if (!fptr) { fprintf (stderr, "ERROR: Could not open input file %s.\n", fname); exit (EXIT_FAILURE); return NULL; } return fptr; } /* Compute the number of harmonics required using the excess bandwidth * formula. */ int exband (complex double kr, double ndig) { double akr; int l; akr = creal (kr); ndig *= ndig; l = ceil (akr + 1.8 * cbrt(ndig * akr)); return l; } /* Computes the Legendre polynomials up to order n for the argument x. The * values are stored in the array v. */ int legpoly (int n, double x, double *v) { int i; /* Don't bother computing anything for order less than zero. */ if (n < 0) return -1; /* Make sure the argument is within [-1,1] as expected. */ if (fabs(x) > 1.0 + DBL_EPSILON) return -2; /* The first function value. */ v[0] = 1.0; /* If the order happens to be zero, there is no going further. */ if (n < 1) return 0; /* The second function value. */ v[1] = x; /* The recursion formula for Legendre polynomials. */ for (i = 1; i < n - 1; ++i) v[i + 1] = ((2 * i + 1) * x * v[i] - i * v[i - 1]) / (i + 1); return 0; } /* Computes the wave number from the relative sound speed and * unitless (dB) attenuation coefficient. */ complex double wavenum (double cr, double alpha) { double kr, ki; ki = log(10) * alpha / 20; kr = 2 * M_PI / cr; return kr + I * ki; } /* Computes the inverse wave number from the relative sound speed and * unitless (dB) attenuation coefficient. */ complex double invwavenum (double cr, double alpha) { double kr, ki, mag, csq; csq = cr * cr; kr = 2 * M_PI * cr; ki = log(10) * alpha / 20; mag = 4 * M_PI * M_PI + ki * ki * csq; return (kr / mag) - I * (ki * csq / mag); } /* Copy the spherical harmonic representation from one location to another. */ int copysh (int deg, complex double *out, int ldo, complex double *in, int ldi) { int i, j, offo, offi; /* Copy the spherical harmonic coefficients into the right place. */ for (i = 0; i < deg; ++i) { offo = i * ldo; offi = i * ldi; /* Copy the zero-order coefficients. */ out[offo] = in[offi]; /* Copy the other coefficients. */ for (j = 1; j <= i; ++j) { out[offo + j] = in[offi + j]; out[offo + ldo - j] = in[offi + ldi - j]; } } return deg; } /* Multiply in a radial component to the spherical harmonic. */ int shradial (int deg, complex double *a, int lda, complex double k, double r) { complex double kr, *hlkr; int i, j, off; hlkr = malloc (deg * sizeof(complex double)); /* Compute the Hankel functions for all degrees. */ kr = k * r; spbesh (hlkr, kr, deg); for (i = 0; i < deg; ++i) { off = i * lda; /* The zero-order coefficients. */ a[off] *= hlkr[i]; /* The other coefficients. */ for (j = 1; j <= i; ++j) { a[off + j] *= hlkr[i]; a[off + lda - j] *= hlkr[i]; } } free (hlkr); return deg; } /* Compute the harmonic coefficients for an incident plane wave. */ int shincident (int deg, complex double *a, int lda, complex double mag, double theta, double phi) { double cth, *lgvals; int l, m, dm1, npm, off; long lgi, lgn; complex double scale[4] = { 1, -I, -1, I }, cx, fx; /* The coefficient has a 4 pi factor that must be included. */ mag *= 4 * M_PI; dm1 = deg - 1; cth = cos(theta); lgn = gsl_sf_legendre_array_n (dm1); lgvals = malloc (lgn * sizeof(double)); /* Compute the Legendre polynomials of zero order for all degrees. */ gsl_sf_legendre_array_e (GSL_SF_LEGENDRE_SPHARM, dm1, cth, 1., lgvals); /* Compute the zero-order coefficients for all degrees. */ for (l = 0; l < deg; ++l) { lgi = gsl_sf_legendre_array_index(l, 0); a[l * lda] += scale[l % 4] * mag * lgvals[lgi]; } for (m = 1; m < deg; ++m) { npm = lda - m; /* Compute the phi variation. */ cx = cexp (I * m * phi); #pragma omp critical(incaug) for (l = m; l < deg; ++l) { off = l * lda; lgi = gsl_sf_legendre_array_index(l, m); fx = scale[l % 4] * mag * lgvals[lgi]; /* The positive-order coefficient. */ a[off + m] += fx * conj (cx); /* The negative-order coefficient. */ a[off + npm] += fx * cx; } } free (lgvals); return deg; } static int lgval (double *p, double *dp, double t, int m) { double p0 = 1.0, p1 = t; int k; /* Set values explicitly for low orders. */ if (m < 1) { *p = 1.0; *dp = 0.0; return m; } else if (m < 2) { *p = t; *dp = 1.0; return m; } /* Otherwise compute the values explicitly. */ for (k = 1; k < m; ++k) { *p = ((2.0 * k + 1.0) * t * p1 - k * p0) / (1.0 + k); p0 = p1; p1 = *p; } *dp = m * (p0 - t * p1) / (1.0 - t * t); return m; } int gauleg (int m, double *nodes, double *weights) { int i, j, nroots = (m + 1) / 2; double t, p, dp, dt; const int maxit = 100; const double tol = 1.0e-14; #pragma omp parallel for default(shared) private(i,j,t,p,dp,dt) for (i = 0; i < nroots; ++i) { t = cos (M_PI * (i + 0.75) / (m + 0.5)); for (j = 0; j < maxit; ++j) { /* Compute the value of the Legendre polynomial. */ lgval (&p, &dp, t, m); /* Perform a Newton-Raphson update. */ dt = -p / dp; t += dt; /* Break if convergence has been achieved. */ if (fabs(dt) < tol) break; } /* Update the nodes and weights. */ nodes[i] = t; nodes[m - i - 1] = -t; weights[i] = 2.0 / (1.0 - t * t) / (dp * dp); weights[m - i - 1] = weights[i]; } return 0; }
{ "alphanum_fraction": 0.5880631949, "avg_line_length": 22.339869281, "ext": "c", "hexsha": "d9f432e2f388702544ca883ac9320f8fca007497", "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": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ahesford/fastsphere", "max_forks_repo_path": "util.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "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": "ahesford/fastsphere", "max_issues_repo_path": "util.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ahesford/fastsphere", "max_stars_repo_path": "util.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2383, "size": 6836 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include <gsl/gsl-lite.hpp> #include <nlohmann/json_fwd.hpp> #include <cstdint> #include <string> namespace cb::crypto { enum class Algorithm { MD5, SHA1, SHA256, SHA512 }; bool isSupported(Algorithm algorithm); const int MD5_DIGEST_SIZE = 16; const int SHA1_DIGEST_SIZE = 20; const int SHA256_DIGEST_SIZE = 32; const int SHA512_DIGEST_SIZE = 64; /** * Generate a HMAC digest of the key and data by using the given * algorithm * * @throws std::invalid_argument - unsupported algorithm * std::runtime_error - Failures generating the HMAC */ std::string HMAC(Algorithm algorithm, std::string_view key, std::string_view data); /** * Generate a PBKDF2_HMAC digest of the key and data by using the given * algorithm * * @throws std::invalid_argument - unsupported algorithm * std::runtime_error - Failures generating the HMAC */ std::string PBKDF2_HMAC(Algorithm algorithm, const std::string& pass, std::string_view salt, unsigned int iterationCount); /** * Generate a digest by using the requested algorithm */ std::string digest(Algorithm algorithm, std::string_view data); enum class Cipher { AES_256_cbc }; Cipher to_cipher(const std::string& str); /** * Encrypt the specified data by using a given cipher * * @param cipher The cipher to use * @param key The key used for encryption * @param ivec The IV to use for encryption * @param data The Pointer to the data to encrypt * @return The encrypted data */ std::string encrypt(Cipher cipher, std::string_view key, std::string_view iv, std::string_view data); /** * Encrypt the specified data * * { * "cipher" : "name of the cipher", * "key" : "base64 of the raw key", * "iv" : "base64 of the raw iv" * } * * @param meta the json description of the encryption to use * @param data Pointer to the data to encrypt * @param length the length of the data to encrypt * @return The encrypted data */ std::string encrypt(const nlohmann::json& json, std::string_view data); /** * Decrypt the specified data by using a given cipher * * @param cipher The cipher to use * @param key The key used for encryption * @param ivec The IV to use for encryption * @param data The data to decrypt * @return The decrypted data */ std::string decrypt(Cipher cipher, std::string_view key, std::string_view iv, std::string_view data); /** * Decrypt the specified data * * { * "cipher" : "name of the cipher", * "key" : "base64 of the raw key", * "iv" : "base64 of the raw iv" * } * * @param meta the json description of the encryption to use * @param data Pointer to the data to decrypt * @param length the length of the data to decrypt * @return The decrypted data */ std::string decrypt(const nlohmann::json& json, std::string_view data); } // namespace cb::crypto
{ "alphanum_fraction": 0.6599374467, "avg_line_length": 29.0661157025, "ext": "h", "hexsha": "78042042b511d4f6c14e30b6f7d39c5a03e5f8a3", "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": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "BenHuddleston/kv_engine", "max_forks_repo_path": "include/cbcrypto/cbcrypto.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "BenHuddleston/kv_engine", "max_issues_repo_path": "include/cbcrypto/cbcrypto.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "BenHuddleston/kv_engine", "max_stars_repo_path": "include/cbcrypto/cbcrypto.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 843, "size": 3517 }
#ifndef AVERAGER_H_ #define AVERAGER_H_ #include <gsl/gsl_statistics_double.h> #include <string.h> #include <iostream> class Averager { public: virtual ~Averager() {}; virtual void reset() = 0; virtual void feed(const double x) = 0; virtual double get_mean() const = 0; virtual double get_var() const = 0; virtual unsigned int get_n() const = 0; }; class SimpleAverager: public Averager { public: SimpleAverager(): _n(0), _sum(0), _sum_of_squares(0) {} virtual void reset() { _n = 0; _sum = 0; _sum_of_squares = 0; } virtual void feed(const double x) { _n++; _sum += x; _sum_of_squares += x * x; } virtual double get_mean() const { return _sum / _n; } virtual double get_var() const { return 1./(_n - 1) * (_sum_of_squares - _n * get_mean()*get_mean()); } virtual unsigned int get_n() const { return _n; } private: unsigned int _n; double _sum; double _sum_of_squares; }; class BufferAverager: public Averager { public: BufferAverager(const size_t bufsize): bufsize_(bufsize), n_(0), i_(0) { buf_ = new double[bufsize]; } virtual ~BufferAverager() { delete[] buf_; } virtual void feed(const double x) { if (i_ == bufsize_) { i_ = 0; } if (i_ < bufsize_) { buf_[i_] = x; i_++; if (i_ > n_) n_++; } } virtual double get_mean() const { return gsl_stats_mean(buf_, 1, n_); } virtual double get_var() const { return gsl_stats_variance(buf_, 1, n_); } virtual unsigned int get_n() const { return n_; } virtual void reset() { memset(buf_, 0, bufsize_ * sizeof(double)); n_ = 0; i_ = 0; } void dump(std::ostream& out) { for (int j = 0; j < n_; j++) out << buf_[j] << "\n"; } private: const size_t bufsize_; double* buf_; unsigned int n_; unsigned int i_; }; class FancyAverager: public Averager { public: FancyAverager(): _mean_avg(), _sq_avg(), _cub_avg() {} virtual void reset() { _mean_avg.reset(); _sq_avg.reset(); } virtual void feed(const double x) { _mean_avg.feed(x); _sq_avg.feed(x*x); _cub_avg.feed(x*x*x); } virtual unsigned int get_n() const { return _mean_avg.get_n(); } virtual double get_mean() const { return _mean_avg.get_mean(); } virtual double get_var() const { return _mean_avg.get_var(); } double get_mean_of_square() const { return _sq_avg.get_mean(); } double get_var_of_square() const { return _sq_avg.get_var(); } double get_mean_of_cube() const { return _cub_avg.get_mean(); } double get_var_of_cube() const { return _cub_avg.get_var(); } private: SimpleAverager _mean_avg; SimpleAverager _sq_avg; SimpleAverager _cub_avg; }; #endif // AVERAGER_H_
{ "alphanum_fraction": 0.5766182299, "avg_line_length": 23.4728682171, "ext": "h", "hexsha": "502039019e65757eb3296cb0b6982e376ddfa8c1", "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": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ModelDBRepository/228604", "max_forks_repo_path": "simulation/neurophys/averager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "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": "ModelDBRepository/228604", "max_issues_repo_path": "simulation/neurophys/averager.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ModelDBRepository/228604", "max_stars_repo_path": "simulation/neurophys/averager.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 854, "size": 3028 }
/* vector/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #if defined( _MSC_VER ) && defined( GSL_DLL ) #undef inline #define inline __forceinline #endif #if (!GSL_RANGE_CHECK) && defined(HAVE_INLINE) #undef GSL_RANGE_CHECK #define GSL_RANGE_CHECK 1 #endif #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> int status = 0; #ifndef DESC #define DESC "" #endif #define BASE_GSL_COMPLEX_LONG #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX_LONG #define BASE_GSL_COMPLEX #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX #define BASE_GSL_COMPLEX_FLOAT #include "templates_on.h" #include "test_complex_source.c" #include "templates_off.h" #undef BASE_GSL_COMPLEX_FLOAT #define BASE_LONG_DOUBLE #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_LONG_DOUBLE #define BASE_DOUBLE #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_FLOAT #define BASE_ULONG #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_ULONG #define BASE_LONG #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_LONG #define BASE_UINT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_UINT #define BASE_INT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_INT #define BASE_USHORT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_USHORT #define BASE_SHORT #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_SHORT #define BASE_UCHAR #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_UCHAR #define BASE_CHAR #include "templates_on.h" #include "test_source.c" #include "templates_off.h" #undef BASE_CHAR void my_error_handler (const char *reason, const char *file, int line, int err); int main (void) { size_t stride, ostride, N; gsl_ieee_env_setup (); for (N = 10; N < 1024; N = 2*N + 1) { for (stride = 1; stride < 5 ; stride++) { test_func (stride, N); test_float_func (stride, N); test_long_double_func (stride, N); test_ulong_func (stride, N); test_long_func (stride, N); test_uint_func (stride, N); test_int_func (stride, N); test_ushort_func (stride, N); test_short_func (stride, N); test_uchar_func (stride, N); test_char_func (stride, N); test_complex_func (stride, N); test_complex_float_func (stride, N); test_complex_long_double_func (stride, N); for (ostride = 1; ostride < 5 ; ostride++) { test_ops (stride, ostride, N); test_float_ops (stride, ostride, N); test_long_double_ops (stride, ostride, N); test_ulong_ops (stride, ostride, N); test_long_ops (stride, ostride, N); test_uint_ops (stride, ostride, N); test_int_ops (stride, ostride, N); test_ushort_ops (stride, ostride, N); test_short_ops (stride, ostride, N); test_uchar_ops (stride, ostride, N); test_char_ops (stride, ostride, N); test_complex_ops (stride, ostride, N); test_complex_float_ops (stride, ostride, N); test_complex_long_double_ops (stride, ostride, N); } test_text (stride, N); test_float_text (stride, N); #if HAVE_PRINTF_LONGDOUBLE test_long_double_text (stride, N); #endif test_ulong_text (stride, N); test_long_text (stride, N); test_uint_text (stride, N); test_int_text (stride, N); test_ushort_text (stride, N); test_short_text (stride, N); test_uchar_text (stride, N); test_char_text (stride, N); test_complex_text (stride, N); test_complex_float_text (stride, N); #if HAVE_PRINTF_LONGDOUBLE test_complex_long_double_text (stride, N); #endif test_file (stride, N); test_float_file (stride, N); test_long_double_file (stride, N); test_ulong_file (stride, N); test_long_file (stride, N); test_uint_file (stride, N); test_int_file (stride, N); test_ushort_file (stride, N); test_short_file (stride, N); test_uchar_file (stride, N); test_char_file (stride, N); test_complex_file (stride, N); test_complex_float_file (stride, N); test_complex_long_double_file (stride, N); } } #if GSL_RANGE_CHECK gsl_set_error_handler (&my_error_handler); for (N = 1; N < 1024; N *=2) { for (stride = 1; stride < 5 ; stride++) { test_trap (stride, N); test_float_trap (stride, N); test_long_double_trap (stride, N); test_ulong_trap (stride, N); test_long_trap (stride, N); test_uint_trap (stride, N); test_int_trap (stride, N); test_ushort_trap (stride, N); test_short_trap (stride, N); test_uchar_trap (stride, N); test_char_trap (stride, N); test_complex_trap (stride, N); test_complex_float_trap (stride, N); test_complex_long_double_trap (stride, N); } } #endif exit (gsl_test_summary ()); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err); status = 1; }
{ "alphanum_fraction": 0.6524709302, "avg_line_length": 27.4103585657, "ext": "c", "hexsha": "649ba9fe3507602fcb9370bd07d7923a5052f42a", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_line_length": 81, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 1702, "size": 6880 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_roots.h> #include "ccl.h" #include "ccl_params.h" // Global variable to hold the neutrino phase-space spline gsl_spline* nu_spline=NULL; /* ------- ROUTINE: nu_integrand ------ INPUTS: x: dimensionless momentum, *r: pointer to a dimensionless mass / temperature TASK: Integrand of phase-space massive neutrino integral */ static double nu_integrand(double x, void *r) { double rat=*((double*)(r)); return sqrt(x*x+rat*rat)/(exp(x)+1.0)*x*x; } /* ------- ROUTINE: ccl_calculate_nu_phasespace_spline ------ TASK: Get the spline of the result of the phase-space integral required for massive neutrinos. */ gsl_spline* calculate_nu_phasespace_spline(int *status) { int N=CCL_NU_MNUT_N; double *mnut = ccl_linear_spacing(log(CCL_NU_MNUT_MIN),log(CCL_NU_MNUT_MAX),N); double *y=malloc(sizeof(double)*CCL_NU_MNUT_N); if (y ==NULL) { // Not setting a status_message here because we can't easily pass a cosmology to this function - message printed in ccl_error.c. *status = CCL_ERROR_NU_INT; } // Check whether ccl_splines and ccl_gsl exist; exit gracefully if they // can't be loaded if(ccl_splines==NULL || ccl_gsl==NULL) ccl_cosmology_read_config(); if(ccl_splines==NULL || ccl_gsl==NULL) { ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, "ccl_neutrinos.c: Failed to read config file."); *status = CCL_ERROR_MISSING_CONFIG_FILE; return NULL; } int stat=0, gslstatus; gsl_integration_cquad_workspace * workspace = \ gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION); gsl_function F; F.function = &nu_integrand; for (int i=0; i<CCL_NU_MNUT_N; i++) { double mnut_=exp(mnut[i]); F.params = &(mnut_); gslstatus = gsl_integration_cquad(&F, 0, 1000.0, ccl_gsl->INTEGRATION_NU_EPSABS, ccl_gsl->INTEGRATION_NU_EPSREL, workspace,&y[i], NULL, NULL); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_neutrinos.c: calculate_nu_phasespace_spline():"); stat |= gslstatus; } } gsl_integration_cquad_workspace_free(workspace); double renorm=1./y[0]; for (int i=0; i<CCL_NU_MNUT_N; i++) y[i]*=renorm; gsl_spline* spl = gsl_spline_alloc(A_SPLINE_TYPE, CCL_NU_MNUT_N); stat |= gsl_spline_init(spl, mnut, y, CCL_NU_MNUT_N); // Check for errors in creating the spline if (stat) { // Not setting a status_message here because we can't easily pass a cosmology to this function - message printed in ccl_error.c. *status = CCL_ERROR_NU_INT; free(mnut); free(y); gsl_spline_free(spl); } free(mnut); free(y); return spl; } /* ------- ROUTINE: ccl_nu_phasespace_intg ------ INPUTS: accel: pointer to an accelerator which will evaluate the neutrino phasespace spline if defined, mnuOT: the dimensionless mass / temperature of a single massive neutrino TASK: Get the value of the phase space integral at mnuOT */ double nu_phasespace_intg(gsl_interp_accel* accel, double mnuOT, int* status) { // Check if the global variable for the phasespace spline has been defined yet: if (nu_spline==NULL) nu_spline =calculate_nu_phasespace_spline(status); ccl_check_status_nocosmo(status); double integral_value =0.; // First check the cases where we are in the limits. if (mnuOT<CCL_NU_MNUT_MIN) { return 7./8.; } else if (mnuOT>CCL_NU_MNUT_MAX) { return 0.2776566337*mnuOT; } // Evaluate the spline - this will use the accelerator if it has been defined. int gslstatus = gsl_spline_eval_e(nu_spline, log(mnuOT),accel, &integral_value); if(gslstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(gslstatus, "ccl_neutrinos.c: nu_phasespace_intg():"); *status |= gslstatus; } return integral_value*7./8.; } /* -------- ROUTINE: Omeganuh2 --------- INPUTS: a: scale factor, Nnumass: number of massive neutrino species, mnu: total mass in eV of neutrinos, T_CMB: CMB temperature, accel: pointer to an accelerator which will evaluate the neutrino phasespace spline if defined, status: pointer to status integer. TASK: Compute Omeganu * h^2 as a function of time. !! To all practical purposes, Neff is simply N_nu_mass !! */ double ccl_Omeganuh2 (double a, int N_nu_mass, double* mnu, double T_CMB, gsl_interp_accel* accel, int* status) { double Tnu, a4, prefix_massless, mnuone, OmNuh2; double Tnu_eff, mnuOT, intval, prefix_massive; double total_mass; // To check if this is the massless or massive case. // First check if N_nu_mass is 0 if (N_nu_mass==0) return 0.0; Tnu=T_CMB*pow(4./11.,1./3.); a4=a*a*a*a; // Check if mnu=0. We assume that in the massless case mnu is a pointer to a single element and that element is 0. This should in principle never be called. if (mnu[0] < 0.00017) { // Limit taken from Lesgourges et al. 2012 prefix_massless = NU_CONST * Tnu * Tnu * Tnu * Tnu; return N_nu_mass*prefix_massless*7./8./a4; } // And the remaining massive case. // Tnu_eff is used in the massive case because CLASS uses an effective temperature of nonLCDM components to match to mnu / Omeganu =93.14eV. Tnu_eff = T_ncdm * T_CMB = 0.71611 * T_CMB Tnu_eff = Tnu * TNCDM / (pow(4./11.,1./3.)); // Define the prefix using the effective temperature (to get mnu / Omega = 93.14 eV) for the massive case: prefix_massive = NU_CONST * Tnu_eff * Tnu_eff * Tnu_eff * Tnu_eff; OmNuh2 = 0.; // Initialize to 0 - we add to this for each massive neutrino species. for(int i=0; i<N_nu_mass; i++){ // Get mass over T (mass (eV) / ((kb eV/s/K) Tnu_eff (K)) // This returns the density normalized so that we get nuh2 at a=0 mnuOT = mnu[i] / (Tnu_eff/a) * (EV_IN_J / (KBOLTZ)); // Get the value of the phase-space integral intval=nu_phasespace_intg(accel,mnuOT, status); OmNuh2 = intval*prefix_massive/a4 + OmNuh2; } return OmNuh2; } /* -------- ROUTINE: Omeganuh2_to_Mnu --------- INPUTS: OmNuh2: neutrino mass density today Omeganu * h^2, label: how you want to split up the masses, see ccl_neutrinos.h for options, T_CMB: CMB temperature, accel: pointer to an accelerator which will evaluate the neutrino phasespace spline if defined, status: pointer to status integer. TASK: Given Omeganuh2 today, the method of splitting into masses, and the temperature of the CMB, output a pointer to the array of neutrino masses (may be length 1 if label asks for sum) */ double* ccl_nu_masses(double OmNuh2, ccl_neutrino_mass_splits mass_split, double T_CMB, int* status){ double sumnu; sumnu = 93.14 * OmNuh2; // Now split the sum up into three masses depending on the label given: if(mass_split==ccl_nu_normal){ double *mnu; mnu = malloc(3*sizeof(double)); // See CCL note for how we get these expressions for the neutrino masses in normal and inverted hierarchy. mnu[0] = 2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5) - 0.25 * DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)); mnu[1] = 2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5) + 0.25 * DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5)); mnu[2] = -1./3. * sumnu + 1./3 * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_pos + 4. * sumnu*sumnu, 0.5); if (mnu[0]<0 || mnu[1]<0 || mnu[2]<0){ // The user has provided a sum that is below the physical limit. if (sumnu<1e-14){ mnu[0] = 0.; mnu[1] = 0.; mnu[2] = 0.; }else{ *status = CCL_ERROR_MNU_UNPHYSICAL; } } ccl_check_status_nocosmo(status); return mnu; } else if (mass_split==ccl_nu_inverted){ double *mnu; mnu = malloc(3*sizeof(double)); mnu[0] = 2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5) - 0.25 * DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_neg + 4. * sumnu * sumnu, 0.5)); mnu[1] = 2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5) + 0.25 * DELTAM12_sq / (2./3.* sumnu - 1./6. * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5)); mnu[2] = -1./3. * sumnu + 1./3 * pow(-6. * DELTAM12_sq + 12. * DELTAM13_sq_neg + 4. * sumnu*sumnu, 0.5); if(mnu[0]<0 || mnu[1]<0 || mnu[2]<0){ // The user has provided a sum that is below the physical limit. if (sumnu<1e-14){ mnu[0] = 0.; mnu[1] = 0.; mnu[2] = 0.;; }else{ *status = CCL_ERROR_MNU_UNPHYSICAL; } } ccl_check_status_nocosmo(status); return mnu; } else if (mass_split==ccl_nu_equal){ double *mnu; mnu = malloc(3*sizeof(double)); mnu[0] = sumnu/3.; mnu[1] = sumnu/3.; mnu[2] = sumnu/3.; return mnu; } else if (mass_split == ccl_nu_sum){ double *mnu; mnu = malloc(sizeof(double)); mnu[0] = sumnu; return mnu; } else{ printf("WARNING: mass option = %d not yet supported\n continuing with normal hierarchy\n", mass_split); double *mnu; mnu = malloc(3*sizeof(double)); if (sumnu>0.59){ mnu[0] = (sumnu - 0.59) / 3.; mnu[1] = mnu[0] + 0.009; mnu[2] = mnu[0] + 0.05; }else{ *status = CCL_ERROR_MNU_UNPHYSICAL; } ccl_check_status_nocosmo(status); return mnu; } }
{ "alphanum_fraction": 0.6580950422, "avg_line_length": 37.5366795367, "ext": "c", "hexsha": "6acb0204f691488d6026980453b4c21f57e78e63", "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": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_path": "src/ccl_neutrinos.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "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": "Russell-Jones-OxPhys/CCL", "max_issues_repo_path": "src/ccl_neutrinos.c", "max_line_length": 290, "max_stars_count": null, "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_path": "src/ccl_neutrinos.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3302, "size": 9722 }
#pragma once #include <gsl/span> #include <utility> namespace hz::range { template<typename T> using contiguous_view = gsl::span<T>; template<typename Container> auto make_contiguous_view(Container && c) noexcept -> contiguous_view<std::remove_reference_t<decltype(std::data(*std::forward<Container>(c)))>> { return gsl::make_span(std::forward<Container>(c)); } }
{ "alphanum_fraction": 0.6979695431, "avg_line_length": 28.1428571429, "ext": "h", "hexsha": "b1c806b997652870deef2b8da9c0bf75730eba69", "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": "8ca42d30da06084a00a46830e5bff45409c23bf4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "KABoissonneault/AGEA", "max_forks_repo_path": "include/common/range/view.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ca42d30da06084a00a46830e5bff45409c23bf4", "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": "KABoissonneault/AGEA", "max_issues_repo_path": "include/common/range/view.h", "max_line_length": 150, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8ca42d30da06084a00a46830e5bff45409c23bf4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "KABoissonneault/AGEA", "max_stars_repo_path": "include/common/range/view.h", "max_stars_repo_stars_event_max_datetime": "2017-12-07T02:00:32.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-07T02:00:32.000Z", "num_tokens": 90, "size": 394 }
/* * ----------------------------------------------------------------- * Utilities Library --- util_lib.c * Version: 1.6180 * Date: Mar 12, 2010 * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010 by Americo Barbosa da Cunha Junior * * 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. * * A copy of the GNU General Public License is available in * LICENSE.txt or http://www.gnu.org/licenses/. * ----------------------------------------------------------------- * This is the implementation file of a library * with miscelaneous functions. * ----------------------------------------------------------------- */ #include <stdio.h> #include <gsl/gsl_errno.h> #include "../include/util_lib.h" /* *------------------------------------------------------------ * gsl_fprint_vector * * This function prints a vector in a file. * * Input: * file - output file * v - GSL vector * * Output: * * Return: * success or error * * last update: Nov 6, 2008 *------------------------------------------------------------ */ int gsl_fprint_vector(FILE* file,gsl_vector *v) { if( v == NULL ) return GSL_EINVAL; unsigned int i; for( i = 0; i < v->size; i++ ) fprintf(file," %+.3e", v->data[i]); return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_print_vector * * This function prints a vector on the screen * * Input: * v - GSL vector * * Output: * * Return: * success or error * * last update: Dec 26, 2008 *------------------------------------------------------------ */ int gsl_print_vector(gsl_vector *v) { if( v == NULL ) return GSL_EINVAL; unsigned int i; for( i = 0; i < v->size; i++ ) printf(" %+.3e", v->data[i]); return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_print_matrix_line * * This function prints a matrix line on the screen. * * Input: * i - matrix line to be printed * M - GSL matrix * * Output: * * Return: * success or error * * last update: Dec 26, 2008 *------------------------------------------------------------ */ int gsl_print_matrix_line(unsigned int i,gsl_matrix *M) { if( M == NULL ) return GSL_EINVAL; unsigned int j; printf("\n"); for( j = 0; j < M->size2; j++ ) printf(" %+.3e ", M->data[i*M->tda+j]); return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_print_matrix_column * * This function prints a matrix column on the screen * * Input: * M - GSL matrix * i - matrix column to be printed * * Output: * * Return: * success or error * * last update: Dec 26, 2008 *------------------------------------------------------------ */ int gsl_print_matrix_column(unsigned int j,gsl_matrix *M) { if( M == NULL ) return GSL_EINVAL; unsigned int i; printf("\n"); for( i = 0; i < M->size1; i++ ) printf(" %+.3e\n", M->data[i*M->tda+j]); return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_print_matrix * * This function prints a matrix on the screen * * Input: * M - GSL matrix * * Outpur: * * Return: * success or error * * last update: Dec 26, 2008 *------------------------------------------------------------ */ int gsl_print_matrix(gsl_matrix *M) { if( M == NULL ) return GSL_EINVAL; unsigned int i; for( i = 0; i < M->size1; i++ ) gsl_print_matrix_line(i,M); return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_rand_vector * * This function creates a random vector. * * Input: * seed - random number generator seed * * Output: * v - GSL vector * * Return: * success or error * * last update: Feb 19, 2010 *------------------------------------------------------------ */ int gsl_rand_vector(gsl_rng *r,gsl_vector *v) { if( v == NULL ) return GSL_EINVAL; unsigned int i; for( i = 0; i < v->size; i++ ) v->data[i] = gsl_rng_uniform(r) + 1.0; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_rand_matrix * * This function creates a radom matrix. * * Input: * seed - random number generator seed * * Output: * M - GSL matrix * * Return: * success or error * * last update: Feb 27, 2009 *------------------------------------------------------------ */ int gsl_rand_matrix(gsl_rng *r,gsl_matrix *M) { if( M == NULL ) return GSL_EINVAL; unsigned int i, j; for( i = 0; i < M->size1; i++ ) for( j = 0; j < M->size2; j++ ) M->data[i*M->tda+j] = gsl_rng_uniform(r) + 1.0; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * gsl_diagonal_matrix * * This function creates a diagonal matrix with the elements * of the vector v. * * Input: * v - GSL vector * * Output: * D - GSL matrix * * Return: * success or error * * last update: Feb 26, 2009 *------------------------------------------------------------ */ int gsl_diagonal_matrix(gsl_vector *v,gsl_matrix *D) { if( v == NULL || D == NULL ) return GSL_EINVAL; unsigned int i, j; for( i = 0; i < D->size1; i++ ) for( j = 0; j < D->size2; j++ ) if( i == j ) D->data[i*D->tda+j] = v->data[i]; else D->data[i*D->tda+j] = 0.0; return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * util_time_used * * This function computes the CPU time and Wall time * used in a simulation. * * Input: * cpu_start - cpu clock start flag * cpu_end - cpu clock end flag * wall_start - wall clock start flag * wall_end - wall clock end flag * * last update: Nov 10, 2009 *------------------------------------------------------------ */ void util_time_used(clock_t cpu_start,clock_t cpu_end, time_t wall_start,time_t wall_end) { double cpu_used; double wall_used; cpu_used = ((double) (cpu_end - cpu_start)) / CLOCKS_PER_SEC; wall_used = difftime(wall_end,wall_start); printf("\n"); printf("\n CPU time (s): %+.6e",cpu_used); printf("\n Wall time (s): %+.6e",wall_used); printf("\n"); return; } /*------------------------------------------------------------*/
{ "alphanum_fraction": 0.4332678454, "avg_line_length": 20.6351351351, "ext": "c", "hexsha": "6e7f904658ce42c62e3e6a13e8132b2df8c93b5e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-1.0/src/util_lib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "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": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-1.0/src/util_lib.c", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-2.0/src/util_lib.c", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 1824, "size": 7635 }
#ifndef H_GPM_STRIPPED_DOWN #define H_GPM_STRIPPED_DOWN #include <gsl/gsl_vector.h> #include <gsl/gsl_histogram.h> #include "../csm_all.h" void ght_find_theta_range(LDP laser_ref, LDP laser_sens, const double*x0, double max_linear_correction, double max_angular_correction_deg, int interval, gsl_histogram*hist, int*num_correspondences); void ght_one_shot(LDP laser_ref, LDP laser_sens, const double*x0, double max_linear_correction, double max_angular_correction_deg, int interval, double*x, int*num_correspondences) ; #endif
{ "alphanum_fraction": 0.7465986395, "avg_line_length": 32.6666666667, "ext": "h", "hexsha": "b8d6a29aab707e786e813c8e02b6bf36fcdb9415", "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": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "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": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/csm/gpm/gpm.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 143, "size": 588 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "DirectionalLight.h" namespace Library { class Texture2D; class ProxyModel; } namespace Rendering { class NormalMappingMaterial; class NormalMappingDemo final : public Library::DrawableGameComponent { public: NormalMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); NormalMappingDemo(const NormalMappingDemo&) = delete; NormalMappingDemo(NormalMappingDemo&&) = default; NormalMappingDemo& operator=(const NormalMappingDemo&) = default; NormalMappingDemo& operator=(NormalMappingDemo&&) = default; ~NormalMappingDemo(); bool RealNormalMapEnabled() const; void SetRealNormalMapEnabled(bool enabled); void ToggleRealNormalMap(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float DirectionalLightIntensity() const; void SetDirectionalLightIntensity(float intensity); const DirectX::XMFLOAT3& LightDirection() const; void RotateDirectionalLight(DirectX::XMFLOAT2 amount); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: std::shared_ptr<NormalMappingMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; std::uint32_t mVertexCount{ 0 }; Library::DirectionalLight mDirectionalLight; std::unique_ptr<Library::ProxyModel> mProxyModel; std::shared_ptr<Library::Texture2D> mRealNormalMap; std::shared_ptr<Library::Texture2D> mDefaultNormalMap; bool mUpdateMaterial{ true }; bool mRealNormalMapEnabled{ true }; }; }
{ "alphanum_fraction": 0.7834710744, "avg_line_length": 30.7627118644, "ext": "h", "hexsha": "52f288eb006991c9f185f89e96c9e3a2d246179b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/6.1_Normal_Mapping/NormalMappingDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 451, "size": 1815 }
#ifndef OPENMC_TALLIES_FILTER_SPH_HARM_H #define OPENMC_TALLIES_FILTER_SPH_HARM_H #include <string> #include <gsl/gsl> #include "openmc/tallies/filter.h" namespace openmc { enum class SphericalHarmonicsCosine { scatter, particle }; //============================================================================== //! Gives spherical harmonics expansion moments of a tally score //============================================================================== class SphericalHarmonicsFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~SphericalHarmonicsFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override {return "sphericalharmonics";} void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle* p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors int order() const { return order_; } void set_order(int order); SphericalHarmonicsCosine cosine() const { return cosine_; } void set_cosine(gsl::cstring_span cosine); private: //---------------------------------------------------------------------------- // Data members int order_; //! The type of angle that this filter measures when binning events. SphericalHarmonicsCosine cosine_ {SphericalHarmonicsCosine::particle}; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_SPH_HARM_H
{ "alphanum_fraction": 0.546301689, "avg_line_length": 26.4153846154, "ext": "h", "hexsha": "aec21e117be2add8184308e86c01f2942c389fed", "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": "571ed3b6ab449e555fc9c8452106425d26b19bd3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ypark234/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_sph_harm.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "571ed3b6ab449e555fc9c8452106425d26b19bd3", "max_issues_repo_issues_event_max_datetime": "2020-03-17T18:59:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-02-24T15:13:15.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ypark234/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_sph_harm.h", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "571ed3b6ab449e555fc9c8452106425d26b19bd3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ypark234/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_sph_harm.h", "max_stars_repo_stars_event_max_datetime": "2020-11-19T14:46:10.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-19T14:46:10.000Z", "num_tokens": 337, "size": 1717 }
#pragma once #include <gsl/gsl> #include <map> #include <optional> #include "aseprite_file.h" #include "halley/text/halleystring.h" #include "halley/maths/vector4.h" namespace Halley { class Path; class Image; struct ImageData; class AsepriteReader { public: static std::map<String, Vector<ImageData>> importAseprite(const String& spriteName, const Path& filename, gsl::span<const gsl::byte> fileData, bool trim, int padding, bool groupSeparated, bool sequenceSeparated); static void addImageData(int tagFrameNumber, int origFrameNumber, Vector<ImageData>& frameData, std::unique_ptr<Image> frameImage, const AsepriteFile& aseFile, const String& baseName, const String& sequence, const String& direction, int duration, bool trim, int padding, bool hasFrameNumber, std::optional<String> group, bool firstImage, const String& spriteName, const Path& filename); }; }
{ "alphanum_fraction": 0.7335490831, "avg_line_length": 34.3333333333, "ext": "h", "hexsha": "f4e7af06271d5f58ee6ae9aa3158cd60ae832db7", "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": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "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": "amrezzd/halley", "max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_line_length": 214, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 222, "size": 927 }
/* * Copyright 2017 RIS. * Authored by Ron Dahlgren <ron@red83.net> */ #ifndef GLOBALS_H_ #define GLOBALS_H_ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <GL/glew.h> #include <GLFW/glfw3.h> #include <unistd.h> #include <ctype.h> #include <math.h> #include <getopt.h> #include <unistd.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> typedef int sd_result; static const sd_result SD_OK = 0; static const sd_result SD_RENDER_INIT_FAILURE = 1; static const sd_result SD_WINDOW_CREATION_FAILURE = 2; static const sd_result SD_NO_FREE_HANDLES = 3; static const sd_result SD_CHECK_ERRNO = 4; static const sd_result SD_GEN_ERROR = 5; static const sd_result SD_SCRIPT_SYNTAX = 6; static const sd_result SD_SCRIPT_TYPE_ERROR = 7; static const sd_result SD_SCRIPT_GENERAL_ERROR = 8; static const sd_result SD_FAILED_TO_READ_NUMBER = 9; // Transform component indication flags static const uint8_t XFORM_X_AXIS = (1 << 0); static const uint8_t XFORM_Y_AXIS = (1 << 1); static const uint8_t XFORM_Z_AXIS = (1 << 2); static const uint8_t XFORM_TRANSLATION = (1 << 3); static const uint8_t XFORM_TRANSLATION_X = (1 << 4); static const uint8_t XFORM_TRANSLATION_Y = (1 << 5); static const uint8_t XFORM_TRANSLATION_Z = (1 << 6); #endif
{ "alphanum_fraction": 0.7406340058, "avg_line_length": 27.2156862745, "ext": "h", "hexsha": "172c3348045509ec909c622f345cf029090e05ce", "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": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "influenza/c8", "max_forks_repo_path": "src/globals.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "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": "influenza/c8", "max_issues_repo_path": "src/globals.h", "max_line_length": 54, "max_stars_count": null, "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "influenza/c8", "max_stars_repo_path": "src/globals.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 393, "size": 1388 }
/* * splinepdf.c: Routines to efficiently sample from a dimension of an * N-dimensional spline surface. Uses a Metropolis-Hastings Markov Chain * sampler. */ #include <math.h> #include <gsl/gsl_rng.h> #include "photospline/splinetable.h" #include "photospline/bspline.h" #include "photospline/splinepdf.h" void logsplinepdf_n_sample(double *result, int results, int burnin, double *coords, int dim, struct splinetable *table, int derivatives, double (* proposal)(void*), double (* proposal_pdf)(double, double, void*), void* proposal_info, const gsl_rng *rng) { int i; int centers[table->ndim]; double val, lastval; double lastlogpdf = -INFINITY, logpdf; double lastproppdf, proppdf; double odds; double mint, maxt; #ifdef DEBUG int accepted=0; #endif /* Find the boundaries by choosing the first and last points * with full support */ mint = table->extents[dim][0]; maxt = table->extents[dim][1]; do { /* * Get a starting point from the proposal distribution, * making sure the PDF at the starting point is finite * to avoid numerical problems. */ coords[dim] = lastval = (*proposal)(proposal_info); lastproppdf = (*proposal_pdf)(lastval,lastval,proposal_info); if (tablesearchcenters(table, coords, centers) != 0) { lastval = mint-1; continue; } lastlogpdf = ndsplineeval(table, coords, centers, 0); if (derivatives) lastlogpdf += log(ndsplineeval(table, coords, centers, derivatives)); } while (isnan(lastlogpdf) || lastval < mint || lastval > maxt); for (i = -burnin; i/burnin < results; i++) { coords[dim] = val = (*proposal)(proposal_info); /* * If we ended up outside the table, reject the sample * and try again */ if (val > maxt || val < mint || tablesearchcenters(table, coords, centers) != 0) goto reject; logpdf = ndsplineeval(table, coords, centers, 0); if (derivatives) logpdf += log(ndsplineeval(table, coords, centers, derivatives)); proppdf = (*proposal_pdf)(val,lastval,proposal_info); odds = exp(logpdf - lastlogpdf); odds *= lastproppdf/proppdf; if (odds > 1. || gsl_rng_uniform(rng) < odds) { /* Accept this value */ lastval = val; lastlogpdf = logpdf; lastproppdf = proppdf; #ifdef DEBUG accepted++; #endif } /* * Lastval has whatever we decided on now. If the burn-in * period has elapsed, write it to output array. * * NB: This code is used in both the accept and reject * cases. */ reject: if (i >= 0 && (i % burnin) == 0) result[i/burnin] = lastval; } #ifdef DEBUG printf("Efficiency: %e\n", (double)(accepted)/(double)(i)); #endif } void splinepdf_n_sample(double *result, int results, int burnin, double *coords, int dim, struct splinetable *table, int derivatives, double (* proposal)(void*), double (* proposal_pdf)(double, double, void*), void *proposal_info, const gsl_rng *rng) { int i; int centers[table->ndim]; double val, lastval; double lastpdf, pdf; double lastproppdf, proppdf; double odds; double mint, maxt; #ifdef DEBUG int accepted=0; #endif /* Find the boundaries by choosing the first and last points * with full support */ mint = table->extents[dim][0]; maxt = table->extents[dim][1]; /* Get a fully-supported starting point from the proposal distribution. */ do { coords[dim] = lastval = (*proposal)(proposal_info); } while (lastval < mint || lastval > maxt || tablesearchcenters(table, coords, centers) != 0); lastproppdf = (*proposal_pdf)(lastval,lastval,proposal_info); lastpdf = ndsplineeval(table, coords, centers, derivatives); for (i = -burnin; i/burnin < results; i++) { coords[dim] = val = (*proposal)(proposal_info); /* * If we ended up outside the table, reject the sample * and try again */ if (val > maxt || val < mint || tablesearchcenters(table, coords, centers) != 0) goto reject; pdf = ndsplineeval(table, coords, centers, derivatives); proppdf = (*proposal_pdf)(val,lastval,proposal_info); odds = pdf/lastpdf; odds *= lastproppdf/proppdf; if (odds > 1. || gsl_rng_uniform(rng) < odds) { /* Accept this value */ lastval = val; lastpdf = pdf; lastproppdf = proppdf; #ifdef DEBUG accepted++; #endif } /* * Lastval has whatever we decided on now. If the burn-in * period has elapsed, write it to output array. * * NB: This code is used in both the accept and reject * cases. */ reject: if (i >= 0 && (i % burnin) == 0) result[i / burnin] = lastval; } #ifdef DEBUG printf("Efficiency: %e\n", (double)(accepted)/(double)(i)); #endif }
{ "alphanum_fraction": 0.6619232428, "avg_line_length": 26.6551724138, "ext": "c", "hexsha": "cd5b4acbe4364ca0ef2e7f77c21a0c594f2d71fe", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_path": "photospline/private/lib/splinepdf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "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": "hschwane/offline_production", "max_issues_repo_path": "photospline/private/lib/splinepdf.c", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_path": "photospline/private/lib/splinepdf.c", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "num_tokens": 1340, "size": 4638 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #include "ray.h" #define pi M_PI //############################################################################# //############################################################################# //Mode finder //Data structure for julia cavity data and mode parameters typedef struct { //Julia cavity info and functions ----------------------------------------- //pointer to Boundary object void *bnd; //pointer to radius function double (*rfunc_p)(void *bnd,double theta); //pointer to (mutating) radius and normal vector angle function void (*rsys_p)(void *bnd, double theta, double results[]); //pointer to RefractiveIndex object void *idx; //pointer to refractive index value function double (*nfunc_p)(void *idx, double r, double theta); //pointer to (mutating) refractive index value and derivative function void (*nderiv_p)(void *idx, double r, double theta, double results[]); //mode-specific parameters ------------------------------------------------ long order; //number of bounces in a period double rtol; //stopping criterion tolerance //preallocated arrays ----------------------------------------------------- double *raypath_r; double *raypath_theta; long *bounceindices; double *bouncepts_chi; long *lengths; double *modebounces; } modeinfo; //############################################################################# //Function for rootfinding int rootfunc(const gsl_vector *x, void *params, gsl_vector *f){ //params is pointer to modeinfo struct containing both cavity info and //simulation parameters modeinfo *mip = (modeinfo *)params; const long order = (*mip).order; double *raypath_r = (double *)(*mip).raypath_r; double *raypath_theta = (double *)(*mip).raypath_theta; long *bounceindices = (long *)(*mip).bounceindices; double *bouncepts_chi = (double *)(*mip).bouncepts_chi; long *lengths = (long *)(*mip).lengths; //Extract initial condition data (print for debugging) const double theta0 = gsl_vector_get(x,0), chi0 = gsl_vector_get(x,1); //printf("theta0 = %.8f, chi0 = %.8f\n",theta0,chi0); //Check for sensible values if(fabs(chi0) > pi/2){ //Out of domain return GSL_EDOM; } //Setup initial ODE coordinate vector components double results[2]; (*(*mip).rsys_p)((*mip).bnd,theta0,results); //result[0] = r0, results[1] = normang0 const double n = (*(*mip).nfunc_p)((*mip).idx,results[0],theta0); const double phi0 = results[1] + chi0; const double pr0 = n*cos(phi0-theta0); const double ptheta0 = n*results[0]*sin(phi0-theta0); //Compute ray rayevolve( //Storage arrays raypath_r,raypath_theta,bounceindices,bouncepts_chi,lengths, //Initial conditions results[0],theta0,pr0,ptheta0, //Simulation parameters 200.0,order+1,1e-12,1e-12, //Cavity parameters (*mip).bnd,(*mip).rfunc_p,(*mip).rsys_p, (*mip).idx,(*mip).nfunc_p,(*mip).nderiv_p); //Store difference in initial and final bounce locations (print for debugging) const double dtheta = fmod(raypath_theta[bounceindices[order]-1] - raypath_theta[bounceindices[0]-1] + pi, 2*pi) - pi; const double dchi = bouncepts_chi[order] - bouncepts_chi[0]; gsl_vector_set(f,0,dtheta); gsl_vector_set(f,1,dchi); //printf("dtheta = %.8f, dchi = %.8f\n",dtheta,dchi); //Test stopping criterion if(gsl_multiroot_test_residual(f,(*mip).rtol) != GSL_CONTINUE){ //Record mode bounce data in results array (to avoid running simulation again) double *modebounces = (double *)(*mip).modebounces; //theta values stored in first half of array (first column after reshaping) //chi values stored in second half of array (second column after reshaping) int i; for(i=0; i<order; i+=1){ modebounces[i] = raypath_theta[bounceindices[i]-1]; modebounces[order+i] = bouncepts_chi[i]; } } return GSL_SUCCESS; } //############################################################################# //Solver function int findmode( //mode-specific variables long order, double modebounces[], //initial position on PSS double theta0, double chi0, //root-finding algorithm parameters double rtol, long maxiter, //Cavity parameters void *bnd, double (*rfunc_p)(void *bnd,double theta), void (*rsys_p)(void *bnd, double theta,double results[]), void *idx, double (*nfunc_p)(void *idx, double r, double theta), void (*nderiv_p)(void *idx, double r, double theta,double results[])){ //Preallocate arrays for reuse long bounceindices[30], lengths[2]; double raypath_r[50000],raypath_theta[50000],bouncepts_chi[30]; //Condense input mode data into modeinfo structs modeinfo mi = {bnd,rfunc_p,rsys_p,idx,nfunc_p,nderiv_p,order,rtol, raypath_r,raypath_theta,bounceindices,bouncepts_chi,lengths,modebounces}; //Store initial guess gsl_vector *x0 = gsl_vector_alloc(2); gsl_vector_set(x0,0,theta0); gsl_vector_set(x0,1,chi0); //Initiate solver const gsl_multiroot_fsolver_type *fs_t = gsl_multiroot_fsolver_dnewton; gsl_multiroot_fsolver *fs = gsl_multiroot_fsolver_alloc(fs_t,2); gsl_multiroot_function mrf = {rootfunc,2,&mi}; gsl_multiroot_fsolver_set(fs,&mrf,x0); gsl_set_error_handler_off(); int status, count = 0; //Iterate solver while(count != maxiter){ status = gsl_multiroot_fsolver_iterate(fs); if(status != GSL_SUCCESS) break; //Some error has occurred gsl_vector *f = gsl_multiroot_fsolver_f(fs); if(gsl_multiroot_test_residual(f,rtol) != GSL_CONTINUE) break; //Done! count += 1; } //Free memory gsl_multiroot_fsolver_free(fs); gsl_vector_free(x0); //In case of error or aborted computation, indicate no result if((status != GSL_SUCCESS) || (count == maxiter)) return 1; return 0; }
{ "alphanum_fraction": 0.5963930348, "avg_line_length": 37.3953488372, "ext": "c", "hexsha": "d5dae4b81df6816b1423e2f9844fa7665b996bc4", "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": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amyascwk/CavChaos.jl", "max_forks_repo_path": "src/mode.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "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": "amyascwk/CavChaos.jl", "max_issues_repo_path": "src/mode.c", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "f4a2f9801af5e67a5648d37901a4e5cd377c064d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amyascwk/CavChaos.jl", "max_stars_repo_path": "src/mode.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1648, "size": 6432 }
#include "ccv.h" #include "ccv_internal.h" #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif #ifdef USE_DISPATCH #include <dispatch/dispatch.h> #endif const ccv_icf_param_t ccv_icf_default_params = { .min_neighbors = 2, .threshold = 0, .step_through = 2, .flags = 0, .interval = 8, }; // cube root approximation using bit hack for 32-bit float // provides a very crude approximation static inline float cbrt_5_f32(float f) { unsigned int* p = (unsigned int*)(&f); *p = *p / 3 + 709921077; return f; } // iterative cube root approximation using Halley's method (float) static inline float cbrta_halley_f32(const float a, const float R) { const float a3 = a * a * a; const float b = a * (a3 + R + R) / (a3 + a3 + R); return b; } // Code based on // http://metamerist.com/cbrt/cbrt.htm // cube root approximation using 2 iterations of Halley's method (float) // this is expected to be ~2.5x times faster than std::pow(x, 3) static inline float fast_cube_root(const float d) { float a = cbrt_5_f32(d); a = cbrta_halley_f32(a, d); return cbrta_halley_f32(a, d); } static inline void _ccv_rgb_to_luv(const float r, const float g, const float b, float* pl, float* pu, float* pv) { const float x = 0.412453f * r + 0.35758f * g + 0.180423f * b; const float y = 0.212671f * r + 0.71516f * g + 0.072169f * b; const float z = 0.019334f * r + 0.119193f * g + 0.950227f * b; const float x_n = 0.312713f, y_n = 0.329016f; const float uv_n_divisor = -2.f * x_n + 12.f * y_n + 3.f; const float u_n = 4.f * x_n / uv_n_divisor; const float v_n = 9.f * y_n / uv_n_divisor; const float uv_divisor = ccv_max((x + 15.f * y + 3.f * z), FLT_EPSILON); const float u = 4.f * x / uv_divisor; const float v = 9.f * y / uv_divisor; const float y_cube_root = fast_cube_root(y); const float l_value = ccv_max(0.f, ((116.f * y_cube_root) - 16.f)); const float u_value = 13.f * l_value * (u - u_n); const float v_value = 13.f * l_value * (v - v_n); // L in [0, 100], U in [-134, 220], V in [-140, 122] *pl = l_value * (255.f / 100.f); *pu = (u_value + 134.f) * (255.f / (220.f + 134.f)); *pv = (v_value + 140.f) * (255.f / (122.f + 140.f)); } // generating the integrate channels features (which combines the grayscale, gradient magnitude, and 6-direction HOG) void ccv_icf(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type) { int ch = CCV_GET_CHANNEL(a->type); assert(ch == 1 || ch == 3); int nchr = (ch == 1) ? 8 : 10; ccv_declare_derived_signature(sig, a->sig != 0, ccv_sign_with_literal("ccv_icf"), a->sig, CCV_EOF_SIGN); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | nchr, CCV_32F | nchr, sig); ccv_object_return_if_cached(, db); ccv_dense_matrix_t* ag = 0; ccv_dense_matrix_t* mg = 0; ccv_gradient(a, &ag, 0, &mg, 0, 1, 1); float* agp = ag->data.f32; float* mgp = mg->data.f32; float* dbp = db->data.f32; ccv_zero(db); int i, j, k; unsigned char* a_ptr = a->data.u8; float magnitude_scaling = 1 / sqrtf(2); // regularize it to 0~1 if (ch == 1) { #define for_block(_, _for_get) \ for (i = 0; i < a->rows; i++) \ { \ for (j = 0; j < a->cols; j++) \ { \ dbp[0] = _for_get(a_ptr, j, 0); \ dbp[1] = mgp[j] * magnitude_scaling; \ float agr = (ccv_clamp(agp[j] <= 180 ? agp[j] : agp[j] - 180, 0, 179.99) / 180.0) * 6; \ int ag0 = (int)agr; \ int ag1 = ag0 < 5 ? ag0 + 1 : 0; \ agr = agr - ag0; \ dbp[2 + ag0] = dbp[1] * (1 - agr); \ dbp[2 + ag1] = dbp[1] * agr; \ dbp += 8; \ } \ a_ptr += a->step; \ agp += a->cols; \ mgp += a->cols; \ } ccv_matrix_getter(a->type, for_block); #undef for_block } else { // color one, luv, gradient magnitude, and 6-direction HOG #define for_block(_, _for_get) \ for (i = 0; i < a->rows; i++) \ { \ for (j = 0; j < a->cols; j++) \ { \ _ccv_rgb_to_luv(_for_get(a_ptr, j * ch, 0) / 255.0, \ _for_get(a_ptr, j * ch + 1, 0) / 255.0, \ _for_get(a_ptr, j * ch + 2, 0) / 255.0, \ dbp, dbp + 1, dbp + 2); \ float agv = agp[j * ch]; \ float mgv = mgp[j * ch]; \ for (k = 1; k < ch; k++) \ { \ if (mgp[j * ch + k] > mgv) \ { \ mgv = mgp[j * ch + k]; \ agv = agp[j * ch + k]; \ } \ } \ dbp[3] = mgv * magnitude_scaling; \ float agr = (ccv_clamp(agv <= 180 ? agv : agv - 180, 0, 179.99) / 180.0) * 6; \ int ag0 = (int)agr; \ int ag1 = ag0 < 5 ? ag0 + 1 : 0; \ agr = agr - ag0; \ dbp[4 + ag0] = dbp[3] * (1 - agr); \ dbp[4 + ag1] = dbp[3] * agr; \ dbp += 10; \ } \ a_ptr += a->step; \ agp += a->cols * ch; \ mgp += a->cols * ch; \ } ccv_matrix_getter(a->type, for_block); #undef for_block } ccv_matrix_free(ag); ccv_matrix_free(mg); } static inline float _ccv_icf_run_feature(ccv_icf_feature_t* feature, float* ptr, int cols, int ch, int x, int y) { float c = feature->beta; int q; for (q = 0; q < feature->count; q++) c += (ptr[(feature->sat[q * 2 + 1].x + x + 1 + (feature->sat[q * 2 + 1].y + y + 1) * cols) * ch + feature->channel[q]] - ptr[(feature->sat[q * 2].x + x + (feature->sat[q * 2 + 1].y + y + 1) * cols) * ch + feature->channel[q]] + ptr[(feature->sat[q * 2].x + x + (feature->sat[q * 2].y + y) * cols) * ch + feature->channel[q]] - ptr[(feature->sat[q * 2 + 1].x + x + 1 + (feature->sat[q * 2].y + y) * cols) * ch + feature->channel[q]]) * feature->alpha[q]; return c; } static inline int _ccv_icf_run_weak_classifier(ccv_icf_decision_tree_t* weak_classifier, float* ptr, int cols, int ch, int x, int y) { float c = _ccv_icf_run_feature(weak_classifier->features, ptr, cols, ch, x, y); if (c > 0) { if (!(weak_classifier->pass & 0x1)) return 1; return _ccv_icf_run_feature(weak_classifier->features + 2, ptr, cols, ch, x, y) > 0; } else { if (!(weak_classifier->pass & 0x2)) return 0; return _ccv_icf_run_feature(weak_classifier->features + 1, ptr, cols, ch, x, y) > 0; } } #ifdef HAVE_GSL static void _ccv_icf_randomize_feature(gsl_rng* rng, ccv_size_t size, int minimum, ccv_icf_feature_t* feature, int grayscale) { feature->count = gsl_rng_uniform_int(rng, CCV_ICF_SAT_MAX) + 1; assert(feature->count <= CCV_ICF_SAT_MAX); int i; feature->beta = 0; for (i = 0; i < feature->count; i++) { int x0, y0, x1, y1; do { x0 = gsl_rng_uniform_int(rng, size.width); x1 = gsl_rng_uniform_int(rng, size.width); y0 = gsl_rng_uniform_int(rng, size.height); y1 = gsl_rng_uniform_int(rng, size.height); } while ((ccv_max(x0, x1) - ccv_min(x0, x1) + 1) * (ccv_max(y0, y1) - ccv_min(y0, y1) + 1) < (minimum + 1) * (minimum + 1) || (ccv_max(x0, x1) - ccv_min(x0, x1) + 1) < minimum || (ccv_max(y0, y1) - ccv_min(y0, y1) + 1) < minimum); feature->sat[i * 2].x = ccv_min(x0, x1); feature->sat[i * 2].y = ccv_min(y0, y1); feature->sat[i * 2 + 1].x = ccv_max(x0, x1); feature->sat[i * 2 + 1].y = ccv_max(y0, y1); feature->channel[i] = gsl_rng_uniform_int(rng, grayscale ? 8 : 10); // 8-channels for grayscale, and 10-channels for rgb assert(feature->channel[i] >= 0 && feature->channel[i] < (grayscale ? 8 : 10)); feature->alpha[i] = gsl_rng_uniform(rng) / (float)((feature->sat[i * 2 + 1].x - feature->sat[i * 2].x + 1) * (feature->sat[i * 2 + 1].y - feature->sat[i * 2].y + 1)); } } static void _ccv_icf_check_params(ccv_icf_new_param_t params) { assert(params.size.width > 0 && params.size.height > 0); assert(params.deform_shift >= 0); assert(params.deform_angle >= 0); assert(params.deform_scale >= 0 && params.deform_scale < 1); assert(params.feature_size > 0); assert(params.acceptance > 0 && params.acceptance < 1.0); } static ccv_dense_matrix_t* _ccv_icf_capture_feature(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_decimal_pose_t pose, ccv_size_t size, ccv_margin_t margin, float deform_angle, float deform_scale, float deform_shift) { float rotate_x = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.pitch; float rotate_y = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.yaw; float rotate_z = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.roll; float scale = gsl_rng_uniform(rng); // to make the scale evenly distributed, for example, when deforming of 1/2 ~ 2, we want it to distribute around 1, rather than any average of 1/2 ~ 2 scale = (1 + deform_scale * scale) / (1 + deform_scale * (1 - scale)); float scale_ratio = sqrtf((float)(size.width * size.height) / (pose.a * pose.b * 4)); float m00 = cosf(rotate_z) * scale; float m01 = cosf(rotate_y) * sinf(rotate_z) * scale; float m02 = (deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) / scale_ratio + pose.x + (margin.right - margin.left) / scale_ratio - image->cols * 0.5; float m10 = (sinf(rotate_y) * cosf(rotate_z) - cosf(rotate_x) * sinf(rotate_z)) * scale; float m11 = (sinf(rotate_y) * sinf(rotate_z) + cosf(rotate_x) * cosf(rotate_z)) * scale; float m12 = (deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) / scale_ratio + pose.y + (margin.bottom - margin.top) / scale_ratio - image->rows * 0.5; float m20 = (sinf(rotate_y) * cosf(rotate_z) + sinf(rotate_x) * sinf(rotate_z)) * scale; float m21 = (sinf(rotate_y) * sinf(rotate_z) - sinf(rotate_x) * cosf(rotate_z)) * scale; float m22 = cosf(rotate_x) * cosf(rotate_y); ccv_dense_matrix_t* b = 0; ccv_perspective_transform(image, &b, 0, m00, m01, m02, m10, m11, m12, m20, m21, m22); ccv_dense_matrix_t* resize = 0; // have 1px border around the grayscale image because we need these to compute correct gradient feature ccv_size_t scale_size = { .width = (int)((size.width + margin.left + margin.right + 2) / scale_ratio + 0.5), .height = (int)((size.height + margin.top + margin.bottom + 2) / scale_ratio + 0.5), }; assert(scale_size.width > 0 && scale_size.height > 0); ccv_slice(b, (ccv_matrix_t**)&resize, 0, (int)(b->rows * 0.5 - (size.height + margin.top + margin.bottom + 2) / scale_ratio * 0.5 + 0.5), (int)(b->cols * 0.5 - (size.width + margin.left + margin.right + 2) / scale_ratio * 0.5 + 0.5), scale_size.height, scale_size.width); ccv_matrix_free(b); b = 0; if (scale_ratio > 1) ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_INTER_CUBIC); else ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_INTER_AREA); ccv_matrix_free(resize); return b; } typedef struct { uint8_t correct:1; double weight; float rate; } ccv_icf_example_state_t; typedef struct { uint8_t classifier:1; uint8_t positives:1; uint8_t negatives:1; uint8_t features:1; uint8_t example_state:1; uint8_t precomputed:1; } ccv_icf_classifier_cascade_persistence_state_t; typedef struct { uint32_t index; float value; } ccv_icf_value_index_t; typedef struct { ccv_function_state_reserve_field; int i; int bootstrap; ccv_icf_new_param_t params; ccv_icf_classifier_cascade_t* classifier; ccv_array_t* positives; ccv_array_t* negatives; ccv_icf_feature_t* features; ccv_size_t size; ccv_margin_t margin; ccv_icf_example_state_t* example_state; uint8_t* precomputed; ccv_icf_classifier_cascade_persistence_state_t x; } ccv_icf_classifier_cascade_state_t; static void _ccv_icf_write_classifier_cascade_state(ccv_icf_classifier_cascade_state_t* state, const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/state", directory); FILE* w = fopen(filename, "w+"); fprintf(w, "%d %d %d\n", state->line_no, state->i, state->bootstrap); fprintf(w, "%d %d %d\n", state->params.feature_size, state->size.width, state->size.height); fprintf(w, "%d %d %d %d\n", state->margin.left, state->margin.top, state->margin.right, state->margin.bottom); fclose(w); int i, q; if (!state->x.positives) { snprintf(filename, 1024, "%s/positives", directory); w = fopen(filename, "wb+"); fwrite(&state->positives->rnum, sizeof(state->positives->rnum), 1, w); fwrite(&state->positives->rsize, sizeof(state->positives->rsize), 1, w); for (i = 0; i < state->positives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(state->positives, i); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); fwrite(a, 1, state->positives->rsize, w); } fclose(w); state->x.positives = 1; } if (!state->x.negatives) { assert(state->negatives->rsize == state->positives->rsize); snprintf(filename, 1024, "%s/negatives", directory); w = fopen(filename, "wb+"); fwrite(&state->negatives->rnum, sizeof(state->negatives->rnum), 1, w); fwrite(&state->negatives->rsize, sizeof(state->negatives->rsize), 1, w); for (i = 0; i < state->negatives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(state->negatives, i); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); fwrite(a, 1, state->negatives->rsize, w); } fclose(w); state->x.negatives = 1; } if (!state->x.features) { snprintf(filename, 1024, "%s/features", directory); w = fopen(filename, "w+"); for (i = 0; i < state->params.feature_size; i++) { ccv_icf_feature_t* feature = state->features + i; fprintf(w, "%d %a\n", feature->count, feature->beta); for (q = 0; q < feature->count; q++) fprintf(w, "%d %a %d %d %d %d\n", feature->channel[q], feature->alpha[q], feature->sat[q * 2].x, feature->sat[q * 2].y, feature->sat[q * 2 + 1].x, feature->sat[q * 2 + 1].y); } fclose(w); state->x.features = 1; } if (!state->x.example_state) { snprintf(filename, 1024, "%s/example_state", directory); w = fopen(filename, "w+"); for (i = 0; i < state->positives->rnum + state->negatives->rnum; i++) fprintf(w, "%u %la %a\n", (uint32_t)state->example_state[i].correct, state->example_state[i].weight, state->example_state[i].rate); fclose(w); state->x.example_state = 1; } if (!state->x.precomputed) { size_t step = (3 * (state->positives->rnum + state->negatives->rnum) + 3) & -4; snprintf(filename, 1024, "%s/precomputed", directory); w = fopen(filename, "wb+"); fwrite(state->precomputed, 1, step * state->params.feature_size, w); fclose(w); state->x.precomputed = 1; } if (!state->x.classifier) { snprintf(filename, 1024, "%s/cascade", directory); ccv_icf_write_classifier_cascade(state->classifier, filename); state->x.classifier = 1; } } static void _ccv_icf_read_classifier_cascade_state(const char* directory, ccv_icf_classifier_cascade_state_t* state) { char filename[1024]; state->line_no = state->i = 0; state->bootstrap = 0; snprintf(filename, 1024, "%s/state", directory); FILE* r = fopen(filename, "r"); if (r) { int feature_size; fscanf(r, "%d %d %d", &state->line_no, &state->i, &state->bootstrap); fscanf(r, "%d %d %d", &feature_size, &state->size.width, &state->size.height); fscanf(r, "%d %d %d %d", &state->margin.left, &state->margin.top, &state->margin.right, &state->margin.bottom); assert(feature_size == state->params.feature_size); fclose(r); } int i, q; snprintf(filename, 1024, "%s/positives", directory); r = fopen(filename, "rb"); state->x.precomputed = state->x.features = state->x.example_state = state->x.classifier = state->x.positives = state->x.negatives = 1; if (r) { int rnum, rsize; fread(&rnum, sizeof(rnum), 1, r); fread(&rsize, sizeof(rsize), 1, r); state->positives = ccv_array_new(rsize, rnum, 0); ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)alloca(rsize); for (i = 0; i < rnum; i++) { fread(a, 1, rsize, r); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); ccv_array_push(state->positives, a); } fclose(r); } snprintf(filename, 1024, "%s/negatives", directory); r = fopen(filename, "rb"); if (r) { int rnum, rsize; fread(&rnum, sizeof(rnum), 1, r); fread(&rsize, sizeof(rsize), 1, r); state->negatives = ccv_array_new(rsize, rnum, 0); ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)alloca(rsize); for (i = 0; i < rnum; i++) { fread(a, 1, rsize, r); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); ccv_array_push(state->negatives, a); } fclose(r); } snprintf(filename, 1024, "%s/features", directory); r = fopen(filename, "r"); if (r) { state->features = (ccv_icf_feature_t*)ccmalloc(state->params.feature_size * sizeof(ccv_icf_feature_t)); for (i = 0; i < state->params.feature_size; i++) { ccv_icf_feature_t* feature = state->features + i; fscanf(r, "%d %a", &feature->count, &feature->beta); for (q = 0; q < feature->count; q++) fscanf(r, "%d %a %d %d %d %d", &feature->channel[q], &feature->alpha[q], &feature->sat[q * 2].x, &feature->sat[q * 2].y, &feature->sat[q * 2 + 1].x, &feature->sat[q * 2 + 1].y); } fclose(r); } snprintf(filename, 1024, "%s/example_state", directory); r = fopen(filename, "r"); if (r) { state->example_state = (ccv_icf_example_state_t*)ccmalloc((state->positives->rnum + state->negatives->rnum) * sizeof(ccv_icf_example_state_t)); for (i = 0; i < state->positives->rnum + state->negatives->rnum; i++) { uint32_t correct; double weight; float rate; fscanf(r, "%u %la %a", &correct, &weight, &rate); state->example_state[i].correct = correct; state->example_state[i].weight = weight; state->example_state[i].rate = rate; } fclose(r); } else state->example_state = 0; snprintf(filename, 1024, "%s/precomputed", directory); r = fopen(filename, "rb"); if (r) { size_t step = (3 * (state->positives->rnum + state->negatives->rnum) + 3) & -4; state->precomputed = (uint8_t*)ccmalloc(sizeof(uint8_t) * state->params.feature_size * step); fread(state->precomputed, 1, step * state->params.feature_size, r); fclose(r); } else state->precomputed = 0; snprintf(filename, 1024, "%s/cascade", directory); state->classifier = ccv_icf_read_classifier_cascade(filename); if (!state->classifier) { state->classifier = (ccv_icf_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_classifier_cascade_t)); state->classifier->count = 0; state->classifier->grayscale = state->params.grayscale; state->classifier->weak_classifiers = (ccv_icf_decision_tree_t*)ccmalloc(sizeof(ccv_icf_decision_tree_t) * state->params.weak_classifier); } else { if (state->classifier->count < state->params.weak_classifier) state->classifier->weak_classifiers = (ccv_icf_decision_tree_t*)ccrealloc(state->classifier->weak_classifiers, sizeof(ccv_icf_decision_tree_t) * state->params.weak_classifier); } } #define less_than(s1, s2, aux) ((s1).value < (s2).value) static CCV_IMPLEMENT_QSORT(_ccv_icf_precomputed_ordering, ccv_icf_value_index_t, less_than) #undef less_than static inline void _ccv_icf_3_uint8_to_1_uint1_1_uint23(uint8_t* u8, uint8_t* u1, uint32_t* uint23) { *u1 = (u8[0] >> 7); *uint23 = (((uint32_t)(u8[0] & 0x7f)) << 16) | ((uint32_t)(u8[1]) << 8) | u8[2]; } static inline uint32_t _ccv_icf_3_uint8_to_1_uint23(uint8_t* u8) { return (((uint32_t)(u8[0] & 0x7f)) << 16) | ((uint32_t)(u8[1]) << 8) | u8[2]; } static inline void _ccv_icf_1_uint1_1_uint23_to_3_uint8(uint8_t u1, uint32_t u23, uint8_t* u8) { u8[0] = ((u1 << 7) | (u23 >> 16)) & 0xff; u8[1] = (u23 >> 8) & 0xff; u8[2] = u23 & 0xff; } static float _ccv_icf_run_feature_on_example(ccv_icf_feature_t* feature, ccv_dense_matrix_t* a) { ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); float c = _ccv_icf_run_feature(feature, ptr, sat->cols, ch, 1, 1); ccv_matrix_free(sat); return c; } static uint8_t* _ccv_icf_precompute_features(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives) { int i, j; // we use 3 bytes to represent the sorted index, and compute feature result (float) on fly size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; uint8_t* precomputed = (uint8_t*)ccmalloc(sizeof(uint8_t) * feature_size * step); ccv_icf_value_index_t* sortkv = (ccv_icf_value_index_t*)ccmalloc(sizeof(ccv_icf_value_index_t) * (positives->rnum + negatives->rnum)); printf(" - precompute features using %uM memory temporarily\n", (uint32_t)((sizeof(float) * (positives->rnum + negatives->rnum) * feature_size + sizeof(uint8_t) * feature_size * step) / (1024 * 1024))); float* featval = (float*)ccmalloc(sizeof(float) * feature_size * (positives->rnum + negatives->rnum)); ccv_disable_cache(); // clean up cache so we have enough space to run it #ifdef USE_DISPATCH dispatch_semaphore_t sema = dispatch_semaphore_create(1); dispatch_apply(positives->rnum + negatives->rnum, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i) { #else for (i = 0; i < positives->rnum + negatives->rnum; i++) { #endif #ifdef USE_DISPATCH dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); #endif if (i % 37 == 0 || i == positives->rnum + negatives->rnum - 1) // don't flush too fast FLUSH(" - precompute %d features through %d%% (%d / %d) examples", feature_size, (int)(i + 1) * 100 / (positives->rnum + negatives->rnum), (int)i + 1, positives->rnum + negatives->rnum); #ifdef USE_DISPATCH dispatch_semaphore_signal(sema); int j; #endif ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(i < positives->rnum ? positives : negatives, i < positives->rnum ? i : i - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); for (j = 0; j < feature_size; j++) { ccv_icf_feature_t* feature = features + j; float c = _ccv_icf_run_feature(feature, ptr, sat->cols, ch, 1, 1); assert(isfinite(c)); featval[(size_t)j * (positives->rnum + negatives->rnum) + i] = c; } ccv_matrix_free(sat); #ifdef USE_DISPATCH }); dispatch_release(sema); #else } #endif printf("\n"); uint8_t* computed = precomputed; float* pfeatval = featval; for (i = 0; i < feature_size; i++) { if (i % 37 == 0 || i == feature_size - 1) // don't flush too fast FLUSH(" - precompute %d examples through %d%% (%d / %d) features", positives->rnum + negatives->rnum, (i + 1) * 100 / feature_size, i + 1, feature_size); for (j = 0; j < positives->rnum + negatives->rnum; j++) sortkv[j].value = pfeatval[j], sortkv[j].index = j; _ccv_icf_precomputed_ordering(sortkv, positives->rnum + negatives->rnum, 0); // the first flag denotes if the subsequent one are equal to the previous one (if so, we have to skip both of them) for (j = 0; j < positives->rnum + negatives->rnum - 1; j++) _ccv_icf_1_uint1_1_uint23_to_3_uint8(sortkv[j].value == sortkv[j + 1].value, sortkv[j].index, computed + j * 3); j = positives->rnum + negatives->rnum - 1; _ccv_icf_1_uint1_1_uint23_to_3_uint8(0, sortkv[j].index, computed + j * 3); computed += step; pfeatval += positives->rnum + negatives->rnum; } ccfree(featval); ccfree(sortkv); printf("\n - features are precomputed on examples and will occupy %uM memory\n", (uint32_t)((feature_size * step) / (1024 * 1024))); return precomputed; } typedef struct { uint32_t pass; double weigh[4]; int first_feature; uint8_t* lut; } ccv_icf_decision_tree_cache_t; static inline float _ccv_icf_compute_threshold_between(ccv_icf_feature_t* feature, uint8_t* computed, ccv_array_t* positives, ccv_array_t* negatives, int index0, int index1) { float c[2]; uint32_t b[2] = { _ccv_icf_3_uint8_to_1_uint23(computed + index0 * 3), _ccv_icf_3_uint8_to_1_uint23(computed + index1 * 3), }; ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(b[0] < positives->rnum ? positives : negatives, b[0] < positives->rnum ? b[0] : b[0] - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place c[0] = _ccv_icf_run_feature_on_example(feature, a); a = (ccv_dense_matrix_t*)ccv_array_get(b[1] < positives->rnum ? positives : negatives, b[1] < positives->rnum ? b[1] : b[1] - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place c[1] = _ccv_icf_run_feature_on_example(feature, a); return (c[0] + c[1]) * 0.5; } static inline void _ccv_icf_example_correct(ccv_icf_example_state_t* example_state, uint8_t* computed, uint8_t* lut, int leaf, ccv_array_t* positives, ccv_array_t* negatives, int start, int end) { int i; for (i = start; i <= end; i++) { uint32_t index = _ccv_icf_3_uint8_to_1_uint23(computed + i * 3); if (!lut || lut[index] == leaf) example_state[index].correct = (index < positives->rnum); } } typedef struct { int error_index; double error_rate; double weigh[2]; int count[2]; } ccv_icf_first_feature_find_t; static ccv_icf_decision_tree_cache_t _ccv_icf_find_first_feature(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_feature_t* feature) { int i; assert(feature != 0); ccv_icf_decision_tree_cache_t intermediate_cache; double aweigh0 = 0, aweigh1 = 0; for (i = 0; i < positives->rnum; i++) aweigh1 += example_state[i].weight, example_state[i].correct = 0; // assuming positive examples we get wrong for (i = positives->rnum; i < positives->rnum + negatives->rnum; i++) aweigh0 += example_state[i].weight, example_state[i].correct = 1; // assuming negative examples we get right size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; ccv_icf_first_feature_find_t* feature_find = (ccv_icf_first_feature_find_t*)ccmalloc(sizeof(ccv_icf_first_feature_find_t) * feature_size); #ifdef USE_DISPATCH dispatch_apply(feature_size, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i) { #else for (i = 0; i < feature_size; i++) { #endif ccv_icf_first_feature_find_t min_find = { .error_rate = 1.0, .error_index = 0, .weigh = {0, 0}, .count = {0, 0}, }; double weigh[2] = {0, 0}; int count[2] = {0, 0}; int j; uint8_t* computed = precomputed + step * i; for (j = 0; j < positives->rnum + negatives->rnum; j++) { uint8_t skip; uint32_t index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &index); conditional_assert(j == positives->rnum + negatives->rnum - 1, !skip); assert(index >= 0 && index < positives->rnum + negatives->rnum); weigh[index < positives->rnum] += example_state[index].weight; assert(example_state[index].weight > 0); assert(weigh[0] <= aweigh0 + 1e-10 && weigh[1] <= aweigh1 + 1e-10); ++count[index < positives->rnum]; if (skip) // the current index is equal to the next one, we cannot differentiate, therefore, skip continue; double error_rate = ccv_min(weigh[0] + aweigh1 - weigh[1], weigh[1] + aweigh0 - weigh[0]); assert(error_rate > 0); if (error_rate < min_find.error_rate) { min_find.error_index = j; min_find.error_rate = error_rate; min_find.weigh[0] = weigh[0]; min_find.weigh[1] = weigh[1]; min_find.count[0] = count[0]; min_find.count[1] = count[1]; } } feature_find[i] = min_find; #ifdef USE_DISPATCH }); #else } #endif ccv_icf_first_feature_find_t best = { .error_rate = 1.0, .error_index = -1, .weigh = {0, 0}, .count = {0, 0}, }; int feature_index = 0; for (i = 0; i < feature_size; i++) if (feature_find[i].error_rate < best.error_rate) { best = feature_find[i]; feature_index = i; } ccfree(feature_find); *feature = features[feature_index]; uint8_t* computed = precomputed + step * feature_index; intermediate_cache.lut = (uint8_t*)ccmalloc(positives->rnum + negatives->rnum); assert(best.error_index < positives->rnum + negatives->rnum - 1 && best.error_index >= 0); if (best.weigh[0] + aweigh1 - best.weigh[1] < best.weigh[1] + aweigh0 - best.weigh[0]) { for (i = 0; i < positives->rnum + negatives->rnum; i++) intermediate_cache.lut[_ccv_icf_3_uint8_to_1_uint23(computed + i * 3)] = (i <= best.error_index); feature->beta = _ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // revert the sign of alpha, after threshold is computed for (i = 0; i < feature->count; i++) feature->alpha[i] = -feature->alpha[i]; intermediate_cache.weigh[0] = aweigh0 - best.weigh[0]; intermediate_cache.weigh[1] = aweigh1 - best.weigh[1]; intermediate_cache.weigh[2] = best.weigh[0]; intermediate_cache.weigh[3] = best.weigh[1]; intermediate_cache.pass = 3; if (best.count[0] == 0) intermediate_cache.pass &= 2; // only positive examples in the right, no need to build right leaf if (best.count[1] == positives->rnum) intermediate_cache.pass &= 1; // no positive examples in the left, no need to build left leaf if (!(intermediate_cache.pass & 1)) // mark positives in the right as correct, if we don't have right leaf _ccv_icf_example_correct(example_state, computed, 0, 0, positives, negatives, 0, best.error_index); } else { for (i = 0; i < positives->rnum + negatives->rnum; i++) intermediate_cache.lut[_ccv_icf_3_uint8_to_1_uint23(computed + i * 3)] = (i > best.error_index); feature->beta = -_ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); intermediate_cache.weigh[0] = best.weigh[0]; intermediate_cache.weigh[1] = best.weigh[1]; intermediate_cache.weigh[2] = aweigh0 - best.weigh[0]; intermediate_cache.weigh[3] = aweigh1 - best.weigh[1]; intermediate_cache.pass = 3; if (best.count[0] == negatives->rnum) intermediate_cache.pass &= 2; // only positive examples in the right, no need to build right leaf if (best.count[1] == 0) intermediate_cache.pass &= 1; // no positive examples in the left, no need to build left leaf if (!(intermediate_cache.pass & 1)) // mark positives in the right as correct if we don't have right leaf _ccv_icf_example_correct(example_state, computed, 0, 0, positives, negatives, best.error_index + 1, positives->rnum + negatives->rnum - 1); } intermediate_cache.first_feature = feature_index; return intermediate_cache; } typedef struct { int error_index; double error_rate; double weigh[2]; } ccv_icf_second_feature_find_t; static double _ccv_icf_find_second_feature(ccv_icf_decision_tree_cache_t intermediate_cache, int leaf, ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_feature_t* feature) { int i; size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; uint8_t* lut = intermediate_cache.lut; double* aweigh = intermediate_cache.weigh + leaf * 2; ccv_icf_second_feature_find_t* feature_find = (ccv_icf_second_feature_find_t*)ccmalloc(sizeof(ccv_icf_second_feature_find_t) * feature_size); #ifdef USE_DISPATCH dispatch_apply(feature_size, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i) { #else for (i = 0; i < feature_size; i++) { #endif ccv_icf_second_feature_find_t min_find = { .error_rate = 1.0, .error_index = 0, .weigh = {0, 0}, }; double weigh[2] = {0, 0}; uint8_t* computed = precomputed + step * i; int j, k; for (j = 0; j < positives->rnum + negatives->rnum; j++) { uint8_t skip; uint32_t index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &index); conditional_assert(j == positives->rnum + negatives->rnum - 1, !skip); assert(index >= 0 && index < positives->rnum + negatives->rnum); // only care about part of the data if (lut[index] == leaf) { uint8_t leaf_skip = 0; for (k = j + 1; skip; k++) { uint32_t new_index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &new_index); // if the next equal one is the same leaf, we cannot distinguish them, skip if ((leaf_skip = (lut[new_index] == leaf))) break; conditional_assert(k == positives->rnum + negatives->rnum - 1, !skip); } weigh[index < positives->rnum] += example_state[index].weight; if (leaf_skip) continue; assert(example_state[index].weight > 0); assert(weigh[0] <= aweigh[0] + 1e-10 && weigh[1] <= aweigh[1] + 1e-10); double error_rate = ccv_min(weigh[0] + aweigh[1] - weigh[1], weigh[1] + aweigh[0] - weigh[0]); if (error_rate < min_find.error_rate) { min_find.error_index = j; min_find.error_rate = error_rate; min_find.weigh[0] = weigh[0]; min_find.weigh[1] = weigh[1]; } } } feature_find[i] = min_find; #ifdef USE_DISPATCH }); #else } #endif ccv_icf_second_feature_find_t best = { .error_rate = 1.0, .error_index = -1, .weigh = {0, 0}, }; int feature_index = 0; for (i = 0; i < feature_size; i++) if (feature_find[i].error_rate < best.error_rate) { best = feature_find[i]; feature_index = i; } ccfree(feature_find); *feature = features[feature_index]; uint8_t* computed = precomputed + step * feature_index; assert(best.error_index < positives->rnum + negatives->rnum - 1 && best.error_index >= 0); if (best.weigh[0] + aweigh[1] - best.weigh[1] < best.weigh[1] + aweigh[0] - best.weigh[0]) { feature->beta = _ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // revert the sign of alpha, after threshold is computed for (i = 0; i < feature->count; i++) feature->alpha[i] = -feature->alpha[i]; // mark everything on the right properly _ccv_icf_example_correct(example_state, computed, lut, leaf, positives, negatives, 0, best.error_index); return best.weigh[1] + aweigh[0] - best.weigh[0]; } else { feature->beta = -_ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // mark everything on the right properly _ccv_icf_example_correct(example_state, computed, lut, leaf, positives, negatives, best.error_index + 1, positives->rnum + negatives->rnum - 1); return best.weigh[0] + aweigh[1] - best.weigh[1]; } } static double _ccv_icf_find_best_weak_classifier(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_decision_tree_t* weak_classifier) { // we are building the specific depth-2 decision tree ccv_icf_decision_tree_cache_t intermediate_cache = _ccv_icf_find_first_feature(features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features); // find the left feature // for the pass, 10 is the left branch, 01 is the right branch weak_classifier->pass = intermediate_cache.pass; double rate = 0; if (weak_classifier->pass & 0x2) rate += _ccv_icf_find_second_feature(intermediate_cache, 0, features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features + 1); else rate += intermediate_cache.weigh[0]; // the negative weights covered by first feature // find the right feature if (weak_classifier->pass & 0x1) rate += _ccv_icf_find_second_feature(intermediate_cache, 1, features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features + 2); else rate += intermediate_cache.weigh[3]; // the positive weights covered by first feature ccfree(intermediate_cache.lut); return rate; } static ccv_array_t* _ccv_icf_collect_validates(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* validatefiles, int grayscale) { ccv_array_t* validates = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), validatefiles->rnum, 0); int i; // collect tests for (i = 0; i < validatefiles->rnum; i++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(validatefiles, i); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, file_info->pose, size, margin, 0, 0, 0); feature->sig = 0; ccv_array_push(validates, feature); ccv_matrix_free(feature); ccv_matrix_free(image); } return validates; } static ccv_array_t* _ccv_icf_collect_positives(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* posfiles, int posnum, float deform_angle, float deform_scale, float deform_shift, int grayscale) { ccv_array_t* positives = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), posnum, 0); int i, j, q; // collect positives (with random deformation) for (i = 0; i < posnum;) { FLUSH(" - collect positives %d%% (%d / %d)", (i + 1) * 100 / posnum, i + 1, posnum); double ratio = (double)(posnum - i) / posfiles->rnum; for (j = 0; j < posfiles->rnum && i < posnum; j++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(posfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } for (q = 0; q < ratio; q++) if (q < (int)ratio || gsl_rng_uniform(rng) <= ratio - (int)ratio) { FLUSH(" - collect positives %d%% (%d / %d)", (i + 1) * 100 / posnum, i + 1, posnum); ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, file_info->pose, size, margin, deform_angle, deform_scale, deform_shift); feature->sig = 0; ccv_array_push(positives, feature); ccv_matrix_free(feature); ++i; if (i >= posnum) break; } ccv_matrix_free(image); } } printf("\n"); return positives; } static uint64_t* _ccv_icf_precompute_classifier_cascade(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* positives) { int step = ((cascade->count - 1) >> 6) + 1; uint64_t* precomputed = (uint64_t*)ccmalloc(sizeof(uint64_t) * positives->rnum * step); uint64_t* result = precomputed; int i, j; for (i = 0; i < positives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)(ccv_array_get(positives, i)); a->data.u8 = (uint8_t*)(a + 1); ccv_dense_matrix_t* icf = 0; ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); for (j = 0; j < cascade->count; j++) if (_ccv_icf_run_weak_classifier(cascade->weak_classifiers + j, ptr, sat->cols, ch, 1, 1)) precomputed[j >> 6] |= (1UL << (j & 63)); else precomputed[j >> 6] &= ~(1UL << (j & 63)); ccv_matrix_free(sat); precomputed += step; } return result; } #define less_than(s1, s2, aux) ((s1) > (s2)) static CCV_IMPLEMENT_QSORT(_ccv_icf_threshold_rating, float, less_than) #undef less_than static void _ccv_icf_classifier_cascade_soft_with_validates(ccv_array_t* validates, ccv_icf_classifier_cascade_t* cascade, double min_accept) { int i, j; int step = ((cascade->count - 1) >> 6) + 1; uint64_t* precomputed = _ccv_icf_precompute_classifier_cascade(cascade, validates); float* positive_rate = (float*)ccmalloc(sizeof(float) * validates->rnum); uint64_t* computed = precomputed; for (i = 0; i < validates->rnum; i++) { positive_rate[i] = 0; for (j = 0; j < cascade->count; j++) { uint64_t accept = computed[j >> 6] & (1UL << (j & 63)); positive_rate[i] += cascade->weak_classifiers[j].weigh[!!accept]; } computed += step; } _ccv_icf_threshold_rating(positive_rate, validates->rnum, 0); float threshold = positive_rate[ccv_min((int)(min_accept * (validates->rnum + 0.5) - 0.5), validates->rnum - 1)]; ccfree(positive_rate); computed = precomputed; // compute the final acceptance per validates / negatives with final threshold uint64_t* acceptance = (uint64_t*)cccalloc(((validates->rnum - 1) >> 6) + 1, sizeof(uint64_t)); int true_positives = 0; for (i = 0; i < validates->rnum; i++) { float rate = 0; for (j = 0; j < cascade->count; j++) { uint64_t accept = computed[j >> 6] & (1UL << (j & 63)); rate += cascade->weak_classifiers[j].weigh[!!accept]; } if (rate >= threshold) { acceptance[i >> 6] |= (1UL << (i & 63)); ++true_positives; } else acceptance[i >> 6] &= ~(1UL << (i & 63)); computed += step; } printf(" - at threshold %f, true positive rate: %f%%\n", threshold, (float)true_positives * 100 / validates->rnum); float* rate = (float*)cccalloc(validates->rnum, sizeof(float)); for (j = 0; j < cascade->count; j++) { computed = precomputed; for (i = 0; i < validates->rnum; i++) { uint64_t correct = computed[j >> 6] & (1UL << (j & 63)); rate[i] += cascade->weak_classifiers[j].weigh[!!correct]; computed += step; } float threshold = FLT_MAX; // find a threshold that keeps all accepted validates still acceptable for (i = 0; i < validates->rnum; i++) { uint64_t correct = acceptance[i >> 6] & (1UL << (i & 63)); if (correct && rate[i] < threshold) threshold = rate[i]; } cascade->weak_classifiers[j].threshold = threshold - 1e-10; } ccfree(rate); ccfree(acceptance); ccfree(precomputed); } typedef struct { ccv_point_t point; float sum; } ccv_point_with_sum_t; static void _ccv_icf_bootstrap_negatives(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* negatives, gsl_rng* rng, ccv_array_t* bgfiles, int negnum, int grayscale, int spread, ccv_icf_param_t params) { #ifdef USE_DISPATCH __block int i; #else int i; #endif #ifdef USE_DISPATCH __block int fppi = 0, is = 0; #else int fppi = 0, is = 0; #endif int t = 0; for (i = 0; i < negnum;) { double ratio = (double)(negnum - i) / bgfiles->rnum; #ifdef USE_DISPATCH dispatch_semaphore_t sem = dispatch_semaphore_create(1); dispatch_apply(bgfiles->rnum, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t j) { #else size_t j; for (j = 0; j < bgfiles->rnum; j++) { #endif int k, x, y, q, p; ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccmalloc(ccv_compute_dense_matrix_size(cascade->size.height + 2, cascade->size.width + 2, (grayscale ? CCV_C1 : CCV_C3) | CCV_8U)); #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i >= negnum || (spread && ratio < 1 && gsl_rng_uniform(rng) > ratio)) { ccfree(a); #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); return; #else continue; #endif } FLUSH(" - bootstrap negatives %d%% (%d / %d) [%u / %d] %s", (i + 1) * 100 / negnum, i + 1, negnum, (uint32_t)(j + 1), bgfiles->rnum, spread ? "" : "without statistic balancing"); #ifdef USE_DISPATCH gsl_rng* crng = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(crng, gsl_rng_get(rng)); dispatch_semaphore_signal(sem); #else gsl_rng* crng = rng; #endif ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(bgfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); return; #else continue; #endif } if (ccv_max(image->rows, image->cols) < 800 || image->rows <= (cascade->size.height - cascade->margin.top - cascade->margin.bottom) || image->cols <= (cascade->size.width - cascade->margin.left - cascade->margin.right)) // background is too small, blow it up to next scale { ccv_dense_matrix_t* blowup = 0; ccv_sample_up(image, &blowup, 0, 0, 0); ccv_matrix_free(image); image = blowup; } if (image->rows <= (cascade->size.height - cascade->margin.top - cascade->margin.bottom) || image->cols <= (cascade->size.width - cascade->margin.left - cascade->margin.right)) // background is still too small, abort { ccv_matrix_free(image); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); return; #else continue; #endif } double scale = pow(2., 1. / (params.interval + 1.)); int next = params.interval + 1; int scale_upto = (int)(log(ccv_min((double)image->rows / (cascade->size.height - cascade->margin.top - cascade->margin.bottom), (double)image->cols / (cascade->size.width - cascade->margin.left - cascade->margin.right))) / log(scale) - DBL_MIN) + 1; ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)ccmalloc(scale_upto * sizeof(ccv_dense_matrix_t*)); memset(pyr, 0, scale_upto * sizeof(ccv_dense_matrix_t*)); #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif ++is; // how many images are scanned #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif if (t % 2 != 0) ccv_flip(image, 0, 0, CCV_FLIP_X); if (t % 4 >= 2) ccv_flip(image, 0, 0, CCV_FLIP_Y); pyr[0] = image; for (q = 1; q < ccv_min(params.interval + 1, scale_upto); q++) ccv_resample(pyr[0], &pyr[q], 0, (int)(pyr[0]->rows / pow(scale, q)), (int)(pyr[0]->cols / pow(scale, q)), CCV_INTER_AREA); for (q = next; q < scale_upto; q++) ccv_sample_down(pyr[q - next], &pyr[q], 0, 0, 0); for (q = 0; q < scale_upto; q++) { #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i >= negnum) { #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif ccv_matrix_free(pyr[q]); continue; } #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif ccv_dense_matrix_t* bordered = 0; ccv_border(pyr[q], (ccv_matrix_t**)&bordered, 0, cascade->margin); ccv_matrix_free(pyr[q]); ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); assert(sat->rows == bordered->rows + 1 && sat->cols == bordered->cols + 1); int ch = CCV_GET_CHANNEL(sat->type); float* ptr = sat->data.f32 + sat->cols * ch; ccv_array_t* seq = ccv_array_new(sizeof(ccv_point_with_sum_t), 64, 0); for (y = 1; y < sat->rows - cascade->size.height - 2; y += params.step_through) { for (x = 1; x < sat->cols - cascade->size.width - 2; x += params.step_through) { int pass = 1; float sum = 0; for (p = 0; p < cascade->count; p++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + p; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, x, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_point_with_sum_t point; point.point = ccv_point(x - 1, y - 1); point.sum = sum; ccv_array_push(seq, &point); } } ptr += sat->cols * ch * params.step_through; } ccv_matrix_free(sat); // shuffle negatives so that we don't have too biased negatives #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif fppi += seq->rnum; // how many detections we have in total #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif if (seq->rnum > 0) { gsl_ran_shuffle(crng, ccv_array_get(seq, 0), seq->rnum, seq->rsize); /* so that we at least collect 10 from each scale */ for (p = 0; p < (spread ? ccv_min(10, seq->rnum) : seq->rnum); p++) // collect enough negatives from this scale { a = ccv_dense_matrix_new(cascade->size.height + 2, cascade->size.width + 2, (grayscale ? CCV_C1 : CCV_C3) | CCV_8U, a, 0); ccv_point_with_sum_t* point = (ccv_point_with_sum_t*)ccv_array_get(seq, p); ccv_slice(bordered, (ccv_matrix_t**)&a, 0, point->point.y, point->point.x, a->rows, a->cols); assert(bordered->rows >= point->point.y + a->rows && bordered->cols >= point->point.x + a->cols); a->sig = 0; // verify the data we sliced is worthy negative ccv_dense_matrix_t* icf = 0; ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); int pass = 1; float sum = 0; for (k = 0; k < cascade->count; k++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + k; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } ccv_matrix_free(sat); if (pass) { #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i < negnum) ccv_array_push(negatives, a); ++i; if (i >= negnum) { #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif break; } #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif } } } ccv_array_free(seq); ccv_matrix_free(bordered); } ccfree(pyr); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); }); dispatch_release(sem); #else } #endif if ((double)fppi / is <= (double)negnum / bgfiles->rnum) // if the targeted negative per image is bigger than our fppi, we don't prob anymore spread = 0; ++t; if (t > (spread ? 4 : 3) && !spread) // we've go over 4 or 3 transformations (original, flip x, flip y, flip x & y, [and original again]), and nothing we can do now break; } printf("\n"); } static ccv_array_t* _ccv_icf_collect_negatives(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* bgfiles, int negnum, float deform_angle, float deform_scale, float deform_shift, int grayscale) { ccv_array_t* negatives = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), negnum, 0); int i, j, q; // randomly collect negatives (with random deformation) for (i = 0; i < negnum;) { FLUSH(" - collect negatives %d%% (%d / %d)", (i + 1) * 100 / negnum, i + 1, negnum); double ratio = (double)(negnum - i) / bgfiles->rnum; for (j = 0; j < bgfiles->rnum && i < negnum; j++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(bgfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } double max_scale_ratio = ccv_min((double)image->rows / size.height, (double)image->cols / size.width); if (max_scale_ratio <= 0.5) // too small to be interesting continue; for (q = 0; q < ratio; q++) if (q < (int)ratio || gsl_rng_uniform(rng) <= ratio - (int)ratio) { FLUSH(" - collect negatives %d%% (%d / %d)", (i + 1) * 100 / negnum, i + 1, negnum); ccv_decimal_pose_t pose; double scale_ratio = gsl_rng_uniform(rng) * (max_scale_ratio - 0.5) + 0.5; pose.a = size.width * 0.5 * scale_ratio; pose.b = size.height * 0.5 * scale_ratio; pose.x = gsl_rng_uniform_int(rng, ccv_max((int)(image->cols - pose.a * 2 + 1.5), 1)) + pose.a; pose.y = gsl_rng_uniform_int(rng, ccv_max((int)(image->rows - pose.b * 2 + 1.5), 1)) + pose.b; pose.roll = pose.pitch = pose.yaw = 0; ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, pose, size, margin, deform_angle, deform_scale, deform_shift); feature->sig = 0; ccv_array_push(negatives, feature); ccv_matrix_free(feature); ++i; if (i >= negnum) break; } ccv_matrix_free(image); } } printf("\n"); return negatives; } #ifdef USE_SANITY_ASSERTION static double _ccv_icf_rate_weak_classifier(ccv_icf_decision_tree_t* weak_classifier, ccv_array_t* positives, ccv_array_t* negatives, ccv_icf_example_state_t* example_state) { int i; double rate = 0; for (i = 0; i < positives->rnum + negatives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(i < positives->rnum ? positives : negatives, i < positives->rnum ? i : i - positives->rnum); a->data.u8 = (uint8_t*)(a + 1); // re-host the pointer to the right place ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); if (i < positives->rnum) { if (_ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1)) { assert(example_state[i].correct); rate += example_state[i].weight; } else { assert(!example_state[i].correct); } } else { if (!_ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1)) { assert(example_state[i].correct); rate += example_state[i].weight; } else { assert(!example_state[i].correct); } } ccv_matrix_free(sat); } return rate; } #endif #endif ccv_icf_classifier_cascade_t* ccv_icf_classifier_cascade_new(ccv_array_t* posfiles, int posnum, ccv_array_t* bgfiles, int negnum, ccv_array_t* validatefiles, const char* dir, ccv_icf_new_param_t params) { #ifdef HAVE_GSL _ccv_icf_check_params(params); assert(posfiles->rnum > 0); assert(bgfiles->rnum > 0); assert(posnum > 0 && negnum > 0); printf("with %d positive examples and %d negative examples\n" "positive examples are going to be collected from %d positive images\n" "negative examples are are going to be collected from %d background images\n", posnum, negnum, posfiles->rnum, bgfiles->rnum); printf("use color? %s\n", params.grayscale ? "no" : "yes"); printf("feature pool size : %d\n" "weak classifier count : %d\n" "soft cascade acceptance : %lf\n" "minimum dimension of ICF feature : %d\n" "number of bootstrap : %d\n" "distortion on translation : %f\n" "distortion on rotation : %f\n" "distortion on scale : %f\n" "learn ICF classifier cascade at size %dx%d with margin (%d,%d,%d,%d)\n" "------------------------\n", params.feature_size, params.weak_classifier, params.acceptance, params.min_dimension, params.bootstrap, params.deform_shift, params.deform_angle, params.deform_scale, params.size.width, params.size.height, params.margin.left, params.margin.top, params.margin.right, params.margin.bottom); gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); // we will keep all states inside this structure for easier save / resume across process // this should work better than ad-hoc one we used in DPM / BBF implementation ccv_icf_classifier_cascade_state_t z; z.params = params; ccv_function_state_begin(_ccv_icf_read_classifier_cascade_state, z, dir); z.classifier->grayscale = params.grayscale; z.size = params.size; z.margin = params.margin; z.classifier->size = ccv_size(z.size.width + z.margin.left + z.margin.right, z.size.height + z.margin.top + z.margin.bottom); z.features = (ccv_icf_feature_t*)ccmalloc(sizeof(ccv_icf_feature_t) * params.feature_size); // generate random features for (z.i = 0; z.i < params.feature_size; z.i++) _ccv_icf_randomize_feature(rng, z.classifier->size, params.min_dimension, z.features + z.i, params.grayscale); z.x.features = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.positives = _ccv_icf_collect_positives(rng, z.size, z.margin, posfiles, posnum, params.deform_angle, params.deform_scale, params.deform_shift, params.grayscale); z.x.positives = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.negatives = _ccv_icf_collect_negatives(rng, z.size, z.margin, bgfiles, negnum, params.deform_angle, params.deform_scale, params.deform_shift, params.grayscale); z.x.negatives = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); for (z.bootstrap = 0; z.bootstrap <= params.bootstrap; z.bootstrap++) { z.example_state = (ccv_icf_example_state_t*)ccmalloc(sizeof(ccv_icf_example_state_t) * (z.negatives->rnum + z.positives->rnum)); memset(z.example_state, 0, sizeof(ccv_icf_example_state_t) * (z.negatives->rnum + z.positives->rnum)); for (z.i = 0; z.i < z.positives->rnum + z.negatives->rnum; z.i++) z.example_state[z.i].weight = (z.i < z.positives->rnum) ? 0.5 / z.positives->rnum : 0.5 / z.negatives->rnum; z.x.example_state = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.precomputed = _ccv_icf_precompute_features(z.features, params.feature_size, z.positives, z.negatives); z.x.precomputed = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); for (z.i = 0; z.i < params.weak_classifier; z.i++) { z.classifier->count = z.i + 1; printf(" - boost weak classifier %d of %d\n", z.i + 1, params.weak_classifier); int j; ccv_icf_decision_tree_t weak_classifier; double rate = _ccv_icf_find_best_weak_classifier(z.features, params.feature_size, z.positives, z.negatives, z.precomputed, z.example_state, &weak_classifier); assert(rate > 0.5); // it has to be better than random chance #ifdef USE_SANITY_ASSERTION double confirm_rate = _ccv_icf_rate_weak_classifier(&weak_classifier, z.positives, z.negatives, z.example_state); #endif double alpha = sqrt((1 - rate) / rate); double beta = 1.0 / alpha; double c = log(rate / (1 - rate)); weak_classifier.weigh[0] = -c; weak_classifier.weigh[1] = c; weak_classifier.threshold = 0; double reweigh = 0; for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++) { z.example_state[j].weight *= (z.example_state[j].correct) ? alpha : beta; z.example_state[j].rate += weak_classifier.weigh[!((j < z.positives->rnum) ^ z.example_state[j].correct)]; reweigh += z.example_state[j].weight; } reweigh = 1.0 / reweigh; #ifdef USE_SANITY_ASSERTION printf(" - on all examples, best feature at rate %lf, confirm rate %lf\n", rate, confirm_rate); #else printf(" - on all examples, best feature at rate %lf\n", rate); #endif // balancing the weight to sum 1.0 for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++) z.example_state[j].weight *= reweigh; z.classifier->weak_classifiers[z.i] = weak_classifier; // compute the threshold at given acceptance float threshold = z.example_state[0].rate; for (j = 1; j < z.positives->rnum; j++) if (z.example_state[j].rate < threshold) threshold = z.example_state[j].rate; int true_positives = 0, false_positives = 0; for (j = 0; j < z.positives->rnum; j++) if (z.example_state[j].rate >= threshold) ++true_positives; for (j = z.positives->rnum; j < z.positives->rnum + z.negatives->rnum; j++) if (z.example_state[j].rate >= threshold) ++false_positives; printf(" - at threshold %f, true positive rate: %f%%, false positive rate: %f%% (%d)\n", threshold, (float)true_positives * 100 / z.positives->rnum, (float)false_positives * 100 / z.negatives->rnum, false_positives); printf(" - first feature :\n"); for (j = 0; j < weak_classifier.features[0].count; j++) printf(" - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[0].channel[j], weak_classifier.features[0].sat[j * 2].x, weak_classifier.features[0].sat[j * 2].y, weak_classifier.features[0].sat[j * 2 + 1].x, weak_classifier.features[0].sat[j * 2 + 1].y); if (weak_classifier.pass & 0x2) { printf(" - second feature, on left :\n"); for (j = 0; j < weak_classifier.features[1].count; j++) printf(" - | - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[1].channel[j], weak_classifier.features[1].sat[j * 2].x, weak_classifier.features[1].sat[j * 2].y, weak_classifier.features[1].sat[j * 2 + 1].x, weak_classifier.features[1].sat[j * 2 + 1].y); } if (weak_classifier.pass & 0x1) { printf(" - second feature, on right :\n"); for (j = 0; j < weak_classifier.features[2].count; j++) printf(" - | - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[2].channel[j], weak_classifier.features[2].sat[j * 2].x, weak_classifier.features[2].sat[j * 2].y, weak_classifier.features[2].sat[j * 2 + 1].x, weak_classifier.features[2].sat[j * 2 + 1].y); } z.classifier->count = z.i + 1; // update count z.classifier->size = ccv_size(z.size.width + z.margin.left + z.margin.right, z.size.height + z.margin.top + z.margin.bottom); z.classifier->margin = z.margin; if (z.i + 1 < params.weak_classifier) { z.x.example_state = 0; z.x.classifier = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); } } if (z.bootstrap < params.bootstrap) // collecting negatives, again { // free expensive memory ccfree(z.example_state); z.example_state = 0; ccfree(z.precomputed); z.precomputed = 0; _ccv_icf_classifier_cascade_soft_with_validates(z.positives, z.classifier, 1); // assuming perfect score, what's the soft cascading will be int exists = z.negatives->rnum; int spread_policy = z.bootstrap < 2; // we don't spread bootstrapping anymore after the first two bootstrappings // try to boostrap half negatives from perfect scoring _ccv_icf_bootstrap_negatives(z.classifier, z.negatives, rng, bgfiles, (negnum + 1) / 2, params.grayscale, spread_policy, params.detector); int leftover = negnum - (z.negatives->rnum - exists); if (leftover > 0) { // if we cannot get enough negative examples, now will use the validates data set to extract more ccv_array_t* validates = _ccv_icf_collect_validates(rng, z.size, z.margin, validatefiles, params.grayscale); _ccv_icf_classifier_cascade_soft_with_validates(validates, z.classifier, params.acceptance); ccv_array_free(validates); _ccv_icf_bootstrap_negatives(z.classifier, z.negatives, rng, bgfiles, leftover, params.grayscale, spread_policy, params.detector); } printf(" - after %d bootstrapping, learn with %d positives and %d negatives\n", z.bootstrap + 1, z.positives->rnum, z.negatives->rnum); z.classifier->count = 0; // reset everything z.x.negatives = 0; } else { z.x.example_state = 0; z.x.classifier = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); } } if (z.precomputed) ccfree(z.precomputed); if (z.example_state) ccfree(z.example_state); ccfree(z.features); ccv_array_free(z.positives); ccv_array_free(z.negatives); gsl_rng_free(rng); ccv_function_state_finish(); return z.classifier; #else assert(0 && "ccv_icf_classifier_cascade_new requires GSL library support"); return 0; #endif } void ccv_icf_classifier_cascade_soft(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* posfiles, double acceptance) { #ifdef HAVE_GSL printf("with %d positive examples\n" "going to accept %.2lf%% positive examples\n", posfiles->rnum, acceptance * 100); ccv_size_t size = ccv_size(cascade->size.width - cascade->margin.left - cascade->margin.right, cascade->size.height - cascade->margin.top - cascade->margin.bottom); printf("use color? %s\n", cascade->grayscale ? "no" : "yes"); printf("compute soft cascading thresholds for ICF classifier cascade at size %dx%d with margin (%d,%d,%d,%d)\n" "------------------------\n", size.width, size.height, cascade->margin.left, cascade->margin.top, cascade->margin.right, cascade->margin.bottom); gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); /* collect positives */ double weigh[2] = { 0, 0 }; int i; for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; weigh[0] += weak_classifier->weigh[0]; weigh[1] += weak_classifier->weigh[1]; } weigh[0] = 1 / fabs(weigh[0]), weigh[1] = 1 / fabs(weigh[1]); for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; weak_classifier->weigh[0] = weak_classifier->weigh[0] * weigh[0]; weak_classifier->weigh[1] = weak_classifier->weigh[1] * weigh[1]; } ccv_array_t* validates = _ccv_icf_collect_validates(rng, size, cascade->margin, posfiles, cascade->grayscale); /* compute soft cascading thresholds */ _ccv_icf_classifier_cascade_soft_with_validates(validates, cascade, acceptance); ccv_array_free(validates); gsl_rng_free(rng); #else assert(0 && "ccv_icf_classifier_cascade_soft requires GSL library support"); #endif } static void _ccv_icf_read_classifier_cascade_with_fd(FILE* r, ccv_icf_classifier_cascade_t* cascade) { cascade->type = CCV_ICF_CLASSIFIER_TYPE_A; fscanf(r, "%d %d %d %d", &cascade->count, &cascade->size.width, &cascade->size.height, &cascade->grayscale); fscanf(r, "%d %d %d %d", &cascade->margin.left, &cascade->margin.top, &cascade->margin.right, &cascade->margin.bottom); cascade->weak_classifiers = (ccv_icf_decision_tree_t*)ccmalloc(sizeof(ccv_icf_decision_tree_t) * cascade->count); int i, q; for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; fscanf(r, "%u %a %a %a", &weak_classifier->pass, &weak_classifier->weigh[0], &weak_classifier->weigh[1], &weak_classifier->threshold); fscanf(r, "%d %a", &weak_classifier->features[0].count, &weak_classifier->features[0].beta); for (q = 0; q < weak_classifier->features[0].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[0].channel[q], &weak_classifier->features[0].alpha[q], &weak_classifier->features[0].sat[q * 2].x, &weak_classifier->features[0].sat[q * 2].y, &weak_classifier->features[0].sat[q * 2 + 1].x, &weak_classifier->features[0].sat[q * 2 + 1].y); if (weak_classifier->pass & 0x2) { fscanf(r, "%d %a", &weak_classifier->features[1].count, &weak_classifier->features[1].beta); for (q = 0; q < weak_classifier->features[1].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[1].channel[q], &weak_classifier->features[1].alpha[q], &weak_classifier->features[1].sat[q * 2].x, &weak_classifier->features[1].sat[q * 2].y, &weak_classifier->features[1].sat[q * 2 + 1].x, &weak_classifier->features[1].sat[q * 2 + 1].y); } if (weak_classifier->pass & 0x1) { fscanf(r, "%d %a", &weak_classifier->features[2].count, &weak_classifier->features[2].beta); for (q = 0; q < weak_classifier->features[2].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[2].channel[q], &weak_classifier->features[2].alpha[q], &weak_classifier->features[2].sat[q * 2].x, &weak_classifier->features[2].sat[q * 2].y, &weak_classifier->features[2].sat[q * 2 + 1].x, &weak_classifier->features[2].sat[q * 2 + 1].y); } } } static void _ccv_icf_write_classifier_cascade_with_fd(ccv_icf_classifier_cascade_t* cascade, FILE* w) { int i, q; fprintf(w, "%d %d %d %d\n", cascade->count, cascade->size.width, cascade->size.height, cascade->grayscale); fprintf(w, "%d %d %d %d\n", cascade->margin.left, cascade->margin.top, cascade->margin.right, cascade->margin.bottom); for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; fprintf(w, "%u %a %a %a\n", weak_classifier->pass, weak_classifier->weigh[0], weak_classifier->weigh[1], weak_classifier->threshold); fprintf(w, "%d %a\n", weak_classifier->features[0].count, weak_classifier->features[0].beta); for (q = 0; q < weak_classifier->features[0].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[0].channel[q], weak_classifier->features[0].alpha[q], weak_classifier->features[0].sat[q * 2].x, weak_classifier->features[0].sat[q * 2].y, weak_classifier->features[0].sat[q * 2 + 1].x, weak_classifier->features[0].sat[q * 2 + 1].y); if (weak_classifier->pass & 0x2) { fprintf(w, "%d %a\n", weak_classifier->features[1].count, weak_classifier->features[1].beta); for (q = 0; q < weak_classifier->features[1].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[1].channel[q], weak_classifier->features[1].alpha[q], weak_classifier->features[1].sat[q * 2].x, weak_classifier->features[1].sat[q * 2].y, weak_classifier->features[1].sat[q * 2 + 1].x, weak_classifier->features[1].sat[q * 2 + 1].y); } if (weak_classifier->pass & 0x1) { fprintf(w, "%d %a\n", weak_classifier->features[2].count, weak_classifier->features[2].beta); for (q = 0; q < weak_classifier->features[2].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[2].channel[q], weak_classifier->features[2].alpha[q], weak_classifier->features[2].sat[q * 2].x, weak_classifier->features[2].sat[q * 2].y, weak_classifier->features[2].sat[q * 2 + 1].x, weak_classifier->features[2].sat[q * 2 + 1].y); } } } ccv_icf_classifier_cascade_t* ccv_icf_read_classifier_cascade(const char* filename) { FILE* r = fopen(filename, "r"); ccv_icf_classifier_cascade_t* cascade = 0; if (r) { cascade = (ccv_icf_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_classifier_cascade_t)); _ccv_icf_read_classifier_cascade_with_fd(r, cascade); fclose(r); } return cascade; } void ccv_icf_write_classifier_cascade(ccv_icf_classifier_cascade_t* cascade, const char* filename) { FILE* w = fopen(filename, "w+"); if (w) { _ccv_icf_write_classifier_cascade_with_fd(cascade, w); fclose(w); } } void ccv_icf_classifier_cascade_free(ccv_icf_classifier_cascade_t* classifier) { ccfree(classifier->weak_classifiers); ccfree(classifier); } ccv_icf_multiscale_classifier_cascade_t* ccv_icf_read_multiscale_classifier_cascade(const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/multiscale", directory); FILE* r = fopen(filename, "r"); if (r) { int octave = 0, count = 0, grayscale = 0; fscanf(r, "%d %d %d", &octave, &count, &grayscale); fclose(r); ccv_icf_multiscale_classifier_cascade_t* classifier = (ccv_icf_multiscale_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_multiscale_classifier_cascade_t) + sizeof(ccv_icf_classifier_cascade_t) * count); classifier->type = CCV_ICF_CLASSIFIER_TYPE_B; classifier->octave = octave; classifier->count = count; classifier->grayscale = grayscale; classifier->cascade = (ccv_icf_classifier_cascade_t*)(classifier + 1); int i; for (i = 0; i < count; i++) { snprintf(filename, 1024, "%s/cascade-%d", directory, i + 1); r = fopen(filename, "r"); if (r) { ccv_icf_classifier_cascade_t* cascade = classifier->cascade + i; _ccv_icf_read_classifier_cascade_with_fd(r, cascade); fclose(r); } } return classifier; } return 0; } void ccv_icf_write_multiscale_classifier_cascade(ccv_icf_multiscale_classifier_cascade_t* classifier, const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/multiscale", directory); FILE* w = fopen(filename, "w+"); fprintf(w, "%d %d %d\n", classifier->octave, classifier->count, classifier->grayscale); fclose(w); int i; for (i = 0; i < classifier->count; i++) { snprintf(filename, 1024, "%s/cascade-%d", directory, i + 1); w = fopen(filename, "w+"); _ccv_icf_write_classifier_cascade_with_fd(classifier->cascade + i, w); fclose(w); } } void ccv_icf_multiscale_classifier_cascade_free(ccv_icf_multiscale_classifier_cascade_t* classifier) { int i; for (i = 0; i < classifier->count; i++) ccfree(classifier->cascade[i].weak_classifiers); ccfree(classifier); } static int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data) { const ccv_comp_t* r1 = (const ccv_comp_t*)_r1; const ccv_comp_t* r2 = (const ccv_comp_t*)_r2; int distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5); return r2->id == r1->id && r2->rect.x <= r1->rect.x + distance && r2->rect.x >= r1->rect.x - distance && r2->rect.y <= r1->rect.y + distance && r2->rect.y >= r1->rect.y - distance && r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) && (int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width && r2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) && (int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height; } static void _ccv_icf_detect_objects_with_classifier_cascade(ccv_dense_matrix_t* a, ccv_icf_classifier_cascade_t** cascades, int count, ccv_icf_param_t params, ccv_array_t* seq[]) { int i, j, k, q, x, y; int scale_upto = 1; for (i = 0; i < count; i++) scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (cascades[i]->size.height - cascades[i]->margin.top - cascades[i]->margin.bottom), (double)a->cols / (cascades[i]->size.width - cascades[i]->margin.left - cascades[i]->margin.right))) / log(2.) - DBL_MIN) + 1); ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto); pyr[0] = a; for (i = 1; i < scale_upto; i++) { pyr[i] = 0; ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0); } for (i = 0; i < scale_upto; i++) { // run it for (j = 0; j < count; j++) { double scale_ratio = pow(2., 1. / (params.interval + 1)); double scale = 1; ccv_icf_classifier_cascade_t* cascade = cascades[j]; for (k = 0; k <= params.interval; k++) { int rows = (int)(pyr[i]->rows / scale + 0.5); int cols = (int)(pyr[i]->cols / scale + 0.5); if (rows < cascade->size.height || cols < cascade->size.width) break; ccv_dense_matrix_t* image = k == 0 ? pyr[i] : 0; if (k > 0) ccv_resample(pyr[i], &image, 0, rows, cols, CCV_INTER_AREA); ccv_dense_matrix_t* bordered = 0; ccv_border(image, (ccv_matrix_t**)&bordered, 0, cascade->margin); if (k > 0) ccv_matrix_free(image); rows = bordered->rows; cols = bordered->cols; ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_matrix_free(bordered); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); int ch = CCV_GET_CHANNEL(sat->type); float* ptr = sat->data.f32; for (y = 0; y < rows; y += params.step_through) { if (y >= sat->rows - cascade->size.height - 1) break; for (x = 0; x < cols; x += params.step_through) { if (x >= sat->cols - cascade->size.width - 1) break; int pass = 1; float sum = 0; for (q = 0; q < cascade->count; q++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + q; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, x, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_comp_t comp; comp.rect = ccv_rect((int)((x + 0.5) * scale * (1 << i) - 0.5), (int)((y + 0.5) * scale * (1 << i) - 0.5), (cascade->size.width - cascade->margin.left - cascade->margin.right) * scale * (1 << i), (cascade->size.height - cascade->margin.top - cascade->margin.bottom) * scale * (1 << i)); comp.id = j + 1; comp.neighbors = 1; comp.confidence = sum; ccv_array_push(seq[j], &comp); } } ptr += sat->cols * ch * params.step_through; } ccv_matrix_free(sat); scale *= scale_ratio; } } } for (i = 1; i < scale_upto; i++) ccv_matrix_free(pyr[i]); } static void _ccv_icf_detect_objects_with_multiscale_classifier_cascade(ccv_dense_matrix_t* a, ccv_icf_multiscale_classifier_cascade_t** multiscale_cascade, int count, ccv_icf_param_t params, ccv_array_t* seq[]) { int i, j, k, q, x, y, ix, iy, py; assert(multiscale_cascade[0]->count % multiscale_cascade[0]->octave == 0); ccv_margin_t margin = multiscale_cascade[0]->cascade[multiscale_cascade[0]->count - 1].margin; for (i = 1; i < count; i++) { assert(multiscale_cascade[i]->count % multiscale_cascade[i]->octave == 0); assert(multiscale_cascade[i - 1]->grayscale == multiscale_cascade[i]->grayscale); assert(multiscale_cascade[i - 1]->count == multiscale_cascade[i]->count); assert(multiscale_cascade[i - 1]->octave == multiscale_cascade[i]->octave); ccv_icf_classifier_cascade_t* cascade = multiscale_cascade[i]->cascade + multiscale_cascade[i]->count - 1; margin.top = ccv_max(margin.top, cascade->margin.top); margin.right = ccv_max(margin.right, cascade->margin.right); margin.bottom = ccv_max(margin.bottom, cascade->margin.bottom); margin.left = ccv_max(margin.left, cascade->margin.left); } int scale_upto = 1; for (i = 0; i < count; i++) scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (multiscale_cascade[i]->cascade[0].size.height - multiscale_cascade[i]->cascade[0].margin.top - multiscale_cascade[i]->cascade[0].margin.bottom), (double)a->cols / (multiscale_cascade[i]->cascade[0].size.width - multiscale_cascade[i]->cascade[0].margin.left - multiscale_cascade[i]->cascade[0].margin.right))) / log(2.) - DBL_MIN) + 2 - multiscale_cascade[i]->octave); ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto); pyr[0] = a; for (i = 1; i < scale_upto; i++) { pyr[i] = 0; ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0); } for (i = 0; i < scale_upto; i++) { ccv_dense_matrix_t* bordered = 0; ccv_border(pyr[i], (ccv_matrix_t**)&bordered, 0, margin); ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_matrix_free(bordered); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); int ch = CCV_GET_CHANNEL(sat->type); assert(CCV_GET_DATA_TYPE(sat->type) == CCV_32F); // run it for (j = 0; j < count; j++) { double scale_ratio = pow(2., (double)multiscale_cascade[j]->octave / multiscale_cascade[j]->count); int starter = i > 0 ? multiscale_cascade[j]->count - (multiscale_cascade[j]->count / multiscale_cascade[j]->octave) : 0; double scale = pow(scale_ratio, starter); for (k = starter; k < multiscale_cascade[j]->count; k++) { ccv_icf_classifier_cascade_t* cascade = multiscale_cascade[j]->cascade + k; int rows = (int)(pyr[i]->rows / scale + cascade->margin.top + 0.5); int cols = (int)(pyr[i]->cols / scale + cascade->margin.left + 0.5); int top = margin.top - cascade->margin.top; int right = margin.right - cascade->margin.right; int bottom = margin.bottom - cascade->margin.bottom; int left = margin.left - cascade->margin.left; if (sat->rows - top - bottom <= cascade->size.height || sat->cols - left - right <= cascade->size.width) break; float* ptr = sat->data.f32 + top * sat->cols * ch; for (y = 0, iy = py = top; y < rows; y += params.step_through) { iy = (int)((y + 0.5) * scale + top); if (iy >= sat->rows - cascade->size.height - 1) break; if (iy > py) { ptr += sat->cols * ch * (iy - py); py = iy; } for (x = 0; x < cols; x += params.step_through) { ix = (int)((x + 0.5) * scale + left); if (ix >= sat->cols - cascade->size.width - 1) break; int pass = 1; float sum = 0; for (q = 0; q < cascade->count; q++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + q; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, ix, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_comp_t comp; comp.rect = ccv_rect((int)((x + 0.5) * scale * (1 << i)), (int)((y + 0.5) * scale * (1 << i)), (cascade->size.width - cascade->margin.left - cascade->margin.right) << i, (cascade->size.height - cascade->margin.top - cascade->margin.bottom) << i); comp.id = j + 1; comp.neighbors = 1; comp.confidence = sum; ccv_array_push(seq[j], &comp); } } } scale *= scale_ratio; } } ccv_matrix_free(sat); } for (i = 1; i < scale_upto; i++) ccv_matrix_free(pyr[i]); } ccv_array_t* ccv_icf_detect_objects(ccv_dense_matrix_t* a, void* cascade, int count, ccv_icf_param_t params) { assert(count > 0); int i, j, k; int type = *(((int**)cascade)[0]); for (i = 1; i < count; i++) { // check all types to be the same assert(*(((int**)cascade)[i]) == type); } ccv_array_t** seq = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * count); for (i = 0; i < count; i++) seq[i] = ccv_array_new(sizeof(ccv_comp_t), 64, 0); switch (type) { case CCV_ICF_CLASSIFIER_TYPE_A: _ccv_icf_detect_objects_with_classifier_cascade(a, (ccv_icf_classifier_cascade_t**)cascade, count, params, seq); break; case CCV_ICF_CLASSIFIER_TYPE_B: _ccv_icf_detect_objects_with_multiscale_classifier_cascade(a, (ccv_icf_multiscale_classifier_cascade_t**)cascade, count, params, seq); break; } ccv_array_t* result_seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0); ccv_array_t* seq2 = ccv_array_new(sizeof(ccv_comp_t), 64, 0); for (k = 0; k < count; k++) { /* the following code from OpenCV's haar feature implementation */ if(params.min_neighbors == 0) { for (i = 0; i < seq[k]->rnum; i++) { ccv_comp_t* comp = (ccv_comp_t*)ccv_array_get(seq[k], i); ccv_array_push(result_seq, comp); } } else { ccv_array_t* idx_seq = 0; ccv_array_clear(seq2); // group retrieved rectangles in order to filter out noise int ncomp = ccv_array_group(seq[k], &idx_seq, _ccv_is_equal_same_class, 0); ccv_comp_t* comps = (ccv_comp_t*)cccalloc(sizeof(ccv_comp_t), ncomp + 1); // count number of neighbors for (i = 0; i < seq[k]->rnum; i++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq[k], i); int idx = *(int*)ccv_array_get(idx_seq, i); comps[idx].id = r1.id; if (r1.confidence > comps[idx].confidence || comps[idx].neighbors == 0) { comps[idx].rect = r1.rect; comps[idx].confidence = r1.confidence; } ++comps[idx].neighbors; } // calculate average bounding box for (i = 0; i < ncomp; i++) { int n = comps[i].neighbors; if (n >= params.min_neighbors) ccv_array_push(seq2, comps + i); } // filter out large object rectangles contains small object rectangles for (i = 0; i < seq2->rnum; i++) { ccv_comp_t* r2 = (ccv_comp_t*)ccv_array_get(seq2, i); int distance = (int)(ccv_min(r2->rect.width, r2->rect.height) * 0.25 + 0.5); for (j = 0; j < seq2->rnum; j++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq2, j); if (i != j && abs(r1.id) == r2->id && r1.rect.x >= r2->rect.x - distance && r1.rect.y >= r2->rect.y - distance && r1.rect.x + r1.rect.width <= r2->rect.x + r2->rect.width + distance && r1.rect.y + r1.rect.height <= r2->rect.y + r2->rect.height + distance && // if r1 (the smaller one) is better, mute r2 (r2->confidence <= r1.confidence && r2->neighbors < r1.neighbors)) { r2->id = -r2->id; break; } } } // filter out small object rectangles inside large object rectangles for (i = 0; i < seq2->rnum; i++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq2, i); if (r1.id > 0) { int flag = 1; for (j = 0; j < seq2->rnum; j++) { ccv_comp_t r2 = *(ccv_comp_t*)ccv_array_get(seq2, j); int distance = (int)(ccv_min(r2.rect.width, r2.rect.height) * 0.25 + 0.5); if (i != j && abs(r1.id) == abs(r2.id) && r1.rect.x >= r2.rect.x - distance && r1.rect.y >= r2.rect.y - distance && r1.rect.x + r1.rect.width <= r2.rect.x + r2.rect.width + distance && r1.rect.y + r1.rect.height <= r2.rect.y + r2.rect.height + distance && // if r2 is better, we mute r1 (r2.confidence > r1.confidence || r2.neighbors >= r1.neighbors)) { flag = 0; break; } } if (flag) ccv_array_push(result_seq, &r1); } } ccv_array_free(idx_seq); ccfree(comps); } ccv_array_free(seq[k]); } ccv_array_free(seq2); return result_seq; }
{ "alphanum_fraction": 0.6682054854, "avg_line_length": 40.9956437561, "ext": "c", "hexsha": "edc9a7383ee1b2b01353220be71f5a0c9e7b17a7", "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": "1e76acb233cfad49b1be8378bfe8556cae3d9c9b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bshawk/ccv", "max_forks_repo_path": "lib/ccv_icf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1e76acb233cfad49b1be8378bfe8556cae3d9c9b", "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": "bshawk/ccv", "max_issues_repo_path": "lib/ccv_icf.c", "max_line_length": 455, "max_stars_count": 1, "max_stars_repo_head_hexsha": "1e76acb233cfad49b1be8378bfe8556cae3d9c9b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bshawk/ccv", "max_stars_repo_path": "lib/ccv_icf.c", "max_stars_repo_stars_event_max_datetime": "2015-04-06T16:36:20.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-06T16:36:20.000Z", "num_tokens": 27557, "size": 84697 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for the instrumental noise for LISA-type detectors. * * Formulas taken from Królak&al gr-qc/0401108 (c.f. section III). */ #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "LISAnoise.h" /* static double tflight_SI = L_SI/C_SI; */ /* static double twopitflight_SI = 2.*PI*L_SI/C_SI; */ /* Proof mass and optic noises - f in Hz */ /* Taken from (4) in McWilliams&al_0911 */ static double SpmLISA2010(const double f) { double invf2 = 1./(f*f); //return 2.5e-48 * invf2 * sqrt(1. + 1e-8*invf2); //const double Daccel=3.0e-15; //acceleration noise in m/s^2/sqrt(Hz) const double Daccel=3.0e-15; //scaled off L3LISA-v1 to for equal-SNR PE experiment const double SaccelFF=Daccel*Daccel/4.0/PI/PI/C_SI/C_SI; //f^-2 coeff for fractional-freq noise PSD from accel noise; yields 2.54e-48 from 3e-15; double invf8=invf2*invf2*invf2*invf2; //Here we add an eyeball approximation based on 4yrs integration with L3LISAReferenceMission looking at a private comm from Neil Cornish 2016.11.12 double WDWDnoise=5000.0/sqrt(1e-21*invf8 + invf2 + 3e28/invf8)*SaccelFF*invf2; return SaccelFF * invf2 * sqrt(1. + 1e-8*invf2) + WDWDnoise; } static double SopLISA2010(const double f) { const double Dop=2.0e-11; //Optical path noise in m/rtHz (Standard LISA) const double SopFF=Dop*Dop*4.0*PI*PI/C_SI/C_SI; //f^2 coeff for OP frac-freq noise PSD. Yields 1.76e-37 for Dop=2e-11. return SopFF * f * f; } /* Proof mass and optical noises - f in Hz */ /* L3 Reference Mission, from Petiteau LISA-CST-TN-0001 */ static double SpmLISA2017(const double f) { double invf2 = 1./(f*f); //double invf4=invf2*invf2; //double invf8=invf4*invf4; //double invf10=invf8*invf2; const double twopi2=4.0*PI*PI; double ddtsq=twopi2/invf2; //time derivative factor const double C2=1.0*C_SI*C_SI; //veloc to doppler const double Daccel_white=3.0e-15; //acceleration noise in m/s^2/sqrt(Hz) const double Daccel_white2=Daccel_white*Daccel_white; const double Dloc=1.7e-12; //local IFO noise in m/sqrt(Hz) const double Dloc2=Dloc*Dloc; double Saccel_white=Daccel_white2/ddtsq; //PM vel noise PSD (white accel part) //double Saccel_red=Saccel_white*(1.0 + 2.12576e-44*invf10 + 3.6e-7*invf2); //reddening factor from Petiteau Eq 1 double Saccel_red=Saccel_white*(1.0 + 36.0*(pow(3e-5/f,10) + 1e-8*invf2)); //reddening factor from Petiteau Eq 1 //Saccel_red*=4.0;//Hack to decrease low-freq sens by fac of 2. double Sloc=Dloc2*ddtsq/4.0;//Factor of 1/4.0 is in Petiteau eq 2 double S4yrWDWD=5.16e-27*exp(-pow(f,1.2)*2.9e3)*pow(f,(-7./3.))*0.5*(1.0 + tanh(-(f-2.0e-3)*1.9e3))*ddtsq;//Stas' fit for 4yr noise (converted from Sens curve to position noise by multipyling by 3*L^2/80) which looks comparable to my fit), then converted to velocity noise double Spm_vel = ( Saccel_red + Sloc + S4yrWDWD ); return Spm_vel / C2;//finally convert from velocity noise to fractional-frequency doppler noise. } static double SopLISA2017(const double f) { //double invf2 = 1./(f*f); const double twopi2=4.0*PI*PI; double ddtsq=twopi2*f*f; //time derivative factor const double C2=C_SI*C_SI; //veloc to doppler const double Dloc=1.7e-12; //local IFO noise in m/sqrt(Hz) const double Dsci=8.9e-12; //science IFO noise in m/sqrt(Hz) const double Dmisc=2.0e-12; //misc. optical path noise in m/sqrt(Hz) const double Dop2=Dsci*Dsci+Dloc*Dloc+Dmisc*Dmisc; double Sop=Dop2*ddtsq/C2; //f^2 coeff for OP frac-freq noise PSD. Yields 1.76e-37 for Dop=2e-11. return Sop; } /* Proof mass and optical noises - f in Hz */ /* LISA Proposal, copied from the LISA Data Challenge pipeline */ static double SpmLISAProposal(const double f) { /* Acceleration noise */ double noise_Sa_a = 9.e-30; /* m^2/sec^4 /Hz */ /* In acceleration */ double Sa_a = noise_Sa_a * (1.0 + pow(0.4e-3/f, 2)) * (1.0 + pow((f/8e-3), 4)); /* In displacement */ double Sa_d = Sa_a * pow(2.*PI*f, -4); /* In relative frequency unit */ double Sa_nu = Sa_d * pow(2.*PI*f/C_SI, 2); double Spm = Sa_nu; return Spm; } static double SopLISAProposal(const double f) { /* Optical Metrology System noise */ double noise_Soms_d = pow((10e-12), 2); /* m^2/Hz */ /* In displacement */ double Soms_d = noise_Soms_d * (1. + pow(2.e-3/f, 4)); /* In relative frequency unit */ double Soms_nu = Soms_d * pow(2.*PI*f/C_SI, 2); double Sop = Soms_nu; return Sop; } /* Compute proof mass and optical noises, for a given choice of noise - f in Hz */ static void ComputeLISASpmSop(double* Spm, double* Sop, const double f, LISANoiseType noise) { if(noise==LISAProposalnoise) { *Spm = SpmLISAProposal(f); *Sop = SopLISAProposal(f); } else if(noise==LISA2017noise) { *Spm = SpmLISA2017(f); *Sop = SopLISA2017(f); } else if(noise==LISA2010noise) { *Spm = SpmLISA2010(f); *Sop = SopLISA2010(f); } else { printf("Error in ComputeLISASpmSop: LISANoiseType not recognized.\n"); exit(1); } } /* Noise Sn for TDI observables - factors have been scaled out both in the response and the noise */ /* Rescaled by 4*sin2pifL^2 */ double SnXYZ(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 4*( 2*(1. + c2*c2)*Spm + Sop ); } /* No rescaling */ double Snalphabetagamma(const LISAconstellation *variant, double f) { double pifL = PI*variant->ConstL/C_SI*f; double s1 = sin(pifL); double s3 = sin(3*pifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*( (4*s3*s3 + 8*s1*s1)*Spm + 3*Sop ); } /* Rescaled by 2*sin2pifL^2 */ double SnAXYZ(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop; } /* Rescaled by 2*sin2pifL^2 */ double SnEXYZ(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop; } /* Rescaled by 8*sin2pifL^2*sinpifL^2 */ double SnTXYZ(const LISAconstellation *variant, double f) { double pifL = PI*variant->ConstL/C_SI*f; double s1 = sin(pifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 4*s1*s1*Spm + Sop; } /* Rescaled by 8*sin2pifL^2 */ double SnAalphabetagamma(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop; } /* Rescaled by 8*sin2pifL^2 */ double SnEalphabetagamma(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop; } /* Rescaled by sin3pifL^2/sinpifL^2 */ double SnTalphabetagamma(const LISAconstellation *variant, double f) { double pifL = PI*variant->ConstL/C_SI*f; double s1 = sin(pifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 8*s1*s1*Spm + 2*Sop; } /* Noise functions for AET(XYZ) without rescaling */ /* Scaling by 2*sin2pifL^2 put back */ double SnAXYZNoRescaling(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double s2 = sin(twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*s2*s2 * (2*(3. + 2*c2 + c4)*SpmLISA2017(f) + (2 + c2)*SopLISA2017(f)); } /* Scaling by 2*sin2pifL^2 put back */ double SnEXYZNoRescaling(const LISAconstellation *variant, double f) { double twopifL = 2.*PI*variant->ConstL/C_SI*f; double c2 = cos(twopifL); double c4 = cos(2*twopifL); double s2 = sin(twopifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 2*s2*s2 * (2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop); } /* Scaling by 8*sin2pifL^2*sinpifL^2 put back*/ double SnTXYZNoRescaling(const LISAconstellation *variant, double f) { double pifL = PI*variant->ConstL/C_SI*f; double s1 = sin(pifL); double s2 = sin(2*pifL); double Spm = 0., Sop = 0.; ComputeLISASpmSop(&Spm, &Sop, f, variant->noise); return 8*s1*s1*s2*s2 * (4*s1*s1*Spm + Sop); } /* The noise functions themselves /* Note - we factored out and cancelled the factors of the type sin(n pi f L) */ /* double NoiseSnA(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double cos1 = cos(twopifL); */ /* double cos2 = cos(2*twopifL); */ /* return 32*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */ /* } */ /* double NoiseSnE(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double cos1 = cos(twopifL); */ /* double cos2 = cos(2*twopifL); */ /* return 32*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */ /* } */ /* double NoiseSnT(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double sinhalf = sin(0.5*twopifL); */ /* double cos1 = cos(twopifL); */ /* return 8*( 4*sinhalf*sinhalf*Spm(f) + Sop(f) ); */ /* } */ /* Function returning the relevant noise function, given a set of TDI observables and a channel */ ObjectFunction NoiseFunction(const LISAconstellation *variant, const TDItag tditag, const int nchan) { ObjectFunction fn; switch(tditag) { case TDIXYZ: case TDIX: { switch(nchan) { case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break; case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break; case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break; } break; } case TDIalphabetagamma: case TDIalpha: { switch(nchan) { case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break; case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break; case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break; } break; } case TDIAETXYZ: case TDIAXYZ: case TDIEXYZ: case TDITXYZ: { switch(nchan) { case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnAXYZ}; break; case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnEXYZ}; break; case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnTXYZ}; break; } break; } case TDIAETalphabetagamma: case TDIAalphabetagamma: case TDIEalphabetagamma: case TDITalphabetagamma: { switch(nchan) { case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnAalphabetagamma}; break; case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnEalphabetagamma}; break; case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnTalphabetagamma}; break; } break; } } if(fn.object==NULL) { printf("Error in NoiseFunction: incorrect argument.\n"); exit(1); } return fn; } //Previous version - we had put a noise floor to mitigate cancellation lines /* double NoiseSnA(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double sinhalf = sin(0.5*twopifL); */ /* double sin3half = sin(1.5*twopifL); */ /* double cos1 = cos(twopifL); */ /* double cos2 = cos(2*twopifL); */ /* double res = 32*sinhalf*sinhalf*sin3half*sin3half*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */ /* return fmax(res, 1e-46); */ /* } */ /* double NoiseSnE(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double sinhalf = sin(0.5*twopifL); */ /* double sin3half = sin(1.5*twopifL); */ /* double cos1 = cos(twopifL); */ /* double cos2 = cos(2*twopifL); */ /* double res = 32*sinhalf*sinhalf*sin3half*sin3half*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */ /* return fmax(res, 1e-46); */ /* } */ /* double NoiseSnT(const double f) { */ /* double twopifL = 2.*PI*L_SI/C_SI*f; */ /* double sinhalf = sin(0.5*twopifL); */ /* double sin3half = sin(1.5*twopifL); */ /* double cos1 = cos(twopifL); */ /* double res = 8*(1+2*cos1)*(1+2*cos1)*sin3half*sin3half*( 4*sinhalf*sinhalf*Spm(f) + Sop(f) ); */ /* return fmax(res, 1e-46); */ /* } */
{ "alphanum_fraction": 0.6677318725, "avg_line_length": 37.9855491329, "ext": "c", "hexsha": "bc07363d54781f152ebcc8bbe147522423de7f15", "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": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "LISAsim/LISAnoise.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "LISAsim/LISAnoise.c", "max_line_length": 274, "max_stars_count": null, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "LISAsim/LISAnoise.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4839, "size": 13143 }
/** * @file xdegnome.c * @author Daniel R. Tabin * @brief Unit tests for Degnome */ #include "degnome.h" #include <stdio.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #include <unistd.h> #include <limits.h> unsigned long rngseed=0; int main(int argc, char **argv) { int verbose = 0; int seeded =0; if (argc == 2) { if (strncmp(argv[1], "-v", 2) != 0) { fprintf(stderr, "usage: xdegnome [-v] [-s] [0000000000]\n"); exit(EXIT_FAILURE); } verbose = 1; } else if (argc == 3) { if (strncmp(argv[1], "-s", 2) != 0) { fprintf(stderr, "usage: xdegnome [-v] [-s] [0000000000]\n"); exit(EXIT_FAILURE); } rngseed = (unsigned long) atoi(argv[2]); } else if (argc == 4) { if (strncmp(argv[1], "-v", 2) != 0) { fprintf(stderr, "usage: xdegnome [-v] [-s] [0000000000]\n"); exit(EXIT_FAILURE); } else if (strncmp(argv[2], "-s", 2) != 0) { fprintf(stderr, "usage: xdegnome [-v] [-s] [0000000000]\n"); exit(EXIT_FAILURE); } verbose = 1; seeded = 1; rngseed = (unsigned long) atoi(argv[3]); } else if (argc != 1) { fprintf(stderr, "usage: xdegnome [-v] [-s] [seed]\n"); exit(EXIT_FAILURE); } chrom_size = 15; if (verbose) { printf("Chromosome is length %u\n", chrom_size); } Degnome* bom_mom = Degnome_new(); // good parent Degnome* bad_dad = Degnome_new(); // bad parent Degnome* tst_bby = Degnome_new(); // their child // ============ change this to seed rn if (seeded == 0) { time_t currtime = time(NULL); // time unsigned long pid = (unsigned long) getpid(); // process id rngseed = currtime ^ pid; // random seed } gsl_rng* rng = gsl_rng_alloc(gsl_rng_taus); // rand generator gsl_rng_set(rng, rngseed); rngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1); // ============ change this to seed rn for (int i = 0; i < chrom_size; i++) { bom_mom->dna_array[i] = 2*i; bad_dad->dna_array[i] = 1*i; bom_mom->hat_size += bom_mom->dna_array[i]; bad_dad->hat_size += bad_dad->dna_array[i]; } if (verbose) { printf("pre-mating values:\n"); for (int i = 0; i < chrom_size; i++) { printf("Mom: %lf\t Dad: %f\n", bom_mom->dna_array[i], bad_dad->dna_array[i]); } printf("Mom hat_size: %lf\t Dad hat_size: %f\n", bom_mom->hat_size, bad_dad->hat_size); } Degnome_mate(tst_bby, bom_mom, bad_dad, rng, 0, 0,2); if (verbose) { printf("post-mating values:\n"); for (int i = 0; i < chrom_size; i++) { printf("Mom: %lf\t Dad: %f\t Kid: %f\n", bom_mom->dna_array[i], bad_dad->dna_array[i], tst_bby->dna_array[i]); } printf("Mom hat_size: %lf\t Dad hat_size: %f\t Kid hat_size: %f\n", bom_mom->hat_size, bad_dad->hat_size, tst_bby->hat_size); } Degnome_free(bom_mom); Degnome_free(bad_dad); Degnome_free(tst_bby); gsl_rng_free(rng); printf("All tests for xdegnome completed\n"); }
{ "alphanum_fraction": 0.5847797063, "avg_line_length": 26.2807017544, "ext": "c", "hexsha": "caa82546821f49ea03e577501d5cb3a2da7b6e2a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "masalemi/PopGenSim", "max_forks_repo_path": "src/xdegnome.c", "max_issues_count": 27, "max_issues_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "masalemi/PopGenSim", "max_issues_repo_path": "src/xdegnome.c", "max_line_length": 128, "max_stars_count": 3, "max_stars_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "masalemi/PopGenSim", "max_stars_repo_path": "src/xdegnome.c", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "num_tokens": 1025, "size": 2996 }
/* * qubit.h * * Created on: 30 Jan 2019 * Author: jobinrjohnson */ #ifndef IMPLEMENTATION_QUBIT_H_ #define IMPLEMENTATION_QUBIT_H_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_rng.h> #include <iostream> class Qubit { protected: gsl_vector_complex *v_state; public: Qubit(); Qubit(double, double, double, double); virtual ~Qubit(); void print_state(); gsl_vector_complex *get_state(); bool set_state(gsl_vector_complex *); }; #endif /* IMPLEMENTATION_QUBIT_H_ */
{ "alphanum_fraction": 0.7225225225, "avg_line_length": 16.8181818182, "ext": "h", "hexsha": "5cc5c3bf4f8189b4bf1a2fc060a18cb6d0ab0df5", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-11-12T08:04:28.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-06T09:04:35.000Z", "max_forks_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jobinrjohnson/QSim", "max_forks_repo_path": "implementation/include/qubit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4", "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": "jobinrjohnson/QSim", "max_issues_repo_path": "implementation/include/qubit.h", "max_line_length": 39, "max_stars_count": 4, "max_stars_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jobinrjohnson/QSim", "max_stars_repo_path": "implementation/include/qubit.h", "max_stars_repo_stars_event_max_datetime": "2022-03-05T20:22:06.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-03T18:58:37.000Z", "num_tokens": 155, "size": 555 }
/* 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: mat_file.c * * Description: Write and read the generator matrices on files * * Version: 1.0 * Created: 03/05/2014 13:52:15 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <string.h> #include "funcs.h" /* * FUNCTION * Name: mat_write * Description: Save the generator matrix in a file. * */ int mat_write ( gsl_matrix* mat, char* name ) { FILE* f = fopen ( name, "w" ) ; if ( f == NULL ) printf("Error: %s.\nFailed to open %s.\n", strerror(errno), name) ; int status = gsl_matrix_fprintf ( f, mat, "%.9f" ) ; fclose (f) ; return status; } /* ----- end of function mat_write ----- */ /* * FUNCTION * Name: mat_read * Description: Read the Redfield matrix from a file * */ int mat_read ( gsl_matrix* mat, char* name ) { FILE* f = fopen ( name, "r" ) ; if ( f == NULL ) printf( "Error: %s.\nFailed to open %s.\n", strerror(errno), name ) ; int status = gsl_matrix_fscanf ( f, mat ) ; fclose (f) ; return status; } /* ----- end of function mat_read ----- */
{ "alphanum_fraction": 0.6730415594, "avg_line_length": 29.8791208791, "ext": "c", "hexsha": "3ceb869deca3d7b18e8e8de0f8edd90dd327f4a0", "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": "mat_file.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": "mat_file.c", "max_line_length": 79, "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": "mat_file.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 687, "size": 2719 }
/// /// @file /// /// @brief This file contains code that is used to validate the output of the /// example codes. /// /// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University /// /// @section LICENSE /// /// Copyright (c) 2019-2020, Umeå Universitet /// /// 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. /// /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived from this /// software without specific prior written permission. /// /// 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. /// #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> static inline double squ(double x) { return x*x; } void check_orthogonality(int n, size_t ldQ, double const *Q) { size_t ldT = ((n/8)+1)*8; double *T = malloc(n*ldT*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0, Q, ldQ, Q, ldQ, 0.0, T, ldT); double dot = 0.0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) dot += squ(T[i*ldT+j] - (i == j ? 1.0 : 0.0)); double norm = ((long long)1<<52) * sqrt(dot)/sqrt(n); if (norm < 1000) { printf("The matrix is orthogonal.\n"); } else { fprintf(stderr, "Matrix is not orthogonal.\n"); exit(EXIT_FAILURE); } free(T); } void check_residual( int n, size_t ldQ, size_t ldA, size_t ldZ, size_t ldC, double const *Q, double const *A, double const *Z, double const *C) { size_t ldT = ((n/8)+1)*8; double *T = malloc(n*ldT*sizeof(double)); size_t ldY = ((n/8)+1)*8; double *Y = malloc(n*ldT*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0, Q, ldQ, A, ldA, 0.0, T, ldT); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0, T, ldT, Z, ldZ, 0.0, Y, ldY); double dot = 0.0, a_dot = 0.0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dot += squ(Y[i*ldY+j] - C[i*ldC+j]); a_dot += squ(C[i*ldC+j]); } } double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot); if (norm < 1000) { printf("The residual is small enough.\n"); } else { fprintf(stderr, "The residual is too large.\n"); exit(EXIT_FAILURE); } free(T); free(Y); }
{ "alphanum_fraction": 0.6382034932, "avg_line_length": 32.2053571429, "ext": "c", "hexsha": "5871050866104b1a18a10b43297805aa3a858ef3", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_path": "examples/validate.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "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": "NLAFET/StarNEig", "max_issues_repo_path": "examples/validate.c", "max_line_length": 80, "max_stars_count": 12, "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_path": "examples/validate.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "num_tokens": 1019, "size": 3607 }
/* linalg/test_qrc.c * * Copyright (C) 2020 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 <gsl/gsl_test.h> #include <gsl/gsl_math.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_permutation.h> static int test_QRc_decomp_eps(const gsl_matrix_complex * m, const double eps, const char * desc) { int s = 0; const size_t M = m->size1; const size_t N = m->size2; size_t i, j; gsl_matrix_complex * qr = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * a = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * q = gsl_matrix_complex_alloc(M, M); gsl_matrix_complex * r = gsl_matrix_complex_alloc(M, N); gsl_vector_complex * d = gsl_vector_complex_alloc(N); gsl_matrix_complex_memcpy(qr, m); s += gsl_linalg_complex_QR_decomp(qr, d); s += gsl_linalg_complex_QR_unpack(qr, d, q, r); /* compute a = q r */ gsl_blas_zgemm (CblasNoTrans, CblasNoTrans, GSL_COMPLEX_ONE, q, r, GSL_COMPLEX_ZERO, a); for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { gsl_complex aij = gsl_matrix_complex_get(a, i, j); gsl_complex mij = gsl_matrix_complex_get(m, i, j); int foo_r = check(GSL_REAL(aij), GSL_REAL(mij), eps); int foo_i = check(GSL_IMAG(aij), GSL_IMAG(mij), eps); if (foo_r || foo_i) { printf("%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_REAL(aij), GSL_REAL(mij)); printf("%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_IMAG(aij), GSL_IMAG(mij)); } s += foo_r + foo_i; } } gsl_vector_complex_free(d); gsl_matrix_complex_free(qr); gsl_matrix_complex_free(a); gsl_matrix_complex_free(q); gsl_matrix_complex_free(r); return s; } static int test_QRc_decomp(gsl_rng * r) { int s = 0; size_t N, M; /* test random matrices */ for (N = 1; N <= 20; ++N) { for (M = 1; M <= 20; ++M) { gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, M); create_random_complex_matrix(A, r); test_QRc_decomp_eps(A, 1.0e6 * GSL_MAX(N, M) * GSL_DBL_EPSILON, "complex_QR_decomp random"); gsl_matrix_complex_free(A); } } return s; } static int test_QRc_solve_eps(const gsl_matrix_complex * A, const gsl_vector_complex * rhs, const gsl_vector_complex * sol, const double eps, const char * desc) { int s = 0; const size_t M = A->size1; const size_t N = A->size2; size_t i; gsl_matrix_complex * QR = gsl_matrix_complex_alloc(M, N); gsl_vector_complex * tau = gsl_vector_complex_alloc(N); gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_matrix_complex_memcpy(QR, A); s += gsl_linalg_complex_QR_decomp(QR, tau); s += gsl_linalg_complex_QR_solve(QR, tau, rhs, x); for (i = 0; i < M; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s real (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, xi, yi); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s imag (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, xi, yi); } gsl_matrix_complex_free(QR); gsl_vector_complex_free(tau); gsl_vector_complex_free(x); return s; } static int test_QRc_solve(gsl_rng * r) { int s = 0; size_t N; for (N = 1; N <= 50; ++N) { gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N); gsl_vector_complex * sol = gsl_vector_complex_alloc(N); gsl_vector_complex * rhs = gsl_vector_complex_alloc(N); create_random_complex_matrix(A, r); create_random_complex_vector(sol, r); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_ONE, A, sol, GSL_COMPLEX_ZERO, rhs); s += test_QRc_solve_eps(A, rhs, sol, 1.0e5 * N * GSL_DBL_EPSILON, "complex QR_solve_r random"); gsl_matrix_complex_free(A); gsl_vector_complex_free(sol); gsl_vector_complex_free(rhs); } return s; } static int test_QRc_lssolve_eps(const gsl_matrix_complex * A, const gsl_vector_complex * rhs, const gsl_vector_complex * sol, const double eps, const char * desc) { int s = 0; const size_t M = A->size1; const size_t N = A->size2; size_t i; gsl_matrix_complex * QR = gsl_matrix_complex_alloc(M, N); gsl_vector_complex * tau = gsl_vector_complex_alloc(N); gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_vector_complex * r = gsl_vector_complex_alloc(M); gsl_vector_complex * r2 = gsl_vector_complex_alloc(M); gsl_matrix_complex_memcpy(QR, A); s += gsl_linalg_complex_QR_decomp(QR, tau); s += gsl_linalg_complex_QR_lssolve(QR, tau, rhs, x, r); for (i = 0; i < N; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s sol real (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s sol imag (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } /* compute residual and check */ gsl_vector_complex_memcpy(r2, rhs); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_NEGONE, A, sol, GSL_COMPLEX_ONE, r2); for (i = 0; i < M; i++) { gsl_complex xi = gsl_vector_complex_get(r, i); gsl_complex yi = gsl_vector_complex_get(r2, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s res real (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s res imag (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } gsl_matrix_complex_free(QR); gsl_vector_complex_free(tau); gsl_vector_complex_free(x); gsl_vector_complex_free(r); gsl_vector_complex_free(r2); return s; } static int test_QRc_lssolve() { int s = 0; const double tol = 1.0e-10; { const double A_data[] = { 6.70178096995592e-01, 2.51765675689489e-01, 7.18387884271362e-01, 3.61106008613644e-01, 3.36342428526987e-02, 5.25755806084206e-01, 5.87596968507183e-01, 5.27700895952418e-01, 6.85871226549483e-01, 3.71216051930735e-01, 4.40045953339814e-01, 2.08875308141557e-01, 8.62676230425306e-01, 5.79995188556082e-01, 4.86983443637474e-02, 2.82915411954634e-01, 2.92843706013013e-01, 5.61536446182319e-01, 6.85137614758495e-02, 8.90853425372411e-01, 4.38527971314087e-01, 4.78136089625096e-01, 1.57942824868494e-01, 8.38451530279972e-01, 6.36273325487226e-01, 7.74039464290391e-02, 5.45646256301364e-01, 7.80075219450629e-01, 9.27400956530167e-01, 7.01700239834713e-02, 1.09682812589509e-01, 5.64047584357803e-01, 4.46922541620762e-02, 3.03438549353353e-01, 8.09200219159660e-01, 1.44245237525133e-01 }; const double rhs_data[] = { 5.82246876454474e-01, 1.42259458199622e-02, 6.25588177982770e-01, 3.79195077388159e-01, 8.45448918385455e-02, 3.20808711881935e-01, 8.02701461544476e-01, 5.65141425118050e-01, 8.34227120735637e-01, 4.69005326248388e-01, 9.73712086117648e-01, 3.47197650692321e-01 }; const double sol_data[] = { -2.07103028285037e-01, -3.77392587461962e-01, 7.46590544020302e-01, -1.10976592416587e-01, 6.07653916072011e-01, 2.05471935567110e-01 }; gsl_matrix_complex_const_view A = gsl_matrix_complex_const_view_array(A_data, 6, 3); gsl_vector_complex_const_view rhs = gsl_vector_complex_const_view_array(rhs_data, 6); gsl_vector_complex_const_view sol = gsl_vector_complex_const_view_array(sol_data, 3); test_QRc_lssolve_eps(&A.matrix, &rhs.vector, &sol.vector, tol, "complex QR_lssolve test1"); } return s; } static int test_QRc_decomp_r_eps(const gsl_matrix_complex * m, const double eps, const char * desc) { int s = 0; const size_t M = m->size1; const size_t N = m->size2; size_t i, j; gsl_matrix_complex * QR = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * T = gsl_matrix_complex_alloc(N, N); gsl_matrix_complex * A = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * R = gsl_matrix_complex_alloc(N, N); gsl_matrix_complex * Q = gsl_matrix_complex_alloc(M, M); gsl_matrix_complex_view Q1 = gsl_matrix_complex_submatrix(Q, 0, 0, M, N); gsl_vector_complex_const_view tau = gsl_matrix_complex_const_diagonal(T); gsl_matrix_complex_memcpy(QR, m); s += gsl_linalg_complex_QR_decomp_r(QR, T); s += gsl_linalg_complex_QR_unpack_r(QR, T, Q, R); /* compute A = Q R */ gsl_matrix_complex_memcpy(A, &Q1.matrix); gsl_blas_ztrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, GSL_COMPLEX_ONE, R, A); for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { gsl_complex aij = gsl_matrix_complex_get(A, i, j); gsl_complex mij = gsl_matrix_complex_get(m, i, j); gsl_test_rel(GSL_REAL(aij), GSL_REAL(mij), eps, "%s real (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i,j, GSL_REAL(aij), GSL_REAL(mij)); gsl_test_rel(GSL_IMAG(aij), GSL_IMAG(mij), eps, "%s imag (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i,j, GSL_IMAG(aij), GSL_IMAG(mij)); } } if (M > N) { gsl_matrix_complex * R_alt = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * Q_alt = gsl_matrix_complex_alloc(M, M); /* test that Q2 was computed correctly by comparing with Level 2 algorithm */ gsl_linalg_complex_QR_unpack(QR, &tau.vector, Q_alt, R_alt); for (i = 0; i < M; i++) { for (j = 0; j < M; j++) { gsl_complex aij = gsl_matrix_complex_get(Q, i, j); gsl_complex bij = gsl_matrix_complex_get(Q_alt, i, j); gsl_test_rel(GSL_REAL(aij), GSL_REAL(bij), eps, "%s real Q (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_REAL(aij), GSL_REAL(bij)); gsl_test_rel(GSL_IMAG(aij), GSL_IMAG(bij), eps, "%s imag Q (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", desc, M, N, i, j, GSL_IMAG(aij), GSL_IMAG(bij)); } } gsl_matrix_complex_free(R_alt); gsl_matrix_complex_free(Q_alt); } gsl_matrix_complex_free(QR); gsl_matrix_complex_free(T); gsl_matrix_complex_free(A); gsl_matrix_complex_free(Q); gsl_matrix_complex_free(R); return s; } static int test_QRc_decomp_r(gsl_rng * r) { int s = 0; size_t M, N; for (M = 1; M <= 50; ++M) { for (N = 1; N <= M; ++N) { gsl_matrix_complex * A = gsl_matrix_complex_alloc(M, N); create_random_complex_matrix(A, r); s += test_QRc_decomp_r_eps(A, 1.0e6 * M * GSL_DBL_EPSILON, "complex_QR_decomp_r random"); gsl_matrix_complex_free(A); } } return s; } static int test_QRc_solve_r_eps(const gsl_matrix_complex * A, const gsl_vector_complex * rhs, const gsl_vector_complex * sol, const double eps, const char * desc) { int s = 0; const size_t M = A->size1; const size_t N = A->size2; size_t i; gsl_matrix_complex * QR = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * T = gsl_matrix_complex_alloc(N, N); gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_matrix_complex_memcpy(QR, A); s += gsl_linalg_complex_QR_decomp_r(QR, T); s += gsl_linalg_complex_QR_solve_r(QR, T, rhs, x); for (i = 0; i < M; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s real (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s imag (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } gsl_matrix_complex_free(QR); gsl_matrix_complex_free(T); gsl_vector_complex_free(x); return s; } static int test_QRc_solve_r(gsl_rng * r) { int s = 0; size_t N; for (N = 1; N <= 50; ++N) { gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N); gsl_vector_complex * sol = gsl_vector_complex_alloc(N); gsl_vector_complex * rhs = gsl_vector_complex_alloc(N); create_random_complex_matrix(A, r); create_random_complex_vector(sol, r); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_ONE, A, sol, GSL_COMPLEX_ZERO, rhs); s += test_QRc_solve_r_eps(A, rhs, sol, 1.0e6 * N * GSL_DBL_EPSILON, "complex_QR_solve_r random"); gsl_matrix_complex_free(A); gsl_vector_complex_free(sol); gsl_vector_complex_free(rhs); } return s; } static int test_QRc_lssolve_r_eps(const gsl_matrix_complex * A, const gsl_vector_complex * rhs, const gsl_vector_complex * sol, const double eps, const char * desc) { int s = 0; const size_t M = A->size1; const size_t N = A->size2; size_t i; gsl_matrix_complex * QR = gsl_matrix_complex_alloc(M, N); gsl_matrix_complex * T = gsl_matrix_complex_alloc(N, N); gsl_vector_complex * x = gsl_vector_complex_alloc(M); gsl_vector_complex * r = gsl_vector_complex_alloc(M); gsl_vector_complex * work = gsl_vector_complex_alloc(N); gsl_vector_complex_const_view x1 = gsl_vector_complex_const_subvector(x, N, M - N); double rnorm_expected, rnorm; gsl_matrix_complex_memcpy(QR, A); s += gsl_linalg_complex_QR_decomp_r(QR, T); s += gsl_linalg_complex_QR_lssolve_r(QR, T, rhs, x, work); for (i = 0; i < N; i++) { gsl_complex xi = gsl_vector_complex_get(x, i); gsl_complex yi = gsl_vector_complex_get(sol, i); gsl_test_rel(GSL_REAL(xi), GSL_REAL(yi), eps, "%s sol real (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_REAL(xi), GSL_REAL(yi)); gsl_test_rel(GSL_IMAG(xi), GSL_IMAG(yi), eps, "%s sol imag (%3lu)[%lu]: %22.18g %22.18g\n", desc, N, i, GSL_IMAG(xi), GSL_IMAG(yi)); } /* compute residual and check */ gsl_vector_complex_memcpy(r, rhs); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_NEGONE, A, sol, GSL_COMPLEX_ONE, r); rnorm_expected = gsl_blas_dznrm2(r); rnorm = gsl_blas_dznrm2(&x1.vector); gsl_test_rel(rnorm, rnorm_expected, eps, "%s rnorm (%3lu): %22.18g %22.18g\n", desc, N, rnorm, rnorm_expected); gsl_matrix_complex_free(QR); gsl_matrix_complex_free(T); gsl_vector_complex_free(x); gsl_vector_complex_free(r); gsl_vector_complex_free(work); return s; } static int test_QRc_lssolve_r() { int s = 0; const double tol = 1.0e-10; { const double A_data[] = { 6.70178096995592e-01, 2.51765675689489e-01, 7.18387884271362e-01, 3.61106008613644e-01, 3.36342428526987e-02, 5.25755806084206e-01, 5.87596968507183e-01, 5.27700895952418e-01, 6.85871226549483e-01, 3.71216051930735e-01, 4.40045953339814e-01, 2.08875308141557e-01, 8.62676230425306e-01, 5.79995188556082e-01, 4.86983443637474e-02, 2.82915411954634e-01, 2.92843706013013e-01, 5.61536446182319e-01, 6.85137614758495e-02, 8.90853425372411e-01, 4.38527971314087e-01, 4.78136089625096e-01, 1.57942824868494e-01, 8.38451530279972e-01, 6.36273325487226e-01, 7.74039464290391e-02, 5.45646256301364e-01, 7.80075219450629e-01, 9.27400956530167e-01, 7.01700239834713e-02, 1.09682812589509e-01, 5.64047584357803e-01, 4.46922541620762e-02, 3.03438549353353e-01, 8.09200219159660e-01, 1.44245237525133e-01 }; const double rhs_data[] = { 5.82246876454474e-01, 1.42259458199622e-02, 6.25588177982770e-01, 3.79195077388159e-01, 8.45448918385455e-02, 3.20808711881935e-01, 8.02701461544476e-01, 5.65141425118050e-01, 8.34227120735637e-01, 4.69005326248388e-01, 9.73712086117648e-01, 3.47197650692321e-01 }; const double sol_data[] = { -2.07103028285037e-01, -3.77392587461962e-01, 7.46590544020302e-01, -1.10976592416587e-01, 6.07653916072011e-01, 2.05471935567110e-01 }; gsl_matrix_complex_const_view A = gsl_matrix_complex_const_view_array(A_data, 6, 3); gsl_vector_complex_const_view rhs = gsl_vector_complex_const_view_array(rhs_data, 6); gsl_vector_complex_const_view sol = gsl_vector_complex_const_view_array(sol_data, 3); test_QRc_lssolve_r_eps(&A.matrix, &rhs.vector, &sol.vector, tol, "complex_QR_lssolve_r test1"); } return s; }
{ "alphanum_fraction": 0.6474176039, "avg_line_length": 36.5460122699, "ext": "c", "hexsha": "4d2564dfa08aa8d42b89f4c669af3d35683045a9", "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/linalg/test_qrc.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/linalg/test_qrc.c", "max_line_length": 121, "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/linalg/test_qrc.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": 5779, "size": 17871 }
/* ============================================================ * * decomp_eb.c * * Martin Kilbinger, Liping Fu 2008, 2009 * * ============================================================ */ #include "decomp_eb.h" #include <gsl/gsl_sf_gamma.h> /* === CFHTLS Wide 3rd data release, Fu&Kilbinger (2010) === */ /* S/N, Psi=19' eta=1/50 */ const double a_FK10_SN[N_FK10] = {0.1197730890, -0.3881211865, 0.5212557875, -0.3440507036, 0.2761305382, -0.07286690971}; /* FoM, Psi=222', eta=1/10 */ const double a_FK10_FoM_eta10[N_FK10] = {0.009877788826, 0.1061397843, -0.4300211814, 0.5451016406, -0.3372272549, 0.1716983151}; /* FoM, Psi=222', eta=1/50 */ const double a_FK10_FoM_eta50[N_FK10] = {0.1239456383, -0.3881431858, 0.5579593467, -0.3679282338, 0.1540941993, 0.01293361618}; /* First-kind Chebyshev polynomial of order n */ #define EPS 1.0e-10 double Cheby(double x, int n, error **err) { double Cn; testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, "x = %g out of range", *err, __LINE__, -1, x); if (x<-1) x = -1.0; if (x>1) x = 1.0; Cn = cos (n * acos (x)); return Cn; } #undef EPS /* Second-kind Chebyshev polynomial of order n */ #define EPS 1.0e-10 double Cheby2(double x, int n, error **err) { double Un; testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, "x = %g out of range", *err, __LINE__, -1, x); if (x<-1) x = -1.0; if (x>1) x = 1.0; if (x == 1) { Un = n + 1; } else if (x == -1) { Un = pow(-1.0, n) * (n + 1.0); } else { Un = sin((n+1.0)*acos(x))/sin(acos (x)); } return Un; } #undef EPS /* Legendre polynomial of order n */ double Legen(double x, int n) { switch (n) { case 0: return 1.0; case 1: return x; default: return (2.0*n-1.0)/(double)n*x*Legen(x,n-1)-(n-1.0)/(double)n*Legen(x,n-2); } } /* General basis function of order n */ #define EPS 1.0e-10 double C(double x, int n, poly_t poly, error **err) { double c; testErrorRetVA(x<-1-EPS || x>1+EPS, mr_range, "x = %g out of range", *err, __LINE__, -1, x); if (x<-1) x = -1.0; if (x>1) x = 1.0; switch (poly) { case cheby : c = Cheby(x, n, err); forwardError(*err, __LINE__, -1.0); break; case cheby2 : c = Cheby2(x, n, err); forwardError(*err, __LINE__, -1.0); break; case legen : c = Legen(x, n); break; default : *err = addErrorVA(mr_poly, "Unknown polynomial type %d", *err, __LINE__, poly); return -1.0; } return c; } #undef EPS /* ============================================================ * * The filter function for the generalised ring statistics. * * FK09 (11). * * ============================================================ */ #define EPS 1.0e-6 double Tp(double x, const double *a, int N, poly_t poly, error **err) { int n; double res, Cn, Cnm1=0.0, Cnm2; if (x<-1-EPS || x>+1+EPS) return 0; /* NEW! */ //if (x<-1) x = -1; //if (x>+1) x = +1; testErrorRetVA(N<=0, mr_range, "N has to be larger than zero but is %d", *err, __LINE__, 0.0, N); testErrorRetVA(x>+1+EPS, mr_range, "x=%.10f out of range", *err, __LINE__, 0.0, x); testErrorRetVA(x<-1-EPS, mr_range, "x=%.10f out of range", *err, __LINE__, 0.0, x); if (poly==cheby || poly==cheby2) { Cnm2 = 1.0; if (poly==cheby) Cnm1 = x; else if (poly==cheby2) Cnm1 = 2.0*x; res = 0.0; res += a[0] * Cnm2; if (N==1) return res; res += a[1] * Cnm1; if (N==2) return res; for (n=2; n<N; n++) { /* Chebyshev (both T,U) recurrence relation * * C_n(x) = 2 x C_{n-1}(x) - C_{n-2}(x) */ Cn = 2.0*x*Cnm1 - Cnm2; res += a[n] * Cn; Cnm2 = Cnm1; Cnm1 = Cn; } } else { for (n=0,res=0.0; n<N; n++) { Cn = C(x, n, poly, err); forwardError(*err, __LINE__, -1); res += a[n] * Cn; } } return res; } #undef EPS /* ============================================================ * * FK09 (24). * * ============================================================ */ double Fn0(double x, int n, poly_t poly, error **err) { double fn0, denom=0.0; int nn; if (n<0) nn = -n; else nn = n; if (poly==cheby) { if (nn==0) return x + 1.0; if (nn==1) return 0.5*(x*x - 1.0); } else if (poly==cheby2) { if (n==-1) return 0.0; /* n, not nn: no symmetry for cheby2! */ } else { *err = addErrorVA(mr_poly, "Tm for polynomial type %d not defined", *err, __LINE__, poly); return 0.0; } fn0 = 0.0; if (nn%2==0) fn0 += 1.0; /* n even */ else fn0 -= 1.0; /* n odd */ //printf("# ** 1 %g\n", fn0); fn0 += x*Cheby(x, nn, err); forwardError(*err, __LINE__, 0.0); //printf("# ** 2 %g\n", fn0); if (poly==cheby) fn0 += n*(1 - x*x)*Cheby2(x, n-1, err); else if (poly==cheby2) fn0 -= (1 - x*x)*Cheby2(x, n-1, err); forwardError(*err, __LINE__, 0.0); //printf("# ** 3 %g\n", fn0); if (poly==cheby) denom = 1.0 - (double)(n*n); else if (poly==cheby2) denom = 1.0+(double)n; /* n, not nn! */ fn0 /= denom; return fn0; } /* ============================================================ * * FK09 (26) * * ============================================================ */ void Fnnu(double x, int n, poly_t poly, double Fn[], error **err) { double f0, fp1, fp2, fp3, fm1, fm2, fm3; f0 = Fn0(x, n, poly, err); forwardError(*err, __LINE__,); fp1 = Fn0(x, n+1, poly, err); forwardError(*err, __LINE__,); fp2 = Fn0(x, n+2, poly, err); forwardError(*err, __LINE__,); fp3 = Fn0(x, n+3, poly, err); forwardError(*err, __LINE__,); fm1 = Fn0(x, n-1, poly, err); forwardError(*err, __LINE__,); fm2 = Fn0(x, n-2, poly, err); forwardError(*err, __LINE__,); fm3 = Fn0(x, n-3, poly, err); forwardError(*err, __LINE__,); Fn[0] = f0; Fn[1] = 0.5*(fp1 + fm1); Fn[2] = 0.25*(fp2 + 2.0*f0 + fm2); Fn[3] = 0.125*(fp3 + 3.0*fp1 + 3.0*fm1 + fm3); } /* ============================================================ * * FK09 (23) * * ============================================================ */ #define EPS 1.0e-10 double alpha_explicit(double x, int n, double R, poly_t poly, error **err) { double r, Fn[4], alpha; testErrorRet(poly!=cheby && poly!=cheby2, mr_poly, "Explicit expression only obtained so far for cheby1 and cheby2", *err, __LINE__, 0.0); if (x<-1.0+EPS) return 0.0; assert(x>-1.0); r = 3.0/dsqr(x + R); Fnnu(x, n, poly, Fn, err); forwardError(*err, __LINE__, 0.0); alpha = R*(1.0-r*R*R)*Fn[0]; alpha += (1.0 - 3.0*r*R*R)*Fn[1]; alpha += -3.0*r*R*Fn[2]; alpha += -r*Fn[3]; alpha *= 4.0/3.0*r; return alpha; } /* ============================================================ * * The filter function T_- obtained from T_+, FK09 (20). * * ============================================================ */ #define EPS 1.0e-10 double Tm(double x, const double *a, int N, poly_t poly, double R, error **err) { double tm, c, alph; int n; testErrorRetVA(x<-1-EPS, mr_range, "x=%.20f smaller than -1", *err, __LINE__, 0.0, x); for (n=0,tm=0.0; n<N; n++) { c = C(x, n, poly, err); forwardError(*err, __LINE__, 0.0); alph = alpha_explicit(x, n, R, poly, err); forwardError(*err, __LINE__, 0.0); tm += a[n]*(c + alph); } return tm; } #undef EPS /* ================================================================== * * Returns the generalised ring statistic using a as the coefficients * * of the T_+ decomposition, see FK09 (4, 8, 11). * * The correlation functions xi+ and xi- are read from the * * Nxi-dimensional arrays xip and xim, on angular scales th. * * N is the size of the coefficient-array a. * * ================================================================== */ double RR_data(const double *xip, const double *xim, const double *th, const int Nxi, double THETA_MIN, double THETA_MAX, const double *a, int N, poly_t poly, int pm, error **err) { double theta, dtheta, res, A, B, x, summand; double dt1, dt2; int i; testErrorRetVA(abs(pm)!=1, mr_incompatible, "pm=%d not valid, has to be +1 or -1", *err, __LINE__, 0.0, pm); testErrorRetVA(THETA_MIN<th[0], mr_range, "THETA_MIN=%g' is smaller than minimum angular scale for xi+-, %g'", *err, __LINE__, 0.0, THETA_MIN/arcmin, th[0]/arcmin); testErrorRetVA(THETA_MAX>th[Nxi-1], mr_range, "THETA_MAX=%g' is larger than maximum angular scale for xi+-, %g'", *err, __LINE__, 0.0, THETA_MAX/arcmin, th[Nxi-1]/arcmin); if (a==NULL) { *err = addError(mr_null, "Coefficients a=NULL", *err, __LINE__); return 0.0; } /* FK09 (8) */ A = (THETA_MAX - THETA_MIN)/2.0; B = (THETA_MAX + THETA_MIN)/2.0; for (i=0,res=0.0; i<Nxi; i++) { theta = th[i]; if (theta < THETA_MIN) continue; else if (theta > THETA_MAX) break; /* theta[i] is the bin center */ if (i==0) { dt1 = (th[i+1] - th[i])/2.; dtheta = 2*dt1; } else if (i==Nxi-1) { dt2 = (th[i] - th[i-1])/2.; dtheta = 2*dt2; } else { dt1 = (th[i+1] - th[i])/2.; dt2 = (th[i] - th[i-1])/2.; dtheta = dt2 + dt1; } x = (theta-B)/A; if (pm==+1) { summand = xip[i]*theta/dsqr(THETA_MAX); summand *= Tp(x, a, N, poly, err); forwardError(*err, __LINE__, -1.0); } else if (pm==-1) { summand = xim[i]*theta/dsqr(THETA_MAX); summand *= Tm(x, a, N, poly, B/A, err); forwardError(*err, __LINE__, -1.0); } else { summand = 0.0; } res += summand*dtheta; } testErrorRet(!finite(res), math_infnan, "R is not finite", *err, __LINE__, 0.0); return res; } /* If cov_mode=outer, n, m are not used. For cov_mode=inner, a, N are not used. * * If cov_mode=fromZ, the covariance using Z+ is returned and a, N are not used. */ #define EPS 1.0e-5 double cov_RR(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly, const double *theta, const double *cov_xi, int Ntheta, cov_mode_t cov_mode, int n, int m, double fac, error **err) { double sum, dlogtheta, tmp, A[2], B[2], xi, xj, yi, yj, thetai, thetaj; int i, j; static double **Cov_xi = NULL; /* Testing for a==NULL not possible because cov_RR is also called from get_cov_RR_inner_array */ if (cov_mode==fromZ) { #ifdef __MRING_H sum = cov_RR_Z(THETA_MIN, THETA_MAX, theta, cov_xi, Ntheta, err); forwardError(*err, __LINE__, 0.0); return sum; #else *err = addError(mr_type, "cov_mode 'fromZ' not supported here", *err, __LINE__); return 0.0; #endif } for (i=0; i<2; i++) { A[i] = (THETA_MAX[i] - THETA_MIN[i])/2.0; B[i] = (THETA_MAX[i] + THETA_MIN[i])/2.0; } dlogtheta = log(theta[1]) - log(theta[0]); for (i=0; i<2; i++) { testErrorRetVA(theta[0]>THETA_MIN[i], mr_range, "Minumum of xi-covariance (%g=%g') larger than THETA_MIN (%g=%g')", *err, __LINE__, -1, theta[0], theta[0]/arcmin, THETA_MIN[i], THETA_MIN[i]/arcmin); testErrorRetVA(theta[Ntheta-1]<THETA_MAX[i], mr_range, "Maximum of xi-covariance scale (%g=%g') smaller than THETA_MAX (%g=%g')", *err, __LINE__, -1, theta[Ntheta-1], theta[Ntheta-1]/arcmin, THETA_MAX[i], THETA_MAX[i]/arcmin); } if (Cov_xi==NULL) { Cov_xi = sm2_matrix(0, Ntheta-1, 0, Ntheta-1, err); forwardError(*err, __LINE__, -1.0); for (i=0; i<Ntheta; i++) { for (j=0; j<Ntheta; j++) { Cov_xi[i][j] = cov_xi[i*Ntheta+j]; } } //if (fac<1.12) //fprintf(stderr, "WARNING: Cov-xi-factor = %g, too small for stable inversion of covariance!!!\n", fac); } sum = 0.0; //for (i=0; i<Ntheta; i++) { //thetai = theta[i]; for (thetai=theta[0]; thetai<=theta[Ntheta-1]; thetai*=fac) { if (thetai<THETA_MIN[0] || thetai>THETA_MAX[0]) continue; xi = (thetai-B[0])/A[0]; yi = thetai/THETA_MAX[0]; //for (j=0; j<Ntheta; j++) { //thetaj = theta[j]; for (thetaj=theta[0]; thetaj<=theta[Ntheta-1]; thetaj*=fac) { if (thetaj<THETA_MIN[1] || thetaj>THETA_MAX[1]) continue; xj = (thetaj-B[1])/A[1]; yj = thetaj/THETA_MAX[1]; tmp = dsqr(dlogtheta); if (cov_mode==outer) { tmp *= Tp(xi, a, N, poly, err); forwardError(*err, __LINE__, -1); tmp *= Tp(xj, a, N, poly, err); forwardError(*err, __LINE__, -1); } else { tmp *= C(xi, n, poly, err); forwardError(*err, __LINE__, -1); tmp *= C(xj, m, poly, err); forwardError(*err, __LINE__, -1); } tmp *= dsqr(yi*yj); //tmp *= cov_xi[i*Ntheta+j]; tmp *= sm2_interpol2d(Cov_xi, Ntheta, log(theta[0]), log(theta[Ntheta-1]), dlogtheta, log(thetai), Ntheta, log(theta[0]), log(theta[Ntheta-1]), dlogtheta, log(thetaj), 0.0, 0.0, err); forwardError(*err, __LINE__, -1.0); sum += tmp; } } /* Comment the following two lines for faster code, but be aware that no check is done * whether the input covariance changes! */ sm2_free_matrix(Cov_xi, 0, Ntheta-1, 0, Ntheta-1); Cov_xi = NULL; return sum; } #undef EPS /* RR-Covariance using a diagonal xi-covariance. * * If cov_mode=outer, n, m are not used. For cov_mode=inner, a, N are not used. * * If cov_mode=fromZ, the covariance using Z+ is returned and a, N are not used. */ #define EPS 1.0e-5 double cov_RR_diag_xi(const double *THETA_MIN, const double *THETA_MAX, const double *a, int N, poly_t poly, const double *theta, const double *var_xi, int Ntheta, int islog, error **err) { double sum, dlogtheta, dtheta, tmp, A[2], B[2], xi, xj, yi, yj, thetai, thetaj; int i; for (i=0; i<2; i++) { A[i] = (THETA_MAX[i] - THETA_MIN[i])/2.0; B[i] = (THETA_MAX[i] + THETA_MIN[i])/2.0; } if (islog==0) { dtheta = theta[1] - theta[0]; dlogtheta = 0.0; } else if (islog==1) { dlogtheta = log(theta[1]) - log(theta[0]); dtheta = 0.0; } else { *err = addErrorVA(mr_type, "Invalid flag islog = %d\n", *err, __LINE__, islog); return 0.0; } for (i=0; i<2; i++) { testErrorRetVA(theta[0]>THETA_MIN[i], mr_range, "Minumum of xi-covariance (%g=%g') larger than THETA_MIN (%g=%g')", *err, __LINE__, -1, theta[0], theta[0]/arcmin, THETA_MIN[i], THETA_MIN[i]/arcmin); testErrorRetVA(theta[Ntheta-1]<THETA_MAX[i], mr_range, "Maximum of xi-covariance scale (%g=%g') smaller than THETA_MAX (%g=%g')", *err, __LINE__, -1, theta[Ntheta-1], theta[Ntheta-1]/arcmin, THETA_MAX[i], THETA_MAX[i]/arcmin); } sum = 0.0; for (i=0; i<Ntheta; i++) { thetai = theta[i]; thetaj = thetai; if (thetai<THETA_MIN[0] || thetai>THETA_MAX[0]) continue; xi = (thetai-B[0])/A[0]; yi = thetai/THETA_MAX[0]; xj = (thetaj-B[1])/A[1]; yj = thetaj/THETA_MAX[1]; if (islog==0) { // tmp = dsqr(dtheta) /thetai/thetai; tmp = dsqr(dtheta)*yi*yj/THETA_MAX[0]/THETA_MAX[1]; } else { tmp = dsqr(dlogtheta); tmp *= dsqr(yi*yj); } tmp *= Tp(xi, a, N, poly, err); forwardError(*err, __LINE__, -1); tmp *= Tp(xj, a, N, poly, err); forwardError(*err, __LINE__, -1); tmp *= var_xi[i]; // tmp *= dsqr(yi*yj); sum += tmp; } return sum; } #undef EPS /* ============================================================ * * Returns the chi^2 for a null test (RR=0). * * ============================================================ */ double chi2_RB_null(const double *RB, const double *covRB, int NRB) { int i, j; double c2; for (i=0,c2=0.0; i<NRB; i++) { for (j=0; j<NRB; j++) { c2 += RB[i] * covRB[i*NRB+j] * RB[j]; } } return c2; } /* ============================================================ * * Reads COSEBIs zeros and normalisation coefficients from file * * and returns polynomial coefficients. File name is automatic, * * scale checks are done. * * ============================================================ */ double *read_zeros_norm_cosebi_auto_check(double Psimin, double Psimax, const char *path, error **err) { double *c_cosebi, psimin, psimax; char rname[1024]; sprintf(rname, "%s/cosebi_tplog_rN_%d_%.3f_%.3f", path == NULL ? "." : path, NMAX_COSEBI, Psimin/arcmin, Psimax/arcmin); c_cosebi = read_zeros_norm_cosebi(rname, &psimin, &psimax, err); forwardError(*err, __LINE__, NULL); testErrorRetVA(fabs(psimin-Psimin/arcmin)>EPSILON, mr_file, "Inconsistent file %s, psimin=%g should be %g according to the file name", *err, __LINE__, NULL, rname, psimin, Psimin/arcmin); testErrorRetVA(fabs(psimax-Psimax/arcmin)>EPSILON, mr_file, "Inconsistent file %s, psimax=%g should be %g according to the file name", *err, __LINE__, NULL, rname, psimax, Psimax/arcmin); return c_cosebi; } /* ============================================================ * * Reads COSEBIs zeros and normalisation coefficients from file * * and sets corresponding min and max scales. * * Calculates polynomial coefficients c and returns them. * * ============================================================ */ double *read_zeros_norm_cosebi(const char *rname, double *psimin, double *psimax, error **err) { FILE *F; int Nzeros, Ncoeff, k, n, off_c, off_R, nmax; ssize_t nread; double *Rn, *Norm, *c; char *str, *line=NULL; F = fopen_err(rname, "r", err); forwardError(*err, __LINE__, NULL); /* Read two header lines */ line = malloc_err(1024*sizeof(char), err); forwardError(*err, __LINE__, NULL); str = fgets(line, 1024, F); str = fgets(line, 1024, F); free(line); nread = fscanf(F, "%d %lg %lg\n", &nmax, psimin, psimax); testErrorRet(nread != 3, mr_file, "File has wrong format.", *err, __LINE__, NULL); testErrorRetVA(nmax > NMAX_COSEBI, mr_range, "COSEBI number of modes n=%d read from file %s cannot be larger than NMAX_COSEBI=%d", *err, __LINE__, NULL, nmax, rname, NMAX_COSEBI); /* Number of zeros for nmax polynomials, * * sum_{i=1}^{nmax+1} (i+1) = sum_{i=0}^{nmax+1} i - 1 */ Nzeros = (nmax+1) * (nmax+2) / 2 - 1; //fprintf(stderr, "nmax = %d , Psi = [%g, %g]\n", nmax, *psimin, *psimax); //fprintf(stderr, "Reading %d Rn, %d Norm, from %s\n", Nzeros, nmax, rname); Rn = malloc_err(sizeof(double)*Nzeros, err); forwardError(*err, __LINE__, NULL); Norm = malloc_err(sizeof(double)*nmax, err); forwardError(*err, __LINE__, NULL); /* Read zeros */ for (k=0; k<Nzeros; k++) { fscanf(F, "%lg ", Rn+k); } /* Read normalisations */ for (k=0; k<nmax; k++) { fscanf(F, "%lg ", Norm+k); } fclose(F); /* Calculate polynomial coefficients */ Ncoeff = NMAX_COSEBI * (NMAX_COSEBI + 5) / 2; c = malloc_err(sizeof(double)*Ncoeff, err); forwardError(*err, __LINE__, NULL); /* Polynomial T_i of order i+1 */ for (n=1,off_R=0; n<=nmax; n++) { off_c = n*(n + 3)/2 - 2; // Offset for coefficients for polynomial #n for (k=0; k<n+2; k++) { c[k + off_c] = sum_combinations(n+1-k, n+1, Rn+off_R, err); forwardError(*err, __LINE__, NULL); c[k + off_c] *= Norm[n-1]; if (k % 2 == 1) c[k + off_c] = -c[k + off_c]; if (n % 2 == 0) c[k + off_c] = -c[k + off_c]; } off_R = (n+1)*(n+2)/2 - 1; // Ncoeff for index i, degree i+1 } free(Rn); free(Norm); return c; } /* ============================================================ * * COSEBI logarithmis filter function, SEK10 (28). The * * coefficients have to be precalculated from the zeros, output * * by Mathematica. * * Not normalised. * * ============================================================ */ double Tplog_c(double z, const double *c, int n, error **err) { int i, off_c; double res, zpowerm; const double *cn; off_c = n*(n + 3)/2 - 2; // Offset for coefficients for polynomial #n cn = c + off_c; for (i=0,res=0.0,zpowerm=1.0; i<=n+1; i++) { res += cn[i] * zpowerm; zpowerm *= z; } testErrorRet(!finite(res), math_infnan, "Tplog is not finite", *err, __LINE__, 0.0); return res; } /* ============================================================ * * Filter function, SEK10 (38, 39). Normalised. * * ============================================================ */ double Tmlog(double z, const double *c, int n, error **err) { int m, off_c; double res, zpowerm; const double *cn; off_c = n*(n + 3)/2 - 2; // Offset for coefficients for polynomial #n cn = c + off_c; for (m=0,res=0.0,zpowerm=1; m<=n; m++) { // n+1 MKDEBUG ?? res += dnm(n, m ,cn) * zpowerm; zpowerm *= z; } res += an2(n, cn) * exp(-2.0*z) - an4(n, cn) * exp(-4.0*z); testErrorRet(!finite(res), math_infnan, "Tmlog is not finite", *err, __LINE__, 0.0); return res; } double an2(int n, const double *c) { int j; double res, jfac, m2powerjp1; for (j=0,res=0.0,jfac=1.0,m2powerjp1=-2.0; j<=n+1; j++) { res += c[j]*jfac / m2powerjp1; jfac *= j + 1.0; /* factorial(j) */ m2powerjp1 *= -2.0; /* (-2)^(j+1) */ } res *= 4.0; return res; } double an4(int n, const double *c) { int j; double res, jfac, m4powerjp1; for (j=0,res=0.0,jfac=1.0,m4powerjp1=-4.0; j<=n+1; j++) { res += c[j]*jfac / m4powerjp1; jfac *= j + 1.0; m4powerjp1 *= -4.0; /* (-4)^(j+1) */ } res *= 12.0; return res; } /* dnm(n+1, n, c) = 0 */ double dnm(int n, const int m, const double *c) { int j; double res, jfac, m2powermjm1, p2powermjm1, mfac; p2powermjm1 = 0.5; m2powermjm1 = -0.5; mfac = gsl_sf_fact(m); for (j=m,res=0.0,jfac=mfac; j<=n+1; j++) { res += c[j] * jfac * m2powermjm1 * (3.0 * p2powermjm1 - 1.0); jfac *= j + 1.0; /* j! */ m2powermjm1 /= -2.0; /* (-2)^(m-j-1) */ p2powermjm1 /= 2.0; /* 2^(m-k-1) */ } res *= 4.0/mfac; res += c[m]; return res; } double sum_combinations(int j, int n, const double *r, error **err) { gsl_combination *c; size_t i, c_i; double sum, prod; if (n==0) return 1.0; c = gsl_combination_calloc(n, j); sum = 0.0; do { for (i=0,prod=1.0; i<j; i++) { c_i = gsl_combination_get(c, i); prod *= r[c_i]; //printf(" %zu", c_i); } sum += prod; //printf("{"); gsl_combination_fprintf(stdout, c, " %u"); printf (" }\n"); } while (gsl_combination_next(c) == GSL_SUCCESS); gsl_combination_free(c); return sum; } /* ============================================================ * * E-/B-mode correlation functions from COSEBIs, SEK10 (40). * * The results are stored in xi_pm_EB = (E+, E-, B+, B-). * * ============================================================ */ void xipmEB(double theta, double THETA_MIN, double THETA_MAX, const double *c, const double *E, const double *B, int N, double xi_pm_EB[4], error **err) { double Tp, Tm, z; int n; for (n=0; n<4; n++) { xi_pm_EB[n] = 0.0; } for (n=1; n<=N; n++) { z = log(theta/THETA_MIN); Tp = Tplog_c(z, c, n, err); Tm = Tmlog(z, c, n, err); xi_pm_EB[0] += E[n] * Tp; // E+ xi_pm_EB[1] += E[n] * Tm; // E- xi_pm_EB[2] += B[n] * Tp; // B+ xi_pm_EB[3] += B[n] * Tm; // B- } for (n=0; n<4; n++) { xi_pm_EB[n] *= 2.0 / theta / (THETA_MAX - THETA_MIN); } }
{ "alphanum_fraction": 0.5209239475, "avg_line_length": 28.84409257, "ext": "c", "hexsha": "752887e7482cc1504dc5310ba4f3e52824c4641d", "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": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "danielgruen/ccv", "max_forks_repo_path": "src/nicaea_2.5/Cosmo/src/decomp_eb.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "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": "danielgruen/ccv", "max_issues_repo_path": "src/nicaea_2.5/Cosmo/src/decomp_eb.c", "max_line_length": 129, "max_stars_count": 2, "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_path": "src/nicaea_2.5/Cosmo/src/decomp_eb.c", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "num_tokens": 8380, "size": 23681 }
#include <errno.h> #include <getopt.h> #include <gsl/gsl_spmatrix.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> static int clock = 1; static int results = 0; static int verbose = 0; static int help = 0; int test (size_t m, size_t n, size_t nnz, const size_t *ptr, const size_t *ind, size_t B, double epsilon, double delta, int trials, int clock, int results, int verbose); char *name (); static void usage () { fprintf(stderr,"usage: %s [options] <input>\n" " <input> MatrixMarket file (estimate fill of this matrix)\n" " -B, --max-block-size <arg> Maximum block dimension for fill estimates\n" " -e, --epsilon <arg> Be accurate to relative error epsilon\n" " -d, --delta <arg> With probability (1 - delta)\n" " -t, --trials <arg> Number of trials to run\n" " -c, --clock Display timing information\n" " -C, --noclock Do not display timing information\n" " -r, --results Display fill estimates for all trials\n" " -R, --noresults Do not display fill estimates\n" " -v, --verbose Verbose mode\n" " -q, --quiet Quiet mode\n" " -h, --help Display help message\n", name()); } int main (int argc, char **argv) { size_t B = 12; double epsilon = 0.1; double delta = 0.01; int trials = 1; /* Beware. Option parsing below. */ long longarg; double doublearg; while (1) { static char *options = "B:e:d:t:cCrRvqh"; static struct option long_options[] = { {"max-block-size", required_argument, 0, 'B'}, {"trials", required_argument, 0, 't'}, {"epsilon", required_argument, 0, 'e'}, {"delta", required_argument, 0, 'd'}, {"clock", no_argument, &clock, 1}, {"noclock", no_argument, &clock, 0}, {"results", no_argument, &results, 1}, {"noresults", no_argument, &results, 0}, {"verbose", no_argument, &verbose, 1}, {"quiet", no_argument, &verbose, 0}, {"help", no_argument, &help, 1}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; int c = getopt_long (argc, argv, options, long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; if (c == 0 && long_options[option_index].flag == 0) c = long_options[option_index].val; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ break; case 'B': errno = 0; longarg = strtol(optarg, 0, 10); if (errno != 0 || longarg < 1) { printf("option -B takes an integer maximum block size >= 1\n"); usage(); return 1; } B = longarg; break; case 'e': errno = 0; doublearg = strtod(optarg, 0); if (errno != 0 || doublearg < 0.0) { printf("option -e takes a desired relative error >= 0.0\n"); usage(); return 1; } epsilon = doublearg; break; case 'd': errno = 0; doublearg = strtod(optarg, 0); if (errno != 0 || doublearg < 0.0 || doublearg > 1.0) { printf("option -d takes a desired probability >= 0.0 and <= 1.0\n"); usage(); return 1; } delta = doublearg; break; case 't': errno = 0; longarg = strtol(optarg, 0, 10); if (errno != 0 || longarg < 1) { printf("option -t takes an integer number of trials >= 1\n"); usage(); return 1; } trials = longarg; break; case 'c': clock = 1; break; case 'C': clock = 0; break; case 'r': results = 1; break; case 'R': results = 0; break; case 'v': verbose = 1; break; case 'q': verbose = 0; break; case 'h': help = 1; break; case '?': usage(); return 1; default: abort(); } } if (help) { printf("Run a fill estimation algorithm!\n"); usage(); return 0; } if (argc - optind > 1) { printf("<input> cannot be more than one file\n"); usage(); return 1; } if (argc - optind < 1) { printf("<input> not specified\n"); usage(); return 1; } struct stat statthing; if (stat(argv[optind], &statthing) < 0 || !S_ISREG(statthing.st_mode)){ printf("<input> must be filename of MatrixMarket matrix\n"); usage(); return 1; } FILE *f = fopen(argv[optind], "r"); gsl_spmatrix *triples = gsl_spmatrix_fscanf(f); fclose(f); if (triples == 0) { printf("<input> must be filename of MatrixMarket matrix\n"); usage(); return 1; } gsl_spmatrix *csr = gsl_spmatrix_crs(triples); gsl_spmatrix_free(triples); //gsl_spmatrix_fprintf(stdout, csr, "%g"); int ret = test(csr->size1, csr->size2, csr->nz, csr->p, csr->i, B, epsilon, delta, trials, clock, results, verbose); gsl_spmatrix_free(csr); return ret; }
{ "alphanum_fraction": 0.5137769447, "avg_line_length": 24.8139534884, "ext": "c", "hexsha": "86605794f7d1b03981b21ebb5cee78a18f3afba6", "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": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_path": "src/run_fill.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "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": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_path": "src/run_fill.c", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "src/run_fill.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1500, "size": 5335 }
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /*---------------------------------------------------------------------------*/ /* This 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 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 */ /* If not, see <http://www.gnu.org/licenses/>. */ /*---------------------------------------------------------------------------*/ /* */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <sys/param.h> #include <sys/stat.h> #include <stddef.h> #include <sys/time.h> #define TRUE 1 #define FALSE 0 #define MAXSTR 1024 #define MAXELEM 1024 /* Some data types */ #define INT16 1 /* 16 bit integer */ #define INT32 2 /* 32 bit integer */ #define FLT32 3 /* 32 bit float */ #define DBL64 4 /* 64 bit double */ /* Include GSL libraries */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multifit_nlin.h> /* Include local functions */ #include "gsl_functions.c" /* local GSL functions */ #include "utils.c" #include "getpars.c" #include "fdf.c" #include "image_functions.c" /* Include Analyze libraries */ #include "AVW.c" /* local AVW functions */ #ifdef NOTLIKELY #include <AVW.h> #include <AVW_ImageFile.h> #include <AVW.c> #endif //#include "avw.c"
{ "alphanum_fraction": 0.5518380834, "avg_line_length": 33.1643835616, "ext": "h", "hexsha": "2e7a34217d25fd2b357802e079eae98763b39d93", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "timburrow/openvnmrj-source", "max_forks_repo_path": "src/bin_image/utils.h", "max_issues_count": 128, "max_issues_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "timburrow/openvnmrj-source", "max_issues_repo_path": "src/bin_image/utils.h", "max_line_length": 79, "max_stars_count": 32, "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_path": "src/bin_image/utils.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "num_tokens": 518, "size": 2421 }
/* * SPDX-FileCopyrightText: Copyright 2021, Siavash Ameli <sameli@berkeley.edu> * SPDX-License-Identifier: BSD-3-Clause * SPDX-FileType: SOURCE * * This program is free software: you can redistribute it and/or modify it * under the terms of the license found in the LICENSE.txt file in the root * directory of this source tree. */ #ifndef _C_BASIC_ALGEBRA_CBLAS_INTERFACE_H_ #define _C_BASIC_ALGEBRA_CBLAS_INTERFACE_H_ // ======= // Headers // ======= #include "../_definitions/definitions.h" // USE_CBLAS #if (USE_CBLAS == 1) #include <cblas.h> // CBLAS_LAYOUT, CBLAS_TRANSPOSE, cblas_sgemv, cblas_dgemv, // cblas_scopy, cblas_dcopy, cblas_saxpy, cblas_daxpy, // cblas_snrm2, cblas_dnrm2, cblas_sscal, cblas_dscal typedef CBLAS_ORDER CBLAS_LAYOUT; // backward compatibility with CBLAS_LAYOUT // =============== // cblas interface // =============== /// \namespace cblas_interface /// /// \brief A collection of templates to wrapper cblas functions. namespace cblas_interface { // cblas xgemv template <typename DataType> void xgemv( CBLAS_LAYOUT layout, CBLAS_TRANSPOSE TransA, const int M, const int N, const DataType alpha, const DataType* A, const int lda, const DataType* X, const int incX, const DataType beta, DataType* Y, const int incY); // cblas xcopy template <typename DataType> void xcopy( const int N, const DataType* X, const int incX, DataType* Y, const int incY); // cblas xaxpy template <typename DataType> void xaxpy( const int N, const DataType alpha, const DataType* X, const int incX, DataType* Y, const int incY); // cblas xdot template <typename DataType> DataType xdot( const int N, const DataType* X, const int incX, const DataType* Y, const int incY); // cblas xnrm2 template <typename DataType> DataType xnrm2( const int N, const DataType* X, const int incX); // cblas xscal template <typename DataType> void xscal( const int N, const DataType alpha, DataType* X, const int incX); } // namespace cblas_interface #endif // USE_CBLAS #endif // _C_BASIC_ALGEBRA_CBLAS_INTERFACE_H_
{ "alphanum_fraction": 0.5821068939, "avg_line_length": 24.8269230769, "ext": "h", "hexsha": "d9e739b0c8906111c8e7a50a7e7a1b04b592fcdd", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-08-21T12:12:44.000Z", "max_forks_repo_forks_event_min_datetime": "2021-08-21T12:12:44.000Z", "max_forks_repo_head_hexsha": "fe759af016c5845d88ca98e56994b6c86c132792", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ameli/TraceInv", "max_forks_repo_path": "imate/_c_basic_algebra/cblas_interface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fe759af016c5845d88ca98e56994b6c86c132792", "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": "ameli/TraceInv", "max_issues_repo_path": "imate/_c_basic_algebra/cblas_interface.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fe759af016c5845d88ca98e56994b6c86c132792", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ameli/TraceInv", "max_stars_repo_path": "imate/_c_basic_algebra/cblas_interface.h", "max_stars_repo_stars_event_max_datetime": "2021-08-21T12:12:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-21T12:12:28.000Z", "num_tokens": 637, "size": 2582 }
/* specfunc/bessel_I1.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. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_bessel.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" #define ROOT_EIGHT (2.0*M_SQRT2) /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on SLATEC besi1(), besi1e() */ /* chebyshev expansions series for bi1 on the interval 0. to 9.00000d+00 with weighted error 2.40e-17 log weighted error 16.62 significant figures required 16.23 decimal places required 17.14 series for ai1 on the interval 1.25000d-01 to 3.33333d-01 with weighted error 6.98e-17 log weighted error 16.16 significant figures required 14.53 decimal places required 16.82 series for ai12 on the interval 0. to 1.25000d-01 with weighted error 3.55e-17 log weighted error 16.45 significant figures required 14.69 decimal places required 17.12 */ static double bi1_data[11] = { -0.001971713261099859, 0.407348876675464810, 0.034838994299959456, 0.001545394556300123, 0.000041888521098377, 0.000000764902676483, 0.000000010042493924, 0.000000000099322077, 0.000000000000766380, 0.000000000000004741, 0.000000000000000024 }; static cheb_series bi1_cs = { bi1_data, 10, -1, 1, 10 }; static double ai1_data[21] = { -0.02846744181881479, -0.01922953231443221, -0.00061151858579437, -0.00002069971253350, 0.00000858561914581, 0.00000104949824671, -0.00000029183389184, -0.00000001559378146, 0.00000001318012367, -0.00000000144842341, -0.00000000029085122, 0.00000000012663889, -0.00000000001664947, -0.00000000000166665, 0.00000000000124260, -0.00000000000027315, 0.00000000000002023, 0.00000000000000730, -0.00000000000000333, 0.00000000000000071, -0.00000000000000006 }; static cheb_series ai1_cs = { ai1_data, 20, -1, 1, 11 }; static double ai12_data[22] = { 0.02857623501828014, -0.00976109749136147, -0.00011058893876263, -0.00000388256480887, -0.00000025122362377, -0.00000002631468847, -0.00000000383538039, -0.00000000055897433, -0.00000000001897495, 0.00000000003252602, 0.00000000001412580, 0.00000000000203564, -0.00000000000071985, -0.00000000000040836, -0.00000000000002101, 0.00000000000004273, 0.00000000000001041, -0.00000000000000382, -0.00000000000000186, 0.00000000000000033, 0.00000000000000028, -0.00000000000000003 }; static cheb_series ai12_cs = { ai12_data, 21, -1, 1, 9 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result) { const double xmin = 2.0 * GSL_DBL_MIN; const double x_small = ROOT_EIGHT * GSL_SQRT_DBL_EPSILON; const double y = fabs(x); /* CHECK_POINTER(result) */ if(y == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(y < xmin) { UNDERFLOW_ERROR(result); } else if(y < x_small) { result->val = 0.5*x; result->err = 0.0; return GSL_SUCCESS; } else if(y <= 3.0) { const double ey = exp(-y); gsl_sf_result c; cheb_eval_e(&bi1_cs, y*y/4.5-1.0, &c); result->val = x * ey * (0.875 + c.val); result->err = ey * c.err + y * GSL_DBL_EPSILON * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(y <= 8.0) { const double sy = sqrt(y); gsl_sf_result c; double b; double s; cheb_eval_e(&ai1_cs, (48.0/y-11.0)/5.0, &c); b = (0.375 + c.val) / sy; s = (x > 0.0 ? 1.0 : -1.0); result->val = s * b; result->err = c.err / sy; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sy = sqrt(y); gsl_sf_result c; double b; double s; cheb_eval_e(&ai12_cs, 16.0/y-1.0, &c); b = (0.375 + c.val) / sy; s = (x > 0.0 ? 1.0 : -1.0); result->val = s * b; result->err = c.err / sy; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result) { const double xmin = 2.0 * GSL_DBL_MIN; const double x_small = ROOT_EIGHT * GSL_SQRT_DBL_EPSILON; const double y = fabs(x); /* CHECK_POINTER(result) */ if(y == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(y < xmin) { UNDERFLOW_ERROR(result); } else if(y < x_small) { result->val = 0.5*x; result->err = 0.0; return GSL_SUCCESS; } else if(y <= 3.0) { gsl_sf_result c; cheb_eval_e(&bi1_cs, y*y/4.5-1.0, &c); result->val = x * (0.875 + c.val); result->err = y * c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(y < GSL_LOG_DBL_MAX) { const double ey = exp(y); gsl_sf_result I1_scaled; gsl_sf_bessel_I1_scaled_e(x, &I1_scaled); result->val = ey * I1_scaled.val; result->err = ey * I1_scaled.err + y * GSL_DBL_EPSILON * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { OVERFLOW_ERROR(result); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_I1_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_I1_scaled_e(x, &result)); } double gsl_sf_bessel_I1(const double x) { EVAL_RESULT(gsl_sf_bessel_I1_e(x, &result)); }
{ "alphanum_fraction": 0.6077510276, "avg_line_length": 26.3011583012, "ext": "c", "hexsha": "18b2c0e3315b23fb8c6a1fa6fef827ec977d60ac", "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/specfunc/bessel_I1.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/specfunc/bessel_I1.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/specfunc/bessel_I1.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": 2310, "size": 6812 }
// -*- C++ -*- // // michael a.g. aïvázis <michael.aivazis@para-sim.com> // // (c) 2013-2020 parasim inc // (c) 2010-2020 california institute of technology // all rights reserved // // code guard #if !defined(altar_bayesian_CoolingStep_h) #define altar_bayesian_CoolingStep_h // externals #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> // place everything in the local namespace namespace altar { namespace bayesian { // forward declarations class CoolingStep; } // of namespace bayesian } // of namespace altar // declaration class altar::bayesian::CoolingStep { // types public: typedef gsl_vector vector_t; typedef gsl_matrix matrix_t; // interface public: inline auto samples() const; inline auto parameters() const; inline auto beta() const; inline void beta(double value); inline auto theta() const; inline auto prior() const; inline auto data() const; inline auto posterior() const; inline auto sigma() const; // meta-methods public: virtual ~CoolingStep(); inline CoolingStep(size_t samples, size_t parameters, double beta=0.0); // data private: const size_t _samples; // the number of samples const size_t _parameters; // the number of model parameters double _beta; // the current temperature matrix_t * const _theta; // the sample set, a (samples x parameters) matrix vector_t * const _prior; // the log likelihoods of the samples in the model prior vector_t * const _data; // the log likelihoods of the samples given the data vector_t * const _posterior; // the posterior log likelihood matrix_t * const _sigma; // the parameter covariance // disallow private: CoolingStep(const CoolingStep &) = delete; const CoolingStep & operator=(const CoolingStep &) = delete; }; // get the inline definitions #define altar_bayesian_CoolingStep_icc #include "CoolingStep.icc" #undef altar_bayesian_CoolingStep_icc # endif // end of file
{ "alphanum_fraction": 0.7016491754, "avg_line_length": 24.1084337349, "ext": "h", "hexsha": "9611a3b3ce79bec9b8f8c7e794a6273e7177d387", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2022-02-10T07:10:00.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-26T18:40:41.000Z", "max_forks_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "AlTarFramework/altar", "max_forks_repo_path": "altar/lib/libaltar/bayesian/CoolingStep.h", "max_issues_count": 13, "max_issues_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7", "max_issues_repo_issues_event_max_datetime": "2022-02-16T06:48:30.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-20T15:55:50.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "AlTarFramework/altar", "max_issues_repo_path": "altar/lib/libaltar/bayesian/CoolingStep.h", "max_line_length": 85, "max_stars_count": 32, "max_stars_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "AlTarFramework/altar", "max_stars_repo_path": "altar/lib/libaltar/bayesian/CoolingStep.h", "max_stars_repo_stars_event_max_datetime": "2021-12-15T23:48:38.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-24T05:32:27.000Z", "num_tokens": 504, "size": 2001 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <memory> #include <numeric> #include <algorithm> #include <vector> #include <string> #include <limits> #include <memory> #include <optional> #include <list> #include <map> #include <deque> #include <chrono> #include <variant> #include <cassert> #include <wrl/client.h> #include <wrl/implements.h> #include <wil/wrl.h> #include <wil/result.h> #include <gsl/gsl> #include <d3d12.h> #include <d3d12sdklayers.h> #include "External/D3DX12/d3dx12.h" #include <DirectML.h> #include "core/common/common.h" #include "ErrorHandling.h" // DirectML helper libraries #include "External/DirectMLHelpers/ApiTraits.h" #include "External/DirectMLHelpers/ApiHelpers.h" #include "External/DirectMLHelpers/DirectMLSchema.h" #include "External/DirectMLHelpers/AbstractOperatorDesc.h" #include "External/DirectMLHelpers/GeneratedSchemaTypes.h" #include "External/DirectMLHelpers/SchemaHelpers.h" #include "External/DirectMLHelpers/GeneratedSchemaHelpers.h" using Microsoft::WRL::ComPtr; // Windows pollutes the macro space, causing a build break in schema.h. #undef OPTIONAL #include "core/providers/dml/DmlExecutionProvider/inc/DmlExecutionProvider.h" #include "core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h" #include "core/providers/dml/OperatorAuthorHelper/Common.h" #include "DmlCommon.h" #include "TensorDesc.h" #include "DescriptorPool.h" #include "IExecutionProvider.h"
{ "alphanum_fraction": 0.7832446809, "avg_line_length": 25.4915254237, "ext": "h", "hexsha": "d057c944359c4e124c200522e1000a537b07b872", "lang": "C", "max_forks_count": 11, "max_forks_repo_forks_event_max_datetime": "2022-03-09T21:24:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-08T15:50:39.000Z", "max_forks_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lchang20/onnxruntime", "max_forks_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_issues_count": 82, "max_issues_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_issues_repo_issues_event_max_datetime": "2022-03-27T07:33:51.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-21T20:03:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lchang20/onnxruntime", "max_issues_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_line_length": 77, "max_stars_count": 25, "max_stars_repo_head_hexsha": "97b8f6f394ae02c73ed775f456fd85639c91ced1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lchang20/onnxruntime", "max_stars_repo_path": "onnxruntime/core/providers/dml/DmlExecutionProvider/src/precomp.h", "max_stars_repo_stars_event_max_datetime": "2022-03-09T21:24:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-28T09:07:15.000Z", "num_tokens": 358, "size": 1504 }
/* randist/tdist.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The t-distribution has the form p(x) dx = (Gamma((nu + 1)/2)/(sqrt(pi nu) Gamma(nu/2)) * (1 + (x^2)/nu)^-((nu + 1)/2) dx The method used here is the one described in Knuth */ double gsl_ran_tdist (const gsl_rng * r, const double nu) { if (nu <= 2) { double Y1 = gsl_ran_ugaussian (r); double Y2 = gsl_ran_chisq (r, nu); double t = Y1 / sqrt (Y2 / nu); return t; } else { double Y1, Y2, Z, t; do { Y1 = gsl_ran_ugaussian (r); Y2 = gsl_ran_exponential (r, 1 / (nu/2 - 1)); Z = Y1 * Y1 / (nu - 2); } while (1 - Z < 0 || exp (-Y2 - Z) > (1 - Z)); /* Note that there is a typo in Knuth's formula, the line below is taken from the original paper of Marsaglia, Mathematics of Computation, 34 (1980), p 234-256 */ t = Y1 / sqrt ((1 - 2 / nu) * (1 - Z)); return t; } } double gsl_ran_tdist_pdf (const double x, const double nu) { double p; double lg1 = gsl_sf_lngamma (nu / 2); double lg2 = gsl_sf_lngamma ((nu + 1) / 2); p = ((exp (lg2 - lg1) / sqrt (M_PI * nu)) * pow ((1 + x * x / nu), -(nu + 1) / 2)); return p; }
{ "alphanum_fraction": 0.6228571429, "avg_line_length": 25.9259259259, "ext": "c", "hexsha": "1faae4c69586957a5d6640e85669fd9dd3c35ff1", "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/randist/tdist.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/randist/tdist.c", "max_line_length": 72, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/tdist.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": 682, "size": 2100 }
/* * 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 type_f33c5e03_70f2_4879_9504_332323832a40_h #define type_f33c5e03_70f2_4879_9504_332323832a40_h #include <ariel/config.h> #include <gslib/type.h> #include <gslib/string.h> #include <gslib/math.h> #include <gslib/std.h> __ariel_begin__ struct ariel_export color { union { struct { byte red, green, blue, alpha; }; uint _data; }; public: color() { data() = 0; } color(int r, int g, int b) { set_color(r, g, b); } color(int r, int g, int b, int a) { set_color(r, g, b, a); } uint& data() { return _data; } uint data() const { return _data; } void set_color(int r, int g, int b) { red = r, green = g, blue = b, alpha = 255; } void set_color(int r, int g, int b, int a) { red = r, green = g, blue = b, alpha = a; } bool operator !=(const color& cr) const { return blue != cr.blue || green != cr.green || red != cr.red || alpha != cr.alpha; } bool operator ==(const color& cr) const { return blue == cr.blue && green == cr.green && red == cr.red && alpha == cr.alpha; } color& lerp(const color& c1, const color& c2, float s) { assert(s >= 0.f && s <= 1.f); float t = 1.f - s; red = (int)(s * c1.red + t * c2.red); green = (int)(s * c1.green + t * c2.green); blue = (int)(s * c1.blue + t * c2.blue); alpha = (int)(s * c1.alpha + t * c2.alpha); return *this; } }; struct ariel_export font { enum { declare_mask(ftm_italic, 0), declare_mask(ftm_underline, 1), declare_mask(ftm_strikeout, 2), }; public: string name; int size; int escape; int orient; int weight; /* 0-9 */ uint mask; private: friend class fsys_win32; friend class fsys_dwrite; mutable uint sysfont; public: font() { size = 0; escape = 0; orient = 0; weight = 3; mask = 0; sysfont = 0; } font(const font& that) { name = that.name; size = that.size; escape = that.escape; orient = that.orient; weight = that.weight; mask = that.mask; sysfont = that.sysfont; } font(const gchar* n, int sz) { name.assign(n); size = sz; escape = 0; orient = 0; weight = 3; mask = 0; sysfont = 0; } font& operator = (const font& that) { name = that.name; size = that.size; escape = that.escape; orient = that.orient; weight = that.weight; mask = that.mask; return *this; } bool operator == (const font& that) const { if(name != that.name) return false; if(size != that.size) return false; if(escape != that.escape) return false; if(orient != that.orient) return false; if(weight != that.weight) return false; if(mask != that.mask) return false; return true; } bool operator != (const font& that) const { if(name != that.name) return true; if(size != that.size) return true; if(escape != that.escape) return true; if(orient != that.orient) return true; if(weight != that.weight) return true; if(mask != that.mask) return true; return false; } size_t hash_value() const { hasher h; h.add_bytes((const byte*)name.c_str(), name.length() * sizeof(gchar)); h.add_bytes((const byte*)&size, sizeof(size)); h.add_bytes((const byte*)&escape, sizeof(escape)); h.add_bytes((const byte*)&orient, sizeof(orient)); h.add_bytes((const byte*)&weight, sizeof(weight)); return h.add_bytes((const byte*)&mask, sizeof(mask)); } }; struct ariel_export viewport { float left; float top; float width; float height; float min_depth; float max_depth; }; struct ariel_export axis_aligned_bound_box { float left = FLT_MAX; float right = -FLT_MAX; float top = FLT_MAX; float bottom = -FLT_MAX; float front = FLT_MAX; float back = -FLT_MAX; public: void reset() { left = top = front = FLT_MAX; right = bottom = back = -FLT_MAX; } float width() const { return right - left; } float height() const { return bottom - top; } float depth() const { return back - front; } }; struct ariel_export origin_bound_sphere { float radius = 0.f; }; struct ariel_export bound_sphere { vec3 origin; float radius = 0.f; }; enum res_type { res_mesh, }; class __gs_novtable ariel_export res_node abstract { public: virtual ~res_node() {} virtual res_type get_type() const = 0; virtual const string& get_name() const { return _name; } virtual bool has_name() const { return !_name.empty(); } protected: string _name; public: void set_name(const string& name) { _name = name; } }; __ariel_end__ namespace std { template<> class hash<gs::ariel::font> #if defined(_MSC_VER) && (_MSC_VER < 1914) : public unary_function<gs::ariel::font, size_t> #endif { public: size_t operator()(const gs::ariel::font& ft) const { return ft.hash_value(); } }; }; #endif
{ "alphanum_fraction": 0.5555871481, "avg_line_length": 27.8023715415, "ext": "h", "hexsha": "f8ff71e746ee4da2514982be26ad4813039ce9d5", "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/type.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/type.h", "max_line_length": 131, "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/type.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": 1753, "size": 7034 }
#ifndef ___BEST_SCORE_SO_FAR_FOR_NLOPT_H____ #define ___BEST_SCORE_SO_FAR_FOR_NLOPT_H____ #include "OptimizedNonlinearController.h" #include <mutex> #include <nlopt.h> #include <thread> class BestNLOptScoreSoFar { public: std::mutex my_mutex; std::thread* thethread; bool force_stop; nlopt_opt opt; MyNLOPTdata my_nloptdata; int num_iterations_so_far; double* my_best_params; double my_best_score; double original_starting_score; int which_algorithm; BestNLOptScoreSoFar() : my_best_params(nullptr), thethread(nullptr), opt(nullptr), force_stop(false) {} BestNLOptScoreSoFar(const BestNLOptScoreSoFar & other) : my_nloptdata(other.my_nloptdata), thethread(other.thethread), my_best_params(other.my_best_params), force_stop(other.force_stop), opt(other.opt) {} void Reset() { num_iterations_so_far = 0; if(my_best_params != nullptr) {free(my_best_params); my_best_params = nullptr;} my_best_score = 1e12; original_starting_score = 1e12; which_algorithm = 0; force_stop = false; if(opt != nullptr) {nlopt_destroy(opt);} opt = nullptr; } }; #endif
{ "alphanum_fraction": 0.7703568161, "avg_line_length": 23.7608695652, "ext": "h", "hexsha": "dce27a03569e8f153f23a9b9778a38ad8a3e2b44", "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": "90577a4abb2215065845d0f878a85cc345b1ae98", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jasonbunk/InvertedPendulumVisualControl", "max_forks_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "90577a4abb2215065845d0f878a85cc345b1ae98", "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": "jasonbunk/InvertedPendulumVisualControl", "max_issues_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_line_length": 205, "max_stars_count": null, "max_stars_repo_head_hexsha": "90577a4abb2215065845d0f878a85cc345b1ae98", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jasonbunk/InvertedPendulumVisualControl", "max_stars_repo_path": "Source/NLControllerOptimization/BestNLOptScoreSoFar.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 304, "size": 1093 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cblas.h> #include "linear_algebra.h" Matrix *new_matrix(int row_num, int col_num) { Matrix *matrix = malloc(sizeof(Matrix)); if (matrix == NULL) return NULL; matrix->data = malloc((unsigned long) (row_num * col_num) * sizeof(double)); if (matrix->data == NULL) { perror("Error allocating memory for a matrix"); exit(EXIT_FAILURE); } matrix->row_num = row_num; matrix->col_num = col_num; return matrix; } Matrix *new_matrix_from_array(double *array, int row_num, int col_num) { Matrix *matrix = new_matrix(row_num, col_num); memcpy(matrix->data, array, (unsigned long)(row_num * col_num) * sizeof(double)); return matrix; } void free_matrix(Matrix *matrix) { free(matrix->data); free(matrix); } Matrix *add_matrices(Matrix *matrix1, Matrix *matrix2) { if (matrix1->row_num != matrix2->row_num || matrix1->col_num != matrix2->col_num) { perror("Dimensions of the two matrices do not match"); exit(EXIT_FAILURE); } Matrix *result_matrix = new_matrix(matrix1->row_num, matrix1->col_num); int i; int elements = matrix1->row_num * matrix1->col_num; for (i = 0; i < elements; i++) { result_matrix->data[i] = matrix1->data[i] + matrix2->data[i]; } return result_matrix; } Matrix *multiply_matrices(Matrix *matrix1, Matrix *matrix2) { if (matrix1->col_num != matrix2->row_num) { perror("Incompatible matrix dimensions"); exit(EXIT_FAILURE); } Matrix *product = new_matrix(matrix1->row_num, matrix2->col_num); int m = matrix1->row_num; int n = matrix2->col_num; int k = matrix1->col_num; // Use high-performace matrix multiplication from BLAS cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, matrix1->data, k, matrix2->data, n, 0, product->data, n); return product; } void multiply_vector_by_vector_transpose(Matrix *vector1, Matrix *vector2, double scalar, Matrix *matrix) { if (vector1->col_num != 1 || vector2->col_num != 1) { perror("Not a vector."); exit(EXIT_FAILURE); } int m = vector1->row_num; int n = vector2->row_num; cblas_dger(CblasRowMajor, m, n, scalar, vector1->data, 1, vector2->data, 1, matrix->data, n); } Matrix *multiply_matrix_with_vector(Matrix *matrix, Matrix *vector, double scalar) { if (matrix->col_num != vector->row_num) { perror("Incompatible matrix dimensions"); exit(EXIT_FAILURE); } if (vector->col_num != 1) { perror("Not a vector."); exit(EXIT_FAILURE); } Matrix *product = new_matrix(matrix->row_num, 1); int m = matrix->row_num; int n = matrix->col_num; cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, scalar, matrix->data, n, vector->data, 1, 0, product->data, 1); return product; } Matrix *multiply_upper_symmetric_matrix_with_vector(Matrix *matrix, Matrix *vector) { if (matrix->col_num != matrix->row_num) { perror("Matrix is not square"); exit(EXIT_FAILURE); } if (matrix->col_num != vector->row_num) { perror("Incompatible matrix dimensions"); exit(EXIT_FAILURE); } if (vector->col_num != 1) { perror("Not a vector."); exit(EXIT_FAILURE); } Matrix *product = new_matrix(matrix->row_num, 1); int n = matrix->col_num; cblas_dsymv(CblasRowMajor, CblasUpper, n, 1, matrix->data, n, vector->data, 1, 0, product->data, 1); return product; } void multiply_matrix_with_a_number(Matrix *matrix, double number) { int i; int n = matrix->col_num; int row_num = matrix->row_num; for (i = 0; i < row_num; i++) { cblas_dscal(n, number, matrix->data + i * n, 1); } } Matrix *transpose_matrix(Matrix *matrix) { Matrix *product = new_matrix(matrix->col_num, matrix->row_num); int i, j; for (i = 0; i < matrix->col_num; i++) { for (j = 0; j < matrix->row_num; j++) { product->data[i * matrix->row_num + j] = matrix->data[j * matrix->col_num + i]; } } return product; } double dot_product(Matrix *matrix1, Matrix *matrix2) { if (matrix1->row_num != matrix2->row_num || matrix1->col_num != 1 || matrix2->col_num != 1) { perror("Matrices are not n by 1."); exit(EXIT_FAILURE); } int i; double result = 0; for (i = 0; i < matrix1->row_num; i++) { result += matrix1->data[i] * matrix2->data[i]; } return result; } double norm(Matrix *matrix) { return sqrt(dot_product(matrix, matrix)); } Matrix *gramian(Matrix *matrix) { Matrix *product = new_matrix(matrix->col_num, matrix->col_num); int n = matrix->col_num; int k = matrix->row_num; cblas_dsyrk(CblasRowMajor, CblasUpper, CblasTrans, n, k, 1, matrix->data, n, 0, product->data, n); return product; }
{ "alphanum_fraction": 0.6141841169, "avg_line_length": 22.4977777778, "ext": "c", "hexsha": "df83902ae3bcf9350118f8af912bca78ecbd012c", "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": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "evgenyneu/image_compressor_c", "max_forks_repo_path": "src/linear_algebra.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "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": "evgenyneu/image_compressor_c", "max_issues_repo_path": "src/linear_algebra.c", "max_line_length": 105, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "evgenyneu/image_compressor_c", "max_stars_repo_path": "src/linear_algebra.c", "max_stars_repo_stars_event_max_datetime": "2019-11-20T07:33:22.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-20T07:33:22.000Z", "num_tokens": 1404, "size": 5062 }
/* vector/gsl_vector_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_FLOAT_H__ #define __GSL_VECTOR_FLOAT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_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_float *block; int owner; } gsl_vector_float; typedef struct { gsl_vector_float vector; } _gsl_vector_float_view; typedef _gsl_vector_float_view gsl_vector_float_view; typedef struct { gsl_vector_float vector; } _gsl_vector_float_const_view; typedef const _gsl_vector_float_const_view gsl_vector_float_const_view; /* Allocation */ GSL_FUN gsl_vector_float *gsl_vector_float_alloc (const size_t n); GSL_FUN gsl_vector_float *gsl_vector_float_calloc (const size_t n); GSL_FUN gsl_vector_float *gsl_vector_float_alloc_from_block (gsl_block_float * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_float *gsl_vector_float_alloc_from_vector (gsl_vector_float * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_float_free (gsl_vector_float * v); /* Views */ GSL_FUN _gsl_vector_float_view gsl_vector_float_view_array (float *v, size_t n); GSL_FUN _gsl_vector_float_view gsl_vector_float_view_array_with_stride (float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_float_const_view gsl_vector_float_const_view_array (const float *v, size_t n); GSL_FUN _gsl_vector_float_const_view gsl_vector_float_const_view_array_with_stride (const float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_float_view gsl_vector_float_subvector (gsl_vector_float *v, size_t i, size_t n); GSL_FUN _gsl_vector_float_view gsl_vector_float_subvector_with_stride (gsl_vector_float *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_float_const_view gsl_vector_float_const_subvector (const gsl_vector_float *v, size_t i, size_t n); GSL_FUN _gsl_vector_float_const_view gsl_vector_float_const_subvector_with_stride (const gsl_vector_float *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_FUN void gsl_vector_float_set_zero (gsl_vector_float * v); GSL_FUN void gsl_vector_float_set_all (gsl_vector_float * v, float x); GSL_FUN int gsl_vector_float_set_basis (gsl_vector_float * v, size_t i); GSL_FUN int gsl_vector_float_fread (FILE * stream, gsl_vector_float * v); GSL_FUN int gsl_vector_float_fwrite (FILE * stream, const gsl_vector_float * v); GSL_FUN int gsl_vector_float_fscanf (FILE * stream, gsl_vector_float * v); GSL_FUN int gsl_vector_float_fprintf (FILE * stream, const gsl_vector_float * v, const char *format); GSL_FUN int gsl_vector_float_memcpy (gsl_vector_float * dest, const gsl_vector_float * src); GSL_FUN int gsl_vector_float_reverse (gsl_vector_float * v); GSL_FUN int gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w); GSL_FUN int gsl_vector_float_swap_elements (gsl_vector_float * v, const size_t i, const size_t j); GSL_FUN float gsl_vector_float_max (const gsl_vector_float * v); GSL_FUN float gsl_vector_float_min (const gsl_vector_float * v); GSL_FUN void gsl_vector_float_minmax (const gsl_vector_float * v, float * min_out, float * max_out); GSL_FUN size_t gsl_vector_float_max_index (const gsl_vector_float * v); GSL_FUN size_t gsl_vector_float_min_index (const gsl_vector_float * v); GSL_FUN void gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax); GSL_FUN int gsl_vector_float_add (gsl_vector_float * a, const gsl_vector_float * b); GSL_FUN int gsl_vector_float_sub (gsl_vector_float * a, const gsl_vector_float * b); GSL_FUN int gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b); GSL_FUN int gsl_vector_float_div (gsl_vector_float * a, const gsl_vector_float * b); GSL_FUN int gsl_vector_float_scale (gsl_vector_float * a, const float x); GSL_FUN int gsl_vector_float_add_constant (gsl_vector_float * a, const double x); GSL_FUN int gsl_vector_float_axpby (const float alpha, const gsl_vector_float * x, const float beta, gsl_vector_float * y); GSL_FUN float gsl_vector_float_sum (const gsl_vector_float * a); GSL_FUN int gsl_vector_float_equal (const gsl_vector_float * u, const gsl_vector_float * v); GSL_FUN int gsl_vector_float_isnull (const gsl_vector_float * v); GSL_FUN int gsl_vector_float_ispos (const gsl_vector_float * v); GSL_FUN int gsl_vector_float_isneg (const gsl_vector_float * v); GSL_FUN int gsl_vector_float_isnonneg (const gsl_vector_float * v); GSL_FUN INLINE_DECL float gsl_vector_float_get (const gsl_vector_float * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x); GSL_FUN INLINE_DECL float * gsl_vector_float_ptr (gsl_vector_float * v, const size_t i); GSL_FUN INLINE_DECL const float * gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN float gsl_vector_float_get (const gsl_vector_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN float * gsl_vector_float_ptr (gsl_vector_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (float *) (v->data + i * v->stride); } INLINE_FUN const float * gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const float *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_FLOAT_H__ */
{ "alphanum_fraction": 0.690680527, "avg_line_length": 34.0452674897, "ext": "h", "hexsha": "fda772b4db0f4b886a877fc5c6c67b296d796bcc", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.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/gsl/gsl_vector_float.h", "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/gsl/gsl_vector_float.h", "max_line_length": 123, "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/gsl/gsl_vector_float.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 2003, "size": 8273 }
#ifndef structs_h #define structs_h #include <ceed.h> #include <petsc.h> // ----------------------------------------------------------------------------- // PETSc Operator Structs // ----------------------------------------------------------------------------- // Data for PETSc Matshell typedef struct UserO_ *UserO; struct UserO_ { MPI_Comm comm; DM dm; Vec X_loc, Y_loc, diag; CeedVector x_ceed, y_ceed; CeedOperator op; Ceed ceed; }; // Data for PETSc Prolong/Restrict Matshells typedef struct UserProlongRestr_ *UserProlongRestr; struct UserProlongRestr_ { MPI_Comm comm; DM dmc, dmf; Vec loc_vec_c, loc_vec_f, mult_vec; CeedVector ceed_vec_c, ceed_vec_f; CeedOperator op_prolong, op_restrict; Ceed ceed; }; // ----------------------------------------------------------------------------- // libCEED Data Structs // ----------------------------------------------------------------------------- // libCEED data struct for level typedef struct CeedData_ *CeedData; struct CeedData_ { Ceed ceed; CeedBasis basis_x, basis_u, basis_c_to_f; CeedElemRestriction elem_restr_x, elem_restr_u, elem_restr_u_i, elem_restr_qd_i; CeedQFunction qf_apply; CeedOperator op_apply, op_restrict, op_prolong; CeedVector q_data, x_ceed, y_ceed; }; // BP specific data typedef struct { CeedInt num_comp_x, num_comp_u, topo_dim, q_data_size, q_extra; CeedQFunctionUser setup_geo, setup_rhs, apply, error; const char *setup_geo_loc, *setup_rhs_loc, *apply_loc, *error_loc; CeedEvalMode in_mode, out_mode; CeedQuadMode q_mode; PetscBool enforce_bc; PetscErrorCode (*bc_func)(PetscInt, PetscReal, const PetscReal *, PetscInt, PetscScalar *, void *); } BPData; #endif // structs_h
{ "alphanum_fraction": 0.6095183486, "avg_line_length": 28.5901639344, "ext": "h", "hexsha": "63f0abc7d9cee1bc32d1156ac05b70d17bce3f40", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/petsc/include/structs.h", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/petsc/include/structs.h", "max_line_length": 82, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/petsc/include/structs.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 450, "size": 1744 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #define USAGE "./mcmc_loktavolterra.x n_steps n_burn" void rg4th(float *resultado, float x, float y, float a, float b, float c, float d, float h); void x_prime(float *valor, float x, float y, float alpha, float beta); void y_prime(float *valor, float x, float y, float gamma, float delta); void my_model(float *mine_presas,float *mine_depredadores,float *tiempo,float ini_presas, float ini_depredadores,float a, float b, float c, float d, int n_puntos); void likelihood(float *chi,float *presas,float *depredadores,float *mine_presas,float *mine_depredadores,int n_puntos); void mcmc(int n_steps,float *a,float *b,float *c,float *d,float *l,float *tiempo,float *presas,float *depredadores,int n_puntos,float *mine_presas,float *mine_depredadores, float ini_presas, float ini_depredadores); void min(float *mine_presas,float *mine_depredadores,float ini_presas,float ini_depredadores,float *tiempo,float *a,float *b,float *c,float *d,float *l,int n_steps,int n_puntos); void leer(float *tiempo, float *presas, float *depredadores, int n_puntos); float *reserva(int n_puntos); void print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn); int main(int argc, char **argv){ srand48(time(NULL)); //Valores que entran int n_steps=atof(argv[1]); int n_burn=atof(argv[2]); //Inicializacion de los arrays que guardan los datos int n_puntos= 96; float *tiempo; float *presas; float *depredadores; tiempo=reserva(n_puntos); presas=reserva(n_puntos); depredadores=reserva(n_puntos); leer(tiempo, presas, depredadores, n_puntos); //Condiciones iniciales para resolver las ecuaciones diferenciales float ini_presas, ini_depredadores; ini_presas=presas[0]; ini_depredadores=depredadores[0]; //Array con los resultados del ajuste float *mine_presas; mine_presas=reserva(n_puntos); float *mine_depredadores; mine_depredadores=reserva(n_puntos); //Arrays que guardan los datos de las variables float *a; //alpha float *b; //beta float *c; //gamma float *d; //delta float *l; a=reserva(n_steps); b=reserva(n_steps); c=reserva(n_steps); d=reserva(n_steps); l=reserva(n_steps); //Primer paso en la cadena a[0]=drand48(); b[0]=drand48(); c[0]=drand48(); d[0]=drand48(); float chi; my_model(mine_presas,mine_depredadores,tiempo,ini_presas,ini_depredadores,a[0],b[0],c[0],d[0],n_puntos); likelihood(&chi,presas,depredadores,mine_presas,mine_depredadores,n_puntos); l[0]=chi; mcmc(n_steps,a,b,c,d,l,tiempo,presas,depredadores,n_puntos,mine_presas,mine_depredadores,ini_presas,ini_depredadores); min(mine_presas,mine_depredadores,ini_presas,ini_depredadores,tiempo,a,b,c,d,l,n_steps,n_puntos); print_array(a,b,c,d,l,n_steps,n_burn); free(tiempo); free(presas); free(mine_presas); free(depredadores); free(mine_depredadores); free(a); free(b); free(c); free(d); return 0; } //OBTENCION DEL MEJOR AJUSTE void min(float *mine_presas,float *mine_depredadores,float ini_presas,float ini_depredadores,float *tiempo,float *a,float *b,float *c,float *d,float *l,int n_steps,int n_puntos){ int i; float temp, a2, b2, c2, d2; temp=l[0]; a2=a[0]; b2=b[0]; c2=c[0]; d2=d[0]; for(i=1;i<n_steps;i++){ if(temp > l[i] ){ temp=l[i]; a2=a[i]; b2=b[i]; c2=c[i]; d2=d[i]; } } my_model(mine_presas,mine_depredadores,tiempo,ini_presas,ini_depredadores,a2,b2,c2,d2,n_puntos); } //ITERACIONES void mcmc(int n_steps,float *a,float *b,float *c,float *d,float *l,float *tiempo,float *presas,float *depredadores,int n_puntos,float *mine_presas,float *mine_depredadores, float ini_presas, float ini_depredadores){ int i; float a2,b2,c2,d2,chi,chi2,alpha,beta; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for(i=0;i<(n_steps-1);i++){ a2 = a[i] + gsl_ran_gaussian(r, 0.1); b2 = b[i] + gsl_ran_gaussian(r, 0.1); c2 = c[i] + gsl_ran_gaussian(r, 0.1); d2 = c[i] + gsl_ran_gaussian(r, 0.1); float *presas_init; float *presas_prime; presas_init=reserva(n_puntos); presas_prime=reserva(n_puntos); float *depredadores_init; float *depredadores_prime; depredadores_init=reserva(n_puntos); depredadores_prime=reserva(n_puntos); my_model(presas_init,depredadores_init,tiempo,ini_presas,ini_depredadores,a[i],b[i],c[i],d[i],n_puntos); likelihood(&chi,presas,depredadores,presas_init,depredadores_init,n_puntos); my_model(presas_prime,depredadores_prime,tiempo,ini_presas,ini_depredadores,a2,b2,c2,d2,n_puntos); likelihood(&chi2,presas,depredadores,presas_prime,depredadores_prime,n_puntos); alpha = -chi2 + chi; if(alpha >= 0.0){ a[i+1]=a2; b[i+1]=b2; c[i+1]=c2; d[i+1]=d2; l[i+1]=chi2; } else{ beta = drand48(); if(alpha < -6000.0 ){ a[i+1]=a[i]; b[i+1]=b[i]; c[i+1]=c[i]; d[i+1]=d[i]; l[i+1]=chi; } else if(beta <= exp(alpha)){ a[i+1]=a2; b[i+1]=b2; c[i+1]=c2; d[i+1]=d2; l[i+1]=chi2; } else{ a[i+1]=a[i]; b[i+1]=b[i]; c[i+1]=c[i]; d[i+1]=d[i]; l[i+1]=chi; } } free(presas_init); free(presas_prime); free(depredadores_init); free(depredadores_prime); } gsl_rng_free (r); } //IMPRESION DE LOS ARRAYS void print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn){ int i; for(i=n_burn;i<n_steps;i++){ printf("%f %f %f %f %f\n", a[i], b[i], c[i] , d[i], l[i]); } } //DEFINICION DEL CALCULO DEL AJUSTE void my_model(float *mine_presas,float *mine_depredadores,float *tiempo,float ini_presas, float ini_depredadores,float a, float b, float c, float d, int n_puntos){ //Condiciones iniciales mine_presas[0] = ini_presas; mine_depredadores[0] = ini_depredadores; //Recorrido R-K int i; for(i=1;i<n_puntos;i++){ float *r; float h; h = tiempo[i]-tiempo[i-1]; r=reserva(2); rg4th(r, mine_presas[i-1], mine_depredadores[i-1], a, b, c, d, h); mine_presas[i]=r[0]; mine_depredadores[i]=r[1]; free(r); } } //RUNGE-KUTTA DE CUARTO ORDEN void rg4th(float *resultado, float x, float y, float a, float b, float c, float d, float h){ float k1_x,k1_y; x_prime(&k1_x,x,y,a,b); y_prime(&k1_y,x,y,c,d); //First step float x1,y1; x1 = x + (h/2.0) * k1_x; y1 = y + (h/2.0) * k1_y; float k2_x,k2_y; x_prime(&k2_x,x1,y1,a,b); y_prime(&k2_y,x1,y1,c,d); //Second step float x2,y2; x2 = x + (h/2.0) * k2_x; y2 = y + (h/2.0) * k2_y; float k3_x,k3_y; x_prime(&k3_x,x2,y2,a,b); y_prime(&k3_y,x2,y2,c,d); //Third step float x3,y3; x3 = x + h * k3_x; y3 = y + h * k3_y; float k4_x,k4_y; x_prime(&k4_x,x3,y3,a,b); y_prime(&k4_y,x3,y3,c,d); //Fourth step float average_x, average_y; average_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x); average_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y); resultado[0] = x + h * average_x; resultado[1] = y + h * average_y; } //ECUACION DIFERENCIAL DE PRESAS void x_prime(float *valor, float x, float y, float alpha, float beta){ *valor= x * (alpha - beta * y); } //ECUACION DIFERENCIAL DE DEPREDADORES void y_prime(float *valor, float x, float y, float gamma, float delta){ *valor = -1 * y * (gamma - delta * x); } //RESERVA DEL AJUSTE float *reserva(int n_puntos){ float *array; int i; if(!(array = malloc(n_puntos * sizeof(float)))){ printf("Problema en reserva\n"); exit(1); } for(i=0;i<n_puntos;i++){ array[i] = 0.0; } return array; } //CALCULO DE LA VARIACION DEL AJUSTE void likelihood(float *chi,float *presas,float *depredadores,float *mine_presas,float *mine_depredadores,int n_puntos){ int i; float temp1=0; float temp2=0; for(i=0;i<n_puntos;i++){ temp1=temp1+pow(presas[i]-mine_presas[i],2.0); temp2=temp2+pow(depredadores[i]-mine_depredadores[i],2.0); } *chi=(1.0/2.0)*(temp1+temp2); } //LECTURA DEL ARCHIVO void leer(float *tiempo, float *presas, float *depredadores,int n_puntos){ FILE *in; int i; in=fopen("archivo.dat","r"); if(!in){ printf("problems opening the file %s\n","archivo.dat"); exit(1); } for(i=0;i<(n_puntos);i++){ fscanf(in, "%f %f %f\n", &tiempo[i], &presas[i], &depredadores[i]); } fclose(in); }
{ "alphanum_fraction": 0.6708542714, "avg_line_length": 26.9612903226, "ext": "c", "hexsha": "d1ffddd5ab94478ca467974f14dd28a71349f411", "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": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BarreraMonica/HW7_MC", "max_forks_repo_path": "poblaciones/poblaciones.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "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": "BarreraMonica/HW7_MC", "max_issues_repo_path": "poblaciones/poblaciones.c", "max_line_length": 215, "max_stars_count": null, "max_stars_repo_head_hexsha": "307b86e4e85d4c25edc3346a5ce8a23eafbe4e87", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BarreraMonica/HW7_MC", "max_stars_repo_path": "poblaciones/poblaciones.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2970, "size": 8358 }
#include "als.h" #include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #define MAX_NAME_LEN 10 /* Define global variables */ global_info info; feature_t *movieMatrix; // feature matrix of movies feature_t *userMatrix; // feature matrix of users // store rating matrix in a compressed way int userNum; int movieNum; int ratingNum; int* userStartIdx; int* movieId; double* movieRating; int* movieStartIdx; int* userId; double* userRating; struct movie* movie_hashtable; // to record the number of rating for each movie struct user* user_hashtable; // to record the number of rating for each user void computePredictionRMSE(gsl_matrix * M, gsl_matrix * U, gsl_matrix * R); //--------------------------------------------- //------- helper function for hashtable-------- //--------------------------------------------- void add_movie(int id, double rating) { struct movie* res; HASH_FIND_INT(movie_hashtable, &id, res); if (res == NULL) { struct movie* new_movie = (struct movie*)malloc(sizeof(struct movie)); new_movie -> id = id; new_movie -> rating_num = 1; new_movie -> num = 1; new_movie -> total_rating = rating; HASH_ADD_INT(movie_hashtable, id, new_movie); } else { res -> rating_num ++; res -> num ++; res -> total_rating += rating; } } void delete_movie(int id) { struct movie* res; HASH_FIND_INT(movie_hashtable, &id, res); res -> rating_num --; } int find_movie(int id) { struct movie *result; HASH_FIND_INT(movie_hashtable, &id, result); if (result == NULL) { return 0; } else { return result -> rating_num; } } double get_movie_average(int id) { struct movie *result; HASH_FIND_INT(movie_hashtable, &id, result); if (result == NULL) { return 0; } else { return result -> total_rating / ((double)result -> num); } } void add_user(int id) { struct user* res; HASH_FIND_INT(user_hashtable, &id, res); if (res == NULL) { struct user* new_user = (struct user*)malloc(sizeof(struct user)); new_user -> id = id; new_user -> rating_num = 1; HASH_ADD_INT(user_hashtable, id, new_user); } else { res -> rating_num ++; } } void delete_user(int id) { struct user* res; HASH_FIND_INT(user_hashtable, &id, res); res -> rating_num --; } int find_user(int id) { struct user *result; HASH_FIND_INT(user_hashtable, &id, result); if (result == NULL) { return 0; } else { return result -> rating_num; } } //------------------------------------------------ //-----------process input data------------------- //------------------------------------------------ /* * get the input relevant stat */ void getInputStat(char* inputFilename) { userNum = 0; movieNum = 0; ratingNum = 0; FILE* fp = fopen(inputFilename, "r"); if (fp == NULL) { fprintf(stderr, "Failed to read input file %s\n", inputFilename); exit(-1); } ssize_t read; size_t len = 0; char* line = NULL; int uid = 0; int mid = 0; double rating = 0; if ((read = getline(&line, &len, fp)) != -1) { printf("Start reading file, get input stat\n"); } while ((read = getline(&line, &len, fp)) != -1) { ratingNum++; // split the data line with comma char* tmp = line; char* last_pos = line; int word_len = 0; int comma_cnt = 0; while (comma_cnt < 3) { if (*tmp == ',') { word_len = tmp - last_pos; char tmpbuf[MAX_NAME_LEN] = ""; strncpy(tmpbuf, last_pos, word_len); if (comma_cnt == 0) { uid = atoi(tmpbuf); } else if (comma_cnt == 1) { mid = atoi(tmpbuf); } else { rating = atof(tmpbuf); } comma_cnt++; last_pos = tmp + 1; } tmp++; } add_movie(mid, rating); // keep record of rating number for each movie add_user(uid); // keep record of rating number of each user userNum = max(userNum, uid); movieNum = max(movieNum, mid); } printf("There are %d ratings, %d users, %d movies\n", ratingNum, userNum, movieNum); } void initUserStartIndex() { int i; int sum = 0; for (i = 1; i <= userNum; ++i) { int user_rating = find_user(i); userStartIdx[i - 1] = sum; sum += user_rating; } userStartIdx[userNum] = ratingNum; } void initMovieStartIndex() { int i; int sum = 0; for (i = 1; i <= movieNum; ++i) { int movie_rating = find_movie(i); movieStartIdx[i - 1] = sum; sum += movie_rating; } movieStartIdx[movieNum] = ratingNum; } void initRatingMatrix(int uid, int mid, double rating) { int movieIdx = movieStartIdx[mid] - find_movie(mid); int userIdx = userStartIdx[uid] - find_user(uid); userId[movieIdx] = uid; userRating[movieIdx] = rating; movieId[userIdx] = mid; movieRating[userIdx] = rating; delete_movie(mid); delete_user(uid); } void initMatrix() { printf("Init movie matrix\n"); int i, j; for (i = 0; i < movieNum; ++i) { int start_idx = i * info.numFeatures; movieMatrix[start_idx] = get_movie_average(i + 1); // initialize the random small value for (j = 1; j < info.numFeatures; ++j) { movieMatrix[start_idx + j] = (rand() % 1000) / 1000.0; } } } // read input file // initializa the rating matrix & movie matrix void readInput(char* inputFilename) { FILE* fp = fopen(inputFilename, "r"); if (fp == NULL) { fprintf(stderr, "Failed to read input file %s\n", inputFilename); exit(-1); } ssize_t read; size_t len = 0; char* line = NULL; int uid = 0; int mid = 0; double rating = 0; if ((read = getline(&line, &len, fp)) != -1) { printf("Start reading file, get rating details\n"); } while ((read = getline(&line, &len, fp)) != -1) { // split the data line with comma char* tmp = line; char* last_pos = line; int word_len = 0; int comma_cnt = 0; while (comma_cnt < 3) { if (*tmp == ',') { word_len = tmp - last_pos; char tmpbuf[MAX_NAME_LEN] = ""; strncpy(tmpbuf, last_pos, word_len); if (comma_cnt == 0) { uid = atoi(tmpbuf); } else if (comma_cnt == 1) { mid = atoi(tmpbuf); } else { rating = atof(tmpbuf); } comma_cnt++; last_pos = tmp + 1; } tmp++; } // initialize the rating matrix (use compression) initRatingMatrix(uid, mid, rating); } } // init basic arg void init(int numFeatures, int numIter, double lambda) { info.numIter = numIter; info.numFeatures = numFeatures; info.lambda = lambda; } /* * allocate data structure memory */ void init_data(int userNum, int movieNum, int ratingNum, int nproc) { printf("allocating data memory\n"); int movieSpan = (movieNum + nproc - 1) / nproc; int userSpan = (userNum + nproc - 1) / nproc; userStartIdx = (int*)calloc(userNum + 1, sizeof(int)); movieId = (int*)calloc(ratingNum + 1, sizeof(int)); movieRating = (double*)calloc(ratingNum + 1, sizeof(double)); movieStartIdx = (int*)calloc(movieNum + 1, sizeof(int)); userId = (int*)calloc(ratingNum + 1, sizeof(int)); userRating = (double*)calloc(ratingNum + 1, sizeof(double)); movieMatrix = (feature_t *)calloc(info.numFeatures * movieSpan * nproc, sizeof(feature_t)); userMatrix = (feature_t *)calloc(info.numFeatures * userSpan * nproc, sizeof(feature_t)); } //----------------------------------------------------------------- //---------------------real computation---------------------------- //----------------------------------------------------------------- void compute(int procID, int nproc, char* inputFilename, int numFeatures, int numIterations, double lambda) { const int root = 0; // set the rank 0 processor as the root int span; // initialize init(numFeatures, numIterations, lambda); /* Read the input file and initialization */ if (procID == root) { getInputStat(inputFilename); } /* broadcast the information of basic stat*/ MPI_Bcast(&userNum, 1, MPI_INT, root, MPI_COMM_WORLD); MPI_Bcast(&movieNum, 1, MPI_INT, root, MPI_COMM_WORLD); MPI_Bcast(&ratingNum, 1, MPI_INT, root, MPI_COMM_WORLD); // initialize the data structure init_data(userNum, movieNum, ratingNum, nproc); if (procID == root) { initUserStartIndex(); initMovieStartIndex(); } /* broadcast the information about start index */ MPI_Bcast(userStartIdx, userNum + 1, MPI_INT, root, MPI_COMM_WORLD); MPI_Bcast(movieStartIdx, movieNum + 1, MPI_INT, root, MPI_COMM_WORLD); /* Read the input file and get detailed rating */ if (procID == root) { readInput(inputFilename); } MPI_Bcast(movieId, ratingNum + 1, MPI_INT, root, MPI_COMM_WORLD); MPI_Bcast(movieRating, ratingNum + 1, MPI_DOUBLE, root, MPI_COMM_WORLD); MPI_Bcast(userId, ratingNum + 1, MPI_INT, root, MPI_COMM_WORLD); MPI_Bcast(userRating, ratingNum + 1, MPI_DOUBLE, root, MPI_COMM_WORLD); // initialize movie/ user matrix if (procID == root) { initMatrix(); } MPI_Bcast(movieMatrix, numFeatures * movieNum, MPI_DOUBLE, root, MPI_COMM_WORLD); // initialize n_user and n_movie int* n_user = (int *)malloc(sizeof(int) * userNum); int* n_movie = (int *)malloc(sizeof(int) * movieNum); int i, j; for (i = 0; i < userNum; ++i) { n_user[i] = userStartIdx[i+1] - userStartIdx[i]; } for (i = 0; i < movieNum; ++i) { n_movie[i] = movieStartIdx[i+1] - movieStartIdx[i]; } // create gsl objects gsl_matrix * M = gsl_matrix_alloc (numFeatures, movieNum); gsl_matrix * U = gsl_matrix_alloc (numFeatures, userNum); gsl_matrix * R = gsl_matrix_alloc (userNum, movieNum); gsl_matrix * A = gsl_matrix_alloc (numFeatures, numFeatures); gsl_matrix * Ainv = gsl_matrix_alloc (numFeatures, numFeatures); gsl_matrix * E = gsl_matrix_alloc (numFeatures, numFeatures); for (i = 0; i < numFeatures; ++i) gsl_matrix_set(E, i, i, 1); gsl_matrix * F = gsl_matrix_alloc (numFeatures, numFeatures); gsl_vector * V = gsl_vector_alloc (numFeatures); gsl_vector * Rm = gsl_vector_alloc (movieNum); gsl_vector * Ru = gsl_vector_alloc (userNum); gsl_permutation *p = gsl_permutation_alloc(numFeatures); gsl_vector * O = gsl_vector_alloc (numFeatures); /* Start */ // start iteration if (procID == root) { printf("Start iteration\n"); computePredictionRMSE(M, U, R); } int iter = 0; for (iter = 0; iter < numIterations; ++iter) { // Each processor solve user feature if (procID == root) { printf("Updating user (iter = %d)\n", iter); } int user_idx; int user_num = 0; // check span // NOTE THE NUMBER SHOULD BE DIVISIBLE span = (userNum + nproc - 1) / nproc; int user_start_idx = min(procID * span, userNum); int user_end_idx = min(user_start_idx + span, userNum); for (user_idx = user_start_idx; user_idx < user_end_idx; ++user_idx) { user_num++; gsl_matrix_set_zero (M); for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i) for (j = 0; j < numFeatures; ++j) gsl_matrix_set(M, j, i - userStartIdx[user_idx], movieMatrix[(movieId[i]-1) * numFeatures + j]); gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1, M, M, 0, A); gsl_matrix_memcpy(F, E); gsl_matrix_scale(F, lambda * n_user[user_idx]); gsl_matrix_add(A, F); // A = M M^T + lambda * n * E gsl_vector_set_zero (Rm); for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i) gsl_vector_set(Rm, i - userStartIdx[user_idx], movieRating[i]); gsl_blas_dgemv(CblasNoTrans, 1, M, Rm, 0, V); // V = M R^T int s; gsl_linalg_LU_decomp(A, p, &s); gsl_linalg_LU_invert(A, p, Ainv); gsl_blas_dgemv(CblasNoTrans, 1, Ainv, V, 0, O); // O = A^-1 V for (j = 0; j < numFeatures; ++j) userMatrix[user_idx * numFeatures + j] = gsl_vector_get(O, j); } // allgather (everyone gets a local copy of U) MPI_Allgather(&userMatrix[user_start_idx * numFeatures], span * numFeatures, MPI_DOUBLE, userMatrix, span * numFeatures, MPI_DOUBLE, MPI_COMM_WORLD); // solver movie feature matrix if (procID == root) { printf("Updating movie (iter = %d)\n", iter); } int movie_idx; int movie_num = 0; span = (movieNum + nproc - 1) / nproc; int movie_start_idx = min(procID * span, movieNum); int movie_end_idx = min(movie_start_idx + span, movieNum); for (movie_idx = movie_start_idx; movie_idx < movie_end_idx; ++movie_idx) { if (movieStartIdx[movie_idx] == movieStartIdx[movie_idx+1]) continue; movie_num++; gsl_matrix_set_zero (U); for (i = movieStartIdx[movie_idx]; i < movieStartIdx[movie_idx+1]; ++i) for (j = 0; j < numFeatures; ++j) gsl_matrix_set(U, j, i - movieStartIdx[movie_idx], userMatrix[(userId[i]-1) * numFeatures + j]); gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1, U, U, 0, A); gsl_matrix_memcpy(F, E); gsl_matrix_scale(F, lambda * n_movie[movie_idx]); gsl_matrix_add(A, F); // A = U U^T + lambda * n * E gsl_vector_set_zero (Ru); for (i = movieStartIdx[movie_idx]; i < movieStartIdx[movie_idx+1]; ++i) gsl_vector_set(Ru, i - movieStartIdx[movie_idx], userRating[i]); gsl_blas_dgemv(CblasNoTrans, 1, U, Ru, 0, V); // V = U R^T int s; gsl_linalg_LU_decomp(A, p, &s); gsl_linalg_LU_invert(A, p, Ainv); gsl_blas_dgemv(CblasNoTrans, 1, Ainv, V, 0, O); // O = A^-1 V for (j = 0; j < numFeatures; ++j) movieMatrix[movie_idx * numFeatures + j] = gsl_vector_get(O, j); } // allgather (everyone gets a local copy of M) MPI_Allgather(&movieMatrix[movie_start_idx * numFeatures], span * numFeatures, MPI_DOUBLE, movieMatrix, span * numFeatures, MPI_DOUBLE, MPI_COMM_WORLD); // compute prediction and rmse if (procID == root) { computePredictionRMSE(M, U, R); } } gsl_matrix_free (M); gsl_matrix_free (U); gsl_matrix_free (R); gsl_matrix_free (A); gsl_matrix_free (Ainv); gsl_matrix_free (E); gsl_matrix_free (F); gsl_vector_free (V); gsl_vector_free (Rm); gsl_vector_free (Ru); gsl_vector_free (O); gsl_permutation_free (p); free(n_user); free(n_movie); free(userStartIdx); free(movieId); free(movieRating); free(movieStartIdx); free(userId); free(userRating); free(movieMatrix); free(userMatrix); } void computePredictionRMSE(gsl_matrix * M, gsl_matrix * U, gsl_matrix * R) { int i, j, user_idx; for (i = 0; i < movieNum; ++i) for (j = 0; j < info.numFeatures; ++j) gsl_matrix_set(M, j, i, movieMatrix[i * info.numFeatures + j]); for (i = 0; i < userNum; ++i) for (j = 0; j < info.numFeatures; ++j) gsl_matrix_set(U, j, i, userMatrix[i * info.numFeatures + j]); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1, U, M, 0, R); double rmse = 0; for (user_idx = 0; user_idx < userNum; ++user_idx) for (i = userStartIdx[user_idx]; i < userStartIdx[user_idx+1]; ++i) { double diff = movieRating[i] - gsl_matrix_get(R, user_idx, movieId[i] - 1); rmse += diff * diff; } printf("RMSE = %f\n", rmse / ratingNum); }
{ "alphanum_fraction": 0.5623245535, "avg_line_length": 30.7211009174, "ext": "c", "hexsha": "5df898862d244c0700b19b9b40eec0683012cd2c", "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": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zheweis/15618-Project", "max_forks_repo_path": "als/als.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "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": "zheweis/15618-Project", "max_issues_repo_path": "als/als.c", "max_line_length": 116, "max_stars_count": 1, "max_stars_repo_head_hexsha": "64bf98fcdfc8cc1fed510f3c0d62c0204093f603", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zheweis/15618-Project", "max_stars_repo_path": "als/als.c", "max_stars_repo_stars_event_max_datetime": "2020-12-06T17:12:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-06T17:12:01.000Z", "num_tokens": 4441, "size": 16743 }
#pragma once #include <memory_resource> #include <vector> #include <gsl-lite/gsl-lite.hpp> #include <thrust/sort.h> #include <cuda/define_specifiers.hpp> #include <thrustshift/memory-resource.h> namespace thrustshift { //! Col indices must be ordered template <typename DataType, typename IndexType> class CSR { public: using value_type = DataType; using index_type = IndexType; private: bool cols_are_sorted() { for (size_t row_id = 0; row_id < this->num_rows(); ++row_id) { if (!std::is_sorted(col_indices_.begin() + row_ptrs_[row_id], col_indices_.begin() + row_ptrs_[row_id + 1])) { return false; } } return true; } public: CSR() : row_ptrs_(1, 0, &pmr::default_resource), num_cols_(0) { } template <class DataRange, class ColIndRange, class RowPtrsRange, class MemoryResource> CSR(DataRange&& values, ColIndRange&& col_indices, RowPtrsRange&& row_ptrs, size_t num_cols, MemoryResource& memory_resource) : values_(values.begin(), values.end(), &memory_resource), col_indices_(col_indices.begin(), col_indices.end(), &memory_resource), row_ptrs_(row_ptrs.begin(), row_ptrs.end(), &memory_resource), num_cols_(num_cols) { gsl_Expects(values.size() == col_indices.size()); gsl_Expects(row_ptrs.size() > 0); gsl_Expects(row_ptrs[0] == 0); gsl_ExpectsAudit(cols_are_sorted()); } template <class DataRange, class ColIndRange, class RowPtrsRange> CSR(DataRange&& values, ColIndRange&& col_indices, RowPtrsRange&& row_ptrs, size_t num_cols) : CSR(std::forward<DataRange>(values), std::forward<ColIndRange>(col_indices), std::forward<RowPtrsRange>(row_ptrs), num_cols, pmr::default_resource) { } // The copy constructor is declared explicitly to ensure // managed memory is used per default. CSR(const CSR& other) : CSR(other.values(), other.col_indices(), other.row_ptrs(), other.num_cols()) { } CSR(CSR&& other) = default; CSR& operator=(const CSR& other) = default; gsl_lite::span<DataType> values() { return gsl_lite::make_span(values_); } gsl_lite::span<const DataType> values() const { return gsl_lite::make_span(values_); } gsl_lite::span<IndexType> col_indices() { return gsl_lite::make_span(col_indices_); } gsl_lite::span<const IndexType> col_indices() const { return gsl_lite::make_span(col_indices_); } gsl_lite::span<IndexType> row_ptrs() { return gsl_lite::make_span(row_ptrs_); } gsl_lite::span<const IndexType> row_ptrs() const { return gsl_lite::make_span(row_ptrs_); } size_t num_rows() const { return row_ptrs_.size() - 1; } size_t num_cols() const { return num_cols_; } void sort_column_indices() { for (size_t row_id = 0; row_id < num_rows(); ++row_id) { const auto nns_start = row_ptrs_[row_id]; const auto nns_end = row_ptrs_[row_id + 1]; thrust::sort_by_key(thrust::host, col_indices_.begin() + nns_start, col_indices_.begin() + nns_end, values_.begin() + nns_start); } } /*! \brief Add additional elements to each row of the matrix. * * A row might already have the maximum number of element. Therefore * not every row might be extended by exactly `num_max_additional_elements_per_row`. * */ void extend_rows(int num_max_additional_elements_per_row, DataType value = 0) { if (num_max_additional_elements_per_row == 0) { return; } gsl_Expects(num_max_additional_elements_per_row >= 0); std::vector<DataType> tmp_values(values_.begin(), values_.end()); std::vector<IndexType> tmp_col_indices(col_indices_.begin(), col_indices_.end()); size_t num_additional_elements = 0; const int nc = gsl_lite::narrow<int>(num_cols()); auto get_num_additional_elements_per_row = [&](size_t row_id) { const int num_elements_curr_row = row_ptrs_[row_id + 1] - row_ptrs_[row_id]; return std::max(std::min(num_max_additional_elements_per_row, nc - num_elements_curr_row), 0); }; for (size_t row_id = 0; row_id < num_rows(); ++row_id) { num_additional_elements += get_num_additional_elements_per_row(row_id); } const size_t new_nnz = values_.size() + num_additional_elements; values_.resize(new_nnz); col_indices_.resize(new_nnz); int nns_offset = 0; for (size_t row_id = 0; row_id < num_rows(); ++row_id) { const int num_additional_elements_curr_row = get_num_additional_elements_per_row(row_id); int nns_id = row_ptrs_[row_id]; const int nns_end = row_ptrs_[row_id + 1]; const int nnz_curr_row = nns_end - nns_id; int curr_col_id = 0; int num_added_elements = 0; for (int new_nns_id = nns_offset; new_nns_id < nns_offset + num_additional_elements_curr_row + row_ptrs_[row_id + 1] - row_ptrs_[row_id]; ++new_nns_id) { const int other_col_id = nns_id == nns_end ? std::numeric_limits<int>::max() : tmp_col_indices[nns_id]; if (curr_col_id < other_col_id && num_added_elements < num_additional_elements_curr_row) { values_[new_nns_id] = value; col_indices_[new_nns_id] = curr_col_id; ++curr_col_id; ++num_added_elements; } else { values_[new_nns_id] = tmp_values[nns_id]; col_indices_[new_nns_id] = other_col_id; curr_col_id = other_col_id + 1; ++nns_id; } } row_ptrs_[row_id] = nns_offset; nns_offset += nnz_curr_row + num_additional_elements_curr_row; } row_ptrs_.back() = values_.size(); gsl_ExpectsAudit(std::is_sorted(row_ptrs_.begin(), row_ptrs_.end())); gsl_ExpectsAudit(cols_are_sorted()); } private: std::pmr::vector<DataType> values_; std::pmr::vector<IndexType> col_indices_; std::pmr::vector<IndexType> row_ptrs_; size_t num_cols_; }; template <typename DataType, typename IndexType> bool operator==(const CSR<DataType, IndexType>& a, const CSR<DataType, IndexType>& b) { return equal(a.values(), b.values()) && equal(a.col_indices(), b.col_indices()) && equal(a.row_ptrs(), b.row_ptrs()) && a.num_rows() == b.num_rows() && a.num_cols() == b.num_cols(); } template <typename DataType, typename IndexType> class CSR_view { public: using value_type = DataType; using index_type = IndexType; template <typename OtherDataType, typename OtherIndexType> CSR_view(CSR<OtherDataType, OtherIndexType>& owner) : values_(owner.values()), col_indices_(owner.col_indices()), row_ptrs_(owner.row_ptrs()), num_cols_(owner.num_cols()) { } template <typename OtherDataType, typename OtherIndexType> CSR_view(const CSR<OtherDataType, OtherIndexType>& owner) : values_(owner.values()), col_indices_(owner.col_indices()), row_ptrs_(owner.row_ptrs()), num_cols_(owner.num_cols()) { } template <class DataRange, class ColIndRange, class RowPtrsRange> CSR_view(DataRange&& values, ColIndRange&& col_indices, RowPtrsRange&& row_ptrs, size_t num_cols) : values_(values), col_indices_(col_indices), row_ptrs_(row_ptrs), num_cols_(num_cols) { gsl_Expects(values.size() == col_indices.size()); gsl_Expects(row_ptrs.size() > 0); gsl_ExpectsAudit(row_ptrs[0] == 0); gsl_ExpectsAudit(row_ptrs.back() == values.size()); gsl_ExpectsAudit(std::is_sorted(row_ptrs.begin(), row_ptrs.end())); } CSR_view(const CSR_view& other) = default; CSR_view(CSR_view&& other) = default; CUDA_FHD gsl_lite::span<DataType> values() { return values_; } CUDA_FHD gsl_lite::span<const DataType> values() const { return values_; } CUDA_FHD gsl_lite::span<IndexType> col_indices() { return col_indices_; } CUDA_FHD gsl_lite::span<const IndexType> col_indices() const { return col_indices_; } CUDA_FHD gsl_lite::span<IndexType> row_ptrs() { return row_ptrs_; } CUDA_FHD gsl_lite::span<const IndexType> row_ptrs() const { return row_ptrs_; } CUDA_FHD size_t num_rows() const { return row_ptrs_.size() - 1; } CUDA_FHD size_t num_cols() const { return num_cols_; } CUDA_FHD auto max_row_nnz() const { using I = typename std::remove_const<IndexType>::type; I mnnz = 0; for (size_t row_id = 1; row_id < row_ptrs_.size(); ++row_id) { mnnz = std::max(row_ptrs_[row_id] - row_ptrs_[row_id - 1], mnnz); } return mnnz; } private: gsl_lite::span<DataType> values_; gsl_lite::span<IndexType> col_indices_; gsl_lite::span<IndexType> row_ptrs_; size_t num_cols_; }; } // namespace thrustshift
{ "alphanum_fraction": 0.6658738249, "avg_line_length": 28.8529411765, "ext": "h", "hexsha": "d064a6bb6693c859824ce85278b722782f1ea793", "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": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_path": "include/thrustshift/CSR.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "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": "codecircuit/thrustshift", "max_issues_repo_path": "include/thrustshift/CSR.h", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_path": "include/thrustshift/CSR.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": 2337, "size": 8829 }
#ifndef _H_LIMBER #define _H_LIMBER #include <gsl/gsl_spline.h> #include <stdbool.h> #include "interp2d.h" //#include <gsl/gsl_interp2d.h> //#include <gsl/gsl_spline2d.h> // The integrated C_ell are in general allowed to be zero or negative if // they describe cross-correlations. We use these statuses to describe // errors where a log was requested also. // LIMBER_STATUS_NEGATIVE is probably always an error // but LIMBER_STATUS_ZERO is not necessarily #define LIMBER_STATUS_OK 0 #define LIMBER_STATUS_ZERO 1 #define LIMBER_STATUS_NEGATIVE 2 #define LIMBER_STATUS_ERROR 3 // These are the options you can set for // the Limber integrator. typedef struct limber_config{ bool xlog; // The output spline will be in terms of log(ell) not ell bool ylog; int n_ell; // Number of ell values you want in the spline double * ell; // The chosen ell values you want double prefactor; //Scaling prefactor int status; // did everything go okay? double absolute_tolerance; double relative_tolerance; } limber_config; gsl_spline * limber_integral(limber_config * config, gsl_spline * WbX, gsl_spline * WfX, gsl_spline * WmX, gsl_spline * WbY, gsl_spline * WfY, gsl_spline * WmY, Interpolator2D * P, Interpolator2D * f, Interpolator2D * D, Interpolator2D * BB); #endif
{ "alphanum_fraction": 0.7595330739, "avg_line_length": 33.8157894737, "ext": "h", "hexsha": "a8c6c5c332197f0fcf4490dc8c0d035b3c2b983a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/limber.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/limber.h", "max_line_length": 190, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/limber.h", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 370, "size": 1285 }
//! \file reaction.h //! Data for an incident neutron reaction #ifndef OPENMC_REACTION_H #define OPENMC_REACTION_H #include <string> #include <gsl/gsl> #include "hdf5.h" #include "openmc/reaction_product.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Data for a single reaction including cross sections (possibly at multiple //! temperatures) and reaction products (with secondary angle-energy //! distributions) //============================================================================== class Reaction { public: //! Construct reaction from HDF5 data //! \param[in] group HDF5 group containing reaction data //! \param[in] temperatures Desired temperatures for cross sections explicit Reaction(hid_t group, const vector<int>& temperatures); //! \brief Calculate reaction rate based on group-wise flux distribution // //! \param[in] i_temp Temperature index //! \param[in] energy Energy group boundaries in [eV] //! \param[in] flux Flux in each energy group (not normalized per eV) //! \param[in] grid Nuclide energy grid //! \return Reaction rate double collapse_rate(gsl::index i_temp, gsl::span<const double> energy, gsl::span<const double> flux, const vector<double>& grid) const; //! Cross section at a single temperature struct TemperatureXS { int threshold; vector<double> value; }; int mt_; //!< ENDF MT value double q_value_; //!< Reaction Q value in [eV] bool scatter_in_cm_; //!< scattering system in center-of-mass? bool redundant_; //!< redundant reaction? vector<TemperatureXS> xs_; //!< Cross section at each temperature vector<ReactionProduct> products_; //!< Reaction products }; //============================================================================== // Non-member functions //============================================================================== //! Return reaction name given an ENDF MT value // //! \param[in] mt ENDF MT value //! \return Name of the corresponding reaction std::string reaction_name(int mt); //! Return reaction type (MT value) given a reaction name // //! \param[in] name Reaction name //! \return Corresponding reaction type (MT value) int reaction_type(std::string name); } // namespace openmc #endif // OPENMC_REACTION_H
{ "alphanum_fraction": 0.6150927487, "avg_line_length": 32.4931506849, "ext": "h", "hexsha": "a597e623712a5a899637a1daf3cbf957ea994317", "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": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_path": "include/openmc/reaction.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_path": "include/openmc/reaction.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_path": "include/openmc/reaction.h", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "num_tokens": 484, "size": 2372 }
/* testutilities.c * * 24-May-2008 Initial write: Ting Zhao */ #include <stdlib.h> #include <string.h> #include <utilities.h> #include <math.h> #include "tz_utilities.h" #include "tz_error.h" #include "tz_file_list.h" #include "tz_image_lib_defs.h" #include "tz_stack_utils.h" /* #include "tz_matlabio.h" #include "tz_rastergeom.h" #include <gsl/gsl_math.h> */ int main(int argc, char *argv[]) { static char *Spec[] = {"[-t]", NULL}; Process_Arguments(argc, argv, Spec, 1); if (Is_Arg_Matched("-t")) { /* example test */ /* extract file name without extension from a path */ const char *path = "../data/test.tif"; char *name = fname(path, NULL); if (strcmp(name, "test") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } /* The user is responsible for freeing the returned value */ free(name); /* The routine returns NULL when no name can be extracted */ path = "."; if (fname(path, NULL) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } path = "../data/"; if (fname(path, NULL) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } /* Different parts can be put together to form a path */ char new_path[500]; fullpath_e("../data/", "test", "tif", new_path); if (strcmp(new_path, "../data/test.tif") != 0) { printf("%s\n", new_path); PRINT_EXCEPTION("Bug?", "Unexpected file path."); return 1; } fullpath_e("", "test", "tif", new_path); if (strcmp(new_path, "test.tif") != 0) { printf("%s\n", new_path); PRINT_EXCEPTION("Bug?", "Unexpected file path."); return 1; } { /* unit test */ char buffer[500]; if (fname(NULL, buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname("\0", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname(".", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("t", buffer), "t") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname("/", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname("test/", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("test", buffer), "test") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("./test", buffer), "test") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("/test", buffer), "test") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("/.test", buffer), ".test") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("t.est", buffer), "t") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fname("/t.est", buffer), "t") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname("/.", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (fname("data/.", buffer) != NULL) { PRINT_EXCEPTION("Bug?", "Unexpected file name."); return 1; } if (strcmp(fullpath_e("dir", "file", "ext", buffer), "dir/file.ext") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected path name."); return 1; } if (strcmp(fullpath_e("dir/", "file", "ext", buffer), "dir/file.ext") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected path name."); return 1; } if (strcmp(fullpath_e("dir", "file", NULL, buffer), "dir/file") != 0) { PRINT_EXCEPTION("Bug?", "Unexpected path name."); return 1; } if (strcmp(fullpath_e("dir", "file", ".", buffer), "dir/file.") != 0) { printf("%s\n", buffer); PRINT_EXCEPTION("Bug?", "Unexpected path name."); return 1; } if (strcmp(fullpath_e("dir", "file", ".ext", buffer), "dir/file.ext") != 0) { printf("%s\n", buffer); PRINT_EXCEPTION("Bug?", "Unexpected path name."); return 1; } } printf(":) Testing passed.\n"); return 0; } #if 0 FILE *fp = fopen("../data/test.fbd", "r"); size_t len; char *line; while (!feof(fp)) { if ((line = fgetln(fp, &len)) != NULL) { printf("read %lu: ", len); line[len-1] = '\0'; printf("%s\n", line); } } fclose(fp); #endif #if 0 char path[100]; Find_Matlab_Binpath(path); printf("%s : %lu\n", path, strlen(path)); #endif #if 0 int a = 10000; int b = 11; XOR_SWAP(a, b); printf("%d %d\n", a, b); #endif #if 0 printf("%d\n", 2 << 2); printf("%d\n", Compare_Float(1.01, 1.002, 0.0005)); printf("%d\n", gsl_fcmp(1.01, 1.002, 0.0005)); #endif #if 0 char *s1 = "hello"; printf("%p\n", s1); s1[0] = 't'; printf("%s\n", s1); #endif #if 0 double x = -100.4350; printf("%g\n", Cube_Root(x) * Cube_Root(x) * Cube_Root(x)); #endif #if 0 printf("%d\n", Raster_Line_Map(852, 451, 296)); return 1; int m = 33; int n = 10; int i; for (i = 0; i < m; i++) { printf("%d ", Raster_Line_Map(m, n, i)); } printf("\n"); #endif #if 0 int w1 = 302; int h1 = 586; int nw2; int nh2; Raster_Ratio_Scale(w1, h1, 425, 236, &nw2, &nh2); printf("%d x %d\n", nw2, nh2); printf("%g => %g\n", (double) w1 / h1, (double) nw2 / nh2); #endif #if 0 //printf("%u\n", Hexstr_To_Uint("BA9B")); char str[9]; printf("%s\n", Uint_To_Hexstr(262, str)); #endif #if 0 FILE *fp = fopen("/Users/zhaot/Work/neurolabi/data/movie/a0.BMP", "r"); Fprint_File_Binary(fp, 20, stdout); fclose(fp); #endif #if 0 printf("%d\n", Round_Div(110, -19)); #endif #if 0 printf("%d\n", Raster_Linear_Map(31, 10, 100, 0, 231)); #endif #if 0 printf("%d\n", Raster_Point_Zoom_Offset(0, 2, 100, 512, 500, 1)); #endif #if 0 fcopy("../data/test.tif", "../data/test2.tif"); #endif #if 0 printf("%d bytes\n", fsize("../data/test.tif")); #endif #if 0 printf("%g %g %g\n", Infinity, -Infinity, NaN); #endif #if 0 size_t x = 1000; printf("%zd\n", (size_t) 1000 * 1000 * 1000 * 4); #endif #if 0 size_t index = Stack_Util_Offset(1000, 1000, 1000, 2000, 2000, 2000); printf("%zd\n", index); int x, y, z; Stack_Util_Coord(index, 2000, 2000, &x, &y, &z); printf("%d %d %d\n", x, y, z); #endif #if 0 printf("%s\n", fname("../data/test.dot", NULL)); printf("%s\n", dname("../data/test.dot", NULL)); printf("%s\n", dname("/test.dot", NULL)); printf("%s\n", dname("test.dot", NULL)); #endif #if 0 char *line = malloc(2048 * 2048 * 4); char *data = malloc(1024 * 1024 * 4); int i; int j; tic(); for (i = 0; i < 2048; i++) { for (j = 0; j < 2048; j++) { if (*line != *data++) { *line++ = *data; *line++ = *data; *line = *data; line += 2; } /* memset(line, *data++, 3); line += 4; */ } } printf("%lld\n", toc()); #endif #if 0 char buf[11]; Memset_Pattern4( buf, "1234", 10 ); buf[10] = '\0'; printf("%s\n", buf); Memset_Pattern4( buf, "4321", 8 ); buf[8] = '\0'; printf("%s\n", buf); Memset_Pattern4( buf, "4321", 2); buf[2] = '\0'; printf("%s\n", buf); #endif #if 0 char *block[1000000]; int i; tic(); for (i = 0; i < 1000000; i++) { block[i] = (char*) malloc(i % 991 + 10); } printf("%lld\n", toc()); int index[1000000]; int j; int offset = 0; for (i = 0; i < 100; i++) { for (j = 0; j < 10000; j++) { index[offset++] = j * 100 + i; } } tic(); for (i = 999999; i >= 0; i--) { free(block[index[i]]); } printf("%lld\n", toc()); #endif #if 0 int (*test)[10]; int test2[10]; test = &test2; printf("%p\n", test); printf("%p\n", *test); printf("%p\n", test2); #endif #if 0 int a[100]; int i = 0; i[a] = 0; printf("%d\n", i[a]); #endif #if 0 free(NULL); #endif #if 0 int i; for (i = 0; i < 10; i++) { int n = 0; n++; printf("%d\n", n); } #endif #if 0 printf("%g\n", round(0.5)); printf("%g\n", floor(0.5)); #endif #if 0 if (fcmp("../data/test2.tb", "../data/test3.tb")) { printf("The files are different.\n"); } else { printf("The files are the same.\n"); } #endif #if 0 char str[65]; printf("%s\n", double_binstr(0.0, str)); #endif #if 0 printf("%d\n", MEDIAN3(0, 1, 2)); printf("%d\n", MEDIAN3(0, 2, 1)); printf("%d\n", MEDIAN3(1, 0, 2)); printf("%d\n", MEDIAN3(2, 1, 0)); printf("%d\n", MEDIAN3(1, 2, 0)); printf("%d\n", MEDIAN3(2, 0, 1)); printf("%d\n", MEDIAN3(0, 1, 1)); printf("%d\n", MEDIAN3(1, 0, 1)); printf("%d\n", MEDIAN3(1, 1, 0)); printf("%d\n", MEDIAN3(2, 1, 1)); printf("%d\n", MEDIAN3(1, 2, 1)); printf("%d\n", MEDIAN3(1, 1, 2)); #endif #if 0 unsigned char ch1 = 255; char ch = ch1; printf("%x\n", ch); ch1 = -1; printf("%x\n", ch1); #endif #if 0 //size_t fs = fsize("../data/spikes/pm002.nev"); FILE *fp = fopen("../data/spikes/pm002.nev", "r"); /* fseek(fp, fs - 104*5, SEEK_SET); uint32_t tmp1; uint16_t tmp2; uint8_t tmp3; fread(&tmp1, 4, 1, fp); fread(&tmp2, 2, 1, fp); fread(&tmp3, 1, 1, fp); printf("%u, %u, %u\n", tmp1, tmp2, tmp3); */ uint32_t head_size; fseek(fp, 12, SEEK_SET); fread(&head_size, 4, 1, fp); fseek(fp, head_size, SEEK_SET); int packetcnt = 4325366; char *buffer = (char*) malloc(packetcnt * 104); fread(buffer, 1, packetcnt * 104, fp); int offset = 0; uint32_t tmp1; uint16_t tmp2; uint8_t tmp3; int i; for (i = 0; i < packetcnt; i++) { tmp1 = *((uint32_t*) (buffer + offset)); offset += 4; tmp2 = *((uint16_t*) (buffer + offset)); offset += 2; tmp3 = *((uint8_t*) (buffer + offset)); if (i > 4325360) { printf("%u %u %u\n", tmp1, tmp2, tmp3); } offset += 1; offset += 97; } fclose(fp); #endif #if 0 File_List *list = New_File_List(); //File_List_Load_Dir("/home/zhaot/Work/neutube/neurolabi/data/test", "tif", list); File_List_Load_Dir("../data", "tif", list); File_List_Sort_By_Number(list); Print_File_List(list); #endif #if 0 int start, end; dir_fnum_pair("../data/ting_example_stack/superpixel_maps", ".*\\.png", &start, &end); printf("%d, %d\n", start, end); #endif #if 0 color_t color; uint8_t overflow = Value_To_Color(0, color); printf("%u %u %u %u\n", overflow, color[2], color[1], color[0]); #endif #if 0 printf("%*sD\n", 3, "t"); #endif #if 1 #endif return 0; }
{ "alphanum_fraction": 0.5443465217, "avg_line_length": 20.472168906, "ext": "c", "hexsha": "5c8dec1053efb3c0775ebd4ada8bc882a7ea863f", "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/testutilities.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/testutilities.c", "max_line_length": 84, "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/testutilities.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": 3688, "size": 10666 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include "ccl.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) { ccl_raise_warning( CCL_ERROR_MEMORY, "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_linlog spacing ------ * INPUTS: [xminlog,xmax] of the interval to be divided in bins * xmin when linear spacing starts * Nlog number of logarithmically spaced bins * Nlin number of linearly spaced bins * OUTPUT: bin edges in range [xminlog,xmax] * */ double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlog, int Nlin) { if (Nlog<2) { ccl_raise_warning( CCL_ERROR_LINLOGSPACE, "ERROR: Cannot make log-spaced array with %d points - need at least 2\n", Nlog); return NULL; } if (!(xminlog>0 && xmin>0)) { ccl_raise_warning( CCL_ERROR_LINLOGSPACE, "ERROR: Cannot make log-spaced array xminlog or xmin non-positive (had %le, %le)\n", xminlog, xmin); return NULL; } if (xminlog>xmin){ ccl_raise_warning(CCL_ERROR_LINLOGSPACE, "ERROR: xminlog must be smaller as xmin"); return NULL; } if (xmin>xmax){ ccl_raise_warning(CCL_ERROR_LINLOGSPACE, "ERROR: xmin must be smaller as xmax"); return NULL; } double * x = malloc(sizeof(double)*(Nlin+Nlog-1)); if (x==NULL) { ccl_raise_warning( CCL_ERROR_MEMORY, "ERROR: Could not allocate memory for array of size (Nlin+Nlog-1)=%d)\n", (Nlin+Nlog-1)); return x; } double dx = (xmax-xmin)/(Nlin -1.); double log_xchange = log(xmin); double log_xmin = log(xminlog); double dlog_x = (log_xchange - log_xmin) / (Nlog-1.); for (int i=0; i<Nlin+Nlog-1; i++) { if (i<Nlog) x[i] = exp(log_xmin + dlog_x*i); if (i>=Nlog) x[i] = xmin + dx*(i-Nlog+1); } x[0]=xminlog; //Make sure roundoff errors don't spoil edges x[Nlog-1]=xmin; //Make sure roundoff errors don't spoil edges x[Nlin+Nlog-2]=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) { ccl_raise_warning( CCL_ERROR_LOGSPACE, "ERROR: Cannot make log-spaced array with %d points - need at least 2\n", N); return NULL; } if (!(xmin>0 && xmax>0)) { ccl_raise_warning( CCL_ERROR_LOGSPACE, "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) { ccl_raise_warning( CCL_ERROR_MEMORY, "ERROR: Could not allocate memory for log-spaced array (N=%d)\n", N); return x; } double xratio = exp(dlog_x); x[0] = xmin; //Make sure roundoff errors don't spoil edges for (int i=1; i<N-1; i++) { x[i] = x[i-1] * xratio; } 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_gsl_warning(stat, "ccl_utils.c: ccl_splin_eval():"); return NAN; } return y; } } #define CCL_GAMMA1 2.6789385347077476336556 //Gamma(1/3) #define CCL_GAMMA2 1.3541179394264004169452 //Gamma(2/3) #define CCL_ROOTPI12 21.269446210866192327578 //12*sqrt(pi) double ccl_j_bessel(int l,double x) { double jl; double ax=fabs(x); double ax2=x*x; if(l<0) { fprintf(stderr,"CosmoMas: l>0 for Bessel function"); exit(1); } if(l<7) { if(l==0) { if(ax<0.1) jl=1-ax2*(1-ax2/20.)/6.; else jl=sin(x)/x; } else if(l==1) { if(ax<0.2) jl=ax*(1-ax2*(1-ax2/28)/10)/3; else jl=(sin(x)/ax-cos(x))/ax; } else if(l==2) { if(ax<0.3) jl=ax2*(1-ax2*(1-ax2/36)/14)/15; else jl=(-3*cos(x)/ax-sin(x)*(1-3/ax2))/ax; } else if(l==3) { if(ax<0.4) jl=ax*ax2*(1-ax2*(1-ax2/44)/18)/105; else jl=(cos(x)*(1-15/ax2)-sin(x)*(6-15/ax2)/ax)/ax; } else if(l==4) { if(ax<0.6) jl=ax2*ax2*(1-ax2*(1-ax2/52)/22)/945; else jl=(sin(x)*(1-(45-105/ax2)/ax2)+cos(x)*(10-105/ax2)/ax)/ax; } else if(l==5) { if(ax<1.0) jl=ax2*ax2*ax*(1-ax2*(1-ax2/60)/26)/10395; else { jl=(sin(x)*(15-(420-945/ax2)/ax2)/ax- cos(x)*(1-(105-945/ax2)/ax2))/ax; } } else { if(ax<1.0) jl=ax2*ax2*ax2*(1-ax2*(1-ax2/68)/30)/135135; else { jl=(sin(x)*(-1+(210-(4725-10395/ax2)/ax2)/ax2)+ cos(x)*(-21+(1260-10395/ax2)/ax2)/ax)/ax; } } } else { double nu=l+0.5; double nu2=nu*nu; if(ax<1.0E-40) jl=0; else if((ax2/l)<0.5) { jl=(exp(l*log(ax/nu)-M_LN2+nu*(1-M_LN2)-(1-(1-3.5/nu2)/(30*nu2))/(12*nu))/nu)* (1-ax2/(4*nu+4)*(1-ax2/(8*nu+16)*(1-ax2/(12*nu+36)))); } else if((l*l/ax)<0.5) { double beta=ax-0.5*M_PI*(l+1); jl=(cos(beta)*(1-(nu2-0.25)*(nu2-2.25)/(8*ax2)*(1-(nu2-6.25)*(nu2-12.25)/(48*ax2)))- sin(beta)*(nu2-0.25)/(2*ax)*(1-(nu2-2.25)*(nu2-6.25)/(24*ax2)* (1-(nu2-12.25)*(nu2-20.25)/(80*ax2))))/ax; } else { double l3=pow(nu,0.325); if(ax<nu-1.31*l3) { double cosb=nu/ax; double sx=sqrt(nu2-ax2); double cotb=nu/sx; double secb=ax/nu; double beta=log(cosb+sx/ax); double cot3b=cotb*cotb*cotb; double cot6b=cot3b*cot3b; double sec2b=secb*secb; double expterm=((2+3*sec2b)*cot3b/24 -((4+sec2b)*sec2b*cot6b/16 +((16-(1512+(3654+375*sec2b)*sec2b)*sec2b)*cot3b/5760 +(32+(288+(232+13*sec2b)*sec2b)*sec2b)*sec2b*cot6b/(128*nu))* cot6b/nu)/nu)/nu; jl=sqrt(cotb*cosb)/(2*nu)*exp(-nu*beta+nu/cotb-expterm); } else if(ax>nu+1.48*l3) { double cosb=nu/ax; double sx=sqrt(ax2-nu2); double cotb=nu/sx; double secb=ax/nu; double beta=acos(cosb); double cot3b=cotb*cotb*cotb; double cot6b=cot3b*cot3b; double sec2b=secb*secb; double trigarg=nu/cotb-nu*beta-0.25*M_PI- ((2+3*sec2b)*cot3b/24+(16-(1512+(3654+375*sec2b)*sec2b)*sec2b)* cot3b*cot6b/(5760*nu2))/nu; double expterm=((4+sec2b)*sec2b*cot6b/16- (32+(288+(232+13*sec2b)*sec2b)*sec2b)* sec2b*cot6b*cot6b/(128*nu2))/nu2; jl=sqrt(cotb*cosb)/nu*exp(-expterm)*cos(trigarg); } else { double beta=ax-nu; double beta2=beta*beta; double sx=6/ax; double sx2=sx*sx; double secb=pow(sx,0.3333333333333333333333); double sec2b=secb*secb; jl=(CCL_GAMMA1*secb+beta*CCL_GAMMA2*sec2b -(beta2/18-1.0/45.0)*beta*sx*secb*CCL_GAMMA1 -((beta2-1)*beta2/36+1.0/420.0)*sx*sec2b*CCL_GAMMA2 +(((beta2/1620-7.0/3240.0)*beta2+1.0/648.0)*beta2-1.0/8100.0)*sx2*secb*CCL_GAMMA1 +(((beta2/4536-1.0/810.0)*beta2+19.0/11340.0)*beta2-13.0/28350.0)*beta*sx2*sec2b*CCL_GAMMA2 -((((beta2/349920-1.0/29160.0)*beta2+71.0/583200.0)*beta2-121.0/874800.0)* beta2+7939.0/224532000.0)*beta*sx2*sx*secb*CCL_GAMMA1)*sqrt(sx)/CCL_ROOTPI12; } } } if((x<0)&&(l%2!=0)) jl=-jl; return jl; } //Spline destructor void ccl_spline_free(SplPar *spl) { gsl_spline_free(spl->spline); gsl_interp_accel_free(spl->intacc); free(spl); }
{ "alphanum_fraction": 0.6139255147, "avg_line_length": 26.850931677, "ext": "c", "hexsha": "2e7ff93830d093a30c5d0be7e55f89f92079cea3", "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": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_path": "src/ccl_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "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": "Russell-Jones-OxPhys/CCL", "max_issues_repo_path": "src/ccl_utils.c", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "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": 3341, "size": 8646 }
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <err.h> #include <gsl/gsl_rng.h> #include <tskit/tables.h> #define check_tsk_error(val) if (val < 0) {\ errx(EXIT_FAILURE, "line %d: %s", __LINE__, tsk_strerror(val));\ } void simulate(tsk_table_collection_t *tables, int N, int T, int simplify_interval, gsl_rng *rng) { tsk_id_t *buffer, *parents, *children, child, left_parent, right_parent; double breakpoint; int ret, j, t, b; assert(simplify_interval != 0); // leads to division by zero buffer = malloc(2 * N * sizeof(tsk_id_t)); if (buffer == NULL) { errx(EXIT_FAILURE, "Out of memory"); } tables->sequence_length = 1.0; parents = buffer; for (j = 0; j < N; j++) { parents[j] = tsk_node_table_add_row(&tables->nodes, 0, T, TSK_NULL, TSK_NULL, NULL, 0); check_tsk_error(parents[j]); } b = 0; for (t = T - 1; t >= 0; t--) { /* Alternate between using the first and last N values in the buffer */ parents = buffer + (b * N); b = (b + 1) % 2; children = buffer + (b * N); for (j = 0; j < N; j++) { child = tsk_node_table_add_row(&tables->nodes, 0, t, TSK_NULL, TSK_NULL, NULL, 0); check_tsk_error(child); left_parent = parents[gsl_rng_uniform_int(rng, N)]; right_parent = parents[gsl_rng_uniform_int(rng, N)]; do { breakpoint = gsl_rng_uniform(rng); } while (breakpoint == 0); /* tiny proba of breakpoint being 0 */ ret = tsk_edge_table_add_row(&tables->edges, 0, breakpoint, left_parent, child); check_tsk_error(ret); ret = tsk_edge_table_add_row(&tables->edges, breakpoint, 1, right_parent, child); check_tsk_error(ret); children[j] = child; } if (t % simplify_interval == 0) { printf("Simplify at generation %d: (%d nodes %d edges)", t, tables->nodes.num_rows, tables->edges.num_rows); /* Note: Edges must be sorted for simplify to work, and we use a brute force * approach of sorting each time here for simplicity. This is inefficient. */ ret = tsk_table_collection_sort(tables, NULL, 0); check_tsk_error(ret); ret = tsk_table_collection_simplify(tables, children, N, 0, NULL); check_tsk_error(ret); printf(" -> (%d nodes %d edges)\n", tables->nodes.num_rows, tables->edges.num_rows); for (j = 0; j < N; j++) { children[j] = j; } } } free(buffer); } int main(int argc, char **argv) { int ret; tsk_table_collection_t tables; gsl_rng *rng = gsl_rng_alloc(gsl_rng_default); if (argc != 5) { errx(EXIT_FAILURE, "usage: N T simplify-interval output-file"); } ret = tsk_table_collection_init(&tables, 0); check_tsk_error(ret); simulate(&tables, atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), rng); ret = tsk_table_collection_dump(&tables, argv[4], 0); check_tsk_error(ret); tsk_table_collection_free(&tables); gsl_rng_free(rng); return 0; }
{ "alphanum_fraction": 0.5791100124, "avg_line_length": 35.1739130435, "ext": "c", "hexsha": "257496a03750050a1adafc2a02998aa0bb622fd5", "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": "92fe9c04a27385401732a698843756aa797bacdd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "winni2k/tskit", "max_forks_repo_path": "c/examples/haploid_wright_fisher.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "92fe9c04a27385401732a698843756aa797bacdd", "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": "winni2k/tskit", "max_issues_repo_path": "c/examples/haploid_wright_fisher.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "92fe9c04a27385401732a698843756aa797bacdd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "winni2k/tskit", "max_stars_repo_path": "c/examples/haploid_wright_fisher.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 870, "size": 3236 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <gsl.h> #include <nlohmann/json_fwd.hpp> #include <cstdint> #include <string> /** * The Event class represents the information needed for a single * audit event entry. */ class Event { public: Event() = delete; /** * Construct and initialize a new Event structure based off the * provided JSON. See ../README.md for information about the * layout of the JSON element. * * @param entry * @throws std::runtime_error for errors accessing the expected * elements */ explicit Event(const nlohmann::json& json); /// The identifier for this entry uint32_t id; /// The name of the entry std::string name; /// The full description of the entry std::string description; /// Set to true if this entry should be handled synchronously bool sync; /// Set to true if this entry is enabled (or should be dropped) bool enabled; /// Set to true if the user may enable filtering for the enry bool filtering_permitted; /// The textual representation of the JSON describing mandatory /// fields in the event (NOTE: this is currently not enforced /// by the audit daemon) std::string mandatory_fields; /// The textual representation of the JSON describing the optional /// fields in the event (NOTE: this is currently not enforced /// by the audit daemon) std::string optional_fields; };
{ "alphanum_fraction": 0.6720779221, "avg_line_length": 33.1692307692, "ext": "h", "hexsha": "94285d535ceddd528877f487da5b098e150b40f5", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z", "max_forks_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "paolococchi/kv_engine", "max_forks_repo_path": "auditd/generator/generator_event.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "40256dca6bf77fb4bcc18e8ef7d9b8f991bf4e45", "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": "paolococchi/kv_engine", "max_issues_repo_path": "auditd/generator/generator_event.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_path": "auditd/generator/generator_event.h", "max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z", "num_tokens": 486, "size": 2156 }
/* multifit/covar.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 <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_blas.h> int gsl_multifit_gradient (const gsl_matrix * J, const gsl_vector * f, gsl_vector * g) { int status = gsl_blas_dgemv (CblasTrans, 1.0, J, f, 0.0, g); return status; }
{ "alphanum_fraction": 0.7121212121, "avg_line_length": 33, "ext": "c", "hexsha": "ad04b63df3bb2eabf0d02a6d4bc0fbc10e357976", "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/multifit/gradient.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/multifit/gradient.c", "max_line_length": 72, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/multifit/gradient.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": 310, "size": 1122 }
/* examples/C/ssmfe/hermitian.c - Example code for SPRAL_SSMFE package */ /* Hermitian operator example */ #include "spral.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <cblas.h> /* central differences for i d/dx */ void apply_idx(int n, int m, const double complex *x_ptr, double complex *y_ptr) { const double complex (*x)[n] = (const double complex (*)[n]) x_ptr; double complex (*y)[n] = (double complex (*)[n]) y_ptr; for(int j=0; j<m; j++) { for(int i=0; i<n; i++) { int il = (i==0) ? n-1 : i-1; int ir = (i==n-1) ? 0 : i+1; y[j][i] = _Complex_I * (x[j][ir] - x[j][il]); } } } /* main routine */ int main(void) { const int n = 80; /* problem size */ const int nep = 5; /* eigenpairs wanted */ double lambda[nep]; /* eigenvalues */ double complex X[nep][n]; /* eigenvectors */ struct spral_ssmfe_rciz rci; /* reverse communication data */ struct spral_ssmfe_options options; /* options */ void *keep; /* private data */ struct spral_ssmfe_inform inform; /* information */ /* Initialize options to default values */ spral_ssmfe_default_options(&options); rci.job = 0; keep = NULL; while(true) { /* reverse communication loop */ spral_ssmfe_standard_double_complex(&rci, nep, nep, lambda, n, &X[0][0], n, &keep, &options, &inform); switch ( rci.job ) { case 1: apply_idx(n, rci.nx, rci.x, rci.y); break; case 2: // No preconditioning break; default: goto finished; } } finished: printf("%d eigenpairs converged in %d iterations\n", inform.left, inform.iteration); for(int i=0; i<inform.left; i++) printf(" lambda[%1d] = %13.7e\n", i, lambda[i]); spral_ssmfe_free_double_complex(&keep, &inform); /* Success */ return 0; }
{ "alphanum_fraction": 0.5650614754, "avg_line_length": 32, "ext": "c", "hexsha": "f6802b7e70d045735d9a739234ba53101ab0705e", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2022-02-28T14:58:37.000Z", "max_forks_repo_forks_event_min_datetime": "2016-09-30T20:52:47.000Z", "max_forks_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mjacobse/spral", "max_forks_repo_path": "examples/C/ssmfe/hermitian.c", "max_issues_count": 51, "max_issues_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_issues_repo_issues_event_max_datetime": "2022-03-11T12:52:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-09-20T19:01:18.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mjacobse/spral", "max_issues_repo_path": "examples/C/ssmfe/hermitian.c", "max_line_length": 87, "max_stars_count": 76, "max_stars_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mjacobse/spral", "max_stars_repo_path": "examples/C/ssmfe/hermitian.c", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:34.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-03T13:58:37.000Z", "num_tokens": 561, "size": 1952 }
#pragma once #include <vector> #include <gsl-lite/gsl-lite.hpp> #include <Eigen/Sparse> #include <thrustshift/CSR.h> #include <thrustshift/container-conversion.h> #include <thrustshift/managed-vector.h> #include <thrustshift/memory-resource.h> namespace thrustshift { namespace eigen { //! Return a CSR matrix with the default memory resource of the CSR class template <class EigenSparseMatrix> auto sparse_mtx2csr(EigenSparseMatrix&& m_) { using DataType = typename std::remove_reference<EigenSparseMatrix>::type::value_type; using StorageIndex = typename std::remove_reference<EigenSparseMatrix>::type::StorageIndex; // Create copy because we might modify the container with `makeCompressed` Eigen::SparseMatrix<DataType, Eigen::RowMajor, StorageIndex> m = m_; m.makeCompressed(); auto m_data = m.data(); auto nnz = m.nonZeros(); auto rows = m.rows(); const DataType* A = &m_data.value(0); const StorageIndex* IA = m.outerIndexPtr(); const StorageIndex* JA = &m_data.index(0); managed_vector<DataType> seq_A(A, A + nnz); managed_vector<StorageIndex> seq_JA(JA, JA + nnz); managed_vector<StorageIndex> seq_IA(IA, IA + rows + 1); return CSR<DataType, StorageIndex>( seq_A, seq_JA, seq_IA, gsl_lite::narrow<size_t>(m.cols())); } // Forward declaration to avoid co-dependent headers template <class EigenSparseMatrix, class COO_C> EigenSparseMatrix coo2sparse_mtx(COO_C&& coo); template <class EigenSparseMatrix, class CSR_C> EigenSparseMatrix csr2sparse_mtx(CSR_C&& csr) { using DataType = typename std::remove_reference<EigenSparseMatrix>::type::value_type; using StorageIndex = typename std::remove_reference<EigenSparseMatrix>::type::StorageIndex; return coo2sparse_mtx<EigenSparseMatrix>( csr2coo<thrustshift::COO<DataType, StorageIndex>>( std::forward<CSR_C>(csr), pmr::default_resource)); } } // namespace eigen } // namespace thrustshift
{ "alphanum_fraction": 0.7502606882, "avg_line_length": 29.5076923077, "ext": "h", "hexsha": "96442b2d1c523fd07c51478c7c55b6af55e89a22", "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/eigen3-interface/CSR.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/eigen3-interface/CSR.h", "max_line_length": 75, "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/eigen3-interface/CSR.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": 480, "size": 1918 }
#ifdef USE_MKL #include <mkl.h> #else #include <cblas.h> #endif // contains all calls to C-interface BLAS functions // e.g. http://www.netlib.org/lapack/explore-html/d1/dff/cblas__example1_8c_source.html // returns the dot product of x and y // http://www.netlib.org/lapack/explore-html/d5/df6/ddot_8f_source.html double specex_dot(int n, const double *x, const double *y){ return cblas_ddot(n, x, 1, y, 1); } // y += alpha*x // http://www.netlib.org/lapack/explore-html/d9/dcd/daxpy_8f_source.html void specex_axpy(int n, const double *alpha, const double *x, const double *y){ cblas_daxpy(n, *alpha, x, 1, y, 1); } // A += alpha*x*x**T, where A is a symmetric matrx (only lower half is filled) // http://www.netlib.org/lapack/explore-html/d3/d60/dsyr_8f_source.html void specex_syr(int n, const double *alpha, const double *x, const double *A){ cblas_dsyr(CblasColMajor, CblasLower, n, *alpha, x, 1, A, n); } // C = alpha*A**T + beta*C, where A is a symmetric matrx // http://www.netlib.org/lapack/explore-html/dc/d05/dsyrk_8f_source.html void specex_syrk(int n, int k, const double *alpha, const double *A, const double *beta, const double *C){ cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, n, k, *alpha, A, n, *beta, C, n); } // y = alpha*A*x + beta*y // http://www.netlib.org/lapack/explore-html/dc/da8/dgemv_8f_source.html void specex_gemv(int m, int n, const double *alpha, const double *A, const double *x, const double *beta, const double *y){ cblas_dgemv(CblasColMajor, CblasNoTrans, m, n, *alpha, A, m, x, 1, *beta, y, 1); } // C = alpha*A*B + beta*C // http://www.netlib.org/lapack/explore-html/d7/d2b/dgemm_8f_source.html void specex_gemm(int m, int n, int k, const double *alpha, const double *A, const double *B, const double *beta, const double *C){ cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, *alpha, A, m, B, k, *beta, C, m); }
{ "alphanum_fraction": 0.6959247649, "avg_line_length": 38.28, "ext": "c", "hexsha": "3bb4edbe7a95f9f693ea9b586dee99d695c6647b", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-07-18T16:32:34.000Z", "max_forks_repo_forks_event_min_datetime": "2016-06-16T17:43:38.000Z", "max_forks_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "tskisner/specex", "max_forks_repo_path": "src/specex_blas.c", "max_issues_count": 39, "max_issues_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_issues_repo_issues_event_max_datetime": "2022-01-07T00:11:25.000Z", "max_issues_repo_issues_event_min_datetime": "2016-06-17T19:58:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "tskisner/specex", "max_issues_repo_path": "src/specex_blas.c", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "c5ae74a85305395cdd3cb4a3ac966bef4eacd8b2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tskisner/specex", "max_stars_repo_path": "src/specex_blas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 672, "size": 1914 }
/* randist/logistic.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The logistic distribution has the form, p(x) dx = (1/a) exp(-x/a) / (1 + exp(-x/a))^2 dx for -infty < x < infty */ double gsl_ran_logistic (const gsl_rng * r, const double a) { double x, z; do { x = gsl_rng_uniform_pos (r); } while (x == 1); z = log (x / (1 - x)); return a * z; } double gsl_ran_logistic_pdf (const double x, const double a) { double u = exp (-fabs(x)/a); double p = u / (fabs(a) * (1 + u) * (1 + u)); return p; }
{ "alphanum_fraction": 0.6680911681, "avg_line_length": 26, "ext": "c", "hexsha": "c1e05d4f8197d6cb451f417a77a24e5743e83242", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/logistic.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/randist/logistic.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/logistic.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": 414, "size": 1404 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "tests.h" void test_hpr2 (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; int N = 1; float alpha[2] = {-1.0f, 0.0f}; float Ap[] = { 0.159f, -0.13f }; float X[] = { 0.854f, 0.851f }; int incX = -1; float Y[] = { 0.526f, -0.267f }; int incY = -1; float Ap_expected[] = { -0.284974f, 0.0f }; cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr2(case 1458) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr2(case 1458) imag"); }; }; }; { int order = 101; int uplo = 122; int N = 1; float alpha[2] = {-1.0f, 0.0f}; float Ap[] = { 0.159f, -0.13f }; float X[] = { 0.854f, 0.851f }; int incX = -1; float Y[] = { 0.526f, -0.267f }; int incY = -1; float Ap_expected[] = { -0.284974f, 0.0f }; cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr2(case 1459) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr2(case 1459) imag"); }; }; }; { int order = 102; int uplo = 121; int N = 1; float alpha[2] = {-1.0f, 0.0f}; float Ap[] = { 0.159f, -0.13f }; float X[] = { 0.854f, 0.851f }; int incX = -1; float Y[] = { 0.526f, -0.267f }; int incY = -1; float Ap_expected[] = { -0.284974f, 0.0f }; cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr2(case 1460) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr2(case 1460) imag"); }; }; }; { int order = 102; int uplo = 122; int N = 1; float alpha[2] = {-1.0f, 0.0f}; float Ap[] = { 0.159f, -0.13f }; float X[] = { 0.854f, 0.851f }; int incX = -1; float Y[] = { 0.526f, -0.267f }; int incY = -1; float Ap_expected[] = { -0.284974f, 0.0f }; cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, "chpr2(case 1461) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, "chpr2(case 1461) imag"); }; }; }; { int order = 101; int uplo = 121; int N = 1; double alpha[2] = {-0.3, 0.1}; double Ap[] = { 0.772, 0.997 }; double X[] = { -0.173, -0.839 }; int incX = -1; double Y[] = { 0.941, -0.422 }; int incY = -1; double Ap_expected[] = { 0.829742, 0.0 }; cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr2(case 1462) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr2(case 1462) imag"); }; }; }; { int order = 101; int uplo = 122; int N = 1; double alpha[2] = {-0.3, 0.1}; double Ap[] = { 0.772, 0.997 }; double X[] = { -0.173, -0.839 }; int incX = -1; double Y[] = { 0.941, -0.422 }; int incY = -1; double Ap_expected[] = { 0.829742, 0.0 }; cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr2(case 1463) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr2(case 1463) imag"); }; }; }; { int order = 102; int uplo = 121; int N = 1; double alpha[2] = {-0.3, 0.1}; double Ap[] = { 0.772, 0.997 }; double X[] = { -0.173, -0.839 }; int incX = -1; double Y[] = { 0.941, -0.422 }; int incY = -1; double Ap_expected[] = { 0.829742, 0.0 }; cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr2(case 1464) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr2(case 1464) imag"); }; }; }; { int order = 102; int uplo = 122; int N = 1; double alpha[2] = {-0.3, 0.1}; double Ap[] = { 0.772, 0.997 }; double X[] = { -0.173, -0.839 }; int incX = -1; double Y[] = { 0.941, -0.422 }; int incY = -1; double Ap_expected[] = { 0.829742, 0.0 }; cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, "zhpr2(case 1465) real"); gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, "zhpr2(case 1465) imag"); }; }; }; }
{ "alphanum_fraction": 0.5086296527, "avg_line_length": 25.579787234, "ext": "c", "hexsha": "7fb7dee72012f4310be29a6dc128ae6d18a137ed", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_line_length": 84, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 2073, "size": 4809 }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <glob.h> #include <unistd.h> #include <dirent.h> #include <limits.h> #include "hdf5.h" #include <math.h> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> //#include "mclib_3d.h" #include "mclib.h" #include <omp.h> #include "mpi.h" #include "mc_synch.h" #define PROP_DIM1 1 #define PROP_DIM2 8 #define PROP_DIM3 8 #define COORD_DIM1 2 #define R_DIM_2D 9120 #define THETA_DIM_2D 2000 //define constants const double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27, FINE_STRUCT=7.29735308e-3, CHARGE_EL= 4.8032068e-10; const double K_B=1.380658e-16, M_P=1.6726231e-24, THOM_X_SECT=6.65246e-25, M_EL=9.1093879e-28 , R_EL=2.817941499892705e-13; int getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame) { int i=0, j=0, val=0, original_num_procs=-1, rand_num=0; int frame2=0, framestart=0, scatt_framestart=0, ph_num=0; double time=0; char mc_chkpt_files[200]="", restrt=""; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function struct photon *phPtr=NULL; //pointer to array of photons //DIR * dirp; //struct dirent * entry; //struct stat st = {0}; glob_t files; //if (angle_rank==0) { //find number of mc_checkpt files there are //loop through them and find out which prior processes didnt finish and keep track of which ones didnt snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s", dir,"mc_chkpt_*" ); val=glob(mc_chkpt_files, 0, NULL,&files ); //printf("TEST: %s\n", mc_chkpt_files); //look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs srand(angle_rank); //printf("NUM_FILES: %d\n",files.gl_pathc); rand_num=rand() % files.gl_pathc; snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" ); //printf("TEST: %s\n", mc_chkpt_files); if ( access( mc_chkpt_files, F_OK ) == -1 ) { while(( access( mc_chkpt_files, F_OK ) == -1 ) ) { rand_num=rand() % files.gl_pathc; snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" ); //printf("TEST: %s\n", mc_chkpt_files); } } readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs); //original_num_procs= 70; } int count_procs[original_num_procs], count=0; int cont_procs[original_num_procs]; //create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering for (j=0;j<original_num_procs;j++) { count_procs[j]=j; cont_procs[j]=-1; //set to impossible value for previous mpi process rank that needs to be con't } int limit= (angle_rank != angle_procs-1) ? (angle_rank+1)*original_num_procs/angle_procs : original_num_procs; //char mc_chkpt_files[200]=""; printf("Angle ID: %d, start_num: %d, limit: %d\n", angle_rank, (angle_rank*original_num_procs/angle_procs), limit); count=0; for (j=floor(angle_rank*original_num_procs/angle_procs);j<limit;j++) { snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", j,".dat" ); //printf("TEST: %s\n", mc_chkpt_files); if ( access( mc_chkpt_files, F_OK ) != -1 ) { readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, count_procs[j], &i); free(phPtr); phPtr=NULL; if ((framestart<=frame2) && (scatt_framestart<=last_frame)) //add another condition here { cont_procs[count]=j; //printf("ACCEPTED: %s\n", mc_chkpt_files); count++; } } else { cont_procs[count]=j; //printf("ACCEPTED: %s\n", mc_chkpt_files); count++; } } (*proc_array)=malloc (count * sizeof (int )); //allocate space to pointer to hold the old process angle_id's count=0; for (i=0;i<original_num_procs;i++) { if (cont_procs[i]!=-1) { (*proc_array)[count]=cont_procs[i]; count++; } } //save number of old processes this process counted need to be restarted *counted_cont_procs=count; globfree(& files); return original_num_procs; } void printPhotons(struct photon *ph, int num_ph, int num_ph_abs, int num_ph_emit, int num_null_ph, int scatt_synch_num_ph, int frame,int frame_inj, int frame_last, char dir[200], int angle_rank, FILE *fPtr ) { //function to save the photons' positions and 4 momentum //now using hdf5 file for each process w/ group structure /(weights or Hydro File #)/(p0,p1,p2,p3, r0, r1, r2, s0, s1, s2, or num_scatt) //open the file if it exists and see if the group exists for the given frame, if frame doesnt exist then write datasets for all photons as extendable //if the frame does exist then read information from the prewritten data and then add new data to it as extended chunk int i=0, count=0, rank=1, net_num_ph=num_ph-num_ph_abs-num_null_ph, weight_net_num_ph= num_ph-num_ph_abs-num_null_ph, global_weight_net_num_ph=(frame==frame_inj) ? num_ph-num_ph_abs-num_null_ph : num_ph_emit-num_ph_abs ; //can have more photons absorbed than emitted, weight_net_num_ph=(frame==frame_inj) ? num_ph-num_ph_abs-num_null_ph : scatt_synch_num_ph #if defined(_OPENMP) int num_thread=omp_get_num_threads(); #endif char mc_file[200]="", group[200]="", group_weight[200]="", *ph_type=NULL; double p0[net_num_ph], p1[net_num_ph], p2[net_num_ph], p3[net_num_ph] , r0[net_num_ph], r1[net_num_ph], r2[net_num_ph], num_scatt[net_num_ph], weight[weight_net_num_ph], global_weight[net_num_ph]; double s0[net_num_ph], s1[net_num_ph], s2[net_num_ph], s3[net_num_ph], comv_p0[net_num_ph], comv_p1[net_num_ph], comv_p2[net_num_ph], comv_p3[net_num_ph]; hid_t file, file_init, dspace, dspace_weight, dspace_global_weight, fspace, mspace, prop, prop_weight, prop_global_weight, group_id; hid_t dset_p0, dset_p1, dset_p2, dset_p3, dset_r0, dset_r1, dset_r2, dset_s0, dset_s1, dset_s2, dset_s3, dset_num_scatt, dset_weight, dset_weight_2, dset_comv_p0, dset_comv_p1, dset_comv_p2, dset_comv_p3, dset_ph_type; herr_t status, status_group, status_weight, status_weight_2; hsize_t dims[1]={net_num_ph}, dims_weight[1]={weight_net_num_ph}, dims_old[1]={0}; //1 is the number of dimansions for the dataset, called rank hsize_t maxdims[1]={H5S_UNLIMITED}; hsize_t size[1]; hsize_t offset[1]; fprintf(fPtr, "num_ph %d num_ph_abs %d num_null_ph %d num_ph_emit %d\nAllocated weight to be %d values large and other arrays to be %d\n",num_ph,num_ph_abs,num_null_ph,num_ph_emit, weight_net_num_ph, net_num_ph); ph_type=malloc((net_num_ph)*sizeof(char)); //save photon data into large arrays, NEED TO KNOW HOW MANY NULL PHOTONS WE HAVE AKA SAVED SPACE THAT AREN'T ACTUALLY PHOTONS TO PROPERLY SAVE SPACE FOR ARRAYS ABOVE weight_net_num_ph=0; count=0;//used to keep track of weight values since it may not be the same as num_ph //#pragma omp parallel for num_threads(num_thread) reduction(+:weight_net_num_ph) for (i=0;i<num_ph;i++) { if ((ph+i)->weight != 0) { p0[count]= ((ph+i)->p0); p1[count]= ((ph+i)->p1); p2[count]= ((ph+i)->p2); p3[count]= ((ph+i)->p3); r0[count]= ((ph+i)->r0); r1[count]= ((ph+i)->r1); r2[count]= ((ph+i)->r2); s0[count]= ((ph+i)->s0); s1[count]= ((ph+i)->s1); s2[count]= ((ph+i)->s2); s3[count]= ((ph+i)->s3); num_scatt[count]= ((ph+i)->num_scatt); //if ((frame==frame_inj) || ((scatt_synch_num_ph > 0) && ((ph+i)->type == COMPTONIZED_PHOTON))) //if the frame is the same one that the photons were injected in, save the photon weights OR if there are synchrotron photons that havent been absorbed { weight[weight_net_num_ph]= ((ph+i)->weight); weight_net_num_ph++; //fprintf(fPtr, "%d %c %e %e %e %e %e %e %e %e\n", i, (ph+i)->type, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt, (ph+i)->weight, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->p0*C_LIGHT/1.6e-9); } if ((frame==frame_last)) { global_weight[count]=((ph+i)->weight); } *(ph_type+count)=(ph+i)->type; //printf("%d %c %e %e %e %e %e %e %e %e %c\n", i, (ph+i)->type, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt, (ph+i)->weight, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->p0*C_LIGHT/1.6e-9, *(ph_type+count)); count++; } } //make strings for file name and group snprintf(mc_file,sizeof(mc_file),"%s%s%d%s",dir,"mc_proc_", angle_rank, ".h5" ); snprintf(group,sizeof(mc_file),"%d",frame ); //see if file exists, if not create it, if it does just open it status = H5Eset_auto(NULL, NULL, NULL); //turn off automatic error printing file_init=H5Fcreate(mc_file, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT); //see if the file initially does/doesnt exist file=file_init; status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //turn on auto error printing if (file_init<0) { //the file exists, open it with read write file=H5Fopen(mc_file, H5F_ACC_RDWR, H5P_DEFAULT); //fprintf(fPtr,"In IF\n"); //see if the group exists status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); /* fprintf(fPtr, group); if (status_group == 0) { fprintf (fPtr, "The group exists.\n"); //now try to see if there's a weight data set for this group } else { fprintf (fPtr, "The group either does NOT exist\n or some other error occurred.\n"); } */ } if ((file_init>=0) || (status_group != 0) ) { //printf("In IF\n"); //if the file exists, see if the weight exists //snprintf(group_weight,sizeof(group),"/PW",i ); status = H5Eset_auto(NULL, NULL, NULL); status_weight = H5Gget_objinfo (file, "/PW", 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); fprintf(fPtr,"Status of /PW %d\n", status_weight); //the file has been newly created or if the group does not exist then create the group for the frame group_id = H5Gcreate2(file, group, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); /* Modify dataset creation properties, i.e. enable chunking */ prop = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop, rank, dims); if ((frame==frame_inj) || (scatt_synch_num_ph > 0)) { prop_weight= H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop_weight, rank, dims_weight); } if ((frame==frame_last)) { status = H5Pset_chunk (prop, rank, dims); } /* Create the data space with unlimited dimensions. */ dspace = H5Screate_simple (rank, dims, maxdims); dspace_weight=H5Screate_simple (rank, dims_weight, maxdims); /* Create a new dataset within the file using chunk creation properties. */ dset_p0 = H5Dcreate2 (group_id, "P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_p1 = H5Dcreate2 (group_id, "P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_p2 = H5Dcreate2 (group_id, "P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_p3 = H5Dcreate2 (group_id, "P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); //if (COMV_SWITCH!=0) #if COMV_SWITCH == ON { dset_comv_p0 = H5Dcreate2 (group_id, "COMV_P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_comv_p1 = H5Dcreate2 (group_id, "COMV_P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_comv_p2 = H5Dcreate2 (group_id, "COMV_P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_comv_p3 = H5Dcreate2 (group_id, "COMV_P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); } #endif dset_r0 = H5Dcreate2 (group_id, "R0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_r1 = H5Dcreate2 (group_id, "R1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_r2 = H5Dcreate2 (group_id, "R2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); //if (STOKES_SWITCH!=0) #if STOKES_SWITCH == ON { dset_s0 = H5Dcreate2 (group_id, "S0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_s1 = H5Dcreate2 (group_id, "S1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_s2 = H5Dcreate2 (group_id, "S2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); dset_s3 = H5Dcreate2 (group_id, "S3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); } #endif #if SAVE_TYPE == ON { dset_ph_type = H5Dcreate2 (group_id, "PT", H5T_NATIVE_CHAR, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); } #endif dset_num_scatt = H5Dcreate2 (group_id, "NS", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); if ((frame==frame_inj) || (scatt_synch_num_ph > 0)) //if the frame is the same one that the photons were injected in, save the photon weights or if there are emitted photons that havent been absorbed { dset_weight_2 = H5Dcreate2 (group_id, "PW", H5T_NATIVE_DOUBLE, dspace_weight, H5P_DEFAULT, prop_weight, H5P_DEFAULT); //save the new injected photons' weights } if ((frame==frame_last)) { //if saving the injected photons weight dont have to worry about the major ph_weight thats not in a group dset_weight = H5Dcreate2 (file, "PW", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); } /* Write data to dataset */ status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p0); status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p1); status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p2); status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p3); //if (COMV_SWITCH!=0) #if COMV_SWITCH == ON { status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p0); status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p1); status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p2); status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p3); } #endif status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r0); status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r1); status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r2); //if (STOKES_SWITCH!=0) #if STOKES_SWITCH == ON { status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s0); status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s1); status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s2); status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s3); } #endif #if SAVE_TYPE == ON { status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, ph_type); } #endif status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, num_scatt); if ((frame==frame_inj) || (scatt_synch_num_ph > 0)) { status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, weight); status = H5Pclose (prop_weight); status = H5Dclose (dset_weight_2); } if ((frame==frame_last)) { //printf("Before write\n"); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, global_weight); //printf("After write\n"); } status = H5Pclose (prop); } else { //if the group already exists then extend it //find the size of it now /* Open an existing group of the specified file. */ group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_p0 = H5Dopen (group_id, "P0", H5P_DEFAULT); //open dataset //get dimensions of array and save it dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims_old //extend the dataset size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p0, size); /* Select a hyperslab in extended portion of dataset */ fspace = H5Dget_space (dset_p0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); /* Define memory space */ mspace = H5Screate_simple (rank, dims, NULL); /* Write the data to the extended portion of dataset */ status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, p0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_p1 = H5Dopen (group_id, "P1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p1, size); fspace = H5Dget_space (dset_p1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, p1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_p2 = H5Dopen (group_id, "P2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p2, size); fspace = H5Dget_space (dset_p2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, p2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_p3 = H5Dopen (group_id, "P3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_p3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_p3, size); fspace = H5Dget_space (dset_p3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, p3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); //if (COMV_SWITCH!=0) #if COMV_SWITCH == ON { dset_comv_p0 = H5Dopen (group_id, "COMV_P0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p0, size); fspace = H5Dget_space (dset_comv_p0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, comv_p0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_comv_p1 = H5Dopen (group_id, "COMV_P1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p1, size); fspace = H5Dget_space (dset_comv_p1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, comv_p1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_comv_p2 = H5Dopen (group_id, "COMV_P2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p2, size); fspace = H5Dget_space (dset_comv_p2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, comv_p2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_comv_p3 = H5Dopen (group_id, "COMV_P3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_comv_p3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_comv_p3, size); fspace = H5Dget_space (dset_comv_p3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, comv_p3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); } #endif dset_r0 = H5Dopen (group_id, "R0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r0, size); fspace = H5Dget_space (dset_r0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, r0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_r1 = H5Dopen (group_id, "R1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r1, size); fspace = H5Dget_space (dset_r1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, r1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_r2 = H5Dopen (group_id, "R2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_r2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_r2, size); fspace = H5Dget_space (dset_r2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, r2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); //if (STOKES_SWITCH!=0) #if STOKES_SWITCH == ON { dset_s0 = H5Dopen (group_id, "S0", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s0); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s0, size); fspace = H5Dget_space (dset_s0); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, s0); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_s1 = H5Dopen (group_id, "S1", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s1); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s1, size); fspace = H5Dget_space (dset_s1); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, s1); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_s2 = H5Dopen (group_id, "S2", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s2, size); fspace = H5Dget_space (dset_s2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, s2); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); dset_s3 = H5Dopen (group_id, "S3", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_s3); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_s3, size); fspace = H5Dget_space (dset_s3); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, s3); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); } #endif #if SAVE_TYPE == ON { dset_ph_type = H5Dopen (group_id, "PT", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_ph_type); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_ph_type, size); fspace = H5Dget_space (dset_ph_type); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, mspace, fspace, H5P_DEFAULT, ph_type); status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); } #endif dset_num_scatt = H5Dopen (group_id, "NS", H5P_DEFAULT); //open dataset dspace = H5Dget_space (dset_num_scatt); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims size[0] = dims[0]+ dims_old[0]; status = H5Dset_extent (dset_num_scatt, size); fspace = H5Dget_space (dset_num_scatt); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims, NULL); mspace = H5Screate_simple (rank, dims, NULL); status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, num_scatt); //see if the weights group exists, if it does then we can extend it, otherwise we need to create it and write the new values to it snprintf(group_weight,sizeof(group_weight),"PW",i ); status = H5Eset_auto(NULL, NULL, NULL); status_weight = H5Gget_objinfo (group_id, "PW", 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); fprintf(fPtr,"Status of /frame/PW %d\n", status_weight); //if (((frame==frame_inj) || (scatt_synch_num_ph > 0)) ) { status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); if (((frame==frame_last))) { //make sure to append the newly injected/emitted photons from the most recent set of injected photons to the global weights dset_weight = H5Dopen (file, "PW", H5P_DEFAULT); //open dataset //get dimensions of array and save it dspace = H5Dget_space (dset_weight); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims //extend the dataset size[0] = dims_weight[0]+ dims_old[0]; status = H5Dset_extent (dset_weight, size); /* Select a hyperslab in extended portion of dataset */ fspace = H5Dget_space (dset_weight); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims_weight, NULL); /* Define memory space */ mspace = H5Screate_simple (rank, dims_weight, NULL); /* Write the data to the extended portion of dataset */ status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, weight); } if (status_weight >= 0) { //will have to create the weight dataset for the new set of phtons that have been injected, although it may already be created since emitting photons now //see if the group exists status = H5Eset_auto(NULL, NULL, NULL); status_weight_2 = H5Gget_objinfo (group_id, "/PW", 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); if (status_weight_2 < 0) { //the dataset doesnt exist /* Modify dataset creation properties, i.e. enable chunking */ prop = H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop, rank, dims); /* Create the data space with unlimited dimensions. */ dspace = H5Screate_simple (rank, dims, maxdims); dset_weight_2 = H5Dcreate2 (group_id, "PW", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, prop, H5P_DEFAULT); //save the new injected photons' weights status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, weight); status = H5Pclose (prop); } else { //it exists and need to modify it dset_weight_2 = H5Dopen (group_id, "PW", H5P_DEFAULT); //open dataset //get dimensions of array and save it dspace = H5Dget_space (dset_weight_2); status=H5Sget_simple_extent_dims(dspace, dims_old, NULL); //save dimesnions in dims //extend the dataset size[0] = dims_weight[0]+ dims_old[0]; status = H5Dset_extent (dset_weight_2, size); /* Select a hyperslab in extended portion of dataset */ fspace = H5Dget_space (dset_weight_2); offset[0] = dims_old[0]; status = H5Sselect_hyperslab (fspace, H5S_SELECT_SET, offset, NULL, dims_weight, NULL); /* Define memory space */ mspace = H5Screate_simple (rank, dims_weight, NULL); /* Write the data to the extended portion of dataset */ status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, mspace, fspace, H5P_DEFAULT, weight); } } else { fprintf(fPtr, "The frame exists in the hdf5 file but the weight dataset for the frame doesnt exist, therefore creating it.\n"); fflush(fPtr); prop_weight= H5Pcreate (H5P_DATASET_CREATE); status = H5Pset_chunk (prop_weight, rank, dims_weight); dspace_weight=H5Screate_simple (rank, dims_weight, maxdims); dset_weight_2 = H5Dcreate2 (group_id, "PW", H5T_NATIVE_DOUBLE, dspace_weight, H5P_DEFAULT, prop_weight, H5P_DEFAULT); status = H5Dwrite (dset_weight_2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, weight); status = H5Pclose (prop_weight); } status = H5Dclose (dset_weight_2); } status = H5Sclose (dspace); status = H5Sclose (mspace); status = H5Sclose (fspace); } /* Close resources */ free(ph_type); //status = H5Sclose (dspace); status = H5Dclose (dset_p0); status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3); //if (COMV_SWITCH!=0) #if COMV_SWITCH == ON { status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3); } #endif status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2); //if (STOKES_SWITCH!=0) #if STOKES_SWITCH == ON { status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3); } #endif #if SAVE_TYPE == ON { status = H5Dclose (dset_ph_type); } #endif status = H5Dclose (dset_num_scatt); if ((frame==frame_last)) { status = H5Dclose (dset_weight); } /* Close the group. */ status = H5Gclose(group_id); /* Terminate access to the file. */ status = H5Fclose(file); } int saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size ) { //function to save data necessary to restart simulation if it ends //need to save all photon data FILE *fPtr=NULL; char checkptfile[2000]=""; char command[2000]=""; char restart; int i=0, success=0;; snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" ); //snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s%d%s",dir,"mc_chkpt_", angle_rank, "_frame_", scatt_frame, ".dat" ); //look at frame 1341? if ((scatt_frame!=last_frame) && (scatt_frame != frame)) { //quick way to preserve old chkpt file if the new one overwrites the old one and corrupts it for some reason snprintf(command, sizeof(command), "%s%s %s_old","exec cp ",checkptfile, checkptfile); system(command); fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); success=1; } else { //can call printPhotons here or return an int signifying if the checkpoint save worked fwrite(&angle_size, sizeof(int), 1, fPtr); restart='c'; fwrite(&restart, sizeof(char), 1, fPtr); //printf("Rank: %d wrote restart %c\n", angle_rank, restart); fflush(stdout); fwrite(&frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame\n", angle_rank); fflush(stdout); fwrite(&frame2, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame2\n", angle_rank); fflush(stdout); fwrite(&scatt_frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote scatt_frame\n", angle_rank); fflush(stdout); fwrite(&time_now, sizeof(double), 1, fPtr); //printf("Rank: %d wrote time_now\n", angle_rank); fflush(stdout); fwrite(&ph_num, sizeof(int), 1, fPtr); //printf("Rank: %d wrote ph_num\n", angle_rank); fflush(stdout); for(i=0;i<ph_num;i++) { #if SYNCHROTRON_SWITCH == ON if (((ph+i)->type == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0)) { (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon } #endif fwrite((ph+i), sizeof(struct photon ), 1, fPtr); //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr); } success=0; } //printf("Rank: %d wrote photons\n", angle_rank); fflush(stdout); } else if (scatt_frame == frame) { snprintf(command, sizeof(command), "%s%s","exec rm ",checkptfile); system(command); fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); fflush(stdout); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); success=1; } else { fwrite(&angle_size, sizeof(int), 1, fPtr); restart='c'; fwrite(&restart, sizeof(char), 1, fPtr); //printf("Rank: %d wrote restart %c\n", angle_rank, restart); fflush(stdout); fwrite(&frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame\n", angle_rank); fflush(stdout); fwrite(&frame2, sizeof(int), 1, fPtr); //printf("Rank: %d wrote frame2\n", angle_rank); fflush(stdout); fwrite(&scatt_frame, sizeof(int), 1, fPtr); //printf("Rank: %d wrote scatt_frame\n", angle_rank); fflush(stdout); fwrite(&time_now, sizeof(double), 1, fPtr); //printf("Rank: %d wrote time_now\n", angle_rank); fflush(stdout); fwrite(&ph_num, sizeof(int), 1, fPtr); //printf("Rank: %d wrote ph_num\n", angle_rank); fflush(stdout); for(i=0;i<ph_num;i++) { #if SYNCHROTRON_SWITCH == ON if (((ph+i)->type == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0)) { (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon } #endif //fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr); fwrite((ph+i), sizeof(struct photon ), 1, fPtr); } //printf("Rank: %d wrote photons\n", angle_rank); success=0; } fflush(stdout); } else { //quick way to preserve old chkpt file if the new one overwrites the old one and corrupts it for some reason snprintf(command, sizeof(command), "%s%s %s_old","exec cp ",checkptfile, checkptfile); system(command); fPtr=fopen(checkptfile, "wb"); //printf("%s\n", checkptfile); if (fPtr==NULL) { printf("Cannot open %s to save checkpoint\n", checkptfile); success=1; } else { //just finished last iteration of scatt_frame fwrite(&angle_size, sizeof(int), 1, fPtr); restart='r'; fwrite(&restart, sizeof(char), 1, fPtr); fwrite(&frame, sizeof(int), 1, fPtr); fwrite(&frame2, sizeof(int), 1, fPtr); for(i=0;i<ph_num;i++) { #if SYNCHROTRON_SWITCH == ON if (((ph+i)->type == COMPTONIZED_PHOTON) && ((ph+i)->weight != 0)) { (ph+i)->type = OLD_COMPTONIZED_PHOTON; //set this to be an old synchrotron scattered photon } #endif fwrite((ph+i), sizeof(struct photon ), 1, fPtr); } success=0; } } if (success==0) { fclose(fPtr); } return success; } int readCheckpoint(char dir[200], struct photon **ph, int *frame2, int *framestart, int *scatt_framestart, int *ph_num, char *restart, double *time, int angle_rank, int *angle_size ) { //function to read in data from checkpoint file FILE *fPtr=NULL; char checkptfile[200]=""; int i=0; int scatt_synch_num_ph=0;//count the number of scattered synchrotron photons from the previosu frame that were saved //int frame, scatt_frame, ph_num, i=0; struct photon *phHolder=NULL; //pointer to struct to hold data read in from checkpoint file snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" ); printf("Checkpoint file: %s\n", checkptfile); if (access( checkptfile, F_OK ) != -1) //if you can access the file, open and read it { fPtr=fopen(checkptfile, "rb"); //if ((angle_rank==2) || (angle_rank==3) || (angle_rank==4) || (angle_rank==5)) { fread(angle_size, sizeof(int), 1, fPtr); //uncomment once I run MCRAT for the sims that didnt save this originally } fread(restart, sizeof(char), 1, fPtr); //printf("%c\n", *restart); fread(framestart, sizeof(int), 1, fPtr); //printf("%d\n", *framestart); fread(frame2, sizeof(int), 1, fPtr); if((*restart)=='c') { fread(scatt_framestart, sizeof(int), 1, fPtr); //if ((riken_switch==1) && (strcmp(DIM_SWITCH, dim_3d_str)==0) && ((*scatt_framestart)>=3000)) #if SIM_SWITCH == RIKEN && DIMENSIONS == 3 if ((*scatt_framestart)>=3000) { *scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #else { *scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted } #endif //printf("%d\n", *scatt_framestart); fread(time, sizeof(double), 1, fPtr); //printf("%e\n", *time); fread(ph_num, sizeof(int), 1, fPtr); //printf("%d\n", *ph_num); phHolder=malloc(sizeof(struct photon)); (*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data for (i=0;i<(*ph_num);i++) { fread(phHolder, sizeof(struct photon), 1, fPtr); //printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt ); (*ph)[i].p0=phHolder->p0; (*ph)[i].p1=phHolder->p1; (*ph)[i].p2=phHolder->p2; (*ph)[i].p3=phHolder->p3; (*ph)[i].comv_p0=phHolder->comv_p0; (*ph)[i].comv_p1=phHolder->comv_p1; (*ph)[i].comv_p2=phHolder->comv_p2; (*ph)[i].comv_p3=phHolder->comv_p3; (*ph)[i].r0= phHolder->r0; (*ph)[i].r1=phHolder->r1 ; (*ph)[i].r2=phHolder->r2; (*ph)[i].s0=phHolder->s0; (*ph)[i].s1=phHolder->s1; (*ph)[i].s2=phHolder->s2; (*ph)[i].s3=phHolder->s3; (*ph)[i].num_scatt=phHolder->num_scatt; (*ph)[i].weight=phHolder->weight; (*ph)[i].nearest_block_index= phHolder->nearest_block_index; (*ph)[i].type= phHolder->type; #if SYNCHROTRON_SWITCH == ON if (((*ph)[i].weight != 0) && (((*ph)[i].type == COMPTONIZED_PHOTON) || ((*ph)[i].type == OLD_COMPTONIZED_PHOTON)) && ((*ph)[i].p0 > 0)) { scatt_synch_num_ph++; } //printf("%d %c %e %e %e %e %e %e %e\n", i, (*ph)[i].type, (*ph)[i].r0, (*ph)[i].r1, (*ph)[i].r2, (*ph)[i].num_scatt, (*ph)[i].weight, (*ph)[i].p0*C_LIGHT/1.6e-9, (*ph)[i].comv_p0); #endif } free(phHolder); //printf("In readcheckpoint count=%d\n", count); } else { //if ((riken_switch==1) && (strcmp(DIM_SWITCH, dim_3d_str)==0) && ((*framestart)>=3000)) #if SIM_SWITCH == RIKEN && DIMENSIONS == 3 if ((*framestart)>=3000) { *framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #else { *framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start } #endif *scatt_framestart=(*framestart); } fclose(fPtr); } else //if not use default { //*framestart=(*framestart); *scatt_framestart=(*framestart); *restart='r'; } return scatt_synch_num_ph; } void readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart) { //function to read mc.par file FILE *fptr=NULL; char buf[100]=""; double theta_deg; //open file fptr=fopen(file,"r"); //read in frames per sec and other variables outlined in main() fscanf(fptr, "%lf",fluid_domain_x); //printf("%lf\n", *fluid_domain_x ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",fluid_domain_y); //printf("%lf\n", *fluid_domain_y ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",fps); //printf("%f\n", *fps ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm0_small); //printf("%d\n", *frm0_small ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm0_large); //printf("%d\n", *frm0_large ); fgets(buf, 100,fptr); fscanf(fptr, "%d",last_frm); //printf("%d\n", *last_frm ); fgets(buf, 100,fptr); fscanf(fptr, "%d",frm2_small); *frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame //printf("%d\n", *frm2_small ); fgets(buf, 100,fptr); //fscanf(fptr, "%d",photon_num); remove photon num because we dont need this //printf("%d\n", *photon_num ); fscanf(fptr, "%d",frm2_large); *frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame //printf("%d\n", *frm2_large ); fgets(buf, 100,fptr); //fgets(buf, 100,fptr); fscanf(fptr, "%lf",inj_radius_small); //printf("%lf\n", *inj_radius_small ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",inj_radius_large); //printf("%lf\n", *inj_radius_large ); fgets(buf, 100,fptr); //theta jmin fscanf(fptr, "%lf",&theta_deg); *theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes //printf("%f\n", *theta_jmin ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",&theta_deg); *theta_j=theta_deg;//*M_PI/180; //printf("%f\n", *theta_j ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",d_theta_j); //*theta_j=theta_deg;//*M_PI/180; //printf("%f\n", *theta_j ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",ph_weight_small); //printf("%f\n", *ph_weight_small ); fgets(buf, 100,fptr); fscanf(fptr, "%lf",ph_weight_large); fgets(buf, 100,fptr); fscanf(fptr, "%d",min_photons); fgets(buf, 100,fptr); fscanf(fptr, "%d",max_photons); fgets(buf, 100,fptr); *spect=getc(fptr); fgets(buf, 100,fptr); //printf("%c\n",*spect); *restart=getc(fptr); fgets(buf, 100,fptr); //dont need this line fo code for MPI //fscanf(fptr, "%d",num_threads); //printf("MAKE SURE THERE IS NO NUM_THREADS LINE IN THE MC.PAR FILE.\n"); //fgets(buf, 100,fptr); //fscanf(fptr, "%d",dim_switch); //printf("MAKE SURE THERE IS NO DIM_SWITCH LINE IN THE MC.PAR FILE.\n"); //printf("%d\n",*dim_switch); //close file fclose(fptr); } void readAndDecimate(char flash_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\ double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr) { //function to read in data from FLASH file hid_t file,dset, space; herr_t status; hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0]) double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL; double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL; int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0; double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16}; double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0, track_min_r=DBL_MAX, track_max_r=0; #if defined(_OPENMP) int num_thread=omp_get_num_threads(); #endif if (ph_inj_switch==0) { ph_rmin=min_r; ph_rmax=max_r; ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees) ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees) } file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT); //ret=H5Pclose(acc_tpl1); fprintf(fPtr, ">> MCRaT: Reading positional, density, pressure, and velocity information...\n"); fflush(fPtr); //printf("Reading coord\n"); dset = H5Dopen (file, "coordinates", H5P_DEFAULT); //get dimensions of array and save it space = H5Dget_space (dset); H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims //status = H5Sclose (space); //status = H5Dclose (dset); //status = H5Fclose (file); /* * Allocate array of pointers to rows. */ coord_buffer = (double **) malloc (dims[0] * sizeof (double *)); coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double)); block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *)); block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double)); node_buffer= (int **) malloc (dims[0] * sizeof (int *)); node_buffer[0] = (int *) malloc (dims[0] * sizeof (int)); vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *)); vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *)); vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); dens_buffer= (double **) malloc (dims[0] * sizeof (double *)); dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); pres_buffer= (double **) malloc (dims[0] * sizeof (double *)); pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double)); /* * Set the rest of the pointers to rows to the correct addresses. */ for (i=1; i<dims[0]; i++) { coord_buffer[i] = coord_buffer[0] + i * dims[1]; block_sz_buffer[i] = block_sz_buffer[0] + i * COORD_DIM1; node_buffer[i] = node_buffer[0] + i ; vel_x_buffer[i] = vel_x_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; vel_y_buffer[i] = vel_y_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; dens_buffer[i] = dens_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; pres_buffer[i] = pres_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3; } //read data such that first column is x and second column is y //fprintf(fPtr, "Reading Dataset\n"); //fflush(fPtr); //dset = H5Dopen (file, "coordinates", H5P_DEFAULT); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,coord_buffer[0]); //close dataset status = H5Sclose (space); status = H5Dclose (dset); //printf("Reading block size\n"); dset = H5Dopen (file, "block size", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,block_sz_buffer[0]); // first column of buffer is x and second column is y status = H5Dclose (dset); //status = H5Fclose (file); dset = H5Dopen (file, "node type", H5P_DEFAULT); status = H5Dread (dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,node_buffer[0]); status = H5Dclose (dset); dset = H5Dopen (file, "velx", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_x_buffer[0]); status = H5Dclose (dset); //status = H5Fclose (file); //printf("Reading vely\n"); dset = H5Dopen (file, "vely", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_y_buffer[0]); status = H5Dclose (dset); //status = H5Fclose (file); //printf("Reading dens\n"); dset = H5Dopen (file, "dens", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,dens_buffer[0]); status = H5Dclose (dset); //printf("Reading pres\n"); dset = H5Dopen (file, "pres", H5P_DEFAULT); //printf("Reading Dataset\n"); status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,pres_buffer[0]); status = H5Dclose (dset); //H5Pclose(xfer_plist); status = H5Fclose (file); fprintf(fPtr,">> Selecting good node types (=1)\n"); //find out how many good nodes there are for (i=0;i<dims[0];i++) { if (node_buffer[i][0]==1 ){ num_nodes++; } } //allocate memory for arrays to hold unprocessed data pres_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); dens_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); velx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); vely_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); x_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); y_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); r_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); szx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); szy_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double )); //find where the good values corresponding to the good gones (=1) and save them to the previously allocated pointers which are 1D arrays //also create proper x and y arrays and block size arrays //and then free up the buffer memory space fprintf(fPtr,">> Creating and reshaping arrays\n"); count=0; for (i=0;i<dims[0];i++) { if (node_buffer[i][0]==1 ) { x1_count=0; y1_count=0; for (j=0;j<(PROP_DIM1*PROP_DIM2*PROP_DIM3);j++) { *(pres_unprc+count)=pres_buffer[i][j]*HYDRO_P_SCALE; *(dens_unprc+count)=dens_buffer[i][j]*HYDRO_D_SCALE; *(velx_unprc+count)=vel_x_buffer[i][j]; *(vely_unprc+count)=vel_y_buffer[i][j]; *(szx_unprc+count)=((block_sz_buffer[i][0])/8)*HYDRO_L_SCALE; //divide by 8 for resolution, multiply by 1e9 to scale properly? *(szy_unprc+count)=((block_sz_buffer[i][1])/8)*HYDRO_L_SCALE; if (j%8==0) { x1_count=0; } if ((j%8==0) && (j!=0)) { y1_count++; } *(x_unprc+count)=(coord_buffer[i][0]+block_sz_buffer[i][0]*x1[x1_count])*HYDRO_L_SCALE; *(y_unprc+count)=(coord_buffer[i][1]+block_sz_buffer[i][1]*x1[y1_count])*HYDRO_L_SCALE; //printf("%d,%d,%d,%d\n",count,j,x1_count,y1_count); x1_count++; count++; } } } free (pres_buffer[0]); free (dens_buffer[0]);free (vel_x_buffer[0]);free (vel_y_buffer[0]); free(coord_buffer[0]);free(block_sz_buffer[0]);free(node_buffer[0]); free (pres_buffer);free(dens_buffer);free(vel_x_buffer);free(vel_y_buffer);free(coord_buffer);free(block_sz_buffer);free(node_buffer); //fill in radius array and find in how many places r > injection radius //have single thread execute this while loop and then have inner loop be parallel #if SYNCHROTRON_SWITCH == ON elem_factor=2; #else elem_factor=0; #endif r_count=0; while (r_count==0) { r_count=0; elem_factor++; for (i=0;i<count;i++) { *(r_unprc+i)=pow((*(x_unprc+i))*(*(x_unprc+i))+(*(y_unprc+i))*(*(y_unprc+i)),0.5); if (ph_inj_switch==0) { r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5); r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner); if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) ) { r_count++; } } else { if (*(r_unprc+i)> (0.95*r_inj) ) { r_count++; } } } //fprintf(fPtr, "r_count: %d count: %d\n", r_count, count); } fprintf(fPtr, "Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\n", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI); fflush(fPtr); //allocate memory to hold processed data (*pres)=malloc (r_count * sizeof (double )); (*velx)=malloc (r_count * sizeof (double )); (*vely)=malloc (r_count * sizeof (double )); (*dens)=malloc (r_count * sizeof (double )); (*x)=malloc (r_count * sizeof (double )); (*y)=malloc (r_count * sizeof (double )); (*r)=malloc (r_count * sizeof (double )); (*theta)=malloc (r_count * sizeof (double )); (*gamma)=malloc (r_count * sizeof (double )); (*dens_lab)=malloc (r_count * sizeof (double )); (*szx)=malloc (r_count * sizeof (double )); (*szy)=malloc (r_count * sizeof (double )); (*temp)=malloc (r_count * sizeof (double )); //assign values based on r> 0.95*r_inj j=0; for (i=0;i<count;i++) { if (ph_inj_switch==0) { r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5); r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner); if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax)) { (*pres)[j]=*(pres_unprc+i); (*velx)[j]=*(velx_unprc+i); (*vely)[j]=*(vely_unprc+i); (*dens)[j]=*(dens_unprc+i); (*x)[j]=*(x_unprc+i); (*y)[j]=*(y_unprc+i); (*r)[j]=*(r_unprc+i); (*szx)[j]=*(szx_unprc+i); (*szy)[j]=*(szy_unprc+i); (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1)); (*temp)[j]=pow(3*(*(pres_unprc+i))/(A_RAD) ,1.0/4.0); j++; /* if (*(r_unprc+i)<track_min_r) { track_min_r=*(r_unprc+i); } if (*(r_unprc+i)>track_max_r) { track_max_r=*(r_unprc+i); } */ } } else { if (*(r_unprc+i)> (0.95*r_inj) ) { (*pres)[j]=*(pres_unprc+i); (*velx)[j]=*(velx_unprc+i); (*vely)[j]=*(vely_unprc+i); (*dens)[j]=*(dens_unprc+i); (*x)[j]=*(x_unprc+i); (*y)[j]=*(y_unprc+i); (*r)[j]=*(r_unprc+i); (*szx)[j]=*(szx_unprc+i); (*szy)[j]=*(szy_unprc+i); (*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis (*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c (*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1)); (*temp)[j]=pow(3*(*(pres_unprc+i))/(A_RAD) ,1.0/4.0); j++; } } } //fprintf(fPtr, "Actual Min and Max Flash grid radii are: %e %e\n", track_min_r, track_max_r); //fflush(fPtr); *number=r_count; free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc); //exit(0); } void photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\ double *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, FILE *fPtr) { int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0; double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax; double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame) double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values float num_dens_coeff; double r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0; double position_rand=0, position2_rand=0; if (spect=='w') //from MCRAT paper, w for wien spectrum { num_dens_coeff=8.44; //printf("in wien spectrum\n"); } else { num_dens_coeff=20.29; //this is for black body spectrum //printf("in BB spectrum"); } //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for //and then rcord which blocks have to have "x" amount of photons injected there rmin=r_inj - 0.5*C_LIGHT/fps; rmax=r_inj + 0.5*C_LIGHT/fps; for(i=0;i<array_length;i++) { #if GEOMETRY == CARTESIAN r_grid_innercorner = pow((*(x+i) - *(szx+i)/2.0) * ((*(x+i) - *(szx+i)/2.0))+(*(y+i) - *(szy+i)/2.0) * (*(y+i) - *(szy+i)/2.0),0.5); r_grid_outercorner = pow((*(x+i) + *(szx+i)/2.0) * ((*(x+i) + *(szx+i)/2.0))+(*(y+i) + *(szy+i)/2.0) * (*(y+i) + *(szy+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y+i) - *(szx+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y+i) + *(szx+i)/2.0) /r_grid_outercorner); #elif GEOMETRY == SPHERICAL r_grid_innercorner = (*(r+i)) - 0.5 * (*(szx+i)); r_grid_outercorner = (*(r+i)) + 0.5 * (*(szx+i)); theta_grid_innercorner = (*(theta+i)) - 0.5 * (*(szy+i)); theta_grid_outercorner = (*(theta+i)) + 0.5 * (*(szy+i)); #endif //look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO IMPLEMENT //if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max)) { block_cnt++; } } //printf("Blocks: %d\n", block_cnt); //allocate memory to record density of photons for each block ph_dens=malloc(block_cnt * sizeof(int)); //calculate the photon density for each block and save it to the array j=0; ph_tot=0; ph_weight_adjusted=ph_weight; //printf("%d %d\n", max_photons, min_photons); while ((ph_tot>max_photons) || (ph_tot<min_photons) ) { j=0; ph_tot=0; for (i=0;i<array_length;i++) { //printf("%d\n",i); //printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min); #if GEOMETRY == CARTESIAN r_grid_innercorner = pow((*(x+i) - *(szx+i)/2.0) * ((*(x+i) - *(szx+i)/2.0))+(*(y+i) - *(szy+i)/2.0) * (*(y+i) - *(szy+i)/2.0),0.5); r_grid_outercorner = pow((*(x+i) + *(szx+i)/2.0) * ((*(x+i) + *(szx+i)/2.0))+(*(y+i) + *(szy+i)/2.0) * (*(y+i) + *(szy+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y+i) - *(szx+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y+i) + *(szx+i)/2.0) /r_grid_outercorner); #elif GEOMETRY == SPHERICAL r_grid_innercorner = (*(r+i)) - 0.5 * (*(szx+i)); r_grid_outercorner = (*(r+i)) + 0.5 * (*(szx+i)); theta_grid_innercorner = (*(theta+i)) - 0.5 * (*(szy+i)); theta_grid_outercorner = (*(theta+i)) + 0.5 * (*(szy+i)); #endif //if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max)) { #if GEOMETRY == SPHERICAL { ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta } #else { //using FLASH ph_dens_calc=(4.0/3.0)*(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2, } #endif (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc //printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc); //sum up all the densities to get total number of photons ph_tot+=(*(ph_dens+j)); j++; } } if (ph_tot>max_photons) { //if the number of photons is too big make ph_weight larger ph_weight_adjusted*=10; } else if (ph_tot<min_photons) { ph_weight_adjusted*=0.5; } //printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot); } //printf("%d\n", ph_tot); //allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid (*ph)=malloc (ph_tot * sizeof (struct photon )); p_comv=malloc(4*sizeof(double)); boost=malloc(3*sizeof(double)); l_boost=malloc(4*sizeof(double)); //go through blocks and assign random energies/locations to proper number of photons ph_tot=0; k=0; for (i=0;i<array_length;i++) { #if GEOMETRY == CARTESIAN r_grid_innercorner = pow((*(x+i) - *(szx+i)/2.0) * ((*(x+i) - *(szx+i)/2.0))+(*(y+i) - *(szy+i)/2.0) * (*(y+i) - *(szy+i)/2.0),0.5); r_grid_outercorner = pow((*(x+i) + *(szx+i)/2.0) * ((*(x+i) + *(szx+i)/2.0))+(*(y+i) + *(szy+i)/2.0) * (*(y+i) + *(szy+i)/2.0),0.5); theta_grid_innercorner = acos( (*(y+i) - *(szx+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner theta_grid_outercorner = acos( (*(y+i) + *(szx+i)/2.0) /r_grid_outercorner); #elif GEOMETRY == SPHERICAL r_grid_innercorner = (*(r+i)) - 0.5 * (*(szx+i)); r_grid_outercorner = (*(r+i)) + 0.5 * (*(szx+i)); theta_grid_innercorner = (*(theta+i)) - 0.5 * (*(szy+i)); theta_grid_outercorner = (*(theta+i)) + 0.5 * (*(szy+i)); #endif //if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) ) if ((rmin <= r_grid_outercorner) && (r_grid_innercorner <= rmax ) && (theta_grid_outercorner >= theta_min) && (theta_grid_innercorner <= theta_max)) { //*(temps+i)=0.76*(*(temps+i)); for(j=0;j<( *(ph_dens+k) ); j++ ) { //have to get random frequency for the photon comoving frequency y_dum=1; //initalize loop yfr_dum=0; while (y_dum>yfr_dum) { fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz //printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i))); y_dum=gsl_rng_uniform_pos(rand); //printf("%lf ",fr_dum); if (spect=='w') { yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum } else { fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency } //printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum); } //printf("i: %d freq:%lf\n ",ph_tot, fr_dum); position_phi=gsl_rng_uniform(rand)*2*M_PI; com_v_phi=gsl_rng_uniform(rand)*2*M_PI; com_v_theta=acos((gsl_rng_uniform(rand)*2)-1); //printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta); //populate 4 momentum comoving array *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT; *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi); *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi); *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta); //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code... *(boost+0)=-1*(*(vx+i))*cos(position_phi); *(boost+1)=-1*(*(vx+i))*sin(position_phi); *(boost+2)=-1*(*(vy+i)); //boost to lab frame lorentzBoost(boost, p_comv, l_boost, 'p', fPtr); //printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3)); (*ph)[ph_tot].p0=(*(l_boost+0)); (*ph)[ph_tot].p1=(*(l_boost+1)); (*ph)[ph_tot].p2=(*(l_boost+2)); (*ph)[ph_tot].p3=(*(l_boost+3)); (*ph)[ph_tot].comv_p0=(*(p_comv+0)); (*ph)[ph_tot].comv_p1=(*(p_comv+1)); (*ph)[ph_tot].comv_p2=(*(p_comv+2)); (*ph)[ph_tot].comv_p3=(*(p_comv+3)); //place photons in rand positions within fluid element #if GEOMETRY == CARTESIAN position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0; //choose between -size/2 to size/2 (*ph)[ph_tot].r0= (*(x+i)+position_rand)*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi (*ph)[ph_tot].r1=(*(x+i)+position_rand)*sin(position_phi) ; position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0; (*ph)[ph_tot].r2=(*(y+i)+position_rand); //y coordinate in flash becomes z coordinate in MCRaT #elif GEOMETRY == SPHERICAL position_rand=gsl_rng_uniform_pos(rand)*(*(szx+i))-(*(szx+i))/2.0; //choose between -size/2 to size/2 position2_rand=gsl_rng_uniform_pos(rand)*(*(szy+i))-(*(szy+i))/2.0; (*ph)[ph_tot].r0= (*(r+i)+position_rand)*sin(*(theta+i)+position2_rand)*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi (*ph)[ph_tot].r1=(*(r+i)+position_rand)*sin(*(theta+i)+position2_rand)*sin(position_phi) ; (*ph)[ph_tot].r2=(*(r+i)+position_rand)*cos(*(theta+i)+position2_rand); //y coordinate in flash becomes z coordinate in MCRaT #endif (*ph)[ph_tot].s0=1; //initalize stokes parameters as non polarized photon, stokes parameterized are normalized such that I always =1 (*ph)[ph_tot].s1=0; (*ph)[ph_tot].s2=0; (*ph)[ph_tot].s3=0; (*ph)[ph_tot].num_scatt=0; (*ph)[ph_tot].weight=ph_weight_adjusted; (*ph)[ph_tot].nearest_block_index=0; (*ph)[ph_tot].type=INJECTED_PHOTON; //i for injected //printf("%d\n",ph_tot); ph_tot++; } k++; } } *ph_num=ph_tot; //save number of photons //printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num); free(ph_dens); free(p_comv);free(boost); free(l_boost); } void lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr) { //function to perform lorentz boost //if doing boost for an electron last argument is 'e' and there wont be a check for zero norm //if doing boost for a photon last argument is 'p' and there will be a check for zero norm double beta=0, gamma=0, *boosted_p=NULL; gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector /* fprintf(fPtr,"Boost: %e, %e, %e, %e\n",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2)); fflush(fPtr); fprintf(fPtr,"4 Momentum to Boost: %e, %e, %e, %e\n",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3)); fflush(fPtr); */ //if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost if (gsl_blas_dnrm2(&b.vector) > 0) { //fprintf(fPtr,"in If\n"); //fflush(fPtr); beta=gsl_blas_dnrm2(&b.vector); gamma=1.0/sqrt(1-pow(beta, 2.0)); //fprintf(fPtr,"Beta: %e\tGamma: %e\n",beta,gamma ); //fflush(fPtr); //initalize matrix values gsl_matrix_set(lambda1, 0,0, gamma); gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma); gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma); gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma); gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*(gsl_vector_get(&b.vector,0)*gsl_vector_get(&b.vector,0))/(beta*beta) ) ); gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/(beta*beta) ) )); gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/(beta*beta) ) )); gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*(gsl_vector_get(&b.vector,1)*gsl_vector_get(&b.vector,1))/(beta*beta) ) ); gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2))/(beta*beta) ) ); gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*(gsl_vector_get(&b.vector,2)*gsl_vector_get(&b.vector,2))/(beta*beta) ) ); gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1)); gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2)); gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3)); gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2)); gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3)); gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3)); gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime ); /* fprintf(fPtr,"Lorentz Boost Matrix 0: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 1: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 2: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3)); fflush(fPtr); fprintf(fPtr,"Lorentz Boost Matrix 3: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3)); fflush(fPtr); fprintf(fPtr,"Before Check: %e %e %e %e\n ",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3)); fflush(fPtr); */ //double check vector for 0 norm condition if photon if (object == 'p') { //fprintf(fPtr,"In if\n"); boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0)); } else { boosted_p=gsl_vector_ptr(p_ph_prime, 0); } /* fprintf(fPtr,"After Check: %e %e %e %e\n ", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) ); fflush(fPtr); * */ } else { /* fprintf(fPtr,"in else"); fflush(fPtr); * */ //double check vector for 0 norm condition if (object=='p') { boosted_p=zeroNorm(p_ph); } else { //if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost boosted_p=gsl_vector_ptr(&p.vector, 0); } } //assign values to result *(result+0)=*(boosted_p+0); *(result+1)=*(boosted_p+1); *(result+2)=*(boosted_p+2); *(result+3)=*(boosted_p+3); //free up memory //free(boosted_p); gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime); } double *zeroNorm(double *p_ph) { //ensures zero norm condition of photon 4 monetum is held int i=0; double normalizing_factor=0; gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) ) { normalizing_factor=(gsl_blas_dnrm2(&p.vector )); //fprintf(fPtr,"in zero norm if\n"); //fflush(fPtr); //go through and correct 4 momentum assuming the energy is correct *(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0)); *(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0)); *(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0)); } /* if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) ) { printf("This isnt normalized in the function\nThe difference is: %e\n", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) ); } */ //normalized within a factor of 10^-53 return p_ph; } int findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z) { double dist=0, dist_min=1e15, block_dist=0; int min_index=0, j=0; dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved block_dist=3e9; while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist { for(j=0;j<array_num;j++) { //if the distance between them is within 3e9, to restrict number of possible calculations, calulate the total distance between the box and photon #if DIMENSIONS == 2 if ((fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist)) { dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)) , 2.0),0.5); //fprintf(fPtr,"Dist calculated as: %e, index: %d\n", dist, j); //printf("In outer if statement, OLD: %e, %d\n", dist_min, min_index); if((dist<dist_min)) { //fprintf(fPtr,"In innermost if statement, OLD: %e, %d\n", dist_min, min_index); dist_min=dist; //save new minimum distance min_index=j; //save index //printf("New Min dist: %e, New min Index: %d, Array_Num: %d\n", dist_min, min_index, array_num); } } #elif DIMENSIONS == 3 if ((fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist) && (fabs(ph_z- (*(z+j)))<block_dist)) { dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)),2.0 ) + pow(ph_z- (*(z+j)) , 2.0),0.5); if((dist<dist_min)) { //printf("In innermost if statement, OLD: %e, %d\n", dist_min, min_index); dist_min=dist; //save new minimum distance min_index=j; //save index //fprintf(fPtr,"New Min dist: %e, New min Index: %d, Array_Num: %e\n", dist_min, min_index, array_num); } } #endif } block_dist*=10; //increase size of accepted distances for gris points, if dist_min==1e12 then the next time the acceptance range wil be larger } return min_index; } int findContainingBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int old_block_index, int find_block_switch, FILE *fPtr) { int i=0, within_block_index=0; bool is_in_block=0; //boolean to determine if the photon is outside of a grid //can parallelize here to save time? for (i=0;i<array_num;i++) { is_in_block=checkInBlock(i, ph_x, ph_y, ph_z, x, y, z, szx, szy); if (is_in_block) { within_block_index=i; //change for loop index once the block is found so the code doesnt search the rest of the grids to see if the photon is within those grids i=array_num; } } //printf("Within Block Index: %d\n",within_block_index); //if ((strcmp(DIM_SWITCH, dim_3d_str)==0) || (riken_switch==1)) #if SIM_SWITCH == RIKEN || DIMENSIONS == 3 { fprintf(fPtr, "3D switch is: %d and SIM switch is: %d\n", DIMENSIONS, SIM_SWITCH); } #endif if (is_in_block==0) { fprintf(fPtr, "Couldn't find a block that the photon is in\nx: %e y:%e\n", ph_x, ph_y); fflush(fPtr); within_block_index=-1; } return within_block_index; } int checkInBlock(int block_index, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy) { bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block double x0=0, x1=0, x2=0, sz_x0=0, sz_x1=0, sz_x2=0; //coordinate and sizes of grid block, in cartesian its x,y,z in spherical its r,theta,phi int return_val=0; //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { #if GEOMETRY == SPHERICAL { x0=pow(pow((*(x+block_index)),2.0)+pow((*(y+block_index)),2.0), 0.5); //radius x1=atan2((*(x+block_index)), (*(y+block_index))); //theta sz_x0=(*(szx+block_index)); sz_x1=(*(szy+block_index)); //pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) atan2(ph_x, ph_y) is_in_block= (2*fabs( ph_x - x0)- sz_x0 <= 0) && (2*fabs(ph_y - x1 ) - sz_x1 <= 0); //ph_x is ph_r for this geometry } #else { x0=(*(x+block_index)); x1=(*(y+block_index)); sz_x0=(*(szx+block_index)); sz_x1=(*(szy+block_index)); is_in_block= (2*fabs(ph_x-x0)-sz_x0 <= 0) && (2*fabs(ph_y-x1)-sz_x1 <= 0); } #endif } #endif /* else { if (riken_switch==1) { x0=pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5); x1=acos((*(z+block_index))/pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5)); x2=atan2((*(y+block_index)), (*(x+block_index))); sz_x0=(*(szy+block_index)); sz_x1=(*(szx+block_index)); sz_x2=(*(szx+block_index)); is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0)+pow(ph_z, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(acos(ph_z/pow(pow(ph_x, 2.0) + pow(ph_y,2.0 ) + pow(ph_z , 2.0),0.5)) - x1 ) <= sz_x1/2.0) && (fabs(atan2(ph_y, ph_x) - x2 ) <= sz_x2/2.0); //not sure why the code was going to this line above here for spherical test } } */ if (is_in_block) { return_val=1; } else { return_val=0; } return return_val; } int findNearestPropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double hydro_domain_x, double hydro_domain_y, double epsilon_b, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\ double *temp, double *all_time_steps, int *sorted_indexes, gsl_rng * rand, int find_nearest_block_switch, FILE *fPtr) { int i=0, min_index=0, ph_block_index=0, num_thread=1, thread_id=0; double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, ph_r=0, ph_theta=0; double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates double ph_v_norm=0, fl_v_norm=0, synch_x_sect=0; double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0 ; double rnd_tracker=0, n_dens_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0; #if defined(_OPENMP) num_thread=omp_get_num_threads(); //default is one above if theres no openmp usage #endif bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block int index=0, num_photons_find_new_element=0; double mfp=0,min_mfp=0, beta=0; double el_p[4]; double ph_p_comv[4], ph_p[4], fluid_beta[3]; //initialize gsl random number generator fo each thread const gsl_rng_type *rng_t; gsl_rng **rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); rng[0]=rand; //#pragma omp parallel for num_threads(nt) for(i=1;i<num_thread;i++) { rng[i] = gsl_rng_alloc (rng_t); gsl_rng_set(rng[i],gsl_rng_get(rand)); } //go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away //can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius //or just parallelize this part here min_mfp=1e12; #pragma omp parallel for num_threads(num_thread) firstprivate( is_in_block, ph_block_index, ph_x, ph_y, ph_z, ph_phi, ph_r, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker, ph_p_comv, el_p, ph_p, fluid_beta) private(i) shared(min_mfp ) reduction(+:num_photons_find_new_element) for (i=0;i<num_ph; i++) { //fprintf(fPtr, "%d, %d,%e\n", i, ((ph+i)->nearest_block_index), ((ph+i)->weight)); //fflush(fPtr); if (find_nearest_block_switch==0) { ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault here } else { ph_block_index=0; // therefore if starting a new frame set index=0 to avoid this issue } //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { #if GEOMETRY == SPHERICAL ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to 2d spherical coordinate ph_y=((ph+i)->r2); ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5); ph_theta=acos(ph_y/ph_r); //this is actually theta in this context ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0)); #elif GEOMETRY == CARTESIAN ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate (2d cartesian hydro coordinates) ph_y=((ph+i)->r2); ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0)); ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5); #endif } #else { ph_x=((ph+i)->r0); ph_y=((ph+i)->r1); ph_z=((ph+i)->r2); ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5); } #endif //printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y); //if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded // absorbed photons have ph_block_index=-1, therefore if this value is not less than 0, calulate the mfp properly but doesnt work when go to new frame and find new indexes (will change b/c will get rid of these photons when printing) //alternatively make decision based on 0 weight if (((ph_y<hydro_domain_y) && (ph_x<hydro_domain_x)) && ((ph+i)->nearest_block_index != -1) ) //can use sorted index to see which photons have been absorbed efficiently before printing and get the indexes { #if GEOMETRY == SPHERICAL is_in_block=checkInBlock(ph_block_index, ph_r, ph_theta, ph_z, x, y, z, szx, szy); #elif GEOMETRY == CARTESIAN is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy); #endif //when rebinning photons can have comoving 4 momenta=0 and nearest_block_index=0 (and block 0 be the actual block the photon is in making it not refind the proper index and reclaulate the comoving 4 momenta) which can make counting synch scattered photons be thrown off, thus take care of this case by forcing the function to recalc things #if SYNCHROTRON_SWITCH == ON if ((ph_block_index==0) && ( ((ph+i)->comv_p0)+((ph+i)->comv_p1)+((ph+i)->comv_p2)+((ph+i)->comv_p3) == 0 ) ) { is_in_block=0; //say that photon is not in the block, force it to recompute things } #endif if (find_nearest_block_switch==0 && is_in_block) { //keep the saved grid index min_index=ph_block_index; } else { //find the new index of the block closest to the photon //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh //find the new index of the block that the photon is actually in #if DIMENSIONS == 2 { #if GEOMETRY == SPHERICAL min_index=findContainingBlock(array_num, ph_r, ph_theta, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr); #elif GEOMETRY == CARTESIAN min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr); #endif } #endif if (min_index != -1) { (ph+i)->nearest_block_index=min_index; //save the index if min_index != -1 //also recalculate the photons' comoving frequency in this new fluid element ph_p[0]=((ph+i)->p0); ph_p[1]=((ph+i)->p1); ph_p[2]=((ph+i)->p2); ph_p[3]=((ph+i)->p3); //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { fluid_beta[0]=(*(velx+min_index))*cos(ph_phi); fluid_beta[1]=(*(velx+min_index))*sin(ph_phi); fluid_beta[2]=(*(vely+min_index)); } #else { fluid_beta[0]=(*(velx+min_index)); fluid_beta[1]=(*(vely+min_index)); fluid_beta[2]=(*(velz+min_index)); } #endif lorentzBoost(&fluid_beta, &ph_p, &ph_p_comv, 'p', fPtr); ((ph+i)->comv_p0)=ph_p_comv[0]; ((ph+i)->comv_p1)=ph_p_comv[1]; ((ph+i)->comv_p2)=ph_p_comv[2]; ((ph+i)->comv_p3)=ph_p_comv[3]; num_photons_find_new_element+=1; } else { fprintf(fPtr, "Photon number %d FLASH index not found, making sure it doesnt scatter.\n", i); } } //if min_index!= -1 (know which fluid element photon is in) do all this stuff, otherwise make sure photon doesnt scatter if (min_index != -1) { //fprintf(fPtr,"Min Index: %d\n", min_index); //save values (n_dens_lab_tmp)= (*(dens_lab+min_index)); (n_vx_tmp)= (*(velx+min_index)); (n_vy_tmp)= (*(vely+min_index)); (n_temp_tmp)= (*(temp+min_index)); //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { (n_vz_tmp)= (*(velz+min_index)); } #endif //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { fl_v_x=(*(velx+min_index))*cos(ph_phi); fl_v_y=(*(velx+min_index))*sin(ph_phi); fl_v_z=(*(vely+min_index)); } #else { fl_v_x=(*(velx+min_index)); fl_v_y=(*(vely+min_index)); fl_v_z=(*(velz+min_index)); } #endif fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5); ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5); //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { beta=pow((n_vx_tmp*n_vx_tmp)+(n_vy_tmp*n_vy_tmp),0.5); } #else { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5); } #endif *(ph_p+0)=((ph+i)->p0); *(ph_p+1)=((ph+i)->p1); *(ph_p+2)=((ph+i)->p2); *(ph_p+3)=((ph+i)->p3); //ph_p_comv[0]=((ph+i)->comv_p0); //ph_p_comv[1]=((ph+i)->comv_p1); //ph_p_comv[2]=((ph+i)->comv_p2); //ph_p_comv[3]=((ph+i)->comv_p3); //printf("ph: p0 %e p1 %e p2 %e p3 %e\n", *(ph_p_comv+0), *(ph_p_comv+1), *(ph_p_comv+2), *(ph_p_comv+3)); //singleElectron(&el_p[0], n_temp_tmp, &ph_p_comv[0], rng[omp_get_thread_num()], fPtr); //get random electron //printf("after singleElectron n_temp_tmp %e from ptr %e n_dens_tmp %e from ptr %e\n", n_temp_tmp, (*(temp+min_index)), n_dens_tmp, (*(dens+min_index))); //printf("Chosen el: p0 %e p1 %e p2 %e p3 %e\nph: p0 %e p1 %e p2 %e p3 %e\n", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3), *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3)); //synch_x_sect=synCrossSection(n_dens_tmp/M_P, n_temp_tmp, ph_p_comv[0]*C_LIGHT/PL_CONST, sqrt((el_p[0]*el_p[0]/(M_EL*M_EL*C_LIGHT*C_LIGHT))-1), epsilon_b); //printf("i: %d flash_array_idx %d synch_x_sect %e freq %e temp %e el_dens %e\n", i, min_index, synch_x_sect, *(ph_p+0)*C_LIGHT/PL_CONST, n_temp_tmp, n_dens_tmp/M_P); //if (synch_x_sect==0) //{ //*(will_scatter+i)=1; //this photon will scatter b/c probability of absorption=0 //} /* else { if (gsl_rng_uniform_pos(rng[omp_get_thread_num()])>(THOM_X_SECT/(THOM_X_SECT+synch_x_sect))) { //this photon will be absorbed *(will_scatter+i)=0; } else { *(will_scatter+i)=1; } } photons can onlt scatter now */ //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case rnd_tracker=0; #if defined(_OPENMP) thread_id=omp_get_thread_num(); #endif rnd_tracker=gsl_rng_uniform_pos(rng[thread_id]); //printf("Rnd_tracker: %e Thread number %d \n",rnd_tracker, omp_get_thread_num() ); //mfp=(-1)*log(rnd_tracker)*(M_P/((n_dens_tmp))/(THOM_X_SECT)); ///(1.0-beta*((n_cosangle)))) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths DO EVERYTHING IN COMOV FRAME NOW mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOM_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //if (mfp/C_LIGHT < 1e-100) //{ // fprintf("Photon %d has a mfp of %d\n", i, mfp); // exit(0); //} } else { mfp=min_mfp; } } else { mfp=min_mfp; //fprintf(fPtr,"Photon %d In ELSE\n", i); //exit(0); } *(all_time_steps+i)=mfp/C_LIGHT; } //exit(0); //free rand number generator for (i=1;i<num_thread;i++) { gsl_rng_free(rng[i]); } free(rng); //printf("HERE\n"); for (i=0;i<num_ph;i++) { *(sorted_indexes+i)= i; //save indexes to array to use in qsort } //printf("before QSORT\n"); #if (defined _GNU_SOURCE || defined __GNU__ || defined __linux__) qsort_r(sorted_indexes, num_ph, sizeof (int), compare2, all_time_steps); #elif (defined __APPLE__ || defined __MACH__ || defined __DARWIN__ || defined __FREEBSD__ || defined __BSD__ || defined OpenBSD3_1 || defined OpenBSD3_9) qsort_r(sorted_indexes, num_ph, sizeof (int), all_time_steps, compare); #else #error Cannot detect operating system #endif //for (i=0;i<num_ph;i++) //{ // fprintf(fPtr, "Qsort: %d GSL: %d\n", *(sorted_indexes_2+i), *(sorted_indexes+i)); //} //exit(0); //print number of times we had to refind the index of the elemtn photons were located in if (find_nearest_block_switch!=0) { num_photons_find_new_element=0; //force this to be 0 since we forced MCRaT to find the indexes for all the photons here } //fprintf(fPtr, "MCRat had to refind where %d photons were located in the grid\n", num_photons_find_new_element); //(*time_step)=*(all_time_steps+(*(sorted_indexes+0))); //dont need to return index b/c photonEvent doesnt use this, but mcrat.c uses this info //index= *(sorted_indexes+0);//first element of sorted array //free(el_p);free(ph_p_comv); return num_photons_find_new_element; } int compare (void *ar, const void *a, const void *b) { //from https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/ int aa = *(int *) a; int bb = *(int *) b; double *arr=NULL; arr=ar; //printf("%d, %d\n", aa, bb); //printf("%e, %e\n", arr[aa] , arr[bb]); //return (aa - bb); /* if (arr[aa] < arr[bb]) return -1; if (arr[aa] == arr[bb]) return 0; if (arr[aa] > arr[bb]) return 1; */ return ((arr[aa] > arr[bb]) - (arr[aa] < arr[bb])); } int compare2 ( const void *a, const void *b, void *ar) { //have 2 compare funcions b/c of changes in qsort_r between BSD and GNU //from https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/ int aa = *(int *) a; int bb = *(int *) b; double *arr=NULL; arr=ar; //printf("%d, %d\n", aa, bb); //printf("%e, %e\n", arr[aa] , arr[bb]); //return (aa - bb); /* if (arr[aa] < arr[bb]) return -1; if (arr[aa] == arr[bb]) return 0; if (arr[aa] > arr[bb]) return 1; */ return ((arr[aa] > arr[bb]) - (arr[aa] < arr[bb])); } int interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\ double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int find_nearest_block_switch, FILE *fPtr) { /* * THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW, not used */ int i=0, j=0, min_index=0, ph_block_index=0, thread_id=0; int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4]; double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0; double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates double r=0, theta=0; double ph_v_norm=0, fl_v_norm=0; double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0; double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0; int num_thread=2;//omp_get_max_threads(); bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block int index=0; double mfp=0,min_mfp=0, beta=0; //initialize gsl random number generator fo each thread const gsl_rng_type *rng_t; gsl_rng **rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); rng[0]=rand; //#pragma omp parallel for num_threads(nt) for(i=1;i<num_thread;i++) { rng[i] = gsl_rng_alloc (rng_t); gsl_rng_set(rng[i],gsl_rng_get(rand)); } //go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away //can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius //or just parallelize this part here min_mfp=1e12; #pragma omp parallel for num_threads(num_thread) firstprivate( r, theta,dv, v, all_adjacent_block_indexes, j, left_block_index, right_block_index, top_block_index, bottom_block_index, is_in_block, ph_block_index, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp ) for (i=0;i<num_ph; i++) { //printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1)); if (find_nearest_block_switch==0) { ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault } else { ph_block_index=0; //if starting a new frame set index=0 to avoid this issue } //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate ph_y=((ph+i)->r2); ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0)); } #else { ph_x=((ph+i)->r0); ph_y=((ph+i)->r1); ph_z=((ph+i)->r2); } #endif //printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y); is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy); if (find_nearest_block_switch==0 && is_in_block) { //keep the saved grid index min_index=ph_block_index; } else { //find the new index of the block closest to the photon //min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh //find the new index of the block that the photon is actually in min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, ph_block_index, find_nearest_block_switch, fPtr); (ph+i)->nearest_block_index=min_index; //save the index } //look for the blocks surounding the block of interest and order them by the left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved right_dist_min=1e15; top_dist_min=1e15; bottom_dist_min=1e15; for (j=0;j<array_num;j++) { //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)) , 2.0),0.5); } #else { dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)),2.0 ) + pow((*(z+min_index))- (*(z+j)) , 2.0),0.5); } #endif if ((*(x+j))<(*(x+min_index)) && (dist < left_dist_min) ) { left_block_index=j; left_dist_min=dist; } else if ((*(x+j))>(*(x+min_index)) && (dist < right_dist_min)) { right_block_index=j; right_dist_min=dist; } if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) ) { bottom_block_index=j; bottom_dist_min=dist; } else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) ) { top_block_index=j; top_dist_min=dist; } } all_adjacent_block_indexes[0]=left_block_index; all_adjacent_block_indexes[1]=right_block_index; all_adjacent_block_indexes[2]=bottom_block_index; all_adjacent_block_indexes[3]=top_block_index; //do a weighted average of the 4 nearest grids based on volume v=0; (n_dens_lab_tmp)=0; (n_vx_tmp)= 0; (n_vy_tmp)= 0; (n_temp_tmp)= 0; (n_vz_tmp)= 0; for (j=0;j<4;j++) { #if SIM_SWITCH == RIKEN { r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5); theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j]))); dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ; } #else { //using FLASH dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ; } #endif v+=dv; //save values (n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv; (n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv; (n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv; (n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv; //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { (n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv; } #endif } //fprintf(fPtr,"Outside\n"); //save values (n_dens_lab_tmp)/= v; (n_vx_tmp)/= v; (n_vy_tmp)/= v; (n_temp_tmp)/= v; //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { (n_vz_tmp)/= v; } #endif //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { fl_v_x=n_vx_tmp*cos(ph_phi); fl_v_y=n_vx_tmp*sin(ph_phi); fl_v_z=n_vy_tmp; } #else { fl_v_x=n_vx_tmp; fl_v_y=n_vy_tmp; fl_v_z=n_vz_tmp; } #endif fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5); ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5); //(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product (n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5); } #else { beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5); } #endif //put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case rnd_tracker=0; #if defined(_OPENMP) thread_id=omp_get_thread_num(); #endif rnd_tracker=gsl_rng_uniform_pos(rng[thread_id]); mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOM_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths #pragma omp critical if ( mfp<min_mfp) { min_mfp=mfp; n_dens_lab_min= n_dens_lab_tmp; n_vx_min= n_vx_tmp; n_vy_min= n_vy_tmp; //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { n_vz_min= n_vz_tmp; } #endif n_temp_min= n_temp_tmp; index=i; //fprintf(fPtr, "Thread is %d. new min: %e for photon %d with block properties: %e, %e, %e Located at: %e, %e, Dist: %e\n", omp_get_thread_num(), mfp, index, n_vx_tmp, n_vy_tmp, n_temp_tmp, *(x+min_index), *(y+min_index), dist_min); //fflush(fPtr); #pragma omp flush(min_mfp) } } //free rand number generator for (i=1;i<num_thread;i++) { gsl_rng_free(rng[i]); } free(rng); *(n_dens_lab)= n_dens_lab_min; *(n_vx)= n_vx_min; *(n_vy)= n_vy_min; //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { *(n_vz)= n_vz_min; } #endif *(n_temp)= n_temp_min; (*time_step)=min_mfp/C_LIGHT; return index; } void updatePhotonPosition(struct photon *ph, int num_ph, double t, FILE *fPtr) { //move photons by speed of light int i=0; #if defined(_OPENMP) int num_thread=omp_get_num_threads(); #endif double old_position=0, new_position=0, divide_p0=0; #pragma omp parallel for num_threads(num_thread) firstprivate(old_position, new_position, divide_p0) for (i=0;i<num_ph;i++) { if (((ph+i)->type != SYNCHROTRON_POOL_PHOTON) && ((ph+i)->weight != 0)) { old_position= pow( pow((ph+i)->r0,2)+pow((ph+i)->r1,2)+pow((ph+i)->r2,2), 0.5 ); //uncommented checks since they were not necessary anymore divide_p0=1.0/((ph+i)->p0); ((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position ((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y ((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z new_position= pow( pow((ph+i)->r0,2)+pow((ph+i)->r1,2)+pow((ph+i)->r2,2), 0.5 ); /* if ((new_position-old_position)/t > C_LIGHT) { fprintf(fPtr, "PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\n", i, ((new_position-old_position)/t)/C_LIGHT); } */ //if ( (ph+i)->s0 != 1) { // fprintf(fPtr, "PHOTON NUMBER %d DOES NOT HAVE I=1. Instead it is: %e\n", i, (ph+i)->s0); } //printf("In update function: %e, %e, %e, %e, %e, %e, %e\n",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) ); } } //printf("In update function: %e, %e, %e, %e\n",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) ); } void mullerMatrixRotation(double theta, double *s, FILE *fPtr) { //makes a CCW rotation od the stokes parameters when the photon velocity vector is pointed towards the observer, follows Lundman gsl_matrix *M= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do rotation as defined in McMaster 1961 (has it to rotate CW in that paper) gsl_vector *result= gsl_vector_alloc(4); gsl_vector_view stokes; stokes=gsl_vector_view_array(s, 4); //fprintf(fPtr, "sokes parameter before= %e %e %e %e\n", gsl_vector_get(&stokes.vector, 0), gsl_vector_get(&stokes.vector, 1), gsl_vector_get(&stokes.vector, 2), gsl_vector_get(&stokes.vector, 3)); gsl_matrix_set(M, 0,0,1); gsl_matrix_set(M, 3,3,1); gsl_matrix_set(M, 1,1,cos(2*theta)); gsl_matrix_set(M, 2,2,cos(2*theta)); gsl_matrix_set(M, 1,2,-1*sin(2*theta)); gsl_matrix_set(M, 2,1,sin(2*theta)); gsl_blas_dgemv(CblasNoTrans, 1, M, &stokes.vector, 0, result); //Ms=s //fprintf(fPtr, "stokes parameter after= %e %e %e %e\n\n", gsl_vector_get(result, 0), gsl_vector_get(result, 1), gsl_vector_get(result, 2), gsl_vector_get(result, 3)); //save back to the original stokes vector *(s+0)=gsl_vector_get(result, 0); *(s+1)=gsl_vector_get(result, 1); *(s+2)=gsl_vector_get(result, 2); *(s+3)=gsl_vector_get(result, 3); gsl_vector_free(result); gsl_matrix_free (M); } void findXY(double *v_ph, double *vector, double *x, double *y) { //finds the stokes plane coordinate x,y axis for the photon velocity with respect to some reference vector //assumes that pointers point to array of 3 doubles in length double norm=0; *(y+0)= ((*(v_ph+1))*(*(vector+2))-(*(v_ph+2))*(*(vector+1))); *(y+1)= -1*((*(v_ph+0))*(*(vector+2))-(*(v_ph+2))*(*(vector+0))); *(y+2)= ((*(v_ph+0))*(*(vector+1))-(*(v_ph+1))*(*(vector+0))); // vector X v_ph norm=1.0/sqrt( (*(y+0))*(*(y+0)) + (*(y+1))*(*(y+1)) + (*(y+2))*(*(y+2))); *(y+0) *= norm; *(y+1) *= norm; *(y+2) *= norm; *(x+0)= (*(y+1))*(*(v_ph+2))-(*(y+2))*(*(v_ph+1)); *(x+1)= -1*((*(y+0))*(*(v_ph+2))-(*(y+2))*(*(v_ph+0))); *(x+2)= (*(y+0))*(*(v_ph+1))-(*(y+1))*(*(v_ph+0)); norm=1.0/sqrt( (*(x+0))*(*(x+0)) + (*(x+1))*(*(x+1)) + (*(x+2))*(*(x+2))); *(x+0) *= norm; *(x+1) *= norm; *(x+2) *= norm; } double findPhi(double *x_old, double *y_old, double *x_new, double *y_new) { //find the angle to rotate the stokes vector to transform from one set of stokes coordinates to another //this is given by Lundman gsl_vector_view y=gsl_vector_view_array(y_old, 3); gsl_vector_view x=gsl_vector_view_array(x_old, 3); gsl_vector_view y_prime=gsl_vector_view_array(y_new, 3); gsl_vector_view x_prime=gsl_vector_view_array(x_new, 3); double factor=0, dot_prod_result=0; gsl_blas_ddot(&x.vector, &y_prime.vector, &dot_prod_result); if (dot_prod_result>0) { factor=1; } else if (dot_prod_result<0) { factor=-1; } else { factor=0; } gsl_blas_ddot(&y.vector, &y_prime.vector, &dot_prod_result); if ((dot_prod_result<-1) || (dot_prod_result>1)) { //printf("The old dot poduct was %e, the new one is %e\n",dot_prod_result, round(dot_prod_result)); dot_prod_result=round(dot_prod_result);//do this rounding so numerical error that causes value to be <-1 or >1 gets rounded and becomes a real value if its close enough to these limits } return -1*factor*acos(dot_prod_result); } void stokesRotation(double *v, double *v_ph, double *v_ph_boosted, double *s, FILE *fPtr) { //takes 3 velocities of the initial photon, v_ph, the boosted photon, v_ph_boosted. and the boost vector, v double z_hat[3]={0,0,1}; //z to calulate stokes double x[3]={0,0,0}, y[3]={0,0,0}, x_new[3]={0,0,0}, y_new[3]={0,0,0};//initalize arrays to hold stokes coordinate system double phi=0; //if (i==0) { //find stokes coordinate sys in orig frame with respect to z axis findXY(v_ph, &z_hat, &x, &y); } //find stokes coordinate sys in orig frame with respect to boost vector findXY(v_ph, v, &x_new, &y_new); phi=findPhi(x, y, x_new, y_new);//now find rotation between the two coordinate systems //rotate the stokes vector now to put it in the coordinate system fo the boosted photon and the boost evctor mullerMatrixRotation(phi, s, fPtr); /* if ( isnan(*(s+0)) || isnan(*(s+1)) || isnan(*(s+2)) || isnan(*(s+3)) ) { printf("A stokes value is nan\n\n"); } */ //find the new coordinates of the rotated stokes vector with the boosted photon and the boost vector findXY(v_ph_boosted, v, &x, &y); //find stokes coordinate sys in orig frame with respect to z axis findXY(v_ph_boosted, &z_hat, &x_new, &y_new); phi=findPhi(x, y, x_new, y_new);//now find rotation between the two coordinate systems //do the rotation of the stokes vector to put it in the coordinate system of the boosted photon and the z axis mullerMatrixRotation(phi, s, fPtr); /* if ( isnan(*(s+0)) || isnan(*(s+1)) || isnan(*(s+2)) || isnan(*(s+3)) ) { printf("A stokes value is nan\n\n"); } */ } double photonEvent(struct photon *ph, int num_ph, double dt_max, double *all_time_steps, int *sorted_indexes, double *all_flash_vx, double *all_flash_vy, double *all_flash_vz, double *all_fluid_temp, int *scattered_ph_index, int *frame_scatt_cnt, int *frame_abs_cnt, gsl_rng * rand, FILE *fPtr) { //function to perform single photon scattering int i=0, index=0, ph_index=0, event_did_occur=0; //variable event_did_occur is to keep track of wether a scattering or absorption actually occured or not, double scatt_time=0, old_scatt_time=0; //keep track of new time to scatter vs old time to scatter to know how much to incrementally propagate the photons if necessary double phi=0, theta=0; //phi and theta for the 4 momentum double ph_phi=0, flash_vx=0, flash_vy=0, flash_vz=0, fluid_temp=0; double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector double *s=malloc(4*sizeof(double)); //vector to hold the stokes parameters for a given photon i=0; old_scatt_time=0; event_did_occur=0; //fprintf(fPtr,"In this function Num_ph %d\n", num_ph); //fflush(fPtr); while (i<num_ph && event_did_occur==0 ) { ph_index=(*(sorted_indexes+i)); scatt_time= *(all_time_steps+ph_index); //get the time until the photon scatters //IF THE TIME IS GREATER THAN dt_max dont let the photons positions be updated if (scatt_time<dt_max) { updatePhotonPosition(ph, num_ph, scatt_time-old_scatt_time, fPtr); //fprintf(fPtr,"i: %d, Photon: %d, Delta t=%e\n", i, ph_index, scatt_time-old_scatt_time); //fflush(fPtr); //if the photon should scatter then do so, will_scatter==1 //if (*(will_scatter+ph_index) != 0 ) ont need b/c all photns are able to scatter and none can be explicitly absorbed //{ //WHAT IF THE PHOTON MOVES TO A NEW BLOCK BETWEEN WHEN WE CALC MFP AND MOVE IT TO DO THE SCATTERING???? //it mostly happens at low optical depth, near the photosphere so we would have a large mfp anyways so we probably wouldn't be in this function in that case index=(ph+ph_index)->nearest_block_index; //the sorted_indexes gives index of photon with smallest time to potentially scatter then extract the index of the block closest to that photon flash_vx=*(all_flash_vx+ index); flash_vy=*(all_flash_vy+ index); fluid_temp=*(all_fluid_temp+ index); //if (strcmp(DIM_SWITCH, dim_3d_str)==0) #if DIMENSIONS == 3 { flash_vz=*(all_flash_vz+ index); } #endif ph_phi=atan2(((ph+ph_index)->r1), (((ph+ph_index)->r0))); /* if (isnan((ph+ph_index)->r0) || isnan((ph+ph_index)->r1) || isnan((ph+ph_index)->r2)) { printf("Not a number\n"); } fprintf(fPtr,"ph_phi=%e\n", ph_phi); fflush(fPtr); */ //convert flash coordinated into MCRaT coordinates //printf("Getting fluid_beta\n"); //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { (*(fluid_beta+0))=flash_vx*cos(ph_phi); (*(fluid_beta+1))=flash_vx*sin(ph_phi); (*(fluid_beta+2))=flash_vy; } #else { (*(fluid_beta+0))=flash_vx; (*(fluid_beta+1))=flash_vy; (*(fluid_beta+2))=flash_vz; } #endif /* fprintf(fPtr,"FLASH v: %e, %e\n", flash_vx,flash_vy); fflush(fPtr); */ //fill in photon 4 momentum //printf("filling in 4 momentum in photonScatter for photon index %d\n", ph_index); //if ((ph+ph_index)->type == SYNCHROTRON_POOL_PHOTON) { //printf("The scattering photon is a seed photon w/ comv freq %e Hz.\n", ((ph+ph_index)->comv_p0)*C_LIGHT/PL_CONST); //*nu_c_scatt=((ph+ph_index)->comv_p0)*C_LIGHT/PL_CONST;//dont need this anymore b/c the SYNCHROTRON_POOL_PHOTON photon doesnt move from its cell } *(ph_p+0)=((ph+ph_index)->p0); *(ph_p+1)=((ph+ph_index)->p1); *(ph_p+2)=((ph+ph_index)->p2); *(ph_p+3)=((ph+ph_index)->p3); *(ph_p_comov+0)=((ph+ph_index)->comv_p0); *(ph_p_comov+1)=((ph+ph_index)->comv_p1); *(ph_p_comov+2)=((ph+ph_index)->comv_p2); *(ph_p_comov+3)=((ph+ph_index)->comv_p3); //fill in stokes parameters *(s+0)=((ph+ph_index)->s0); //I ==1 *(s+1)=((ph+ph_index)->s1); //Q/I *(s+2)=((ph+ph_index)->s2); //U/I *(s+3)=((ph+ph_index)->s3); //V/I /* fprintf(fPtr,"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\nStokes params %e %e %e %e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2), *(s+0), *(s+1), *(s+2), *(s+3)); fflush(fPtr); fprintf(fPtr,"Fluid Beta: %e, %e, %e\n", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2)); fflush(fPtr); */ //first we bring the photon to the fluid's comoving frame //lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr); //*(ph_p_comov+0)=((ph+ph_index)->comv_p0); //*(ph_p_comov+1)=((ph+ph_index)->comv_p1); //*(ph_p_comov+2)=((ph+ph_index)->comv_p2); //*(ph_p_comov+3)=((ph+ph_index)->comv_p3); /* fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3); fflush(fPtr); fprintf(fPtr, "Before Scattering, In Comov_frame:\n"); fflush(fPtr); fprintf(fPtr, "ph_comov: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); fflush(fPtr); */ //fprintf(fPtr, "Theta: %e Phi %e Lab: x_tilde: %e, %e, %e, y_tilde: %e %e %e\n", theta, phi, *(x_tilde+0), *(x_tilde+1), *(x_tilde+2), *(y_tilde+0), *(y_tilde+1), *(y_tilde+2)); //then rotate the stokes plane by some angle such that we are in the stokes coordinat eystsem after the lorentz boost //if (STOKES_SWITCH != 0) #if STOKES_SWITCH == ON { stokesRotation(fluid_beta, (ph_p+1), (ph_p_comov+1), s, fPtr); } #endif //exit(0); //second we generate a thermal electron at the correct temperature singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr); //fprintf(fPtr,"el_comov: %e, %e, %e,%e\n", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3)); //fflush(fPtr); //third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function event_did_occur=singleScatter(el_p_comov, ph_p_comov, s, rand, fPtr); //fprintf(fPtr,"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); //fflush(fPtr); //event_did_occur=0; if (event_did_occur==1) { //fprintf(fPtr,"Within the if!\n"); //fflush(fPtr); //if the scattering occured have to uodate the phtoon 4 momentum. if photon didnt scatter nothing changes //fourth we bring the photon back to the lab frame *(negative_fluid_beta+0)=-1*( *(fluid_beta+0)); *(negative_fluid_beta+1)=-1*( *(fluid_beta+1)); *(negative_fluid_beta+2)=-1*( *(fluid_beta+2)); lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr); //fprintf(fPtr,"Scattered Photon in Lab frame: %e, %e, %e,%e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3)); //fflush(fPtr); #if STOKES_SWITCH == ON { stokesRotation(negative_fluid_beta, (ph_p_comov+1), (ph_p+1), s, fPtr); //rotate to boost back to lab frame //save stokes parameters ((ph+ph_index)->s0)= *(s+0); //I ==1 ((ph+ph_index)->s1)= *(s+1); ((ph+ph_index)->s2)= *(s+2); ((ph+ph_index)->s3)= *(s+3); } #endif if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4) { fprintf(fPtr,"Extremely High Photon Energy!!!!!!!!\n"); fflush(fPtr); } //fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3); //fprintf(fPtr, "Old: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3)); //assign the photon its new lab 4 momentum ((ph+ph_index)->p0)=(*(ph_p+0)); ((ph+ph_index)->p1)=(*(ph_p+1)); ((ph+ph_index)->p2)=(*(ph_p+2)); ((ph+ph_index)->p3)=(*(ph_p+3)); //assign it the comoving frame 4 momentum ((ph+ph_index)->comv_p0)=(*(ph_p_comov+0)); ((ph+ph_index)->comv_p1)=(*(ph_p_comov+1)); ((ph+ph_index)->comv_p2)=(*(ph_p_comov+2)); ((ph+ph_index)->comv_p3)=(*(ph_p_comov+3)); //printf("Done assigning values to original struct\n"); //incremement that photons number of scatterings ((ph+ph_index)->num_scatt)+=1; *frame_scatt_cnt+=1; //incrememnt total number of scatterings } } else { // if the photon scatt_time > dt_max //have to adjust the time properly so that the time si now appropriate for the next frame scatt_time=dt_max; updatePhotonPosition(ph, num_ph, scatt_time-old_scatt_time, fPtr); event_did_occur=1; //set equal to 1 to get out of the loop b/c other subsequent photons will have scatt_time > dt_max } old_scatt_time=scatt_time; i++; } //exit(0); *scattered_ph_index=ph_index; //save the index of the photon that was scattered //fprintf(fPtr,"scattered_ph_index: %d %d\n", *scattered_ph_index, (*(sorted_indexes+i-1))); //fflush(fPtr); free(el_p_comov); free(ph_p_comov); free(fluid_beta); free(negative_fluid_beta); free(ph_p); free(s); ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL; //retrun total time elapsed to scatter a photon return scatt_time; } void singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr) { //generates an electron with random energy double factor=0, gamma=0; double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0; gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum gsl_vector *result=gsl_vector_alloc (3); //fprintf(fPtr, "Temp in singleElectron: %e\n", temp); if (temp>= 1e7) { //printf("In if\n"); factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0)); y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities f_x_dum=0; while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) ) { x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor); beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5); y_dum=gsl_rng_uniform(rand)/2.0; f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); // //fprintf(fPtr,"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\n", x_dum, f_x_dum, y_dum); } gamma=x_dum; } else { //printf("In else\n"); factor=pow(K_B*temp/M_EL,0.5); //calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of "factor" gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5); //each vel direction is normal distribution -> maxwellian when multiplied } //fprintf(fPtr,"Chosen Gamma: %e\n",gamma); beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5); //printf("Beta is: %e in singleElectron\n", beta); phi=gsl_rng_uniform(rand)*2*M_PI; y_dum=1; //initalize loop to get a random theta f_x_dum=0; while (y_dum>f_x_dum) { y_dum=gsl_rng_uniform(rand)*1.3; x_dum=gsl_rng_uniform(rand)*M_PI; f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum))); } theta=x_dum; //fprintf(fPtr,"Beta: %e\tPhi: %e\tTheta: %e\n",beta,phi, theta); //fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *(el_p+0)=gamma*(M_EL)*(C_LIGHT); *(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta); *(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi); *(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi); //printf("Old: %e, %e, %e,%e\n", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3)); el_p_prime=gsl_vector_view_array((el_p+1), 3); //find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) ); //printf("Calculated Photon phi and theta in singleElectron:%e, %e\n", ph_phi, ph_theta); //fill in rotation matrix to rotate around x axis to get rid of phi angle gsl_matrix_set(rot, 1,1,1); gsl_matrix_set(rot, 2,2,cos(ph_theta)); gsl_matrix_set(rot, 0,0,cos(ph_theta)); gsl_matrix_set(rot, 0,2,-sin(ph_theta)); gsl_matrix_set(rot, 2,0,sin(ph_theta)); gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2)); printf("Middle: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2)); */ gsl_matrix_set_all(rot,0); gsl_matrix_set(rot, 0,0,1); gsl_matrix_set(rot, 1,1,cos(-ph_phi)); gsl_matrix_set(rot, 2,2,cos(-ph_phi)); gsl_matrix_set(rot, 1,2,-sin(-ph_phi)); gsl_matrix_set(rot, 2,1,sin(-ph_phi)); gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2)); printf("Final EL_P_vec: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2)); */ gsl_matrix_free (rot);gsl_vector_free(result); } int singleScatter(double *el_comov, double *ph_comov, double *s, gsl_rng * rand, FILE *fPtr) { //This routine performs a scattering between a photon and a moving electron. int i=0, scattering_occured=0; double dotprod_1; //to test orthogonality double *z_axis_electron_rest_frame=malloc(3*sizeof(double)); //basis vector of the z axis in the elctron rest frame double *el_v=malloc(3*sizeof(double)); double *negative_el_v=malloc(3*sizeof(double)); double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation double *el_p_prime=malloc(4*sizeof(double)); double phi0=0, phi1=0, phi=0, theta=0; double y_dum, f_x_dum, x_dum; double x_tilde[3]={0,0,0}, y_tilde[3]={0,0,0}, x_tilde_new[3]={0,0,0}, y_tilde_new[3]={0,0,0};//initalize arrays to hold stokes coordinate system gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations gsl_matrix *rot1= gsl_matrix_calloc (3, 3); gsl_matrix *scatt= gsl_matrix_calloc (4, 4); //fano's matrix for scattering stokes parameters gsl_vector *scatt_result=gsl_vector_alloc (4); gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations gsl_vector *result1=gsl_vector_alloc (3); gsl_vector *result=gsl_vector_alloc (4); gsl_vector *whole_ph_p=gsl_vector_alloc (4); gsl_vector *ph_p_orig=gsl_vector_alloc (4) ;//vector to hold the original incoming photon velocity vector in the electron rest frame gsl_vector_view ph_p ;//create vector to hold comoving photon and electron 4 momentum gsl_vector_view el_p ; gsl_vector_view stokes, test, test_x, test_y; /* Dont need these vectors anymore, plus didnt have code to free allocations so it was causing memory leaks gsl_vector *result0_x=gsl_vector_alloc (3); //vectors to hold results of rotations for stokes coordinates gsl_vector *result1_x=gsl_vector_alloc (3); gsl_vector *result0_y=gsl_vector_alloc (3); //vectors to hold results of rotations for stokes coordinates gsl_vector *result1_y=gsl_vector_alloc (3); */ //fill in z-axis basis vector *(z_axis_electron_rest_frame+0)=0; *(z_axis_electron_rest_frame+1)=0; *(z_axis_electron_rest_frame+2)=1; /* was for testing against Kraw *(s+0)=1; //should be 1.0 *(s+1)=1; *(s+2)=0; *(s+3)=0; *(ph_comov+0)=PL_CONST*1e12/C_LIGHT; *(ph_comov+1)=0; //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product *(ph_comov+2)=0; *(ph_comov+3)=PL_CONST*1e12/C_LIGHT; theta=85*M_PI/180; phi=0; dotprod_1=pow(1-(pow(100, -2.0)) ,0.5); *(el_comov+0)=100*M_EL*C_LIGHT; *(el_comov+1)=100*M_EL*C_LIGHT*dotprod_1*sin(theta)*cos(phi); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product *(el_comov+2)=100*M_EL*C_LIGHT*dotprod_1*sin(theta)*sin(phi); *(el_comov+3)=100*M_EL*C_LIGHT*dotprod_1*cos(theta); */ //fill in electron velocity array and photon 4 momentum *(el_v+0)=(*(el_comov+1))/(*(el_comov+0)); *(el_v+1)=(*(el_comov+2))/(*(el_comov+0)); *(el_v+2)=(*(el_comov+3))/(*(el_comov+0)); //printf("el_v: %e, %e, %e\n", *(el_v+0), *(el_v+1), *(el_v+2)); //lorentz boost into frame where the electron is stationary lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr); lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr); //printf("New ph_p in electron rest frame: %e, %e, %e,%e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //rotate 'stokes plane' //if (STOKES_SWITCH != 0) #if STOKES_SWITCH == ON { stokesRotation(el_v, (ph_comov+1), (ph_p_prime+1), s, fPtr); stokes=gsl_vector_view_array(s, 4); } #endif //printf(fPtr, "y_tilde: %e, %e, %e\n", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2)); ph_p=gsl_vector_view_array((ph_p_prime+1), 3); el_p=gsl_vector_view_array(el_p_prime,4); gsl_vector_set(ph_p_orig, 0, *(ph_p_prime+0)); gsl_vector_set(ph_p_orig, 1, *(ph_p_prime+1)); gsl_vector_set(ph_p_orig, 2, *(ph_p_prime+2)); gsl_vector_set(ph_p_orig, 3, *(ph_p_prime+3)); //gsl_blas_ddot(&y_tilde_rot.vector, &ph_p.vector, &dotprod_1); //fprintf(fPtr, "After lorentz boost Angle between the y_tilde_rot and the photon velocity vector is: %e\n", acos(dotprod_1/ gsl_blas_dnrm2(&ph_p.vector))*180/M_PI); phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) ); //fprintf(fPtr,"Photon Phi: %e\n", phi0); //rotate the axes so that the photon incomes along the x-axis gsl_matrix_set(rot0, 2,2,1); gsl_matrix_set(rot0, 0,0,cos(-phi0)); gsl_matrix_set(rot0, 1,1,cos(-phi0)); gsl_matrix_set(rot0, 0,1,-sin(-phi0)); gsl_matrix_set(rot0, 1,0,sin(-phi0)); gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0); //printf("Before Scatter rot0: stokes x=(%e, %e, %e) y=(%e, %e, %e)", gsl_vector_get(result0_x,0), gsl_vector_get(result0_x,1), gsl_vector_get(result0_x,2), gsl_vector_get(result0_y,0), gsl_vector_get(result0_y,1), gsl_vector_get(result0_y,2)); //fprintf(fPtr, "y_tilde: %e, %e, %e y_tilde_rot_result: %e, %e, %e\n", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2), gsl_vector_get(y_tilde_rot_result,0), gsl_vector_get(y_tilde_rot_result,1), gsl_vector_get(y_tilde_rot_result,2)); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2)); */ //set values of ph_p_prime equal to the result and get new phi from result *(ph_p_prime+1)=gsl_vector_get(result0,0); *(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now? *(ph_p_prime+3)=gsl_vector_get(result0,2); phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0)); //printf("rotation 1: %e, %e, %e\n", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //fprintf(fPtr, "Photon Phi: %e\n", phi1); //printf("make sure the vector view is good: %e, %e, %e,%e\n", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2)); //rotate around y to bring it all along x gsl_matrix_set(rot1, 1,1,1); gsl_matrix_set(rot1, 0,0,cos(-phi1)); gsl_matrix_set(rot1, 2,2,cos(-phi1)); gsl_matrix_set(rot1, 0,2,-sin(-phi1)); gsl_matrix_set(rot1, 2,0,sin(-phi1)); gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1); //fprintf(fPtr, "y_tilde: %e, %e, %e y_tilde_rot vector view: %e, %e, %e\n", *(y_tilde+0), *(y_tilde+1), *(y_tilde+2), gsl_vector_get(&y_tilde_rot.vector,0), gsl_vector_get(&y_tilde_rot.vector,1), gsl_vector_get(&y_tilde_rot.vector,2)); /* printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2)); */ //set values of ph_p_prime equal to the result and get new phi from result *(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy? *(ph_p_prime+2)=gsl_vector_get(result1,1); *(ph_p_prime+3)=0; //just directly setting it to 0 now? //printf("rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //know that the stokes y axis is in -y_hat direction and stokes x asis is in the z_hat direction due to rotations and making inclimg photn come along x_hat direction, dont need to rotate the stokes plane/vector. this happens as the rotations occur (tested in python code) //double checking here //printf("Before Scatter: stokes x=(%e, %e, %e) y=(%e, %e, %e) ph_p=(%e, %e, %e, %e)\n", gsl_vector_get(result1_x,0), gsl_vector_get(result1_x,1), gsl_vector_get(result1_x,2), gsl_vector_get(result1_y,0), gsl_vector_get(result1_y,1), gsl_vector_get(result1_y,2), *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //determine if the scattering will occur between photon and electron //scattering_occured=comptonScatter(&theta, &phi, rand, fPtr); //determine the angles phi and theta for the photon to scatter into using thompson differential cross section scattering_occured=kleinNishinaScatter(&theta, &phi, *(ph_p_prime+0), *(s+1), *(s+2), rand, fPtr);//determine the angles phi and theta for the photon to scatter into using KN differential cross section, if the photon will end up scattering //fprintf(fPtr,"Phi: %e, Theta: %e\n", phi, theta); //theta=2.4475668271885342; //phi=4.014719957630734; //*(s+0)=1; //should be 1.0 //*(s+1)=1; //*(s+2)=0; //*(s+3)=0; if (scattering_occured==1) { //perform scattering and compute new 4-momenta of electron and photon //scattered photon 4 momentum gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); // scattered energy of photon gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) ); gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) );//assume phi is clockwise from z to y gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) ); //fprintf(fPtr, "New ph_p0=%e Old= %e\n", gsl_vector_get(result,0), *(ph_p_prime+0)); //gsl_vector_fprintf(fPtr,result, "%e" ); //recalc x_tilde from rotation about y by angle theta do x_tilde=y_tilde X v_ph //test =gsl_vector_view_array(gsl_vector_ptr(result, 1), 3); //scatt_result is a dummy, dont need to change the stokes parameters here, just need to find the axis such that y is out of the plane of k_o-k see Ito figure 12 in polarized emission from stratisfied jets //gsl_blas_ddot(&y_tilde_rot.vector, &test.vector, &dotprod_1); //fprintf(fPtr, "Angle between the y_tilde_rot and the photon velocity vector is: %e\n", acos(dotprod_1/ gsl_blas_dnrm2(&test.vector))*180/M_PI); //gsl_vector_fprintf(fPtr,&y_tilde_rot.vector, "%e" ); //gsl_vector_fprintf(fPtr,&x_tilde_rot.vector, "%e" ); //exit(0); //calculate electron 4 momentum //prescattered photon 4 momentum gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0))); gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1))); gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2))); gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3))); gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon gsl_vector_add(&el_p.vector ,whole_ph_p); /* printf("After scattering:\n"); printf("el_p: %e, %e, %e,%e\n", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3)); printf("ph_p: %e, %e, %e,%e\n", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3)); */ //rotate back to comoving frame *(ph_p_prime+0)=gsl_vector_get(result,0); *(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product *(ph_p_prime+2)=gsl_vector_get(result,2); *(ph_p_prime+3)=gsl_vector_get(result,3); gsl_matrix_set_all(rot1,0); gsl_matrix_set(rot1, 1,1,1); gsl_matrix_set(rot1, 0,0,cos(-phi1)); gsl_matrix_set(rot1, 2,2,cos(-phi1)); gsl_matrix_set(rot1, 0,2,sin(-phi1)); gsl_matrix_set(rot1, 2,0,-sin(-phi1)); gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1); /* printf("Photon Phi: %e\n", phi1); printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2)); */ //set values of ph_p_prime to result1 from undoing 2nd rotation *(ph_p_prime+1)=gsl_vector_get(result1,0); *(ph_p_prime+2)=gsl_vector_get(result1,1); *(ph_p_prime+3)=gsl_vector_get(result1,2); //printf("Undo rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //ignore the electron, dont care about it, undo the first rotation gsl_matrix_set_all(rot0,0); gsl_matrix_set(rot0, 2,2,1); gsl_matrix_set(rot0, 0,0,cos(-phi0)); gsl_matrix_set(rot0, 1,1,cos(-phi0)); gsl_matrix_set(rot0, 0,1,sin(-phi0)); gsl_matrix_set(rot0, 1,0,-sin(-phi0)); gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0); /* printf("Photon Phi: %e\n", phi0); printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2)); printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2)); printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2)); */ //do the scattering of the stokes vector //rotate it by phi and then scatter it and rotate back and then renormalize it such that i=1 //if (STOKES_SWITCH != 0) #if STOKES_SWITCH == ON { //orient the stokes coordinate system such that its perpendicular to the scattering plane findXY(gsl_vector_ptr(ph_p_orig, 1),z_axis_electron_rest_frame, x_tilde, y_tilde); findXY(gsl_vector_ptr(result0,0),gsl_vector_ptr(ph_p_orig, 1), x_tilde_new, y_tilde_new); phi=findPhi(x_tilde, y_tilde, x_tilde_new, y_tilde_new); mullerMatrixRotation(phi, s, fPtr); //find the theta between the incoming and scattered photons, by doing dot product and taking arccos of it theta=acos((gsl_vector_get(ph_p_orig,1)*gsl_vector_get(result0,0)+gsl_vector_get(ph_p_orig,2)*gsl_vector_get(result0,1)+gsl_vector_get(ph_p_orig,3)*gsl_vector_get(result0,2) )/(gsl_vector_get(ph_p_orig,0)*(*(ph_p_prime+0))) ); //do the scattering of the stokes parameters gsl_matrix_set(scatt, 0,0,1.0+pow(cos(theta), 2.0)+((1-cos(theta))*(gsl_vector_get(ph_p_orig,0) - gsl_vector_get(result,0))/(M_EL*C_LIGHT ) ) ); //following lundman's matrix gsl_matrix_set(scatt, 0,1, sin(theta)*sin(theta)); gsl_matrix_set(scatt, 1,0, sin(theta)*sin(theta)); gsl_matrix_set(scatt, 1,1,1.0+cos(theta)*cos(theta)); gsl_matrix_set(scatt, 2,2, 2.0*cos(theta)); gsl_matrix_set(scatt, 3,3, 2.0*cos(theta)+ ((cos(theta))*(1-cos(theta))*(gsl_vector_get(ph_p_orig,0) - gsl_vector_get(result,0))/(M_EL*C_LIGHT )) ); //gsl_matrix_scale(scatt, (gsl_vector_get(result,0)/(*(ph_p_prime+0)))*((gsl_vector_get(result,0)/(*(ph_p_prime+0))))*0.5*3*THOM_X_SECT/(8*M_PI) ); //scale the matrix by 0.5*r_0^2 (\epsilon/\epsilon_0)^2 DONT NEED THIS BECAUSE WE NORMALIZE STOKES VECTOR SO THIS CANCELS ITSELF OUT gsl_blas_dgemv(CblasNoTrans, 1, scatt, &stokes.vector, 0, scatt_result); /* fprintf(fPtr,"before s: %e, %e, %e,%e\n", gsl_vector_get(&stokes.vector,0), gsl_vector_get(&stokes.vector,1), gsl_vector_get(&stokes.vector,2), gsl_vector_get(&stokes.vector,3)); fprintf(fPtr,"Scatt Matrix 0: %e,%e, %e, %e\n", gsl_matrix_get(scatt, 0,0), gsl_matrix_get(scatt, 0,1), gsl_matrix_get(scatt, 0,2), gsl_matrix_get(scatt, 0,3)); fprintf(fPtr,"Scatt Matrix 1: %e,%e, %e, %e\n", gsl_matrix_get(scatt, 1,0), gsl_matrix_get(scatt, 1,1), gsl_matrix_get(scatt, 1,2), gsl_matrix_get(scatt, 1,3)); fprintf(fPtr,"Scatt Matrix 2: %e,%e, %e, %e\n", gsl_matrix_get(scatt, 2,0), gsl_matrix_get(scatt, 2,1), gsl_matrix_get(scatt, 2,2), gsl_matrix_get(scatt, 2,3)); fprintf(fPtr,"Scatt Matrix 3: %e,%e, %e, %e\n", gsl_matrix_get(scatt, 3,0), gsl_matrix_get(scatt, 3,1), gsl_matrix_get(scatt, 3,2), gsl_matrix_get(scatt, 3,3)); fprintf(fPtr,"s: %e, %e, %e,%e\n", gsl_vector_get(scatt_result,0), gsl_vector_get(scatt_result,1), gsl_vector_get(scatt_result,2), gsl_vector_get(scatt_result,3)); */ //normalize and rotate back *(s+0)=gsl_vector_get(scatt_result,0)/gsl_vector_get(scatt_result,0); //should be 1.0 *(s+1)=gsl_vector_get(scatt_result,1)/gsl_vector_get(scatt_result,0); *(s+2)=gsl_vector_get(scatt_result,2)/gsl_vector_get(scatt_result,0); *(s+3)=gsl_vector_get(scatt_result,3)/gsl_vector_get(scatt_result,0); //fprintf(fPtr,"s after norm: %e, %e, %e,%e\n", gsl_vector_get(&stokes.vector,0), gsl_vector_get(&stokes.vector,1), gsl_vector_get(&stokes.vector,2), gsl_vector_get(&stokes.vector,3)); //need to find current stokes coordinate system defined in the plane of k-k_0 findXY(gsl_vector_ptr(result0,0),gsl_vector_ptr(ph_p_orig, 1), x_tilde, y_tilde); //then find the new coordinate system between scattered photon 4 onetum and the z axis findXY(gsl_vector_ptr(result0,0),z_axis_electron_rest_frame, x_tilde_new, y_tilde_new); //find phi to transform between the two coodinate systems phi=findPhi(x_tilde, y_tilde, x_tilde_new, y_tilde_new); //do the rotation mullerMatrixRotation(phi, s, fPtr); } #endif //now update the array with the new scattered photon 4 monetum *(ph_p_prime+1)=gsl_vector_get(result0,0); *(ph_p_prime+2)=gsl_vector_get(result0,1); *(ph_p_prime+3)=gsl_vector_get(result0,2); //gsl_blas_ddot(&y_tilde_rot.vector, &ph_p.vector, &dotprod_1); //fprintf(fPtr, "Angle between the y_tilde_rot and the photon velocity vector is: %e\n", acos(dotprod_1/ gsl_blas_dnrm2(&ph_p.vector))*180/M_PI); //printf("Undo rotation 1: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3)); //deboost photon to lab frame *(negative_el_v+0)=(-1*(*(el_v+0))); *(negative_el_v+1)=(-1*(*(el_v+1))); *(negative_el_v+2)=(-1*(*(el_v+2))); lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr); //printf("Undo boost 1: %e, %e, %e, %e\n", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3)); //dont need to find stokes vector and do previosu rotations, can just find the stokes coordinates in function because the stokes coordinate vectors rotate with the photon vector and no rotations to a new stokes coordinate system are needed //if (STOKES_SWITCH != 0) #if STOKES_SWITCH == ON { stokesRotation(negative_el_v, (ph_p_prime+1), (ph_comov+1), s, fPtr); } #endif //exit(0); } gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_matrix_free(scatt);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result); gsl_vector_free(scatt_result);gsl_vector_free(ph_p_orig); gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v); free(z_axis_electron_rest_frame); return scattering_occured; } int comptonScatter(double *theta, double *phi, gsl_rng * rand, FILE *fPtr) { double y_dum, f_x_dum, x_dum; //generate random theta and phi angles for scattering *phi=gsl_rng_uniform(rand)*2*M_PI; //printf("Phi: %e\n", phi); y_dum=1; //initalize loop to get a random theta f_x_dum=0; while (y_dum>f_x_dum) { y_dum=gsl_rng_uniform(rand)*1.09; x_dum=gsl_rng_uniform(rand)*M_PI; f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2)); } *theta=x_dum; return 1; } int kleinNishinaScatter(double *theta, double *phi, double p0, double q, double u, gsl_rng * rand, FILE *fPtr) { //sample theta using: https://doi.org/10.13182/NSE11-57 double phi_dum=0, cos_theta_dum=0, f_phi_dum=0, f_cos_theta_dum=0, f_theta_dum=0, phi_y_dum=0, cos_theta_y_dum=0, KN_x_section_over_thomson_x_section=0, rand_num=0; double mu=0, phi_norm=0, phi_max=0, norm=0; int will_scatter=0; double energy_ratio= p0/(M_EL*C_LIGHT ); //h*nu / mc^2 , units of p0 is erg/c //determine the KN cross section over the thomson cross section From RYBICKI AND LIGHTMAN pg 197 KN_x_section_over_thomson_x_section= (3.0/4.0)*( ( ((1+energy_ratio)/ pow(energy_ratio,3.0))*(((2*energy_ratio)*(1+energy_ratio)/(1+2*energy_ratio)) - log(1+2*energy_ratio))) + (log(1+2*energy_ratio)/(2*energy_ratio)) - ((1+3*energy_ratio)/pow((1+2*energy_ratio),2.0)) ); rand_num=gsl_rng_uniform(rand); if ((rand_num<= KN_x_section_over_thomson_x_section) || (p0 < 1e-2*(M_EL*C_LIGHT ) )) { //include last condition so low energy seed phtoons can scatter (as they should under thompson scattering), calculating KN_x_section_over_thomson_x_section incurs numerical error at very low frequencies //fprintf(fPtr,"In If!\n"); //fflush(fPtr); //sample a theta and phi from the differential cross sections phi_y_dum=1; //initalize loop to get a random phi and theta cos_theta_y_dum=1; f_cos_theta_dum=0; f_phi_dum=0; while ((cos_theta_y_dum>f_cos_theta_dum)) { //do phi and theta seperately, sample theta using: https://doi.org/10.13182/NSE11-57 cos_theta_y_dum=gsl_rng_uniform(rand)*2; cos_theta_dum=gsl_rng_uniform(rand)*2-1; f_cos_theta_dum=pow((1+energy_ratio*(1-cos_theta_dum)),-2)*(energy_ratio*(1-cos_theta_dum)+(1/(1+energy_ratio*(1-cos_theta_dum))) + cos_theta_dum*cos_theta_dum); } *theta=acos(cos_theta_dum); mu=1+energy_ratio*(1-cos(*theta)); f_theta_dum=(pow(mu, -1.0) + pow(mu, -3.0) - pow(mu, -2.0)*pow(sin(*theta), 2.0))*sin(*theta); while ((phi_y_dum>f_phi_dum) ) { #if STOKES_SWITCH == OFF { //not considering polarization therefore can jjst sample between 0 and 2*pi evenly phi_dum=gsl_rng_uniform(rand)*2*M_PI; phi_y_dum=-1; // this is to exit the while statement //fprintf(fPtr," phi_dum: %e\n", phi_dum); //fflush(fPtr); } #else { if (u==0 && q==0) { phi_dum=gsl_rng_uniform(rand)*2*M_PI; phi_y_dum=-1; // this is to exit the while statement } else { //if we are considering polarization calulate the norm for the distributiion to be between 1 and 0 phi_max=abs(atan2(-u,q))/2.0; norm=(f_theta_dum + pow(mu, -2.0)*pow(sin(*theta), 3.0) * (q*cos(2*phi_max)-u*sin(2*phi_max))); //fprintf(fPtr,"norm: %e\n", norm); //fflush(fPtr); phi_y_dum=gsl_rng_uniform(rand); phi_dum=gsl_rng_uniform(rand)*2*M_PI; f_phi_dum=(f_theta_dum + pow(mu, -2.0)*pow(sin(*theta), 3.0) * (q*cos(2*phi_dum)-u*sin(2*phi_dum)))/norm; //signs on q and u based on Lundman/ McMaster //fprintf(fPtr,"phi_y_dum: %e, theta_dum: %e, mu: %e, f_theta_dum: %e, phi_dum: %e, f_phi_dum: %e, u: %e, q: %e\n", phi_y_dum, theta_dum, mu, f_theta_dum, phi_dum, f_phi_dum, u, q); //fflush(fPtr); } } #endif } *phi=phi_dum; will_scatter=1; } else { will_scatter=0; } return will_scatter; } double averagePhotonEnergy(struct photon *ph, int num_ph) { //to calculate weighted photon energy in ergs int i=0; #if defined(_OPENMP) int num_thread=omp_get_num_threads(); #endif double e_sum=0, w_sum=0; #pragma omp parallel for reduction(+:e_sum) reduction(+:w_sum) for (i=0;i<num_ph;i++) { #if SYNCHROTRON_SWITCH == ON if (((ph+i)->weight != 0)) //dont want account for null or absorbed OLD_COMPTONIZED_PHOTON photons #endif { e_sum+=(((ph+i)->p0)*((ph+i)->weight)); w_sum+=((ph+i)->weight); } } return (e_sum*C_LIGHT)/w_sum; } void phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg, FILE *fPtr ) { int temp_max=0, temp_min=INT_MAX, i=0, count=0, count_synch=0, count_comp=0, count_i=0; #if defined(_OPENMP) int num_thread=omp_get_num_threads(); #endif double sum=0, avg_r_sum=0, avg_r_sum_synch=0, avg_r_sum_comp=0, avg_r_sum_inject=0; //printf("Num threads: %d", num_thread); #pragma omp parallel for num_threads(num_thread) reduction(min:temp_min) reduction(max:temp_max) reduction(+:sum) reduction(+:avg_r_sum) reduction(+:count) for (i=0;i<ph_num;i++) { #if SYNCHROTRON_SWITCH == ON if (((ph+i)->weight != 0)) //dont want account for null or absorbed OLD_COMPTONIZED_PHOTON photons #endif { sum+=((ph+i)->num_scatt); avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5); //printf("%d %c %e %e %e %e %e %e\n", i, (ph+i)->type, (ph+i)->p0, (ph+i)->comv_p0, (ph+i)->r0, (ph+i)->r1, (ph+i)->r2, (ph+i)->num_scatt); if (((ph+i)->num_scatt) > temp_max ) { temp_max=((ph+i)->num_scatt); //printf("The new max is: %d\n", temp_max); } //if ((i==0) || (((ph+i)->num_scatt)<temp_min)) if (((ph+i)->num_scatt)<temp_min) { temp_min=((ph+i)->num_scatt); //printf("The new min is: %d\n", temp_min); } if (((ph+i)->type) == INJECTED_PHOTON ) { avg_r_sum_inject+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5); count_i++; } if ((((ph+i)->type) == COMPTONIZED_PHOTON) || (((ph+i)->type) == OLD_COMPTONIZED_PHOTON)) { avg_r_sum_comp+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5); count_comp++; } count++; } if (((ph+i)->type) == SYNCHROTRON_POOL_PHOTON ) { avg_r_sum_synch+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5); count_synch++; } } fprintf(fPtr, "In this frame Avg r for i type: %e c and o type: %e and s type: %e\n", avg_r_sum_inject/count_i, avg_r_sum_comp/count_comp, avg_r_sum_synch/count_synch); fflush(fPtr); //exit(0); *avg=sum/count; *r_avg=avg_r_sum/count; *max=temp_max; *min=temp_min; } void cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array) { double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2 int i=0; double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity; for (i=0; i<num_array;i++) { *(gamma+i)=gamma_infinity; *(vx+i)=0; *(vy+i)=vel; *(dens+i)=ddensity; *(dens_lab+i)=lab_dens; *(pres+i)=(A_RAD*pow(t_comov, 4.0))/(3); *(temp+i)=pow(3*(*(pres+i))/(A_RAD) ,1.0/4.0); //just assign t_comov } } void sphericalPrep(double *r, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr) { double gamma_infinity=100, lumi=1e52, r00=1e8; //shopuld be 10^57 //double gamma_infinity=5, lumi=1e52, r00=1e8; //shopuld be 10^57 double vel=0; int i=0; for (i=0;i<num_array;i++) { if ((*(r+i)) >= (r00*gamma_infinity)) { *(gamma+i)=gamma_infinity; *(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0)); } else { *(gamma+i)=(*(r+i))/r00; *(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(*(r+i), 4.0) ); } vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5); *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i))); *(dens_lab+i)=(*(dens+i))*(*(gamma+i)); *(temp+i)=pow(3*(*(pres+i))/(A_RAD) ,1.0/4.0); //fprintf(fPtr,"Gamma: %lf\nR: %lf\nPres: %e\nvel %lf\nX: %lf\nY %lf\nVx: %lf\nVy: %lf\nDens: %e\nLab_Dens: %e\nTemp: %lf\n", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i)); } } void structuredFireballPrep(double *r, double *theta, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr) { //This model is provided by Lundman, Peer, Ryde 2014, use this to compare our MCRaT polarization to their polarizations double gamma_0=100, lumi=1e52, r00=1e8, theta_j=1e-2, p=4; //theta_j in paper is 1e-2, 3e-2, 1e-1 and p is 1,2,4 double T_0=pow(lumi/(4*M_PI*r00*r00*A_RAD*C_LIGHT), 1.0/4.0); double eta=0, r_sat=0; double vel=0, theta_ratio=0; int i=0; for (i=0;i<num_array;i++) { theta_ratio=(*(theta+i))/theta_j; eta=gamma_0*pow(1+pow(theta_ratio, 2*p) , -0.5); if (*(theta+i) >= theta_j*pow(gamma_0/2, 1.0/p)) { //*(gamma+i)=2; //outside with of shear layer have gamma be 2 like in paper eta=2.0; } r_sat=eta*r00; if ((*(r+i)) >= r_sat) { *(gamma+i)=eta; *(temp+i)=T_0*pow(r_sat/(*(r+i)), 2.0/3.0)/eta; } else { *(gamma+i)=(*(r+i))/r_sat; //not sure if this is right but it shouldn't matter since we're injecting our photons far from r00 *(temp+i)=T_0; } vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5); *(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5); *(dens+i)=M_P*lumi/(4*M_PI*M_P*C_LIGHT*C_LIGHT*C_LIGHT*eta*vel*(*(gamma+i))*(*(r+i))*(*(r+i))); //equation paper has extra c, but then units dont work out *(dens_lab+i)=(*(dens+i))*(*(gamma+i)); *(pres+i)=(A_RAD*pow(*(temp+i), 4.0))/(3); //fprintf(fPtr,"eta: %lf\nr_sat: %lf\nGamma: %lf\nR: %lf\nTheta: %lf\nPres: %e\nvel %lf\nX: %lf\nY %lf\nVx: %lf\nVy: %lf\nDens: %e\nLab_Dens: %e\nTemp: %lf\n\n", eta, r_sat, *(gamma+i), *(r+i), (*(theta+i)), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i)); } } void dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, FILE *fPtr ) { //function to merge files in mcdir produced by various threads double *p0=NULL, *p1=NULL, *p2=NULL, *p3=NULL, *comv_p0=NULL, *comv_p1=NULL, *comv_p2=NULL, *comv_p3=NULL, *r0=NULL, *r1=NULL, *r2=NULL, *s0=NULL, *s1=NULL, *s2=NULL, *s3=NULL, *num_scatt=NULL, *weight=NULL; int i=0, j=0, k=0, isNotCorrupted=0, num_types=9; //just save lab 4 momentum, position and num_scatt by default int increment=1; char filename_k[2000]="", file_no_thread_num[2000]="", cmd[2000]="", mcdata_type[20]=""; char group[200]="", *ph_type=NULL; hid_t file, file_new, group_id, dspace; hsize_t dims[1]={0}; herr_t status, status_group; hid_t dset_p0, dset_p1, dset_p2, dset_p3, dset_comv_p0, dset_comv_p1, dset_comv_p2, dset_comv_p3, dset_r0, dset_r1, dset_r2, dset_s0, dset_s1, dset_s2, dset_s3, dset_num_scatt, dset_weight, dset_weight_frame, dset_ph_type; //printf("Merging files in %s\n", dir); //#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k) // i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for #if COMV_SWITCH == ON && STOKES_SWITCH == ON { num_types=17;//both switches on, want to save comv and stokes } #elif COMV_SWITCH == ON || STOKES_SWITCH == ON { num_types=13;//either switch acivated, just subtract 4 datasets } #else { num_types=9;//just save lab 4 momentum, position and num_scatt } #endif #if SAVE_TYPE == ON { num_types+=1; } #endif for (i=start_frame;i<last_frame;i=i+increment) { fprintf(fPtr, "Merging files for frame: %d\n", i); fflush(fPtr); #if SIM_SWITCH == RIKEN && DIMENSIONS == 3 if (i>=3000) { increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1 } #endif j=0; for (k=0;k<numprocs;k++) { //for each process' file, find out how many elements and add up to find total number of elements needed in the data set for the frame number snprintf(filename_k,sizeof(filename_k),"%s%s%d%s",dir,"mc_proc_", k, ".h5" ); //open the file file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT); //see if the frame exists snprintf(group,sizeof(group),"%d",i ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //if it does open it and read in the size if (status_group == 0) { //open the datatset group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_p0 = H5Dopen (group_id, "P0", H5P_DEFAULT); //open dataset //get the number of points dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims j+=dims[0];//calculate the total number of photons to save to new hdf5 file status = H5Sclose (dspace); status = H5Dclose (dset_p0); status = H5Gclose(group_id); } status = H5Fclose(file); } //for continuing if the simulation gets stopped, check to see if the new file exists and if the information is correct //if the information is incorrect, create file by overwriting it, otherwise dont need to do anything snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s%d%s",dir,"mcdata_", i, ".h5" ); status = H5Eset_auto(NULL, NULL, NULL); //turn off automatic error printing file_new=H5Fcreate(file_no_thread_num, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT); //see if the file initially does/doesnt exist status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); //turn on auto error printing if (file_new<0) { //fprintf(fPtr, "Checking File %s\n",file_no_thread_num ); //fflush(fPtr); //the file exists, open it with read write file_new=H5Fopen(file_no_thread_num, H5F_ACC_RDWR, H5P_DEFAULT); for (k=0;k<num_types;k++) { #if COMV_SWITCH == ON && STOKES_SWITCH == ON { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P1");break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P3"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S0"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S1");break; case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S2"); break; case 14: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S3"); break; case 15: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 16: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 17: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #elif STOKES_SWITCH == ON && COMV_SWITCH == OFF { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S0"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S1");break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S2"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "S3"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #elif STOKES_SWITCH == OFF && COMV_SWITCH == ON { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P1");break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "COMV_P3"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 10: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 11: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 12: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 13: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #else { switch (k) { case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break; case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break; case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break; case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break; case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break; case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break; case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break; case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break; case 8: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PW"); break; #if SAVE_TYPES == ON { case 9: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "PT"); break; } #endif } } #endif //open the datatset dset_p0 = H5Dopen (file_new, mcdata_type, H5P_DEFAULT); //open dataset //get the number of points dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims //fprintf(fPtr, "j:%d, dim: %d\n",j, dims[0] ); //fflush(fPtr); isNotCorrupted += fmod(dims[0], j); //if the dimension is the dame then the fmod ==0 (remainder of 0), if all datatsets are ==0 then you get a truth value of 0 meaning that it isnt corrupted status = H5Sclose (dspace); status = H5Dclose (dset_p0); } status = H5Fclose(file_new); file_new=-1; //do this so if the file exists it doesnt go into the rewriting portion if the file does exist } //fprintf(fPtr, "file %s has isNotCorrupted=%d\n", file_no_thread_num, isNotCorrupted ); //fflush(fPtr); //if the new file doesnt have the dimensions that it should, open it and write over the file, or if the file doesnt exist if ((file_new>=0) || (isNotCorrupted != 0 )) { //fprintf(fPtr, "In IF\n" ); //fflush(fPtr); if (isNotCorrupted != 0) { //if the data is corrupted overwrite the file file_new = H5Fcreate (file_no_thread_num, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); } //now allocate enough ememory for j number of points p0=malloc(j*sizeof(double)); p1=malloc(j*sizeof(double)); p2=malloc(j*sizeof(double)); p3=malloc(j*sizeof(double)); comv_p0=malloc(j*sizeof(double)); comv_p1=malloc(j*sizeof(double)); comv_p2=malloc(j*sizeof(double)); comv_p3=malloc(j*sizeof(double)); r0=malloc(j*sizeof(double)); r1=malloc(j*sizeof(double)); r2=malloc(j*sizeof(double)); s0=malloc(j*sizeof(double)); s1=malloc(j*sizeof(double)); s2=malloc(j*sizeof(double)); s3=malloc(j*sizeof(double)); num_scatt=malloc(j*sizeof(double)); weight=malloc(j*sizeof(double)); ph_type=malloc((j)*sizeof(char)); j=0; for (k=0;k<numprocs;k++) { //for each process open and read the contents of the dataset snprintf(filename_k,sizeof(filename_k),"%s%s%d%s",dir,"mc_proc_", k, ".h5" ); file=H5Fopen(filename_k, H5F_ACC_RDONLY, H5P_DEFAULT); snprintf(group,sizeof(group),"%d",i ); status = H5Eset_auto(NULL, NULL, NULL); status_group = H5Gget_objinfo (file, group, 0, NULL); status = H5Eset_auto(H5E_DEFAULT, H5Eprint2, stderr); if (status_group == 0) { //open the datatset group_id = H5Gopen2(file, group, H5P_DEFAULT); dset_p0 = H5Dopen (group_id, "P0", H5P_DEFAULT); //open dataset dset_p1 = H5Dopen (group_id, "P1", H5P_DEFAULT); dset_p2 = H5Dopen (group_id, "P2", H5P_DEFAULT); dset_p3 = H5Dopen (group_id, "P3", H5P_DEFAULT); #if COMV_SWITCH == ON { dset_comv_p0 = H5Dopen (group_id, "COMV_P0", H5P_DEFAULT); //open dataset dset_comv_p1 = H5Dopen (group_id, "COMV_P1", H5P_DEFAULT); dset_comv_p2 = H5Dopen (group_id, "COMV_P2", H5P_DEFAULT); dset_comv_p3 = H5Dopen (group_id, "COMV_P3", H5P_DEFAULT); } #endif dset_r0 = H5Dopen (group_id, "R0", H5P_DEFAULT); dset_r1 = H5Dopen (group_id, "R1", H5P_DEFAULT); dset_r2 = H5Dopen (group_id, "R2", H5P_DEFAULT); #if STOKES_SWITCH == ON { dset_s0 = H5Dopen (group_id, "S0", H5P_DEFAULT); dset_s1 = H5Dopen (group_id, "S1", H5P_DEFAULT); dset_s2 = H5Dopen (group_id, "S2", H5P_DEFAULT); dset_s3 = H5Dopen (group_id, "S3", H5P_DEFAULT); } #endif dset_num_scatt = H5Dopen (group_id, "NS", H5P_DEFAULT); #if SYNCHROTRON_SWITCH == ON { dset_weight = H5Dopen (group_id, "PW", H5P_DEFAULT); // have to account for this only being used for synchrotron emission switch being on } #else { dset_weight = H5Dopen (file, "PW", H5P_DEFAULT); //for non synch runs look at the global /PW dataset } #endif #if SAVE_TYPE == ON { dset_ph_type = H5Dopen (group_id, "PT", H5P_DEFAULT); } #endif //read the data in status = H5Dread(dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (p0+j)); status = H5Dread(dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (p1+j)); status = H5Dread(dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (p2+j)); status = H5Dread(dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (p3+j)); #if COMV_SWITCH == ON { status = H5Dread(dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (comv_p0+j)); status = H5Dread(dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (comv_p1+j)); status = H5Dread(dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (comv_p2+j)); status = H5Dread(dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (comv_p3+j)); } #endif status = H5Dread(dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (r0+j)); status = H5Dread(dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (r1+j)); status = H5Dread(dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (r2+j)); #if STOKES_SWITCH == ON { status = H5Dread(dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (s0+j)); status = H5Dread(dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (s1+j)); status = H5Dread(dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (s2+j)); status = H5Dread(dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (s3+j)); } #endif status = H5Dread(dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (num_scatt+j)); status = H5Dread(dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, (weight+j)); #if SAVE_TYPE == ON { status = H5Dread(dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, (ph_type+j)); } #endif //get the number of points dspace = H5Dget_space (dset_p0); status=H5Sget_simple_extent_dims(dspace, dims, NULL); //save dimesnions in dims j+=dims[0];//calculate the total number of photons to save to new hdf5 file status = H5Sclose (dspace); status = H5Dclose (dset_p0); status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3); #if COMV_SWITCH == ON { status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3); } #endif status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2); #if STOKES_SWITCH == ON { status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3); } #endif #if SAVE_TYPE == ON { status = H5Dclose (dset_ph_type); } #endif status = H5Dclose (dset_num_scatt); status = H5Dclose (dset_weight); status = H5Gclose(group_id); } status = H5Fclose(file); } //create the datatspace and dataset dims[0]=j; dspace = H5Screate_simple(1, dims, NULL); dset_p0=H5Dcreate2(file_new, "P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_p1=H5Dcreate2(file_new, "P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_p2=H5Dcreate2(file_new, "P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_p3=H5Dcreate2(file_new, "P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #if COMV_SWITCH == ON { dset_comv_p0=H5Dcreate2(file_new, "COMV_P0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_comv_p1=H5Dcreate2(file_new, "COMV_P1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_comv_p2=H5Dcreate2(file_new, "COMV_P2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_comv_p3=H5Dcreate2(file_new, "COMV_P3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } #endif dset_r0=H5Dcreate2(file_new, "R0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_r1=H5Dcreate2(file_new, "R1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_r2=H5Dcreate2(file_new, "R2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #if STOKES_SWITCH == ON { dset_s0=H5Dcreate2(file_new, "S0", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_s1=H5Dcreate2(file_new, "S1", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_s2=H5Dcreate2(file_new, "S2", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_s3=H5Dcreate2(file_new, "S3", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } #endif dset_num_scatt=H5Dcreate2(file_new, "NS", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); dset_weight=H5Dcreate2(file_new, "PW", H5T_NATIVE_DOUBLE, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #if SAVE_TYPE == ON { dset_ph_type=H5Dcreate2(file_new, "PT", H5T_NATIVE_CHAR, dspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } #endif //save the data in the new file status = H5Dwrite (dset_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p0); status = H5Dwrite (dset_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p1); status = H5Dwrite (dset_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p2); status = H5Dwrite (dset_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, p3); #if COMV_SWITCH == ON { status = H5Dwrite (dset_comv_p0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p0); status = H5Dwrite (dset_comv_p1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p1); status = H5Dwrite (dset_comv_p2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p2); status = H5Dwrite (dset_comv_p3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, comv_p3); } #endif status = H5Dwrite (dset_r0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r0); status = H5Dwrite (dset_r1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r1); status = H5Dwrite (dset_r2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, r2); #if STOKES_SWITCH == ON { status = H5Dwrite (dset_s0, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s0); status = H5Dwrite (dset_s1, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s1); status = H5Dwrite (dset_s2, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s2); status = H5Dwrite (dset_s3, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, s3); } #endif #if SAVE_TYPE == ON { status = H5Dwrite (dset_ph_type, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, ph_type); } #endif status = H5Dwrite (dset_num_scatt, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, num_scatt); status = H5Dwrite (dset_weight, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, weight); status = H5Sclose (dspace); status = H5Dclose (dset_p0); status = H5Dclose (dset_p1); status = H5Dclose (dset_p2); status = H5Dclose (dset_p3); #if COMV_SWITCH == ON { status = H5Dclose (dset_comv_p0); status = H5Dclose (dset_comv_p1); status = H5Dclose (dset_comv_p2); status = H5Dclose (dset_comv_p3); } #endif status = H5Dclose (dset_r0); status = H5Dclose (dset_r1); status = H5Dclose (dset_r2); #if STOKES_SWITCH == ON { status = H5Dclose (dset_s0); status = H5Dclose (dset_s1); status = H5Dclose (dset_s2); status = H5Dclose (dset_s3); } #endif #if SAVE_TYPE == ON { status = H5Dclose (dset_ph_type); } #endif status = H5Dclose (dset_num_scatt); status = H5Dclose (dset_weight); status = H5Fclose (file_new); free(p0);free(p1); free(p2);free(p3); free(comv_p0);free(comv_p1); free(comv_p2);free(comv_p3); free(r0);free(r1); free(r2); free(s0);free(s1); free(s2);free(s3); free(num_scatt); free(weight); free(ph_type); isNotCorrupted=0; } } //exit(0); } void modifyFlashName(char flash_file[200], char prefix[200], int frame) { int lim1=0, lim2=0, lim3=0; char test[200]="" ; //if (strcmp(DIM_SWITCH, dim_2d_str)==0) #if DIMENSIONS == 2 { //2D case lim1=10; lim2=100; lim3=1000; } #else { //3d case lim1=100; lim2=1000; lim3=10000; } #endif if (frame<lim1) { //snprintf(flash_file,sizeof(flash_file), "%s%.3d%d",prefix,000,frame); //FILEPATH,FILEROOT snprintf(test,sizeof(test), "%s%s%.3d%d",FILEPATH,FILEROOT,000,frame); } else if (frame<lim2) { //snprintf(flash_file,sizeof(flash_file), "%s%.2d%d",prefix,00,frame); snprintf(test,sizeof(test), "%s%s%.2d%d",FILEPATH,FILEROOT,00,frame); } else if (frame<lim3) { //snprintf(flash_file,sizeof(flash_file), "%s%d%d",prefix,0,frame); snprintf(test,sizeof(test), "%s%s%d%d",FILEPATH,FILEROOT,0,frame); } else { //snprintf(flash_file,sizeof(flash_file), "%s%d",prefix,frame); snprintf(test,sizeof(test), "%s%s%d",FILEPATH,FILEROOT,frame); } strncpy(flash_file, test, sizeof(test));//had to do this workaround for some weird reason //printf("test: %s\n", flash_file); } void readHydro2D(char hydro_prefix[200], int frame, double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r, double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, FILE *fPtr) { FILE *hydroPtr=NULL; char hydrofile[200]="", file_num[200]="", full_file[200]="", file_end[200]="" ; char buf[10]=""; int i=0, j=0, k=0, elem=0, elem_factor=0; int all_index_buffer=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files int r_index=0, theta_index=0; float buffer=0; float *dens_unprc=NULL,*vel_r_unprc=NULL, *vel_theta_unprc=NULL,*pres_unprc=NULL; double ph_rmin=0, ph_rmax=0; double r_in=1e10; //double *r_edge=malloc(sizeof(double)*(R_DIM_2D+1)); //double *dr=malloc(sizeof(double)*(R_DIM_2D)); double *r_unprc=malloc(sizeof(double)*R_DIM_2D); double *theta_unprc=malloc(sizeof(double)*THETA_DIM_2D); if (ph_inj_switch==0) { ph_rmin=min_r; ph_rmax=max_r; } snprintf(file_end,sizeof(file_end),"%s","small.data" ); //density snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" ); modifyFlashName(file_num, hydrofile, frame); fprintf(fPtr,">> Opening file %s\n", file_num); fflush(fPtr); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr); fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr); fread(&r_min_index, sizeof(int)*1, 1,hydroPtr); fread(&r_max_index, sizeof(int)*1, 1,hydroPtr); fclose(hydroPtr); //fortran indexing starts @ 1, but C starts @ 0 r_min_index--;//=r_min_index-1; r_max_index--;//=r_max_index-1; theta_min_index--;//=theta_min_index-1; theta_max_index--;//=theta_max_index-1; elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements fprintf(fPtr,"Elem %d\n", elem); fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); fflush(fPtr); //now with number of elements allocate data dens_unprc=malloc(elem*sizeof(float)); vel_r_unprc=malloc(elem*sizeof(float)); vel_theta_unprc=malloc(elem*sizeof(float)); pres_unprc=malloc(elem*sizeof(float)); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran /* for (i=0;i<elem;i++) { fread((dens_unprc+i), sizeof(float),1, hydroPtr); //read data } */ fread(dens_unprc, sizeof(float),elem, hydroPtr); fclose(hydroPtr); //V_r snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" ); modifyFlashName(file_num, hydrofile, frame); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_r_unprc, sizeof(float),elem, hydroPtr); //data fclose(hydroPtr); //V_theta snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" ); modifyFlashName(file_num, hydrofile, frame); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(vel_theta_unprc, sizeof(float), elem, hydroPtr); //data fclose(hydroPtr); //u04 is phi component but is all 0 //pres snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" ); modifyFlashName(file_num, hydrofile, frame); snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end); //fprintf(fPtr,">> Opening file %s\n", full_file); //fflush(fPtr); hydroPtr=fopen(full_file, "rb"); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran //elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index); //fprintf(fPtr,"Elem %d\n", elem); //fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index); //fflush(fPtr); fread(pres_unprc, sizeof(float),elem, hydroPtr); //data fclose(hydroPtr); /* for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k ))); //fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k ))); fflush(fPtr); } } exit(0); */ //R snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x1.data" ); hydroPtr=fopen(hydrofile, "r"); //fprintf(fPtr,">> Opening file %s\n", hydrofile); //fflush(fPtr); i=0; while (i<R_DIM_2D) { fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { //printf("Here\n"); fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //theta from y axis snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" ); hydroPtr=fopen(hydrofile, "r"); //fprintf(fPtr,">> Opening file %s\n", hydrofile); //fflush(fPtr); i=0; while (i<THETA_DIM_2D) { fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value fgets(buf, 3,hydroPtr); //read comma /* if (i<5) { fprintf(fPtr,"Theta %d: %e\n", i, *(theta_unprc+i)); fflush(fPtr); } */ i++; } fclose(hydroPtr); //limit number of array elements //fill in radius array and find in how many places r > injection radius elem_factor=0; elem=0; while (elem==0) { elem_factor++; elem=0; for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { i=r_min_index+k; //look at indexes of r that are included in small hydro file //if I have photons do selection differently than if injecting photons if (ph_inj_switch==0) { //if calling this function when propagating photons, choose blocks based on where the photons are if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } else { //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) )) { // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k ) elem++; } } } } } fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj); fflush(fPtr); (*pres)=malloc (elem * sizeof (double )); (*velx)=malloc (elem * sizeof (double )); (*vely)=malloc (elem * sizeof (double )); (*dens)=malloc (elem * sizeof (double )); (*x)=malloc (elem * sizeof (double )); (*y)=malloc (elem * sizeof (double )); (*r)=malloc (elem * sizeof (double )); (*theta)=malloc (elem * sizeof (double )); (*gamma)=malloc (elem * sizeof (double )); (*dens_lab)=malloc (elem * sizeof (double )); //szx becomes delta r szy becomes delta theta (*szx)=malloc (elem * sizeof (double )); (*szy)=malloc (elem * sizeof (double )); (*temp)=malloc (elem * sizeof (double )); elem=0; for (j=0 ;j<(theta_max_index+1-theta_min_index); j++) { for (k=0; k<(r_max_index+1-r_min_index); k++) { r_index=r_min_index+k; //look at indexes of r that are included in small hydro file theta_index=theta_min_index+j; if (ph_inj_switch==0) { if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) )) { (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )); (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index)); (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index)); (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k )); (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index)); (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*r)[elem]=*(r_unprc+r_index); (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000); (*szy)[elem]=(M_PI/2)/2000; (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); elem++; } } else { if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) )) { (*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )); (*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index)); (*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index)); (*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k )); (*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index)); (*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index)); (*r)[elem]=*(r_unprc+r_index); (*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000); (*szy)[elem]=(M_PI/2)/2000; (*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis (*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c (*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); (*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); elem++; } } } } (*number)=elem; //fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj); //fflush(fPtr); free(pres_unprc); //works when not being freed? //fprintf(fPtr, "pres Done\n\n"); //fflush(fPtr); free(vel_r_unprc); //fprintf(fPtr, "vel_r Done\n\n"); //fflush(fPtr); free(vel_theta_unprc); //fprintf(fPtr, "vel_theta Done\n\n"); //fflush(fPtr); free(dens_unprc); //fprintf(fPtr, "dens Done\n\n"); //fflush(fPtr); free(r_unprc); //fprintf(fPtr, "r Done\n\n"); //fflush(fPtr); free(theta_unprc); //fprintf(fPtr, "theta Done\n\n"); //fflush(fPtr); pres_unprc=NULL; vel_r_unprc=NULL; vel_theta_unprc=NULL; dens_unprc=NULL; r_unprc=NULL; theta_unprc=NULL; //fprintf(fPtr, "ALL Done\n\n"); //fflush(fPtr); }
{ "alphanum_fraction": 0.5508457903, "avg_line_length": 45.3002574767, "ext": "c", "hexsha": "80bd2767cab1854de40c499f0fd5bcdd95a35052", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-19T09:13:42.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "Src/mclib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_path": "Src/mclib.c", "max_line_length": 420, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "Src/mclib.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 66745, "size": 228721 }
/* histogram/init.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> gsl_histogram * gsl_histogram_alloc (size_t n) { gsl_histogram *h; if (n == 0) { GSL_ERROR_VAL ("histogram length n must be positive integer", GSL_EDOM, 0); } h = (gsl_histogram *) malloc (sizeof (gsl_histogram)); if (h == 0) { GSL_ERROR_VAL ("failed to allocate space for histogram struct", GSL_ENOMEM, 0); } h->range = (double *) malloc ((n + 1) * sizeof (double)); if (h->range == 0) { free (h); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for histogram ranges", GSL_ENOMEM, 0); } h->bin = (double *) malloc (n * sizeof (double)); if (h->bin == 0) { free (h->range); free (h); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for histogram bins", GSL_ENOMEM, 0); } h->n = n; return h; } static void make_uniform (double range[], size_t n, double xmin, double xmax) { size_t i; for (i = 0; i <= n; i++) { double f1 = ((double) (n-i) / (double) n); double f2 = ((double) i / (double) n); range[i] = f1 * xmin + f2 * xmax; } } gsl_histogram * gsl_histogram_calloc_uniform (const size_t n, const double xmin, const double xmax) { gsl_histogram *h; if (xmin >= xmax) { GSL_ERROR_VAL ("xmin must be less than xmax", GSL_EINVAL, 0); } h = gsl_histogram_calloc (n); if (h == 0) { return h; } make_uniform (h->range, n, xmin, xmax); return h; } gsl_histogram * gsl_histogram_calloc (size_t n) { gsl_histogram * h = gsl_histogram_alloc (n); if (h == 0) { return h; } { size_t i; for (i = 0; i < n + 1; i++) { h->range[i] = i; } for (i = 0; i < n; i++) { h->bin[i] = 0; } } h->n = n; return h; } void gsl_histogram_free (gsl_histogram * h) { RETURN_IF_NULL (h); free (h->range); free (h->bin); free (h); } /* These initialization functions suggested by Achim Gaedke */ int gsl_histogram_set_ranges_uniform (gsl_histogram * h, double xmin, double xmax) { size_t i; const size_t n = h->n; if (xmin >= xmax) { GSL_ERROR ("xmin must be less than xmax", GSL_EINVAL); } /* initialize ranges */ make_uniform (h->range, n, xmin, xmax); /* clear contents */ for (i = 0; i < n; i++) { h->bin[i] = 0; } return GSL_SUCCESS; } int gsl_histogram_set_ranges (gsl_histogram * h, const double range[], size_t size) { size_t i; const size_t n = h->n; if (size != (n+1)) { GSL_ERROR ("size of range must match size of histogram", GSL_EINVAL); } /* initialize ranges */ for (i = 0; i <= n; i++) { h->range[i] = range[i]; } /* clear contents */ for (i = 0; i < n; i++) { h->bin[i] = 0; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5792016273, "avg_line_length": 19.665, "ext": "c", "hexsha": "6c2fdf740614b986806fd11dcb67f3ae91b6ea27", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/init.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/init.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/histogram/init.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": 1133, "size": 3933 }
#ifndef _amici_TPL_MODELNAME_h #define _amici_TPL_MODELNAME_h #include <cmath> #include <memory> #include <gsl/gsl-lite.hpp> #include "amici/model_ode.h" #include "amici/solver_cvodes.h" #include "sundials/sundials_types.h" namespace amici { class Solver; namespace model_TPL_MODELNAME { extern std::array<const char*, TPL_NP> parameterNames; extern std::array<const char*, TPL_NK> fixedParameterNames; extern std::array<const char*, TPL_NX_RDATA> stateNames; extern std::array<const char*, TPL_NY> observableNames; extern std::array<const char*, TPL_NW> expressionNames; extern std::array<const char*, TPL_NP> parameterIds; extern std::array<const char*, TPL_NK> fixedParameterIds; extern std::array<const char*, TPL_NX_RDATA> stateIds; extern std::array<const char*, TPL_NY> observableIds; extern std::array<const char*, TPL_NW> expressionIds; TPL_JY_DEF TPL_DJYDSIGMA_DEF TPL_DJYDY_DEF TPL_DJYDY_COLPTRS_DEF TPL_DJYDY_ROWVALS_DEF TPL_ROOT_DEF TPL_DWDP_DEF TPL_DWDP_COLPTRS_DEF TPL_DWDP_ROWVALS_DEF TPL_DWDX_DEF TPL_DWDX_COLPTRS_DEF TPL_DWDX_ROWVALS_DEF TPL_DWDW_DEF TPL_DWDW_COLPTRS_DEF TPL_DWDW_ROWVALS_DEF TPL_DXDOTDW_DEF TPL_DXDOTDW_COLPTRS_DEF TPL_DXDOTDW_ROWVALS_DEF TPL_DXDOTDP_EXPLICIT_DEF TPL_DXDOTDP_EXPLICIT_COLPTRS_DEF TPL_DXDOTDP_EXPLICIT_ROWVALS_DEF TPL_DXDOTDX_EXPLICIT_DEF TPL_DXDOTDX_EXPLICIT_COLPTRS_DEF TPL_DXDOTDX_EXPLICIT_ROWVALS_DEF TPL_DYDX_DEF TPL_DYDP_DEF TPL_SIGMAY_DEF TPL_DSIGMAYDP_DEF TPL_W_DEF TPL_X0_DEF TPL_X0_FIXEDPARAMETERS_DEF TPL_SX0_DEF TPL_SX0_FIXEDPARAMETERS_DEF TPL_XDOT_DEF TPL_Y_DEF TPL_STAU_DEF TPL_DELTAX_DEF TPL_DELTASX_DEF TPL_X_RDATA_DEF TPL_X_SOLVER_DEF TPL_TOTAL_CL_DEF /** * @brief AMICI-generated model subclass. */ class Model_TPL_MODELNAME : public amici::Model_ODE { public: /** * @brief Default constructor. */ Model_TPL_MODELNAME() : amici::Model_ODE( amici::ModelDimensions( TPL_NX_RDATA, // nx_rdata TPL_NXTRUE_RDATA, // nxtrue_rdata TPL_NX_SOLVER, // nx_solver TPL_NXTRUE_SOLVER, // nxtrue_solver TPL_NX_SOLVER_REINIT, // nx_solver_reinit TPL_NP, // np TPL_NK, // nk TPL_NY, // ny TPL_NYTRUE, // nytrue TPL_NZ, // nz TPL_NZTRUE, // nztrue TPL_NEVENT, // nevent TPL_NOBJECTIVE, // nobjective TPL_NW, // nw TPL_NDWDX, // ndwdx TPL_NDWDP, // ndwdp TPL_NDWDW, // ndwdw TPL_NDXDOTDW, // ndxdotdw TPL_NDJYDY, // ndjydy 0, // nnz TPL_UBW, // ubw TPL_LBW // lbw ), amici::SimulationParameters( std::vector<realtype>{TPL_FIXED_PARAMETERS}, // fixedParameters std::vector<realtype>{TPL_PARAMETERS} // dynamic parameters ), TPL_O2MODE, // o2mode std::vector<realtype>(TPL_NX_SOLVER, 0.0), // idlist std::vector<int>{}, // z2event true, // pythonGenerated TPL_NDXDOTDP_EXPLICIT, // ndxdotdp_explicit TPL_NDXDOTDX_EXPLICIT, // ndxdotdx_explicit TPL_W_RECURSION_DEPTH // w_recursion_depth ) {} /** * @brief Clone this model instance. * @return A deep copy of this instance. */ virtual amici::Model *clone() const override { return new Model_TPL_MODELNAME(*this); } /** model specific implementation of fJrz * @param nllh regularization for event measurements z * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint **/ virtual void fJrz(realtype *nllh, const int iz, const realtype *p, const realtype *k, const realtype *rz, const realtype *sigmaz) override {} TPL_JY_IMPL /** model specific implementation of fJz * @param nllh negative log-likelihood for event measurements z * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurements at timepoint **/ virtual void fJz(realtype *nllh, const int iz, const realtype *p, const realtype *k, const realtype *z, const realtype *sigmaz, const realtype *mz) override {} /** model specific implementation of fdJrzdsigma * @param dJrzdsigma Sensitivity of event penalization Jrz w.r.t. * standard deviation sigmaz * @param iz event output index * @param p parameter vector * @param k constant vector * @param rz model root output at timepoint * @param sigmaz event measurement standard deviation at timepoint **/ virtual void fdJrzdsigma(realtype *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const realtype *rz, const realtype *sigmaz) override {} /** model specific implementation of fdJrzdz * @param dJrzdz partial derivative of event penalization Jrz * @param iz event output index * @param p parameter vector * @param k constant vector * @param rz model root output at timepoint * @param sigmaz event measurement standard deviation at timepoint **/ virtual void fdJrzdz(realtype *dJrzdz, const int iz, const realtype *p, const realtype *k, const realtype *rz, const realtype *sigmaz) override {} TPL_DJYDSIGMA_IMPL /** model specific implementation of fdJzdsigma * @param dJzdsigma Sensitivity of event measurement * negative log-likelihood Jz w.r.t. standard deviation sigmaz * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurement at timepoint **/ virtual void fdJzdsigma(realtype *dJzdsigma, const int iz, const realtype *p, const realtype *k, const realtype *z, const realtype *sigmaz, const realtype *mz) override {} /** model specific implementation of fdJzdz * @param dJzdz partial derivative of event measurement negative *log-likelihood Jz * @param iz event output index * @param p parameter vector * @param k constant vector * @param z model event output at timepoint * @param sigmaz event measurement standard deviation at timepoint * @param mz event measurement at timepoint **/ virtual void fdJzdz(realtype *dJzdz, const int iz, const realtype *p, const realtype *k, const realtype *z, const realtype *sigmaz, const realtype *mz) override {} /** model specific implementation of fdeltasx * @param deltaqB sensitivity update * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector * @param ip sensitivity index * @param ie event index * @param xdot new model right hand side * @param xdot_old previous model right hand side * @param xB adjoint state **/ virtual void fdeltaqB(realtype *deltaqB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {} TPL_DELTASX_IMPL TPL_DELTAX_IMPL /** model specific implementation of fdeltaxB * @param deltaxB adjoint state update * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector * @param ie event index * @param xdot new model right hand side * @param xdot_old previous model right hand side * @param xB current adjoint state **/ virtual void fdeltaxB(realtype *deltaxB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {} /** model specific implementation of fdrzdp * @param drzdp partial derivative of root output rz w.r.t. model parameters *p * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector * @param ip parameter index w.r.t. which the derivative is requested **/ virtual void fdrzdp(realtype *drzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {} /** model specific implementation of fdrzdx * @param drzdx partial derivative of root output rz w.r.t. model states x * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector **/ virtual void fdrzdx(realtype *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {} TPL_DSIGMAYDP_IMPL /** model specific implementation of fsigmaz * @param dsigmazdp partial derivative of standard deviation of event *measurements * @param t current time * @param p parameter vector * @param k constant vector * @param ip sensitivity index **/ virtual void fdsigmazdp(realtype *dsigmazdp, const realtype t, const realtype *p, const realtype *k, const int ip) override {} TPL_DJYDY_IMPL TPL_DJYDY_COLPTRS_IMPL TPL_DJYDY_ROWVALS_IMPL TPL_DWDP_IMPL TPL_DWDP_COLPTRS_IMPL TPL_DWDP_ROWVALS_IMPL TPL_DWDX_IMPL TPL_DWDX_COLPTRS_IMPL TPL_DWDX_ROWVALS_IMPL TPL_DWDW_IMPL TPL_DWDW_COLPTRS_IMPL TPL_DWDW_ROWVALS_IMPL TPL_DXDOTDW_IMPL TPL_DXDOTDW_COLPTRS_IMPL TPL_DXDOTDW_ROWVALS_IMPL TPL_DXDOTDP_EXPLICIT_IMPL TPL_DXDOTDP_EXPLICIT_COLPTRS_IMPL TPL_DXDOTDP_EXPLICIT_ROWVALS_IMPL TPL_DXDOTDX_EXPLICIT_IMPL TPL_DXDOTDX_EXPLICIT_COLPTRS_IMPL TPL_DXDOTDX_EXPLICIT_ROWVALS_IMPL TPL_DYDX_IMPL TPL_DYDP_IMPL /** model specific implementation of fdzdp * @param dzdp partial derivative of event-resolved output z w.r.t. model *parameters p * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector * @param ip parameter index w.r.t. which the derivative is requested **/ virtual void fdzdp(realtype *dzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {} /** model specific implementation of fdzdx * @param dzdx partial derivative of event-resolved output z w.r.t. model *states x * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector **/ virtual void fdzdx(realtype *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {} TPL_ROOT_IMPL /** model specific implementation of frz * @param rz value of root function at current timepoint (non-output events *not included) * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector **/ virtual void frz(realtype *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {} TPL_SIGMAY_IMPL /** model specific implementation of fsigmaz * @param sigmaz standard deviation of event measurements * @param t current time * @param p parameter vector * @param k constant vector **/ virtual void fsigmaz(realtype *sigmaz, const realtype t, const realtype *p, const realtype *k) override {} /** model specific implementation of fsrz * @param srz Sensitivity of rz, total derivative * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param sx current state sensitivity * @param h heaviside vector * @param ip sensitivity index **/ virtual void fsrz(realtype *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {} TPL_STAU_IMPL TPL_SX0_IMPL TPL_SX0_FIXEDPARAMETERS_IMPL /** model specific implementation of fsz * @param sz Sensitivity of rz, total derivative * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector * @param sx current state sensitivity * @param ip sensitivity index **/ virtual void fsz(realtype *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {} TPL_W_IMPL TPL_X0_IMPL TPL_X0_FIXEDPARAMETERS_IMPL TPL_XDOT_IMPL TPL_Y_IMPL /** model specific implementation of fz * @param z value of event output * @param ie event index * @param t current time * @param x current state * @param p parameter vector * @param k constant vector * @param h heaviside vector **/ virtual void fz(realtype *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {} TPL_X_RDATA_IMPL TPL_X_SOLVER_IMPL TPL_TOTAL_CL_IMPL std::string getName() const override { return "TPL_MODELNAME"; } /** * @brief Get names of the model parameters * @return the names */ virtual std::vector<std::string> getParameterNames() const override { return std::vector<std::string>(parameterNames.begin(), parameterNames.end()); } /** * @brief Get names of the model states * @return the names */ virtual std::vector<std::string> getStateNames() const override { return std::vector<std::string>(stateNames.begin(), stateNames.end()); } /** * @brief Get names of the fixed model parameters * @return the names */ virtual std::vector<std::string> getFixedParameterNames() const override { return std::vector<std::string>(fixedParameterNames.begin(), fixedParameterNames.end()); } /** * @brief Get names of the observables * @return the names */ virtual std::vector<std::string> getObservableNames() const override { return std::vector<std::string>(observableNames.begin(), observableNames.end()); } /** * @brief Get names of model expressions * @return Expression names */ virtual std::vector<std::string> getExpressionNames() const override { return std::vector<std::string>(expressionNames.begin(), expressionNames.end()); } /** * @brief Get ids of the model parameters * @return the ids */ virtual std::vector<std::string> getParameterIds() const override { return std::vector<std::string>(parameterIds.begin(), parameterIds.end()); } /** * @brief Get ids of the model states * @return the ids */ virtual std::vector<std::string> getStateIds() const override { return std::vector<std::string>(stateIds.begin(), stateIds.end()); } /** * @brief Get ids of the fixed model parameters * @return the ids */ virtual std::vector<std::string> getFixedParameterIds() const override { return std::vector<std::string>(fixedParameterIds.begin(), fixedParameterIds.end()); } /** * @brief Get ids of the observables * @return the ids */ virtual std::vector<std::string> getObservableIds() const override { return std::vector<std::string>(observableIds.begin(), observableIds.end()); } /** * @brief Get IDs of model expressions * @return Expression IDs */ virtual std::vector<std::string> getExpressionIds() const override { return std::vector<std::string>(expressionIds.begin(), expressionIds.end()); } /** * @brief function indicating whether reinitialization of states depending on fixed parameters is permissible * @return flag indicating whether reinitialization of states depending on fixed parameters is permissible */ virtual bool isFixedParameterStateReinitializationAllowed() const override { return TPL_REINIT_FIXPAR_INITCOND; } /** * @brief returns the AMICI version that was used to generate the model * @return AMICI version string */ virtual std::string getAmiciVersion() const override { return "TPL_AMICI_VERSION_STRING"; } /** * @brief returns the amici version that was used to generate the model * @return AMICI git commit hash */ virtual std::string getAmiciCommit() const override { return "TPL_AMICI_COMMIT_STRING"; } virtual bool hasQuadraticLLH() const override { return TPL_QUADRATIC_LLH; } }; } // namespace model_TPL_MODELNAME } // namespace amici #endif /* _amici_TPL_MODELNAME_h */
{ "alphanum_fraction": 0.6008776304, "avg_line_length": 34.8159722222, "ext": "h", "hexsha": "79eec1d51c091c0d3e27f32e291113c47a634035", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-09-20T14:53:43.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-20T14:53:43.000Z", "max_forks_repo_head_hexsha": "09132907788a4b443f4d93223b34ee9fc5ad051a", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "jvanhoefer/AMICI", "max_forks_repo_path": "src/model_header.ODE_template.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "09132907788a4b443f4d93223b34ee9fc5ad051a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "jvanhoefer/AMICI", "max_issues_repo_path": "src/model_header.ODE_template.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "09132907788a4b443f4d93223b34ee9fc5ad051a", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "jvanhoefer/AMICI", "max_stars_repo_path": "src/model_header.ODE_template.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4872, "size": 20054 }
#include <viaio/VImage.h> #include <math.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include "gsl_utils.h" #define ABS(x) ((x) >= 0) ? (x) : -(x) #define MIN(a,b) ((a) < (b)) ? (a) : (b) #define MAX(a,b) ((a) > (b)) ? (a) : (b) #define ROUND(x) (int)(((x) >= 0) ? ((x) + 0.5) : ((x) - 0.5)) void whitecov2(VImage effect_image,VImage rho_vol, gsl_matrix_float* Y, gsl_matrix_float* X, gsl_matrix_float* con, VFloat* Dfs, int numlags, int slice) { int numcon = 1; int n = Y->size1; VFloat Df = Dfs[numcon]; int i=0,j=0,k=0; /* some checks and warnings */ if(X->size2 != n) VError("whitecov2: Warning! sizes of design and data matrix do not match, n=%d, %ld",n,X->size2); if(X->size1 != con->size2) VError("whitecov2: Warning! contrast and design do not match."); gsl_vector_float* irho = gsl_vector_float_alloc(VImageNBands(rho_vol)); if(numlags == 1) { float* p = irho->data; const float drho = 0.01; for(i=0;i<irho->size;i++) { float tmp = ROUND((VPixel(rho_vol, i, slice, 0, VFloat) / drho)) * drho; tmp = MIN(tmp, (1-drho)); tmp = MAX(tmp, (-1+drho)); *p++ = tmp; } } else { float* p = irho->data; for(i=1;i<=irho->size;i++) *p++ = i; } /* : X=X'; */ gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2, X->size1); gsl_matrix_float_transpose_memcpy(transX, X); /* : Xstar=X; */ gsl_matrix_float* XStar = gsl_matrix_float_alloc(transX->size1, transX->size2); gsl_matrix_float_memcpy(XStar, transX); /* END allocate memory buffer */ /****************************** order == 1 *****************************/ if (numlags == 1) { /* allocate memory buffers */ gsl_vector_float* pixBig = gsl_vector_float_alloc(irho->size); gsl_matrix_float* pinvXStar = gsl_matrix_float_alloc(XStar->size2, XStar->size1); gsl_matrix_float* V = gsl_matrix_float_alloc(pinvXStar->size1, pinvXStar->size1); gsl_matrix_float* buffer_01 = gsl_matrix_float_alloc(con->size1,V->size2); gsl_matrix_float* buffer_02 = gsl_matrix_float_alloc(con->size1,con->size1); gsl_matrix_float* cVcinv = gsl_matrix_float_alloc(con->size1, con->size1); gsl_vector_float* u = funique(irho); float* rho = u->data; for(i=0;i<u->size;i++) { /* : pix=int16(find(irho==rho)); */ float* p = irho->data; float* ppB = pixBig->data; int counter = 0; for(j=0;j<irho->size;j++) { if(*p++ == *rho) { *ppB++ = (float)j; counter++; } } gsl_vector_float* pix = gsl_vector_float_alloc(counter); ppB = pixBig->data; float* pp = pix->data; for(j=0;j<counter;j++) *pp++ = *ppB++; /* : Ystar=Y(:,pix); */ gsl_matrix_float* YStar = fmat_subcols(Y,pix); /* : factor=1./sqrt(1-rho^2); */ float factor = pow(1 - *rho * *rho, -0.5); /* : Ystar(k1,:)=(Y(k1,pix)-rho*Y(k1-1,pix))*factor; */ /* point to last element */ float* pStar = YStar->data+(YStar->size1*YStar->size2)-1; /* traverse matrix in reverse order */ for (j = 0; j < (YStar->size1-1)*YStar->size2; ++j) { *pStar = (*pStar - *rho * *(pStar - YStar->size2)) * factor; pStar--; } /* : Xstar(k1,:)=(X(k1,:)-rho*X(k1-1,:))*factor; */ pStar = XStar->data+XStar->size2; float* pX = transX->data+transX->size2; for (j = 0; j < (XStar->size1-1)*XStar->size2; ++j) { *pStar++ = (*pX - *rho * *(pX - transX->size2)) * factor; pX++; } /* : pinvXstar=pinv(Xstar); */ fmat_PseudoInv(XStar,pinvXStar); /* : betahat=pinvXstar*Ystar; */ gsl_matrix_float* betahat = fmat_x_mat(pinvXStar, YStar,NULL); /* : resid=Ystar-Xstar*betahat; */ gsl_matrix_float* buffer = fmat_x_mat(XStar, betahat, NULL); gsl_matrix_float_sub(YStar, buffer); gsl_matrix_float* resid = YStar; gsl_matrix_float_free(buffer); /* : SSE=sum(resid.^2,1); */ buffer = gsl_matrix_float_alloc(resid->size1, resid->size2); gsl_matrix_float_memcpy (buffer, resid); gsl_matrix_float_mul_elements (buffer, buffer); gsl_vector_float* sse = fsum(buffer, 1,NULL); gsl_matrix_float_free(buffer); /* : sd=sqrt(SSE/Df); */ gsl_vector_float* sd = gsl_vector_float_alloc(sse->size); float* pSSE = sse->data; float* pSD = sd->data; for (j = 0; j < sse->size; ++j) { *pSD++ = (float)sqrt(*pSSE++/Df); } /* : V=pinvXstar*pinvXstar'; */ fmat_x_matT(pinvXStar, pinvXStar, V); /* : mag_ef=contrast*betahat; */ gsl_matrix_float* mag_ef = fmat_x_mat(con, betahat, NULL); /* : mag_sd=sqrt(diag(contrast*V*contrast'))*sd; */ fmat_x_mat(con,V,buffer_01); fmat_x_matT(buffer_01, con, buffer_02); gsl_vector_float_view diag = gsl_matrix_float_diagonal(buffer_02); gsl_matrix_float* mag_sd = gsl_matrix_float_alloc(diag.vector.size, sd->size); float* pMag = mag_sd->data; for (j = 0; j < diag.vector.size; ++j) { float s = sqrt(gsl_vector_float_get(&diag.vector,j)); pSD = sd->data; for (k = 0; k < sd->size; ++k) { *pMag++ = s * (*pSD++); } } /* effect_slice(pix,1)= (mag_ef./(mag_sd+(mag_sd<=0)).*(mag_sd>0))'; */ VFloat* peff = VPixelPtr(effect_image,slice,0,0); float* pmeff = mag_ef->data; float* pmsd = mag_sd->data; float* ppix = pix->data; for (j=0; j<pix->size; ++j) { *(peff+(int)*ppix++) = *pmeff / (*pmsd+(*pmsd<=0)) * (*pmsd>0); pmeff++; pmsd++; } /* free some memory */ gsl_matrix_float_free(betahat); gsl_matrix_float_free(YStar); gsl_matrix_float_free(mag_ef); gsl_matrix_float_free(mag_sd); gsl_vector_float_free(pix); gsl_vector_float_free(sse); gsl_vector_float_free(sd); rho++; } /* END for(i=0;i<u->size;i++) */ /* free some memory */ gsl_vector_float_free(pixBig); gsl_matrix_float_free(pinvXStar); gsl_matrix_float_free(V); gsl_matrix_float_free(buffer_01); gsl_matrix_float_free(buffer_02); gsl_matrix_float_free(cVcinv); } /******************* END order == 1 **********************************/ /*************************** order > 1 *********************************/ else{ /* allocate memory buffer */ gsl_vector_float* Coradj_pix = gsl_vector_float_alloc(VImageNColumns(rho_vol)+1); gsl_matrix_float* Ainv = gsl_matrix_float_alloc(Coradj_pix->size, Coradj_pix->size); gsl_matrix* dbuff = gsl_matrix_alloc(Ainv->size1,Ainv->size2); gsl_matrix_float* A = gsl_matrix_float_alloc(Ainv->size1,Ainv->size2); int nl = Ainv->size2; gsl_matrix_float* buffer_01 = gsl_matrix_float_alloc(n-nl,1); gsl_matrix_float* buffer_02 = gsl_matrix_float_alloc(A->size1,1); gsl_matrix_float* buffer_03 = gsl_matrix_float_alloc(A->size1,transX->size2); gsl_matrix_float* B = gsl_matrix_float_alloc(buffer_01->size1, A->size2); gsl_matrix_float* Vmhalf = gsl_matrix_float_alloc(n-nl,n); gsl_matrix_float* buffer_04 = gsl_matrix_float_alloc(Vmhalf->size1, transX->size2); gsl_matrix_float* YStar = gsl_matrix_float_alloc(n,1); gsl_matrix_float* pinvXStar = gsl_matrix_float_alloc(XStar->size2, XStar->size1); gsl_matrix_float* betahat = gsl_matrix_float_alloc(pinvXStar->size1, YStar->size2); gsl_matrix_float* buffer_05 = gsl_matrix_float_alloc(XStar->size1, betahat->size2); gsl_vector_float* sse = gsl_vector_float_alloc(1); gsl_vector_float* sd = gsl_vector_float_alloc(YStar->size2); gsl_matrix_float* V = gsl_matrix_float_alloc(pinvXStar->size1, pinvXStar->size1); gsl_matrix_float* mag_ef = gsl_matrix_float_alloc(con->size1, betahat->size2); gsl_matrix_float* buffer_06 = gsl_matrix_float_alloc(con->size1, V->size2); gsl_matrix_float* buffer_07 = gsl_matrix_float_alloc(con->size1, con->size1); gsl_matrix_float* mag_sd = gsl_matrix_float_alloc(con->size1, sd->size); gsl_matrix_float* buffer_08 = gsl_matrix_float_alloc(mag_ef->size1, mag_ef->size2); gsl_vector_float* sst = gsl_vector_float_alloc(1); /* END allocate memory buffer */ /* we know that irho only contains a list of indices for every voxel so we can skip the unique call and iterate over irho itself */ float* rho = irho->data; for(i=0;i<irho->size;i++) { /* : Coradj_pix=squeeze(rho_vol(pix,slice,:)); */ float* pCoradj = Coradj_pix->data+1; for(k=0;k<Coradj_pix->size-1;k++) { *(pCoradj++) = VPixel(rho_vol, i, slice, k, VFloat); } /* : [Ainvt posdef]=chol(toeplitz([1 Coradj_pix'])); */ /* at first the toeplitz matrix */ Coradj_pix->data[0] = 1; fmat_toeplitz(Coradj_pix, Ainv); /* the cholesky decomposition */ /* double buffer */ for(j=0;j<Ainv->size1;j++) { for(k=0;k<Ainv->size2;k++) { gsl_matrix_set(dbuff,j,k,(double)gsl_matrix_float_get(Ainv,j,k)); } } if(gsl_linalg_cholesky_decomp(dbuff) == GSL_EDOM) VError("Calculation error, cholesky decomposition failed for pix=%d",i); /* note: the gsl cholesky factorization returns the inverse * of Ainvt in the lower triangular part of it's output matrix. * Since we will use the inverse matrix of Ainvt in the next steps we * will work with the lower triangular part in contrast to the matlab algorithm */ /* convert back to float and remove upper triangular matrix */ for(j=0;j<Ainv->size1;j++) { for(k=0;k<Ainv->size2;k++) { if(j<k) { gsl_matrix_float_set(Ainv,j,k,0); } else { gsl_matrix_float_set(Ainv,j,k,(float)gsl_matrix_get(dbuff,j,k)); } } } /* : A=inv(Ainvt'); */ fInv(Ainv, A); /* : B=ones(n-nl,1)*A(nl,:); */ gsl_matrix_float_set_all(buffer_01,1); gsl_matrix_float_view subm = gsl_matrix_float_submatrix(A,nl-1,0,1,A->size2); fmat_x_mat(buffer_01,&subm.matrix,B); /* : Vmhalf=spdiags(double(B),double(1:nl),double(n-nl),double(n)); */ gsl_matrix_float_set_zero(Vmhalf); for(j=0;j<B->size1;j++) { for(k=0;k<B->size2;k++) { gsl_matrix_float_set(Vmhalf,j,k+1+j,gsl_matrix_float_get(B,j,k)); } } /* : Ystar=single(zeros(n,1)); */ gsl_matrix_float_set_zero(YStar); /* : Ystar(1:nl)=A*Y(1:nl,pix); */ subm = gsl_matrix_float_submatrix(Y,0,i,nl,1); fmat_x_mat(A,&subm.matrix,buffer_02); for(j=0;j<nl;j++) { gsl_matrix_float_set(YStar,j,0,gsl_matrix_float_get(buffer_02,j,0)); } /* : Ystar((nl+1):n)=single(Vmhalf*double(Y(:,pix))); */ subm = gsl_matrix_float_submatrix(Y,0,i,Y->size1,1); fmat_x_mat(Vmhalf,&subm.matrix,buffer_01); for(j=nl;j<n;j++) { gsl_matrix_float_set(YStar,j,0,gsl_matrix_float_get(buffer_01,j-nl,0)); } /* : Xstar(1:nl,:)=A*X(1:nl,:); */ subm = gsl_matrix_float_submatrix(transX,0,0,nl,transX->size2); fmat_x_mat(A, &subm.matrix, buffer_03); for(j=0;j<buffer_03->size1;j++) { for(k=0;k<buffer_03->size2;k++) { gsl_matrix_float_set(XStar,j,k,gsl_matrix_float_get(buffer_03,j,k)); } } /* : Xstar((nl+1):n,:)=single(Vmhalf*double(X)); */ fmat_x_mat(Vmhalf,transX,buffer_04); for(j=nl;j<n;j++) { for(k=0;k<transX->size2;k++) { gsl_matrix_float_set(XStar,j,k,gsl_matrix_float_get(buffer_04,j-nl,k)); } } /* : pinvXstar=pinv(Xstar); */ fmat_PseudoInv(XStar,pinvXStar); /* : betahat=pinvXstar*Ystar; */ fmat_x_mat(pinvXStar, YStar,betahat); /* : resid=Ystar-Xstar*betahat; */ fmat_x_mat(XStar, betahat, buffer_05); gsl_matrix_float_sub(YStar, buffer_05); gsl_matrix_float* resid = YStar; /* : SSE=sum(resid.^2,1); */ gsl_matrix_float_mul_elements (resid, resid); fsum(resid, 1,sse); /* : sd=sqrt(SSE/Df); */ float* pSSE = sse->data; float* pSD = sd->data; for (j = 0; j < sse->size; ++j) { *pSD++ = (float)sqrt(*pSSE++/Df); } /* : V=pinvXstar*pinvXstar'; */ fmat_x_matT(pinvXStar, pinvXStar, V); /* : mag_ef=contrast*betahat; */ fmat_x_mat(con, betahat, mag_ef); /* : mag_sd=sqrt(diag(contrast*V*contrast'))*sd; */ fmat_x_mat(con,V,buffer_06); fmat_x_matT(buffer_06, con, buffer_07); gsl_vector_float_view diag = gsl_matrix_float_diagonal(buffer_07); float* pMag = mag_sd->data; for (j = 0; j < diag.vector.size; ++j) { float s = sqrt(gsl_vector_float_get(&diag.vector,j)); pSD = sd->data; for (k = 0; k < sd->size; ++k) { *pMag++ = s * *pSD++; } } /* effect_slice(pix,1)= (mag_ef./(mag_sd+(mag_sd<=0)).*(mag_sd>0))'; */ VFloat* peff = VPixelPtr(effect_image, slice, 0, 0); float* pmeff = mag_ef->data; float* pmsd = mag_sd->data; *(peff+i) = *pmeff / (*pmsd+(*pmsd<=0)) * (*pmsd>0); /* next value */ rho++; } /* END for(i=0;i<irho->size;i++) */ /* free some memory */ gsl_vector_float_free(Coradj_pix); gsl_matrix_float_free(Ainv); gsl_matrix_free(dbuff); gsl_matrix_float_free(A); gsl_matrix_float_free(buffer_01); gsl_matrix_float_free(buffer_02); gsl_matrix_float_free(buffer_03); gsl_matrix_float_free(buffer_04); gsl_matrix_float_free(B); gsl_matrix_float_free(Vmhalf); gsl_matrix_float_free(YStar); gsl_matrix_float_free(pinvXStar); gsl_matrix_float_free(buffer_05); gsl_vector_float_free(sd); gsl_matrix_float_free(V); gsl_matrix_float_free(mag_ef); gsl_matrix_float_free(buffer_06); gsl_matrix_float_free(buffer_07); gsl_matrix_float_free(mag_sd); gsl_matrix_float_free(buffer_08); gsl_vector_float_free(sse); gsl_vector_float_free(sst); }/************************************** END order > 1 ***************************************/ /* : * minus = ones(size(effect_slice),'single'); * minus(find(effect_slice<0))=single(-1.0); * effect_slice=single(sqrt(Df .* log(1 + effect_slice.^2 ./ Df) .* (1 - 0.5 ./ Df))); * effect_slice=effect_slice .* minus; */ double u=0; VFloat* peff = VPixelPtr(effect_image, slice,0,0); for (i = 0; i < VImageNColumns(effect_image) * VImageNRows(effect_image); ++i) { VFloat oldVal = *peff; Df = Dfs[0]; u = (double)(*peff); u = sqrt(Df * log(1.0 + pow(u,2.0) / Df) * (1 - 0.5 / Df)); u = (oldVal < 0) ? u * (-1.0) : u; if (gsl_isnan(u) || gsl_isinf(u)) u = 0; (*peff) = (float)u; peff++; } /* free allocated memory */ gsl_matrix_float_free(XStar); gsl_matrix_float_free(transX); /* END free allocated memory */ }
{ "alphanum_fraction": 0.5854200719, "avg_line_length": 36.0731132075, "ext": "c", "hexsha": "dbb6cf85e494640d926979be126e7296393252df", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/vlisa_prewhitening/whitecov2.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/vlisa_prewhitening/whitecov2.c", "max_line_length": 109, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/vlisa_prewhitening/whitecov2.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": 4685, "size": 15295 }
#include <math.h> #include <stdio.h> #include <mpfr.h> #include <petsc.h> #include <stdlib.h> #include <string.h> #include "../ellipsoid/ellipsoid.h" #undef __FUNCT__ #define __FUNCT__ "TestNormalizationMPFR" PetscErrorCode TestNormalizationMPFR() { PetscErrorCode ierr; EllipsoidalSystem e; const PetscInt prec = 128; PetscReal xA = 3.0; PetscReal yB = 2.0; PetscReal zC = 1.0; mpfr_t a, b, c; mpfr_t a2, b2, c2; mpfr_t a3, b3, c3; mpfr_t temp1, temp2, temp3; mpfr_t pi; PetscFunctionBegin; mpfr_set_default_prec(4*prec); mpfr_inits(a, b, c, NULL); mpfr_inits(a2, b2, c2, NULL); mpfr_inits(a3, b3, c3, NULL); mpfr_inits(temp1, temp2, temp3, pi, NULL); mpfr_set_d(a, xA, MPFR_RNDN); mpfr_set_d(b, yB, MPFR_RNDN); mpfr_set_d(c, zC, MPFR_RNDN); //init ellipsoidal system printf("initEllipsoidalSystem...\n"); ierr = initEllipsoidalSystem(&e, xA, yB, zC, prec);CHKERRQ(ierr); printf("done.\n"); mpfr_mul(a2, a, a, MPFR_RNDN); mpfr_mul(a3, a2, a, MPFR_RNDN); mpfr_mul(b2, b, b, MPFR_RNDN); mpfr_mul(b3, b2, b, MPFR_RNDN); mpfr_mul(c2, c, c, MPFR_RNDN); mpfr_mul(c3, c2, c, MPFR_RNDN); mpfr_t firstTerm, secondTerm, LambdaD, LambdaDprime; mpfr_inits(firstTerm, secondTerm, LambdaD, LambdaDprime, NULL); //Dassios (B14) //firstTerm = (a*a + b*b + c*c)/3.0; mpfr_add(firstTerm, a2, b2, MPFR_RNDN); mpfr_add(firstTerm, firstTerm, c2, MPFR_RNDN); mpfr_div_d(firstTerm, firstTerm, 3.0, MPFR_RNDN); //double secondTerm = sqrt((a*a*a*a - b*b*c*c) + (b*b*b*b - a*a*c*c) + (c*c*c*c - a*a*b*b))/3.0; mpfr_mul(temp1, a3, a, MPFR_RNDN); mpfr_mul(temp2, b2, c2, MPFR_RNDN); mpfr_sub(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp2, b3, b, MPFR_RNDN); mpfr_mul(temp3, a2, c2, MPFR_RNDN); mpfr_sub(temp2, temp2, temp3, MPFR_RNDN); mpfr_add(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp2, c3, c, MPFR_RNDN); mpfr_mul(temp3, a2, b2, MPFR_RNDN); mpfr_sub(temp2, temp2, temp3, MPFR_RNDN); mpfr_add(temp1, temp1, temp2, MPFR_RNDN); mpfr_sqrt(secondTerm, temp1, MPFR_RNDN); //double LambdaD = firstTerm + secondTerm; mpfr_add(LambdaD, firstTerm, secondTerm, MPFR_RNDN); //double LambdaDprime = firstTerm - secondTerm; mpfr_sub(LambdaDprime, firstTerm, secondTerm, MPFR_RNDN); mpfr_t hx, hy, hz; mpfr_inits(hx, hy, hz, NULL); //Dassios (B16)-(B20) //double hx = sqrt(b*b - c*c); mpfr_sub(temp1, b2, c2, MPFR_RNDN); mpfr_sqrt(hx, temp1, MPFR_RNDN); //double hy = e.k; mpfr_set(hy, e.hp_k, MPFR_RNDN); //double hz = e.h; mpfr_set(hz, e.hp_h, MPFR_RNDN); //set pi mpfr_const_pi(pi, MPFR_RNDN); mpfr_t analytic[9]; mpfr_t approx[9], doubleApprox[9]; for(PetscInt k=0; k < 9; ++k) mpfr_inits(analytic[k], approx[k], doubleApprox[k], NULL); //analytic[0] = 4*PETSC_PI mpfr_mul_d(analytic[0], pi, 4.0, MPFR_RNDN); printf("analytic[0] = %4.4e\n", mpfr_get_d(analytic[0], MPFR_RNDN)); //analytic[1] = 4*PETSC_PI/3 * hy*hy*hz*hz mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN); mpfr_mul(temp2, hy, hy, MPFR_RNDN); mpfr_mul(temp2, temp2, hz, MPFR_RNDN); mpfr_mul(temp2, temp2, hz, MPFR_RNDN); mpfr_mul(analytic[1], temp1, temp2, MPFR_RNDN); //analytic[2] = 4*PETSC_PI/3 * hx*hx*hz*hz mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN); mpfr_mul(temp2, hx, hx, MPFR_RNDN); mpfr_mul(temp2, temp2, hz, MPFR_RNDN); mpfr_mul(temp2, temp2, hz, MPFR_RNDN); mpfr_mul(analytic[2], temp1, temp2, MPFR_RNDN); //analytic[3] = 4*PETSC_PI/3 * hx*hx*hy*hy mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN); mpfr_mul(temp2, hx, hx, MPFR_RNDN); mpfr_mul(temp2, temp2, hy, MPFR_RNDN); mpfr_mul(temp2, temp2, hy, MPFR_RNDN); mpfr_mul(analytic[3], temp1, temp2, MPFR_RNDN); //analytic[4] = -8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaD - a*a)*(LambdaD - b*b)*(LambdaD - c*c) //analytic[5] = 8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaDprime - a*a)*(LambdaDprime - b*b)*(LambdaDprime - c*c), ierr = calcNormalizationMPFR(&e, 0, 0, approx+0);CHKERRQ(ierr); ierr = calcNormalization (&e, 0, 0, doubleApprox+0);CHKERRQ(ierr); ierr = calcNormalizationMPFR(&e, 1, 0, approx+1);CHKERRQ(ierr); ierr = calcNormalizationMPFR(&e, 1, 1, approx+2);CHKERRQ(ierr); mpfr_t err[9]; for(PetscInt k=0; k < 4; ++k) { mpfr_init(err[k]); mpfr_sub(err[k], approx[k], analytic[k], MPFR_RNDN); mpfr_div(err[k], err[k], analytic[k], MPFR_RNDN); mpfr_abs(err[k], err[k], MPFR_RNDN); mpfr_log10(err[k], err[k], MPFR_RNDN); printf("the error is %2.2f\n", mpfr_get_d(err[k], MPFR_RNDN)); } for(PetscInt k=0; k < 9; ++k) mpfr_clears(analytic[k], approx[k], err[k], doubleApprox[k], NULL); mpfr_clears(hx, hy, hz, NULL); mpfr_clears(temp1, temp2, temp3, pi, NULL); mpfr_clears(a3, b3, c3, NULL); mpfr_clears(a2, b2, c2, NULL); mpfr_clears(a, b, c, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT __ "main" PetscErrorCode main(int argc, char **argv) { PetscErrorCode ierr; PetscFunctionBeginUser; ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr); ierr = TestNormalizationMPFR(); ierr = PetscFinalize(); }
{ "alphanum_fraction": 0.6667932409, "avg_line_length": 29.4245810056, "ext": "c", "hexsha": "ecee96e2d317560cf7c704b855b8122261a7e4dc", "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": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_path": "src/tests/testEllMPFR.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "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": "tom-klotz/ellipsoid-solvation", "max_issues_repo_path": "src/tests/testEllMPFR.c", "max_line_length": 121, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_path": "src/tests/testEllMPFR.c", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "num_tokens": 2073, "size": 5267 }
/* interpolation/test2d.c * * Copyright 2012 David Zaslavsky * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_test.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> /* tests a single evaluator function from the low-level interface */ static int test_single_low_level( double (*evaluator)(const gsl_interp2d *, const double[], const double[], const double[], const double, const double, gsl_interp_accel *, gsl_interp_accel *), int (*evaluator_e)(const gsl_interp2d *, const double[], const double[], const double[], const double, const double, gsl_interp_accel *, gsl_interp_accel *, double *), const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, const double expected_results[], size_t i) { if (expected_results != NULL) { int status; double result = evaluator(interp, xarr, yarr, zarr, x, y, xa, ya); gsl_test_rel(result, expected_results[i], 1e-10, "low level %s %d", gsl_interp2d_name(interp), i); status = evaluator_e(interp, xarr, yarr, zarr, x, y, xa, ya, &result); if (status == GSL_SUCCESS) { gsl_test_rel(result, expected_results[i], 1e-10, "low level _e %s %d", gsl_interp2d_name(interp), i); } } return 0; } /* tests a single evaluator function from the high-level interface */ static int test_single_high_level( double (*evaluator)(const gsl_spline2d *, const double, const double, gsl_interp_accel *, gsl_interp_accel *), int (*evaluator_e)(const gsl_spline2d *, const double, const double, gsl_interp_accel *, gsl_interp_accel *, double *), const gsl_spline2d * interp, const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, const double expected_results[], size_t i) { if (expected_results != NULL) { int status; double result = evaluator(interp, x, y, xa, ya); gsl_test_rel(result, expected_results[i], 1e-10, "high level %s %d", gsl_spline2d_name(interp), i); status = evaluator_e(interp, x, y, xa, ya, &result); if (status == GSL_SUCCESS) { gsl_test_rel(result, expected_results[i], 1e-10, "high level _e %s %d", gsl_spline2d_name(interp), i); } } return 0; } /* * Tests that a given interpolation type reproduces the data points * it is given, and then tests that it correctly reproduces additional * values. */ static int test_interp2d( const double xarr[], const double yarr[], const double zarr[], /* data */ size_t xsize, size_t ysize, /* array sizes */ const double xval[], const double yval[], /* test points */ const double zval[], /* expected results */ const double zxval[], const double zyval[], const double zxxval[], const double zyyval[], const double zxyval[], size_t test_size, /* number of test points */ const gsl_interp2d_type * T) { gsl_interp_accel *xa = gsl_interp_accel_alloc(); gsl_interp_accel *ya = gsl_interp_accel_alloc(); int status = 0; size_t xi, yi, zi, i; gsl_interp2d * interp = gsl_interp2d_alloc(T, xsize, ysize); gsl_spline2d * interp_s = gsl_spline2d_alloc(T, xsize, ysize); unsigned int min_size = gsl_interp2d_type_min_size(T); gsl_test_int(min_size, T->min_size, "gsl_interp2d_type_min_size on %s", gsl_interp2d_name(interp)); gsl_interp2d_init(interp, xarr, yarr, zarr, xsize, ysize); gsl_spline2d_init(interp_s, xarr, yarr, zarr, xsize, ysize); /* First check that the interpolation reproduces the given points */ for (xi = 0; xi < xsize; xi++) { double x = xarr[xi]; for (yi = 0; yi < ysize; yi++) { double y = yarr[yi]; zi = gsl_interp2d_idx(interp, xi, yi); test_single_low_level(&gsl_interp2d_eval, &gsl_interp2d_eval_e, interp, xarr, yarr, zarr, x, y, xa, ya, zarr, zi); test_single_low_level(&gsl_interp2d_eval_extrap, &gsl_interp2d_eval_extrap_e, interp, xarr, yarr, zarr, x, y, xa, ya, zarr, zi); test_single_high_level(&gsl_spline2d_eval, &gsl_spline2d_eval_e, interp_s, x, y, xa, ya, zarr, zi); test_single_high_level(&gsl_spline2d_eval_extrap, &gsl_spline2d_eval_extrap_e, interp_s, x, y, xa, ya, zarr, zi); } } /* Then check additional points provided */ for (i = 0; i < test_size; i++) { double x = xval[i]; double y = yval[i]; test_single_low_level(&gsl_interp2d_eval, &gsl_interp2d_eval_e, interp, xarr, yarr, zarr, x, y, xa, ya, zval, i); test_single_low_level(&gsl_interp2d_eval_deriv_x, &gsl_interp2d_eval_deriv_x_e, interp, xarr, yarr, zarr, x, y, xa, ya, zxval, i); test_single_low_level(&gsl_interp2d_eval_deriv_y, &gsl_interp2d_eval_deriv_y_e, interp, xarr, yarr, zarr, x, y, xa, ya, zyval, i); test_single_low_level(&gsl_interp2d_eval_deriv_xx,&gsl_interp2d_eval_deriv_xx_e, interp, xarr, yarr, zarr, x, y, xa, ya, zxxval, i); test_single_low_level(&gsl_interp2d_eval_deriv_yy,&gsl_interp2d_eval_deriv_yy_e, interp, xarr, yarr, zarr, x, y, xa, ya, zyyval, i); test_single_low_level(&gsl_interp2d_eval_deriv_xy,&gsl_interp2d_eval_deriv_xy_e, interp, xarr, yarr, zarr, x, y, xa, ya, zxyval, i); test_single_high_level(&gsl_spline2d_eval, &gsl_spline2d_eval_e, interp_s, x, y, xa, ya, zval, i); test_single_high_level(&gsl_spline2d_eval_extrap, &gsl_spline2d_eval_extrap_e, interp_s, x, y, xa, ya, zval, i); test_single_high_level(&gsl_spline2d_eval_deriv_x, &gsl_spline2d_eval_deriv_x_e, interp_s, x, y, xa, ya, zxval, i); test_single_high_level(&gsl_spline2d_eval_deriv_y, &gsl_spline2d_eval_deriv_y_e, interp_s, x, y, xa, ya, zyval, i); test_single_high_level(&gsl_spline2d_eval_deriv_xx,&gsl_spline2d_eval_deriv_xx_e, interp_s, x, y, xa, ya, zxxval, i); test_single_high_level(&gsl_spline2d_eval_deriv_yy,&gsl_spline2d_eval_deriv_yy_e, interp_s, x, y, xa, ya, zyyval, i); test_single_high_level(&gsl_spline2d_eval_deriv_xy,&gsl_spline2d_eval_deriv_xy_e, interp_s, x, y, xa, ya, zxyval, i); test_single_low_level(&gsl_interp2d_eval_extrap, &gsl_interp2d_eval_extrap_e, interp, xarr, yarr, zarr, x, y, xa, ya, zval, i); } gsl_interp_accel_free(xa); gsl_interp_accel_free(ya); gsl_interp2d_free(interp); gsl_spline2d_free(interp_s); return status; } /* * Tests bilinear interpolation using a symmetric function, f(x,y)==f(y,x), * and diagonal interpolation points (x,y) where x==y. If these tests don't * pass, something is seriously broken. */ static int test_bilinear_symmetric() { int status; double xarr[] = {0.0, 1.0, 2.0, 3.0}; double yarr[] = {0.0, 1.0, 2.0, 3.0}; double zarr[] = {1.0, 1.1, 1.2, 1.3, 1.1, 1.2, 1.3, 1.4, 1.2, 1.3, 1.4, 1.5, 1.3, 1.4, 1.5, 1.6}; double xval[] = {0.0, 0.5, 1.0, 1.5, 2.5, 3.0}; double yval[] = {0.0, 0.5, 1.0, 1.5, 2.5, 3.0}; double zval[] = {1.0, 1.1, 1.2, 1.3, 1.5, 1.6}; size_t xsize = sizeof(xarr) / sizeof(xarr[0]); size_t ysize = sizeof(yarr) / sizeof(yarr[0]); size_t test_size = sizeof(xval) / sizeof(xval[0]); status = test_interp2d(xarr, yarr, zarr, xsize, ysize, xval, yval, zval, NULL, NULL, NULL, NULL, NULL, test_size, gsl_interp2d_bilinear); gsl_test(status, "bilinear interpolation with symmetric values"); return status; } /* * Tests bilinear interpolation with an asymmetric function, f(x,y)!=f(y,x), * and off-diagonal interpolation points (x,y) where x and y may or may not * be equal. */ static int test_bilinear_asymmetric_z() { int status; double xarr[] = {0.0, 1.0, 2.0, 3.0}; double yarr[] = {0.0, 1.0, 2.0, 3.0}; double zarr[] = {1.0, 1.1, 1.2, 1.4, 1.3, 1.4, 1.5, 1.7, 1.5, 1.6, 1.7, 1.9, 1.6, 1.9, 2.2, 2.3}; double xval[] = { 0.0, 0.5, 1.0, 1.5, 2.5, 3.0, 1.3954, 1.6476, 0.824957, 2.41108, 2.98619, 1.36485 }; double yval[] = {0.0, 0.5, 1.0, 1.5, 2.5, 3.0, 0.265371, 2.13849, 1.62114, 1.22198, 0.724681, 0.0596087 }; /* results computed using Mathematica 9.0.1.0 */ double zval[] = {1.0, 1.2, 1.4, 1.55, 2.025, 2.3, 1.2191513, 1.7242442248, 1.5067237, 1.626612, 1.6146423, 1.15436761}; size_t xsize = sizeof(xarr) / sizeof(xarr[0]); size_t ysize = sizeof(yarr) / sizeof(yarr[0]); size_t test_size = sizeof(xval) / sizeof(xval[0]); status = test_interp2d(xarr, yarr, zarr, xsize, ysize, xval, yval, zval, NULL, NULL, NULL, NULL, NULL, test_size, gsl_interp2d_bilinear); gsl_test(status, "bilinear interpolation with asymmetric z values"); return status; } static int test_bicubic() { int status; double xarr[] = {0.0, 1.0, 2.0, 3.0}; double yarr[] = {0.0, 1.0, 2.0, 3.0}; double zarr[] = {1.0, 1.1, 1.2, 1.3, 1.1, 1.2, 1.3, 1.4, 1.2, 1.3, 1.4, 1.5, 1.3, 1.4, 1.5, 1.6}; double xval[] = {1.0, 1.5, 2.0}; double yval[] = {1.0, 1.5, 2.0}; double zval[] = {1.2, 1.3, 1.4}; size_t xsize = sizeof(xarr) / sizeof(xarr[0]); size_t ysize = sizeof(yarr) / sizeof(yarr[0]); size_t test_size = sizeof(xval) / sizeof(xval[0]); status = test_interp2d(xarr, yarr, zarr, xsize, ysize, xval, yval, zval, NULL, NULL, NULL, NULL, NULL, test_size, gsl_interp2d_bicubic); gsl_test(status, "bicubic interpolation on linear function"); return status; } static int test_bicubic_nonlinear() { int status; double xarr[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; double yarr[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; /* least common multiple of x and y */ double zarr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 6, 4, 10, 6, 14, 8, 3, 6, 3, 12, 15, 6, 21, 24, 4, 4, 12, 4, 20, 12, 28, 8, 5, 10, 15, 20, 5, 30, 35, 40, 6, 6, 6, 12, 30, 6, 42, 24, 7, 14, 21, 28, 35, 42, 7, 56, 8, 8, 24, 8, 40, 24, 56, 8}; double xval[] = {1.4, 2.3, 4.7, 3.3, 7.5, 6.6, 5.1}; double yval[] = {1.0, 1.8, 1.9, 2.5, 2.7, 4.1, 3.3}; /* results computed using GSL 1D cubic interpolation twice */ double zval[] = { 1.4, 3.11183531264736, 8.27114315792559, 5.03218982537718, 22.13230634702637, 23.63206834997871, 17.28553080971182 }; size_t xsize = sizeof(xarr) / sizeof(xarr[0]); size_t ysize = sizeof(yarr) / sizeof(yarr[0]); size_t test_size = sizeof(xval) / sizeof(xval[0]); status = test_interp2d(xarr, yarr, zarr, xsize, ysize, xval, yval, zval, NULL, NULL, NULL, NULL, NULL, test_size, gsl_interp2d_bicubic); gsl_test(status, "bicubic interpolation on nonlinear symmetric function"); return status; } /* This function contributed by Andrew W. Steiner <awsteiner@gmail.com> */ static int test_bicubic_nonlinear_nonsq() { int status; double xarr[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; double yarr[] = {1.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0}; double zarr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 2, 6, 4, 10, 6, 14, 8, 11, 12, 3, 6, 3, 12, 15, 6, 21, 24, 13, 14, 4, 4, 12, 4, 20, 12, 28, 8, 15, 16, 5, 10, 15, 20, 5, 30, 35, 40, 17, 18, 6, 6, 6, 12, 30, 6, 42, 24, 19, 20, 7, 14, 21, 28, 35, 42, 7, 56, 21, 22, 8, 8, 24, 8, 40, 24, 56, 8, 23, 24}; double xval[] = {1.4, 2.3, 9.7, 3.3, 9.5, 6.6, 5.1}; double yval[] = {1.0, 1.8, 1.9, 2.5, 2.7, 4.1, 3.3}; /* results computed using GSL 1D cubic interpolation twice */ double zval[] = { 1.4, 2.46782030941187003, 10.7717721621846465, 4.80725067958096375, 11.6747032398627297, 11.2619968682970111, 9.00168877916872567}; size_t xsize = sizeof(xarr) / sizeof(xarr[0]); size_t ysize = sizeof(yarr) / sizeof(yarr[0]); size_t test_size = sizeof(xval) / sizeof(xval[0]); status = test_interp2d(xarr, yarr, zarr, xsize, ysize, xval, yval, zval, NULL, NULL, NULL, NULL, NULL, test_size, gsl_interp2d_bicubic); gsl_test(status, "bicubic interpolation on nonlinear symmetric function"); return status; } /* runs all the tests */ int test_interp2d_main(void) { int status = 0; status += test_bilinear_symmetric(); status += test_bilinear_asymmetric_z(); status += test_bicubic(); status += test_bicubic_nonlinear(); status += test_bicubic_nonlinear_nonsq(); return status; }
{ "alphanum_fraction": 0.5956062408, "avg_line_length": 41.0718390805, "ext": "c", "hexsha": "547949fea3b6b5619e3610b0c5a123b5a351c946", "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": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_path": "thirdparty/gsl-2.7/interpolation/test2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "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": "igormcoelho/optstats", "max_issues_repo_path": "thirdparty/gsl-2.7/interpolation/test2d.c", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_path": "thirdparty/gsl-2.7/interpolation/test2d.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4955, "size": 14293 }
/*** * Copyright 2020 The Katla Authors * * 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 KATLA_SQLITE_DATABASE_H #define KATLA_SQLITE_DATABASE_H #include "katla/core/core.h" #include "katla/core/error.h" #include "sqlite3.h" #include <memory> #include <vector> #include <optional> #include <gsl/span> namespace katla { struct SqliteTableData { int nrOfColumns {}; std::vector<std::string> columnNames; std::vector<std::string> data; }; struct SqliteQueryResult { std::optional<SqliteTableData> queryResult; }; class SqliteDatabase { public: SqliteDatabase(); virtual ~SqliteDatabase(); outcome::result<void, Error> init(); outcome::result<void, Error> open(); outcome::result<void, Error> close(); outcome::result<void, Error> create(std::string path); outcome::result<SqliteQueryResult, Error> exec(std::string sql); outcome::result<SqliteQueryResult, Error> insert(std::string table, gsl::span<std::pair<std::string, std::string>> values); void setPath(std::string path) { m_path = path; } bool isOpen () { return m_handle != nullptr; } private: sqlite3* m_handle {}; std::string m_path {}; }; } #endif
{ "alphanum_fraction": 0.6963048499, "avg_line_length": 23.7260273973, "ext": "h", "hexsha": "f30b8231478fa57b772d13be412d05fa7faac4a1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "plok/katla", "max_forks_repo_path": "sqlite/sqlite-database.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "plok/katla", "max_issues_repo_path": "sqlite/sqlite-database.h", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "plok/katla", "max_stars_repo_path": "sqlite/sqlite-database.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 416, "size": 1732 }
#pragma once #include "common/to_do.h" #include "open_file.h" #include "trees/regular_file.h" #include <gsl/span> namespace dogbox::tree { enum class read_caching { none, one_piece }; inline std::ostream &operator<<(std::ostream &out, read_caching const printed) { switch (printed) { case read_caching::none: return out << "none"; case read_caching::one_piece: return out << "one_piece"; } TO_DO(); } constexpr dogbox::tree::read_caching all_read_caching_modes[] = { dogbox::tree::read_caching::none, dogbox::tree::read_caching::one_piece}; size_t read_file(open_file &file, sqlite3 &database, regular_file::length_type const offset, gsl::span<std::byte> const into, read_caching const caching); }
{ "alphanum_fraction": 0.6192714454, "avg_line_length": 25.7878787879, "ext": "h", "hexsha": "89f71973dee558301335799644e97a143bc371f2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "TyRoXx/dogbox", "max_forks_repo_path": "trees/read_file.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_issues_repo_issues_event_max_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "TyRoXx/dogbox", "max_issues_repo_path": "trees/read_file.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "TyRoXx/dogbox", "max_stars_repo_path": "trees/read_file.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 207, "size": 851 }
/* cdf/tdistinv.c * * Copyright (C) 2007, 2010 Brian Gough * Copyright (C) 2002 Jason H. Stover. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_gamma.h> #include <stdio.h> static double inv_cornish_fisher (double z, double nu) { double a = 1 / (nu - 0.5); double b = 48.0 / (a * a); double cf1 = z * (3 + z * z); double cf2 = z * (945 + z * z * (360 + z * z * (63 + z * z * 4))); double y = z - cf1 / b + cf2 / (10 * b * b); double t = GSL_SIGN (z) * sqrt (nu * expm1 (a * y * y)); return t; } double gsl_cdf_tdist_Pinv (const double P, const double nu) { double x, ptail; if (P == 1.0) { return GSL_POSINF; } else if (P == 0.0) { return GSL_NEGINF; } if (nu == 1.0) { x = tan (M_PI * (P - 0.5)); return x; } else if (nu == 2.0) { x = (2 * P - 1) / sqrt (2 * P * (1 - P)); return x; } ptail = (P < 0.5) ? P : 1 - P; if (sqrt (M_PI * nu / 2) * ptail > pow (0.05, nu / 2)) { double xg = gsl_cdf_ugaussian_Pinv (P); x = inv_cornish_fisher (xg, nu); } else { /* Use an asymptotic expansion of the tail of integral */ double beta = gsl_sf_beta (0.5, nu / 2); if (P < 0.5) { x = -sqrt (nu) * pow (beta * nu * P, -1.0 / nu); } else { x = sqrt (nu) * pow (beta * nu * (1 - P), -1.0 / nu); } /* Correct nu -> nu/(1+nu/x^2) in the leading term to account for higher order terms. This avoids overestimating x, which makes the iteration unstable due to the rapidly decreasing tails of the distribution. */ x /= sqrt (1 + nu / (x * x)); } { double dP, phi; unsigned int n = 0; start: dP = P - gsl_cdf_tdist_P (x, nu); phi = gsl_ran_tdist_pdf (x, nu); if (dP == 0.0 || n++ > 32) goto end; { double lambda = dP / phi; double step0 = lambda; double step1 = ((nu + 1) * x / (x * x + nu)) * (lambda * lambda / 4.0); double step = step0; if (fabs (step1) < fabs (step0)) { step += step1; } if (P > 0.5 && x + step < 0) x /= 2; else if (P < 0.5 && x + step > 0) x /= 2; else x += step; if (fabs (step) > 1e-10 * fabs (x)) goto start; } end: if (fabs(dP) > GSL_SQRT_DBL_EPSILON * P) { GSL_ERROR_VAL("inverse failed to converge", GSL_EFAILED, GSL_NAN); } return x; } } double gsl_cdf_tdist_Qinv (const double Q, const double nu) { double x, qtail; if (Q == 0.0) { return GSL_POSINF; } else if (Q == 1.0) { return GSL_NEGINF; } if (nu == 1.0) { x = tan (M_PI * (0.5 - Q)); return x; } else if (nu == 2.0) { x = (1 - 2 * Q) / sqrt (2 * Q * (1 - Q)); return x; } qtail = (Q < 0.5) ? Q : 1 - Q; if (sqrt (M_PI * nu / 2) * qtail > pow (0.05, nu / 2)) { double xg = gsl_cdf_ugaussian_Qinv (Q); x = inv_cornish_fisher (xg, nu); } else { /* Use an asymptotic expansion of the tail of integral */ double beta = gsl_sf_beta (0.5, nu / 2); if (Q < 0.5) { x = sqrt (nu) * pow (beta * nu * Q, -1.0 / nu); } else { x = -sqrt (nu) * pow (beta * nu * (1 - Q), -1.0 / nu); } /* Correct nu -> nu/(1+nu/x^2) in the leading term to account for higher order terms. This avoids overestimating x, which makes the iteration unstable due to the rapidly decreasing tails of the distribution. */ x /= sqrt (1 + nu / (x * x)); } { double dQ, phi; unsigned int n = 0; start: dQ = Q - gsl_cdf_tdist_Q (x, nu); phi = gsl_ran_tdist_pdf (x, nu); if (dQ == 0.0 || n++ > 32) goto end; { double lambda = - dQ / phi; double step0 = lambda; double step1 = ((nu + 1) * x / (x * x + nu)) * (lambda * lambda / 4.0); double step = step0; if (fabs (step1) < fabs (step0)) { step += step1; } if (Q < 0.5 && x + step < 0) x /= 2; else if (Q > 0.5 && x + step > 0) x /= 2; else x += step; if (fabs (step) > 1e-10 * fabs (x)) goto start; } } end: return x; }
{ "alphanum_fraction": 0.5079395817, "avg_line_length": 21.5166666667, "ext": "c", "hexsha": "d64e496c8ab71fa0cd9046f00bccd6e50aa1ea6a", "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": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_path": "folding_libs/gsl-1.14/cdf/tdistinv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "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": "parasol-ppl/PPL_utils", "max_issues_repo_path": "folding_libs/gsl-1.14/cdf/tdistinv.c", "max_line_length": 77, "max_stars_count": null, "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/cdf/tdistinv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1735, "size": 5164 }
#ifndef __CNN_CONV_H__ #define __CNN_CONV_H__ #include <cblas.h> #include <string.h> #include "cnn_macro.h" #include "cnn_types.h" #ifdef CNN_WITH_CUDA #include <cublas_v2.h> #include <cuda_runtime.h> #include "cnn_init.h" void cnn_map_gpu(float* dst, float* src, int* map, int len); void cnn_map_inv_gpu(float* dst, float* src, int* map, int len); #endif static inline void cnn_conv_unroll_2d_valid(int* indexMap, int dstHeight, int dstWidth, int kSize, int srcHeight, int srcWidth, int srcCh) { int __kMemSize = kSize * kSize; int __srcImSize = srcHeight * srcWidth; int __indexMapCols = __kMemSize * srcCh; for (int __h = 0; __h < dstHeight; __h++) { int __dstRowShift = __h * dstWidth; for (int __w = 0; __w < dstWidth; __w++) { int __indexMapRow = __dstRowShift + __w; int __indexMemBase = __indexMapRow * __indexMapCols; for (int __ch = 0; __ch < srcCh; __ch++) { int __indexMemShiftBase = __indexMemBase + __kMemSize * __ch; int __srcChShift = __ch * __srcImSize; for (int __convH = 0; __convH < kSize; __convH++) { int __indexMemShift = __indexMemShiftBase + __convH * kSize; int __srcShift = (__h + __convH) * srcWidth + __srcChShift; for (int __convW = 0; __convW < kSize; __convW++) { indexMap[__indexMemShift + __convW] = __srcShift + (__w + __convW); } } } } } } static inline void cnn_conv_unroll_2d_same(int* indexMap, int dstHeight, int dstWidth, int kSize, int srcHeight, int srcWidth, int srcCh) { int __kMemSize = kSize * kSize; int __srcImSize = srcHeight * srcWidth; int __indexMapCols = __kMemSize * srcCh; int __convHBase = -kSize / 2; int __convWBase = -kSize / 2; for (int __h = 0; __h < dstHeight; __h++) { int __dstRowShift = __h * dstWidth; for (int __w = 0; __w < dstWidth; __w++) { int __indexMapRow = __dstRowShift + __w; int __indexMemBase = __indexMapRow * __indexMapCols; for (int __ch = 0; __ch < srcCh; __ch++) { int __indexMemShiftBase = __indexMemBase + __kMemSize * __ch; int __srcChShift = __ch * __srcImSize; for (int __convH = 0; __convH < kSize; __convH++) { int __indexMemShift = __indexMemShiftBase + __convH * kSize; int __convHIndex = __h + __convH + __convHBase; if (__convHIndex >= 0 && __convHIndex < srcHeight) { int __srcShift = __convHIndex * srcWidth + __srcChShift; for (int __convW = 0; __convW < kSize; __convW++) { int __convWIndex = __w + __convW + __convWBase; if (__convWIndex >= 0 && __convWIndex < srcWidth) { int __tmpIndex = __srcShift + __convWIndex; indexMap[__indexMemShift + __convW] = __tmpIndex; } } } } } } } } static inline void cnn_conv_2d(float* dst, int dstHeight, int dstWidth, float* kernel, int kSize, int chIn, int chOut, float* src, int srcHeight, int srcWidth) { int __kMemSize = kSize * kSize; int __filterSize = chIn * __kMemSize; int __dstImSize = dstHeight * dstWidth; int __srcImSize = srcHeight * srcWidth; for (int __chOut = 0; __chOut < chOut; __chOut++) { int __filterShift = __chOut * __filterSize; int __dstChShift = __chOut * __dstImSize; for (int __chIn = 0; __chIn < chIn; __chIn++) { int __kShiftBase = __chIn * __kMemSize + __filterShift; int __srcChShift = __chIn * __srcImSize; for (int __h = 0; __h < dstHeight; __h++) { int __dstShift = __h * dstWidth + __dstChShift; for (int __w = 0; __w < dstWidth; __w++) { float __conv = 0; for (int __convH = 0; __convH < kSize; __convH++) { int __kShift = __convH * kSize + __kShiftBase; int __srcShift = (__h + __convH) * srcWidth + __srcChShift; for (int __convW = 0; __convW < kSize; __convW++) { __conv += kernel[__kShift + __convW] * src[__srcShift + (__w + __convW)]; } } dst[__dstShift + __w] += __conv; } } } } } static inline void cnn_conv_2d_grad(float* srcGrad, int srcHeight, int srcWidth, float* kernel, int kSize, int srcCh, int lCh, float* lGrad, int lHeight, int lWidth) { int __kMemSize = kSize * kSize; int __filterSize = srcCh * __kMemSize; int __lImSize = lHeight * lWidth; int __srcImSize = srcHeight * srcWidth; for (int __lCh = 0; __lCh < lCh; __lCh++) { int __filterShift = __lCh * __filterSize; int __lChShift = __lCh * __lImSize; for (int __srcCh = 0; __srcCh < srcCh; __srcCh++) { int __srcChShift = __srcCh * __srcImSize; int __kShiftBase = __srcCh * __kMemSize + __filterShift; for (int __h = 0; __h < lHeight; __h++) { int __lShift = __h * lHeight + __lChShift; for (int __w = 0; __w < lWidth; __w++) { for (int __convH = 0; __convH < kSize; __convH++) { int __kShift = __convH * kSize + __kShiftBase; int __srcShift = (__h + __convH) * srcWidth + __srcChShift; for (int __convW = 0; __convW < kSize; __convW++) { srcGrad[__srcShift + (__w + __convW)] += lGrad[__lShift + __w] * kernel[__kShift + __convW]; } } } } } } } static inline void cnn_conv_2d_kernel_grad(float* lGrad, int lHeight, int lWidth, float* kGrad, int kSize, int lCh, int srcCh, float* src, int srcHeight, int srcWidth) { int __kMemSize = kSize * kSize; int __filterSize = srcCh * __kMemSize; int __lImSize = lHeight * lWidth; int __srcImSize = srcHeight * srcWidth; for (int __lCh = 0; __lCh < lCh; __lCh++) { int __filterShift = __lCh * __filterSize; int __lChShift = __lCh * __lImSize; for (int __srcCh = 0; __srcCh < srcCh; __srcCh++) { int __srcChShift = __srcCh * __srcImSize; int __kShiftBase = __srcCh * __kMemSize + __filterShift; for (int __h = 0; __h < lHeight; __h++) { int __lShift = __h * lWidth + __lChShift; for (int __w = 0; __w < lWidth; __w++) { for (int __convH = 0; __convH < kSize; __convH++) { int __kShift = __convH * kSize + __kShiftBase; int __srcShift = (__h + __convH) * srcWidth + __srcChShift; for (int __convW = 0; __convW < kSize; __convW++) { kGrad[__kShift + __convW] += lGrad[__lShift + __w] * src[__srcShift + (__w + __convW)]; } } } } } } } static inline void cnn_forward_conv(union CNN_LAYER* layerRef, struct CNN_CONFIG* cfgRef, int layerIndex) { #ifdef CNN_WITH_CUDA float alpha = 1.0; float beta = 0.0; struct CNN_LAYER_CONV* layerPtr = &layerRef[layerIndex].conv; struct CNN_MAT* outData = &layerPtr->outMat.data; struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data; cnn_assert_cudnn(cudnnConvolutionForward( cnnInit.cudnnHandle, // &alpha, // layerPtr->srcTen, preOutData->mat, // layerPtr->kernelTen, layerPtr->kernel.mat, // layerPtr->convDesc, layerPtr->convAlgoFW, cnnInit.wsData, cnnInit.wsSize, // &beta, // layerPtr->dstTen, outData->mat)); #if defined(CNN_CONV_BIAS_FILTER) beta = 1.0; cnn_assert_cudnn(cudnnAddTensor(cnnInit.cudnnHandle, // &alpha, // layerPtr->biasTen, layerPtr->bias.mat, // &beta, // layerPtr->dstTen, outData->mat)); #endif #else // Cache int mapRows = layerRef[layerIndex].outMat.width * layerRef[layerIndex].outMat.height; int mapCols = layerRef[layerIndex - 1].outMat.channel * cfgRef->layerCfg[layerIndex].conv.size * cfgRef->layerCfg[layerIndex].conv.size; int mapSize = mapRows * mapCols; int* indexMap = layerRef[layerIndex].conv.indexMap; int chOut = layerRef[layerIndex].outMat.channel; float* kernel = layerRef[layerIndex].conv.kernel.mat; // Clear outputs // memset(layerRef[layerIndex].outMat.data.mat, 0, // sizeof(float) * layerRef[layerIndex].outMat.data.rows * // layerRef[layerIndex].outMat.data.cols); for (int j = 0; j < cfgRef->batch; j++) { int srcShift = j * layerRef[layerIndex - 1].outMat.data.cols; int dstShift = j * layerRef[layerIndex].outMat.data.cols; int mapShift = j * mapSize; float* srcPtr = layerRef[layerIndex - 1].outMat.data.mat + srcShift; float* dstPtr = layerRef[layerIndex].outMat.data.mat + dstShift; float* mapPtr = layerRef[layerIndex].conv.unroll.mat + mapShift; for (int k = 0; k < mapSize; k++) { int tmpIndex = indexMap[k]; if (tmpIndex >= 0) { mapPtr[k] = srcPtr[tmpIndex]; } } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, chOut, mapRows, mapCols, 1.0, kernel, mapCols, mapPtr, mapCols, 0.0, dstPtr, mapRows); // Add bias #if defined(CNN_CONV_BIAS_FILTER) #ifdef DEBUG #pragma message("cnn_forward_conv(): Enable convolution filter bias") #endif for (int ch = 0; ch < chOut; ch++) { cblas_saxpy( mapRows, 1.0, &layerRef[layerIndex].conv.bias.mat[ch], 0, &layerRef[layerIndex].outMat.data.mat[dstShift + ch * mapRows], 1); } #elif defined(CNN_CONV_BIAS_LAYER) #ifdef DEBUG #pragma message("cnn_forward_conv(): Enable convolution layer bias") #endif cblas_saxpy(layerRef[layerIndex].conv.bias.cols, 1.0, layerRef[layerIndex].conv.bias.mat, 1, &layerRef[layerIndex].outMat.data.mat[dstShift], 1); #endif } #endif } static inline void cnn_backward_conv(union CNN_LAYER* layerRef, struct CNN_CONFIG* cfgRef, int layerIndex) { #ifdef CNN_WITH_CUDA float alpha = 1.0; float beta = 1.0; struct CNN_LAYER_CONV* layerPtr = &layerRef[layerIndex].conv; struct CNN_MAT* outData = &layerPtr->outMat.data; struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data; cnn_assert_cudnn(cudnnConvolutionBackwardFilter( cnnInit.cudnnHandle, // &alpha, // layerPtr->srcTen, preOutData->mat, // layerPtr->dstTen, outData->grad, // layerPtr->convDesc, layerPtr->convAlgoBWFilter, cnnInit.wsData, cnnInit.wsSize, // &beta, // layerPtr->kernelTen, layerPtr->kernel.grad)); cnn_assert_cudnn( cudnnConvolutionBackwardBias(cnnInit.cudnnHandle, // &alpha, // layerPtr->dstTen, outData->grad, // &beta, // layerPtr->biasTen, layerPtr->bias.grad)); #else // Cache int mapRows = layerRef[layerIndex].outMat.width * layerRef[layerIndex].outMat.height; int mapCols = layerRef[layerIndex - 1].outMat.channel * cfgRef->layerCfg[layerIndex].conv.size * cfgRef->layerCfg[layerIndex].conv.size; int mapSize = mapRows * mapCols; int* indexMap = layerRef[layerIndex].conv.indexMap; int chOut = layerRef[layerIndex].outMat.channel; float* kernel = layerRef[layerIndex].conv.kernel.mat; float* kGrad = layerRef[layerIndex].conv.kernel.grad; // Sum gradient for (int j = 0; j < cfgRef->batch; j++) { int gradShift = j * layerRef[layerIndex].outMat.data.cols; int mapShift = j * mapSize; float* gradPtr = &layerRef[layerIndex].outMat.data.grad[gradShift]; float* mapPtr = &layerRef[layerIndex].conv.unroll.mat[mapShift]; cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, chOut, mapCols, mapRows, 1.0, gradPtr, mapRows, mapPtr, mapCols, 1.0, kGrad, mapCols); // Sum bias gradient matrix #if defined(CNN_CONV_BIAS_FILTER) #ifdef DEBUG #pragma message("cnn_forward_conv(): Enable convolution filter bias") #endif for (int ch = 0; ch < chOut; ch++) { cblas_saxpy(mapRows, 1.0, &gradPtr[ch * mapRows], 1, &layerRef[layerIndex].conv.bias.grad[ch], 0); } #elif defined(CNN_CONV_BIAS_LAYER) #ifdef DEBUG #pragma message("cnn_forward_conv(): Enable convolution layer bias") #endif cblas_saxpy(layerRef[layerIndex].conv.bias.cols, 1.0, gradPtr, 1, layerRef[layerIndex].conv.bias.grad, 1); #endif } #endif // Find layer gradient if (layerIndex > 1) { #ifdef CNN_WITH_CUDA cudaMemset(preOutData->grad, 0, sizeof(float) * preOutData->rows * preOutData->cols); beta = 0.0; cnn_assert_cudnn(cudnnConvolutionBackwardData( cnnInit.cudnnHandle, // &alpha, // layerPtr->kernelTen, layerPtr->kernel.mat, // layerPtr->dstTen, outData->grad, // layerPtr->convDesc, layerPtr->convAlgoBWGrad, cnnInit.wsData, cnnInit.wsSize, // &beta, // layerPtr->srcTen, preOutData->grad)); #else memset(layerRef[layerIndex - 1].outMat.data.grad, 0, sizeof(float) * layerRef[layerIndex - 1].outMat.data.rows * layerRef[layerIndex - 1].outMat.data.cols); for (int j = 0; j < cfgRef->batch; j++) { int gradShift = j * layerRef[layerIndex].outMat.data.cols; int preGradShift = j * layerRef[layerIndex - 1].outMat.data.cols; int mapShift = j * mapSize; float* gradPtr = layerRef[layerIndex].outMat.data.grad + gradShift; float* preGradPtr = layerRef[layerIndex - 1].outMat.data.grad + preGradShift; float* mapPtr = layerRef[layerIndex].conv.unroll.grad + mapShift; cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, mapRows, mapCols, chOut, 1.0, gradPtr, mapRows, kernel, mapCols, 0.0, mapPtr, mapCols); for (int i = 0; i < mapSize; i++) { int tmpIndex = indexMap[i]; if (tmpIndex >= 0) { preGradPtr[tmpIndex] += mapPtr[i]; } } } #endif } } #endif
{ "alphanum_fraction": 0.5062104523, "avg_line_length": 36.5481798715, "ext": "h", "hexsha": "a70d0ada64716f016554db044f70ff0674b9c160", "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": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jamesljlster/cnn", "max_forks_repo_path": "src/cnn_conv.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "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": "jamesljlster/cnn", "max_issues_repo_path": "src/cnn_conv.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jamesljlster/cnn", "max_stars_repo_path": "src/cnn_conv.h", "max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z", "num_tokens": 4297, "size": 17068 }
#include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <uuid/uuid.h> #include <openssl/sha.h> #include <gsl/gsl_statistics_double.h> #include "sig.h" #include "pok.h" #include "like.h" #include "bn512.h" #include "utils_like.h" double print_trials_res(double * trials_res, int nb_trials) { double mean = gsl_stats_mean(trials_res, 1, nb_trials); double stddev = gsl_stats_sd_m(trials_res, 1, nb_trials, mean); double confidence_lo = mean - ((1.96 * stddev) / sqrt(nb_trials)); double confidence_hi = mean + ((1.96 * stddev) / sqrt(nb_trials)); printf(" mean = %f\n", mean * 1000); printf(" stddev = %f\n", stddev * 1000); printf(" 95%% confidence inteval = [%f, %f]\n\n", confidence_lo * 1000, confidence_hi * 1000); return mean * 1000; } void mesure_pairing(int nb_trials) { printf("pairing : \n"); mclBnG1 P; mclBnG2 Q; mclBnGT e; mclBn_init(MCL_BN462, MCLBN_COMPILED_TIME_VAR); mclBnG1_hashAndMapTo(&P, "abc", 3); mclBnG2_hashAndMapTo(&Q, "def", 3); double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); mclBn_pairing(&e, &P, &Q); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); } void mesure_arithmetic_EC(int nb_trials) { mclBnG1 P, xP; mclBnG2 Q, xQ; mclBnFr x; mclBn_init(MCL_BN462, MCLBN_COMPILED_TIME_VAR); mclBnFr_setByCSPRNG(&x); mclBnG1_hashAndMapTo(&P, "abc", 3); mclBnG2_hashAndMapTo(&Q, "def", 3); double trials_res[nb_trials]; clock_t begin; clock_t end; printf("Scalar mult in G1 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); mclBnG1_mul(&xP, &P, &x); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("Scalar mult in G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); mclBnG2_mul(&xQ, &Q, &x); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("Add point in G1 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); mclBnG1_add(&xP, &P, &xP); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("Add point in G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); mclBnG2_add(&xQ, &Q, &xQ); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); } void mesure_edd25519(int nb_trials) { struct stat st = {0}; size_t sig_len = ED25519_SIG_LENGTH; unsigned char * sig = (unsigned char *) malloc(sig_len * sizeof(unsigned char));; unsigned char msg[] = "Test sig"; if (stat("./keys", &st) == -1) { mkdir("./keys", 0700); } sgen_ed25519("keys/pub.pem", "keys/priv.pem"); double trials_res[nb_trials]; clock_t begin; clock_t end; printf("sig ed25519 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); ssig_ed25519("keys/priv.pem", msg, sizeof(msg), &sig, &sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("verif ed25519 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); sver_ed25519("keys/pub.pem", msg, sizeof(msg), sig, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); free(sig); } void mesure_sok(int nb_trials) { const char * G2_basePoint_hexstr = "1 0257ccc85b58dda0dfb38e3a8cbdc5482e0337e7c1cd96ed61c913820408208f9ad2699bad92e0032ae1f0aa6a8b48807695468e3d934ae1e4df 1d2e4343e8599102af8edca849566ba3c98e2a354730cbed9176884058b18134dd86bae555b783718f50af8b59bf7e850e9b73108ba6aa8cd283 0a0650439da22c1979517427a20809eca035634706e23c3fa7a6bb42fe810f1399a1f41c9ddae32e03695a140e7b11d7c3376e5b68df0db7154e 073ef0cbd438cbe0172c8ae37306324d44d5e6b0c69ac57b393f1ab370fd725cc647692444a04ef87387aa68d53743493b9eba14cc552ca2a93a"; char msg[] = "test"; mclBnFr x, d; mclBnG2 Q, xQ, Rho; mclBnFr_setByCSPRNG(&x); mclBnG2_setStr(&Q, G2_basePoint_hexstr, strlen(G2_basePoint_hexstr), 16); mclBnG2_mul(&xQ, &Q, &x); double trials_res[nb_trials]; clock_t begin; clock_t end; printf("sok_G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); sok_G2(&Q, &x, &xQ, (unsigned char *)msg, strlen(msg), &Rho, &d); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("sokver_G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); sokver_G2(&Q, &xQ, &Rho, &d, (unsigned char *)msg, strlen(msg)); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); } void mesure_nipok(int nb_trials) { const char * G1_basePoint_hexstr = "1 21a6d67ef250191fadba34a0a30160b9ac9264b6f95f63b3edbec3cf4b2e689db1bbb4e69a416a0b1e79239c0372e5cd70113c98d91f36b6980d 0118ea0460f7f7abb82b33676a7432a490eeda842cccfa7d788c659650426e6af77df11b8ae40eb80f475432c66600622ecaa8a5734d36fb03de"; mclBnFr x, d; mclBnG1 P, xP, Rho; mclBnFr_setByCSPRNG(&x); mclBnG1_setStr(&P, G1_basePoint_hexstr, strlen(G1_basePoint_hexstr), 16); mclBnG1_mul(&xP, &P, &x); double trials_res[nb_trials]; clock_t begin; clock_t end; printf("nipok_G1 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); nipok_G1(&P, &x, &xP, &Rho, &d); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("nipokver_G1 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); nipokver_G1(&P, &xP, &Rho, &d); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); } void mesure_eqnipok(int nb_trials) { const char * G1_basePoint_hexstr = "1 21a6d67ef250191fadba34a0a30160b9ac9264b6f95f63b3edbec3cf4b2e689db1bbb4e69a416a0b1e79239c0372e5cd70113c98d91f36b6980d 0118ea0460f7f7abb82b33676a7432a490eeda842cccfa7d788c659650426e6af77df11b8ae40eb80f475432c66600622ecaa8a5734d36fb03de"; const char * G2_basePoint_hexstr = "1 0257ccc85b58dda0dfb38e3a8cbdc5482e0337e7c1cd96ed61c913820408208f9ad2699bad92e0032ae1f0aa6a8b48807695468e3d934ae1e4df 1d2e4343e8599102af8edca849566ba3c98e2a354730cbed9176884058b18134dd86bae555b783718f50af8b59bf7e850e9b73108ba6aa8cd283 0a0650439da22c1979517427a20809eca035634706e23c3fa7a6bb42fe810f1399a1f41c9ddae32e03695a140e7b11d7c3376e5b68df0db7154e 073ef0cbd438cbe0172c8ae37306324d44d5e6b0c69ac57b393f1ab370fd725cc647692444a04ef87387aa68d53743493b9eba14cc552ca2a93a"; mclBnFr x, d; mclBnG1 P, xP, Rho; mclBnG2 Q, xQ, Sigma; mclBnFr_setByCSPRNG(&x); mclBnG1_setStr(&P, G1_basePoint_hexstr, strlen(G1_basePoint_hexstr), 16); mclBnG2_setStr(&Q, G2_basePoint_hexstr, strlen(G2_basePoint_hexstr), 16); mclBnG1_mul(&xP, &P, &x); mclBnG2_mul(&xQ, &Q, &x); double trials_res[nb_trials]; clock_t begin; clock_t end; printf("eq_nipok_G1_G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); eq_nipok_G1_G2(&P, &xP, &Q, &xQ, &x, &Rho, &Sigma, &d); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); printf("eq_nipokver_G1_G2 : \n"); for(int i = 0; i < nb_trials; i++) { begin = clock(); eq_nipokver_G1_G2(&P, &xP, &Q, &xQ, &Rho, &Sigma, &d); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } print_trials_res(trials_res, nb_trials); } double mesure_ake_a_get_mx(mclBnG1 * P, mclBnG2 * Q, mclBnFr * x, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_a_get_mx(P, Q, x, omega, omega_len, xP, xQ, x_ni); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_mx(mclBnG1 * P, mclBnG1 * xP, mclBnG2 * Q, mclBnG2 * xQ, unsigned char * omega, size_t omega_len, XY_ni * x_ni, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_mx(P, xP, Q, xQ, omega, omega_len, x_ni); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_b_get_my(mclBnG2 * Q, mclBnFr * y, unsigned char * omega, size_t omega_len, mclBnG2 * yQ, XY_ni * y_ni, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_b_get_my(Q, y, omega, omega_len, yQ, y_ni); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_b_get_sigma_Y_1(char * priv_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_b_get_sigma_Y_1(priv_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_my(mclBnG2 * Q, mclBnG2 * yQ, unsigned char * omega, size_t omega_len, XY_ni * y_ni, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_my(Q, yQ, omega, omega_len, y_ni); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_sigma_Y_1(char * pub_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_sigma_Y_1(pub_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_a_get_sigma_X(char * priv_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_a_get_sigma_X(priv_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_sigma_X(char * pub_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_sigma_X(pub_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_b_get_sigma_Y_2(char * priv_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, unsigned char * sigma_Y_2, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_b_get_sigma_Y_2(priv_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_sigma_Y_2(char * pub_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, unsigned char * sigma_Y_2, size_t sig_len, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_sigma_Y_2(pub_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_a_get_shared_key(mclBnG1 * L_pk, mclBnG2 * yQ, mclBnFr * x, mclBnGT * ka, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_a_get_shared_key(L_pk, yQ, x, ka); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_b_get_shared_key(mclBnG1 * L_pk, mclBnG2 * xQ, mclBnFr * y, mclBnGT * kb, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_b_get_shared_key(L_pk, xQ, y, kb); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_ake_O_get_sst(char * priv_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, unsigned char * sigma_Y_2, size_t sig_len, SST * sst, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); ake_O_get_sst(priv_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, sst); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; free(sst->m); free(sst->sigma_O); } return print_trials_res(trials_res, nb_trials); } double mesure_verify_sst(char * pub_key_path, unsigned char * omega, size_t omega_len, mclBnG1 * xP, mclBnG2 * xQ, XY_ni * x_ni, mclBnG2 * yQ, XY_ni * y_ni, unsigned char * sigma_Y_1 , unsigned char * sigma_X, unsigned char * sigma_Y_2, size_t sig_len, SST * sst, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_sst(pub_key_path, omega, omega_len, xP, xQ, x_ni, yQ, y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, sst); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_L_ni_for_2L(mclBnG1 * P, mclBnG1 * L1_pk, Lambda_ni * l1_ni, mclBnG1 * L2_pk, Lambda_ni * l2_ni, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_L_ni(P, 4, L1_pk, l1_ni, L2_pk, l2_ni); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_tdgen_get_li_T1_for_2L(mclBnG1 * xP, mclBnG2 * yQ, mclBnFr * l1_sk, mclBnGT * l1_T1, mclBnFr * l2_sk, mclBnGT * l2_T1, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); tdgen_get_li_T1(xP, yQ, 4, l1_sk, l1_T1, l2_sk, l2_T1); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_tdgen_get_li_T2_for_2L(mclBnG1 * P, mclBnG1 * xP, mclBnG2 * yQ, mclBnG1 * L1_pk, mclBnFr * l1_sk, mclBnGT * l1_T1, Lambda_eq_ni * l1_T2, mclBnG1 * L2_pk, mclBnFr * l2_sk, mclBnGT * l2_T1, Lambda_eq_ni * l2_T2, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); tdgen_get_li_T2(P, xP, yQ, 8, L1_pk, l1_sk, l1_T1, l1_T2, L2_pk, l2_sk, l2_T1, l2_T2); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_verify_li_T2_for_2L(mclBnG1 * P, mclBnG1 * xP, mclBnG2 * yQ, mclBnG1 * L1_pk, mclBnGT * l1_T1, Lambda_eq_ni * l1_T2, mclBnG1 * L2_pk, mclBnGT * l2_T1, Lambda_eq_ni * l2_T2, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); verify_li_T2(P, xP, yQ, 6, L1_pk, l1_T1, l1_T2, L2_pk, l2_T1, l2_T2); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } double mesure_open_get_shared_key_for_2(mclBnGT * k, mclBnGT * l1_T1, mclBnGT * l2_T1, int nb_trials) { double trials_res[nb_trials]; clock_t begin; clock_t end; for(int i = 0; i < nb_trials; i++) { begin = clock(); open_get_shared_key(k, 2, l1_T1, l2_T1); end = clock(); trials_res[i] = (double)(end - begin) / CLOCKS_PER_SEC; } return print_trials_res(trials_res, nb_trials); } int main(int argc, char *argv[]) { printf("Run multiple times differents functions of the like potocol. All mesures are in ms.\n\n"); // Mesure perf parameter int nb_trials = 100; if( argc == 2 ) nb_trials = atoi(argv[1]); printf("Number of trials : %d\n\n", nb_trials); double total_time_A = 0.0; double total_time_B = 0.0; double total_time_O = 0.0; double total_time_Ver = 0.0; double total_time_TDGen = 0.0; double total_time_Open = 0.0; /******************************************************************* * * * INDEPENDANT MESURES * * * * *****************************************************************/ mesure_pairing(nb_trials); mesure_arithmetic_EC(nb_trials); mesure_edd25519(nb_trials); mesure_sok(nb_trials); mesure_nipok(nb_trials); mesure_eqnipok(nb_trials); /******************************************************************* * * * LIKE MESURES * * * * *****************************************************************/ // General Param mclBnG1 P, xP; mclBnG2 Q, xQ, yQ; mclBnFr x, y; XY_ni x_ni, y_ni; mclBnGT ka, kb, k, l1_T1, l2_T1; SST sst; Lambda_eq_ni l1_T2, l2_T2; // Id size_t id_len = sizeof(uuid_t); uuid_t id_A, id_B, id_L1, id_L2; uuid_generate_random(id_A); uuid_generate_random(id_B); uuid_generate_random(id_L1); uuid_generate_random(id_L2); size_t omega_len = 4 * id_len; unsigned char omega[omega_len]; // Keys char pub_key_A[] = "keys/a_pub_key.pem"; char priv_key_A[] = "keys/a_priv_key.pem"; char pub_key_B[] = "keys/b_pub_key.pem"; char priv_key_B[] = "keys/b_priv_key.pem"; char pub_key_O[] = "keys/o_pub_key.pem"; char priv_key_O[] = "keys/o_priv_key.pem"; mclBnG1 L1_pk, L2_pk, L_pk; mclBnFr l1_sk, l2_sk; Lambda_ni l1_ni, l2_ni; // Sig buffer size_t sig_len = ED25519_SIG_LENGTH; unsigned char * sigma_Y_1 = (unsigned char *) malloc(sig_len * sizeof(unsigned char)); unsigned char * sigma_X = (unsigned char *) malloc(sig_len * sizeof(unsigned char)); unsigned char * sigma_Y_2 = (unsigned char *) malloc(sig_len * sizeof(unsigned char)); // Setup setup(&P, &Q); //UKeyGen A u_o_key_gen(pub_key_A, priv_key_A); // UKeyGen B u_o_key_gen(pub_key_B, priv_key_B); // UKeyGen O u_o_key_gen(pub_key_O, priv_key_O); // LambdaKeyGen L1 a_key_gen(&P, &l1_sk, &L1_pk, &l1_ni); // LambdaKeyGen L2 a_key_gen(&P, &l2_sk, &L2_pk, &l2_ni); // AKE Precal verify_L_ni(&P, 4, &L1_pk, &l1_ni, &L2_pk, &l2_ni); ake_precalc_add_lipk(&L_pk, 2, &L1_pk, &L2_pk); ake_precalc_get_omega(omega, 8, id_A, id_len, id_B, id_len, id_L1, id_len, id_L2, id_len); // Mesure ake_a_get_mx printf("ake_a_get_mx : \n"); double time_ake_a_get_mx = mesure_ake_a_get_mx(&P, &Q, &x, omega, omega_len, &xP, &xQ, &x_ni, nb_trials); // A : ake_a_get_mx ake_a_get_mx(&P, &Q, &x, omega, omega_len, &xP, &xQ, &x_ni); total_time_A += time_ake_a_get_mx; // Mesure verify_mx printf("verify_mx : \n"); double time_verify_mx = mesure_verify_mx(&P, &xP, &Q, &xQ, omega, omega_len, &x_ni, nb_trials); // O : verify_mx verify_mx(&P, &xP, &Q, &xQ, omega, omega_len, &x_ni); total_time_O += time_verify_mx; // Mesure ake_b_get_my printf("ake_b_get_my : \n"); double time_ake_b_get_my = mesure_ake_b_get_my(&Q, &y, omega, omega_len, &yQ, &y_ni, nb_trials); // Mesure ake_b_get_sigma_Y_1 printf("ake_b_get_sigma_Y_1 : \n"); double time_ake_b_get_sigma_Y_1 = mesure_ake_b_get_sigma_Y_1(priv_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len, nb_trials); // B : ake_b_get_my, verify_mx, ake_b_get_sigma_Y_1 verify_mx(&P, &xP, &Q, &xQ, omega, omega_len, &x_ni); ake_b_get_my(&Q, &y, omega, omega_len, &yQ, &y_ni); ake_b_get_sigma_Y_1(priv_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len); total_time_B += time_verify_mx + time_ake_b_get_my + time_ake_b_get_sigma_Y_1; // Mesure verify_my printf("verify_my : \n"); double time_verify_my = mesure_verify_my(&Q, &yQ, omega, omega_len, &y_ni, nb_trials); // Mesure verify_sigma_Y_1 printf("verify_sigma_Y_1 : \n"); double time_verify_sigma_Y_1 = mesure_verify_sigma_Y_1(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len, nb_trials); // O : verify_my, verify_sigma_Y_1 verify_my(&Q, &yQ, omega, omega_len, &y_ni); verify_sigma_Y_1(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len); total_time_O += time_verify_my + time_verify_sigma_Y_1; // Mesure ake_a_get_sigma_X printf("ake_a_get_sigma_X : \n"); double time_ake_a_get_sigma_X = mesure_ake_a_get_sigma_X(priv_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len, nb_trials); // A : verify_my, verify_sigma_Y_1, ake_a_get_sigma_X verify_my(&Q, &yQ, omega, omega_len, &y_ni); verify_sigma_Y_1(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len); ake_a_get_sigma_X(priv_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len); total_time_A += time_verify_my + time_verify_sigma_Y_1 + time_ake_a_get_sigma_X; // Mesure verify_sigma_X printf("verify_sigma_X : \n"); double time_verify_sigma_X = mesure_verify_sigma_X(pub_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len, nb_trials); // O : verify_sigma_X verify_sigma_X(pub_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len); total_time_O += time_verify_sigma_X; // Mesure ake_b_get_sigma_Y_2 printf("ake_b_get_sigma_Y_2 : \n"); double time_ake_b_get_sigma_Y_2 = mesure_ake_b_get_sigma_Y_2(priv_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, nb_trials); // B : verify_sigma_X, ake_b_get_sigma_Y_2 verify_sigma_X(pub_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len); ake_b_get_sigma_Y_2(priv_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len); total_time_B += time_verify_sigma_X + time_ake_b_get_sigma_Y_2; // Mesure ake_a_get_shared_key printf("ake_a_get_shared_key : \n"); double time_ake_a_get_shared_key = mesure_ake_a_get_shared_key(&L_pk, &yQ, &x, &ka, nb_trials); // A : ake_a_get_shared_key ake_a_get_shared_key(&L_pk, &yQ, &x, &ka); total_time_A += time_ake_a_get_shared_key; // Mesure ake_b_get_shared_key printf("ake_b_get_shared_key : \n"); double time_ake_b_get_shared_key = mesure_ake_b_get_shared_key(&L_pk, &xQ, &y, &kb, nb_trials); // B : ake_b_get_shared_key ake_b_get_shared_key(&L_pk, &xQ, &y, &kb); total_time_B += time_ake_b_get_shared_key; // Mesure ake_b_get_sigma_Y_2 printf("verify_sigma_Y_2 : \n"); double time_verify_sigma_Y_2 = mesure_verify_sigma_Y_2(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, nb_trials); // Mesure ake_O_get_sst printf("ake_O_get_sst : \n"); double time_ake_O_get_sst = mesure_ake_O_get_sst(priv_key_O, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, &sst, nb_trials); // O : verify_sigma_Y_2, ake_O_get_sst verify_sigma_Y_2(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len); ake_O_get_sst(priv_key_O, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, &sst); total_time_O += time_verify_sigma_Y_2 + time_ake_O_get_sst; // Mesure verify_sst printf("verify_sst : \n"); double time_verify_sst = mesure_verify_sst(pub_key_O, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, &sst, nb_trials); // Mesure verify_L_ni printf("verify_L_ni (2 Authorities) : \n"); double time_verify_L_ni = mesure_verify_L_ni_for_2L(&P, &L1_pk, &l1_ni, &L2_pk, &l2_ni, nb_trials); // Verification verify_L_ni(&P, 4, &L1_pk, &l1_ni, &L2_pk, &l2_ni); verify_mx(&P, &xP, &Q, &xQ, omega, omega_len, &x_ni); verify_my(&Q, &yQ, omega, omega_len, &y_ni); verify_sigma_Y_1(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sig_len); verify_sigma_X(pub_key_A, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sig_len); verify_sigma_Y_2(pub_key_B, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len); verify_sst(pub_key_O, omega, omega_len, &xP, &xQ, &x_ni, &yQ, &y_ni, sigma_Y_1, sigma_X, sigma_Y_2, sig_len, &sst); total_time_Ver += time_verify_L_ni + time_verify_mx + time_verify_my + time_verify_sigma_Y_1 + time_verify_sigma_X + time_verify_sigma_Y_2 + time_verify_sst; // Mesure tdgen_get_li_T1 printf("tdgen_get_li_T1 (2 Authorities) : \n"); double time_tdgen_get_li_T1_for_2L = mesure_tdgen_get_li_T1_for_2L(&xP, &yQ, &l1_sk, &l1_T1, &l2_sk, &l2_T1, nb_trials); // Mesure tdgen_get_li_T2 printf("tdgen_get_li_T2 (2 Authorities) : \n"); double time_tdgen_get_li_T2_for_2L = mesure_tdgen_get_li_T2_for_2L(&P, &xP, &yQ, &L1_pk, &l1_sk, &l1_T1, &l1_T2, &L2_pk, &l2_sk, &l2_T1, &l2_T2, nb_trials); // TDGen tdgen_get_li_T1(&xP, &yQ, 4, &l1_sk, &l1_T1, &l2_sk, &l2_T1); tdgen_get_li_T2(&P, &xP, &yQ, 8, &L1_pk, &l1_sk, &l1_T1, &l1_T2, &L2_pk, &l2_sk, &l2_T1, &l2_T2); total_time_TDGen += time_tdgen_get_li_T1_for_2L + time_tdgen_get_li_T2_for_2L; // Mesure verify_li_T2 printf("verify_li_T2 (2 Authorities) : \n"); double time_verify_li_T2_for_2 = mesure_verify_li_T2_for_2L(&P, &xP, &yQ, &L1_pk, &l1_T1, &l1_T2, &L2_pk, &l2_T1, &l2_T2, nb_trials); // Mesure open_get_shared_key printf("open_get_shared_key (2 Authorities) : \n"); double time_open_get_shared_key_for_2 = mesure_open_get_shared_key_for_2(&k, &l1_T1, &l2_T1, nb_trials); // Open verify_li_T2(&P, &xP, &yQ, 6, &L1_pk, &l1_T1, &l1_T2, &L2_pk, &l2_T1, &l2_T2); open_get_shared_key(&k, 2, &l1_T1, &l2_T1); total_time_Open += time_verify_li_T2_for_2 + time_open_get_shared_key_for_2; // Check key int res = mclBnGT_isEqual(&ka, &kb); if(res != 1) { printf("Keys not equal\n"); } res = mclBnGT_isEqual(&ka, &k); if(res != 1) { printf("Keys not equal\n"); } printf("Total CPU running time for A : %f\n", total_time_A); printf("Total CPU running time for B : %f\n", total_time_B); printf("Total CPU running time for O : %f\n", total_time_O); printf("Total CPU running time for Verification : %f\n", total_time_Ver); printf("Total CPU running time for TDGen (2 Authorities) : %f\n", total_time_TDGen); printf("Total CPU running time for Open (2 Authorities) : %f\n", total_time_Open); free(sigma_Y_1); free(sigma_X); free(sigma_Y_2); free(sst.m); free(sst.sigma_O); return 0; }
{ "alphanum_fraction": 0.6408216076, "avg_line_length": 33.4940411701, "ext": "c", "hexsha": "5fe281ab266510987144c9e29fbd167c4e9c16df", "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": "ada171dfcb8500b2cb722a3c0babcbedf63d396b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AnonymLIKE/like", "max_forks_repo_path": "tests/perfs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ada171dfcb8500b2cb722a3c0babcbedf63d396b", "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": "AnonymLIKE/like", "max_issues_repo_path": "tests/perfs.c", "max_line_length": 511, "max_stars_count": null, "max_stars_repo_head_hexsha": "ada171dfcb8500b2cb722a3c0babcbedf63d396b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AnonymLIKE/like", "max_stars_repo_path": "tests/perfs.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10958, "size": 30915 }
#ifndef VKST_PLAT_FILE_HANDLE_H #define VKST_PLAT_FILE_HANDLE_H #include <plat/filesystem.h> #include <turf/c/core.h> #include <gsl.h> namespace plat { // A RAII wrapper around the C stdio file handle class file_handle { public: enum class open_modes : uint8_t { read = 0x1, write = 0x2, append = 0x4, }; // enum class open_modes static file_handle open(plat::filesystem::path const& path, open_modes mode, std::error_code& ec) noexcept; file_handle() noexcept = default; std::FILE* get() noexcept { return _handle.get(); } operator std::FILE*() noexcept { return get(); } explicit operator bool() noexcept { return static_cast<bool>(_handle); } void reset() noexcept { _handle.reset(); } private: file_handle(FILE* handle) noexcept : _handle{handle, &std::fclose} {} using file_ptr = gsl::unique_ptr<std::FILE, decltype(&std::fclose)>; file_ptr _handle{nullptr, &std::fclose}; }; // class file_handle inline constexpr auto operator|(file_handle::open_modes a, file_handle::open_modes b) noexcept { using U = std::underlying_type_t<file_handle::open_modes>; return static_cast<file_handle::open_modes>(static_cast<U>(a) | static_cast<U>(b)); } inline constexpr auto operator&(file_handle::open_modes a, file_handle::open_modes b) noexcept { using U = std::underlying_type_t<file_handle::open_modes>; return static_cast<file_handle::open_modes>(static_cast<U>(a) & static_cast<U>(b)); } } // namespace plat #endif // VKST_PLAT_FILE_HANDLE_H
{ "alphanum_fraction": 0.6481812761, "avg_line_length": 31.0555555556, "ext": "h", "hexsha": "41af5e62c3700f11abe31e2776a05ef0f84047b4", "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": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": [ "Zlib" ], "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_path": "src/plat/file_handle.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib" ], "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_path": "src/plat/file_handle.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": [ "Zlib" ], "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_path": "src/plat/file_handle.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 399, "size": 1677 }
// SPDX-License-Identifier: MIT // The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018-2019, Johannes Leupolz // // 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. #ifndef PEMC_BASIC_RAW_MEMORY_H_ #define PEMC_BASIC_RAW_MEMORY_H_ #include <gsl/gsl_byte> #include <memory> namespace pemc { using deleter_t = std::function<void(void*)>; using unique_void_ptr = std::unique_ptr<void, deleter_t>; // The following method can be used to reserve some bulk memory. // The unique_void_ptr keeps track of the memory to avoid leaks. // unique_ptr are not used, because they do not support void. // Example of usage: // > unique_void_ptr stateMemory = unique_void(::operator new(amount of memory ) // ); > gsl::byte* p_stateMemory = static_cast<gsl::byte*>(stateMemory.get()); unique_void_ptr unique_void(void* ptr); /// <summary> /// Compares the two buffers <paramref name="buffer1" /> and <paramref /// name="buffer2" />, returning <c>true</c> when the buffers are equivalent. /// </summary> /// <param name="buffer1">The first buffer of memory to compare.</param> /// <param name="buffer2">The second buffer of memory to compare.</param> /// <param name="sizeInBytes">The size of the buffers in bytes.</param> bool areBuffersEqual(gsl::byte* buffer1, gsl::byte* buffer2, size_t sizeInBytes); /// <summary> /// Copies <paramref name="sizeInBytes" />-many bytes from <paramref /// name="source" /> to <see cref="destination" />. /// </summary> /// <param name="source">The first buffer of memory to compare.</param> /// <param name="destination">The second buffer of memory to compare.</param> /// <param name="sizeInBytes">The size of the buffers in bytes.</param> void copyBuffers(gsl::byte* source, gsl::byte* destination, size_t sizeInBytes); /// <summary> /// Hashes the <paramref name="buffer" />. /// </summary> /// <param name="buffer">The buffer of memory that should be hashed.</param> /// <param name="sizeInBytes">The size of the buffer in bytes.</param> /// <param name="seed">The seed value for the hash.</param> /// <remarks>See also https://en.wikipedia.org/wiki/MurmurHash (MurmurHash3 /// implementation)</remarks> uint32_t hashBuffer(gsl::byte* buffer, size_t sizeInBytes, int32_t seed); } // namespace pemc #endif // PEMC_BASIC_RAW_MEMORY_H_
{ "alphanum_fraction": 0.7240974464, "avg_line_length": 43.6794871795, "ext": "h", "hexsha": "99d58be28d01f5565a510211c1b28ab745b66650", "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": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_path": "pemc/basic/raw_memory.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "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": "joleuger/pemc", "max_issues_repo_path": "pemc/basic/raw_memory.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_path": "pemc/basic/raw_memory.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 815, "size": 3407 }
/* ################################################################################## */ /* ### ### */ /* ### sigvel.c ### */ /* ### ### */ /* ### Original: hydra.c (public version of Gadget 2) ### */ /* ### Author: Volker Springel ### */ /* ### ### */ /* ### Modified: February 2011 ### */ /* ### Author: Fabrice Durier ### */ /* ### ### */ /* ################################################################################## */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef NOMPI #include <mpi.h> #endif #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" /*! \file sigvel.c * Re-Computation of SPH acceleration and maximum signal velocity * for 'feedback' particles only. * * This file is a modified version of hydra.c, where the SPH forces are * computed, and where the rate of change of entropy due to the shock heating * (via artificial viscosity) is computed. */ #ifdef TIMESTEP_UPDATE static double hubble_a, atime, hubble_a2, fac_mu, fac_vsic_fix, a3inv, fac_egy; #ifdef PERIODIC static double boxSize, boxHalf; #ifdef LONG_X static double boxSize_X, boxHalf_X; #else #define boxSize_X boxSize #define boxHalf_X boxHalf #endif #ifdef LONG_Y static double boxSize_Y, boxHalf_Y; #else #define boxSize_Y boxSize #define boxHalf_Y boxHalf #endif #ifdef LONG_Z static double boxSize_Z, boxHalf_Z; #else #define boxSize_Z boxSize #define boxHalf_Z boxHalf #endif #endif /*! This function is the driver routine for the update of the calculation * of hydrodynamical force due to the feedback impact * from either SNe or BHs on active gas particles. */ void get_sigvel(void) { long long ntot, ntotleft; int i, j, k, n, ngrp, maxfill, source, ndone; int *nbuffer, *noffset, *nsend_local, *nsend, *numlist, *ndonelist; int level, sendTask, recvTask, nexport, place; double soundspeed_i; double tstart, tend, sumt, sumcomm; double timecomp = 0, timecommsumm = 0, timeimbalance = 0, sumimbalance; #ifndef NOMPI MPI_Status status; #endif #ifdef PERIODIC boxSize = All.BoxSize; boxHalf = 0.5 * All.BoxSize; #ifdef LONG_X boxHalf_X = boxHalf * LONG_X; boxSize_X = boxSize * LONG_X; #endif #ifdef LONG_Y boxHalf_Y = boxHalf * LONG_Y; boxSize_Y = boxSize * LONG_Y; #endif #ifdef LONG_Z boxHalf_Z = boxHalf * LONG_Z; boxSize_Z = boxSize * LONG_Z; #endif #endif if(All.ComovingIntegrationOn) { /* Factors for comoving integration of hydro */ hubble_a = All.Omega0 / (All.Time * All.Time * All.Time) + (1 - All.Omega0 - All.OmegaLambda) / (All.Time * All.Time) + All.OmegaLambda; hubble_a = All.Hubble * sqrt(hubble_a); hubble_a2 = All.Time * All.Time * hubble_a; fac_mu = pow(All.Time, 3 * (GAMMA - 1) / 2) / All.Time; fac_egy = pow(All.Time, 3 * (GAMMA - 1)); fac_vsic_fix = hubble_a * pow(All.Time, 3 * GAMMA_MINUS1); a3inv = 1 / (All.Time * All.Time * All.Time); atime = All.Time; } else hubble_a = hubble_a2 = atime = fac_mu = fac_vsic_fix = a3inv = fac_egy = 1.0; /* `NumSphUpdate' gives the number of feedback particles on this processor that want a force update */ for(n = 0, NumSphUpdate = 0; n < N_gas; n++) { if(P[n].Ti_endstep == All.Ti_Current && SphP[n].FeedbackFlag > 1) NumSphUpdate++; } numlist = malloc(NTask * sizeof(int) * NTask); #ifndef NOMPI MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, GADGET_WORLD); #else numlist[0] = NumSphUpdate; #endif for(i = 0, ntot = 0; i < NTask; i++) ntot += numlist[i]; free(numlist); if(ThisTask == 0 && ntot) printf("\t ---> Number of feedback particles = %ld \n\n", ntot); noffset = malloc(sizeof(int) * NTask); /* offsets of bunches in common list */ nbuffer = malloc(sizeof(int) * NTask); nsend_local = malloc(sizeof(int) * NTask); nsend = malloc(sizeof(int) * NTask * NTask); ndonelist = malloc(sizeof(int) * NTask); i = 0; /* first particle for this task */ ntotleft = ntot; /* particles left for all tasks together */ while(ntotleft > 0) { for(j = 0; j < NTask; j++) nsend_local[j] = 0; /* do local particles and prepare export list */ tstart = second(); for(nexport = 0, ndone = 0; i < N_gas && nexport < All.BunchSizeHydro - NTask; i++) if(P[i].Ti_endstep == All.Ti_Current && SphP[i].FeedbackFlag > 1) { ndone++; for(j = 0; j < NTask; j++) Exportflag[j] = 0; get_sigvel_evaluate(i, 0); for(j = 0; j < NTask; j++) { if(Exportflag[j]) { for(k = 0; k < 3; k++) { HydroDataIn[nexport].Pos[k] = P[i].Pos[k]; HydroDataIn[nexport].Vel[k] = SphP[i].VelPred[k]; } HydroDataIn[nexport].Hsml = SphP[i].Hsml; HydroDataIn[nexport].Mass = P[i].Mass; HydroDataIn[nexport].DhsmlDensityFactor = SphP[i].DhsmlDensityFactor; HydroDataIn[nexport].Density = SphP[i].Density; HydroDataIn[nexport].Pressure = SphP[i].Pressure; HydroDataIn[nexport].Timestep = P[i].Ti_endstep - P[i].Ti_begstep; /* calculation of F1 */ soundspeed_i = sqrt(GAMMA * SphP[i].Pressure / SphP[i].Density); HydroDataIn[nexport].F1 = fabs(SphP[i].DivVel) / (fabs(SphP[i].DivVel) + SphP[i].CurlVel + 0.0001 * soundspeed_i / SphP[i].Hsml / fac_mu); HydroDataIn[nexport].Index = i; HydroDataIn[nexport].Task = j; nexport++; nsend_local[j]++; } } } tend = second(); timecomp += timediff(tstart, tend); qsort(HydroDataIn, nexport, sizeof(struct hydrodata_in), hydro_compare_key); for(j = 1, noffset[0] = 0; j < NTask; j++) noffset[j] = noffset[j - 1] + nsend_local[j - 1]; tstart = second(); #ifndef NOMPI MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, GADGET_WORLD); #else nsend[0] = nsend_local[0]; #endif tend = second(); timeimbalance += timediff(tstart, tend); /* now do the particles that need to be exported */ for(level = 1; level < (1 << PTask); level++) { tstart = second(); for(j = 0; j < NTask; j++) nbuffer[j] = 0; for(ngrp = level; ngrp < (1 << PTask); ngrp++) { maxfill = 0; for(j = 0; j < NTask; j++) { if((j ^ ngrp) < NTask) if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]) maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]; } if(maxfill >= All.BunchSizeHydro) break; sendTask = ThisTask; recvTask = ThisTask ^ ngrp; #ifndef NOMPI if(recvTask < NTask) { if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0) { /* get the particles */ MPI_Sendrecv(&HydroDataIn[noffset[recvTask]], nsend_local[recvTask] * sizeof(struct hydrodata_in), MPI_BYTE, recvTask, TAG_HYDRO_A, &HydroDataGet[nbuffer[ThisTask]], nsend[recvTask * NTask + ThisTask] * sizeof(struct hydrodata_in), MPI_BYTE, recvTask, TAG_HYDRO_A, GADGET_WORLD, &status); } } #endif for(j = 0; j < NTask; j++) if((j ^ ngrp) < NTask) nbuffer[j] += nsend[(j ^ ngrp) * NTask + j]; } tend = second(); timecommsumm += timediff(tstart, tend); /* now do the imported particles */ tstart = second(); for(j = 0; j < nbuffer[ThisTask]; j++) get_sigvel_evaluate(j, 1); tend = second(); timecomp += timediff(tstart, tend); /* do a block to measure imbalance */ tstart = second(); #ifndef NOMPI MPI_Barrier(GADGET_WORLD); #endif tend = second(); timeimbalance += timediff(tstart, tend); /* get the result */ tstart = second(); for(j = 0; j < NTask; j++) nbuffer[j] = 0; for(ngrp = level; ngrp < (1 << PTask); ngrp++) { maxfill = 0; for(j = 0; j < NTask; j++) { if((j ^ ngrp) < NTask) if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]) maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j]; } if(maxfill >= All.BunchSizeHydro) break; sendTask = ThisTask; recvTask = ThisTask ^ ngrp; #ifndef NOMPI if(recvTask < NTask) { if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0) { /* send the results */ MPI_Sendrecv(&HydroDataResult[nbuffer[ThisTask]], nsend[recvTask * NTask + ThisTask] * sizeof(struct hydrodata_out), MPI_BYTE, recvTask, TAG_HYDRO_B, &HydroDataPartialResult[noffset[recvTask]], nsend_local[recvTask] * sizeof(struct hydrodata_out), MPI_BYTE, recvTask, TAG_HYDRO_B, GADGET_WORLD, &status); /* add the result to the particles */ for(j = 0; j < nsend_local[recvTask]; j++) { source = j + noffset[recvTask]; place = HydroDataIn[source].Index; for(k = 0; k < 3; k++) SphP[place].FeedAccel[k] += HydroDataPartialResult[source].Acc[k]; if(SphP[place].MaxSignalVel < HydroDataPartialResult[source].MaxSignalVel) SphP[place].MaxSignalVel = HydroDataPartialResult[source].MaxSignalVel; } } } #endif for(j = 0; j < NTask; j++) if((j ^ ngrp) < NTask) nbuffer[j] += nsend[(j ^ ngrp) * NTask + j]; } tend = second(); timecommsumm += timediff(tstart, tend); level = ngrp - 1; } #ifndef NOMPI MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, GADGET_WORLD); #else ndonelist[0] = ndone; #endif for(j = 0; j < NTask; j++) ntotleft -= ndonelist[j]; } free(ndonelist); free(nsend); free(nsend_local); free(nbuffer); free(noffset); /* collect some timing information */ #ifndef NOMPI MPI_Reduce(&timecomp, &sumt, 1, MPI_DOUBLE, MPI_SUM, 0, GADGET_WORLD); MPI_Reduce(&timecommsumm, &sumcomm, 1, MPI_DOUBLE, MPI_SUM, 0, GADGET_WORLD); MPI_Reduce(&timeimbalance, &sumimbalance, 1, MPI_DOUBLE, MPI_SUM, 0, GADGET_WORLD); #else sumt = timecomp; sumcomm = timecommsumm; sumimbalance = timeimbalance; #endif if(ThisTask == 0) { All.CPU_HydCompWalk += sumt / NTask; All.CPU_HydCommSumm += sumcomm / NTask; All.CPU_HydImbalance += sumimbalance / NTask; } } /*! This function is the 'core' of the SPH force update. A target * particle is specified which may either be local, or reside in the * communication buffer. * Note that only the acceleration due to feedback and the change * of signal velocity are updated, not the actual variation of Entropy rate. */ void get_sigvel_evaluate(int target, int mode) { int j, k, n, timestep, startnode, numngb; FLOAT *pos, *vel; FLOAT mass, h_i, dhsmlDensityFactor, rho, pressure, f1, f2; double acc[3], dtEntropy, maxSignalVel; double dx, dy, dz, dvx, dvy, dvz; double h_i2, hinv, hinv4; double p_over_rho2_i, p_over_rho2_j, soundspeed_i, soundspeed_j; double hfc, dwk_i, vdotr, vdotr2, visc, mu_ij, rho_ij, vsig; double h_j, dwk_j, r, r2, u, hfc_visc; #ifndef NOVISCOSITYLIMITER double dt; #endif if(mode == 0) { pos = P[target].Pos; vel = SphP[target].VelPred; h_i = SphP[target].Hsml; mass = P[target].Mass; dhsmlDensityFactor = SphP[target].DhsmlDensityFactor; rho = SphP[target].Density; pressure = SphP[target].Pressure; timestep = P[target].Ti_endstep - P[target].Ti_begstep; soundspeed_i = sqrt(GAMMA * pressure / rho); f1 = fabs(SphP[target].DivVel) / (fabs(SphP[target].DivVel) + SphP[target].CurlVel + 0.0001 * soundspeed_i / SphP[target].Hsml / fac_mu); } else { pos = HydroDataGet[target].Pos; vel = HydroDataGet[target].Vel; h_i = HydroDataGet[target].Hsml; mass = HydroDataGet[target].Mass; dhsmlDensityFactor = HydroDataGet[target].DhsmlDensityFactor; rho = HydroDataGet[target].Density; pressure = HydroDataGet[target].Pressure; timestep = HydroDataGet[target].Timestep; soundspeed_i = sqrt(GAMMA * pressure / rho); f1 = HydroDataGet[target].F1; } /* initialize variables before SPH loop is started */ acc[0] = acc[1] = acc[2] = dtEntropy = 0; maxSignalVel = 0; p_over_rho2_i = pressure / (rho * rho) * dhsmlDensityFactor; h_i2 = h_i * h_i; /* Now start the actual SPH computation for this particle */ startnode = All.MaxPart; do { numngb = ngb_treefind_pairs(&pos[0], h_i, &startnode); for(n = 0; n < numngb; n++) { j = Ngblist[n]; dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC /* find the closest image in the given box size */ if(dx > boxHalf_X) dx -= boxSize_X; if(dx < -boxHalf_X) dx += boxSize_X; if(dy > boxHalf_Y) dy -= boxSize_Y; if(dy < -boxHalf_Y) dy += boxSize_Y; if(dz > boxHalf_Z) dz -= boxSize_Z; if(dz < -boxHalf_Z) dz += boxSize_Z; #endif r2 = dx * dx + dy * dy + dz * dz; h_j = SphP[j].Hsml; if(r2 < h_i2 || r2 < h_j * h_j) { r = sqrt(r2); if(r > 0) { p_over_rho2_j = SphP[j].Pressure / (SphP[j].Density * SphP[j].Density); soundspeed_j = sqrt(GAMMA * p_over_rho2_j * SphP[j].Density); dvx = vel[0] - SphP[j].VelPred[0]; dvy = vel[1] - SphP[j].VelPred[1]; dvz = vel[2] - SphP[j].VelPred[2]; vdotr = dx * dvx + dy * dvy + dz * dvz; if(All.ComovingIntegrationOn) vdotr2 = vdotr + hubble_a2 * r2; else vdotr2 = vdotr; if(r2 < h_i2) { hinv = 1.0 / h_i; #ifndef TWODIMS hinv4 = hinv * hinv * hinv * hinv; #else hinv4 = hinv * hinv * hinv / boxSize_Z; #endif u = r * hinv; if(u < 0.5) dwk_i = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4); else dwk_i = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u); } else { dwk_i = 0; } if(r2 < h_j * h_j) { hinv = 1.0 / h_j; #ifndef TWODIMS hinv4 = hinv * hinv * hinv * hinv; #else hinv4 = hinv * hinv * hinv / boxSize_Z; #endif u = r * hinv; if(u < 0.5) dwk_j = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4); else dwk_j = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u); } else { dwk_j = 0; } if(soundspeed_i + soundspeed_j > maxSignalVel) maxSignalVel = soundspeed_i + soundspeed_j; if(vdotr2 < 0) /* ... artificial viscosity */ { mu_ij = fac_mu * vdotr2 / r; /* note: this is negative! */ vsig = soundspeed_i + soundspeed_j - 3 * mu_ij; if(vsig > maxSignalVel) maxSignalVel = vsig; if(P[j].Ti_endstep == All.Ti_Current) if(vsig > SphP[j].MaxSignalVel) SphP[j].MaxSignalVel = vsig; rho_ij = 0.5 * (rho + SphP[j].Density); f2 = fabs(SphP[j].DivVel) / (fabs(SphP[j].DivVel) + SphP[j].CurlVel + 0.0001 * soundspeed_j / fac_mu / SphP[j].Hsml); visc = 0.25 * All.ArtBulkViscConst * vsig * (-mu_ij) / rho_ij * (f1 + f2); /* .... end artificial viscosity evaluation */ #ifndef NOVISCOSITYLIMITER /* make sure that viscous acceleration is not too large */ dt = imax(timestep, (P[j].Ti_endstep - P[j].Ti_begstep)) * All.Timebase_interval; if(dt > 0 && (dwk_i + dwk_j) < 0) { visc = dmin(visc, 0.5 * fac_vsic_fix * vdotr2 / (0.5 * (mass + P[j].Mass) * (dwk_i + dwk_j) * r * dt)); } #endif } else visc = 0; p_over_rho2_j *= SphP[j].DhsmlDensityFactor; hfc_visc = 0.5 * P[j].Mass * visc * (dwk_i + dwk_j) / r; hfc = hfc_visc + P[j].Mass * (p_over_rho2_i * dwk_i + p_over_rho2_j * dwk_j) / r; acc[0] -= hfc * dx; acc[1] -= hfc * dy; acc[2] -= hfc * dz; if(P[j].Ti_endstep == All.Ti_Current) { if(SphP[j].FeedbackFlag == 0) SphP[j].FeedbackFlag = 1; if(maxSignalVel > SphP[j].MaxSignalVel) SphP[j].MaxSignalVel = maxSignalVel; SphP[j].FeedAccel[0] -= hfc * dx; SphP[j].FeedAccel[1] -= hfc * dy; SphP[j].FeedAccel[2] -= hfc * dz; } } } } fflush(stdout); } while(startnode >= 0); /* Now collect the result at the right place */ if(mode == 0) { SphP[target].MaxSignalVel = maxSignalVel; for(k = 0; k < 3; k++) SphP[target].FeedAccel[k] = acc[k]; } else { HydroDataResult[target].MaxSignalVel = maxSignalVel; for(k = 0; k < 3; k++) HydroDataResult[target].Acc[k] = acc[k]; } } #endif
{ "alphanum_fraction": 0.5391853, "avg_line_length": 30.2646566164, "ext": "c", "hexsha": "1dcfd47828c165c9624b81f0461b3b9aab7ca510", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rieder/amuse", "max_forks_repo_path": "src/amuse/community/gadget2/src/sigvel.c", "max_issues_count": 690, "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rknop/amuse", "max_issues_repo_path": "src/amuse/community/gadget2/src/sigvel.c", "max_line_length": 104, "max_stars_count": 131, "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rknop/amuse", "max_stars_repo_path": "src/amuse/community/gadget2/src/sigvel.c", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "num_tokens": 5435, "size": 18068 }
#ifndef buildin_40bf10d0_ba81_4f06_accf_8020d3698607_h #define buildin_40bf10d0_ba81_4f06_accf_8020d3698607_h #include <gslib\type.h> #include <gslib\string.h> #include <rathen\config.h> __rathen_begin__ #define max_opr 4 struct oprnode { int prior; gchar opr[max_opr]; bool unary; }; struct oprinfo { string opr; bool unary; oprinfo(const gchar* o, bool u): opr(o), unary(u) {} oprinfo(const string& s, bool u): opr(s), unary(u) {} }; struct unary_oprinfo: public oprinfo { unary_oprinfo(const gchar* o): oprinfo(o, true) {} unary_oprinfo(const string& s): oprinfo(s, true) {} }; struct binary_oprinfo: public oprinfo { binary_oprinfo(const gchar* o): oprinfo(o, false) {} binary_oprinfo(const string& s): oprinfo(s, false) {} }; class opr_manager { public: /* * the operators: ( ) ++ -- - ! ~ += -= *= /= %= * / % + - << >> < > <= >= == != & | ^ && || = */ static const oprnode opr_list[]; private: opr_manager() {} public: static opr_manager* get_singleton_ptr() { static opr_manager inst; return &inst; } const oprnode* get_unary_operator(const gchar* src) const; const oprnode* get_binary_operator(const gchar* src) const; const oprnode* get_unary_operator(const string& src) const { return get_unary_operator(src.c_str()); } const oprnode* get_binary_operator(const string& src) const { return get_binary_operator(src.c_str()); } const oprnode* get_operator(const oprinfo& info) const { return info.unary ? get_unary_operator(info.opr) : get_binary_operator(info.opr); } /* * Currently, only priority '1' was unary. * pass the 'opr' to this function, in case of any proper changes in the future. */ bool is_unary(int prior, const gchar* opr) const { return prior == 1; } bool is_unary(int prior, const string& opr) const { return prior == 1; } }; #define _opr_manager opr_manager::get_singleton_ptr() #define max_key 8 struct key_node { int pattern; gchar key[max_key]; }; class key_manager { public: static const key_node key_list[]; enum { /* * Respectively like: * stop; * exit(...); * else {...} * if(...) {...} */ pat_err = 0x00, pat_raw = 0x01, pat_arg = 0x02, pat_seg = 0x04, pat_com = 0x08, }; private: key_manager() {} public: static key_manager* get_singleton_ptr() { static key_manager inst; return &inst; } const key_node* get_key(const gchar* src) const; const key_node* get_key(const string& src) const { return get_key(src.c_str()); } int get_key_pattern(const gchar* src) const; int get_key_pattern(const string& src) const { return get_key_pattern(src.c_str()); } }; #define _key_manager key_manager::get_singleton_ptr() __rathen_end__ #endif
{ "alphanum_fraction": 0.579029734, "avg_line_length": 23.4926470588, "ext": "h", "hexsha": "c930316f919f4b28efd023aa53cc441a47d69755", "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/rathen/buildin.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/rathen/buildin.h", "max_line_length": 109, "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/rathen/buildin.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": 835, "size": 3195 }
#ifndef _PARAMETERS_H_ #define _PARAMETERS_H_ #include <string> #include <fstream> #include <iostream> #include <cstdlib> #include "../Headers/voxel.h" #include <math.h> #include <gsl/gsl_rng.h> using namespace std; class Parameters{ //Atributs public: int it; //Contador int nt; // Nombre de passos total int ntout; // Nombre de pasos per l'output int neq; //Number of equations float dt; // Pas de temps float t; string Dir_Output; string Dir_Input; string NumPar_Dat; string Data_Dat; string Init_Cond_Dat; int nNodes; int nNodes_inh; string Kex_Dat; string Kin_Dat; float ** Kex; //Coupling matrix for excitatory population float ** Kin; //Coupling matrix for inhibitory population voxel * V; //Voxel ofstream fout_data; ofstream fout_init_cond; public: Parameters(); ~Parameters(); //Mètodes void Read_Kex_Dat(void); void Read_Kin_Dat(void); void RefreshDelay(void); void Read_NumPar_Dat(void); void WriteData(); void WriteInitialConditions(int); void openfiles(); void closefiles(); //private: }; #endif
{ "alphanum_fraction": 0.6751313485, "avg_line_length": 15.8611111111, "ext": "h", "hexsha": "dddd2395479b7e1ef657054237c2541972b85fa2", "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": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dmalagarriga/PLoS_2015_segregation", "max_forks_repo_path": "TEST_1/Headers/Parameters.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "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": "dmalagarriga/PLoS_2015_segregation", "max_issues_repo_path": "TEST_1/Headers/Parameters.h", "max_line_length": 58, "max_stars_count": 1, "max_stars_repo_head_hexsha": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dmalagarriga/PLoS_2015_segregation", "max_stars_repo_path": "TEST_1/Headers/Parameters.h", "max_stars_repo_stars_event_max_datetime": "2020-10-28T08:49:49.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-28T08:49:49.000Z", "num_tokens": 299, "size": 1142 }
// SMCTC: rng.hh // // Copyright Adam Johansen, 2008. // // This file is part of SMCTC. // // SMCTC 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. // // SMCTC 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 SMCTC. If not, see <http://www.gnu.org/licenses/>. // //! \file //! \brief Random number generation. //! //! This file contains the definitions for the smc::rng and smc::rnginfo class. //! It wraps the random number generation facilities provided by the GSL and provides a convenient interfaces to access several of its more commonly-used features. #ifndef __SMC_RNG_HH #define __SMC_RNG_HH 1.0 extern "C" { #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> } namespace smc { ///A gsl-rng information handling class (not templated) class gslrnginfo { private: ///This is a null terminated array of the available random number generators. const gsl_rng_type** typePtArray; ///The number of available random number generators. int nNumber; protected: gslrnginfo(); public: ///Returns a reference to the sole static instance of this class. static gslrnginfo* GetInstance(); ///Returns the number of available random number generators. int GetNumber(); ///Returns the name of random number generator number nIndex. const char* GetNameByIndex(int nIndex); ///Returns a pointer to random number generator nIndex. const gsl_rng_type* GetPointerByIndex(int nIndex); ///Returns a pointer to the random number generator with name szName (or null if it doesn't exist). const gsl_rng_type* GetPointerByName(const char* szName); }; ///The global application instance of the gslrnginfo class: extern gslrnginfo rngset; ///A random number generator class. /// At present this serves as a wrapper for the gsl random number generation code. class rng { private: ///This is the type of random number generator underlying the class. const gsl_rng_type* type; ///This is a pointer to the internal workspace of the rng including its current state. gsl_rng* pWorkspace; public: ///Initialise the random number generator using default settings rng(); ///Initialise the random number generator using the default seed for the type rng(const gsl_rng_type* Type); ///Initialise the random number generator using specified type and seed rng(const gsl_rng_type* Type,unsigned long int lSeed); ///Free the workspace allocated for random number generation ~rng(); ///Provide access to the raw random number generator gsl_rng* GetRaw(void); ///Generate a multinomial random vector with parameters (n,w[1:k]) and store it in X void Multinomial(unsigned n, unsigned k, const double* w, unsigned* X); ///Returns a random integer generated uniformly between the minimum and maximum values specified long UniformDiscrete(long lMin, long lMax); ///Returns a random number generated from a Beta distribution with the specified parameters. double Beta(double da, double db); ///Returns a random number generated from a Cauchy distribution with the specified scale parameter. double Cauchy(double dScale); ///Returns a random number generated from an exponential distribution with the specified mean. double Exponential(double dMean); ///Return a random number generated from a gamma distribution with shape alpha and scale beta. double Gamma(double dAlpha, double dBeta); ///Returns a random number generated from a Laplacian distribution with the specified scale. double Laplacian(double dScale); ///Returns a random number generated from a Lognormal distribution of location mu and scale sigma double Lognormal(double dMu, double dSigma); ///Return a random number generated from a normal distribution with a specified mean and standard deviation double Normal(double dMean, double dStd); ///Return a random number generated from a standard normal distribution double NormalS(void); ///Returns a random number from a normal distribution, conditional upon it exceeding the specified threshold. double NormalTruncated(double dMean, double dStd, double dThreshold); ///Return a student-t random number generated with a specified number of degrees of freedom double StudentT(double dDF); ///Return a random number generated uniformly between dMin and dMax double Uniform(double dMin, double dMax); ///Returns a random number generated from the standard uniform[0,1) distribution double UniformS(void); }; } #endif
{ "alphanum_fraction": 0.7332277855, "avg_line_length": 41.081300813, "ext": "h", "hexsha": "964c687e1311ea59857137cbc7f418bec70c11b3", "lang": "C", "max_forks_count": 15, "max_forks_repo_forks_event_max_datetime": "2021-10-08T13:20:35.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-26T22:34:24.000Z", "max_forks_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "williamg42/IMU-GPS-Fusion", "max_forks_repo_path": "include/rng.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_issues_repo_issues_event_max_datetime": "2019-04-02T17:45:59.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-22T09:21:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "williamg42/IMU-GPS-Fusion", "max_issues_repo_path": "include/rng.h", "max_line_length": 163, "max_stars_count": 27, "max_stars_repo_head_hexsha": "58cb79d35e35786ecea1bf8023a639fd8bb148c0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "williamg42/IMU-GPS-Fusion", "max_stars_repo_path": "include/rng.h", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:16:46.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-22T09:11:16.000Z", "num_tokens": 1108, "size": 5053 }
#include "lah.h" #ifdef HAVE_LAPACK #include <lapacke.h> lah_Return lah_eigenValue(lah_mat *P, lah_value *S, lah_mat *Z) { lapack_int res, nEig; lapack_int *isuppz; if (P == NULL || S == NULL || Z == NULL || P->nR != P->nC) { return lahReturnParameterError; } /* allocate space for the output parameters and workspace arrays */ isuppz = malloc(2 * P->nR * sizeof(lapack_int)); /* Data allocation */ /* Sollte A-> data nur dreiecksmatrix enthalten ?*/ res = SYEVR(LAH_LAPACK_LAYOUT, 'V', 'A', 'L', P->nR, P->data, P->nR, 0, 0, 0, 0, LAMCH('S'), &nEig, S, Z->data, P->nR, isuppz); /* free support array */ free(isuppz); if (res > 0) return lahReturnExternError; else if (res < 0) return lahReturnParameterError; else return lahReturnOk; } #endif
{ "alphanum_fraction": 0.576, "avg_line_length": 26.5151515152, "ext": "c", "hexsha": "2ae0701d5f03d68dbf2d53fa60a9362f556b4942", "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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_path": "Source/lah_eigenValue.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "maj0e/linear-algebra-helpers", "max_issues_repo_path": "Source/lah_eigenValue.c", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_path": "Source/lah_eigenValue.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 286, "size": 875 }
/* modulo-bias - test for modulo bias in poor random number generation; * the bias does not appear where RAND_MAX is much larger than m. for a * three-sided dice roll, the last RAND_MAX to fail what I think is a * chi-squared 0.05 test is 257; given a system RAND_MAX of a much * larger value, this would likely only be of concern if the modulo m is * very, very large, or if an 8-bit system is being used. better results * are obtained where m evenly divides RAND_MAX; RAND_MAX of 100000 and * m = 4 only fails at 62 and below (assuming no errors on my part) * * actually, the exact numbers depend on the rand() implementation and * the seed; Mac OS X rand() produced the 257 for an arbitrary seed; * this version tries out multiple seeds (TRIALS) and emits what is * likely the maximum failure of the fitness test for that seed. * However! it still remains that if RAND_MAX is much larger than the * range, there is no (statistically significant) modulo bias */ #include <err.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <gsl/gsl_cdf.h> /* how many results to generate (3 == (0,1,2)) and how many tests to * run; TESTNUM will need to be high enough to distinguish signal from * the noise, but not too long that too much CPU is wasted */ #define RANGE 3 #define TESTNUM 99999 /* CHI^2 test foo, assuming uniform distribution of the RANGE values * over the TESTNUM runs, and 95% confidence */ #define EXPECTED TESTNUM / (double) RANGE #define DEG_OF_FREE RANGE - 1 #define FITNESS 0.05 /* this may have to go up if larger RANGE are being tested, e.g. some * huge prime vs. some other huge prime, or otherwise scale in some * relation to RANGE and randmax */ #define NOBIAS_RUN 100 /* how many (hopefully) different random seeds to do the test under */ #define TRIALS 500 #define randof(x) ((rand() % x) % RANGE) unsigned int results[RANGE]; int main(void) { unsigned int i, maxfail, nobias, randmax, testnum, trialnum; double sq; #ifdef __OpenBSD__ if (pledge("stdio", NULL) == -1) err(1, "pledge failed"); #endif //setvbuf(stdout, (char *)NULL, _IOLBF, (size_t) 0); for (trialnum = 0; trialnum < TRIALS; trialnum++) { /* pseudorandom within pseudorandom, per Dune */ srand(arc4random()); nobias = 0; for (randmax = RANGE; randmax < UINT_MAX; randmax += 1) { for (testnum = 0; testnum < TESTNUM; testnum++) { results[randof(randmax)]++; } sq = 0.0; for (i = 0; i < RANGE; i++) { sq += pow((double) results[i] - EXPECTED, 2) / EXPECTED; results[i] = 0; // reset for the next test } if (gsl_cdf_chisq_Q(sq, DEG_OF_FREE) <= FITNESS) { maxfail = randmax; nobias = 0; } else { if (nobias++ >= NOBIAS_RUN) { break; } } } printf("%d\n", maxfail); } exit(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.634027326, "avg_line_length": 33.7802197802, "ext": "c", "hexsha": "3c992a8f5fb9c6eb3f73d2c48ffdf488b071b92e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-17T09:25:48.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-03T15:58:46.000Z", "max_forks_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "thrig/scripts", "max_forks_repo_path": "random/modulo-bias.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_issues_repo_issues_event_max_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-04T08:43:07.000Z", "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "thrig/scripts", "max_issues_repo_path": "random/modulo-bias.c", "max_line_length": 72, "max_stars_count": 17, "max_stars_repo_head_hexsha": "cbde9e8ea8c3abcad0745276b06a30f1c21f9221", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "thrig/scripts", "max_stars_repo_path": "random/modulo-bias.c", "max_stars_repo_stars_event_max_datetime": "2021-11-14T06:31:45.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-30T18:00:47.000Z", "num_tokens": 815, "size": 3074 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (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. $Id: minimizer_low.c 11822 2014-02-25 21:18:45Z dstrubbe $ */ #include <config.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include "string_f.h" /* A. First, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself and its gradient. */ /* This is a type used to communicate with Fortran; func_d is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func_d)(const int*, const double*, double*, const int*, double*); typedef struct{ func_d func; } param_fdf_t; /* Compute both f and df together. */ static void my_fdf (const gsl_vector *v, void *params, double *f, gsl_vector *df) { double *x, *gradient, ff2; int i, dim, getgrad; param_fdf_t * p; p = (param_fdf_t *) params; dim = v->size; x = (double *)malloc(dim*sizeof(double)); gradient = (double *)malloc(dim*sizeof(double)); for(i=0; i<dim; i++) x[i] = gsl_vector_get(v, i); getgrad = (df == NULL) ? 0 : 1; p->func(&dim, x, &ff2, &getgrad, gradient); if(f != NULL) *f = ff2; if(df != NULL){ for(i=0; i<dim; i++) gsl_vector_set(df, i, gradient[i]); } free(x); free(gradient); } static double my_f (const gsl_vector *v, void *params) { double val; my_fdf(v, params, &val, NULL); return val; } /* The gradient of f, df = (df/dx, df/dy). */ static void my_df (const gsl_vector *v, void *params, gsl_vector *df) { my_fdf(v, params, NULL, df); } typedef void (*print_f_ptr)(const int*, const int*, const double*, const double*, const double*, const double*); int FC_FUNC_(oct_minimize, OCT_MINIMIZE) (const int *method, const int *dim, double *point, const double *step, const double *line_tol, const double *tolgrad, const double *toldr, const int *maxiter, func_d f, const print_f_ptr write_info, double *minimum) { int iter = 0; int status; double maxgrad, maxdr; int i; double * oldpoint; double * grad; const gsl_multimin_fdfminimizer_type *T = NULL; gsl_multimin_fdfminimizer *s; gsl_vector *x; gsl_vector *absgrad, *absdr; gsl_multimin_function_fdf my_func; param_fdf_t p; p.func = f; oldpoint = (double *) malloc(*dim * sizeof(double)); grad = (double *) malloc(*dim * sizeof(double)); my_func.f = &my_f; my_func.df = &my_df; my_func.fdf = &my_fdf; my_func.n = *dim; my_func.params = (void *) &p; /* Starting point */ x = gsl_vector_alloc (*dim); for(i=0; i<*dim; i++) gsl_vector_set (x, i, point[i]); /* Allocate space for the gradient */ absgrad = gsl_vector_alloc (*dim); absdr = gsl_vector_alloc (*dim); //GSL recommends line_tol = 0.1; switch(*method){ case 1: T = gsl_multimin_fdfminimizer_steepest_descent; break; case 2: T = gsl_multimin_fdfminimizer_conjugate_fr; break; case 3: T = gsl_multimin_fdfminimizer_conjugate_pr; break; case 4: T = gsl_multimin_fdfminimizer_vector_bfgs; break; case 5: T = gsl_multimin_fdfminimizer_vector_bfgs2; break; } s = gsl_multimin_fdfminimizer_alloc (T, *dim); gsl_multimin_fdfminimizer_set (s, &my_func, x, *step, *line_tol); do { iter++; for(i=0; i<*dim; i++) oldpoint[i] = point[i]; /* Iterate */ status = gsl_multimin_fdfminimizer_iterate (s); /* Get current minimum, point and gradient */ *minimum = gsl_multimin_fdfminimizer_minimum(s); for(i=0; i<*dim; i++) point[i] = gsl_vector_get(gsl_multimin_fdfminimizer_x(s), i); for(i=0; i<*dim; i++) grad[i] = gsl_vector_get(gsl_multimin_fdfminimizer_gradient(s), i); /* Compute convergence criteria */ for(i=0; i<*dim; i++) gsl_vector_set(absdr, i, fabs(point[i]-oldpoint[i])); maxdr = gsl_vector_max(absdr); for(i=0; i<*dim; i++) gsl_vector_set(absgrad, i, fabs(grad[i])); maxgrad = gsl_vector_max(absgrad); /* Print information */ write_info(&iter, dim, minimum, &maxdr, &maxgrad, point); /* Store infomation for next iteration */ for(i=0; i<*dim; i++) oldpoint[i] = point[i]; if (status) break; if ( (maxgrad <= *tolgrad) || (maxdr <= *toldr) ) status = GSL_SUCCESS; else status = GSL_CONTINUE; } while (status == GSL_CONTINUE && iter <= *maxiter); if(status == GSL_CONTINUE) status = 1025; gsl_multimin_fdfminimizer_free (s); gsl_vector_free (x); gsl_vector_free(absgrad); gsl_vector_free(absdr); free(oldpoint); free(grad); return status; } /* B. Second, the interface to the gsl function that calculates the minimum of a one-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; func1 is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func1)(const double*, double*); typedef struct{ func1 func; } param_f1_t; double fn1(double x, void * params) { param_f1_t * p = (param_f1_t* ) params; double fx; p->func(&x, &fx); return fx; } void FC_FUNC_(oct_1dminimize, OCT_1DMINIMIZE)(double *a, double *b, double *m, func1 f, int *status) { int iter = 0; int max_iter = 100; const gsl_min_fminimizer_type *T; gsl_min_fminimizer *s; gsl_function F; param_f1_t p; p.func = f; F.function = &fn1; F.params = (void *) &p; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc (T); *status = gsl_min_fminimizer_set (s, &F, *m, *a, *b); gsl_set_error_handler_off(); do { iter++; *status = gsl_min_fminimizer_iterate (s); *m = gsl_min_fminimizer_x_minimum (s); *a = gsl_min_fminimizer_x_lower (s); *b = gsl_min_fminimizer_x_upper (s); *status = gsl_min_test_interval (*a, *b, 0.00001, 0.0); /*if (*status == GSL_SUCCESS) printf ("Converged:\n");*/ /*printf ("%5d [%.7f, %.7f] %.7f \n", iter, *a, *b,*m);*/ } while (*status == GSL_CONTINUE && iter < max_iter); gsl_min_fminimizer_free(s); } /* C. Third, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; funcn is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*funcn)(int*, double*, double*); typedef struct{ funcn func; } param_fn_t; double fn(const gsl_vector *v, void * params) { double val; double *x; int i, dim; param_fn_t * p; p = (param_fn_t *) params; dim = v->size; x = (double *)malloc(dim*sizeof(double)); for(i=0; i<dim; i++) x[i] = gsl_vector_get(v, i); p->func(&dim, x, &val); free(x); return val; } typedef void (*print_f_fn_ptr)(const int*, const int*, const double*, const double*, const double*); int FC_FUNC_(oct_minimize_direct, OCT_MINIMIZE_DIRECT) (const int *method, const int *dim, double *point, const double *step, const double *toldr, const int *maxiter, funcn f, const print_f_fn_ptr write_info, double *minimum) { int iter = 0, status, i; double size; const gsl_multimin_fminimizer_type *T = NULL; gsl_multimin_fminimizer *s = NULL; gsl_vector *x, *ss; gsl_multimin_function my_func; param_fn_t p; p.func = f; my_func.f = &fn; my_func.n = *dim; my_func.params = (void *) &p; /* Set the initial vertex size vector */ ss = gsl_vector_alloc (*dim); gsl_vector_set_all (ss, *step); /* Starting point */ x = gsl_vector_alloc (*dim); for(i=0; i<*dim; i++) gsl_vector_set (x, i, point[i]); switch(*method){ case 6: T = gsl_multimin_fminimizer_nmsimplex; break; } s = gsl_multimin_fminimizer_alloc (T, *dim); gsl_multimin_fminimizer_set (s, &my_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if(status) break; *minimum = gsl_multimin_fminimizer_minimum(s); for(i=0; i<*dim; i++) point[i] = gsl_vector_get(gsl_multimin_fminimizer_x(s), i); size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, *toldr); write_info(&iter, dim, minimum, &size, point); } while (status == GSL_CONTINUE && iter < *maxiter); if(status == GSL_CONTINUE) status = 1025; gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); return status; }
{ "alphanum_fraction": 0.6643147317, "avg_line_length": 25.9113573407, "ext": "c", "hexsha": "49e98c62fe815469c9e0469e272439cb82f941db", "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": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gimunu/octopus-metric", "max_forks_repo_path": "src/math/minimizer_low.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "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": "gimunu/octopus-metric", "max_issues_repo_path": "src/math/minimizer_low.c", "max_line_length": 112, "max_stars_count": null, "max_stars_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gimunu/octopus-metric", "max_stars_repo_path": "src/math/minimizer_low.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2770, "size": 9354 }
#include <cblas.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define STRASSEN_LOWER_BOUND 128 #define NAN -1 typedef float REAL_NUMBER; typedef struct { int nrows; int ncols; REAL_NUMBER* data; } matrix; matrix read_matrix(const char* file_name) { FILE* fp = fopen(file_name, "r"); matrix m; m.nrows = 0; m.ncols = 0; // get ncols and nrows REAL_NUMBER tempf = 0; char tempc = 1; while (tempc != '\n') { fscanf(fp, "%f", &tempf); fscanf(fp, "%c", &tempc); m.ncols++; } m.nrows++; while (fscanf(fp, "%c", &tempc) != EOF) { if (tempc == '\n') { m.nrows++; } } // read data rewind(fp); m.data = (REAL_NUMBER*)malloc(m.ncols * m.nrows * sizeof(REAL_NUMBER)); REAL_NUMBER* pread = m.data; for (int i = 0; i < m.ncols * m.nrows; i++) { // fscanf(fp, "%f", &m.data[i]); // fscanf(fp, "%f", m.data + i); fscanf(fp, "%f", pread); pread++; } fclose(fp); return m; } void print_matrix(matrix* m, const char* file_name) { FILE* fp = fopen(file_name, "w"); for (int i = 0; i < m->ncols * m->nrows; i++) { if (i > 0 && i % m->ncols == 0) { fputc('\n', fp); } fprintf(fp, "%g ", m->data[i]); } fputc('\n', fp); // last blank line fclose(fp); } matrix create_matrix(int nrows, int ncols, REAL_NUMBER fill) { matrix m = { .nrows = nrows, .ncols = ncols, .data = (REAL_NUMBER*)malloc(nrows * ncols * sizeof(REAL_NUMBER))}; if (fill != NAN) { for (int i = 0; i < nrows * ncols; i++) { m.data[i] = fill; } } return m; } int main(int argc, char const* argv[]) { if (argc != 4) { printf("Wrong number of arguments."); exit(EXIT_FAILURE); } const enum CBLAS_ORDER Order = CblasRowMajor; const enum CBLAS_TRANSPOSE TransA = CblasNoTrans; const enum CBLAS_TRANSPOSE TransB = CblasNoTrans; const float alpha=1; const float beta=0; double start, end; start = clock(); matrix m1 = read_matrix(argv[1]); matrix m2 = read_matrix(argv[2]); end = clock(); printf("Read file time: %fs\n", (double)(end - start) / CLOCKS_PER_SEC); start = clock(); matrix res = create_matrix(m1.nrows, m2.ncols, NAN); cblas_sgemm(Order, TransA, TransB, m1.nrows, m2.ncols, m1.ncols, alpha, m1.data, m1.ncols, m2.data, m2.ncols, beta, res.data, res.ncols); end = clock(); printf("Multiplication time: %fs\n", (double)(end - start) / CLOCKS_PER_SEC); print_matrix(&res, argv[3]); return 0; } // gcc -I D:\OpenBLAS-0.3.18-x64\include -L D:\OpenBLAS-0.3.18-x64\lib .\matmul_OpenBLAS.c -lopenblas -o matmul_OpenBLAS
{ "alphanum_fraction": 0.5551181102, "avg_line_length": 24.0862068966, "ext": "c", "hexsha": "8275dcdfaeb6fb551d03a9cb1ed68f75a9d6b53b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-27T08:16:02.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-03T03:01:20.000Z", "max_forks_repo_head_hexsha": "f585fd685a51e19fddc9c582846547d34442c6ef", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "XDZhelheim/CS205_C_CPP_Lab", "max_forks_repo_path": "project3/test/matmul_OpenBLAS.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f585fd685a51e19fddc9c582846547d34442c6ef", "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": "XDZhelheim/CS205_C_CPP_Lab", "max_issues_repo_path": "project3/test/matmul_OpenBLAS.c", "max_line_length": 141, "max_stars_count": 3, "max_stars_repo_head_hexsha": "f585fd685a51e19fddc9c582846547d34442c6ef", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "XDZhelheim/CS205_C_CPP_Lab", "max_stars_repo_path": "project3/test/matmul_OpenBLAS.c", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:15:45.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-11T08:12:40.000Z", "num_tokens": 867, "size": 2794 }
#ifndef CIMPLE_POLYTOPE_LIBRARY_CIMPLE_H #define CIMPLE_POLYTOPE_LIBRARY_CIMPLE_H #include <math.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_matrix.h> #include "cimple_gsl_library_extension.h" #include <gurobi_c.h> #include "setoper.h" #include <cdd.h> #include "cimple_auxiliary_functions.h" #include "cimple_minksum_wrapper.h" /** * H left side of polytope (sometimes noted A or L) * G right side of polytope (sometimes noted b or M) * * H.x <= G * * Chebyshev center is a possible definition of the "center" of the polytope. */ typedef struct polytope{ gsl_matrix * H; gsl_vector * G; double *chebyshev_center; }polytope; /** * @brief "Constructor" Dynamically allocates the space a polytope needs * @param k H.size1 == G.size * @param n H.size2 * @return */ struct polytope *polytope_alloc(size_t k, size_t n); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the polytope * @param polytope */ void polytope_free(polytope *polytope); /** * Subdivision of abstract state containing additionally to the polytope also safe mode instructions * The array of polytopes "polytope **safe_mode" contains N polytopes the system has to go through to reach the invariant set */ typedef struct cell{ polytope **safe_mode; polytope *polytope_description; }cell; /** * @brief "Constructor" Dynamically allocates the space a cell needs * @param k cell.polytope.H.size1 == G.size * @param n cell.polytope.HH.size2 * @return */ struct cell *cell_alloc(size_t k, size_t n, int time_horizon); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the cell * @param cell */ void cell_free(cell *cell); /** * Convex region of several (cells_count) polytopes (array of polytopes**) * hull_over_polytopes is the convex hull of polytopes in that abstract state * hull.A = NULL if only one polytope exists in that region */ typedef struct abstract_state{ polytope *convex_hull; int cells_count; cell **cells; int transitions_in_count; struct abstract_state** transitions_in; int transitions_out_count; struct abstract_state** transitions_out; int distance_invariant_set; struct abstract_state * next_state; cell *invariant_set; }abstract_state; /** * @brief "Constructor" Dynamically allocates the space a region of polytope needs * * Allocates memory space according to the cells_count and their respective sizes * * @param k Array with the number of rows of each polytope dim([cells_count]) * @param k_hull number of rows of convex hull polytope of the region * @param n system_dynamics size (e.g. s_dyn.A.size1) * @param cells_count * @return */ struct abstract_state *abstract_state_alloc(size_t *k, size_t k_hull, size_t n, int transitions_in_count, int transitions_out_count, int cells_count, int time_horizon); /** * @brief "Destructor" Deallocates the dynamically allocated memory of the region of polytopes * @param abstract_state */ void abstract_state_free(abstract_state * abstract_state); /** * @brief Converts two C arrays to a polytope consistent of a left side matrix (i.e. H) and right side vector (i.e. G) * @param polytope empty polytope with allocated memory * @param k number of rows of polytope (H.size1 or G.size) * @param n dimension of polytope = system_dynamics size (e.g. s_dyn.A.size1) * @param left_side C array to be converted to left side matrix * @param right_side C array to be converted to right side vector * @param name name of polytope, will be displayed to user terminal to inform about successfull initialization */ void polytope_from_arrays(polytope *polytope, double *left_side, double *right_side, double *cheby, char*name); /** * @brief Converts a polytope in gsl form to cdd constraint form * @param original * @param err * @return */ dd_PolyhedraPtr polytope_to_cdd(polytope *original, dd_ErrorType *err); /** * @brief Converts a polytope in cdd constraint form to gsl form * @param original * @return */ polytope* cdd_to_polytope(dd_PolyhedraPtr *original); /** * @brief Generate a polytope representing a scaled unit cube * @param scale * @param dimensions * @return gsl polytope */ polytope * polytope_scaled_unit_cube(double scale, int dimensions); /** * @brief Checks whether a state is in a certain polytope * @param polytope * @param x state to be checked * @return 0 if state is not in polytope or 1 if it is */ bool polytope_check_state(polytope *polytope, gsl_vector *x); /** * @brief Check whether P1 \ subset P2 * @param P1 * @param P2 * @return */ bool polytope_is_subset(polytope *P1, polytope *P2); /** * @brief Unite inequalities of P1 and P2 in new polytope and remove redundancies * @param P1 * @param P2 * @return */ polytope * polytope_unite_inequalities(polytope *P1, polytope *P2); /** * @brief Project gsl polytope of n+ dimensions to the first n dimensions * @param original * @param n * @return gsl polytope */ polytope* polytope_projection(polytope * original, size_t n); /** * @brief Multiplication of a polytope with a matrix * @param original * @param scale * @return gsl polytope */ polytope * polytope_linear_transform(polytope *original, gsl_matrix *scale); /** * @brief Remove redundancies from gsl polytope inequalities * @param original * @return */ polytope * polytope_minimize(polytope *original); /** * @brief Compute Minkowski sum of two polytopes * @param P1 * @param P2 * @return */ polytope * polytope_minkowski(polytope *P1, polytope *P2); /** * @brief Compute Pontryagin difference of two polytopes C=A-B s.t.: * A-B = {c \in A-B| c+b \in A, \forall b \in B} * @param P1 * @param P2 * @return */ polytope * polytope_pontryagin(polytope* P1, polytope* P2); /** * @brief Set up constraints in quadratic problem for GUROBI * @param constraints * @param model * @param N * @return */ int polytope_to_constraints_gurobi(polytope *constraints, GRBmodel *model, size_t N); /** * @brief Generate a polytope representing a scaled unit cube * @param scale * @param dimensions * @return cdd polytope */ dd_PolyhedraPtr cdd_scaled_unit_cube(double scale, int dimensions); /** * @brief Project cdd polytope of n+ dimensions to the first n dimensions * @param original * @param n * @return cdd polytope */ void cdd_projection(dd_PolyhedraPtr *original, dd_PolyhedraPtr *new, size_t n, dd_ErrorType *err); /** * @brief Remove redundancies from cdd polytope inequalities * @param original * @return cdd polytope */ dd_PolyhedraPtr cdd_minimize(dd_PolyhedraPtr *original, dd_ErrorType *err); #endif //CIMPLE_POLYTOPE_LIBRARY_CIMPLE_H
{ "alphanum_fraction": 0.6478070757, "avg_line_length": 27.3442028986, "ext": "h", "hexsha": "c9c3218f7fb77d93ba149cc46b1b00ea9576db6b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/cimple_polytope_library.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/cimple_polytope_library.h", "max_line_length": 125, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/cimple_polytope_library.h", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 1891, "size": 7547 }
/*********************************** V1 IMPLEMENTATION USING RANDOM POINTS ************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <cblas.h> #include <string.h> #include <mpi.h> #include "../inc/knnring.h" int main(int argc, char *argv[]){ int p_rank; int p_size; int n; int d; int k; double *X; //INITIALIZE MPI COMMUNICATIONS MPI_Init(&argc,&argv); if(argc<4){ printf("ERROR: GIVE CORRECT NUMBERS OF ARGUMENTS n,d,k\n"); exit(1); }else{ n = atoi(argv[1]); d = atoi(argv[2]); k = atoi(argv[3]); } MPI_Comm_size(MPI_COMM_WORLD, &p_size); MPI_Comm_rank(MPI_COMM_WORLD, &p_rank); MPI_Status status; // STATUS COMMUNICATION int tag = 1; //COMMUNICATION TAG struct timespec ts_start; struct timespec ts_end; double time; if(p_rank == 0){ X = (double *)malloc(n*d*sizeof(double)); for(int i=1;i<p_size;i++){ create_points(X,n*d); MPI_Send(X,n*d,MPI_DOUBLE, i, tag, MPI_COMM_WORLD); } //compute points for myself create_points(X,n*d); clock_gettime(CLOCK_MONOTONIC, &ts_start); knnresult results = distrAllkNN(X,n,d,k); clock_gettime(CLOCK_MONOTONIC, &ts_end); time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000; printf("TOTAL V1 time: %lf\n",time); //WRITE RESULTS TO FILE char str[200]; snprintf(str,sizeof(str),"results/dist_knn_%d_%d_%d.txt",n,d,k); //write_to_file(str,results.nidx,results.ndist,n*k,results.k); for(int p=1;p<p_size;p++){ MPI_Recv(results.nidx, n*k, MPI_INT,p,tag,MPI_COMM_WORLD, &status); MPI_Recv(results.ndist,n*k, MPI_DOUBLE,p,tag,MPI_COMM_WORLD, &status); //write_to_file(str,results.nidx,results.ndist,n*k,results.k); } }else{ //receive points X = (double *)malloc(n*d*sizeof(double)); MPI_Recv(X,n*d,MPI_DOUBLE, 0, tag, MPI_COMM_WORLD, &status); clock_gettime(CLOCK_MONOTONIC, &ts_start); knnresult results = distrAllkNN(X,n,d,k); clock_gettime(CLOCK_MONOTONIC, &ts_end); time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000; //printf("TOTAL V1 time: %lf from process %d\n",time,p_rank); MPI_Send(results.nidx, n*k, MPI_INT ,0,tag,MPI_COMM_WORLD); MPI_Send(results.ndist,n*k, MPI_DOUBLE,0,tag,MPI_COMM_WORLD); } //execution is over MPI_Finalize(); printf("DONE ....=>EXITING\n"); return 0; }
{ "alphanum_fraction": 0.632629108, "avg_line_length": 27.1914893617, "ext": "c", "hexsha": "9cec664e40376adf3650b51b8b5ffbfd72bfa7f3", "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": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kv13/Parallel-And-Distributed-Systems", "max_forks_repo_path": "assignment2/src/v1_mpi2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "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": "kv13/Parallel-And-Distributed-Systems", "max_issues_repo_path": "assignment2/src/v1_mpi2.c", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kv13/Parallel-And-Distributed-Systems", "max_stars_repo_path": "assignment2/src/v1_mpi2.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 745, "size": 2556 }
#include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include "gauss.h" #define SQRT_2_PI 2.506628274631 /* sqrt(2*PI) */ #define LOG_SQRT_2_PI 0.918938533204673 /* log(sqrt(2*PI)) */ gauss_t gauss_init_prec(double prec_mean, double prec){ gauss_t r; r.prec_mean = prec_mean; r.prec = prec; r.var = 1.0 / prec; r.mean = prec_mean / prec; r.stddev = sqrt(r.var); return r; } gauss_t gauss_init_var(double mean, double var){ gauss_t r; r.var = var; r.mean = mean; r.stddev = sqrt(var); r.prec = 1.0 / var; r.prec_mean = r.prec * r.mean; return r; } gauss_t gauss_init_std(double mean, double stddev){ gauss_t r; r.var = stddev * stddev; r.mean = mean; r.stddev = stddev; r.prec = 1.0 / r.var; r.prec_mean = r.prec * r.mean; return r; } double gauss_log_product_normal(gauss_t a, gauss_t b){ if(a.prec == 0 || b.prec == 0) return 0.0; double var_sum = a.var + b.var; double mean_diff = a.mean - b.mean; return -LOG_SQRT_2_PI - (log(var_sum)/2.0) - ((mean_diff * mean_diff) / (2.0 * var_sum)); } double gauss_log_ratio_normal(gauss_t a, gauss_t b){ if(a.prec == 0 || b.prec == 0) return 0.0; double var_diff = a.var - b.var; double mean_diff = a.mean - b.mean; return log(b.var) + LOG_SQRT_2_PI - (log(var_diff)/2.0) + ((mean_diff * mean_diff) / (2.0 * var_diff)); } double gauss_cdf_P(gauss_t a, double x){ return gsl_cdf_gaussian_P(x - a.mean, a.stddev); } double gauss_cdf_Q(gauss_t a, double x){ return gsl_cdf_gaussian_Q(x - a.mean, a.stddev); } gauss_t gauss_add(gauss_t a, gauss_t b){ gauss_t r; r.mean = a.mean + b.mean; r.var = a.var + b.var; r.prec = 1.0 / r.var; r.prec_mean = r.prec * r.mean; r.stddev = sqrt(r.var); return r; } gauss_t gauss_sub(gauss_t a, gauss_t b){ gauss_t temp = b; temp.mean = -temp.mean; return gauss_add(a, temp); } double gauss_abs_diff(gauss_t a, gauss_t b){ double prec_mean_diff = fabs(a.prec_mean - b.prec_mean); double prec_diff = sqrt(fabs(a.prec - b.prec)); return (prec_mean_diff > prec_diff) ? prec_mean_diff : prec_diff; } gauss_t gauss_div(gauss_t a, gauss_t b){ double prec = a.prec - b.prec; double prec_mean = a.prec_mean - b.prec_mean; return gauss_init_prec(prec_mean, prec); } gauss_t gauss_mul(gauss_t a, gauss_t b){ double prec = a.prec + b.prec; double prec_mean = a.prec_mean + b.prec_mean; return gauss_init_prec(prec_mean, prec); }
{ "alphanum_fraction": 0.6483560545, "avg_line_length": 24.213592233, "ext": "c", "hexsha": "8c314da6c7814b40f3fdf9ecd5036480073d2980", "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": "gauss.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": "gauss.c", "max_line_length": 104, "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": "gauss.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 810, "size": 2494 }
#include "sparse-matrix.h" #include "sparse-solver.h" #include "sparse-solver-private.h" #include <stdlib.h> #include <string.h> #if HAVE_MKL_LAPACK #include <mkl_lapacke.h> #else #include <lapacke.h> #endif #include <assert.h> void sparse_lapack_init (SparseSolver *solver) { } void sparse_lapack_clear (SparseSolver *solver) { } int sparse_lapack_solve (SparseSolver *solver, SparseMatrix *A, void *x, const void *b) { lapack_int ret; assert (A->storage == SPARSE_MATRIX_STORAGE_DENSE); assert (A->shape[0] == A->shape[1]); lapack_int *pivot = malloc (A->shape[0] * sizeof (lapack_int)); if (A->type == SPARSE_MATRIX_TYPE_DOUBLE) { memcpy (x, b, A->shape[1] * sizeof (double)); ret = LAPACKE_dgesv (LAPACK_ROW_MAJOR, A->shape[0], 1, A->data, A->shape[1], pivot, (double*) x, 1); } else if (A->type == SPARSE_MATRIX_TYPE_FLOAT) { memcpy (x, b, A->shape[1] * sizeof (float)); ret = LAPACKE_sgesv (LAPACK_ROW_MAJOR, A->shape[0], 1, A->data, A->shape[1], pivot, (float*) x, 1); } else { assert (0); } free (pivot); return ret == 0; }
{ "alphanum_fraction": 0.4405422058, "avg_line_length": 22.2328767123, "ext": "c", "hexsha": "113ec1fc9a0bbf5c5de1951def5a2be2f54d59ff", "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": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "major-lab/mirbooking", "max_forks_repo_path": "contrib/sparse/sparse-lapack.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "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": "major-lab/mirbooking", "max_issues_repo_path": "contrib/sparse/sparse-lapack.c", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "major-lab/mirbooking", "max_stars_repo_path": "contrib/sparse/sparse-lapack.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 387, "size": 1623 }
#ifndef OPENMC_TALLIES_FILTER_H #define OPENMC_TALLIES_FILTER_H #include <cstdint> #include <string> #include <unordered_map> #include "pugixml.hpp" #include <gsl/gsl> #include "openmc/constants.h" #include "openmc/hdf5_interface.h" #include "openmc/memory.h" #include "openmc/particle.h" #include "openmc/tallies/filter_match.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Modifies tally score events. //============================================================================== class Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors, factory functions Filter(); virtual ~Filter(); //! Create a new tally filter // //! \tparam T Type of the filter //! \param[in] id Unique ID for the filter. If none is passed, an ID is //! automatically assigned //! \return Pointer to the new filter object template<typename T> static T* create(int32_t id = -1); //! Create a new tally filter // //! \param[in] type Type of the filter //! \param[in] id Unique ID for the filter. If none is passed, an ID is //! automatically assigned //! \return Pointer to the new filter object static Filter* create(const std::string& type, int32_t id = -1); //! Create a new tally filter from an XML node // //! \param[in] node XML node //! \return Pointer to the new filter object static Filter* create(pugi::xml_node node); //! Uses an XML input to fill the filter's data fields. virtual void from_xml(pugi::xml_node node) = 0; //---------------------------------------------------------------------------- // Methods virtual std::string type() const = 0; //! Matches a tally event to a set of filter bins and weights. //! //! \param[in] p Particle being tracked //! \param[in] estimator Tally estimator being used //! \param[out] match will contain the matching bins and corresponding //! weights; note that there may be zero matching bins virtual void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const = 0; //! Writes data describing this filter to an HDF5 statepoint group. virtual void to_statepoint(hid_t filter_group) const { write_dataset(filter_group, "type", type()); write_dataset(filter_group, "n_bins", n_bins_); } //! Return a string describing a filter bin for the tallies.out file. // //! For example, an `EnergyFilter` might return the string //! "Incoming Energy [0.625E-6, 20.0)". virtual std::string text_label(int bin) const = 0; //---------------------------------------------------------------------------- // Accessors //! Get unique ID of filter //! \return Unique ID int32_t id() const { return id_; } //! Assign a unique ID to the filter //! \param[in] Unique ID to assign. A value of -1 indicates that an ID should //! be automatically assigned void set_id(int32_t id); //! Get number of bins //! \return Number of bins int n_bins() const { return n_bins_; } gsl::index index() const { return index_; } //---------------------------------------------------------------------------- // Data members protected: int n_bins_; private: int32_t id_ {C_NONE}; gsl::index index_; }; //============================================================================== // Global variables //============================================================================== namespace model { extern "C" int32_t n_filters; extern std::unordered_map<int, int> filter_map; extern vector<unique_ptr<Filter>> tally_filters; } //============================================================================== // Non-member functions //============================================================================== //! Make sure index corresponds to a valid filter int verify_filter(int32_t index); } // namespace openmc #endif // OPENMC_TALLIES_FILTER_H
{ "alphanum_fraction": 0.5542558487, "avg_line_length": 29.9850746269, "ext": "h", "hexsha": "9620632a340dfe7869b01b85a6afeb14be45eece", "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": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cjwyett/openmc", "max_forks_repo_path": "include/openmc/tallies/filter.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cjwyett/openmc", "max_issues_repo_path": "include/openmc/tallies/filter.h", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cjwyett/openmc", "max_stars_repo_path": "include/openmc/tallies/filter.h", "max_stars_repo_stars_event_max_datetime": "2020-02-07T20:23:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-07T20:23:33.000Z", "num_tokens": 875, "size": 4018 }
/* 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: entropy.c * * Description: Calculate the entropy production for a given state, generator * and equilibrium state * * Version: 1.0 * Created: 05/05/2014 20:53:01 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include <gsl/gsl_math.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "funcs.h" /* * FUNCTION * Name: entropy_production * Description: * */ double entropy_production ( const gsl_vector* rho, const gsl_vector* rhoeq, const gsl_matrix* L ) { /* l1, l2, l3 */ double l[3] ; unsigned int i, j ; for ( i = 1 ; i < 3 ; i++ ) { l[i] = 0 ; for ( j = 0 ; j < 3 ; j++ ) l[i] += gsl_matrix_get(L,i,j)*VECTOR(rho,j) ; } /* L[rho] */ double Lr = 0 ; for ( i = 1 ; i < 3 ; i++ ) Lr += l[i]*VECTOR(rho,i) ; /* L[rhoeq] */ double Leq = 0 ; for ( i = 1 ; i < 3 ; i++ ) Leq += l[i]*VECTOR(rhoeq,i) ; /* r , req */ double r, req ; r = req = 0 ; r = gsl_hypot3(VECTOR(rho,1),VECTOR(rho,2),VECTOR(rho,3)) ; req = gsl_hypot3(VECTOR(rhoeq,1),VECTOR(rhoeq,2), VECTOR(rhoeq,3)) ; /* internal entropy s */ double s ; if ( r < 1 && req < 1 ) s = -(gsl_sf_log((1+r)/(1-r))*Lr/r -gsl_sf_log((1+req)/(1-req))*Leq/req); else if ( r < 1 && req >= 0 ) s = -gsl_sf_log((1+r)/(1-r))*Lr/r ; else s = 0 ; return s; } /* ----- end of function entropy_production ----- */ /* * FUNCTION * Name: entropy_of_state * Description: Calculate the Von Neumann entropy of state 'rho' * */ double entropy_of_state ( const gsl_vector* rho ) { double entr = 0 ; /* Finding the eigenvalues */ gsl_eigen_herm_workspace* rho_ei = gsl_eigen_herm_alloc(2); gsl_matrix_complex* dens = gsl_matrix_complex_calloc (2,2); gsl_matrix_complex_set (dens, 0, 0, gsl_complex_rect(1+VECTOR(rho, 3),0)); gsl_matrix_complex_set (dens,0,1,gsl_complex_rect(VECTOR(rho,1),-VECTOR(rho,2))); gsl_matrix_complex_set (dens,1,0,gsl_complex_rect(VECTOR(rho,1),VECTOR(rho,2))); gsl_matrix_complex_set (dens,1,1,gsl_complex_rect(1-VECTOR(rho,3),0)); gsl_matrix_complex_scale (dens, gsl_complex_rect(0.5,0)); gsl_vector* eigenvalues = gsl_vector_calloc(2) ; gsl_eigen_herm (dens, eigenvalues, rho_ei) ; /* Calculating entropy */ double norm = gsl_hypot3( VECTOR(rho,1), VECTOR(rho,2), VECTOR(rho,3) ) ; if ( gsl_fcmp(norm, 1, 1e-9) > 0 ) entr = 0 ; else entr = - (VECTOR(eigenvalues,0)*gsl_sf_log(VECTOR(eigenvalues,0)) + VECTOR(eigenvalues,1)*gsl_sf_log(VECTOR(eigenvalues,1))) ; return (entr); } /* ----- end of function entropy_of_state ----- */
{ "alphanum_fraction": 0.6682464455, "avg_line_length": 31.2592592593, "ext": "c", "hexsha": "1b7a61376a32a817372151837c09a214ac21e1c5", "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": "entropy.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": "entropy.c", "max_line_length": 82, "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": "entropy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1272, "size": 4220 }
/**************************************************************** * * vpreprocess: FreqFilter.c * * Copyright (C) Max Planck Institute * for Human Cognitive and Brain Sciences, Leipzig * * <lipsia@cbs.mpg.de> * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * $Id: FreqFilter.c 3181 2008-04-01 15:19:44Z karstenm $ * *****************************************************************/ #include <viaio/VImage.h> #include <viaio/Vlib.h> #include <viaio/mu.h> #include <viaio/option.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <fftw3.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> extern gsl_matrix *DataMap(VImage *src,VImage mask,size_t nvox,int); gsl_matrix *DataMap(VImage *src,VImage mask,size_t nvox,int tail) { int j,b,r,c; int nrows=0,ncols=0,nt0=0; double tiny=1.0e-6; int nslices = VImageNBands(mask); VImageDimensions(src,nslices,&nt0,&nrows,&ncols); int nt = nt0 + 2*tail; gsl_matrix *A = gsl_matrix_calloc(nvox,nt); size_t n=0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { double u = VGetPixel(src[b],0,r,c); if (fabs(u) < tiny) continue; for (j=0; j<tail; j++) { u = (double)VGetPixel(src[b],tail-j,r,c); gsl_matrix_set(A,n,j,u); } for (j=tail; j<nt-tail; j++) { u = (double)VGetPixel(src[b],j-tail,r,c); gsl_matrix_set(A,n,j,u); } for (j=nt-tail; j<nt; j++) { u = (double)VGetPixel(src[b],2*nt-3*tail-2-j,r,c); gsl_matrix_set(A,n,j,u); } n++; } } } return A; } void VFreqFilter(VAttrList list,VFloat high,VFloat low,VBoolean stop,VFloat sharp) { VString str1=NULL; double *in=NULL; fftw_complex *out; fftw_plan p1,p2; int i,j,nc,b,r,c; float freq=0,alpha=0; double *highp=NULL, *lowp=NULL; double x_high, x_low, x; double u=0,v=0,tiny=1.0e-6; /* dialog messages */ str1 = (VString)VMalloc(sizeof(char)*4); if (stop) strcpy(str1, "stop"); else strcpy(str1, "pass"); if (low>0 && high>0) fprintf(stderr," band %s filter: 1/%.1f Hz and 1/%.1f Hz\n",str1,high,low); else { if (high>0) fprintf(stderr," high %s filter: 1/%.1f Hz\n",str1,high); if (low>0) fprintf(stderr," low %s filter: 1/%.1f Hz\n",str1,low); } /* read functional data */ int nrows=0,ncols=0,nt=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&nt,&nrows,&ncols); /* read header info */ double *D = (double *)VCalloc(8,sizeof(double)); for (i=0; i<8; i++) D[i] = 1.0; VAttrList geolist = VGetGeoInfo(list); if (geolist != NULL) D = VGetGeoPixdim(geolist,D); double tr = D[4]; VFloat xtr=-1; if (VGetAttr(VImageAttrList(src[0]),"repetition_time",NULL,VFloatRepn,&xtr) == VAttrFound) { tr = (double)xtr; } if (tr > 100) tr /= 1000.0; /* convert to seconds */ if (tr < 0.01) VError("FreqFilter: implausible TR (%f seconds)",tr); fprintf(stderr," image dimensions: %d x %d x %d, nt= %d, TR= %.3f secs\n",nslices,nrows,ncols,nt,tr); /* alloc memory */ double nx = (double)nt; int tail = 50; if (nt<tail) tail=nt-2; nt += 2 * tail; nc = (nt / 2) + 1; in = (double *)fftw_malloc(sizeof(double) * nt); out = fftw_malloc (sizeof (fftw_complex ) * nc); for (i=0; i<nt; i++) in[i] = 0; /* make plans */ p1 = fftw_plan_dft_r2c_1d (nt,in,out,FFTW_ESTIMATE); p2 = fftw_plan_dft_c2r_1d (nt,out,in,FFTW_ESTIMATE); /* repetition time */ alpha = (double)nt * tr; /* filter function */ if (sharp > 0) { highp = (double *)malloc(sizeof(double) * nc); lowp = (double *)malloc(sizeof(double) * nc); for (i=1; i <nc; i++) { highp[i] = 1.0 / (1.0 + exp( (alpha/high -(double)i)*sharp ) ); lowp[i] = 1.0 / (1.0 + exp( ((double)i - alpha/low)*sharp ) ); } } /* create ROI mask */ VImage mask = VCreateImage(nslices,nrows,ncols,VBitRepn); VFillImage(mask,VAllBands,0); size_t nvox=0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { double u = VGetPixel(src[b],0,r,c); if (fabs(u) < tiny) continue; VPixel(mask,b,r,c,VBit) = 1; nvox++; } } } /* map to double values */ gsl_matrix *A = DataMap(src,mask,nvox,tail); double zmax = gsl_matrix_max(A); double zmin = gsl_matrix_min(A); /* main process */ size_t n=0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { if (VPixel(mask,b,r,c,VBit) == 0) continue; for (i=0; i<nt; i++) { in[i] = gsl_matrix_get(A,n,i); } /* fft */ fftw_execute(p1); /* remove specified frequencies */ for (i=1; i <nc; i++) { if (sharp > 0) { /* highpass */ if (high > 0) x_high = highp[i]; else x_high = 1.0; /* lowpass */ if (low > 0) x_low = lowp[i]; else x_low = 1.0; x = x_high + x_low - 1.0; if (stop) x = fabs(1.0-x); out[i][0] *= x; out[i][1] *= x; } else { /* hard thresholding */ freq = 1.0/(double)i * alpha; /* 1/frequency */ if ((!stop && (freq < low || (freq > high && high>0))) || (stop && !(freq < low || (freq > high && high>0)))) out[i][0] = out[i][1] = 0; } } /* inverse fft */ fftw_execute(p2); for (i=0; i<nt; i++) { gsl_matrix_set(A,n,i,in[i]/nx); } n++; } } } /* rescale */ VRepnKind repn = VPixelRepn(src[0]); double smax = VPixelMaxValue(src[0]); double smin = VPixelMinValue(src[0]); double ymax = 32000; if (repn == VFloatRepn || repn == VDoubleRepn) ymax = 1000.0; for (b=0; b<nslices; b++) { VFillImage(src[b],VAllBands,0); } zmax = gsl_matrix_max(A); zmin = gsl_matrix_min(A); /* write output */ n=0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { if (VPixel(mask,b,r,c,VBit) == 0) continue; /* map to output image */ for (j=tail; j<nt-tail; j++) { u = gsl_matrix_get(A,n,j); if (fabs(u) > 0.0001) u = (u-zmin)/(zmax-zmin); else u = 0; if (u > 1.0) u = 1.0; if (u < 0) u = 0; v = u*ymax; if (v > smax) v = smax; if (v < smin) v = smin; VSetPixel(src[b],j-tail,r,c,v); } n++; } } } VDestroyImage(mask); gsl_matrix_free(A); }
{ "alphanum_fraction": 0.5725462304, "avg_line_length": 24.6666666667, "ext": "c", "hexsha": "be09fb4893915bca21886e1e306e09ece8956550", "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/FreqFilter.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/FreqFilter.c", "max_line_length": 107, "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/FreqFilter.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": 2490, "size": 7030 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2017 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 <cblas.h> #include <lapacke.h> #include <rokko/cmatrix.h> int imax(int x, int y) { return (x > y) ? x : y; } int main(int argc, char** argv) { int n = 5; int i, j, info; double norm; double *w; double **a, **u, **t; if (argc > 1) n = atoi(argv[1]); /* generate matrix */ a = alloc_dmatrix(n, n); for (j = 0; j < n; ++j) { for (i = 0; i < n; ++i) { mat_elem(a, i, j) = n - imax(i, j); } } printf("Matrix A: "); fprint_dmatrix(stdout, n, n, a); /* diagonalization */ u = alloc_dmatrix(n, n); cblas_dcopy(n * n, mat_ptr(a), 1, mat_ptr(u), 1); w = alloc_dvector(n); info = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'U', n, mat_ptr(u), n, vec_ptr(w)); if (info != 0) { fprintf(stderr, "Error: dsyev fails with error code %d\n", info); exit(255); } printf("Eigenvalues: "); fprint_dvector(stdout, n, w); printf("Eigenvectors: "); fprint_dmatrix(stdout, n, n, u); /* orthogonality check */ t = alloc_dmatrix(n, n); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, mat_ptr(u), n, mat_ptr(u), n, 0, mat_ptr(t), n); for (i = 0; i < n; ++i) mat_elem(t, i, i) -= 1; norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, mat_ptr(t), n); printf("|| U^t U - I || = %e\n", norm); if (norm > 1e-10) { fprintf(stderr, "Error: orthogonality check\n"); exit(255); } /* eigenvalue check */ cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1, mat_ptr(a), n, mat_ptr(u), n, 0, mat_ptr(t), n); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, mat_ptr(u), n, mat_ptr(t), n, 0, mat_ptr(a), n); for (i = 0; i < n; ++i) mat_elem(a, i, i) -= w[i]; norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, mat_ptr(a), n); printf("|| U^t A U - diag(w) || = %e\n", norm); if (norm > 1e-10) { fprintf(stderr, "Error: eigenvalue check\n"); exit(255); } free_dmatrix(a); free_dmatrix(u); free_dvector(w); free_dmatrix(t); return 0; }
{ "alphanum_fraction": 0.5529601289, "avg_line_length": 30.2804878049, "ext": "c", "hexsha": "7f301933b0cc60b5c7cf23946fa54d0ffd17f770", "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/lapack/dsyev.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/lapack/dsyev.c", "max_line_length": 83, "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/lapack/dsyev.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": 858, "size": 2483 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_sf.h> // Compute the psi polygamma function int main (int argc, char **argv) { if ( argc != 3 ) { fprintf(stderr,"Incorrect arguments\n"); return 1; } double x1 = atof(argv[1]); double x2 = atof(argv[2]); printf("%g\n",gsl_sf_psi_n(x1,x2)); return 0; }
{ "alphanum_fraction": 0.601744186, "avg_line_length": 16.380952381, "ext": "c", "hexsha": "e2a38b561c3e71aa94c598970bdfff838bab268b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-02-10T19:59:53.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-22T07:53:00.000Z", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_path": "src/idl/TEST/Isotropy2/psi.c", "max_issues_count": 8, "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_issues_event_max_datetime": "2022-02-01T16:24:43.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-28T17:09:50.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_path": "src/idl/TEST/Isotropy2/psi.c", "max_line_length": 46, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_path": "src/idl/TEST/Isotropy2/psi.c", "max_stars_repo_stars_event_max_datetime": "2021-11-26T10:20:02.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-09T05:03:24.000Z", "num_tokens": 106, "size": 344 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include "parmt_config.h" #include "compearth.h" #ifdef PARMT_USE_INTEL #include <mkl.h> #include <mkl_lapacke.h> #include <mkl_cblas.h> #include <ipps.h> #else #include <lapacke.h> #include <cblas.h> #endif #include "iscl/array/array.h" #include "iscl/linalg/linalg.h" #include "iscl/memory/memory.h" #include "iscl/statistics/statistics.h" #include "iscl/sorting/sorting.h" static double median_sorted_array(int n, const double *__restrict x); static int setG64f(const int npts, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, double *__restrict__ G); #define LDG 8 int parmt_computeL1Magnitude64f(const int ldm, const int nobs, const int nmtSolve, const int maxit, const double eps, const double tol, const int *__restrict__ signalPtr, const int *__restrict__ lags, const int *__restrict__ mtPtr, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, const double *__restrict__ mts, const double *__restrict__ d, double *__restrict__ mags) { const char *fcnm = "parmt_computeL1Magnitude64f\0"; double *G, *est, *obs, *wts, xmag; double m6[8] __attribute__((aligned(64))); int i, i1, i2, ierr, imt, jmt, k, maxlag, nptsAll, nptsPad; bool luseLag; const double p = 1.0; const double one = 1.0; const double zero = 0.0; nptsAll = signalPtr[nobs]; if (nobs < 1) { printf("%s: Error no observations\n", fcnm); return -1; } // Get the max number of lags maxlag = 0; luseLag = false; if (lags != NULL) { luseLag = true; maxlag = lags[array_absArgmax32i(nobs, lags, &ierr)]; } if (maxlag == 0){luseLag = false;} nptsPad = nptsAll + nobs*maxlag; G = memory_calloc64f(nptsPad*LDG); obs = memory_calloc64f(nptsPad); est = memory_calloc64f(nptsPad); wts = memory_calloc64f(nptsPad); // Insert the Green's functions and data into the moment tensor matrix if (!luseLag) { for (k=0; k<nobs; k++) { i1 = signalPtr[k]; i2 = signalPtr[k+1]; for (i=i1; i<i2; i++) { G[i*LDG+0] = Gxx[i]; G[i*LDG+1] = Gyy[i]; G[i*LDG+2] = Gzz[i]; G[i*LDG+3] = Gxy[i]; G[i*LDG+4] = Gxz[i]; G[i*LDG+5] = Gyz[i]; obs[i] = d[i]; } } } else { } for (imt=0; imt<nmtSolve; imt++) { // Extract the moment tensor jmt = mtPtr[imt]; for (i=0; i<6; i++) { m6[0] = mts[ldm*jmt+0]; } // Remove the scalar moment compearth_CMT2m0(1, 1, m6, &xmag); cblas_dscal(6, 1.0/xmag, m6, 1); // Create the linear model [G*m]*M0 = [est]*{M0} = {obs} cblas_dgemv(CblasRowMajor, CblasNoTrans, nptsAll, 6, one, G, LDG, m6, 1, zero, est, 1); // Solve for magnitude in the L1 norm ierr = linalg_irls64f_work(nptsAll, 1, maxit, p, eps, tol, est, obs, &xmag, wts); mags[imt] = xmag; double xmagMw; compearth_m02mw(1, CE_KANAMORI_1978, &xmag, &xmagMw); printf("%f\n", xmagMw); } memory_free64f(&wts); memory_free64f(&G); memory_free64f(&obs); memory_free64f(&est); return 0; } int parmt_computeL1StationMagnitude64f(const int ldm, const int nmt, const int npts, const int nblock, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, const double *__restrict__ mts, const double *__restrict__ d, double *__restrict__ mags) { const char *fcnm = "parmt_computeL1StationMagnitude64f\0"; double *G, *M, *R, *Dmat, *res, *resSort, xmag, xopt; const double one = 1.0; const double zero = 0.0; const double negOne =-one; int *perm; bool lsorted; int i, ic, idx, ierr, imt, jdx, jmt, mblock, Mrows, Ncols; const int Kcols = 6; // Number of columns of G Mrows = npts; mblock = nblock;// + computePadding6f(npts); G = memory_calloc64f(LDG*npts); R = memory_calloc64f(mblock*npts); M = memory_calloc64f(mblock*8); Dmat = memory_calloc64f(mblock*npts); res = memory_calloc64f(npts); resSort = memory_calloc64f(npts); perm = memory_calloc32i(npts); for (i=0; i<npts; i++){perm[i] = i;} // Set the observations for (i=0; i<npts; i++) { for (ic=0; ic<nblock; ic++) { Dmat[mblock*i+ic] = d[i]; } } #ifdef __INTEL_COMPILER __assume_aligned(G, 64); #endif ierr = setG64f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, G); if (ierr != 0) { printf("%s: Failed to set G\n", fcnm); return -1; } int nsorted = 0; for (jmt=0; jmt<nmt; jmt=jmt+nblock) { Ncols = MIN(nblock, nmt - jmt); // Number of columns of M // Set the observations cblas_dcopy(npts*mblock, Dmat, 1, R, 1); for (i=0; i<6; i++) { for (ic=0; ic<Ncols; ic++) { imt = jmt + ic; idx = ldm*imt + i; jdx = mblock*i; M[jdx+ic] = mts[idx];///xmag; } } // Compute R = GM - D = GM - R cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Mrows, Ncols, Kcols, one, G, LDG, M, mblock, negOne, R, mblock); //lsorted = false; //for (i=0; i<npts; i++){perm[i] = i;} // Sort the columns of the residual matrix for (ic=0; ic<Ncols; ic++) { imt = jmt + ic; // Compute the absolute value of the residual for (i=0; i<npts; i++) { res[i] = fabs(R[ic+i*mblock]); } //cblas_dcopy(npts, &R[ic], mblock, res, 1); // Apply the old permutation sorting_applyPermutation64f_work(npts, perm, res, resSort); lsorted = sorting_issorted64f(npts, resSort, SORT_ASCENDING, &ierr); if (!lsorted) { sorting_argsort64f_work(npts, res, SORT_ASCENDING, perm); sorting_applyPermutation64f_work(npts, perm, res, resSort); } else { nsorted = nsorted + 1; } // Compute the median xopt = median_sorted_array(npts, resSort); //compearth_CMT2mw(1, 1, &mts[8*imt], &xmag); compearth_CMT2m0(1, 1, &mts[8*imt], &xmag); xopt = xopt*xmag; compearth_m02mw(1, CE_KANAMORI_1978, &xopt, &mags[imt]); } } printf("%d %d\n", nsorted, nmt); memory_free32i(&perm); memory_free64f(&G); memory_free64f(&R); memory_free64f(&M); memory_free64f(&Dmat); memory_free64f(&res); memory_free64f(&resSort); return 0; } static double median_sorted_array(int n, const double *__restrict x) { double xmed; int n2; const double half = 0.5; n2 = n/2; // Even -> average middle two elements if (fmod(n, 2) == 0) { xmed = half*(x[n2-1] + x[n2]); } // Median is middle element else { xmed = x[n2]; } return xmed; } static int setG64f(const int npts, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, double *__restrict__ G) { const char *fcnm = "setG64f\0"; int i; bool lalign; if (Gxx == NULL || Gyy == NULL || Gzz == NULL || Gxy == NULL || Gxz == NULL || G == NULL || npts < 1) { if (Gxx == NULL){printf("%s: Error Gxx is NULL\n", fcnm);} if (Gyy == NULL){printf("%s: Error Gyy is NULL\n", fcnm);} if (Gzz == NULL){printf("%s: Error Gzz is NULL\n", fcnm);} if (Gxy == NULL){printf("%s: Error Gxy is NULL\n", fcnm);} if (Gxz == NULL){printf("%s: Error Gxz is NULL\n", fcnm);} if (Gyz == NULL){printf("%s: ERror Gyz is NULL\n", fcnm);} if (npts < 1) { printf("%s: No points in Green's functions\n", fcnm); } return -1; } lalign = true; if (memory_isAligned(Gxx, 64) != 1 || memory_isAligned(Gyy, 64) != 1 || memory_isAligned(Gzz, 64) != 1 || memory_isAligned(Gxy, 64) != 1 || memory_isAligned(Gxz, 64) != 1 || memory_isAligned(Gyz, 64) != 1 || memory_isAligned(G, 64) != 1) { lalign = false; } if (lalign) { #pragma omp simd aligned(G, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz: 64) for (i=0; i<npts; i++) { G[LDG*i+0] = Gxx[i]; G[LDG*i+1] = Gyy[i]; G[LDG*i+2] = Gzz[i]; G[LDG*i+3] = Gxy[i]; G[LDG*i+4] = Gxz[i]; G[LDG*i+5] = Gyz[i]; } } else { #pragma omp simd for (i=0; i<npts; i++) { G[LDG*i+0] = Gxx[i]; G[LDG*i+1] = Gyy[i]; G[LDG*i+2] = Gzz[i]; G[LDG*i+3] = Gxy[i]; G[LDG*i+4] = Gxz[i]; G[LDG*i+5] = Gyz[i]; } } return 0; }
{ "alphanum_fraction": 0.4873872215, "avg_line_length": 32.9151515152, "ext": "c", "hexsha": "e0ca78a846528a7986a577caedacb4d947d0fdab", "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/magnitude.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/magnitude.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/magnitude.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3168, "size": 10862 }
#include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include "time_utility_c.h" /** INS Variables **/ /* Matrix */ gsl_matrix *WEII; gsl_matrix *TBIC; gsl_matrix *TDCI; gsl_matrix *TEIC; gsl_matrix *TBDC; gsl_matrix *TBICI; gsl_matrix *TLI; /* Vector */ gsl_vector *EVBI; gsl_vector *EVBID; gsl_vector *ESBI; gsl_vector *ESBID; gsl_vector *RICI; gsl_vector *RICID; gsl_vector *TBIC_Q; gsl_vector *TBIDC_Q; gsl_vector *SBIIC; gsl_vector *VBIIC; gsl_vector *SBEEC; gsl_vector *VBEEC; gsl_vector *WBICI; gsl_vector *EGRAVI; gsl_vector *VBECD; gsl_vector *INS_I_ATT_ERR; gsl_vector *TESTV; gsl_vector *TMP_old; gsl_vector *VBIIC_old; gsl_vector *POS_ERR; gsl_vector *GRAVGI; gsl_vector *TBDCQ; gsl_vector *VBIIC_old_old; gsl_vector *PHI_C; gsl_vector *DELTA_VEL_C; gsl_vector *PHI_LOW_C; gsl_vector *PHI_HIGH_C; /* Double */ double dbic; double dvbec; double alphacx; double betacx; double thtvdcx; double psivdcx; double alppcx; double phipcx; double loncx; double latcx; double altc; double phibdcx; double thtbdcx; double psibdcx; double ins_pos_err; double ins_vel_err; double ins_tilt_err; double ins_pose_err; double ins_vele_err; double ins_phi_err; double ins_tht_err; double ins_psi_err; /* Unsigned int */ unsigned int gpsupdate; unsigned int liftoff; unsigned int ideal; GPS_TIME gpstime; UTC_TIME utctime; /*******************/ /* Control variables */ double fmasse; double mdot; double fmass0; double xcg_0; double xcg_1; double isp; double xcg; double thrust; double mass_ratio; double reference_point; double d; double theta_a_cmd; double theta_b_cmd; double theta_c_cmd; double theta_d_cmd; double lx; // pitch double thterror; double perrori; double perrorp; double perror_old; double pitchiout_old; double pN; double pdout_old; double kpp; double kpi; double kpd; double kppp; double pitchcmd; double pitchcmd_new; double pitchcmd_old; double pitchcmd_out_old; // roll double rollerror; double rerrori; double rerrorp; double rerror_old; double rolliout_old; double rN; double rdout_old; double krp; double kri; double krd; double krpp; double rollcmd; // yaw double yawerror; double yerrori; double yerrorp; double yerror_old; double yawiout_old; double yN; double ydout_old; double kyp; double kyi; double kyd; double kypp; double yawcmd; // aoa double aoaerror; double aoaerrori; double aoaerrorp; double aoaerror_old; double aoaiout_old; double aoaN; double aoadout_old; double kaoap; double kaoai; double kaoad; double kaoapp; double aoaerror_smooth_old; double aoaerror_new; double aoaerror_out_old; double aoacmd; gsl_vector *IBBB0; gsl_vector *IBBB1; gsl_vector *IBBB2; gsl_vector *CONTROLCMD; gsl_vector *CMDQ; gsl_vector *TCMDQ; gsl_vector *delta_euler; gsl_vector *euler; gsl_vector *WBICBT; /*********************/
{ "alphanum_fraction": 0.7724358974, "avg_line_length": 14.4742268041, "ext": "c", "hexsha": "36935ff0d69971823939f70fe763ccd202a067e8", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_path": "models/gnc/src/gnc_var.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "cihuang123/Next-simulation", "max_issues_repo_path": "models/gnc/src/gnc_var.c", "max_line_length": 27, "max_stars_count": null, "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_path": "models/gnc/src/gnc_var.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 882, "size": 2808 }
#pragma once #include "text_parser.h" #include "text_renderer.h" #include "terminal_io.h" #include "geometry.h" #include <string> #include <vector> #include <gsl/span> namespace terminal_editor { enum class Color { Black = 30, Red = 31, Green = 32, Yellow = 33, Blue = 34, Magenta = 35, Cyan = 36, White = 37, Bright_Black = 90, Bright_Red = 91, Bright_Green = 92, Bright_Yellow = 93, Bright_Blue = 94, Bright_Magenta = 95, Bright_Cyan = 96, Bright_White = 97, }; enum class Style { Bold = 1, Normal = 22, }; struct Attributes { Color fgColor; Color bgColor; Style style; }; class ScreenBuffer; class ScreenCanvas { ScreenBuffer& m_screenBuffer; Point m_origin; ///< Point in screen coordinates that all drawing functions are relative to. Rect m_clipRect; ///< In screen coordinates. public: /// clipRect will be clipped to screenBuffer bounds. ScreenCanvas(ScreenBuffer& screenBuffer, Point origin, Rect clipRect); /// Sub canvas will be clipped to this canvas size. /// @param rect Sub rectangle of this canvas. Rect is relative to this canvas' origin. ScreenCanvas getSubCanvas(Rect rect); /// Clears canvas to given color. void clear(Color bgColor) { auto localRect = m_clipRect; localRect.move(-m_origin.asSize()); // In local coordinates. fill(localRect, bgColor); } /// Draw filled rectangle. void fill(Rect rect, Color bgColor); /// Draw rectangle. void fillRect(Rect rect, bool doubleEdge, bool fill, Attributes attributes); /// Draws given text on the canvas. /// Text is clipped to boundaries of the canvas. /// So only graphemes fully inside are drawn. /// @param text Input string, doesn't have to be valid or printable UTF-8. void print(Point pt, const std::string& text, Attributes normal, Attributes invalid, Attributes replacement); /// Draws given text on the canvas. /// Text is clipped to boundaries of the canvas. /// So only graphemes fully inside are drawn. /// @param graphemes Graphemes to draw. void print(Point pt, gsl::span<const Grapheme> graphemes, Attributes normal, Attributes invalid, Attributes replacement); }; class ScreenBuffer { public: struct Character { std::string text; ///< UTF-8 text to draw. If empty, then this place will be drawn by preceeding character with width > 1. int width; ///< Width of text once it will be rendered. Attributes attributes; bool operator==(const Character& other) const { if (text != other.text) return false; if (width != other.width) return false; if (attributes.fgColor != other.attributes.fgColor) return false; if (attributes.bgColor != other.attributes.bgColor) return false; if (attributes.style != other.attributes.style) return false; return true; } }; private: Size size; std::vector<Character> characters; std::vector<Character> previousCharacters; bool fullRepaintNeeded; ///< If true while screen will be repainted. Otherwise only changes from previousCharacters will be repainted. public: ScreenBuffer() : fullRepaintNeeded(true) { } ScreenCanvas getCanvas() { return ScreenCanvas(*this, Point{0, 0}, getSize()); } /// Sets fullRepaintNeeded flag. Used when contents of the screen were changed without ScreenBuffer. void setFullRepaintNeeded() { fullRepaintNeeded = true; } Size getSize() const { return size; } int getWidth() const { return size.width; } int getHeight() const { return size.height; } /// Resizes this screen buffer. void resize(int w, int h); /// Clears screen to given color. void clear(Color bgColor); /// Draws a filled rectangle with given color. /// Rectangle is first clipped to fit the scren buffer. void fillRect(Rect rect, Color bgColor); /// Draws given text on the screen. /// Throws if text is not entirely on the screen. /// @param text Input string, doesn't have to be valid or printable UTF-8. void print(int x, int y, const std::string& text, Attributes attributes); /// Draws given graphemes on the screen. /// Throws if text is not entirely on the screen. /// @param graphemes Graphemes to draw. void print(int x, int y, gsl::span<const Grapheme> graphemes, Attributes attributes); /// Draws this screen buffer to the console. void present(); }; /// Returns Grapheme that corresponds to given simpleCharacter. /// @param simpleCharacter Must be a valid UTF-8 string, that converts to a printable character of width 1. template<int N> Grapheme simpleGrapheme(const char (&simpleChar)[N]) { return { GraphemeKind::NORMAL, simpleChar, "", 1, {simpleChar, N - 1} }; } /// Draws a rectangle with borders. /// Rectangle is clipped by the clipRect. clipRect must be wholy inside screen buffer. void draw_rect(ScreenBuffer& screenBuffer, Rect clipRect, Rect rect, bool doubleEdge, bool fill, Attributes attributes); /// Measures given text on the terminal /// @param eventQueue Event queue to use for listening for the result. /// @param codePoints List of code points to measure. /// @return Length of the code points. Can be zero. int measureText(EventQueue& eventQueue, gsl::span<uint32_t> codePoints); } // namespace terminal_editor
{ "alphanum_fraction": 0.6587357955, "avg_line_length": 32, "ext": "h", "hexsha": "21ded3e9f4c51302b062287709fa21527df6d695", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_path": "text_ui/screen_buffer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "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": "Zbyl/terminal-editor", "max_issues_repo_path": "text_ui/screen_buffer.h", "max_line_length": 142, "max_stars_count": null, "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_path": "text_ui/screen_buffer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1284, "size": 5632 }
#ifndef CTETRA_INPUT_H #define CTETRA_INPUT_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> typedef void (*InputFn)(double k[3], gsl_vector *values); typedef void (*UEInputFn)(double k[3], gsl_vector *evalues, gsl_matrix_complex *evecs); #endif // CTETRA_INPUT_H
{ "alphanum_fraction": 0.761732852, "avg_line_length": 23.0833333333, "ext": "h", "hexsha": "0e87fea7af952acb15a24904329ffd2719ea36b9", "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": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "input.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "input.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "input.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 81, "size": 277 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include "atomic.h" #include "monotonic.h" #include <memcached/types.h> #include <gsl/gsl> #include <functional> #include <unordered_map> struct DocKey; namespace Collections { // The reserved name of the system owned, default collection. const char* const DefaultCollectionName = "_default"; static std::string_view DefaultCollectionIdentifier(DefaultCollectionName); const char* const DefaultScopeName = "_default"; static std::string_view DefaultScopeIdentifier(DefaultScopeName); // The SystemEvent keys are given some human readable tags to make disk or // memory dumps etc... more helpful. const char* const CollectionEventDebugTag = "_collection"; const char* const ScopeEventDebugTag = "_scope"; // Couchstore private file name for manifest data const char CouchstoreManifest[] = "_local/collections_manifest"; // Name of file where the manifest will be kept on persistent buckets const char* const ManifestFile = "collections.manifest"; static std::string_view ManifestFileName(ManifestFile); // Length of the string excluding the zero terminator (i.e. strlen) const size_t CouchstoreManifestLen = sizeof(CouchstoreManifest) - 1; using ManifestUid = WeaklyMonotonic<uint64_t>; // Struct/Map used in summary stat collecting (where we do vb accumulation) struct AccumulatedStats { AccumulatedStats& operator+=(const AccumulatedStats& other); uint64_t itemCount{0}; uint64_t diskSize{0}; uint64_t opsStore{0}; uint64_t opsDelete{0}; uint64_t opsGet{0}; }; using Summary = std::unordered_map<CollectionID, AccumulatedStats>; struct ManifestUidNetworkOrder { explicit ManifestUidNetworkOrder(ManifestUid uid) : uid(htonll(uid)) { } ManifestUid to_host() const { return ManifestUid(ntohll(uid)); } ManifestUid::value_type uid; }; static_assert(sizeof(ManifestUidNetworkOrder) == 8, "ManifestUidNetworkOrder must have fixed size of 8 bytes as " "written to disk."); /** * Return a ManifestUid from a C-string. * A valid ManifestUid is a C-string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid C-string uid * @param len a length for validation purposes * @throws std::invalid_argument if uid is invalid */ ManifestUid makeUid(const char* uid, size_t len = 16); /** * Return a ManifestUid from a std::string * A valid ManifestUid is a std::string where each character satisfies * std::isxdigit and can be converted to a ManifestUid by std::strtoull. * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline ManifestUid makeUid(const std::string& uid) { return makeUid(uid.c_str()); } /** * Return a CollectionID from a C-string. * A valid CollectionID is a C-string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul. * * @param uid C-string uid * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const char* uid) { // CollectionID is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<CollectionID>(makeUid(uid, 8)); } /** * Return a CollectionID from a std::string * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * * @param uid std::string * @throws std::invalid_argument if uid is invalid */ static inline CollectionID makeCollectionID(const std::string& uid) { return makeCollectionID(uid.c_str()); } /** * Return a ScopeID from a C-string. * A valid CollectionID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid C-string uid * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const char* uid) { // ScopeId is 8 characters max and smaller than a ManifestUid return gsl::narrow_cast<ScopeID>(makeUid(uid, 8)); } /** * Return a ScopeID from a std::string * A valid ScopeID is a std::string where each character satisfies * std::isxdigit and can be converted to a CollectionID by std::strtoul * @param uid std::string * @return std::invalid_argument if uid is invalid */ static inline ScopeID makeScopeID(const std::string& uid) { return makeScopeID(uid.c_str()); } /** * The metadata of a single collection * * Default construction yields the default collection */ struct CollectionMetaData { ScopeID sid{ScopeID::Default}; // The scope that the collection belongs to CollectionID cid{CollectionID::Default}; // The collection's ID std::string name{DefaultCollectionName}; // The collection's name cb::ExpiryLimit maxTtl{}; // The collection's maxTTL bool operator==(const CollectionMetaData& other) const { return sid == other.sid && cid == other.cid && name == other.name && maxTtl == other.maxTtl; } }; /** * The metadata of a single scope * * Default construction yields the default scope */ struct ScopeMetaData { ScopeID sid{ScopeID::Default}; // The scope's ID std::string name{DefaultScopeName}; // The scope's name bool operator==(const ScopeMetaData& other) const { return sid == other.sid && name == other.name; } }; /** * For creation of collection SystemEvents - The SystemEventFactory * glues the CollectionID into the event key (so create of x doesn't * collide with create of y). This method yields the 'keyExtra' parameter * * @param collection The value to turn into a string * @return the keyExtra parameter to be passed to SystemEventFactory */ std::string makeCollectionIdIntoString(CollectionID collection); /** * For creation of collection SystemEvents - The SystemEventFactory * glues the CollectionID into the event key (so create of x doesn't * collide with create of y). This method basically reverses * makeCollectionIdIntoString so we can get a CollectionID from a * SystemEvent key * * @param key DocKey from an Item in the System namespace and is a collection * event * @return the ID which was in the event */ CollectionID getCollectionIDFromKey(const DocKey& key); /// Same as getCollectionIDFromKey but for events changing scopes ScopeID getScopeIDFromKey(const DocKey& key); /** * Callback function for processing against dropped collections in an ephemeral * vb, returns true if the key at seqno should be dropped * * @param DocKey the key of the item we should process * @param int64_t the seqno of the item */ using IsDroppedEphemeralCb = std::function<bool(const DocKey&, int64_t)>; /** * A function for determining if a collection is visible */ using IsVisibleFunction = std::function<bool(ScopeID, std::optional<CollectionID>)>; namespace VB { enum class ManifestUpdateStatus { Success, // The new Manifest has a 'UID' that is < current. Behind, // The new Manifest has a 'UID' that is == current, but adds/drops // collections/scopes. EqualUidWithDifferences, // The new Manifest changes scopes or collections immutable properties, e.g. // current has {id:8, name:"c1"} and new has {id:8,name:"c2"}. ImmutablePropertyModified }; std::string to_string(ManifestUpdateStatus); /// values required by the flusher to calculate new collection statistics struct StatsForFlush { uint64_t itemCount; size_t diskSize; uint64_t highSeqno; }; // Following classes define the metadata that will be held by the Manager but // referenced from VB::Manifest class CollectionSharedMetaData; class CollectionSharedMetaDataView { public: CollectionSharedMetaDataView(std::string_view name, ScopeID scope, cb::ExpiryLimit maxTtl); CollectionSharedMetaDataView(const CollectionSharedMetaData&); std::string to_string() const; std::string_view name; const ScopeID scope; const cb::ExpiryLimit maxTtl; }; // The type stored by the Manager SharedMetaDataTable class CollectionSharedMetaData : public RCValue { public: CollectionSharedMetaData(std::string_view name, ScopeID scope, cb::ExpiryLimit maxTtl); CollectionSharedMetaData(const CollectionSharedMetaDataView& view); bool operator==(const CollectionSharedMetaDataView& view) const; bool operator!=(const CollectionSharedMetaDataView& view) const { return !(*this == view); } bool operator==(const CollectionSharedMetaData& meta) const; bool operator!=(const CollectionSharedMetaData& meta) const { return !(*this == meta); } const std::string name; const ScopeID scope; const cb::ExpiryLimit maxTtl; }; std::ostream& operator<<(std::ostream& os, const CollectionSharedMetaData& meta); class ScopeSharedMetaData; class ScopeSharedMetaDataView { public: ScopeSharedMetaDataView(const ScopeSharedMetaData&); ScopeSharedMetaDataView(std::string_view name) : name(name) { } std::string to_string() const; std::string_view name; }; // The type stored by the Manager SharedMetaDataTable class ScopeSharedMetaData : public RCValue { public: ScopeSharedMetaData(const ScopeSharedMetaDataView& view); bool operator==(const ScopeSharedMetaDataView& view) const; bool operator!=(const ScopeSharedMetaDataView& view) const { return !(*this == view); } bool operator==(const ScopeSharedMetaData& meta) const; bool operator!=(const ScopeSharedMetaData& meta) const { return !(*this == meta); } const std::string name; }; std::ostream& operator<<(std::ostream& os, const ScopeSharedMetaData& meta); } // namespace VB } // end namespace Collections
{ "alphanum_fraction": 0.7205825243, "avg_line_length": 33.660130719, "ext": "h", "hexsha": "9e0d59a26965f179b1b98e9ff9fd733970458566", "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": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "vpn03/kv_engine", "max_forks_repo_path": "engines/ep/src/collections/collections_types.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "vpn03/kv_engine", "max_issues_repo_path": "engines/ep/src/collections/collections_types.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "vpn03/kv_engine", "max_stars_repo_path": "engines/ep/src/collections/collections_types.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2383, "size": 10300 }
#include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <time.h> #include <string.h> int main(int argc, char * argv[]) { if (argc != 3 || strcmp(argv[1], "-h") == 0) { printf("Usage: ./gslDeterm N_MATRIX(<=1000) ITERATIONS(~1000)\n"); return 1; } srand(time(NULL)); int MAT_DIM = 6; int N_MATRIX = atoi(argv[1]); int ITERATIONS = atoi(argv[2]); int i,j,k, count; double start, end, t_time = 0.0, dummy; printf("N_MATRIX: %d, ITERATIONS: %d\n", N_MATRIX, ITERATIONS); gsl_permutation *p; gsl_matrix *m_list[N_MATRIX]; gsl_vector *x = gsl_vector_alloc (MAT_DIM); int signum; double b_data[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; gsl_vector_view b = gsl_vector_view_array (b_data, 6); // Do this ITERATIONS times, timing only the loop with the determinant // finding for (count=0; count<ITERATIONS; count++) { // Initialise a list of gsl arrays for (i=0; i<N_MATRIX; i++) m_list[i] = gsl_matrix_alloc(MAT_DIM,MAT_DIM); // Initialise values to random integers 0 -> 99 for (i=0; i<N_MATRIX; i++) for (j=0; j<MAT_DIM; j++) for (k=0; k<MAT_DIM; k++) gsl_matrix_set (m_list[i], j, k, rand()%100); p = gsl_permutation_alloc(m_list[0]->size1); //start time: find the determinant of each matrix in //m_list start = (double)clock() /(double) CLOCKS_PER_SEC; for (i=0; i<N_MATRIX; i++) { gsl_linalg_LU_decomp(m_list[i], p, &signum); gsl_linalg_LU_solve(m_list[i], p, &b.vector, x); } end = (double)clock() / (double) CLOCKS_PER_SEC; t_time += end - start; } printf("GSL: %d matrices, %d iterations, cpu time: %fs\n", N_MATRIX, ITERATIONS, t_time); gsl_permutation_free(p); for (i=0; i<N_MATRIX; i++) gsl_matrix_free(m_list[i]); gsl_vector_free (x); return 0; }
{ "alphanum_fraction": 0.6132478632, "avg_line_length": 26, "ext": "c", "hexsha": "356a6b79323a2fed3f9debf1089df3d180d726b2", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z", "max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_path": "benchmarks/matrix_library_tests/gslLinEq.c", "max_issues_count": 13, "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_path": "benchmarks/matrix_library_tests/gslLinEq.c", "max_line_length": 72, "max_stars_count": 4, "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_path": "benchmarks/matrix_library_tests/gslLinEq.c", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z", "max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z", "num_tokens": 615, "size": 1872 }
#pragma once #include <gsl.h> #include "TMP_Helper.h" #include "HE_Assert.h" #include "HE_Math.h" #include <type_traits> namespace HE { struct MemoryBlock { void* ptr; size_t length; void* begin() const { return ptr; } void* end() const { return static_cast<char*>(ptr) + length; } }; using Blk = MemoryBlock; // Max alignment constexpr size_t PlatformMaxAlignment = Math::Max(alignof(void*), alignof(size_t)); static_assert(Math::IsPow2(PlatformMaxAlignment), "PlatformMaxAlignment is not a power of 2, as should be"); namespace Private { template<class T> using try_allocate = std::enable_if_t<std::is_same<Blk, decltype(std::declval<T>().allocate(std::declval<size_t>()))>::value>; // Custom aligned allocation's alignment parameter generally has to be a power of 2 and bigger than the allocator's default alignment, // in order to respect the allocator's semantics template<class T> using try_aligned_allocate = std::enable_if_t<std::is_same<Blk, decltype(std::declval<T>().allocate(std::declval<size_t>(), std::declval<size_t>()))>::value>; template<class T> using try_deallocate = decltype(std::declval<T>().deallocate(std::declval<Blk>())); template<class T> using try_deallocateAll = decltype(std::declval<T>().deallocateAll()); template<class T> using try_owns = std::enable_if_t<std::is_same<bool, decltype(std::declval<T>().owns(std::declval<Blk>()))>::value>; template<class T> using try_it = std::enable_if_t<std::is_same<T, decltype(T::it)>::value>; } // Allocator // Must have (for allocator of type T): // - MemoryBlock T::allocate(size_t) // - void T::deallocate(MemoryBlock) noexcept template<class T> using is_allocator = and_ < has_op<T, Private::try_allocate>, has_op<T, Private::try_deallocate> > ; template<class... T> constexpr bool IsAllocator() { return and_<is_allocator<T>...>::value; } // StatelessAllocator // - Allocator // - StateSize<T>::value == 0 // - is_same<decltype(T::it), T> template<class T> using is_stateless_allocator = and_<is_allocator<T>, equal_<StateSize<T>, std::integral_constant<size_t, 0>>>; template<class... T> constexpr bool IsStatelessAllocator() { return and_<is_stateless_allocator<T>...>::value; } // OwningAllocator // Must have (for allocator of type T) // - HE::is_allocator<T>() // - bool T::owns(MemoryBlock) template<class T> using is_owning_allocator = and_<is_allocator<T>, has_op<T, Private::try_owns>>; template<class... T> constexpr bool IsOwningAllocator() { return and_<is_owning_allocator<T>...>::value; } // AlignedAllocator // Must have (for allocator of type T) // - HE::is_allocator<T>() // - bool T::allocate(size_t, size_t) template<class T> using is_aligned_allocator = and_<is_allocator<T>, has_op<T, Private::try_aligned_allocate>>; template<class... T> constexpr bool IsAlignedAllocator() { return and_<is_aligned_allocator<T>...>::value; } // Generic allocator functions template< class Type, class Allocator, class Enable = std::enable_if_t<is_allocator<Allocator>::value>> Blk allocate(Allocator&& a) { return a.allocate(sizeof(Type)); } template<class Type, class Allocator, class Enable = std::enable_if_t<is_allocator<Allocator>::value>> Blk allocate(Allocator&& a, size_t count) { return a.allocate(count*sizeof(Type), alignof(Type)); } class NullAllocator { public: static constexpr size_t alignment = 64 * 1024; static NullAllocator it; Blk allocate(size_t); Blk allocate(size_t, size_t); void deallocate(Blk) noexcept; void deallocateAll() noexcept; bool owns(Blk); }; // Returns the beginning of the buffer is the buffer is big enough, even if it // was already allocated. This is because the allocator does no tracking. The client // is responsible for making sure memory doesn't get corrupted // Probably shouldn't be used as the main allocator of the Fallback allocator, but pairs // well with Segregator template<size_t N> class alignas(PlatformMaxAlignment) LightInlineAllocator { public: static constexpr size_t alignment = PlatformMaxAlignment; Blk allocate(size_t n) { if (n <= N) { return{ m_buffer, n }; } else { return{ nullptr, 0 }; } } Blk allocate(size_t n, size_t a) { EXPECTS(Math::IsPow2(alignment) && a >= alignment); auto const p = reinterpret_cast<char*>(Math::RoundUpToMultipleOf(reinterpret_cast<size_t>(&m_buffer[0]), a)); Blk const b{ p, n }; if (b.end() <= m_buffer + N) { return b; } else { return{ nullptr, 0 }; } } bool owns(Blk b) { return b.begin() >= m_buffer && b.end() <= m_buffer + N; } void deallocate(Blk) noexcept {} private: char m_buffer[N]; }; class MallocAllocator { public: static constexpr size_t alignment = PlatformMaxAlignment; static MallocAllocator it; Blk allocate(size_t n); void deallocate(Blk) noexcept; }; class AlignedMallocAllocator { public: static constexpr size_t alignment = PlatformMaxAlignment; static AlignedMallocAllocator it; Blk allocate(size_t n); Blk allocate(size_t n, size_t alignment); void deallocate(Blk) noexcept; }; template< class Primary, class Fallback > class FallbackAllocator; namespace Private { template < class Primary, class Fallback, class Enable = void> struct FallbackAllocatorImpl { }; template< class Primary, class Fallback > using FallbackStatelessCond = std::enable_if_t< and_< equal_<StateSize<Primary>, std::integral_constant<size_t, 0>>, equal_<StateSize<Fallback>, std::integral_constant<size_t, 0>> >::value >; template < class Primary, class Fallback > struct FallbackAllocatorImpl<Primary, Fallback, FallbackStatelessCond<Primary, Fallback> > { static FallbackAllocator<Primary, Fallback> it; }; } template< class Primary, class Fallback > class FallbackAllocator : private Primary, private Fallback, private Private::FallbackAllocatorImpl<Primary, Fallback> { protected: using P = Primary; using F = Fallback; static_assert(IsOwningAllocator<P>(), "Primary allocator does not meet the HE::OwningAllocator concept"); static_assert(IsAllocator<F>(), "Fallback allocator does not meet the HE::Allocator concept"); public: static constexpr size_t alignment = Math::Min(Primary::alignment, Fallback::alignment); Blk allocate(size_t n) { auto const blk = P::allocate(n); if (!blk.ptr) return F::allocate(n); return blk; } template<class Enable = std::enable_if_t<and_<is_aligned_allocator<Primary>, is_aligned_allocator<Fallback>>::value>> Blk allocate(size_t n, size_t alignment) { auto const blk = P::allocate(n, alignment); if (!blk.ptr) return F::allocate(n, alignment); return blk; } void deallocate(Blk b) noexcept { if (P::owns(b)) P::deallocate(b); else F::deallocate(b); } template<class Enable = std::enable_if_t<and_<has_op<Primary, Private::try_deallocateAll>, has_op<Fallback, Private::try_deallocateAll>>::value>> void deallocateAll() noexcept { Primary::deallocateAll(); Fallback::deallocateAll(); } template<class Enable = std::enable_if_t<is_owning_allocator<Fallback>::value>> bool owns(Blk b) { return Primary::owns(b) || Fallback::owns(b); } }; template< class Primary, class Fallback > FallbackAllocator<Primary, Fallback> Private::FallbackAllocatorImpl<Primary, Fallback, Private::FallbackStatelessCond<Primary, Fallback>>::it; namespace Allocator { constexpr size_t unbounded = static_cast<size_t>(-1); } // An allocator that allocates nodes on a Parent allocator and internally keeps blocks // of memory on deallocation instead of actually deallocating them, but only // if they have a certain size // Important: Actual deallocations to the parent allocator are not guaranteed to be ordered as // deallocated in the Freelist allocator, and therefore should not be used with allocators // that require ordered deallocations, such as StackAllocator // minSize: Minimum size of the allocation to be considered in range // maxSize: Maxsimum size of the allocation to be considered in range // batchCount: Number of allocations on a fresh "in range" allocation. Basically fills up the Freelist with batchCount nodes on allocation // maxNodes: Max number of nodes the freelist can keep template< class Parent, size_t MinSize, size_t MaxSize = MinSize, size_t MaxNodes = Allocator::unbounded, class Enable = std::enable_if_t<is_allocator<Parent>::value> > class FreelistAllocator : private Parent { static_assert(MaxSize >= MinSize, "FreelistAllocator's MaxSize should be higher or equal to MinSize"); static_assert(MaxSize >= sizeof(void*), "FreelistAllocator's MaxSize and MinSize should be higher or equal than sizeof(void*)"); public: static constexpr size_t alignment = Parent::alignment; Blk allocate(size_t n) { return allocateImpl(n); } template<class Enable = std::enable_if_t<is_aligned_allocator<Parent>::value>> Blk allocate(size_t n, size_t alignment) { return allocateImpl(n, alignment); } void deallocate(Blk b) noexcept { if ((MaxNodes == Allocator::unbounded || m_nNodesCount != MaxNodes) && inRange(b.length)) { auto const next = m_pFreelistRoot; m_pFreelistRoot = static_cast<Node*>(b.ptr); m_pFreelistRoot->next = next; ++m_nNodesCount; } else { Parent::deallocate(b); } } // Only O(1) if the Parent allocator supports deallocateAll // If the Freelist is unbounded and the Parent doesn't support deallocateAll, // the Freelist will do a best effort of deallocating all the nodes in its freelist // in O(n) void deallocateAll() noexcept { deallocateAllImpl(); } static constexpr bool has_fast_deallocateAll() { return has_op<Parent, Private::try_deallocateAll>::value; } bool owns(Blk b) { return Parent::owns(b); } private: struct Node { Node* next; }; Node* m_pFreelistRoot{ nullptr }; size_t m_nNodesCount{ 0 }; bool inRange(size_t n) const { if (MinSize == MaxSize) return n == MaxSize; return (MinSize == 0 || n >= MinSize) && n <= MaxSize; } template<class... Args> Blk allocateImpl(size_t n, Args... args) { if (!inRange(n)) return Parent::allocate(n, args...); if (!m_pFreelistRoot) { auto const b = Parent::allocate(MaxSize, args...); return{ b.ptr, n }; } else { Blk const result{ static_cast<void*>(m_pFreelistRoot), n }; m_pFreelistRoot = m_pFreelistRoot->next; --m_nNodesCount; return result; } } void deallocateAllImpl(std::enable_if_t<has_op<Parent, Private::try_deallocateAll>::value>* = nullptr) noexcept { Parent::deallocateAll(); m_pFreelistRoot = nullptr; } // In this case, we can only guarantee a complete deallocation if the freelist is unbounded void deallocateAllImpl(std::enable_if_t< and_< not_<has_op<Parent, Private::try_deallocateAll>>, has_op<Parent, Private::try_deallocate>, equal_<std::integral_constant<size_t, MaxNodes>, std::integral_constant<size_t, Allocator::unbounded>> >::value>* = nullptr) noexcept { auto next = m_pFreelistRoot; while (next) { Blk const b{ static_cast<void*>(next), MaxSize }; next = next->next; Parent::deallocate(b); } m_pFreelistRoot = nullptr; } }; template<class Parent, class PrefixType, class SuffixType> class AffixAllocator; namespace Private { template < class Parent, class PrefixType, class SuffixType, class Enable = void> struct AffixParentImpl : protected Parent { }; template < class Parent, class PrefixType, class SuffixType> struct AffixParentImpl<Parent, PrefixType, SuffixType, std::enable_if_t<StateSize<Parent>::value == 0>> : protected Parent { static AffixAllocator<Parent, PrefixType, SuffixType> it; }; template<class PrefixType> struct PrefixImpl { template<class Enable = std::enable_if_t<StateSize<PrefixType>::value != 0>> static PrefixType& Prefix(Blk& b) { return reinterpret_cast<PrefixType*>(b.ptr)[-1]; } }; template<> struct PrefixImpl<void>{}; template<class PrefixType, class SuffixType> struct SuffixImpl { template<class Enable = std::enable_if_t<StateSize<SuffixType>::value != 0>> static SuffixType& Suffix(Blk& b) { auto const p = static_cast<char*>(b.ptr) + b.length; return *reinterpret_cast<SuffixType*>(p); } protected: static size_t totalAllocationSize(size_t s) { if (StateSize<SuffixType>::value == 0) { return s + StateSize<PrefixType>::value; } else { return Math::RoundUpToMultipleOf(s + StateSize<PrefixType>::value, alignof(SuffixType)) + StateSize<SuffixType>::value; } } }; template<class PrefixType> struct SuffixImpl<PrefixType, void> { protected: static size_t totalAllocationSize(size_t s) { return s + StateSize<PrefixType>::value; } }; } template<class Parent, class PrefixType, class SuffixType = void> class AffixAllocator : public Private::AffixParentImpl<Parent, PrefixType, SuffixType>, public Private::PrefixImpl<PrefixType>, public Private::SuffixImpl<PrefixType, SuffixType> { public: static constexpr size_t alignment = StateSize<PrefixType>::value ? alignof(PrefixType) : Parent::alignment; Blk allocate(size_t n) { auto const result = Parent::allocate(totalAllocationSize(n)); if (!result.ptr) return result; return{ static_cast<char*>(result.ptr) + StateSize<PrefixType>::value, n }; } bool owns(Blk b) { return Parent::owns(actualAllocation(b)); } void deallocate(Blk b) { Parent::deallocate(actualAllocation(b)); } private: // Takes a requested allocation, and returns the actual allocation that was request to the parent static Blk actualAllocation(Blk b) { if (!b.ptr) return{ nullptr, 0 }; return{ static_cast<char*>(b.ptr) - StateSize<PrefixType>::value, totalAllocationSize(b.length) }; } }; template<class Parent, class PrefixType, class SuffixType> AffixAllocator<Parent, PrefixType, SuffixType> Private::AffixParentImpl<Parent, PrefixType, SuffixType, std::enable_if_t<StateSize<Parent>::value == 0>>::it; template < size_t Threshold, class SmallAllocator, class LargeAllocator > class SegregateAllocator; namespace Private { template < size_t Threshold, class SmallAllocator, class LargeAllocator, class Enable = void> struct SegregateAllocatorImpl { }; template< class SmallAllocator, class LargeAllocator > using SegregateAllocatorStatelessCond = std::enable_if_t< and_< equal_<StateSize<SmallAllocator>, std::integral_constant<size_t, 0>>, equal_<StateSize<LargeAllocator>, std::integral_constant<size_t, 0>> >::value >; template < size_t Threshold, class SmallAllocator, class LargeAllocator > struct SegregateAllocatorImpl<Threshold, SmallAllocator, LargeAllocator, SegregateAllocatorStatelessCond<SmallAllocator, LargeAllocator> > { static SegregateAllocator<Threshold, SmallAllocator, LargeAllocator> it; }; } // Seggregator template<size_t Threshold, class SmallAllocator, class LargeAllocator > class SegregateAllocator : private SmallAllocator, private LargeAllocator { public: constexpr static size_t alignment = Math::Min(SmallAllocator::alignment, LargeAllocator::alignment); Blk allocate(size_t n) { return allocate_Impl(n); } Blk allocate(size_t n, size_t alignment_requirement) { EXPECTS(alignment_requirement >= alignment && Math::IsPow2(alignment_requirement)); return allocate_Impl(n, alignment_requirement); } bool owns(Blk b) { return n <= Threshold ? SmallAllocator::owns(b) : LargeAllocator::owns(b); } void deallocate(Blk b) { return n <= Threshold ? SmallAllocator::deallocate(b) : LargeAllocator::deallocate(b); } void deallocateAll() { SmallAllocator::deallocateAll(); LargeAllocator::deallocateAll(); } private: template<class... Args> Blk allocate_Impl(size_t n, Args... args) { return n <= Threshold ? SmallAllocator::allocate(n, args...) : LargeAllocator::allocate(n, args...); } }; template < size_t Threshold, class SmallAllocator, class LargeAllocator > SegregateAllocator<Threshold, SmallAllocator, LargeAllocator> Private::SegregateAllocatorImpl<Threshold, SmallAllocator, LargeAllocator, Private::SegregateAllocatorStatelessCond<SmallAllocator, LargeAllocator>>::it; }
{ "alphanum_fraction": 0.7125075896, "avg_line_length": 28.2989690722, "ext": "h", "hexsha": "e74ac1243123080de72845b6ccff2b976ed9c38e", "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": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "KABoissonneault/Hazel_Engine", "max_forks_repo_path": "src/Source/SDK/HE_Allocator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "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": "KABoissonneault/Hazel_Engine", "max_issues_repo_path": "src/Source/SDK/HE_Allocator.h", "max_line_length": 216, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5ab97f6ccbc2c77bd92dd9dc84f2f64670e586d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "KABoissonneault/Hazel_Engine", "max_stars_repo_path": "src/Source/SDK/HE_Allocator.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4457, "size": 16470 }
// // Created by Huy Vo on 2019-06-29. // #ifndef PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_ #define PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_ #include <petsc.h> #include <iostream> #include "Sys.h" namespace pacmensl { template<typename PetscT> class Petsc { protected: PetscT dat = nullptr; int Destroy(PetscT *obj); public: Petsc() { static_assert(std::is_convertible<PetscT, Vec>::value || std::is_convertible<PetscT, Mat>::value || std::is_convertible<PetscT, IS>::value || std::is_convertible<PetscT, VecScatter>::value || std::is_convertible<PetscT, KSP>::value || std::is_convertible<PetscT, TS>::value, "pacmensl::Petsc can only wrap PETSc objects."); } PetscT *mem() { return &dat; } const PetscT *mem() const { return &dat; } bool IsEmpty() { return (dat == nullptr); } operator PetscT() { return dat; } ~Petsc() { Destroy(&dat); } }; template<> int Petsc<Vec>::Destroy(Vec *obj); template<> int Petsc<Mat>::Destroy(Mat *obj); template<> int Petsc<IS>::Destroy(IS *obj); template<> int Petsc<VecScatter>::Destroy(VecScatter *obj); template<> int Petsc<KSP>::Destroy(KSP *obj); template<> int Petsc<TS>::Destroy(TS *obj); PacmenslErrorCode ExpandVec(Petsc<Vec> &p, const std::vector<PetscInt> &new_indices, const PetscInt new_local_size); PacmenslErrorCode ExpandVec(Vec &p, const std::vector<PetscInt> &new_indices, const PetscInt new_local_size); } #endif //PACMENSL_SRC_PETSCWRAP_PETSCWRAP_H_
{ "alphanum_fraction": 0.6837549933, "avg_line_length": 23.8412698413, "ext": "h", "hexsha": "7299fc51d38e1e470d968ae1df82f346357e1e77", "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": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "voduchuy/pacmensl", "max_forks_repo_path": "src/PetscWrap/PetscWrap.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "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": "voduchuy/pacmensl", "max_issues_repo_path": "src/PetscWrap/PetscWrap.h", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "d35adb165caef5c8fa992be6fda16e1bfb1dfd4a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "voduchuy/pacmensl", "max_stars_repo_path": "src/PetscWrap/PetscWrap.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 443, "size": 1502 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_results_Filter_h_ #define SQ_INCLUDE_GUARD_results_Filter_h_ #include "core/Field.h" #include "core/typeutil.h" #include "parser/FilterSpec.h" #include <gsl/gsl> #include <memory> namespace sq::results { struct Filter; using FilterPtr = std::unique_ptr<Filter>; struct Filter { /** * Create a Filter for the given spec. */ SQ_ND static FilterPtr create(const parser::FilterSpec &spec); /** * Apply this filter to a Result. */ SQ_ND virtual Result operator()(Result &&result) const = 0; virtual ~Filter() = default; Filter() = default; Filter(const Filter &) = delete; Filter(Filter &&) = delete; Filter &operator=(const Filter &) = delete; Filter &operator=(Filter &&) = delete; }; } // namespace sq::results #endif // SQ_INCLUDE_GUARD_results_Filter_h_
{ "alphanum_fraction": 0.5982824427, "avg_line_length": 24.3720930233, "ext": "h", "hexsha": "1bc82ce14f43ba0eb99087560c7b0bc8b98af82e", "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/results/include/results/Filter.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/results/include/results/Filter.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/results/include/results/Filter.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": 225, "size": 1048 }
/** \file oposim_fns.c \brief Funciones auxiliares */ #include <stdio.h> #include <gsl/gsl_rng.h> #include <time.h> #include <stdlib.h> #include "oposim.h" static gsl_rng *r = NULL; /**< \a r es el generador de números aleatorios */ /** \fn void random_init(char opc) \brief Inicializador del generador de números aleatorios. \param opc a character. */ void random_init(char opc) { if (!r) { switch(opc) { case 'm': r = gsl_rng_alloc(gsl_rng_mt19937); break; case 't': r = gsl_rng_alloc(gsl_rng_taus); break; case 'g': r = gsl_rng_alloc(gsl_rng_gfsr4); break; case 'x': r = gsl_rng_alloc(gsl_rng_ranlxs0); break; default: r = gsl_rng_alloc(gsl_rng_mrg); } printf("Usando RNG %s\n", gsl_rng_name(r)); gsl_rng_set(r, time(NULL)); } } /** \fn void random_free() \brief Destructor del generador de números aleatorios */ void random_free() { if (!r) { gsl_rng_free(r); } } /** \fn int s_experimento(int temas, int bolas, int estudiados) \brief Realiza una simulación. \param temas Número de temas en la oposición. \param bolas Número de bolas que se extraen. \param estudiados Número de temas estudiados. \return Número temas estudiados que estarían entre los extraídos. */ int s_experimento(int temas, int bolas, int estudiados) { //printf("bolas extraidas: "); int b_extraidas[bolas]; int bola; for (int i = 0; i < bolas; i++) { do { bola = (int) gsl_rng_uniform_int(r, temas) + 1; for (int j = 0; j < i; j++) { if (b_extraidas[j] == bola) { bola = 0; break; } } } while (!bola); //printf("%d ", bola); b_extraidas[i] = bola; } int res = 0; for (int i = 0; i < bolas; i++) { if(b_extraidas[i] <= estudiados) res++; } //printf("\n"); return res; } /** \fn int *experimento(int temas, int bolas, int estudiados, int reps) \brief Realiza varias simulaciones y devuelve los resultados. \param temas Número de temas en la oposición. \param bolas Número de bolas que se extraen. \param estudiados Número de temas estudiados. \param reps Número de veces que se realizará el experimento. \return Histograma con las veces que el número de temas estudiados estaba entre las bolas extraídas. */ int *experimento(int temas, int bolas, int estudiados, int reps) { int *res = (int *)calloc(bolas + 1, sizeof(int)); for (int i = 0; i < reps; i++) res[s_experimento(temas, bolas, estudiados)]++; return res; } /** \fn double *frecs(int *histograma, int l) \brief Calcula las frecuencias relativas. \param histograma array de frecuencias absolutas \param l longitud del histograma \return array con las frecuencias relativas */ double *frecs(int *histograma, int l) { double suma = 0; for (int i = 0; i < l; i++) suma += histograma[i]; double *res = (double *)calloc(l, sizeof(double)); for (int i = 0; i < l; i++) res[i] = histograma[i] / suma; return res; }
{ "alphanum_fraction": 0.6478114478, "avg_line_length": 22, "ext": "c", "hexsha": "c5b402a378b43be0367aaa228986153d037d2911", "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": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonatanlv/oposim", "max_forks_repo_path": "oposim_fns.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "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": "jonatanlv/oposim", "max_issues_repo_path": "oposim_fns.c", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonatanlv/oposim", "max_stars_repo_path": "oposim_fns.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 895, "size": 2970 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include "ccl.h" //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 ccl_f1d_t *ccl_f1d_t_new(int n,double *x,double *y,double y0,double yf, ccl_f1d_extrap_t extrap_lo_type, ccl_f1d_extrap_t extrap_hi_type, int *status) { ccl_f1d_t *spl=malloc(sizeof(ccl_f1d_t)); if(spl==NULL) { *status = CCL_ERROR_MEMORY; return NULL; } spl->spline=gsl_spline_alloc(gsl_interp_akima,n); if (spl->spline == NULL) { *status = CCL_ERROR_MEMORY; free(spl); return NULL; } int parstatus=gsl_spline_init(spl->spline,x,y,n); if(parstatus) { *status = CCL_ERROR_SPLINE; gsl_spline_free(spl->spline); free(spl); return NULL; } if(*status==0) { spl->y0=y0; spl->yf=yf; spl->x_ini=x[0]; spl->x_end=x[n-1]; spl->y_ini=y[0]; spl->y_end=y[n-1]; spl->extrap_lo_type=extrap_lo_type; spl->extrap_hi_type=extrap_hi_type; } // Compute derivatives // Low-end if(spl->extrap_lo_type == ccl_f1d_extrap_const) { spl->der_lo = 0; } else if(spl->extrap_lo_type == ccl_f1d_extrap_linx_liny) { spl->der_lo = (y[1]-y[0])/(x[1]-x[0]); } else if(spl->extrap_lo_type == ccl_f1d_extrap_linx_logy) { if(y[1]*y[0]<=0) *status = CCL_ERROR_SPLINE; else spl->der_lo = log(y[1]/y[0])/(x[1]-x[0]); } else if(spl->extrap_lo_type == ccl_f1d_extrap_logx_liny) { if(x[1]*x[0]<=0) *status = CCL_ERROR_SPLINE; else spl->der_lo = (y[1]-y[0])/log(x[1]/x[0]); } else if(spl->extrap_lo_type == ccl_f1d_extrap_logx_logy) { if((y[1]*y[0]<=0) || (x[1]*x[0]<=0)) *status = CCL_ERROR_SPLINE; else spl->der_lo = log(y[1]/y[0])/log(x[1]/x[0]); } else // No extrapolation spl->der_lo = 0; // High-end if(spl->extrap_hi_type == ccl_f1d_extrap_const) { spl->der_hi = 0; } else if(spl->extrap_hi_type == ccl_f1d_extrap_linx_liny) { spl->der_hi = (y[n-1]-y[n-2])/(x[n-1]-x[n-2]); } else if(spl->extrap_hi_type == ccl_f1d_extrap_linx_logy) { if(y[n-1]*y[n-2]<=0) *status = CCL_ERROR_SPLINE; else spl->der_hi = log(y[n-1]/y[n-2])/(x[n-1]-x[n-2]); } else if(spl->extrap_hi_type == ccl_f1d_extrap_logx_liny) { if(x[n-1]*x[n-2]<=0) *status = CCL_ERROR_SPLINE; else spl->der_hi = (y[n-1]-y[n-2])/log(x[n-1]/x[n-2]); } else if(spl->extrap_hi_type == ccl_f1d_extrap_logx_logy) { if((y[n-1]*y[n-2]<=0) || (x[n-1]*x[n-2]<=0)) *status = CCL_ERROR_SPLINE; else spl->der_hi = log(y[n-1]/y[n-2])/log(x[n-1]/x[n-2]); } else // No extrapolation spl->der_hi = 0; // If one of the derivatives could not be calculated // then return NULL. if (*status){ ccl_f1d_t_free(spl); spl = NULL; } return spl; } //Evaluates spline at x checking for bound errors double ccl_f1d_t_eval(ccl_f1d_t *spl,double x) { // Extrapolation // Lin_x, lin_y // f(x) = f_n + (x-x_n) * der // der = (f_n - f_{n-1}) / (x_n - x_{n-1}) // // Log_x, lin_y // f(x) = f_n + log(x/x_n) * der // der = (f_n - f_{n-1}) / log(x_n/x_{n-1}) // Lin_x, log_y // f(x) = f_n * exp[ (x - x_n) * der ] // der = log(f_n/f_{n-1})/(x_n-x_{n-1}) // Log_x, log_y // f(x) = f_n * exp[ log(x/x_n) * der ] // der = log(f_n/f_{n-1})/log(x_n/x_{n-1}) if(x<=spl->x_ini) { if(spl->extrap_lo_type==ccl_f1d_extrap_const) return spl->y0; else if(spl->extrap_lo_type==ccl_f1d_extrap_linx_liny) { return spl->y_ini + spl->der_lo * (x - spl->x_ini); } else if(spl->extrap_lo_type==ccl_f1d_extrap_logx_liny) { return spl->y_ini + spl->der_lo * log(x/spl->x_ini); } else if(spl->extrap_lo_type==ccl_f1d_extrap_linx_logy) { return spl->y_ini * exp(spl->der_lo * (x - spl->x_ini)); } else if(spl->extrap_lo_type==ccl_f1d_extrap_logx_logy) { return spl->y_ini * pow(x/spl->x_ini, spl->der_lo); } else { ccl_raise_gsl_warning(CCL_ERROR_SPLINE_EV, "ccl_f1d.c: ccl_f1d_t_eval(): " "x-value below range."); return NAN; } } else if(x>=spl->x_end) { if(spl->extrap_hi_type==ccl_f1d_extrap_const) return spl->yf; else if(spl->extrap_hi_type==ccl_f1d_extrap_linx_liny) { return spl->y_end + spl->der_hi * (x - spl->x_end); } else if(spl->extrap_hi_type==ccl_f1d_extrap_logx_liny) { return spl->y_end + spl->der_hi * log(x/spl->x_end); } else if(spl->extrap_hi_type==ccl_f1d_extrap_linx_logy) { return spl->y_end * exp(spl->der_hi * (x - spl->x_end)); } else if(spl->extrap_hi_type==ccl_f1d_extrap_logx_logy) { return spl->y_end * pow(x/spl->x_end, spl->der_hi); } else { ccl_raise_gsl_warning(CCL_ERROR_SPLINE_EV, "ccl_f1d.c: ccl_f1d_t_eval(): " "x-value above range."); return NAN; } } else { double y; int stat=gsl_spline_eval_e(spl->spline,x,NULL,&y); if (stat!=GSL_SUCCESS) { ccl_raise_gsl_warning(stat, "ccl_f1d.c: ccl_f1d_t_eval(): " "x-value outside range."); return NAN; } return y; } } //Spline destructor void ccl_f1d_t_free(ccl_f1d_t *spl) { if (spl != NULL) { gsl_spline_free(spl->spline); } free(spl); }
{ "alphanum_fraction": 0.5880088009, "avg_line_length": 27.1343283582, "ext": "c", "hexsha": "96697cbbaf312e3d387cc7caed458c65b8574e58", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "src/ccl_f1d.c", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "src/ccl_f1d.c", "max_line_length": 71, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "src/ccl_f1d.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 2059, "size": 5454 }
/* gsl_histogram2d_calloc_range.c * Copyright (C) 2000 Simone Piccardi * * This library 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 library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*************************************************************** * * File gsl_histogram2d_calloc_range.c: * Routine to create a variable binning 2D histogram providing * the input range vectors. Need GSL library and header. * Do range check and allocate the histogram data. * * Author: S. Piccardi * Jan. 2000 * ***************************************************************/ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram2d.h> /* * Routine that create a 2D histogram using the given * values for X and Y ranges */ gsl_histogram2d * gsl_histogram2d_calloc_range (size_t nx, size_t ny, double *xrange, double *yrange) { size_t i, j; gsl_histogram2d *h; /* check arguments */ if (nx == 0) { GSL_ERROR_VAL ("histogram length nx must be positive integer", GSL_EDOM, 0); } if (ny == 0) { GSL_ERROR_VAL ("histogram length ny must be positive integer", GSL_EDOM, 0); } /* init ranges */ for (i = 0; i < nx; i++) { if (xrange[i] >= xrange[i + 1]) { GSL_ERROR_VAL ("histogram xrange not in increasing order", GSL_EDOM, 0); } } for (j = 0; j < ny; j++) { if (yrange[j] >= yrange[j + 1]) { GSL_ERROR_VAL ("histogram yrange not in increasing order" ,GSL_EDOM, 0); } } /* Allocate histogram */ h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d)); if (h == 0) { GSL_ERROR_VAL ("failed to allocate space for histogram struct", GSL_ENOMEM, 0); } h->xrange = (double *) malloc ((nx + 1) * sizeof (double)); if (h->xrange == 0) { /* exception in constructor, avoid memory leak */ free (h); GSL_ERROR_VAL ("failed to allocate space for histogram xrange", GSL_ENOMEM, 0); } h->yrange = (double *) malloc ((ny + 1) * sizeof (double)); if (h->yrange == 0) { /* exception in constructor, avoid memory leak */ free (h); GSL_ERROR_VAL ("failed to allocate space for histogram yrange", GSL_ENOMEM, 0); } h->bin = (double *) malloc (nx * ny * sizeof (double)); if (h->bin == 0) { /* exception in constructor, avoid memory leak */ free (h->xrange); free (h->yrange); free (h); GSL_ERROR_VAL ("failed to allocate space for histogram bins", GSL_ENOMEM, 0); } /* init histogram */ /* init ranges */ for (i = 0; i <= nx; i++) { h->xrange[i] = xrange[i]; } for (j = 0; j <= ny; j++) { h->yrange[j] = yrange[j]; } /* clear contents */ for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { h->bin[i * ny + j] = 0; } } h->nx = nx; h->ny = ny; return h; }
{ "alphanum_fraction": 0.5430672269, "avg_line_length": 24.8888888889, "ext": "c", "hexsha": "6f14d8784e84ff2b4b8ee36e7a1410ea10df3118", "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/histogram/calloc_range2d.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range2d.c", "max_line_length": 74, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/histogram/calloc_range2d.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": 989, "size": 3808 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv2.h> int func (double t, const double y[], double f[], void *params) { double mu = *(double *)params; f[0] = y[1]; f[1] = -y[0] - mu*y[1]*(y[0]*y[0] - 1); return GSL_SUCCESS; } int jac (double t, const double y[], double *dfdy, double dfdt[], void *params) { double mu = *(double *)params; gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2); gsl_matrix * m = &dfdy_mat.matrix; gsl_matrix_set (m, 0, 0, 0.0); gsl_matrix_set (m, 0, 1, 1.0); gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0); gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0)); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } int main (void) { double mu = 10; gsl_odeiv2_system sys = {func, jac, 2, &mu}; gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rk8pd, 1e-6, 1e-6, 0.0); int i; double t = 0.0, t1 = 100.0; double y[2] = { 1.0, 0.0 }; for (i = 1; i <= 100; i++) { double ti = i * t1 / 100.0; int status = gsl_odeiv2_driver_apply (d, &t, ti, y); if (status != GSL_SUCCESS) { printf ("error, return value=%d\n", status); break; } printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); } gsl_odeiv2_driver_free (d); return 0; }
{ "alphanum_fraction": 0.5710037175, "avg_line_length": 21.3492063492, "ext": "c", "hexsha": "5a336515d2a2bc905590c020c56bf663668944d1", "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": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "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": "ruslankuzmin/julia", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.c", "max_line_length": 63, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/ode-initval.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": 560, "size": 1345 }