Search is not available for this dataset
text
string
meta
dict
// // ger.h // Linear Algebra Template Library // // Created by Rodney James on 12/23/11. // Copyright (c) 2011 University of Colorado Denver. All rights reserved. // #ifndef _ger_h #define _ger_h /// @file ger.h Performs vector outer product. #include "latl.h" namespace LATL { /// @brief Performs a vector outer product of two real vectors. /// /// For a real matrix A, real vectors x and y, and real scalar alpha, /// /// A := alpha * x * y' + A /// /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param m Specifies the number of rows of the matrix A. m>=0 /// @param n Specifies the number of coumns of the matrix A. n>=0 /// @param alpha Real scalar. /// @param x Pointer to real vector x. /// @param incx Increment of the vector x. x!=0 /// @param y Pointer to real vector y. /// @param incy Increment of the vector y. y!=0 /// @param A Pointer to real m-by-n matrix A. /// @param ldA Column length of matrix A. ldA>=m. /// @ingroup BLAS template <typename real_t> int GER(int_t m, int_t n, real_t alpha, real_t *x, int_t incx, real_t *y, int_t incy, real_t *A, int_t ldA) { const real_t zero(0.0); int_t i,j,kx,jy,ix; if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; else if((m==0)||(n==0)||(alpha==zero)) return 0; jy=(incy>0)?0:(1-n)*incy; kx=(incx>0)?0:(1-m)*incx; if(incx==1) { for(j=0;j<n;j++) { for(i=0;i<m;i++) A[i]+=x[i]*alpha*y[jy]; jy+=incy; A+=ldA; } } else { for(j=0;j<n;j++) { ix=kx; for(i=0;i<m;i++) { A[i]+=x[ix]*alpha*y[jy]; ix+=incx; } A+=ldA; jy+=incy; } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int GER<float>(int_t m, int_t n, float alpha, float *x, int_t incx, float *y, int_t incy, float *A, int_t ldA) { if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; cblas_sger(CblasColMajor,m,n,alpha,x,incx,y,incy,A,ldA); return 0; } template <> int GER<double>(int_t m, int_t n, double alpha, double *x, int_t incx, double *y, int_t incy, double *A, int_t ldA) { if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; cblas_dger(CblasColMajor,m,n,alpha,x,incx,y,incy,A,ldA); return 0; } #endif } #endif
{ "alphanum_fraction": 0.5057698648, "avg_line_length": 23.3307692308, "ext": "h", "hexsha": "4f381420d867715ee010907caf812cae878eafa5", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/ger.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/ger.h", "max_line_length": 130, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/ger.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 940, "size": 3033 }
#include <stdio.h> #include <string.h> #include <stdlib.h> //#include </usr/local/include/gsl/gsl_matrix.h> #include <gsl/gsl_matrix.h> // suprisingly, both work #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> /* * * Program that reads reference spectra and measure spectra data * and linearly unmixes the data using method of least squares fit. * Assumes readings is set to 400 and file path is preset to: * "/mnt/c/Users/jakei/'OneDrive - McGill University'/'Year 2'/1BIEN210/'Group Project'/". * * syntax: ./linearUnmixer MUfilename ref1filename ref2filename ref3filename ... * returns: completion status, prints composition of ref1, ref2, ... , refn * * * **************************************************************** * * Author Dept. Date Notes * * **************************************************************** * * Jake Z Bio. Eng. Mar 12 2020 Initial version * * Jake Z " Apr 03 2020 It works now! TODO: investigate the discrepancy between what you set $readings and the amount of space you allocate to the matrices as you forgot to account for the initial data clearing of the title headers in the data. * * */ const int READINGS = 1300; //note, if the readings specified here is more then the number of readings in file, funky stuff happens, TODO: implent check for this const int SKIP = 50; int normalizeVector( gsl_vector *vector ) { double min = gsl_vector_min( vector ); double norm = gsl_vector_max( vector ) - min; gsl_vector_add_constant( vector, -min ); gsl_vector_scale( vector, 1/norm ); return 0; } int readFileVector( gsl_vector *vector, char *filePath, char *fileName ) //read file vals into vector { char tmpFilepath[120] = "\0"; char tmpReading[20]; char *tmp2; double reading; //WARNING this is similar to global var $readings, consider renaming strcat( tmpFilepath, filePath ); //TODO replace this and the first instance of strcat into strcpy, that should work strcat( tmpFilepath, fileName ); //combines the filepath and name into one searchable /path/file FILE *file = fopen( tmpFilepath, "rt"); printf("%s\n", tmpFilepath); //TODO DELETE THIS if ( file == NULL ) { //check if file exists fprintf( stderr, "Error, unable to locate the Mu data file\n"); exit(100); } for ( int i = 0; i < SKIP; i++) //move past header of read files { fgets( tmpReading, 19, file ); } for ( int i = 0; i < READINGS; i++ ) { fgets( tmpReading, 19, file ); tmp2 = strrchr( tmpReading, '\t' ); tmp2 = tmp2 + 1; reading = atof(tmp2); gsl_vector_set( vector, i, reading); } fclose(file); printf("successful vector \n"); //TODO delete this return 0; } int readFileMatrix( gsl_matrix *matrix, char *filePath, int argc, char *argv[] ) { char *tmp2; double reading; for ( int j = 2; j < argc; j++ ) { gsl_vector_view column; char tmpFilepath[120] = "\0"; //TODO replace this and the first instance of strcat into strcpy, that should work char tmpReading[20]; strcat( tmpFilepath, filePath ); strcat( tmpFilepath, argv[j] ); //combines the filepath and name into one searchable /path/file FILE *file = fopen( tmpFilepath, "rt"); printf("%s\n", tmpFilepath); //TODO DELETE THIS if ( file == NULL ) { //check if file exists fprintf( stderr, "Error, unable to locate a reference data file\n"); exit(100); } for ( int i = 0; i < SKIP; i++) //move past header of read files { fgets( tmpReading, 20, file); } for ( int i = 0; i < READINGS; i++ ) //fill the ith element of the jth column { fgets( tmpReading, 19, file ); tmp2 = strrchr( tmpReading, '\t' ); tmp2 = tmp2 + 1; reading = atof(tmp2); gsl_matrix_set( matrix, i, j-2, reading ); } fclose(file); column = gsl_matrix_column( matrix, j-2 ); //NORMALISE EACH REFERENCE VECOTR. normalizeVector( &column.vector ); } printf("success, matrix filled \n"); //TODO DELETE THIS return 0; } int main(int argc, char *argv[]) { if ( argc <= 2 ) { fprintf( stderr, "Error, incorrect usage.\n./linearUnmixer MU_SPECTRA REF_SPECTRA\n"); return 3; } //spectrum files labelled /mnt/c/Users/jakei/'OneDrive - McGill University'/'Year 2'/1BIEN210/'Group Project'/SpectrumFile_00N.txt //intialize and allocate memory for variabels int numRefs = argc - 2; //char *filePath = ""; char *filePath = "/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/"; gsl_vector *muVector = gsl_vector_alloc(READINGS); gsl_vector *fVector = gsl_vector_alloc(numRefs); gsl_vector *x = gsl_vector_alloc(numRefs); //TODO RENAME x AND PROBECOMPVECTOR gsl_matrix *refMatrix = gsl_matrix_alloc(READINGS, numRefs); gsl_matrix *C = gsl_matrix_alloc( numRefs, numRefs ); gsl_matrix *Cinverse = gsl_matrix_alloc( numRefs, numRefs ); int s; gsl_permutation *p = gsl_permutation_alloc(numRefs); //CHANGED ALLOC TO CALLOC //initailize the variables to 0 gsl_vector_set_zero(muVector); gsl_vector_set_zero(fVector); gsl_vector_set_zero(x); gsl_matrix_set_zero(refMatrix); gsl_matrix_set_zero(C); gsl_permutation_init(p); //INITIALISED THE PERMUTATION readFileVector( muVector, filePath, argv[1] ); //call function which reads in values of first arguement file into the vector mu readFileMatrix( refMatrix, filePath, argc, argv ); //obtain matrix of reference vals, (400, 2) in 400 READINGS w/ 2 probes //normalize values, vector is already normalised normalizeVector( muVector ); //print vector to csv file for plotting FILE *csvfile = fopen( "/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/muVector.csv", "wt" ); gsl_vector_fprintf( csvfile, muVector, "%f" ); fclose(csvfile); FILE *csvfile2 = fopen( "/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/refVectors.txt", "wt" ); gsl_matrix_fprintf( csvfile2, refMatrix, "%f" ); fclose(csvfile2); //now we have variable muVector with vals and refMatrix with vals. gsl_blas_dgemm( CblasTrans, CblasNoTrans, 1, refMatrix, refMatrix, 0, C); //matrix C is now A^T A gsl_blas_dgemv( CblasTrans, 1, refMatrix, muVector, 0, fVector); //fVector is 'b' gsl_linalg_LU_decomp( C, p, &s); // gsl_linalg_LU_solve( C, p, fVector, x ); //can replace with gsl_linalg_LU_svx and delete x vector from program gsl_linalg_LU_invert( C, p, Cinverse ); //TODO maybe implement the other way you can solve for basis using inverse on both sides, (A^T A )^-1 A^T A x = (a^t a)^-1 (a^t b) = x gsl_blas_dgemv( CblasNoTrans, 1, Cinverse, fVector, 0, x); /* gsl_vector_fprintf( stdout, muVector, "%f" ); printf("***********************************************\n"); */ gsl_vector_fprintf( stdout, x, "%f" ); gsl_matrix_free(Cinverse); gsl_matrix_free(C); gsl_matrix_free(refMatrix); gsl_vector_free(muVector); gsl_vector_free(fVector); gsl_vector_free(x); return 0; }
{ "alphanum_fraction": 0.6795779737, "avg_line_length": 39.0903954802, "ext": "c", "hexsha": "4a089466e354cc78dfc765dc0918d8c93f0c0c92", "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": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jakeinater/spectralILU", "max_forks_repo_path": "backup/beta.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "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": "jakeinater/spectralILU", "max_issues_repo_path": "backup/beta.c", "max_line_length": 256, "max_stars_count": null, "max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jakeinater/spectralILU", "max_stars_repo_path": "backup/beta.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2042, "size": 6919 }
#ifndef RL_MDL_NLOPTINVERSEKINEMATICS_H #define RL_MDL_NLOPTINVERSEKINEMATICS_H #include <chrono> #include <nlopt.h> #include <random> #include <utility> #include "InverseKinematics.h" namespace rl { namespace mdl { class NloptInverseKinematics : public InverseKinematics { public: NloptInverseKinematics(Kinematic* kinematic); virtual ~NloptInverseKinematics(); bool solve(); ::rl::math::Real delta; ::std::chrono::nanoseconds duration; ::rl::math::Real epsilonRotation; ::rl::math::Real epsilonTranslation; double tolerance; protected: private: static void check(const nlopt_result& ret); ::rl::math::Real error(const ::rl::math::Vector& q); static ::rl::math::Real f(unsigned n, const double* x, double* grad, void* data); ::std::uniform_real_distribution< ::rl::math::Real> randDistribution; ::std::mt19937 randEngine; }; } } #endif // RL_MDL_NLOPTINVERSEKINEMATICS_H
{ "alphanum_fraction": 0.6822810591, "avg_line_length": 19.2549019608, "ext": "h", "hexsha": "c879b1f9e601287af81a0578981e131f7109a6ab", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:26:06.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-10T17:26:06.000Z", "max_forks_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "Roboy/rl", "max_forks_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "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": "Roboy/rl", "max_issues_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "Roboy/rl", "max_stars_repo_path": "src/rl/mdl/NloptInverseKinematics.h", "max_stars_repo_stars_event_max_datetime": "2020-11-10T17:26:21.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-10T17:26:21.000Z", "num_tokens": 288, "size": 982 }
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <terminal/Color.h> #include <terminal/RenderBuffer.h> #include <terminal/Screen.h> #include <terminal_renderer/Atlas.h> #include <terminal_renderer/BoxDrawingRenderer.h> #include <terminal_renderer/RenderTarget.h> #include <text_shaper/font.h> #include <text_shaper/shaper.h> #include <crispy/FNV.h> #include <crispy/LRUCache.h> #include <crispy/point.h> #include <crispy/size.h> #include <unicode/convert.h> #include <unicode/run_segmenter.h> #include <gsl/span> #include <gsl/span_ext> #include <functional> #include <list> #include <memory> #include <unordered_map> #include <vector> namespace terminal::renderer { enum class TextStyle { Invalid = 0x00, Regular = 0x10, Bold = 0x11, Italic = 0x12, BoldItalic = 0x13, }; constexpr TextStyle operator|(TextStyle a, TextStyle b) noexcept { return static_cast<TextStyle>(static_cast<unsigned>(a) | static_cast<unsigned>(b)); } constexpr bool operator<(TextStyle a, TextStyle b) noexcept { return static_cast<unsigned>(a) < static_cast<unsigned>(b); } struct TextCacheKey { std::u32string_view text; TextStyle style; constexpr bool operator<(TextCacheKey const& _rhs) const noexcept { if (text < _rhs.text) return true; return text < _rhs.text || style < _rhs.style; } constexpr bool operator==(TextCacheKey const& _rhs) const noexcept { return text == _rhs.text && style == _rhs.style; } constexpr bool operator!=(TextCacheKey const& _rhs) const noexcept { return !(*this == _rhs); } }; } // end namespace terminal::renderer namespace std { template <> struct hash<terminal::renderer::TextCacheKey> { size_t operator()(terminal::renderer::TextCacheKey const& _key) const noexcept { auto fnv = crispy::FNV<char32_t> {}; return static_cast<size_t>(fnv(fnv.basis(), _key.text, static_cast<char32_t>(_key.style))); } }; } // namespace std namespace terminal::renderer { struct GridMetrics; enum class TextShapingEngine { OpenShaper, //!< Uses open-source implementation: harfbuzz/freetype/fontconfig DWrite, //!< native platform support: Windows CoreText, //!< native platform support: OS/X }; enum class FontLocatorEngine { Mock, //!< mock font locator API FontConfig, //!< platform independant font locator API DWrite, //!< native platform support: Windows CoreText, //!< native font locator on OS/X }; std::unique_ptr<text::font_locator> createFontLocator(FontLocatorEngine _engine); struct FontDescriptions { double dpiScale = 1.0; crispy::Point dpi = { 0, 0 }; // 0 => auto-fill with defaults text::font_size size; text::font_description regular; text::font_description bold; text::font_description italic; text::font_description boldItalic; text::font_description emoji; text::render_mode renderMode; TextShapingEngine textShapingEngine = TextShapingEngine::OpenShaper; FontLocatorEngine fontLocator = FontLocatorEngine::FontConfig; bool builtinBoxDrawing = true; }; inline bool operator==(FontDescriptions const& a, FontDescriptions const& b) noexcept { return a.size.pt == b.size.pt && a.regular == b.regular && a.bold == b.bold && a.italic == b.italic && a.boldItalic == b.boldItalic && a.emoji == b.emoji && a.renderMode == b.renderMode; } inline bool operator!=(FontDescriptions const& a, FontDescriptions const& b) noexcept { return !(a == b); } struct FontKeys { text::font_key regular; text::font_key bold; text::font_key italic; text::font_key boldItalic; text::font_key emoji; }; /// Text Rendering Pipeline class TextRenderer: public Renderable { public: TextRenderer(GridMetrics const& _gridMetrics, text::shaper& _textShaper, FontDescriptions& _fontDescriptions, FontKeys const& _fontKeys); void setRenderTarget(RenderTarget& _renderTarget) override; void debugCache(std::ostream& _textOutput) const; void clearCache() override; void updateFontMetrics(); void setPressure(bool _pressure) noexcept { pressure_ = _pressure; } /// Must be invoked before a new terminal frame is rendered. void beginFrame(); /// Renders a given terminal's grid cell that has been /// transformed into a RenderCell. void renderCell(RenderCell const& _cell); /// Must be invoked when rendering the terminal's text has finished for this frame. void endFrame(); private: /// Puts a sequence of codepoints that belong to the same grid cell at @p _pos /// at the end of the currently filled line. void appendCell(gsl::span<char32_t const> _codepoints, TextStyle _style, RGBColor _color); text::shape_result const& cachedGlyphPositions(); text::shape_result requestGlyphPositions(); text::shape_result shapeRun(unicode::run_segmenter::range const& _run); void endSequence(); void renderRun(crispy::Point _startPos, gsl::span<text::glyph_position const> _glyphPositions, RGBColor _color); /// Renders an arbitrary texture. void renderTexture(crispy::Point const& _pos, RGBAColor const& _color, atlas::TextureInfo const& _textureInfo); // rendering // struct GlyphMetrics { ImageSize bitmapSize; // glyph size in pixels crispy::Point bearing; // offset baseline and left to top and left of the glyph's bitmap }; using TextureAtlas = atlas::MetadataTextureAtlas<text::glyph_key, GlyphMetrics>; using DataRef = TextureAtlas::DataRef; std::optional<DataRef> getTextureInfo(text::glyph_key const& _id, unicode::PresentationStyle _presentation); void renderTexture(crispy::Point const& _pos, RGBAColor const& _color, atlas::TextureInfo const& _textureInfo, GlyphMetrics const& _glyphMetrics, text::glyph_position const& _gpos); TextureAtlas* atlasForBitmapFormat(text::bitmap_format _format) noexcept { switch (_format) { case text::bitmap_format::alpha_mask: return monochromeAtlas_.get(); case text::bitmap_format::rgba: return colorAtlas_.get(); case text::bitmap_format::rgb: return lcdAtlas_.get(); default: return nullptr; // Should NEVER EVER happen. } } // general properties // GridMetrics const& gridMetrics_; FontDescriptions& fontDescriptions_; FontKeys const& fonts_; // performance optimizations // bool pressure_ = false; std::unordered_map<text::glyph_key, text::bitmap_format> glyphToTextureMapping_; std::list<std::u32string> cacheKeyStorage_; crispy::LRUCache<TextCacheKey, text::shape_result> cache_; // target surface rendering // text::shaper& textShaper_; std::unique_ptr<TextureAtlas> monochromeAtlas_; std::unique_ptr<TextureAtlas> colorAtlas_; std::unique_ptr<TextureAtlas> lcdAtlas_; // sub-renderer // BoxDrawingRenderer boxDrawingRenderer_; // render states TextStyle style_ = TextStyle::Invalid; RGBColor color_ {}; crispy::Point textPosition_; std::vector<char32_t> codepoints_; std::vector<unsigned> clusters_; unsigned cellCount_ = 0; bool textStartFound_ = false; bool forceCellGroupSplit_ = false; // output fields // std::vector<text::shape_result> shapedLines_; }; } // namespace terminal::renderer namespace fmt { // {{{ template <> struct formatter<terminal::renderer::FontDescriptions> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(terminal::renderer::FontDescriptions const& fd, FormatContext& ctx) { return format_to(ctx.out(), "({}, {}, {}, {}, {}, {})", fd.size, fd.regular, fd.bold, fd.italic, fd.boldItalic, fd.emoji, fd.renderMode); } }; template <> struct formatter<terminal::renderer::FontLocatorEngine> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(terminal::renderer::FontLocatorEngine value, FormatContext& ctx) { using terminal::renderer::FontLocatorEngine; switch (value) { case FontLocatorEngine::Mock: return format_to(ctx.out(), "Mock"); case FontLocatorEngine::FontConfig: return format_to(ctx.out(), "FontConfig"); case FontLocatorEngine::DWrite: return format_to(ctx.out(), "DirectWrite"); case FontLocatorEngine::CoreText: return format_to(ctx.out(), "CoreText"); } return format_to(ctx.out(), "UNKNOWN"); } }; template <> struct formatter<terminal::renderer::TextShapingEngine> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(terminal::renderer::TextShapingEngine value, FormatContext& ctx) { using terminal::renderer::TextShapingEngine; switch (value) { case TextShapingEngine::OpenShaper: return format_to(ctx.out(), "OpenShaper"); case TextShapingEngine::DWrite: return format_to(ctx.out(), "DirectWrite"); case TextShapingEngine::CoreText: return format_to(ctx.out(), "CoreText"); } return format_to(ctx.out(), "UNKNOWN"); } }; template <> struct formatter<terminal::renderer::TextCacheKey> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(terminal::renderer::TextCacheKey value, FormatContext& ctx) { return format_to(ctx.out(), "({}, \"{}\")", value.style, unicode::convert_to<char>(value.text)); } }; } // namespace fmt
{ "alphanum_fraction": 0.6657158631, "avg_line_length": 29.7753424658, "ext": "h", "hexsha": "f4ceb71b7934cabc782aa1a4374c882f13ad2a81", "lang": "C", "max_forks_count": 24, "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:24:42.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-02T15:40:00.000Z", "max_forks_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "dankamongmen/contour", "max_forks_repo_path": "src/terminal_renderer/TextRenderer.h", "max_issues_count": 204, "max_issues_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:46:05.000Z", "max_issues_repo_issues_event_min_datetime": "2021-07-01T10:10:01.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "dankamongmen/contour", "max_issues_repo_path": "src/terminal_renderer/TextRenderer.h", "max_line_length": 104, "max_stars_count": 404, "max_stars_repo_head_hexsha": "21c4dab7f97b41017fb7f57d742defe765157413", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "contour-terminal/contour", "max_stars_repo_path": "src/terminal_renderer/TextRenderer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:16:18.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-01T11:38:20.000Z", "num_tokens": 2480, "size": 10868 }
#ifndef GBNET_GRAPHORNOR #define GBNET_GRAPHORNOR #include <iostream> #include <string> #include <vector> #include <utility> #include <map> #include <set> #include <stdio.h> #include <gsl/gsl_rng.h> #include "RVNode.h" #include "XNode.h" #include "HNodeORNOR.h" #include "YDataNode.h" #include "SNode.h" #include "TNode.h" #include "ZNode.h" #include "NodeDictionary.h" #include "GraphBase.h" #include "YNoiseNode.h" namespace gbn { const double SPRIOR[3 * 3] = {0.40, 0.40, 0.20, 0.30, 0.40, 0.30, 0.20, 0.40, 0.40}; class GraphORNOR: public GraphBase { private: protected: public: const double XPROB[2] = {0.99, 0.01}; const double XPROB_ACTIVE[2] = {0.10, 0.90}; double SPROB[3][3] = {{0.900, 0.090, 0.010}, {0.050, 0.900, 0.050}, {0.010, 0.090, 0.900}}; double YPROB[3] = {0.05, 0.90, 0.05}; double YNOISE[3][3] = {{0.945, 0.050, 0.005}, {0.050, 0.900, 0.050}, {0.005, 0.050, 0.945}}; const double YNOISE_ALPHA[3][3] = {{2000, 100, 10}, { 100, 2000, 100}, { 10, 100, 2000}}; GraphORNOR (unsigned int); virtual ~GraphORNOR (); void build_structure (network_t, evidence_dict_t, prior_active_tf_set_t, bool = true, const double [3 * 3] = SPRIOR, double z_alpha = 25., double z_beta = 25., double z0_alpha = 25., double z0_beta = 25., double t_alpha = 25., double t_beta = 25., bool comp_yprob = true, bool const_params = false, double t_focus = 2., double t_lmargin = 2., double t_hmargin = 2., double zn_focus = 2., double zn_lmargin = 8., double zn_hmargin = 2.); }; } #endif
{ "alphanum_fraction": 0.4800959233, "avg_line_length": 33.6290322581, "ext": "h", "hexsha": "ee8a6e8bca5ba9af5fb22c4671bc9e8ba85a05ef", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umbibio/gbnet", "max_forks_repo_path": "libgbnet/include/GraphORNOR.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "umbibio/gbnet", "max_issues_repo_path": "libgbnet/include/GraphORNOR.h", "max_line_length": 247, "max_stars_count": null, "max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umbibio/gbnet", "max_stars_repo_path": "libgbnet/include/GraphORNOR.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 599, "size": 2085 }
// // beta.h // // code using beta distribution // // copyright 2020 Peter Andrews // #ifndef PAA_BETA_H_ #define PAA_BETA_H_ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <cmath> #include <mutex> #include <utility> #include "error.h" #include "utility.h" namespace paa { class GSLRNG { public: explicit GSLRNG(const uint64_t seed) : gen{gsl_rng_alloc(gsl_rng_mt19937)} { if (!gen) throw Error("Problem creating gsl generator"); gsl_rng_set(gen, seed); } ~GSLRNG() { gsl_rng_free(gen); } operator gsl_rng * () const { return gen; } GSLRNG(const GSLRNG &) = delete; GSLRNG & operator=(const GSLRNG &) = delete; void lock() { mutex.lock(); } void unlock() { mutex.unlock(); } private: gsl_rng * gen; std::mutex mutex{}; }; template<class Val> class BetaT { public: using Params = std::pair<Val, Val>; BetaT(const Val alpha__, const Val beta__) : alpha_{alpha__}, beta_{beta__} { if (alpha_ <= 0) throw Error("Nonpositive alpha in Beta distribution"); if (beta_ <= 0) throw Error("Nonpositive beta in Beta distribution"); } explicit BetaT(const Params params) : BetaT{params.first, params.second} {} BetaT(const Val mean_, const Val stdev_, const bool) : alpha_{get_alpha(mean_, stdev_)}, beta_{get_beta(mean_, stdev_)} { if (stdev_ >= max_stdev(mean_)) throw Error("Maximum stdev for basic Beta distribution is") << max_stdev(mean_); } Val alpha() const { return alpha_; } Val beta() const { return beta_; } Val low() const { return 0.0; } Val high() const { return 1.0; } Val range() const { return 1.0; } Val middle() const { return 0.5; } static Val get_alpha(const Val mean_, const Val stdev_) { return mean_ * (mean_ * (1 - mean_) / sqr(stdev_) - 1); } static Val get_beta(const Val mean_, const Val stdev_) { return (1 - mean_) * (mean_ * (1 - mean_) / sqr(stdev_) - 1); } static Val max_stdev(const Val mean_) { return sqrt(mean_ * (1 - mean_)); } Val mean() const { return alpha_ / (alpha_ + beta_); } Val stdev() const { return sqrt((alpha_ * beta_) / (sqr(alpha_ + beta_) * (alpha_ + beta_ + 1))); } Val operator()(const Val val) const { return gsl_ran_beta_pdf(val, alpha_, beta_); } Val operator()(gsl_rng * gen) const { return gsl_ran_beta(gen, alpha_, beta_); } private: Val alpha_; Val beta_; }; using Beta = BetaT<double>; using fBeta = BetaT<float>; template<class Val> class Beta4T { public: Beta4T(const Val alpha__, const Val beta__, const Val low__, const Val high__) : beta_dist{alpha__, beta__}, low_{low__}, high_{high__} { if (mean() < low()) throw Error("Mean less than low in Beta distribution"); if (mean() > high()) throw Error("Mean greater than high in Beta distribution"); } Beta4T(const Val mean_, const Val stdev_, const Val low__, const Val high__, const bool) : beta_dist{get_alpha_beta(mean_, stdev_, low__, high__)}, low_{low__}, high_{high__} {} Val alpha() const { return beta_dist.alpha(); } Val beta() const { return beta_dist.beta(); } Val low() const { return low_; } Val high() const { return high_; } Val range() const { return (high_ - low_); } Val middle() const { return (high_ - low_) / 2; } Val mean() const { return low_ + scale * beta_dist.mean(); } Val stdev() const { return scale * beta_dist.stdev(); } static Val max_stdev(const Val mean_, const Val low__, const Val high__) { const Val sf{high__ - low__}; const Val m{(mean_ - low__) / sf}; return sf * BetaT<Val>::max_stdev(m); } Val operator()(const Val val) const { return static_cast<Val>(beta_dist((val - low_) / scale)) / scale; } Val operator()(gsl_rng * gen) const { return low_ + scale * static_cast<Val>(beta_dist(gen)); } private: static typename BetaT<Val>::Params get_alpha_beta( const Val mean_, const Val stdev_, const Val low__, const Val high__) { const Val sf{high__ - low__}; const Val m{(mean_ - low__) / sf}; const Val sd{stdev_ / sf}; return typename BetaT<Val>::Params{ BetaT<Val>::get_alpha(m, sd), BetaT<Val>::get_beta(m, sd)}; } BetaT<Val> beta_dist; Val low_; Val high_; Val scale{high_ - low_}; }; using Beta4 = Beta4T<double>; using fBeta4 = Beta4T<float>; } // namespace paa #endif // PAA_BETA_H_
{ "alphanum_fraction": 0.6337743889, "avg_line_length": 28.7677419355, "ext": "h", "hexsha": "8d6ec89085f8b1b78956570d07f4ae513878347a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-11-20T15:47:54.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-20T15:47:54.000Z", "max_forks_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_forks_repo_licenses": [ "Zlib", "MIT" ], "max_forks_repo_name": "docpaa/mumdex", "max_forks_repo_path": "utility/beta.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib", "MIT" ], "max_issues_repo_name": "docpaa/mumdex", "max_issues_repo_path": "utility/beta.h", "max_line_length": 79, "max_stars_count": 5, "max_stars_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_stars_repo_licenses": [ "Zlib", "MIT" ], "max_stars_repo_name": "docpaa/mumdex", "max_stars_repo_path": "utility/beta.h", "max_stars_repo_stars_event_max_datetime": "2019-11-23T00:58:54.000Z", "max_stars_repo_stars_event_min_datetime": "2018-02-07T15:58:30.000Z", "num_tokens": 1266, "size": 4459 }
/** * * @file example_cposv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example of solving a linear system with a Cholesky factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated c Tue Jan 7 11:45:21 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> int check_solution(int, int, PLASMA_Complex32_t*, int, PLASMA_Complex32_t*, PLASMA_Complex32_t*, int); int IONE=1; int ISEED[4] = {0,0,0,1}; /* initial seed for clarnv() */ int main () { int cores = 2; int N = 10; int LDA = 10; int NRHS = 5; int LDB = 10; int info; int info_solution; PLASMA_Complex32_t *A1 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *A2 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *B1 = (PLASMA_Complex32_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *B2 = (PLASMA_Complex32_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex32_t)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)){ printf("Out of Memory \n "); return EXIT_SUCCESS; } /* Plasma Initialize */ PLASMA_Init(cores); printf("-- PLASMA is initialized to run on %d cores. \n",cores); /*------------------------------------------------------------- * TESTING CPOSV */ /* Initialize A1 and A2 for Symmetric Positif Matrix (Hessenberg in the complex case) */ PLASMA_cplghe( (float)N, N, A1, LDA, 51 ); PLASMA_clacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_cplrnt( N, NRHS, B1, LDB, 371 ); PLASMA_clacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); /* PLASMA CPOSV */ info = PLASMA_cposv(PlasmaUpper, N, NRHS, A2, LDA, B2, LDB); /* Check the solution */ info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB); if ((info_solution != 0)|(info != 0)) printf("-- Error in CPOSV example ! \n"); else printf("-- Run of CPOSV example successful ! \n"); free(A1); free(A2); free(B1); free(B2); PLASMA_Finalize(); return EXIT_SUCCESS; } /*------------------------------------------------------------------------ * Check the accuracy of the solution of the linear system */ int check_solution(int N, int NRHS, PLASMA_Complex32_t *A1, int LDA, PLASMA_Complex32_t *B1, PLASMA_Complex32_t *B2, int LDB) { int info_solution; float Rnorm, Anorm, Xnorm, Bnorm; PLASMA_Complex32_t alpha, beta; float *work = (float *)malloc(N*sizeof(float)); float eps; eps = LAPACKE_slamch_work('e'); alpha = 1.0; beta = -1.0; Xnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B2, LDB, work); Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work); Bnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, CBLAS_SADDR(alpha), A1, LDA, B2, LDB, CBLAS_SADDR(beta), B1, LDB); Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, NRHS, B1, LDB, work); printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n",Rnorm/((Anorm*Xnorm+Bnorm)*N*eps)); if (Rnorm/((Anorm*Xnorm+Bnorm)*N*eps) > 10.0){ printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; }
{ "alphanum_fraction": 0.6192764989, "avg_line_length": 30.6434108527, "ext": "c", "hexsha": "6541dd4d40f4fb1412fc1a1093b0f1fa8f363a56", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "examples/example_cposv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "examples/example_cposv.c", "max_line_length": 137, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "examples/example_cposv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1318, "size": 3953 }
#pragma once #include <gsl\gsl> #include <winrt\base.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "FullScreenQuad.h" namespace Rendering { class ComputeShaderMaterial; class ComputeShaderDemo final : public Library::DrawableGameComponent { public: ComputeShaderDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); ComputeShaderDemo(const ComputeShaderDemo&) = delete; ComputeShaderDemo(ComputeShaderDemo&&) = default; ComputeShaderDemo& operator=(const ComputeShaderDemo&) = default; ComputeShaderDemo& operator=(ComputeShaderDemo&&) = default; ~ComputeShaderDemo(); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); float BlueColor() const; void SetBlueColor(float blueColor); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: std::unique_ptr<ComputeShaderMaterial> mMaterial; Library::FullScreenQuad mFullScreenQuad; winrt::com_ptr<ID3D11ShaderResourceView> mColorTexture; bool mAnimationEnabled{ true }; }; }
{ "alphanum_fraction": 0.7754569191, "avg_line_length": 29.4615384615, "ext": "h", "hexsha": "53f5e8ceb3eae3cc2f2c560e93382dd65656822e", "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/11.2_Compute_Shaders/ComputeShaderDemo.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/11.2_Compute_Shaders/ComputeShaderDemo.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/11.2_Compute_Shaders/ComputeShaderDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 277, "size": 1149 }
/***************************************************************************** * * * Copyright 2018 Rice University * * * * 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 LDA_DOC_TOPIC_PROB_SELECT_H #define LDA_DOC_TOPIC_PROB_SELECT_H #include "Lambda.h" #include "LambdaCreationFunctions.h" #include "SelectionComp.h" #include "PDBVector.h" #include "IntIntVectorPair.h" #include "IntDoubleVectorPair.h" #include "DocAssignment.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <random> #include <gsl/gsl_vector.h> /* This class samples the topic probability for the document */ using namespace pdb; class LDADocTopicProbSelection : public SelectionComp<IntDoubleVectorPair, DocAssignment> { private: Vector<double> prior; Handle<Vector<char>> myMem; int topicNum; public: ENABLE_DEEP_COPY LDADocTopicProbSelection() {} LDADocTopicProbSelection(Vector<double>& fromPrior) { this->prior = fromPrior; this->topicNum = fromPrior.size(); /* Set up the random number generator */ gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937); std::random_device rd; std::mt19937 gen(rd()); gsl_rng_set(src, gen()); int spaceNeeded = sizeof(gsl_rng) + src->type->size; myMem = makeObject<Vector<char>>(spaceNeeded, spaceNeeded); memcpy(myMem->c_ptr(), src, sizeof(gsl_rng)); memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size); gsl_rng_free(src); } Lambda<bool> getSelection(Handle<DocAssignment> checkMe) override { return makeLambda(checkMe, [](Handle<DocAssignment>& checkMe) { return true; }); } Lambda<Handle<IntDoubleVectorPair>> getProjection(Handle<DocAssignment> checkMe) override { return makeLambda(checkMe, [&](Handle<DocAssignment>& checkMe) { gsl_rng* rng = getRng(); Vector<unsigned>& topicCount = checkMe->getVector(); Handle<Vector<double>> mySamples = makeObject<Vector<double>>(topicNum, topicNum); double* totalProb = new double[topicNum]; for (int i = 0; i < topicNum; i++) { totalProb[i] = (this->prior)[i] + topicCount[i]; } /* Sample the topic probability */ gsl_ran_dirichlet(rng, topicNum, totalProb, mySamples->c_ptr()); Handle<IntDoubleVectorPair> result = makeObject<IntDoubleVectorPair>(checkMe->getKey(), mySamples); delete[] totalProb; return result; }); } gsl_rng* getRng() { gsl_rng* dst = (gsl_rng*)myMem->c_ptr(); dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng)); dst->type = gsl_rng_mt19937; return dst; } }; #endif
{ "alphanum_fraction": 0.5372868414, "avg_line_length": 37.419047619, "ext": "h", "hexsha": "5a37c6d94f05f57962296842aeaec43fe5ed046d", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2020-08-03T00:58:24.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-14T03:39:14.000Z", "max_forks_repo_head_hexsha": "a6f1c8ac8f75c09615f08752c82179f33cfc6d89", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "dcbdan/plinycompute", "max_forks_repo_path": "applications/TestLDA/sharedLibraries/headers/LDADocTopicProbSelection.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "a6f1c8ac8f75c09615f08752c82179f33cfc6d89", "max_issues_repo_issues_event_max_datetime": "2018-11-01T15:36:07.000Z", "max_issues_repo_issues_event_min_datetime": "2018-07-03T21:50:14.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "dcbdan/plinycompute", "max_issues_repo_path": "applications/TestLDA/sharedLibraries/headers/LDADocTopicProbSelection.h", "max_line_length": 95, "max_stars_count": 29, "max_stars_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "dimitrijejankov/pdb", "max_stars_repo_path": "pdb/src/sharedLibraries/headers/LDA/LDADocTopicProbSelection.h", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:45:12.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-14T03:19:32.000Z", "num_tokens": 799, "size": 3929 }
/* deriv/deriv.c * * Copyright (C) 2004, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_deriv.h> static void central_deriv (const gsl_function * f, double x, double h, double *result, double *abserr_round, double *abserr_trunc) { /* Compute the derivative using the 5-point rule (x-h, x-h/2, x, x+h/2, x+h). Note that the central point is not used. Compute the error using the difference between the 5-point and the 3-point rule (x-h,x,x+h). Again the central point is not used. */ double fm1 = GSL_FN_EVAL (f, x - h); double fp1 = GSL_FN_EVAL (f, x + h); double fmh = GSL_FN_EVAL (f, x - h / 2); double fph = GSL_FN_EVAL (f, x + h / 2); double r3 = 0.5 * (fp1 - fm1); double r5 = (4.0 / 3.0) * (fph - fmh) - (1.0 / 3.0) * r3; double e3 = (fabs (fp1) + fabs (fm1)) * GSL_DBL_EPSILON; double e5 = 2.0 * (fabs (fph) + fabs (fmh)) * GSL_DBL_EPSILON + e3; /* The next term is due to finite precision in x+h = O (eps * x) */ double dy = GSL_MAX (fabs (r3 / h), fabs (r5 / h)) *(fabs (x) / h) * GSL_DBL_EPSILON; /* The truncation error in the r5 approximation itself is O(h^4). However, for safety, we estimate the error from r5-r3, which is O(h^2). By scaling h we will minimise this estimated error, not the actual truncation error in r5. */ *result = r5 / h; *abserr_trunc = fabs ((r5 - r3) / h); /* Estimated truncation error O(h^2) */ *abserr_round = fabs (e5 / h) + dy; /* Rounding error (cancellations) */ } int gsl_deriv_central (const gsl_function * f, double x, double h, double *result, double *abserr) { double r_0, round, trunc, error; central_deriv (f, x, h, &r_0, &round, &trunc); error = round + trunc; if (round < trunc && (round > 0 && trunc > 0)) { double r_opt, round_opt, trunc_opt, error_opt; /* Compute an optimised stepsize to minimize the total error, using the scaling of the truncation error (O(h^2)) and rounding error (O(1/h)). */ double h_opt = h * pow (round / (2.0 * trunc), 1.0 / 3.0); central_deriv (f, x, h_opt, &r_opt, &round_opt, &trunc_opt); error_opt = round_opt + trunc_opt; /* Check that the new error is smaller, and that the new derivative is consistent with the error bounds of the original estimate. */ if (error_opt < error && fabs (r_opt - r_0) < 4.0 * error) { r_0 = r_opt; error = error_opt; } } *result = r_0; *abserr = error; return GSL_SUCCESS; } static void forward_deriv (const gsl_function * f, double x, double h, double *result, double *abserr_round, double *abserr_trunc) { /* Compute the derivative using the 4-point rule (x+h/4, x+h/2, x+3h/4, x+h). Compute the error using the difference between the 4-point and the 2-point rule (x+h/2,x+h). */ double f1 = GSL_FN_EVAL (f, x + h / 4.0); double f2 = GSL_FN_EVAL (f, x + h / 2.0); double f3 = GSL_FN_EVAL (f, x + (3.0 / 4.0) * h); double f4 = GSL_FN_EVAL (f, x + h); double r2 = 2.0*(f4 - f2); double r4 = (22.0 / 3.0) * (f4 - f3) - (62.0 / 3.0) * (f3 - f2) + (52.0 / 3.0) * (f2 - f1); /* Estimate the rounding error for r4 */ double e4 = 2 * 20.67 * (fabs (f4) + fabs (f3) + fabs (f2) + fabs (f1)) * GSL_DBL_EPSILON; /* The next term is due to finite precision in x+h = O (eps * x) */ double dy = GSL_MAX (fabs (r2 / h), fabs (r4 / h)) * fabs (x / h) * GSL_DBL_EPSILON; /* The truncation error in the r4 approximation itself is O(h^3). However, for safety, we estimate the error from r4-r2, which is O(h). By scaling h we will minimise this estimated error, not the actual truncation error in r4. */ *result = r4 / h; *abserr_trunc = fabs ((r4 - r2) / h); /* Estimated truncation error O(h) */ *abserr_round = fabs (e4 / h) + dy; } int gsl_deriv_forward (const gsl_function * f, double x, double h, double *result, double *abserr) { double r_0, round, trunc, error; forward_deriv (f, x, h, &r_0, &round, &trunc); error = round + trunc; if (round < trunc && (round > 0 && trunc > 0)) { double r_opt, round_opt, trunc_opt, error_opt; /* Compute an optimised stepsize to minimize the total error, using the scaling of the estimated truncation error (O(h)) and rounding error (O(1/h)). */ double h_opt = h * pow (round / (trunc), 1.0 / 2.0); forward_deriv (f, x, h_opt, &r_opt, &round_opt, &trunc_opt); error_opt = round_opt + trunc_opt; /* Check that the new error is smaller, and that the new derivative is consistent with the error bounds of the original estimate. */ if (error_opt < error && fabs (r_opt - r_0) < 4.0 * error) { r_0 = r_opt; error = error_opt; } } *result = r_0; *abserr = error; return GSL_SUCCESS; } int gsl_deriv_backward (const gsl_function * f, double x, double h, double *result, double *abserr) { return gsl_deriv_forward (f, x, -h, result, abserr); }
{ "alphanum_fraction": 0.6200947226, "avg_line_length": 33.0279329609, "ext": "c", "hexsha": "2cec7941d58b19eb85b0c02221019758ca7de8e7", "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/deriv/deriv.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/deriv/deriv.c", "max_line_length": 92, "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/deriv/deriv.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": 1850, "size": 5912 }
#include <gsl/gsl_chebyshev.h> const struct _GSLMethods chebyshev_f = { (void_m_t) gsl_cheb_free, /* gsl_multimin_fminimizer_restart */ (void_m_t) NULL, NULL, NULL}; static int PyGSL_cheb_init(PyGSL_Solver *self, PyObject *args, PyObject *kw) { ; }
{ "alphanum_fraction": 0.7074074074, "avg_line_length": 22.5, "ext": "c", "hexsha": "cb44e2c6c1736fdd91cc1670fb984d566f1f0a26", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_line_length": 65, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/chebyshev.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 90, "size": 270 }
/* Copyright (c) 2015, Patrick Weltevrede 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. 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. */ #define _FILE_OFFSET_BITS 64 #define _USE_LARGEFILE 1 #define _LARGEFILE_SOURCE 1 #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_sort.h> #include "psrsalsa.h" #define MaxNrOnpulseRegions 10 int NrOnpulseRegions, OnPulseRegion[MaxNrOnpulseRegions][2]; void PlotProfile(int NrBins, float *Ipulse, char *xlabel, char *ylabel, char *title, int Highlight, int color, int clearPage); void ShiftProfile(int shift, int NrBins, float *Iprofile, float *outputProfile); int main(int argc, char **argv) { char output_fname[1000], PlotDevice[100], singlechar, *inputname; int circularShift, noinput, onlyI, memsave, currentfilenumber, dummy_int; int shift, bin1, bin2, subintWritten, poladd, freqadd; long i, j, pol, fchan, nsub, binnr, nrinputfiles, subintslost, currentOutputSubint, sumNsub, curNrInsubint; float *Iprofile, *Iprofile_firstfile, *shiftedProfile, *subint, x, y, *float_ptr, *float_ptr2; datafile_definition **fin; datafile_definition fout, clone; psrsalsaApplication application; initApplication(&application, "padd", "[options] inputfiles"); application.switch_blocksize = 1; application.switch_verbose = 1; application.switch_debug = 1; application.switch_filelist = 1; application.switch_iformat = 1; application.switch_oformat = 1; application.switch_formatlist = 1; application.switch_fscr = 1; application.switch_FSCR = 1; application.switch_nocounters = 1; application.switch_changeRefFreq = 1; application.oformat = FITS_format; strcpy(PlotDevice, "?"); onlyI = 0; strcpy(output_fname, "addedfile.gg"); NrOnpulseRegions = 0; circularShift = 0; noinput = 0; shift = 0; memsave = 0; sumNsub = 1; poladd = 0; freqadd = 0; x = y = singlechar = 0; if(argc < 2) { printf("Program to add data files together. Usage:\n\n"); printApplicationHelp(&application); printf("Optional options:\n"); printf("-w Output name. Default is \"%s\"\n", output_fname); printf("-I Only process the first polarization channel\n"); printf("-c Turn on circular shifting (so that no subint is lost).\n"); printf(" The first and last subintegrations are spilling over\n"); printf(" into each other.\n"); printf("-n No graphical input, circular shifting by this number of\n"); printf(" bins, so this option implies -c. So -n 0 results in a\n"); printf(" simple concatenation of the input files.\n"); printf("-nsub This number of subintegrations are summed before being\n"); printf(" written out\n"); printf("-poladd The input files are to be interpretted as separate\n"); printf(" polarization channels (option implies -n 0).\n"); printf("-freqadd The input files are to be interpretted as separate\n"); printf(" frequency bands (option implies -n 0).\n"); printf("-memsave Only one full input data-set exists in memory at a time,\n"); printf(" but every input file will be opened twice.\n"); printf("\n"); printCitationInfo(); terminateApplication(&application); return 0; }else { for(i = 1; i < argc; i++) { dummy_int = i; if(processCommandLine(&application, argc, argv, &dummy_int)) { i = dummy_int; }else if(strcmp(argv[i], "-w") == 0 || strcmp(argv[i], "-W") == 0) { strcpy(output_fname,argv[i+1]); i++; }else if(strcmp(argv[i], "-memsave") == 0) { memsave = 1; }else if(strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "-C") == 0) { circularShift = 1; }else if(strcmp(argv[i], "-I") == 0) { onlyI = 1; }else if(strcmp(argv[i], "-poladd") == 0) { poladd = 1; circularShift = 1; noinput = 1; shift = 0; }else if(strcmp(argv[i], "-freqadd") == 0) { freqadd = 1; circularShift = 1; noinput = 1; shift = 0; }else if(strcmp(argv[i], "-n") == 0) { circularShift = 1; noinput = 1; if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &shift, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot parse '%s' option.", argv[i]); return 0; } i++; }else if(strcmp(argv[i], "-nsub") == 0) { if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%ld", &sumNsub, NULL) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot parse '%s' option.", argv[i]); return 0; } if(sumNsub < 1) { fflush(stdout); printerror(application.verbose_state.debug, "ERROR padd: Cannot parse option %s, expected one integer number > 1", argv[i]); return 0; } i++; }else { if(argv[i][0] == '-') { printerror(application.verbose_state.debug, "ERROR padd: Unknown option %s. Run padd without command-line options to get help.", argv[i]); terminateApplication(&application); return 0; }else { if(applicationAddFilename(i, application.verbose_state) == 0) return 0; } } } } if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) { return 0; } nrinputfiles = numberInApplicationFilenameList(&application, argv, application.verbose_state); if(nrinputfiles < 2) { printerror(application.verbose_state.debug, "ERROR padd: Need at least two input files"); return 0; } if(freqadd && poladd) { printerror(application.verbose_state.debug, "ERROR padd: Cannot use the -freqadd and -poladd flag simultaneously."); return 0; } if(sumNsub != 1 && poladd) { printerror(application.verbose_state.debug, "ERROR padd: Cannot use the -nsub and -poladd flag simultaneously."); return 0; } if(sumNsub != 1 && freqadd) { printerror(application.verbose_state.debug, "ERROR padd: Cannot use the -nsub and -freqadd flag simultaneously."); return 0; } if(circularShift != 1 && poladd) { printerror(application.verbose_state.debug, "ERROR padd: You must use the -c option together with -poladd."); return 0; } if(circularShift != 1 && freqadd) { printerror(application.verbose_state.debug, "ERROR padd: You must use the -c option together with -freqadd."); return 0; } if((noinput != 1 || shift != 0) && poladd) { printerror(application.verbose_state.debug, "ERROR padd: You must use the -n 0 option together with -poladd."); return 0; } if((noinput != 1 || shift != 0) && freqadd) { printerror(application.verbose_state.debug, "ERROR padd: You must use the -n 0 option together with -poladd."); return 0; } fin = malloc(nrinputfiles*sizeof(datafile_definition *)); if(fin == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Memory allocation error"); return 0; } for(i = 0; i < nrinputfiles; i++) { fin[i] = malloc(sizeof(datafile_definition)); if(fin[i] == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Memory allocation error"); return 0; } } currentfilenumber = 0; while((inputname = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) { verbose_definition verbose2; copyVerboseState(application.verbose_state, &verbose2); verbose2.indent = application.verbose_state.indent + 2; if(memsave == 0 || (currentfilenumber == 0 && noinput == 0)) { if(currentfilenumber == 0) { printf("Read in input files:\n"); } if(openPSRData(fin[currentfilenumber], inputname, application.iformat, 0, 1, 0, verbose2) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot open %s\n", inputname); return 0; } if(currentfilenumber == 0) { for(i = 1; i < argc; i++) { if(strcmp(argv[i], "-header") == 0) { fflush(stdout); printwarning(application.verbose_state.debug, "WARNING: If using the -header option, be aware it applied BEFORE the preprocessing."); } } } if(preprocessApplication(&application, fin[currentfilenumber]) == 0) { printerror(application.verbose_state.debug, "ERROR padd: preprocess option failed on file %s\n", inputname); return 0; } }else { if(currentfilenumber == 0) printf("Read in headers of input files:\n"); if(openPSRData(fin[currentfilenumber], inputname, application.iformat, 0, 0, 0, verbose2) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot open %s\n", inputname); return 0; } if(readHeaderPSRData(fin[currentfilenumber], 1, 0, verbose2) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot read header of file %s\n", inputname); return 0; } } if(currentfilenumber == 0 && noinput == 0) { Iprofile_firstfile = (float *)malloc(fin[0]->NrPols*fin[0]->NrBins*sizeof(float)); shiftedProfile = (float *)malloc(fin[0]->NrPols*fin[0]->NrBins*sizeof(float)); if(Iprofile_firstfile == NULL || shiftedProfile == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Cannot allocate memory."); return 0; } if(read_profilePSRData(*fin[0], Iprofile_firstfile, NULL, 0, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Reading pulse profile of first input file failed."); return 0; } } if(memsave) { if(closePSRData(fin[currentfilenumber], 1, application.verbose_state) != 0) { printerror(application.verbose_state.debug, "ERROR padd: Closing file %s failed\n", inputname); return 0; } } if(fin[currentfilenumber]->NrBins != fin[0]->NrBins) { printerror(application.verbose_state.debug, "ERROR padd: Number of pulse longitude bins not equal in input files."); return 0; } if(fin[0]->NrPols != fin[currentfilenumber]->NrPols && onlyI == 0) { printerror(application.verbose_state.debug, "ERROR padd: Number of polarization channels are different. Maybe you want to use the -I option?"); return 0; } if(freqadd == 0) { if(fin[currentfilenumber]->NrFreqChan != fin[0]->NrFreqChan) { printerror(application.verbose_state.debug, "ERROR padd: Number of frequency channels not equal in input files."); return 0; } } if(poladd || freqadd) { if(fin[0]->NrSubints != fin[currentfilenumber]->NrSubints) { printerror(application.verbose_state.debug, "ERROR padd: Number of subints are different. This is not allowed with the -poladd or -freqadd options."); return 0; } } if(poladd) { if(fin[currentfilenumber]->NrPols != 1) { printerror(application.verbose_state.debug, "ERROR padd: Number of polarization channels in input files should be 1 if using the -poladd option."); return 0; } } if(fin[currentfilenumber]->isDeDisp != fin[0]->isDeDisp) { printerror(application.verbose_state.debug, "ERROR padd: Dedispersion state is not equal in input files."); return 0; } if(fin[currentfilenumber]->isDeFarad != fin[0]->isDeFarad) { printerror(application.verbose_state.debug, "ERROR padd: De-Faraday rotation state is not equal in input files."); return 0; } if(fin[currentfilenumber]->isDePar != fin[0]->isDePar) { printerror(application.verbose_state.debug, "ERROR padd: Parallactic angle state is not equal in input files."); return 0; } currentfilenumber++; } printf("Reading of input files done\n"); unsigned long *sort_indx; sort_indx = (unsigned long *)malloc(nrinputfiles*sizeof(unsigned long)); if(sort_indx == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Memory allocation error\n"); return 0; } for(currentfilenumber = 0; currentfilenumber < nrinputfiles; currentfilenumber++) { sort_indx[currentfilenumber] = currentfilenumber; } cleanPSRData(&fout, application.verbose_state); copy_params_PSRData(*(fin[0]), &fout, application.verbose_state); if(onlyI) { fout.NrPols = 1; } fout.format = application.oformat; fout.NrSubints = 0; subintslost = 0; if(poladd) { fout.NrPols = nrinputfiles; fout.NrSubints = fin[0]->NrSubints; }else if(freqadd) { fout.NrSubints = fin[0]->NrSubints; fout.NrFreqChan = 0; for(currentfilenumber = 0; currentfilenumber < nrinputfiles; currentfilenumber++) { fout.NrFreqChan += fin[currentfilenumber]->NrFreqChan; } fout.freqMode = FREQMODE_FREQTABLE; if(fout.freqlabel_list != NULL) { free(fout.freqlabel_list); } fout.freqlabel_list = (double *)malloc(fout.NrFreqChan*fout.NrSubints*sizeof(double)); if(fout.freqlabel_list == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Memory allocation error"); return 0; } long currentOutputChan = 0; for(i = 0; i < nrinputfiles; i++) { currentfilenumber = sort_indx[i]; for(fchan = 0; fchan < fin[currentfilenumber]->NrFreqChan; fchan++) { for(nsub = 0; nsub < fin[currentfilenumber]->NrSubints; nsub++) { double freq; freq = get_weighted_channel_freq(*(fin[currentfilenumber]), nsub, fchan, application.verbose_state); if(set_weighted_channel_freq(&fout, nsub, currentOutputChan, freq, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Constructing frequency table failed"); return 0; } } currentOutputChan++; } } }else { for(i = 0; i < nrinputfiles; i++) { fout.NrSubints += fin[i]->NrSubints; if(circularShift == 0) { fout.NrSubints -= 1; subintslost += 1; } } } if(freqadd || poladd) { printf("\nOutput data will be %ld subints, %ld phase bins %ld frequency channels and %ld polarizations.\n", fout.NrSubints, fout.NrBins, fout.NrFreqChan, fout.NrPols); }else { printf("\nInput data contains %ld subints, %ld phase bins %ld frequency channels and %ld polarizations.\n", fout.NrSubints+subintslost, fout.NrBins, fout.NrFreqChan, fout.NrPols); printf("%ld subints are lost because of the alignment of input data", subintslost); if(subintslost > 0) printf(" (consider using -c option)"); } fout.tsubMode = TSUBMODE_TSUBLIST; if(fout.tsub_list != NULL) { free(fout.tsub_list); } fout.tsub_list = (double *)malloc(fout.NrSubints*sizeof(double)); if(fout.tsub_list == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Memory allocation error"); return 0; } currentOutputSubint = 0; fout.tsub_list[0] = 0; subintWritten = 0; curNrInsubint = 0; if(poladd || freqadd) { for(nsub = 0; nsub < fin[0]->NrSubints; nsub++) { fout.tsub_list[nsub] = get_tsub(*(fin[0]), nsub, application.verbose_state); } }else { for(i = 0; i < nrinputfiles; i++) { currentfilenumber = sort_indx[i]; for(nsub = 0; nsub < fin[currentfilenumber]->NrSubints; nsub++) { if(currentOutputSubint < fout.NrSubints) fout.tsub_list[currentOutputSubint] += get_tsub(*(fin[currentfilenumber]), nsub, application.verbose_state); if(sumNsub == 1) { subintWritten = 1; }else if(curNrInsubint == sumNsub - 1) { subintWritten = 1; } curNrInsubint++; if(subintWritten) { subintWritten = 0; curNrInsubint = 0; currentOutputSubint++; if(currentOutputSubint < fout.NrSubints) fout.tsub_list[currentOutputSubint] = 0; } } } } if(freqadd == 0 && poladd == 0) { dummy_int = fout.NrSubints % sumNsub; fout.NrSubints = fout.NrSubints/sumNsub; printf("\nOutput data will contain %ld subints", fout.NrSubints); if(sumNsub > 1) printf(" after summing every %ld input subints", sumNsub); if(dummy_int) printf(" (%d input subints lost because of incomplete last subint)", dummy_int); printf("\n\n"); } if(fout.gentype == GENTYPE_PULSESTACK && sumNsub != 1) { if(fout.NrSubints != 1) { fout.gentype = GENTYPE_SUBINTEGRATIONS; }else { fout.gentype = GENTYPE_PROFILE; } } if(openPSRData(&fout, output_fname, fout.format, 1, 0, 0, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot open %s", output_fname); return 0; } if(writeHeaderPSRData(&fout, argc, argv, application.history_cmd_only, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Cannot write header to %s", output_fname); return 0; } Iprofile = (float *)malloc(fout.NrPols*fout.NrBins*sizeof(float)); if(Iprofile == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Cannot allocate memory."); return 0; } if(sumNsub > 1) { subint = (float *)malloc(fout.NrPols*fout.NrBins*fout.NrFreqChan*sizeof(float)); if(subint == NULL) { printerror(application.verbose_state.debug, "ERROR padd: Cannot allocate memory."); return 0; } } if(noinput == 0) { ppgopen(PlotDevice); ppgask(0); ppgslw(1); } currentfilenumber = 0; currentOutputSubint = 0; curNrInsubint = 0; subintWritten = 0; rewindFilenameList(&application); long currentfilenumber_index; long fchan_offset = 0; while((inputname = getNextFilenameFromList(&application, argv, application.verbose_state)) != NULL) { currentfilenumber_index = sort_indx[currentfilenumber]; if(memsave) { closePSRData(fin[currentfilenumber_index], 0, application.verbose_state); if(openPSRData(fin[currentfilenumber_index], inputname, application.iformat, 0, 1, 0, application.verbose_state) == 0) { printerror(application.verbose_state.debug, "ERROR padd: Cannot open %s\n", inputname); return 0; } if(currentfilenumber == 0) { for(i = 1; i < argc; i++) { if(strcmp(argv[i], "-header") == 0) { fflush(stdout); printwarning(application.verbose_state.debug, "WARNING: If using the -header option, be aware it applied BEFORE the preprocessing."); } } } if(preprocessApplication(&application, fin[currentfilenumber_index]) == 0) { printerror(application.verbose_state.debug, "ERROR padd: preprocess option failed on file %s\n", inputname); return 0; } } if(shift >= fout.NrBins) shift -= fout.NrBins; if(shift < 0) shift += fout.NrBins; if(noinput == 0 && currentfilenumber != 0) { if(read_profilePSRData(*fin[currentfilenumber_index], Iprofile, NULL, 0, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Reading pulse profile failed."); return 0; } do { ShiftProfile(shift, fout.NrBins, Iprofile, shiftedProfile); PlotProfile(fout.NrBins, Iprofile_firstfile, "Bin number", "Intensity", "Click to shift profile, press s to stop", 0, 1, 1); PlotProfile(fout.NrBins, shiftedProfile, "", "", "", 0, 2, 0); j = 0; do { if(j == 0) ppgband(0, 0, 0.0, 0.0, &x, &y, &singlechar); else ppgband(4, 0, bin1, 0.0, &x, &y, &singlechar); if(singlechar == 65) { if(j == 0) bin1 = x; else bin2 = x; j++; }else if(singlechar == 115 || singlechar ==83 ) { j = 10; } }while(j < 2); if(j < 10) { shift += bin2 - bin1; if(shift >= fout.NrBins) shift -= fout.NrBins; if(shift < 0) shift += fout.NrBins; } }while(j < 10); } if(shift != 0) { if(continuous_shift(*fin[currentfilenumber_index], &clone, shift, circularShift, "padd", MEMORY_format, 0, NULL, application.verbose_state, application.verbose_state.debug) != 1) { printerror(application.verbose_state.debug, "ERROR padd: circular shift failed."); } swap_orig_clone(fin[currentfilenumber_index], &clone, application.verbose_state); } long nrPulsesInCurFile; nrPulsesInCurFile = fin[currentfilenumber_index]->NrSubints; if(shift == 0 && circularShift == 0) nrPulsesInCurFile -= 1; for(nsub = 0; nsub < nrPulsesInCurFile; nsub++) { int nrpolsinloop; nrpolsinloop = fout.NrPols; if(poladd) { nrpolsinloop = 1; } for(pol = 0; pol < nrpolsinloop; pol++) { for(fchan = 0; fchan < fin[currentfilenumber_index]->NrFreqChan; fchan++) { if(readPulsePSRData(fin[currentfilenumber_index], nsub, pol, fchan, 0, fin[currentfilenumber_index]->NrBins, Iprofile, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Read error"); return 0; } if(sumNsub == 1) { if(poladd == 0 && freqadd == 0) { if(writePulsePSRData(&fout, currentOutputSubint, pol, fchan, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Write error"); return 0; } }else { if(poladd) { if(writePulsePSRData(&fout, nsub, currentfilenumber, fchan, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Write error"); return 0; } }else if(freqadd) { if(writePulsePSRData(&fout, nsub, pol, fchan+fchan_offset, 0, fout.NrBins, Iprofile, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Write error"); return 0; } } } subintWritten = 1; }else { float_ptr = &subint[fout.NrBins*(pol+fout.NrPols*fchan)]; float_ptr2 = Iprofile; if(curNrInsubint == 0) { for(binnr = 0; binnr < fout.NrBins; binnr++) { *float_ptr = *float_ptr2; float_ptr++; float_ptr2++; } }else { for(binnr = 0; binnr < fout.NrBins; binnr++) { *float_ptr += *float_ptr2; float_ptr++; float_ptr2++; } } if(curNrInsubint == sumNsub - 1) { if(writePulsePSRData(&fout, currentOutputSubint, pol, fchan, 0, fout.NrBins, float_ptr-fout.NrBins, application.verbose_state) != 1) { printerror(application.verbose_state.debug, "ERROR padd: Write error"); return 0; } subintWritten = 1; } } } } curNrInsubint++; if(subintWritten) { subintWritten = 0; curNrInsubint = 0; currentOutputSubint++; } if(application.verbose_state.nocounters == 0) { printf("Processing input file %d: %.1f%% \r", currentfilenumber+1, (100.0*(nsub+1))/(float)(fin[currentfilenumber_index]->NrSubints)); fflush(stdout); } } if(freqadd) { fchan_offset += fin[currentfilenumber_index]->NrFreqChan; } if(application.verbose_state.nocounters == 0) { printf("Processing file %d is done (%s). \n", currentfilenumber+1, fin[currentfilenumber_index]->filename); } closePSRData(fin[currentfilenumber_index], 0, application.verbose_state); currentfilenumber++; } closePSRData(&fout, 0, application.verbose_state); if(noinput == 0) ppgend(); free(Iprofile); if(noinput == 0) { free(shiftedProfile); free(Iprofile_firstfile); } if(sumNsub > 1) free(subint); for(i = 0; i < nrinputfiles; i++) { free(fin[i]); } free(fin); free(sort_indx); terminateApplication(&application); return 0; } int CheckOnPulse(int bin, int NrRegions, int Regions[MaxNrOnpulseRegions][2]) { int i; for(i = 0; i < NrRegions; i++) { if(bin >= Regions[i][0] && bin <= Regions[i][1]) return i+1; } return 0; } void PlotProfile(int NrBins, float *Ipulse, char *xlabel, char *ylabel, char *title, int Highlight, int color, int clearPage) { long j; float ymin, ymax; ymin = ymax = Ipulse[0]; for(j = 1; j < NrBins; j++) { if(Ipulse[j] > ymax) ymax = Ipulse[j]; if(Ipulse[j] < ymin) ymin = Ipulse[j]; } if(clearPage) { ppgpage(); ppgsci(1); ppgsvp(0.1, 0.9, 0.1, 0.9); ppgswin(0,NrBins-1,-0.1,1.1); ppgbox("bcnsti",0.0,0,"bcnti",0.0,0); ppglab(xlabel, ylabel, title); } ppgsci(color); ppgmove(0, Ipulse[0]/ymax); for(j = 1; j < NrBins; j++) { if(Highlight != 0) ppgsci(color+CheckOnPulse(j,NrOnpulseRegions,OnPulseRegion)); else ppgsci(color); ppgdraw(j, Ipulse[j]/ymax); } ppgsci(1); } void ShiftProfile(int shift, int NrBins, float *Iprofile, float *outputProfile) { int b, b2; for(b = 0; b < NrBins; b++) { b2 = b+shift; if(b2 < 0) b2 += NrBins; if(b2 >= NrBins) b2 -= NrBins; outputProfile[b2] = Iprofile[b]; } }
{ "alphanum_fraction": 0.6622334238, "avg_line_length": 39.1350531108, "ext": "c", "hexsha": "3366c74756779708a5b0a05270297840533ab659", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_path": "src/prog/padd.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_path": "src/prog/padd.c", "max_line_length": 755, "max_stars_count": 5, "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_path": "src/prog/padd.c", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "num_tokens": 7244, "size": 25790 }
// ============================================================================= // == niw_sampled.h // == -------------------------------------------------------------------------- // == A class for a Normal Inverse-Wishart distribution // == -------------------------------------------------------------------------- // == Copyright 2013. MIT. All Rights Reserved. // == Written by Jason Chang 11-03-2013 // == -------------------------------------------------------------------------- // == If this code is used, the following should be cited: // == // == [1] J. Chang and J. W. Fisher II, "Parallel Sampling of DP Mixtures // == Models using Sub-Cluster Splits". Neural Information Processing // == Systems (NIPS 2013), Lake Tahoe, NV, USA, Dec 2013. // ============================================================================= #ifndef _NIW_SAMPLED_H_INCLUDED_ #define _NIW_SAMPLED_H_INCLUDED_ //#include "matrix.h" //#include "mex.h" #include <math.h> //#include "array.h" //#include "helperMEX.h" //#include "debugMEX.h" #include "dpmmSubclusters/normal.h" #include "dpmmSubclusters/linear_algebra.h" #include "dpmmSubclusters/myfuncs.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <Eigen/Cholesky> #include <vector> using std::vector; #ifndef pi #define pi 3.14159265 #endif #ifndef logpi #define logpi 1.144729885849 #endif class niw_sampled { gsl_rng *r; public: // prior hyperparameters double kappah; double nuh; arr(double) thetah; arr(double) Deltah; int D; int D2; // sufficient statistics of the observed data arr(double) t; arr(double) T; int N; // posterior hyperparameters double kappa; double nu; arr(double) theta; arr(double) Delta; arr(double) tempVec; arr(double) tempMtx; // instantiated gaussian parameters normal param; double logpmu_prior, logpmu_posterior; public: // -------------------------------------------------------------------------- // -- niw_sampled // -- constructor; initializes to empty // -------------------------------------------------------------------------- niw_sampled(); // -------------------------------------------------------------------------- // -- niw_sampled // -- copy constructor; // -------------------------------------------------------------------------- niw_sampled(const niw_sampled& that); // -------------------------------------------------------------------------- // -- operator= // -- assignment operator // -------------------------------------------------------------------------- niw_sampled& operator=(const niw_sampled& that); // -------------------------------------------------------------------------- // -- copy // -- returns a copy of this // -------------------------------------------------------------------------- void copy(const niw_sampled& that); // -------------------------------------------------------------------------- // -- niw_sampled // -- constructor; intializes to all the values given // -------------------------------------------------------------------------- niw_sampled(int _D, double _kappah, double _nuh, arr(double) _thetah, arr(double) _Deltah); // -------------------------------------------------------------------------- // -- ~niw_sampled // -- destructor // -------------------------------------------------------------------------- virtual ~niw_sampled(); // -------------------------------------------------------------------------- // -- ~cleanup // -- deletes all the memory allocated by this // -------------------------------------------------------------------------- virtual void cleanup(); public: // -------------------------------------------------------------------------- // -- empty // -- Empties out the statistics of the niw_sampled (i.e. no data). // -------------------------------------------------------------------------- void clear(); void empty(); bool isempty() const; int getN() const; int getD() const; arr(double) get_mean() const; arr(double) get_cov() const; arr(double) get_prec() const; gsl_rng* get_r(); void set_normal(normal &other); void set_normal(arr(double) _mean, arr(double) _cov); normal* get_normal(); // -------------------------------------------------------------------------- // -- update_posteriors // -- Updates the posterior hyperparameters // -------------------------------------------------------------------------- void update_posteriors(); void update_posteriors_sample(); // -------------------------------------------------------------------------- // -- add_data // -- functions to add an observation to the niw_sampled. Updates the sufficient // -- statistics, posterior hyperparameters, and predictive parameters // -- // -- parameters: // -- - data : the new observed data point of size [1 D] // -------------------------------------------------------------------------- void add_data_init(arr(double) data); void add_data(arr(double) data); void merge_with(niw_sampled* &other, bool doSample); void merge_with(niw_sampled* &other1, niw_sampled* &other2, bool doSample); void merge_with(niw_sampled &other, bool doSample); void merge_with(niw_sampled &other1, niw_sampled &other2, bool doSample); void set_stats(int _N, arr(double) _t, arr(double) _T); double Jdivergence(const niw_sampled &other); double predictive_loglikelihood(arr(double) data) const; double predictive_loglikelihood_mode(arr(double) data) const; double data_loglikelihood() const; double data_loglikelihood_marginalized() const; double data_loglikelihood_marginalized_testmerge(niw_sampled *other) const; void sample(normal &_param); void sample_scale(normal &_param); void sample(); void find_mode(); double logmu_posterior(const normal &_param) const; double logmu_posterior() const; double logmu_prior(const normal &_param) const; double logmu_prior() const; }; inline double niw_sampled::predictive_loglikelihood(arr(double) data) const { return param.predictive_loglikelihood(data); } #endif
{ "alphanum_fraction": 0.4671672791, "avg_line_length": 33.8324324324, "ext": "h", "hexsha": "4e1aa02feaf0ebc0658348b47b30e33e536661ef", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": [ "MIT-feh" ], "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_path": "include/dpmmSubclusters/niw_sampled.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT-feh" ], "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_path": "include/dpmmSubclusters/niw_sampled.h", "max_line_length": 94, "max_stars_count": 11, "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": [ "MIT-feh" ], "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_path": "include/dpmmSubclusters/niw_sampled.h", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "num_tokens": 1237, "size": 6259 }
#include <limits.h> #include <asf.h> #include <asf_export.h> #include <asf_raster.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_statistics.h> /* Get sample size in bytes of the data types represented by the meta_parameters_t. */ size_t get_sample_size (meta_parameters *metadata) { size_t sample_size; switch ( metadata->general->data_type ) { case BYTE: sample_size = sizeof (int8_t); break; case INTEGER16: sample_size = sizeof (int16_t); break; case INTEGER32: sample_size = sizeof (int32_t); break; case REAL32: sample_size = sizeof (float); break; case REAL64: sample_size = sizeof (double); break; default: /* Other types aren't handled. */ asfPrintError ("This program can handle byte, int16, int32, real32, and real64 data types.\n"); sample_size = 0; // not reached } return sample_size; } /* Get the image data in data file image_data_file_name, using metadata metadata. A pointer to new memory containing the image data is returned. */ void * get_image_data (meta_parameters *metadata, const char *image_data_file) { size_t sample_size = get_sample_size (metadata); size_t pixel_count; void *data; size_t read_count; int return_code; /* Read the image data itself. */ FILE *ifp = fopen (image_data_file, "r"); if ( ifp == NULL ) asfPrintError("Failed to open %s: %s", image_data_file, strerror(errno)); /* Total number of samples in image. */ pixel_count = metadata->general->line_count * metadata->general->sample_count; data = MALLOC (pixel_count * sample_size); read_count = fread (data, sample_size, pixel_count, ifp); if ( read_count != pixel_count ) { if ( feof (ifp) ) { asfPrintError("Read wrong amount of data from %s", image_data_file); } else if ( ferror (ifp) ) { asfPrintError("Read of file %s failed: %s", image_data_file, strerror(errno)); } else { /* Shouldn't get here. */ asfPrintError("Unknown error reading %s\n", image_data_file); } exit (EXIT_FAILURE); } return_code = fclose (ifp); asfRequire ((return_code==0), "Error closing file %s\n", image_data_file); return data; } /* Return the average of all the kernel_size * kernel_size elements centered around element i, j. The i and j arguments must be within the bounds of img, and the kernel_size must be odd. The image is reflected at the edges and corners for the purpose of determining this average. */ unsigned char averaging_kernel (gsl_matrix_uchar *img, int kernel_size, size_t i, size_t j) { int i_idx, j_idx; int i_min = i - kernel_size / 2; int i_max = i + kernel_size / 2; int j_min = j - kernel_size / 2; int j_max = j + kernel_size / 2; int sum = 0; int average; /* Truncated average. */ asfRequire(kernel_size%2 != 0, "Odd-sized kernels only.\n"); for ( i_idx = i_min ; i_idx < i_max ; i_idx++ ) { /* The i index to use, adjusted in case we are off the edge of the image. This choice (and the corresponding choice for j) implement a kernel that pretends that a mirror image of the image exists at the image edges (and corners). */ int itu = i_idx; if ( itu < 0 ) itu = -itu - 1; else if ( itu >= img->size1 ) itu = img->size1 - (itu - img->size1) - 1; for ( j_idx = j_min ; j_idx < j_max ; j_idx++ ) { /* See the comment for variable itu above. */ int jtu = j_idx; if ( jtu < 0 ) jtu = -jtu - 1; else if ( jtu >= img->size2 ) jtu = img->size2 - (jtu - img->size2) - 1; sum += gsl_matrix_uchar_get (img, itu, jtu); } } average = sum / pow (kernel_size, 2); /* Truncated average. */ /* Since we are averaging unsigned char values, this should always be true. */ asfRequire(average<=UCHAR_MAX, "The average value of the image is above its maximum value.\n"); return average; } /* Average together tiles of kernel_size pixels in the *width by *height image at pixels, reducing its size by a factor of about kernel size in each dimension. The new image replaces the old in pixels (extra memory is freed) and a pointer to the possibly relocated pixel data is returned. The new image width and height replace the input width and height arguments. */ unsigned char *average_unsigned_char_pixels (unsigned char *pixels, unsigned long *width, unsigned long *height, int kernel_size) { /* Input width and height. */ size_t iwidth = *width, iheight = *height; gsl_matrix_uchar *iimg; size_t ii, jj; size_t owidth; size_t oheight; gsl_matrix_uchar *oimg; unsigned char *reallocated_pixels; asfRequire (kernel_size%2 != 0, "Odd-sized kernels only.\n"); /* Make a matrix form of the input image for easy indexing. */ iimg = gsl_matrix_uchar_alloc (iheight, iwidth); for ( ii = 0 ; ii < iheight ; ii++ ) { for ( jj = 0 ; jj < iwidth ; jj++ ) { gsl_matrix_uchar_set (iimg, ii, jj, pixels[ii * iwidth + jj]); } } /* Dimensions of the averaged image. */ owidth = ceil (iwidth / kernel_size); oheight = ceil (iheight / kernel_size); /* Form the output image. */ oimg = gsl_matrix_uchar_alloc (oheight, owidth); for ( ii = 0 ; ii < oheight ; ii++ ) { for ( jj = 0 ; jj < owidth ; jj++ ) { gsl_matrix_uchar_set (oimg, ii, jj, averaging_kernel (iimg, kernel_size, ii * kernel_size + kernel_size / 2, jj * kernel_size + kernel_size / 2)); } } /* Write output image back into pixel memory. */ for ( ii = 0 ; ii < oheight ; ii++ ) { for ( jj = 0 ; jj < owidth ; jj++ ) { pixels[ii * owidth + jj] = gsl_matrix_uchar_get (oimg, ii, jj); } } /* Done with matrix forms of the image. */ gsl_matrix_uchar_free (oimg); gsl_matrix_uchar_free (iimg); /* Modify the input/output arguments and resize the allocated space as promised. */ *width = owidth; *height = oheight; reallocated_pixels = realloc (pixels, owidth * oheight); return reallocated_pixels; } /* Given a block of pixel_count floats, map them linearly from range [max (minsample, mean - 3 * sigma), min (maxsample, mean + 3 * sigma)] into the unsigned char range, with input samples outside the above range clamped. Return the data in new malloc()ed memory. */ unsigned char *map_floats_to_unsigned_bytes (float *daf, size_t pixel_count) { unsigned char *pixels = malloc (pixel_count * sizeof (unsigned char)); /* Minimum and maximum values in the input data. */ float imin = gsl_stats_float_min (daf, 1, pixel_count); float imax = gsl_stats_float_max (daf, 1, pixel_count); /* Mean value of input data. */ float imean = gsl_stats_float_mean (daf, 1, pixel_count); /* Standard deviation of input data. */ float isdev = gsl_stats_float_sd (daf, 1, pixel_count); /* Minimum and maximum after clamping. */ float omin = GSL_MAX (imean - 3 * isdev, imin); float omax = GSL_MIN (imean + 3 * isdev, imax); /* Shift we need to apply to the data to get it to fall in the range of the unsigned chars. */ float bias = -omin + 0.25; /* Compute all the output pixels. */ size_t ii; for ( ii = 0 ; ii < pixel_count ; ii++ ) { if ( daf[ii] < omin ) { pixels[ii] = 0; /* Clamp low. */ } else if ( daf[ii] > omax ) { pixels[ii] = UCHAR_MAX; /* Clamp high. */ } else { pixels[ii] = (daf[ii] + bias) * (UCHAR_MAX / (omax - omin)); } } return pixels; } /* Scale the *width x *height image at pixels st its large dimension is less than or equal to max_large_dimension. The memory pointed to by pixels is resized and possible relocated, with the new location being returned. The new image width and height are returned in *width and *height. */ unsigned char *scale_unsigned_char_image_dimensions (unsigned char *pixels, unsigned long max_large_dimension, unsigned long *width, unsigned long *height) { /* This assertion is pretty obvious, but since the algorithm needs it to work correctly, its included. */ asfRequire(max_large_dimension>1, "Image needs to be at least one pixel by one pixel.\n"); if ( GSL_MAX (*width, *height) > max_large_dimension ) { int kernel_size = GSL_MAX (*width, *height) / max_large_dimension + 1; if ( kernel_size % 2 != 1 ) { kernel_size++; } pixels = average_unsigned_char_pixels (pixels, width, height, kernel_size); } return pixels; } /* Figure basic statistics for the image as needed for the different data scaling techniques available to the user */ void get_statistics (FloatImage *si, scale_t sample_mapping, int sampling_stride, float *mean, float *standard_deviation, float *min_sample, float *max_sample, float *omin, float *omax, gsl_histogram **hist, float no_data) { asfRequire(*max_sample >= *min_sample, "get_statistics() error ...max_sample parameter < min_sample parameter\n"); if ( sample_mapping == SIGMA ) { float_image_approximate_statistics (si, sampling_stride, mean, standard_deviation, no_data); *omin = *mean - 2 * (*standard_deviation); *omax = *mean + 2 * (*standard_deviation); } else if ( sample_mapping == MINMAX ) { float_image_statistics (si, min_sample, max_sample, mean, standard_deviation, no_data); *omin = *min_sample; *omax = *max_sample; } else if ( sample_mapping == HISTOGRAM_EQUALIZE ) { float_image_statistics (si, min_sample, max_sample, mean, standard_deviation, no_data); // Add a little bit of tail padding on the histgram to avoid problems // when searching for image min or max in the histogram (gsl histogram // limitation) //*omin = *min_sample * 0.025 * (*min_sample); //*omax = *max_sample * 0.025 * (*max_sample); // // NOTE: The above doesn't work properly for data with negative // values and also, I think the first multiply is a typo and that // a '+' was probably intended. If so, then the affect of the // above code is for the GSL increment (bin counting) function to // ignore values outside the adjusted min/max range, e.g. ignore // boundary case values (black and white noise tends to sum in the // limits, so ignoring the boundaries produces a higher quality // image.) // NOTE: The following assumes that the intent of the above code was // to ignore boundary case values, but the new histogram limits are // now calculated based on the full data range. float bin_range; bin_range = (*max_sample - *min_sample) / NUM_HIST_BINS; *omin = *min_sample + (0.025 * bin_range); *omax = *max_sample - (0.025 * bin_range); *hist = float_image_gsl_histogram (si, *omin, *omax, NUM_HIST_BINS); } } #ifndef linux #ifndef darwin #ifndef win32 static double round (double arg) { return floor (arg + 0.5); } #endif // #ifndef win32 #endif // #ifndef darwin #endif // #ifndef linux /* Create a byte value based on the floating point value and whatever scaling method the user chose */ unsigned char pixel_float2byte(float paf, scale_t sample_mapping, float omin, float omax, gsl_histogram *hist, gsl_histogram_pdf *hist_pdf, float no_data_value) { const unsigned char min_brightness=0; // Minimum brightess via byte const unsigned char max_brightness=UCHAR_MAX; // Maximum brightess via byte unsigned char pab = 0; // Pixel As Byte. size_t hist_bin; // histogram bin for given float value double slope, offset; // This case is easy -- always map the "no data" value to 0. if (paf == no_data_value) return 0; switch ( sample_mapping ) { case TRUNCATE: if ( paf <= (float) min_brightness ) { pab = min_brightness; } else if ( paf >= (float) max_brightness ) { pab = max_brightness; } else { pab = (unsigned char) paf; } break; case MINMAX: case MINMAX_MEDIAN: case SIGMA: slope = max_brightness / (omax-omin); offset = -slope * omin; if ((slope * paf + offset) < (float)min_brightness) pab = min_brightness; else if ((slope * paf + offset) > (float)max_brightness) pab = max_brightness; else pab = slope * paf + offset; break; case HISTOGRAM_EQUALIZE: // Since we used a mask when we called float_image_statistics() earlier, // we've got to account for it when writing the image out. The only way we // could think to do that was casting the mask value to byte :(. // // FIXME: The following cast of FLOAT_IMAGE_DEFAULT_MASK (currently equal // to 0.0) is incorrect for images such as DEMs and db's that contain // negative data. I'm voting for something similar, but force data values // sufficiently close to omin TO omin ...if we do any forcing at all. // SIDE EFFECTS: As-is, the following will result in black shot-noise and // 'topo line' type artifacts in images that contain negative data (in regions // where zero-crossings occur or in noise near 0.0) // if (0==gsl_fcmp(paf, FLOAT_IMAGE_DEFAULT_MASK, 0.00000000001)) { pab = (unsigned char)FLOAT_IMAGE_DEFAULT_MASK; } else { // Determine which bin the pixel-as-float is in if (paf <= gsl_histogram_min(hist)) { hist_bin = 0; } else if (paf >= gsl_histogram_max(hist)) { hist_bin = gsl_histogram_bins(hist) - 1; } else { // Pixel is within a valid range, so the following should not complain gsl_histogram_find (hist, paf, &hist_bin); } double pdf_at_index = gsl_histogram_get ((gsl_histogram*)hist_pdf, hist_bin); pab = (unsigned char)(max_brightness * pdf_at_index); } break; default: asfPrintError("Impossible: sample_mapping=%d\n", sample_mapping); break; } return pab; }
{ "alphanum_fraction": 0.6394912427, "avg_line_length": 34.4210526316, "ext": "c", "hexsha": "8808ba7d7d5234def7849b86f70c63e7dcc88b81", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_export/util.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_export/util.c", "max_line_length": 99, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_export/util.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 3793, "size": 14388 }
/** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_interp.h> #include "aXe_grism.h" #include "aXe_utils.h" #include "inout_aper.h" #include "aper_conf.h" #include "spc_spc.h" #include "spce_PET.h" #include "fringe_conf.h" #include "ipixcorr_utils.h" #define AXE_IMAGE_PATH "AXE_IMAGE_PATH" #define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH" #define AXE_CONFIG_PATH "AXE_CONFIG_PATH" int main (int argc, char *argv[]) { char *opt; char aper_file[MAXCHAR]; char aper_file_path[MAXCHAR]; char conf_file[MAXCHAR]; char conf_file_path[MAXCHAR]; char grism_file[MAXCHAR]; char grism_file_path[MAXCHAR]; char IPC_file[MAXCHAR]; char IPC_file_path[MAXCHAR]; char PET_file[MAXCHAR]; char PET_file_path[MAXCHAR]; char IPC_func[MAXCHAR]; char IPC_func_path[MAXCHAR]; char ID[60]; aperture_conf *conf; object **oblist; observation *obs = NULL; interpolator *ipcorr; int index; //int i; ap_pixel *PET; fitsfile *PET_ptr; fitsfile *IPC_ptr; FITScards *cards; int f_status=0; int bckmode = 0; int aperID=0, beamID=0; //int objindex; int spec_OAF=0; int point_like=0; int origname=0; beam act_beam; double max_ext; if ((argc < 3) || (opt = get_online_option ("help", argc, argv))) { fprintf (stdout, "aXe_FRINGECORR Version %s:\n",RELEASE); exit (1); } fprintf (stdout, "aXe_PETIPC: Starting...\n"); // reset the parameter index index = 0; // read in the grism image name strcpy(grism_file, argv[++index]); build_path (AXE_IMAGE_PATH, grism_file, grism_file_path); // read in the configuration file name strcpy(conf_file, argv[++index]); build_path (AXE_CONFIG_PATH, conf_file, conf_file_path); // load the configuration file conf = get_aperture_descriptor(conf_file_path); // determine the science extension number get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1); // Determine if we are using the special bck mode // In this mode, file names are handled diferently if ((opt = get_online_option("bck", argc, argv))) bckmode = 1; // determine whether the corrected PET should maintain the // filename of the original PET if ((opt = get_online_option("origname", argc, argv))) origname = 1; // get or set up the input OAF name if ((opt = get_online_option("in_OAF", argc, argv))) { // copy the parameter value if given strcpy(aper_file, opt); // mark that there is a special OAF file spec_OAF=1; } else { // copy the grism name and construct the name // if not given as parameter strcpy(aper_file, grism_file); replace_file_extension (grism_file, aper_file, ".fits", ".OAF", conf->science_numext); } build_path(AXE_OUTPUT_PATH, aper_file, aper_file_path); // get or set up the output PET name if ((opt = get_online_option("out_PET", argc, argv))) { // copy the parameter value if given strcpy(IPC_file, opt); } else { // copy the grism name and construct the name // if not given as parameter strcpy(IPC_file, grism_file); if (bckmode) replace_file_extension(grism_file, IPC_file, ".fits", "_ipc.BCK.PET.fits", conf->science_numext); else replace_file_extension(grism_file, IPC_file, ".fits", "_ipc.PET.fits", conf->science_numext); } build_path(AXE_OUTPUT_PATH, IPC_file, IPC_file_path); // get or set up the output PET name if ((opt = get_online_option("in_PET", argc, argv))) { // copy the parameter value if given strcpy(PET_file, opt); } else { // copy the grism name and construct the name // if not given as parameter strcpy(PET_file, grism_file); if (bckmode) replace_file_extension(grism_file, PET_file, ".fits", ".BCK.PET.fits", conf->science_numext); else replace_file_extension(grism_file, PET_file, ".fits", ".PET.fits", conf->science_numext); } build_path(AXE_OUTPUT_PATH, PET_file, PET_file_path); // Build the intrapixel correction file name sprintf(IPC_func,"%s",conf->IPIXfunc); // overwrite it with the parameter if given if ((opt = get_online_option ("IPIXFUNCTION", argc, argv))) strcpy(IPC_func,opt); if (!strcmp(IPC_file,"None")) // check whether the correction function is given; // complain if not given! aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETIPC: Correction function must be given!!\n"); else // compose the full pathname build_path (AXE_CONFIG_PATH, IPC_func, IPC_func_path); // get the maximum extension number if ((opt = get_online_option ("max_ext", argc, argv))) max_ext = atof(opt); else max_ext = 0.0; // check whether either max_ext is defined // OR a special OAF file is given if (!max_ext && !spec_OAF) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETIPC: Either maximum extension\n" "OR a special OAF file must be given!\n"); fprintf (stdout, "aXe_PETIPC: Grism file name: %s\n", grism_file_path); fprintf (stdout, "aXe_PETIPC: Configuration file name: %s\n", conf_file_path); fprintf (stdout, "aXe_PETIPC: Correction function: %s\n", IPC_func_path); fprintf (stdout, "aXe_PETIPC: Input OAF file name: %s\n", aper_file_path); fprintf (stdout, "aXe_PETIPC: Input PET file name: %s\n", PET_file_path); if (origname) fprintf (stdout, "aXe_PETIPC: Output PET file name: %s\n", PET_file_path); else fprintf (stdout, "aXe_PETIPC: Output PET file name: %s\n", IPC_file_path); fprintf (stdout, "aXe_PETIPC: Maximal extension for point objects: %f\n", max_ext); // load the aperture list fprintf (stdout, "aXe_PETIPC: Loading object aperture list..."); fflush(stdout); oblist = file_to_object_list_seq (aper_file_path, obs); fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist)); fflush(stdout); // Open the PET file for reading fits_open_file (&PET_ptr, PET_file_path, READONLY, &f_status); if (f_status) { ffrprt (stdout, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETIPC: Could not open file: %s\n", PET_file_path); } // open the output PET file IPC_ptr = create_PET_opened(IPC_file_path,1); // copy the keywords from the input // to the output PET cards = get_FITS_cards_opened(PET_ptr); put_FITS_cards_opened(IPC_ptr, cards); free_FITScards(cards); // create an interpolator reading in the fits file ipcorr = create_interp_ftable(IPC_func_path,2,"X","FX",IPCORR_INTERP_TYPE); while ((aperID!=-1) || (beamID!=-1)) { // Get the PET for this object PET = get_ALL_from_next_in_PET(PET_ptr, &aperID, &beamID); if ((aperID==-1) && (beamID==-1)) break; // PET is empty, skip it if (PET==NULL) { fprintf(stdout, "Empty PET BEAM %d%c...\n", aperID, BEAM(beamID)); continue; } // select the actual beam from the beam list act_beam = find_beam_in_object_list(oblist, aperID, beamID); // determine whether the object is pointlike point_like = is_pointlike(act_beam, spec_OAF, max_ext); if (point_like) { fprintf(stdout, "aXe_PETIPC: Correcting BEAM %d%c...\n", aperID, BEAM(beamID)); intpix_corr_pet(act_beam, conf_file_path, ipcorr, PET); } else { fprintf(stdout, "aXe_PETIPC: Skipping BEAM %d%c...\n", aperID, BEAM(beamID)); } sprintf(ID, "%d%c", aperID, BEAM (beamID)); add_ALL_to_PET(PET, ID, IPC_ptr, 0); /* Copy header from OPET extension into this SPC extension */ cards = get_FITS_cards_opened(PET_ptr); put_FITS_cards_opened(IPC_ptr,cards); free_FITScards(cards); if (PET!=NULL) free(PET); } // free the object list if (oblist!=NULL) free_oblist (oblist); // free the interpolator free_interp(ipcorr); // free the configuration structure free_aperture_conf(conf); fits_close_file (PET_ptr, &f_status); if (f_status) { ffrprt (stderr, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETIPC: " "Error closing PET: %s\n", PET_file_path); } fits_close_file (IPC_ptr, &f_status); if (f_status) { ffrprt (stderr, f_status); aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_PETIPC: " "Error closing PET: %s\n", IPC_file_path); } // check whether the old // PET name should be retained if (origname) { // delete the original // PET file if (remove(PET_file_path) != 0) fprintf (stdout, "aXe_PETIPC: Problems deleting %s!\n", PET_file_path); // rename the corrcted PET file if (rename(IPC_file_path, PET_file_path) !=0) fprintf (stdout, "aXe_PETIPC: Problems renaming %s to %s!\n", IPC_file_path, PET_file_path); } // say goodbye fprintf (stdout, "aXe_PETIPC: Done...\n"); exit (0); }
{ "alphanum_fraction": 0.6585150914, "avg_line_length": 26.2369942197, "ext": "c", "hexsha": "c6c2c0ce35de3100979bb11bb22fe19cdb8f2d1b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/aXe_PETIPC.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/aXe_PETIPC.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/aXe_PETIPC.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2639, "size": 9078 }
/* Copyright 2017 Jiawei Chiu 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 <algorithm> #include <array> #include <chrono> #include <cmath> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <memory> #include <random> #include <sstream> #include <string> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <cublas_v2.h> #include <cuda_runtime.h> #include <curand.h> #include <cusolverDn.h> #include <cusparse.h> // When BLAS functions are missing, we fallback on Eigen. #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/SparseCore> #include <cublas_v2.h> // #include <magma_lapack.h> #include <magma_v2.h> #include <lapacke.h> namespace gi { using std::abs; using std::cout; using std::ifstream; using std::istream; using std::istringstream; using std::max; using std::min; using std::ostream; using std::ofstream; using std::ostringstream; using std::sqrt; using std::string; using std::unique_ptr; using std::vector; void MainInit(int argc, char **argv); class Timer { public: Timer(); void reset(); double elapsed() const; private: typedef std::chrono::high_resolution_clock clock_; typedef std::chrono::duration<double, std::ratio<1> > second_; std::chrono::time_point<clock_> beg_; }; struct EngineOptions { int omp_num_threads = 1; int device = 0; // For GPU device. int num_streams = 4; // Number of CUDA streams. int rng_seed = 56150941; }; #define CUDA_CALL(x) \ { CHECK_EQ(x, cudaSuccess) << "CUDA error: " << x; } #define CURAND_CALL(x) \ { CHECK_EQ(x, CURAND_STATUS_SUCCESS) << "CURAND error: " << x; } #define CUBLAS_CALL(x) \ { CHECK_EQ(x, CUBLAS_STATUS_SUCCESS) << "CUBLAS error: " << x; } #define CUSOLVER_CALL(x) \ { CHECK_EQ(x, CUSOLVER_STATUS_SUCCESS) << "CUSOLVER error: " << x; } #define CUSPARSE_CALL(x) \ { CHECK_EQ(x, CUSPARSE_STATUS_SUCCESS) << "CUSPARSE error: " << x; } class Engine { public: Engine(const EngineOptions &opt); ~Engine(); static Engine *instance() { return instance_; } static cudaStream_t stream(int i) { return instance()->stream_[i]; } static curandGenerator_t curand() { return instance()->curand_; } static cublasHandle_t cublas() { return instance()->cublas_; } static cusparseHandle_t cusparse() { return instance()->cusparse_; } static cusparseMatDescr_t cusparse_desc() { return instance()->cusparse_desc_; } static cusolverDnHandle_t cusolver_dn() { return instance()->cusolver_dn_; } static std::mt19937 &rng() { return instance()->rng_; } static float *device_s_one() { return instance()->device_s_one_; } static float *device_s_zero() { return instance()->device_s_zero_; } private: vector<cudaStream_t> stream_; curandGenerator_t curand_; cublasHandle_t cublas_; cusparseHandle_t cusparse_; cusparseMatDescr_t cusparse_desc_; cusolverDnHandle_t cusolver_dn_; std::mt19937 rng_; float *device_s_one_; float *device_s_zero_; static Engine *instance_; }; // Some convenience functions for GPU kernels. // Returns number of blocks and number of threads given n things to work on. void BlocksThreads(int max_blocks, int max_threads, int n, int *num_blocks, int *num_threads); }
{ "alphanum_fraction": 0.6741879494, "avg_line_length": 28.4014084507, "ext": "h", "hexsha": "636401312e8d5e74e20417daba7bd127b11e26ab", "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": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "tinkerstash/gpuimpute", "max_forks_repo_path": "base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "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": "tinkerstash/gpuimpute", "max_issues_repo_path": "base.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "185609b9f2a8cfa45ee2054b0404bb03aaa71dad", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "tinkerstash/gpuimpute", "max_stars_repo_path": "base.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 984, "size": 4033 }
/* ode-initval/test.c * * Copyright (C) 2009, 2010 Tuomo Keskitalo * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Some functions and tests based on test.c by G. Jungman. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_odeiv2.h> #include "odeiv_util.h" /* Maximum number of ODE equations */ #define MAXEQ 15 /* Maximum number of ODE solvers */ #define MAXNS 20 /* Track number of function and jacobian evaluations in tests with global variables */ int nfe; int nje; /**********************************************************/ /* ODE test system definitions */ /**********************************************************/ /* RHS for f=2. Solution y = 2 * t + t0 */ int rhs_linear (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = 2.0; return GSL_SUCCESS; } int jac_linear (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = 0.0; dfdt[0] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_lin = { rhs_linear, jac_linear, 1, 0 }; /* RHS for f=y. Equals y=exp(t) with initial value y(0)=1.0 */ int rhs_exp (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = y[0]; return GSL_SUCCESS; } int jac_exp (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = y[0]; dfdt[0] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_exp = { rhs_exp, jac_exp, 1, 0 }; int rhs_sin (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = -y[1]; f[1] = y[0]; return GSL_SUCCESS; } int jac_sin (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = 0.0; dfdy[1] = -1.0; dfdy[2] = 1.0; dfdy[3] = 0.0; dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_sin = { rhs_sin, jac_sin, 2, 0 }; /* Sine/cosine with random failures */ static int rhs_xsin_reset = 0; static int jac_xsin_reset = 0; int rhs_xsin (double t, const double y[], double f[], void *params) { static int n = 0, m = 0; extern int nfe; nfe += 1; if (rhs_xsin_reset) { rhs_xsin_reset = 0; n = 0; m = 1; } n++; if (n >= m) { m = n * 1.3; return GSL_EFAILED; } if (n > 40 && n < 65) { f[0] = GSL_NAN; f[1] = GSL_NAN; return GSL_EFAILED; } f[0] = -y[1]; f[1] = y[0]; return GSL_SUCCESS; } int jac_xsin (double t, const double y[], double *dfdy, double dfdt[], void *params) { static int n = 0; extern int nje; nje += 1; if (jac_xsin_reset) { jac_xsin_reset = 0; n = 0; } n++; if (n > 50 && n < 55) { dfdy[0] = GSL_NAN; dfdy[1] = GSL_NAN; dfdy[2] = GSL_NAN; dfdy[3] = GSL_NAN; dfdt[0] = GSL_NAN; dfdt[1] = GSL_NAN; return GSL_EFAILED; } dfdy[0] = 0.0; dfdy[1] = -1.0; dfdy[2] = 1.0; dfdy[3] = 0.0; dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_xsin = { rhs_xsin, jac_xsin, 2, 0 }; /* RHS for classic stiff example dy0 / dt = 998 * y0 + 1998 * y1 y0(0) = 1.0 dy1 / dt = -999 * y0 - 1999 * y1 y1(0) = 0.0 solution is y0 = 2 * exp(-t) - exp(-1000 * t) y1 = - exp(-t) + exp(-1000 * t) */ int rhs_stiff (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = 998.0 * y[0] + 1998.0 * y[1]; f[1] = -999.0 * y[0] - 1999.0 * y[1]; return GSL_SUCCESS; } int jac_stiff (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = 998.0; dfdy[1] = 1998.0; dfdy[2] = -999.0; dfdy[3] = -1999.0; dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_stiff = { rhs_stiff, jac_stiff, 2, 0 }; /* Cosine function */ int rhs_cos (double t, const double *y, double *dydt, void *params) { dydt[0] = cos (t); return GSL_SUCCESS; } int jac_cos (double t, const double y[], double *dfdy, double dfdt[], void *params) { dfdy[0] = 0.0; dfdt[0] = -sin (t); return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_cos = { rhs_cos, jac_cos, 1, 0 }; /* Broken problem for testing numerical problems in user function that leads to decrease of step size in gsl_odeiv2_evolve below machine precision. */ int rhs_broken (double t, const double y[], double f[], void *params) { if (t < 10.0) { f[0] = 1.0; } else { f[0] = GSL_NAN; return 123; } return GSL_SUCCESS; } int jac_broken (double t, const double y[], double *dfdy, double dfdt[], void *params) { if (t < 10.0) { dfdy[0] = 0.0; dfdt[0] = 0.0; } else { dfdy[0] = GSL_NAN; dfdt[0] = GSL_NAN; return 123; } return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_broken = { rhs_broken, jac_broken, 1, 0 }; /* Immediate user break (at t > 1.5) test sine system */ int rhs_sin_ub (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = -y[1]; f[1] = y[0]; if (t > 1.5) { return GSL_EBADFUNC; } return GSL_SUCCESS; } int jac_sin_ub (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = 0.0; dfdy[1] = -1.0; dfdy[2] = 1.0; dfdy[3] = 0.0; dfdt[0] = 0.0; dfdt[1] = 0.0; if (t > 1.5) { return GSL_EBADFUNC; } return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_sin_ub = { rhs_sin_ub, jac_sin_ub, 2, 0 }; /* Badly scaled random function */ int rhs_br (double t, const double *y, double *dydt, void *params) { dydt[0] = (rand () - RAND_MAX / 2) * 2e100; return GSL_SUCCESS; } int jac_br (double t, const double y[], double *dfdy, double dfdt[], void *params) { dfdy[0] = (rand () - RAND_MAX / 2) * 2e100; dfdt[0] = (rand () - RAND_MAX / 2) * 2e100; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_br = { rhs_br, jac_br, 1, 0 }; /* stepfn and stepfn2 based on testcases from Frank Reininghaus <frank78ac@googlemail.com> */ /* Derivative change at t=0, small derivative */ int rhs_stepfn (double t, const double *y, double *dydt, void *params) { if (t >= 1.0) dydt[0] = 1; else dydt[0] = 0; return GSL_SUCCESS; } int jac_stepfn (double t, const double y[], double *dfdy, double dfdt[], void *params) { dfdy[0] = 0.0; dfdt[0] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_stepfn = { rhs_stepfn, jac_stepfn, 1, 0 }; /* Derivative change at t=0, large derivative */ int rhs_stepfn2 (double t, const double *y, double *dydt, void *params) { if (t >= 0.0) dydt[0] = 1e300; else dydt[0] = 0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_stepfn2 = { rhs_stepfn2, jac_stepfn, 1, 0 }; /* Volterra-Lotka predator-prey model f0 = (a - b * y1) * y0 y0(0) = 2.725 f1 = (-c + d * y0) * y1 y1(0) = 1.0 */ int rhs_vl (double t, const double y[], double f[], void *params) { const double a = -1.0; const double b = -1.0; const double c = -2.0; const double d = -1.0; extern int nfe; nfe += 1; f[0] = (a - b * y[1]) * y[0]; f[1] = (-c + d * y[0]) * y[1]; return GSL_SUCCESS; } int jac_vl (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double a = -1.0; const double b = -1.0; const double c = -2.0; const double d = -1.0; extern int nje; nje += 1; dfdy[0] = a - b * y[1]; dfdy[1] = -b * y[0]; dfdy[2] = d * y[1]; dfdy[3] = -c + d * y[0]; dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_vl = { rhs_vl, jac_vl, 2, 0 }; /* van Der Pol oscillator f0 = y1 y0(0) = 1.0 f1 = -y0 + mu * y1 * (1 - y0^2) y1(0) = 0.0 */ int rhs_vanderpol (double t, const double y[], double f[], void *params) { const double mu = 10.0; extern int nfe; nfe += 1; f[0] = y[1]; f[1] = -y[0] + mu * y[1] * (1.0 - y[0] * y[0]); return GSL_SUCCESS; } int jac_vanderpol (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double mu = 10.0; extern int nje; nje += 1; dfdy[0] = 0.0; dfdy[1] = 1.0; dfdy[2] = -2.0 * mu * y[0] * y[1] - 1.0; dfdy[3] = mu * (1.0 - y[0] * y[0]); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_vanderpol = { rhs_vanderpol, jac_vanderpol, 2, 0 }; /* Stiff trigonometric example f0 = -50 * (y0 - cos(t)) y0(0) = 0.0 */ int rhs_stifftrig (double t, const double y[], double f[], void *params) { extern int nfe; nfe += 1; f[0] = -50 * (y[0] - cos (t)); return GSL_SUCCESS; } int jac_stifftrig (double t, const double y[], double *dfdy, double dfdt[], void *params) { extern int nje; nje += 1; dfdy[0] = -50; dfdt[0] = -50 * sin (t); return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_stifftrig = { rhs_stifftrig, jac_stifftrig, 1, 0 }; /* The Oregonator - chemical Belusov-Zhabotinskii reaction y0(0) = 1.0, y1(0) = 2.0, y2(0) = 3.0 */ int rhs_oregonator (double t, const double y[], double f[], void *params) { const double c1 = 77.27; const double c2 = 8.375e-6; const double c3 = 0.161; extern int nfe; nfe += 1; f[0] = c1 * (y[1] + y[0] * (1 - c2 * y[0] - y[1])); f[1] = 1 / c1 * (y[2] - y[1] * (1 + y[0])); f[2] = c3 * (y[0] - y[2]); return GSL_SUCCESS; } int jac_oregonator (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double c1 = 77.27; const double c2 = 8.375e-6; const double c3 = 0.161; extern int nje; nje += 1; dfdy[0] = c1 * (1 - 2 * c2 * y[0] - y[1]); dfdy[1] = c1 * (1 - y[0]); dfdy[2] = 0.0; dfdy[3] = 1 / c1 * (-y[1]); dfdy[4] = 1 / c1 * (-1 - y[0]); dfdy[5] = 1 / c1; dfdy[6] = c3; dfdy[7] = 0.0; dfdy[8] = -c3; dfdt[0] = 0.0; dfdt[1] = 0.0; dfdt[2] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_oregonator = { rhs_oregonator, jac_oregonator, 3, 0 }; /* E5 - a stiff badly scaled chemical problem by Enright, Hull & Lindberg (1975): Comparing numerical methods for stiff systems of ODEs. BIT, vol. 15, pp. 10-48. f0 = -a * y0 - b * y0 * y2 y0(0) = 1.76e-3 f1 = a * y0 - m * c * y1 * y2 y1(0) = 0.0 f2 = a * y0 - b * y0 * y2 - m * c * y1 * y2 + c * y3 y2(0) = 0.0 f3 = b * y0 * y2 - c * y3 y3(0) = 0.0 */ int rhs_e5 (double t, const double y[], double f[], void *params) { const double a = 7.89e-10; const double b = 1.1e7; const double c = 1.13e3; const double m = 1.0e6; extern int nfe; nfe += 1; f[0] = -a * y[0] - b * y[0] * y[2]; f[1] = a * y[0] - m * c * y[1] * y[2]; f[3] = b * y[0] * y[2] - c * y[3]; f[2] = f[1] - f[3]; return GSL_SUCCESS; } int jac_e5 (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double a = 7.89e-10; const double b = 1.1e7; const double c = 1.13e3; const double m = 1.0e6; extern int nje; nje += 1; dfdy[0] = -a - b * y[2]; dfdy[1] = 0.0; dfdy[2] = -b * y[0]; dfdy[3] = 0.0; dfdy[4] = a; dfdy[5] = -m * c * y[2]; dfdy[6] = -m * c * y[1]; dfdy[7] = 0.0; dfdy[8] = a - b * y[2]; dfdy[9] = -m * c * y[2]; dfdy[10] = -b * y[0] - m * c * y[1]; dfdy[11] = c; dfdy[12] = b * y[2]; dfdy[13] = 0.0; dfdy[14] = b * y[0]; dfdy[15] = -c; dfdt[0] = 0.0; dfdt[1] = 0.0; dfdt[2] = 0.0; dfdt[3] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_e5 = { rhs_e5, jac_e5, 4, 0 }; /* Chemical reaction system of H.H. Robertson (1966): The solution of a set of reaction rate equations. In: J. Walsh, ed.: Numer. Anal., an Introduction, Academ. Press, pp. 178-182. f0 = -a * y0 + b * y1 * y2 y0(0) = 1.0 f1 = a * y0 - b * y1 * y2 - c * y1^2 y1(0) = 0.0 f2 = c * y1^2 y2(0) = 0.0 */ int rhs_robertson (double t, const double y[], double f[], void *params) { const double a = 0.04; const double b = 1.0e4; const double c = 3.0e7; extern int nfe; nfe += 1; f[0] = -a * y[0] + b * y[1] * y[2]; f[2] = c * y[1] * y[1]; f[1] = -f[0] - f[2]; return GSL_SUCCESS; } int jac_robertson (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double a = 0.04; const double b = 1.0e4; const double c = 3.0e7; extern int nje; nje += 1; dfdy[0] = -a; dfdy[1] = b * y[2]; dfdy[2] = b * y[1]; dfdy[3] = a; dfdy[4] = -b * y[2] - 2 * c * y[1]; dfdy[5] = -b * y[1]; dfdy[6] = 0.0; dfdy[7] = 2 * c * y[1]; dfdy[8] = 0.0; dfdt[0] = 0.0; dfdt[1] = 0.0; dfdt[2] = 0.0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_robertson = { rhs_robertson, jac_robertson, 3, 0 }; /* A two-dimensional oscillating Brusselator system. f0 = a + y0^2 * y1 - (b + 1) * y0 y0(0) = 1.5 f1 = b * y0 - y0^2 * y1 y1(0) = 3.0 */ int rhs_brusselator (double t, const double y[], double f[], void *params) { const double a = 1.0; const double b = 3.0; extern int nfe; nfe += 1; f[0] = a + y[0] * y[0] * y[1] - (b + 1.0) * y[0]; f[1] = b * y[0] - y[0] * y[0] * y[1]; return GSL_SUCCESS; } int jac_brusselator (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double b = 3.0; extern int nje; nje += 1; dfdy[0] = 2 * y[0] * y[1] - (b + 1.0); dfdy[1] = y[0] * y[0]; dfdy[2] = b - 2 * y[0] * y[1]; dfdy[3] = -y[0] * y[0]; dfdt[0] = 0; dfdt[1] = 0; return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_brusselator = { rhs_brusselator, jac_brusselator, 2, 0 }; /* Ring Modulator, stiff ODE of dimension 15. Reference: Walter M. Lioen, Jacques J.B. de Swart, Test Set for Initial Value Problem Solvers, Release 2.1 September 1999, http://ftp.cwi.nl/IVPtestset/software.htm */ #define NRINGMOD 15 int rhs_ringmod (double t, const double y[], double f[], void *params) { const double c = 1.6e-8; const double cs = 2e-12; const double cp = 1e-8; const double r = 25e3; const double rp = 50e0; const double lh = 4.45e0; const double ls1 = 2e-3; const double ls2 = 5e-4; const double ls3 = 5e-4; const double rg1 = 36.3; const double rg2 = 17.3; const double rg3 = 17.3; const double ri = 5e1; const double rc = 6e2; const double gamma = 40.67286402e-9; const double delta = 17.7493332; const double pi = 3.141592653589793238462643383; const double uin1 = 0.5 * sin (2e3 * pi * t); const double uin2 = 2 * sin (2e4 * pi * t); const double ud1 = +y[2] - y[4] - y[6] - uin2; const double ud2 = -y[3] + y[5] - y[6] - uin2; const double ud3 = +y[3] + y[4] + y[6] + uin2; const double ud4 = -y[2] - y[5] + y[6] + uin2; const double qud1 = gamma * (exp (delta * ud1) - 1.0); const double qud2 = gamma * (exp (delta * ud2) - 1.0); const double qud3 = gamma * (exp (delta * ud3) - 1.0); const double qud4 = gamma * (exp (delta * ud4) - 1.0); extern int nfe; nfe += 1; f[0] = (y[7] - 0.5 * y[9] + 0.5 * y[10] + y[13] - y[0] / r) / c; f[1] = (y[8] - 0.5 * y[11] + 0.5 * y[12] + y[14] - y[1] / r) / c; f[2] = (y[9] - qud1 + qud4) / cs; f[3] = (-y[10] + qud2 - qud3) / cs; f[4] = (y[11] + qud1 - qud3) / cs; f[5] = (-y[12] - qud2 + qud4) / cs; f[6] = (-y[6] / rp + qud1 + qud2 - qud3 - qud4) / cp; f[7] = -y[0] / lh; f[8] = -y[1] / lh; f[9] = (0.5 * y[0] - y[2] - rg2 * y[9]) / ls2; f[10] = (-0.5 * y[0] + y[3] - rg3 * y[10]) / ls3; f[11] = (0.5 * y[1] - y[4] - rg2 * y[11]) / ls2; f[12] = (-0.5 * y[1] + y[5] - rg3 * y[12]) / ls3; f[13] = (-y[0] + uin1 - (ri + rg1) * y[13]) / ls1; f[14] = (-y[1] - (rc + rg1) * y[14]) / ls1; return GSL_SUCCESS; } int jac_ringmod (double t, const double y[], double *dfdy, double dfdt[], void *params) { const double c = 1.6e-8; const double cs = 2e-12; const double cp = 1e-8; const double r = 25e3; const double rp = 50e0; const double lh = 4.45e0; const double ls1 = 2e-3; const double ls2 = 5e-4; const double ls3 = 5e-4; const double rg1 = 36.3; const double rg2 = 17.3; const double rg3 = 17.3; const double ri = 5e1; const double rc = 6e2; const double gamma = 40.67286402e-9; const double delta = 17.7493332; const double pi = 3.141592653589793238462643383; const double uin2 = 2 * sin (2e4 * pi * t); const double ud1 = +y[2] - y[4] - y[6] - uin2; const double ud2 = -y[3] + y[5] - y[6] - uin2; const double ud3 = +y[3] + y[4] + y[6] + uin2; const double ud4 = -y[2] - y[5] + y[6] + uin2; const double qpud1 = gamma * delta * exp (delta * ud1); const double qpud2 = gamma * delta * exp (delta * ud2); const double qpud3 = gamma * delta * exp (delta * ud3); const double qpud4 = gamma * delta * exp (delta * ud4); extern int nje; size_t i; nje += 1; for (i = 0; i < NRINGMOD * NRINGMOD; i++) { dfdy[i] = 0.0; } dfdy[0 * NRINGMOD + 0] = -1 / (c * r); dfdy[0 * NRINGMOD + 7] = 1 / c; dfdy[0 * NRINGMOD + 9] = -0.5 / c; dfdy[0 * NRINGMOD + 10] = -dfdy[0 * NRINGMOD + 9]; dfdy[0 * NRINGMOD + 13] = dfdy[0 * NRINGMOD + 7]; dfdy[1 * NRINGMOD + 1] = dfdy[0 * NRINGMOD + 0]; dfdy[1 * NRINGMOD + 8] = dfdy[0 * NRINGMOD + 7]; dfdy[1 * NRINGMOD + 11] = dfdy[0 * NRINGMOD + 9]; dfdy[1 * NRINGMOD + 12] = dfdy[0 * NRINGMOD + 10]; dfdy[1 * NRINGMOD + 14] = dfdy[0 * NRINGMOD + 13]; dfdy[2 * NRINGMOD + 2] = (-qpud1 - qpud4) / cs; dfdy[2 * NRINGMOD + 4] = qpud1 / cs; dfdy[2 * NRINGMOD + 5] = -qpud4 / cs; dfdy[2 * NRINGMOD + 6] = (qpud1 + qpud4) / cs; dfdy[2 * NRINGMOD + 9] = 1 / cs; dfdy[3 * NRINGMOD + 3] = (-qpud2 - qpud3) / cs; dfdy[3 * NRINGMOD + 4] = -qpud3 / cs; dfdy[3 * NRINGMOD + 5] = qpud2 / cs; dfdy[3 * NRINGMOD + 6] = (-qpud2 - qpud3) / cs; dfdy[3 * NRINGMOD + 10] = -1 / cs; dfdy[4 * NRINGMOD + 2] = qpud1 / cs; dfdy[4 * NRINGMOD + 3] = -qpud3 / cs; dfdy[4 * NRINGMOD + 4] = (-qpud1 - qpud3) / cs; dfdy[4 * NRINGMOD + 6] = (-qpud1 - qpud3) / cs; dfdy[4 * NRINGMOD + 11] = 1 / cs; dfdy[5 * NRINGMOD + 2] = -qpud4 / cs; dfdy[5 * NRINGMOD + 3] = qpud2 / cs; dfdy[5 * NRINGMOD + 5] = (-qpud2 - qpud4) / cs; dfdy[5 * NRINGMOD + 6] = (qpud2 + qpud4) / cs; dfdy[5 * NRINGMOD + 12] = -1 / cs; dfdy[6 * NRINGMOD + 2] = (qpud1 + qpud4) / cp; dfdy[6 * NRINGMOD + 3] = (-qpud2 - qpud3) / cp; dfdy[6 * NRINGMOD + 4] = (-qpud1 - qpud3) / cp; dfdy[6 * NRINGMOD + 5] = (qpud2 + qpud4) / cp; dfdy[6 * NRINGMOD + 6] = (-qpud1 - qpud2 - qpud3 - qpud4 - 1 / rp) / cp; dfdy[7 * NRINGMOD + 0] = -1 / lh; dfdy[8 * NRINGMOD + 1] = dfdy[7 * NRINGMOD + 0]; dfdy[9 * NRINGMOD + 0] = 0.5 / ls2; dfdy[9 * NRINGMOD + 2] = -1 / ls2; dfdy[9 * NRINGMOD + 9] = -rg2 / ls2; dfdy[10 * NRINGMOD + 0] = -0.5 / ls3; dfdy[10 * NRINGMOD + 3] = 1 / ls3; dfdy[10 * NRINGMOD + 10] = -rg3 / ls3; dfdy[11 * NRINGMOD + 1] = dfdy[9 * NRINGMOD + 0]; dfdy[11 * NRINGMOD + 4] = dfdy[9 * NRINGMOD + 2]; dfdy[11 * NRINGMOD + 11] = dfdy[9 * NRINGMOD + 9]; dfdy[12 * NRINGMOD + 1] = dfdy[10 * NRINGMOD + 0]; dfdy[12 * NRINGMOD + 5] = dfdy[10 * NRINGMOD + 3]; dfdy[12 * NRINGMOD + 12] = dfdy[10 * NRINGMOD + 10]; dfdy[13 * NRINGMOD + 0] = -1 / ls1; dfdy[13 * NRINGMOD + 13] = -(ri + rg1) / ls1; dfdy[14 * NRINGMOD + 1] = dfdy[13 * NRINGMOD + 0]; dfdy[14 * NRINGMOD + 14] = -(rc + rg1) / ls1; for (i = 0; i < NRINGMOD; i++) { dfdt[i] = 0.0; } return GSL_SUCCESS; } gsl_odeiv2_system rhs_func_ringmod = { rhs_ringmod, jac_ringmod, NRINGMOD, NULL }; /**********************************************************/ /* Functions for carrying out tests */ /**********************************************************/ void test_odeiv_stepper (const gsl_odeiv2_step_type * T, const gsl_odeiv2_system * sys, const double h, const double t, const char desc[], const double ystart[], const double yfin[], const double relerr) { /* tests stepper T with one fixed length step advance of system sys and compares the result with given values yfin */ double y[MAXEQ] = { 0.0 }; double yerr[MAXEQ] = { 0.0 }; double scale_abs[MAXEQ]; size_t ne = sys->dimension; size_t i; gsl_odeiv2_driver *d; for (i = 0; i < MAXEQ; i++) { scale_abs[i] = 1.0; } d = gsl_odeiv2_driver_alloc_scaled_new (sys, T, h, relerr, relerr, 1.0, 0.0, scale_abs); DBL_MEMCPY (y, ystart, MAXEQ); { int s = gsl_odeiv2_step_apply (d->s, t, h, y, yerr, 0, 0, sys); if (s != GSL_SUCCESS) { gsl_test (s, "test_odeiv_stepper: %s step_apply returned %d", desc, s); } } for (i = 0; i < ne; i++) { gsl_test_rel (y[i], yfin[i], relerr, "%s %s step(%d)", gsl_odeiv2_step_name (d->s), desc, i); } gsl_odeiv2_driver_free (d); } void test_stepper (const gsl_odeiv2_step_type * T) { /* Tests stepper T with a step of selected systems */ double y[MAXEQ] = { 0.0 }; double yfin[MAXEQ] = { 0.0 }; /* Step length */ double h; /* Required tolerance */ double err_target; /* classic stiff */ h = 1e-7; err_target = 1e-4; y[0] = 1.0; y[1] = 0.0; { const double e1 = exp (-h); const double e2 = exp (-1000.0 * h); yfin[0] = 2.0 * e1 - e2; yfin[1] = -e1 + e2; } test_odeiv_stepper (T, &rhs_func_stiff, h, 0.0, "classic_stiff", y, yfin, err_target); /* linear */ h = 1e-1; err_target = 1e-10; y[0] = 0.58; yfin[0] = y[0] + 2 * h; test_odeiv_stepper (T, &rhs_func_lin, h, 0.0, "linear", y, yfin, err_target); /* exponential */ h = 1e-4; err_target = 1e-8; y[0] = exp (2.7); yfin[0] = exp (2.7 + h); test_odeiv_stepper (T, &rhs_func_exp, h, 2.7, "exponential", y, yfin, err_target); /* cosine-sine */ h = 1e-3; err_target = 1e-6; y[0] = cos (1.2); y[1] = sin (1.2); yfin[0] = cos (1.2 + h); yfin[1] = sin (1.2 + h); test_odeiv_stepper (T, &rhs_func_sin, h, 1.2, "cosine-sine", y, yfin, err_target); } void test_evolve_system (const gsl_odeiv2_step_type * T, const gsl_odeiv2_system * sys, double t0, double t1, double hstart, double y[], double yfin[], double err_target, const char *desc) { /* Tests system sys with stepper T. Step length is controlled by error estimation from the stepper. */ int steps = 0; size_t i; double t = t0; double h = hstart; /* Tolerance factor in testing errors */ const double factor = 10; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_standard_new (sys, T, h, err_target, err_target, 1.0, 0.0); double *y_orig = (double *) malloc (sys->dimension * sizeof (double)); int s = 0; extern int nfe, nje; nfe = 0; nje = 0; while (t < t1) { double t_orig = t; memcpy (y_orig, y, sys->dimension * sizeof (double)); s = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, sys, &t, t1, &h, y); #ifdef DEBUG printf ("test_evolve_system at: %.5e %.5e %.5e %d\n", t, y[0], y[1], gsl_odeiv2_step_order (d->s)); #endif if (s != GSL_SUCCESS) { /* check that t and y are unchanged */ gsl_test_abs (t, t_orig, 0.0, "%s t must be restored on failure", gsl_odeiv2_step_name (d->s)); for (i = 0; i < sys->dimension; i++) { gsl_test_abs (y[i], y_orig[i], 0.0, "%s y must be restored on failure", gsl_odeiv2_step_name (d->s), desc, i); } if (sys != &rhs_func_xsin) { /* apart from xsin, other functions should not return errors */ gsl_test (s, "%s evolve_apply returned %d", gsl_odeiv2_step_name (d->s), s); break; } } if (steps > 100000) { gsl_test (GSL_EFAILED, "%s evolve_apply reached maxiter", gsl_odeiv2_step_name (d->s)); break; } steps++; } gsl_test (s, "%s %s [%g,%g], %d steps (nfe %d, nje %d) completed", gsl_odeiv2_step_name (d->s), desc, t0, t1, steps, nfe, nje); /* err_target is target error of one step. Test if stepper has made larger error than (tolerance factor times) the number of steps times the err_target. */ for (i = 0; i < sys->dimension; i++) { gsl_test_abs (y[i], yfin[i], factor * d->e->count * err_target, "%s %s evolve(%d)", gsl_odeiv2_step_name (d->s), desc, i); } free (y_orig); gsl_odeiv2_driver_free (d); } int sys_driver (const gsl_odeiv2_step_type * T, const gsl_odeiv2_system * sys, double t0, double t1, double hstart, double y[], double epsabs, double epsrel, const char desc[]) { /* This function evolves a system sys with stepper T from t0 to t1. Step length is varied via error control with possibly different absolute and relative error tolerances. */ int s = 0; int steps = 0; double t = t0; double h = hstart; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_standard_new (sys, T, h, epsabs, epsrel, 1.0, 0.0); extern int nfe, nje; nfe = 0; nje = 0; while (t < t1) { s = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, sys, &t, t1, &h, y); #ifdef DEBUG printf ("sys_driver at: %.5e %.5e %.5e %d\n", t, y[0], y[1], gsl_odeiv2_step_order (d->s)); #endif if (s != GSL_SUCCESS) { gsl_test (s, "sys_driver: %s evolve_apply returned %d", gsl_odeiv2_step_name (d->s), s); break; } if (steps > 1e7) { gsl_test (GSL_EMAXITER, "sys_driver: %s evolve_apply reached maxiter at t=%g", gsl_odeiv2_step_name (d->s), t); s = GSL_EMAXITER; break; } steps++; } gsl_test (s, "%s %s [%g,%g], %d steps (nfe %d, nje %d) completed", gsl_odeiv2_step_name (d->s), desc, t0, t1, steps, nfe, nje); gsl_odeiv2_driver_free (d); return s; } void test_evolve_linear (const gsl_odeiv2_step_type * T, double h, double err) { /* Test linear evolve */ double y[1]; double yfin[1]; y[0] = 1.0; yfin[0] = 9.0; test_evolve_system (T, &rhs_func_lin, 0.0, 4.0, h, y, yfin, err, "linear[0,4]"); } void test_evolve_exp (const gsl_odeiv2_step_type * T, double h, double err) { /* Test exponential evolve */ double y[1]; double yfin[1]; y[0] = 1.0; yfin[0] = exp (2.0); test_evolve_system (T, &rhs_func_exp, 0.0, 2.0, h, y, yfin, err, "exp[0,2]"); } void test_evolve_sin (const gsl_odeiv2_step_type * T, double h, double err) { /* Test sinusoidal evolve */ double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; yfin[0] = cos (2.0); yfin[1] = sin (2.0); test_evolve_system (T, &rhs_func_sin, 0.0, 2.0, h, y, yfin, err, "sine[0,2]"); } void test_evolve_xsin (const gsl_odeiv2_step_type * T, double h, double err) { /* Test sinusoidal evolve including a failing window */ double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; yfin[0] = cos (2.0); yfin[1] = sin (2.0); rhs_xsin_reset = 1; jac_xsin_reset = 1; test_evolve_system (T, &rhs_func_xsin, 0.0, 2.0, h, y, yfin, err, "sine[0,2] w/errors"); } void test_evolve_stiff1 (const gsl_odeiv2_step_type * T, double h, double err) { /* Test classical stiff problem evolve, t=[0,1] */ double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; { double arg = 1.0; double e1 = exp (-arg); double e2 = exp (-1000.0 * arg); yfin[0] = 2.0 * e1 - e2; yfin[1] = -e1 + e2; } test_evolve_system (T, &rhs_func_stiff, 0.0, 1.0, h, y, yfin, err, "stiff[0,1]"); } void test_evolve_stiff5 (const gsl_odeiv2_step_type * T, double h, double err) { /* Test classical stiff problem evolve, t=[0,5] */ double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; { double arg = 5.0; double e1 = exp (-arg); double e2 = exp (-1000.0 * arg); yfin[0] = 2.0 * e1 - e2; yfin[1] = -e1 + e2; } test_evolve_system (T, &rhs_func_stiff, 0.0, 5.0, h, y, yfin, err, "stiff[0,5]"); } void test_evolve_negative_h (const gsl_odeiv2_step_type * T, double h, double err) { /* Test evolution in negative direction */ /* Tolerance factor in testing errors */ const double factor = 10; const gsl_odeiv2_system sys = rhs_func_cos; double t = 0; double t1 = -4.0; double y = 0.0; double yfin = sin (t1); gsl_odeiv2_driver *d; /* Make initial h negative */ h = -fabs (h); d = gsl_odeiv2_driver_alloc_standard_new (&sys, T, h, err, err, 1.0, 0.0); while (t > t1) { int status = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, &sys, &t, t1, &h, &y); if (status != GSL_SUCCESS) { gsl_test (status, "%s evolve_apply returned %d for negative h", gsl_odeiv2_step_name (d->s), status); break; } } gsl_test_abs (y, yfin, factor * d->e->count * err, "%s evolution with negative h", gsl_odeiv2_step_name (d->s)); gsl_odeiv2_driver_free (d); } void test_broken (const gsl_odeiv2_step_type * T, double h, double err) { /* Check for gsl_odeiv2_evolve_apply. The user function fails at t>=10, which in this test causes step size to decrease below machine precision and return with a failure code. */ /* Tolerance factor in testing errors */ const double factor = 10; const gsl_odeiv2_system sys = rhs_func_broken; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new (&sys, T, h, err, err); double t = 0; double t1 = 100.0; double y = 0.0; const double final_max_h = GSL_DBL_EPSILON; int status; while (t < t1) { status = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, &sys, &t, t1, &h, &y); if (status != GSL_SUCCESS) { break; } } gsl_test_abs (h + final_max_h, final_max_h, factor * final_max_h, "%s test_broken: step size at break point", gsl_odeiv2_step_name (d->s)); gsl_test_abs (t, 10.0, factor * err, "%s test_broken: point of break", gsl_odeiv2_step_name (d->s)); /* GSL_FAILURE results from stepper failure, 123 from user function */ if (status != GSL_FAILURE && status != 123) { gsl_test (status, "%s test_broken: evolve return value %d", gsl_odeiv2_step_name (d->s), status); } else { gsl_test (GSL_SUCCESS, "%s test_broken: evolve return value %d", gsl_odeiv2_step_name (d->s), status); } gsl_odeiv2_driver_free (d); } void test_stepsize_fail (const gsl_odeiv2_step_type * T, double h) { /* Check for gsl_odeiv2_evolve_apply. The user function works apparently fine (returns GSL_SUCCESS) but is faulty in this case. gsl_odeiv2_evolve_apply therefore decreases the step-size below machine precision and therefore stops with GSL_FAILURE. */ /* Error tolerance */ const double epsabs = 1e-16; const double epsrel = 1e-6; /* Tolerance factor in testing errors */ const double factor = 10; const double final_max_h = GSL_DBL_EPSILON; const gsl_odeiv2_system sys = rhs_func_br; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new (&sys, T, h, epsabs, epsrel); double t = 1.0; double t1 = 1e5; double y = 0.0; int status; while (t < t1) { status = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, &sys, &t, t1, &h, &y); if (status != GSL_SUCCESS) { break; } } gsl_test_abs (h + final_max_h, final_max_h, factor * final_max_h, "%s test_stepsize_fail: step size at break point", gsl_odeiv2_step_name (d->s)); gsl_test_abs (t, 1.0, 1e-6, "%s test_stepsize_fail: point of break", gsl_odeiv2_step_name (d->s)); gsl_test_int (status, GSL_FAILURE, "%s test_stepsize_fail: evolve return value", gsl_odeiv2_step_name (d->s)); gsl_odeiv2_driver_free (d); } void test_user_break (const gsl_odeiv2_step_type * T, double h) { /* Tests for user signaled immediate break */ const double tol = 1e-8; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new (&rhs_func_sin_ub, T, h, tol, tol); double y[] = { 1.0, 0.0 }; double t = 0.0; const double t1 = 8.25; int s = gsl_odeiv2_driver_apply (d, &t, t1, y); gsl_test ((s - GSL_EBADFUNC), "%s test_user_break returned %d", gsl_odeiv2_step_name (d->s), s); gsl_odeiv2_driver_free (d); } void test_stepfn (const gsl_odeiv2_step_type * T) { /* Test evolve on a small derivative change at t=0 */ double epsabs = 1e-16; double epsrel = 1e-6; const gsl_odeiv2_system sys = rhs_func_stepfn; double t = 0.0; double h = 1e-6; double y = 0.0; int i = 0; int status = 0; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new (&sys, T, h, epsabs, epsrel); while (t < 2 && i < 1000000) { status = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, &sys, &t, 2, &h, &y); #ifdef DEBUG printf ("test_stepfn at: i=%d status=%d t=%g h=%g y=%g\n", i, status, t, h, y); #endif if (status != GSL_SUCCESS) break; i++; } gsl_test (status, "evolve step function, return value (stepfn/%s): %d", gsl_odeiv2_step_name (d->s), status); gsl_test_abs (t, 2, 1e-16, "evolve step function, t (stepfn/%s)", gsl_odeiv2_step_name (d->s)); gsl_test_rel (y, 1, epsrel, "evolve step function, y (stepfn/%s)", gsl_odeiv2_step_name (d->s)); gsl_odeiv2_driver_free (d); } void test_stepfn2 (const gsl_odeiv2_step_type * T) { /* Test evolve on a large derivative change at t=0 */ double epsabs = 1e-16; double epsrel = 1e-6; const gsl_odeiv2_system sys = rhs_func_stepfn2; double t = -1.0; double h = 1e-6; double y = 0.0; int i = 0; int status; const int maxiter = 100000; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_yp_new (&sys, T, h, epsabs, epsrel); while (t < 1.0 && i < maxiter) { status = gsl_odeiv2_evolve_apply (d->e, d->c, d->s, &sys, &t, 1.0, &h, &y); #ifdef DEBUG printf ("test_stepfn2 at: i=%d status=%d t=%g h=%g y=%g\n", i, status, t, h, y); #endif if (status != GSL_SUCCESS) break; i++; } if (i >= maxiter) printf ("FAIL: evolve big step function, (stepfn2/%s) reached maxiter\n", gsl_odeiv2_step_name (d->s)); gsl_test_abs (t, 1.0, 1e-16, "evolve big step function, t (stepfn2/%s)", gsl_odeiv2_step_name (d->s)); gsl_test_rel (y, 1e300, epsrel, "evolve big step function, y (stepfn2/%s)", gsl_odeiv2_step_name (d->s)); gsl_odeiv2_driver_free (d); } void test_nonstiff_problems (void) { /* Compares output of non-stiff (or only moderately stiff) problems with several steppers */ const gsl_odeiv2_step_type *steppers[MAXNS]; /* Required error tolerance for each stepper. */ double err_target[MAXNS]; /* initial values for each ode-solver */ double y[MAXEQ * MAXNS]; size_t i, k, p; /* Number of problems to test */ #define CONST_NONSTIFF_NPROB 4 /* Problems, their names and number of equations */ const gsl_odeiv2_system *prob[] = { &rhs_func_vl, &rhs_func_vanderpol, &rhs_func_stifftrig, &rhs_func_brusselator }; const char *probname[] = { "volterra-lotka", "vanderpol", "stifftrig", "brusselator" }; const size_t sd[] = { 2, 2, 1, 2 }; /* Integration interval for problems */ const double start[CONST_NONSTIFF_NPROB] = { 0.0 }; const double end[] = { 9.0, 100.0, 1.5, 20.0 }; const double epsabs = 1e-8; const double epsrel = 1e-8; const double initstepsize = 1e-5; /* Steppers */ steppers[0] = gsl_odeiv2_step_rk4; err_target[0] = 1e-6; steppers[1] = gsl_odeiv2_step_rk2; err_target[1] = 1e-6; steppers[2] = gsl_odeiv2_step_rkf45; err_target[2] = 1e-6; steppers[3] = gsl_odeiv2_step_rkck; err_target[3] = 1e-6; steppers[4] = gsl_odeiv2_step_rk8pd; err_target[4] = 1e-6; steppers[5] = gsl_odeiv2_step_rk1imp; err_target[5] = 1e-3; steppers[6] = gsl_odeiv2_step_rk2imp; err_target[6] = 1e-5; steppers[7] = gsl_odeiv2_step_rk4imp; err_target[7] = 1e-6; steppers[8] = gsl_odeiv2_step_bsimp; err_target[8] = 1e-6; steppers[9] = gsl_odeiv2_step_msadams; err_target[9] = 1e-5; steppers[10] = gsl_odeiv2_step_msbdf; err_target[10] = 1e-5; steppers[11] = 0; /* Loop over problems */ for (p = 0; p < CONST_NONSTIFF_NPROB; p++) { /* Initialize */ for (i = 0; i < MAXNS * MAXEQ; i++) { y[i] = 0.0; } for (i = 0; i < MAXNS; i++) { switch (p) { case 0: y[i * sd[p]] = 2.725; y[i * sd[p] + 1] = 1.0; break; case 1: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 0.0; break; case 2: y[i * sd[p]] = 0.0; break; case 3: y[i * sd[p]] = 1.5; y[i * sd[p] + 1] = 3.0; break; default: gsl_test (GSL_EFAILED, "test_nonstiff_problems: initialization error\n"); return; } } /* Call each solver for the problem */ for (i = 0; steppers[i] != 0; i++) { int s = sys_driver (steppers[i], prob[p], start[p], end[p], initstepsize, &y[sd[p] * i], epsabs, epsrel, probname[p]); if (s != GSL_SUCCESS) { gsl_test (s, "test_nonstiff_problems %s %s", steppers[i]->name, probname[p]); } } /* Compare results */ for (i = 1; steppers[i] != 0; i++) for (k = 0; k < sd[p]; k++) { const double val1 = y[k]; const double val2 = y[sd[p] * i + k]; gsl_test_rel (val1, val2, (GSL_MAX (err_target[0], err_target[i])), "%s/%s %s [%d]", steppers[0]->name, steppers[i]->name, probname[p], k); } } } void test_stiff_problems (void) { /* Compares output of stiff problems with several steppers */ const gsl_odeiv2_step_type *steppers[MAXNS]; /* Required error tolerance for each stepper. */ double err_target[MAXNS]; /* initial values for each ode-solver */ double y[MAXEQ * MAXNS]; size_t i, k, p; /* Number of problems to test */ #define CONST_STIFF_NPROB 3 /* Problems, their names and number of equations */ const gsl_odeiv2_system *prob[] = { &rhs_func_oregonator, &rhs_func_e5, &rhs_func_robertson }; const char *probname[] = { "oregonator", "e5", "robertson" }; const size_t sd[] = { 3, 4, 3 }; /* Integration interval for problems */ const double start[CONST_STIFF_NPROB] = { 0.0 }; const double end[] = { 360.0, 1e4, 1e4 }; const double epsabs = 1e-40; const double epsrel = 1e-7; const double initstepsize = 1e-5; /* Steppers */ steppers[0] = gsl_odeiv2_step_bsimp; err_target[0] = 1e-6; steppers[1] = gsl_odeiv2_step_rk1imp; err_target[1] = 5e-3; steppers[2] = gsl_odeiv2_step_rk2imp; err_target[2] = 5e-5; steppers[3] = gsl_odeiv2_step_rk4imp; err_target[3] = 5e-5; steppers[4] = gsl_odeiv2_step_msbdf; err_target[4] = 1e-4; steppers[5] = 0; /* Loop over problems */ for (p = 0; p < CONST_STIFF_NPROB; p++) { /* Initialize */ for (i = 0; i < MAXNS * MAXEQ; i++) { y[i] = 0.0; } for (i = 0; i < MAXNS; i++) { switch (p) { case 0: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 2.0; y[i * sd[p] + 2] = 3.0; break; case 1: y[i * sd[p]] = 1.76e-3; y[i * sd[p] + 1] = 0.0; y[i * sd[p] + 2] = 0.0; y[i * sd[p] + 3] = 0.0; break; case 2: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 0.0; y[i * sd[p] + 2] = 0.0; break; default: gsl_test (GSL_EFAILED, "test_stiff_problems: initialization error\n"); return; } } /* Call each solver for the problem */ for (i = 0; steppers[i] != 0; i++) { int s = sys_driver (steppers[i], prob[p], start[p], end[p], initstepsize, &y[sd[p] * i], epsabs, epsrel, probname[p]); if (s != GSL_SUCCESS) { gsl_test (s, "test_stiff_problems %s %s", steppers[i]->name, probname[p]); } } /* Compare results */ for (i = 1; steppers[i] != 0; i++) for (k = 0; k < sd[p]; k++) { const double val1 = y[k]; const double val2 = y[sd[p] * i + k]; gsl_test_rel (val1, val2, (GSL_MAX (err_target[0], err_target[i])), "%s/%s %s [%d]", steppers[0]->name, steppers[i]->name, probname[p], k); } } } void test_extreme_problems (void) { /* Compares output of numerically particularly demanding problems with several steppers */ const gsl_odeiv2_step_type *steppers[MAXNS]; /* Required error tolerance for each stepper. */ double err_target[MAXNS]; /* initial values for each ode-solver */ double y[MAXEQ * MAXNS]; size_t i, k, p; /* Number of problems to test */ #define CONST_EXTREME_NPROB 3 /* Problems, their names and number of equations */ const gsl_odeiv2_system *prob[] = { &rhs_func_e5, &rhs_func_robertson, &rhs_func_ringmod }; const char *probname[] = { "e5_bigt", "robertson_bigt", "ringmod" }; const size_t sd[] = { 4, 3, NRINGMOD }; /* Integration interval for problems */ const double start[CONST_EXTREME_NPROB] = { 0.0 }; const double end[CONST_EXTREME_NPROB] = { 1e11, 1e11, 1e-5 }; const double epsabs[CONST_EXTREME_NPROB] = { 1e1 * GSL_DBL_MIN, 1e1 * GSL_DBL_MIN, 1e-12 }; const double epsrel[CONST_EXTREME_NPROB] = { 1e-12, 1e-12, 1e-12 }; const double initstepsize[CONST_EXTREME_NPROB] = { 1e-5, 1e-5, 1e-10 }; /* Steppers */ steppers[0] = gsl_odeiv2_step_bsimp; err_target[0] = 1e-3; steppers[1] = gsl_odeiv2_step_msbdf; err_target[1] = 1e-3; steppers[2] = 0; /* Loop over problems */ for (p = 0; p < CONST_EXTREME_NPROB; p++) { /* Initialize */ for (i = 0; i < MAXNS * MAXEQ; i++) { y[i] = 0.0; } for (i = 0; i < MAXNS; i++) { switch (p) { case 0: y[i * sd[p]] = 1.76e-3; y[i * sd[p] + 1] = 0.0; y[i * sd[p] + 2] = 0.0; y[i * sd[p] + 3] = 0.0; break; case 1: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 0.0; y[i * sd[p] + 2] = 0.0; break; case 2: { size_t j; for (j = 0; j < NRINGMOD; j++) { y[i * sd[p] + j] = 0.0; } } break; default: gsl_test (GSL_EFAILED, "test_extreme_problems: initialization error\n"); return; } } /* Call each solver for the problem */ for (i = 0; steppers[i] != 0; i++) { int s = sys_driver (steppers[i], prob[p], start[p], end[p], initstepsize[p], &y[sd[p] * i], epsabs[p], epsrel[p], probname[p]); if (s != GSL_SUCCESS) { printf ("start=%.5e, initstepsize=%.5e\n", start[p], initstepsize[p]); gsl_test (s, "test_extreme_problems %s %s", steppers[i]->name, probname[p]); } } /* Compare results */ for (i = 1; steppers[i] != 0; i++) for (k = 0; k < sd[p]; k++) { const double val1 = y[k]; const double val2 = y[sd[p] * i + k]; gsl_test_rel (val1, val2, (GSL_MAX (err_target[0], err_target[i])), "%s/%s %s [%d]", steppers[0]->name, steppers[i]->name, probname[p], k); } } } void test_driver (const gsl_odeiv2_step_type * T) { /* Tests for gsl_odeiv2_driver object */ int s; const double tol = 1e-8; const double hmax = 1e-2; double y[] = { 1.0, 0.0 }; double t = 0.0; const double tinit = 0.0; const double t1 = 8.25; const double t2 = 100; const double t3 = -2.5; const size_t minsteps = ceil (t1 / hmax); const size_t maxsteps = 20; const double hmin = 1e-10; const unsigned long int nfsteps = 100000; const double hfixed = 0.000025; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new (&rhs_func_sin, T, 1e-3, tol, tol); gsl_odeiv2_driver_set_hmax (d, hmax); s = gsl_odeiv2_driver_apply (d, &t, t1, y); if (s != GSL_SUCCESS) { gsl_test (s, "%s test_driver apply returned %d", gsl_odeiv2_step_name (d->s), s); } /* Test that result is correct */ gsl_test_rel (y[0], cos (t1), d->n * tol, "%s test_driver y0", gsl_odeiv2_step_name (d->s)); gsl_test_rel (y[1], sin (t1), d->n * tol, "%s test_driver y1", gsl_odeiv2_step_name (d->s)); /* Test that maximum step length is obeyed */ if (d->n < minsteps) { gsl_test (1, "%s test_driver steps %d < minsteps %d \n", gsl_odeiv2_step_name (d->s), d->n, minsteps); } else { gsl_test (0, "%s test_driver max step length test", gsl_odeiv2_step_name (d->s)); } /* Test changing integration direction from forward to backward */ gsl_odeiv2_driver_reset_hstart (d, -1e-3); s = gsl_odeiv2_driver_apply (d, &t, tinit, y); if (s != GSL_SUCCESS) { gsl_test (s, "%s test_driver apply returned %d", gsl_odeiv2_step_name (d->s), s); } gsl_test_rel (y[0], cos (tinit), d->n * tol, "%s test_driver y0", gsl_odeiv2_step_name (d->s)); gsl_test_rel (y[1], sin (tinit), d->n * tol, "%s test_driver y1", gsl_odeiv2_step_name (d->s)); gsl_odeiv2_driver_free (d); /* Test that maximum number of steps is obeyed */ d = gsl_odeiv2_driver_alloc_y_new (&rhs_func_sin, T, 1e-3, tol, tol); gsl_odeiv2_driver_set_hmax (d, hmax); gsl_odeiv2_driver_set_nmax (d, maxsteps); s = gsl_odeiv2_driver_apply (d, &t, t2, y); if (d->n != maxsteps + 1) { gsl_test (1, "%s test_driver steps %d, expected %d", gsl_odeiv2_step_name (d->s), d->n, maxsteps + 1); } else { gsl_test (0, "%s test_driver max steps test", gsl_odeiv2_step_name (d->s)); } gsl_odeiv2_driver_free (d); /* Test that minimum step length is obeyed */ d = gsl_odeiv2_driver_alloc_y_new (&rhs_func_broken, T, 1e-3, tol, tol); gsl_odeiv2_driver_set_hmin (d, hmin); y[0] = 0.0; t = 0.0; s = gsl_odeiv2_driver_apply (d, &t, t2, y); if (s != GSL_ENOPROG) { gsl_test (1, "%s test_driver min step test returned %d", gsl_odeiv2_step_name (d->s), s); } else { gsl_test (0, "%s test_driver min step test", gsl_odeiv2_step_name (d->s)); } gsl_odeiv2_driver_free (d); /* Test negative integration direction */ d = gsl_odeiv2_driver_alloc_y_new (&rhs_func_sin, T, -1e-3, tol, tol); y[0] = 1.0; y[1] = 0.0; t = 2.5; s = gsl_odeiv2_driver_apply (d, &t, t3, y); { const double tol = 1e-3; const double test = fabs (t - t3); const double val = fabs (sin (-5.0) - y[1]); if (test > GSL_DBL_EPSILON) { gsl_test (1, "%s test_driver negative dir diff %e, expected less than %e", gsl_odeiv2_step_name (d->s), test, GSL_DBL_EPSILON); } else if (val > tol) { gsl_test (1, "%s test_driver negative dir val %e, expected less than %e", gsl_odeiv2_step_name (d->s), val, tol); } else { gsl_test (s, "%s test_driver negative direction test", gsl_odeiv2_step_name (d->s)); } } /* Test driver_apply_fixed_step */ gsl_odeiv2_driver_reset_hstart (d, 1e-3); s = gsl_odeiv2_driver_apply_fixed_step (d, &t, hfixed, nfsteps, y); if (s != GSL_SUCCESS) { gsl_test (s, "%s test_driver apply_fixed_step returned %d", gsl_odeiv2_step_name (d->s), s); } { const double tol = 1e-3; const double val = fabs (sin (-2.5) - y[1]); if (fabs (t) > nfsteps * GSL_DBL_EPSILON) { gsl_test (1, "%s test_driver apply_fixed_step t %e, expected less than %e", gsl_odeiv2_step_name (d->s), fabs (t), nfsteps * GSL_DBL_EPSILON); } else if (val > tol) { gsl_test (1, "%s test_driver apply_fixed_step val %e, expected less than %e", gsl_odeiv2_step_name (d->s), val, tol); } else { gsl_test (s, "%s test_driver apply_fixed_step test", gsl_odeiv2_step_name (d->s)); } } gsl_odeiv2_driver_free (d); } void benchmark_precision (void) { /* Tests steppers with several error tolerances and evaluates their performance and precision. */ /* Maximum number of tolerances to be tested */ #define MAXNT 12 const gsl_odeiv2_step_type *steppers[MAXNS]; /* Required error tolerance for each stepper. */ double err_target[MAXNS]; /* initial values for each ode-solver */ double y[MAXEQ * MAXNS * MAXNT]; /* precise results from e.g. analytical solution */ double yres[MAXEQ]; size_t i, j, k, p; /* Number of problems to test */ #define CONST_BENCHMARK_PRECISION_NPROB 3 /* Problems, their names and number of equations */ const gsl_odeiv2_system *prob[] = { &rhs_func_sin, &rhs_func_exp, &rhs_func_stiff }; const char *probname[] = { "rhs_func_sin", "rhs_func_exp", "rhs_func_stiff" }; const size_t sd[] = { 2, 1, 2 }; /* Integration interval for problems */ const double start[] = { 0.0, 0.0, 0.0 }; const double end[] = { 2.4, 8.4, 1.2 }; const double epsabs[] = { 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14, 0 }; const double epsrel[] = { 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14, 0 }; const double initstepsize = 1e-5; /* number of function and jacobian evaluations */ extern int nfe, nje; int nnfe[MAXNS * MAXNT] = { 0.0 }; int nnje[MAXNS * MAXNT] = { 0.0 }; /* Steppers */ steppers[0] = gsl_odeiv2_step_rk4; err_target[0] = 1e-6; steppers[1] = gsl_odeiv2_step_rk2; err_target[1] = 1e-6; steppers[2] = gsl_odeiv2_step_rkf45; err_target[2] = 1e-6; steppers[3] = gsl_odeiv2_step_rkck; err_target[3] = 1e-6; steppers[4] = gsl_odeiv2_step_rk8pd; err_target[4] = 1e-6; steppers[5] = gsl_odeiv2_step_rk1imp; err_target[5] = 1e-3; steppers[6] = gsl_odeiv2_step_rk2imp; err_target[6] = 1e-5; steppers[7] = gsl_odeiv2_step_rk4imp; err_target[7] = 1e-6; steppers[8] = gsl_odeiv2_step_bsimp; err_target[8] = 1e-6; steppers[9] = gsl_odeiv2_step_msadams; err_target[9] = 1e-5; steppers[10] = gsl_odeiv2_step_msbdf; err_target[10] = 1e-5; steppers[11] = 0; /* Loop over problems */ for (p = 0; p < CONST_BENCHMARK_PRECISION_NPROB; p++) { /* Initialize */ for (i = 0; i < MAXNS * MAXEQ * MAXNT; i++) { y[i] = 0.0; } for (i = 0; i < MAXNS * MAXNT; i++) { switch (p) { case 0: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 0.0; yres[0] = cos (2.4); yres[1] = sin (2.4); break; case 1: y[i * sd[p]] = 1.0; yres[0] = exp (8.4); break; case 2: y[i * sd[p]] = 1.0; y[i * sd[p] + 1] = 0.0; yres[0] = 2 * exp (-1.2) - exp (-1000 * 1.2); yres[1] = -exp (-1.2) + exp (-1000 * 1.2); break; default: gsl_test (GSL_EFAILED, "benchmark_precision: initialization error\n"); return; } } /* Call each solver for the problem */ for (i = 0; steppers[i] != 0; i++) for (j = 0; epsrel[j] != 0; j++) { int s = sys_driver (steppers[i], prob[p], start[p], end[p], initstepsize, &y[sd[p] * (j + i * MAXNT)], epsabs[j], epsrel[j], probname[p]); if (s != GSL_SUCCESS) { for (k = 0; k < sd[p]; k++) { y[sd[p] * (j + i * MAXNT) + k] = GSL_NAN; } } else { nnfe[j + i * MAXNT] = nfe; nnje[j + i * MAXNT] = nje; } } /* Print results */ printf ("benchmark_precision: diff = (y_true - y) / y_true with %s\n epsrel: ", probname[p]); for (i = 0; epsrel[i] != 0.0; i++) { printf ("%12.0e ", epsrel[i]); } printf ("\n"); for (i = 0; steppers[i] != 0; i++) { for (k = 0; k < sd[p]; k++) { printf ("%8s diff[%d]: ", steppers[i]->name, (int) k); for (j = 0; epsrel[j] != 0; j++) { const double diff = (yres[k] - y[sd[p] * (j + i * MAXNT) + k]) / yres[k]; printf ("%12.5e ", diff); } printf ("\n"); } } printf ("\n"); /* Print number of function/jacobian evaluations */ printf ("benchmark_precision: number of function/jacobian evaluations with %s\n epsrel: ", probname[p]); for (i = 0; epsrel[i] != 0.0; i++) { printf ("%12.0e ", epsrel[i]); } printf ("\n"); for (i = 0; steppers[i] != 0; i++) { printf ("%8s nfe/nje: ", steppers[i]->name); for (j = 0; epsrel[j] != 0; j++) { printf ("%9d %9d | ", nnfe[j + i * MAXNT], nnje[j + i * MAXNT]); } printf ("\n"); } printf ("\n"); } } void test_evolve_temp (const gsl_odeiv2_step_type * T, double h, double err) { /* Temporary test */ double y[3]; double yfin[3]; y[0] = 1.0; y[1] = 0.0; y[2] = 0.0; yfin[0] = 0; yfin[1] = 0; yfin[2] = 0; test_evolve_system (T, &rhs_func_stiff, 0.0, 1.0, h, y, yfin, err, "temp"); } /**********************************************************/ /* Main function */ /**********************************************************/ int main (void) { /* Benchmark routine to compare stepper performance */ /* benchmark_precision(); return 0; */ /* Test single problem, for debugging purposes */ /* test_evolve_temp (gsl_odeiv2_step_msadams, 1e-3, 1e-8); return 0; */ int i; struct ptype { const gsl_odeiv2_step_type *type; double h; } p[MAXNS]; struct ptype explicit_stepper[MAXNS]; p[0].type = gsl_odeiv2_step_rk4; p[0].h = 1.0e-3; p[1].type = gsl_odeiv2_step_rk2; p[1].h = 1.0e-3; p[2].type = gsl_odeiv2_step_rkf45; p[2].h = 1.0e-3; p[3].type = gsl_odeiv2_step_rkck; p[3].h = 1.0e-3; p[4].type = gsl_odeiv2_step_rk8pd; p[4].h = 1.0e-3; p[5].type = gsl_odeiv2_step_rk1imp; p[5].h = 1.0e-3; p[6].type = gsl_odeiv2_step_rk2imp; p[6].h = 1.0e-3; p[7].type = gsl_odeiv2_step_rk4imp; p[7].h = 1.0e-3; p[8].type = gsl_odeiv2_step_bsimp; p[8].h = 1.0e-3; p[9].type = gsl_odeiv2_step_msadams; p[9].h = 1.0e-3; p[10].type = gsl_odeiv2_step_msbdf; p[10].h = 1.0e-3; p[11].type = 0; gsl_ieee_env_setup (); /* Basic tests for all steppers */ for (i = 0; p[i].type != 0; i++) { test_stepper (p[i].type); test_evolve_linear (p[i].type, p[i].h, 1e-10); test_evolve_exp (p[i].type, p[i].h, 1e-5); test_evolve_sin (p[i].type, p[i].h, 1e-8); test_evolve_xsin (p[i].type, p[i].h, 1e-8); test_evolve_xsin (p[i].type, 0.1, 1e-8); test_evolve_stiff1 (p[i].type, p[i].h, 1e-7); test_evolve_stiff5 (p[i].type, p[i].h, 1e-7); test_evolve_negative_h (p[i].type, p[i].h, 1e-7); test_broken (p[i].type, p[i].h, 1e-8); test_stepsize_fail (p[i].type, p[i].h); test_user_break (p[i].type, p[i].h); test_driver (p[i].type); } /* Derivative test for explicit steppers */ explicit_stepper[0].type = gsl_odeiv2_step_rk4; explicit_stepper[0].h = 1.0e-3; explicit_stepper[1].type = gsl_odeiv2_step_rk2; explicit_stepper[1].h = 1.0e-3; explicit_stepper[2].type = gsl_odeiv2_step_rkf45; explicit_stepper[2].h = 1.0e-3; explicit_stepper[3].type = gsl_odeiv2_step_rkck; explicit_stepper[3].h = 1.0e-3; explicit_stepper[4].type = gsl_odeiv2_step_rk8pd; explicit_stepper[4].h = 1.0e-3; explicit_stepper[5].type = gsl_odeiv2_step_msadams; explicit_stepper[5].h = 1.0e-3; explicit_stepper[6].type = 0; for (i = 0; explicit_stepper[i].type != 0; i++) { test_stepfn (explicit_stepper[i].type); test_stepfn2 (explicit_stepper[i].type); } /* Special tests */ test_nonstiff_problems (); test_stiff_problems (); test_extreme_problems (); exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.53612813, "avg_line_length": 23.6565576999, "ext": "c", "hexsha": "ae87bd0e19ea4bcd5bea7e129bee0c40cb15f4e2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/ode-initval2/test.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/ode-initval2/test.c", "max_line_length": 102, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/ode-initval2/test.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": 21790, "size": 60064 }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #ifndef LIBND4J_BLAS_HELPER_H #define LIBND4J_BLAS_HELPER_H #include <system/pointercast.h> #include <types/float16.h> #include <cblas.h> #include <helpers/logger.h> #ifdef _WIN32 #define CUBLASWINAPI __stdcall #define CUSOLVERAPI __stdcall #else #define CUBLASWINAPI #define CUSOLVERAPI #endif namespace sd { typedef enum{ CUBLAS_STATUS_SUCCESS =0, CUBLAS_STATUS_NOT_INITIALIZED =1, CUBLAS_STATUS_ALLOC_FAILED =3, CUBLAS_STATUS_INVALID_VALUE =7, CUBLAS_STATUS_ARCH_MISMATCH =8, CUBLAS_STATUS_MAPPING_ERROR =11, CUBLAS_STATUS_EXECUTION_FAILED=13, CUBLAS_STATUS_INTERNAL_ERROR =14, CUBLAS_STATUS_NOT_SUPPORTED =15, CUBLAS_STATUS_LICENSE_ERROR =16 } cublasStatus_t; typedef enum { CUBLAS_OP_N=0, CUBLAS_OP_T=1, CUBLAS_OP_C=2 } cublasOperation_t; struct cublasContext; typedef struct cublasContext *cublasHandle_t; typedef enum { CUDA_R_16F= 2, /* real as a half */ CUDA_C_16F= 6, /* complex as a pair of half numbers */ CUDA_R_32F= 0, /* real as a float */ CUDA_C_32F= 4, /* complex as a pair of float numbers */ CUDA_R_64F= 1, /* real as a double */ CUDA_C_64F= 5, /* complex as a pair of double numbers */ CUDA_R_8I = 3, /* real as a signed char */ CUDA_C_8I = 7, /* complex as a pair of signed char numbers */ CUDA_R_8U = 8, /* real as a unsigned char */ CUDA_C_8U = 9, /* complex as a pair of unsigned char numbers */ CUDA_R_32I= 10, /* real as a signed int */ CUDA_C_32I= 11, /* complex as a pair of signed int numbers */ CUDA_R_32U= 12, /* real as a unsigned int */ CUDA_C_32U= 13 /* complex as a pair of unsigned int numbers */ } cublasDataType_t; typedef void (*CblasSgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, float alpha, float *A, int lda, float *X, int incX, float beta, float *Y, int incY); typedef void (*CblasDgemv)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, int M, int N, double alpha, double *A, int lda, double *X, int incX, double beta, double *Y, int incY); typedef void (*CblasSgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K, float alpha, float *A, int lda, float *B, int ldb, float beta, float *C, int ldc); typedef void (*CblasDgemm)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, int M, int N, int K, double alpha, double *A, int lda, double *B, int ldb, double beta, double *C, int ldc); typedef void (*CblasSgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array, int *M_Array, int *N_Array, int *K_Array, float *alpha_Array, float **A_Array, int *lda_Array, float **B_Array, int *ldb_Array, float *beta_Array, float **C_Array, int *ldc_Array, int group_count, int *group_size); typedef void (*CblasDgemmBatch)(CBLAS_ORDER Layout, CBLAS_TRANSPOSE *TransA_Array, CBLAS_TRANSPOSE *TransB_Array, int *M_Array, int *N_Array, int *K_Array, double *alpha_Array, double **A_Array, int *lda_Array, double **B_Array, int* ldb_Array, double *beta_Array, double **C_Array, int *ldc_Array, int group_count, int *group_size); #ifdef LAPACK_ROW_MAJOR #undef LAPACK_ROW_MAJOR #endif #ifdef LAPACK_COL_MAJOR #undef LAPACK_COL_MAJOR #endif enum LAPACK_LAYOUT { LAPACK_ROW_MAJOR=101, LAPACK_COL_MAJOR=102 }; typedef int (*LapackeSgesvd)(LAPACK_LAYOUT matrix_layout, char jobu, char jobvt, int m, int n, float* a, int lda, float* s, float* u, int ldu, float* vt, int ldvt, float* superb); typedef int (*LapackeDgesvd)(LAPACK_LAYOUT matrix_layout, char jobu, char jobvt, int m, int n, double* a, int lda, double* s, double* u, int ldu, double* vt, int ldvt, double* superb); typedef int (*LapackeSgesdd)(LAPACK_LAYOUT matrix_layout, char jobz, int m, int n, float* a, int lda, float* s, float* u, int ldu, float* vt, int ldvt); typedef int (*LapackeDgesdd)(LAPACK_LAYOUT matrix_layout, char jobz, int m, int n, double* a, int lda, double* s, double* u, int ldu, double* vt, int ldvt); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n, float *alpha, /* host or device pointer */ float *A, int lda, float *x, int incx, float *beta, /* host or device pointer */ float *y, int incy); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemv)(cublasHandle_t handle, cublasOperation_t trans, int m, int n, double *alpha, /* host or device pointer */ double *A, int lda, double *x, int incx, double *beta, /* host or device pointer */ double *y, int incy); typedef cublasStatus_t (CUBLASWINAPI *CublasHgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, __half *alpha, /* host or device pointer */ __half *A, int lda, __half *B, int ldb, __half *beta, /* host or device pointer */ __half *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ float *A, int lda, float *B, int ldb, float *beta, /* host or device pointer */ float *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemm)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, double *alpha, /* host or device pointer */ double *A, int lda, double *B, int ldb, double *beta, /* host or device pointer */ double *C, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemmEx)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ void *A, cublasDataType_t Atype, int lda, void *B, cublasDataType_t Btype, int ldb, float *beta, /* host or device pointer */ void *C, cublasDataType_t Ctype, int ldc); typedef cublasStatus_t (CUBLASWINAPI *CublasHgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, __half *alpha, /* host or device pointer */ __half *Aarray[], int lda, __half *Barray[], int ldb, __half *beta, /* host or device pointer */ __half *Carray[], int ldc, int batchCount); typedef cublasStatus_t (CUBLASWINAPI *CublasSgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, float *alpha, /* host or device pointer */ float *Aarray[], int lda, float *Barray[], int ldb, float *beta, /* host or device pointer */ float *Carray[], int ldc, int batchCount); typedef cublasStatus_t (CUBLASWINAPI *CublasDgemmBatched)(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, double *alpha, /* host or device pointer */ double *Aarray[], int lda, double *Barray[], int ldb, double *beta, /* host or device pointer */ double *Carray[], int ldc, int batchCount); typedef enum{ CUSOLVER_STATUS_SUCCESS=0, CUSOLVER_STATUS_NOT_INITIALIZED=1, CUSOLVER_STATUS_ALLOC_FAILED=2, CUSOLVER_STATUS_INVALID_VALUE=3, CUSOLVER_STATUS_ARCH_MISMATCH=4, CUSOLVER_STATUS_MAPPING_ERROR=5, CUSOLVER_STATUS_EXECUTION_FAILED=6, CUSOLVER_STATUS_INTERNAL_ERROR=7, CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED=8, CUSOLVER_STATUS_NOT_SUPPORTED = 9, CUSOLVER_STATUS_ZERO_PIVOT=10, CUSOLVER_STATUS_INVALID_LICENSE=11 } cusolverStatus_t; typedef enum { CUSOLVER_EIG_TYPE_1=1, CUSOLVER_EIG_TYPE_2=2, CUSOLVER_EIG_TYPE_3=3 } cusolverEigType_t ; typedef enum { CUSOLVER_EIG_MODE_NOVECTOR=0, CUSOLVER_EIG_MODE_VECTOR=1 } cusolverEigMode_t ; struct cusolverDnContext; typedef struct cusolverDnContext *cusolverDnHandle_t; typedef cusolverStatus_t (CUSOLVERAPI *CusolverDnSgesvdBufferSize)( cusolverDnHandle_t handle, int m, int n, int *lwork); typedef cusolverStatus_t (CUSOLVERAPI *CusolverDnDgesvdBufferSize)( cusolverDnHandle_t handle, int m, int n, int *lwork); typedef cusolverStatus_t (CUSOLVERAPI *CusolverDnSgesvd)( cusolverDnHandle_t handle, signed char jobu, signed char jobvt, int m, int n, float *A, int lda, float *S, float *U, int ldu, float *VT, int ldvt, float *work, int lwork, float *rwork, int *info); typedef cusolverStatus_t (CUSOLVERAPI *CusolverDnDgesvd)( cusolverDnHandle_t handle, signed char jobu, signed char jobvt, int m, int n, double *A, int lda, double *S, double *U, int ldu, double *VT, int ldvt, double *work, int lwork, double *rwork, int *info); enum BlasFunctions { GEMV = 0, GEMM = 1, }; class BlasHelper { private: bool _hasHgemv = false; bool _hasHgemm = false; bool _hasHgemmBatch = false; bool _hasSgemv = false; bool _hasSgemm = false; bool _hasSgemmBatch = false; bool _hasDgemv = false; bool _hasDgemm = false; bool _hasDgemmBatch = false; CblasSgemv cblasSgemv; CblasDgemv cblasDgemv; CblasSgemm cblasSgemm; CblasDgemm cblasDgemm; CblasSgemmBatch cblasSgemmBatch; CblasDgemmBatch cblasDgemmBatch; LapackeSgesvd lapackeSgesvd; LapackeDgesvd lapackeDgesvd; LapackeSgesdd lapackeSgesdd; LapackeDgesdd lapackeDgesdd; CublasSgemv cublasSgemv; CublasDgemv cublasDgemv; CublasHgemm cublasHgemm; CublasSgemm cublasSgemm; CublasDgemm cublasDgemm; CublasSgemmEx cublasSgemmEx; CublasHgemmBatched cublasHgemmBatched; CublasSgemmBatched cublasSgemmBatched; CublasDgemmBatched cublasDgemmBatched; CusolverDnSgesvdBufferSize cusolverDnSgesvdBufferSize; CusolverDnDgesvdBufferSize cusolverDnDgesvdBufferSize; CusolverDnSgesvd cusolverDnSgesvd; CusolverDnDgesvd cusolverDnDgesvd; public: static BlasHelper& getInstance(); void initializeFunctions(Nd4jPointer *functions); void initializeDeviceFunctions(Nd4jPointer *functions); template <typename T> bool hasGEMV(); template <typename T> bool hasGEMM(); bool hasGEMM(const sd::DataType dtype); bool hasGEMV(const sd::DataType dtype); template <typename T> bool hasBatchedGEMM(); CblasSgemv sgemv(); CblasDgemv dgemv(); CblasSgemm sgemm(); CblasDgemm dgemm(); CblasSgemmBatch sgemmBatched(); CblasDgemmBatch dgemmBatched(); LapackeSgesvd sgesvd(); LapackeDgesvd dgesvd(); LapackeSgesdd sgesdd(); LapackeDgesdd dgesdd(); // destructor ~BlasHelper() noexcept; }; } #endif
{ "alphanum_fraction": 0.4124487705, "avg_line_length": 44.0632054176, "ext": "h", "hexsha": "038df67b5c6ed6ad25405f1aa30ecdc74fcd6e09", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-08-06T09:55:54.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-02T03:01:33.000Z", "max_forks_repo_head_hexsha": "e11ddf3c24d355b43d36431687b807c8561aaae4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "pxiuqin/deeplearning4j", "max_forks_repo_path": "libnd4j/include/helpers/BlasHelper.h", "max_issues_count": 132, "max_issues_repo_head_hexsha": "e11ddf3c24d355b43d36431687b807c8561aaae4", "max_issues_repo_issues_event_max_datetime": "2021-08-02T17:02:13.000Z", "max_issues_repo_issues_event_min_datetime": "2019-10-26T11:01:50.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "pxiuqin/deeplearning4j", "max_issues_repo_path": "libnd4j/include/helpers/BlasHelper.h", "max_line_length": 104, "max_stars_count": 10, "max_stars_repo_head_hexsha": "a1fcc5f19f0f637e83252b00982b3f12b401f679", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "mjlorenzo305/deeplearning4j", "max_stars_repo_path": "libnd4j/include/helpers/BlasHelper.h", "max_stars_repo_stars_event_max_datetime": "2021-12-25T02:35:47.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-24T08:44:08.000Z", "num_tokens": 3804, "size": 19520 }
/* * libDefs.h * This file and its associated source file contain any functions and * statements (within the actual program) that need to be modified * when adding a new library. This includes any work done on complex * numbers, FFT planning and execution, and would also contain the * definition of the appropriate MPI type to represent the complex * number, except that I decided to assume they were all just two * MPI_DOUBLEs. (Bit compatability can be verified.) * * Defining HAS_AUTO in compilation is an instruction to use the parallel * version of the library as well. * * We use the less eye-friendly version of the C complex number type * to avoid namespace collisions -- complex is equivalent to _Complex. * * Created by Ian Kirker on 14/04/2008. * */ #ifndef HEADER_LIBDEFS #define HEADER_LIBDEFS #include <complex.h> #include <mpi.h> #ifndef FFT_fftw2 #ifndef FFT_fftw3 #ifndef FFT_mkl #ifndef FFT_essl #ifndef FFT_acml #define FFT_fftw3 /* Default to make test building easier. */ #endif #endif #endif #endif #endif /* Include FFT library of choice */ #ifdef FFT_fftw2 #ifdef FFTW_TYPE_SPECIFIED #include <dfftw.h> #ifdef HAS_AUTO #include <dfftw_mpi.h> #endif #else #include <fftw.h> #ifdef HAS_AUTO #include <fftw_mpi.h> #endif #endif #define FFT_NAME "fftw2" #define FFT_fftw2_LIBKEY typedef fftw_complex complexType; typedef fftw_plan oneDplanType; typedef fftwnd_plan twoDplanType; #ifdef HAS_AUTO typedef fftwnd_mpi_plan parallelPlanType; #endif #endif #ifdef FFT_fftw3 #include <fftw3.h> #define FFT_NAME "fftw3" #define FFT_fftw3_LIBKEY 1 typedef fftw_complex complexType; typedef fftw_plan planType; #ifdef HAS_AUTO typedef fftw_plan parallelPlanType; #endif #endif #ifdef FFT_essl #include <essl.h> #define FFT_NAME "essl" #define FFT_essl_LIBKEY 2 typedef dcmplx complexType; typedef double planType[20000]; #ifdef HAS_AUTO #include <pessl.h> #include <Cblacs.h> /* This refers to the BLACS handle you get back from the grid init calls. */ typedef int parallelPlanType; #endif #endif #ifdef FFT_acml #include <acml.h> #define FFT_NAME "acml" #define FFT_acml_LIBKEY 3 typedef doublecomplex complexType; /* In ACML, the closest you can get to making a plan is to run * a transform and have it save the data in the array it uses as a buffer, * so we alloc some space later but say that the planType is a pointer now. */ typedef complexType *planType; #endif #ifdef FFT_mkl #include <mkl_dfti.h> #define FFT_NAME "mkl" #define FFT_mkl_LIBKEY 4 typedef _Complex double complexType; typedef DFTI_DESCRIPTOR_HANDLE planType; #ifdef HAS_AUTO typedef DFTI_DESCRIPTOR_DM_HANDLE parallelPlanType; #endif #endif void prepareFFTs(complexType *data, int decomp, int use2DFFT, int extent, int domainSize[2], MPI_Comm commColumn); void performFFTset(complexType *data, complexType *buffer, int extent, int domainSize[2]); void perform2DFFT(complexType *data, complexType *buffer, int extent, int domainSize[2]); void performAutomatic3DFFT(complexType *data, complexType *buffer, int extent, int domainSize[2]); void cleanUpFFTs(int decomp); int libraryHasAutomaticDecomposition(); void printLib(); void complexSwap(complexType *, complexType *); void complexSet(complexType *z, double real, double imag); void complexAssign( complexType *z, complexType w ); double complexAbsNorm(complexType z, complexType w); _Complex double complexNative( complexType z ); #endif
{ "alphanum_fraction": 0.7577569029, "avg_line_length": 27.2325581395, "ext": "h", "hexsha": "131cd620374f8bc6a88a8790b4650dc33b9dc35c", "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": "aad4f50a185c9220e6fc7dc2faa72cb8ab7d1882", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ikirker/3dfft", "max_forks_repo_path": "libDefs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "aad4f50a185c9220e6fc7dc2faa72cb8ab7d1882", "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": "ikirker/3dfft", "max_issues_repo_path": "libDefs.h", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "aad4f50a185c9220e6fc7dc2faa72cb8ab7d1882", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ikirker/3dfft", "max_stars_repo_path": "libDefs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 943, "size": 3513 }
/* randist/multinomial.c * * Copyright (C) 2002 Gavin E. Crooks <gec@compbio.berkeley.edu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_gamma.h> /* The multinomial distribution has the form N! n_1 n_2 n_K prob(n_1, n_2, ... n_K) = -------------------- p_1 p_2 ... p_K (n_1! n_2! ... n_K!) where n_1, n_2, ... n_K are nonnegative integers, sum_{k=1,K} n_k = N, and p = (p_1, p_2, ..., p_K) is a probability distribution. Random variates are generated using the conditional binomial method. This scales well with N and does not require a setup step. Ref: C.S. David, The computer generation of multinomial random variates, Comp. Stat. Data Anal. 16 (1993) 205-217 */ void gsl_ran_multinomial (const gsl_rng * r, const size_t K, const unsigned int N, const double p[], unsigned int n[]) { size_t k; double norm = 0.0; double sum_p = 0.0; unsigned int sum_n = 0; /* p[k] may contain non-negative weights that do not sum to 1.0. * Even a probability distribution will not exactly sum to 1.0 * due to rounding errors. */ for (k = 0; k < K; k++) { norm += p[k]; } for (k = 0; k < K; k++) { if (p[k] > 0.0) { n[k] = gsl_ran_binomial (r, p[k] / (norm - sum_p), N - sum_n); } else { n[k] = 0; } sum_p += p[k]; sum_n += n[k]; } } double gsl_ran_multinomial_pdf (const size_t K, const double p[], const unsigned int n[]) { return exp (gsl_ran_multinomial_lnpdf (K, p, n)); } double gsl_ran_multinomial_lnpdf (const size_t K, const double p[], const unsigned int n[]) { size_t k; unsigned int N = 0; double log_pdf = 0.0; double norm = 0.0; for (k = 0; k < K; k++) { N += n[k]; } for (k = 0; k < K; k++) { norm += p[k]; } log_pdf = gsl_sf_lnfact (N); for (k = 0; k < K; k++) { log_pdf -= gsl_sf_lnfact (n[k]); } for (k = 0; k < K; k++) { log_pdf += log (p[k] / norm) * n[k]; } return log_pdf; }
{ "alphanum_fraction": 0.5787888926, "avg_line_length": 24.5, "ext": "c", "hexsha": "321e1727079370ce7c6ce39b534ed79af246e335", "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/randist/multinomial.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/randist/multinomial.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/randist/multinomial.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": 900, "size": 2989 }
/* bspline/bspline.c * * Copyright (C) 2006 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 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> /* * This module contains routines related to calculating B-splines. * The algorithms used are described in * * [1] Carl de Boor, "A Practical Guide to Splines", Springer * Verlag, 1978. */ static int bspline_eval_all(const double x, gsl_vector *B, size_t *idx, gsl_bspline_workspace *w); static inline size_t bspline_find_interval(const double x, int *flag, gsl_bspline_workspace *w); /* gsl_bspline_alloc() Allocate space for a bspline workspace. The size of the workspace is O(5k + nbreak) Inputs: k - spline order (cubic = 4) nbreak - number of breakpoints Return: pointer to workspace */ gsl_bspline_workspace * gsl_bspline_alloc(const size_t k, const size_t nbreak) { if (k == 0) { GSL_ERROR_NULL("k must be at least 1", GSL_EINVAL); } else if (nbreak < 2) { GSL_ERROR_NULL("nbreak must be at least 2", GSL_EINVAL); } else { gsl_bspline_workspace *w; w = (gsl_bspline_workspace *) calloc(1, sizeof(gsl_bspline_workspace)); if (w == 0) { GSL_ERROR_NULL("failed to allocate space for workspace", GSL_ENOMEM); } w->k = k; w->km1 = k - 1; w->nbreak = nbreak; w->l = nbreak - 1; w->n = w->l + k - 1; w->knots = gsl_vector_alloc(w->n + k); if (w->knots == 0) { gsl_bspline_free(w); GSL_ERROR_NULL("failed to allocate space for knots vector", GSL_ENOMEM); } w->deltal = gsl_vector_alloc(k); w->deltar = gsl_vector_alloc(k); if (!w->deltal || !w->deltar) { gsl_bspline_free(w); GSL_ERROR_NULL("failed to allocate space for delta vectors", GSL_ENOMEM); } w->B = gsl_vector_alloc(k); if (w->B == 0) { gsl_bspline_free(w); GSL_ERROR_NULL("failed to allocate space for temporary spline vector", GSL_ENOMEM); } return (w); } } /* gsl_bspline_alloc() */ /* Return number of coefficients */ size_t gsl_bspline_ncoeffs (gsl_bspline_workspace * w) { return w->n; } /* Return order */ size_t gsl_bspline_order (gsl_bspline_workspace * w) { return w->k; } /* Return number of breakpoints */ size_t gsl_bspline_nbreak (gsl_bspline_workspace * w) { return w->nbreak; } double gsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w) { size_t j = i + w->k - 1; return gsl_vector_get(w->knots, j); } /* gsl_bspline_free() Free a bspline workspace Inputs: w - workspace to free Return: none */ void gsl_bspline_free(gsl_bspline_workspace *w) { if (!w) return; if (w->knots) gsl_vector_free(w->knots); if (w->deltal) gsl_vector_free(w->deltal); if (w->deltar) gsl_vector_free(w->deltar); if (w->B) gsl_vector_free(w->B); free(w); } /* gsl_bspline_free() */ /* gsl_bspline_knots() Compute the knots from the given breakpoints: knots(1:k) = breakpts(1) knots(k+1:k+l-1) = breakpts(i), i = 2 .. l knots(n+1:n+k) = breakpts(l + 1) where l is the number of polynomial pieces (l = nbreak - 1) and n = k + l - 1 (using matlab syntax for the arrays) The repeated knots at the beginning and end of the interval correspond to the continuity condition there. See pg. 119 of [1]. Inputs: breakpts - breakpoints w - bspline workspace Return: success or error */ int gsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w) { if (breakpts->size != w->nbreak) { GSL_ERROR("breakpts vector has wrong size", GSL_EBADLEN); } else { size_t i; /* looping */ for (i = 0; i < w->k; ++i) gsl_vector_set(w->knots, i, gsl_vector_get(breakpts, 0)); for (i = 1; i < w->l; ++i) { gsl_vector_set(w->knots, w->k - 1 + i, gsl_vector_get(breakpts, i)); } for (i = w->n; i < w->n + w->k; ++i) gsl_vector_set(w->knots, i, gsl_vector_get(breakpts, w->l)); return GSL_SUCCESS; } } /* gsl_bspline_knots() */ /* gsl_bspline_knots_uniform() Construct uniformly spaced knots on the interval [a,b] using the previously specified number of breakpoints. 'a' is the position of the first breakpoint and 'b' is the position of the last breakpoint. Inputs: a - left side of interval b - right side of interval w - bspline workspace Return: success or error Notes: 1) w->knots is modified to contain the uniformly spaced knots 2) The knots vector is set up as follows (using octave syntax): knots(1:k) = a knots(k+1:k+l-1) = a + i*delta, i = 1 .. l - 1 knots(n+1:n+k) = b */ int gsl_bspline_knots_uniform(const double a, const double b, gsl_bspline_workspace *w) { size_t i; /* looping */ double delta; /* interval spacing */ double x; delta = (b - a) / (double) w->l; for (i = 0; i < w->k; ++i) gsl_vector_set(w->knots, i, a); x = a + delta; for (i = 0; i < w->l - 1; ++i) { gsl_vector_set(w->knots, w->k + i, x); x += delta; } for (i = w->n; i < w->n + w->k; ++i) gsl_vector_set(w->knots, i, b); return GSL_SUCCESS; } /* gsl_bspline_knots_uniform() */ /* gsl_bspline_eval() Evaluate the basis functions B_i(x) for all i. This is basically a wrapper function for bspline_eval_all() which formats the output in a nice way. Inputs: x - point for evaluation B - (output) where to store B_i(x) values the length of this vector is n = nbreak + k - 2 = l + k - 1 = w->n w - bspline workspace Return: success or error Notes: The w->knots vector must be initialized prior to calling this function (see gsl_bspline_knots()) */ int gsl_bspline_eval(const double x, gsl_vector *B, gsl_bspline_workspace *w) { if (B->size != w->n) { GSL_ERROR("B vector length does not match n", GSL_EBADLEN); } else { size_t i; /* looping */ size_t idx = 0; size_t start; /* first non-zero spline */ /* find all non-zero B_i(x) values */ bspline_eval_all(x, w->B, &idx, w); /* store values in appropriate part of given vector */ start = idx - w->k + 1; for (i = 0; i < start; ++i) gsl_vector_set(B, i, 0.0); for (i = start; i <= idx; ++i) gsl_vector_set(B, i, gsl_vector_get(w->B, i - start)); for (i = idx + 1; i < w->n; ++i) gsl_vector_set(B, i, 0.0); return GSL_SUCCESS; } } /* gsl_bspline_eval() */ /**************************************** * INTERNAL ROUTINES * ****************************************/ /* bspline_eval_all() Evaluate all non-zero B-splines B_i(x) using algorithm (8) of chapter X of [1] The idea is something like this. Given x \in [t_i, t_{i+1}] with t_i < t_{i+1} and the t_i are knots, the values of the B-splines not automatically zero fit into a triangular array as follows: 0 0 0 B_{i-2,3} B_{i-1,2} B_{i,1} B_{i-1,3} ... B_{i,2} 0 B_{i,3} 0 0 where B_{i,k} is the ith B-spline of order k. The boundary 0s indicate that those B-splines not in the table vanish at x. To compute the non-zero B-splines of a given order k, we use Eqs. (4) and (5) of chapter X of [1]: (4) B_{i,1}(x) = { 1, t_i <= x < t_{i+1} 0, else } (5) B_{i,k}(x) = (x - t_i) ----------------- B_{i,k-1}(x) (t_{i+k-1} - t_i) t_{i+k} - x + ----------------- B_{i+1,k-1}(x) t_{i+k} - t_{i+1} So (4) gives us the first column of the table and we can use the recurrence relation (5) to get the rest of the columns. Inputs: x - point at which to evaluate splines B - (output) where to store B-spline values (length k) idx - (output) B-spline function index of last output value (B_{idx}(x) is stored in the last slot of 'B') w - bspline workspace Return: success or error Notes: 1) the w->knots vector must be initialized before calling this function 2) On output, B contains: B = [B_{i-k+1,k}, B_{i-k+2,k}, ..., B_{i-1,k}, B_{i,k}] where 'i' is stored in 'idx' on output 3) based on PPPACK bsplvb */ static int bspline_eval_all(const double x, gsl_vector *B, size_t *idx, gsl_bspline_workspace *w) { if (B->size != w->k) { GSL_ERROR("B vector not of length k", GSL_EBADLEN); } else { size_t i; /* spline index */ size_t j; /* looping */ size_t ii; /* looping */ int flag = 0; /* error flag */ double saved; double term; i = bspline_find_interval(x, &flag, w); if (flag == -1) { GSL_ERROR("x outside of knot interval", GSL_EINVAL); } else if (flag == 1) { if (x <= gsl_vector_get(w->knots, i) + GSL_DBL_EPSILON) { --i; } else { GSL_ERROR("x outside of knot interval", GSL_EINVAL); } } *idx = i; gsl_vector_set(B, 0, 1.0); for (j = 0; j < w->k - 1; ++j) { gsl_vector_set(w->deltar, j, gsl_vector_get(w->knots, i + j + 1) - x); gsl_vector_set(w->deltal, j, x - gsl_vector_get(w->knots, i - j)); saved = 0.0; for (ii = 0; ii <= j; ++ii) { term = gsl_vector_get(B, ii) / (gsl_vector_get(w->deltar, ii) + gsl_vector_get(w->deltal, j - ii)); gsl_vector_set(B, ii, saved + gsl_vector_get(w->deltar, ii) * term); saved = gsl_vector_get(w->deltal, j - ii) * term; } gsl_vector_set(B, j + 1, saved); } return GSL_SUCCESS; } } /* bspline_eval_all() */ /* bspline_find_interval() Find knot interval such that t_i <= x < t_{i + 1} where the t_i are knot values. Inputs: x - x value flag - (output) error flag w - bspline workspace Return: i (index in w->knots corresponding to left limit of interval) Notes: The error conditions are reported as follows: Condition Return value Flag --------- ------------ ---- x < t_0 0 -1 t_i <= x < t_{i+1} i 0 t_{n+k-1} <= x l+k-1 +1 */ static inline size_t bspline_find_interval(const double x, int *flag, gsl_bspline_workspace *w) { size_t i; if (x < gsl_vector_get(w->knots, 0)) { *flag = -1; return 0; } /* find i such that t_i <= x < t_{i+1} */ for (i = w->k - 1; i < w->k + w->l - 1; ++i) { const double ti = gsl_vector_get(w->knots, i); const double tip1 = gsl_vector_get(w->knots, i + 1); if (tip1 < ti) { GSL_ERROR("knots vector is not increasing", GSL_EINVAL); } if (ti <= x && x < tip1) break; } if (i == w->k + w->l - 1) *flag = 1; else *flag = 0; return i; } /* bspline_find_interval() */
{ "alphanum_fraction": 0.5555826426, "avg_line_length": 24.7108433735, "ext": "c", "hexsha": "847a4984038702a5d283cba7d124b60510e30b14", "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/bspline/bspline.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/bspline/bspline.c", "max_line_length": 93, "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/bspline/bspline.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": 3587, "size": 12306 }
#ifndef AMICI_VECTOR_H #define AMICI_VECTOR_H #include <vector> #include <type_traits> #include <amici/exception.h> #include <nvector/nvector_serial.h> #include <gsl/gsl-lite.hpp> namespace amici { /** Since const N_Vector is not what we want */ using const_N_Vector = std::add_const_t<typename std::remove_pointer_t<N_Vector>> *; inline const realtype* N_VGetArrayPointerConst(const_N_Vector x) { return N_VGetArrayPointer(const_cast<N_Vector>(x)); } /** AmiVector class provides a generic interface to the NVector_Serial struct */ class AmiVector { public: /** * @brief Default constructor */ AmiVector() = default; /** Creates an std::vector<realtype> and attaches the * data pointer to a newly created N_Vector_Serial. * Using N_VMake_Serial ensures that the N_Vector * module does not try to deallocate the data vector * when calling N_VDestroy_Serial * @brief empty constructor * @param length number of elements in vector */ explicit AmiVector(const long int length) : vec_(static_cast<decltype(vec_)::size_type>(length), 0.0), nvec_(N_VMake_Serial(length, vec_.data())) {} /** Moves data from std::vector and constructs an nvec that points to the * data * @brief constructor from std::vector, * @param rvec vector from which the data will be moved */ explicit AmiVector(std::vector<realtype> rvec) : vec_(std::move(rvec)), nvec_(N_VMake_Serial(static_cast<long int>(vec_.size()), vec_.data())) {} /** Copy data from gsl::span and constructs a vector * @brief constructor from gsl::span, * @param rvec vector from which the data will be copied */ explicit AmiVector(gsl::span<realtype> rvec) : AmiVector(std::vector<realtype>(rvec.begin(), rvec.end())) {} /** * @brief copy constructor * @param vold vector from which the data will be copied */ AmiVector(const AmiVector &vold) : vec_(vold.vec_) { nvec_ = N_VMake_Serial(static_cast<long int>(vold.vec_.size()), vec_.data()); } /** * @brief move constructor * @param other vector from which the data will be moved */ AmiVector(AmiVector&& other) noexcept : nvec_(nullptr) { vec_ = std::move(other.vec_); synchroniseNVector(); } /** * @brief destructor */ ~AmiVector(); /** * @brief copy assignment operator * @param other right hand side * @return left hand side */ AmiVector &operator=(AmiVector const &other); /** * @brief operator *= (element-wise multiplication) * @param multiplier multiplier * @return result */ AmiVector &operator*=(AmiVector const& multiplier) { N_VProd(getNVector(), const_cast<N_Vector>(multiplier.getNVector()), getNVector()); return *this; } /** * @brief operator /= (element-wise division) * @param divisor divisor * @return result */ AmiVector &operator/=(AmiVector const& divisor) { N_VDiv(getNVector(), const_cast<N_Vector>(divisor.getNVector()), getNVector()); return *this; } /** * @brief Returns an iterator that points to the first element of the * vector. * @return iterator that points to the first element */ auto begin() { return vec_.begin(); } /** * @brief Returns an iterator that points to one element after the last * element of the vector. * @return iterator that points to one element after the last element */ auto end() { return vec_.end(); } /** * @brief data accessor * @return pointer to data array */ realtype *data(); /** * @brief const data accessor * @return const pointer to data array */ const realtype *data() const; /** * @brief N_Vector accessor * @return N_Vector */ N_Vector getNVector(); /** * @brief N_Vector accessor * @return N_Vector */ const_N_Vector getNVector() const; /** * @brief Vector accessor * @return Vector */ std::vector<realtype> const &getVector() const; /** * @brief returns the length of the vector * @return length */ int getLength() const; /** * @brief fills vector with zero values */ void zero(); /** * @brief changes the sign of data elements */ void minus(); /** * @brief sets all data elements to a specific value * @param val value for data elements */ void set(realtype val); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ realtype &operator[](int pos); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ realtype &at(int pos); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ const realtype &at(int pos) const; /** * @brief copies data from another AmiVector * @param other data source */ void copy(const AmiVector &other); /** * @brief Take absolute value (in-place) */ void abs() { N_VAbs(getNVector(), getNVector()); }; private: /** main data storage */ std::vector<realtype> vec_; /** N_Vector, will be synchronized such that it points to data in vec */ N_Vector nvec_ {nullptr}; /** * @brief reconstructs nvec such that data pointer points to vec data array */ void synchroniseNVector(); }; /** * @brief AmiVectorArray class. * * Provides a generic interface to arrays of NVector_Serial structs */ class AmiVectorArray { public: /** * @brief Default constructor */ AmiVectorArray() = default; /** * Creates an std::vector<realype> and attaches the * data pointer to a newly created N_VectorArray * using CloneVectorArrayEmpty ensures that the N_Vector * module does not try to deallocate the data vector * when calling N_VDestroyVectorArray_Serial * @brief empty constructor * @param length_inner length of vectors * @param length_outer number of vectors */ AmiVectorArray(long int length_inner, long int length_outer); /** * @brief copy constructor * @param vaold object to copy from */ AmiVectorArray(const AmiVectorArray &vaold); ~AmiVectorArray() = default; /** * @brief copy assignment operator * @param other right hand side * @return left hand side */ AmiVectorArray &operator=(AmiVectorArray const &other); /** * @brief accessor to data of AmiVector elements * @param pos index of AmiVector * @return pointer to data array */ realtype *data(int pos); /** * @brief const accessor to data of AmiVector elements * @param pos index of AmiVector * @return const pointer to data array */ const realtype *data(int pos) const; /** * @brief accessor to elements of AmiVector elements * @param ipos inner index in AmiVector * @param jpos outer index in AmiVectorArray * @return element */ realtype &at(int ipos, int jpos); /** * @brief const accessor to elements of AmiVector elements * @param ipos inner index in AmiVector * @param jpos outer index in AmiVectorArray * @return element */ const realtype &at(int ipos, int jpos) const; /** * @brief accessor to NVectorArray * @return N_VectorArray */ N_Vector *getNVectorArray(); /** * @brief accessor to NVector element * @param pos index of corresponding AmiVector * @return N_Vector */ N_Vector getNVector(int pos); /** * @brief const accessor to NVector element * @param pos index of corresponding AmiVector * @return N_Vector */ const_N_Vector getNVector(int pos) const; /** * @brief accessor to AmiVector elements * @param pos index of AmiVector * @return AmiVector */ AmiVector &operator[](int pos); /** * @brief const accessor to AmiVector elements * @param pos index of AmiVector * @return const AmiVector */ const AmiVector &operator[](int pos) const; /** * @brief length of AmiVectorArray * @return length */ int getLength() const; /** * @brief set every AmiVector in AmiVectorArray to zero */ void zero(); /** * @brief flattens the AmiVectorArray to a vector in row-major format * @param vec vector into which the AmiVectorArray will be flattened. Must * have length equal to number of elements. */ void flatten_to_vector(std::vector<realtype> &vec) const; /** * @brief copies data from another AmiVectorArray * @param other data source */ void copy(const AmiVectorArray &other); private: /** main data storage */ std::vector<AmiVector> vec_array_; /** * N_Vector array, will be synchronized such that it points to * respective elements in the vec_array */ std::vector<N_Vector> nvec_array_; }; /** * @brief Computes z = a*x + b*y * @param a coefficient for x * @param x a vector * @param b coefficient for y * @param y another vector with same size as x * @param z result vector of same size as x and y */ inline void linearSum(realtype a, AmiVector const& x, realtype b, AmiVector const& y, AmiVector& z) { N_VLinearSum(a, const_cast<N_Vector>(x.getNVector()), b, const_cast<N_Vector>(y.getNVector()), z.getNVector()); } /** * @brief Compute dot product of x and y * @param x vector * @param y vector * @return dot product of x and y */ inline realtype dotProd(AmiVector const& x, AmiVector const& y) { return N_VDotProd(const_cast<N_Vector>(x.getNVector()), const_cast<N_Vector>(y.getNVector())); } } // namespace amici namespace gsl { /** * @brief Create span from N_Vector * @param nv * @return */ inline span<realtype> make_span(N_Vector nv) { return span<realtype>(N_VGetArrayPointer(nv), N_VGetLength_Serial(nv)); } } // namespace gsl #endif /* AMICI_VECTOR_H */
{ "alphanum_fraction": 0.6228626321, "avg_line_length": 25.7037037037, "ext": "h", "hexsha": "102a75e7f84146d69642b1bd5d87e58a8821bd85", "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": "15f14c24b781daf5ceb3606d79edbbf57155a043", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "kristianmeyerr/AMICI", "max_forks_repo_path": "include/amici/vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "15f14c24b781daf5ceb3606d79edbbf57155a043", "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": "kristianmeyerr/AMICI", "max_issues_repo_path": "include/amici/vector.h", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "15f14c24b781daf5ceb3606d79edbbf57155a043", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "kristianmeyerr/AMICI", "max_stars_repo_path": "include/amici/vector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2627, "size": 10410 }
#define S_FUNCTION_NAME solve_chol #define S_FUNCTION_LEVEL 2 // Example: w = solve_chol(R,b); /* * Need to include simstruc.h for the definition of the SimStruct and * its associated macro definitions. */ #include <string.h> #include "simstruc.h" #include <lapacke.h> #if !defined(_WIN32) /* not Win32/Matlab */ #define dpotrs dpotrs_ #endif extern int_T dpotrs_(char *, int_T *, int_T *, real_T *, int_T *, real_T *, int_T *, int_T *); /*=========* * Defines * *=========*/ //#define SIZE_IDX 50 //#define SIZE_PARAM(S) ssGetSFcnParam(S,SIZE_IDX) #define NINPUTS 2 #define NOUTPUTS 1 static void mdlInitializeSizes(SimStruct *S) { int_T needsInput = 1; /* direct feedthrough */ ssSetNumSFcnParams(S, 0); /* Number of expected parameters */ if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) { /* * If the number of expected input parameters is not * equal to the number of parameters entered in the * dialog box, return. The Simulink engine generates an * error indicating that there is a parameter mismatch. */ return; } ssSetNumContStates( S, 0); ssSetNumDiscStates( S, 0); if (!ssSetNumInputPorts(S, NINPUTS)) return; /* R: a dynamically sized 2-D matrix input */ ssSetInputPortMatrixDimensions(S, 0, 50, 50); ssSetInputPortRequiredContiguous(S, 0, true); /*direct input signal access*/ ssSetInputPortDirectFeedThrough(S, 0, 1); /* b: a dynamically sized 1-D matrix input */ ssSetInputPortWidth(S, 0, 50); ssSetInputPortRequiredContiguous(S, 0, true); /*direct input signal access*/ ssSetInputPortDirectFeedThrough(S, 0, 1); if (!ssSetNumOutputPorts(S, NOUTPUTS)) return; /* b: a dynamically sized 1-D matrix output */ ssSetOutputPortWidth(S, 0, 50); /* * Set the number of sample times. */ ssSetNumSampleTimes(S, 1); /* Inherit the sample time. */ ssSetInputPortSampleTime(S, 0, INHERITED_SAMPLE_TIME); ssSetInputPortSampleTime(S, 1, INHERITED_SAMPLE_TIME); } /* Function: mdlInitializeSampleTimes ========================================= * Abstract: * Port based sample times have already been configured, therefore this * method doesn't need to perform any action (you can check the * current port sample times). */ static void mdlInitializeSampleTimes(SimStruct *S) { ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); ssSetModelReferenceSampleTimeDefaultInheritance(S); /* Inherit sample time */ } /* Function: mdlOutputs ======================================================= * Abstract: * * solve_chol - solve a linear system A*X = B using the Cholesky factorization * of A (square, symmetric and positive definite) using LAPACK/DPOTRS. * */ static void mdlOutputs(SimStruct *S, int_T tid) { int_T *dims1 = ssGetInputPortDimensions(S, 0); int_T *dims2 = ssGetInputPortDimensions(S, 1); int_T n1 = dims1[0]; /* number of rows in inputs A*/ int_T m1 = dims1[1]; /* number of columns in inputs A*/ int_T n2 = dims2[0]; /* number of rows in inputs B*/ int_T m2 = dims2[1]; /* number of columns in inputs B*/ int_T q; real_T *C = ssGetOutputPortSignal(S,0); real_T *A = ssGetInputPortSignal(S,0); real_T *B = ssGetInputPortSignal(S,1); UNUSED_ARG(tid); /* not used in single tasking mode */ if (n1 != m1) mexErrMsgTxt("First argument matrix must be square."); if (n1 != n2) mexErrMsgTxt("Both argument matrices must have the same number of rows."); // C = mxCreateDoubleMatrix(n, m, mxREAL); /* space for output X */ if (n1 == 0) return; /* if argument was empty matrix, do no more */ //memcpy( C, mxGetPr(B), m*n*mxGetElementSize(C) ); /* copy data */ dpotrs("U", &n1, &m2, mxGetPr(A), &n1, C, &n1, &q); /* solve system */ if (q < 0) mexErrMsgTxt("Error: illegal input to solve_chol"); }
{ "alphanum_fraction": 0.6438631791, "avg_line_length": 32.5901639344, "ext": "c", "hexsha": "71ca35967b79a6c57a48070c7e271e03eabe864b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-02-29T17:38:21.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-29T17:38:21.000Z", "max_forks_repo_head_hexsha": "e846493cafdcdb14d4233d2720c8c7cdb6144059", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "woutervandijk0/Inverse_dynamics_learning", "max_forks_repo_path": "Functions/solve_chol/simulink/solve_chol.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e846493cafdcdb14d4233d2720c8c7cdb6144059", "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": "woutervandijk0/Inverse_dynamics_learning", "max_issues_repo_path": "Functions/solve_chol/simulink/solve_chol.c", "max_line_length": 81, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e846493cafdcdb14d4233d2720c8c7cdb6144059", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "woutervandijk0/Inverse_dynamics_learning", "max_stars_repo_path": "Functions/solve_chol/simulink/solve_chol.c", "max_stars_repo_stars_event_max_datetime": "2021-01-28T02:13:36.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-10T21:24:44.000Z", "num_tokens": 1138, "size": 3976 }
/* specfunc/mathieu_coeff.c * * Copyright (C) 2002 Lowell Johnson * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: L. Johnson */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_sf_mathieu.h> /***************************************************************************** * backward_recurse * * Purpose: ****************************************************************************/ static void backward_recurse_c(double aa, double qq, double xx, double *ff, double *gx, int even_odd, int ni) { int ii, nn; double g1; g1 = *gx; ff[ni] = xx; if (even_odd == 0) { for (ii=0; ii<ni; ii++) { nn = GSL_SF_MATHIEU_COEFF - ii - 1; ff[ni-ii-1] = -1.0/((4*nn*nn - aa)/qq + ff[ni-ii]); } if (ni == GSL_SF_MATHIEU_COEFF - 1) ff[0] *= 2.0; } else { for (ii=0; ii<ni; ii++) { nn = GSL_SF_MATHIEU_COEFF - ii - 1; ff[ni-ii-1] = -1.0/(((2*nn + 1)*(2*nn + 1) - aa)/qq + ff[ni-ii]); } } *gx = ff[0] - g1; } static void backward_recurse_s(double aa, double qq, double xx, double *ff, double *gx, int even_odd, int ni) { int ii, nn; double g1; g1 = *gx; ff[ni] = xx; if (even_odd == 0) { for (ii=0; ii<ni; ii++) { nn = GSL_SF_MATHIEU_COEFF - ii - 1; ff[ni-ii-1] = -1.0/((4*(nn + 1)*(nn + 1) - aa)/qq + ff[ni-ii]); } } else { for (ii=0; ii<ni; ii++) { nn = GSL_SF_MATHIEU_COEFF - ii - 1; ff[ni-ii-1] = -1.0/(((2*nn + 1)*(2*nn + 1) - aa)/qq + ff[ni-ii]); } } *gx = ff[0] - g1; } int gsl_sf_mathieu_a_coeff(int order, double qq, double aa, double coeff[]) { int ni, nn, ii, even_odd; double eps, g1, g2, x1, x2, e1, e2, de, xh, sum, ratio, ff[GSL_SF_MATHIEU_COEFF]; eps = 1e-14; coeff[0] = 1.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* If the coefficient array is not large enough to hold all necessary coefficients, error out. */ if (order > GSL_SF_MATHIEU_COEFF) return GSL_FAILURE; /* Handle the trivial case where q = 0. */ if (qq == 0.0) { for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) coeff[ii] = 0.0; coeff[order/2] = 1.0; return GSL_SUCCESS; } if (order < 5) { nn = 0; sum = 0.0; if (even_odd == 0) ratio = aa/qq; else ratio = (aa - 1 - qq)/qq; } else { if (even_odd == 0) { coeff[1] = aa/qq; coeff[2] = (aa - 4)/qq*coeff[1] - 2; sum = coeff[0] + coeff[1] + coeff[2]; for (ii=3; ii<order/2+1; ii++) { coeff[ii] = (aa - 4*(ii - 1)*(ii - 1))/qq*coeff[ii-1] - coeff[ii-2]; sum += coeff[ii]; } } else { coeff[1] = (aa - 1)/qq - 1; sum = coeff[0] + coeff[1]; for (ii=2; ii<order/2+1; ii++) { coeff[ii] = (aa - (2*ii - 1)*(2*ii - 1))/qq*coeff[ii-1] - coeff[ii-2]; sum += coeff[ii]; } } nn = ii - 1; ratio = coeff[nn]/coeff[nn-1]; } ni = GSL_SF_MATHIEU_COEFF - nn - 1; /* Compute first two points to start root-finding. */ if (even_odd == 0) x1 = -qq/(4.0*GSL_SF_MATHIEU_COEFF*GSL_SF_MATHIEU_COEFF); else x1 = -qq/((2.0*GSL_SF_MATHIEU_COEFF + 1.0)*(2.0*GSL_SF_MATHIEU_COEFF + 1.0)); g1 = ratio; backward_recurse_c(aa, qq, x1, ff, &g1, even_odd, ni); x2 = g1; g2 = ratio; backward_recurse_c(aa, qq, x2, ff, &g2, even_odd, ni); /* Find the root. */ while (1) { /* Compute the relative error. */ e1 = g1 - x1; e2 = g2 - x2; de = e1 - e2; /* If we are close enough to the root, break... */ if (fabs(de) < eps) break; /* Otherwise, determine the next guess and try again. */ xh = (e1*x2 - e2*x1)/de; x1 = x2; g1 = g2; x2 = xh; g2 = ratio; backward_recurse_c(aa, qq, x2, ff, &g2, even_odd, ni); } /* Compute the rest of the coefficients. */ sum += coeff[nn]; for (ii=nn+1; ii<GSL_SF_MATHIEU_COEFF; ii++) { coeff[ii] = ff[ii-nn-1]*coeff[ii-1]; sum += coeff[ii]; /* If the coefficients are getting really small, set the remainder to zero. */ if (fabs(coeff[ii]) < 1e-20) { for (; ii<GSL_SF_MATHIEU_COEFF;) coeff[ii++] = 0.0; } } /* Normalize the coefficients. */ for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) coeff[ii] /= sum; return GSL_SUCCESS; } int gsl_sf_mathieu_b_coeff(int order, double qq, double aa, double coeff[]) { int ni, nn, ii, even_odd; double eps, g1, g2, x1, x2, e1, e2, de, xh, sum, ratio, ff[GSL_SF_MATHIEU_COEFF]; eps = 1e-10; coeff[0] = 1.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* If the coefficient array is not large enough to hold all necessary coefficients, error out. */ if (order > GSL_SF_MATHIEU_COEFF) return GSL_FAILURE; /* Handle the trivial case where q = 0. */ if (qq == 0.0) { for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) coeff[ii] = 0.0; coeff[(order-1)/2] = 1.0; return GSL_SUCCESS; } if (order < 5) { nn = 0; sum = 0.0; if (even_odd == 0) ratio = (aa - 4)/qq; else ratio = (aa - 1 - qq)/qq; } else { if (even_odd == 0) { coeff[1] = (aa - 4)/qq; sum = 2*coeff[0] + 4*coeff[1]; for (ii=2; ii<order/2; ii++) { coeff[ii] = (aa - 4*ii*ii)/qq*coeff[ii-1] - coeff[ii-2]; sum += 2*(ii + 1)*coeff[ii]; } } else { coeff[1] = (aa - 1)/qq + 1; sum = coeff[0] + 3*coeff[1]; for (ii=2; ii<order/2+1; ii++) { coeff[ii] = (aa - (2*ii - 1)*(2*ii - 1))/qq*coeff[ii-1] - coeff[ii-2]; sum += (2*(ii + 1) - 1)*coeff[ii]; } } nn = ii - 1; ratio = coeff[nn]/coeff[nn-1]; } ni = GSL_SF_MATHIEU_COEFF - nn - 1; /* Compute first two points to start root-finding. */ if (even_odd == 0) x1 = -qq/(4.0*(GSL_SF_MATHIEU_COEFF + 1.0)*(GSL_SF_MATHIEU_COEFF + 1.0)); else x1 = -qq/((2.0*GSL_SF_MATHIEU_COEFF + 1.0)*(2.0*GSL_SF_MATHIEU_COEFF + 1.0)); g1 = ratio; backward_recurse_s(aa, qq, x1, ff, &g1, even_odd, ni); x2 = g1; g2 = ratio; backward_recurse_s(aa, qq, x2, ff, &g2, even_odd, ni); /* Find the root. */ while (1) { /* Compute the relative error. */ e1 = g1 - x1; e2 = g2 - x2; de = e1 - e2; /* If we are close enough to the root, break... */ if (fabs(de) < eps) break; /* Otherwise, determine the next guess and try again. */ xh = (e1*x2 - e2*x1)/de; x1 = x2; g1 = g2; x2 = xh; g2 = ratio; backward_recurse_s(aa, qq, x2, ff, &g2, even_odd, ni); } /* Compute the rest of the coefficients. */ sum += 2*(nn + 1)*coeff[nn]; for (ii=nn+1; ii<GSL_SF_MATHIEU_COEFF; ii++) { coeff[ii] = ff[ii-nn-1]*coeff[ii-1]; sum += 2*(ii + 1)*coeff[ii]; /* If the coefficients are getting really small, set the remainder to zero. */ if (fabs(coeff[ii]) < 1e-20) { for (; ii<GSL_SF_MATHIEU_COEFF;) coeff[ii++] = 0.0; } } /* Normalize the coefficients. */ for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) coeff[ii] /= sum; return GSL_SUCCESS; }
{ "alphanum_fraction": 0.4905238376, "avg_line_length": 24.340974212, "ext": "c", "hexsha": "960b37e677a3683e6c6c6f86fa54955c43a73cf1", "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/mathieu_coeff.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/mathieu_coeff.c", "max_line_length": 83, "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/mathieu_coeff.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": 2863, "size": 8495 }
#include <math.h> #include <gsl/gsl_linalg.h> #include "advanceCN.h" #include "applyBC.h" #include "userFunc.h" #include "ppmExtrap.h" #include "getNextIterate.h" /**************************************************************************/ /* Time step advance routine with Crank-Nicolson time centering */ /**************************************************************************/ double advanceCN(const double t, const double dt, const grid *grd, double *col, double *pres, double *eInt, double *mBnd, double *eBnd, double *mSrc, double *eSrc, const bool eos_func, const double gamma_val, const double delta_val, const bool alpha_func, const double alpha_val, const pres_bc_type ibc_pres, const enth_bc_type ibc_enth, const bool ibc_func, const double ibc_pres_val, const double ibc_enth_val, const pres_bc_type obc_pres, const enth_bc_type obc_enth, const bool obc_func, const double obc_pres_val, const double obc_enth_val, const bool massSrc_func, const double massSrc_val, const bool intEnSrc_func, const double intEnSrc_val, const double errTol, const double dtTol, const unsigned long maxIter, const unsigned long interpOrder, const bool noUpdate, const bool verbose, const wksp *w, void *params, unsigned long *itCount #ifdef TESTING_MODE , double *resid, unsigned long *rtype, double *advanceTime, double *nextIterTime, double *userTime #endif ) { double pIn, qIn, pOut, qOut; double err, errCell; double dPres, dCol, dEInt, dtMin; double ibc_pres_val1, ibc_enth_val1, obc_pres_val1, obc_enth_val1; double h_up, h_up1; double mBndTemp[2], eBndTemp[2]; unsigned long maxErrCell, converged, residType; long i; #if AA_M > 0 long nHist; double residMax = 0.0; #endif #ifdef TESTING_MODE clock_t start_t, end_t, user_start_t, user_end_t; clock_t next_iter_start_t, next_iter_end_t; start_t = clock(); #endif /****************************************************************/ /* Step 1: initialize workspace arrays from starting conditions */ /****************************************************************/ /* Copy column density and pressure */ for (i=0; i<grd->nr; i++) { w->colNew[i] = col[i]; w->pres_g[i+1] = w->presNew_g[i+1] = pres[i]; } /* Evaluate EOS parameters and get enthalpy */ if (eos_func == 1) { #if AA_M > 0 nHist = 3*grd->nr; #endif #ifdef TESTING_MODE user_start_t = clock(); #endif userEOS(t, dt, grd, col, pres, eInt, params, w->gammaLast, w->deltaLast); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif for (i=0; i<grd->nr; i++) { w->eIntTmp[i] = w->eIntNew[i] = eInt[i]; w->gammaNew[i] = w->gammaLast[i]; w->deltaNew[i] = w->deltaLast[i]; w->hint_g[i+1] = (pres[i] + eInt[i])/col[i]; } } else { #if AA_M > 0 nHist = 2*grd->nr; #endif for (i=0; i<grd->nr; i++) { w->gammaLast[i] = w->gammaNew[i] = gamma_val; w->deltaLast[i] = w->deltaNew[i] = delta_val; w->hint_g[i+1] = gamma_val/(gamma_val-1.0)*pres[i]/col[i]; } } /* Get starting viscosity */ if (alpha_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userAlpha(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, params, w->alpha_g+1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } else { for (i=1; i<=grd->nr; i++) w->alpha_g[i] = alpha_val; } /* Store starting mass and energy fluxes through boundary */ mBndTemp[0] = mBnd[0]; mBndTemp[1] = mBnd[1]; eBndTemp[0] = eBnd[0]; eBndTemp[1] = eBnd[1]; /* Store starting source function values */ if (massSrc_func == 1) { for (i=0; i<grd->nr; i++) { w->mSrc[i] = mSrc[i]; w->eSrc[i] = eSrc[i]; } } else if (intEnSrc_func == 1) { for (i=0; i<grd->nr; i++) w->eSrc[i] = eSrc[i]; } /****************************************************************/ /* Step 2: apply boundary conditions at old time */ /****************************************************************/ /* Set alpha in ghost cells */ w->alpha_g[0] = w->alpha_g[1]; w->alpha_g[grd->nr+1] = w->alpha_g[grd->nr]; /* Get pressure / enthalpy boundary values */ if (ibc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userIBC(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, ibc_pres, ibc_enth, params, &ibc_pres_val1, &ibc_enth_val1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } else { ibc_pres_val1 = ibc_pres_val; ibc_enth_val1 = ibc_enth_val; } if (obc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userOBC(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, obc_pres, obc_enth, params, &obc_pres_val1, &obc_enth_val1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } else { obc_pres_val1 = obc_pres_val; obc_enth_val1 = obc_enth_val; } /* Set boundary conditions from user-specified parameters */ applyBC(grd, w->alpha_g, ibc_pres, ibc_enth, ibc_pres_val1, ibc_enth_val1, obc_pres, obc_enth, obc_pres_val1, obc_enth_val1, w->pres_g, w->hint_g, &pIn, &qIn, &pOut, &qOut); /****************************************************************/ /* Step 3: get mass flux, source terms, and RHS at old time */ /****************************************************************/ /* Mass and energy source terms */ if (massSrc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userMassSrc(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, params, w->massSrcLast); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif for (i=0; i<grd->nr; i++) { w->mSrc[i] += 0.5 * dt * w->massSrcLast[i]; w->eSrc[i] += 0.5 * dt * w->massSrcLast[i] * (grd->psiEff_g[i+1] + w->deltaLast[i]*pres[i]/col[i]); } } else { for (i=0; i<grd->nr; i++) w->massSrcLast[i] = massSrc_val; } if (intEnSrc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userIntEnSrc(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, params, w->intEnSrc); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif for (i=0; i<grd->nr; i++) w->eSrc[i] += 0.5 * dt * w->intEnSrc[i]; } else { for (i=0; i<grd->nr; i++) w->intEnSrc[i] = intEnSrc_val; } /* Reconstruct internal enthalpies at cell edges */ if (interpOrder == 1) { for (i=0; i<=grd->nr+1; i++) w->hintL_g[i] = w->hintR_g[i] = w->hint_g[i]; } else if (interpOrder == 2) { if (grd->linear == 1) { for (i=1; i<=grd->nr+1; i++) w->hintR_g[i-1] = w->hintL_g[i] = ((grd->r_g[i]-grd->r_h[i-1]) * w->hint_g[i-1] + (grd->r_h[i-1]-grd->r_g[i-1]) * w->hint_g[i]) / (grd->r_g[i] - grd->r_g[i-1]); } else { for (i=1; i<=grd->nr+1; i++) w->hintR_g[i-1] = w->hintL_g[i] = (log(grd->r_g[i]/grd->r_h[i-1]) * w->hint_g[i-1] + log(grd->r_h[i-1]/grd->r_g[i-1]) * w->hint_g[i]) / log(grd->r_g[i]/grd->r_g[i-1]); } /* Limit the slope */ for (i=1; i<=grd->nr+1; i++) { if (w->hintR_g[i-1]/w->hint_g[i-1]-1.0 > SLOPELIMIT) { w->hintR_g[i-1] = w->hint_g[i-1]*(1.0+SLOPELIMIT); } else if (w->hintR_g[i-1]/w->hint_g[i-1] < 1.0-SLOPELIMIT) { w->hintR_g[i-1] = w->hint_g[i-1]*(1.0-SLOPELIMIT); } if (w->hintL_g[i]/w->hint_g[i]-1.0 > SLOPELIMIT) { w->hintL_g[i] = w->hint_g[i]*(1.0+SLOPELIMIT); } else if (w->hintL_g[i]/w->hint_g[i] < 1.0-SLOPELIMIT) { w->hintL_g[i] = w->hint_g[i]*(1.0-SLOPELIMIT); } } } else if (interpOrder == 3) { ppmExtrap(grd->nr+2, grd->dr_g, w->hint_g, w->hintL_g, w->hintR_g, w->ppmwksp_g); } /* Compute fluxes at cell edges */ for (i=0; i<=grd->nr; i++) { /* Mass flux; initialize the new mass flux to match the old one, as is appropriate for the first guess in the iteration below */ w->fmLast_h[i] = w->fmNew_h[i] = -grd->g_h[i] * (SQR(grd->r_g[i+1])*(1-grd->beta_g[i+1]) * w->pres_g[i+1]*w->alpha_g[i+1] - SQR(grd->r_g[i])*(1-grd->beta_g[i]) * w->pres_g[i]*w->alpha_g[i]); /* Enthalpy flux; use upwinding */ if (w->fmLast_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i]; else h_up = w->hintL_g[i+1] + grd->psiEff_h[i]; w->feLast_h[i] = h_up * w->fmLast_h[i]; /* Torque flux */ w->ftLast_h[i] = M_PI * grd->r_h[i] * grd->vphi_h[i] * (1-grd->beta_h[i]) * (w->pres_g[i+1]*w->alpha_g[i+1] + w->pres_g[i]*w->alpha_g[i]); } /* Fill RHS vector */ for (i=0; i<grd->nr; i++) { gsl_vector_set(w->rhs_g, i+1, pres[i] - 0.5*dt/grd->area[i] * (w->gammaLast[i]-1.0) * (w->feLast_h[i+1] - w->feLast_h[i] + w->ftLast_h[i+1] - w->ftLast_h[i] - (grd->psiEff_g[i+1] + w->deltaLast[i+1]*pres[i]/col[i]) *(w->fmLast_h[i+1] - w->fmLast_h[i])) + 0.5*dt*(w->gammaLast[i]-1) * w->intEnSrc[i]); } /* Zero out energy source, since below we expect this to be the rate from the previous iteration of the loop */ for (i=0; i<grd->nr; i++) w->intEnSrc[i] = 0.0; /****************************************************************/ /* Step 4: main iteration loop */ /****************************************************************/ /* Status message */ if (verbose) printf("advanceCN: starting iteration, dt = %e\n", dt); /* Start loop */ for (*itCount = 1, converged = 0; 1; (*itCount)++) { /**************************************************************/ /* Step 4a: compute enthalpy, alpha, and BC for current guess */ /**************************************************************/ /* Get new EOS parameters and cell-center enthalpies */ if (eos_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userEOS(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew, params, w->gammaNew, w->deltaNew); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif for (i=1; i<=grd->nr; i++) w->hint_g[i] = (w->presNew_g[i] + w->eIntNew[i-1]) / w->colNew[i-1]; } else { for (i=1; i<=grd->nr; i++) { w->hint_g[i] = gamma_val/(gamma_val-1.0) * w->presNew_g[i]/w->colNew[i-1]; } } /* If alpha is non-constant, get new values */ if (alpha_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userAlpha(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew, w->gammaNew, w->deltaNew, params, w->alpha_g+1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif w->alpha_g[0] = w->alpha_g[1]; w->alpha_g[grd->nr+1] = w->alpha_g[grd->nr]; } /* Subtract off energy source term from previous iteration; we need to do this here because we're about to update gamma */ for (i=0; i<grd->nr; i++) { gsl_vector_set(w->rhs_g, i+1, gsl_vector_get(w->rhs_g, i+1) - 0.5*dt*(w->gammaNew[i]-1)*w->intEnSrc[i]); } /* Get new pressure / enthalpy boundary values */ if (ibc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userIBC(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew, w->gammaNew, w->deltaNew, ibc_pres, ibc_enth, params, &ibc_pres_val1, &ibc_enth_val1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } if (obc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userOBC(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew, w->gammaNew, w->deltaNew, obc_pres, obc_enth, params, &obc_pres_val1, &obc_enth_val1); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } /* Set boundary conditions from user-specified parameters, and also set ghost cell elements in RHS matrix */ applyBC(grd, w->alpha_g, ibc_pres, ibc_enth, ibc_pres_val1, ibc_enth_val1, obc_pres, obc_enth, obc_pres_val1, obc_enth_val1, w->presNew_g, w->hint_g, &pIn, &qIn, &pOut, &qOut); gsl_vector_set(w->rhs_g, 0, pIn); gsl_vector_set(w->rhs_g, grd->nr+1, pOut); /* Get new enthalpies at cell centers and extrapolated to cell edges */ if (interpOrder == 1) { for (i=0; i<=grd->nr+1; i++) w->hintL_g[i] = w->hintR_g[i] = w->hint_g[i]; } else if (interpOrder == 2) { if (grd->linear == 1) { for (i=1; i<=grd->nr+1; i++) w->hintR_g[i-1] = w->hintL_g[i] = ((grd->r_g[i]-grd->r_h[i-1]) * w->hint_g[i-1] + (grd->r_h[i-1]-grd->r_g[i-1]) * w->hint_g[i]) / (grd->r_g[i] - grd->r_g[i-1]); } else { for (i=1; i<=grd->nr+1; i++) w->hintR_g[i-1] = w->hintL_g[i] = (log(grd->r_g[i]/grd->r_h[i-1]) * w->hint_g[i-1] + log(grd->r_h[i-1]/grd->r_g[i-1]) * w->hint_g[i]) / log(grd->r_g[i]/grd->r_g[i-1]); } /* Limit the slope */ for (i=1; i<=grd->nr+1; i++) { if (w->hintR_g[i-1]/w->hint_g[i-1]-1.0 > SLOPELIMIT) { w->hintR_g[i-1] = w->hint_g[i-1]*(1.0+SLOPELIMIT); } else if (w->hintR_g[i-1]/w->hint_g[i-1] < 1.0-SLOPELIMIT) { w->hintR_g[i-1] = w->hint_g[i-1]*(1.0-SLOPELIMIT); } if (w->hintL_g[i]/w->hint_g[i]-1.0 > SLOPELIMIT) { w->hintL_g[i] = w->hint_g[i]*(1.0+SLOPELIMIT); } else if (w->hintL_g[i]/w->hint_g[i] < 1.0-SLOPELIMIT) { w->hintL_g[i] = w->hint_g[i]*(1.0-SLOPELIMIT); } } } else if (interpOrder == 3) { ppmExtrap(grd->nr+2, grd->dr_g, w->hint_g, w->hintL_g, w->hintR_g, w->ppmwksp_g); } /**************************************************************/ /* Step 4b: add energy source term to RHS vector for pressure */ /* solve */ /**************************************************************/ /* If source term can vary, compute its value for this iteration */ if (intEnSrc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userIntEnSrc(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew, w->gammaNew, w->deltaNew, params, w->intEnSrc); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } for (i=0; i<grd->nr; i++) { gsl_vector_set(w->rhs_g, i+1, gsl_vector_get(w->rhs_g, i+1) + 0.5*dt*(w->gammaNew[i]-1)*w->intEnSrc[i]); } /**************************************************************/ /* Step 4c: construct the tridiagonal matrix */ /**************************************************************/ /* Upper diagonal */ gsl_vector_set(w->ud_g, 0, -qIn); for (i=1; i<=grd->nr; i++) { if (w->fmNew_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i]; else h_up = w->hintL_g[i+1] + grd->psiEff_h[i]; gsl_vector_set(w->ud_g, i, 0.5*dt*w->alpha_g[i+1]*(w->gammaNew[i-1]-1.0) / grd->area[i-1] * (grd->g_h[i]*SQR(grd->r_g[i+1]) * (1-grd->beta_g[i+1]) * (grd->psiEff_g[i] + w->deltaNew[i-1] * w->presNew_g[i]/w->colNew[i-1] - h_up) + M_PI*grd->r_h[i]*grd->vphi_h[i] * (1-grd->beta_h[i]))); } /* Lower diagonal */ for (i=0; i<grd->nr; i++) { if (w->fmNew_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i]; else h_up = w->hintL_g[i+1] + grd->psiEff_h[i]; gsl_vector_set(w->ld_g, i, 0.5*dt*w->alpha_g[i]*(w->gammaNew[i]-1.0) / grd->area[i] * (grd->g_h[i]*SQR(grd->r_g[i]) * (1-grd->beta_g[i]) * (grd->psiEff_g[i+1] + w->deltaNew[i] * w->presNew_g[i+1]/w->colNew[i] - h_up) - M_PI*grd->r_h[i]*grd->vphi_h[i] * (1-grd->beta_h[i]))); } gsl_vector_set(w->ld_g, grd->nr, -qOut); /* Diagonal */ for (i=1; i<=grd->nr; i++) { if (w->fmNew_h[i-1] > 0) h_up = w->hintR_g[i-1] + grd->psiEff_h[i-1]; else h_up = w->hintL_g[i] + grd->psiEff_h[i-1]; if (w->fmNew_h[i] > 0) h_up1 = w->hintR_g[i] + grd->psiEff_h[i]; else h_up1 = w->hintL_g[i+1] + grd->psiEff_h[i]; gsl_vector_set(w->diag_g, i, 1.0 + 0.5*dt*w->alpha_g[i]*(w->gammaNew[i-1]-1.0) / grd->area[i-1] * ((grd->g_h[i]* (h_up1 - grd->psiEff_g[i] - w->deltaNew[i-1] * w->presNew_g[i]/w->colNew[i-1]) + grd->g_h[i-1]* (h_up - grd->psiEff_g[i] - w->deltaNew[i-1] * w->presNew_g[i]/w->colNew[i-1])) * SQR(grd->r_g[i]) * (1-grd->beta_g[i]) + M_PI*(grd->r_h[i]*grd->vphi_h[i]* (1-grd->beta_h[i]) - grd->r_h[i-1]*grd->vphi_h[i-1]* (1-grd->beta_h[i-1])))); } /**************************************************************/ /* Step 4d: solve the matrix equation to get the new pressure */ /* guess */ /**************************************************************/ if (gsl_linalg_solve_tridiag(w->diag_g, w->ud_g, w->ld_g, w->rhs_g, w->presTmp_g)) { /* Non-zero return code means error has occured, probably due to bad inputs data. Bail out, and let the driver try again */ if (verbose) printf(" ...iteration %ld, detected NaN or Inf in tridiagonal inputs, exiting without convergence!\n", *itCount); #ifdef TESTING_MODE end_t = clock(); *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC; #endif return(-1.0); } /**************************************************************/ /* Step 4e: get the new column density guess */ /**************************************************************/ /* Get new mass fluxes */ for (i=0; i<=grd->nr; i++) w->fmNew_h[i] = -grd->g_h[i] * (SQR(grd->r_g[i+1])* (1-grd->beta_g[i+1]) * gsl_vector_get(w->presTmp_g, i+1)*w->alpha_g[i+1] - SQR(grd->r_g[i])* (1-grd->beta_g[i]) * gsl_vector_get(w->presTmp_g, i)*w->alpha_g[i]); /* Get source terms at new time */ if (massSrc_func == 1) { #ifdef TESTING_MODE user_start_t = clock(); #endif userMassSrc(t+dt, dt, grd, w->colNew, w->presNew_g, w->eIntNew, w->gammaNew, w->deltaNew, params, w->massSrcNew); #ifdef TESTING_MODE user_end_t = clock(); *userTime += (double) (user_end_t - user_start_t) / CLOCKS_PER_SEC; #endif } else { for (i=0; i<grd->nr; i++) w->massSrcNew[i] = massSrc_val; } /* Get new column density guess */ for (i=0; i<grd->nr; i++) { w->colTmp[i] = col[i] - dt/grd->area[i] * 0.5 * (w->fmNew_h[i+1] - w->fmNew_h[i] + w->fmLast_h[i+1] - w->fmLast_h[i]) + dt * 0.5 * (w->massSrcLast[i] + w->massSrcNew[i]); } /**************************************************************/ /* Step 4f: if doing separate internal energy evolution, get */ /* new internal energy guess */ /**************************************************************/ if (eos_func == 1) { for (i=0; i<grd->nr; i++) { w->eIntTmp[i] = eInt[i] + 0.5 * (1.0/(w->gammaLast[i]-1.0) + 1.0/(w->gammaNew[i]-1.0)) * (gsl_vector_get(w->presTmp_g, i+1) - pres[i]) + 0.5 * (w->deltaLast[i]*pres[i]/col[i] + w->deltaNew[i]*gsl_vector_get(w->presTmp_g, i+1) / w->colTmp[i]) * (w->colTmp[i]-col[i]); } } /**************************************************************/ /* Step 4g: check for convergence or loop termination; print */ /* status message */ /**************************************************************/ /* Compute residuals on pressure */ err = 0.0; maxErrCell = -1; residType = 0; for (i=0; i<grd->nr; i++) { if (!isfinite(gsl_vector_get(w->presTmp_g, i+1))) { /* If we've diverged to the point of getting inf's, we won't converge, so bail out */ if (verbose) printf(" ...iteration %ld, detected NaN or Inf in tridiagonal solution, cell %ld, exiting without convergence!\n", *itCount, i); #ifdef TESTING_MODE end_t = clock(); *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC; #endif return(-1.0); } errCell = (gsl_vector_get(w->presTmp_g, i+1) - w->presNew_g[i+1]) / gsl_vector_get(w->presTmp_g, i+1); if (fabs(errCell) > fabs(err)) { maxErrCell = i; err = errCell; } } /* Compute residuals on column density */ for (i=0; i<grd->nr; i++) { errCell = (w->colTmp[i] - w->colNew[i]) / w->colTmp[i]; if (fabs(errCell) > fabs(err)) { maxErrCell = i; err = errCell; residType = 1; } } /* Compute residuals on internal energy */ for (i=0; i<grd->nr; i++) { errCell = (w->eIntTmp[i] - w->eIntNew[i]) / w->eIntTmp[i]; if (fabs(errCell) > fabs(err)) { maxErrCell = i; err = errCell; residType = 2; } } #ifdef TESTING_MODE /* In testing mode, store residuals and residual type */ resid[*itCount-1] += err; rtype[*itCount-1] = residType; #endif /* Print status */ if (fabs(err) < errTol) converged = 1; if (verbose) { printf(" ...iteration %ld, max residual = %e in cell %ld", *itCount, err, maxErrCell); if (residType==0) printf(" pressure\n"); else if (residType==1) printf(" density\n"); else if (residType==2) printf(" internal energy\n"); if (converged == 1) { printf(" ...converged!\n"); } else if (*itCount == maxIter) { printf(" ...reached maximum iterations, exiting without convergence! Max residual = %e in cell %ld\n", err, maxErrCell); } } /* If we have converged, shift temporaries into final arrays, then exit the loop */ if (converged) { for (i=0; i<grd->nr; i++) { w->colNew[i] = w->colTmp[i]; w->presNew_g[i+1] = gsl_vector_get(w->presTmp_g, i+1); if (eos_func == 1) w->eIntNew[i] = w->eIntTmp[i]; } w->presNew_g[0] = gsl_vector_get(w->presTmp_g, 0); w->presNew_g[grd->nr+1] = gsl_vector_get(w->presTmp_g, grd->nr+1); break; } /* If we've exceeded iteration limit, bail out */ if (*itCount == maxIter) { #ifdef TESTING_MODE end_t = clock(); *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC; #endif return(-1.0); } /**************************************************************/ /* Step 4h: if we're here, we haven't converged yet, so use */ /* Anderson acceleration to generate new guesses at solution */ /**************************************************************/ #ifdef TESTING_MODE next_iter_start_t = clock(); #endif getNextIterate(grd, eos_func, w #if AA_M > 0 , *itCount, nHist, &residMax #endif ); #ifdef TESTING_MODE next_iter_end_t = clock(); *nextIterTime += (double) (next_iter_end_t - next_iter_start_t) / CLOCKS_PER_SEC; #endif } /* End main iteration loop */ /****************************************************************/ /* Step 5: compute rate of change of pressure and column */ /* density; use this to estimate new time step */ /****************************************************************/ dtMin = LARGE; for (i=0; i<grd->nr; i++) { dCol = fabs(w->colNew[i] - col[i]) + SMALL; dPres = fabs(w->presNew_g[i+1] - pres[i]) + SMALL; dtMin = fmin( dtMin, dtTol*dt * fmin(col[i]/dCol, pres[i]/dPres) ); if (eos_func == 1) { dEInt = fabs(w->eIntNew[i] - eInt[i]) + SMALL; dtMin = fmin( dtMin, dtTol*dt * eInt[i]/dEInt ); } } if (verbose > 0) printf("advanceCN: estimated dtNew = %e\n", dtMin); /****************************************************************/ /* Step 6: record the total mass and energy transported across */ /* the inner and outer boundaries during this time step. */ /****************************************************************/ /* Mass fluxes */ mBndTemp[0] += 0.5*dt*(w->fmLast_h[0] + w->fmNew_h[0]); mBndTemp[1] += 0.5*dt*(w->fmLast_h[grd->nr] + w->fmNew_h[grd->nr]); /* Old time energy fluxes */ eBndTemp[0] += 0.5*dt*(w->feLast_h[0] + w->ftLast_h[0]); eBndTemp[1] += 0.5*dt*(w->feLast_h[grd->nr] + w->ftLast_h[grd->nr]); /* New time energy fluxes; need to get enthalpy to evaluate f_E */ if (w->fmNew_h[0] > 0) h_up = w->hintR_g[0] + grd->psiEff_h[0]; else h_up = w->hintL_g[1] + grd->psiEff_h[0]; eBndTemp[0] += 0.5*dt*h_up*w->fmNew_h[0]; if (w->fmNew_h[grd->nr] > 0) h_up1 = w->hintR_g[grd->nr] + grd->psiEff_h[grd->nr]; else h_up1 = w->hintL_g[grd->nr+1] + grd->psiEff_h[grd->nr]; eBndTemp[1] += 0.5*dt*h_up1*w->fmNew_h[grd->nr]; /* New time torque fluxes */ eBndTemp[0] += 0.5*dt*M_PI*grd->r_h[0]*grd->vphi_h[0]*(1.0-grd->beta_h[0]) * (w->presNew_g[1]*w->alpha_g[1] + w->presNew_g[0]*w->alpha_g[0]); eBndTemp[1] += 0.5*dt*M_PI*grd->r_h[grd->nr]*grd->vphi_h[grd->nr] *(1.0-grd->beta_h[grd->nr]) * (w->presNew_g[grd->nr+1]*w->alpha_g[grd->nr+1] + w->presNew_g[grd->nr]*w->alpha_g[grd->nr]); /****************************************************************/ /* Step 7: if using source functions, record total mass and */ /* energy added to every cell by sources */ /****************************************************************/ ; if (massSrc_func == 1) { for (i=0; i<grd->nr; i++) { w->mSrc[i] += 0.5 * dt * w->massSrcNew[i]; w->eSrc[i] += 0.5 * dt * w->massSrcNew[i] * (grd->psiEff_g[i+1] + w->deltaNew[i]*w->presNew_g[i+1]/w->colNew[i]); } } if (intEnSrc_func == 1) { for (i=0; i<grd->nr; i++) w->eSrc[i] += 0.5 * dt * w->intEnSrc[i]; } /****************************************************************/ /* Step 8: store final values in arrays */ /****************************************************************/ if (noUpdate==0) { for (i=0; i<grd->nr; i++) { pres[i] = w->presNew_g[i+1]; col[i] = w->colNew[i]; } if (eos_func==1) for (i=0; i<grd->nr; i++) eInt[i] = w->eIntNew[i]; mBnd[0] = mBndTemp[0]; mBnd[1] = mBndTemp[1]; eBnd[0] = eBndTemp[0]; eBnd[1] = eBndTemp[1]; if (massSrc_func == 1) { for (i=0; i<grd->nr; i++) { mSrc[i] = w->mSrc[i]; eSrc[i] = w->eSrc[i]; } } else if (intEnSrc_func == 1) { for (i=0; i<grd->nr; i++) eSrc[i] = w->eSrc[i]; } } /****************************************************************/ /* Step 9: return new time step */ /****************************************************************/ #ifdef TESTING_MODE end_t = clock(); *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC; #endif return(dtMin); }
{ "alphanum_fraction": 0.5161408255, "avg_line_length": 33.3166869671, "ext": "c", "hexsha": "e1b9c950b0fd448c109b5c7ed9412049367d5f5f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "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": "franciscaconcha/amuse-vader", "max_issues_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_line_length": 133, "max_stars_count": null, "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9257, "size": 27353 }
/* interpolation/gsl_interp.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #ifndef __GSL_INTERP_H__ #define __GSL_INTERP_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* evaluation accelerator */ typedef struct { size_t cache; /* cache of index */ size_t miss_count; /* keep statistics */ size_t hit_count; } gsl_interp_accel; /* interpolation object type */ typedef struct { const char * name; unsigned int min_size; void * (*alloc) (size_t size); int (*init) (void *, const double xa[], const double ya[], size_t size); int (*eval) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y); int (*eval_deriv) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_p); int (*eval_deriv2) (const void *, const double xa[], const double ya[], size_t size, double x, gsl_interp_accel *, double * y_pp); int (*eval_integ) (const void *, const double xa[], const double ya[], size_t size, gsl_interp_accel *, double a, double b, double * result); void (*free) (void *); } gsl_interp_type; /* general interpolation object */ typedef struct { const gsl_interp_type * type; double xmin; double xmax; size_t size; void * state; } gsl_interp; /* available types */ GSL_VAR const gsl_interp_type * gsl_interp_linear; GSL_VAR const gsl_interp_type * gsl_interp_polynomial; GSL_VAR const gsl_interp_type * gsl_interp_cspline; GSL_VAR const gsl_interp_type * gsl_interp_cspline_periodic; GSL_VAR const gsl_interp_type * gsl_interp_akima; GSL_VAR const gsl_interp_type * gsl_interp_akima_periodic; gsl_interp_accel * gsl_interp_accel_alloc(void); size_t gsl_interp_accel_find(gsl_interp_accel * a, const double x_array[], size_t size, double x); int gsl_interp_accel_reset (gsl_interp_accel * a); void gsl_interp_accel_free(gsl_interp_accel * a); gsl_interp * gsl_interp_alloc(const gsl_interp_type * T, size_t n); int gsl_interp_init(gsl_interp * obj, const double xa[], const double ya[], size_t size); const char * gsl_interp_name(const gsl_interp * interp); unsigned int gsl_interp_min_size(const gsl_interp * interp); int gsl_interp_eval_e(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a, double * y); double gsl_interp_eval(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a); int gsl_interp_eval_deriv_e(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a, double * d); double gsl_interp_eval_deriv(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a); int gsl_interp_eval_deriv2_e(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a, double * d2); double gsl_interp_eval_deriv2(const gsl_interp * obj, const double xa[], const double ya[], double x, gsl_interp_accel * a); int gsl_interp_eval_integ_e(const gsl_interp * obj, const double xa[], const double ya[], double a, double b, gsl_interp_accel * acc, double * result); double gsl_interp_eval_integ(const gsl_interp * obj, const double xa[], const double ya[], double a, double b, gsl_interp_accel * acc); void gsl_interp_free(gsl_interp * interp); size_t gsl_interp_bsearch(const double x_array[], double x, size_t index_lo, size_t index_hi); #ifdef HAVE_INLINE extern inline size_t gsl_interp_bsearch(const double x_array[], double x, size_t index_lo, size_t index_hi); extern inline size_t gsl_interp_bsearch(const double x_array[], double x, size_t index_lo, size_t index_hi) { size_t ilo = index_lo; size_t ihi = index_hi; while(ihi > ilo + 1) { size_t i = (ihi + ilo)/2; if(x_array[i] > x) ihi = i; else ilo = i; } return ilo; } #endif #ifdef HAVE_INLINE extern inline size_t gsl_interp_accel_find(gsl_interp_accel * a, const double xa[], size_t len, double x) { size_t x_index = a->cache; if(x < xa[x_index]) { a->miss_count++; a->cache = gsl_interp_bsearch(xa, x, 0, x_index); } else if(x > xa[x_index + 1]) { a->miss_count++; a->cache = gsl_interp_bsearch(xa, x, x_index, len-1); } else { a->hit_count++; } return a->cache; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_INTERP_H__ */
{ "alphanum_fraction": 0.6544130103, "avg_line_length": 29.078817734, "ext": "h", "hexsha": "d4757ca95e06de818718d9de638bc3a8e4aedf35", "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/interpolation/gsl_interp.h", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/interpolation/gsl_interp.h", "max_line_length": 148, "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/interpolation/gsl_interp.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1454, "size": 5903 }
#include <math.h> // Constants not defined in MSVC's math.h #ifndef M_SQRT1_2 #define M_SQRT1_2 0.70710678118654746172 #endif #ifndef M_2_SQRTPI #define M_2_SQRTPI 1.12837916709551255856 #endif #include <gsl/gsl_spline.h> #include <galpy_potentials.h> // ChandrasekharDynamicalFrictionForce: 8 arguments: amp,ms,rhm,gamma^2, // lnLambda, minr^2, ro, rf double ChandrasekharDynamicalFrictionForceAmplitude(double R,double z, double phi,double t, double r2, struct potentialArg * potentialArgs, double vR,double vT, double vz){ double sr,X,Xfactor,d_ind,forceAmplitude; double * args= potentialArgs->args; //Get args double amp= *args; double ms= *(args+9); double rhm= *(args+10); double gamma2= *(args+11); double lnLambda= *(args+12); double ro= *(args+14); double rf= *(args+15); double GMvs; double r= sqrt( r2 ); double v2= vR * vR + vT * vT + vz * vz; double v= sqrt( v2 ); // Constant or variable Lambda if ( lnLambda < 0 ) { GMvs= ms/v/v; if ( GMvs < rhm ) lnLambda= 0.5 * log ( 1. + r2 / gamma2 / rhm / rhm ); else lnLambda= 0.5 * log ( 1. + r2 / gamma2 / GMvs / GMvs ); } d_ind= (r-ro)/(rf-ro); d_ind= d_ind < 0 ? 0. : ( d_ind > 1 ? 1. : d_ind); sr= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); X= M_SQRT1_2 * v / sr; Xfactor= erf ( X ) - M_2_SQRTPI * X * exp ( - X * X ); forceAmplitude= - amp * Xfactor * lnLambda / v2 / v \ * calcDensity(R,z,phi,t,potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); // Caching *(args + 1)= R; *(args + 2)= z; *(args + 3)= phi; *(args + 4)= t; *(args + 5)= vR; *(args + 6)= vT; *(args + 7)= vz; *(args + 8)= forceAmplitude; return forceAmplitude; } double ChandrasekharDynamicalFrictionForceRforce(double R,double z, double phi, double t, struct potentialArg * potentialArgs, double vR,double vT, double vz){ double forceAmplitude; double * args= potentialArgs->args; double r2= R * R + z * z; if ( r2 < *(args+13) ) // r < minr, don't bother caching return 0.; //Get args double cached_R= *(args + 1); double cached_z= *(args + 2); double cached_phi= *(args + 3); double cached_t= *(args + 4); double cached_vR= *(args + 5); double cached_vT= *(args + 6); double cached_vz= *(args + 7); if ( R != cached_R || phi != cached_phi || z != cached_z || t != cached_t \ || vR != cached_vR || vT != cached_vT || vz != cached_vz ) forceAmplitude= ChandrasekharDynamicalFrictionForceAmplitude(R,z,phi,t,r2, potentialArgs, vR,vT,vz); else forceAmplitude= *(args + 8); return forceAmplitude * vR; } double ChandrasekharDynamicalFrictionForcezforce(double R,double z, double phi, double t, struct potentialArg * potentialArgs, double vR,double vT, double vz){ double forceAmplitude; double * args= potentialArgs->args; double r2= R * R + z * z; if ( r2 < *(args+13) ) // r < minr, don't bother caching return 0.; //Get args double cached_R= *(args + 1); double cached_z= *(args + 2); double cached_phi= *(args + 3); double cached_t= *(args + 4); double cached_vR= *(args + 5); double cached_vT= *(args + 6); double cached_vz= *(args + 7); if ( R != cached_R || phi != cached_phi || z != cached_z || t != cached_t \ || vR != cached_vR || vT != cached_vT || vz != cached_vz ) //LCOV_EXCL_START forceAmplitude= ChandrasekharDynamicalFrictionForceAmplitude(R,z,phi,t,r2, potentialArgs, vR,vT,vz); //LCOV_EXCL_STOP else forceAmplitude= *(args + 8); return forceAmplitude * vz; } double ChandrasekharDynamicalFrictionForcephiforce(double R,double z, double phi,double t, struct potentialArg * potentialArgs, double vR,double vT, double vz){ double forceAmplitude; double * args= potentialArgs->args; double r2= R * R + z * z; if ( r2 < *(args+13) ) // r < minr, don't bother caching return 0.; //Get args double cached_R= *(args + 1); double cached_z= *(args + 2); double cached_phi= *(args + 3); double cached_t= *(args + 4); double cached_vR= *(args + 5); double cached_vT= *(args + 6); double cached_vz= *(args + 7); if ( R != cached_R || phi != cached_phi || z != cached_z || t != cached_t \ || vR != cached_vR || vT != cached_vT || vz != cached_vz ) //LCOV_EXCL_START forceAmplitude= ChandrasekharDynamicalFrictionForceAmplitude(R,z,phi,t,r2, potentialArgs, vR,vT,vz); //LCOV_EXCL_STOP else forceAmplitude= *(args + 8); return forceAmplitude * vT * R; }
{ "alphanum_fraction": 0.6191085519, "avg_line_length": 32.1164383562, "ext": "c", "hexsha": "4d20979848ed3a11ea8aadb27b8cf8fec4b3e890", "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": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_path": "galpy/potential/potential_c_ext/ChandrasekharDynamicalFrictionForce.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "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": "gusbeane/galpy", "max_issues_repo_path": "galpy/potential/potential_c_ext/ChandrasekharDynamicalFrictionForce.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_path": "galpy/potential/potential_c_ext/ChandrasekharDynamicalFrictionForce.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1573, "size": 4689 }
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2020 Jijoong Moon <jijoong.moon@samsung.com> * * @file blas_interface.h * @date 28 Aug 2020 * @see https://github.com/nnstreamer/nntrainer * @author Jijoong Moon <jijoong.moon@samsung.com> * @bug No known bugs except for NYI items * @brief This is dummy header for blas support * */ #ifndef __BLAS_INTERFACE_H_ #define __BLAS_INTERFACE_H_ #ifdef __cplusplus #ifdef USE_BLAS extern "C" { #include <cblas.h> } #else enum CBLAS_ORDER { CblasRowMajor = 101, CblasColMajor = 102 }; enum CBLAS_TRANSPOSE { CblasNoTrans = 111, CblasTrans = 112, CblasConjTrans = 113 }; #endif #ifdef USE_CUBLAS #include <helper_cuda.h> #include <helper_functions.h> #endif namespace nntrainer { void sscal(const int N, const float alpha, float *X, const int incX); float snrm2(const int N, const float *X, const int incX); void scopy(const unsigned int N, const float *X, const int incX, float *Y, const int intY); float sdot(const unsigned int N, const float *X, const unsigned int incX, const float *Y, const unsigned int incY); void saxpy(const unsigned int N, const float alpha, const float *X, const int incX, float *Y, const int incY); void sgemm(CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, const unsigned int M, const unsigned int N, const unsigned int K, const float alpha, const float *A, const unsigned int lda, const float *B, const unsigned int ldb, const float beta, float *C, const unsigned int ldc); void sgemv(CBLAS_ORDER order, CBLAS_TRANSPOSE TransA, const unsigned int M, const unsigned int N, const float alpha, const float *A, const unsigned int lda, const float *X, const int incX, const float beta, float *Y, const int incY); unsigned int isamax(const unsigned int N, const float *X, const int incX); } /* namespace nntrainer */ #endif /* __cplusplus */ #endif /* __BLAS_INTERFACE_H__ */
{ "alphanum_fraction": 0.696039604, "avg_line_length": 29.7058823529, "ext": "h", "hexsha": "18cf9f5bf9429757ef03285f5e4f2d31b428c82c", "lang": "C", "max_forks_count": 45, "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:47:12.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-24T06:17:05.000Z", "max_forks_repo_head_hexsha": "d22eeaa6591bedeff2480fc7853ebca60ebaa80c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "SIJUN0725/nntrainer", "max_forks_repo_path": "nntrainer/tensor/blas_interface.h", "max_issues_count": 1815, "max_issues_repo_head_hexsha": "d22eeaa6591bedeff2480fc7853ebca60ebaa80c", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:14:47.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-24T08:15:43.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "SIJUN0725/nntrainer", "max_issues_repo_path": "nntrainer/tensor/blas_interface.h", "max_line_length": 78, "max_stars_count": 91, "max_stars_repo_head_hexsha": "d22eeaa6591bedeff2480fc7853ebca60ebaa80c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "SIJUN0725/nntrainer", "max_stars_repo_path": "nntrainer/tensor/blas_interface.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T18:56:32.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-24T06:52:34.000Z", "num_tokens": 551, "size": 2020 }
/**************************************************************** wigner_gsl.h / wigner_gsl_twice.h Defines Wigner coupling and recoupling symbols as wrappers for GSL angular momentum functions: - wigner_gsl.h -- takes HalfInt angular momentum arguments (RECOMMENDED) - wigner_gsl_twice.h -- takes integer "twice value" angular momentum arguments Naming convention: - Function names *not* ending in '2' accept HalfInt arguments J. - Function names ending in '2' accept integer arguments 2*J. See, e.g., appendix to de Shalit and Talmi for underlying formulas. DOCUMENTATION: See wigner_gsl.h (rather than wigner_gsl_twice.h) for more complete function comments. Language: C++ Mark A. Caprio University of Notre Dame 2/16/10 (mac): Created. 11/13/15 (mac): Add unitary 6J for (12)3-(13)2 recoupling and Racah reduction factor. 2/27/16 (mac): Update includes for restructured header files. 3/8/16 (mac): Enclose in namespace. 6/8/16 (mac): Update #define guard directive. 6/21/16 (mac): Remove Racah reduction factor. Update comments. 10/18/16 (mac): Update Unitary6J comment. Rename wigner2_gsl.h to wigner_gsl_twice.h. 4/28/18 (mac): Restore missing Hat2 and ParitySign2 to wigner_gsl_twice.h. ****************************************************************/ #ifndef WIGNER_GSL_H_ #define WIGNER_GSL_H_ #include <gsl/gsl_sf_coupling.h> #include "am.h" namespace am { // Wigner3J(ja,jb,jc,ma,mb,mc) // returns Wigner 3-J symbol // wrapper for gsl_sf_coupling_3j inline double Wigner3J( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& ma, const HalfInt& mb, const HalfInt& mc ) { return gsl_sf_coupling_3j( TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), TwiceValue(ma), TwiceValue(mb), TwiceValue(mc) ); } // ClebschGordan(ja,ma,jb,mb,jc,mc) // returns Clebsch-Gordan coefficient // wrapper for gsl_sf_coupling_3j inline double ClebschGordan( const HalfInt& ja, const HalfInt& ma, const HalfInt& jb, const HalfInt& mb, const HalfInt& jc, const HalfInt& mc ) { return Hat(jc)*ParitySign(ja-jb+mc) *gsl_sf_coupling_3j( TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), TwiceValue(ma), TwiceValue(mb), -TwiceValue(mc) ); } // Wigner6J(ja,jb,jc,jd,je,jf) // returns Wigner 6-J symbol // wrapper for gsl_sf_coupling_6j inline double Wigner6J( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& jd, const HalfInt& je, const HalfInt& jf ) { return gsl_sf_coupling_6j( TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), TwiceValue(jd), TwiceValue(je), TwiceValue(jf) ); } // Unitary6J(ja,jb,jc,jd,je,jf) // wrapper for gsl_sf_coupling_6j // returns unitary recoupling symbol for (12)3-1(23) recoupling // // Arguments follow row order in 6J symbol: // Unitary6J(J1,J2,J12,J3,J,J23) // This is equivalent to U(J1,J2,J,J3,J12,J23), though neither is a // particularly memorable ordering. Why not (J1,J2,J3,J12,J23,J)?! inline double Unitary6J( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& jd, const HalfInt& je, const HalfInt& jf ) { return ParitySign(ja+jb+jd+je)*Hat(jc)*Hat(jf) *Wigner6J(ja,jb,jc,jd,je,jf); } // Unitary6JZ(ja,jb,jc,jd,je,jf) // wrapper for gsl_sf_coupling_6j // returns unitary recoupling symbol for (12)3-(13)2 recoupling // the name "Z" follows Millener for this purpose // // Arguments follow row order in 6J symbol: // Unitary6JZ(J1,J2,J12,J,J3,J13) // This is equivalent to Z(J2,J1,J,J3,J12,J13), though neither is a // particularly memorable ordering. Why not (J1,J2,J3,J12,J13,J)?! inline double Unitary6JZ( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& jd, const HalfInt& je, const HalfInt& jf ) { return ParitySign(jb+je+jc+jf)*Hat(jc)*Hat(jf) *Wigner6J(ja,jb,jc,jd,je,jf); } // Wigner9J(ja,jb,jc,jd,je,jf,jg,jh,ji) // returns Wigner 9-J symbol // wrapper for gsl_sf_coupling_9j inline double Wigner9J( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& jd, const HalfInt& je, const HalfInt& jf, const HalfInt& jg, const HalfInt& jh, const HalfInt& ji ) { return gsl_sf_coupling_9j( TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), TwiceValue(jd), TwiceValue(je), TwiceValue(jf), TwiceValue(jg), TwiceValue(jh), TwiceValue(ji) ); } // Unitary9J(ja,jb,jc,jd,je,jf,jg,jh,ji) // returns unitary 9-J symbol // wrapper for gsl_sf_coupling_9j inline double Unitary9J( const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, const HalfInt& jd, const HalfInt& je, const HalfInt& jf, const HalfInt& jg, const HalfInt& jh, const HalfInt& ji ) { return Hat(jc)*Hat(jf)*Hat(jg)*Hat(jh) *Wigner9J( ja, jb, jc, jd, je, jf, jg, jh, ji ); } } // namespace #endif
{ "alphanum_fraction": 0.6299257567, "avg_line_length": 29.8465909091, "ext": "h", "hexsha": "4c2f4590186271ce57185b69c22658040bad55f4", "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": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "e-eight/am", "max_forks_repo_path": "wigner_gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "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": "e-eight/am", "max_issues_repo_path": "wigner_gsl.h", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "e-eight/am", "max_stars_repo_path": "wigner_gsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1712, "size": 5253 }
/* ode-initval/rk2imp.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. */ /* Runge-Kutta 2, Gaussian implicit. Also known as the implicit midpoint rule. */ /* Author: G. Jungman */ /* Error estimation by step doubling, see eg. Ascher, U.M., Petzold, L.R., Computer methods for ordinary differential and differential-algebraic equations, SIAM, Philadelphia, 1998. The method is also described in eg. this reference. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "odeiv_util.h" typedef struct { double *Y1; double *y0; double *ytmp; double *y_onestep; double *y0_orig; } rk2imp_state_t; static void * rk2imp_alloc (size_t dim) { rk2imp_state_t *state = (rk2imp_state_t *) malloc (sizeof (rk2imp_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for rk2imp_state", GSL_ENOMEM); } state->Y1 = (double *) malloc (dim * sizeof (double)); if (state->Y1 == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for Y1", GSL_ENOMEM); } state->ytmp = (double *) malloc (dim * sizeof (double)); if (state->ytmp == 0) { free (state->Y1); free (state); GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->Y1); free (state->ytmp); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } state->y_onestep = (double *) malloc (dim * sizeof (double)); if (state->y_onestep == 0) { free (state->Y1); free (state->ytmp); free (state->y0); free (state); GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM); } state->y0_orig = (double *) malloc (dim * sizeof (double)); if (state->y0_orig == 0) { free (state->y_onestep); free (state->Y1); free (state->ytmp); free (state->y0); free (state); GSL_ERROR_NULL ("failed to allocate space for y0_orig", GSL_ENOMEM); } return state; } static int rk2imp_step (double *y, rk2imp_state_t *state, const double h, const double t, const size_t dim, const gsl_odeiv_system *sys) { /* Makes a Runge-Kutta 2nd order implicit advance with step size h. y0 is initial values of variables y. The implicit matrix equations to solve are: Y1 = y0 + h/2 * f(t + h/2, Y1) y = y0 + h * f(t + h/2, Y1) */ const double *y0 = state->y0; double *Y1 = state->Y1; double *ytmp = state->ytmp; int max_iter=3; int nu; size_t i; /* iterative solution of Y1 = y0 + h/2 * f(t + h/2, Y1) Y1 should include initial values at call. Note: This method does not check for convergence of the iterative solution! */ for (nu = 0; nu < max_iter; nu++) { for (i = 0; i < dim; i++) { ytmp[i] = y0[i] + 0.5 * h * Y1[i]; } { int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, Y1); if (s != GSL_SUCCESS) { return s; } } } /* assignment */ for (i = 0; i < dim; i++) { y[i] = y0[i] + h * Y1[i]; } return GSL_SUCCESS; } static int rk2imp_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; size_t i; double *Y1 = state->Y1; double *y0 = state->y0; double *y_onestep = state->y_onestep; double *y0_orig = state->y0_orig; /* Error estimation is done by step doubling procedure */ /* initialization step */ DBL_MEMCPY (y0, y, dim); /* Save initial values for possible failures */ DBL_MEMCPY (y0_orig, y, dim); if (dydt_in != NULL) { DBL_MEMCPY (Y1, dydt_in, dim); } else { int s = GSL_ODEIV_FN_EVAL (sys, t, y, Y1); if (s != GSL_SUCCESS) { return s; } } /* First traverse h with one step (save to y_onestep) */ DBL_MEMCPY (y_onestep, y, dim); { int s = rk2imp_step (y_onestep, state, h, t, dim, sys); if (s != GSL_SUCCESS) { return s; } } /* Then with two steps with half step length (save to y) */ { int s = rk2imp_step (y, state, h / 2.0, t, dim, sys); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } } DBL_MEMCPY (y0, y, dim); { int s = GSL_ODEIV_FN_EVAL (sys, t + h / 2.0, y, Y1); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } } { int s = rk2imp_step (y, state, h / 2.0, t + h / 2.0, dim, sys); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } } /* Derivatives at output */ if (dydt_out != NULL) { int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } } /* Error estimation */ for (i = 0; i < dim; i++) { yerr[i] = 4.0 * (y[i] - y_onestep[i]) / 3.0; } return GSL_SUCCESS; } static int rk2imp_reset (void *vstate, size_t dim) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; DBL_ZERO_MEMSET (state->Y1, dim); DBL_ZERO_MEMSET (state->ytmp, dim); DBL_ZERO_MEMSET (state->y0, dim); DBL_ZERO_MEMSET (state->y_onestep, dim); DBL_ZERO_MEMSET (state->y0_orig, dim); return GSL_SUCCESS; } static unsigned int rk2imp_order (void *vstate) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 2; } static void rk2imp_free (void *vstate) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; free (state->Y1); free (state->ytmp); free (state->y0); free (state->y_onestep); free (state->y0_orig); free (state); } static const gsl_odeiv_step_type rk2imp_type = { "rk2imp", /* name */ 1, /* can use dydt_in */ 1, /* gives exact dydt_out */ &rk2imp_alloc, &rk2imp_apply, &rk2imp_reset, &rk2imp_order, &rk2imp_free }; const gsl_odeiv_step_type *gsl_odeiv_step_rk2imp = &rk2imp_type;
{ "alphanum_fraction": 0.597557629, "avg_line_length": 21.6261127596, "ext": "c", "hexsha": "53c31c4d768cbdae1a5127b1ced1481d4a635959", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/ode-initval/rk2imp.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/ode-initval/rk2imp.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/rk2imp.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": 2293, "size": 7288 }
/***************************************************************************** * * * Copyright 2018 Rice University * * * * 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 LDA_INITIAL_TOPIC_PROB_SELECT_H #define LDA_INITIAL_TOPIC_PROB_SELECT_H #include "Lambda.h" #include "LambdaCreationFunctions.h" #include "SelectionComp.h" #include "PDBVector.h" #include "SumResult.h" #include "IntDoubleVectorPair.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <random> #include <gsl/gsl_vector.h> /* The class for initializing the topic-probability for a document */ using namespace pdb; class LDAInitialTopicProbSelection : public SelectionComp<IntDoubleVectorPair, SumResult> { private: Vector<double> prior; Handle<Vector<char>> myMem; public: ENABLE_DEEP_COPY LDAInitialTopicProbSelection() {} LDAInitialTopicProbSelection(Vector<double>& fromPrior) { this->prior = fromPrior; /* Prepare the random number genrator */ /* Set up the gsl_rng *src */ gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937); std::random_device rd; std::mt19937 gen(rd()); gsl_rng_set(src, gen()); /* Allocate space needed for myRand */ int spaceNeeded = sizeof(gsl_rng) + src->type->size; myMem = makeObject<Vector<char>>(spaceNeeded, spaceNeeded); /* Copy src over */ memcpy(myMem->c_ptr(), src, sizeof(gsl_rng)); memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size); gsl_rng_free(src); } Lambda<bool> getSelection(Handle<SumResult> checkMe) override { return makeLambda(checkMe, [](Handle<SumResult>& checkMe) { return true; }); } Lambda<Handle<IntDoubleVectorPair>> getProjection(Handle<SumResult> checkMe) override { return makeLambda(checkMe, [&](Handle<SumResult>& checkMe) { gsl_rng* rng = getRng(); Handle<IntDoubleVectorPair> result = makeObject<IntDoubleVectorPair>(); int topicNum = this->prior.size(); result->setInt(checkMe->getKey()); Handle<Vector<double>> mySamples = makeObject<Vector<double>>(topicNum, topicNum); /* Sample for the topic-probability */ gsl_ran_dirichlet(rng, topicNum, this->prior.c_ptr(), mySamples->c_ptr()); result->setVector(mySamples); return result; }); } /* Get the GSL RNG from myMem */ gsl_rng* getRng() { gsl_rng* dst = (gsl_rng*)myMem->c_ptr(); dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng)); dst->type = gsl_rng_mt19937; return dst; } Vector<double> getPrior() { return this->prior; } }; #endif
{ "alphanum_fraction": 0.5382633342, "avg_line_length": 37.6796116505, "ext": "h", "hexsha": "c03edaa48011d8643d9407f219e5573903a3799e", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2020-08-03T00:58:24.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-14T03:39:14.000Z", "max_forks_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "dimitrijejankov/pdb", "max_forks_repo_path": "pdb/src/sharedLibraries/headers/LDAInitialTopicProbSelection.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_issues_repo_issues_event_max_datetime": "2018-11-01T15:36:07.000Z", "max_issues_repo_issues_event_min_datetime": "2018-07-03T21:50:14.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "dimitrijejankov/pdb", "max_issues_repo_path": "pdb/src/sharedLibraries/headers/LDAInitialTopicProbSelection.h", "max_line_length": 94, "max_stars_count": 29, "max_stars_repo_head_hexsha": "395b5ebd48c2c1b14a56bf24aeea726b36559074", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "dimitrijejankov/pdb", "max_stars_repo_path": "pdb/src/sharedLibraries/headers/LDAInitialTopicProbSelection.h", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:45:12.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-14T03:19:32.000Z", "num_tokens": 788, "size": 3881 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* inet_aton -> per utilizzarla in gcc: __USE_MISC */ #define __USE_MISC #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> #include "buffer.h" #include "list.h" #include "router.h" #include <gsl/gsl_matrix.h> #define DIM_BUFFER 1000 #define POISON_ID -1 struct msg_t { int msg_id; int msg_time; float msg_x; float msg_z; }; struct routing_table_t { int dimension; list list_table; }; struct router_t { int router_id; struct routing_table_t routing_table; pthread_mutex_t router_mutex; }; struct parametri_accepter_t { int accepter_agents_number; char *accepter_address; int accepter_port; list accepter_lista_buffer; int accepter_in_out; }; struct parametri_dispatcher_t { buffer dispatcher_buffer_in; list dispatcher_lista_buffer_out; }; struct parametri_receiver_t { int receiver_id; int receiver_socket; buffer receiver_buffer; }; struct parametri_sender_t { int sender_id; int sender_socket; buffer sender_buffer; }; typedef struct msg_t *msg; typedef struct parametri_accepter_t *parametri_accepter; typedef struct parametri_dispatcher_t *parametri_dispatcher; typedef struct parametri_receiver_t *parametri_receiver; typedef struct parametri_sender_t *parametri_sender; static pthread_mutex_t router_class_mutex; static int routerObjectsNumber = 0; static int numero_receiver_vivi = 0; static int numero_dispatcher_vivi = 0; static int numero_sender_vivi = 0; static void initClassRouter() { pthread_mutex_init(&(router_class_mutex), NULL); } static void cleanClassRouter() { pthread_mutex_destroy(&(router_class_mutex)); } router allocRouter() { router router_M_; if (routerObjectsNumber == 0) initClassRouter(); routerObjectsNumber++; router_M_ = (router) malloc(sizeof (struct router_t)); pthread_mutex_init(&(router_M_->router_mutex), NULL); return router_M_; } void freeRouter(router _F_router) { pthread_mutex_destroy(&(_F_router->router_mutex)); free(_F_router); _F_router = NULL; routerObjectsNumber--; if (routerObjectsNumber == 0) cleanClassRouter(); } static int listenFrom(char * _ip_address_local, int _ip_port_local) { int socket_M_; struct sockaddr_in sockaddr_in_local_; memset(&sockaddr_in_local_, 0, sizeof (sockaddr_in_local_)); sockaddr_in_local_.sin_family = AF_INET; sockaddr_in_local_.sin_port = htons(_ip_port_local); inet_aton(_ip_address_local, &(sockaddr_in_local_.sin_addr)); if ((socket_M_ = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("listenFrom: socket() Error\n"); exit(1); } if (bind(socket_M_, (struct sockaddr *) & sockaddr_in_local_, sizeof (struct sockaddr_in)) == -1) { perror("listenFrom: bind() Error\n"); exit(1); } if (listen(socket_M_, 1) == -1) { perror("listenFrom: listen() Error\n"); exit(1); } return socket_M_; } static void sendMsg(int _socket, msg _msg) { if (send(_socket, _msg, sizeof (struct msg_t), 0) == -1) { perror("sendMsg: send() Error\n"); exit(1); }; /* int net_id; int net_x; int net_z; net_id = htonl(_msg->msg_id); if (send(_socket, &net_id, sizeof (net_id), 0) == -1) { perror("sendMsg: send() Error\n"); exit(1); }; net_x = htonl(_msg->msg_x); if (send(_socket, &net_x, sizeof (net_x), 0) == -1) { perror("sendMsg: send() Error\n"); exit(1); }; net_z = htonl(_msg->msg_z); if (send(_socket, &net_z, sizeof (net_z), 0) == -1) { perror("sendMsg: send() Error\n"); exit(1); }; */ } static msg recvMsg(int _socket) { msg _M_msg = (struct msg_t *) malloc(sizeof (struct msg_t)); if (recv(_socket, _M_msg, sizeof (struct msg_t), 0) == -1) { perror("recvMsg: recv() Error\n"); exit(1); } /* int net_id; int net_x; int net_z; msg _M_msg = (struct msg_t *) malloc(sizeof (struct msg_t)); if (recv(_socket, &net_id, sizeof (net_id), 0) == -1) { perror("recvMsg: recv() Error\n"); exit(1); } _M_msg->msg_id = ntohl(net_id); if (recv(_socket, &net_x, sizeof (net_x), 0) == -1) { perror("recvMsg: recv() Error\n"); exit(1); } _M_msg->msg_x = ntohl(net_x); if (recv(_socket, &net_z, sizeof (net_z), 0) == -1) { perror("recvMsg: recv() Error\n"); exit(1); } _M_msg->msg_z = ntohl(net_z); */ return _M_msg; } static parametri_receiver allocParamReceiver(int _receiver_socket, buffer _receiver_buffer) { parametri_receiver _M_parametri_receiver = (parametri_receiver) malloc(sizeof (struct parametri_receiver_t)); _M_parametri_receiver->receiver_socket = _receiver_socket; _M_parametri_receiver->receiver_buffer = _receiver_buffer; return _M_parametri_receiver; } /* * Quando il Receiver riceve dall'agent un messaggio con id = POISON_ID allora: * - lo inoltra nel buffer * - chiude la connessione con l'agent * - fa il fflush del file di log e lo chiude * - decrementa numero_receiver_vivi * - termina */ static void *runReceiver(void *_parametri_receiver) { parametri_receiver _parametri = (parametri_receiver) _parametri_receiver; int _receiver_socket = _parametri->receiver_socket; buffer _receiver_buffer = _parametri->receiver_buffer; msg _msg; int _receiver_id; FILE *receiver_log; char receiver_log_file_name[FILENAME_MAX]; /* * Riceve il messaggio di presentazione dall'agent * - imposta l'id del receiver * - imposta l'id del _receiver_buffer * - reinvia all'agent il messaggio ricevuto */ _msg = recvMsg(_receiver_socket); _receiver_id = _msg->msg_id; setBufferID(_receiver_buffer, _receiver_id); /* * Apre il file di log */ sprintf(receiver_log_file_name, "receiver_%d.log", _receiver_id); receiver_log = fopen(receiver_log_file_name, "w"); if (receiver_log == NULL) { perror("Errore apertura file: \"receiver.log\"\n"); exit(1); }; setbuf(receiver_log, NULL); fprintf(receiver_log, "R%d: Open log\n", _receiver_id); /*sleep(1);*/ fprintf(receiver_log, "R%d: Parametri invocazione:\n", _receiver_id); fprintf(receiver_log, "R%d: Wait: rcv\n", _receiver_id); fprintf(receiver_log, "R%d: > (%d,%d,%f,%f)\n", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(receiver_log, "R%d: Wait: rcv\n", _receiver_id); /* * Riceve un messaggio e lo pone nel buffer finchè non riceve il POISON_ID */ _msg = recvMsg(_receiver_socket); fprintf(receiver_log, "R%d: > (%d,%d,%f,%f)\n", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(receiver_log, "R%d: Loop:\n", _receiver_id); fprintf(receiver_log, "R%d: > while(msg != POISON_ID)\n", _receiver_id); fprintf(receiver_log, "R%d: --- Loop Start ---\n", _receiver_id); while (_msg->msg_id != POISON_ID) { putInBuffer_blocking(_receiver_buffer, _msg); fprintf(receiver_log, "R%d: >>> putInBuffer(%d,%d,%f,%f)\n", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(receiver_log, "R%d: >>> Wait: rcv\n", _receiver_id); _msg = recvMsg(_receiver_socket); }; fprintf(receiver_log, "R%d: ---- Loop End ----\n", _receiver_id); fprintf(receiver_log, "R%d: Signal:\n", _receiver_id); putInBuffer_blocking(_receiver_buffer, _msg); fprintf(receiver_log, "R%d: > putInBuffer(%d,%d,%f,%f) \n", _receiver_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(receiver_log, "R%d: Socket:\n", _receiver_id); /* * Chiude la connessione con l'agent */ send(_receiver_socket, "", 1, 0); close(_receiver_socket); fprintf(receiver_log, "R%d: > close receiver socket\n", _receiver_id); fprintf(receiver_log, "R%d: Memoria\n", _receiver_id); free(_parametri_receiver); fprintf(receiver_log, "R%d: > parametri\n", _receiver_id); /* * fflush e chiusura del logfile */ fprintf(receiver_log, "R%d: Close log\n", _receiver_id); fflush(receiver_log); fclose(receiver_log); /* Decrementa numero_receiver_vivi e termina*/ numero_receiver_vivi--; return NULL; } static parametri_sender allocParamSender(int _sender_socket, buffer _sender_buffer) { parametri_sender _M_parametri_sender = (parametri_sender) malloc(sizeof (struct parametri_sender_t)); _M_parametri_sender->sender_socket = _sender_socket; _M_parametri_sender->sender_buffer = _sender_buffer; return _M_parametri_sender; } /* * Quando il Sender prende dal buffer un messaggio con id = POISON_ID * vuol dire che quello è l'ultimo messaggio e il buffer non ne contiene altri: * - attende che i dispatcher siano morti * - elimina il sender buffer associato * - chiude la connessione con l'agent * - fa il fflush del file di log e lo chiude * - decrementa numero_sender_buffer * - termina */ static void *runSender(void *_parametri_sender) { parametri_sender _parametri = (parametri_sender) _parametri_sender; int _sender_socket = _parametri->sender_socket; buffer _sender_buffer = _parametri->sender_buffer; int _sender_id; msg _msg; FILE *sender_log; char sender_log_file_name[FILENAME_MAX]; /* * Riceve il messaggio di presentazione dall'agent: * - imposta l'id del sender * - imposta l'id del _sender_buffer * - reinvia all'agent il messaggio ricevuto */ _msg = recvMsg(_sender_socket); _sender_id = _msg->msg_id; setBufferID(_sender_buffer, _sender_id); /* * Apre il file di log */ sprintf(sender_log_file_name, "sender_%d.log", _sender_id); sender_log = fopen(sender_log_file_name, "w"); if (sender_log == NULL) { perror("Errore apertura file: \"sender.log\"\n"); exit(1); }; setbuf(sender_log, NULL); fprintf(sender_log, "S%d: Open log\n", _sender_id); /*sleep(1);*/ fprintf(sender_log, "S%d: Parametri di invocazione:\n", _sender_id); fprintf(sender_log, "S%d: Wait: rcv\n", _sender_id); fprintf(sender_log, "S%d: > (%d,%d,%f,%f)\n", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(sender_log, "S%d: Wait: getFromBuffer\n", _sender_id); /* * Riceve un messaggio e lo pone nel buffer finchè non riceve il POISON_ID */ _msg = getFromBuffer_blocking(_sender_buffer); fprintf(sender_log, "S%d: > (%d,%d,%f,%f)\n", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(sender_log, "S%d: Loop:\n", _sender_id); fprintf(sender_log, "S%d: > while(msg != POISON_ID)\n", _sender_id); fprintf(sender_log, "S%d: --- Loop Start ---\n", _sender_id); while (_msg->msg_id != POISON_ID) { sendMsg(_sender_socket, _msg); fprintf(sender_log, "S%d: >>> snd (%d,%d,%f,%f)\n", _sender_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z); fprintf(sender_log, "S%d: >>> Wait: getFromBuffer\n", _sender_id); _msg = getFromBuffer_blocking(_sender_buffer); }; fprintf(sender_log, "S%d: ---- Loop End ----\n", _sender_id); fprintf(sender_log, "S%d: Wait:\n", _sender_id); /* * Attende che tutti i dispatcher siano morti */ fprintf(sender_log, "S%d: > while(dispatcher > 0)\n", _sender_id); while (numero_dispatcher_vivi > 0); fprintf(sender_log, "S%d: Socket:\n", _sender_id); /* * Chiude la connessione con l'agent */ send(_sender_socket, "", 1, 0); close(_sender_socket); fprintf(sender_log, "S%d: > close sender socket\n", _sender_id); fprintf(sender_log, "S%d: Memoria:\n", _sender_id); /* * Elimina il receiver buffer associato */ freeBuffer(_sender_buffer); fprintf(sender_log, "S%d: > free(sender_buffer)\n", _sender_id); free(_parametri_sender); fprintf(sender_log, "S%d: > parametri\n", _sender_id); /* * fflush e chiusura del logfile */ fprintf(sender_log, "S%d: Close log\n", _sender_id); fflush(sender_log); fclose(sender_log); /* Decrementa numero_sender_vivi e termina*/ numero_sender_vivi--; return NULL; } static parametri_accepter allocParamAccepter(int _accepter_agents_number, char *_accepter_address, int _accepter_port, list _accepter_lista_buffer, int _accepter_in_out) { parametri_accepter _M_parametri_accepter = (parametri_accepter) malloc(sizeof (struct parametri_accepter_t)); _M_parametri_accepter->accepter_agents_number = _accepter_agents_number; _M_parametri_accepter->accepter_address = _accepter_address; _M_parametri_accepter->accepter_port = _accepter_port; _M_parametri_accepter->accepter_lista_buffer = _accepter_lista_buffer; _M_parametri_accepter->accepter_in_out = _accepter_in_out; return _M_parametri_accepter; } /* * Quando l'accepter riceve _accepter_agents_number connessioni in input e in output * vuol dire che tutti gli agents si sono collegati: * - chiude le due porte in listening * - fa il fflush del file di log e lo chiude * - termina */ static void *runAccepter(void *_parametri_accepter) { parametri_accepter _parametri = (parametri_accepter) _parametri_accepter; int _accepter_agents_number; char *_accepter_address; int _accepter_port; list _accepter_lista_buffer; int _accepter_in_out; int listening_socket; int communication_socket; FILE *accepter_log; char *accepter_log_file_name; char *in_out; char *accepter_error; /* Apre il file di log */ _accepter_in_out = _parametri->accepter_in_out; if (_accepter_in_out == 0) { accepter_log_file_name = "accepter_in.log"; accepter_error = "Errore apertura file: \"accepter_in.log\"\n"; in_out = "AI"; } else { accepter_log_file_name = "accepter_out.log"; accepter_error = "Errore apertura file: \"accepter_out.log\"\n"; in_out = "AO"; }; accepter_log = fopen(accepter_log_file_name, "w"); if (accepter_log == NULL) { perror(accepter_error); exit(1); }; setbuf(accepter_log, NULL); fprintf(accepter_log, "%s: Open log\n", in_out); fprintf(accepter_log, "%s: Parametri di invocazione:\n", in_out); _accepter_agents_number = _parametri->accepter_agents_number; fprintf(accepter_log, "%s: > %d\n", in_out, _accepter_agents_number); _accepter_address = _parametri->accepter_address; fprintf(accepter_log, "%s: > %s\n", in_out, _accepter_address); _accepter_port = _parametri->accepter_port; fprintf(accepter_log, "%s: > %d\n", in_out, _accepter_port); _accepter_lista_buffer = _parametri->accepter_lista_buffer; fprintf(accepter_log, "%s: > %d\n", in_out, _accepter_in_out); fprintf(accepter_log, "%s: Socket:\n", in_out); fprintf(accepter_log, "%s: > listenFrom(%s,%d)\n", in_out, _accepter_address, _accepter_port); listening_socket = listenFrom(_accepter_address, _accepter_port); if (_accepter_in_out == 0) { fprintf(accepter_log, "%s: Loop:\n", in_out); fprintf(accepter_log, "%s: > while(receiver < agents)\n", in_out); fprintf(accepter_log, "%s: ---------- Loop Start ----------\n", in_out); while (numero_receiver_vivi < _accepter_agents_number) { buffer _M_buffer = allocBuffer(DIM_BUFFER); pthread_t receiver_; if ((communication_socket = accept(listening_socket, NULL, NULL)) == -1) { perror("Accepter accept() Error\n"); exit(1); } fprintf(accepter_log, "%s: >>> accept connection\n", in_out); addElementToList(_accepter_lista_buffer, _M_buffer); numero_receiver_vivi++; pthread_create(&receiver_, NULL, &runReceiver, allocParamReceiver(communication_socket, _M_buffer)); } fprintf(accepter_log, "%s: ----------- Loop End -----------\n", in_out); } else { fprintf(accepter_log, "%s: Loop:\n", in_out); fprintf(accepter_log, "%s: > while(sender < agents)\n", in_out); fprintf(accepter_log, "%s: --------- Loop Start ---------\n", in_out); while (numero_sender_vivi < _accepter_agents_number) { buffer _M_buffer = allocBuffer(DIM_BUFFER); pthread_t sender_; if ((communication_socket = accept(listening_socket, NULL, NULL)) == -1) { perror("Accepter accept() Error\n"); exit(1); } fprintf(accepter_log, "%s: >>> accept connection\n", in_out); addElementToList(_accepter_lista_buffer, _M_buffer); numero_sender_vivi++; pthread_create(&sender_, NULL, &runSender, allocParamSender(communication_socket, _M_buffer)); } fprintf(accepter_log, "%s: ---------- Loop End ----------\n", in_out); } fprintf(accepter_log, "%s: Socket:\n", in_out); /* * Chiude le due porte in listening */ close(listening_socket); fprintf(accepter_log, "%s: > close listen socket\n", in_out); fprintf(accepter_log, "%s: Memoria:\n", in_out); free(_parametri_accepter); fprintf(accepter_log, "%s: > parametri\n", in_out); /* * fflush e chiusura del logfile */ fprintf(accepter_log, "%s: Close log\n", in_out); fflush(accepter_log); fclose(accepter_log); return NULL; } static parametri_dispatcher allocParamDispatcher(buffer _dispatcher_buffer_in, list _dispatcher_lista_buffer_out) { parametri_dispatcher _M_parametri_dispatcher = (parametri_dispatcher) malloc(sizeof (struct parametri_dispatcher_t)); _M_parametri_dispatcher->dispatcher_buffer_in = _dispatcher_buffer_in; _M_parametri_dispatcher->dispatcher_lista_buffer_out = _dispatcher_lista_buffer_out; return _M_parametri_dispatcher; } /* * Quando il dispatcher riceve il POISON_ID allora: * - lo inoltra nel sender buffer associato e solo in quello * - attende che tutti i receiver siano morti * - elimina il receiver buffer associato * - fa il fflush del file di log e lo chiude * - decrementa numero_dispatcher_vivi * - termina */ static void *runDispatcher(void *_parametri_dispatcher) { parametri_dispatcher _parametri = (parametri_dispatcher) _parametri_dispatcher; buffer _dispatcher_buffer_in = _parametri->dispatcher_buffer_in; list _dispatcher_lista_buffer_out; int _dispatcher_id; int _sender_buffer_id; list_iterator it_out; buffer _sender_buffer; msg _msg; gsl_matrix *_dispatcher_adjacency_matrix; FILE *dispatcher_adjacency_matrix_file; FILE *dispatcher_log; char dispatcher_log_file_name[FILENAME_MAX]; _dispatcher_adjacency_matrix = gsl_matrix_alloc(6, 6); dispatcher_adjacency_matrix_file = fopen("adjacency_matrix.txt", "r"); gsl_matrix_fscanf(dispatcher_adjacency_matrix_file, _dispatcher_adjacency_matrix); fclose(dispatcher_adjacency_matrix_file); /* gsl_matrix_fprintf(stdout, adjacency_matrix, "%f"); printf("valore 0,0 = %f\n",gsl_matrix_get(adjacency_matrix,0,0)); printf("valore 1,0 = %f\n",gsl_matrix_get(adjacency_matrix,1,0)); printf("valore 0,1 = %f\n",gsl_matrix_get(adjacency_matrix,0,1)); printf("valore 1,1 = %f\n",gsl_matrix_get(adjacency_matrix,1,1)); */ /* Apre il file di log impostando il suo id a quello del buffer associato */ _dispatcher_id = getBufferID(_dispatcher_buffer_in); sprintf(dispatcher_log_file_name, "dispatcher_%d.log", _dispatcher_id); dispatcher_log = fopen(dispatcher_log_file_name, "w"); if (dispatcher_log == NULL) { perror("Errore apertura file: \"dispatcher.log\"\n"); exit(1); }; setbuf(dispatcher_log, NULL); fprintf(dispatcher_log, "D%d: Open log\n", _dispatcher_id); /*sleep(1);*/ fprintf(dispatcher_log, "D%d: Parametri di invocazione:\n", _dispatcher_id); _dispatcher_lista_buffer_out = _parametri->dispatcher_lista_buffer_out; fprintf(dispatcher_log, "D%d: Wait:\n", _dispatcher_id); fprintf(dispatcher_log, "D%d: > getFromBuffer(receiver_buffer)\n", _dispatcher_id); /* * Riceve un messaggio e lo pone in tutti i sender buffer finchè non riceve il POISON_ID */ _msg = getFromBuffer_blocking(_dispatcher_buffer_in); fprintf(dispatcher_log, "D%d: ----------- Loop Start -----------\n", _dispatcher_id); while (_msg->msg_id != POISON_ID) { it_out = allocListIterator(_dispatcher_lista_buffer_out); while (hasNextList(it_out) == 1) { int i; _sender_buffer = nextElementFromList(it_out); _sender_buffer_id = getBufferID(_sender_buffer); i = gsl_matrix_get(_dispatcher_adjacency_matrix, _sender_buffer_id - 1, _dispatcher_id - 1); /* i = 1;*/ /* fprintf(dispatcher_log, "sender %d receiver %d matrix_get %d\n", _sender_buffer_id, _dispatcher_id, i); */ if (i == 1) { putInBuffer_blocking(_sender_buffer, _msg); fprintf(dispatcher_log, "D%d: > (%d,%d,%f,%f) > %d\n", _dispatcher_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z, _sender_buffer_id); } } freeListIterator(it_out); fprintf(dispatcher_log, "D%d: ----------------------------------\n", _dispatcher_id); _msg = getFromBuffer_blocking(_dispatcher_buffer_in); } fprintf(dispatcher_log, "D%d: ------------ Loop End ------------\n", _dispatcher_id); /* * Inoltra nel sender buffer associato e solo in quello il POISON_ID */ it_out = allocListIterator(_dispatcher_lista_buffer_out); _sender_buffer = nextElementFromList(it_out); _sender_buffer_id = getBufferID(_sender_buffer); while (_sender_buffer_id != _dispatcher_id) { _sender_buffer = nextElementFromList(it_out); _sender_buffer_id = getBufferID(_sender_buffer); } putInBuffer_blocking(_sender_buffer, _msg); fprintf(dispatcher_log, "D%d: Signal:\n", _dispatcher_id); fprintf(dispatcher_log, "D%d: > snd (%d,%d,%f,%f) > %d\n", _dispatcher_id, _msg->msg_id, _msg->msg_time, _msg->msg_x, _msg->msg_z, _sender_buffer_id); fprintf(dispatcher_log, "D%d: Wait:\n", _dispatcher_id); fprintf(dispatcher_log, "D%d: > numero_receiver_vivi > 0\n", _dispatcher_id); /* * Attende che tutti i receiver siano morti */ while (numero_receiver_vivi > 0); fprintf(dispatcher_log, "D%d: Memoria:\n", _dispatcher_id); /* * free delle variabili usate */ freeBuffer(_dispatcher_buffer_in); fprintf(dispatcher_log, "D%d: > free(receiver_buffer)\n", _dispatcher_id); free(_parametri_dispatcher); fprintf(dispatcher_log, "D%d: > parametri\n", _dispatcher_id); /* * Fa il fflush del file di log e lo chiude */ fprintf(dispatcher_log, "D%d: Close log\n", _dispatcher_id); fflush(dispatcher_log); fclose(dispatcher_log); /* * Decrementa numero_dispatcher_vivi e termina */ numero_dispatcher_vivi--; return NULL; } parametri_router allocParamRouter(char *_router_ip_to_listen, int _port_client_to_router, int _port_router_to_client) { parametri_router _M_parametri_router = (struct parametri_router_t *) malloc(sizeof (struct parametri_router_t)); _M_parametri_router->router_ip_to_listen = _router_ip_to_listen; _M_parametri_router->port_router_to_client = _port_router_to_client; _M_parametri_router->port_client_to_router = _port_client_to_router; return _M_parametri_router; } void *runRouter(void *_parametri_router) { parametri_router _parametri = (parametri_router) _parametri_router; char *_router_ip_to_listen; int _port_client_to_router; int _port_router_to_client; int _router_agents_number; list lista_buffer_in_M_; list_iterator it_in; buffer _buffer_in; list lista_buffer_out_M_; pthread_t dispatcher_T_; pthread_t accepter_in_T_; pthread_t accepter_out_T_; FILE *router_log; /* * Apre il file di log */ router_log = fopen("router.log", "w"); if (router_log == NULL) { perror("Errore apertura file: \"router.log\"\n"); exit(1); }; setbuf(router_log, NULL); fprintf(router_log, ": Open log\n"); fprintf(router_log, ": Parametri di invocazione:\n"); _router_ip_to_listen = _parametri->router_ip_to_listen; fprintf(router_log, ": > _router_ip_to_listen = %s\n", _router_ip_to_listen); _port_client_to_router = _parametri->port_client_to_router; fprintf(router_log, ": > _port_client_to_router = %d\n", _port_client_to_router); _port_router_to_client = _parametri->port_router_to_client; fprintf(router_log, ": > _port_router_to_client = %d\n", _port_router_to_client); fprintf(router_log, ": Memoria:\n"); _router_agents_number = 6; fprintf(router_log, ": > _router_agents_number = %d\n", _router_agents_number); lista_buffer_in_M_ = allocList(); fprintf(router_log, ": > alloc(lista_buffer_in)\n"); lista_buffer_out_M_ = allocList(); fprintf(router_log, ": > alloc(lista_buffer_out)\n"); /* * Fa partire i due accepter (threads) */ pthread_create(&accepter_in_T_, NULL, &runAccepter, allocParamAccepter(_router_agents_number, _router_ip_to_listen, _port_client_to_router, lista_buffer_in_M_, 0)); fprintf(router_log, ": Thread -< Accepter():\n"); fprintf(router_log, ": > _accepter_agents_number = %d\n", _router_agents_number); fprintf(router_log, ": > _accepter_address = %s\n", _router_ip_to_listen); fprintf(router_log, ": > _accepter_port = %d\n", _port_client_to_router); fprintf(router_log, ": > _accepter_in_out = %d\n", 0); pthread_create(&accepter_out_T_, NULL, &runAccepter, allocParamAccepter(_router_agents_number, _router_ip_to_listen, _port_router_to_client, lista_buffer_out_M_, 1)); fprintf(router_log, ": Thread -< Accepter():\n"); fprintf(router_log, ": > _accepter_agents_number = %d\n", _router_agents_number); fprintf(router_log, ": > _accepter_address = %s\n", _router_ip_to_listen); fprintf(router_log, ": > _accepter_port = %d\n", _port_router_to_client); fprintf(router_log, ": > _accepter_in_out = %d\n", 1); /* * Attende che i due accepter abbiano terminato il loro compito */ fprintf(router_log, ": Wait:\n"); fprintf(router_log, ": > pthread_join(accepter_out)\n"); pthread_join(accepter_out_T_, NULL); fprintf(router_log, ": > pthread_join(accepter_in)\n"); pthread_join(accepter_in_T_, NULL); fprintf(router_log, ": Loop:\n"); fprintf(router_log, ": > while hasNext(lista_buffer_in)\n"); /* * Associa ad ogni receiver buffer un dispatcher */ it_in = allocListIterator(lista_buffer_in_M_); fprintf(router_log, ": ----------- Loop Start -----------\n"); while (hasNextList(it_in) == 1) { _buffer_in = nextElementFromList(it_in); numero_dispatcher_vivi++; pthread_create(&dispatcher_T_, NULL, &runDispatcher, allocParamDispatcher(_buffer_in, lista_buffer_out_M_)); fprintf(router_log, ": >>> create dispatcher thread\n"); } freeListIterator(it_in); fprintf(router_log, ": ------------ Loop End ------------\n"); /* Attende che tutti i sender thread creati siano morti, infatti loro sono gli ultimi a morire */ fprintf(router_log, ": Wait:\n"); fprintf(router_log, ": > numero_sender_vivi > 0\n"); while (numero_sender_vivi > 0); fprintf(router_log, ": Memoria:\n"); /* * free delle variabili usate */ freeList(lista_buffer_in_M_); lista_buffer_in_M_ = NULL; fprintf(router_log, ": > free(lista_buffer_in)\n"); freeList(lista_buffer_out_M_); lista_buffer_out_M_ = NULL; fprintf(router_log, ": > free(lista_buffer_out)\n"); free(_parametri_router); fprintf(router_log, ": > parametri\n"); /* * fflush e chiusura del logfile */ fprintf(router_log, ": Close log\n"); fflush(router_log); fclose(router_log); return NULL; }
{ "alphanum_fraction": 0.6648795432, "avg_line_length": 26.8951310861, "ext": "c", "hexsha": "beee8a9feccabd910636c1c17bc75e1966d68c2e", "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": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vittorioc/VirtualAgent", "max_forks_repo_path": "router.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "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": "vittorioc/VirtualAgent", "max_issues_repo_path": "router.c", "max_line_length": 171, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0455a86a79ef2c5a817b9a1ec26d9025703d22ab", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vittorioc/VirtualAgent", "max_stars_repo_path": "router.c", "max_stars_repo_stars_event_max_datetime": "2017-01-29T01:05:11.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-29T01:05:11.000Z", "num_tokens": 7591, "size": 28724 }
/* * fvector.h * * Created on: Feb 4, 2014 * Author: vbonnici */ #ifndef FVECTOR_H_ #define FVECTOR_H_ #include <limits> #include <vector> #include "data_ts.h" #include <gsl/gsl_rng.h> using namespace dolierlib; namespace dolierlib{ /* * shuffle sequences... remember to swap also their lengths */ void shuffle( std::vector<dna5_t*> &f_sequences, std::vector<usize_t> &f_lengths, int ntimes) { srand( (unsigned)time(NULL) ); size_t f,s; //dna5_t *tmp_s; usize_t tmp_l; for(int i=0; i<ntimes; i++){ f = static_cast<size_t>(ceil((rand()/(RAND_MAX +1.0))*(static_cast<double>(f_sequences.size() -1)))); s = static_cast<size_t>(ceil((rand()/(RAND_MAX +1.0))*(static_cast<double>(f_sequences.size() -1)))); // std::cout<<f<<"\t"<<s<<"\n"; std::swap(f_sequences[f], f_sequences[s]); std::swap(f_lengths[f], f_lengths[s]); } } /* * swap randomly the first leading_possequences with a forward position */ void leading_shuffle( std::vector<dna5_t*> &f_sequences, std::vector<usize_t> &f_lengths, size_t leading_pos) { srand( (unsigned)time(NULL) ); size_t f; for(size_t i=0; i<leading_pos; i++){ f = static_cast<size_t>(ceil((rand()/(RAND_MAX))*(static_cast<double>(f_sequences.size()- leading_pos -1)))) + leading_pos; //f = static_cast<size_t>((gsl_rng_uniform (r) * static_cast<double>(f_sequences.size() - leading_pos))) + leading_pos // std::cout<<i<<"\t"<<f<<"\n"; // print_dna5(f_sequences[i], f_lengths[i]);std::cout<<"\t";print_dna5(f_sequences[f], f_lengths[f]);std::cout<<"\n"; std::swap(f_sequences[i], f_sequences[f]); std::swap(f_lengths[i], f_lengths[f]); // print_dna5(f_sequences[i], f_lengths[i]);std::cout<<"\t";print_dna5(f_sequences[f], f_lengths[f]);std::cout<<"\n"; } } /* * Get kmers spectra. * Only non-zero columns are reported. * Let X to be the length of the longest input sequences, then theoretically we have sum_{i=1}^{i<=X}(4^i) features (possible kmers) * but some of these theoretical kmers do not appear in the input sequences, so they are excluded from the output spectra. * Moreover, if sequences are all of the same length, the working X is X-1. * */ void fvector( std::vector<dna5_t*> &f_sequences, std::vector<usize_t> &f_lengths, double ***vectors, //output spectra, it's pointer size_t *vector_length, //length of spectra, it's a pointer double **weights ) { DNA5MS_t f_ms(true); concat(f_ms, f_sequences, f_lengths, false); f_ms.areUndefTeminated = true; CsFullyContainer f_ds(true); build_fully_ds(f_ms, f_ds); //build_strict_ds(f_ms, f_ds); Cs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs); SASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length); size_t max_length = 0; for(size_t i=0; i<f_lengths.size(); i++){ if(f_lengths[i] > max_length) max_length = f_lengths[i]; } size_t nof_features = 0; size_t *nof_kfeatures = new size_t[max_length+1]; for(size_t i=1; i<=max_length; i++){ NSAIterator it = NSAIterator::begin(f_ms, f_ds, i); nof_kfeatures[i] = nof(it); nof_features += nof_kfeatures[i]; std::cout<<i<<"\t"<<nof_kfeatures[i]<<"\t"<<f_sequences.size()<<"\n"; //if sequences are all of the same length, the working X is X-1. if(nof_kfeatures[i] == f_sequences.size() && i<=max_length){ if(i>1){ std::cout<<"#\n"; max_length = i-1; nof_features -= nof_kfeatures[i]; } else{ max_length = i; } break; } } //double **table = new double*[f_sequences.size()]; (*vectors) = new double*[f_sequences.size()]; for(size_t i=0; i<f_sequences.size(); i++){ (*vectors)[i] = new double[nof_features]; for(size_t j=0; j<nof_features; j++) (*vectors)[i][j] = 0; } (*weights) = new double[nof_features]; size_t c_nf = 0; size_t ii; for(size_t k=1; k<=max_length; k++){ NSAIterator it = NSAIterator::begin(f_ms, f_ds, k); dna5_t *kmer = new dna5_t[k]; while(it.next()){ it.get_kmer(kmer); // std::cout<<c_nf<<"\t";print_dna5(kmer,k); std::cout<<"\n"; for(ii=it.i_start; ii<it.i_end; ii++){ (*vectors)[f_dlindex.ss_ids[ii]][c_nf]++; (*weights)[c_nf] = k; } c_nf++; } } *vector_length = nof_features; } /* * normalize vectors by column, from [0,max] to [min,max]/(max-min) */ void normalize(double **matrix, size_t size1, size_t size2) { for(size_t i=0; i<size2; i++){ double min = std::numeric_limits<double>::max(); double max = std::numeric_limits<double>::min(); for(size_t j=0; j<size1; j++){ if(matrix[j][i]< min) min = matrix[j][i]; if(matrix[j][i] > max) max = matrix[j][i]; } double f = max - min; for(size_t j=0; j<size1; j++){ matrix[j][i] = (matrix[j][i] - min) / f; } } } /* * normalize vectors by column, from [0,max] to [0,max]/(max) */ void normalize_by_sum(double **matrix, size_t size1, size_t size2) { for(size_t i=0; i<size2; i++){ double sum = 0; for(size_t j=0; j<size1; j++){ sum += matrix[j][i]; } for(size_t j=0; j<size1; j++){ matrix[j][i] /= sum; } } } /* * Keep only those columns having at least one element >= min_value. * Unselected columns are putted at the end of the matrix. */ void keep_only( double **matrix, //input matrix size_t size1, //number of rows size_t size2, //number of columns double min_value, //min value for selection size_t *new_size2 //result number of columns ) { size_t to_size = size2; size_t to_pos = 0; for(size_t j=0; j<size2; j++){ bool keep = false; for(size_t i=0; i<size1; i++){ if(matrix[i][j] >= min_value){ keep = true; break; } } if(keep){ if(j != to_pos){ for(size_t i=0; i<size1; i++){ matrix[i][to_pos] = matrix[i][j]; } } to_pos++; } else{ to_size--; } } *new_size2 = to_size; } /* * Same behaviour of keep_only, but it swap the weights matrix, too. */ void keep_only(double **matrix, size_t size1, size_t size2, double min_value, size_t *new_size2, double *weights) { size_t to_size = size2; size_t to_pos = 0; for(size_t j=0; j<size2; j++){ bool keep = false; for(size_t i=0; i<size1; i++){ if(matrix[i][j] >= min_value){ keep = true; break; } } if(keep){ if(j != to_pos){ for(size_t i=0; i<size1; i++){ matrix[i][to_pos] = matrix[i][j]; } weights[to_pos] = weights[j]; } to_pos++; } else{ to_size--; } } *new_size2 = to_size; } /* * Theoretical spectra are vectors if length sum_{i=1}^{i<=X}(4^i). * Thus, weights[i] correspond to the specific length i of the releated theoretical kmer. * */ void get_fvectors_weights(double *weights, size_t length, std::vector<dna5_t*> &f_sequences, std::vector<usize_t> &f_lengths){ // size_t base = 0; // size_t ebase = 0; // size_t cbase = 0; // for(size_t i=0;i<length; i++){ // if(cbase == ebase){ // base++; // ebase = static_cast<size_t>(pow(4, base)); // cbase = 0; // } // weights[i] = base; // cbase++; // } DNA5MS_t f_ms(true); concat(f_ms, f_sequences, f_lengths, false); f_ms.areUndefTeminated = true; CsFullyContainer f_ds(true); build_fully_ds(f_ms, f_ds); //build_strict_ds(f_ms, f_ds); Cs5DLIndex f_dlindex(f_ms.seq, f_ms.seq_length, f_ds.SA, f_ms.lengths, f_ms.nof_seqs); SASearcher sas(f_ms.seq, f_ds.SA, f_ms.seq_length); size_t max_length = 0; for(size_t i=0; i<f_lengths.size(); i++){ if(f_lengths[i] > max_length) max_length = f_lengths[i]; } size_t nof_features = 0; size_t *nof_kfeatures = new size_t[max_length+1]; for(size_t i=1; i<=max_length; i++){ NSAIterator it = NSAIterator::begin(f_ms, f_ds, i); nof_kfeatures[i] = nof(it); nof_features += nof_kfeatures[i]; std::cout<<i<<"\t"<<nof_kfeatures[i]<<"\t"<<f_sequences.size()<<"\n"; //if sequences are all of the same length, the working X is X-1. if(nof_kfeatures[i] == f_sequences.size() && i<=max_length){ if(i>1){ std::cout<<"#\n"; max_length = i-1; nof_features -= nof_kfeatures[i]; } else{ max_length = i; } break; } } size_t c_nf = 0; size_t ii; for(size_t k=1; k<=max_length; k++){ NSAIterator it = NSAIterator::begin(f_ms, f_ds, k); dna5_t *kmer = new dna5_t[k]; while(it.next()){ it.get_kmer(kmer); // std::cout<<c_nf<<"\t";print_dna5(kmer,k); std::cout<<"\n"; for(ii=it.i_start; ii<it.i_end; ii++){ weights[c_nf] = k; } c_nf++; } } } void print_matrix(double **matrix, size_t size1, size_t size2){ for(size_t i=0; i<size1; i++){ for(size_t j=0; j<size2; j++){ std::cout<<matrix[i][j]<<" "; } std::cout<<"\n"; } } } #endif /* FVECTOR_H_ */
{ "alphanum_fraction": 0.6315421378, "avg_line_length": 22.6957671958, "ext": "h", "hexsha": "5ca0d5d3cd394da48110648b2d5e66029a484c2f", "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": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vbonnici/DoLiER", "max_forks_repo_path": "dolierlib/clustering/fvector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "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": "vbonnici/DoLiER", "max_issues_repo_path": "dolierlib/clustering/fvector.h", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vbonnici/DoLiER", "max_stars_repo_path": "dolierlib/clustering/fvector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2812, "size": 8579 }
/* * ----------------------------------------------------------------- * Thermochemistry Library --- thrm_lib.h * Version: 1.6180 * Date: Dec 29, 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 header file for a library with * thermochemistry routines. * ----------------------------------------------------------------- */ #ifndef __THRM_LIB_H__ #define __THRM_LIB_H__ #include <gsl/gsl_vector.h> #include <nvector/nvector_serial.h> /* * ------------------------------------------------------------ * Types: struct thrm_struct, thrm_wrk * ------------------------------------------------------------ * This structure contains fields of the Chemkin workspace. * * last update: Mar 5, 2009 * ------------------------------------------------------------ */ typedef struct thrm_struct { int *iwk; /* integer work vector */ double *rwk; /* real work vector */ char *cwk; /* character work vector */ int leniwk; /* iwk dimension */ int lenrwk; /* rwk dimension */ int lencwk; /* cwk dimension */ int n_e; /* # of chemical elements */ int n_s; /* # of elementary species */ int n_r; /* # of elementary reactions */ } thrm_wrk; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ void thrm_title(); void thrm_mech(int n_e, int n_s, int n_r, char *mech); int thrm_input(int *steps, double *t0, double *delta_t, double *Tmax, double *Tmin, double *tol); thrm_wrk* thrm_alloc(); void thrm_free(void **thrm_bl); int thrm_init(thrm_wrk *thrm); void thrm_composition(thrm_wrk *thrm, gsl_vector *phi); void thrm_page_heading0(FILE *file); double thrm_h2T(thrm_wrk *thrm, double *phi, double Tmax, double Tmin, double tol); void thrm_temp_meanvar(int Np, gsl_vector **ps, thrm_wrk *thrm, double Tmax, double Tmin, double tol, double *mean, double *var); double thrm_rrsum(gsl_vector *phi); double thrm_mfsum(gsl_vector *phi); int thrm_mfsign(gsl_vector *phi); int thrm_eqs(double t, N_Vector phi, N_Vector Rphi, void *thrm_data); int thrm_eqs2(double t, N_Vector phi, N_Vector Sphi, void *thrm_data); #endif /* __THRM_LIB_H__ */
{ "alphanum_fraction": 0.4803921569, "avg_line_length": 27.6090225564, "ext": "h", "hexsha": "f9cac26280ff1ffb1f03b7d0b6ccff295841d3a8", "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/include/thrm_lib.h", "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/include/thrm_lib.h", "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-1.0/include/thrm_lib.h", "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": 784, "size": 3672 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <Accelerate/Accelerate.h> #include "infmcmc.h" #define nj1 32 #define nk1 32 void infmcmc_initChain(INFCHAIN *C, const int nj, const int nk) { const int maxk = (nk >> 1) + 1; const int sspectral = sizeof(fftw_complex) * nj * maxk; const int sphysical = sizeof(double ) * nj * nk; //const int obsVecMem = sizeof(double ) * sizeObsVector; FILE *fp; unsigned long int seed; // Set up variables C->nj = nj; C->nk = nk; //C->sizeObsVector = sizeObsVector; C->currentIter = 0; C->accepted = 0; C->_shortTimeAccProbAvg = 0.0; C->_bLow = 0.0; C->_bHigh = 1.0; // Allocate a ton of memory C->currentPhysicalState = (double *)malloc(sphysical); C->avgPhysicalState = (double *)malloc(sphysical); C->varPhysicalState = (double *)malloc(sphysical); C->proposedPhysicalState = (double *)malloc(sphysical); C->_M2 = (double *)malloc(sphysical); //C->currentStateObservations = (double *)malloc(obsVecMem); //C->proposedStateObservations = (double *)malloc(obsVecMem); //C->data = (double *)malloc(obsVecMem); C->currentSpectralState = (fftw_complex *)fftw_malloc(sspectral); C->avgSpectralState = (fftw_complex *)fftw_malloc(sspectral); C->priorDraw = (fftw_complex *)fftw_malloc(sspectral); C->proposedSpectralState = (fftw_complex *)fftw_malloc(sspectral); memset(C->currentPhysicalState, 0, sphysical); memset(C->avgPhysicalState, 0, sphysical); memset(C->varPhysicalState, 0, sphysical); memset(C->proposedPhysicalState, 0, sphysical); memset(C->_M2, 0, sphysical); memset(C->currentSpectralState, 0, sspectral); memset(C->avgSpectralState, 0, sspectral); memset(C->proposedSpectralState, 0, sspectral); C->accProb = 0.0; C->avgAccProb = 0.0; C->logLHDCurrentState = 0.0; /* * Set some default values */ C->alphaPrior = 3.0; C->rwmhStepSize = 1e-4; C->priorVar = 1.0; C->priorStd = 1.0; C->r = gsl_rng_alloc(gsl_rng_taus2); fp = fopen("/dev/urandom", "rb"); if (fp != NULL) { fread(&seed, sizeof(unsigned long int), 1, fp); gsl_rng_set(C->r, seed); fclose(fp); printf("Using random seed\n"); } else { gsl_rng_set(C->r, 0); printf("Using zero seed\n"); } C->_c2r = fftw_plan_dft_c2r_2d(nj, nk, C->proposedSpectralState, C->proposedPhysicalState, FFTW_MEASURE); C->_r2c = fftw_plan_dft_r2c_2d(nj, nk, C->currentPhysicalState, C->currentSpectralState, FFTW_MEASURE); } void infmcmc_freeChain(INFCHAIN *C) { // Free all allocated memory used by the chain free(C->currentPhysicalState); free(C->avgPhysicalState); free(C->varPhysicalState); free(C->proposedPhysicalState); free(C->_M2); //free(C->currentStateObservations); //free(C->proposedStateObservations); fftw_free(C->currentSpectralState); fftw_free(C->avgSpectralState); fftw_free(C->priorDraw); fftw_free(C->proposedSpectralState); gsl_rng_free(C->r); } void infmcmc_resetChain(INFCHAIN *C) { infmcmc_freeChain(C); infmcmc_initChain(C, C->nj, C->nk); } void infmcmc_writeChain(const INFCHAIN *C, FILE *fp) { const int s = C->nj * C->nk; fwrite(&(C->nj), sizeof(int), 1, fp); fwrite(&(C->nk), sizeof(int), 1, fp); fwrite(&(C->currentIter), sizeof(int), 1, fp); fwrite(C->currentPhysicalState, sizeof(double), s, fp); fwrite(C->avgPhysicalState, sizeof(double), s, fp); fwrite(C->varPhysicalState, sizeof(double), s, fp); fwrite(&(C->logLHDCurrentState), sizeof(double), 1, fp); fwrite(&(C->accProb), sizeof(double), 1, fp); fwrite(&(C->avgAccProb), sizeof(double), 1, fp); } void infmcmc_writeChainInfo(const INFCHAIN *C, FILE *fp) { fwrite(&(C->nj), sizeof(int), 1, fp); fwrite(&(C->nk), sizeof(int), 1, fp); } void infmcmc_writeVFChain(const INFCHAIN *U, const INFCHAIN *V, FILE *fp) { const int s = U->nj * U->nk; fwrite(U->currentPhysicalState, sizeof(double), s, fp); fwrite(U->avgPhysicalState, sizeof(double), s, fp); fwrite(U->varPhysicalState, sizeof(double), s, fp); fwrite(V->currentPhysicalState, sizeof(double), s, fp); fwrite(V->avgPhysicalState, sizeof(double), s, fp); fwrite(V->varPhysicalState, sizeof(double), s, fp); fwrite(&(U->logLHDCurrentState), sizeof(double), 1, fp); fwrite(&(U->accProb), sizeof(double), 1, fp); fwrite(&(U->avgAccProb), sizeof(double), 1, fp); } void infmcmc_printChain(INFCHAIN *C) { printf("Iteration %d\n", C->currentIter); printf("-- Length is %d x %d\n", C->nj, C->nk); printf("-- llhd val is %lf\n", C->logLHDCurrentState); printf("-- Acc. prob is %.10lf\n", C->accProb); printf("-- Avg. acc. prob is %.10lf\n", C->avgAccProb); printf("-- Beta is %.10lf\n\n", C->rwmhStepSize); //finmcmc_printCurrentState(C); //finmcmc_printAvgState(C); //finmcmc_printVarState(C); } void randomPriorDraw(INFCHAIN *C) { int j, k; const int maxk = (C->nk >> 1) + 1; const int nko2 = C->nk >> 1; const int njo2 = C->nj >> 1; double xrand, yrand, c; //const double one = 1.0; c = 4.0 * M_PI * M_PI; for(j = 0; j < C->nj; j++) { for(k = 0; k < maxk; k++) { xrand = gsl_ran_gaussian_ziggurat(C->r, C->priorStd); if((j == 0) && (k == 0)) { C->priorDraw[0] = 0.0; } else if((j == njo2) && (k == nko2)) { C->priorDraw[maxk*njo2+nko2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0); } else if((j == 0) && (k == nko2)) { C->priorDraw[nko2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0); } else if((j == njo2) && (k == 0)) { C->priorDraw[maxk*njo2] = /*C->nj */ xrand / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0); } else { xrand /= sqrt(2.0); yrand = gsl_ran_gaussian_ziggurat(C->r, C->priorStd) / sqrt(2.0); C->priorDraw[maxk*j+k] = /*C->nj */ (xrand + I * yrand) / pow(c * ((j * j) + (k * k)), (double)C->alphaPrior/2.0); if(j > njo2) { C->priorDraw[maxk*j+k] = conj(C->priorDraw[maxk*(C->nj-j)+k]); } } } } } void randomDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2) { int j, k; const int maxk = (C1->nk >> 1) + 1; const int njo2 = C2->nj >> 1; const int nko2 = C1->nk >> 1; double modk; randomPriorDraw(C1); for (j = 0; j < C1->nj; j++) { for (k = 0; k < maxk; k++) { if (j == 0 && k == 0) { C1->priorDraw[0] = 0.0; C2->priorDraw[0] = 0.0; continue; } modk = sqrt(j * j + k * k); if (j < njo2) { C2->priorDraw[maxk*j+k] = -j * C1->priorDraw[maxk*j+k] / modk; } else if (j > njo2) { C2->priorDraw[maxk*j+k] = -(j - C1->nj) * C1->priorDraw[maxk*j+k] / modk; } else { C2->priorDraw[maxk*j+k] = 0.0; } if (k < nko2) { C1->priorDraw[maxk*j+k] *= k / modk; } else { C1->priorDraw[maxk*j+k] = 0.0; } } } } void infmcmc_seedWithPriorDraw(INFCHAIN *C) { const int size = sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1); fftw_complex *uk = (fftw_complex *)fftw_malloc(size); const fftw_plan p = fftw_plan_dft_c2r_2d(C->nj, C->nk, uk, C->currentPhysicalState, FFTW_ESTIMATE); randomPriorDraw(C); memcpy(uk, C->priorDraw, size); //fixme: put into current spectral state fftw_execute(p); fftw_destroy_plan(p); fftw_free(uk); } void infmcmc_seedWithDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2) { const int size = sizeof(fftw_complex) * C1->nj * ((C1->nk >> 1) + 1); fftw_complex *uk = (fftw_complex *)fftw_malloc(size); const fftw_plan p = fftw_plan_dft_c2r_2d(C1->nj, C1->nk, uk, C1->currentPhysicalState, FFTW_ESTIMATE); randomDivFreePriorDraw(C1, C2); memcpy(uk, C1->priorDraw, size); fftw_execute_dft_c2r(p, uk, C1->currentPhysicalState); memcpy(uk, C2->priorDraw, size); fftw_execute_dft_c2r(p, uk, C2->currentPhysicalState); memcpy(C1->currentSpectralState, C1->priorDraw, size); memcpy(C2->currentSpectralState, C2->priorDraw, size); fftw_destroy_plan(p); fftw_free(uk); } void infmcmc_proposeRWMH(INFCHAIN *C) { int j, k; const int maxk = (C->nk >> 1) + 1; const int N = C->nj * C->nk; const double sqrtOneMinusBeta2 = sqrt(1.0 - C->rwmhStepSize * C->rwmhStepSize); double *u = (double *)malloc(sizeof(double) * C->nj * C->nk); fftw_complex *uk = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * C->nj * maxk); memcpy(u, C->currentPhysicalState, sizeof(double) * C->nj * C->nk); fftw_execute_dft_r2c(C->_r2c, u, C->currentSpectralState); // Draw from prior distribution randomPriorDraw(C); for(j = 0; j < C->nj; j++) { for(k = 0; k < maxk; k++) { C->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C->currentSpectralState[maxk*j+k] + C->rwmhStepSize * C->priorDraw[maxk*j+k]; C->proposedSpectralState[maxk*j+k] /= N; } } memcpy(uk, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * maxk); fftw_execute_dft_c2r(C->_c2r, uk, C->proposedPhysicalState); fftw_free(uk); free(u); } void infmcmc_adaptRWMHStepSize(INFCHAIN *C, double inc) { // Adapt to stay in 20-30% range. int adaptFreq = 100; double rate; if (C->currentIter > 0 && C->currentIter % adaptFreq == 0) { rate = (double) C->_shortTimeAccProbAvg / adaptFreq; if (rate < 0.2) { //C->_bHigh = C->rwmhStepSize; //C->rwmhStepSize = (C->_bLow + C->_bHigh) / 2.0; C->rwmhStepSize -= inc; } else if (rate > 0.3) { //C->_bLow = C->rwmhStepSize; //C->rwmhStepSize = (C->_bLow + C->_bHigh) / 2.0; C->rwmhStepSize += inc; } C->_shortTimeAccProbAvg = 0.0; } else { C->_shortTimeAccProbAvg += C->accProb; } } void infmcmc_proposeDivFreeRWMH(INFCHAIN *C1, INFCHAIN *C2) { int j, k; const int maxk = (C1->nk >> 1) + 1; const int N = C1->nj * C1->nk; const double sqrtOneMinusBeta2 = sqrt(1.0 - C1->rwmhStepSize * C1->rwmhStepSize); double *u = (double *)malloc(sizeof(double) * C1->nj * C1->nk); fftw_complex *uk = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * C1->nj * maxk); memcpy(u, C1->currentPhysicalState, sizeof(double) * C1->nj * C1->nk); fftw_execute_dft_r2c(C1->_r2c, u, C1->currentSpectralState); memcpy(u, C2->currentPhysicalState, sizeof(double) * C2->nj * C2->nk); fftw_execute_dft_r2c(C2->_r2c, u, C2->currentSpectralState); // Draw from prior distribution randomDivFreePriorDraw(C1, C2); for(j = 0; j < C1->nj; j++) { for(k = 0; k < maxk; k++) { C1->currentSpectralState[maxk*j+k] /= N; C2->currentSpectralState[maxk*j+k] /= N; C1->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C1->currentSpectralState[maxk*j+k] + C1->rwmhStepSize * C1->priorDraw[maxk*j+k]; //C1->proposedSpectralState[maxk*j+k] /= N; C2->proposedSpectralState[maxk*j+k] = sqrtOneMinusBeta2 * C2->currentSpectralState[maxk*j+k] + C2->rwmhStepSize * C2->priorDraw[maxk*j+k]; //C2->proposedSpectralState[maxk*j+k] /= N; } } memcpy(uk, C1->proposedSpectralState, sizeof(fftw_complex) * C1->nj * maxk); fftw_execute_dft_c2r(C1->_c2r, uk, C1->proposedPhysicalState); memcpy(uk, C2->proposedSpectralState, sizeof(fftw_complex) * C1->nj * maxk); fftw_execute_dft_c2r(C2->_c2r, uk, C2->proposedPhysicalState); fftw_free(uk); free(u); } void infmcmc_updateAvgs(INFCHAIN *C) { int j, k; double deltar; fftw_complex deltac; C->currentIter++; /* Update physical vectors */ if (C->currentIter == 1) { for (j = 0; j < C->nj; j++) { for (k = 0; k < C->nk; k++) { deltar = C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k]; C->avgPhysicalState[C->nk * j + k] += (deltar / C->currentIter); C->_M2[C->nk * j + k] += (deltar * (C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k])); C->varPhysicalState[C->nk * j + k] = -1.0; } } } else { for (j = 0; j < C->nj; j++) { for (k = 0; k < C->nk; k++) { deltar = C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k]; C->avgPhysicalState[C->nk * j + k] += (deltar / C->currentIter); C->_M2[C->nk * j + k] += (deltar * (C->currentPhysicalState[C->nk * j + k] - C->avgPhysicalState[C->nk * j + k])); C->varPhysicalState[C->nk * j + k] = C->_M2[C->nk * j + k] / (C->currentIter - 1); } } } /* Update spectral vectors */ if (C->currentIter == 1) { for (j = 0; j < C->nj; j++) { for (k = 0; k < C->nk/2 + 1; k++) { deltac = C->currentSpectralState[(C->nk/2 + 1) * j + k] - C->avgSpectralState[(C->nk/2 + 1) * j + k]; C->avgSpectralState[(C->nk/2 + 1) * j + k] += (deltac / C->currentIter); } } } else { for (j = 0; j < C->nj; j++) { for (k = 0; k < C->nk/2 + 1; k++) { deltac = C->currentSpectralState[(C->nk/2 + 1) * j + k] - C->avgSpectralState[(C->nk/2 + 1) * j + k]; C->avgSpectralState[(C->nk/2 + 1) * j + k] += (deltac / C->currentIter); } } } /* Update scalars */ C->avgAccProb += ((C->accProb - C->avgAccProb) / C->currentIter); } void infmcmc_updateRWMH(INFCHAIN *C, double logLHDOfProposal) { double alpha; alpha = exp(C->logLHDCurrentState - logLHDOfProposal); if (alpha > 1.0) { alpha = 1.0; } // fixme: set acc prob here instead if (gsl_rng_uniform(C->r) < alpha) { memcpy(C->currentSpectralState, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1)); memcpy(C->currentPhysicalState, C->proposedPhysicalState, sizeof(double) * C->nj * C->nk); C->accProb = alpha; C->logLHDCurrentState = logLHDOfProposal; } infmcmc_updateAvgs(C); } void infmcmc_updateVectorFieldRWMH(INFCHAIN *C1, INFCHAIN *C2, double logLHDOfProposal) { double alpha; // log likelihoods will be the same for both chains alpha = exp(C1->logLHDCurrentState - logLHDOfProposal); if (alpha > 1.0) { alpha = 1.0; } C1->accepted = 0; C2->accepted = 0; C1->accProb = alpha; C2->accProb = alpha; if (gsl_rng_uniform(C1->r) < alpha) { C1->accepted = 1; C2->accepted = 1; memcpy(C1->currentSpectralState, C1->proposedSpectralState, sizeof(fftw_complex) * C1->nj * ((C1->nk >> 1) + 1)); memcpy(C1->currentPhysicalState, C1->proposedPhysicalState, sizeof(double) * C1->nj * C1->nk); C1->logLHDCurrentState = logLHDOfProposal; memcpy(C2->currentSpectralState, C2->proposedSpectralState, sizeof(fftw_complex) * C2->nj * ((C2->nk >> 1) + 1)); memcpy(C2->currentPhysicalState, C2->proposedPhysicalState, sizeof(double) * C2->nj * C2->nk); C2->logLHDCurrentState = logLHDOfProposal; } infmcmc_updateAvgs(C1); infmcmc_updateAvgs(C2); } void infmcmc_setRWMHStepSize(INFCHAIN *C, double beta) { C->rwmhStepSize = beta; } void infmcmc_setPriorAlpha(INFCHAIN *C, double alpha) { C->alphaPrior = alpha; } void infmcmc_setPriorVar(INFCHAIN *C, double var) { C->priorVar = var; C->priorStd = sqrt(var); } double L2Field(fftw_complex *uk, int nj, int nk) { int j, k; const int maxk = (nk >> 1) + 1; double sum = 0.0; for (j = 0; j < nj; j++) { for (k = 0; k < maxk; k++) { sum += cabs(uk[maxk*j+k]) * cabs(uk[maxk*j+k]); } } return 2.0 * sum; } double infmcmc_L2Current(INFCHAIN *C) { return L2Field(C->currentSpectralState, C->nj, C->nk); } double infmcmc_L2Proposed(INFCHAIN *C) { return L2Field(C->proposedSpectralState, C->nj, C->nk); } double infmcmc_L2Prior(INFCHAIN *C) { return L2Field(C->priorDraw, C->nj, C->nk); } void randomPriorDrawOLD(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs) { int j, k; double xrand, yrand, c;//, scale; //const double one = 1.0; c = 4.0 * M_PI * M_PI; for(j = 0; j < nj1; j++) { for(k = 0; k < nk1/2 + 1; k++) { if((j == 0) && (k == 0)) { randDrawCoeffs[0] = 0.0; } else if((j == nj1/2) && (k == nk1/2)) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0); randDrawCoeffs[(nk1/2 + 1) * nj1/2 + nk1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0); } else if((j == 0) && (k == nk1/2)) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0); randDrawCoeffs[nk1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0); } else if((j == nj1/2) && (k == 0)) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0); randDrawCoeffs[(nk1/2 + 1) * nj1/2] = xrand / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0); } else { xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / sqrt(2.0); yrand = gsl_ran_gaussian_ziggurat(r, 1.0) / sqrt(2.0); randDrawCoeffs[(nk1/2 + 1) * j + k] = (xrand + I * yrand) / pow((c * ((j * j) + (k * k))), (double)PRIOR_ALPHA/2.0); if(j > nj1/2) { randDrawCoeffs[(nk1/2 + 1) * j + k] = conj(randDrawCoeffs[(nk1/2+1)*(nj1-j)+k]); } } } } /* for(j = 1; j < nj1 / 2; j++) { for(k = 0; k < nk1 / 2 + 1; k++) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2; yrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2; scale = pow(c * ((j * j) + (k * k)), (double)PRIOR_ALPHA/2.0); randDrawCoeffs[(nk1/2 + 1) * j + k] = (xrand + I * yrand) / scale; randDrawCoeffs[(nk1/2 + 1) * (nj1-j) + k] = (xrand - I * yrand) / scale; } } for(k = 1; k < nk1 / 2 + 1; k++) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2; randDrawCoeffs[k] = (xrand + I * yrand) / pow(c * (k * k), (double)PRIOR_ALPHA/2.0); } for(k = 0; k < nk1/2; k++) { xrand = gsl_ran_gaussian_ziggurat(r, 1.0) / M_SQRT2; randDrawCoeffs[(nk1/2+1)*(nj1/2)+k] = (xrand + I * yrand) / pow(c * ((nj1 * nj1 / 4) + (k * k)), (double)PRIOR_ALPHA/2.0); } randDrawCoeffs[0] = 0.0; xrand = gsl_ran_gaussian_ziggurat(r, 1.0); randDrawCoeffs[(nk1/2+1)*(nj1/2)+(nk1/2)] = xrand / pow(c * ((j * j) + (k * k)), (double)PRIOR_ALPHA/2.0); */ } void setRWMHStepSize(CHAIN *C, double stepSize) { C->rwmhStepSize = stepSize; } void resetAvgs(CHAIN *C) { /* Sets avgPhysicalState to currentPhysicalState and avgSpectralState to currentSpectralState */ const size_t size_doublenj = sizeof(double) * C->nj; memcpy(C->avgPhysicalState, C->currentPhysicalState, size_doublenj * C->nk); memcpy(C->avgSpectralState, C->currentSpectralState, size_doublenj * ((C->nk >> 1) + 1)); } void resetVar(CHAIN *C) { // Sets varPhysicalState to 0 memset(C->varPhysicalState, 0, sizeof(double) * C->nj * C->nk); } void proposeIndependence(CHAIN *C) { const int maxk = (C->nk >> 1) + 1; memcpy(C->proposedSpectralState, C->priorDraw, sizeof(fftw_complex) * C->nj * maxk); } double lsqFunctional(const double * const data, const double * const obsVec, const int obsVecSize, const double obsStdDev) { int i; double temp1, sum1 = 0.0; for(i = 0; i < obsVecSize; i++) { temp1 = (data[i] - obsVec[i]); sum1 += temp1 * temp1; } return sum1 / (2.0 * obsStdDev * obsStdDev); } void acceptReject(CHAIN *C) { const double phi1 = lsqFunctional(C->data, C->currentStateObservations, C->sizeObsVector, C->obsStdDev); const double phi2 = lsqFunctional(C->data, C->proposedStateObservations, C->sizeObsVector, C->obsStdDev); double tempAccProb = exp(phi1 - phi2); if(tempAccProb > 1.0) { tempAccProb = 1.0; } if(gsl_rng_uniform(C->r) < tempAccProb) { memcpy(C->currentSpectralState, C->proposedSpectralState, sizeof(fftw_complex) * C->nj * ((C->nk >> 1) + 1)); memcpy(C->currentPhysicalState, C->proposedPhysicalState, sizeof(double) * C->nj * C->nk); memcpy(C->currentStateObservations, C->proposedStateObservations, sizeof(double) * C->sizeObsVector); C->accProb = tempAccProb; C->currentLSQFunctional = phi2; } else { C->currentLSQFunctional = phi1; } } // //void updateChain(CHAIN *C) { //C->currentIter++; //void updateAvgs(CHAIN *C); //void updateVar(CHAIN *C); /* int main(void) { int nj = 32, nk = 32, sizeObsVector = 0; unsigned long int randseed = 0; FILE *fp; CHAIN *C; C = (CHAIN *)malloc(sizeof(CHAIN)); initChain(C, nj, nk, sizeObsVector, randseed); randomPriorDraw2(C); fp = fopen("2.dat", "w"); fwrite(C->priorDraw, sizeof(fftw_complex), nj * (nk / 2 + 1), fp); fclose(fp); return 0; } */
{ "alphanum_fraction": 0.5901164172, "avg_line_length": 30.9941089838, "ext": "c", "hexsha": "b59756ab4ab54757e990c3d111b85c761083bf7e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dmcdougall/mcmclib", "max_forks_repo_path": "mcmclib/infmcmc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dmcdougall/mcmclib", "max_issues_repo_path": "mcmclib/infmcmc.c", "max_line_length": 144, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dmcdougall/mcmclib", "max_stars_repo_path": "mcmclib/infmcmc.c", "max_stars_repo_stars_event_max_datetime": "2015-11-21T22:02:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-21T22:02:58.000Z", "num_tokens": 7589, "size": 21045 }
static char help[] = "Solve nonlinear Liouville-Bratu equation in 2D on a structured-grid. Option prefix lb_.\n" "Solves\n" " - nabla^2 u - lambda e^u = 0\n" "on the unit square [0,1]x[0,1] subject to zero Dirichlet boundary conditions.\n" "Critical value occurs about at lambda = 6.808. Optional exact solution\n" "(Liouville 1853) in case lambda=1.0.\n\n"; /* compare: timer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8 timer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8 -snes_fd_color timer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -da_refine 8 -snes_mf_operator timer ./bratu2D -snes_monitor -snes_converged_reason -ksp_converged_reason -pc_type mg -snes_grid_sequence 8 timer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs timer mpiexec -n 4 ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs timer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type ngs -fas_levels_snes_ngs_sweeps 2 timer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type newtonls -fas_coarse_ksp_type preonly -fas_coarse_pc_type cholesky timer ./bratu2D -snes_monitor -snes_converged_reason -lb_showcounts -da_refine 8 -snes_type fas -fas_levels_snes_type ngs -fas_coarse_snes_type newtonls -fas_coarse_ksp_type cg -fas_coarse_pc_type icc -snes_fas_monitor -snes_fas_levels 6 */ /* excellent evidence of convergence in Liouville exact solution case: $ for LEV in 3 4 5 6 7 8 9; do ./bratu2D -da_refine $LEV -snes_monitor -snes_fd_color -snes_rtol 1.0e-10 -lb_exact -pc_type mg; done */ #include <petsc.h> #include "../../ch6/poissonfunctions.h" typedef struct { PetscReal lambda; PetscBool exact; int residualcount, ngscount; } BratuCtx; static PetscReal g_zero(PetscReal x, PetscReal y, PetscReal z, void *ctx) { return 0.0; } static PetscReal g_liouville(PetscReal x, PetscReal y, PetscReal z, void *ctx) { PetscReal r2 = (x + 1.0) * (x + 1.0) + (y + 1.0) * (y + 1.0), qq = r2 * r2 + 1.0, omega = r2 / (qq * qq); return 32.0 * omega; } extern PetscErrorCode FormUExact(DMDALocalInfo*, Vec, PoissonCtx*); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal **, PetscReal**, PoissonCtx*); extern PetscErrorCode NonlinearGS(SNES, Vec, Vec, void*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da, da_after; SNES snes; Vec u, uexact; PoissonCtx user; BratuCtx bctx; DMDALocalInfo info; PetscBool showcounts = PETSC_FALSE; PetscLogDouble flops; PetscReal errinf; PetscInitialize(&argc,&argv,NULL,help); user.Lx = 1.0; user.Ly = 1.0; user.Lz = 1.0; user.cx = 1.0; user.cy = 1.0; user.cz = 1.0; user.g_bdry = &g_zero; bctx.lambda = 1.0; bctx.exact = PETSC_FALSE; bctx.residualcount = 0; bctx.ngscount = 0; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"lb_","Liouville-Bratu equation solver options",""); CHKERRQ(ierr); ierr = PetscOptionsReal("-lambda","coefficient of e^u (reaction) term", "bratu2D.c",bctx.lambda,&(bctx.lambda),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-exact","use case of Liouville exact solution", "bratu2D.c",bctx.exact,&(bctx.exact),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-showcounts","at finish, print numbers of calls to call-back functions", "bratu2D.c",showcounts,&showcounts,NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); if (bctx.exact) { if (bctx.lambda != 1.0) { SETERRQ(PETSC_COMM_SELF,1,"Liouville exact solution only implemented for lambda = 1.0\n"); } user.g_bdry = &g_liouville; } user.addctx = &bctx; ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX, // contrast with fish2 3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,0.0,1.0); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetDM(snes,da); CHKERRQ(ierr); ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr); ierr = SNESSetNGS(snes,NonlinearGS,&user); CHKERRQ(ierr); // this is the Jacobian of the Poisson equation, thus ONLY APPROXIMATE // ... consider using -snes_fd_color or -snes_mf_operator ierr = DMDASNESSetJacobianLocal(da, (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = DMGetGlobalVector(da,&u); CHKERRQ(ierr); ierr = VecSet(u,0.0); CHKERRQ(ierr); // initialize to zero ierr = SNESSolve(snes,NULL,u); CHKERRQ(ierr); ierr = DMRestoreGlobalVector(da,&u);CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); if (showcounts) { ierr = PetscGetFlops(&flops); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"flops = %.3e, residual calls = %d, NGS calls = %d\n", flops,bctx.residualcount,bctx.ngscount); CHKERRQ(ierr); } ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr); if (bctx.exact) { ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); // SNES owns u; we do not destroy it ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr); ierr = FormUExact(&info,uexact,&user); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecDestroy(&uexact); CHKERRQ(ierr); // no longer needed ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "done on %d x %d grid: error |u-uexact|_inf = %.3e\n", info.mx,info.my,errinf); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD,"done on %d x %d grid ...\n",info.mx,info.my); CHKERRQ(ierr); } ierr = SNESDestroy(&snes); CHKERRQ(ierr); return PetscFinalize(); } PetscErrorCode FormUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) { PetscErrorCode ierr; BratuCtx *bctx = (BratuCtx*)(user->addctx); PetscInt i, j; PetscReal hx, hy, x, y, **au; if (user->g_bdry != &g_liouville) { SETERRQ(PETSC_COMM_SELF,1,"exact solution only implemented for g_liouville() boundary conditions\n"); } if (bctx->lambda != 1.0) { SETERRQ(PETSC_COMM_SELF,2,"Liouville exact solution only implemented for lambda = 1.0\n"); } hx = 1.0 / (PetscReal)(info->mx - 1); hy = 1.0 / (PetscReal)(info->my - 1); ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr); for (j=info->ys; j<info->ys+info->ym; j++) { y = j * hy; for (i=info->xs; i<info->xs+info->xm; i++) { x = i * hx; au[j][i] = user->g_bdry(x,y,0.0,bctx); } } ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr); return 0; } // compute F(u), the residual of the discretized PDE on the given grid PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal **au, PetscReal **FF, PoissonCtx *user) { PetscErrorCode ierr; BratuCtx *bctx = (BratuCtx*)(user->addctx); PetscInt i, j; PetscReal hx, hy, darea, hxhy, hyhx, x, y; hx = 1.0 / (PetscReal)(info->mx - 1); hy = 1.0 / (PetscReal)(info->my - 1); darea = hx * hy; hxhy = hx / hy; hyhx = hy / hx; for (j = info->ys; j < info->ys + info->ym; j++) { y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { if (j==0 || i==0 || i==info->mx-1 || j==info->my-1) { x = i * hx; FF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,bctx); } else { FF[j][i] = hyhx * (2.0 * au[j][i] - au[j][i-1] - au[j][i+1]) + hxhy * (2.0 * au[j][i] - au[j-1][i] - au[j+1][i]) - darea * bctx->lambda * PetscExpScalar(au[j][i]); } } } ierr = PetscLogFlops(12.0 * info->xm * info->ym); CHKERRQ(ierr); (bctx->residualcount)++; return 0; } // do nonlinear Gauss-Seidel (processor-block) sweeps on // F(u) = b PetscErrorCode NonlinearGS(SNES snes, Vec u, Vec b, void *ctx) { PetscErrorCode ierr; PetscInt i, j, k, maxits, totalits=0, sweeps, l; PetscReal atol, rtol, stol, hx, hy, darea, hxhy, hyhx, x, y, **au, **ab, bij, uu, phi0, phi, dphidu, s; DM da; DMDALocalInfo info; PoissonCtx *user = (PoissonCtx*)(ctx); BratuCtx *bctx = (BratuCtx*)(user->addctx); Vec uloc; ierr = SNESNGSGetSweeps(snes,&sweeps);CHKERRQ(ierr); ierr = SNESNGSGetTolerances(snes,&atol,&rtol,&stol,&maxits);CHKERRQ(ierr); ierr = SNESGetDM(snes,&da);CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); hx = 1.0 / (PetscReal)(info.mx - 1); hy = 1.0 / (PetscReal)(info.my - 1); darea = hx * hy; hxhy = hx / hy; hyhx = hy / hx; ierr = DMGetLocalVector(da,&uloc);CHKERRQ(ierr); for (l=0; l<sweeps; l++) { ierr = DMGlobalToLocalBegin(da,u,INSERT_VALUES,uloc);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da,u,INSERT_VALUES,uloc);CHKERRQ(ierr); ierr = DMDAVecGetArray(da,uloc,&au);CHKERRQ(ierr); if (b) { ierr = DMDAVecGetArrayRead(da,b,&ab); CHKERRQ(ierr); } for (j = info.ys; j < info.ys + info.ym; j++) { y = j * hy; for (i = info.xs; i < info.xs + info.xm; i++) { if (j==0 || i==0 || i==info.mx-1 || j==info.my-1) { x = i * hx; au[j][i] = user->g_bdry(x,y,0.0,bctx); } else { if (b) bij = ab[j][i]; else bij = 0.0; // do pointwise Newton iterations on scalar function // phi(u) = hyhx * (2 u - au[j][i-1] - au[j][i+1]) // + hxhy * (2 u - au[j-1][i] - au[j+1][i]) // - darea * lambda * e^u - bij uu = au[j][i]; phi0 = 0.0; for (k = 0; k < maxits; k++) { phi = hyhx * (2.0 * uu - au[j][i-1] - au[j][i+1]) + hxhy * (2.0 * uu - au[j-1][i] - au[j+1][i]) - darea * bctx->lambda * PetscExpScalar(uu) - bij; if (k == 0) phi0 = phi; dphidu = 2.0 * (hyhx + hxhy) - darea * bctx->lambda * PetscExpScalar(uu); s = - phi / dphidu; // Newton step uu += s; totalits++; if ( atol > PetscAbsReal(phi) || rtol*PetscAbsReal(phi0) > PetscAbsReal(phi) || stol*PetscAbsReal(uu) > PetscAbsReal(s) ) { break; } } au[j][i] = uu; } } } ierr = DMDAVecRestoreArray(da,uloc,&au);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da,uloc,INSERT_VALUES,u);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da,uloc,INSERT_VALUES,u);CHKERRQ(ierr); } ierr = DMRestoreLocalVector(da,&uloc);CHKERRQ(ierr); if (b) { ierr = DMDAVecRestoreArrayRead(da,b,&ab);CHKERRQ(ierr); } ierr = PetscLogFlops(21.0 * totalits); CHKERRQ(ierr); (bctx->ngscount)++; return 0; }
{ "alphanum_fraction": 0.5785953177, "avg_line_length": 43.6041666667, "ext": "c", "hexsha": "dc5fa4c51b276bfab4a86622781fb200f184abc1", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch7/solns/bratu2D.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch7/solns/bratu2D.c", "max_line_length": 237, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch7/solns/bratu2D.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 3904, "size": 12558 }
#include <petsc.h> #include <petscmath.h> #include "compressibleFlow.h" #include "mesh.h" #include "petscdmplex.h" #include "petscts.h" typedef struct { PetscInt dim; PetscReal k; PetscReal gamma; PetscReal Rgas; PetscReal L; } Constants; typedef struct { Constants constants; FlowData flowData; } ProblemSetup; static PetscReal ComputeTExact( PetscReal time, const PetscReal xyz[], Constants *constants, PetscReal rho){ PetscReal cv = constants->gamma*constants->Rgas/(constants->gamma - 1) - constants->Rgas; PetscReal alpha = constants->k/(rho*cv); PetscReal Tinitial = 100.0; PetscReal T = 300.0; for(PetscReal n =1; n < 2000; n ++){ PetscReal Bn = -Tinitial*2.0*(-1.0 + PetscPowReal(-1.0, n))/(n*PETSC_PI); T += Bn*PetscSinReal(n * PETSC_PI*xyz[0]/constants->L)*PetscExpReal(-n*n*PETSC_PI*PETSC_PI*alpha*time/(PetscSqr(constants->L))); } return T; } static PetscErrorCode InitialConditions(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *node, void *ctx) { PetscFunctionBeginUser; Constants *constants = (Constants *)ctx; PetscReal T = ComputeTExact(time, xyz, constants, 1.0); PetscReal u = 0.0; PetscReal v = xyz[0]; PetscReal rho = 1.0; PetscReal p= rho*constants->Rgas*T; PetscReal e = p/((constants->gamma - 1.0)*rho); PetscReal eT = e + 0.5*(u*u + v*v); node[RHO] = rho; node[RHOE] = rho*eT; node[RHOU + 0] = rho*u; node[RHOU + 1] = rho*v; PetscFunctionReturn(0); } static PetscReal computeTemperature(PetscInt dim, const PetscScalar* conservedValues, PetscReal gamma, PetscReal Rgas){ PetscReal density = conservedValues[RHO]; PetscReal totalEnergy = conservedValues[RHOE]/density; // Get the velocity in this direction PetscReal speedSquare = 0.0; for (PetscInt d =0; d < dim; d++){ speedSquare += PetscSqr(conservedValues[RHOU + d]/density); } // assumed eos PetscReal internalEnergy = (totalEnergy) - 0.5 * speedSquare; PetscReal p = (gamma - 1.0)*density*internalEnergy; PetscReal T = p/(Rgas*density); return T; } static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) { PetscFunctionBeginUser; PetscErrorCode ierr; FlowData flowData = (FlowData)ctx; // Get the DM DM dm; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = FlowViewFromOptions(flowData, "-sol_view"); CHKERRQ(ierr); ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), "TS at %f\n", time); CHKERRQ(ierr); // Compute the error void *exactCtxs[1]; PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); PetscDS ds; ierr = DMGetDS(dm, &ds); CHKERRQ(ierr); // Get the exact solution ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]); CHKERRQ(ierr); // Create an vector to hold the exact solution Vec exactVec; ierr = VecDuplicate(u, &exactVec); CHKERRQ(ierr); ierr = DMProjectFunction(dm, time, exactFuncs, exactCtxs, INSERT_ALL_VALUES, exactVec); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)exactVec, "exact"); CHKERRQ(ierr); ierr = VecViewFromOptions(exactVec, NULL, "-sol_view"); CHKERRQ(ierr); // For each component, compute the l2 norms ierr = VecAXPY(exactVec, -1.0, u); CHKERRQ(ierr); PetscReal ferrors[4]; ierr = VecSetBlockSize(exactVec, 4); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Timestep: %04d time = %-8.4g \t\n", (int)step, (double)time); CHKERRQ(ierr); ierr = VecStrideNormAll(exactVec, NORM_2, ferrors); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double)(ferrors[0]), (double)(ferrors[1]), (double)(ferrors[2]), (double)(ferrors[3])); CHKERRQ(ierr); // And the infinity error ierr = VecStrideNormAll(exactVec, NORM_INFINITY, ferrors); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double)ferrors[0], (double)ferrors[1], (double)ferrors[2], (double)ferrors[3]); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)exactVec, "error"); CHKERRQ(ierr); ierr = VecViewFromOptions(exactVec, NULL, "-sol_view"); CHKERRQ(ierr); ierr = VecDestroy(&exactVec); CHKERRQ(ierr); PetscFunctionReturn(0); } // //static PetscErrorCode FillBoundary(PetscInt dim, PetscInt dof, const PetscFVFaceGeom *faceGeom, const PetscFVCellGeom *cellGeom, const PetscFVCellGeom *cellGeomG, const PetscScalar *a_xI, const PetscScalar *a_xGradI, const PetscScalar *a_xG, PetscScalar *a_xGradG, void *ctx){ // // for(PetscInt pd = 0; pd < dof; ++pd) { // PetscReal dPhidS = a_xG[pd] - a_xI[pd]; // // // over each direction // for (PetscInt dir = 0; dir < dim; dir++) { // PetscReal dx = (cellGeomG->centroid[dir] - faceGeom->centroid[dir]); // // // If there is a contribution in this direction // if (PetscAbs(dx) > 1E-8) { // a_xGradG[pd*dim + dir] = dPhidS / (dx); // } else { // a_xGradG[pd*dim + dir] = 0.0; // } // } // } // return 0; //} // ///** // * this function updates the boundaries with the gradient computed from the boundary cell value // * @param dm // * @param auxFvm // * @param gradLocalVec // * @return // */ //static PetscErrorCode DMPlexFillGradientInBoundaryFVM(DM dm, PetscFV auxFvm, Vec localXVec, Vec gradLocalVec){ // PetscFunctionBeginUser; // PetscErrorCode ierr; // // // Get the dmGrad // DM dmGrad; // ierr = VecGetDM(gradLocalVec, &dmGrad);CHKERRQ(ierr); // // // get the problem // PetscDS prob; // PetscInt nFields; // ierr = DMGetDS(dm, &prob);CHKERRQ(ierr); // ierr = PetscDSGetNumFields(prob, &nFields);CHKERRQ(ierr); // if (nFields > 1){ // SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Cannot fill DMPlexFillGradientInBoundaryFVM with more than a single field." ); // } // PetscInt field; // ierr = PetscDSGetFieldIndex(prob, (PetscObject) auxFvm, &field);CHKERRQ(ierr); // PetscInt dof; // ierr = PetscDSGetFieldSize(prob, field, &dof);CHKERRQ(ierr); // // // Obtaining local cell ownership // PetscInt cellStart, cellEnd, cEndInterior; // ierr = DMPlexGetHeightStratum(dm, 0, &cellStart, &cellEnd);CHKERRQ(ierr); // ierr = DMPlexGetGhostCellStratum(dm, &cEndInterior, NULL);CHKERRQ(ierr); // cEndInterior = cEndInterior < 0 ? cellEnd: cEndInterior; // // // Get the fvm face and cell geometry // Vec cellGeomVec = NULL;/* vector of structs related to cell geometry*/ // Vec faceGeomVec = NULL;/* vector of structs related to face geometry*/ // ierr = DMPlexGetGeometryFVM(dm, &faceGeomVec, &cellGeomVec, NULL);CHKERRQ(ierr); // // // get the dm for each geom type // DM dmFaceGeom, dmCellGeom; // ierr = VecGetDM(faceGeomVec, &dmFaceGeom);CHKERRQ(ierr); // ierr = VecGetDM(cellGeomVec, &dmCellGeom);CHKERRQ(ierr); // // // extract the gradLocalVec // PetscScalar * gradLocalArray; // ierr = VecGetArray(gradLocalVec, &gradLocalArray);CHKERRQ(ierr); // // const PetscScalar* localArray; // ierr = VecGetArrayRead(localXVec, &localArray);CHKERRQ(ierr); // // // get the dim // PetscInt dim; // ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr); // // // extract the arrays for the face and cell geom, along with their dm // const PetscScalar *cellGeomArray; // ierr = VecGetArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr); // // const PetscScalar *faceGeomArray; // ierr = VecGetArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr); // // // March over each face // for (PetscInt cell = cellStart; cell < cEndInterior; ++cell) { // // Get the face information // PetscInt numFaces; // const PetscInt *faces; // ierr = DMPlexGetConeSize(dm, cell, &numFaces);CHKERRQ(ierr); // ierr = DMPlexGetCone(dm, cell, &faces);CHKERRQ(ierr); // // //March over each face // for(PetscInt f =0 ; f < numFaces; f++){ // PetscBool boundary; // ierr = DMIsBoundaryPoint(dm, faces[f], &boundary);CHKERRQ(ierr); // // // if this is on the boundary // if(boundary){ // // get the boundary cell index // const PetscInt *fcells; // ierr = DMPlexGetSupport(dm, faces[f], &fcells);CHKERRQ(ierr); // PetscInt side = (cell != fcells[0]); /* c is on left=0 or right=1 of face */ // PetscInt ncell = fcells[!side]; /* the neighbor */ // // // get the face geom // const PetscFVFaceGeom *faceGeom; // ierr = DMPlexPointLocalRead(dmFaceGeom, faces[f], faceGeomArray, &faceGeom);CHKERRQ(ierr); // // // get the cell centroid information // const PetscFVCellGeom *cellGeom; // const PetscFVCellGeom *cellGeomGhost; // ierr = DMPlexPointLocalRead(dmCellGeom, cell, cellGeomArray, &cellGeom);CHKERRQ(ierr); // ierr = DMPlexPointLocalRead(dmCellGeom, ncell, cellGeomArray, &cellGeomGhost);CHKERRQ(ierr); // // // Read the local point // PetscScalar* boundaryGradCellValues; // ierr = DMPlexPointLocalRef(dmGrad, ncell, gradLocalArray, &boundaryGradCellValues);CHKERRQ(ierr); // // const PetscScalar* cellGradValues; // ierr = DMPlexPointLocalRead(dmGrad, cell, gradLocalArray, &cellGradValues);CHKERRQ(ierr); // // const PetscScalar* boundaryCellValues; // ierr = DMPlexPointLocalRead(dm, ncell, localArray, &boundaryCellValues);CHKERRQ(ierr); // const PetscScalar* cellValues; // ierr = DMPlexPointLocalRead(dm, cell, localArray, &cellValues);CHKERRQ(ierr); // // // compute the gradient for the boundary node and pass in // //const PetscReal *cellGeom, const PetscReal *cellGeomG, const PetscScalar *a_xI, const PetscScalar *a_xGradI, PetscScalar *a_xG, PetscScalar *a_xGradG, void *ctx // ierr = FillBoundary(dim, dof, faceGeom, cellGeom, cellGeomGhost, cellValues, cellGradValues, boundaryCellValues, boundaryGradCellValues, NULL);CHKERRQ(ierr); // } // } // } // // ierr = VecRestoreArrayRead(localXVec, &localArray);CHKERRQ(ierr); // ierr = VecRestoreArray(gradLocalVec, &gradLocalArray);CHKERRQ(ierr); // ierr = VecRestoreArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr); // ierr = VecRestoreArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr); // // PetscFunctionReturn(0); //} // //static PetscErrorCode DiffusionSource(DM dm, PetscReal time, Vec locXVec, Vec globFVec, void *ctx){ // // Call the flux calculation // PetscErrorCode ierr; // // ProblemSetup *setup = (ProblemSetup *)ctx; // // // call the base rhs function eval // ierr = DMPlexTSComputeRHSFunctionFVM(dm, time, locXVec, globFVec, setup->flowData);CHKERRQ(ierr); // // // update the aux fields // ierr = UpdateAuxFields(NULL, locXVec, setup->flowData);CHKERRQ(ierr); // // Constants constants = setup->constants; // // // get the fvm field assuming that it is the first // PetscFV auxFvm; // ierr = DMGetField(setup->flowData->auxDm,0, NULL, (PetscObject*)&auxFvm);CHKERRQ(ierr); // // PetscInt dim; // ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr); // // // Get the locXArray // const PetscScalar *locXArray; // ierr = VecGetArrayRead(locXVec, &locXArray);CHKERRQ(ierr); // // // Get the fvm face and cell geometry // Vec cellGeomVec = NULL;/* vector of structs related to cell geometry*/ // Vec faceGeomVec = NULL;/* vector of structs related to face geometry*/ // // // extract the fvm data // ierr = DMPlexGetGeometryFVM(setup->flowData->dm, &faceGeomVec, &cellGeomVec, NULL);CHKERRQ(ierr); // // // Get the needed auxDm // DM auxFieldGradDM = NULL; /* dm holding the grad information */ // ierr = DMPlexGetDataFVM(setup->flowData->auxDm, auxFvm, NULL, NULL, &auxFieldGradDM);CHKERRQ(ierr); // if(!auxFieldGradDM){ // SETERRQ(PetscObjectComm((PetscObject)setup->flowData->auxDm), PETSC_ERR_ARG_WRONGSTATE, "The FVM method for aux variables must support computing gradients."); // } // // // get the dm for each geom type // DM dmFaceGeom, dmCellGeom; // ierr = VecGetDM(faceGeomVec, &dmFaceGeom);CHKERRQ(ierr); // ierr = VecGetDM(cellGeomVec, &dmCellGeom);CHKERRQ(ierr); // // // extract the arrays for the face and cell geom, along with their dm // const PetscScalar *faceGeomArray, *cellGeomArray; // ierr = VecGetArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr); // ierr = VecGetArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr); // // // Obtaining local cell and face ownership // PetscInt faceStart, faceEnd; // PetscInt cellStart, cellEnd; // ierr = DMPlexGetHeightStratum(dm, 1, &faceStart, &faceEnd);CHKERRQ(ierr); // ierr = DMPlexGetHeightStratum(dm, 0, &cellStart, &cellEnd);CHKERRQ(ierr); // // // get the ghost label // DMLabel ghostLabel; // ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr); // // // extract the localFArray from the locFVec // PetscScalar *fa; // Vec locFVec; // ierr = DMGetLocalVector(dm, &locFVec);CHKERRQ(ierr); // ierr = VecZeroEntries(locFVec);CHKERRQ(ierr); // ierr = VecGetArray(locFVec, &fa);CHKERRQ(ierr); // // // create a global and local grad vector for the auxField // Vec gradGlobalVec, gradLocalVec; // ierr = DMCreateGlobalVector(auxFieldGradDM, &gradGlobalVec);CHKERRQ(ierr); // ierr = VecSet(gradGlobalVec, NAN);CHKERRQ(ierr); // // // compute the global grad values // ierr = DMPlexReconstructGradientsFVM(setup->flowData->auxDm, setup->flowData->auxField, gradGlobalVec);CHKERRQ(ierr); // // // Map to a local grad vector // ierr = DMCreateLocalVector(auxFieldGradDM, &gradLocalVec);CHKERRQ(ierr); // ierr = DMGlobalToLocalBegin(auxFieldGradDM, gradGlobalVec, INSERT_VALUES, gradLocalVec);CHKERRQ(ierr); // ierr = DMGlobalToLocalEnd(auxFieldGradDM, gradGlobalVec, INSERT_VALUES, gradLocalVec);CHKERRQ(ierr); // // // fill the boundary conditions // ierr = DMPlexFillGradientInBoundaryFVM(setup->flowData->auxDm, auxFvm, setup->flowData->auxField, gradLocalVec);CHKERRQ(ierr); // // // access the local vector // const PetscScalar *localGradArray; // ierr = VecGetArrayRead(gradLocalVec,&localGradArray);CHKERRQ(ierr); // // // march over each face // for (PetscInt face = faceStart; face < faceEnd; ++face) { // PetscFVFaceGeom *fg; // PetscFVCellGeom *cgL, *cgR; // const PetscScalar *gradL; // const PetscScalar *gradR; // // // make sure that this is a valid face to check // PetscInt ghost, nsupp, nchild; // ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr); // ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr); // ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr); // if (ghost >= 0 || nsupp > 2 || nchild > 0){ // continue;// skip this face // } // // // get the face geometry // ierr = DMPlexPointLocalRead(dmFaceGeom, face, faceGeomArray, &fg);CHKERRQ(ierr); // // // Get the left and right cells for this face // const PetscInt *faceCells; // ierr = DMPlexGetSupport(dm, face, &faceCells);CHKERRQ(ierr); // // // get the cell geom for the left and right faces // ierr = DMPlexPointLocalRead(dmCellGeom, faceCells[0], cellGeomArray, &cgL);CHKERRQ(ierr); // ierr = DMPlexPointLocalRead(dmCellGeom, faceCells[1], cellGeomArray, &cgR);CHKERRQ(ierr); // // // extract the cell grad // ierr = DMPlexPointLocalRead(auxFieldGradDM, faceCells[0], localGradArray, &gradL);CHKERRQ(ierr); // ierr = DMPlexPointLocalRead(auxFieldGradDM, faceCells[1], localGradArray, &gradR);CHKERRQ(ierr); // // PetscInt f = 0; // // // extract the field values // PetscScalar *xL, *xR, // ierr = DMPlexPointLocalFieldRead(dm, faceCells[0], f, locXArray, &xL);CHKERRQ(ierr); // ierr = DMPlexPointLocalFieldRead(dm, faceCells[1], f, locXArray, &xR);CHKERRQ(ierr); // // // Compute the normal grad // PetscReal normalGrad = 0.0; // PetscInt dof = 0; // for (PetscInt d = 0; d < dim; ++d){ // normalGrad += fg->normal[d]*0.5*(gradL[dof*dim + d] + gradR[dof*dim + d]); // } // // // compute the normal heatFlux // PetscReal normalHeatFlux = -constants.k *normalGrad; // // // Add to the source terms of f // PetscScalar *fL = NULL, *fR = NULL; // ierr = DMLabelGetValue(ghostLabel,faceCells[0],&ghost);CHKERRQ(ierr); // if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, faceCells[0], f, fa, &fL);CHKERRQ(ierr);} // ierr = DMLabelGetValue(ghostLabel,faceCells[1],&ghost);CHKERRQ(ierr); // if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, faceCells[1], f, fa, &fR);CHKERRQ(ierr);} // // if(fL){ // fL[RHOE] -= normalHeatFlux/cgL->volume; // } // if(fR){ // fR[RHOE] += normalHeatFlux/cgR->volume; // } // } // // // Add the new locFVec to the globFVec // ierr = VecRestoreArray(locFVec, &fa);CHKERRQ(ierr); // ierr = DMLocalToGlobalBegin(dm, locFVec, INSERT_VALUES, globFVec);CHKERRQ(ierr); // ierr = DMLocalToGlobalEnd(dm, locFVec, INSERT_VALUES, globFVec);CHKERRQ(ierr); // ierr = DMRestoreLocalVector(dm, &locFVec);CHKERRQ(ierr); // // // restore the arrays // ierr = VecRestoreArrayRead(gradLocalVec, &localGradArray);CHKERRQ(ierr); // ierr = VecRestoreArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr); // ierr = VecRestoreArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr); // ierr = VecRestoreArrayRead(locXVec, &locXArray);CHKERRQ(ierr); // // // destroy grad vectors // ierr = VecDestroy(&gradGlobalVec);CHKERRQ(ierr); // ierr = VecDestroy(&gradLocalVec);CHKERRQ(ierr); // //// VecView(globFVec, PETSC_VIEWER_STDOUT_WORLD); // // PetscFunctionReturn(0); //} static PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { PetscFunctionBeginUser; Constants *constants = (Constants *)ctx; // compute the centroid location of the real cell // Offset the calc assuming the cells are square PetscReal x[3]; for(PetscInt i =0; i < constants->dim; i++){ // x[i] = c[i] - n[i]*0.5;//TODO:zero boundary x[i] = c[i] + n[i]*0.5;//TODO:uniform grad } // compute the temperature PetscReal Tinside = ComputeTExact(time, x, constants, 1.0); PetscReal boundaryValue = 300.0; PetscReal T = boundaryValue;//boundaryValue - (Tinside - boundaryValue);//TODO: fix uniform grad // PetscReal T = c[0] < constants->L/2.0 ? 300 : 400; PetscReal u = 0.0; PetscReal v = 0.0; PetscReal rho = 1.0; PetscReal p= rho*constants->Rgas*T; PetscReal e = p/((constants->gamma - 1.0)*rho); PetscReal eT = e + 0.5*(u*u + v*v); a_xG[RHO] = rho; a_xG[RHOE] = rho*eT; a_xG[RHOU + 0] = rho*u; a_xG[RHOU + 1] = rho*v; PetscFunctionReturn(0); } static PetscErrorCode PhysicsBoundary_Mirror(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { PetscFunctionBeginUser; Constants *constants = (Constants *)ctx; // Offset the calc assuming the cells are square for(PetscInt f =0; f < RHOU + constants->dim; f++){ a_xG[f] = a_xI[f]; } PetscFunctionReturn(0); } int main(int argc, char **argv) { // Setup the problem Constants constants; // sub sonic constants.dim = 2; constants.L = 0.1; constants.gamma = 1.4; constants.k = 0.3; constants.Rgas = 1.0; PetscErrorCode ierr; // create the mesh // setup the ts DM dm; /* problem definition */ TS ts; /* timestepper */ // initialize petsc and mpi PetscInitialize(&argc, &argv, NULL, "HELP"); // Create a ts ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr); ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr); ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr); // Create a mesh // hard code the problem setup PetscReal start[] = {0.0, 0.0}; PetscReal end[] = {constants.L, constants.L}; PetscReal nxHeight = 3; PetscInt nx[] = {nxHeight, nxHeight}; ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr); // Setup the flow data FlowData flowData; /* store some of the flow data*/ ierr = FlowCreate(&flowData);CHKERRQ(ierr); // Combine the flow data ProblemSetup problemSetup; problemSetup.flowData = flowData; problemSetup.constants = constants; //Setup CompressibleFlow_SetupDiscretization(flowData, &dm); // Add in the flow parameters PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS]; params[CFL] = 0.5; params[GAMMA] = constants.gamma; params[RGAS] = constants.Rgas; params[K] = constants.k; // set up the finite volume fluxes CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params); // Add in any boundary conditions PetscDS prob; ierr = DMGetDS(flowData->dm, &prob); CHKERRABORT(PETSC_COMM_WORLD, ierr); const PetscInt idsLeft[]= {2, 4}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall left", "Face Sets", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 2, idsLeft, &constants);CHKERRQ(ierr); const PetscInt idsTop[]= {1, 3}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "top/bottom", "Face Sets", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Mirror, NULL, 2, idsTop, &constants);CHKERRQ(ierr); // ierr = FlowRegisterAuxField(flowData, "Temperature", "T", 1, FV);CHKERRQ(ierr); // Complete the problem setup ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Override the flow calc for now // ierr = DMTSSetRHSFunctionLocal(flowData->dm, DiffusionSource, &problemSetup);CHKERRQ(ierr); // Name the flow field ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the TS ierr = TSSetFromOptions(ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); ierr = TSMonitorSet(ts, MonitorError, problemSetup.flowData, NULL);CHKERRQ(ierr); CHKERRABORT(PETSC_COMM_WORLD, ierr); // set the initial conditions PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {InitialConditions}; void* ctxs[1] ={&constants}; ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr); // for the mms, add the exact solution ierr = PetscDSSetExactSolution(prob, 0, InitialConditions, &constants);CHKERRQ(ierr); // Output the mesh ierr = DMViewFromOptions(flowData->dm, NULL, "-dm_view");CHKERRQ(ierr); // Compute the end time so it goes around once // compute dt PetscReal cv = constants.gamma*constants.Rgas/(constants.gamma - 1) - constants.Rgas; PetscReal dxMin = constants.L/(10 * PetscPowRealInt(2, 2)); PetscReal alpha = PetscAbs(constants.k/ (cv * 1.0)); double dt_conduc = 0.00000625;//.3*PetscSqr(dxMin) / alpha; PetscPrintf(PETSC_COMM_WORLD, "dt_conduc: %f\n", dt_conduc); TSSetTimeStep(ts, dt_conduc); // TSSetMaxTime(ts, 0.001); TSSetMaxSteps(ts, 600); PetscDSView(prob, PETSC_VIEWER_STDOUT_WORLD); DMView(flowData->auxDm, PETSC_VIEWER_STDOUT_WORLD); ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr); FlowDestroy(&flowData); TSDestroy(&ts); return PetscFinalize(); }
{ "alphanum_fraction": 0.6495510204, "avg_line_length": 39.1373801917, "ext": "c", "hexsha": "622891421214a8051c784f3d9435948dd66e152e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_path": "eulerWithDiffusion.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_path": "eulerWithDiffusion.c", "max_line_length": 279, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_path": "eulerWithDiffusion.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7076, "size": 24500 }
#ifndef __MTPOWERSPECTRUM_ENGINE_H__ #define __MTPOWERSPECTRUM_ENGINE_H__ #include <memory> #include <vector> #include <gsl/gsl_errno.h> #include <gsl/gsl_fft_complex.h> #include "mspass/seismic/TimeSeries.h" #include "mspass/utility/dmatrix.h" #include "mspass/seismic/PowerSpectrum.h" namespace mspass::algorithms::deconvolution{ /*! \brief Multittaper power spectral estimator. The multitaper method uses averages of spectra windowed by Slepian functions. This class can be used to compute power spectra. For efficiency the design has constructors that build the Slepian functions and cache them in a private area. Use of the pply method that returns vector of power spectral estimates. Get methods can be called to get frequency properties of the data returned. This could have been done with a class, but that was judged better left to a python wrapper using this class. */ class MTPowerSpectrumEngine { public: MTPowerSpectrumEngine(); MTPowerSpectrumEngine(const int winsize, const double tbp, const int ntapers); MTPowerSpectrumEngine(const MTPowerSpectrumEngine& parent); ~MTPowerSpectrumEngine(); //~MTPowerSpectrumEngine(); MTPowerSpectrumEngine& operator=(const MTPowerSpectrumEngine& parent); /*! \process a TimeSeries. This is one of two methods for applying the multiaper algorithm to data. This one uses dt and data length to set the Rayleigh bin size (df). If the input data vector length is not the same as the operator length an elog complaint is posted to parent. Short data are processed but should be considered suspect unless the sizes differ by only a tiny fraction (e.g. and off by one error from rounding). Long data will be truncated on the right (i.e. sample 0 will be the start of the window used). \param parent is the data to process \return vector containing estimated power spwecrum */ mspass::seismic::PowerSpectrum apply(const mspass::seismic::TimeSeries& d); /*! \brief Low level processing of vector of data. This is lower level function that processes a raw vector of data. Since it does not know the sample interval it cannot compute the rayleigh bin size so if callers need that feature they must do that (simple) calculation themselves. Unlike the TimeSeries method this one will throw an exception if the input data size does not match the operator size. \param d is the vector of data to process. d.size() must this->taperlen() value. \return vector containing estimated power spectrum (usual convention with 0 containing 0 frequency value) \exception throw a MsPASSError if the size of d does not match operator length */ std::vector<double> apply(const std::vector<double>& d); double df() const {return deltaf;}; std::vector<double> frequencies(); /*! Retrieve the taper length.*/ int taper_length() const { return taperlen; }; /*! Retrieve time-bandwidth product.*/ double time_bandwidth_product() const { return tbp; }; /*! Return number of tapers used by this engine. */ int number_tapers() const { return ntapers; }; /*! \brief PUtter equivalent of df. The computation of the Rayleigh bin size (dt) is actually quote trivial but this convenience functon allows users of the vector<double> method to handle the comutation easily. It uses the internal oeprator size, however, to compute the df size it returns because the operator is dogmatic about using that size. Users wishing to call the frequency method and the apply method on raw vector data need to call this function before calling frequency. \param dt is the data sample interval (time domain) \return computed df */ double set_df(double dt) { deltaf=1.0/(dt*static_cast<double>(taperlen)); return deltaf; }; private: int taperlen; int ntapers; double tbp; mspass::utility::dmatrix tapers; /* Frequency bin interval of last data processed.*/ double deltaf; gsl_fft_complex_wavetable *wavetable; gsl_fft_complex_workspace *workspace; }; } //namespace ed #endif
{ "alphanum_fraction": 0.7548148148, "avg_line_length": 37.5, "ext": "h", "hexsha": "453fe6157bee7e0745b5b203a5d6e355279064f2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-10-01T05:59:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-08-03T18:40:04.000Z", "max_forks_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Yangzhengtang/mspass", "max_forks_repo_path": "cxx/include/mspass/algorithms/deconvolution/MTPowerSpectrumEngine.h", "max_issues_count": 151, "max_issues_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7", "max_issues_repo_issues_event_max_datetime": "2021-06-22T03:41:09.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-27T23:19:55.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Yangzhengtang/mspass", "max_issues_repo_path": "cxx/include/mspass/algorithms/deconvolution/MTPowerSpectrumEngine.h", "max_line_length": 83, "max_stars_count": 11, "max_stars_repo_head_hexsha": "7ac6db4afa7577f0e67981490fd89d50e35bf4c7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Yangzhengtang/mspass", "max_stars_repo_path": "cxx/include/mspass/algorithms/deconvolution/MTPowerSpectrumEngine.h", "max_stars_repo_stars_event_max_datetime": "2021-05-19T14:59:03.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-28T16:02:44.000Z", "num_tokens": 1003, "size": 4050 }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by agibsonccc on 2/6/16. // #ifndef NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H #define NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H #include <cblas.h> /* enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 }; enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113, AtlasConj=114}; enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; */ #ifdef __cplusplus extern "C" { #endif /** * Converts a character * to its proper enum * for row (c) or column (f) ordering * default is row major */ CBLAS_ORDER convertOrder(int from); /** * Converts a character to its proper enum * t -> transpose * n -> no transpose * c -> conj */ CBLAS_TRANSPOSE convertTranspose(int from); /** * Upper or lower * U/u -> upper * L/l -> lower * * Default is upper */ CBLAS_UPLO convertUplo(int from); /** * For diagonals: * u/U -> unit * n/N -> non unit * * Default: unit */ CBLAS_DIAG convertDiag(int from); /** * Side of a matrix, left or right * l /L -> left * r/R -> right * default: left */ CBLAS_SIDE convertSide(int from); #ifdef __cplusplus } #endif #endif // NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H
{ "alphanum_fraction": 0.6688931298, "avg_line_length": 25.2530120482, "ext": "h", "hexsha": "4e20d282281a725dc513d53e88061fba1053137a", "lang": "C", "max_forks_count": 572, "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:46:46.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T22:13:57.000Z", "max_forks_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "steljord2/deeplearning4j", "max_forks_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_issues_count": 1685, "max_issues_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:45:15.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-12T17:41:33.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "steljord2/deeplearning4j", "max_issues_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_line_length": 81, "max_stars_count": 2206, "max_stars_repo_head_hexsha": "4653c97a713cc59e41d4313ddbafc5ff527f8714", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "steljord2/deeplearning4j", "max_stars_repo_path": "libnd4j/include/cblas_enum_conversion.h", "max_stars_repo_stars_event_max_datetime": "2022-03-29T08:14:27.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-12T18:57:14.000Z", "num_tokens": 534, "size": 2096 }
#include "stdlib.h" #include "stdio.h" #include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" #include <gsl/gsl_statistics.h> int main(int argc, const char * argv[]) { unsigned long int hexdouble; int a; a = atoi(argv[1]); int argv_cnt = 2; double b[5]; for(int i = 0; i < a; i++) { sscanf(argv[argv_cnt++], "%lX", &hexdouble); b[i] = *(double*)(&hexdouble); } unsigned long c = 1; double d[5]; for(int i = 0; i < a; i++) { sscanf(argv[argv_cnt++], "%lX", &hexdouble); d[i] = *(double*)(&hexdouble); } unsigned long e = 1; double g; sscanf(argv[argv_cnt++], "%lX", &hexdouble); g = *(double*)(&hexdouble); double h; sscanf(argv[argv_cnt++], "%lX", &hexdouble); h = *(double*)(&hexdouble); double result = gsl_stats_wkurtosis_m_sd(b, c, d, e, a, g, h); //printf("%.15f\n", result); VALGRIND_PRINT_VALUES("result", 1, &result); return 0; }
{ "alphanum_fraction": 0.643437863, "avg_line_length": 26.90625, "ext": "c", "hexsha": "b100ffff08ce88daa68dd87a74bbc70add700ebf", "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": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "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": "floatfeather/FpGenetic", "max_issues_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 297, "size": 861 }
/* $Id$ */ /* * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <inttypes.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <cairo.h> #include <gtk/gtk.h> #include <gsl/gsl_multifit.h> #include <kplot.h> #include "extern.h" void draw(GtkWidget *w, cairo_t *cr, struct curwin *cur) { double x, y; cur->redraw = 0; /* White-out the view. */ x = gtk_widget_get_allocated_width(w); y = gtk_widget_get_allocated_height(w); cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); cairo_rectangle(cr, 0.0, 0.0, x, y); cairo_fill(cr); /* Draw our plot. */ kplot_draw(cur->views[cur->view], x, y, cr); }
{ "alphanum_fraction": 0.7207142857, "avg_line_length": 29.1666666667, "ext": "c", "hexsha": "20075b334d5bbfab9a7d489326e41f37e650418a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "draw.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_path": "draw.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "draw.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 374, "size": 1400 }
/* * SPDX-License-Identifier: BSD-3-Clause * * sph_linked_list.c : * Header containing the declarions for several * cell linked list operations, including hash * calculations, setup hash tables and neighbour finding. * * (C) Copyright 2021 José Hugo Elsas * Author: José Hugo Elsas <jhelsas@gmail.com> * */ #include <math.h> #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <stdbool.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "MZC3D64.h" #include "MZC2D64.h" #include "sph_data_types.h" #include "sph_linked_list.h" #define dbg false int safe_free_box(linkedListBox *box){ kh_destroy(0, box->hbegin); kh_destroy(1, box->hend); free(box); return 0; } int compare_int64_t(const void *p,const void *q){ int64_t *data1,*data2; data1 = (int64_t*)p; data2 = (int64_t*)q; if(data1[0] < data2[0]) // data[0] is the hash value, return -1; // data[1] is the corresponding else if(data1[0] == data2[0]) // in the unsorted array return 0; else return 1; } #define safe_check_alloc(ptr,N,dtype) { \ (ptr) = (dtype*)malloc((N)*sizeof(dtype));\ if((ptr)==NULL){ \ success=0; \ goto finishlabel; \ } \ } #define safe_check__aligned_alloc(ptr,alignment,N,dtype) { \ (ptr) = (dtype*)aligned_alloc(alignment,(N)*sizeof(dtype));\ if((ptr)==NULL){ \ success=0; \ goto finishlabel; \ } \ } #define safe_free(ptr) { \ if(ptr != NULL)\ free(ptr); \ } /* * Function SPHparticle_SoA_malloc: * Easily allocate the SPHparticle array * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particle struct reference */ int SPHparticle_SoA_malloc(int N,SPHparticle **lsph){ int success=1; //const int alignment = 32; (*lsph) = (SPHparticle*)malloc(1*sizeof(SPHparticle)); if(lsph==NULL){ success = 0; goto finishlabel; } (*lsph)->x = NULL; (*lsph)->y = NULL; (*lsph)->z = NULL; (*lsph)->ux = NULL; (*lsph)->uy = NULL; (*lsph)->uz = NULL; (*lsph)->Fx = NULL; (*lsph)->Fy = NULL; (*lsph)->Fz = NULL; (*lsph)->nu = NULL; (*lsph)->rho= NULL; (*lsph)->id = NULL; (*lsph)->hash= NULL; safe_check_alloc((*lsph)->x , N ,double); safe_check_alloc((*lsph)->y , N ,double); safe_check_alloc((*lsph)->z , N ,double); safe_check_alloc((*lsph)->ux , N ,double); safe_check_alloc((*lsph)->uy , N ,double); safe_check_alloc((*lsph)->uz , N ,double); safe_check_alloc((*lsph)->Fx , N ,double); safe_check_alloc((*lsph)->Fy , N ,double); safe_check_alloc((*lsph)->Fz , N ,double); safe_check_alloc((*lsph)->nu , N ,double); safe_check_alloc((*lsph)->rho , N ,double); safe_check_alloc((*lsph)->id , N ,int64_t); safe_check_alloc((*lsph)->hash,2*N,int64_t); // SPHparticle_SoA_malloc((*lsph)->x , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->y , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->z , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->ux , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->uy , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->uz , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->Fx , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->Fy , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->Fz , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->nu , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->rho , 32, N ,double); // SPHparticle_SoA_malloc((*lsph)->id , 32, N ,int64_t); // SPHparticle_SoA_malloc((*lsph)->hash, 32,2*N,int64_t); finishlabel: if(success) return 0; else{ if(*lsph==NULL) return 1; safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z); safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz); safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz); safe_free((*lsph)->nu); safe_free((*lsph)->rho); safe_free((*lsph)->id); safe_free((*lsph)->hash); return 1; } } /* * Function SPHparticleSOA_safe_free: * Easily free the SPHparticle array * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particle struct reference */ int SPHparticleSOA_safe_free(int N,SPHparticle **lsph){ if(*lsph==NULL) return 1; safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z); safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz); safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz); safe_free((*lsph)->nu); safe_free((*lsph)->rho); safe_free((*lsph)->id); safe_free((*lsph)->hash); free((*lsph)); return 0; } /* * Function gen_unif_rdn_pos: * Generate particles positions uniformely in a [0,1]^3 box * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particles array * seed <int> : seed for the PRNG */ int gen_unif_rdn_pos(int64_t N, int seed, SPHparticle *lsph){ const gsl_rng_type *T=NULL; gsl_rng *r=NULL; if(lsph==NULL) return 1; gsl_rng_env_setup(); // Initialize environment for PRNG generator T = gsl_rng_default; // Set generator type as default type r = gsl_rng_alloc(T); // allocate state for it gsl_rng_set(r,seed); // set seed accordingly for(int64_t i=0;i<N;i+=1){ lsph->x[i] = gsl_rng_uniform(r); // Generate a uniform value for X component between 0 and 1 lsph->y[i] = gsl_rng_uniform(r); // Generate a uniform value for Y component between 0 and 1 lsph->z[i] = gsl_rng_uniform(r); // Generate a uniform value for Z component between 0 and 1 lsph->ux[i] = 0.0; lsph->Fx[i] = 0.0; // set velocity and force components as zero lsph->uy[i] = 0.0; lsph->Fy[i] = 0.0; // as they will not be needed lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0; lsph->nu[i] = 1.0/N; // set each particle mass as to the total mass be 1 lsph->rho[i] = 0.0; // initialize density to zero lsph->id[i] = (int64_t) i; // set the particle's id lsph->hash[2*i+0] = (int64_t) 0; // initialize particle's hash value as zero lsph->hash[2*i+1] = (int64_t) i; // set particle's index position by the position in current array } gsl_rng_free(r); // release the PRNG return 0; } /* * Function gen_unif_rdn_pos_box: * Generate particles positions uniformely in a * [Xmin,Xmax]x[Ymin,Ymax]x[Zmin,Zmax] box * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particles array * seed <int> : seed for the PRNG * box <linkedListBox*> : Cell Linked List box */ int gen_unif_rdn_pos_box(int64_t N, int seed, linkedListBox *box,SPHparticle *lsph){ const gsl_rng_type *T=NULL; gsl_rng *r=NULL; if(lsph==NULL) return 1; gsl_rng_env_setup(); // Initialize environment for PRNG generator T = gsl_rng_default; // Set generator type as default type r = gsl_rng_alloc(T); // allocate state for it gsl_rng_set(r,seed); // set seed accordingly for(int64_t i=0;i<N;i+=1){ lsph->x[i] = gsl_rng_uniform(r)*(box->Xmax-box->Xmin) // Generate a uniform value for X + box->Xmin; // component between Xmin and Xmax lsph->y[i] = gsl_rng_uniform(r)*(box->Ymax-box->Ymin) // Generate a uniform value for Y + box->Ymin; // component between Ymin and Ymax lsph->z[i] = gsl_rng_uniform(r)*(box->Zmax-box->Zmin) // Generate a uniform value for Z + box->Zmin; // component between Zmin and Zmax lsph->ux[i] = 0.0; lsph->Fx[i] = 0.0; // set velocity and force components as zero lsph->uy[i] = 0.0; lsph->Fy[i] = 0.0; // as they will not be needed lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0; lsph->nu[i] = 1.0/N; // set each particle mass as to the total mass be 1 lsph->rho[i] = 0.0; // initialize density to zero lsph->id[i] = (int64_t) i; // set the particle's id lsph->hash[2*i+0] = (int64_t) 0; // initialize particle's hash value as zero lsph->hash[2*i+1] = (int64_t) i; // set particle's index position by the position in current array } gsl_rng_free(r); return 0; } /* * Function compute_hash_MC3D: * Compute the Morton Z hashes for all particles based on * the parameters given by the Cell Linked List box * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particles array * box <linkedListBox*> : Box of cell linked lists */ int compute_hash_MC3D(int64_t N, SPHparticle *lsph, linkedListBox *box){ if(lsph==NULL) return 1; if(box==NULL) return 1; const double etax = box->Nx/(box->Xmax - box->Xmin); const double etay = box->Ny/(box->Ymax - box->Ymin); const double etaz = box->Nz/(box->Zmax - box->Zmin); for(int64_t i=0;i<N;i+=1){ uint32_t kx,ky,kz; kx = (uint32_t)(etax*(lsph->x[i] - box->Xmin)); // Compute cell index in the X direction ky = (uint32_t)(etay*(lsph->y[i] - box->Ymin)); // Compute cell index in the Y direction kz = (uint32_t)(etaz*(lsph->z[i] - box->Zmin)); // Compute cell index in the Z direction if((kx<0)||(ky<0)||(kz<0)) // The can't be negative indexes return 1; else if((kx>=box->Nx)||(ky>=box->Nx)||(kz>=box->Nx)) // Nor indexes greater than the upper bounds return 1; else{ lsph->hash[2*i+0] = ullMC3Dencode(kx,ky,kz); // If ok, compute the corresponding Morton Z hash lsph->hash[2*i+1] = i; } } return 0; } /* * To swap two arrays, copy data from the original array into * a swap buffer in the right order, and then overrite the original array. */ #define swap_loop(N,lsph,temp_swap,member,type) for(int64_t i=0;i<(N);i+=1) \ (temp_swap)[i] = (lsph)->member[(lsph)->hash[2*i+1]];\ memcpy((lsph)->member,temp_swap,(N)*sizeof(type)) /* * Function reorder_lsph_SoA: * reorder the array according to the indexes reordered according to * their hashes. * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particles array * swap_arr <void*> : buffer for reordering data in the array */ int reorder_lsph_SoA(int N, SPHparticle *lsph, void *swap_arr){ int64_t *int64_temp_swap = (int64_t *)swap_arr; swap_loop(N,lsph,int64_temp_swap,id ,int64_t); double *double_temp_swap = (double *)swap_arr; swap_loop(N,lsph,double_temp_swap,nu ,double); swap_loop(N,lsph,double_temp_swap,rho,double); swap_loop(N,lsph,double_temp_swap,x ,double); swap_loop(N,lsph,double_temp_swap,y ,double); swap_loop(N,lsph,double_temp_swap,z ,double); swap_loop(N,lsph,double_temp_swap,ux ,double); swap_loop(N,lsph,double_temp_swap,uy ,double); swap_loop(N,lsph,double_temp_swap,uz ,double); swap_loop(N,lsph,double_temp_swap,Fx ,double); swap_loop(N,lsph,double_temp_swap,Fy ,double); swap_loop(N,lsph,double_temp_swap,Fz ,double); return 0; } /* * Function setup_interval_hashtables: * Setup the information where each cell begins and ends in the SPH * Array in a pair of hash tables for quick consultation. * This effectively completes the creation of the implicit * cell linked list structure initiated by sorting the array * according to hashes. * * Arguments: * N <int> : Number of Particles * lsph <SPHparticle**> : SoA Particles array * box <linkedListBox*> : Box of cell linked lists */ int setup_interval_hashtables(int64_t N,SPHparticle *lsph,linkedListBox *box){ int ret; int64_t hash0 = lsph->hash[2*0]; // Store the first hash in hash0 khiter_t kbegin,kend; if(lsph==NULL) return 1; if(box==NULL) return 1; kbegin = kh_put(0, box->hbegin, lsph->hash[2*0], &ret); // Insert start hash as first value kh_value(box->hbegin, kbegin) = (int64_t)0; // Set the start index of first cell as 0 for(int64_t i=0;i<N;i+=1){ lsph->hash[i] = lsph->hash[2*i]; // Clean the first half of the array only to contain hashes if(lsph->hash[i] == hash0) // If the the particle hash is the same as the previous continue; // skip because they are in the same cell hash0 = lsph->hash[i]; // otherwise, store the new hash in hash0 kend = kh_put(1, box->hend , lsph->hash[i-1], &ret); // If so, insert the previous hash as an cell end kh_value(box->hend , kend) = i; // and set this index as the upper index of that cell kbegin = kh_put(0, box->hbegin, lsph->hash[i ], &ret); // and then insert this new hash as the begining kh_value(box->hbegin, kbegin) = i; // of a new cell in with the lower index as this index } kend = kh_put(1, box->hend , lsph->hash[2*(N-1)], &ret); // finally set the last hash for the end of the last cell, kh_value(box->hend , kend) = N; // and the number of particles as the index of the last cell return 0; } /* * Function neighbour_hash_3d: * Find the hashes of all valid cells that neighbor cell with * int hash. * * Arguments: * hash <int64_t> : Hash of the central cell * nblist <int64_t*> : Array for hashes of the neighbor cells * width <int> : Width of the neighborhood * box <linkedListBox*> : Box of cell linked lists */ int neighbour_hash_3d(int64_t hash,int64_t *nblist,int width, linkedListBox *box){ int idx=0,kx=0,ky=0,kz=0; kx = ullMC3DdecodeX(hash); // To find a given cell's neighbors, start by first ky = ullMC3DdecodeY(hash); // recovering the integer index of that cell in kz = ullMC3DdecodeZ(hash); // the overall box domain for(int ix=-width;ix<=width;ix+=1){ // iterate over all cells surrounding the original cell for(int iy=-width;iy<=width;iy+=1){ // as long as they are within width of the original cell for(int iz=-width;iz<=width;iz+=1){ if((kx+ix<0)||(ky+iy<0)||(kz+iz<0)) // if the cell is off bounds for having lower index then 0 nblist[idx++] = -1; // annotate the cell as invalid else if( (kx+ix>=box->Nx)||(ky+iy>=box->Ny)||(kz+iz>=box->Nz) ) // or if it is off bounds for having higher index then nblist[idx++] = -1; // the maximum, also annotate as invalid else if( kh_get(0, box->hbegin, ullMC3Dencode(kx+ix,ky+iy,kz+iz)) == kh_end(box->hbegin) ) // Also, if no corresponding hash nblist[idx++] = -1; // is not found in the hash table, also annotate as invalid else // at last, if it has no problems nblist[idx++] = ullMC3Dencode(kx+ix,ky+iy,kz+iz); // annotate the hash of the corresponding cell } } } return 0; } /* * Function count_box_pairs: * Count the number of valid cell pairs * * Arguments: * box <linkedListBox*> : Box of cell linked lists */ int count_box_pairs(linkedListBox *box){ int64_t pair_count = 0; // initialize the number of pairs as zero for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid node_hash = kh_key(box->hbegin, kbegin); // get the hash of that cell neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors if(nblist[j]>=0){ // if the neighbor is valid pair_count += 1; // count it as a valid for a pair } } } } return pair_count; } /* * Function setup_box_pairs: * Pre-compute indexes for all valid cell pairs. * * Arguments: * box <linkedListBox*> : Box of cell linked lists * Returns: * node_begin <int64_t*> : Array for receiver cell begin indexes * node_end <int64_t*> : Array for receiver cell end indexes * nb_begin <int64_t*> : Array for sender cell begin indexes * nb_end <int64_t*> : Array for sender cell end indexes */ int setup_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0,particle_pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // get the iterator for the end index node_hash = kh_key(box->hbegin, kbegin); // and also get the corresponding hash neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors if(nblist[j]>=0){ // check if the neighbor is valid node_begin[pair_count] = kh_value(box->hbegin, kbegin); // get the cell's begin index node_end[pair_count] = kh_value(box->hend, kend); // get the cell's end index nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // get the neighbor's begin index nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // get the neighbor's end index particle_pair_count += (nb_end[pair_count]-nb_begin[pair_count])* // just for bookeeping/profiling, (node_end[pair_count]-node_begin[pair_count]); // annotate the number of particle pairs pair_count += 1; // that are part of the computation } } } } if(dbg) printf("particle_pair_count = %ld\n",particle_pair_count); return pair_count; } /* * Function setup_unique_box_pairs: * Pre-compute indexes for all valid unique cell pairs. * by unique means that if [node_begin,node_end)x[nb_begin,nb_end) * is in the list, [nb_begin,nb_end)x[node_begin,node_end) is not. * * Arguments: * box <linkedListBox*> : Box of cell linked lists * Returns: * node_begin <int64_t*> : Array for receiver cell begin indexes * node_end <int64_t*> : Array for receiver cell end indexes * nb_begin <int64_t*> : Array for sender cell begin indexes * nb_end <int64_t*> : Array for sender cell end indexes */ int setup_unique_box_pairs(linkedListBox *box, int64_t *node_begin,int64_t *node_end, int64_t *nb_begin,int64_t *nb_end) { int64_t pair_count = 0, particle_pair_count = 0; for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells int64_t node_hash=-1; int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // get the iterator for the end index node_hash = kh_key(box->hbegin, kbegin); // and also get the corresponding hash neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors if(nblist[j]>=0){ // check if the neighbor is valid if(kh_value(box->hbegin, kbegin) <= // and if the node_index is smaller kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) )) // then the neighbor index { node_begin[pair_count] = kh_value(box->hbegin, kbegin); // get the cell's begin index node_end[pair_count] = kh_value(box->hend, kend); // get the cell's end index nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // get the neighbor's begin index nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // get the neighbor's end index particle_pair_count += (nb_end[pair_count]-nb_begin[pair_count])* // just for bookeeping/profiling, (node_end[pair_count]-node_begin[pair_count]); // annotate the number of particle pairs pair_count += 1; // that are part of the computation } } } } } if(dbg) printf("particle_pair_count = %ld\n",particle_pair_count); return pair_count; } /* * Function print_sph_particles_density: * Write in disk the density values for the computed SPH particles. * * Arguments: * prefix <const char*> : prefix for the file name * is_cll <bool> : boolean defined naive or cell linked list case * N <int64_t> : Number of SPH particles * h <double> : smoothing length * seed <long int> : seed utilized for the PRNG * runs <int> : Number of runs executed * lsph <SPHparticle*> : Array of SPH particles * box <linkedListBox*> : Box of cell linked lists * Returns: * 0 <int> : Error code * fp <FILE*> : Written file with particle densities */ int print_sph_particles_density(const char *prefix, bool is_cll, int64_t N, double h, long int seed, int runs, SPHparticle *lsph, linkedListBox *box){ FILE *fp; char filename[2048+1]; if(is_cll){ sprintf(filename, "data/cd3d(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv", prefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax); fp = fopen(filename,"w"); fprintf(fp,"id,x,y,z,rho\n"); for(int64_t i=0;i<N;i+=1) fprintf(fp,"%ld,%lf,%lf,%lf,%lf\n",lsph->id[i],lsph->x[i],lsph->y[i],lsph->z[i],lsph->rho[i]); fclose(fp); } else{ sprintf(filename, "data/cd3d(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv", prefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax); fp = fopen(filename,"w"); fprintf(fp,"id,x,y,z,rho\n"); for(int64_t i=0;i<N;i+=1) fprintf(fp,"%ld,%lf,%lf,%lf,%lf\n",lsph->id[i],lsph->x[i],lsph->y[i],lsph->z[i],lsph->rho[i]); fclose(fp); } return 0; } /* * Function print_sph_particles_density: * Write in disk the density values for the computed SPH particles. * * Arguments: * prefix <const char*> : prefix for the file name * is_cll <bool> : boolean defined naive or cell linked list case * N <int64_t> : Number of SPH particles * h <double> : smoothing length * seed <long int> : seed utilized for the PRNG * runs <int> : Number of runs executed * lsph <SPHparticle*> : Array of SPH particles * box <linkedListBox*> : Box of cell linked lists * times <double*> : timings for each of the processing steps * Returns: * 0 <int> : Error code * fp <FILE*> : Written file with particle densities */ int print_time_stats(const char *prefix, bool is_cll, int64_t N, double h, long int seed, int runs, SPHparticle *lsph, linkedListBox *box,double *times){ FILE *fp; char filename[1024+1]; if(is_cll){ const int COMPUTE_BLOCKS = 5; double t[COMPUTE_BLOCKS], dt[COMPUTE_BLOCKS], total_time, dtotal_time; sprintf(filename, "data/times-(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv", prefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax); fp = fopen(filename,"w"); fprintf(fp,"id,compute_hash_MC3D,sorting,reorder_lsph_SoA,setup_interval_hashtables,compute_density\n"); for(int run=0;run<runs;run+=1) fprintf(fp,"%d,%lf,%lf,%lf,%lf,%lf\n",run,times[COMPUTE_BLOCKS*run+0],times[COMPUTE_BLOCKS*run+1],times[COMPUTE_BLOCKS*run+2], times[COMPUTE_BLOCKS*run+3],times[COMPUTE_BLOCKS*run+4]); fclose(fp); total_time = 0.; for(int k=0;k<COMPUTE_BLOCKS;k+=1){ t[k]=0.; dt[k]=0.; for(int run=0;run<runs;run+=1) t[k] += times[COMPUTE_BLOCKS*run+k]; t[k] /= runs; for(int run=0;run<runs;run+=1) dt[k] += (times[COMPUTE_BLOCKS*run+k]-t[k])*(times[COMPUTE_BLOCKS*run+k]-t[k]); dt[k] /= runs; dt[k] = sqrt(dt[k]); total_time += t[k]; } dtotal_time = 0.; for(int run=0;run<runs;run+=1){ double rgm = 0.; for(int k=0;k<COMPUTE_BLOCKS;k+=1) rgm += times[COMPUTE_BLOCKS*run+k]; dtotal_time += (rgm-total_time)*(rgm-total_time); } dtotal_time /= runs; dtotal_time = sqrt(dtotal_time); if(dbg){ printf("compute_hash_MC3D calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[0],dt[0],100*t[0]/total_time,100*dt[0]/total_time); printf("qsort calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[1],dt[1],100*t[1]/total_time,100*dt[1]/total_time); printf("reorder_lsph_SoA calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[2],dt[2],100*t[2]/total_time,100*dt[2]/total_time); printf("setup_interval_hashtables calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[3],dt[3],100*t[3]/total_time,100*dt[3]/total_time); printf("compute_density_3d load balanced calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[4],dt[4],100*t[4]/total_time,100*dt[4]/total_time); printf("compute_density_3d load balanced total time : %.5lf +- %.6lf s : %.3lf%%\n",total_time,dtotal_time,100.); } } else{ const int COMPUTE_BLOCKS = 1; double t[COMPUTE_BLOCKS], dt[COMPUTE_BLOCKS], total_time, dtotal_time; sprintf(filename, "data/times-(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv", prefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax); fp = fopen(filename,"w"); fprintf(fp,"id,compute_density\n"); for(int run=0;run<runs;run+=1) fprintf(fp,"%d,%lf\n",run,times[COMPUTE_BLOCKS*run+0]); fclose(fp); total_time = 0.; for(int k=0;k<COMPUTE_BLOCKS;k+=1){ t[k]=0.; dt[k]=0.; for(int run=0;run<runs;run+=1) t[k] += times[COMPUTE_BLOCKS*run+k]; t[k] /= runs; for(int run=0;run<runs;run+=1) dt[k] += (times[COMPUTE_BLOCKS*run+k]-t[k])*(times[COMPUTE_BLOCKS*run+k]-t[k]); dt[k] /= runs; dt[k] = sqrt(dt[k]); total_time += t[k]; } dtotal_time = 0.; for(int run=0;run<runs;run+=1){ double rgm = 0.; for(int k=0;k<1;k+=1) rgm += times[COMPUTE_BLOCKS*run+k]; dtotal_time += (rgm-total_time)*(rgm-total_time); } dtotal_time /= runs; dtotal_time = sqrt(dtotal_time); if(dbg) printf("compute_density_3d naive %s : %.5lf +- %.6lf s : %.3lf%%\n",prefix,total_time,dtotal_time,100.); } return 0; }
{ "alphanum_fraction": 0.5617118459, "avg_line_length": 41.6157024793, "ext": "c", "hexsha": "dc36cd72bb63b177c0fc32d36e0ee63b62672de1", "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": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_path": "SoA/src/sph_linked_list.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "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": "jhelsas/sphalerite", "max_issues_repo_path": "SoA/src/sph_linked_list.c", "max_line_length": 154, "max_stars_count": null, "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_path": "SoA/src/sph_linked_list.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8842, "size": 30213 }
/* matrix/gsl_matrix_short.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_MATRIX_SHORT_H__ #define __GSL_MATRIX_SHORT_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_vector_short.h> #include <gsl/gsl_blas_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; short * data; gsl_block_short * block; int owner; } gsl_matrix_short; typedef struct { gsl_matrix_short matrix; } _gsl_matrix_short_view; typedef _gsl_matrix_short_view gsl_matrix_short_view; typedef struct { gsl_matrix_short matrix; } _gsl_matrix_short_const_view; typedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view; /* Allocation */ GSL_FUN gsl_matrix_short * gsl_matrix_short_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_short * gsl_matrix_short_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_short * gsl_matrix_short_alloc_from_block (gsl_block_short * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix_short * gsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector_short * gsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m, const size_t i); GSL_FUN gsl_vector_short * gsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m, const size_t j); GSL_FUN void gsl_matrix_short_free (gsl_matrix_short * m); /* Views */ GSL_FUN _gsl_matrix_short_view gsl_matrix_short_submatrix (gsl_matrix_short * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_short_view gsl_matrix_short_row (gsl_matrix_short * m, const size_t i); GSL_FUN _gsl_vector_short_view gsl_matrix_short_column (gsl_matrix_short * m, const size_t j); GSL_FUN _gsl_vector_short_view gsl_matrix_short_diagonal (gsl_matrix_short * m); GSL_FUN _gsl_vector_short_view gsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k); GSL_FUN _gsl_vector_short_view gsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k); GSL_FUN _gsl_vector_short_view gsl_matrix_short_subrow (gsl_matrix_short * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_short_view gsl_matrix_short_subcolumn (gsl_matrix_short * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_short_view gsl_matrix_short_view_array (short * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_short_view gsl_matrix_short_view_array_with_tda (short * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_short_view gsl_matrix_short_view_vector (gsl_vector_short * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_short_view gsl_matrix_short_view_vector_with_tda (gsl_vector_short * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_short_const_view gsl_matrix_short_const_submatrix (const gsl_matrix_short * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_row (const gsl_matrix_short * m, const size_t i); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_column (const gsl_matrix_short * m, const size_t j); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_diagonal (const gsl_matrix_short * m); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m, const size_t k); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m, const size_t k); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_subrow (const gsl_matrix_short * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_short_const_view gsl_matrix_short_const_subcolumn (const gsl_matrix_short * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_short_const_view gsl_matrix_short_const_view_array (const short * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_short_const_view gsl_matrix_short_const_view_array_with_tda (const short * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_short_const_view gsl_matrix_short_const_view_vector (const gsl_vector_short * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_short_const_view gsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_short_set_zero (gsl_matrix_short * m); GSL_FUN void gsl_matrix_short_set_identity (gsl_matrix_short * m); GSL_FUN void gsl_matrix_short_set_all (gsl_matrix_short * m, short x); GSL_FUN int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ; GSL_FUN int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ; GSL_FUN int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format); GSL_FUN int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src); GSL_FUN int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2); GSL_FUN int gsl_matrix_short_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_short * dest, const gsl_matrix_short * src); GSL_FUN int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_short_transpose (gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src); GSL_FUN int gsl_matrix_short_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_short * dest, const gsl_matrix_short * src); GSL_FUN short gsl_matrix_short_max (const gsl_matrix_short * m); GSL_FUN short gsl_matrix_short_min (const gsl_matrix_short * m); GSL_FUN void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out); GSL_FUN void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax); GSL_FUN void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin); GSL_FUN void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_FUN int gsl_matrix_short_equal (const gsl_matrix_short * a, const gsl_matrix_short * b); GSL_FUN int gsl_matrix_short_isnull (const gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_ispos (const gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_isneg (const gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_isnonneg (const gsl_matrix_short * m); GSL_FUN int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b); GSL_FUN int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b); GSL_FUN int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b); GSL_FUN int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b); GSL_FUN int gsl_matrix_short_scale (gsl_matrix_short * a, const double x); GSL_FUN int gsl_matrix_short_scale_rows (gsl_matrix_short * a, const gsl_vector_short * x); GSL_FUN int gsl_matrix_short_scale_columns (gsl_matrix_short * a, const gsl_vector_short * x); GSL_FUN int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x); GSL_FUN int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i); GSL_FUN int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j); GSL_FUN int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v); GSL_FUN int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x); GSL_FUN INLINE_DECL short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } } #endif return m->data[i * m->tda + j] ; } INLINE_FUN void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } } #endif m->data[i * m->tda + j] = x ; } INLINE_FUN short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (short *) (m->data + (i * m->tda + j)) ; } INLINE_FUN const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (const short *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_SHORT_H__ */
{ "alphanum_fraction": 0.6710351936, "avg_line_length": 37.1092896175, "ext": "h", "hexsha": "d6ae90b6c0f2be0917d29d042abfbe2fca9aea60", "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": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "zhanghe9704/jspec2", "max_forks_repo_path": "include/gsl/gsl_matrix_short.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "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": "zhanghe9704/jspec2", "max_issues_repo_path": "include/gsl/gsl_matrix_short.h", "max_line_length": 144, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "zhanghe9704/jspec2", "max_stars_repo_path": "include/gsl/gsl_matrix_short.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": 3339, "size": 13582 }
/* linalg/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_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_complex_math.h> #include "gsl_linalg.h" int check (double x, double actual, double eps); gsl_matrix * create_hilbert_matrix(size_t size); gsl_matrix * create_general_matrix(size_t size1, size_t size2); gsl_matrix * create_vandermonde_matrix(size_t size); gsl_matrix * create_moler_matrix(size_t size); gsl_matrix * create_row_matrix(size_t size1, size_t size2); gsl_matrix * create_2x2_matrix(double a11, double a12, double a21, double a22); int test_matmult(void); int test_matmult_mod(void); int test_LU_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_LU_solve(void); int test_LUc_solve_dim(const gsl_matrix_complex * m, const double * actual, double eps); int test_LUc_solve(void); int test_QR_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_QR_solve(void); int test_QR_lssolve_dim(const gsl_matrix * m, const double * actual, double eps); int test_QR_lssolve(void); int test_QR_decomp_dim(const gsl_matrix * m, double eps); int test_QR_decomp(void); int test_QRPT_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_QRPT_solve(void); int test_QRPT_decomp_dim(const gsl_matrix * m, double eps); int test_QRPT_decomp(void); int test_QR_update_dim(const gsl_matrix * m, double eps); int test_QR_update(void); int test_SV_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_SV_solve(void); int test_SV_decomp_dim(const gsl_matrix * m, double eps); int test_SV_decomp(void); int test_cholesky_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_cholesky_solve(void); int test_cholesky_decomp_dim(const gsl_matrix * m, double eps); int test_cholesky_decomp(void); int test_HH_solve_dim(const gsl_matrix * m, const double * actual, double eps); int test_HH_solve(void); int test_TD_solve_dim(size_t dim, double d, double od, const double * actual, double eps); int test_TD_solve(void); int test_bidiag_decomp_dim(const gsl_matrix * m, double eps); int test_bidiag_decomp(void); int check (double x, double actual, double eps) { if (actual == 0) return fabs(x) > eps; else return (fabs(x - actual)/fabs(actual)) > eps; } gsl_matrix * create_hilbert_matrix(size_t size) { size_t i, j; gsl_matrix * m = gsl_matrix_alloc(size, size); for(i=0; i<size; i++) { for(j=0; j<size; j++) { gsl_matrix_set(m, i, j, 1.0/(i+j+1.0)); } } return m; } gsl_matrix * create_general_matrix(size_t size1, size_t size2) { size_t i, j; gsl_matrix * m = gsl_matrix_alloc(size1, size2); for(i=0; i<size1; i++) { for(j=0; j<size2; j++) { gsl_matrix_set(m, i, j, 1.0/(i+j+1.0)); } } return m; } gsl_matrix * create_singular_matrix(size_t size1, size_t size2) { size_t i, j; gsl_matrix * m = gsl_matrix_alloc(size1, size2); for(i=0; i<size1; i++) { for(j=0; j<size2; j++) { gsl_matrix_set(m, i, j, 1.0/(i+j+1.0)); } } /* zero the first column */ for(j = 0; j <size2; j++) gsl_matrix_set(m,0,j,0.0); return m; } gsl_matrix * create_vandermonde_matrix(size_t size) { size_t i, j; gsl_matrix * m = gsl_matrix_alloc(size, size); for(i=0; i<size; i++) { for(j=0; j<size; j++) { gsl_matrix_set(m, i, j, pow(i + 1.0, size - j - 1.0)); } } return m; } gsl_matrix * create_moler_matrix(size_t size) { size_t i, j; gsl_matrix * m = gsl_matrix_alloc(size, size); for(i=0; i<size; i++) { for(j=0; j<size; j++) { gsl_matrix_set(m, i, j, GSL_MIN(i+1,j+1)-2.0); } } return m; } gsl_matrix_complex * create_complex_matrix(size_t size) { size_t i, j; gsl_matrix_complex * m = gsl_matrix_complex_alloc(size, size); for(i=0; i<size; i++) { for(j=0; j<size; j++) { gsl_complex z = gsl_complex_rect(1.0/(i+j+1.0), 1/(i*i+j*j+0.5)); gsl_matrix_complex_set(m, i, j, z); } } return m; } gsl_matrix * create_row_matrix(size_t size1, size_t size2) { size_t i; gsl_matrix * m = gsl_matrix_calloc(size1, size2); for(i=0; i<size1; i++) { gsl_matrix_set(m, i, 0, 1.0/(i+1.0)); } return m; } gsl_matrix * create_2x2_matrix(double a11, double a12, double a21, double a22) { gsl_matrix * m = gsl_matrix_alloc(2, 2); gsl_matrix_set(m, 0, 0, a11); gsl_matrix_set(m, 0, 1, a12); gsl_matrix_set(m, 1, 0, a21); gsl_matrix_set(m, 1, 1, a22); return m; } gsl_matrix * m35; gsl_matrix * m53; gsl_matrix * m97; gsl_matrix * s35; gsl_matrix * s53; gsl_matrix * hilb2; gsl_matrix * hilb3; gsl_matrix * hilb4; gsl_matrix * hilb12; gsl_matrix * row3; gsl_matrix * row5; gsl_matrix * row12; gsl_matrix * A22; gsl_matrix_complex * c7; double m53_lssolution[] = {52.5992295702070, -337.7263113752073, 351.8823436427604}; double hilb2_solution[] = {-8.0, 18.0} ; double hilb3_solution[] = {27.0, -192.0, 210.0}; double hilb4_solution[] = {-64.0, 900.0, -2520.0, 1820.0}; double hilb12_solution[] = {-1728.0, 245388.0, -8528520.0, 127026900.0, -1009008000.0, 4768571808.0, -14202796608.0, 27336497760.0, -33921201600.0, 26189163000.0, -11437874448.0, 2157916488.0 }; double c7_solution[] = { 2.40717272023734e+01, -9.84612797621247e+00, -2.69338853034031e+02, 8.75455232472528e+01, 2.96661356736296e+03, -1.02624473923993e+03, -1.82073812124749e+04, 5.67384473042410e+03, 5.57693879019068e+04, -1.61540963210502e+04, -7.88941207561151e+04, 1.95053812987858e+04, 3.95548551241728e+04, -7.76593696255317e+03 }; gsl_matrix * vander2; gsl_matrix * vander3; gsl_matrix * vander4; gsl_matrix * vander12; double vander2_solution[] = {1.0, 0.0}; double vander3_solution[] = {0.0, 1.0, 0.0}; double vander4_solution[] = {0.0, 0.0, 1.0, 0.0}; double vander12_solution[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0}; gsl_matrix * moler10; /* matmult now obsolete */ #ifdef MATMULT int test_matmult(void) { int s = 0; gsl_matrix * A = gsl_matrix_calloc(2, 2); gsl_matrix * B = gsl_matrix_calloc(2, 3); gsl_matrix * C = gsl_matrix_calloc(2, 3); gsl_matrix_set(A, 0, 0, 10.0); gsl_matrix_set(A, 0, 1, 5.0); gsl_matrix_set(A, 1, 0, 1.0); gsl_matrix_set(A, 1, 1, 20.0); gsl_matrix_set(B, 0, 0, 10.0); gsl_matrix_set(B, 0, 1, 5.0); gsl_matrix_set(B, 0, 2, 2.0); gsl_matrix_set(B, 1, 0, 1.0); gsl_matrix_set(B, 1, 1, 3.0); gsl_matrix_set(B, 1, 2, 2.0); gsl_linalg_matmult(A, B, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 105.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 65.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 30.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 30.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 65.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 42.0) > GSL_DBL_EPSILON ); gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(C); return s; } int test_matmult_mod(void) { int s = 0; gsl_matrix * A = gsl_matrix_calloc(3, 3); gsl_matrix * B = gsl_matrix_calloc(3, 3); gsl_matrix * C = gsl_matrix_calloc(3, 3); gsl_matrix * D = gsl_matrix_calloc(2, 3); gsl_matrix * E = gsl_matrix_calloc(2, 3); gsl_matrix * F = gsl_matrix_calloc(2, 2); gsl_matrix_set(A, 0, 0, 10.0); gsl_matrix_set(A, 0, 1, 5.0); gsl_matrix_set(A, 0, 2, 1.0); gsl_matrix_set(A, 1, 0, 1.0); gsl_matrix_set(A, 1, 1, 20.0); gsl_matrix_set(A, 1, 2, 5.0); gsl_matrix_set(A, 2, 0, 1.0); gsl_matrix_set(A, 2, 1, 3.0); gsl_matrix_set(A, 2, 2, 7.0); gsl_matrix_set(B, 0, 0, 10.0); gsl_matrix_set(B, 0, 1, 5.0); gsl_matrix_set(B, 0, 2, 2.0); gsl_matrix_set(B, 1, 0, 1.0); gsl_matrix_set(B, 1, 1, 3.0); gsl_matrix_set(B, 1, 2, 2.0); gsl_matrix_set(B, 2, 0, 1.0); gsl_matrix_set(B, 2, 1, 3.0); gsl_matrix_set(B, 2, 2, 2.0); gsl_matrix_set(D, 0, 0, 10.0); gsl_matrix_set(D, 0, 1, 5.0); gsl_matrix_set(D, 0, 2, 1.0); gsl_matrix_set(D, 1, 0, 1.0); gsl_matrix_set(D, 1, 1, 20.0); gsl_matrix_set(D, 1, 2, 5.0); gsl_matrix_set(E, 0, 0, 10.0); gsl_matrix_set(E, 0, 1, 5.0); gsl_matrix_set(E, 0, 2, 2.0); gsl_matrix_set(E, 1, 0, 1.0); gsl_matrix_set(E, 1, 1, 3.0); gsl_matrix_set(E, 1, 2, 2.0); gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_NONE, B, GSL_LINALG_MOD_NONE, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 106.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 68.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 32.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 35.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 80.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 52.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 0) - 20.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 1) - 35.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 2) - 22.0) > GSL_DBL_EPSILON ); gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_TRANSPOSE, B, GSL_LINALG_MOD_NONE, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 102.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 56.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 24.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 73.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 94.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 56.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 0) - 22.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 1) - 41.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 2) - 26.0) > GSL_DBL_EPSILON ); gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_NONE, B, GSL_LINALG_MOD_TRANSPOSE, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 127.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 27.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 27.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 120.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 71.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 71.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 0) - 39.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 1) - 24.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 2) - 24.0) > GSL_DBL_EPSILON ); gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_TRANSPOSE, B, GSL_LINALG_MOD_TRANSPOSE, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 107.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 15.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 15.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 156.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 71.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 71.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 0) - 49.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 1) - 30.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 2) - 30.0) > GSL_DBL_EPSILON ); /* now try for non-symmetric matrices */ gsl_linalg_matmult_mod(D, GSL_LINALG_MOD_TRANSPOSE, E, GSL_LINALG_MOD_NONE, C); s += ( fabs(gsl_matrix_get(C, 0, 0) - 101.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 1) - 53.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 0, 2) - 22.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 0) - 70.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 1) - 85.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 1, 2) - 50.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 0) - 15.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 1) - 20.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(C, 2, 2) - 12.0) > GSL_DBL_EPSILON ); gsl_linalg_matmult_mod(D, GSL_LINALG_MOD_NONE, E, GSL_LINALG_MOD_TRANSPOSE, F); s += ( fabs(gsl_matrix_get(F, 0, 0) - 127.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(F, 0, 1) - 27.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(F, 1, 0) - 120.0) > GSL_DBL_EPSILON ); s += ( fabs(gsl_matrix_get(F, 1, 1) - 71.0) > GSL_DBL_EPSILON ); gsl_matrix_free(A); gsl_matrix_free(B); gsl_matrix_free(C); gsl_matrix_free(D); gsl_matrix_free(E); gsl_matrix_free(F); return s; } #endif int test_LU_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; int signum; size_t i, dim = m->size1; gsl_permutation * perm = gsl_permutation_alloc(dim); gsl_vector * rhs = gsl_vector_alloc(dim); gsl_matrix * lu = gsl_matrix_alloc(dim,dim); gsl_vector * x = gsl_vector_alloc(dim); gsl_vector * residual = gsl_vector_alloc(dim); gsl_matrix_memcpy(lu,m); for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_LU_decomp(lu, perm, &signum); s += gsl_linalg_LU_solve(lu, perm, rhs, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i),actual[i],eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } s += gsl_linalg_LU_refine(m, lu, perm, rhs, x, residual); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i),actual[i],eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g (improved)\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(residual); gsl_vector_free(x); gsl_matrix_free(lu); gsl_vector_free(rhs); gsl_permutation_free(perm); return s; } int test_LU_solve(void) { int f; int s = 0; f = test_LU_solve_dim(hilb2, hilb2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve hilbert(2)"); s += f; f = test_LU_solve_dim(hilb3, hilb3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve hilbert(3)"); s += f; f = test_LU_solve_dim(hilb4, hilb4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve hilbert(4)"); s += f; f = test_LU_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " LU_solve hilbert(12)"); s += f; f = test_LU_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve vander(2)"); s += f; f = test_LU_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve vander(3)"); s += f; f = test_LU_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " LU_solve vander(4)"); s += f; f = test_LU_solve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " LU_solve vander(12)"); s += f; return s; } int test_LUc_solve_dim(const gsl_matrix_complex * m, const double * actual, double eps) { int s = 0; int signum; size_t i, dim = m->size1; gsl_permutation * perm = gsl_permutation_alloc(dim); gsl_vector_complex * rhs = gsl_vector_complex_alloc(dim); gsl_matrix_complex * lu = gsl_matrix_complex_alloc(dim,dim); gsl_vector_complex * x = gsl_vector_complex_alloc(dim); gsl_vector_complex * residual = gsl_vector_complex_alloc(dim); gsl_matrix_complex_memcpy(lu,m); for(i=0; i<dim; i++) { gsl_complex z = gsl_complex_rect (2.0*i+1.0, 2.0*i+2.0); gsl_vector_complex_set(rhs, i, z); } s += gsl_linalg_complex_LU_decomp(lu, perm, &signum); s += gsl_linalg_complex_LU_solve(lu, perm, rhs, x); for(i=0; i<dim; i++) { gsl_complex z = gsl_vector_complex_get(x, i); int foo_r = check(GSL_REAL(z),actual[2*i],eps); int foo_i = check(GSL_IMAG(z),actual[2*i+1],eps); if(foo_r || foo_i) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, GSL_REAL(z), actual[2*i]); printf("%3d[%d]: %22.18g %22.18g\n", dim, i, GSL_IMAG(z), actual[2*i+1]); } s += foo_r + foo_i; } s += gsl_linalg_complex_LU_refine(m, lu, perm, rhs, x, residual); for(i=0; i<dim; i++) { gsl_complex z = gsl_vector_complex_get(x, i); int foo_r = check(GSL_REAL(z),actual[2*i],eps); int foo_i = check(GSL_IMAG(z),actual[2*i+1],eps); if(foo_r || foo_i) { printf("%3d[%d]: %22.18g %22.18g (improved)\n", dim, i, GSL_REAL(z), actual[2*i]); printf("%3d[%d]: %22.18g %22.18g (improved)\n", dim, i, GSL_IMAG(z), actual[2*i+1]); } s += foo_r + foo_i; } gsl_vector_complex_free(residual); gsl_vector_complex_free(x); gsl_matrix_complex_free(lu); gsl_vector_complex_free(rhs); gsl_permutation_free(perm); return s; } int test_LUc_solve(void) { int f; int s = 0; f = test_LUc_solve_dim(c7, c7_solution, 1024.0 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " complex_LU_solve complex(7)"); s += f; return s; } int test_QR_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; size_t i, dim = m->size1; gsl_vector * rhs = gsl_vector_alloc(dim); gsl_matrix * qr = gsl_matrix_alloc(dim,dim); gsl_vector * d = gsl_vector_alloc(dim); gsl_vector * x = gsl_vector_alloc(dim); gsl_matrix_memcpy(qr,m); for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_QR_decomp(qr, d); s += gsl_linalg_QR_solve(qr, d, rhs, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i), actual[i], eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(x); gsl_vector_free(d); gsl_matrix_free(qr); gsl_vector_free(rhs); return s; } int test_QR_solve(void) { int f; int s = 0; f = test_QR_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve hilbert(2)"); s += f; f = test_QR_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve hilbert(3)"); s += f; f = test_QR_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve hilbert(4)"); s += f; f = test_QR_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " QR_solve hilbert(12)"); s += f; f = test_QR_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve vander(2)"); s += f; f = test_QR_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve vander(3)"); s += f; f = test_QR_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_solve vander(4)"); s += f; f = test_QR_solve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " QR_solve vander(12)"); s += f; return s; } int test_QR_lssolve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; size_t i, M = m->size1, N = m->size2; gsl_vector * rhs = gsl_vector_alloc(M); gsl_matrix * qr = gsl_matrix_alloc(M,N); gsl_vector * d = gsl_vector_alloc(N); gsl_vector * x = gsl_vector_alloc(N); gsl_vector * r = gsl_vector_alloc(M); gsl_vector * res = gsl_vector_alloc(M); gsl_matrix_memcpy(qr,m); for(i=0; i<M; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_QR_decomp(qr, d); s += gsl_linalg_QR_lssolve(qr, d, rhs, x, res); for(i=0; i<N; i++) { int foo = check(gsl_vector_get(x, i), actual[i], eps); if(foo) { printf("(%3d,%3d)[%d]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(x, i), actual[i]); } s += foo; } /* compute residual r = b - m x */ if (M == N) { gsl_vector_set_zero(r); } else { gsl_vector_memcpy(r, rhs); gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r); }; for(i=0; i<N; i++) { int foo = check(gsl_vector_get(res, i), gsl_vector_get(r,i), sqrt(eps)); if(foo) { printf("(%3d,%3d)[%d]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(res, i), gsl_vector_get(r,i)); } s += foo; } gsl_vector_free(r); gsl_vector_free(res); gsl_vector_free(x); gsl_vector_free(d); gsl_matrix_free(qr); gsl_vector_free(rhs); return s; } int test_QR_lssolve(void) { int f; int s = 0; f = test_QR_lssolve_dim(m53, m53_lssolution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve m(5,3)"); s += f; f = test_QR_lssolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve hilbert(2)"); s += f; f = test_QR_lssolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve hilbert(3)"); s += f; f = test_QR_lssolve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve hilbert(4)"); s += f; f = test_QR_lssolve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " QR_lssolve hilbert(12)"); s += f; f = test_QR_lssolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve vander(2)"); s += f; f = test_QR_lssolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve vander(3)"); s += f; f = test_QR_lssolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_lssolve vander(4)"); s += f; f = test_QR_lssolve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " QR_lssolve vander(12)"); s += f; return s; } int test_QR_decomp_dim(const gsl_matrix * m, double eps) { int s = 0; size_t i,j, M = m->size1, N = m->size2; gsl_matrix * qr = gsl_matrix_alloc(M,N); gsl_matrix * a = gsl_matrix_alloc(M,N); gsl_matrix * q = gsl_matrix_alloc(M,M); gsl_matrix * r = gsl_matrix_alloc(M,N); gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N)); gsl_matrix_memcpy(qr,m); s += gsl_linalg_QR_decomp(qr, d); s += gsl_linalg_QR_unpack(qr, d, q, r); /* compute a = q r */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, q, r, 0.0, a); for(i=0; i<M; i++) { for(j=0; j<N; j++) { double aij = gsl_matrix_get(a, i, j); double mij = gsl_matrix_get(m, i, j); int foo = check(aij, mij, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, aij, mij); } s += foo; } } gsl_vector_free(d); gsl_matrix_free(qr); gsl_matrix_free(a); gsl_matrix_free(q); gsl_matrix_free(r); return s; } int test_QR_decomp(void) { int f; int s = 0; f = test_QR_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp m(3,5)"); s += f; f = test_QR_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp m(5,3)"); s += f; f = test_QR_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(2)"); s += f; f = test_QR_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(3)"); s += f; f = test_QR_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(4)"); s += f; f = test_QR_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp hilbert(12)"); s += f; f = test_QR_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(2)"); s += f; f = test_QR_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(3)"); s += f; f = test_QR_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_decomp vander(4)"); s += f; f = test_QR_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */ gsl_test(f, " QR_decomp vander(12)"); s += f; return s; } int test_QRPT_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; int signum; size_t i, dim = m->size1; gsl_permutation * perm = gsl_permutation_alloc(dim); gsl_vector * rhs = gsl_vector_alloc(dim); gsl_matrix * qr = gsl_matrix_alloc(dim,dim); gsl_vector * d = gsl_vector_alloc(dim); gsl_vector * x = gsl_vector_alloc(dim); gsl_vector * norm = gsl_vector_alloc(dim); gsl_matrix_memcpy(qr,m); for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_QRPT_decomp(qr, d, perm, &signum, norm); s += gsl_linalg_QRPT_solve(qr, d, perm, rhs, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i), actual[i], eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(norm); gsl_vector_free(x); gsl_vector_free(d); gsl_matrix_free(qr); gsl_vector_free(rhs); gsl_permutation_free(perm); return s; } int test_QRPT_solve(void) { int f; int s = 0; f = test_QRPT_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve hilbert(2)"); s += f; f = test_QRPT_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve hilbert(3)"); s += f; f = test_QRPT_solve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve hilbert(4)"); s += f; f = test_QRPT_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " QRPT_solve hilbert(12)"); s += f; f = test_QRPT_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve vander(2)"); s += f; f = test_QRPT_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve vander(3)"); s += f; f = test_QRPT_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_solve vander(4)"); s += f; f = test_QRPT_solve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " QRPT_solve vander(12)"); s += f; return s; } int test_QRPT_decomp_dim(const gsl_matrix * m, double eps) { int s = 0, signum; size_t i,j, M = m->size1, N = m->size2; gsl_matrix * qr = gsl_matrix_alloc(M,N); gsl_matrix * a = gsl_matrix_alloc(M,N); gsl_matrix * q = gsl_matrix_alloc(M,M); gsl_matrix * r = gsl_matrix_alloc(M,N); gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N)); gsl_vector * norm = gsl_vector_alloc(N); gsl_permutation * perm = gsl_permutation_alloc(N); gsl_matrix_memcpy(qr,m); s += gsl_linalg_QRPT_decomp(qr, d, perm, &signum, norm); s += gsl_linalg_QR_unpack(qr, d, q, r); /* compute a = q r */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, q, r, 0.0, a); /* Compute QR P^T by permuting the elements of the rows of QR */ for (i = 0; i < M; i++) { gsl_vector_view row = gsl_matrix_row (a, i); gsl_permute_vector_inverse (perm, &row.vector); } for(i=0; i<M; i++) { for(j=0; j<N; j++) { double aij = gsl_matrix_get(a, i, j); double mij = gsl_matrix_get(m, i, j); int foo = check(aij, mij, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, aij, mij); } s += foo; } } gsl_permutation_free (perm); gsl_vector_free(norm); gsl_vector_free(d); gsl_matrix_free(qr); gsl_matrix_free(a); gsl_matrix_free(q); gsl_matrix_free(r); return s; } int test_QRPT_decomp(void) { int f; int s = 0; f = test_QRPT_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp m(3,5)"); s += f; f = test_QRPT_decomp_dim(m53, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp m(5,3)"); s += f; f = test_QRPT_decomp_dim(s35, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp s(3,5)"); s += f; f = test_QRPT_decomp_dim(s53, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp s(5,3)"); s += f; f = test_QRPT_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp hilbert(2)"); s += f; f = test_QRPT_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp hilbert(3)"); s += f; f = test_QRPT_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp hilbert(4)"); s += f; f = test_QRPT_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp hilbert(12)"); s += f; f = test_QRPT_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp vander(2)"); s += f; f = test_QRPT_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp vander(3)"); s += f; f = test_QRPT_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QRPT_decomp vander(4)"); s += f; f = test_QRPT_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */ gsl_test(f, " QRPT_decomp vander(12)"); s += f; return s; } int test_QR_update_dim(const gsl_matrix * m, double eps) { int s = 0; size_t i,j,k, M = m->size1, N = m->size2; gsl_vector * rhs = gsl_vector_alloc(N); gsl_matrix * qr1 = gsl_matrix_alloc(M,N); gsl_matrix * qr2 = gsl_matrix_alloc(M,N); gsl_matrix * q1 = gsl_matrix_alloc(M,M); gsl_matrix * r1 = gsl_matrix_alloc(M,N); gsl_matrix * q2 = gsl_matrix_alloc(M,M); gsl_matrix * r2 = gsl_matrix_alloc(M,N); gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N)); gsl_vector * solution1 = gsl_vector_alloc(N); gsl_vector * solution2 = gsl_vector_alloc(N); gsl_vector * u = gsl_vector_alloc(M); gsl_vector * v = gsl_vector_alloc(N); gsl_vector * w = gsl_vector_alloc(M); gsl_matrix_memcpy(qr1,m); gsl_matrix_memcpy(qr2,m); for(i=0; i<N; i++) gsl_vector_set(rhs, i, i+1.0); for(i=0; i<M; i++) gsl_vector_set(u, i, sin(i+1.0)); for(i=0; i<N; i++) gsl_vector_set(v, i, cos(i+2.0) + sin(i*i+3.0)); for(i=0; i<M; i++) { double ui = gsl_vector_get(u, i); for(j=0; j<N; j++) { double vj = gsl_vector_get(v, j); double qij = gsl_matrix_get(qr1, i, j); gsl_matrix_set(qr1, i, j, qij + ui * vj); } } s += gsl_linalg_QR_decomp(qr2, d); s += gsl_linalg_QR_unpack(qr2, d, q2, r2); /* compute w = Q^T u */ for (j = 0; j < M; j++) { double sum = 0; for (i = 0; i < M; i++) sum += gsl_matrix_get (q2, i, j) * gsl_vector_get (u, i); gsl_vector_set (w, j, sum); } s += gsl_linalg_QR_update(q2, r2, w, v); /* compute qr2 = q2 * r2 */ for (i = 0; i < M; i++) { for (j = 0; j< N; j++) { double sum = 0; for (k = 0; k <= GSL_MIN(j,M-1); k++) { double qik = gsl_matrix_get(q2, i, k); double rkj = gsl_matrix_get(r2, k, j); sum += qik * rkj ; } gsl_matrix_set (qr2, i, j, sum); } } for(i=0; i<M; i++) { for(j=0; j<N; j++) { double s1 = gsl_matrix_get(qr1, i, j); double s2 = gsl_matrix_get(qr2, i, j); int foo = check(s1, s2, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, s1, s2); } s += foo; } } gsl_vector_free(solution1); gsl_vector_free(solution2); gsl_vector_free(d); gsl_vector_free(u); gsl_vector_free(v); gsl_vector_free(w); gsl_matrix_free(qr1); gsl_matrix_free(qr2); gsl_matrix_free(q1); gsl_matrix_free(r1); gsl_matrix_free(q2); gsl_matrix_free(r2); gsl_vector_free(rhs); return s; } int test_QR_update(void) { int f; int s = 0; f = test_QR_update_dim(m35, 2 * 512.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update m(3,5)"); s += f; f = test_QR_update_dim(m53, 2 * 512.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update m(5,3)"); s += f; f = test_QR_update_dim(hilb2, 2 * 512.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update hilbert(2)"); s += f; f = test_QR_update_dim(hilb3, 2 * 512.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update hilbert(3)"); s += f; f = test_QR_update_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update hilbert(4)"); s += f; f = test_QR_update_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update hilbert(12)"); s += f; f = test_QR_update_dim(vander2, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update vander(2)"); s += f; f = test_QR_update_dim(vander3, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update vander(3)"); s += f; f = test_QR_update_dim(vander4, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " QR_update vander(4)"); s += f; f = test_QR_update_dim(vander12, 0.0005); /* FIXME: bad accuracy */ gsl_test(f, " QR_update vander(12)"); s += f; return s; } int test_SV_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; size_t i, dim = m->size1; gsl_vector * rhs = gsl_vector_alloc(dim); gsl_matrix * u = gsl_matrix_alloc(dim,dim); gsl_matrix * q = gsl_matrix_alloc(dim,dim); gsl_vector * d = gsl_vector_alloc(dim); gsl_vector * x = gsl_vector_calloc(dim); gsl_matrix_memcpy(u,m); for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_SV_decomp(u, q, d, x); s += gsl_linalg_SV_solve(u, q, d, rhs, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i), actual[i], eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(x); gsl_vector_free(d); gsl_matrix_free(u); gsl_matrix_free(q); gsl_vector_free(rhs); return s; } int test_SV_solve(void) { int f; int s = 0; f = test_SV_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve hilbert(2)"); s += f; f = test_SV_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve hilbert(3)"); s += f; f = test_SV_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve hilbert(4)"); s += f; f = test_SV_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " SV_solve hilbert(12)"); s += f; f = test_SV_solve_dim(vander2, vander2_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve vander(2)"); s += f; f = test_SV_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve vander(3)"); s += f; f = test_SV_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_solve vander(4)"); s += f; f = test_SV_solve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " SV_solve vander(12)"); s += f; return s; } int test_SV_decomp_dim(const gsl_matrix * m, double eps) { int s = 0; double di1; size_t i,j, M = m->size1, N = m->size2; gsl_matrix * v = gsl_matrix_alloc(M,N); gsl_matrix * a = gsl_matrix_alloc(M,N); gsl_matrix * q = gsl_matrix_alloc(N,N); gsl_matrix * dqt = gsl_matrix_alloc(N,N); gsl_vector * d = gsl_vector_alloc(N); gsl_vector * w = gsl_vector_alloc(N); gsl_matrix_memcpy(v,m); s += gsl_linalg_SV_decomp(v, q, d, w); /* Check that singular values are non-negative and in non-decreasing order */ di1 = 0.0; for (i = 0; i < N; i++) { double di = gsl_vector_get (d, i); if (di < 0) { s++; printf("singular value %d = %22.18g < 0\n", i, di); } if(i > 0 && di > di1) { s++; printf("singular value %d = %22.18g vs previous %22.18g\n", i, di, di1); } di1 = di; } /* Scale dqt = D Q^T */ for (i = 0; i < N ; i++) { double di = gsl_vector_get (d, i); for (j = 0; j < N; j++) { double qji = gsl_matrix_get(q, j, i); gsl_matrix_set (dqt, i, j, qji * di); } } /* compute a = v dqt */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, v, dqt, 0.0, a); for(i=0; i<M; i++) { for(j=0; j<N; j++) { double aij = gsl_matrix_get(a, i, j); double mij = gsl_matrix_get(m, i, j); int foo = check(aij, mij, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, aij, mij); } s += foo; } } gsl_vector_free(w); gsl_vector_free(d); gsl_matrix_free(v); gsl_matrix_free(a); gsl_matrix_free(q); gsl_matrix_free(dqt); return s; } int test_SV_decomp(void) { int f; int s = 0; /* M<N not implemented yet */ #if 0 f = test_SV_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp m(3,5)"); s += f; #endif f = test_SV_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp m(5,3)"); s += f; f = test_SV_decomp_dim(moler10, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp moler(10)"); s += f; f = test_SV_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp hilbert(2)"); s += f; f = test_SV_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp hilbert(3)"); s += f; f = test_SV_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp hilbert(4)"); s += f; f = test_SV_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp hilbert(12)"); s += f; f = test_SV_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp vander(2)"); s += f; f = test_SV_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp vander(3)"); s += f; f = test_SV_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp vander(4)"); s += f; f = test_SV_decomp_dim(vander12, 1e-4); gsl_test(f, " SV_decomp vander(12)"); s += f; f = test_SV_decomp_dim(row3, 10 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp row3"); s += f; f = test_SV_decomp_dim(row5, 128 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp row5"); s += f; f = test_SV_decomp_dim(row12, 1024 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp row12"); s += f; { double i1, i2, i3, i4; double lower = -2, upper = 2; for (i1 = lower; i1 <= upper; i1++) { for (i2 = lower; i2 <= upper; i2++) { for (i3 = lower; i3 <= upper; i3++) { for (i4 = lower; i4 <= upper; i4++) { gsl_matrix_set (A22, 0,0, i1); gsl_matrix_set (A22, 0,1, i2); gsl_matrix_set (A22, 1,0, i3); gsl_matrix_set (A22, 1,1, i4); f = test_SV_decomp_dim(A22, 16 * GSL_DBL_EPSILON); gsl_test(f, " SV_decomp A(2x2)(%g, %g, %g, %g)", i1,i2,i3,i4); s += f; } } } } } return s; } int test_cholesky_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; size_t i, dim = m->size1; gsl_vector * rhs = gsl_vector_alloc(dim); gsl_matrix * u = gsl_matrix_alloc(dim,dim); gsl_vector * x = gsl_vector_calloc(dim); gsl_matrix_memcpy(u,m); for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0); s += gsl_linalg_cholesky_decomp(u); s += gsl_linalg_cholesky_solve(u, rhs, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i), actual[i], eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(x); gsl_matrix_free(u); gsl_vector_free(rhs); return s; } int test_cholesky_solve(void) { int f; int s = 0; f = test_cholesky_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_solve hilbert(2)"); s += f; f = test_cholesky_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_solve hilbert(3)"); s += f; f = test_cholesky_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_solve hilbert(4)"); s += f; f = test_cholesky_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " cholesky_solve hilbert(12)"); s += f; return s; } int test_cholesky_decomp_dim(const gsl_matrix * m, double eps) { int s = 0; size_t i,j, M = m->size1, N = m->size2; gsl_matrix * v = gsl_matrix_alloc(M,N); gsl_matrix * a = gsl_matrix_alloc(M,N); gsl_matrix * l = gsl_matrix_alloc(M,N); gsl_matrix * lt = gsl_matrix_alloc(N,N); gsl_matrix_memcpy(v,m); s += gsl_linalg_cholesky_decomp(v); /* Compute L LT */ for (i = 0; i < N ; i++) { for (j = 0; j < N; j++) { double vij = gsl_matrix_get(v, i, j); gsl_matrix_set (l, i, j, i>=j ? vij : 0); gsl_matrix_set (lt, i, j, i<=j ? vij : 0); } } /* compute a = l lt */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, lt, 0.0, a); for(i=0; i<M; i++) { for(j=0; j<N; j++) { double aij = gsl_matrix_get(a, i, j); double mij = gsl_matrix_get(m, i, j); int foo = check(aij, mij, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, aij, mij); } s += foo; } } gsl_matrix_free(v); gsl_matrix_free(a); gsl_matrix_free(l); gsl_matrix_free(lt); return s; } int test_cholesky_decomp(void) { int f; int s = 0; f = test_cholesky_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_decomp hilbert(2)"); s += f; f = test_cholesky_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_decomp hilbert(3)"); s += f; f = test_cholesky_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_decomp hilbert(4)"); s += f; f = test_cholesky_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " cholesky_decomp hilbert(12)"); s += f; return s; } int test_HH_solve_dim(const gsl_matrix * m, const double * actual, double eps) { int s = 0; size_t i, dim = m->size1; gsl_permutation * perm = gsl_permutation_alloc(dim); gsl_matrix * hh = gsl_matrix_alloc(dim,dim); gsl_vector * d = gsl_vector_alloc(dim); gsl_vector * x = gsl_vector_alloc(dim); gsl_matrix_memcpy(hh,m); for(i=0; i<dim; i++) gsl_vector_set(x, i, i+1.0); s += gsl_linalg_HH_svx(hh, x); for(i=0; i<dim; i++) { int foo = check(gsl_vector_get(x, i),actual[i],eps); if( foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(x); gsl_vector_free(d); gsl_matrix_free(hh); gsl_permutation_free(perm); return s; } int test_HH_solve(void) { int f; int s = 0; f = test_HH_solve_dim(hilb2, hilb2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve hilbert(2)"); s += f; f = test_HH_solve_dim(hilb3, hilb3_solution, 128.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve hilbert(3)"); s += f; f = test_HH_solve_dim(hilb4, hilb4_solution, 2.0 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve hilbert(4)"); s += f; f = test_HH_solve_dim(hilb12, hilb12_solution, 0.5); gsl_test(f, " HH_solve hilbert(12)"); s += f; f = test_HH_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve vander(2)"); s += f; f = test_HH_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve vander(3)"); s += f; f = test_HH_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " HH_solve vander(4)"); s += f; f = test_HH_solve_dim(vander12, vander12_solution, 0.05); gsl_test(f, " HH_solve vander(12)"); s += f; return s; } int test_TD_solve_dim(size_t dim, double d, double od, const double * actual, double eps) { int s = 0; size_t i; gsl_vector * offdiag = gsl_vector_alloc(dim-1); gsl_vector * diag = gsl_vector_alloc(dim); gsl_vector * rhs = gsl_vector_alloc(dim); gsl_vector * x = gsl_vector_alloc(dim); for(i=0; i<dim; i++) { gsl_vector_set(diag, i, d); gsl_vector_set(rhs, i, i + 1.0); } for(i=0; i<dim-1; i++) { gsl_vector_set(offdiag, i, od); } s += gsl_linalg_solve_symm_tridiag(diag, offdiag, rhs, x); for(i=0; i<dim; i++) { double si = gsl_vector_get(x, i); double ai = actual[i]; int foo = check(si, ai, eps); if(foo) { printf("%3d[%d]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]); } s += foo; } gsl_vector_free(x); gsl_vector_free(rhs); gsl_vector_free(diag); gsl_vector_free(offdiag); return s; } int test_TD_solve(void) { int f; int s = 0; double actual[16]; actual[0] = 0.0; actual[1] = 2.0; f = test_TD_solve_dim(2, 1.0, 0.5, actual, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " solve_TD dim=2 A"); s += f; actual[0] = 3.0/8.0; actual[1] = 15.0/8.0; f = test_TD_solve_dim(2, 1.0, 1.0/3.0, actual, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " solve_TD dim=2 B"); s += f; actual[0] = 5.0/8.0; actual[1] = 9.0/8.0; actual[2] = 2.0; actual[3] = 15.0/8.0; actual[4] = 35.0/8.0; f = test_TD_solve_dim(5, 1.0, 1.0/3.0, actual, 8.0 * GSL_DBL_EPSILON); gsl_test(f, " solve_TD dim=5"); s += f; return s; } int test_bidiag_decomp_dim(const gsl_matrix * m, double eps) { int s = 0; size_t i,j,k,r, M = m->size1, N = m->size2; gsl_matrix * A = gsl_matrix_alloc(M,N); gsl_matrix * a = gsl_matrix_alloc(M,N); gsl_matrix * b = gsl_matrix_alloc(N,N); gsl_matrix * u = gsl_matrix_alloc(M,N); gsl_matrix * v = gsl_matrix_alloc(N,N); gsl_vector * tau1 = gsl_vector_alloc(N); gsl_vector * tau2 = gsl_vector_alloc(N-1); gsl_vector * d = gsl_vector_alloc(N); gsl_vector * sd = gsl_vector_alloc(N-1); gsl_matrix_memcpy(A,m); s += gsl_linalg_bidiag_decomp(A, tau1, tau2); s += gsl_linalg_bidiag_unpack(A, tau1, u, tau2, v, d, sd); gsl_matrix_set_zero(b); for (i = 0; i < N; i++) gsl_matrix_set(b, i,i, gsl_vector_get(d,i)); for (i = 0; i < N-1; i++) gsl_matrix_set(b, i,i+1, gsl_vector_get(sd,i)); /* Compute A = U B V^T */ for (i = 0; i < M ; i++) { for (j = 0; j < N; j++) { double sum = 0; for (k = 0; k < N; k++) { for (r = 0; r < N; r++) { sum += gsl_matrix_get(u, i, k) * gsl_matrix_get (b, k, r) * gsl_matrix_get(v, j, r); } } gsl_matrix_set (a, i, j, sum); } } for(i=0; i<M; i++) { for(j=0; j<N; j++) { double aij = gsl_matrix_get(a, i, j); double mij = gsl_matrix_get(m, i, j); int foo = check(aij, mij, eps); if(foo) { printf("(%3d,%3d)[%d,%d]: %22.18g %22.18g\n", M, N, i,j, aij, mij); } s += foo; } } gsl_matrix_free(A); gsl_matrix_free(a); gsl_matrix_free(u); gsl_matrix_free(v); gsl_matrix_free(b); gsl_vector_free(tau1); gsl_vector_free(tau2); gsl_vector_free(d); gsl_vector_free(sd); return s; } int test_bidiag_decomp(void) { int f; int s = 0; f = test_bidiag_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp m(5,3)"); s += f; f = test_bidiag_decomp_dim(m97, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp m(9,7)"); s += f; f = test_bidiag_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp hilbert(2)"); s += f; f = test_bidiag_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp hilbert(3)"); s += f; f = test_bidiag_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp hilbert(4)"); s += f; f = test_bidiag_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON); gsl_test(f, " bidiag_decomp hilbert(12)"); s += f; return s; } int main(void) { gsl_ieee_env_setup (); m35 = create_general_matrix(3,5); m53 = create_general_matrix(5,3); m97 = create_general_matrix(9,7); s35 = create_singular_matrix(3,5); s53 = create_singular_matrix(5,3); hilb2 = create_hilbert_matrix(2); hilb3 = create_hilbert_matrix(3); hilb4 = create_hilbert_matrix(4); hilb12 = create_hilbert_matrix(12); vander2 = create_vandermonde_matrix(2); vander3 = create_vandermonde_matrix(3); vander4 = create_vandermonde_matrix(4); vander12 = create_vandermonde_matrix(12); moler10 = create_moler_matrix(10); c7 = create_complex_matrix(7); row3 = create_row_matrix(3,3); row5 = create_row_matrix(5,5); row12 = create_row_matrix(12,12); A22 = create_2x2_matrix (0.0, 0.0, 0.0, 0.0); /* Matmult now obsolete */ #ifdef MATMULT gsl_test(test_matmult(), "Matrix Multiply"); gsl_test(test_matmult_mod(), "Matrix Multiply with Modification"); #endif gsl_test(test_bidiag_decomp(), "Bidiagonal Decomposition"); gsl_test(test_LU_solve(), "LU Decomposition and Solve"); gsl_test(test_LUc_solve(), "Complex LU Decomposition and Solve"); gsl_test(test_QR_decomp(), "QR Decomposition"); gsl_test(test_QR_solve(), "QR Solve"); gsl_test(test_QR_lssolve(), "QR LS Solve"); gsl_test(test_QR_update(), "QR Rank-1 Update"); gsl_test(test_QRPT_decomp(), "QRPT Decomposition"); gsl_test(test_QRPT_solve(), "QRPT Solve"); gsl_test(test_SV_decomp(), "Singular Value Decomposition"); gsl_test(test_SV_solve(), "SVD Solve"); gsl_test(test_cholesky_decomp(),"Cholesky Decomposition"); gsl_test(test_cholesky_solve(), "Cholesky Solve"); gsl_test(test_HH_solve(), "Householder solve"); gsl_test(test_TD_solve(), "Tridiagonal solve"); gsl_matrix_free(hilb2); gsl_matrix_free(hilb3); gsl_matrix_free(hilb4); gsl_matrix_free(hilb12); gsl_matrix_free(vander2); gsl_matrix_free(vander3); gsl_matrix_free(vander4); gsl_matrix_free(vander12); gsl_matrix_complex_free(c7); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.6213656388, "avg_line_length": 27.3045379989, "ext": "c", "hexsha": "5aab682fb69e4fc3313c3017f4da407f2b7c3414", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/linalg/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/linalg/test.c", "max_line_length": 105, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/linalg/test.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 18455, "size": 49940 }
/* ** detrending, fit polynomial or order 1 (linear), 3 or 5 ** G.Lohmann, Aug 2016, MPI-KYB */ #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 <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_multifit.h> #define ABS(x) ((x) < 0 ? -(x) : (x)) void VGetStats(double *data,int nt,int i0,double *ave,double *sigma) { int i; double u,sum1,sum2,nx; sum1 = sum2 = 0; for (i=i0; i<nt; i++) { u = data[i]; sum1 += u; sum2 += u*u; } nx = (double)nt; double mean = sum1/nx; (*ave) = mean; (*sigma) = sqrt((sum2 - nx * mean * mean) / (nx - 1.0)); } void VDetrend(VAttrList list,VFloat minval,VShort type,VShort i0) { int slice,row,col,i,j; /* get image dimensions */ int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); int nrows = VImageNRows (src[0]); int ncols = VImageNColumns (src[0]); int ntimesteps = VImageNBands (src[0]); if (nslices < 1) VError(" no slices"); double smax = VPixelMaxValue(src[0]); double smin = VPixelMinValue(src[0]); /* ini regression matrix */ int p = 4; if (type == 2) p = 6; gsl_vector *y = gsl_vector_calloc(ntimesteps); gsl_vector *c = gsl_vector_calloc(p); gsl_matrix *X = gsl_matrix_calloc(ntimesteps,p); for (j=0; j<ntimesteps; j++) { double u = (double)j; gsl_matrix_set(X,j,0,1); gsl_matrix_set(X,j,1,u); gsl_matrix_set(X,j,2,u*u); gsl_matrix_set(X,j,3,u*u*u); if (type == 2) { gsl_matrix_set(X,j,4,u*u*u*u); gsl_matrix_set(X,j,5,u*u*u*u*u); } } gsl_multifit_linear_workspace *workspace = gsl_multifit_linear_alloc ((size_t)ntimesteps,(size_t)p); gsl_matrix *cov = gsl_matrix_calloc(p,p); double *x = (double *) VCalloc(ntimesteps,sizeof(double)); for (j=0; j<ntimesteps; j++) x[j] = (double)j; gsl_vector *w = gsl_vector_calloc(ntimesteps); for (j=0; j<ntimesteps; j++) w->data[j] = (double)1.0; for (i=0; i<=i0; i++) w->data[i] = 0.01; /* ignore initial time steps */ /* remove baseline drift */ double c0=0,c1=0,c2=0,c3=0,c4=0,c5=0,cov00,cov01,cov11,chisq; for (slice=0; slice<nslices; slice++) { if (slice%5==0)fprintf(stderr," slice %5d of %d\r",slice,nslices); for (row=0; row<nrows; row++) { for (col=0; col<ncols; col++) { for (j=0; j<ntimesteps; j++) { y->data[j] = VGetPixel(src[slice],j,row,col); } if (y->data[0] < minval+1.0e-8) { for (j=0; j<ntimesteps; j++) VSetPixel(src[slice],j,row,col,0.0); goto skip; } double mean=0,sigma=0; VGetStats(y->data,ntimesteps,i0,&mean,&sigma); /* remove linear trend */ if (type == 0) { gsl_fit_wlinear (x,1,w->data,1,y->data,1,j,&c0,&c1,&cov00,&cov01,&cov11,&chisq); for (j=0; j<i0; j++) y->data[j] = 0; for (j=i0; j<ntimesteps; j++) { y->data[j] = y->data[j] - (c0 + c1*x[j]); } } /* remove cubic polynomial */ if (type == 1) { gsl_multifit_wlinear (X,w,y,c,cov,&chisq,workspace); c0 = c->data[0]; c1 = c->data[1]; c2 = c->data[2]; c3 = c->data[3]; for (j=0; j<i0; j++) y->data[j] = 0; for (j=i0; j<ntimesteps; j++) { double u = x[j]; y->data[j] = y->data[j] - (c0 + c1*u + c2*u*u + c3*u*u*u); } } /* remove polynomial of order 5 */ if (type == 2) { gsl_multifit_wlinear (X,w,y,c,cov,&chisq,workspace); c0 = c->data[0]; c1 = c->data[1]; c2 = c->data[2]; c3 = c->data[3]; c4 = c->data[4]; c5 = c->data[5]; for (j=0; j<i0; j++) y->data[j] = 0; for (j=i0; j<ntimesteps; j++) { double u = x[j]; double u2 = u*u; double u3 = u2*u; y->data[j] = y->data[j] - (c0 + c1*u + c2*u2 + c3*u3 + c4*u2*u2 + c5*u2*u3); } } double a = 1.25; double sum=0,nx=0; for (j=i0; j<ntimesteps; j++) { sum += a*y->data[j] + mean; nx++; } if (nx > 0) sum /= nx; for (j=0; j<i0; j++) VSetPixel(src[slice],j,row,col,sum); for (j=i0; j<ntimesteps; j++) { double u = a*y->data[j] + mean; if (u > smax) u = smax; if (u < smin) u = smin; VSetPixel(src[slice],j,row,col,u); } skip: ; } } } fprintf(stderr,"\n"); }
{ "alphanum_fraction": 0.5741354808, "avg_line_length": 24.9822485207, "ext": "c", "hexsha": "650e00e0e0025a6cdcc4762f89ac9880ba09c165", "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/vdetrend/Detrend.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/vdetrend/Detrend.c", "max_line_length": 102, "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/vdetrend/Detrend.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": 1628, "size": 4222 }
/// \file /// A helper class defining numerical complex matrices for use with BLAS. /// Needs a CBLAS compatible BLAS library! #pragma once #include <array> #include <complex> #include <iomanip> #include <iostream> #include <limits> #ifndef USE_MKL #include <cblas.h> #else #include <mkl.h> #endif // ********************************************************************** /// Numerical complex matrix class /// \brief This class defines a complex matrix with n rows and n columns /// /// This class implements a complex matrix. The entries are stored in an /// std::array in row-major order, so that it is easy to implement linear /// algebra functions using the standard CBLAS interface. // ********************************************************************** template <std::size_t n> class nummat { private: std::array<std::complex<double>, n * n> mat; public: // ********************************************************************** // Constructors // ********************************************************************** constexpr nummat() { mat.fill(std::complex<double>(0.0)); } /// Construct a matrix from an array constexpr nummat(std::array<std::complex<double>, n * n> const &init) : mat(init) { } constexpr nummat(std::complex<double> const &c) { mat.fill(std::complex<double>(0.0)); for (auto i = 0LU; i < n; ++i) { mat[i + n * i] = c; } } ///! Copy constructor constexpr nummat(nummat<n> const &orig) = default; // ********************************************************************** // Methods // ********************************************************************** /// Access elements of matrix std::complex<double> &operator()(std::size_t const i, std::size_t const j) { return mat[i * n + j]; } constexpr std::complex<double> const &operator()(std::size_t const i, std::size_t const j) const { return mat[i * n + j]; } std::complex<double> *data() noexcept { return mat.data(); } std::complex<double> const *data() const noexcept { return mat.data(); } /// Matrix multiplication constexpr nummat<n> operator*(nummat<n> const &rhs) const { constexpr std::complex<double> alpha(1.0); constexpr std::complex<double> beta(0.0); nummat<n> res; cblas_zgemm(CBLAS_ORDER::CblasRowMajor, CBLAS_TRANSPOSE::CblasNoTrans, CBLAS_TRANSPOSE::CblasNoTrans, n, n, n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(this->data()), n, reinterpret_cast<const double *>(rhs.data()), n, reinterpret_cast<const double *>(&beta), reinterpret_cast<double *>(res.data()), n); return res; } /// Matrix subtraction constexpr nummat<n> operator-(nummat<n> const &rhs) const { constexpr std::complex<double> alpha(-1.0); nummat<n> res(this->mat); cblas_zaxpy(n * n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(rhs.data()), 1, reinterpret_cast<double *>(res.data()), 1); return res; } /// Matrix addition constexpr nummat<n> operator+(nummat<n> const &rhs) const { std::complex<double> alpha(1.0); nummat<n> res(this->mat); cblas_zaxpy(n * n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(rhs.data()), 1, reinterpret_cast<double *>(res.data()), 1); return res; } /// Operator "+=" for matrix addition void operator+=(nummat<n> const &rhs) { constexpr std::complex<double> alpha(1.0); cblas_zaxpy(n * n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(rhs.data()), 1, reinterpret_cast<double *>(this->data()), 1); } /// Operator "-=" for matrix subtraction void operator-=(nummat<n> const &rhs) { constexpr std::complex<double> alpha(-1.0); cblas_zaxpy(n * n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(rhs.data()), 1, reinterpret_cast<double *>(this->data()), 1); } /// Scalar multiplication (from right) nummat<n> operator*(std::complex<double> const &rhs) const { nummat<n> res(this->mat); cblas_zscal(n * n, reinterpret_cast<const double *>(&rhs), reinterpret_cast<double *>(res.data()), 1); return res; } /// Operator "*=" for scalar multiplication. (Rescaling) void operator*=(std::complex<double> const &a) { cblas_zscal(n * n, reinterpret_cast<const double *>(&a), reinterpret_cast<double *>(this->data()), 1); } /// Scalar division constexpr nummat<n> operator/(std::complex<double> const &rhs) const { return (*this) * (1. / rhs); } /// Equality check \todo Better float equal? constexpr bool operator==(nummat<n> const &right) const { bool res = true; for (auto i = 0LU; i < n; ++i) { for (auto j = 0LU; j < n; ++j) { res = ((*this)(i, j) == right(i, j)); if (not res) return res; } } return res; } // Multiplication with Hermitian conjugate constexpr nummat<n> mult_conj(nummat<n> const &rhs) const { constexpr std::complex<double> alpha(1.0); constexpr std::complex<double> beta(0.0); nummat<n> res; cblas_zgemm(CBLAS_ORDER::CblasRowMajor, CBLAS_TRANSPOSE::CblasNoTrans, CBLAS_TRANSPOSE::CblasConjTrans, n, n, n, reinterpret_cast<const double *>(&alpha), reinterpret_cast<const double *>(this->data()), n, reinterpret_cast<const double *>(rhs.data()), n, reinterpret_cast<const double *>(&beta), reinterpret_cast<double *>(res.data()), n); return res; } // Real part // constexpr nummat<n> real() const { // nummat<n> res; // for (auto i=0LU; i<n;++i){ // for(auto j=0LU; j<n;++j){ // res(i,j)= this->mat[i*n+j]; // } // } // return res; // } /// Hermitian conjugate constexpr nummat<n> dagger() const { nummat<n> res; for (auto i = 0LU; i < n; ++i) { for (auto j = 0LU; j < n; ++j) { res(i, j) = std::conj(this->mat[j * n + i]); } } return res; } /// Matrix inverse \todo Implement for general matrix constexpr nummat<n> inverse() const { if (*this == nummat<n>(1.)) { return nummat<n>(this->mat); } else { throw std::runtime_error("Inverse only implemented for unit matrix!"); } } /// Matrix log \todo Implement for general matrix constexpr nummat<n> log() const { nummat<n> res(0.0); if (*this == nummat<n>(1.)) { return res; } else { throw std::runtime_error("Log only implemented for unit matrix!"); } } // ********************************************************************** // Friends // ********************************************************************** /// Multiplication with scalar from the left friend constexpr nummat<n> operator*(std::complex<double> const &lhs, nummat<n> const &rhs) { auto res = rhs; return res * lhs; } /// Simple printing of nummat friend std::ostream &operator<<(std::ostream &stream, nummat<n> const &nm) { stream.precision(6); for (auto i = 0ul; i < n * n; ++i) { stream << std::fixed << "(" << std::setw(13) << std::real(nm.mat[i]) << "," << std::setw(13) << std::imag(nm.mat[i]) << ")\t"; if (0 == (i + 1) % n) { stream << "\n"; } } return stream; } }; // Non-member functions /// Trace template <std::size_t n> constexpr std::complex<double> trace(nummat<n> const &M) { std::complex<double> res(0.0); for (auto i = 0LU; i < n; ++i) { res += M(i, i); } return res; } /// Dagger (needed as a non-member function for expansions) template <std::size_t n> constexpr nummat<n> dagger(nummat<n> const &M) { return M.dagger(); } /// Inverse (needed as a non-member function for expansions) /// /// Wraps member function template <std::size_t n> constexpr nummat<n> inverse(nummat<n> const &M) { return M.inverse(); } /// Matrix Log (needed as a non-member function for expansions) /// /// Wraps member function template <std::size_t n> constexpr nummat<n> log(nummat<n> const &M) { return M.log(); } /// Construct diagonal matrix from array template <std::size_t n> constexpr nummat<n> diag(std::array<std::complex<double>, n> const &init) { nummat<n> M; for (auto i = 0LU; i < n; ++i) { M(i, i) = init[i]; } return M; } /// Frobenius norm of a matrix template <std::size_t n> double normF(nummat<n> const &M) { return cblas_dznrm2(n * n, reinterpret_cast<const double *>(M.data()), 1); } /// Matrix exponential /// (Via Taylor series. This is probably neither fast nor stable.) template <std::size_t n> nummat<n> exp(nummat<n> const &M, const double &error = std::numeric_limits<double>::epsilon(), const size_t &maxiter = 100LU) { double prec_goal = error; // Sanity check if (prec_goal < std::numeric_limits<double>::epsilon()) { prec_goal = std::numeric_limits<double>::epsilon(); std::cout << "Warning! Precision goal was reset to machine epsilon in matrix exp" << prec_goal << std::endl; } nummat<n> res{ 1.0 }, old{ M }, aux{ 1.0 }; double eps = 1.0; double fac = 1.0; size_t iter = 0LU; while (eps > error && iter < maxiter) { ++iter; fac *= static_cast<double>(iter); aux = aux * M; res += aux / fac; // Error estimate. (Quite pessimistic) eps = normF(old - res); // std::cout << "Error: " << eps << std::endl; old = res; } // std::cout << iter << std::endl; return res; } /// Inflates compressed Hermitian matrix (CblasUpper format) to a dense matrix template <size_t NN> void inflate(nummat<NN> &M) { for (auto i = 1LU; i < NN; ++i) { for (auto j = 0LU; j < i; ++j) { M(i, j) = std::conj(M(j, i)); } } }
{ "alphanum_fraction": 0.5539157812, "avg_line_length": 25.1584158416, "ext": "h", "hexsha": "e61640e7c2a1c3682bd53be2a4bebc92db6bbc4a", "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": "278c3e1ebb49b5a89884b7dacba8021c699b4e64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "puv13/nsptpp", "max_forks_repo_path": "src/nummat.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "278c3e1ebb49b5a89884b7dacba8021c699b4e64", "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": "puv13/nsptpp", "max_issues_repo_path": "src/nummat.h", "max_line_length": 78, "max_stars_count": 3, "max_stars_repo_head_hexsha": "278c3e1ebb49b5a89884b7dacba8021c699b4e64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "puv13/nsptpp", "max_stars_repo_path": "src/nummat.h", "max_stars_repo_stars_event_max_datetime": "2021-12-15T13:22:57.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-11T05:51:42.000Z", "num_tokens": 2666, "size": 10164 }
/* multifit/work.c * * Copyright (C) 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> gsl_multifit_linear_workspace * gsl_multifit_linear_alloc (size_t n, size_t p) { gsl_multifit_linear_workspace *w; w = (gsl_multifit_linear_workspace *) malloc (sizeof (gsl_multifit_linear_workspace)); if (w == 0) { GSL_ERROR_VAL ("failed to allocate space for multifit_linear struct", GSL_ENOMEM, 0); } w->n = n; /* number of observations */ w->p = p; /* number of parameters */ w->A = gsl_matrix_alloc (n, p); if (w->A == 0) { free (w); GSL_ERROR_VAL ("failed to allocate space for A", GSL_ENOMEM, 0); } w->Q = gsl_matrix_alloc (p, p); if (w->Q == 0) { gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for Q", GSL_ENOMEM, 0); } w->QSI = gsl_matrix_alloc (p, p); if (w->QSI == 0) { gsl_matrix_free (w->Q); gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for QSI", GSL_ENOMEM, 0); } w->S = gsl_vector_alloc (p); if (w->S == 0) { gsl_matrix_free (w->QSI); gsl_matrix_free (w->Q); gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for S", GSL_ENOMEM, 0); } w->t = gsl_vector_alloc (n); if (w->t == 0) { gsl_vector_free (w->S); gsl_matrix_free (w->QSI); gsl_matrix_free (w->Q); gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for t", GSL_ENOMEM, 0); } w->xt = gsl_vector_calloc (p); if (w->xt == 0) { gsl_vector_free (w->t); gsl_vector_free (w->S); gsl_matrix_free (w->QSI); gsl_matrix_free (w->Q); gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for xt", GSL_ENOMEM, 0); } w->D = gsl_vector_calloc (p); if (w->D == 0) { gsl_vector_free (w->D); gsl_vector_free (w->t); gsl_vector_free (w->S); gsl_matrix_free (w->QSI); gsl_matrix_free (w->Q); gsl_matrix_free (w->A); free (w); GSL_ERROR_VAL ("failed to allocate space for xt", GSL_ENOMEM, 0); } return w; } void gsl_multifit_linear_free (gsl_multifit_linear_workspace * work) { gsl_matrix_free (work->A); gsl_matrix_free (work->Q); gsl_matrix_free (work->QSI); gsl_vector_free (work->S); gsl_vector_free (work->t); gsl_vector_free (work->xt); gsl_vector_free (work->D); free (work); }
{ "alphanum_fraction": 0.6174977605, "avg_line_length": 24.9925373134, "ext": "c", "hexsha": "f05e3ff4b5da9bd0ee5c6308a0b6141585c7b1ba", "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/multifit/work.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/multifit/work.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/multifit/work.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": 976, "size": 3349 }
#ifndef ADD_TO_TASK_INCLUDE #define ADD_TO_TASK_INCLUDE #include <functional> #include <initializer_list> #include <optional> #include <string> #include <utility> #include <vector> #include <gsl/pointers> #include "base-utils/nonEmptyString.h" #include "core/task.h" namespace execHelper::test { using AddToTaskFunction = std::function<core::TaskCollection(std::string)>; inline void addToTask(const std::string& value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { task->append(func(value)); } inline void addToTask(const NonEmptyString& value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { task->append(func(*value)); } inline void addToTask(bool value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { if(value) { task->append(func("true")); } else { task->append(func("false")); } } inline void addToTask(const std::vector<std::string>& value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { std::for_each( value.begin(), value.end(), [&task, func](const auto& element) { task->append(func(element)); }); } inline void addToTask(const std::pair<std::string, std::string>& value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { task->append(func(value.first + "=" + value.second)); } template <typename T> inline void addToTask(const std::optional<T>& value, gsl::not_null<core::Task*> task, AddToTaskFunction func) { if(value) { addToTask(*value, task, func); } } template <typename T> inline void addToTask(const std::optional<T>& value, gsl::not_null<core::Task*> task, AddToTaskFunction func, const T& defaultValue) { if(value) { addToTask(*value, task, func); } else { addToTask(defaultValue, task, func); } } } // namespace execHelper::test #endif /* ADD_TO_TASK_INCLUDE */
{ "alphanum_fraction": 0.6286276439, "avg_line_length": 28.6338028169, "ext": "h", "hexsha": "222a8f05577857ab182afdd43aa8c51672010c77", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "test/utils/include/utils/addToTask.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "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": "exec-helper/source", "max_issues_repo_path": "test/utils/include/utils/addToTask.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "test/utils/include/utils/addToTask.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 476, "size": 2033 }
#ifndef __gslSpline_ #define __gslSpline__ #include "include/stdinc.h" #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_integration.h> class gslSpline { protected: const gsl_interp_type *spline_type; gsl_interp_accel *acc; gsl_spline *spl; public: gslSpline(vector<double> &x, vector<double> &y) { spline_type = gsl_interp_cspline; spl = gsl_spline_alloc(spline_type, x.size()); acc = gsl_interp_accel_alloc(); gsl_spline_init(spl, &x[0], &y[0], x.size()); } ~gslSpline() { gsl_interp_accel_free(acc); gsl_spline_free(spl); } void init(vector<double> &x, vector<double> &y) { gsl_interp_accel_free(acc); gsl_spline_free(spl); spl = gsl_spline_alloc(spline_type, x.size()); acc = gsl_interp_accel_alloc(); gsl_spline_init(spl, &x[0], &y[0], x.size()); } inline real eval (double xc) {return gsl_spline_eval(spl, xc, acc);} inline real deriv (double xc) {return gsl_spline_eval_deriv(spl, xc, acc);} inline real deriv2(double xc) {return gsl_spline_eval_deriv2(spl, xc, acc);} inline real integ (double x_lo, double x_up) { return gsl_spline_eval_integ(spl, x_lo, x_up, acc); } }; #endif // __gslSpline__
{ "alphanum_fraction": 0.6905901116, "avg_line_length": 28.5, "ext": "h", "hexsha": "5bd73e083bb5f5243acd871f1390e1087ad9d58a", "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/mmams/src/mmas2/src/gsl/gslSpline.h", "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/mmams/src/mmas2/src/gsl/gslSpline.h", "max_line_length": 79, "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/mmams/src/mmas2/src/gsl/gslSpline.h", "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": 381, "size": 1254 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef NOMPI #include <mpi.h> #endif #include <sys/types.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include "allvars.h" #include "proto.h" /*! \file begrun.c * \brief initial set-up of a simulation run * * This file contains various functions to initialize a simulation run. In * particular, the parameterfile is read in and parsed, the initial * conditions or restart files are read, and global variables are * initialized to their proper values. */ /*! This function performs the initial set-up of the simulation. First, the * parameterfile is set, then routines for setting units, reading * ICs/restart-files are called, auxialiary memory is allocated, etc. */ void begrun(void) { struct global_data_all_processes all; if(ThisTask == 0) { printf("\nThis is Gadget, version `%s'.\n", GADGETVERSION); printf("\nRunning on %d processors.\n", NTask); } read_parameter_file(ParameterFile); /* ... read in parameters for this run */ allocate_commbuffers(); /* ... allocate buffer-memory for particle exchange during force computation */ set_units(); #if defined(PERIODIC) && (!defined(PMGRID) || defined(FORCETEST)) ewald_init(); #endif open_outputfiles(); random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(random_generator, 42); /* start-up seed */ #ifdef PMGRID long_range_init(); #endif All.TimeLastRestartFile = CPUThisRun; if(RestartFlag == 0 || RestartFlag == 2) { set_random_numbers(); init(); /* ... read in initial model */ } else { all = All; /* save global variables. (will be read from restart file) */ restart(RestartFlag); /* ... read restart file. Note: This also resets all variables in the struct `All'. However, during the run, some variables in the parameter file are allowed to be changed, if desired. These need to copied in the way below. Note: All.PartAllocFactor is treated in restart() separately. */ All.MinSizeTimestep = all.MinSizeTimestep; All.MaxSizeTimestep = all.MaxSizeTimestep; All.BufferSize = all.BufferSize; All.BunchSizeForce = all.BunchSizeForce; All.BunchSizeDensity = all.BunchSizeDensity; All.BunchSizeHydro = all.BunchSizeHydro; All.BunchSizeDomain = all.BunchSizeDomain; All.TimeLimitCPU = all.TimeLimitCPU; All.ResubmitOn = all.ResubmitOn; All.TimeBetSnapshot = all.TimeBetSnapshot; All.TimeBetStatistics = all.TimeBetStatistics; All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile; All.ErrTolIntAccuracy = all.ErrTolIntAccuracy; All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac; All.ErrTolForceAcc = all.ErrTolForceAcc; All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion; All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion; All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel; All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency; All.SnapFormat = all.SnapFormat; All.NumFilesPerSnapshot = all.NumFilesPerSnapshot; All.MaxNumNgbDeviation = all.MaxNumNgbDeviation; All.ArtBulkViscConst = all.ArtBulkViscConst; All.ArtBulkViscBeta = 2*all.ArtBulkViscConst; All.OutputListOn = all.OutputListOn; All.CourantFac = all.CourantFac; All.OutputListLength = all.OutputListLength; memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength); strcpy(All.ResubmitCommand, all.ResubmitCommand); strcpy(All.OutputListFilename, all.OutputListFilename); strcpy(All.OutputDir, all.OutputDir); strcpy(All.RestartFile, all.RestartFile); strcpy(All.EnergyFile, all.EnergyFile); strcpy(All.InfoFile, all.InfoFile); strcpy(All.CpuFile, all.CpuFile); strcpy(All.TimingsFile, all.TimingsFile); strcpy(All.SnapshotFileBase, all.SnapshotFileBase); if(All.TimeMax != all.TimeMax) readjust_timebase(All.TimeMax, all.TimeMax); } #ifdef PMGRID long_range_init_regionsize(); #endif if(All.ComovingIntegrationOn) init_drift_table(); if(RestartFlag == 2) All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 1); else All.Ti_nextoutput = find_next_outputtime(All.Ti_Current); All.TimeLastRestartFile = CPUThisRun; } /*! Computes conversion factors between internal code units and the * cgs-system. */ void set_units(void) { double meanweight; All.UnitTime_in_s = All.UnitLength_in_cm / All.UnitVelocity_in_cm_per_s; All.UnitTime_in_Megayears = All.UnitTime_in_s / SEC_PER_MEGAYEAR; if(All.GravityConstantInternal == 0) All.G = GRAVITY / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g * pow(All.UnitTime_in_s, 2); else All.G = All.GravityConstantInternal; All.UnitDensity_in_cgs = All.UnitMass_in_g / pow(All.UnitLength_in_cm, 3); All.UnitPressure_in_cgs = All.UnitMass_in_g / All.UnitLength_in_cm / pow(All.UnitTime_in_s, 2); All.UnitCoolingRate_in_cgs = All.UnitPressure_in_cgs / All.UnitTime_in_s; All.UnitEnergy_in_cgs = All.UnitMass_in_g * pow(All.UnitLength_in_cm, 2) / pow(All.UnitTime_in_s, 2); /* convert some physical input parameters to internal units */ All.Hubble = HUBBLE * All.UnitTime_in_s; if(ThisTask == 0) { printf("\nHubble (internal units) = %g\n", All.Hubble); printf("G (internal units) = %g\n", All.G); printf("UnitMass_in_g = %g \n", All.UnitMass_in_g); printf("UnitTime_in_s = %g \n", All.UnitTime_in_s); printf("UnitVelocity_in_cm_per_s = %g \n", All.UnitVelocity_in_cm_per_s); printf("UnitDensity_in_cgs = %g \n", All.UnitDensity_in_cgs); printf("UnitEnergy_in_cgs = %g \n", All.UnitEnergy_in_cgs); printf("\n"); } meanweight = 4.0 / (1 + 3 * HYDROGEN_MASSFRAC); /* note: we assume neutral gas here */ #ifdef ISOTHERM_EQS All.MinEgySpec = 0; #else All.MinEgySpec = 1 / meanweight * (1.0 / GAMMA_MINUS1) * (BOLTZMANN / PROTONMASS) * All.MinGasTemp; All.MinEgySpec *= All.UnitMass_in_g / All.UnitEnergy_in_cgs; #endif } /*! This function opens various log-files that report on the status and * performance of the simulstion. On restart from restart-files * (start-option 1), the code will append to these files. */ void open_outputfiles(void) { char mode[2], buf[200]; if(ThisTask != 0) /* only the root processor writes to the log files */ return; if(RestartFlag == 0) strcpy(mode, "w"); else strcpy(mode, "a"); sprintf(buf, "%s%s", All.OutputDir, All.CpuFile); if(!(FdCPU = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.InfoFile); if(!(FdInfo = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.EnergyFile); if(!(FdEnergy = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } sprintf(buf, "%s%s", All.OutputDir, All.TimingsFile); if(!(FdTimings = fopen(buf, mode))) { printf("error in opening file '%s'\n", buf); endrun(1); } #ifdef FORCETEST if(RestartFlag == 0) { sprintf(buf, "%s%s", All.OutputDir, "forcetest.txt"); if(!(FdForceTest = fopen(buf, "w"))) { printf("error in opening file '%s'\n", buf); endrun(1); } fclose(FdForceTest); } #endif } /*! This function closes the global log-files. */ void close_outputfiles(void) { if(ThisTask != 0) /* only the root processor writes to the log files */ return; fclose(FdCPU); fclose(FdInfo); fclose(FdEnergy); fclose(FdTimings); #ifdef FORCETEST fclose(FdForceTest); #endif } /*! This function parses the parameterfile in a simple way. Each paramater * is defined by a keyword (`tag'), and can be either of type double, int, * or character string. The routine makes sure that each parameter * appears exactly once in the parameterfile, otherwise error messages are * produced that complain about the missing parameters. */ void read_parameter_file(char *fname) { #define DOUBLE 1 #define STRING 2 #define INT 3 #define MAXTAGS 300 FILE *fd, *fdout; char buf[200], buf1[200], buf2[200], buf3[400]; int i, j, nt; int id[MAXTAGS]; void *addr[MAXTAGS]; char tag[MAXTAGS][50]; int errorFlag = 0; if(sizeof(long long) != 8) { if(ThisTask == 0) printf("\nType `long long' is not 64 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(int) != 4) { if(ThisTask == 0) printf("\nType `int' is not 32 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(float) != 4) { if(ThisTask == 0) printf("\nType `float' is not 32 bit on this platform. Stopping.\n\n"); endrun(0); } if(sizeof(double) != 8) { if(ThisTask == 0) printf("\nType `double' is not 64 bit on this platform. Stopping.\n\n"); endrun(0); } if(ThisTask == 0) /* read parameter file on process 0 */ { nt = 0; strcpy(tag[nt], "InitCondFile"); addr[nt] = All.InitCondFile; id[nt++] = STRING; strcpy(tag[nt], "OutputDir"); addr[nt] = All.OutputDir; id[nt++] = STRING; strcpy(tag[nt], "SnapshotFileBase"); addr[nt] = All.SnapshotFileBase; id[nt++] = STRING; strcpy(tag[nt], "EnergyFile"); addr[nt] = All.EnergyFile; id[nt++] = STRING; strcpy(tag[nt], "CpuFile"); addr[nt] = All.CpuFile; id[nt++] = STRING; strcpy(tag[nt], "InfoFile"); addr[nt] = All.InfoFile; id[nt++] = STRING; strcpy(tag[nt], "TimingsFile"); addr[nt] = All.TimingsFile; id[nt++] = STRING; strcpy(tag[nt], "RestartFile"); addr[nt] = All.RestartFile; id[nt++] = STRING; strcpy(tag[nt], "ResubmitCommand"); addr[nt] = All.ResubmitCommand; id[nt++] = STRING; strcpy(tag[nt], "OutputListFilename"); addr[nt] = All.OutputListFilename; id[nt++] = STRING; strcpy(tag[nt], "OutputListOn"); addr[nt] = &All.OutputListOn; id[nt++] = INT; strcpy(tag[nt], "Omega0"); addr[nt] = &All.Omega0; id[nt++] = DOUBLE; strcpy(tag[nt], "OmegaBaryon"); addr[nt] = &All.OmegaBaryon; id[nt++] = DOUBLE; strcpy(tag[nt], "OmegaLambda"); addr[nt] = &All.OmegaLambda; id[nt++] = DOUBLE; strcpy(tag[nt], "HubbleParam"); addr[nt] = &All.HubbleParam; id[nt++] = DOUBLE; strcpy(tag[nt], "BoxSize"); addr[nt] = &All.BoxSize; id[nt++] = DOUBLE; strcpy(tag[nt], "PeriodicBoundariesOn"); addr[nt] = &All.PeriodicBoundariesOn; id[nt++] = INT; strcpy(tag[nt], "TimeOfFirstSnapshot"); addr[nt] = &All.TimeOfFirstSnapshot; id[nt++] = DOUBLE; strcpy(tag[nt], "CpuTimeBetRestartFile"); addr[nt] = &All.CpuTimeBetRestartFile; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBetStatistics"); addr[nt] = &All.TimeBetStatistics; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBegin"); addr[nt] = &All.TimeBegin; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeMax"); addr[nt] = &All.TimeMax; id[nt++] = DOUBLE; strcpy(tag[nt], "TimeBetSnapshot"); addr[nt] = &All.TimeBetSnapshot; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitVelocity_in_cm_per_s"); addr[nt] = &All.UnitVelocity_in_cm_per_s; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitLength_in_cm"); addr[nt] = &All.UnitLength_in_cm; id[nt++] = DOUBLE; strcpy(tag[nt], "UnitMass_in_g"); addr[nt] = &All.UnitMass_in_g; id[nt++] = DOUBLE; strcpy(tag[nt], "TreeDomainUpdateFrequency"); addr[nt] = &All.TreeDomainUpdateFrequency; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolIntAccuracy"); addr[nt] = &All.ErrTolIntAccuracy; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolTheta"); addr[nt] = &All.ErrTolTheta; id[nt++] = DOUBLE; strcpy(tag[nt], "ErrTolForceAcc"); addr[nt] = &All.ErrTolForceAcc; id[nt++] = DOUBLE; strcpy(tag[nt], "MinGasHsmlFractional"); addr[nt] = &All.MinGasHsmlFractional; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxSizeTimestep"); addr[nt] = &All.MaxSizeTimestep; id[nt++] = DOUBLE; strcpy(tag[nt], "MinSizeTimestep"); addr[nt] = &All.MinSizeTimestep; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxRMSDisplacementFac"); addr[nt] = &All.MaxRMSDisplacementFac; id[nt++] = DOUBLE; strcpy(tag[nt], "ArtBulkViscConst"); addr[nt] = &All.ArtBulkViscConst; id[nt++] = DOUBLE; strcpy(tag[nt], "CourantFac"); addr[nt] = &All.CourantFac; id[nt++] = DOUBLE; strcpy(tag[nt], "DesNumNgb"); addr[nt] = &All.DesNumNgb; id[nt++] = DOUBLE; strcpy(tag[nt], "MaxNumNgbDeviation"); addr[nt] = &All.MaxNumNgbDeviation; id[nt++] = DOUBLE; strcpy(tag[nt], "ComovingIntegrationOn"); addr[nt] = &All.ComovingIntegrationOn; id[nt++] = INT; strcpy(tag[nt], "ICFormat"); addr[nt] = &All.ICFormat; id[nt++] = INT; strcpy(tag[nt], "SnapFormat"); addr[nt] = &All.SnapFormat; id[nt++] = INT; strcpy(tag[nt], "NumFilesPerSnapshot"); addr[nt] = &All.NumFilesPerSnapshot; id[nt++] = INT; strcpy(tag[nt], "NumFilesWrittenInParallel"); addr[nt] = &All.NumFilesWrittenInParallel; id[nt++] = INT; strcpy(tag[nt], "ResubmitOn"); addr[nt] = &All.ResubmitOn; id[nt++] = INT; strcpy(tag[nt], "TypeOfTimestepCriterion"); addr[nt] = &All.TypeOfTimestepCriterion; id[nt++] = INT; strcpy(tag[nt], "TypeOfOpeningCriterion"); addr[nt] = &All.TypeOfOpeningCriterion; id[nt++] = INT; strcpy(tag[nt], "TimeLimitCPU"); addr[nt] = &All.TimeLimitCPU; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningHalo"); addr[nt] = &All.SofteningHalo; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningDisk"); addr[nt] = &All.SofteningDisk; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBulge"); addr[nt] = &All.SofteningBulge; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningGas"); addr[nt] = &All.SofteningGas; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningStars"); addr[nt] = &All.SofteningStars; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBndry"); addr[nt] = &All.SofteningBndry; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningHaloMaxPhys"); addr[nt] = &All.SofteningHaloMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningDiskMaxPhys"); addr[nt] = &All.SofteningDiskMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBulgeMaxPhys"); addr[nt] = &All.SofteningBulgeMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningGasMaxPhys"); addr[nt] = &All.SofteningGasMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningStarsMaxPhys"); addr[nt] = &All.SofteningStarsMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "SofteningBndryMaxPhys"); addr[nt] = &All.SofteningBndryMaxPhys; id[nt++] = DOUBLE; strcpy(tag[nt], "BufferSize"); addr[nt] = &All.BufferSize; id[nt++] = INT; strcpy(tag[nt], "PartAllocFactor"); addr[nt] = &All.PartAllocFactor; id[nt++] = DOUBLE; strcpy(tag[nt], "TreeAllocFactor"); addr[nt] = &All.TreeAllocFactor; id[nt++] = DOUBLE; strcpy(tag[nt], "GravityConstantInternal"); addr[nt] = &All.GravityConstantInternal; id[nt++] = DOUBLE; strcpy(tag[nt], "InitGasTemp"); addr[nt] = &All.InitGasTemp; id[nt++] = DOUBLE; strcpy(tag[nt], "MinGasTemp"); addr[nt] = &All.MinGasTemp; id[nt++] = DOUBLE; if((fd = fopen(fname, "r"))) { sprintf(buf, "%s%s", fname, "-usedvalues"); if(!(fdout = fopen(buf, "w"))) { printf("error opening file '%s' \n", buf); errorFlag = 1; } else { while(!feof(fd)) { *buf = 0; fgets(buf, 200, fd); if(sscanf(buf, "%s%s%s", buf1, buf2, buf3) < 2) continue; if(buf1[0] == '%') continue; for(i = 0, j = -1; i < nt; i++) if(strcmp(buf1, tag[i]) == 0) { j = i; tag[i][0] = 0; break; } if(j >= 0) { switch (id[j]) { case DOUBLE: *((double *) addr[j]) = atof(buf2); fprintf(fdout, "%-35s%g\n", buf1, *((double *) addr[j])); break; case STRING: strcpy(addr[j], buf2); fprintf(fdout, "%-35s%s\n", buf1, buf2); break; case INT: *((int *) addr[j]) = atoi(buf2); fprintf(fdout, "%-35s%d\n", buf1, *((int *) addr[j])); break; } } else { fprintf(stdout, "Error in file %s: Tag '%s' not allowed or multiple defined.\n", fname, buf1); errorFlag = 1; } } fclose(fd); fclose(fdout); i = strlen(All.OutputDir); if(i > 0) if(All.OutputDir[i - 1] != '/') strcat(All.OutputDir, "/"); sprintf(buf1, "%s%s", fname, "-usedvalues"); sprintf(buf2, "%s%s", All.OutputDir, "parameters-usedvalues"); sprintf(buf3, "cp %s %s", buf1, buf2); system(buf3); } } else { printf("\nParameter file %s not found.\n\n", fname); errorFlag = 2; } if(errorFlag != 2) for(i = 0; i < nt; i++) { if(*tag[i]) { printf("Error. I miss a value for tag '%s' in parameter file '%s'.\n", tag[i], fname); errorFlag = 1; } } if(All.OutputListOn && errorFlag == 0) errorFlag += read_outputlist(All.OutputListFilename); else All.OutputListLength = 0; } #ifndef NOMPI MPI_Bcast(&errorFlag, 1, MPI_INT, 0, GADGET_WORLD); #endif if(errorFlag) { #ifndef NOMPI MPI_Finalize(); #endif exit(0); } /* now communicate the relevant parameters to the other processes */ #ifndef NOMPI MPI_Bcast(&All, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD); #endif if(All.NumFilesWrittenInParallel < 1) { if(ThisTask == 0) printf("NumFilesWrittenInParallel MUST be at least 1\n"); endrun(0); } if(All.NumFilesWrittenInParallel > NTask) { if(ThisTask == 0) printf("NumFilesWrittenInParallel MUST be smaller than number of processors\n"); endrun(0); } #ifdef PERIODIC if(All.PeriodicBoundariesOn == 0) { if(ThisTask == 0) { printf("Code was compiled with periodic boundary conditions switched on.\n"); printf("You must set `PeriodicBoundariesOn=1', or recompile the code.\n"); } endrun(0); } #else if(All.PeriodicBoundariesOn == 1) { if(ThisTask == 0) { printf("Code was compiled with periodic boundary conditions switched off.\n"); printf("You must set `PeriodicBoundariesOn=0', or recompile the code.\n"); } endrun(0); } #endif if(All.TypeOfTimestepCriterion >= 1) { if(ThisTask == 0) { printf("The specified timestep criterion\n"); printf("is not valid\n"); } endrun(0); } #if defined(LONG_X) || defined(LONG_Y) || defined(LONG_Z) #ifndef NOGRAVITY if(ThisTask == 0) { printf("Code was compiled with LONG_X/Y/Z, but not with NOGRAVITY.\n"); printf("Stretched periodic boxes are not implemented for gravity yet.\n"); } endrun(0); #endif #endif #undef DOUBLE #undef STRING #undef INT #undef MAXTAGS } /*! this function reads a table with a list of desired output times. The * table does not have to be ordered in any way, but may not contain more * than MAXLEN_OUTPUTLIST entries. */ int read_outputlist(char *fname) { FILE *fd; if(!(fd = fopen(fname, "r"))) { printf("can't read output list in file '%s'\n", fname); return 1; } All.OutputListLength = 0; do { if(fscanf(fd, " %lg ", &All.OutputListTimes[All.OutputListLength]) == 1) All.OutputListLength++; else break; } while(All.OutputListLength < MAXLEN_OUTPUTLIST); fclose(fd); printf("\nfound %d times in output-list.\n", All.OutputListLength); return 0; } /*! If a restart from restart-files is carried out where the TimeMax * variable is increased, then the integer timeline needs to be * adjusted. The approach taken here is to reduce the resolution of the * integer timeline by factors of 2 until the new final time can be * reached within TIMEBASE. */ void readjust_timebase(double TimeMax_old, double TimeMax_new) { int i; long long ti_end; if(ThisTask == 0) { printf("\nAll.TimeMax has been changed in the parameterfile\n"); printf("Need to adjust integer timeline\n\n\n"); } if(TimeMax_new < TimeMax_old) { if(ThisTask == 0) printf("\nIt is not allowed to reduce All.TimeMax\n\n"); endrun(556); } if(All.ComovingIntegrationOn) ti_end = log(TimeMax_new / All.TimeBegin) / All.Timebase_interval; else ti_end = (TimeMax_new - All.TimeBegin) / All.Timebase_interval; while(ti_end > TIMEBASE) { All.Timebase_interval *= 2.0; ti_end /= 2; All.Ti_Current /= 2; #ifdef PMGRID All.PM_Ti_begstep /= 2; All.PM_Ti_endstep /= 2; #endif for(i = 0; i < NumPart; i++) { P[i].Ti_begstep /= 2; P[i].Ti_endstep /= 2; } } All.TimeMax = TimeMax_new; }
{ "alphanum_fraction": 0.6159500693, "avg_line_length": 25.6279620853, "ext": "c", "hexsha": "eca9b0a6d69a5ac64f01fd7b18df6940fd4ce0d7", "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/begrun.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/begrun.c", "max_line_length": 103, "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/begrun.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": 6364, "size": 21630 }
#include <petsc.h> #include "quantum_gates.h" void projectq_qasm_read(char[],PetscInt*,circuit*); void projectq_vqe_get_expectation(char[],Vec,PetscScalar*); void _projectq_qasm_add_gate(char*,circuit*,PetscReal); void projectq_vqe_get_expectation_encoded(char[],Vec,PetscScalar*,PetscInt,...); void qiskit_qasm_read(char[],PetscInt*,circuit*); void _qiskit_qasm_add_gate(char*,circuit*,PetscReal); void qiskit_vqe_get_expectation(char[],Vec,PetscScalar*); void quil_read(char[],PetscInt*,circuit*); void _quil_add_gate(char*,circuit*,PetscReal); void _quil_get_angle_pi(char[],PetscReal*);
{ "alphanum_fraction": 0.8023648649, "avg_line_length": 42.2857142857, "ext": "h", "hexsha": "b6bb7a5232e1c1c3e777fa521bb86717bf60461e", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z", "max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z", "max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sgulania/QuaC", "max_forks_repo_path": "src/qasm_parser.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sgulania/QuaC", "max_issues_repo_path": "src/qasm_parser.h", "max_line_length": 80, "max_stars_count": 23, "max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sgulania/QuaC", "max_stars_repo_path": "src/qasm_parser.h", "max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z", "num_tokens": 173, "size": 592 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_fit.h> #include "cosmocalc.h" double nonlinear_corrfunc_integ_funct(double k, void *p) { double r = ((double*)p)[0]; double a = ((double*)p)[1]; return nonlinear_powspec(k,a)*k/r; } double nonlinear_corrfunc_exact(double r, double a) { double I0; double abserr,p[2]; gsl_integration_workspace *workspace; gsl_function F; gsl_integration_qawo_table *wf; gsl_integration_workspace *cycle_workspace; #define WORKSPACE_NUM 70 #define ABSERR 0.0 #define RELERR 1e-3 workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); cycle_workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); wf = gsl_integration_qawo_table_alloc(r,1e3-1e-7,GSL_INTEG_SINE,(size_t) WORKSPACE_NUM); F.function = &nonlinear_corrfunc_integ_funct; p[0] = r; p[1] = a; F.params = p; gsl_integration_qawo(&F,1e-7,ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,wf,&I0,&abserr); gsl_integration_qawo_table_free(wf); gsl_integration_workspace_free(cycle_workspace); gsl_integration_workspace_free(workspace); #undef ABSERR #undef RELERR #undef WORKSPACE_NUM return I0/2.0/M_PI/M_PI; } double nonlinear_corrfunc(double r, double a) { static int initFlag = 1; static int currCosmoNum; static double aint; static gsl_spline *cosmocalc_nonlinear_corrfunc_spline = NULL; static gsl_interp_accel *cosmocalc_nonlinear_corrfunc_acc = NULL; double nonlinear_corrfunc_table[COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH]; double r_table[COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH]; long i; if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum || a != aint) { initFlag = 0; currCosmoNum = cosmoData.cosmoNum; aint = a; for(i=0;i<COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH;++i) { r_table[i] = log(CF_R_MAX/CF_R_MIN)/(COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH-1.0)*((double) i) + log(CF_R_MIN); nonlinear_corrfunc_table[i] = nonlinear_corrfunc_exact(exp(r_table[i]),aint); } //init the spline and accelerators if(cosmocalc_nonlinear_corrfunc_spline != NULL) gsl_spline_free(cosmocalc_nonlinear_corrfunc_spline); cosmocalc_nonlinear_corrfunc_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH)); gsl_spline_init(cosmocalc_nonlinear_corrfunc_spline,r_table,nonlinear_corrfunc_table,(size_t) (COSMOCALC_NONLINEAR_CORRFUNC_TABLE_LENGTH)); if(cosmocalc_nonlinear_corrfunc_acc != NULL) gsl_interp_accel_reset(cosmocalc_nonlinear_corrfunc_acc); else cosmocalc_nonlinear_corrfunc_acc = gsl_interp_accel_alloc(); } if(r < CF_R_MIN) return 0.0; else if(r < CF_R_MAX) return gsl_spline_eval(cosmocalc_nonlinear_corrfunc_spline,log(r),cosmocalc_nonlinear_corrfunc_acc); else return 0.0; }
{ "alphanum_fraction": 0.7590682196, "avg_line_length": 31.3020833333, "ext": "c", "hexsha": "74db359fc03b0803e5d87254fa269a7349dd970b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_path": "src/nonlinear_corrfunc.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_path": "src/nonlinear_corrfunc.c", "max_line_length": 145, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_path": "src/nonlinear_corrfunc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 905, "size": 3005 }
#ifndef SPARSE_AUC_AUC_OPT_METHODS_H #define SPARSE_AUC_AUC_OPT_METHODS_H #include <time.h> #include <stdbool.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <limits.h> // These are the third part library needed. #include <cblas.h> #include "fast_pcst.h" #include "loss.h" #define PI 3.14159265358979323846 #define sign(x) (x > 0) - (x < 0) #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #define swap(a, b) { register double temp=(a);(a)=(b);(b)=temp; } #define is_posi(x) ( x > 0.0 ? 1.0 : 0.0) #define is_nega(x) ( x < 0.0 ? 1.0 : 0.0) typedef struct { double *wt; double *wt_prev; double *aucs; double *rts; int auc_len; // how many auc evaluated. int total_iterations; // total iterations int total_epochs; // total epochs executed. } AlgoResults; typedef struct { int num_passes; int verbose; int step_len; int record_aucs; double stop_eps; } GlobalParas; AlgoResults *make_algo_results(int data_p, int total_num_eval); bool free_algo_results(AlgoResults *re); typedef struct { Array *re_nodes; Array *re_edges; double *prizes; double *costs; int num_pcst; double run_time; int num_iter; } GraphStat; typedef struct { const double *x_tr_vals; const int *x_tr_inds; const int *x_tr_poss; const int *x_tr_lens; const double *y_tr; bool is_sparse; int n; int p; // this is only for the graph operator. bool is_graph; int m; // number of edges. EdgePair *edges; double *weights; int g; double *proj_prizes; GraphStat *graph_stat; } Data; GraphStat *make_graph_stat(int p, int m); bool free_graph_stat(GraphStat *graph_stat); typedef struct { double val; int index; } data_pair; bool head_tail_binsearch( const EdgePair *edges, const double *costs, const double *prizes, int n, int m, int target_num_clusters, int root, int sparsity_low, int sparsity_high, int max_num_iter, PruningMethod pruning, int verbose, GraphStat *stat); /** * SOLAM: Stochastic Online AUC Maximization * --- * BibTEX: * @inproceedings{ying2016stochastic, * title={Stochastic online AUC maximization}, * author={Ying, Yiming and Wen, Longyin and Lyu, Siwei}, * booktitle={Advances in neural information processing systems}, * pages={451--459}, * year={2016} * } * @param data * @param paras * @param re * @param para_xi * @param para_r * @author --- (Email: ---) * @return */ bool _algo_solam(Data *data, GlobalParas *paras, AlgoResults *re, double para_xi, double para_r); /** * This function implements the algorithm proposed in the following paper. * Stochastic Proximal Algorithms for AUC Maximization. * --- * @inproceedings{natole2018stochastic, * title={Stochastic proximal algorithms for AUC maximization}, * author={Natole, Michael and Ying, Yiming and Lyu, Siwei}, * booktitle={International Conference on Machine Learning}, * pages={3707--3716}, * year={2018}} * --- * Do not use the function directly. Instead, call it by Python Wrapper. * @param data * @param paras * @param re * @param para_xi * @param para_l1_reg * @param para_l2_reg * @author --- (Email: ---) */ void _algo_spam(Data *data, GlobalParas *paras, AlgoResults *re, double para_xi, double para_l1_reg, double para_l2_reg); /** * Stochastic Hard Thresholding for AUC maximization. * @param data * @param paras * @param re * @param para_s * @param para_b * @param para_c * @param para_l2_reg */ void _algo_sht_auc(Data *data, GlobalParas *paras, AlgoResults *re, int version, int operator_id, int para_s, int para_b, double para_c, double para_l2_reg); void _algo_sto_iht(Data *data, GlobalParas *paras, AlgoResults *re, int para_s, int para_b, double para_xi, double para_l2_reg); /** * * @param data * @param paras * @param re * @param para_s * @param para_tau * @param para_zeta * @param para_step_init * @param para_l2 */ void _algo_hsg_ht(Data *data, GlobalParas *paras, AlgoResults *re, int para_s, double para_tau, double para_zeta, double para_step_init, double para_l2); int _hard_thresholding(double *arr, int n, int k); /** * * @param data * @param paras * @param re * @param para_tau * @param para_eta * @param para_lambda */ void _algo_opauc(Data *data, GlobalParas *paras, AlgoResults *re, int para_tau, double para_eta, double para_lambda); /** * This function implements the algorithm, FSAUC, proposed in the following paper: * --- * @inproceedings{liu2018fast, * title={Fast stochastic AUC maximization with O (1/n)-convergence rate}, * author={Liu, Mingrui and Zhang, Xiaoxuan and Chen, Zaiyi and Wang, Xiaoyu and Yang, Tianbao}, * booktitle={International Conference on Machine Learning}, * pages={3195--3203}, * year={2018}} * --- * @param data * @param paras * @param re * @param para_r * @param para_g */ void _algo_fsauc(Data *data, GlobalParas *paras, AlgoResults *re, double para_r, double para_g); #endif //SPARSE_AUC_AUC_OPT_METHODS_H
{ "alphanum_fraction": 0.6069253524, "avg_line_length": 24.7715517241, "ext": "h", "hexsha": "c83abbe86a98df2c07cdee776e98f096812af650", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-08T11:52:16.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-08T11:52:16.000Z", "max_forks_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "baojianzhou/sparse-auc", "max_forks_repo_path": "algo_wrapper/auc_opt_methods.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "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": "baojianzhou/sparse-auc", "max_issues_repo_path": "algo_wrapper/auc_opt_methods.h", "max_line_length": 96, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "baojianzhou/sparse-auc", "max_stars_repo_path": "algo_wrapper/auc_opt_methods.h", "max_stars_repo_stars_event_max_datetime": "2020-11-13T13:45:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-13T13:45:14.000Z", "num_tokens": 1532, "size": 5747 }
//gcc -g meanpreds.c -o meanpreds #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "my_misc.c" #define isnum(c) (((c>='0') && (c<='9'))||(c=='-')||(c=='+')||(c==' ')) //static char pr[1024]; #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix_double.h> //#include <gsl/gsl_multimin.h> #include <gsl/gsl_multiroots.h> //#include "my_misc.c" //#define GSL 1 #undef GSL #define GSL 1 //#define GSL 0 int GSLtag; void least_gsl_error_handler( const char * reason, const char * file, int line, int gsl_errno) { // printf("%s:%d: %s (gsl_error: %s)\n", // file, line, reason, gsl_strerror(gsl_errno)); printf("%s:%d: %s (gsl_error %d)\n", file, line, reason,gsl_errno); GSLtag=1; } double VarY; void calc_Ainvb(double *M, double *A_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A in R^{ndata x nx} (ndata>nx) M in R^{nx x 1} */ int i; gsl_vector *S; gsl_vector *work; gsl_vector *x; gsl_vector *b; gsl_matrix *V; gsl_matrix *A; if(ndata<=0){ M[0]=1; for(i=1;i<nx;i++) M[i]=1./nx; } else{ A =gsl_matrix_alloc(ndata,nx); b =gsl_vector_alloc(ndata);b->data=b_data; A->data=A_data; // for(i=0;i<ndata;i++){printf("%e %e %d #bi,Ai\n",A->data[i],b->data[i],i); } V = gsl_matrix_alloc (nx,nx); S = gsl_vector_alloc (nx); work = gsl_vector_alloc(nx); x = gsl_vector_alloc(nx); gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0; #if GSL == 1 gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh #elif GSL == 2 gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh #elif GSL == 3 {//faster gsl_matrix *X; X = gsl_matrix_alloc (nx,nx); gsl_linalg_SV_decomp_mod (A, X, V, S, work); gsl_matrix_free(X); } #endif // for(i=nxmarume;i<nx;i++){ fprintf(stdout,"Lambda"); for(i=0;i<nx;i++){ // if(nx>40) break; // fprintf(stdout,"S->data[%d]=%e;",i,S->data[i]); fprintf(stdout,"(%d)%e",i,S->data[i]); } fprintf(stdout,"\n"); VarY=0; if(GSLtag==1){ fprintf(stderr,"\nEigenValue=");for(i=0;i<nx;i++) fprintf(stderr,"%e ",S->data[i]); fprintf(stderr,"\n"); for(i=0;i<nx;i++) M[i]=1./nx; } else{ if(nxmarume>=0){//Principal Component Analysis for(i=nxmarume;i<nx;i++) S->data[i]=0; for(i=0;i<nxmarume;i++) VarY+=S->data[i]; gsl_linalg_SV_solve(A,V,S,b,x); for(i=0;i<nx;i++) M[i]=gsl_vector_get(x,i); // {//check // double err=0,yhat; // int j; // for(i=0;i<ndata;i++){ // if(i>10) break; // yhat=b_data[i]; // for(j=0;j<nx;j++){ // yhat-= M[j]*A_data[i*nx+j]; // } // err+=square(yhat); // fprintf(stderr,"err=%e=%e/%d. yhat=%e=(%e",err/(i+1.),err,i,yhat,b_data[i]); // for(j=0;j<nx;j++) fprintf(stderr,"-(%e)*(%e)",M[j],A_data[i*nx+j]); // fprintf(stderr,")^2\n"); // } // } } else{//Minor Component Analysis int ii=0; int im=-nxmarume; for(i=nx-1;i>=0;i--){ if(S->data[i]>1e-20){ ii++; VarY+=S->data[i]; if(ii>=im) break; } } int j; double M0=-V->data[i]; for(j=1;j<nx;j++){ M[j-1]=V->data[j*nx+i]/M0; } // double M0=-V->data[i*nx]; // for(j=1;j<nx;j++){ // M[j-1]=V->data[i*nx+j]/M0; // } } } gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(x); gsl_matrix_free(V); gsl_matrix_free(A); gsl_vector_free(b); } } void calc_AtinvbMCA(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A=At in R^{ndata x nx} M in R^{nx x 1} */ int nx1=nx+1,i,j,jnx1; gsl_matrix *A =gsl_matrix_alloc(ndata,nx1); for(j=0;j<ndata;j++){ jnx1=j*nx1; A->data[jnx1]=b_data[j]; for(i=0;i<nx;i++){ A->data[jnx1+i+1]=At_data[i*ndata+j]; } } calc_Ainvb(M, (double *)(A->data), b_data, nx1, ndata, -nxmarume); gsl_matrix_free(A); } void calc_Atinvb(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume) { /* b= A M --> M= Ainv b b in R^{ndata x 1} A=At in R^{ndata x nx} M in R^{nx x 1} */ gsl_matrix *At =gsl_matrix_alloc(nx,ndata); gsl_matrix *A =gsl_matrix_alloc(ndata,nx); At->data=At_data; gsl_matrix_transpose_memcpy(A, At); calc_Ainvb(M, (double *)(A->data), b_data, nx, ndata, nxmarume); gsl_matrix_free(A); gsl_matrix_free(At); } void calc_yp(double *y, double *a_data, int nx, int ndata,int nxmarume) {//M[i]=Ainv b int i, l,j; double sumS=0,sumSj=0; gsl_vector *S; gsl_vector *work; gsl_vector *x; // gsl_vector *b; gsl_matrix *V; gsl_matrix *A; A =gsl_matrix_alloc(ndata,nx); A->data=a_data; // b =gsl_vector_alloc(ndata); // b->data=b_data; V = gsl_matrix_alloc (nx,nx); S = gsl_vector_alloc (nx); work = gsl_vector_alloc(nx); x = gsl_vector_alloc(nx); gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0; #if GSL == 1 gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh #elif GSL == 2 gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh #elif GSL == 3 {//faster gsl_matrix *X; X = gsl_matrix_alloc (nx,nx); gsl_linalg_SV_decomp_mod (A, X, V, S, work); gsl_matrix_free(X); } #endif // for(i=nxmarume;i<nx;i++){ sumS=sumSj=0; for(l=0;l<nx;l++) sumS+=gsl_vector_get(S,l); if(nxmarume>=0){ for(i=0;i<ndata;i++){ y[i]=0; for(l=0;l<nxmarume;l++){ // fprintf(stderr,"S%d=%e.\n",l,gsl_vector_get(S,l)); for(j=0;j<nx;j++){ // y[i]+=S->data[l]*A->data[i*nx+l]*V->data[j*nx+l]; y[i]+=gsl_vector_get(S,l)*gsl_matrix_get(A,i,l)*gsl_matrix_get(V,j,l); } } y[i]/=nx; if(i<5){ sumSj+=gsl_vector_get(S,i); fprintf(stderr,"[%d]y=%e, s=%e, CumulativeProp=%f=%f/%f\n",i,y[i],gsl_vector_get(S,i),sumSj/sumS,sumSj,sumS); } } } else{ int ll=0; for(i=0;i<ndata;i++){ y[i]=0; for(l=nx;;l--){ if(gsl_vector_get(S,l)<=1e-30) continue; if(i==0) fprintf(stderr,"S%d=%e.\n",l,gsl_vector_get(S,l)); for(j=0;j<nx;j++){ y[i]+=gsl_vector_get(S,l)*gsl_matrix_get(A,i,l)*gsl_matrix_get(V,j,l); } if(++ll>=-nxmarume) break; } y[i]/=nx; if(i<5){ sumSj+=gsl_vector_get(S,i); if(i<5) fprintf(stderr,"[%d]y=%e, s=%e, CumulativeProp=%f=%f/%f\n",i,y[i],gsl_vector_get(S,i),sumSj/sumS,sumSj,sumS); } } } gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(x); gsl_matrix_free(V); } ////For Maximizing the Entropy of the training data ////For Minimizing the minus of the Entropy of the training data //Lagrange Method int my_df_Entropy(const gsl_vector *v, void *params, gsl_vector *df) { double **dp = (double **)params; int nd=(int)((double)*dp[0]); int nl=(int)((double)*dp[1]); double *y=(double *)dp[2]; double *f=(double *)dp[3]; int sgn=(int)((double)*dp[4]); double *yp=(double*)malloc(sizeof(double)*nd); double *e2=(double*)malloc(sizeof(double)*nd); double *e =(double*)malloc(sizeof(double)*nd); double *dHdp=(double*)malloc(sizeof(double)*nd); double *dpde2=(double*)malloc(sizeof(double)*nd*nd); double E2,lognd=log(nd),pi; int i,j,k,l; E2=0; for(i=0;i<nd;i++){ yp[i]=0; for(j=0;j<nl;j++) yp[i]+=square(v->data[j])*f[j*nd+i]; e[i]=(y[i]-yp[i]); e2[i]=e[i]*e[i]; E2+=e2[i]; } for(i=0;i<nd;i++){ pi=e2[i]/E2; dHdp[i]=(log(pi)+1.)/lognd;//for the minus Entropy for(k=0;k<nd;k++){ if(i == k) dpde2[i*nd+k]=1./E2-e2[i]/E2/E2; else dpde2[i*nd+k]=-e2[i]/E2/E2; } } // double dfnorm=0; // fprintf(stdout,"df="); for(l=0;l<nl;l++){ df->data[l]=0; for(i=0;i<nd;i++){ for(k=0;k<nd;k++){ df->data[l]+=dHdp[i]*dpde2[i*nd+k]*(2.*e[k]*(-2.*v->data[l]*f[l*nd+k])); // df->data[l]+=dHdp[i]*dpde2[i*nd+k]*(-2.*e[k]*f[l*nd+k]); } df->data[l]+= 2.*v->data[nl]*v->data[l]*sgn;//for Penalty // df->data[l]-= 2.*v->data[nl]*v->data[l];//for Penalty // df->data[l] = C0*(-2.*e[i]*f[l*nd+i])/E0 +C1*df->data[l];//for H=C0*E2/E0+C1*Entropy } // dfnorm+=square(df->data[l]); // fprintf(stdout,"%.4f ",df->data[l]); } //Lagrange for sumv=1. v->data[nd]=lambda double sumv=0;//for Lagrange for(j=0;j<nl;j++) sumv+=square(v->data[j]);//for Lagrange df->data[nl]=(sumv-1.)*sgn;//for Lagrange L=H+lambda*(sum c_l-1) // df->data[nl]=1.-sumv;//for Lagrange L=H-lambda*(sum c_l-1) // fprintf(stdout,";dfnorm=%.4e\n",dfnorm); free(yp); free(e); free(e2); return GSL_SUCCESS; } int gsl_print_state (size_t iter, gsl_multiroot_fsolver * s, void *params) { double **dp = (double **)params; int nd=(int)((double)*dp[0]); int nl=(int)((double)*dp[1]); double *y=(double *)dp[2]; double *f=(double *)dp[3]; double *yp=(double*)malloc(sizeof(double)*nd); double *e2=(double*)malloc(sizeof(double)*nd); double *e =(double*)malloc(sizeof(double)*nd); double E2,pi; int i,j; E2=0; for(i=0;i<nd;i++){ yp[i]=0; for(j=0;j<nl;j++) yp[i]+=square(gsl_vector_get (s->x, j))*f[j*nd+i]; e[i]=(y[i]-yp[i]); e2[i]=e[i]*e[i]; E2+=e2[i]; } double H=0;// for(i=0;i<nd;i++){ pi=e2[i]/E2; H += pi*log(pi);//the minus Entropy } H/=log(nd); printf ("iter = %3u H=%f x0=%.3e...%.3e " "dL/dx=%.3e...%3e\n", (unsigned int)iter,-H, square(gsl_vector_get (s->x, 0)), gsl_vector_get (s->x, nl), gsl_vector_get (s->f, 0), gsl_vector_get (s->f, nl)); return 0; } //////For Maximizing the Entropy of the training data //////For Minimizing the minus of the Entropy of the training data //double //my_f_Entropy(const gsl_vector *v, void *params) //{ // //params // /* // e_i=y_i- sum_l v[l] f[l][i] (l=0:nx-1) // p_i= e_i^2/ sum_j e_j^2 // H= sum_i p_i log(p_i); // // */ // double **dp = (double **)params; // int nd=(int)((double)*dp[0]); // int nl=(int)((double)*dp[1]); // double *y=(double *)dp[2]; // double *f=(double *)dp[3]; // double C0=(double)*dp[4]; //// double C1=(double)*dp[5]; //// double E0=(double)*dp[6]; // double *e2=(double*)malloc(sizeof(double)*nd); // double E2; // double H,ypi,pi; // int i,j; // E2=0; // for(i=0;i<nd;i++){ // ypi=0; for(j=0;j<nl;j++) ypi+=square(v->data[j])*f[j*nd+i]; // e2[i]=square(ypi-y[i]); // E2+=e2[i]; // } // H=0; // for(i=0;i<nd;i++){ // pi=e2[i]/E2; // H += pi*log(pi);//the minus Entropy // } // H/=log(nd); // // // H=C0*E2/E0+C1*H;//for H=C0*E2/E0+C1*Entropy // // //Lagrange for sumv=1. v->data[nd]=lambda // double sumv=0;//for Lagrange // for(j=0;j<nl;j++) sumv+=square(v->data[j]);//for Lagrange // // if(C0*(sumv-1.)<0) C0*=-1; // // H+=v->data[nl]*(sumv-1.);//for Lagrange // fprintf(stderr,"H=%f,sumv=%e",H,sumv); // H+=C0*(sumv-1.);//for Penalty method // ///// // free(e2); // return H; //} // ///* The gradient of f, df = (df/dx, df/dy). */ //void //my_df_Entropy(const gsl_vector *v, void *params, // gsl_vector *df) //{ // double **dp = (double **)params; // int nd=(int)((double)*dp[0]); // int nl=(int)((double)*dp[1]); // double *y=(double *)dp[2]; // double *f=(double *)dp[3]; // double C0=(double)*dp[4]; // // double C1=(double)*dp[5]; // // double E0=(double)*dp[6]; // double *yp=(double*)malloc(sizeof(double)*nd); // double *e2=(double*)malloc(sizeof(double)*nd); // double *e =(double*)malloc(sizeof(double)*nd); // double *dHdp=(double*)malloc(sizeof(double)*nd); // double *dpde2=(double*)malloc(sizeof(double)*nd*nd); // double E2,lognd=log(nd),pi; // int i,j,k,l; //// { //// double sumv; //// for(j=0;j<nl;j++) sumv+=square(v->data[j]);//for Lagrange //// if(C0*(sumv-1.)<0) C0*=-1; //// } // E2=0; // for(i=0;i<nd;i++){ // yp[i]=0; for(j=0;j<nl;j++) yp[i]+=square(v->data[j])*f[j*nd+i]; // e[i]=(y[i]-yp[i]); // e2[i]=e[i]*e[i]; // E2+=e2[i]; // } // for(i=0;i<nd;i++){ // pi=e2[i]/E2; // // dHdp[i]=(-log(pi)-1.)/lognd; // dHdp[i]=(log(pi)+1.)/lognd;//for the minus Entropy // for(k=0;k<nd;k++){ // if(i == k) dpde2[i*nd+k]=1./E2-e2[i]/E2/E2; // else dpde2[i*nd+k]=-e2[i]/E2/E2; // } // } // double dfnorm=0; // // fprintf(stdout,"df="); // for(l=0;l<nl;l++){ // df->data[l]=0; // for(i=0;i<nd;i++){ // for(k=0;k<nd;k++){ // df->data[l]+=dHdp[i]*dpde2[i*nd+k]*(2.*e[k]*(-2.*v->data[l]*f[l*nd+k])); // // df->data[l]+=dHdp[i]*dpde2[i*nd+k]*(-2.*e[k]*f[l*nd+k]); // } // df->data[l]+= 2.*C0*v->data[l];//for Penalty // // df->data[l] = C0*(-2.*e[i]*f[l*nd+i])/E0 +C1*df->data[l];//for H=C0*E2/E0+C1*Entropy // } // dfnorm+=square(df->data[l]); // // fprintf(stdout,"%.4f ",df->data[l]); // } // //Lagrange for sumv=1. v->data[nd]=lambda // // double sumv=0;//for Lagrange // // for(j=0;j<nl;j++) sumv+=square(v->data[j]);//for Lagrange // // df->data[nl]=sumv-1.;//for Lagrange // // fprintf(stdout,";dfnorm=%.4e\n",dfnorm); // free(yp); // free(e); // free(e2); //} // ///* Compute both f and df together. */ //void //my_fdf_Entropy(const gsl_vector *x, void *params, // double *f, gsl_vector *df) //{ // *f = my_f_Entropy(x, params); // my_df_Entropy(x, params, df); //} //// typedef struct{ int r1; int r2; double r3; int nr; double r12; double *r; double ymin; double ymax; } RESOLUTION; #define ZERO 1e-20 int init_res(RESOLUTION *res) { int i; char buff[32]; if(res->r2==0) return(-1); if(fabs(res->ymax-res->ymin)<ZERO) { res->r2=0; return(-1); } if(res->r3<-ZERO){//negrect resolution for the meanpred res->r2=0; return(-1); } res->r12=(double)res->r1/res->r2; // res->nr=(res->ymax-res->ymin)/res->r12; res->nr=(res->ymax-res->ymin)/res->r12+0.5;//?? // res->r12=(res->ymax-res->ymin)/res->nr;//for ymin and ymax more reliable than r1 and r2 for ijcnn06 res->r=(double*)malloc(sizeof(double)*(res->nr+1)); if(fabs(res->r3)>ZERO){ for(i=0;i<=res->nr;i++){ sprintf(buff,"%.10le",((int)((i*res->r12+res->ymin)/res->r3+0.5))*res->r3);//r3$B7e$G;M<N8^F~(B sscanf(buff,"%lf",&res->r[i]); } } else{ for(i=0;i<=res->nr;i++){ sprintf(buff,"%.10le",(double)i*res->r12+res->ymin); sscanf(buff,"%lf",&res->r[i]); } } return(0); } double y_res(double y,RESOLUTION *res) { int ii; if(res->r2==0) return(y); // ii=(int)((y-ymin)/r12+0.5);//4sha5nyu ii=floor((y-res->ymin)/res->r12+0.5);//4sha5nyu if(y<res->ymin) return((double)res->r[0]); if(y>res->ymax) return((double)res->r[res->nr]); return((double)res->r[ii]); } #define buffsize 1024 int main(int argc, char **argv) { int i,j,l; FILE *fp; char buff[buffsize]; double *yp,_yp; double *y,_y,*yr,_yr; int *n,_n; int num=0,num0=0; // char *fnpredict="predict+.dat"; // char *fnloss="loss+.dat"; int intmode=0, j0=1,nfiles=argc-1; char fn_is[256],fn_pred[256],fn_pred0[256],fn_prob[256]; double _is,_mseis,_n_msetrain,_msetrain,_n_cells2,_nCells1,_n_mse,_mse,_msetrainis; double *prob,*sigma2,meansigma2,probtotal; FILE *fp0; int bayesmode=0; //0 (for flat probability) or 1 (for probatility decaying according to MSE). double bayesopt1=0;//for adjusting probability (1 for same probatility) double bayesopt2=0;//0 for original L, 1 for L_derivative requiring nfiles>=3. double bayesopt3=0;//?? double bayesopt4=0;//?? // double *ds; // int *s; double Lvar,Lvarval,Lval,LD=0,_LD;// double skew,kurtosis,entropy,skew2,skewa;//skew=3rd moment, kurtosis=4th moment double m2,m3,m4,m5,m6,m3a,m5a;//5th moment, 6th moment double m3p,m3m;//m3plus,m3minus int nm3p,nm3m; double mcov;//mean covariance double Lvar0; double Ltrain,LtrainE,H0; double *var,*vv; int *cc,ccmax=0; double _var,_vv,_cc; double *kyorix2,_kyorix2,_e2; int LDmode=2; RESOLUTION res={0,0,0,}; double *yp00; int nop=0; if(argc<2){ fprintf(stderr,"Usage: %s [ib:<intmode>:<basesmode>[:<probfile>]] <pred&is-body#1> <pred&is-body#1> ... \n",argv[0]); fprintf(stderr,"<intmode>:1 for intmode, 0 for real.\n"); fprintf(stderr,"<bayesmode>:0 simple ensemble.?\n"); fprintf(stderr,"<bayesmode>:1 for bayes mode1 exp.\n"); fprintf(stderr,"<bayesmode>:2 for bayes mode2 YpInvY.\n"); fprintf(stderr,"<bayesmode>:-1 for reading from probfile.\n"); fprintf(stderr,"res:<r1>:<r2>:<ymin>:<ymax>.\n"); fprintf(stderr,"Old Usage: %s [<int>:<bases>] <pred&is-body#1> <pred&is-body#1> ... \n",argv[0]); fprintf(stderr,"par:paramfile.\n"); exit(1); } // fprintf(stderr,"last arg[%d]='%s'\n",argc,argv[argc-1]); int parfile=0; // for(i=1;i<argc;i++){ if(strncmp(argv[i],"par:",4)==0){//for compatibility to old version parfile=1; break; } } char *_argv0; if(parfile==1){ char *fn=&argv[i][4]; FILE *fp; if((fp=fopen(fn,"r"))==NULL){ fprintf(stderr,"Param file (%s) open error.\n",fn); return(-1); } fseek( fp, 0L, SEEK_END ); int fsize=ftell(fp); fseek( fp, 0L, SEEK_SET );//rewind(fp);// // fprintf(stderr,"fsize=%d\n",fsize); _argv0=(char*)malloc(sizeof(char)*fsize); fgets(_argv0,fsize,fp); fclose(fp); argc=1; char *p=_argv0; for(j=0;j<fsize;j++) if(p[j]==' ') argc++; argv=(char**)malloc(sizeof(char*)*(argc)); for(j=1;j<argc;j++){ for(p++;;p++) if(*p==' ') {*p=0;break;} for(p++;;p++) if(*p!=' ') break; argv[j]=p; } } intmode=0; bayesmode=0; j0=1; nfiles=argc-1; for(i=j0;i<argc;i++){ if(strncmp(argv[i],"int",3)==0){//for compatibility to old version intmode=1; j0++; nfiles--; } else if(strncmp(argv[i],"ib:",3)==0){ sscanf(&(argv[i][3]),"%d:%d:%lf:%lf:%lf:%lf",&intmode,&bayesmode,&bayesopt1,&bayesopt2,&bayesopt3,&bayesopt4); if(bayesmode==-1) sprintf(fn_prob,"%s",&(argv[1][8])); j0++; nfiles--; } else if(strncmp(argv[i],"ry:",3)==0){ sscanf(&argv[i][3],"%d:%d:%lf:%lf:%lf",&res.r1,&res.r2,&res.r3,&res.ymin,&res.ymax); j0++; nfiles--; init_res(&res); } else if(strncmp(argv[i],"LDm:",4)==0){ sscanf(&argv[i][4],"%d",&LDmode); j0++; nfiles--; init_res(&res); } else if(strncmp(argv[i],"nop:",4)==0){ sscanf(&argv[i][4],"%d",&nop); j0++; nfiles--; } } //// if(nop!=1){ printf("#start:%s",argv[0]); for(i=1;i<argc;i++){ printf(" %s",argv[i]); } } // else{//if(nop==1){ // fprintf(stdout,"+"); // fflush(stdout); // } int (*net_printf)(char *); if(nop==0) net_printf=printf1; else net_printf=noprintf; prob =(double*) malloc(sizeof(double)*nfiles); sigma2=(double*) malloc(sizeof(double)*nfiles); meansigma2=0; for(j=0;j<nfiles;j++) argv[j+j0][strlen(argv[j+j0])-8]=0; //argv[j+j0]=fn_bodypred.dat for(j=0;j<nfiles;j++){ sprintf(fn_is,"%sis.dat",argv[j+j0]); if((fp=fopen(fn_is,"r"))==NULL){ fprintf(stderr,"#Execute without '%s'\n",fn_is); // fprintf(stderr,"file(%s) could not be opened!\n",fn_is); num=0; sigma2[j]=0; meansigma2+=0;//050914 num0=0; } else{ fscanf(fp,"%lf%lf%lf%lf%lf%lf%lf%lf%lf",&_is,&_mseis,&_n_msetrain,&_msetrain,&_n_cells2,&_nCells1,&_n_mse,&_mse,&_msetrainis); // num=_n_msetrain; sigma2[j]=_msetrain; meansigma2+=_msetrain;//050902?? // num=_n_mse; sigma2[j]=_mse; meansigma2+=_mse;//050823 num=_n_mse; sigma2[j]=_msetrain; meansigma2+=_msetrain;//050914 num0=_n_msetrain; // fprintf(stderr,"sigma2[%d]%e\n",j,sigma2[j]); fclose(fp); } } meansigma2/=nfiles; //////////////////////////////// if(bayesmode>=100){}//end of bayesmode>=100 else{//bayesmode <100 if(bayesmode==0){//same probability probtotal=nfiles; for(j=0;j<nfiles;j++) prob[j]=1./probtotal; probtotal=0; for(j=0;j<nfiles;j++) probtotal+=prob[j]; } else if(bayesmode==1){//probatility depending on MSE(=sigma2) int jj;double probj;//probj is 1/prob[j] for avoiding marumegosa. probtotal=0; for(j=0;j<nfiles;j++){ probj=0; for(jj=0;jj<nfiles;jj++){ if(jj==j) probj+=1; else probj+= exp((sigma2[j]-sigma2[jj])*bayesopt1/meansigma2); } prob[j]=1./probj; probtotal+=prob[j]; } for(j=0;j<nfiles;j++) prob[j]/=probtotal; probtotal=0; for(j=0;j<nfiles;j++) probtotal+=prob[j]; } //////////////////////////////// int m_LD=bayesopt2,nfiles2;//bayesopt2=m for LD= Loss_D = sum_{j=1}^m ((f_{l0+j}-f_{l0})^2 +(f_{l0-j}-f_{l0})^2) if(bayesmode==3) m_LD=0; else m_LD=bayesopt2; if(nfiles<m_LD*2+1) m_LD=(nfiles-1)/2;// (nfiles,m_LD)=(2,0),(3,1),(4,1),(5,2),(6,2); nfiles2=nfiles-m_LD*2;//for LD of generalization error int nmean=nfiles-nfiles2+1;//nmean=2*m_LD+1 // double *ww =(double*) malloc(sizeof(double)*nfiles*(nmean)); //#define LDmode 2 //#define LDmode 4 // //LDmode==4 is only for ib:0:0:0:m ??? //#if LDmode == 2 // double *ww =(double*) malloc(sizeof(double)*(nfiles+1)*(nmean)); //#elif LDmode == 4 // double *ww0 =(double*) malloc(sizeof(double)*(nfiles+1)*(nmean)*2); // double *ww =(double*) malloc(sizeof(double)*(nfiles+1)*(nmean)*(nmean)); double *ww =(double*) malloc(sizeof(double)*(nfiles)*(nmean)*(nmean)); //#endif // double *ww=&ww0[1]; double *ww0=&ww[(m_LD+m_LD*nmean)*nfiles]; {//////////for Lvar0 // double *yp0=(double*) malloc(sizeof(double)*num0*nfiles); // double *yt0=(double*) malloc(sizeof(double)*(nfiles+1)*num0+2); // double *yt=(double*) &yt0[2];//yt[0]=num0,yt[1]=nmean; double *yt=(double*) malloc(sizeof(double)*(nfiles+1)*num0); double *yp01=(double*) &yt[num0]; double *yp =(double*) malloc(sizeof(double)*num0); // nfiles2=nfiles-2*bayesopt2;//for LD of generalization error if(nfiles<3) {m_LD=bayesopt2=0;nfiles2=nfiles;}//training ? // else {m_LD=1;nfiles2=nfiles-2*bayesopt2;}//for LD of generalization error // probtotal=0; // for(j=m_LD;j<nfiles2+m_LD;j++){//prediction of training data? for(j=0;j<nfiles;j++){//prediction of training data? #define NEWp0 #ifdef NEWp0 { char *p1,*p; sprintf(fn_pred0,"%s",argv[j+j0]); for(p=fn_pred0;;p++){if(*p=='+') break;} p1=++p; for(;;p++){if(*p=='+') break;} ++p; sprintf(p1,"%spred0.dat",p); } #else sprintf(fn_pred0,"%spred0.dat",argv[j+j0]); #endif fp0=fopen(fn_pred0,"r"); for(i=0;i<num0;i++){ fgets(buff,buffsize,fp0); sscanf(buff,"%lf%d%lf%lf%lf%lf%lf",&_yp,&_n,&_y,&_yr,&_var,&_cc,&_vv);//sscanf(buff,"%lf%d%lf%lf",&_yp,&_n,&_y,&_yr); if(res.r3<0) _yp=_yr; //neglect resolution for the meanpred else _yp=y_res(_yp,&res); // yp0[i*nfiles+j] =_yp; yp01[j*num0+i] =_yp; yt[i]=_y; } fclose(fp0); } if(bayesmode==2){ // if(1==0 && nfiles==1) ww[0]=1; // else { for(j=0;j<nmean;j++){ for(l=0;l<nmean;l++){ //LDmode = 2,4,8 neighbours if(LDmode==2 && l!=m_LD) continue;//only yoko if(LDmode==4 && (l-m_LD)*(j-m_LD)!=0 ) continue;//only tate&yoko //calc_AtinvbMCA((double *)(&ww[j*nfiles]),(double *)(&yp01[j*num0]),(double *)(&yt[0]),(int)(nfiles2),(int)num0,(int)bayesopt1); calc_Atinvb((double *)(&ww[(l*nmean+j)*nfiles]),(double *)(&yp01[j*num0]),(double *)(&yt[0]),(int)(nfiles2+l-m_LD),(int)num0,(int)bayesopt1); // calc_Ainvb((double *)(&ww[j*nfiles]),(double *)(&yp0[j]),(double *)(&yt[j]),(int)(nfiles2),(int)num0,(int)bayesopt1); // calc_Ainvb((double *)(&ww[j*nfiles]),(double *)(&yp01[j*num0]),(double *)(&yt[0]),(int)(nfiles2),(int)num0,(int)bayesopt1); // calc_Ainvb((double *)(&ww[j*nfiles]),(double *)(&yp01[j*num0]),(double *)(&yt[0]),(int)(nfiles2),(int)num0,(int)bayesopt1); // for(i=0;i<=nfiles2;i++) ww[j*nfiles+i]=1./nfiles2; // for(i=0;i<10;i++) fprintf(stderr,"j%2d,i%2d)yt%+e yp%+e %+e\n",j,i,yt[i],yp01[(j)*num0+i],yp01[(j+1)*num0+i]); if(fabs(VarY)<1e-10){ for(i=0;i<nfiles2+l-m_LD;i++) ww[(l*nmean+j)*nfiles+i]=1./(nfiles2+l-m_LD); } fprintf(stderr,"w[%d,%d]:",j,l); for(i=0;i<nfiles2+l-m_LD;i++) fprintf(stderr,"%+.4f ",ww[(l*nmean+j)*nfiles+i]); fprintf(stderr,"\n"); } } } } else if(bayesmode==3){//ib:0:3:10:0:0 ib:0:3:itermax:0:0 H=C0*E2/E0+C1*Entropy for(j=0;j<nmean;j++){ for(l=0;l<nmean;l++){ if(LDmode==2 && l!=m_LD) continue;//only yoko if(LDmode==4 && (l-m_LD)*(j-m_LD)!=0 ) continue;//only tate&yoko { size_t iter = 0; size_t itermax=bayesopt1;if(itermax<1e-20) itermax=100; int status; double nl=(double)(nfiles2+l-m_LD); double nd=(double)num0; int nl1=nl+1; double *par[7]; double sgn; if(bayesopt2>=0) sgn=1; else sgn=-1; par[0]=(double *)&nd; par[1]=&nl; par[2]=&yt[0]; par[3]=&yp01[j*num0]; par[4]=&sgn; const gsl_multiroot_fsolver_type *T; gsl_multiroot_fsolver *s; gsl_multiroot_function df = {&my_df_Entropy, nl1, &par}; gsl_vector *x = gsl_vector_alloc (nl1); //&ww[(l*nmean+j)*nfiles]; for(i=0;i<=nl;i++) gsl_vector_set (x, i, sqrt(1./nl)); gsl_vector_set (x, nl, 0.0);//Good!? T = gsl_multiroot_fsolver_hybrids; s = gsl_multiroot_fsolver_alloc (T, nl1); gsl_multiroot_fsolver_set (s, &df, x); gsl_print_state (iter, s, par); do { iter++; status = gsl_multiroot_fsolver_iterate (s); gsl_print_state (iter, s, par); /* check if solver is stuck */ if (status) { printf ("Minimum not found (ERR=%d)? See /usr/include/gsl/gsl_errno.h for details.",status); if (status==GSL_EBADFUNC) {printf ("Encountered a singular point.\n");} else if (status==GSL_EBADFUNC) {printf ("Noprogress.\n");} else if (status==GSL_ENOPROGJ) {printf (" ERR=%d:Jacobian is not improving the solution.\n",GSL_ENOPROGJ);} break;}//break at Sucess or failure ? // status = gsl_multiroot_test_residual (s->f, 1e-7); status = gsl_multiroot_test_residual (s->f, 1./nl); } while (status == GSL_CONTINUE && iter < itermax); for(i=0;i<nl;i++) ww[(l*nmean+j)*nfiles+i]=square(gsl_vector_get (s->x, i)); gsl_multiroot_fsolver_free (s); gsl_vector_free (x); double sumw=0; fprintf(stderr,"w[%d,%d]:",j,l); for(i=0;i<nl;i++) fprintf(stderr,"%+.4f ",ww[(l*nmean+j)*nfiles+i]); for(i=0;i<nl;i++) sumw+=ww[(l*nmean+j)*nfiles+i]; fprintf(stderr,"sumw=%f\n",sumw); } } } } else{//for bayesmode!=2 for(l=0;l<nmean;l++){ if(LDmode==2 && l!=m_LD) continue;//only yoko for(j=0;j<nmean;j++){ if(LDmode==4 && (l-m_LD)*(j-m_LD)!=0 ) continue;//only tate&yoko for(i=0;i<nfiles2+l-m_LD;i++) ww[(l*nmean+j)*nfiles+i]=1./(nfiles2+l-m_LD); } // fprintf(stderr,"w[0-%d,0-%d]=%+.4f\n",nfiles2,nfiles2+l-m_LD,1./(nfiles2+l-m_LD)); } } LtrainE=Ltrain=Lvar0=0; for(i=0;i<num0;i++){ // yp[i]=0;for(j=m_LD;j<nfiles2+m_LD;j++) yp[i]+=(yp01[j*num0+i]*ww[m_LD*nfiles+j-m_LD]);//prediction of training data yp[i]=0; for(j=0;j<nfiles2;j++){ yp[i]+=(yp01[(j+m_LD)*num0+i]*ww0[j]);//prediction of training data } // for(j=m_LD;j<nfiles2+m_LD;j++){ // // yp[i]+=(yp01[j*num0+i]*ww[(m_LD+m_LD*nmean)*nfiles+j-m_LD]);//prediction of training data // yp[i]+=(yp01[j*num0+i]*ww0[j-m_LD]);//prediction of training data // } yp[i]=y_res(yp[i],&res); for(j=m_LD;j<nfiles2+m_LD;j++){ Lvar0+= square(yp[i]-yp01[j*num0+i]); LtrainE += square(yp01[(j)*num0+i]-yt[i]); } // for(j=m_LD;j<nfiles2+m_LD;j++) Lvar0+= exp(square(yp[i]-yp01[j*num0+i]));//???060530 Ltrain+= square(yt[i]-yp[i]); } // Lvar0 /=(nfiles2*num0); // Lvar0 = VarY;//????? //Lvar0 /=(nfiles2*num0-1+1e-10); //unbiased estimator if(nfiles2>=2) Lvar0 /=((num0+ZERO)*(nfiles2)*(nfiles2-1));//estimated variance of ensemble prediction else Lvar0 /=(num0+ZERO); //average of unbiased estimator Ltrain/=(num0+ZERO); LtrainE/=(nfiles*num0+ZERO); // free(yp01);//??why bat result if active? #define Ltrain4Entropy #ifdef Ltrain4Entropy { double pn,E2sum=Ltrain*num0;//Entropy H0=0; for(i=0;i<num0;i++){ pn=square(yp[i]-yt[i])/E2sum; H0 -= pn*log(pn); } H0/=log(num0+ZERO); // Ltrain=H0; } #endif free(yt);// free(yp);// }//end of "for Lvar0" #define BAYES2GE 1 #if BAYES2GE == 1 {// int li,l; yp00=(double*) malloc(sizeof(double)*num*nfiles); //#if LDmode == 2 // double *ypbuff=(double*) malloc(sizeof(double)*num*nmean); //#elif LDmode == 4 // double *ypbuff=(double*) malloc(sizeof(double)*num*nmean*2); double *ypbuff=(double*) malloc(sizeof(double)*num*nmean*(nmean)); //#endif y=(double*) malloc(sizeof(double)*num); yr=(double*) malloc(sizeof(double)*num); n=(int*) malloc(sizeof(int)*num); var=(double*) malloc(sizeof(double)*num); vv=(double*) malloc(sizeof(double)*num); // cc=(int*) malloc(sizeof(int)*num); cc=(int*) malloc(sizeof(int)*num*nfiles); kyorix2=(double*)malloc(sizeof(double)*num); // yp=&ypbuff[num*(int)(bayesopt2)];//??what happen when bayesopt2==0?? yp=&ypbuff[(m_LD+m_LD*nmean)*num];//center of nmean*nmean=(2*m_LD+1)*(2*m_LD+1) // yp=&ypbuff[m_LD*num];// for(i=0;i<num;i++){yp[i]= n[i]= y[i]= yr[i]=var[i]=vv[i]=0; } {///??? for(j=0;j<nfiles;j++){ sprintf(fn_pred,"%spred.dat",argv[j+j0]); fp=fopen(fn_pred,"r"); for(i=0;i<num;i++){ fgets(buff,buffsize,fp); sscanf(buff,"%lf%d%lf%lf%lf%lf%lf%lf%lf",&_yp,&_n,&_y,&_yr,&_var,&_cc,&_vv,&_e2,&_kyorix2); // yp0[i*nfiles+j] =y_res(_yp,&res); if(res.r3<0) yp00[j*num+i]=_yr; //neglect resolution for the meanpred else yp00[j*num+i] =y_res(_yp,&res); // yp00[j*num+i] =y_res(_yp,&res); cc[j*num+i] =_cc;//?? if(ccmax<_cc) ccmax=_cc; if(j>=m_LD && j<nfiles-m_LD){ // yp[i]+=_yp*prob[j];//sum for j in [1,...,nfiles-2] n[i]+=_n; y[i]+=_y;//sum for j in [1,...,nfiles-2] yr[i]+=_yr; var[i]+=(_var*_vv); vv[i]+=_vv; // cc[i]=_cc; kyorix2[i]=_kyorix2; } } // if(j>=m_LD && j<nfiles-m_LD) probtotal+=prob[j]; fclose(fp); } ////////////// Lvar=Lvarval=Lval=0; skew=kurtosis=entropy=mcov=skew2=0,skewa=0; m3p=m3m=m2=m3a=m4=m5a=m6=0;nm3p=nm3m=0; for(i=0;i<num;i++){//num=1? // yp[i]/=probtotal;//mean for j in [1,...,nfiles-2] // yp[i]=y_res(yp[i]/probtotal,&res); yp[i]=0; // for(j=0;j<nfiles2;j++) {yp[i] +=yp0[i*nfiles+j]*ww[(m_LD)*nfiles+j];} // for(j=0;j<nfiles2;j++) {yp[i] +=yp00[(j+m_LD)*num+i]*ww[(m_LD)*nfiles+j];} // for(j=m_LD;j<nfiles2+m_LD;j++) yp[i]+=(yp00[j*num+i]*ww[m_LD*nfiles+j]);//prediction of center of test data // for(j=0;j<nfiles2;j++) yp[i]+=(yp00[(j+m_LD)*num+i]*ww[(m_LD+n_LD*nmean)*nfiles+j]);//prediction of center of test data for(j=0;j<nfiles2;j++) yp[i]+=(yp00[(j+m_LD)*num+i]*ww0[j]);//prediction of center of test data yp[i]=y_res(yp[i],&res); n[i] = (int)((double)n[i]/nfiles2+0.5); y[i] = y[i]/nfiles2;//mean for j in [1,...,nfiles-2] yr[i]= yr[i]/nfiles2; // for(j=m_LD;j<nfiles-m_LD;j++){ // for(j=m_LD;j<nfiles2+m_LD;j++){ double skewj=0,sigma2j=0; double m2j=0,m3j=0,m4j=0,m5j=0,m6j=0; double m3pj=0,m3mj=0; // int nm3pj=0,nm3mj=0; double nm3pj=0,nm3mj=0; for(j=0;j<nfiles2;j++){//number of bags double err=yp00[(j+m_LD)*num+i]-yp[i];//inversed 091008 double err2_=err*err; m2j+=err2_;//sigma2j+=err2;//m2j skew2+=(err>0)?(err2_):(-err2_);//? m3j+=(err2_*=err);//skewj+=(errn=err2*err);//m3j if(err>0){ nm3pj++; m3pj+=err2_;//err^3 } else if(err<0){ nm3mj++; m3mj+=err2_;//err^3 } m4j+=(err2_*=err);//kurtosis+=(errn=errn*err);//m4j m5j+=(err2_*=err); m6j+=(err2_*=err); //Lvar += square(yp[i]-yp00[(j+m_LD)*num+i]); //Lvar += square(yp[i]-yp00[(j+m_LD)*num+i]); //Lvar += exp(square(yp[i]-yp00[(j+m_LD)*num+i]));//???060530 Lvarval += square(yp00[(j+m_LD)*num+i]-y[i]); {//mean covariance int l; for(l=0;l<nfiles2;l++){ if(l!=j) mcov+=(err*(yp00[(l+m_LD)*num+i]-yp[i])); } } }//closing for(j=0;j<nfiles2;j++){ Lval += square(yp[i]-y[i]); Lvar+=m2j;//Lvar+=sigma2j; double sj=sqrt(m2j/nfiles2);// double sj=sqrt(sigma2j/nfiles); sj+=ZERO; nm3pj+=ZERO; nm3mj+=ZERO; int mnorm=0; if(mnorm==0){//original m2+=(m2j/nfiles2); m3+=(m3j/nfiles2)/pow(sj,3.);//skew+=skewj;//m3 m3a+=fabs(m3j/nfiles2)/pow(sj,3.);//skewa+=fabs(skewj/nfiles2)/pow(sj,3);//m3a m3p+=(m3pj/(nm3pj))/pow(sj,3.); m3m+=(m3mj/(nm3mj))/pow(sj,3.); nm3p+=nm3pj; nm3m+=nm3mj; m4 += (m4j/nfiles2)/pow(sj,4.);// m5a+=fabs(m5j/nfiles2)/pow(sj,5.);//?5/2 m6 += (m6j/nfiles2)/pow(sj,6.);//?3=6/2 } else if(mnorm==1){//new for normalize m3,m4,m5,m6 m2+=(m2j/nfiles2); m3+=pow(m3j/nfiles2,1./3.)/sj;//skew+=skewj;//m3 m3a+=pow(fabs(m3j/nfiles2),1./3.)/sj;//skewa+=fabs(skewj/nfiles2)/pow(sj,3);//m3a m4 +=pow(m4j/nfiles2,1./4.)/sj;// m5a+=pow(fabs(m5j/nfiles2),1./5.)/sj;//?5/2 m6 +=pow(m6j/nfiles2,1./6.)/sj;//?3=6/2 } else if(mnorm==2){//this does not work for skew and kurtosis m2+=(m2j/nfiles2); m3+=pow(m3j/nfiles2,1./3.);//skew+=skewj;//m3 m3a+=pow(fabs(m3j/nfiles2),1./3.);//skewa+=fabs(skewj/nfiles2)/pow(sj,3);//m3a m4 +=pow(m4j/nfiles2,1./4.);// m5a+=pow(fabs(m5j/nfiles2),1./5.);// m6 +=pow(m6j/nfiles2,1./6.);// } // if(i<10) fprintf(stderr,"[%d]Lval=%9.3e,yp=%.3e,y=%.3e\n",i,Lval,yp[i],y[i]); // if(i>1900) fprintf(stderr,"[%d]Lval=%9.3e,yp=%.3e,y=%.3e\n",i,Lval/num,yp[i],y[i]); }//closing for(i=0;i<num;i++){ int num2=num*nfiles2; //Lvar /= (nfiles2*num); //?? if(nfiles2>=2) Lvar /=((num)*(nfiles2)*(nfiles2-1.));//estimated variance of ensemble prediction //if(nfiles2>=2) Lvar /=num2;//estimated variance of ensemble prediction //else Lvar/=(num); for(i=0;i<num;i++){ for(j=0;j<nfiles2;j++){ double err=yp[i]-yp00[(j+m_LD)*num+i]; double p=(err*err)/(Lvar+ZERO); p+=ZERO; entropy -= p*log(p); } } entropy/=log(num2+ZERO); // Lvar/=num2;//?see above mcov/=(num2*(nfiles2-1)); double sigma=sqrt(Lvar); double sigma3=sigma*sigma*sigma; m2/=num; m3/=num;//skew=(skew/num2)/sigma3;// skewa/=num; m3a/=num;// skewa/=num; m3p/=num; m3m/=num; m4/=num;//kurtosis=(kurtosis/num2)/sigma3/sigma;//!modified 20130418 m5a/=num; m6=m6/num; skew=m3;skewa=m3a;kurtosis=m4; Lvar=m2+ZERO;//?? // skew2=skew2/num2/Lvar; // kurtosis=(kurtosis/num2)/sigma3/sigma-3;//!!!m4-3 ///////////// //Lvar /=((nfiles2*num)*(nfiles2*num-1.));//A-type Uncertainty // Lvar /=((nfiles2*num)*(nfiles2*num-1.));//A-type Uncertainty Lvarval /= (num2); Lval /= (num); // fprintf(stderr,"#Lvar=%e,Lvarval=%e,Lval=%e,_LD:",Lvar,Lvarval,Lval); // fprintf(stderr,"#Lvar=%e,Lvarval=%e,Lval=%e,num=%d,_LD:",Lvar,Lvarval,Lval,num); //fprintf(stderr,"%g %g %g %g %g %g #Ltst,Lvar,skew,krt,ent,log|s*k|#n%db%d\n",Lval,Lvar,skew,kurtosis,entropy,log(fabs(skew*kurtosis)),num,nfiles); { FILE *fp=fopen("loss.dat","w"); fprintf(fp,"%g %g %g %g %g %d %d %g %g %g %d %g %g %g %g %d %g %d\n#Ltst,Lvar,skw,krt,ent,n,b,cor,skwa,yp0,num,skw2,m5a,m6,m3p,nm3p,m3m,nm3m\n", Lval,Lvar,m3,m4,entropy,num,nfiles,mcov/Lvar,m3a,yp[0],num,skew2,m5a,m6,m3p,nm3p,m3m,nm3m);//4=K,9=sa,13=m5a,14=m6 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // fprintf(fp,"%g %g %g %g %g %d %d %g %g %g %d %g %g %g\n#Ltst,Lvar,skw,krt,ent,n,b,cor,skwa,yp0,num,skw2\n",Lval,Lvar,skew,kurtosis,entropy,num,nfiles,mcov/Lvar,skewa,yp[0],num,skew2,m5a,m6);//4=K,9=sa,13=m5a,14=m6 // fprintf(fp,"%g %g %g %g %g %d %d %g %g %g %d\n#Ltst,Lvar,skw,krt,ent,n,b,cor,skew2,yp0,num\n",Lval,Lvar,skew,kurtosis,entropy,num,nfiles,mcov/Lvar,skew2,yp[0],num); // fprintf(fp,"%.4g %.4g %.4g %.4g %.4g %d %d\n#Ltst,Lvar,skew,krt,ent,n,b\n",Lval,Lvar,skew,kurtosis,entropy,num,nfiles); fclose(fp); // fprintf(stderr,"###cat loss.dat###\n"); // system("cat loss.dat"); // fprintf(stderr,"#######\n"); } // fprintf(stderr,"#Lvar%e,Lvarval%e,Ltst%e,skew%.3g,krt%g,ent%.3g,n%d,b%d,",Lvar,Lvarval,Lval,skew,kurtosis,entropy,num,nfiles); int jj; for(i=0;i<num;i++){ for(j=-m_LD;j<=m_LD;j++){//l1 for(l=-m_LD;l<=m_LD;l++){//ld if(j==0 && l==0 ) continue;//already obtained above if(LDmode==2 && l!=0) continue;//only yoko if(LDmode==4 && (l)*(j)!=0 ) continue;//only tate&yoko li=(l*nmean+j)*num+i; yp[li]=0; // for(j=0;j<nfiles2;j++) {yp[li] +=yp0[i*nfiles+j]*ww[(m_LD+l)*nfiles+j];} // for(j=0;j<nfiles2;j++) {yp[li] +=yp00[(j+m_LD+l)*num+i]*ww[(m_LD+l)*nfiles+j];} for(jj=0;jj<nfiles2+l;jj++) { yp[li] +=yp00[(jj+m_LD+j)*num+i]*ww0[(l*nmean+j)*nfiles+jj]; // fprintf(stderr,"jj+m_LD+j=%d+%d+%d=%d\n",jj,m_LD,j,jj+m_LD+j); } yp[li]=y_res(yp[li],&res); // li=(l+m_LD+1)*num+i; // yp[li]=0; // for(j=0;j<nfiles2+l;j++) {yp[li] +=yp00[(j+m_LD)*num+i]*ww[((l*nmean+m_LD)*nfiles+j];} // yp[li]=y_res(yp[li],&res); } } } if(1==0){//unnecessary???? LD=0; for(j=-m_LD;j<=m_LD;j++){//l1 for(l=-m_LD;l<=m_LD;l++){ if(j==0 && l==0 ) continue;//already obtained above if(LDmode==2 && l!=0) continue;//only yoko if(LDmode==4 && (l)*(j)!=0 ) continue;//only tate&yoko _LD=0; for(i=0;i<num;i++) { _LD += square(yp[i]-yp[(l*nmean+j)*num+i]); // _LD += square(yp[i]-yp[l*num+i]); // _LD += square(yp[i]-yp[(l+m_LD+1)*num+i]); } _LD/=num; LD+=_LD; fprintf(stderr,"_LD%9.3e ",_LD); } } if(LDmode==2) LD/=(m_LD*4.);// else if(LDmode==4) LD/=(m_LD*8.);// else LD/=(nmean*nmean-1);// // LD/=(m_LD*8.);//LD/=(m_LD*2.); fprintf(stderr,"LD%e\n",LD); }//end of if(1==0) }//end of ??? }//end of for BAYES2GE #endif }//end of bayesmode<100 //obtain heterosedastic err only vaid for known y[i] ? #define newvari #ifdef newvari //20150115 double *bias=(double*) malloc(sizeof(double)*num); double *err=(double*) malloc(sizeof(double)*num); int *nVi=(int*) malloc(sizeof(int)*num); { int ji,ii; for(i=0;i<num;i++) { bias[i]=var[i]=nVi[i]=0; } ccmax+=1; double *varcc=(double*)malloc(sizeof(double)*ccmax); double *biascc=(double*)malloc(sizeof(double)*ccmax); int *nvarcc=(int*)malloc(sizeof(int)*ccmax); // free *varcc; for(j=0;j<nfiles;j++){//bags int cci; for(cci=0;cci<ccmax;cci++) varcc[cci]=biascc[cci]=nvarcc[cci]=0; for(i=0;i<num;i++){ err[i]=yp00[j*num+i]-yp[i]; varcc[cc[i]]+=square(err[i]); biascc[cc[i]]=err[i]; nvarcc[cc[i]]++; // { // fp=fopen("predict+.dat","w"); // fprintf(fp,"hello\n"); // fclose(fp); // } } for(i=0;i<num;i++){ var[i]+=varcc[cc[i]]; bias[i]+=biascc[cc[i]]; nVi[i]+=nvarcc[cc[i]]; } } for(i=0;i<num;i++){ bias[i]/=nVi[i]; var[i]/=nVi[i]; } net_printf("##################new variance###\n"); } #else //old var[i] double *bias=(double*) malloc(sizeof(double)*num); double *err=(double*) malloc(sizeof(double)*num); int *nVi=(int*) malloc(sizeof(int)*num); int *nVib=(int*) malloc(sizeof(int)*num); { int ji,ii; for(i=0;i<num;i++) { err[i]=yp[i]-y[i]; bias[i]=var[i]=nViv[i]=nVib[i]=0; } for(j=0;j<nfiles;j++){//bags for(i=0;i<num;i++){ bias[i]+=err[i]; nVib[i]++; var[i] +=square(err[i]);nVi[i]++; // if(1==0){//for check Lval0=9.126e-02 {//for obtaining the average of the noise ji=j*num+i; for(ii=i+1;ii<num;ii++){ if(cc[ji]==cc[j*num+ii]) {//error for the same cell //bias[i]+=err[ii]; nVib[i]++; //bias[ii]+=err[i]; nVib[ii]++; var[i] +=square(err[ii]); nVi[i]++; var[ii]+=square(err[i]); nVi[ii]++; } } } } } for(i=0;i<num;i++){ bias[i]/=nVib[i]; var[i]/=nViv[i]; } } #endif ////// // fp=fopen(fnpredict,"w"); fp=fopen("predict+.dat","w"); for(i=0;i<num;i++){ if(intmode==1){ // fprintf(fp,"%d %d %.7e %.7e %.7e %d %.7e %.7e %.7e #Y^,t,Y,yr,var,c,v,k,b\n",(int)(yp[i]+0.5),n[i],y[i],yr[i],var[i]/vv[i],cc[i],vv[i],kyorix2[i],bias[i]); fprintf(fp,"%d %d %.7e %.7e %.7e %d %.7e %.7e %.7e %d #Y^,t,Y,yr,var,c,v,k,b,nvar\n",(int)(yp[i]+0.5),n[i],y[i],yr[i],var[i],cc[i],vv[i],kyorix2[i],bias[i],nVi[i]); } else{ fprintf(fp,"%.7e %d %.7e %.7e %.7e %d %.7e %.7e %.7e %d #Y^,t,Y,yr,var,c,v,k,b,nvar\n",yp[i],n[i],y[i],yr[i],var[i],cc[i],vv[i],kyorix2[i],bias[i],nVi[i]); // {//error check // char buff[256]; // sprintf(buff,"%.7e %d %.7e %.7e %.7e %d %.7e %.7e %.7e %d #Y^,t,Y,yr,var,c,v,k,b,nvar\n",yp[i],n[i],y[i],yr[i],var[i],cc[i],vv[i],kyorix2[i],bias[i],nVi[i]); // fprintf(stdout,"%s",buff); // fprintf(fp,"%s",buff); // } // fprintf(fp,"%.7e %d %.7e %.7e %.7e %d %.7e %.7e %.7e #Y^,t,Y,yr,var,c,v,k,b\n",yp[i],n[i],y[i],yr[i],var[i]/vv[i],cc[i],vv[i],kyorix2[i],bias[i]); } } fclose(fp); // fp=fopen(fnloss,"w"); fp=fopen("loss+.dat","w"); fprintf(fp,"%13.7e %13.7e %13.7e %13.7e %13.7e %d %d %.7e %.7e %.7e #LD Lval Lvar Lvarval Lvar0 nfiles num Ltrain LtrainE H0\n",LD,Lval,Lvar,Lvarval,Lvar0,nfiles,num,Ltrain,LtrainE,H0); fclose(fp); // fprintf(stderr,"Created '%s'=%s",fnpredict,fnbody(argv[1],pr)); // for(j=2;j<=nfiles;j++) fprintf(stderr,"+%s" ,fnbody(argv[j],pr)); // fprintf(stderr,"\n"); net_printf(strx3("Created '%s' and '%s'. #LDmode=%d.\n","predict+.dat","loss+.dat",LDmode)); return(1); }
{ "alphanum_fraction": 0.5564540992, "avg_line_length": 33.2547318612, "ext": "c", "hexsha": "8b32c0ff1c2bb6e010012af19b012717cf18cb82", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "1021/can2comp/meanpred.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "1021/can2comp/meanpred.c", "max_line_length": 221, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "1021/can2comp/meanpred.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 16244, "size": 42167 }
#include <math.h> #include <stdlib.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #include <fastpm/constrainedgaussian.h> #include "pmpfft.h" #include <gsl/gsl_linalg.h> double fastpm_2pcf_eval(FastPM2PCF* self, double r) { double rMax = self->size * self->step_size; if(r > rMax) return 0.0; if(r == rMax) return self->xi[self->size]; int i = (int)floor(r / self->step_size); double prev = self->xi[i], next = self->xi[i + 1]; double deltaR = r - i * self->step_size; return prev + (next - prev) * deltaR / self->step_size; } /* void fastpm_generate_covariance_matrix(PM *pm, fastpm_fkfunc pkfunc, void * data, FastPMFloat *cov_x) { } */ void fastpm_2pcf_from_powerspectrum(FastPM2PCF *self, fastpm_fkfunc pkfunc, void * data, double r_max, int steps) { self->size = steps; self->step_size = r_max / steps; self->xi = malloc((steps + 1) * sizeof(double)); double logKMin = -10, logKMax = 5; double logKSteps = 10000; double logKStepSize = (logKMax - logKMin) / logKSteps; double pi = 3.141593; int i, j; for(i = 0; i <= steps; ++i) { double r = i * self->step_size; double res = 0; double prev = 0; for(j = 1; j <= logKSteps; ++j) { double logK = logKMin + j * logKStepSize; double k = exp(logK); double kr = k * r; double func = 1; if(kr > 0) func = sin(kr) / kr; func *= pkfunc(k, data) * k * k * k; res += (prev + func) / 2; prev = func; } res *= logKStepSize / (2 * pi * pi); self->xi[i] = res; } } static void _solve(int size, double * Cij, double * dfi, double * x) { gsl_matrix_view m = gsl_matrix_view_array(Cij, size, size); gsl_vector_view b = gsl_vector_view_array(dfi, size); gsl_vector_view xx = gsl_vector_view_array(x, size); gsl_permutation *p = gsl_permutation_alloc(size); int s; gsl_linalg_LU_decomp(&m.matrix, p, &s); gsl_linalg_LU_solve(&m.matrix, p, &b.vector, &xx.vector); } static void _readout(FastPMConstraint * constraints, int size, PM * pm, FastPMFloat * delta_x, double * dfi) { int i; for(i = 0; i < size; ++i) { int ii[3]; int d; int inBox = 1; int index = 0; for(d = 0; d < 3; ++d) { ii[d] = constraints[i].x[d] * pm->InvCellSize[d] - pm->IRegion.start[d]; if(ii[d] < 0 || ii[d] > pm->IRegion.size[d]) inBox = 0; index += ii[d] * pm->IRegion.strides[d]; } if(inBox) { dfi[i] = delta_x[index]; } else { dfi[i] = 0; } } MPI_Allreduce(MPI_IN_PLACE, dfi, size, MPI_DOUBLE, MPI_SUM, pm_comm(pm)); } static double _sigma(PM * pm, FastPMFloat * delta_x) { double d2 = 0.0; PMXIter xiter; for(pm_xiter_init(pm, &xiter); !pm_xiter_stop(&xiter); pm_xiter_next(&xiter)) { double od = delta_x[xiter.ind] - 1; d2 += od * od; } MPI_Allreduce(MPI_IN_PLACE, &d2, 1, MPI_DOUBLE, MPI_SUM, pm_comm(pm)); /* unbiased estimator of the variance. the mean is 1. */ d2 /= (pm_norm(pm) - 1); return sqrt(d2); } void fastpm_cg_apply_constraints(FastPMConstrainedGaussian *cg, PM * pm, FastPM2PCF *xi, FastPMFloat * delta_k) { FastPMConstraint * constraints = cg->constraints; int size; for(size = 0; constraints[size].x[0] >= 0; size ++) continue; int i; fastpm_info("Constrained Gaussian with %d constraints\n", size); double dfi[size]; double e[size]; double Cij[size * size]; double sigma = 0; FastPMFloat * delta_x = pm_alloc(pm); pm_assign(pm, delta_k, delta_x); pm_c2r(pm, delta_x); sigma = _sigma(pm, delta_x); fastpm_info("Measured sigma on the grid = %g\n", sigma); _readout(constraints, size, pm, delta_x, dfi); for(i = 0; i < size; ++i) { dfi[i] = (1 + constraints[i].c * sigma) - dfi[i]; int j; for(j = i; j < size; ++j) { int d; double r = 0; for(d = 0; d < 3; ++d) { double dx = constraints[i].x[d] - constraints[j].x[d]; if(dx > 0.5*pm->BoxSize[d]){ dx -= pm->BoxSize[d]; } else if(dx < -0.5*pm->BoxSize[d]){ dx += pm->BoxSize[d]; } r += dx * dx; } r = sqrt(r); double v = fastpm_2pcf_eval(xi, r); Cij[i * size + j] = v; Cij[j * size + i] = v; } } _solve(size, Cij, dfi, e); PMXIter xiter; for(pm_xiter_init(pm, &xiter); !pm_xiter_stop(&xiter); pm_xiter_next(&xiter)) { double v = 0; for(i = 0; i < size; ++i) { int d; double r = 0; for(d = 0; d < 3; d ++) { double dx = xiter.iabs[d] * pm->CellSize[d] - constraints[i].x[d]; if(dx > 0.5*pm->BoxSize[d]){ dx -= pm->BoxSize[d]; } else if(dx < -0.5*pm->BoxSize[d]){ dx += pm->BoxSize[d]; } r += dx * dx; } r = sqrt(r); v += e[i] * fastpm_2pcf_eval(xi, r); } delta_x[xiter.ind] += v; } _readout(constraints, size, pm, delta_x, dfi); for(i = 0; i < size; i ++) { fastpm_info("After constraints, Realization x[] = %g %g %g overdensity = %g, peak-sigma= %g\n", constraints[i].x[0], constraints[i].x[1], constraints[i].x[2], (dfi[i] - 1.0), (dfi[i] - 1.0) / sigma); } pm_r2c(pm, delta_x, delta_k); pm_free(pm, delta_x); }
{ "alphanum_fraction": 0.5026872691, "avg_line_length": 27.4377880184, "ext": "c", "hexsha": "b4092458788fcf4eec6a9135241c676ec223b339", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/constrainedgaussian.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/constrainedgaussian.c", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/constrainedgaussian.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1805, "size": 5954 }
#include <stdlib.h> #include <math.h> #include <fftw3.h> #include <gsl/gsl_sf_result.h> #include <gsl/gsl_sf_gamma.h> #include "fftlog.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* This code is FFTLog, which is described in arXiv:astro-ph/9905191 */ static double_complex lngamma_fftlog(double_complex z) { gsl_sf_result lnr, phi; gsl_sf_lngamma_complex_e(creal(z), cimag(z), &lnr, &phi); #ifdef _COMPLEX_STRUCT double_complex res = {lnr.val, phi.val}; return res; #else return lnr.val + I*phi.val; #endif } static double_complex gamma_fftlog(double_complex z) { return cexp(lngamma_fftlog(z)); } static double_complex polar (double r, double phi) { #ifdef _COMPLEX_STRUCT double_complex res = {r*cos(phi) , r*sin(phi)}; return res; #else return (r*cos(phi) +I*(r*sin(phi))); #endif } static void lngamma_4(double x, double y, double* lnr, double* arg) { #ifdef _COMPLEX_STRUCT double_complex z = {x,y}; double_complex w = lngamma_fftlog(z); #else double complex w = lngamma_fftlog(x+y*I); #endif if(lnr) *lnr = creal(w); if(arg) *arg = cimag(w); } static double goodkr(int N, double mu, double q, double L, double kr) { double xp = (mu+1+q)/2; double xm = (mu+1-q)/2; double y = M_PI*N/(2*L); double lnr, argm, argp; lngamma_4(xp, y, &lnr, &argp); lngamma_4(xm, y, &lnr, &argm); double arg = log(2/kr) * N/L + (argp + argm)/M_PI; double iarg = round(arg); if(arg != iarg) kr *= exp((arg - iarg)*L/N); return kr; } void compute_u_coefficients(int N, double mu, double q, double L, double kcrc, double_complex u[]) { double y = M_PI/L; double k0r0 = kcrc * exp(-L); double t = -2*y*log(k0r0/2); if(q == 0) { double x = (mu+1)/2; double lnr, phi; for(int m = 0; m <= N/2; m++) { lngamma_4(x, m*y, &lnr, &phi); u[m] = polar(1.0,m*t + 2*phi); } } else { double xp = (mu+1+q)/2; double xm = (mu+1-q)/2; double lnrp, phip, lnrm, phim; for(int m = 0; m <= N/2; m++) { lngamma_4(xp, m*y, &lnrp, &phip); lngamma_4(xm, m*y, &lnrm, &phim); u[m] = polar(exp(q*log(2) + lnrp - lnrm), m*t + phip - phim); } } for(int m = N/2+1; m < N; m++) u[m] = conj(u[N-m]); if((N % 2) == 0) { #ifdef _COMPLEX_STRUCT double_complex z = {creal(u[N/2]) , 0.0}; u[N/2] = z; #else u[N/2] = (creal(u[N/2]) + I*0.0); #endif } } void fht(int N, const double r[], const double_complex a[], double k[], double_complex b[], double mu, double q, double kcrc, int noring, double_complex* u) { double L = log(r[N-1]/r[0]) * N/(N-1.); double_complex* ulocal = NULL; if(u == NULL) { if(noring) kcrc = goodkr(N, mu, q, L, kcrc); ulocal = malloc (sizeof(double_complex)*N); compute_u_coefficients(N, mu, q, L, kcrc, ulocal); u = ulocal; } /* Compute the convolution b = a*u using FFTs */ fftw_plan forward_plan = fftw_plan_dft_1d(N, (fftw_complex*) a, (fftw_complex*) b, -1, FFTW_ESTIMATE); fftw_plan reverse_plan = fftw_plan_dft_1d(N, (fftw_complex*) b, (fftw_complex*) b, +1, FFTW_ESTIMATE); fftw_execute(forward_plan); for(int m = 0; m < N; m++) #ifdef _COMPLEX_STRUCT { double_complex z = _Cmulcc(b[m],u[m]); z = _Cmulcr(z, 1/(double)(N)); b[m] = z; } #else b[m] *= u[m] / (double)(N); // divide by N since FFTW doesn't normalize the inverse FFT #endif fftw_execute(reverse_plan); fftw_destroy_plan(forward_plan); fftw_destroy_plan(reverse_plan); /* Reverse b array */ double_complex tmp; for(int n = 0; n < N/2; n++) { tmp = b[n]; b[n] = b[N-n-1]; b[N-n-1] = tmp; } /* Compute k's corresponding to input r's */ double k0r0 = kcrc * exp(-L); k[0] = k0r0/r[0]; for(int n = 1; n < N; n++) k[n] = k[0] * exp(n*L/N); free(ulocal); } void fftlog_ComputeXi2D(double bessel_order,int N,const double l[],const double cl[], double th[], double xi[]) { double_complex* a = malloc(sizeof(double_complex)*N); double_complex* b = malloc(sizeof(double_complex)*N); for(int i=0;i<N;i++){ #ifdef _COMPLEX_STRUCT double_complex z = {l[i]*cl[i],0.0}; a[i]=z; #else a[i]=l[i]*cl[i]; #endif } fht(N,l,a,th,b,bessel_order,0,1,1,NULL); for(int i=0;i<N;i++) xi[i]=creal(b[i])/(2*M_PI*th[i]); free(a); free(b); } void fftlog_ComputeXiLM(double l, double m, int N, const double k[], const double pk[], double r[], double xi[]) { double_complex* a = malloc(sizeof(double_complex)*N); double_complex* b = malloc(sizeof(double_complex)*N); for(int i = 0; i < N; i++){ #ifdef _COMPLEX_STRUCT double_complex z= { pow(k[i], m - 0.5) * pk[i],0}; a[i] = z; #else a[i] = pow(k[i], m - 0.5) * pk[i]; #endif } fht(N, k, a, r, b, l + 0.5, 0, 1, 1, NULL); for(int i = 0; i < N; i++) xi[i] = pow(2*M_PI*r[i], -(m-0.5)) * creal(b[i]); free(a); free(b); } void pk2xi(int N, const double k[], const double pk[], double r[], double xi[]) { fftlog_ComputeXiLM(0, 2, N, k, pk, r, xi); } void xi2pk(int N, const double r[], const double xi[], double k[], double pk[]) { static const double TwoPiCubed = 8*M_PI*M_PI*M_PI; fftlog_ComputeXiLM(0, 2, N, r, xi, k, pk); for(int j = 0; j < N; j++) pk[j] *= TwoPiCubed; }
{ "alphanum_fraction": 0.6009578544, "avg_line_length": 24.7393364929, "ext": "c", "hexsha": "fb9d0369af59ea20b36dffed3cc4e7af60b189e3", "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": "6c77d626c0171bc0937c66f562a313e019ce8bf3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "cmbant/CCL", "max_forks_repo_path": "src/fftlog.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6c77d626c0171bc0937c66f562a313e019ce8bf3", "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": "cmbant/CCL", "max_issues_repo_path": "src/fftlog.c", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "6c77d626c0171bc0937c66f562a313e019ce8bf3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "cmbant/CCL", "max_stars_repo_path": "src/fftlog.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1885, "size": 5220 }
#include <stdlib.h> #include <stdio.h> #include <math.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 "fresnel.h" #define acc 1e-8 /* Used for previous version of branching between cases 1a, 1b and 2 in ComputeInt */ /* static const double betathreshold = 1./10; */ /* static const double invbetathreshold = 10.; */ /* static const double lambdathreshold = 0.01; */ /* Used for previous version of branching between cases 1a, 1b and 2 in ComputeInt */ /* static const double factorbranchingcondition = 0.2154434690031884; */ /* static const double case1athreshold = 0.1; */ /* Used for case 0 - hoping to cover previous instability */ /* static const double case0threshold = 0.05; */ /* Used for branching between cases 1a, 1b, 2, 3 and 4 in ComputeInt */ /* FIXME: another round of refinement would be welcome, case 3 has some cases with 1e-4 error */ static const double p2threshold = 0.02; static const double p1threshold1 = 0.1; static const double p1threshold2 = 100.; static const double p2p1slopethreshold = 0.2; static const double coeffdeltaC[13] = {-0.1,-0.0462962962963,-0.0230769230769,-0.0136554621849,-0.00899470899471,-0.00636363636364,-0.00473664266768,-0.00366161616162,-0.00291467938527,-0.00237483953787,-0.0019721019721,-0.00166370896185,-0.00142235123367}; static const double coeffdeltaS[13] = {-0.0714285714286,-0.0318181818182,-0.0174603174603,-0.0109649122807,-0.00750988142292,-0.00546058879392,-0.00414746543779,-0.00325630252101,-0.00262408157145,-0.00215946843854,-0.00180809015222,-0.00153594771242,-0.0013209013209}; static const double fcoeff[12] = {0.3989422275318915, 1.839999368141345e-7, -0.2992429124371606, 0.0029447692036381, 2.48395059327971, 3.897790465813753, -140.2709114924737, 952.371347498219, -3660.703989590287, 8649.34061360465, -11740.93693284928, 7032.8915074629}; static const double gcoeff[12] = {0, 0.1994718004197629, -0.000125952146250442, -0.7386823670326993, -0.353224701618227, 19.45013452321292, -97.8846433217499, 221.1470704754588, -32.29876222016862, -1102.56036216157, 2554.184335427029, -1962.422566478277}; static double invn[12] = {1., 0.5, 0.3333333333333333, 0.25, 0.2, 0.1666666666666667, 0.1428571428571428, 0.125, 0.1111111111111111, 0.1, 0.0909090909090909, 0.0833333333333333}; /* Use for Chebyshev, case 3 */ static double ChebyshevNodes[6] = {0.965925826289068,0.7071067811865475,0.2588190451025207,-0.2588190451025207,-0.7071067811865475,-0.965925826289068}; static double ChebyshevWeights[6][6] = {{0.3333333333333333,0.3333333333333333,0.3333333333333333,0.3333333333333333,0.3333333333333333,0.3333333333333333},{0.3219752754296894,0.2357022603955158,0.0862730150341736,-0.0862730150341736,-0.2357022603955158,-0.3219752754296894},{0.2886751345948129,0.,-0.2886751345948129,-0.2886751345948129,0.,0.2886751345948129},{0.2357022603955158,-0.2357022603955158,-0.2357022603955158,0.2357022603955158,0.2357022603955158,-0.2357022603955158},{0.1666666666666667,-0.3333333333333333,0.1666666666666667,0.1666666666666667,-0.3333333333333333,0.1666666666666667},{0.0862730150341736,-0.2357022603955158,0.3219752754296894,-0.3219752754296894,0.2357022603955158,-0.0862730150341736}}; /* Function computing cexp(I*x)-1 without loss of accuracy*/ static double complex cexpm1i(double x){ double rr;//rr=cos(x)-1=2*sin(x/2)**2 double ri=sin(x); double sinhalf=sin(0.5*x); rr=-2.0*sinhalf*sinhalf; return rr+I*ri; }; /* Function computing the Fresnel integral for any real (positive) number, with 1e-8 accuracy */ /* Reference used: Computation of Fresnel Integrals. II by K. Mielenz, [J. Res. Natl. Inst. Stand. Technol. 105, 589 (2000)] */ static double complex FresnelE(const double x) { double complex res; /* Check argument */ if(x<0) return -FresnelE(-x); /* If x<2, Taylor expansion */ else if(x<2) { double C = 0; double S = 0; double x3 = x*x*x; double x4 = x3*x; int n = 0; double deltaC = x; double deltaS = x3/3.; while(true) { C += deltaC; S += deltaS; //deltaC = -(4*n+1.)/(4*n+5.)/(2*n+1.)/(2*n+2.) * x4 * deltaC; //deltaS = -(4*n+3.)/(4*n+7.)/(2*n+2.)/(2*n+3.) * x4 * deltaS; deltaC = coeffdeltaC[n] * x4 * deltaC; deltaS = coeffdeltaS[n] * x4 * deltaS; n++; if( (fabs(deltaC)<acc && fabs(deltaS)<acc) || n>12) break; } res = C + I*S; } /* If x>2, Mielenz-Boersma formula using tabulated coeffs */ else { double xinv = 1./x; double xinv2 = xinv*xinv; double y[12] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; y[0] = xinv; for(int i=1; i<12; i++) y[i] = y[i-1]*xinv2; double f = 0; double g = 0; for(int i=0; i<12; i++) { f += fcoeff[i] * y[i]; g += gcoeff[i] * y[i]; } res = sqrt(PI/2) * ( (1+I)/2 - (g+I*f) * cexp(I*x*x)); } return res; } /* In fact equivalent to Case 2 */ //static double complex ComputeIntCase0( // gsl_vector* coeffsAreal, /* */ // gsl_vector* coeffsAimag, /* */ // double p0, /* */ // double p1, /* */ // double p2, /* */ // double eps) /* */ // { // /* Get poly coeffs and rescale by epsilon */ // double complex coeffs[4] = {0.,0.,0.,0.}; // double epspow[4] = {0.,0.,0.,0.}; // epspow[0] = 1.; epspow[1] = eps; epspow[2] = eps*eps; epspow[3] = eps * epspow[2]; // for(int i=0; i<=3; i++) { // coeffs[i] = epspow[i] * (gsl_vector_get(coeffsAreal, i+1) + I*gsl_vector_get(coeffsAimag, i+1)); // } // double p0r = p0; // double p1r = p1*epspow[1]; // double p2r = p2*epspow[2]; // // /* In case p2<0, conjugation */ // int conjug = 0; // if(p2r<0) { // conjug=1; // p2r = -p2r; // p1r = -p1r; // p0r = -p0r; // for(int i=0; i<=3; i++) coeffs[i] = conj(coeffs[i]) ; // } // // // // //printf("case0\n"); // // /* Prefactor and bounds after change of variable */ // double sqrtp2r = sqrt(p2r); // double complex factor = 1./sqrtp2r*cexp(I*p0r); // double a = p1r/(2*sqrtp2r); // double b = p1r/(2*sqrtp2r) + sqrtp2r; // /* Coeffs in polynomial changed by shift */ // double alpha = 1./sqrtp2r; // double beta = -p1r/(2*p2r); // double complex a0 = coeffs[0]; double complex a1 = coeffs[1]; double complex a2 = coeffs[2]; double complex a3 = coeffs[3]; // double alpha2 = alpha*alpha; double beta2 = beta*beta; // double complex a0p = a0 + a1*beta + a2*beta2 + a3*beta2*beta; // double complex a1p = a1*alpha + 2*a2*alpha*beta + 3*a3*alpha*beta2; // double complex a2p = a2*alpha2 + 3*a3*alpha2*beta; // double complex a3p = a3*alpha2*alpha; // // /* Result */ // double complex res = 0.; // res = factor*((a0p + I/2*a2p) * (FresnelE(b) - FresnelE(a)) + (1./2*(a3p - I*a1p) - I/2*a2p*b - I/2*a3p*b*b) * cexp(I*b*b) - (1./2*(a3p - I*a1p) - I/2*a2p*a - I/2*a3p*a*a) * cexp(I*a*a)); // // // //printf("%g, %g, %g \n", creal(factor), creal((a0p + I/2*a2p) * (FresnelE(b) - FresnelE(a))), creal(+ (1./2*(a3p - I*a1p) - I/2*a2p*b - I/2*a3p*b*b) * cexp(I*b*b) - (1./2*(a3p - I*a1p) - I/2*a2p*a - I/2*a3p*a*a) * cexp(I*a*a))); // //exit(0); // // /* Remembering conjugation */ // if(conjug) res = conj(res); // return res; // } double complex ComputeIntCase1a( const double complex* coeffsA, /* */ const double p1, /* */ const double p2, /* */ const double scale) /* */ { /* Setting up the coefficients and the required accuracy */ double complex coeffs[12] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; for(int i=0; i<=3; i++) coeffs[i] = coeffsA[i]; int maxj0 = 3; double acctol = 1.e-5/scale; /* Polynomial given by the expansion of cexp(I*p1*x) */ double complex poly1[8] = {0.,0.,0.,0.,0.,0.,0.,0.}; double p1abs = fabs(p1); double complex term1 = 1.; double term1absmax = 1.; int maxj1 = 0; for(int i=0; i<8; i++) { poly1[i] = term1; term1absmax = term1absmax * p1abs * invn[i]; /* Note: invn[i] = 1/(i+1) */ if(term1absmax<acctol) break; term1 = term1 * I*p1 * invn[i]; maxj1++; } /* Polynomial given by the expansion of cexp(I*p2*x2) */ double complex poly2[11] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double p2abs = fabs(p2); double complex term2 = 1.; double term2absmax = 1.; int maxj2 = 0; for(int i=0; i<4; i++) { poly2[2*i] = term2; term2absmax = term2absmax * p2abs * invn[i]; /* Note: invn[i] = 1/(i+1) */ if(term2absmax<acctol) break; term2 = term2 * I*p2 * invn[i]; maxj2 += 2; } /* Multiplying in place the polynomials - we cut according to the fact that we allow for only 12 coeffs up to x^11 (assuming the rest would be negligible anyway), and we know the constant in poly1 and poly2 is always 1. */ for(int i=min(11, maxj0+maxj1); i>=0; i--) { for(int j=max(1, i-maxj0); j<=min(i, maxj1); j++) { coeffs[i] += coeffs[i-j] * poly1[j]; } } maxj0 = min(11, maxj0 + maxj1); for(int i=min(11, maxj0+maxj2); i>=0; i--) { for(int j=max(1, i-maxj0); j<=min(i, maxj2); j++) { coeffs[i] += coeffs[i-j] * poly2[j]; } } maxj0 = min(11, maxj0 + maxj2); /* Computing the integral itself */ double complex res = 0.; for(int i=0; i<=maxj0; i++) { res += coeffs[i] * invn[i]; /* Note: invn[i] = 1/(i+1) */ } return res; } double complex ComputeIntCase1b( const double complex* coeffsA, /* */ const double p1, /* */ const double p2, /* */ const double scale) /* */ { /* Setting up the coefficients and the required accuracy */ double complex coeffs[12] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; for(int i=0; i<=3; i++) coeffs[i] = coeffsA[i]; int maxj0 = 3; double acctol = 1.e-5/scale; /* Polynomial given by the expansion of cexp(I*p2*x2) */ double complex poly2[11] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double p2abs = fabs(p2); double complex term2 = 1.; double term2absmax = 1.; int maxj2 = 0; for(int i=0; i<4; i++) { poly2[2*i] = term2; term2absmax = term2absmax * p2abs * invn[i]; /* Note: invn[i] = 1/(i+1) */ if(term2absmax<acctol) break; term2 = term2 * I*p2 * invn[i]; maxj2 += 2; } /* Multiplying in place the polynomials - we cut according to the fact that we allow for only 12 coeffs up to x^11 (assuming the rest would be negligible anyway), and we know the constant in poly2 is always 1. */ for(int i=min(11, maxj0+maxj2); i>=0; i--) { for(int j=max(1, i-maxj0); j<=min(i, maxj2); j++) { coeffs[i] += coeffs[i-j] * poly2[j]; } } maxj0 = min(11, maxj0 + maxj2); /* Go down the recursion relation */ double invp1 = 1./p1; double complex coeffE1 = 0.; double complex coeffE1minus1 = 0; for(int i=maxj0; i>=1; i--) { coeffE1 += -I*invp1 * coeffs[i]; coeffs[i-1] += I*invp1 * i * coeffs[i]; } coeffE1minus1 = -I*invp1 * coeffs[0]; /* Result */ double complex cexpm1ip1 = cexpm1i(p1); double complex res = (coeffE1*(cexpm1ip1+1.) + coeffE1minus1*cexpm1ip1); return res; } double complex ComputeIntCase2( const double complex* coeffsA, /* */ const double p1, /* */ const double p2) /* */ { /* Setting up the coefficients */ double complex coeffs[4] = {0.,0.,0.,0.}; for(int i=0; i<=3; i++) coeffs[i] = coeffsA[i]; double complex coeffE2 = 0; double complex coefffresnel = 0; double complex constant = 0; /* Conjugate if required */ int conjug = 0; double p1b = p1; double p2b = p2; if(p2<0) { conjug = 1; p1b = -p1; p2b = -p2; for(int i=0; i<=3; i++) coeffs[i] = conj(coeffs[i]); } /* n=3 and n=2 */ double inv2p2 = 1. / (2.*p2b); for(int i=3; i>=2; i--) { coeffE2 += -I*inv2p2 * coeffs[i]; coeffs[i-2] += I*inv2p2 * (i-1) * coeffs[i]; coeffs[i-1] += -p1b * inv2p2 * coeffs[i]; } /* n=1 */ coeffE2 += -I*inv2p2 * coeffs[1]; constant = I*inv2p2 * coeffs[1]; coefffresnel += -p1b * inv2p2 * coeffs[1]; /* n=0 */ coefffresnel += coeffs[0]; /* Fresnel integral and complex exponential */ double complex E2 = cexp(I * (p1b + p2b)); double sqrtp2 = sqrt(p2b); double invsqrtp2 = 1./sqrtp2; double halfratio = 0.5 * p1b * invsqrtp2; double complex fresnel = cexp(-I*halfratio*halfratio) * invsqrtp2 * (FresnelE(halfratio + sqrtp2) - FresnelE(halfratio)); /* Result */ double complex res = (constant + coeffE2*E2 + coefffresnel*fresnel); if(conjug) res = conj(res); /* Remember possible conjugation */ return res; } double complex ComputeIntCase3( const double complex* coeffsA, /* */ const double p1, /* */ const double p2) /* */ { /* Prepare change of variables */ double r = p2/p1; /* Compute integrand F on nodes */ double Fvalues[6] = {0.,0.,0.,0.,0.,0.}; double xk; double y; double sqrtterm; double factor; double x; for(int i=0; i<6; i++) { xk = ChebyshevNodes[i]; y = (1.+xk)/2.; sqrtterm = sqrt(1. + 4.*r*(1.+r)*y); factor = (1.+r)/sqrtterm; x = (2.*(1.+r)*y)/(1. + sqrtterm); Fvalues[i] = coeffsA[3]; for(int j=2; j>=0; j--) Fvalues[i] = coeffsA[j] + x*Fvalues[i]; Fvalues[i] = factor * Fvalues[i]; } /* Compute Chebyshev coefficients ci */ double complex c[6] = {0.,0.,0.,0.,0.,0.}; for(int i=0; i<6; i++) { for(int j=0; j<6; j++) c[i] += ChebyshevWeights[i][j] * Fvalues[j]; } /* Coefficients of polynomial in 1/(I*p), p=p1*(1+r) */ double p = p1*(1.+r); double complex coeffszcos[6] = {0.,0.,0.,0.,0.,0.}; double complex coeffszsin[6] = {0.,0.,0.,0.,0.,0.}; coeffszcos[0] = c[1] + c[3] + c[5]; coeffszcos[1] = -8.*c[2] - 32.*c[4]; coeffszcos[2] = 96.*c[3] + 800.*c[5]; coeffszcos[3] = -1536.*c[4]; coeffszcos[4] = 30720.*c[5]; coeffszcos[5] = 0.; coeffszsin[0] = 0.5*c[0] + c[2] + c[4]; coeffszsin[1] = -2.*c[1] - 18.*c[3] - 50.*c[5]; coeffszsin[2] = 16.*c[2] + 320.*c[4]; coeffszsin[3] = -192.*c[3] -6720.*c[5]; coeffszsin[4] = 3072.*c[4]; coeffszsin[5] = -61440.*c[5]; /* Coefficients of cos(p/2) and sin(p/2) */ double complex z = 1./(I*p); double complex coeffcos = coeffszcos[5]; for(int i=4; i>=0; i--) coeffcos = coeffszcos[i] + z*coeffcos; double complex coeffsin = coeffszsin[5]; for(int i=4; i>=0; i--) coeffsin = coeffszsin[i] + z*coeffsin; coeffcos = z * coeffcos; coeffsin = z * coeffsin; /* Result */ double pov2 = p/2.; return cexp(I*pov2) * (2*cos(pov2)*coeffcos + 2*I*sin(pov2)*coeffsin); } double complex ComputeIntCase4( const double complex* coeffsA, /* */ const double p1, /* */ const double p2) /* */ { double complex a0 = coeffsA[0]; double complex a1 = coeffsA[1]; double complex a2 = coeffsA[2]; double complex a3 = coeffsA[3]; double r = 2.*p2/p1; double inv1plusr = 1./(1.+r); double inv1plusr2 = inv1plusr*inv1plusr; double inv1plusr4 = inv1plusr2*inv1plusr2; double invp1 = 1./p1; double invp12 = invp1*invp1; double invp13 = invp12*invp1; double complex term1 = cexp(I*(p1 + p2))*(-I*invp1*(a0 + a1 + a2 + a3)*inv1plusr + invp12*(a1 + 2.*a2 + 3.*a3)*inv1plusr2 + I*invp13*(2.*a2 + 6.*a3 + r*(3.*a3 - a1))*inv1plusr4); double complex term2 = - (-I*invp1*a0 + invp12*a1 + I*invp13*(2.*a2 - a1*r)); return term1 + term2; } double complex ComputeInt( gsl_matrix* splinecoeffsAreal, /* */ gsl_matrix* splinecoeffsAimag, /* */ gsl_matrix* quadsplinecoeffsphase) /* */ { double complex res = 0.; double complex resint = 0.; /* Number of points - i.e. nb of intervals + 1 */ /* Assumes that the dimensions match and that the frequency vectors are the same between the different splinecoeffs */ int nbpts = (int) quadsplinecoeffsphase->size1; //clock_t tbegtotal = clock(); for(int j=0; j<nbpts-1; j++) { double eps = gsl_matrix_get(quadsplinecoeffsphase, j+1, 0) - gsl_matrix_get(quadsplinecoeffsphase, j, 0); double epspow[4]; epspow[0] = 1.; epspow[1] = eps; epspow[2] = eps*eps; epspow[3] = eps*epspow[2]; double p0 = gsl_matrix_get(quadsplinecoeffsphase, j, 1); /* Rescale the interval to [0,1] and scale out the constant amplitude term */ double p1 = gsl_matrix_get(quadsplinecoeffsphase, j, 2) * eps; double p2 = gsl_matrix_get(quadsplinecoeffsphase, j, 3) * epspow[2]; double complex A0 = gsl_matrix_get(splinecoeffsAreal, j, 1) + I*gsl_matrix_get(splinecoeffsAimag, j, 1); double complex A0inv = 1./A0; double A0abs = cabs(A0); /* Used for accuracy requirement of adaptive Taylor expansions Ia and Ib */ double complex coeffsA[4] = {0.,0.,0.,0.}; coeffsA[0] = 1.; for(int i=1; i<=3; i++) coeffsA[i] = epspow[i] * A0inv * (gsl_matrix_get(splinecoeffsAreal, j, i+1) + I*gsl_matrix_get(splinecoeffsAimag, j, i+1)); /* Factor scaled out */ double complex factor = eps * A0 * cexp(I*p0); double absp1 = fabs(p1); double absp2 = fabs(p2); if(absp1<p1threshold1 && absp2<p2threshold) { resint = factor * ComputeIntCase1a(coeffsA, p1, p2, A0abs); } else if(p1threshold1<=absp1 && absp1<p1threshold2 && absp2<p2threshold) { resint = factor * ComputeIntCase1b(coeffsA, p1, p2, A0abs); } else if(absp2>=p2p1slopethreshold*absp1 && absp2>=p2threshold) { resint = factor * ComputeIntCase2(coeffsA, p1, p2); } else if(absp2<p2p1slopethreshold*absp1 && absp2>=p2threshold && absp1<p1threshold2) { resint = factor * ComputeIntCase3(coeffsA, p1, p2); } else { resint = factor * ComputeIntCase4(coeffsA, p1, p2); } res += resint; } return res; }
{ "alphanum_fraction": 0.610921119, "avg_line_length": 39.8147321429, "ext": "c", "hexsha": "72aa8b3c855d9d8e130a59f8c7a452eb565b9d49", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/fresnel.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": "tools/fresnel.c", "max_line_length": 718, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/fresnel.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 6753, "size": 17837 }
/* matrix/gsl_matrix_complex_long_double.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_MATRIX_COMPLEX_LONG_DOUBLE_H__ #define __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_complex_long_double.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 size1; size_t size2; size_t tda; long double * data; gsl_block_complex_long_double * block; int owner; } gsl_matrix_complex_long_double ; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_view; typedef _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view; typedef struct { gsl_matrix_complex_long_double matrix; } _gsl_matrix_complex_long_double_const_view; typedef const _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view; /* Allocation */ GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix_complex_long_double * gsl_matrix_complex_long_double_alloc_from_matrix (gsl_matrix_complex_long_double * b, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_row_from_matrix (gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN gsl_vector_complex_long_double * gsl_vector_complex_long_double_alloc_col_from_matrix (gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN void gsl_matrix_complex_long_double_free (gsl_matrix_complex_long_double * m); /* Views */ GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_submatrix (gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_row (gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_column (gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_diagonal (gsl_matrix_complex_long_double * m); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subdiagonal (gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_superdiagonal (gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subrow (gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_complex_long_double_view gsl_matrix_complex_long_double_subcolumn (gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array (long double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_array_with_tda (long double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_view gsl_matrix_complex_long_double_view_vector_with_tda (gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_submatrix (const gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_row (const gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_column (const gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_diagonal (const gsl_matrix_complex_long_double * m); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_superdiagonal (const gsl_matrix_complex_long_double * m, const size_t k); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subrow (const gsl_matrix_complex_long_double * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_complex_long_double_const_view gsl_matrix_complex_long_double_const_subcolumn (const gsl_matrix_complex_long_double * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array (const long double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_array_with_tda (const long double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_complex_long_double_const_view gsl_matrix_complex_long_double_const_view_vector_with_tda (const gsl_vector_complex_long_double * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_complex_long_double_set_zero (gsl_matrix_complex_long_double * m); GSL_FUN void gsl_matrix_complex_long_double_set_identity (gsl_matrix_complex_long_double * m); GSL_FUN void gsl_matrix_complex_long_double_set_all (gsl_matrix_complex_long_double * m, gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_fread (FILE * stream, gsl_matrix_complex_long_double * m) ; GSL_FUN int gsl_matrix_complex_long_double_fwrite (FILE * stream, const gsl_matrix_complex_long_double * m) ; GSL_FUN int gsl_matrix_complex_long_double_fscanf (FILE * stream, gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_fprintf (FILE * stream, const gsl_matrix_complex_long_double * m, const char * format); GSL_FUN int gsl_matrix_complex_long_double_memcpy(gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_swap(gsl_matrix_complex_long_double * m1, gsl_matrix_complex_long_double * m2); GSL_FUN int gsl_matrix_complex_long_double_swap_rows(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_swap_columns(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_swap_rowcol(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_transpose (gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_transpose_memcpy (gsl_matrix_complex_long_double * dest, const gsl_matrix_complex_long_double * src); GSL_FUN int gsl_matrix_complex_long_double_isnull (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_ispos (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_isneg (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_isnonneg (const gsl_matrix_complex_long_double * m); GSL_FUN int gsl_matrix_complex_long_double_add (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_sub (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_mul_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_div_elements (gsl_matrix_complex_long_double * a, const gsl_matrix_complex_long_double * b); GSL_FUN int gsl_matrix_complex_long_double_scale (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_add_constant (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); GSL_FUN int gsl_matrix_complex_long_double_add_diagonal (gsl_matrix_complex_long_double * a, const gsl_complex_long_double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_complex_long_double_get_row(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t i); GSL_FUN int gsl_matrix_complex_long_double_get_col(gsl_vector_complex_long_double * v, const gsl_matrix_complex_long_double * m, const size_t j); GSL_FUN int gsl_matrix_complex_long_double_set_row(gsl_matrix_complex_long_double * m, const size_t i, const gsl_vector_complex_long_double * v); GSL_FUN int gsl_matrix_complex_long_double_set_col(gsl_matrix_complex_long_double * m, const size_t j, const gsl_vector_complex_long_double * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x); GSL_FUN INLINE_DECL gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN gsl_complex_long_double gsl_matrix_complex_long_double_get(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { gsl_complex_long_double zero = {{0,0}}; if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ; } } #endif return *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN void gsl_matrix_complex_long_double_set(gsl_matrix_complex_long_double * m, const size_t i, const size_t j, const gsl_complex_long_double x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } } #endif *(gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) = x ; } INLINE_FUN gsl_complex_long_double * gsl_matrix_complex_long_double_ptr(gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } INLINE_FUN const gsl_complex_long_double * gsl_matrix_complex_long_double_const_ptr(const gsl_matrix_complex_long_double * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (const gsl_complex_long_double *)(m->data + 2*(i * m->tda + j)) ; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MATRIX_COMPLEX_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.6967141429, "avg_line_length": 44.4666666667, "ext": "h", "hexsha": "d22636e2c5d73108a4442aafc4b60f66542ae9a5", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "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": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_matrix_complex_long_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3479, "size": 16008 }
/** * Author : Pierre Schnizer * Date: January 2003 */ #ifndef PyGSL_FUNCTION_HELPERS_H #define PyGSL_FUNCTION_HELPERS_H 1 /* ------------------------------------------------------------------------- See gsl_functions_reference.txt for a compilation of the different callbacks found in GSL. Todo: Perhaps split the file in general helpers and special helpers ???? Make all helpers reporting error via PyGSL_set_error_string_for_callback List all functions in these file in a header ------------------------------------------------------------------------- */ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multiroots.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_monte.h> #include <pygsl/utils.h> #include <pygsl/intern.h> #include <pygsl/error_helpers.h> #include <pygsl/general_helpers.h> #include <pygsl/block_helpers.h> #include <pygsl/function_helpers.h> #include <math.h> #include <setjmp.h> /* ------------------------------------------------------------------------- Helper Structs *_func_name : a descriptive message for the internal function used when reporting an error to the user. buffer_is_set : It depends on the user that she/he uses the *BUFFER in the function interfaces. So this variable is set to zero when the struct is generated. I hope this will stop the wrapper trying to jump to NIRVANA. ------------------------------------------------------------------------- */ /* * 11 December 2003 * I return the flag that GSL returned using the flag argument to longjmp. * This flag must be different from zero to be useful. GSL uses * 0 (== GSL_SUCCESS) to indicate it. I check for that here to see if it is * always like that. */ #if GSL_SUCCESS != 0 #error "The function helpers use longjmp. GSL_SUCCESS must be zero. Pygsl Design error" #endif typedef struct { PyObject *function; PyObject *arguments; const char * c_func_name; jmp_buf buffer; int buffer_is_set; } callback_function_params; typedef struct { PyObject *f; PyObject *df; PyObject *fdf; PyObject *arguments; const char * c_f_func_name; const char * c_df_func_name; const char * c_fdf_func_name; jmp_buf buffer; int buffer_is_set; } callback_function_params_fdf; /* ------------------------------------------------------------------------- Copy PyArray to gsl vector, gslarray and vice versa Are these functions ever needed by pure vector or matrix conversion? If so these functions should go into gsl_block_helpers.i ------------------------------------------------------------------------- */ /* 1. A_n O -> A_p */ int PyGSL_function_wrap_Op_On(const gsl_vector * x, gsl_vector *f, PyObject *callback, PyObject * arguments, int n, int p, const char *c_func_name); /* 2. A_n O -> A_n_p */ int PyGSL_function_wrap_Op_Opn(const gsl_vector * x, gsl_matrix *f, PyObject *callback, PyObject *arguments, int n, int p, const char * c_func_name); /* 3 dO -> d gsl_function */ /* 3.1 dO -> d d gsl_function_fdf */ PyGSL_API_EXTERN int PyGSL_function_wrap_helper(double x, double * result, double *result2, PyObject *callback, PyObject *arguments, const char *c_func_name); /* * Pass a NULL pointer for result 2, if not needed. */ /* 4. A_n O -> d (A_n) */ int PyGSL_function_wrap_On_O(const gsl_vector * x, PyObject *callback, PyObject *arguments, double *result1, gsl_vector *result2, int n, const char * c_func_name); /* 5. A_n O -> A_n A_n_p */ int PyGSL_function_wrap_Op_On_Opn(const gsl_vector * x, gsl_vector *f1, gsl_matrix *f2, PyObject *callback, PyObject *arguments, int n, int p, const char * c_func_name); /* ------------------------------------------------------------------------- Register Python Call backs Generic Helper Functions ------------------------------------------------------------------------ */ /* Callbacks using one function */ callback_function_params * PyGSL_convert_to_generic_function(PyObject *object, int *size, int *size2, const char * c_func_name); /* Callbacks using 3 functions */ callback_function_params_fdf * PyGSL_convert_to_generic_function_fdf(PyObject *object, int *size, int *size2, const char * c_f_func_name, const char * c_df_func_name, const char * c_fdf_func_name); void PyGSL_params_free(callback_function_params *p); void PyGSL_params_free_fdf(callback_function_params_fdf *p); double PyGSL_function_wrap(double x, void * params); double PyGSL_function_wrap_f(double x, void * params); double PyGSL_function_wrap_df(double x, void * params); void PyGSL_function_wrap_fdf(double x, void * params, double *f, double * fdf); gsl_function * PyGSL_convert_to_gsl_function(PyObject * object); gsl_function_fdf * PyGSL_convert_to_gsl_function_fdf(PyObject * object); /* Specialised functions ... should they go to callbacks? */ int PyGSL_multiroot_function_wrap(const gsl_vector *x, void *params, gsl_vector *f); int PyGSL_multiroot_function_wrap_f(const gsl_vector *x, void *params, gsl_vector *f); int PyGSL_multiroot_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *J); int PyGSL_multiroot_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); gsl_multiroot_function * PyGSL_convert_to_gsl_multiroot_function(PyObject * object); gsl_multiroot_function_fdf * PyGSL_convert_to_gsl_multiroot_function_fdf(PyObject * object); double PyGSL_multimin_function_wrap(const gsl_vector *x, void *params); double PyGSL_multimin_function_wrap_f(const gsl_vector *x, void *params); void PyGSL_multimin_function_wrap_df(const gsl_vector *x, void *params, gsl_vector *g); void PyGSL_multimin_function_wrap_fdf(const gsl_vector *x, void *params, double *f, gsl_vector *g); gsl_multimin_function * PyGSL_convert_to_gsl_multimin_function(PyObject * object); gsl_multimin_function_fdf * PyGSL_convert_to_gsl_multimin_function_fdf(PyObject * object); int PyGSL_multifit_function_wrap(const gsl_vector *x, void *params, gsl_vector *f); int PyGSL_multifit_function_wrap_f(const gsl_vector *x, void *params, gsl_vector *f); int PyGSL_multifit_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *df); int PyGSL_multifit_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *df); gsl_multifit_function * PyGSL_convert_to_gsl_multifit_function(PyObject * object); gsl_multifit_function_fdf * PyGSL_convert_to_gsl_multifit_function_fdf(PyObject * object); gsl_monte_function * PyGSL_convert_to_gsl_monte_function(PyObject * object); /* gsl_function */ extern char * pygsl_gsl_function; extern char * pygsl_gsl_f_function; extern char * pygsl_gsl_df_function; extern char * pygsl_gsl_fdf_function; /* gsl_multifit */ extern char * pygsl_multifit_function; extern char * pygsl_multifit_f_function; extern char * pygsl_multifit_df_function; extern char * pygsl_multifit_fdf_function; extern char * pygsl_multimin_function; extern char * pygsl_multimin_f_function; extern char * pygsl_multimin_df_function; extern char * pygsl_multimin_fdf_function; /* gsl_multiroot */ extern char * pygsl_multiroot_function; extern char * pygsl_multiroot_f_function; extern char * pygsl_multiroot_df_function; extern char * pygsl_multiroot_fdf_function; /* monte */ extern char * pygsl_monte_function; #ifndef _PyGSL_API_MODULE #define PyGSL_function_wrap_helper \ (*(int (*) (double, double *, double *, PyObject *, PyObject *, const char *)) PyGSL_API[PyGSL_function_wrap_helper_NUM]) #endif /* _PyGSL_API_MODULE */ #endif /* PyGSL_FUNCTION_HELPERS_H */
{ "alphanum_fraction": 0.6929053624, "avg_line_length": 34.1347826087, "ext": "h", "hexsha": "83a4972bd4a6bcf506fc1a2780b509f315697c9a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/function_helpers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1951, "size": 7851 }
#include "ccv.h" #include "ccv_internal.h" #include "nnc/ccv_nnc.h" #include "nnc/ccv_nnc_easy.h" #include "nnc/ccv_nnc_internal.h" #include "../_ccv_nnc_gemm_cpu_opt.h" #if HAVE_ACCELERATE_FRAMEWORK #include <Accelerate/Accelerate.h> #elif HAVE_CBLAS #include <cblas.h> #endif int _ccv_nnc_gemm_forw_cpu_sys(const int transpose_a[2], const int transpose_b[2], const ccv_nnc_tensor_view_t* const a, const ccv_nnc_tensor_view_t* const w, const ccv_nnc_tensor_view_t* const bias, ccv_nnc_tensor_view_t* const b) { #if (defined HAVE_CBLAS || defined HAVE_ACCELERATE_FRAMEWORK) assert(!bias || (bias->info.dim[1] == 0 || bias->info.dim[2] == 0 || bias->info.dim[3] == 0)); // It is a 1-d array int a_batch_size, a_rows, a_cols, a_batch_inc, a_rows_inc, a_cols_inc; int w_batch_size, w_rows, w_cols, w_batch_inc, w_rows_inc, w_cols_inc; int b_batch_size, b_rows, b_cols, b_batch_inc, b_rows_inc, b_cols_inc; const static int no_transpose[2] = {}; ccv_nnc_tensor_get_matrix_params(a->info, CCV_IS_TENSOR_VIEW(a) ? a->inc : a->info.dim, transpose_a, &a_batch_size, &a_rows, &a_cols, &a_batch_inc, &a_rows_inc, &a_cols_inc); ccv_nnc_tensor_get_matrix_params(w->info, CCV_IS_TENSOR_VIEW(w) ? w->inc : w->info.dim, transpose_b, &w_batch_size, &w_rows, &w_cols, &w_batch_inc, &w_rows_inc, &w_cols_inc); ccv_nnc_tensor_get_matrix_params(b->info, CCV_IS_TENSOR_VIEW(b) ? b->inc : b->info.dim, no_transpose, &b_batch_size, &b_rows, &b_cols, &b_batch_inc, &b_rows_inc, &b_cols_inc); assert(a_batch_size == b_batch_size); assert(a_batch_size == b_batch_size || a_batch_size == 1); if (a_batch_size == 1 && b_batch_size > 1) a_batch_inc = 0; assert(w_batch_size == a_batch_size || w_batch_size == 1); if (w_batch_size == 1 && b_batch_size > 1) w_batch_inc = 0; assert(a_rows == b_rows); assert(a_cols == w_rows); assert(w_cols == b_cols); const int is_transpose_a = ccv_nnc_is_matrix_transpose(a->info, transpose_a); const int is_transpose_w = ccv_nnc_is_matrix_transpose(w->info, transpose_b); if (bias) { float* const ones = (float*)ccmalloc(sizeof(float) * b_rows); int i; for (i = 0; i < b_rows; i++) ones[i] = 1; int bias_batch_size, bias_rows, bias_cols, bias_batch_inc, bias_rows_inc, bias_cols_inc; ccv_nnc_tensor_get_matrix_params(bias->info, CCV_IS_TENSOR_VIEW(bias) ? bias->inc : bias->info.dim, no_transpose, &bias_batch_size, &bias_rows, &bias_cols, &bias_batch_inc, &bias_rows_inc, &bias_cols_inc); assert(bias_batch_size == b_batch_size || bias_batch_size == 1); if (bias_batch_size == 1 && b_batch_size > 1) bias_batch_inc = 0; assert(bias_cols == b_cols); for (i = 0; i < b_batch_size; i++) cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, b_cols, b_rows, 1, 1.0, bias->data.f32 + i * bias_batch_inc, bias_rows_inc, ones, 1, 0.0, b->data.f32 + i * b_batch_inc, b_rows_inc); ccfree(ones); const int transa = is_transpose_w ? CblasTrans : CblasNoTrans; const int transb = is_transpose_a ? CblasTrans : CblasNoTrans; const int lda_inc = is_transpose_w ? w_cols_inc : w_rows_inc; const int ldb_inc = is_transpose_a ? a_cols_inc : a_rows_inc; for (i = 0; i < b_batch_size; i++) cblas_sgemm(CblasColMajor, transa, transb, b_cols, b_rows, a_cols, 1.0, w->data.f32 + i * w_batch_inc, lda_inc, a->data.f32 + i * a_batch_inc, ldb_inc, 1.0, b->data.f32 + i * b_batch_inc, b_rows_inc); } else { const int transa = is_transpose_w ? CblasTrans : CblasNoTrans; const int transb = is_transpose_a ? CblasTrans : CblasNoTrans; const int lda_inc = is_transpose_w ? w_cols_inc : w_rows_inc; const int ldb_inc = is_transpose_a ? a_cols_inc : a_rows_inc; int i; for (i = 0; i < b_batch_size; i++) cblas_sgemm(CblasColMajor, transa, transb, b_cols, b_rows, a_cols, 1.0, w->data.f32 + i * w_batch_inc, lda_inc, a->data.f32 + i * a_batch_inc, ldb_inc, 0.0, b->data.f32 + i * b_batch_inc, b_rows_inc); } return CCV_NNC_EXEC_SUCCESS; #else return CCV_NNC_EXEC_INVALID; #endif } int _ccv_nnc_gemm_back_cpu_sys(const int transpose_a[2], const int transpose_b[2], const ccv_nnc_tensor_view_t* const g, const ccv_nnc_tensor_view_t* const a, const ccv_nnc_tensor_view_t* const w, ccv_nnc_tensor_view_t* const dw, ccv_nnc_tensor_view_t* const bias, ccv_nnc_tensor_view_t* const h, const int flags) { #if (defined HAVE_CBLAS || defined HAVE_ACCELERATE_FRAMEWORK) // inputs: gradient, forw prop input, [w] // outputs: [output gradient], weight updates, bias updates assert(!bias || (bias->info.dim[1] == 0 || bias->info.dim[2] == 0 || bias->info.dim[3] == 0)); // It is a 2-d or 3-d array. int g_batch_size, g_rows, g_cols, g_batch_inc, g_rows_inc, g_cols_inc; const static int no_transpose[2] = {}; ccv_nnc_tensor_get_matrix_params(g->info, CCV_IS_TENSOR_VIEW(g) ? g->inc : g->info.dim, no_transpose, &g_batch_size, &g_rows, &g_cols, &g_batch_inc, &g_rows_inc, &g_cols_inc); int i; if (bias) { int bias_batch_size, bias_rows, bias_cols, bias_batch_inc, bias_rows_inc, bias_cols_inc; ccv_nnc_tensor_get_matrix_params(bias->info, CCV_IS_TENSOR_VIEW(bias) ? bias->inc : bias->info.dim, no_transpose, &bias_batch_size, &bias_rows, &bias_cols, &bias_batch_inc, &bias_rows_inc, &bias_cols_inc); assert(bias_cols == g_cols); assert(bias_batch_size == 1 || bias_batch_size == g_batch_size); if (bias_batch_size == 1 && g_batch_size > 1) bias_batch_inc = 0; float* const ones = (float*)ccmalloc(sizeof(float) * g_rows); for (i = 0; i < g_rows; i++) ones[i] = 1; if (g_batch_size > 1 && bias_batch_size == g_batch_size) { for (i = 0; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, bias_cols, bias_rows, g_rows, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, ones, g_rows, 0.0, bias->data.f32 + i * bias_batch_inc, bias_rows_inc); } else { cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, bias_cols, bias_rows, g_rows, 1.0, g->data.f32, g_rows_inc, ones, g_rows, 0.0, bias->data.f32, bias_rows_inc); // We cannot use strided batched alternative because on write, the data could race to the same position for (i = 1; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, bias_cols, bias_rows, g_rows, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, ones, g_rows, 1.0, bias->data.f32, bias_rows_inc); } ccfree(ones); } if (dw) { const int is_transpose_a = ccv_nnc_is_matrix_transpose(a->info, transpose_a); const int is_transpose_w = ccv_nnc_is_matrix_transpose(dw->info, transpose_b); int a_batch_size, a_rows, a_cols, a_batch_inc, a_rows_inc, a_cols_inc; int dw_batch_size, dw_rows, dw_cols, dw_batch_inc, dw_rows_inc, dw_cols_inc; ccv_nnc_tensor_get_matrix_params(a->info, CCV_IS_TENSOR_VIEW(a) ? a->inc : a->info.dim, transpose_a, &a_batch_size, &a_rows, &a_cols, &a_batch_inc, &a_rows_inc, &a_cols_inc); ccv_nnc_tensor_get_matrix_params(dw->info, CCV_IS_TENSOR_VIEW(dw) ? dw->inc : dw->info.dim, transpose_b, &dw_batch_size, &dw_rows, &dw_cols, &dw_batch_inc, &dw_rows_inc, &dw_cols_inc); assert(a_rows == g_rows); assert(a_cols == dw_rows); assert(dw_cols == g_cols); assert(a_batch_size == g_batch_size || a_batch_size == 1); if (a_batch_size == 1 && g_batch_size > 1) a_batch_inc = 0; assert(dw_batch_size == g_batch_size || dw_batch_size == 1); if (dw_batch_size == 1 && g_batch_size > 1) dw_batch_inc = 0; if (g_batch_size > 1 && g_batch_size == dw_batch_size) { if (is_transpose_w) { const int transa = is_transpose_a ? CblasTrans : CblasNoTrans; const int lda_inc = is_transpose_a ? a_cols_inc : a_rows_inc; for (i = 0; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, transa, CblasTrans, dw_rows, dw_cols, a_rows, 1.0, a->data.f32 + i * a_batch_inc, lda_inc, g->data.f32 + i * g_batch_inc, g_rows_inc, 0.0, dw->data.f32 + i * dw_batch_inc, dw_cols_inc); } else { const int transb = is_transpose_a ? CblasNoTrans : CblasTrans; const int ldb_inc = is_transpose_a ? a_cols_inc : a_rows_inc; for (i = 0; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasNoTrans, transb, dw_cols, dw_rows, a_rows, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, a->data.f32 + i * a_batch_inc, ldb_inc, 0.0, dw->data.f32 + i * dw_batch_inc, dw_rows_inc); } } else { if (is_transpose_w) { const int transa = is_transpose_a ? CblasTrans : CblasNoTrans; const int lda_inc = is_transpose_a ? a_cols_inc : a_rows_inc; cblas_sgemm(CblasColMajor, transa, CblasTrans, dw_rows, dw_cols, a_rows, 1.0, a->data.f32, lda_inc, g->data.f32, g_rows_inc, 0.0, dw->data.f32, dw_cols_inc); for (i = 1; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, transa, CblasTrans, dw_rows, dw_cols, a_rows, 1.0, a->data.f32 + i * a_batch_inc, lda_inc, g->data.f32 + i * g_batch_inc, g_rows_inc, 1.0, dw->data.f32, dw_cols_inc); } else { const int transb = is_transpose_a ? CblasNoTrans : CblasTrans; const int ldb_inc = is_transpose_a ? a_cols_inc : a_rows_inc; cblas_sgemm(CblasColMajor, CblasNoTrans, transb, dw_cols, dw_rows, a_rows, 1.0, g->data.f32, g_rows_inc, a->data.f32, ldb_inc, 0.0, dw->data.f32, dw_rows_inc); for (i = 1; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasNoTrans, transb, dw_cols, dw_rows, a_rows, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, a->data.f32 + i * a_batch_inc, ldb_inc, 1.0, dw->data.f32, dw_rows_inc); } } } if (h) { const int is_transpose_h = ccv_nnc_is_matrix_transpose(h->info, transpose_a); const int is_transpose_w = ccv_nnc_is_matrix_transpose(w->info, transpose_b); int h_batch_size, h_rows, h_cols, h_batch_inc, h_rows_inc, h_cols_inc; int w_batch_size, w_rows, w_cols, w_batch_inc, w_rows_inc, w_cols_inc; ccv_nnc_tensor_get_matrix_params(h->info, CCV_IS_TENSOR_VIEW(h) ? h->inc : h->info.dim, transpose_a, &h_batch_size, &h_rows, &h_cols, &h_batch_inc, &h_rows_inc, &h_cols_inc); ccv_nnc_tensor_get_matrix_params(w->info, CCV_IS_TENSOR_VIEW(w) ? w->inc : w->info.dim, transpose_b, &w_batch_size, &w_rows, &w_cols, &w_batch_inc, &w_rows_inc, &w_cols_inc); assert(h_rows == g_rows); assert(h_cols == w_rows); assert(w_cols == g_cols); assert(h_batch_size == g_batch_size || h_batch_size == 1); if (h_batch_size == 1 && g_batch_size > 1) h_batch_inc = 0; assert(w_batch_size == g_batch_size || w_batch_size == 1); if (w_batch_size == 1 && g_batch_size > 1) w_batch_inc = 0; if (g_batch_size > 1 && g_batch_size == h_batch_size) { if (is_transpose_h) { const int transb = is_transpose_w ? CblasTrans : CblasNoTrans; const int ldb_inc = is_transpose_w ? w_cols_inc : w_rows_inc; for (i = 0; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasTrans, transb, h_rows, h_cols, g_cols, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, w->data.f32 + i * w_batch_inc, ldb_inc, 0.0, h->data.f32 + i * h_batch_inc, h_cols_inc); } else { const int transa = is_transpose_w ? CblasNoTrans : CblasTrans; const int lda_inc = is_transpose_w ? w_cols_inc : w_rows_inc; for (i = 0; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, transa, CblasNoTrans, h_cols, h_rows, g_cols, 1.0, w->data.f32 + i * w_batch_inc, lda_inc, g->data.f32 + i * g_batch_inc, g_rows_inc, 0.0, h->data.f32 + i * h_batch_inc, h_rows_inc); } } else { if (is_transpose_h) { const int transb = is_transpose_w ? CblasTrans : CblasNoTrans; const int ldb_inc = is_transpose_w ? w_cols_inc : w_rows_inc; cblas_sgemm(CblasColMajor, CblasTrans, transb, h_rows, h_cols, g_cols, 1.0, g->data.f32, g_rows_inc, w->data.f32, ldb_inc, 0.0, h->data.f32, h_cols_inc); for (i = 1; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, CblasTrans, transb, h_rows, h_cols, g_cols, 1.0, g->data.f32 + i * g_batch_inc, g_rows_inc, w->data.f32 + i * w_batch_inc, ldb_inc, 1.0, h->data.f32, h_cols_inc); } else { const int transa = is_transpose_w ? CblasNoTrans : CblasTrans; const int lda_inc = is_transpose_w ? w_cols_inc : w_rows_inc; cblas_sgemm(CblasColMajor, transa, CblasNoTrans, h_cols, h_rows, g_cols, 1.0, w->data.f32, lda_inc, g->data.f32, g_rows_inc, 0.0, h->data.f32, h_rows_inc); for (i = 1; i < g_batch_size; i++) cblas_sgemm(CblasColMajor, transa, CblasNoTrans, h_cols, h_rows, g_cols, 1.0, w->data.f32 + i * w_batch_inc, lda_inc, g->data.f32 + i * g_batch_inc, g_rows_inc, 1.0, h->data.f32, h_rows_inc); } } } return CCV_NNC_EXEC_SUCCESS; #else return CCV_NNC_EXEC_INVALID; #endif }
{ "alphanum_fraction": 0.7166331051, "avg_line_length": 60.2669902913, "ext": "c", "hexsha": "0f1cce81b7109658a61ec3803817cdfb8cd218b2", "lang": "C", "max_forks_count": 940, "max_forks_repo_forks_event_max_datetime": "2022-03-24T23:27:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-02T02:21:34.000Z", "max_forks_repo_head_hexsha": "579d21e9065d5378be4b21a4b9c0224327fb0a9f", "max_forks_repo_licenses": [ "CC0-1.0", "CC-BY-4.0" ], "max_forks_repo_name": "neonkingfr/ccv", "max_forks_repo_path": "lib/nnc/cmd/blas/cpu_sys/_ccv_nnc_gemm_cpu_sys.c", "max_issues_count": 111, "max_issues_repo_head_hexsha": "579d21e9065d5378be4b21a4b9c0224327fb0a9f", "max_issues_repo_issues_event_max_datetime": "2022-01-05T18:13:11.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-12T15:55:58.000Z", "max_issues_repo_licenses": [ "CC0-1.0", "CC-BY-4.0" ], "max_issues_repo_name": "neonkingfr/ccv", "max_issues_repo_path": "lib/nnc/cmd/blas/cpu_sys/_ccv_nnc_gemm_cpu_sys.c", "max_line_length": 313, "max_stars_count": 3296, "max_stars_repo_head_hexsha": "579d21e9065d5378be4b21a4b9c0224327fb0a9f", "max_stars_repo_licenses": [ "CC0-1.0", "CC-BY-4.0" ], "max_stars_repo_name": "neonkingfr/ccv", "max_stars_repo_path": "lib/nnc/cmd/blas/cpu_sys/_ccv_nnc_gemm_cpu_sys.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:29:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T02:05:51.000Z", "num_tokens": 4292, "size": 12415 }
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions are met: */ /* * Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the following disclaimer. */ /* * 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. */ /* * None of 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 AUTHOR 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. */ #ifndef UKF_MATH_H #define UKF_MATH_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <iostream> #include <cassert> #include <cmath> namespace ukf { namespace math { inline double min(double a, double b) { return a < b ? a : b; } inline double max(double a, double b) { return a < b ? b : a; } inline double signof(double x) { return x <= 0.0 ? -1.0 : 1.0; } inline bool cmp_equal(double x, double y) { return fabs(x - y) <= 1e-10; } inline bool cmp_diff(double x, double y) { return fabs(x - y) >= 1e-10; } /** * @brief This function performs a cholesky update according to Strange et al.(2007) * @author <a href="mailto:Mathieu.Geist@Supelec.Fr">Mathieu.Geist@Supelec.fr</a> * */ void choleskyUpdate(gsl_matrix * sigmaTheta, double alpha, gsl_vector *x) { /* This function performs a cholesky update of the cholesky factorization sigmaTheta, that is it replaces the Cholesky factorization sigmaTheta by the cholesky factorization of sigmaTheta*sigmaTheta^T + alpha * x * x^T The algorithm is an adaptation of a LU factorization rank one update. Reference is : Peter Strange, Andreas Griewank and Matthias Bollhöfer. On the Efficient Update of Rectangular LU Factorizations subject to Low Rank Modifications. Electronic Transactions on Numerical Analysis, 26:161-177, 2007. alg. is given in left part of fig.2.1. Perhaps a more efficient algorithm exists, however it should do the work for now. And the code is probably not optimal... */ if (sigmaTheta->size1 != sigmaTheta->size2) std::cout<<"ERROR ukf::math::choleskyUpdate Cannot use CholeskyUpdate on non-squared matrices"<<std::endl ; int i,j,n= sigmaTheta->size1 ; double tmp ; gsl_matrix *U = gsl_matrix_alloc(n,n) ; gsl_vector *D = gsl_vector_alloc(n) ; gsl_vector *y = gsl_vector_alloc(n) ; // A first thing is to set SS' (chol factor) in a LU form, L being unitriangular // Compute U = L^T and D = diag(L) gsl_matrix_set_zero(U) ; for (i=0; i<n; i++){ gsl_vector_set(D,i,gsl_matrix_get(sigmaTheta,i,i)); for (j=0; j<=i; j++){ gsl_matrix_set(U,j,i,gsl_matrix_get(sigmaTheta,i,j)); } } // Replace L by L*D^{-1} and U by D*U for (i=0; i<n; i++){ for (j=0; j<=i; j++){ tmp = gsl_matrix_get(sigmaTheta,i,j); tmp /= gsl_vector_get(D,j); gsl_matrix_set(sigmaTheta,i,j,tmp); tmp = gsl_matrix_get(U,j,i); tmp *= gsl_vector_get(D,j); gsl_matrix_set(U,j,i,tmp); } } // compute the y = alpha x vector gsl_vector_memcpy(y,x) ; gsl_vector_scale(y,alpha) ; // perform the rank 1 LU modification for (i=0; i<n; i++){ // diagonal update tmp = gsl_matrix_get(U,i,i) + gsl_vector_get(x,i)*gsl_vector_get(y,i); gsl_matrix_set(U,i,i,tmp); tmp = gsl_vector_get(y,i); tmp /= gsl_matrix_get(U,i,i); gsl_vector_set(y,i,tmp); for (j=i+1; j<n; j++){ // L (that is sigmaTheta) update tmp = gsl_vector_get(x,j) - gsl_vector_get(x,i)*gsl_matrix_get(sigmaTheta,j,i); gsl_vector_set(x,j,tmp) ; tmp = gsl_matrix_get(sigmaTheta,j,i) + gsl_vector_get(y,i) * gsl_vector_get(x,j); gsl_matrix_set(sigmaTheta,j,i,tmp); } for (j=i+1; j<n; j++) { // U update tmp = gsl_matrix_get(U,i,j) + gsl_vector_get(x,i)*gsl_vector_get(y,j); gsl_matrix_set(U,i,j,tmp) ; tmp = gsl_vector_get(y,j) - gsl_vector_get(y,i) * gsl_matrix_get(U,i,j); gsl_vector_set(y,j,tmp) ; } } // Now we want the chol decomposition // first D = sqrt(diag(U)) ; for (i=0; i<n; i++){ tmp = gsl_matrix_get(U,i,i) ; if (tmp<=0){std::cout<< "WARNING ukf::math::choleskyUpdate::matrix not positive definite : " << tmp << std::endl;} gsl_vector_set(D,i,sqrt(tmp)) ; } // then L = L*D ; for (i=0; i<n; i++) { for (j=0; j<n; j++) { tmp = gsl_matrix_get(sigmaTheta,i,j) * gsl_vector_get(D,j); gsl_matrix_set(sigmaTheta,i,j,tmp); } } // that's all folks ! //free memory gsl_matrix_free(U); gsl_vector_free(y); gsl_vector_free(D); } } // math } // ukf #endif // UKF_MATH_H
{ "alphanum_fraction": 0.5455064194, "avg_line_length": 38.729281768, "ext": "h", "hexsha": "9cfc41989594fda3a66ec74839ea7b490e4fa2f1", "lang": "C", "max_forks_count": 52, "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_path": "src/ukf_math.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_path": "src/ukf_math.h", "max_line_length": 158, "max_stars_count": 101, "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_path": "src/ukf_math.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "num_tokens": 1575, "size": 7010 }
/* $Id$ */ /* * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #ifdef MAC_INTEGRATION #include <gtkosxapplication.h> #endif #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_histogram.h> #include <kplot.h> #include "extern.h" static const char *const inputs[INPUT__MAX] = { "uniform", "variable", "mapped", }; static const char *const views[VIEW__MAX] = { "times-cdf", /* VIEW_TIMEESCDF */ "times-pdf", /* VIEW_TIMEESPDF */ "raw-mean-stddev", /* VIEW_DEV */ "extinct-incumbent", /* VIEW_EXTI */ "extinct-incumbent-min-cdf", /* VIEW_EXTIMINCDF */ "extinct-incumbent-min-pdf", /* VIEW_EXTIMINPDF */ "extinct-incumbent-min-mean", /* VIEW_EXTIMINS */ "extinct-mutant", /* VIEW_EXTM */ "extinct-mutant-max-cdf", /* VIEW_EXTMMAXCDF */ "extinct-mutant-max-pdf", /* VIEW_EXTMMAXPDF */ "extinct-mutant-max-mean", /* VIEW_EXTMMAXS */ "island-mean", /* VIEW_ISLANDMEAN */ "islander-mean", /* VIEW_ISLANDERMEAN */ "raw-mean", /* VIEW_MEAN */ "raw-mean-min-cdf", /* VIEW_MEANMINCDF */ "raw-mean-min-pdf", /* VIEW_MEANMINPDF */ "raw-mean-min-history", /* VIEW_MEANMINQ */ "raw-mean-min-mean", /* VIEW_MEANMINS */ "fitted-mean", /* VIEW_POLY */ "fitted-mean-min-cdf", /* VIEW_POLYMINCDF */ "fitted-mean-min-pdf", /* VIEW_POLYMINPDF */ "fitted-mean-min-history", /* VIEW_POLYMINQ */ "fitted-mean-min-mean", /* VIEW_POLYMINS */ "extinct-mutant-smooth", /* VIEW_SEXTM */ "extinct-incunmbent-smooth", /* VIEW_SEXTI */ "raw-mean-smooth", /* VIEW_SMEAN */ }; static void hwin_init(struct hwin *c, GtkBuilder *b) { GObject *w; gchar buf[1024]; gchar *bufp; GTimeVal gt; size_t nprocs; c->maptop[MAPTOP_RECORD] = win_init_toggle(b, "radiobutton10"); c->maptop[MAPTOP_RAND] = win_init_toggle(b, "radiobutton11"); c->maptop[MAPTOP_TORUS] = win_init_toggle(b, "radiobutton13"); c->rangeminlambda = win_init_label(b, "label55"); c->rangemaxlambda = win_init_label(b, "label52"); c->rangemeanlambda = win_init_label(b, "label58"); c->rangeerrorbox = win_init_box(b, "box39"); c->rangeerror = win_init_label(b, "label74"); c->rangemin = win_init_label(b, "label43"); c->rangemax = win_init_label(b, "label41"); c->rangemean = win_init_label(b, "label45"); c->rangestatus = win_init_label(b, "label47"); c->rangefunc = win_init_label(b, "label50"); c->rangeparms = win_init_label(b, "label72"); c->buttonrange = win_init_button(b, "button4"); c->mapindices[MAPINDEX_STRIPED] = win_init_toggle(b, "radiobutton15"); c->mapindices[MAPINDEX_FIXED] = win_init_toggle(b, "radiobutton16"); c->mapindexfix = win_init_adjustment(b, "adjustment11"); c->namefill[NAMEFILL_DATE] = win_init_toggle(b, "radiobutton3"); c->namefill[NAMEFILL_M] = win_init_toggle(b, "radiobutton4"); c->namefill[NAMEFILL_T] = win_init_toggle(b, "radiobutton7"); c->namefill[NAMEFILL_MUTANTS] = win_init_toggle(b, "radiobutton8"); c->namefill[NAMEFILL_NONE] = win_init_toggle(b, "radiobutton9"); c->mapbox = win_init_box(b, "box31"); c->config = win_init_window(b, "window1"); c->rangefind = win_init_window(b, "window2"); c->status = win_init_status(b, "statusbar1"); c->menu = win_init_menubar(b, "menubar1"); c->mutants[MUTANTS_DISCRETE] = win_init_radio(b, "radiobutton1"); c->mutants[MUTANTS_GAUSSIAN] = win_init_radio(b, "radiobutton2"); c->weighted = win_init_toggle(b, "checkbutton1"); c->menuquit = win_init_menuitem(b, "menuitem5"); c->input = win_init_label(b, "label19"); c->mutantsigma = win_init_entry(b, "entry17"); c->name = win_init_entry(b, "entry16"); c->stop = win_init_entry(b, "entry9"); c->xmin = win_init_entry(b, "entry8"); c->xmax = win_init_entry(b, "entry10"); c->ymin = win_init_entry(b, "entry18"); c->ymax = win_init_entry(b, "entry19"); c->inputs = win_init_notebook(b, "notebook1"); c->error = win_init_label(b, "label8"); c->func = win_init_entry(b, "entry2"); c->smoothing = win_init_adjustment(b, "adjustment10"); c->nthreads = win_init_adjustment(b, "adjustment3"); c->fitpoly = win_init_adjustment(b, "adjustment4"); c->pop = win_init_adjustment(b, "adjustment1"); c->totalpop = win_init_label(b, "label68"); c->islands = win_init_adjustment(b, "adjustment2"); c->ideathmean = win_init_adjustment(b, "adjustment12"); c->ideathcoef = win_init_entry(b, "entry3"); c->resprocs = win_init_label(b, "label3"); c->onprocs = win_init_label(b, "label36"); c->alpha = win_init_entry(b, "entry13"); c->delta = win_init_entry(b, "entry14"); c->migrate[INPUT_UNIFORM] = win_init_entry(b, "entry1"); c->migrate[INPUT_VARIABLE] = win_init_entry(b, "entry20"); c->migrate[INPUT_MAPPED] = win_init_entry(b, "entry4"); c->incumbents = win_init_entry(b, "entry15"); c->mapfile = win_init_filechoose(b, "filechooserbutton1"); c->mapmigrants[MAPMIGRANT_UNIFORM] = win_init_toggle(b, "radiobutton5"); c->mapmigrants[MAPMIGRANT_DISTANCE] = win_init_toggle(b, "radiobutton6"); c->mapmigrants[MAPMIGRANT_NEAREST] = win_init_toggle(b, "radiobutton12"); c->mapmigrants[MAPMIGRANT_TWONEAREST] = win_init_toggle(b, "radiobutton14"); c->maprandislands = win_init_adjustment(b, "adjustment6"); c->maprandislanders = win_init_adjustment(b, "adjustment7"); c->maptorusislands = win_init_adjustment(b, "adjustment8"); c->maptorusislanders = win_init_adjustment(b, "adjustment9"); gtk_widget_show_all(GTK_WIDGET(c->config)); /* Hide our error message. */ gtk_widget_hide(GTK_WIDGET(c->error)); /* Set the initially-selected notebooks. */ gtk_label_set_text(c->input, inputs [gtk_notebook_get_current_page(c->inputs)]); /* XXX: builder doesn't do this. */ w = gtk_builder_get_object(b, "comboboxtext1"); gtk_combo_box_set_active(GTK_COMBO_BOX(w), 0); #if GLIB_CHECK_VERSION(2, 36, 0) nprocs = g_get_num_processors(); #else nprocs = sysconf(_SC_NPROCESSORS_ONLN); #endif /* Maximum number of processors. */ gtk_adjustment_set_upper(c->nthreads, nprocs); w = gtk_builder_get_object(b, "label12"); (void)g_snprintf(buf, sizeof(buf), "%zu", nprocs); gtk_label_set_text(GTK_LABEL(w), buf); /* Compute initial total population. */ (void)g_snprintf(buf, sizeof(buf), "%g", gtk_adjustment_get_value(c->pop) * gtk_adjustment_get_value(c->islands)); gtk_label_set_text(c->totalpop, buf); g_get_current_time(&gt); bufp = g_time_val_to_iso8601(&gt); gtk_entry_set_text(c->name, bufp); g_free(bufp); /* Hide the rangefinder when we start up. */ gtk_widget_set_visible(GTK_WIDGET(c->rangefind), FALSE); #ifdef MAC_INTEGRATION gtk_widget_hide(GTK_WIDGET(c->menu)); gtk_widget_hide(GTK_WIDGET(c->menuquit)); gtkosx_application_set_menu_bar (gtkosx_application_get(), GTK_MENU_SHELL(c->menu)); gtkosx_application_sync_menubar (gtkosx_application_get()); #endif } /* * Free a given simulation, possibly waiting for the simulation threads * to exit. * The simulation is presumed to have been set as terminating before * running this. * Yes, we can wait if the simulation takes a long time between updates. */ static void sim_free(gpointer arg) { struct sim *p = arg; size_t i; if (NULL == p) return; g_debug("%p: Freeing simulation", p); /* * Join all of our running threads. * They were stopped in the sim_stop function, which was called * before this one. */ for (i = 0; i < p->nprocs; i++) if (NULL != p->threads[i].thread) { g_debug("%p: Freeing joining thread " "(simulation %p)", p->threads[i].thread, p); g_thread_join(p->threads[i].thread); } p->nprocs = 0; simbuf_free(p->bufs.means); simbuf_free(p->bufs.stddevs); simbuf_free(p->bufs.imeans); simbuf_free(p->bufs.times); simbuf_free(p->bufs.istddevs); simbuf_free(p->bufs.islandmeans); simbuf_free(p->bufs.islandstddevs); simbuf_free(p->bufs.mextinct); simbuf_free(p->bufs.iextinct); kdata_destroy(p->bufs.fractions); kdata_destroy(p->bufs.ifractions); kdata_destroy(p->bufs.mutants); kdata_destroy(p->bufs.incumbents); kdata_destroy(p->bufs.islands); kdata_destroy(p->bufs.meanmins); kdata_destroy(p->bufs.mextinctmaxs); kdata_destroy(p->bufs.iextinctmins); kdata_destroy(p->bufs.fitpoly); kdata_destroy(p->bufs.fitpolybuf); kdata_destroy(p->bufs.fitpolymins); kdata_destroy(p->bufs.meanminqbuf); kdata_destroy(p->bufs.fitminqbuf); hnode_free(p->exp); g_mutex_clear(&p->hot.mux); g_cond_clear(&p->hot.cond); g_free(p->name); g_free(p->func); if (NULL != p->ms) for (i = 0; i < p->islands; i++) g_free(p->ms[i]); g_free(p->ms); g_free(p->pops); kml_free(p->kml); if (p->fitpoly) { g_free(p->work.coeffs); gsl_matrix_free(p->work.X); gsl_vector_free(p->work.y); gsl_vector_free(p->work.w); gsl_vector_free(p->work.c); gsl_matrix_free(p->work.cov); gsl_multifit_linear_free(p->work.work); p->fitpoly = 0; } g_free(p->threads); g_free(p); g_debug("%p: Simulation freed", p); } /* * Set a given simulation to stop running. * This must be invoked before sim_free() or simulation threads will * still be running. */ void sim_stop(gpointer arg, gpointer unused) { struct sim *p = arg; int pause; if (p->terminate) return; g_debug("%p: Simulation stopping", p); p->terminate = 1; g_mutex_lock(&p->hot.mux); if (0 != (pause = p->hot.pause)) { p->hot.pause = 0; g_cond_broadcast(&p->hot.cond); } g_mutex_unlock(&p->hot.mux); if (pause) g_debug("%p: Simulation unpausing to stop", p); } /* * Free up all memory. * This can be reentrant (due to gtk-osx's funny handling of * termination), so be careful to nullify things so that if recalled it * doesn't puke. */ static void bmigrate_free(struct bmigrate *p) { g_debug("%p: Freeing main", p); g_list_foreach(p->sims, sim_stop, NULL); g_list_free_full(p->sims, sim_free); p->sims = NULL; hnode_free(p->range.exp); p->range.exp = NULL; if (NULL != p->status_elapsed) g_timer_destroy(p->status_elapsed); p->status_elapsed = NULL; p->clrsz = 0; free(p->clrs); p->clrs = NULL; } /* * Pause or unpause (unset pause and broadcast to condition) a given * simulation depending on its current pause status. */ static void on_sim_pause(struct sim *sim, int dopause) { int pause = -1; g_mutex_lock(&sim->hot.mux); if (0 == dopause && sim->hot.pause) { sim->hot.pause = pause = 0; g_cond_broadcast(&sim->hot.cond); } else if (dopause && 0 == sim->hot.pause) sim->hot.pause = pause = 1; g_mutex_unlock(&sim->hot.mux); if (0 == pause && 0 == dopause) g_debug("Unpausing simulation %p", sim); else if (pause && dopause) g_debug("Pausing simulation %p", sim); } static void cqueue_fill(size_t pos, struct kpair *kp, void *arg) { struct cqueue *q = arg; kp->x = -(double)(CQUEUESZ - pos); kp->y = q->vals[(q->pos + pos + 1) % CQUEUESZ]; } static void cqueue_push(struct cqueue *q, double val) { q->vals[q->pos] = val; if (val > q->vals[q->maxpos]) q->maxpos = q->pos; q->pos = (q->pos + 1) % CQUEUESZ; } /* * This copies data from the threads into local ("cold") storage. * It does so by checking whether the threads have copied out of "hot" * storage (locking their mutex in the process) and, if so, indicates * that we're about to read it (and thus to do so again), then after * reading, reset that the data is stale. */ static gboolean on_sim_copyout(gpointer dat) { struct bmigrate *b = dat; GList *list, *w, *sims; ssize_t pos; struct kpair kp; struct sim *sim; struct curwin *cur; int copy, rc; for (list = b->sims; NULL != list; list = g_list_next(list)) { sim = list->data; if (0 == sim->nprocs) continue; /* * Instruct the simulation to copy out its data into warm * storage. * If it hasn't already done so, then don't copy into * cold storage, as nothing has changed. */ g_mutex_lock(&sim->hot.mux); copy = 0 == sim->hot.copyout; g_mutex_unlock(&sim->hot.mux); if ( ! copy) continue; /* * Don't copy stale data. * Trigger the simulation to copy-out when it gets a * chance. */ if (sim->cold.truns == sim->warm.truns) { assert(sim->cold.tgens == sim->warm.tgens); g_mutex_lock(&sim->hot.mux); g_assert(0 == sim->hot.copyout); sim->hot.copyout = 1; g_mutex_unlock(&sim->hot.mux); continue; } /* * Since we're updating this particular simulation, make * sure that all windows tied to this simulation are * also going to be redrawn when the redrawer is called. */ for (w = b->windows ; w != NULL; w = w->next) { cur = w->data; sims = cur->sims; g_assert(NULL != sims); for ( ; NULL != sims; sims = sims->next) if (sim == sims->data) { cur->redraw = 1; break; } } /* Most strutures we simply copy over. */ simbuf_copy_cold(sim->bufs.times); simbuf_copy_cold(sim->bufs.imeans); simbuf_copy_cold(sim->bufs.istddevs); simbuf_copy_cold(sim->bufs.islandmeans); simbuf_copy_cold(sim->bufs.islandstddevs); simbuf_copy_cold(sim->bufs.means); simbuf_copy_cold(sim->bufs.stddevs); simbuf_copy_cold(sim->bufs.mextinct); simbuf_copy_cold(sim->bufs.iextinct); rc = kdata_buffer_copy (sim->bufs.fitpolybuf, sim->bufs.fitpoly); g_assert(0 != rc); sim->cold.truns = sim->warm.truns; sim->cold.tgens = sim->warm.tgens; pos = kdata_ymin(sim->bufs.means->cold, &kp); g_assert(pos >= 0); kdata_array_add(sim->bufs.meanmins, pos, 1.0); cqueue_push(&sim->bufs.meanminq, kp.x); kdata_array_fill(sim->bufs.meanminqbuf, &sim->bufs.meanminq, cqueue_fill); kdata_array_add(sim->bufs.mextinctmaxs, kdata_ymax(sim->bufs.mextinct->cold, NULL), 1.0); kdata_array_add(sim->bufs.iextinctmins, kdata_ymin(sim->bufs.iextinct->cold, NULL), 1.0); pos = kdata_ymin(sim->bufs.fitpolybuf, &kp); g_assert(pos >= 0); kdata_array_add(sim->bufs.fitpolymins, pos, 1.0); cqueue_push(&sim->bufs.fitminq, kp.x); kdata_array_fill(sim->bufs.fitminqbuf, &sim->bufs.fitminq, cqueue_fill); /* Copy-out when convenient. */ g_mutex_lock(&sim->hot.mux); g_assert(0 == sim->hot.copyout); sim->hot.copyout = 1; g_mutex_unlock(&sim->hot.mux); } return(TRUE); } static gboolean on_sim_autosave(gpointer dat) { struct bmigrate *b = dat; struct curwin *cur; GList *l; GtkWidget *dialog; enum view sv, view; gchar *file; int rc; for (l = b->windows; l != NULL; l = l->next) { cur = l->data; if (NULL == cur->autosave) continue; sv = cur->view; for (view = 0; view < VIEW__MAX; view++) { file = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.pdf", cur->autosave, views[view]); cur->view = view; rc = save(file, cur); g_free(file); if (0 == rc) break; } cur->view = sv; if (view != VIEW__MAX) break; file = g_strdup_printf("%s" G_DIR_SEPARATOR_S "README.txt", cur->autosave); rc = saveconfig(file, cur); g_free(file); if (0 == rc) break; } if (NULL == l) return(TRUE); dialog = gtk_message_dialog_new (GTK_WINDOW(cur->wins.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error auto-saving: %s", strerror(errno)); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); g_free(cur->autosave); cur->autosave = NULL; gtk_widget_hide(GTK_WIDGET (cur->wins.menuunautoexport)); gtk_widget_show(GTK_WIDGET (cur->wins.menuautoexport)); return(TRUE); } static void on_win_redraw(struct curwin *cur) { GList *l; struct sim *sim; size_t i; int rc; for (i = 0, l = cur->sims; NULL != l; l = g_list_next(l), i++) { sim = l->data; rc = kdata_vector_set(cur->winmean, i, i, kdata_pmfmean(sim->bufs.meanmins)); g_assert(0 != rc); rc = kdata_vector_set(cur->winstddev, i, i, kdata_pmfstddev(sim->bufs.meanmins)); g_assert(0 != rc); rc = kdata_vector_set(cur->winfitmean, i, i, kdata_pmfmean(sim->bufs.fitpolymins)); g_assert(0 != rc); rc = kdata_vector_set(cur->winfitstddev, i, i, kdata_pmfstddev(sim->bufs.fitpolymins)); g_assert(0 != rc); rc = kdata_vector_set(cur->winmextinctmean, i, i, kdata_pmfmean(sim->bufs.mextinctmaxs)); g_assert(0 != rc); rc = kdata_vector_set(cur->winmextinctstddev, i, i, kdata_pmfstddev(sim->bufs.mextinctmaxs)); g_assert(0 != rc); rc = kdata_vector_set(cur->winiextinctmean, i, i, kdata_pmfmean(sim->bufs.iextinctmins)); g_assert(0 != rc); rc = kdata_vector_set(cur->winiextinctstddev, i, i, kdata_pmfstddev(sim->bufs.iextinctmins)); g_assert(0 != rc); } gtk_widget_queue_draw(GTK_WIDGET(cur->wins.window)); } /* * Run this fairly often to see if we need to join any worker threads. * Worker threads are joined when they have zero references are in the * terminating state. */ static gboolean on_sim_timer(gpointer dat) { struct bmigrate *b = dat; struct sim *sim; gchar buf[1024]; GList *list; uint64_t runs; size_t i, onprocs, resprocs; double elapsed; onprocs = resprocs = runs = 0; for (list = b->sims; NULL != list; list = g_list_next(list)) { sim = (struct sim *)list->data; runs += sim->cold.tgens; /* * If "terminate" is set, then the thread is (or already * did finish) exiting, so wait for it. * If we wait, it should take only a very small while. */ if (sim->terminate && sim->nprocs > 0) { for (i = 0; i < sim->nprocs; i++) { if (NULL == sim->threads[i].thread) continue; g_debug("%p: Timeout handler joining " "thread (simulation %p)", sim->threads[i].thread, sim); g_thread_join(sim->threads[i].thread); sim->threads[i].thread = NULL; } sim->nprocs = 0; assert(0 == sim->refs); } else if ( ! sim->terminate && ! sim->hot.pause) { onprocs += sim->nprocs; resprocs += sim->nprocs; } else if ( ! sim->terminate) resprocs += sim->nprocs; } /* * Remind us of how many threads we're running. * FIXME: this shows the number of allocated threads, not * necessarily the number of running threads. */ (void)g_snprintf(buf, sizeof(buf), "%zu", resprocs); gtk_label_set_text(b->wins.resprocs, buf); (void)g_snprintf(buf, sizeof(buf), "%zu", onprocs); gtk_label_set_text(b->wins.onprocs, buf); /* * Tell us how many generations have transpired (if no time has * elapsed, then make sure we don't divide by zero). * Then update the status bar. * This will in turn redraw that window portion. */ elapsed = g_timer_elapsed(b->status_elapsed, NULL); if (0.0 == elapsed) elapsed = DBL_MIN; (void)g_snprintf(buf, sizeof(buf), "Running %.0f generations/second.", (runs - b->lastmatches) / elapsed); gtk_statusbar_pop(b->wins.status, 0); gtk_statusbar_push(b->wins.status, 0, buf); g_timer_start(b->status_elapsed); b->lastmatches = runs; /* * Conditionally update our windows. * We do this by iterating through all simulation windows and * seeing if they have the "update" flag set to true. */ for (list = b->windows; list != NULL; list = list->next) if (((struct curwin *)list->data)->redraw) on_win_redraw(list->data); return(TRUE); } gboolean onfocussim(GtkWidget *w, GdkEvent *event, gpointer dat) { #ifdef MAC_INTEGRATION struct curwin *c = dat; gtkosx_application_set_menu_bar (gtkosx_application_get(), GTK_MENU_SHELL(c->wins.menu)); gtkosx_application_sync_menubar (gtkosx_application_get()); #endif return(TRUE); } gboolean onfocusmain(GtkWidget *w, GdkEvent *event, gpointer dat) { #ifdef MAC_INTEGRATION struct bmigrate *b = dat; gtkosx_application_set_menu_bar (gtkosx_application_get(), GTK_MENU_SHELL(b->wins.menu)); gtkosx_application_sync_menubar (gtkosx_application_get()); #endif return(TRUE); } gboolean ondraw(GtkWidget *w, cairo_t *cr, gpointer dat) { draw(w, cr, dat); return(TRUE); } void onunautoexport(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; g_assert(NULL != cur->autosave); g_debug("Disabling auto-exporting: %s", cur->autosave); g_free(cur->autosave); cur->autosave = NULL; gtk_widget_show(GTK_WIDGET(cur->wins.menuautoexport)); gtk_widget_hide(GTK_WIDGET(cur->wins.menuunautoexport)); } void onautoexport(GtkMenuItem *menuitem, gpointer dat) { GtkWidget *dialog; gint res; struct curwin *cur = dat; GtkFileChooser *chooser; g_assert(NULL == cur->autosave); dialog = gtk_file_chooser_dialog_new ("Create Data Folder", cur->wins.window, GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER, "_Cancel", GTK_RESPONSE_CANCEL, "_Create", GTK_RESPONSE_ACCEPT, NULL); chooser = GTK_FILE_CHOOSER(dialog); gtk_file_chooser_set_current_name(chooser, "bmigrate"); res = gtk_dialog_run(GTK_DIALOG(dialog)); if (res != GTK_RESPONSE_ACCEPT) { gtk_widget_destroy(dialog); return; } cur->autosave = gtk_file_chooser_get_filename(chooser); gtk_widget_destroy(dialog); gtk_widget_hide(GTK_WIDGET(cur->wins.menuautoexport)); gtk_widget_show(GTK_WIDGET(cur->wins.menuunautoexport)); g_debug("Auto-exporting: %s", cur->autosave); g_mkdir_with_parents(cur->autosave, 0755); } /* * Toggle a different view of the current window. */ void onviewtoggle(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; /* * First, set the "view" indicator to be the current view as * found in the drop-down menu. */ for (cur->view = 0; cur->view < VIEW__MAX; cur->view++) if (gtk_check_menu_item_get_active (cur->wins.views[cur->view])) break; /* * Next, set the window name to be the label associated with the * respective menu check item. */ g_assert(cur->view < VIEW__MAX); gtk_window_set_title(GTK_WINDOW(cur->wins.window), gtk_menu_item_get_label (GTK_MENU_ITEM(cur->wins.views[cur->view]))); /* Redraw the window. */ gtk_widget_queue_draw(GTK_WIDGET(cur->wins.window)); } /* * Pause all simulations connect to a view. */ void onpause(GtkMenuItem *menuitem, gpointer dat) { GList *l; struct curwin *cur = dat; for (l = cur->sims; NULL != l; l = l->next) on_sim_pause(l->data, 1); } /* * Unpause all simulations connect to a view. */ void onunpause(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; GList *l; for (l = cur->sims ; NULL != l; l = l->next) on_sim_pause(l->data, 0); } gboolean onrangedelete(GtkWidget *widget, GdkEvent *event, gpointer dat) { struct bmigrate *b = dat; gtk_widget_set_visible (GTK_WIDGET(b->wins.rangefind), FALSE); if (b->rangeid > 0) { g_debug("Disabling rangefinder (user request)"); g_source_remove(b->rangeid); b->rangeid = 0; } else g_debug("Rangefinder already disabled (user request)"); return(TRUE); } void onrangeclose(GtkButton *button, gpointer dat) { struct bmigrate *b = dat; gtk_widget_set_visible (GTK_WIDGET(b->wins.rangefind), FALSE); if (b->rangeid > 0) { g_debug("Disabling rangefinder (user request)"); g_source_remove(b->rangeid); b->rangeid = 0; } else g_debug("Rangefinder already disabled (user request)"); } /* * One of the preset continuum functions for our continuum game * possibility. */ void onpreset(GtkComboBox *widget, gpointer dat) { struct bmigrate *b = dat; switch (gtk_combo_box_get_active(widget)) { case (1): /* Tullock */ gtk_entry_set_text(b->wins.func, "x * (1 / X) - x"); break; case (2): /* Cournot */ gtk_entry_set_text(b->wins.func, "(1 - X) * x"); break; case (3): /* Exponential Public Goods */ gtk_entry_set_text(b->wins.func, "(1 - exp(-X)) - x"); break; case (4): /* Quadratic Public Goods */ gtk_entry_set_text(b->wins.func, "sqrt(1 / n * X) - 0.5 * x^2"); break; default: gtk_entry_set_text(b->wins.func, ""); break; } } static void on_totalpop(struct bmigrate *b, gint pnum) { GList *l, *cl, *sv; gchar buf[32]; double v = 0.0; enum maptop maptop; struct kml *kml; struct kmlplace *kmlp; gchar *file; switch (pnum) { case (INPUT_UNIFORM): gtk_label_set_text(b->wins.input, "uniform"); v = gtk_adjustment_get_value(b->wins.pop) * gtk_adjustment_get_value(b->wins.islands); break; case (INPUT_VARIABLE): gtk_label_set_text(b->wins.input, "variable"); l = sv = gtk_container_get_children (GTK_CONTAINER(b->wins.mapbox)); for (; NULL != l; l = g_list_next(l)) { cl = gtk_container_get_children (GTK_CONTAINER(l->data)); v += gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON(g_list_next(cl)->data)); g_list_free(cl); } g_list_free(sv); break; case (INPUT_MAPPED): for (maptop = 0; maptop < MAPTOP__MAX; maptop++) if (gtk_toggle_button_get_active (b->wins.maptop[maptop])) break; switch (maptop) { case (MAPTOP_RECORD): gtk_label_set_text(b->wins.input, "KML islands"); file = gtk_file_chooser_get_filename (b->wins.mapfile); if (NULL == file) break; kml = kml_parse(file, NULL); if (NULL == kml) break; l = kml->kmls; for ( ; NULL != l; l = g_list_next(l)) { kmlp = l->data; v += kmlp->pop; } kml_free(kml); break; case (MAPTOP_RAND): gtk_label_set_text(b->wins.input, "random islands"); v = gtk_adjustment_get_value (b->wins.maprandislands) * gtk_adjustment_get_value (b->wins.maprandislanders); break; case (MAPTOP_TORUS): gtk_label_set_text(b->wins.input, "toroidal islands"); v = gtk_adjustment_get_value (b->wins.maptorusislands) * gtk_adjustment_get_value (b->wins.maptorusislanders); break; default: abort(); } break; default: abort(); } g_snprintf(buf, sizeof(buf), "%g", v); gtk_label_set_text(b->wins.totalpop, buf); } void on_change_input(GtkNotebook *notebook, GtkWidget *page, gint pnum, gpointer dat) { on_totalpop(dat, pnum); } void on_change_mapfile(GtkFileChooserButton *widget, gpointer dat) { struct bmigrate *b = dat; on_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs)); } void on_change_maptype(GtkToggleButton *togglebutton, gpointer dat) { struct bmigrate *b = dat; on_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs)); } void on_change_totalpop(GtkSpinButton *spinbutton, gpointer dat) { struct bmigrate *b = dat; on_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs)); } void onsaveall(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; GtkWidget *dialog; gint res; GtkFileChooser *chooser; char *dir, *file; enum view view, sv; int rc; dialog = gtk_file_chooser_dialog_new ("Create View Data Folder", cur->wins.window, GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER, "_Cancel", GTK_RESPONSE_CANCEL, "_Create", GTK_RESPONSE_ACCEPT, NULL); chooser = GTK_FILE_CHOOSER(dialog); gtk_file_chooser_set_current_name(chooser, "bmigrate"); res = gtk_dialog_run(GTK_DIALOG(dialog)); if (res != GTK_RESPONSE_ACCEPT) { gtk_widget_destroy(dialog); return; } dir = gtk_file_chooser_get_filename(chooser); gtk_widget_destroy(dialog); g_assert(NULL != dir); g_assert('\0' != *dir); sv = cur->view; for (view = 0; view < VIEW__MAX; view++) { file = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.pdf", dir, views[view]); cur->view = view; rc = save(file, cur); g_free(file); if (0 == rc) break; } cur->view = sv; if (view == VIEW__MAX) { file = g_strdup_printf("%s" G_DIR_SEPARATOR_S "README.txt", dir); if (0 == (rc = saveconfig(file, cur))) view = 0; g_free(file); } g_free(dir); if (view == VIEW__MAX) return; dialog = gtk_message_dialog_new (GTK_WINDOW(cur->wins.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error saving: %s", strerror(errno)); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } void onsave(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; GtkWidget *dialog; gint res; GtkFileChooser *chooser; int rc; char *file; dialog = gtk_file_chooser_dialog_new ("Save View Data", cur->wins.window, GTK_FILE_CHOOSER_ACTION_SAVE, "_Cancel", GTK_RESPONSE_CANCEL, "_Save", GTK_RESPONSE_ACCEPT, NULL); chooser = GTK_FILE_CHOOSER(dialog); gtk_file_chooser_set_do_overwrite_confirmation(chooser, TRUE); gtk_file_chooser_set_current_name(chooser, "bmigrate.pdf"); res = gtk_dialog_run(GTK_DIALOG(dialog)); if (res != GTK_RESPONSE_ACCEPT) { gtk_widget_destroy(dialog); return; } file = gtk_file_chooser_get_filename(chooser); gtk_widget_destroy(dialog); g_assert(NULL != file); g_assert('\0' != *file); rc = save(file, cur); g_free(file); if (0 != rc) return; dialog = gtk_message_dialog_new (GTK_WINDOW(cur->wins.window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error saving: %s", strerror(errno)); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } #ifdef MAC_INTEGRATION gboolean onterminate(GtkosxApplication *action, gpointer dat) { bmigrate_free(dat); gtk_main_quit(); return(FALSE); } #endif /* * Run when we quit from a simulation window. */ void onclose(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; g_debug("Simulation window closing"); gtk_widget_destroy(GTK_WIDGET(cur->wins.window)); } /* * Run when we quit from a simulation window. */ void onquitsim(GtkMenuItem *menuitem, gpointer dat) { struct curwin *cur = dat; bmigrate_free(cur->b); gtk_main_quit(); } /* * Run when we quit from a simulation window. */ void onquitmain(GtkMenuItem *menuitem, gpointer dat) { bmigrate_free(dat); gtk_main_quit(); } /* * Run when we destroy the config screen. */ void ondestroy(GtkWidget *object, gpointer dat) { bmigrate_free(dat); gtk_main_quit(); } /* * Run when we press "Quit" on the config screen. */ void on_deactivate(GtkButton *button, gpointer dat) { bmigrate_free(dat); gtk_main_quit(); } /* * Add an island configuration. * For the time being, we only allow the population size of the island * to be specified. * (Inter-island migration probabilities may not yet be assigned.) */ static void mapbox_add(struct bmigrate *b, size_t sz) { GtkWidget *box, *label, *btn; GtkAdjustment *adj; gchar buf[64]; box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5); g_snprintf(buf, sizeof(buf), "Population %zu:", sz); label = gtk_label_new(buf); gtk_misc_set_alignment(GTK_MISC(label), 1.0, 0.5); gtk_label_set_width_chars(GTK_LABEL(label), 20); gtk_container_add(GTK_CONTAINER(box), label); adj = gtk_adjustment_new(2.0, 2.0, 1000.0, 1.0, 10.0, 0.0); btn = gtk_spin_button_new(adj, 1.0, 0); g_signal_connect(btn, "value-changed", G_CALLBACK(on_change_totalpop), b); gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(btn), TRUE); gtk_spin_button_set_snap_to_ticks(GTK_SPIN_BUTTON(btn), TRUE); gtk_container_add(GTK_CONTAINER(box), btn); gtk_container_add(GTK_CONTAINER(b->wins.mapbox), box); gtk_widget_show_all(box); } /* * Remove the last island configuration. */ static void mapbox_rem(struct bmigrate *b) { GList *list, *last; list = gtk_container_get_children(GTK_CONTAINER(b->wins.mapbox)); last = g_list_last(list); gtk_widget_destroy(GTK_WIDGET(last->data)); g_list_free(list); } /* * We've requested more or fewer islands for the mapped scenario. */ void onislandspin(GtkSpinButton *spinbutton, gpointer dat) { struct bmigrate *b = dat; guint oldsz, newsz; GList *list; list = gtk_container_get_children(GTK_CONTAINER(b->wins.mapbox)); oldsz = g_list_length(list); g_list_free(list); newsz = (guint)gtk_spin_button_get_value(spinbutton); if (newsz > oldsz) { while (oldsz++ < newsz) mapbox_add(b, oldsz); } else if (oldsz > newsz) { while (oldsz-- > newsz) mapbox_rem(b); } on_totalpop(b, gtk_notebook_get_current_page(b->wins.inputs)); } int main(int argc, char *argv[]) { GtkBuilder *builder; struct bmigrate b; int rc; memset(&b, 0, sizeof(struct bmigrate)); gtk_init(&argc, &argv); rc = kplotcfg_default_palette(&b.clrs, &b.clrsz); g_assert(0 != rc); /* * Sanity-check to make sure that the hnode expression evaluator * is working properly. * You'll need to actually look at the debugging output to see * if that's the case, of course. */ hnode_test(); builder = builder_get("bmigrate.glade"); if (NULL == builder) return(EXIT_FAILURE); hwin_init(&b.wins, builder); gtk_builder_connect_signals(builder, &b); g_object_unref(G_OBJECT(builder)); /* * Have two running timers: once per second, forcing a refresh of * the window system; then another at four times per second * updating our cold statistics. */ b.status_elapsed = g_timer_new(); g_timeout_add_seconds(1, (GSourceFunc)on_sim_timer, &b); g_timeout_add_seconds(60, (GSourceFunc)on_sim_autosave, &b); g_timeout_add(250, (GSourceFunc)on_sim_copyout, &b); gtk_statusbar_push(b.wins.status, 0, "No simulations."); #ifdef MAC_INTEGRATION g_signal_connect(gtkosx_application_get(), "NSApplicationWillTerminate", G_CALLBACK(onterminate), &b); gtkosx_application_ready(gtkosx_application_get()); #endif gtk_main(); bmigrate_free(&b); return(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.6940387481, "avg_line_length": 26.272513704, "ext": "c", "hexsha": "20eb7bdc4e586242aeb7c933b5aa2df4be643f62", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "bmigrate.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "kristapsdz/bmigrate", "max_issues_repo_path": "bmigrate.c", "max_line_length": 77, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "bmigrate.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 10046, "size": 33550 }
#ifndef TTT_GFX_BUTTON_H #define TTT_GFX_BUTTON_H #include <SDL_render.h> #include <SDL_mouse.h> #include <SDL_mixer.h> #include <gsl/pointers> #include <optional> namespace ttt::gfx { // A basic clickable image button. class Button final { public: Button() = default; Button(SDL_Texture *texture, const SDL_Rect &normalSrc, const SDL_FRect &dst, Mix_Chunk *sound) noexcept; Button(SDL_Texture *texture, const SDL_Rect &normalSrc, const std::optional<SDL_Rect> &hoverSrc, const std::optional<SDL_Rect> &pressedSrc, const SDL_FRect &dst, Mix_Chunk *sound) noexcept; void setTexture(SDL_Texture *texture, const SDL_Rect &normalSrc) noexcept; void setTexture(SDL_Texture *texture, const SDL_Rect &normalSrc, const std::optional<SDL_Rect> &hoverSrc, const std::optional<SDL_Rect> &pressedSrc) noexcept; void setDestination(const SDL_FRect &dst) noexcept; void setSound(Mix_Chunk *sound) noexcept; void update() noexcept; void render(gsl::not_null<SDL_Renderer *> renderer) const noexcept; [[nodiscard]] bool isHoveredOver() const noexcept; [[nodiscard]] bool isPressed() const noexcept; [[nodiscard]] bool wasReleased() const noexcept; private: SDL_Texture *texture{nullptr}; SDL_Rect normalSrc{0, 0, 0, 0}; std::optional<SDL_Rect> hoverSrc; std::optional<SDL_Rect> pressedSrc; SDL_FRect dst{0.0f, 0.0f, 0.0f, 0.0f}; Mix_Chunk *sound{nullptr}; bool hoveredOver{false}; bool pressed{false}; bool released{false}; std::optional<SDL_Point> click; }; inline void Button::setSound(Mix_Chunk *sound) noexcept { this->sound = sound; } inline bool Button::isHoveredOver() const noexcept { return hoveredOver; } inline bool Button::isPressed() const noexcept { return pressed; } inline bool Button::wasReleased() const noexcept { return released; } } #endif
{ "alphanum_fraction": 0.7444933921, "avg_line_length": 31.8596491228, "ext": "h", "hexsha": "7b90609e81782947047108c94119e10de7c6abe4", "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": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "itsArtem/TicTacToe", "max_forks_repo_path": "Source/Graphics/Button.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "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": "itsArtem/TicTacToe", "max_issues_repo_path": "Source/Graphics/Button.h", "max_line_length": 191, "max_stars_count": null, "max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "itsArtem/TicTacToe", "max_stars_repo_path": "Source/Graphics/Button.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 495, "size": 1816 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef COSMIC_RAYS #include "cosmic_rays.h" #endif #ifdef MACH_NUM #include "machfinder.h" #endif #ifdef CS_MODEL #include "cs_metals.h" #endif #ifndef DEBUG #define NDEBUG #endif #include <assert.h> /*! \file hydra.c * \brief Computation of SPH forces and rate of entropy generation * * This file contains the "second SPH loop", where the SPH forces are * computed, and where the rate of change of entropy due to the shock heating * (via artificial viscosity) is computed. */ struct hydrodata_in { MyDouble Pos[3]; MyFloat Vel[3]; MyFloat Hsml; MyFloat Mass; MyFloat Density; MyFloat Pressure; MyFloat F1; MyFloat DhsmlDensityFactor; int Timestep; #ifdef CS_MODEL MyFloat DensityNow; MyFloat Entropy; #endif #ifdef PARTICLE_DEBUG MyIDType ID; /*!< particle identifier */ #endif #ifdef MAGNETIC MyFloat BPred[3]; #ifdef TIME_DEP_MAGN_DISP MyFloat Balpha; #endif #ifdef DIVBCLEANING_DEDNER MyFloat PhiPred; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) MyFloat RotB[3]; #endif #endif #ifdef TIME_DEP_ART_VISC MyFloat alpha; #endif #if defined(NAVIERSTOKES) MyFloat Entropy; #endif #ifdef NAVIERSTOKES MyFloat stressoffdiag[3]; MyFloat stressdiag[3]; MyFloat shear_viscosity; #endif #ifdef NAVIERSTOKES_BULK MyFloat divvel; #endif int NodeList[NODELISTLENGTH]; } *HydroDataIn, *HydroDataGet; struct hydrodata_out { MyLongDouble Acc[3]; MyLongDouble DtEntropy; #ifdef ALTERNATIVE_VISCOUS_TIMESTEP MyFloat MinViscousDt; #else MyFloat MaxSignalVel; #endif #if defined(MAGNETIC) && !defined(EULERPOTENTIALS) MyFloat DtB[3]; #ifdef DIVBCLEANING_DEDNER MyFloat DtPhi; #endif #endif #if defined(CR_SHOCK) MyFloat CR_EnergyChange[NUMCRPOP]; MyFloat CR_BaryonFractionChange[NUMCRPOP]; #endif #ifdef HYDRO_COST_FACTOR int Ninteractions; #endif } *HydroDataResult, *HydroDataOut; #ifdef MACHNUM double hubble_a, atime, hubble_a2, fac_mu, fac_vsic_fix, a3inv, fac_egy; #else static double hubble_a, atime, hubble_a2, fac_mu, fac_vsic_fix, a3inv, fac_egy; #endif /*! This function is the driver routine for the calculation of hydrodynamical * force and rate of change of entropy due to shock heating for all active * particles . */ void hydro_force(void) { int i, j, k, ngrp, ndone, ndone_flag, dummy; int sendTask, recvTask, nexport, nimport, place; double soundspeed_i; double timeall = 0, timecomp1 = 0, timecomp2 = 0, timecommsumm1 = 0, timecommsumm2 = 0, timewait1 = 0, timewait2 = 0; double timecomp, timecomm, timewait, tstart, tend, t0, t1; #if defined(WINDS) || defined(TIME_DEP_ART_VISC) || defined(MAGNETIC) double dmax1, dmax2; #endif #ifdef NAVIERSTOKES double fac; #endif #if (!defined(COOLING) && !defined(CR_SHOCK) && (defined(CR_DISSIPATION) || defined(CR_THERMALIZATION))) double utherm; double dt; int CRpop; #endif #if defined(CR_SHOCK) double rShockEnergy; double rNonRethermalizedEnergy; #ifndef COOLING double utherm, CRpop; #endif #endif #ifdef WINDS double windspeed, hsml_c; #endif #ifdef TIME_DEP_ART_VISC double f, cs_h; #endif #if defined(MAGNETIC) && defined(MAGFORCE) #ifdef TIME_DEP_MAGN_DISP double mu0 = 1; #endif #endif #ifdef DIVBCLEANING_DEDNER double phiphi,tmpb; #endif #ifdef HEALPIX double r_new,t[3]; long ipix; int count=0; int total_count=0; #endif #ifdef WAKEUP for(i = 0; i < NumPart; i++) { if(P[i].Type == 0) SphP[i].wakeup = 0; } #endif if(All.ComovingIntegrationOn) { /* Factors for comoving integration of hydro */ hubble_a = hubble_function(All.Time); 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; #if defined(MAGFORCE) && defined(TIME_DEP_MAGN_DISP) #ifndef MU0_UNITY mu0 *= (4 * M_PI); mu0 /= All.UnitTime_in_s * All.UnitTime_in_s * All.UnitLength_in_cm / (All.UnitMass_in_g * All.HubbleParam * All.HubbleParam); #endif #endif /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPart * sizeof(int)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct hydrodata_in) + sizeof(struct hydrodata_out) + sizemax(sizeof(struct hydrodata_in), sizeof(struct hydrodata_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); CPU_Step[CPU_HYDMISC] += measure_time(); t0 = second(); i = FirstActiveParticle; /* first particle for this task */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ tstart = second(); for(nexport = 0; i >= 0; i = NextActiveParticle[i]) if(P[i].Type == 0) { if(hydro_evaluate(i, 0, &nexport, Send_count) < 0) break; } tend = second(); timecomp1 += timediff(tstart, tend); #ifdef MYSORT mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #else qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #endif tstart = second(); MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); tend = second(); timewait1 += timediff(tstart, tend); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } HydroDataGet = (struct hydrodata_in *) mymalloc(nimport * sizeof(struct hydrodata_in)); HydroDataIn = (struct hydrodata_in *) mymalloc(nexport * sizeof(struct hydrodata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; for(k = 0; k < 3; k++) { HydroDataIn[j].Pos[k] = P[place].Pos[k]; HydroDataIn[j].Vel[k] = SphP[place].VelPred[k]; } HydroDataIn[j].Hsml = PPP[place].Hsml; HydroDataIn[j].Mass = P[place].Mass; HydroDataIn[j].DhsmlDensityFactor = SphP[place].h.DhsmlDensityFactor; HydroDataIn[j].Density = SphP[place].d.Density; HydroDataIn[j].Pressure = SphP[place].Pressure; HydroDataIn[j].Timestep = (P[place].TimeBin ? (1 << P[place].TimeBin) : 0); /* calculation of F1 */ #ifndef ALTVISCOSITY soundspeed_i = sqrt(GAMMA * SphP[place].Pressure / SphP[place].d.Density); #ifndef NAVIERSTOKES HydroDataIn[j].F1 = fabs(SphP[place].v.DivVel) / (fabs(SphP[place].v.DivVel) + SphP[place].r.CurlVel + 0.0001 * soundspeed_i / PPP[place].Hsml / fac_mu); #else HydroDataIn[j].F1 = fabs(SphP[place].v.DivVel) / (fabs(SphP[place].v.DivVel) + SphP[place].u.s.CurlVel + 0.0001 * soundspeed_i / PPP[place].Hsml / fac_mu); #endif #else HydroDataIn[j].F1 = SphP[place].v.DivVel; #endif memcpy(HydroDataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); #ifdef CS_MODEL HydroDataIn[j].DensityNow = SphP[place].d.Density; HydroDataIn[j].Entropy = SphP[place].Entropy; #endif #ifdef MAGNETIC for(k = 0; k < 3; k++) { HydroDataIn[j].BPred[k] = SphP[place].BPred[k]; #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) #ifdef SMOOTH_ROTB HydroDataIn[j].RotB[k] = SphP[place].SmoothedRotB[k]; #else HydroDataIn[j].RotB[k] = SphP[place].RotB[k]; #endif #endif } #ifdef DIVBCLEANING_DEDNER #ifdef SMOOTH_PHI HydroDataIn[j].PhiPred = SphP[place].SmoothPhi; #else HydroDataIn[j].PhiPred = SphP[place].PhiPred; #endif #endif #endif #if defined(NAVIERSTOKES) HydroDataIn[j].Entropy = SphP[place].Entropy; #endif #ifdef TIME_DEP_ART_VISC HydroDataIn[j].alpha = SphP[place].alpha; #endif #ifdef PARTICLE_DEBUG HydroDataIn[j].ID = P[place].ID; #endif #ifdef NAVIERSTOKES for(k = 0; k < 3; k++) { HydroDataIn[j].stressdiag[k] = SphP[i].u.s.StressDiag[k]; HydroDataIn[j].stressoffdiag[k] = SphP[i].u.s.StressOffDiag[k]; } HydroDataIn[j].shear_viscosity = get_shear_viscosity(i); #ifdef NAVIERSTOKES_BULK HydroDataIn[j].divvel = SphP[i].u.s.DivVel; #endif #endif #ifdef TIME_DEP_MAGN_DISP HydroDataIn[j].Balpha = SphP[place].Balpha; #endif } /* exchange particle data */ tstart = second(); for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the particles */ MPI_Sendrecv(&HydroDataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct hydrodata_in), MPI_BYTE, recvTask, TAG_HYDRO_A, &HydroDataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct hydrodata_in), MPI_BYTE, recvTask, TAG_HYDRO_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } tend = second(); timecommsumm1 += timediff(tstart, tend); myfree(HydroDataIn); HydroDataResult = (struct hydrodata_out *) mymalloc(nimport * sizeof(struct hydrodata_out)); HydroDataOut = (struct hydrodata_out *) mymalloc(nexport * sizeof(struct hydrodata_out)); /* now do the particles that were sent to us */ tstart = second(); for(j = 0; j < nimport; j++) { hydro_evaluate(j, 1, &dummy, &dummy); } tend = second(); timecomp2 += timediff(tstart, tend); if(i < 0) ndone_flag = 1; else ndone_flag = 0; tstart = second(); MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); tend = second(); timewait2 += timediff(tstart, tend); /* get the result */ tstart = second(); for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* send the results */ MPI_Sendrecv(&HydroDataResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct hydrodata_out), MPI_BYTE, recvTask, TAG_HYDRO_B, &HydroDataOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct hydrodata_out), MPI_BYTE, recvTask, TAG_HYDRO_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } tend = second(); timecommsumm2 += timediff(tstart, tend); /* add the result to the local particles */ tstart = second(); for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; for(k = 0; k < 3; k++) { SphP[place].a.dHydroAccel[k] += HydroDataOut[j].Acc[k]; } SphP[place].e.dDtEntropy += HydroDataOut[j].DtEntropy; #ifdef HYDRO_COST_FACTOR P[place].GravCost += HYDRO_COST_FACTOR * HydroDataOut[j].Ninteractions; #endif #ifdef ALTERNATIVE_VISCOUS_TIMESTEP if(SphP[place].MinViscousDt > HydroDataOut[j].MinViscousDt) SphP[place].MinViscousDt = HydroDataOut[j].MinViscousDt; #else if(SphP[place].MaxSignalVel < HydroDataOut[j].MaxSignalVel) SphP[place].MaxSignalVel = HydroDataOut[j].MaxSignalVel; #endif #ifdef OUTPUTCOOLRATE SphP[place].CondRate += HydroDataOut[j].CondRate; #endif #if defined(MAGNETIC) && !defined(EULERPOTENTIALS) for(k = 0; k < 3; k++) SphP[place].DtB[k] += HydroDataOut[j].DtB[k]; #ifdef DIVBCLEANING_DEDNER SphP[place].DtPhi += HydroDataOut[j].DtPhi; #endif #endif } tend = second(); timecomp1 += timediff(tstart, tend); myfree(HydroDataOut); myfree(HydroDataResult); myfree(HydroDataGet); } while(ndone < NTask); myfree(DataNodeList); myfree(DataIndexTable); myfree(Ngblist); /* do final operations on results */ #ifdef FLTROUNDOFFREDUCTION for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) if(P[i].Type == 0) { SphP[i].e.DtEntropy = FLT(SphP[i].e.dDtEntropy); for(j = 0; j < 3; j++) SphP[i].a.HydroAccel[j] = FLT(SphP[i].a.dHydroAccel[j]); } #endif for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) if(P[i].Type == 0) { #ifdef CR_SHOCK /* state right here: * * _c denotes comoving quantities * _p denotes physical quantities * * * Delta u_p = rho_p^(gamma-1)/(gamma-1) Delta A * * Delta A = dA/dloga * Delta loga * * dA/dloga = DtE * (gamma-1) / ( H(a) a^2 rho_c^(gamma-1) * * => Delta u_p = DtE * dloga / ( H(a) a^2 a^(3(gamma-1)) ) */ if(SphP[i].e.DtEntropy > 0.0) { rShockEnergy = SphP[i].e.DtEntropy * (P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval / hubble_a2 / fac_egy; } else { rShockEnergy = 0.0; } #endif /* CR_SHOCK */ #ifndef EOS_DEGENERATE /* Translate energy change rate into entropy change rate */ SphP[i].e.DtEntropy *= GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)); #else #ifdef EOS_ENERGY /* DtEntropy stores the energy change rate in internal units */ SphP[i].e.DtEntropy *= All.UnitEnergy_in_cgs / All.UnitTime_in_s; /* DtEntropy stores the energy change rate in physical units */ #else /* DtEntropy stores the energy change rate in internal units */ #ifndef WAKEUP eos_calc_dsdt(SphP[i].temp, SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].u, SphP[i].Entropy, SphP[i].e.DtEntropy * All.UnitEnergy_in_cgs / All.UnitTime_in_s, (P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval * All.UnitTime_in_s, &SphP[i].e.DtEntropy); #else eos_calc_dsdt(SphP[i].temp, SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].u, SphP[i].Entropy, SphP[i].e.DtEntropy * All.UnitEnergy_in_cgs / All.UnitTime_in_s, P[i].dt_step * All.Timebase_interval * All.UnitTime_in_s, &SphP[i].e.DtEntropy); #endif /* DtEntropy stores entropy change in physical units */ #endif #endif #ifdef MACHNUM /* Estimates the Mach number of particle i for non-radiative runs, * or the Mach number, density jump and specific energy jump * in case of cosmic rays! */ #if (CR_SHOCK == 2) GetMachNumberCR(SphP + i); #else #ifndef CS_MODEL GetMachNumber(SphP + i); #else GetMachNumber(SphP + i, P + i); #endif /* CS_MODEL */ #endif /* COSMIC_RAYS */ #endif /* MACHNUM */ #ifdef MACHSTATISTIC GetShock_DtEnergy(SphP + i); #endif #ifdef CR_SHOCK if(rShockEnergy > 0.0) { /* Feed fraction "All.CR_ShockEfficiency" into CR and see what * amount of energy instantly gets rethermalized * * for this, we need the physical time step, which is * Delta t_p = Delta t_c / hubble_a */ /* The CR_find_alpha_InjectTo induces an error in the density jump since it can set * Particle->Shock_DensityJump = 1.0 + 1.0e-6 which is used in ShockInject as the input DensityJump * if (NUMCRPOP > 1) * { * #if ( CR_SHOCK == 1 ) * InjPopulation = CR_Find_Alpha_to_InjectTo(All.CR_ShockAlpha); * #else * InjPopulation = CR_find_alpha_InjectTo(SphP + i); * #endif * } * else * InjPopulation = 0; */ rNonRethermalizedEnergy = CR_Particle_ShockInject(SphP + i, rShockEnergy, (P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval / hubble_a); /* Fraction of total energy that went and remained in CR is * rNonRethermalizedEnergy / rShockEnergy, * hence, we conserve energy if we do: */ #ifndef CR_NO_CHANGE SphP[i].e.DtEntropy *= (1.0 - rNonRethermalizedEnergy / rShockEnergy); #endif /* CR_NO_CHANGE */ assert(rNonRethermalizedEnergy >= 0.0); assert(rNonRethermalizedEnergy <= (rShockEnergy * All.CR_ShockEfficiency)); #if (!defined(COOLING) && (defined(CR_DISSIPATION) || defined(CR_THERMALIZATION))) utherm = 0.0; for(CRpop = 0; CRpop < NUMCRPOP; CRpop++) utherm += CR_Particle_ThermalizeAndDissipate(SphP + i, (P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval / hubble_a, CRpop); /* we need to add this thermalized energy to the internal energy */ SphP[i].e.DtEntropy += GAMMA_MINUS1 * utherm * fac_egy / pow(SphP[i].d.Density, GAMMA_MINUS1) / ((P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval); #endif } #endif /* CR_SHOCK */ #if (!defined(COOLING) && !defined(CR_SHOCK) && (defined(CR_DISSIPATION) || defined(CR_THERMALIZATION))) double utherm; double dt; int CRpop; dt = (P[i].TimeBin ? (1 << P[i].TimeBin) : 0) * All.Timebase_interval / hubble_a; if(P[i].TimeBin) /* upon start-up, we need to protect against dt==0 */ { if(dt > 0) { for(CRpop = 0; CRpop < NUMCRPOP; CRpop++) { utherm = CR_Particle_ThermalizeAndDissipate(SphP + i, dt, CRpop); SphP[i].e.DtEntropy += GAMMA_MINUS1 * utherm * fac_egy / pow(SphP[i].d.Density, GAMMA_MINUS1) / (dt*hubble_a); } } } #endif #ifdef NAVIERSTOKES /* sigma_ab * sigma_ab */ for(k = 0, fac = 0; k < 3; k++) { fac += SphP[i].u.s.StressDiag[k] * SphP[i].u.s.StressDiag[k] + 2 * SphP[i].u.s.StressOffDiag[k] * SphP[i].u.s.StressOffDiag[k]; } #ifndef NAVIERSTOKES_CONSTANT /*entropy increase due to the shear viscosity */ #ifdef NS_TIMESTEP SphP[i].ViscEntropyChange = 0.5 * GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * get_shear_viscosity(i) / SphP[i].d.Density * fac * pow((SphP[i].Entropy * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.5); SphP[i].e.DtEntropy += SphP[i].ViscEntropyChange; #else SphP[i].e.DtEntropy += 0.5 * GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * get_shear_viscosity(i) / SphP[i].d.Density * fac * pow((SphP[i].Entropy * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.5); #endif #else SphP[i].e.DtEntropy += 0.5 * GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * get_shear_viscosity(i) / SphP[i].d.Density * fac; #ifdef NS_TIMESTEP SphP[i].ViscEntropyChange = 0.5 * GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * get_shear_viscosity(i) / SphP[i].d.Density * fac; #endif #endif #ifdef NAVIERSTOKES_BULK /*entropy increase due to the bulk viscosity */ SphP[i].e.DtEntropy += GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * All.NavierStokes_BulkViscosity / SphP[i].d.Density * pow(SphP[i].u.s.a4.DivVel, 2); #ifdef NS_TIMESTEP SphP[i].ViscEntropyChange = GAMMA_MINUS1 / (hubble_a2 * pow(SphP[i].d.Density, GAMMA_MINUS1)) * All.NavierStokes_BulkViscosity / SphP[i].d.Density * pow(SphP[i].u.s.a4.DivVel, 2); #endif #endif #endif /* these entropy increases directly follow from the general heat transfer equation */ #if defined(MAGNETIC) && !defined(EULERPOTENTIALS) /* take care of cosmological dilution */ if(All.ComovingIntegrationOn) for(k = 0; k < 3; k++) SphP[i].DtB[k] -= 2.0 * SphP[i].BPred[k]; #endif #ifdef WINDS /* if we have winds, we decouple particles briefly if delaytime>0 */ if(SphP[i].DelayTime > 0) { for(k = 0; k < 3; k++) SphP[i].a.HydroAccel[k] = 0; SphP[i].e.DtEntropy = 0; #ifdef NOWINDTIMESTEPPING SphP[i].MaxSignalVel = 2 * sqrt(GAMMA * SphP[i].Pressure / SphP[i].d.Density); #else windspeed = sqrt(2 * All.WindEnergyFraction * All.FactorSN * All.EgySpecSN / (1 - All.FactorSN) / All.WindEfficiency) * All.Time; windspeed *= fac_mu; hsml_c = pow(All.WindFreeTravelDensFac * All.PhysDensThresh / (SphP[i].d.Density * a3inv), (1. / 3.)); SphP[i].MaxSignalVel = hsml_c * DMAX((2 * windspeed), SphP[i].MaxSignalVel); #endif } #endif #ifdef SPH_BND_PARTICLES if(P[i].ID == 0) { SphP[i].e.DtEntropy = 0; #ifdef NS_TIMESTEP SphP[i].ViscEntropyChange = 0; #endif for(k = 0; k < 3; k++) SphP[i].a.HydroAccel[k] = 0; } #endif #ifdef HEALPIX r_new=0; for(k = 0; k < 3; k++){ t[k]=P[i].Pos[k]-SysState.CenterOfMassComp[1][k]; r_new=+t[k]*t[k];} r_new=sqrt(r_new); vec2pix_nest((long) All.Nside,t,&ipix); if(All.healpixmap[ipix]*0.975<r_new){ SphP[i].e.DtEntropy = 0; for(k = 0; k < 3; k++) SphP[i].a.HydroAccel[k] = 0; SphP[i].v.DivVel = 0.0; for(k = 0; k < 3; k++){ SphP[i].VelPred[k]=0.0; P[i].Vel[k]=0.0;} count++; } #endif #ifdef TIME_DEP_ART_VISC cs_h = sqrt(GAMMA * SphP[i].Pressure / SphP[i].d.Density) / PPP[i].Hsml; f = fabs(SphP[i].v.DivVel) / (fabs(SphP[i].v.DivVel) + SphP[i].r.CurlVel + 0.0001 * cs_h / fac_mu); SphP[i].Dtalpha = -(SphP[i].alpha - All.AlphaMin) * All.DecayTime * 0.5 * SphP[i].MaxSignalVel / (PPP[i].Hsml * fac_mu) + f * All.ViscSource * DMAX(0.0, -SphP[i].v.DivVel); if(All.ComovingIntegrationOn) SphP[i].Dtalpha /= (hubble_a * All.Time * All.Time); #endif #ifdef MAGNETIC #ifdef TIME_DEP_MAGN_DISP SphP[i].DtBalpha = -(SphP[i].Balpha - All.ArtMagDispMin) * All.ArtMagDispTime * 0.5 * SphP[i].MaxSignalVel / (PPP[i].Hsml * fac_mu) #ifndef ROT_IN_MAG_DIS + All.ArtMagDispSource * fabs(SphP[i].divB) / sqrt(mu0 * SphP[i].d.Density); #else #ifdef SMOOTH_ROTB + All.ArtMagDispSource / sqrt(mu0 * SphP[i].d.Density) * DMAX(fabs(SphP[i].divB), fabs(sqrt(SphP[i].SmoothedRotB[0] * SphP[i].SmoothedRotB[0] + SphP[i].SmoothedRotB[1] * SphP[i].SmoothedRotB[1] + SphP[i].SmoothedRotB[2] * SphP[i].SmoothedRotB[2]))); #else + All.ArtMagDispSource / sqrt(mu0 * SphP[i].d.Density) * DMAX(fabs(SphP[i].divB), fabs(sqrt(SphP[i].RotB[0] * SphP[i].RotB[0] + SphP[i].RotB[1] * SphP[i].RotB[1] + SphP[i].RotB[2] * SphP[i].RotB[2]))); #endif #endif #endif #ifdef DIVBCLEANING_DEDNER phiphi = SphP[i].PhiPred * All.DivBcleanParabolicSigma * 0.5 * SphP[i].MaxSignalVel / (PPP[i].Hsml * fac_mu); phiphi += All.DivBcleanHyperbolicSigma * 0.25 * SphP[i].MaxSignalVel * SphP[i].MaxSignalVel #ifdef SMOOTH_PHI * SphP[i].SmoothDivB / (fac_mu * fac_mu) #else * SphP[i].divB / (fac_mu * fac_mu); #endif SphP[i].DtPhi -= phiphi; #endif #endif } #if defined(CS_MODEL) && defined(CS_FEEDBACK) for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) if(P[i].Type == 0 && (SphP[i].TempPromotion > 0 || SphP[i].DensPromotion > 0)) { SphP[i].TempPromotion = 0; SphP[i].DensPromotion = 0; } #endif #ifdef HEALPIX MPI_Allreduce(&count, &total_count,1 , MPI_INT, MPI_SUM, MPI_COMM_WORLD); if(total_count > 0){ if(ThisTask == 0) printf("hey %i particles where freeezed\n",total_count); if (total_count > 150 ){ if(ThisTask == 0) printf(" Next calculation of Healpix\n"); healpix_halo(All.healpixmap);} total_count= 0; fflush(stdout);} #endif /* collect some timing information */ t1 = WallclockTime = second(); timeall += timediff(t0, t1); timecomp = timecomp1 + timecomp2; timewait = timewait1 + timewait2; timecomm = timecommsumm1 + timecommsumm2; CPU_Step[CPU_HYDCOMPUTE] += timecomp; CPU_Step[CPU_HYDWAIT] += timewait; CPU_Step[CPU_HYDCOMM] += timecomm; CPU_Step[CPU_HYDMISC] += timeall - (timecomp + timewait + timecomm); } /*! This function is the 'core' of the SPH force computation. A target * particle is specified which may either be local, or reside in the * communication buffer. */ int hydro_evaluate(int target, int mode, int *nexport, int *nsend_local) { int startnode, numngb, listindex = 0; int j, k, n, timestep; MyDouble *pos; MyFloat *vel; MyFloat mass, h_i, dhsmlDensityFactor, rho, pressure, f1, f2; MyLongDouble acc[3], dtEntropy; #ifdef HYDRO_COST_FACTOR int ninteractions = 0; #endif #ifdef ALTERNATIVE_VISCOUS_TIMESTEP MyFloat minViscousDt; #else MyFloat maxSignalVel; #endif 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; double r, r2, u; double hfc_visc; double dmin1, dmin2; #if defined(MAGFORCE) double dmax1, dmax2; #endif double BulkVisc_ij; int imax1, imax2; #ifdef NAVIERSTOKES double faci, facj; MyFloat *stressdiag; MyFloat *stressoffdiag; MyFloat shear_viscosity; #ifdef VISCOSITY_SATURATION double VelLengthScale_i, VelLengthScale_j; double IonMeanFreePath_i, IonMeanFreePath_j; #endif #ifdef NAVIERSTOKES_BULK double facbi, facbj; MyFloat divvel; #endif #endif #if defined(NAVIERSTOKES) double Entropy; #endif #ifdef TIME_DEP_ART_VISC MyFloat alpha; #endif #ifdef ALTVISCOSITY double mu_i, mu_j; #endif #ifndef NOVISCOSITYLIMITER double dt; #endif #ifdef MAGNETIC MyFloat *bpred; #ifndef EULERPOTENTIALS double dtB[3]; #endif double dBx, dBy, dBz; double magfac, magfac_i, magfac_j, magfac_i_base; double mu0_1; #ifdef MAGNETIC_DIFFUSION double wk_i, hinv3; #endif #ifdef MAGFORCE double mm_i[3][3], mm_j[3][3]; double b2_i, b2_j; int l; #endif #if defined(MAGNETIC_DISSIPATION) || defined(DIVBCLEANING_DEDNER) double magfac_sym; #endif #ifdef MAGNETIC_DISSIPATION double dTu_diss_b, Balpha_ij; #ifdef MAGDISSIPATION_PERPEN double mft, mvt[3]; #endif #ifdef TIME_DEP_MAGN_DISP double Balpha; #endif #endif #ifdef DIVBCLEANING_DEDNER double PhiPred, DtPhi, phifac; #endif #ifdef MAGNETIC_SIGNALVEL double magneticspeed_i, magneticspeed_j, vcsa2_i, vcsa2_j, Bpro2_i, Bpro2_j; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) MyFloat *rotb; #endif #endif #ifdef PARTICLE_DEBUG MyIDType ID; /*!< particle identifier */ #endif #ifdef CONVENTIONAL_VISCOSITY double c_ij, h_ij; #endif #ifdef CS_MODEL double density, entropy; #endif if(mode == 0) { pos = P[target].Pos; vel = SphP[target].VelPred; h_i = PPP[target].Hsml; mass = P[target].Mass; dhsmlDensityFactor = SphP[target].h.DhsmlDensityFactor; rho = SphP[target].d.Density; pressure = SphP[target].Pressure; timestep = (P[target].TimeBin ? (1 << P[target].TimeBin) : 0); soundspeed_i = sqrt(GAMMA * pressure / rho); #ifdef CS_MODEL density = SphP[target].d.Density; entropy = SphP[target].Entropy; #endif #ifndef ALTVISCOSITY #ifndef NAVIERSTOKES f1 = fabs(SphP[target].v.DivVel) / (fabs(SphP[target].v.DivVel) + SphP[target].r.CurlVel + 0.0001 * soundspeed_i / PPP[target].Hsml / fac_mu); #else f1 = fabs(SphP[target].v.DivVel) / (fabs(SphP[target].v.DivVel) + SphP[target].u.s.CurlVel + 0.0001 * soundspeed_i / PPP[target].Hsml / fac_mu); #endif #else f1 = SphP[target].v.DivVel; #endif #ifdef MAGNETIC bpred = SphP[target].BPred; #ifdef DIVBCLEANING_DEDNER #ifdef SMOOTH_PHI PhiPred = SphP[target].SmoothPhi; #else PhiPred = SphP[target].PhiPred; #endif #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) #ifdef SMOOTH_ROTB rotb = SphP[target].SmoothedRotB; #else rotb = SphP[target].RotB; #endif #endif #ifdef TIME_DEP_MAGN_DISP Balpha = SphP[target].Balpha; #endif #endif /* MAGNETIC */ #ifdef TIME_DEP_ART_VISC alpha = SphP[target].alpha; #endif #if defined(NAVIERSTOKES) Entropy = SphP[target].Entropy; #endif #ifdef PARTICLE_DEBUG ID = P[target].ID; #endif #ifdef NAVIERSTOKES stressdiag = SphP[target].u.s.StressDiag; stressoffdiag = SphP[target].u.s.StressOffDiag; shear_viscosity = get_shear_viscosity(target); #ifdef NAVIERSTOKES_BULK divvel = SphP[target].u.s.a4.DivVel; #endif #endif } 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; #ifdef CS_MODEL density = HydroDataGet[target].DensityNow; entropy = HydroDataGet[target].Entropy; #endif #ifdef MAGNETIC bpred = HydroDataGet[target].BPred; #ifdef DIVBCLEANING_DEDNER PhiPred = HydroDataGet[target].PhiPred; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) rotb = HydroDataGet[target].RotB; #endif #ifdef TIME_DEP_MAGN_DISP Balpha = HydroDataGet[target].Balpha; #endif #endif /* MAGNETIC */ #ifdef TIME_DEP_ART_VISC alpha = HydroDataGet[target].alpha; #endif #if defined(NAVIERSTOKES) Entropy = HydroDataGet[target].Entropy; #endif #ifdef PARTICLE_DEBUG ID = HydroDataGet[target].ID; #endif #ifdef NAVIERSTOKES stressdiag = HydroDataGet[target].stressdiag; stressoffdiag = HydroDataGet[target].stressoffdiag; shear_viscosity = HydroDataGet[target].shear_viscosity; #endif #ifdef NAVIERSTOKES stressdiag = HydroDataGet[target].stressdiag; stressoffdiag = HydroDataGet[target].stressoffdiag; shear_viscosity = HydroDataGet[target].shear_viscosity; #ifdef NAVIERSTOKES_BULK divvel = HydroDataGet[target].divvel; #endif #endif } /* initialize variables before SPH loop is started */ acc[0] = acc[1] = acc[2] = dtEntropy = 0; #ifdef MAGNETIC #ifndef EULERPOTENTIALS for(k = 0; k < 3; k++) dtB[k] = 0; #endif mu0_1 = 1; #ifndef MU0_UNITY mu0_1 /= (4 * M_PI); mu0_1 *= All.UnitTime_in_s * All.UnitTime_in_s * All.UnitLength_in_cm / (All.UnitMass_in_g * All.HubbleParam * All.HubbleParam); #endif #ifdef DIVBCLEANING_DEDNER DtPhi = 0; #endif #ifdef MAGFORCE magfac_i_base = 1 / (rho * rho); #ifndef MU0_UNITY magfac_i_base /= (4 * M_PI); #endif #ifdef CORRECTBFRC magfac_i_base *= dhsmlDensityFactor; #endif for(k = 0, b2_i = 0; k < 3; k++) { b2_i += bpred[k] * bpred[k]; for(l = 0; l < 3; l++) mm_i[k][l] = bpred[k] * bpred[l]; } for(k = 0; k < 3; k++) mm_i[k][k] -= 0.5 * b2_i; #ifdef MAGNETIC_SIGNALVEL #ifdef ALFVEN_VEL_LIMITER vcsa2_i = soundspeed_i * soundspeed_i + DMIN(mu0_1 * b2_i / rho, ALFVEN_VEL_LIMITER * soundspeed_i * soundspeed_i); #else vcsa2_i = soundspeed_i * soundspeed_i + mu0_1 * b2_i / rho; #endif #endif #endif /* end of MAGFORCE */ #endif /* end of MAGNETIC */ p_over_rho2_i = pressure / (rho * rho); p_over_rho2_i *= dhsmlDensityFactor; h_i2 = h_i * h_i; #ifdef ALTERNATIVE_VISCOUS_TIMESTEP minViscousDt = 1.0e32; #else maxSignalVel = soundspeed_i; #endif /* Now start the actual SPH computation for this particle */ if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = HydroDataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } while(startnode >= 0) { while(startnode >= 0) { #ifdef CS_MODEL numngb = cs_ngb_treefind_pairs(pos, h_i, target, &startnode, density, entropy, &vel[0], mode, nexport, nsend_local); #else numngb = ngb_treefind_pairs(pos, h_i, target, &startnode, mode, nexport, nsend_local); #endif if(numngb < 0) return -1; for(n = 0; n < numngb; n++) { j = Ngblist[n]; #ifdef HYDRO_COST_FACTOR ninteractions++; #endif #ifdef BLACK_HOLES if(P[j].Mass == 0) continue; #endif #ifdef NOWINDTIMESTEPPING #ifdef WINDS if(P[j].Type == 0) if(SphP[j].DelayTime > 0) /* ignore the wind particles */ continue; #endif #endif dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC /* now 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 = PPP[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].d.Density * SphP[j].d.Density); soundspeed_j = sqrt(GAMMA * p_over_rho2_j * SphP[j].d.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; rho_ij = 0.5 * (rho + SphP[j].d.Density); 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); #ifdef MAGNETIC_DIFFUSION #ifndef TWODIMS hinv3 = hinv * hinv * hinv; #else hinv3 = hinv * hinv / boxSize_Z; #endif if(u <= 0.5) wk_i = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); else wk_i = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); #endif } else { dwk_i = 0; #ifdef MAGNETIC_DIFFUSION wk_i = 0; #endif } 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; } #ifdef MAGNETIC dBx = bpred[0] - SphP[j].BPred[0]; dBy = bpred[1] - SphP[j].BPred[1]; dBz = bpred[2] - SphP[j].BPred[2]; magfac = P[j].Mass / r; /* we moved 'dwk_i / rho' down ! */ if(All.ComovingIntegrationOn) magfac *= 1. / (hubble_a * All.Time * All.Time); /* last factor takes care of all cosmological prefactor */ #ifdef CORRECTDB magfac *= dhsmlDensityFactor; #endif #if defined(MAGNETIC_DISSIPATION) || defined(DIVBCLEANING_DEDNER) magfac_sym = magfac * (dwk_i + dwk_j) * 0.5; #endif #ifdef MAGNETIC_DISSIPATION #ifdef TIME_DEP_MAGN_DISP Balpha_ij = 0.5 * (Balpha + SphP[j].Balpha); #else Balpha_ij = All.ArtMagDispConst; #endif #endif magfac *= dwk_i / rho; #ifndef EULERPOTENTIALS dtB[0] += magfac * ((bpred[0] * dvy - bpred[1] * dvx) * dy + (bpred[0] * dvz - bpred[2] * dvx) * dz); dtB[1] += magfac * ((bpred[1] * dvz - bpred[2] * dvy) * dz + (bpred[1] * dvx - bpred[0] * dvy) * dx); dtB[2] += magfac * ((bpred[2] * dvx - bpred[0] * dvz) * dx + (bpred[2] * dvy - bpred[1] * dvz) * dy); #endif #ifdef MAGNETIC_DIFFUSION magfac *= All.MagneticEta; dtB[0] += magfac * (rotb[1] * dz - rotb[2] * dy); dtB[1] += magfac * (rotb[2] * dx - rotb[0] * dz); dtB[2] += magfac * (rotb[0] * dy - rotb[1] * dx); magfac *= (r * wk_i / (dwk_i * mu0_1)); dtEntropy += magfac * (rotb[0] * rotb[0] + rotb[1] * rotb[1] + rotb[2] * rotb[2]); #endif #ifdef DIVBCLEANING_DEDNER #ifdef SMOOTH_PHI phifac = magfac_sym * (PhiPred - SphP[j].SmoothPhi) / rho; #else phifac = magfac_sym * (PhiPred - SphP[j].PhiPred) / rho; #endif dtB[0] -= phifac * dx; dtB[1] -= phifac * dy; dtB[2] -= phifac * dz; #endif #ifdef MAGFORCE magfac_j = 1 / (SphP[j].d.Density * SphP[j].d.Density); #ifndef MU0_UNITY magfac_j /= (4 * M_PI); #endif #ifdef CORRECTBFRC magfac_j *= dwk_j * SphP[j].h.DhsmlDensityFactor; magfac_i = dwk_i * magfac_i_base; #else magfac_i = magfac_i_base; #endif for(k = 0, b2_j = 0; k < 3; k++) { b2_j += SphP[j].BPred[k] * SphP[j].BPred[k]; for(l = 0; l < 3; l++) mm_j[k][l] = SphP[j].BPred[k] * SphP[j].BPred[l]; } for(k = 0; k < 3; k++) mm_j[k][k] -= 0.5 * b2_j; #ifdef MAGNETIC_SIGNALVEL #ifdef ALFVEN_VEL_LIMITER vcsa2_j = soundspeed_j * soundspeed_j + DMIN(mu0_1 * b2_j / SphP[j].d.Density, ALFVEN_VEL_LIMITER * soundspeed_j * soundspeed_j); #else vcsa2_j = soundspeed_j * soundspeed_j + mu0_1 * b2_j / SphP[j].d.Density; #endif Bpro2_j = (SphP[j].BPred[0] * dx + SphP[j].BPred[1] * dy + SphP[j].BPred[2] * dz) / r; Bpro2_j *= Bpro2_j; magneticspeed_j = sqrt(vcsa2_j + sqrt(DMAX((vcsa2_j * vcsa2_j - 4 * soundspeed_j * soundspeed_j * Bpro2_j * mu0_1 / SphP[j].d.Density), 0))) / 1.4142136; Bpro2_i = (bpred[0] * dx + bpred[1] * dy + bpred[2] * dz) / r; Bpro2_i *= Bpro2_i; magneticspeed_i = sqrt(vcsa2_i + sqrt(DMAX((vcsa2_i * vcsa2_i - 4 * soundspeed_i * soundspeed_i * Bpro2_i * mu0_1 / rho), 0))) / 1.4142136; #endif #ifdef MAGNETIC_DISSIPATION dTu_diss_b = -magfac_sym * Balpha_ij * (dBx * dBx + dBy * dBy + dBz * dBz); #endif #ifdef CORRECTBFRC magfac = P[j].Mass / r; #else magfac = P[j].Mass * 0.5 * (dwk_i + dwk_j) / r; #endif if(All.ComovingIntegrationOn) magfac *= pow(All.Time, 3 * GAMMA); /* last factor takes care of all cosmological prefactor */ #ifndef MU0_UNITY magfac *= All.UnitTime_in_s * All.UnitTime_in_s * All.UnitLength_in_cm / (All.UnitMass_in_g * All.HubbleParam * All.HubbleParam); /* take care of B unit conversion into GADGET units ! */ #endif for(k = 0; k < 3; k++) acc[k] += magfac * ((mm_i[k][0] * magfac_i + mm_j[k][0] * magfac_j) * dx + (mm_i[k][1] * magfac_i + mm_j[k][1] * magfac_j) * dy + (mm_i[k][2] * magfac_i + mm_j[k][2] * magfac_j) * dz); #if defined(DIVBFORCE) && !defined(EULERPOTENTIALS) for(k = 0; k < 3; k++) acc[k] -= magfac * (((bpred[k] * bpred[0]) * magfac_i + (bpred[k] * SphP[j].BPred[0]) * magfac_j) * dx + ((bpred[k] * bpred[1]) * magfac_i + (bpred[k] * SphP[j].BPred[1]) * magfac_j) * dy + ((bpred[k] * bpred[2]) * magfac_i + (bpred[k] * SphP[j].BPred[2]) * magfac_j) * dz); #endif #endif #endif /* end of MAGNETIC */ #ifndef MAGNETIC_SIGNALVEL vsig = soundspeed_i + soundspeed_j; #else vsig = magneticspeed_i + magneticspeed_j; #endif #ifndef ALTERNATIVE_VISCOUS_TIMESTEP if(vsig > maxSignalVel) maxSignalVel = vsig; #endif if(vdotr2 < 0) /* ... artificial viscosity */ { #ifndef ALTVISCOSITY #ifndef CONVENTIONAL_VISCOSITY mu_ij = fac_mu * vdotr2 / r; /* note: this is negative! */ #else c_ij = 0.5 * (soundspeed_i + soundspeed_j); h_ij = 0.5 * (h_i + h_j); mu_ij = fac_mu * h_ij * vdotr2 / (r2 + 0.0001 * h_ij * h_ij); #endif #ifdef MAGNETIC vsig -= 1.5 * mu_ij; #else vsig -= 3 * mu_ij; #endif #ifndef ALTERNATIVE_VISCOUS_TIMESTEP if(vsig > maxSignalVel) maxSignalVel = vsig; #endif #ifndef NAVIERSTOKES f2 = fabs(SphP[j].v.DivVel) / (fabs(SphP[j].v.DivVel) + SphP[j].r.CurlVel + 0.0001 * soundspeed_j / fac_mu / PPP[j].Hsml); #else f2 = fabs(SphP[j].v.DivVel) / (fabs(SphP[j].v.DivVel) + SphP[j].u.s.CurlVel + 0.0001 * soundspeed_j / fac_mu / PPP[j].Hsml); #endif #ifdef NO_SHEAR_VISCOSITY_LIMITER f1 = f2 = 1; #endif #ifdef TIME_DEP_ART_VISC BulkVisc_ij = 0.5 * (alpha + SphP[j].alpha); #else BulkVisc_ij = All.ArtBulkViscConst; #endif #ifndef CONVENTIONAL_VISCOSITY visc = 0.25 * BulkVisc_ij * vsig * (-mu_ij) / rho_ij * (f1 + f2); #else visc = (-BulkVisc_ij * mu_ij * c_ij + 2 * BulkVisc_ij * mu_ij * mu_ij) / rho_ij * (f1 + f2) * 0.5; #endif #else /* start of ALTVISCOSITY block */ if(f1 < 0) mu_i = h_i * fabs(f1); /* f1 hold here the velocity divergence of particle i */ else mu_i = 0; if(SphP[j].u.s.a4.DivVel < 0) mu_j = h_j * fabs(SphP[j].u.s.a4.DivVel); else mu_j = 0; visc = All.ArtBulkViscConst * ((soundspeed_i + mu_i) * mu_i / rho + (soundspeed_j + mu_j) * mu_j / SphP[j].d.Density); #endif /* end of ALTVISCOSITY block */ /* .... end artificial viscosity evaluation */ /* now make sure that viscous acceleration is not too large */ #ifdef ALTERNATIVE_VISCOUS_TIMESTEP if(visc > 0) { dt = fac_vsic_fix * vdotr2 / (0.5 * (mass + P[j].Mass) * (dwk_i + dwk_j) * r * visc); dt /= hubble_a; if(dt < minViscousDt) minViscousDt = dt; } #endif #ifndef NOVISCOSITYLIMITER dt = 2 * IMAX(timestep, (P[j].TimeBin ? (1 << P[j].TimeBin) : 0)) * All.Timebase_interval; if(dt > 0 && (dwk_i + dwk_j) < 0) { #ifdef BLACK_HOLES if((mass + P[j].Mass) > 0) #endif 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].h.DhsmlDensityFactor; hfc_visc = 0.5 * P[j].Mass * visc * (dwk_i + dwk_j) / r; /* Formulation derived from the Lagrangian */ hfc = hfc_visc + P[j].Mass * (p_over_rho2_i * dwk_i + p_over_rho2_j * dwk_j) / r; #ifdef WINDS if(P[j].Type == 0) if(SphP[j].DelayTime > 0) /* No force by wind particles */ { hfc = hfc_visc = 0; } #endif #ifndef NOACCEL acc[0] += FLT(-hfc * dx); acc[1] += FLT(-hfc * dy); acc[2] += FLT(-hfc * dz); #endif #ifndef EOS_ENERGY dtEntropy += FLT(0.5 * hfc_visc * vdotr2); #else dtEntropy += FLT(0.5 * hfc * vdotr2); #endif #ifdef NAVIERSTOKES faci = mass * shear_viscosity / (rho * rho) * dwk_i / r; #ifndef NAVIERSTOKES_CONSTANT faci *= pow((Entropy * pow(rho * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.5); /*multiplied by E^5/2 */ #endif facj = P[j].Mass * get_shear_viscosity(j) / (SphP[j].d.Density * SphP[j].d.Density) * dwk_j / r; #ifndef NAVIERSTOKES_CONSTANT facj *= pow((SphP[j].Entropy * pow(SphP[j].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.5); /*multiplied by E^5/2 */ #endif #ifdef NAVIERSTOKES_BULK facbi = mass * All.NavierStokes_BulkViscosity / (rho * rho) * dwk_i / r; facbj = P[j].Mass * All.NavierStokes_BulkViscosity / (SphP[j].d.Density * SphP[j].d.Density) * dwk_j / r; #endif #ifdef WINDS if(P[j].Type == 0) if(SphP[j].DelayTime > 0) /* No visc for wind particles */ { faci = facj = 0; #ifdef NAVIERSTOKES_BULK facbi = facbj = 0; #endif } #endif #ifdef VISCOSITY_SATURATION IonMeanFreePath_i = All.IonMeanFreePath * pow((Entropy * pow(rho * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.0) / rho; /* u^2/rho */ IonMeanFreePath_j = All.IonMeanFreePath * pow((SphP[j].Entropy * pow(SphP[j].d.Density * a3inv, GAMMA_MINUS1) / GAMMA_MINUS1), 2.0) / SphP[j].d.Density; /* u^2/rho */ for(k = 0, VelLengthScale_i = 0, VelLengthScale_j = 0; k < 3; k++) { if(fabs(stressdiag[k]) > 0) { VelLengthScale_i = 2 * soundspeed_i / fabs(stressdiag[k]); if(VelLengthScale_i < IonMeanFreePath_i && VelLengthScale_i > 0) { stressdiag[k] = stressdiag[k] * (VelLengthScale_i / IonMeanFreePath_i); } } if(fabs(SphP[j].u.s.StressDiag[k]) > 0) { VelLengthScale_j = 2 * soundspeed_j / fabs(SphP[j].u.s.StressDiag[k]); if(VelLengthScale_j < IonMeanFreePath_j && VelLengthScale_j > 0) { SphP[j].u.s.StressDiag[k] = SphP[j].u.s.StressDiag[k] * (VelLengthScale_j / IonMeanFreePath_j); } } if(fabs(stressoffdiag[k]) > 0) { VelLengthScale_i = 2 * soundspeed_i / fabs(stressoffdiag[k]); if(VelLengthScale_i < IonMeanFreePath_i && VelLengthScale_i > 0) { stressoffdiag[k] = stressoffdiag[k] * (VelLengthScale_i / IonMeanFreePath_i); } } if(fabs(SphP[j].u.s.StressOffDiag[k]) > 0) { VelLengthScale_j = 2 * soundspeed_j / fabs(SphP[j].u.s.StressOffDiag[k]); if(VelLengthScale_j < IonMeanFreePath_j && VelLengthScale_j > 0) { SphP[j].u.s.StressOffDiag[k] = SphP[j].u.s.StressOffDiag[k] * (VelLengthScale_j / IonMeanFreePath_j); } } } #endif /* Acceleration due to the shear viscosity */ acc[0] += faci * (stressdiag[0] * dx + stressoffdiag[0] * dy + stressoffdiag[1] * dz) + facj * (SphP[j].u.s.StressDiag[0] * dx + SphP[j].u.s.StressOffDiag[0] * dy + SphP[j].u.s.StressOffDiag[1] * dz); acc[1] += faci * (stressoffdiag[0] * dx + stressdiag[1] * dy + stressoffdiag[2] * dz) + facj * (SphP[j].u.s.StressOffDiag[0] * dx + SphP[j].u.s.StressDiag[1] * dy + SphP[j].u.s.StressOffDiag[2] * dz); acc[2] += faci * (stressoffdiag[1] * dx + stressoffdiag[2] * dy + stressdiag[2] * dz) + facj * (SphP[j].u.s.StressOffDiag[1] * dx + SphP[j].u.s.StressOffDiag[2] * dy + SphP[j].u.s.StressDiag[2] * dz); /*Acceleration due to the bulk viscosity */ #ifdef NAVIERSTOKES_BULK #ifdef VISCOSITY_SATURATION VelLengthScale_i = 0; VelLengthScale_j = 0; if(fabs(divvel) > 0) { VelLengthScale_i = 3 * soundspeed_i / fabs(divvel); if(VelLengthScale_i < IonMeanFreePath_i && VelLengthScale_i > 0) { divvel = divvel * (VelLengthScale_i / IonMeanFreePath_i); } } if(fabs(SphP[j].u.s.a4.DivVel) > 0) { VelLengthScale_j = 3 * soundspeed_j / fabs(SphP[j].u.s.a4.DivVel); if(VelLengthScale_j < IonMeanFreePath_j && VelLengthScale_j > 0) { SphP[j].u.s.a4.DivVel = SphP[j].u.s.a4.DivVel * (VelLengthScale_j / IonMeanFreePath_j); } } #endif acc[0] += facbi * divvel * dx + facbj * SphP[j].u.s.a4.DivVel * dx; acc[1] += facbi * divvel * dy + facbj * SphP[j].u.s.a4.DivVel * dy; acc[2] += facbi * divvel * dz + facbj * SphP[j].u.s.a4.DivVel * dz; #endif #endif /* end NAVIERSTOKES */ #ifdef MAGNETIC #ifdef MAGNETIC_DISSIPATION <<<<<<< .mine <<<<<<< .mine magfac_sym *= vsig * 0.5 * Balpha_ij * r * rho / (rho_ij * rho_ij); dtEntropy += dTu_diss_b * 0.25 * vsig * mu0_1 * r / (rho_ij * rho_ij); dtB[0] += magfac_sym * dBx; dtB[1] += magfac_sym * dBy; dtB[2] += magfac_sym * dBz; ======= magfac_sym *= vsig * 0.5 * Balpha_ij * r * rho / (rho_ij ) ; dtEntropy += dTu_diss_b * 0.25 * vsig * mu0_1 * r / (rho_ij ); ======= magfac_sym *= vsig * 0.5 * Balpha_ij * r * rho / (rho_ij * rho_ij); dtEntropy += dTu_diss_b * 0.25 * vsig * mu0_1 * r / (rho_ij * rho_ij); >>>>>>> .r5134 dtB[0] += magfac_sym * dBx; dtB[1] += magfac_sym * dBy; dtB[2] += magfac_sym * dBz; >>>>>>> .r5070 #endif #endif #ifdef WAKEUP if(maxSignalVel > 1.1 * SphP[j].MaxSignalVel) { SphP[j].wakeup = 1; } #endif } } } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = HydroDataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } /* Now collect the result at the right place */ if(mode == 0) { for(k = 0; k < 3; k++) SphP[target].a.dHydroAccel[k] = acc[k]; SphP[target].e.dDtEntropy = dtEntropy; #ifdef HYDRO_COST_FACTOR P[target].GravCost += HYDRO_COST_FACTOR * ninteractions; #endif #ifdef ALTERNATIVE_VISCOUS_TIMESTEP SphP[target].MinViscousDt = minViscousDt; #else SphP[target].MaxSignalVel = maxSignalVel; #endif #if defined(MAGNETIC) && !defined(EULERPOTENTIALS) for(k = 0; k < 3; k++) SphP[target].DtB[k] = dtB[k]; #ifdef DIVBCLEANING_DEDNER SphP[target].DtPhi = DtPhi; #endif #endif } else { for(k = 0; k < 3; k++) HydroDataResult[target].Acc[k] = acc[k]; HydroDataResult[target].DtEntropy = dtEntropy; #ifdef HYDRO_COST_FACTOR HydroDataResult[target].Ninteractions = ninteractions; #endif #ifdef ALTERNATIVE_VISCOUS_TIMESTEP HydroDataResult[target].MinViscousDt = minViscousDt; #else HydroDataResult[target].MaxSignalVel = maxSignalVel; #endif #if defined(MAGNETIC) && !defined(EULERPOTENTIALS) for(k = 0; k < 3; k++) HydroDataResult[target].DtB[k] = dtB[k]; #ifdef DIVBCLEANING_DEDNER HydroDataResult[target].DtPhi = DtPhi; #endif #endif } return 0; }
{ "alphanum_fraction": 0.6297357141, "avg_line_length": 26.8267029973, "ext": "c", "hexsha": "63280c231d9a17c1ed2854bc34cb8b1a4cce6a7d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/hydra.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/hydra.c", "max_line_length": 174, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/hydra.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 17067, "size": 49227 }
#ifndef _FUNCTIONS_ #define _FUNCTIONS_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <limits.h> #include <cblas.h> #include <lapacke.h> #include "structs.c" #define PATH_LENGTH 32 #define LINE_LENGTH 26000 #define THRESHOLD 0.05 // Declare functions of functions.c file int is_centroid(int *, int, int); double rand_gaussian(); int centroids_transposition(conformation **, int *, int *, int, double **); double **create_distances_array(conformation **, int, int, int); #endif
{ "alphanum_fraction": 0.7252747253, "avg_line_length": 17.0625, "ext": "h", "hexsha": "ebed542ce329a34147d7b4bc61998dc2994c3617", "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": "b42b8face124a32d8b8ef7d0c3dc5bea9887f824", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chanioxaris/MolecularConfigurations-Clustering", "max_forks_repo_path": "src/functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b42b8face124a32d8b8ef7d0c3dc5bea9887f824", "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": "chanioxaris/MolecularConfigurations-Clustering", "max_issues_repo_path": "src/functions.h", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "b42b8face124a32d8b8ef7d0c3dc5bea9887f824", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chanioxaris/MolecularConfigurations-Clustering", "max_stars_repo_path": "src/functions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 138, "size": 546 }
/* wavelet/dwt.c * * Copyright (C) 2004 Ivo Alxneit * * 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. */ /* function dwt_step is based on the public domain function pwt.c * available from http://www.numerical-recipes.com */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_wavelet.h> #include <gsl/gsl_wavelet2d.h> #define ELEMENT(a,stride,i) ((a)[(stride)*(i)]) static int binary_logn (const size_t n); static void dwt_step (const gsl_wavelet * w, double *a, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); static int binary_logn (const size_t n) { size_t ntest; size_t logn = 0; size_t k = 1; while (k < n) { k *= 2; logn++; } ntest = ((size_t)1 << logn); if (n != ntest) { return -1; /* n is not a power of 2 */ } return logn; } static void dwt_step (const gsl_wavelet * w, double *a, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { double ai, ai1; size_t i, ii; size_t jf; size_t k; size_t n1, ni, nh, nmod; for (i = 0; i < work->n; i++) { work->scratch[i] = 0.0; } nmod = w->nc * n; nmod -= w->offset; /* center support */ n1 = n - 1; nh = n >> 1; if (dir == gsl_wavelet_forward) { for (ii = 0, i = 0; i < n; i += 2, ii++) { double h = 0, g = 0; ni = i + nmod; for (k = 0; k < w->nc; k++) { jf = n1 & (ni + k); h += w->h1[k] * ELEMENT (a, stride, jf); g += w->g1[k] * ELEMENT (a, stride, jf); } work->scratch[ii] += h; work->scratch[ii + nh] += g; } } else { for (ii = 0, i = 0; i < n; i += 2, ii++) { ai = ELEMENT (a, stride, ii); ai1 = ELEMENT (a, stride, ii + nh); ni = i + nmod; for (k = 0; k < w->nc; k++) { jf = (n1 & (ni + k)); work->scratch[jf] += (w->h2[k] * ai + w->g2[k] * ai1); } } } for (i = 0; i < n; i++) { ELEMENT (a, stride, i) = work->scratch[i]; } } int gsl_wavelet_transform (const gsl_wavelet * w, double *data, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { size_t i; if (work->n < n) { GSL_ERROR ("not enough workspace provided", GSL_EINVAL); } if (binary_logn (n) == -1) { GSL_ERROR ("n is not a power of 2", GSL_EINVAL); } if (n < 2) { return GSL_SUCCESS; } if (dir == gsl_wavelet_forward) { for (i = n; i >= 2; i >>= 1) { dwt_step (w, data, stride, i, dir, work); } } else { for (i = 2; i <= n; i <<= 1) { dwt_step (w, data, stride, i, dir, work); } } return GSL_SUCCESS; } int gsl_wavelet_transform_forward (const gsl_wavelet * w, double *data, size_t stride, size_t n, gsl_wavelet_workspace * work) { return gsl_wavelet_transform (w, data, stride, n, gsl_wavelet_forward, work); } int gsl_wavelet_transform_inverse (const gsl_wavelet * w, double *data, size_t stride, size_t n, gsl_wavelet_workspace * work) { return gsl_wavelet_transform (w, data, stride, n, gsl_wavelet_backward, work); } /* Leaving this out for now BJG */ #if 0 int gsl_dwt_vector (const gsl_wavelet * w, gsl_vector *v, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { return gsl_dwt (w, v->data, v->stride, v->size, dir, work); } #endif int gsl_wavelet2d_transform (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { size_t i; if (size1 != size2) { GSL_ERROR ("2d dwt works only with square matrix", GSL_EINVAL); } if (work->n < size1) { GSL_ERROR ("not enough workspace provided", GSL_EINVAL); } if (binary_logn (size1) == -1) { GSL_ERROR ("n is not a power of 2", GSL_EINVAL); } if (size1 < 2) { return GSL_SUCCESS; } if (dir == gsl_wavelet_forward) { for (i = 0; i < size1; i++) /* for every row j */ { gsl_wavelet_transform (w, &ELEMENT(data, tda, i), 1, size1, dir, work); } for (i = 0; i < size2; i++) /* for every column j */ { gsl_wavelet_transform (w, &ELEMENT(data, 1, i), tda, size2, dir, work); } } else { for (i = 0; i < size2; i++) /* for every column j */ { gsl_wavelet_transform (w, &ELEMENT(data, 1, i), tda, size2, dir, work); } for (i = 0; i < size1; i++) /* for every row j */ { gsl_wavelet_transform (w, &ELEMENT(data, tda, i), 1, size1, dir, work); } } return GSL_SUCCESS; } int gsl_wavelet2d_nstransform (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { size_t i, j; if (size1 != size2) { GSL_ERROR ("2d dwt works only with square matrix", GSL_EINVAL); } if (work->n < size1) { GSL_ERROR ("not enough workspace provided", GSL_EINVAL); } if (binary_logn (size1) == -1) { GSL_ERROR ("n is not a power of 2", GSL_EINVAL); } if (size1 < 2) { return GSL_SUCCESS; } if (dir == gsl_wavelet_forward) { for (i = size1; i >= 2; i >>= 1) { for (j = 0; j < i; j++) /* for every row j */ { dwt_step (w, &ELEMENT(data, tda, j), 1, i, dir, work); } for (j = 0; j < i; j++) /* for every column j */ { dwt_step (w, &ELEMENT(data, 1, j), tda, i, dir, work); } } } else { for (i = 2; i <= size1; i <<= 1) { for (j = 0; j < i; j++) /* for every column j */ { dwt_step (w, &ELEMENT(data, 1, j), tda, i, dir, work); } for (j = 0; j < i; j++) /* for every row j */ { dwt_step (w, &ELEMENT(data, tda, j), 1, i, dir, work); } } } return GSL_SUCCESS; } int gsl_wavelet2d_transform_forward (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_workspace * work) { return gsl_wavelet2d_transform (w, data, tda, size1, size2, gsl_wavelet_forward, work); } int gsl_wavelet2d_transform_inverse (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_workspace * work) { return gsl_wavelet2d_transform (w, data, tda, size1, size2, gsl_wavelet_backward, work); } int gsl_wavelet2d_nstransform_forward (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_workspace * work) { return gsl_wavelet2d_nstransform (w, data, tda, size1, size2, gsl_wavelet_forward, work); } int gsl_wavelet2d_nstransform_inverse (const gsl_wavelet * w, double *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_workspace * work) { return gsl_wavelet2d_nstransform (w, data, tda, size1, size2, gsl_wavelet_backward, work); } int gsl_wavelet2d_transform_matrix (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { return gsl_wavelet2d_transform (w, a->data, a->tda, a->size1, a->size2, dir, work); } int gsl_wavelet2d_transform_matrix_forward (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_workspace * work) { return gsl_wavelet2d_transform (w, a->data, a->tda, a->size1, a->size2, gsl_wavelet_forward, work); } int gsl_wavelet2d_transform_matrix_inverse (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_workspace * work) { return gsl_wavelet2d_transform (w, a->data, a->tda, a->size1, a->size2, gsl_wavelet_backward, work); } int gsl_wavelet2d_nstransform_matrix (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_direction dir, gsl_wavelet_workspace * work) { return gsl_wavelet2d_nstransform (w, a->data, a->tda, a->size1, a->size2, dir, work); } int gsl_wavelet2d_nstransform_matrix_forward (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_workspace * work) { return gsl_wavelet2d_nstransform (w, a->data, a->tda, a->size1, a->size2, gsl_wavelet_forward, work); } int gsl_wavelet2d_nstransform_matrix_inverse (const gsl_wavelet * w, gsl_matrix * a, gsl_wavelet_workspace * work) { return gsl_wavelet2d_nstransform (w, a->data, a->tda, a->size1, a->size2, gsl_wavelet_backward, work); }
{ "alphanum_fraction": 0.5090925875, "avg_line_length": 27.2871536524, "ext": "c", "hexsha": "519e955380d48be9f83de7e4792de70cb667bd41", "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/wavelet/dwt.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/wavelet/dwt.c", "max_line_length": 138, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/wavelet/dwt.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": 2990, "size": 10833 }
/* GENETIC - A simple genetic algorithm. Copyright 2014, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file test_genetic.c * \brief Source file to test the genetic algorithm functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> #include <glib.h> #if HAVE_MPI #include <mpi.h> #endif #include "entity.h" #include "population.h" #include "reproduction.h" #include "selection.h" #include "evolution.h" #include "genetic.h" int ntasks = 1; ///< Number of tasks. unsigned int nthreads = 1; ///< Number of threads. GMutex mutex[1]; ///< Mutex to lock memory writing on threads. GeneticVariable v[2]; ///< Array of variables to optimize. /** * Evaluation function. * * \return RMSE error on the linear equations system: x+y=3, x-y=1. */ double evaluate (Entity * entity) ///< Entity to simulate. { double x, y, e1, e2; x = genetic_get_variable (entity, v); y = genetic_get_variable (entity, v + 1); e1 = x + y - 3.; e2 = x - y - 1.; e1 = e1 * e1 + e2 * e2; return e1; } /** * Main function. * * \return 0 always. */ int main (int argn ///< Number of arguments. #if !HAVE_MPI __attribute__ ((unused)) #endif , char **argc ///< Array of argument strings. #if !HAVE_MPI __attribute__ ((unused)) #endif ) { int rank; char *best_genome; double *best_variables, best_objective; #if HAVE_MPI MPI_Init (&argn, &argc); MPI_Comm_size (MPI_COMM_WORLD, &ntasks); MPI_Comm_rank (MPI_COMM_WORLD, &rank); #else rank = 0; #endif nthreads = 4; v[0].maximum = 10.; v[0].minimum = -10.; v[0].nbits = 16; v[1].maximum = 10.; v[1].minimum = -10.; v[1].nbits = 16; genetic_algorithm_default (2, v, 100, 20, 0.3, 0.4, 0.1, 707l, 0.0, &evaluate, &best_genome, &best_variables, &best_objective); if (rank == 0) { printf ("x=%lg y=%lg error=%lg\n", best_variables[0], best_variables[1], best_objective); g_free (best_genome); g_free (best_variables); } #if HAVE_MPI MPI_Finalize (); #endif return 0; }
{ "alphanum_fraction": 0.6364602711, "avg_line_length": 29.1705426357, "ext": "c", "hexsha": "ee121f9f46669f8a9800a907957d27e94f56d128", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_path": "3.0.0/test_genetic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_path": "3.0.0/test_genetic.c", "max_line_length": 79, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_path": "3.0.0/test_genetic.c", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "num_tokens": 923, "size": 3763 }
/** * Interface definitions for the postscript output routines */ #ifndef _SPCE_OUTPUT_H #define _SPCE_OUTPUT_H #include "aper_conf.h" #include <gsl/gsl_matrix.h> /* * Structure to store all information on * a stamp image which is going to be * created. This information is steps in x * start coos in x,y and image dimensions. */ typedef struct { double resolution; double xstart; double ystart; long xsize; long ysize; } drzstamp_dim; /* * Quadrangle structure to be filled with the * corners of a pixel in the drizzled coo-system. * Those corners are then passed to the boxer * subroutine to determine the overlap for a * particular pixel */ typedef struct { double xmax; // the maximum value in x[] double xmin; // the minimum value in x[] double ymax; // the maximum value in y[] double ymin; // the minimum value in y[] // (x[0],y[0]), (x[1],y[1]) double x[4]; // (x[2],y[2]) and (x[3],y[3]) double y[4]; // are the corner points of a pixel // in the coo-system of the drizzled image } quadrangle; typedef struct { gsl_matrix *counts; gsl_matrix *weight; } drzstamp; /* * Structure for all stamp images * of a beam in 'drzprep' */ typedef struct { gsl_matrix *counts; gsl_matrix *error; gsl_matrix *cont; gsl_matrix *model; gsl_matrix *vari; } drzprep; extern gsl_vector_int * get_trace_inds (const ap_pixel * const ap_p); extern gsl_matrix * stamp_img (const ap_pixel * const ap_p, float width, d_point *stp_min); extern drzprep * stamp_img_drzprep (const int opt_extr, const ap_pixel * const ap_p, const ap_pixel * const se_p, float width, float nullval, int usemode, drzstamp_dim dimension, gsl_matrix *drzcoeffs, double exptime, double sky_cps, double rdnoise, const int bckmode); extern void free_drzprep(drzprep *drzprep_stamps); extern gsl_matrix * rectified_stamp_img (const ap_pixel * const ap_p, float width, d_point *stp_min); extern d_point get_minxy_from_PET(const ap_pixel * const ap_p); extern d_point get_maxxy_from_PET(const ap_pixel * const ap_p); extern drzstamp * drizzled_stamp_img (const ap_pixel * const ap_p, double width, const double orient, const drzstamp_dim dimension); extern drzstamp_dim get_drzprep_dim(const ap_pixel *const ap_p, float width, int boxwidth, int boxheight); extern drzstamp_dim get_stamp_dim(const ap_pixel * const ap_p, float width, aperture_conf *conf, const int beamID, d_point *stp_min); extern quadrangle get_quad_from_pixel(const ap_pixel *cur_p, const double orient, const drzstamp_dim dimension); extern gsl_matrix * drizzled_stamp_img_orig (const ap_pixel * const ap_p, float width, aperture_conf *conf); extern void interpolate_over_NaN (gsl_matrix *data); extern void free_stamp_img(gsl_matrix *stamp); extern void free_drzstamp(drzstamp *stamp); #endif
{ "alphanum_fraction": 0.7269885377, "avg_line_length": 22.8492063492, "ext": "h", "hexsha": "776fbc0223e65c54e689776b51e769efc2b2b516", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spce_output.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spce_output.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spce_output.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 780, "size": 2879 }
#include <math.h> #include <stdio.h> #include <mpfr.h> #include <stdlib.h> #include <string.h> #include <petsc.h> #include <time.h> #include "ellipsoid.h" #include "MPFReigs.h" extern void dgeev_(char *jobvl, char *jobvr, int *N, double *A, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info); extern void dgetrs_(char *trans, int *n, int *nrhs, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info); extern void dgetrf_(int *M, int *N, double *A, int *lda, int *ipiv, int *info); static double max(double a, double b) { if( a > b) return a; return b; } static double min(double a, double b) { if( a > b ) return b; return a; } void matTranspose(double *A, int n) { double *cpy = (double*) malloc(sizeof(double)*n*n); memcpy(cpy, A, sizeof(double)*n*n); for(int i=0; i<n; ++i) { for(int j=0; j<n; ++j) { A[i*n+j] = cpy[j*n+i]; } } free(cpy); } #undef __FUNCT__ #define __FUNCT__ "initEllipsoidalSystem" PetscErrorCode initEllipsoidalSystem(struct EllipsoidalSystem *s, double a, double b, double c, PetscInt precision) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; //set pointers to NULL and maxN to 0 s->Dconsts = NULL; s->Rconsts = NULL; s->normConstants = NULL; s->DmaxN = 0; s->RmaxN = 0; //default init Romain constants to order 40 int N = 56; s->a = a; s->b = b; s->c = c; s->precision = precision; mpfr_set_default_prec(4*precision); mpfr_t temp; mpfr_init(temp); s->h2 = a*a-b*b; s->h = sqrt(s->h2); s->k2 = a*a-c*c; s->k = sqrt(s->k2); flopCount += 8; mpfr_inits2(4*s->precision, s->hp_h2, s->hp_h, s->hp_k2, s->hp_k, NULL); //calculates high precision h2 mpfr_set_d(s->hp_h2, b, MPFR_RNDN); mpfr_mul_d(s->hp_h2, s->hp_h2, b, MPFR_RNDN); mpfr_set_d(temp, a, MPFR_RNDN); mpfr_mul_d(temp, temp, a, MPFR_RNDN); mpfr_sub(s->hp_h2, temp, s->hp_h2, MPFR_RNDN); flopCount += 3; //calculates high precision h mpfr_sqrt(s->hp_h, s->hp_h2, MPFR_RNDN); flopCount += 1; //calculates high precision k2 mpfr_set_d(s->hp_k2, c, MPFR_RNDN); mpfr_mul_d(s->hp_k2, s->hp_k2, c, MPFR_RNDN); mpfr_sub(s->hp_k2, temp, s->hp_k2, MPFR_RNDN); flopCount += 2; //calculates high precision k mpfr_sqrt(s->hp_k, s->hp_k2, MPFR_RNDN); flopCount += 1; //initializes all the variables for integrate. mpfr_inits2(4*s->precision, s->alpha, s->beta, s->h_step, s->sum, s->osum, s->psum, s->yk, s->wk, s->lx, s->rx, s->tmp, s->maxTerm, s->curTerm, s->pi2, s->kh, s->msinh, s->mcosh, s->lval, s->rval, NULL); //initialize other temp variables mpfr_inits2(4*s->precision, s->temp1, s->temp2, s->temp3, s->tempa, s->tempb, s->endpt, NULL); //constants mpfr_inits2(4*s->precision, s->mpfrzero, s->mpfrone, NULL); mpfr_set_d(s->mpfrzero, 0.0, MPFR_RNDN); mpfr_set_d(s->mpfrone , 1.0, MPFR_RNDN); ierr = initRomainConstsToOrderN(s, N);CHKERRQ(ierr); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } void ellipsoidInitToOrderN(EllipsoidalSystem *s, int N) { s->Dconsts = (double***) malloc(sizeof(double**)*(N+1)); s->normConstants = (double**) malloc(sizeof(double*)*(N+1)); s->tVals = (char**) malloc(sizeof(char*)*(N+1)); s->tpVals = (int**) malloc(sizeof(int* )*(N+1)); for(int n=0; n<N+1; ++n) { s->Dconsts[n] = (double**) malloc(sizeof(double*)*(2*n+1)); s->normConstants[n] = (double*) malloc(sizeof(double)*(2*n+1)); s->tVals[n] = (char*) malloc(sizeof(char)*(2*n+1)); s->tpVals[n] = (int *) malloc(sizeof(int) *(2*n+1)); } //loop over n for(int n=0; n<=N; ++n) { getCoefsK(s, n, s->Dconsts[n]); if(n != 0) { getCoefsL(s, n, s->Dconsts[n] + (n/2)+1); getCoefsM(s, n, s->Dconsts[n] + (n/2)+1 + (n+1)/2); if(n != 1) { getCoefsN(s, n, s->Dconsts[n] + (n/2)+1 + (n+1)/2 + (n+1)/2); } } //loop over p for(int p=0; p<2*n+1; ++p) { s->tVals [n][p] = getLameTypeT (n, p); s->tpVals[n][p] = getLameTypeTp(n, p); } } } void printMatrix(double *M, int matSize) { for(int n=0; n<matSize; ++n) { for(int m=0; m<matSize; ++m) { printf("%4.4f ", M[n*matSize+m]); } printf("\n"); } } void eigs(double *M, int matSize, double *real, double *imag) { //transpose M for lapack matTranspose(M, matSize); int lwork = 16*matSize; int info; double *work, *wr, *wi; //vr = (double*) malloc(sizeof(double)*matSize*matSize); wr = (double*) malloc(sizeof(double)*matSize); wi = (double*) malloc(sizeof(double)*matSize); work = (double*) malloc(sizeof(double)*lwork); //compute eigenvalues with lapack char complefteig, comprighteig; complefteig = 'N'; //don't compute left eigenvectors comprighteig = 'N'; //don't compute right eigenvectors dgeev_( &complefteig, &comprighteig, &matSize, M, &matSize, wr, wi, NULL, &matSize, NULL, &matSize, work, &lwork, &info ); matTranspose(M, matSize); for(int i=0; i<matSize; ++i) real[i] = wr[i]; if(imag != NULL) { for(int i=0; i<matSize; ++i) imag[i] = wi[i]; } } #undef __FUNCT__ #define __FUNCT__ "getCoefsK" ////////////// //FROM DASSIOS ////////////// PetscErrorCode getCoefsK(EllipsoidalSystem *s, int n, double **coefs) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; //r=n/2 if even, (n-1)/2 if odd int r = n/2; //matrix size for class K is r+1 int matSize = r+1; //constants double alpha = s->h2 + s->k2; double beta = s->h2 * s->k2; //initialize matrix and tridiagonals double *M = (double*) malloc(sizeof(double)*matSize*matSize); double *d = (double*) malloc(sizeof(double)*matSize); double *f = (double*) malloc(sizeof(double)*(matSize-1)); double *g = (double*) malloc(sizeof(double)*(matSize-1)); flopCount = 2; //construct the diagonal (size matSize) for(int i=1; i<=matSize; ++i) d[i-1] = (n - 2*i + 2)*(n - 2*i + 2); flopCount += 7*matSize; //construct above and below diagonal (size matSize-1) for(int i=1; i<matSize; ++i) { g[i-1] = (2./alpha)*i*(2*n - 2*i + 1); f[i-1] = -(beta/alpha)*(n - 2*i + 1)*(n - 2*i + 2); } flopCount += 17*matSize; //fill diagonal with d for(int k=0; k < matSize; ++k) M[k*matSize + k] = d[k]; //fill above diagonal with g, below with f for(int k=0; k < matSize-1; ++k) { M[(k)*matSize + k+1] = g[k]; M[(k+1)*matSize + k] = f[k]; } double *vals = (double*) malloc(sizeof(double)*matSize); eigs(M, matSize, vals, NULL); //for(int i=0; i<matSize; ++i) //printf("Kn=%d vals[%d] = %15.15f\n", n, i, vals[i]); double pj; //loop over each root for(int p=0; p<matSize; ++p) { coefs[p] = (double*) malloc(sizeof(double)*(matSize)); pj = vals[p]; coefs[p][0] = 1.0; if(matSize != 1) coefs[p][1] = alpha*(pj - n*n)/(2*(2*n - 1)); for(int k=2; k<matSize; ++k) { coefs[p][k] = (alpha*(pj - (n - 2*k + 2)*(n - 2*k + 2)) * coefs[p][k-1] + beta*(n - 2*k + 4)*(n - 2*k + 3) * coefs[p][k-2]) /(2*k*(2*n - 2*k + 1)); } } flopCount += 7*matSize + matSize*PetscMax(0,(matSize-2))*27; //for(int i=0; i<matSize; ++i) //printf("%5.5f\n", vals[i]); ierr = PetscLogFlops(flopCount); PetscFunctionReturn(0); } void getCoefsL(EllipsoidalSystem *s, int n, double **coefs) { //r=n/2 if even, (n-1)/2 if odd int r = (n+1)/2; //matrix size for class K is r+1 int matSize = r; //constants double alpha = s->h2 + s->k2; double beta = s->h2 * s->k2; //initialize matrix and tridiagonals double *M = (double*) malloc(sizeof(double)*matSize*matSize); double *d = (double*) malloc(sizeof(double)*matSize); double *f = (double*) malloc(sizeof(double)*(matSize-1)); double *g = (double*) malloc(sizeof(double)*(matSize-1)); //construct the diagonal (size matSize) for(int i=1; i<=matSize; ++i) d[i-1] = (n - 2*i + 1)*(n - 2*i + 1) + (s->k2/alpha)*(2*n - 4*i + 3); //construct above and below diagonal (size matSize-1) for(int i=1; i<matSize; ++i) { g[i-1] = (2./alpha)*i*(2*n - 2*i + 1); f[i-1] = -(beta/alpha)*(n - 2*i + 1)*(n - 2*i); } //fill diagonal with d for(int k=0; k < matSize; ++k) M[k*matSize + k] = d[k]; //fill above diagonal with g, below with f for(int k=0; k < matSize-1; ++k) { M[(k)*matSize + k+1] = g[k]; M[(k+1)*matSize + k] = f[k]; } double *vals = (double*) malloc(sizeof(double)*matSize); eigs(M, matSize, vals, NULL); for(int i=0; i<matSize; ++i) printf("n=%d vals[%d] = %15.15f\n", n, i, vals[i]); //printf("%15.15f\n", (1/alpha)*(2*alpha + 3*s->k2 - 2*sqrt((alpha+s->k2)*(alpha+s->k2) - 5*beta))); double pj; //loop over each root for(int p=0; p<matSize; ++p) { coefs[p] = (double*) malloc(sizeof(double)*(matSize)); pj = vals[p]; coefs[p][0] = 1.0; if(matSize != 1) coefs[p][1] = (alpha*(pj - (n-1)*(n-1)) - (2*n - 1)*(2*n - 1)*s->k2)/(2*(2*n-1)); for(int k=2; k<matSize; ++k) { coefs[p][k] = ((alpha*(pj - (n - 2*k + 3)*(n - 2*k + 3)) - (2*n - 4*k + 7)*s->k2) * coefs[p][k-1] + beta*(n - 2*k + 5)*(n - 2*k + 4)*coefs[p][k-2])/(2*(k - 1)*(2*n - 2*k + 3)); } } } void getCoefsM(EllipsoidalSystem *s, int n, double **coefs) { int wow = 1; wow = wow/2; } void getCoefsN(EllipsoidalSystem *s, int n, double **coefs) { int wow = 1; wow = wow/2; } #undef __FUNCT__ #define __FUNCT__ "calcLame2" PetscErrorCode calcLame2(EllipsoidalSystem *s, int n, int p, double l, double *sol) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; char t = getLameTypeT(n, p); *sol = 0; if (t == 'K') { int r = n/2; for(int k=0; k <= r; ++k) { *sol += s->Dconsts[n][p][k] * pow(l,n - 2*k); flopCount += 2; } } if (t == 'L') { int r = (n+1)/2; for(int k=0; k <= r-1; ++k) { *sol += s->Dconsts[n][p][k] * pow(l, n - 1 - 2*k); flopCount += 2; } *sol *= sqrt(fabs(l*l - s->h2)); flopCount += 3; } ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "ellipsoidToCartesian" PetscErrorCode ellipsoidToCartesian(EllipsoidalSystem *s, Point *p) { PetscErrorCode ierr; PetscFunctionBegin; if(p->type != 'c') { double h2 = s->h2; double k2 = s->k2; double l = p->x1; double m = p->x2; double n = p->x3; //Romain (7) p->x1 = sqrt((l * l * m * m * n * n)/(h2 * k2)); p->x2 = sqrt(((l * l - h2) * (m * m - h2) * (h2-n * n)) / (h2 * (k2 - h2))); p->x3 = sqrt(((l * l - k2) * (k2 - m * m) * (k2 - n * n)) / (k2 * (k2 - h2))); if(l * m * n < 0) p->x1 = -p->x1; if(l * n < 0) p->x2 = -p->x2; if(l * m < 0) p->x3 = -p->x3; p->type = 'c'; } ierr = PetscLogFlops(36); PetscFunctionReturn(0); } void cartesianToEllipsoidal2(struct EllipsoidalSystem *e, struct Point *p) { if(p->type != 'e') { double h2 = e->h2; double k2 = e->k2; double x = p->x1; double y = p->x2; double z = p->x3; double a = -1.0*(x*x + y*y + z*z + h2 + k2); double b = (h2 + k2)*x*x + k2*y*y + h2*z*z + h2*k2; double c = -h2*k2*x*x; double Areal = -(c/2.0) + (a*b/6.0) - (a*a*a/27.0); double Aimag = sqrt(-1.0*((a*a*a*c + b*b*b - a*a*b*b)/27.0 + (9.0*c*c - 6.0*a*b*c + a*a*b*b)/36.0)); double r = sqrt(Areal*Areal + Aimag*Aimag); double Atheta = atan2(Aimag, Areal); //Not sure what I was doing with Broot1, Broot2. Commented out double Aroot1, Aroot2;//, Broot1, Broot2; double ArootReal, ArootImag; //, BrootReal, BrootImag; int Ayes = 0; for(int k=0; k<3; ++k) { Aroot1 = cbrt(r)*cos((Atheta + 2.0*k*PETSC_PI)/3.0); Aroot2 = cbrt(r)*sin((Atheta + 2.0*k*PETSC_PI)/3.0); //what is this jibber jabber //Broot1 = cbrt(r)*cos((Btheta + 2.0*k*PETSC_PI)/3.0); //Broot2 = cbrt(r)*sin((Btheta + 2.0*k*PETSC_PI)/3.0); if(Aroot1 >= 0 && Aroot2 >= 0) { ArootReal = Aroot1; ArootImag = Aroot2; Ayes = 1; } //Not sure what this is for // //if(Broot1 >= 0 && Broot2 >= 0) { //BrootReal = Broot1; //BrootImag = Broot2; //} //printf("A,Ai,B,Bi: %15.15f, %15.15f, %15.15f, %15.15f\n", Aroot1, Aroot2, Broot1, Broot2); } if(Ayes == 0) printf("\n\n\n\n COULD NOT FIND PROPER ROOT FOR A"); double kap1 = -a/3.0 + 2.0*ArootReal; double kap2 = -a/3.0 - ArootReal - sqrt(3.0)*ArootImag; double kap3 = -a/3.0 - ArootReal + sqrt(3.0)*ArootImag; double newX1 = sqrt(kap1); double newX2 = sqrt(kap2); double newX3 = sqrt(kap3); //p->x1 = sqrt(kap1); //p->x2 = sqrt(kap3); //p->x3 = sqrt(kap2); if(x*y*z < 0) newX1 = - newX1; if(x*y < 0) newX2 = -newX2; if(x*z < 0) newX3 = -newX3; p->x1 = newX1; p->x2 = newX2; p->x3 = newX3; } p->type = 'e'; } void cartesianToEllipsoidal(struct EllipsoidalSystem *s, struct Point *p) { if(p->type != 'e') { double h2 = s->h2; double k2 = s->k2; double x = p->x1; double y = p->x2; double z = p->x3; //Use Romain (6) for approximate values double a1 = -(x*x + y*y + z*z + h2 + k2); double a2 = x*x*(h2 + k2) + y*y*k2 + z*z*h2 + h2*k2; double a3 = -x*x*h2*k2; double Q = (a1*a1 - 3.*a2)/9.; double R = (9.*a1*a2 - 27.*a3 - 2.*a1*a1*a1)/54.; double cth = R/sqrt(Q*Q*Q); double th = acos(cth); /* # Wikipedia http://en.wikipedia.org/wiki/List_of_trigonometric_identities # cos x = 4 cos^3 x/3 - 3 cos x/3 # 4 x^3 - 3x - v = 0 ==> {a = 4, b = 0, c = -3, d = -v} # Discriminant = 18abcd - 4b^3d + b^2c^2 - 4ac^3 - 27a^2d^2 # = 0 - 0 + 0 + 432 - 432*v^2 = 432*(1 - v^2) > 0 so 3 real roots # r1 = -1/3a (cbrt((27a^2d + sqrt(729a^4d^2 + 108a^3c^3))/2) + cbrt((27a^2d - sqrt(729a^4d^2 + 108a^3c^3))/2)) # = -1/12 (cbrt((432d + 432 sqrt(d^2 - 1))/2) + cbrt((432d - 432 sqrt(d^2 - 1))/2)) # = -cbrt(216)/12 (cbrt((d + sqrt(v^2 - 1))) + cbrt((d - sqrt(v^2 - 1)))) # = cbrt(216)/(12) (cbrt(cth - i sth) + cbrt(cth + i sth)) */ double lambda[3] = { cos(th/3.0), cos((th+4.0*PETSC_PI)/3.0), cos((th+2.0*PETSC_PI)/3.0) }; double val3 = 2*sqrt(Q)*lambda[2] - a1/3.0; if(val3 < 0 && fabs(val3) < 1e-10) val3 = 0; else if(val3 < 0) { printf("\n\nTHERE WAS AN ISSUE WITH THE TRANSFORM and we got %8.8e\n\n", 2*sqrt(Q)*lambda[2] -a1/3.0); val3 = 0; } //for(int i=0; i<3; ++i) printf("lambda[%d] = %15.15f\n", i, lambda[i]); p->x1 = sqrt(2*sqrt(Q)*lambda[0] - a1/3); p->x2 = sqrt(2*sqrt(Q)*lambda[1] - a1/3); p->x3 = sqrt(val3); //printf("p->x1: %15.15f\n", p->x1); //printf("p->x2: %15.15f\n", p->x2); //printf("p->x3: %15.15f\n", p->x3); /* # Improve the estimate # Get $\min(\lambda^2_i, |\lambda^2 - h^2|, |\lambda^2_i - k^2|)$ # Rewrite ellipsoid cubic so that smallest value is root # Solve the equation using Newton # Transform back */ if(x*y*z < 0) p->x1 = -p->x1; if(x*y < 0) p->x2 = -p->x2; if(x*z < 0) p->x3 = -p->x3; p->type = 'e'; } } #undef __FUNCT__ #define __FUNCT__ "CartesianToEllipsoidalVec" PetscErrorCode CartesianToEllipsoidalVec(EllipsoidalSystem *e, Vec xyzP, Vec ellP) { PetscErrorCode ierr; PetscInt nPts; PetscReal h2, k2; PetscReal x, y, z; PetscReal a1, a2, a3; PetscReal Q, R, cth, th; PetscReal val3; PetscReal lambda, mu, nu; const PetscScalar *xyzPArray; PetscScalar *ellPArray; PetscFunctionBegin; h2 = e->h2; k2 = e->k2; ierr = VecGetSize(xyzP, &nPts);CHKERRQ(ierr); nPts = nPts/3; ierr = VecGetArray (ellP, &ellPArray);CHKERRQ(ierr); ierr = VecGetArrayRead(xyzP, &xyzPArray);CHKERRQ(ierr); for(PetscInt i=0; i < nPts; ++i) { x = xyzPArray[3*i+0]; y = xyzPArray[3*i+1]; z = xyzPArray[3*i+2]; //Use Romain (6) for approximate values a1 = -(x*x + y*y + z*z + h2 + k2); a2 = x*x*(h2 + k2) + y*y*k2 + z*z*h2 + h2*k2; a3 = -x*x*h2*k2; Q = (a1*a1 - 3.*a2)/9.; R = (9.*a1*a2 - 27.*a3 - 2.*a1*a1*a1)/54.; cth = R/sqrt(Q*Q*Q); th = acos(cth); PetscReal lam[3] = { cos(th/3.0), cos((th+4.0*PETSC_PI)/3.0), cos((th+2.0*PETSC_PI)/3.0) }; val3 = 2*sqrt(Q)*lam[2] - a1/3.0; if(val3 < 0 && fabs(val3) < 1e-10) { printf("WOOOOW\n\n"); val3 = 0; } else if(val3 < 0) { printf("\n\nTHERE WAS AN ISSUE WITH THE TRANSFORM and we got %8.8e\n\n", 2*sqrt(Q)*lam[2] -a1/3.0); val3 = 0; } lambda = sqrt(2*sqrt(Q)*lam[0] - a1/3); mu = sqrt(2*sqrt(Q)*lam[1] - a1/3); nu = sqrt(val3); if(x*y*z < 0) lambda = -lambda; if(x*y < 0) mu = -mu; if(x*z < 0) nu = -nu; ellPArray[3*i+0] = lambda; ellPArray[3*i+1] = mu; ellPArray[3*i+2] = nu; } ierr = VecRestoreArrayRead(xyzP, &xyzPArray);CHKERRQ(ierr); ierr = VecRestoreArray (ellP, &ellPArray);CHKERRQ(ierr); PetscFunctionReturn(0); } char getLameTypeT(int n, int p) { int r = n/2; if(p < r+1) return 'K'; else if(p < (n-r) + (r+1)) return 'L'; else if(p < (n-r) + (n-r) + (r+1)) return 'M'; else if(p < 2*n+1) return 'N'; else printf("getLameType passed invalid n,p = (%d,%d)\n", n, p); return 'E'; } int getLameTypeTp(int n, int p) { int r = n/2; if(p < r+1) return p; else if(p < (n-r) + (r+1)) return p - (r+1); else if(p < (n-r) + (n-r) + (r+1)) return p - (n-r) - (r+1); else if(p < 2*n+1) return p - (n-r) - (n-r) - (r+1); else printf("getLameTypeTP passed invalid n,p = (%d,%d)\n", n, p); return 0; } void getLameCoefficientMatrix2(struct EllipsoidalSystem *s, char t, int n, int *mat_size, double *out) { //For a given Lame type and ordr n, return the tridiagonal matrix //the size of the generated coefficient matrix is stored to mat_size //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition //The expressions come from Romain Annex 3 //OPT: We could memorize this double alpha = s->h2; double beta = s->k2 - s->h2; double gamma = alpha - beta; int r = n/2; int size_d; double *d, *g, *f; if(t == 'K') { size_d = r+1; } else if(t == 'L' || t == 'M') { size_d = n-r; } else if(t == 'N') { size_d = r; } d = (double*) malloc(sizeof(double)*size_d); g = (double*) malloc(sizeof(double)*(size_d-1)); f = (double*) malloc(sizeof(double)*(size_d-1)); if (t == 'K') { //g missing last item for(int k = 0; k < r; ++k) g[k] = -(2*k + 2)*(2*k + 1)*beta; if(n%2) { //n is odd for(int k=0; k < r+1; ++k) d[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; for(int k=1; k < r+1; ++k) f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); } else { //n is even for(int k=0; k < r+1; ++k) d[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; for(int k=1; k < r+1; ++k) f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); } } else if (t == 'L') { //g missing last item for(int k = 0; k < n-r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 3)*beta; //printf("g[%d] = %15.15f\n", k, g[k]); //printf("n, r, %d, %d\n", n, r); //printf("beta: %15.15f\n", beta); } if(n%2) { //n is odd for(int k=0; k < n-r; ++k) d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; for(int k=1; k < n-r; ++k) f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); } else { //n is even for(int k=0; k < n-r; ++k) d[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; for(int k=1; k < n-r; ++k) f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); } } else if (t == 'M') { //g missing last item for(int k = 0; k < n-r-1; ++k) g[k] = -(2*k + 2)*(2*k + 1)*beta; if(n%2) { //n is odd for(int k=0; k < n-r; ++k) d[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; for(int k=1; k < n-r; ++k) f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); } else { //n is even for(int k=0; k < n-r; ++k) d[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; for(int k=1; k < n-r; ++k) f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); } } else if (t == 'N') { //g missing last item for(int k = 0; k < r-1; ++k) g[k] = -(2*k + 2)*(2*k + 3)*beta; if(n%2) { //n is odd for(int k=0; k < r; ++k) d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; for(int k=1; k < r; ++k) f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); } else { //n is even for(int k=0; k < r; ++k) d[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta; for(int k=1; k < r; ++k) f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); } } double *M = (double*) calloc(sizeof(double), size_d*size_d); //fill diagonal with d for(int k=0; k < size_d; ++k) M[k*size_d + k] = d[k]; //fill above diagonal with g for(int k=0; k < size_d-1; ++k) M[(k)*size_d + k+1] = g[k]; //fill below diagonal with f for(int k=0; k < size_d-1; ++k) M[(k+1)*size_d + k] = f[k]; //transpose M for lapack matTranspose(M, size_d); int lwork = 16*size_d; int info; double *vr, *work, *wr, *wi; vr = (double*) malloc(sizeof(double)*size_d*size_d); wr = (double*) malloc(sizeof(double)*size_d); wi = (double*) malloc(sizeof(double)*size_d); work = (double*) malloc(sizeof(double)*lwork); //compute eigenvalues with lapack char complefteig, comprighteig; complefteig = 'N'; //don't compute left eigenvectors comprighteig = 'V'; //compute right eigenvectors dgeev_( &complefteig, &comprighteig, &size_d, M, &size_d, wr, wi, NULL, &size_d, vr, &size_d, work, &lwork, &info ); //matTranspose(vr, size_d); //printf("hot\n"); //printf("size_d: %d\n", size_d); free(wr); free(wi); free(d); free(f); free(g); free(work); free(M); //printf("amazing\n"); //printf("diggity\n"); *mat_size = size_d; //return vr; } /* #undef __FUNCT__ #define __FUNCT__ "MatVecMult" PetscErrorCode MatVecMult(PetscInt m, PetscInt n, double **mat, double *vec) { PetscErrorCode ierr; PetscFunctionBegin; for(PetscInt i=0; i<m; ++i) { for(PetscInt j=0; j<n; ++j) { *mat[i*n+j] = } } PetscFunctionReturn(0); } */ #undef __FUNCT__ #define __FUNCT__ "getLameCoefficientMatrixSymmetricMPFR" PetscErrorCode getLameCoefficientMatrixSymmetricMPFR(struct EllipsoidalSystem *s, char t, PetscInt n, PetscInt* const mat_size, mpfr_t **mat) { PetscErrorCode ierr; mpfr_t alpha, beta, gamma; mpfr_t *d, *g, *f, *sigma; mpfr_t temp1, temp2; PetscInt size_d; PetscFunctionBegin; mpfr_inits(temp1, temp2, NULL); //set alpha, beta, gamma mpfr_inits(alpha, beta, gamma, NULL); mpfr_set(alpha, s->hp_h2, MPFR_RNDN); mpfr_sub(beta, s->hp_k2, s->hp_h2, MPFR_RNDN); mpfr_sub(gamma, alpha, beta, MPFR_RNDN); PetscInt r = n/2; if(t=='K') { size_d = r+1; } else if(t=='L' || t=='M') { size_d = n-r; } else if(t=='N') { size_d = r; } d = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d); g = (mpfr_t*) malloc(sizeof(mpfr_t)*(size_d-1)); f = (mpfr_t*) malloc(sizeof(mpfr_t)*(size_d-1)); sigma = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d); for(PetscInt k=0; k<size_d; ++k) { if(k<size_d-1) { mpfr_init(g[k]); mpfr_init(f[k]); } mpfr_init(d[k]); mpfr_init(sigma[k]); } if(t == 'K') { //g missing last item for(PetscInt k=0; k < r; ++k) { //g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount++; mpfr_set_d(temp1, 2*k+2, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul_d(temp1, temp1, -1.0, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_set(g[k], temp1, MPFR_RNDN); } if(n%2) { //n is odd for(PetscInt k=0; k < r+1; ++k) { //d[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 6; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_set_d(temp2, 2*r+2, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_set_d(temp2, 4*k*k, MPFR_RNDN); mpfr_sub(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(d[k], temp1, alpha, MPFR_RNDN); mpfr_set_d(temp1, 2*k+1, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_add(d[k], d[k], temp1, MPFR_RNDN); } for(PetscInt k=1; k < r+1; ++k) { //f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); flopCount += 2; mpfr_set_d(temp1, 2*(r-k) + 2, MPFR_RNDN); mpfr_set_d(temp2, 2*(r+k) + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(f[k-1], temp2, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], f[k-1], -1.0, MPFR_RNDN); } } else { //n is even for(PetscInt k=0; k < r+1; ++k) { //d[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; flopCount += 5; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r, MPFR_RNDN); mpfr_mul(d[k], temp1, alpha, MPFR_RNDN); mpfr_set_d(temp2, 4*k*k, MPFR_RNDN); mpfr_mul(temp2, temp2, gamma, MPFR_RNDN); mpfr_sub(d[k], d[k], temp2, MPFR_RNDN); } for(PetscInt k=1; k < r+1; ++k) { //f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); flopCount += 2; mpfr_set_d(temp1, 2*(r-k)+2, MPFR_RNDN); mpfr_set_d(temp2, 2*(r+k)+1, MPFR_RNDN); mpfr_mul(f[k-1], temp1, temp2, MPFR_RNDN); mpfr_mul(f[k-1], f[k-1], alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], f[k-1], -1.0, MPFR_RNDN); } } } else if (t == 'L') { //g missing last item for(PetscInt k=0; k < n-r-1; ++k) { //g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; mpfr_set_d(temp1, 2*k+2, MPFR_RNDN); mpfr_set_d(temp2, 2*k+3, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_mul_d(g[k], temp1, -1.0, MPFR_RNDN); } if(n%2) { //n is odd for(PetscInt k=0; k < n-r; ++k) { //d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_set_d(temp2, 2*r+2, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(d[k], temp1, alpha, MPFR_RNDN); mpfr_set_d(temp1, 2*k+1, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, gamma, MPFR_RNDN); mpfr_sub(d[k], d[k], temp1, MPFR_RNDN); } for(PetscInt k=1; k < n-r; ++k) { //f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 3; mpfr_set_d(temp1, 2*r - 2*k + 2, MPFR_RNDN); mpfr_set_d(temp2, 2*r + 2*k + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } else { //n is even for(PetscInt k=0; k < n-r; ++k) { //d[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; flopCount += 3; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp2, temp2, temp2, MPFR_RNDN); mpfr_sub(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(d[k], temp1, alpha, MPFR_RNDN); mpfr_set_d(temp1, 2*k+2, MPFR_RNDN); mpfr_mul(temp1, temp1, temp1, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_add(d[k], d[k], temp1, MPFR_RNDN); } for(PetscInt k=1; k < n-r; ++k) { //f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; mpfr_set_d(temp1, 2*r - 2*k, MPFR_RNDN); mpfr_set_d(temp2, 2*r + 2*k + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } } else if (t == 'M') { //g missing last item for(PetscInt k=0; k < n-r-1; ++k) { //g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount += 2; mpfr_set_d(temp1, 2*k+2, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_mul_d(g[k], temp1, -1.0, MPFR_RNDN); } if(n%2) { //n is odd for(PetscInt k=0; k < n-r; ++k) { //d[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; flopCount += 5; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r+2, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul_d(temp2, temp2, 2*k+1, MPFR_RNDN); mpfr_sub(temp1, temp1, temp2, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_set_d(temp2, 4*k*k, MPFR_RNDN); mpfr_mul(temp2, temp2, beta, MPFR_RNDN); mpfr_add(d[k], temp1, temp2, MPFR_RNDN); } for(PetscInt k=1; k < n-r; ++k) { //f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 2; mpfr_set_d(temp1, 2*r - 2*k + 2, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r + 2*k + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } else { //n is even for(PetscInt k=0; k < n-r; ++k) { //d[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp2, temp2, temp2, MPFR_RNDN); mpfr_mul(temp2, temp2, gamma, MPFR_RNDN); mpfr_sub(d[k], temp1, temp2, MPFR_RNDN); } for(PetscInt k=1; k < n-r; ++k) { //f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; mpfr_set_d(temp1, 2*r - 2*k, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r + 2*k + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } } else if (t == 'N') { //g missing last item for(PetscInt k=0; k < r-1; ++k) { //g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; mpfr_set_d(temp1, 2*k+2, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*k+3, MPFR_RNDN); mpfr_mul(temp1, temp1, beta, MPFR_RNDN); mpfr_mul_d(g[k], temp1, -1.0, MPFR_RNDN); } if(n%2) { //n is odd for(PetscInt k=0; k < r; ++k) { //d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; flopCount += 3; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r+2, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_set_d(temp2, 2*k+2, MPFR_RNDN); mpfr_mul(temp2, temp2, temp2, MPFR_RNDN); mpfr_mul(temp2, temp2, gamma, MPFR_RNDN); mpfr_sub(d[k], temp1, temp2, MPFR_RNDN); } for(PetscInt k=1; k < r; ++k) { //f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); flopCount += 2; mpfr_set_d(temp1, 2*r - 2*k, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r + 2*k + 3, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } else { //n is even for(PetscInt k=0; k < r; ++k) { //d[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta; mpfr_set_d(temp1, 2*r+1, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_set_d(temp2, 2*k+2, MPFR_RNDN); mpfr_mul(temp2, temp2, temp2, MPFR_RNDN); mpfr_mul(temp2, temp2, alpha, MPFR_RNDN); mpfr_sub(temp1, temp1, temp2, MPFR_RNDN); mpfr_set_d(temp2, 2*k+1, MPFR_RNDN); mpfr_mul(temp2, temp2, temp2, MPFR_RNDN); mpfr_mul(temp2, temp2, beta, MPFR_RNDN); mpfr_add(d[k], temp1, temp2, MPFR_RNDN); } for(PetscInt k=1; k < r; ++k) { //f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 3; mpfr_set_d(temp1, 2*r - 2*k, MPFR_RNDN); mpfr_mul_d(temp1, temp1, 2*r + 2*k + 1, MPFR_RNDN); mpfr_mul(temp1, temp1, alpha, MPFR_RNDN); mpfr_mul_d(f[k-1], temp1, -1.0, MPFR_RNDN); } } } mpfr_set_d(sigma[0], 1.0, MPFR_RNDN); for(PetscInt k=1; k<size_d; ++k) { mpfr_div(temp1, g[k-1], f[k-1], MPFR_RNDN); mpfr_sqrt(temp1, temp1, MPFR_RNDN); mpfr_mul(sigma[k], temp1, sigma[k-1], MPFR_RNDN); } mpfr_t *M = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d*size_d); //initialize entries and set to 0 for(PetscInt k=0; k < size_d*size_d; ++k) { mpfr_init(M[k]); mpfr_set_d(M[k], 0.0, MPFR_RNDN); } //fill diagonal with d for(PetscInt k=0; k < size_d; ++k) mpfr_set(M[k*size_d + k], d[k], MPFR_RNDN); //fill above diagonal with g for(PetscInt k=0; k < size_d-1; ++k) mpfr_set(M[k*size_d + k+1], g[k], MPFR_RNDN); for(PetscInt k=0; k < size_d-1; ++k) mpfr_set(M[(k+1)*size_d + k], f[k], MPFR_RNDN); //scale entries by values of sigma to get symmetric matrix for(PetscInt i=0; i < size_d; ++i) { for(PetscInt j=0; j < size_d; ++j) { mpfr_mul(M[i*size_d+j], M[i*size_d+j], sigma[i], MPFR_RNDN); mpfr_div(M[i*size_d+j], M[i*size_d+j], sigma[j], MPFR_RNDN); } } //INIT MAT, COMPUTE VALUES *mat = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d*size_d); for(PetscInt k=0; k < size_d*size_d; ++k) { mpfr_init((*mat)[k]); } //printf("Getting eigenvalues for n=%d and t=%c\n", n, t); //compute eigenvectors of symmetric matrix ierr = eigsMPFR(size_d, M, s->precision, *mat);CHKERRQ(ierr); //transform back to get eigenvectors of non-symmetric matrix for(PetscInt i=0; i < size_d; ++i) { for(PetscInt j=0; j < size_d; ++j) { //(*mat)[i*size_d+j] = (*mat)[i*size_d+j]*1./(sigma[j]); mpfr_div((*mat)[i*size_d+j], (*mat)[i*size_d+j], sigma[j], MPFR_RNDN); } } for(PetscInt i=0; i < size_d; ++i) { for(PetscInt j=0; j < size_d; ++j) { mpfr_neg(temp1, s->hp_h2, MPFR_RNDN); mpfr_set_d(temp2, size_d-1, MPFR_RNDN); mpfr_pow(temp1, temp1, temp2, MPFR_RNDN); mpfr_div(temp1, (*mat)[(i*size_d)+size_d-1], temp1, MPFR_RNDN); mpfr_div((*mat)[i*size_d+j], (*mat)[i*size_d+j], temp1, MPFR_RNDN); } } //hard fix for n=0 because i have no idea what goes wrong but i know the coef is 1.0 if(n == 0) mpfr_set_d((*mat)[0], 1.0, MPFR_RNDN); mpfr_clears(alpha, beta, gamma, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "getLameCoefficientMatrixSymmetric" PetscErrorCode getLameCoefficientMatrixSymmetric(struct EllipsoidalSystem *s, char t, int n, int* const mat_size, double **mat) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; //For a given Lame type and ordr n, return the tridiagonal matrix //the size of the generated coefficient matrix is stored to mat_size //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition //The expressions come from Romain Annex 3 //OPT: We could memorize this double alpha = s->h2; double beta = s->k2 - s->h2; double gamma = alpha - beta; flopCount += 2; int r = n/2; int size_d; double *d, *g, *f, *sigma; if(t == 'K') { size_d = r+1; } else if(t == 'L' || t == 'M') { size_d = n-r; } else if(t == 'N') { size_d = r; } d = (double*) malloc(sizeof(double)*size_d); g = (double*) malloc(sizeof(double)*(size_d-1)); f = (double*) malloc(sizeof(double)*(size_d-1)); sigma = (double*) malloc(sizeof(double)*size_d); if (t == 'K') { //g missing last item for(int k = 0; k < r; ++k) { g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount++; } if(n%2) { //n is odd for(int k=0; k < r+1; ++k) { d[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 6; } for(int k=1; k < r+1; ++k) { f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); flopCount += 2; } } else { //n is even for(int k=0; k < r+1; ++k) { d[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; flopCount += 5; } for(int k=1; k < r+1; ++k) { f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); flopCount += 2; } } } else if (t == 'L') { //g missing last item for(int k = 0; k < n-r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; //printf("g[%d] = %15.15f\n", k, g[k]); //printf("n, r, %d, %d\n", n, r); //printf("beta: %15.15f\n", beta); } if(n%2) { //n is odd for(int k=0; k < n-r; ++k) { d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 3; } } else { //n is even for(int k=0; k < n-r; ++k) { d[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; } } } else if (t == 'M') { //g missing last item for(int k = 0; k < n-r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount += 2; } if(n%2) { //n is odd for(int k=0; k < n-r; ++k) { d[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; flopCount += 5; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 2; } } else { //n is even for(int k=0; k < n-r; ++k) { d[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; } } } else if (t == 'N') { //g missing last item for(int k = 0; k < r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; } if(n%2) { //n is odd for(int k=0; k < r; ++k) { d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; flopCount += 3; } for(int k=1; k < r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); flopCount += 2; } } else { //n is even for(int k=0; k < r; ++k) { d[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 4; } for(int k=1; k < r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 3; } } } sigma[0] = 1; for(PetscInt k=1; k<size_d; ++k) { sigma[k] = sqrt(g[k-1]/f[k-1])*sigma[k-1]; } double *M = (double*) calloc(sizeof(double), size_d*size_d); //fill diagonal with d for(int k=0; k < size_d; ++k) M[k*size_d + k] = d[k]; //fill above diagonal with g for(int k=0; k < size_d-1; ++k) M[(k)*size_d + k+1] = g[k]; //fill below diagonal with f for(int k=0; k < size_d-1; ++k) M[(k+1)*size_d + k] = f[k]; //scale entries by values of sigma to get symmetric matrix for(PetscInt i=0; i<size_d; ++i) { for(PetscInt j=0; j<size_d; ++j) { M[i*size_d+j] = M[i*size_d+j]*sigma[i]*(1./sigma[j]); } } /* if(n==5) { printf("\nSYMETRIC MATRIX:\n"); for(PetscInt i=0; i<size_d; ++i) { for(PetscInt j=0; j<size_d; ++j) { printf("%4.4f ", M[i*size_d+j]); } printf("\n"); } } */ //transpose M for lapack matTranspose(M, size_d); int lwork = 16*size_d; int info; double *work, *wr, *wi; *mat = (double*) malloc(sizeof(double)*size_d*size_d); wr = (double*) malloc(sizeof(double)*size_d); wi = (double*) malloc(sizeof(double)*size_d); work = (double*) malloc(sizeof(double)*lwork); //compute eigenvalues with lapack char complefteig, comprighteig; complefteig = 'N'; //don't compute left eigenvectors comprighteig = 'V'; //compute right eigenvectors /* #################################################### */ /* ############## NEED TO ADD FLOP COUNT HERE ######### */ dgeev_( &complefteig, &comprighteig, &size_d, M, &size_d, wr, wi, NULL, &size_d, *mat, &size_d, work, &lwork, &info ); /* #################################################### */ /* #################################################### */ //matTranspose(vr, size_d); //printf("hot\n"); //printf("size_d: %d\n", size_d); free(wr); free(wi); free(d); free(f); free(g); free(work); free(M); //printf("amazing\n"); //printf("diggity\n"); if(mat_size != NULL) *mat_size = size_d; //for(int k=0; k<(m+1); ++k) //b[k] = b[k]/(b[(m+1)-1]/pow(-e->h2,(m+1)-1)); //transform back to get eigenvectors for(PetscInt i=0; i<size_d; ++i) { for(PetscInt j=0; j<size_d; ++j) { (*mat)[i*size_d+j] = (*mat)[i*size_d+j]*1./(sigma[j]); } } for(int i=0; i<size_d; ++i) { for(int k=0; k<size_d; ++k) { (*mat)[i*size_d+k] = (*mat)[i*size_d+k]/((*mat)[(i*size_d) + size_d-1]/pow(-s->h2,(size_d)-1)); flopCount += 3; } } ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); //return vr; PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "getLameCoefficientMatrix" PetscErrorCode getLameCoefficientMatrix(struct EllipsoidalSystem *s, char t, int n, int* const mat_size, double **mat) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; //For a given Lame type and ordr n, return the tridiagonal matrix //the size of the generated coefficient matrix is stored to mat_size //The eigenvectors of this matrix give the coefficients for the polynomaial P in the Lame function definition //The expressions come from Romain Annex 3 //OPT: We could memorize this double alpha = s->h2; double beta = s->k2 - s->h2; double gamma = alpha - beta; flopCount += 2; int r = n/2; int size_d; double *d, *g, *f; if(t == 'K') { size_d = r+1; } else if(t == 'L' || t == 'M') { size_d = n-r; } else if(t == 'N') { size_d = r; } d = (double*) malloc(sizeof(double)*size_d); g = (double*) malloc(sizeof(double)*(size_d-1)); f = (double*) malloc(sizeof(double)*(size_d-1)); if (t == 'K') { //g missing last item for(int k = 0; k < r; ++k) { g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount++; } if(n%2) { //n is odd for(int k=0; k < r+1; ++k) { d[k] = ((2*r + 1)*(2*r + 2) - 4*k*k)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 6; } for(int k=1; k < r+1; ++k) { f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) + 1); flopCount += 2; } } else { //n is even for(int k=0; k < r+1; ++k) { d[k] = 2*r*(2*r + 1)*alpha - 4*k*k*gamma; flopCount += 5; } for(int k=1; k < r+1; ++k) { f[k-1] = -alpha*(2*(r - k) + 2)*(2*(r + k) - 1); flopCount += 2; } } } else if (t == 'L') { //g missing last item for(int k = 0; k < n-r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; //printf("g[%d] = %15.15f\n", k, g[k]); //printf("n, r, %d, %d\n", n, r); //printf("beta: %15.15f\n", beta); } if(n%2) { //n is odd for(int k=0; k < n-r; ++k) { d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 3; } } else { //n is even for(int k=0; k < n-r; ++k) { d[k] = (2*r*(2*r + 1) - (2*k + 1)*(2*k + 1))*alpha + (2*k + 2)*(2*k + 2)*beta; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; } } } else if (t == 'M') { //g missing last item for(int k = 0; k < n-r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 1)*beta; flopCount += 2; } if(n%2) { //n is odd for(int k=0; k < n-r; ++k) { d[k] = ((2*r + 1)*(2*r + 2) - (2*k + 1)*(2*k + 1))*alpha + 4*k*k*beta; flopCount += 5; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k + 2)*(2*r + 2*k + 1); flopCount += 2; } } else { //n is even for(int k=0; k < n-r; ++k) { d[k] = 2*r*(2*r + 1)*alpha - (2*k + 1)*(2*k + 1)*gamma; flopCount += 3; } for(int k=1; k < n-r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 2; } } } else if (t == 'N') { //g missing last item for(int k = 0; k < r-1; ++k) { g[k] = -(2*k + 2)*(2*k + 3)*beta; flopCount += 2; } if(n%2) { //n is odd for(int k=0; k < r; ++k) { d[k] = (2*r + 1)*(2*r + 2)*alpha - (2*k + 2)*(2*k + 2)*gamma; flopCount += 3; } for(int k=1; k < r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k +3); flopCount += 2; } } else { //n is even for(int k=0; k < r; ++k) { d[k] = 2*r*(2*r + 1)*alpha - (2*k + 2)*(2*k + 2)*alpha + (2*k + 1)*(2*k + 1)*beta; flopCount += 4; } for(int k=1; k < r; ++k) { f[k-1] = -alpha*(2*r - 2*k)*(2*r + 2*k + 1); flopCount += 3; } } } double *M = (double*) calloc(sizeof(double), size_d*size_d); //fill diagonal with d for(int k=0; k < size_d; ++k) M[k*size_d + k] = d[k]; //fill above diagonal with g for(int k=0; k < size_d-1; ++k) M[(k)*size_d + k+1] = g[k]; //fill below diagonal with f for(int k=0; k < size_d-1; ++k) M[(k+1)*size_d + k] = f[k]; //transpose M for lapack matTranspose(M, size_d); int lwork = 16*size_d; int info; double *work, *wr, *wi; *mat = (double*) malloc(sizeof(double)*size_d*size_d); wr = (double*) malloc(sizeof(double)*size_d); wi = (double*) malloc(sizeof(double)*size_d); work = (double*) malloc(sizeof(double)*lwork); //compute eigenvalues with lapack char complefteig, comprighteig; complefteig = 'N'; //don't compute left eigenvectors comprighteig = 'V'; //compute right eigenvectors /* #################################################### */ /* ############## NEED TO ADD FLOP COUNT HERE ######### */ dgeev_( &complefteig, &comprighteig, &size_d, M, &size_d, wr, wi, NULL, &size_d, *mat, &size_d, work, &lwork, &info ); /* #################################################### */ /* #################################################### */ //matTranspose(vr, size_d); //printf("hot\n"); //printf("size_d: %d\n", size_d); free(wr); free(wi); free(d); free(f); free(g); free(work); free(M); //printf("amazing\n"); //printf("diggity\n"); if(mat_size != NULL) *mat_size = size_d; //for(int k=0; k<(m+1); ++k) //b[k] = b[k]/(b[(m+1)-1]/pow(-e->h2,(m+1)-1)); for(int i=0; i<size_d; ++i) { for(int k=0; k<size_d; ++k) { (*mat)[i*size_d+k] = (*mat)[i*size_d+k]/((*mat)[(i*size_d) + size_d-1]/pow(-s->h2,(size_d)-1)); flopCount += 3; } } ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); //return vr; PetscFunctionReturn(0); } double *computeLameCoefficients(EllipsoidalSystem *e, int n, int p, int *vecsize) { char t = getLameTypeT(n, p); int tp = getLameTypeTp(n, p); int bsize; double *B; getLameCoefficientMatrix(e, t, n, &bsize, &B); //printf("B SIZE: %d\n", bsize); double *ret = (double*) malloc(sizeof(double)*bsize); memcpy(ret, B+tp*bsize, sizeof(double)*bsize); free(B); *vecsize = bsize; return ret; } #undef __FUNCT__ #define __FUNCT__ "initRomainConstsToOrderN" PetscErrorCode initRomainConstsToOrderN(EllipsoidalSystem *e, int N) { PetscErrorCode ierr; PetscFunctionBegin; if(e->Rconsts != NULL) free(e->Rconsts); //initialize vector of romain constant matrices e->Rconsts = (double***) malloc(sizeof(double**)*(N+1)); //initialize mpfr version e->RconstsMPFR = (mpfr_t***) malloc(sizeof(mpfr_t**)*(N+1)); //int* mat_size; *mat_size = 1; for(int n=0; n<=N; ++n) { printf("n=%d\n", n); e->Rconsts[n] = (double**) malloc(sizeof(double*)*4); e->RconstsMPFR[n] = (mpfr_t**) malloc(sizeof(mpfr_t*)*4); //e->Rconsts[n][0] = getLameCoefficientMatrix(e, 'K', n, NULL); ierr = getLameCoefficientMatrix(e, 'K', n, NULL, e->Rconsts[n]+0);CHKERRQ(ierr); ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'K', n, NULL, e->RconstsMPFR[n]+0);CHKERRQ(ierr); //PetscErrorCode getLameCoefficientMatrixSymmetricMPFR(struct EllipsoidalSystem *s, char t, PetscInt n, PetscInt* const mat_size, mpfr_t **mat) //printf("wowze\n"); if(n != 0) { //e->Rconsts[n][1] = getLameCoefficientMatrix(e, 'L', n, NULL); ierr = getLameCoefficientMatrix(e, 'L', n, NULL, e->Rconsts[n]+1);CHKERRQ(ierr); ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'L', n, NULL, e->RconstsMPFR[n]+1);CHKERRQ(ierr); //e->Rconsts[n][2] = getLameCoefficientMatrix(e, 'M', n, NULL); ierr = getLameCoefficientMatrix(e, 'M', n, NULL, e->Rconsts[n]+2);CHKERRQ(ierr); ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'M', n, NULL, e->RconstsMPFR[n]+2);CHKERRQ(ierr); if(n != 1) { //e->Rconsts[n][3] = getLameCoefficientMatrix(e, 'N', n, NULL); ierr = getLameCoefficientMatrix(e, 'N', n, NULL, e->Rconsts[n]+3);CHKERRQ(ierr); ierr = getLameCoefficientMatrixSymmetricMPFR(e, 'N', n, NULL, e->RconstsMPFR[n]+3);CHKERRQ(ierr); } } } ierr = PetscLogFlops(0); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "CalcLameMPFR" PetscErrorCode CalcLameMPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t l, PetscInt signm, PetscInt signn, mpfr_t *Enp) { PetscErrorCode ierr; mpfr_t l2, psi; mpfr_t temp1, temp2; mpfr_t signh, signk; mpfr_t Lambda_Romain; mpfr_t P; PetscFunctionBegin; mpfr_inits(temp1, temp2, signh, signk, l2, psi, Lambda_Romain, P, NULL); mpfr_mul_d(temp1, l, (double) signm, MPFR_RNDN); if(mpfr_get_d(temp1, MPFR_RNDN) >= 0) mpfr_set_d(signh, 1.0, MPFR_RNDN); else mpfr_set_d(signh, -1.0, MPFR_RNDN); mpfr_mul_d(temp1, l, (double) signn, MPFR_RNDN); if(mpfr_get_d(temp1, MPFR_RNDN) >= 0) mpfr_set_d(signk, 1.0, MPFR_RNDN); else mpfr_set_d(signk, -1.0, MPFR_RNDN); char t = getLameTypeT(n, p); PetscInt tp = getLameTypeTp(n, p); PetscInt r = n/2; PetscInt m, type; mpfr_mul(l2, l, l, MPFR_RNDN); if(t == 'K') { m = r; //psi = pow(l, n-2*r); countFlops++; mpfr_set_d(temp1, n-2*r, MPFR_RNDN); mpfr_pow(psi, l, temp1, MPFR_RNDN); type = 0; } else if(t == 'L') { m = n-r-1; //psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2-e->h2)); countFlops += 3; mpfr_set_d(temp1, 1-n+2*r, MPFR_RNDN); mpfr_pow(temp1, l, temp1, MPFR_RNDN); mpfr_sub(temp2, l2, e->hp_h2, MPFR_RNDN); mpfr_abs(temp2, temp2, MPFR_RNDN); mpfr_sqrt(temp2, temp2, MPFR_RNDN); mpfr_mul(psi, temp1, temp2, MPFR_RNDN); mpfr_mul(psi, psi, signh, MPFR_RNDN); type = 1; } else if(t == 'M') { //psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2-e->k2)); countFlops += 3; m = n-r-1; mpfr_set_d(temp1, 1-n+2*r, MPFR_RNDN); mpfr_pow(temp1, l, temp1, MPFR_RNDN); mpfr_sub(temp2, l2, e->hp_k2, MPFR_RNDN); mpfr_abs(temp2, temp2, MPFR_RNDN); mpfr_sqrt(temp2, temp2, MPFR_RNDN); mpfr_mul(psi, temp1, temp2, MPFR_RNDN); mpfr_mul(psi, psi, signk, MPFR_RNDN); type = 2; } else if(t == 'N') { //psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2-e->k2)*(l2-e->h2))); countFlops += 8; m = r-1; mpfr_sub(temp1, l2, e->hp_k2, MPFR_RNDN); mpfr_sub(temp2, l2, e->hp_h2, MPFR_RNDN); mpfr_mul(temp1, temp1, temp2, MPFR_RNDN); mpfr_sqrt(temp1, temp1, MPFR_RNDN); mpfr_set_d(temp2, n-2*r, MPFR_RNDN); mpfr_pow(temp2, l, temp2, MPFR_RNDN); mpfr_mul(psi, temp1, temp2, MPFR_RNDN); mpfr_mul(psi, psi, signh, MPFR_RNDN); mpfr_mul(psi, psi, signk, MPFR_RNDN); type = 3; } else printf("Invalid Lame Type\n"); mpfr_div(temp1, l2, e->hp_h2, MPFR_RNDN); mpfr_d_sub(Lambda_Romain, 1.0, temp1, MPFR_RNDN); mpfr_t *b = e->RconstsMPFR[n][type]+tp*(m+1); mpfr_set(P, b[m], MPFR_RNDN); for(PetscInt j=m-1; j > -1; --j) { // P = P*Lambda_Romain + b[j] mpfr_mul(P, P, Lambda_Romain, MPFR_RNDN); mpfr_add(P, P, b[j], MPFR_RNDN); } // Enp = psi*P mpfr_mul(*Enp, psi, P, MPFR_RNDN); mpfr_clears(temp1, temp2, signh, signk, l2, psi, Lambda_Romain, P, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "calcLame" PetscErrorCode calcLame(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *Enp) { PetscErrorCode ierr; PetscInt countFlops; PetscFunctionBegin; countFlops = 0; double signh, signk; if(signm*l >= 0) signh = 1; else signh = -1; if(signn*l >= 0) signk = 1; else signk = -1; char t = getLameTypeT(n, p); int tp = getLameTypeTp(n, p); //double *B = getLameCoefficientMatrix(e, t, n, &bsize); //printf("%c\n", t); int r = n/2; double l2 = l*l; double psi; int m; int type; //This comes from Romain Table II if(t == 'K') { m = r; psi = pow(l, n-2*r); countFlops++; type = 0; } else if(t == 'L') { m = n-r-1; psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2-e->h2)); countFlops += 3; type = 1; } else if(t == 'M') { m = n-r-1; psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2-e->k2)); countFlops += 3; type = 2; } else if(t == 'N') { m = r-1; psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2-e->k2)*(l2-e->h2))); countFlops += 8; type = 3; } else printf("Invalid Lame Type\n"); //if(isnan(psi)) //printf("psi is nan and s: %15.15f\n", l); //Romain (30) \sum^m_{j=0} b_j (1 - \frac{\lambda^2}{h^2}) = \sum^m_{j=0} b_j \Lambda^j double Lambda_Romain = (1.0 - (l2/e->h2)); //b = B[tp] //double *b = (double*) malloc(sizeof(double)*(m+1)); double *b = e->Rconsts[n][type]+tp*(m+1); countFlops += 4; //for(int i=0; i<=m; ++i) { //memcpy(b, e->Rconsts[n][type]+tp*(m+1), sizeof(double)*(m+1)); //} //memcpy(b, B+tp*(m+1), sizeof(double)*(m+1)); //Normalize b so that the highest power of lambda has coefficient unity //Romain p242 and Dassios (D9,D10 and their gamma in B16-B20) //for(int k=0; k<(m+1); ++k) //b[k] = b[k]/(b[(m+1)-1]/pow(-e->h2,(m+1)-1)); double P = b[m]; for(int j=m-1; j>-1; --j) { P = P*Lambda_Romain + b[j]; countFlops += 2; } //free(B); //free(b); //printf("psi: %15.15f\n", psi); //printf("p: %d\n", p); *Enp = psi*P; countFlops++; //printf("countFlops: %d\n", countFlops); ierr = PetscLogFlops(countFlops);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "calcLameDerivative" PetscErrorCode calcLameDerivative(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol) { PetscErrorCode ierr; PetscInt logFlops; PetscFunctionBegin; logFlops = 0; //Evaluate \frac{dE^p_n(l)}{dl} //The signs of \mu and \nu are necessary in order to determine the sign of \psi double signh, signk; if(signm*l >= 0) signh = 1; else signh = -1; if(signn*l >= 0) signk = 1; else signk = -1; char t = getLameTypeT(n, p); int tp = getLameTypeTp(n, p); int bsize; double *B; ierr = getLameCoefficientMatrix(e, t, n, &bsize, &B);CHKERRQ(ierr); int r = n/2; double l2 = l*l; logFlops ++; int m; double psi, psider; int type; //This comes from Romain Table II if(t == 'K') { m = r; psi = pow(l, n-2*r); psider = (n-2*r)*pow(l, n-2*r-1); type = 0; logFlops += 3; } else if(t == 'L') { m = n-r-1; psi = pow(l, 1-n+2*r)*signh*sqrt(fabs(l2 - e->h2)); logFlops += 4; psider = (1-n+2*r)*pow(l, -n+2*r)*signh*sqrt(fabs(l2 - e->h2)) + pow(l, 2-n+2*r)*signh/sqrt(fabs(l2 - e->h2)); logFlops += 12; type = 1; } else if(t == 'M') { m = n-r-1; psi = pow(l, 1-n+2*r)*signk*sqrt(fabs(l2 - e->k2)); logFlops += 4; psider = (1-n+2*r)*pow(l, -n+2*r)*signk*sqrt(fabs(l2 - e->k2)) + pow(l, 2-n+2*r)*signk/sqrt(fabs(l2 - e->k2)); logFlops += 12; type = 2; } else if(t == 'N') { m = r-1; psi = pow(l, n-2*r)*signh*signk*sqrt(fabs((l2 - e->k2)*(l2 - e->h2))); logFlops += 8; psider = ((n-2*r)*pow(l, n-2*r-1)*signh*signk*sqrt(fabs((l2 - e->k2)*(l2 - e->h2))) + pow(l, n-2*r+1)*signh*signk*sqrt(fabs((l2 - e->k2)/(l2 - e->h2))) + pow(l, n-2*r+1)*signh*signk*sqrt(fabs((l2 - e->h2)/(l2 - e->k2)))); logFlops += 24; type = 3; } else printf("Invalid Lame type\n"); //Romain (30) \sum^m_{j=0} b_j (1 - \frac{\lambda^2}{h^2}) = \sum^m_{j=0} b_j \Lambda^j double Lambda_Romain = (1.0 - (l2/e->h2)); logFlops += 2; //Romain bottom of p.252 //b = B[tp] double *b = (double*) malloc(sizeof(double)*(m+1)); memcpy(b, e->Rconsts[n][type]+tp*(m+1), sizeof(double)*(m+1)); double P = b[m]; for(int j=m-1; j>-1; --j) { P = P*Lambda_Romain + b[j]; logFlops += 2; } //P' = \sum^{m-1}_{k=0} c_k \Lambda^k where c_k = b_{k+1} (-2 (k+1) \frac{\lambda}{h^2}) double Pder = b[m]*(-2*m*l/e->h2); logFlops += 4; free(b); free(B); *sol = psider*P + psi*Pder; ierr = PetscLogFlops(logFlops);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "integrand" PetscErrorCode integrand(mpfr_t *x, mpfr_t *val, FuncInfo *ctx) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; mpfr_t *temp = &((*ctx).e->temp1); mpfr_d_div(*temp, 1.0, *x, MPFR_RNDN); flopCount ++; double s = mpfr_get_d(*temp, MPFR_RNDZ); double E; ierr = calcLame((*ctx).e, (*ctx).n, (*ctx).p, s, ctx->signm, ctx->signn, &E);CHKERRQ(ierr); mpfr_mul(*temp, *x, *x, MPFR_RNDN); mpfr_set(*val, *temp, MPFR_RNDN); mpfr_mul_d(*temp, *temp, (*ctx).e->k2, MPFR_RNDN); mpfr_mul_d(*val, *val, (*ctx).e->h2, MPFR_RNDN); mpfr_d_sub(*temp, 1.0, *temp, MPFR_RNDZ); mpfr_d_sub(*val, 1.0, *val, MPFR_RNDZ); mpfr_sqrt(*temp, *temp, MPFR_RNDN); mpfr_sqrt(*val, *val, MPFR_RNDN); mpfr_mul(*val, *temp, *val, MPFR_RNDN); mpfr_mul_d(*val, *val, E, MPFR_RNDN); mpfr_mul_d(*val, *val, E, MPFR_RNDN); flopCount += 10; mpfr_d_div(*val, 1.0, *val, MPFR_RNDN); flopCount++; //printf("\n\n\nVAL: %15.15f\n\n\n", mpfr_get_d(*val, MPFR_RNDN)); ierr = PetscLogFlops(flopCount); PetscFunctionReturn(0); } /* void integrand(mpfr_t *x , mpfr_t *val, FuncInfo *ctx) { double x2 = x*x; double s; int n = (*ctx).n; int p = (*ctx).p; if(x==0.0) s = 1e6; else s = 1.0/x; double E = calcLame((*ctx).e, n, p, s); return 1.0 / (E*E*sqrt(1.0 - (*ctx).e->k2*x2)*sqrt(1.0 - (*ctx).e->h2*x2)); } */ #undef __FUNCT__ #define __FUNCT__ "calcI" PetscErrorCode calcI(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol) { PetscErrorCode ierr; PetscInt logFlops; mpfr_t solution; PetscFunctionBegin; mpfr_init(solution); logFlops = 0; if(l < 0) { l *= -1.0; logFlops ++; } //int digits = 14; FuncInfo ctx = { e, n, p, signm, signn}; mpfr_t *a = &(e->tempa); mpfr_t *b = &(e->tempb); mpfr_set_d(*a, 0.0, MPFR_RNDN); mpfr_set_d(*b, 1.0, MPFR_RNDN); mpfr_div_d(*b, *b, l, MPFR_RNDN); logFlops++; //printf("a: %15.15f\nb: %15.15f\n", mpfr_get_d(*a, MPFR_RNDN), mpfr_get_d(*b, MPFR_RNDN)); int err = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*))integrand, e, *a, *b, 14, &solution, &ctx); *sol = mpfr_get_d(solution, MPFR_RNDN); if(err) printf("integral failed\n"); //printf("the integral is: %15.15f\n", *sol); mpfr_clear(solution); ierr = PetscLogFlops(logFlops);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "calcIDerivative" PetscErrorCode calcIDerivative(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *Ideriv) { PetscErrorCode ierr; PetscFunctionBegin; //Evaluate \frac{dI^p_n(l)}{dl} = \frac{-1}{(E^p_n(l))^2 \sqrt{l^2 - k^2}\sqrt{l^2 - h^2}} double l2 = l*l; double k2 = e->k2; double h2 = e->h2; double E; calcLame(e, n, p, l, signm, signn, &E); *Ideriv = -1.0 / (E*E*sqrt(l2 - k2)*sqrt(l2 - h2)); ierr = PetscLogFlops(9); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "normFunction1MPFR" PetscErrorCode normFunction1MPFR(mpfr_t *x, mpfr_t *val, FuncInfo2 *ctx) { PetscErrorCode ierr; PetscInt flopCount; mpfr_t top; PetscFunctionBegin; mpfr_init(top); flopCount = 0; int n = (*ctx).n; int p = (*ctx).p; int numeratorType = (*ctx).numeratorType; int denomSign = (*ctx).denomSign; //double h2 = (*ctx).e->h2; //double k2 = (*ctx).e->k2; EllipsoidalSystem *e = (*ctx).e; ierr = CalcLameMPFR((*ctx).e, n, p, *x, 1, 1, &top); mpfr_t *temp = &((*ctx).e->temp1); mpfr_mul(*temp, *x, *x, MPFR_RNDN); mpfr_sub(*val, e->hp_k2, *temp, MPFR_RNDN); mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN); mpfr_mul(*val, *temp, *val, MPFR_RNDN); mpfr_mul_d(*val, *val, (double) denomSign, MPFR_RNDN); flopCount += 5; if(mpfr_get_d(*val, MPFR_RNDN) < 0 && fabs(mpfr_get_d(*val, MPFR_RNDN)) < tol) { mpfr_mul_d(*val, *val, -1.0, MPFR_RNDN); flopCount++; } mpfr_sqrt(*temp, *val, MPFR_RNDN); mpfr_set(*val, top, MPFR_RNDN); mpfr_mul(*val, *val, top, MPFR_RNDN); flopCount += 2; flopCount += 3; if(numeratorType == 1) { mpfr_mul(*val, *val, *x, MPFR_RNDN); mpfr_mul(*val, *val, *x, MPFR_RNDN); flopCount += 2; } //printf("val before is %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); //printf("denom before is %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); mpfr_div(*val, *val, *temp, MPFR_RNDN); flopCount++; //printf("val is %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); mpfr_clear(top); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "normFunction1" PetscErrorCode normFunction1(mpfr_t *x, mpfr_t *val, FuncInfo2 *ctx) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; int n = (*ctx).n; int p = (*ctx).p; int numeratorType = (*ctx).numeratorType; int denomSign = (*ctx).denomSign; //double h2 = (*ctx).e->h2; //double k2 = (*ctx).e->k2; EllipsoidalSystem *e = (*ctx).e; double top; calcLame((*ctx).e, n, p, mpfr_get_d(*x, MPFR_RNDN), 1, 1, &top); mpfr_t *temp = &((*ctx).e->temp1); mpfr_mul(*temp, *x, *x, MPFR_RNDN); mpfr_sub(*val, e->hp_k2, *temp, MPFR_RNDN); mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN); mpfr_mul(*val, *temp, *val, MPFR_RNDN); mpfr_mul_d(*val, *val, (double) denomSign, MPFR_RNDN); flopCount += 5; if(mpfr_get_d(*val, MPFR_RNDN) < 0 && fabs(mpfr_get_d(*val, MPFR_RNDN)) < tol) { mpfr_mul_d(*val, *val, -1.0, MPFR_RNDN); flopCount++; } mpfr_sqrt(*temp, *val, MPFR_RNDN); mpfr_set_d(*val, top, MPFR_RNDN); mpfr_mul_d(*val, *val, top, MPFR_RNDN); flopCount += 2; flopCount += 3; if(numeratorType == 1) { mpfr_mul(*val, *val, *x, MPFR_RNDN); mpfr_mul(*val, *val, *x, MPFR_RNDN); flopCount += 2; } //printf("val before is %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); //printf("denom before is %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); mpfr_div(*val, *val, *temp, MPFR_RNDN); flopCount++; //printf("val is %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } void normFunction2(mpfr_t *x, mpfr_t *val, FuncInfo3 *ctx) { //printf("x: %8.8e\n", mpfr_get_d(*x, MPFR_RNDN)); //double h2 = (*ctx).e->h2; //double k2 = (*ctx).e->k2; mpfr_t *temp = &((*ctx).e->temp1); EllipsoidalSystem *e = ctx->e; mpfr_set(*temp, e->hp_k2, MPFR_RNDN); mpfr_sub(*temp, *temp, e->hp_h2, MPFR_RNDN); mpfr_mul(*val, *x, e->hp_h2, MPFR_RNDN); mpfr_add(*val, *val, *temp, MPFR_RNDN); mpfr_sqrt(*val, *val, MPFR_RNDN); //printf("val 1: %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); mpfr_abs(*temp, *x, MPFR_RNDN); //printf("absx(actual): %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); mpfr_sqrt(*temp, *temp, MPFR_RNDN); //printf("before multiply val 2: %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); //printf("absx: %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); mpfr_mul(*val, *val, *temp, MPFR_RNDN); //printf("val 2: %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); mpfr_set_d(*temp, 1.0, MPFR_RNDN); mpfr_sub(*temp, *temp, *x, MPFR_RNDN); mpfr_sqrt(*temp, *temp, MPFR_RNDN); //printf("before multiply val 3: %8.8e\n", mpfr_get_d(*temp, MPFR_RNDN)); mpfr_mul(*val, *val, *temp, MPFR_RNDN); //printf("val 3(denom): %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); if((*ctx).numeratorType == 0) { //printf("numerator is 1.0\n"); mpfr_d_div(*val, 1.0, *val, MPFR_RNDN); } else { mpfr_div(*val, *x, *val, MPFR_RNDN); //printf("numerator is x\n"); } //printf("val: %8.8e\n", mpfr_get_d(*val, MPFR_RNDN)); } #undef __FUNCT__ #define __FUNCT__ "calcNormalizationMPFR" PetscErrorCode calcNormalizationMPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t *normConst) { PetscErrorCode ierr; int err[4]; mpfr_t integrals[4]; mpfr_t temp; PetscFunctionBegin; mpfr_inits(integrals[0], integrals[1], integrals[2], integrals[3], temp, NULL); FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 }; FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 }; FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 }; FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 }; mpfr_t *mpfrzero = &(e->mpfrzero); mpfr_t *mpfrone = &(e->mpfrone); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, integrals, &ctx1); err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, integrals+1, &ctx2); err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, integrals+2, &ctx3); err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, integrals+3, &ctx4); //*normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]); mpfr_mul(*normConst, integrals[2], integrals[1], MPFR_RNDN); mpfr_mul(temp, integrals[0], integrals[3], MPFR_RNDN); mpfr_sub(*normConst, *normConst, temp, MPFR_RNDN); mpfr_mul_d(*normConst, *normConst, 8.0, MPFR_RNDN); mpfr_clears(integrals[0], integrals[1], integrals[2], integrals[3], temp, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "calcNormalization2MPFR" PetscErrorCode calcNormalization2MPFR(EllipsoidalSystem *e, PetscInt n, PetscInt p, mpfr_t *intVals, mpfr_t *normConst) { PetscErrorCode ierr; int err[4]; mpfr_t integrals[4]; mpfr_t temp; PetscFunctionBegin; mpfr_init(temp); FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 }; FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 }; FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 }; FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 }; mpfr_t *mpfrzero = &(e->mpfrzero); mpfr_t *mpfrone = &(e->mpfrone); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, intVals, &ctx1); err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, e->hp_h, e->hp_k, e->precision, intVals+1, &ctx2); err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, intVals+2, &ctx3); err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1MPFR, e, *mpfrzero, e->hp_h, e->precision, intVals+3, &ctx4); //*normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]); mpfr_mul(*normConst, intVals[2], intVals[1], MPFR_RNDN); mpfr_mul(temp, intVals[0], intVals[3], MPFR_RNDN); mpfr_sub(*normConst, *normConst, temp, MPFR_RNDN); mpfr_mul_d(*normConst, *normConst, 8.0, MPFR_RNDN); mpfr_clear(temp); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "calcNormalization" PetscErrorCode calcNormalization(EllipsoidalSystem *e, int n, int p, double *normConst) { PetscErrorCode ierr; PetscFunctionBegin; //double h = e->h; //double h2 = e->h2; //double k = e->k; //double k2 = e->k2; //The four integrals making up Romain (51) //structs containing f unction info FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 }; FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 }; FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 }; FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 }; int err[4]; mpfr_t integrals[4]; mpfr_inits(integrals[0], integrals[1], integrals[2], integrals[3], NULL); mpfr_t *mpfrzero = &(e->mpfrzero); mpfr_t *mpfrone = &(e->mpfrone); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integrals, &ctx1); err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integrals+1, &ctx2); err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integrals+2, &ctx3); err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integrals+3, &ctx4); double ints[4]; ints[0] = mpfr_get_d(integrals[0], MPFR_RNDN); ints[1] = mpfr_get_d(integrals[1], MPFR_RNDN); ints[2] = mpfr_get_d(integrals[2], MPFR_RNDN); ints[3] = mpfr_get_d(integrals[3], MPFR_RNDN); *normConst = 8.0*(ints[2]*ints[1] - ints[0]*ints[3]); mpfr_clears(integrals[0], integrals[1], integrals[2], integrals[3], NULL); ierr = PetscLogFlops(4);CHKERRQ(ierr); PetscFunctionReturn(0); /* for(int i=0; i<4; ++i) { //printf("integrals[i] = %8.8e\n", i, integrals[i]); if(err[i]) printf("Integral %d failed in calcNormalization\n", i); } //The basic elliptic integrals Romain (53) //He has an error in the equation, the prefactor should be h/2 //structs containing function info FuncInfo3 ctx20 = { .e = e, .numeratorType = 0, .denomSign = -1 }; FuncInfo3 ctx21 = { .e = e, .numeratorType = 1, .denomSign = -1 }; FuncInfo3 ctx30 = { .e = e, .numeratorType = 0, .denomSign = 1 }; FuncInfo3 ctx31 = { .e = e, .numeratorType = 1, .denomSign = 1 }; double integrals2[4]; mpfr_t *endpt = &(e->endpt); mpfr_set(*endpt, e->hp_k2, MPFR_RNDN); mpfr_div(*endpt, *endpt, e->hp_h2, MPFR_RNDN); mpfr_d_sub(*endpt, 1.0, *endpt, MPFR_RNDN); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2, &ctx20); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2+1, &ctx21); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+2, &ctx30); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+3, &ctx31); //Multiply by prefactor h/2 for(int i=0; i<4; ++i) { //integrals2[i] = .5*h*integrals2[i]; } for(int i=0; i<4; ++i) { if(err[i]) printf("Integral2 %d failed in calcNormalization\n", i); } //Solve system for coefficients double *M = (double*) malloc(sizeof(double)*4); M[0] = integrals2[0]; //integrals2[0]; //transposed for lapack M[1] = integrals2[2]; // M[2] = integrals2[1]; // M[3] = integrals2[3]; // double *sol = (double*) malloc(sizeof(double)*2); sol[0] = integrals[0]; sol[1] = integrals[2]; //variables to store solutions double alpha, beta, A, B; char tchar = 'N'; int two = 2; int one = 1; //ipiv pivot (output for dgetrf, input for dgetrs) int *ipiv = (int*) malloc(sizeof(int)*2); int info; //first solve dgetrf_(&two, &two, M, &two, ipiv, &info); dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info); alpha = sol[0]; beta = sol[1]; sol[0] = integrals[1]; sol[1] = integrals[3]; //second solve dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info); A = sol[0]; B = sol[1]; free(sol); free(M); free(ipiv); //Romain (54) //The factor 8 is from Dassios (see discussion in Deng), since we integrate over the whole ellipsoid rather than just one octant if(fabs(alpha*B - beta*A) == 0) { printf("\n\nbad\n\n\n\n"); printf("alpha*B: %16.16e\n", alpha*B); printf("beta*A: %16.16e\n", beta*A); return 8 * (PETSC_PI/2.0)*1e-14; } return 8 * (PETSC_PI/2.0)*(alpha*B - beta*A); */ } #undef __FUNCT__ #define __FUNCT__ "calcNormalization2" PetscErrorCode calcNormalization2(EllipsoidalSystem *e, PetscInt n, PetscInt p, double *intVals, double *normConst) { PetscErrorCode ierr; PetscFunctionBegin; //double h = e->h; //double h2 = e->h2; //double k = e->k; //double k2 = e->k2; //The four integrals making up Romain (51) //structs containing f unction info FuncInfo2 ctx1 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 }; FuncInfo2 ctx2 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = 1 }; FuncInfo2 ctx3 = { .e = e, .n = n, .p = p, .numeratorType = 0, .denomSign = -1 }; FuncInfo2 ctx4 = { .e = e, .n = n, .p = p, .numeratorType = 1, .denomSign = -1 }; int err[4]; double integrals[4]; mpfr_t integ[4]; mpfr_inits(integ[0], integ[1], integ[2], integ[3], NULL); mpfr_t *mpfrzero = &(e->mpfrzero); mpfr_t *mpfrone = &(e->mpfrone); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integ, &ctx1); integrals[0] = mpfr_get_d(integ[0], MPFR_RNDN); intVals[0] = integrals[0]; err[1] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, e->hp_h, e->hp_k, 16, integ+1, &ctx2); integrals[1] = mpfr_get_d(integ[1], MPFR_RNDN); intVals[1] = integrals[1]; err[2] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integ+2, &ctx3); integrals[2] = mpfr_get_d(integ[2], MPFR_RNDN); intVals[2] = integrals[2]; err[3] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e, *mpfrzero, e->hp_h, 16, integ+3, &ctx4); integrals[3] = mpfr_get_d(integ[3], MPFR_RNDN); intVals[3] = integrals[3]; *normConst = 8.0*(integrals[2]*integrals[1] - integrals[0]*integrals[3]); mpfr_clears(integ[0], integ[1], integ[2], integ[3], NULL); ierr = PetscLogFlops(4);CHKERRQ(ierr); PetscFunctionReturn(0); /* for(int i=0; i<4; ++i) { //printf("integrals[i] = %8.8e\n", i, integrals[i]); if(err[i]) printf("Integral %d failed in calcNormalization\n", i); } //The basic elliptic integrals Romain (53) //He has an error in the equation, the prefactor should be h/2 //structs containing function info FuncInfo3 ctx20 = { .e = e, .numeratorType = 0, .denomSign = -1 }; FuncInfo3 ctx21 = { .e = e, .numeratorType = 1, .denomSign = -1 }; FuncInfo3 ctx30 = { .e = e, .numeratorType = 0, .denomSign = 1 }; FuncInfo3 ctx31 = { .e = e, .numeratorType = 1, .denomSign = 1 }; double integrals2[4]; mpfr_t *endpt = &(e->endpt); mpfr_set(*endpt, e->hp_k2, MPFR_RNDN); mpfr_div(*endpt, *endpt, e->hp_h2, MPFR_RNDN); mpfr_d_sub(*endpt, 1.0, *endpt, MPFR_RNDN); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2, &ctx20); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *endpt, 14, integrals2+1, &ctx21); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+2, &ctx30); err[0] = integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction2, e, *mpfrzero, *mpfrone, 14, integrals2+3, &ctx31); //Multiply by prefactor h/2 for(int i=0; i<4; ++i) { //integrals2[i] = .5*h*integrals2[i]; } for(int i=0; i<4; ++i) { if(err[i]) printf("Integral2 %d failed in calcNormalization\n", i); } //Solve system for coefficients double *M = (double*) malloc(sizeof(double)*4); M[0] = integrals2[0]; //integrals2[0]; //transposed for lapack M[1] = integrals2[2]; // M[2] = integrals2[1]; // M[3] = integrals2[3]; // double *sol = (double*) malloc(sizeof(double)*2); sol[0] = integrals[0]; sol[1] = integrals[2]; //variables to store solutions double alpha, beta, A, B; char tchar = 'N'; int two = 2; int one = 1; //ipiv pivot (output for dgetrf, input for dgetrs) int *ipiv = (int*) malloc(sizeof(int)*2); int info; //first solve dgetrf_(&two, &two, M, &two, ipiv, &info); dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info); alpha = sol[0]; beta = sol[1]; sol[0] = integrals[1]; sol[1] = integrals[3]; //second solve dgetrs_(&tchar, &two, &one, M, &two, ipiv, sol, &two, &info); A = sol[0]; B = sol[1]; free(sol); free(M); free(ipiv); //Romain (54) //The factor 8 is from Dassios (see discussion in Deng), since we integrate over the whole ellipsoid rather than just one octant if(fabs(alpha*B - beta*A) == 0) { printf("\n\nbad\n\n\n\n"); printf("alpha*B: %16.16e\n", alpha*B); printf("beta*A: %16.16e\n", beta*A); return 8 * (PETSC_PI/2.0)*1e-14; } return 8 * (PETSC_PI/2.0)*(alpha*B - beta*A); */ } //calculate the eigenvalues of the surface operator #undef __FUNCT__ #define __FUNCT__ "calcSurfaceOperatorEigenvalues" PetscErrorCode calcSurfaceOperatorEigenvalues(EllipsoidalSystem *e, int n, int p, double l, int signm, int signn, double *sol) { PetscErrorCode ierr; PetscFunctionBegin; double a = e->a; double b = e->b; double c = e->c; double Inp; ierr = calcI(e, n, p, l, signm, signn, &Inp);CHKERRQ(ierr); double Enp; ierr = calcLame(e, n, p, l, signm, signn, &Enp);CHKERRQ(ierr); double EnpDer; calcLameDerivative(e, n, p, l, signm, signn, &EnpDer); *sol = (2.0*a*b*c*(EnpDer/a)*Inp*Enp - 1)/2; ierr = PetscLogFlops(9); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "integrateMPFR" PetscErrorCode integrateMPFR(PetscErrorCode (*f)(mpfr_t *,mpfr_t*,void*), EllipsoidalSystem *e, mpfr_t a, mpfr_t b, int digits, mpfr_t *integral, void *ctx) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; //printf("can we get out of here?\n"); const int safetyFactor = 2; /* Calculate abcissa until 2*p digits */ int p = e->precision; /* Digits of precision in the evaluation */ int l = 0; /* Level of refinement, h = 2^{-l} */ mpfr_t *alpha = &(e->alpha); /* Half-width of the integration interval */ mpfr_t *beta = &(e->beta); /* Center of the integration interval */ mpfr_t *h = &(e->h_step); /* Step size, length between x_k */ mpfr_t *osum = &(e->osum); /* Integral on last level */ mpfr_t *psum = &(e->psum); /* Integral on the level before the last level */ mpfr_t *sum = &(e->sum); /* Integral on current level */ mpfr_t *yk = &(e->yk); /* Quadrature point 1 - x_k on reference domain [-1, 1] */ mpfr_t *lx = &(e->lx); mpfr_t *rx = &(e->rx); /* Quadrature points to the left and right of 0 on the real domain [a, b] */ mpfr_t *wk = &(e->wk); /* Quadrature weight at x_k */ mpfr_t *lval = &(e->lval); mpfr_t *rval = &(e->rval); /* Terms in the quadature *sum to the left and right of 0 */ mpfr_t *pi2 = &(e->pi2); mpfr_t *kh = &(e->kh); mpfr_t *msinh = &(e->msinh); mpfr_t *mcosh = &(e->mcosh); mpfr_t *maxTerm = &(e->maxTerm); mpfr_t *curTerm = &(e->curTerm); mpfr_t *tmp = &(e->tmp); int d; /* Digits of precision in the integral */ int counter = 1; if(digits <= 0) { printf("Please give a positive number of significant digits\n"); return 1; } /* Create high precision storage */ /* Initialization */ mpfr_set(*alpha, b, MPFR_RNDN); mpfr_sub(*alpha, *alpha, a, MPFR_RNDN); mpfr_mul_d(*alpha, *alpha, 0.5, MPFR_RNDN); mpfr_set(*beta, b, MPFR_RNDN); mpfr_add(*beta, *beta, a, MPFR_RNDN); mpfr_mul_d(*beta, *beta, 0.5, MPFR_RNDN); mpfr_set_d(*osum, 0.0, MPFR_RNDN); mpfr_set_d(*psum, 0.0, MPFR_RNDN); mpfr_set_d(*h, 1.0, MPFR_RNDN); mpfr_const_pi(*pi2, MPFR_RNDN); mpfr_mul_d(*pi2, *pi2, 0.5, MPFR_RNDN); flopCount += 5; /* Center term */ //mpfr_set_d(*lx, 0.5*(b+a), MPFR_RNDN); mpfr_set(*lx, b, MPFR_RNDN); mpfr_add(*lx, *lx, a, MPFR_RNDN); mpfr_mul_d(*lx, *lx, .5, MPFR_RNDN); f(lx, sum, ctx); mpfr_mul(*sum, *sum, *alpha, MPFR_RNDN); mpfr_mul(*sum, *sum, *pi2, MPFR_RNDN); flopCount += 4; //DELETE LATER int maxL = 6; double *SUMS = (double*) malloc(sizeof(double)*maxL); int *insideSums = (int*) malloc(sizeof(int)*maxL); /* */ do { double d1, d2, d3, d4; int k = 1; ++l; mpfr_set_d(*maxTerm, 0.0, MPFR_RNDN); /* PetscPrintf(PETSC_COMM_SELF, "LEVEL %D sum: %15.15f\n", l, sum); */ //printf("LEVEL %d sem: %15.15f\n", l, sum); /* At each level of refinement, h --> h/2 and sum --> sum/2 */ mpfr_set(*psum, *osum, MPFR_RNDN); mpfr_set(*osum, *sum, MPFR_RNDN); mpfr_mul_d(*h, *h, 0.5, MPFR_RNDN); mpfr_mul_d(*sum, *sum, 0.5, MPFR_RNDN); flopCount += 2; do { //printf("doot\n"); //if(mpfr_number_p(sum) == 0) //printf("at iterations %d sum is %8.8e a: %8.8f b: %8.8f\n", k, mpfr_get_d(sum, MPFR_RNDN), a, b); mpfr_set_si(*kh, k, MPFR_RNDN); mpfr_mul(*kh, *kh, *h, MPFR_RNDN); /* Weight */ mpfr_set(*wk, *h, MPFR_RNDN); mpfr_sinh_cosh(*msinh, *mcosh, *kh, MPFR_RNDN); mpfr_mul(*msinh, *msinh, *pi2, MPFR_RNDN); mpfr_mul(*mcosh, *mcosh, *pi2, MPFR_RNDN); mpfr_cosh(*tmp, *msinh, MPFR_RNDN); mpfr_sqr(*tmp, *tmp, MPFR_RNDN); mpfr_mul(*wk, *wk, *mcosh, MPFR_RNDN); mpfr_div(*wk, *wk, *tmp, MPFR_RNDN); flopCount += 8; /* Abscissa */ mpfr_set_d(*yk, 1.0, MPFR_RNDZ); mpfr_cosh(*tmp, *msinh, MPFR_RNDN); mpfr_div(*yk, *yk, *tmp, MPFR_RNDZ); mpfr_exp(*tmp, *msinh, MPFR_RNDN); mpfr_div(*yk, *yk, *tmp, MPFR_RNDZ); flopCount += 4; /* Quadrature points */ mpfr_sub_d(*lx, *yk, 1.0, MPFR_RNDZ); mpfr_mul(*lx, *lx, *alpha, MPFR_RNDU); mpfr_add(*lx, *lx, *beta, MPFR_RNDU); mpfr_d_sub(*rx, 1.0, *yk, MPFR_RNDZ); mpfr_mul(*rx, *rx, *alpha, MPFR_RNDD); mpfr_add(*rx, *rx, *beta, MPFR_RNDD); flopCount += 4; //printf("poot\n"); /* Evaluation */ f(lx, lval, ctx); //printf("lval: %8.8e\n", mpfr_get_d(lval, MPFR_RNDN)); f(rx, rval, ctx); //printf("rval: %8.8e\n", mpfr_get_d(rval, MPFR_RNDN)); //check if function evaluates to inf or nan int update = 1; if(mpfr_number_p(*lval) == 0) { update = 0; //printf("lval is nan/inf *lx: %15.15e\n", mpfr_get_d(*lx, MPFR_RNDN)); } if(mpfr_number_p(*rval) == 0) { update = 0; //printf("rval is nan/inf\n"); } /* Update if function not inf or nan*/ if(update == 1) { mpfr_mul(*tmp, *wk, *alpha, MPFR_RNDN); mpfr_mul(*tmp, *tmp, *lval, MPFR_RNDN); mpfr_add(*sum, *sum, *tmp, MPFR_RNDN); mpfr_abs(*tmp, *tmp, MPFR_RNDN); mpfr_max(*maxTerm, *maxTerm, *tmp, MPFR_RNDN); mpfr_set(*curTerm, *tmp, MPFR_RNDN); mpfr_mul(*tmp, *wk, *alpha, MPFR_RNDN); mpfr_mul(*tmp, *tmp, *rval, MPFR_RNDN); mpfr_add(*sum, *sum, *tmp, MPFR_RNDN); mpfr_abs(*tmp, *tmp, MPFR_RNDN); mpfr_max(*maxTerm, *maxTerm, *tmp, MPFR_RNDN); mpfr_max(*curTerm, *curTerm, *tmp, MPFR_RNDN); flopCount += 8; counter += 2; } /* if (l == 1) printf("k is %d and sum is %15.15f and *wk is %15.15f\n", k, sum, *wk); */ ++k; /* Only need to evaluate every other point on refined levels */ if (l != 1) ++k; mpfr_log10(*tmp, *wk, MPFR_RNDN); flopCount++; mpfr_abs(*tmp, *tmp, MPFR_RNDN); } while (mpfr_get_d(*tmp, MPFR_RNDN) < safetyFactor*p); /* Only need to evaluate sum until weights are < 32 digits\ of precision */ SUMS[l-1] = mpfr_get_d(*sum, MPFR_RNDN); insideSums[l-1] = counter; mpfr_sub(*tmp, *sum, *osum, MPFR_RNDN); mpfr_abs(*tmp, *tmp, MPFR_RNDN); mpfr_log10(*tmp, *tmp, MPFR_RNDN); d1 = mpfr_get_d(*tmp, MPFR_RNDN); mpfr_sub(*tmp, *sum, *psum, MPFR_RNDN); mpfr_abs(*tmp, *tmp, MPFR_RNDN); mpfr_log10(*tmp, *tmp, MPFR_RNDN); d2 = mpfr_get_d(*tmp, MPFR_RNDN); mpfr_log10(*tmp, *maxTerm, MPFR_RNDN); d3 = mpfr_get_d(*tmp, MPFR_RNDN) - p; mpfr_log10(*tmp, *curTerm, MPFR_RNDN); d4 = mpfr_get_d(*tmp, MPFR_RNDN); d = (int) fabs(min(0, max(max(max((d1*d1)/d2, 2*d1), d3), d4))); flopCount += 9; } while (d < digits && l < maxL); mpfr_set(*integral, *sum, MPFR_RNDN); //*integral = mpfr_get_d(*sum, MPFR_RNDN); /* Cleanup */ //mpfr_clears(*alpha, *beta, h, sum, *osum, *psum, *yk, *wk, *lx, *rx, *tmp, *maxTerm, *curTerm, *pi2, *kh, *msinh, *mcosh, lval, rval, NULL); //printf("yes we can\n"); //printf("levels: %d\n", l); /* if(l == maxL) { for(int i=0; i<l; ++i) { printf("SUMS[%d] = %15.15f\n", i, SUMS[i]); printf("inside total = %d\n", insideSums[i]); } } */ //printf("total is: %d\n", counter); free(SUMS); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "integrateMidpoint" PetscErrorCode integrateMidpoint(PetscErrorCode (*f)(mpfr_t *,mpfr_t*,void*), mpfr_t a, mpfr_t b, int n, double *integral, void *ctx) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; int digs = 32; mpfr_t delT, sum, fval, xval; mpfr_init2(delT, 4*digs); mpfr_init2(sum, 4*digs); mpfr_init2(fval, 4*digs); mpfr_init2(xval, 4*digs); mpfr_set_d(sum, 0.0, MPFR_RNDN); //calculate delT mpfr_sub(delT, b, a, MPFR_RNDN); mpfr_div_ui(delT, delT, n, MPFR_RNDN); //start xval at a+.5*delT mpfr_mul_d(xval, delT, 0.5, MPFR_RNDN); mpfr_add(xval, a, xval, MPFR_RNDN); flopCount += 4; for(int i=0; i < n; ++i) { *integral = mpfr_get_d(sum, MPFR_RNDN); //calculate function value f(&xval, &fval, ctx); //increment sum mpfr_add(sum, sum, fval, MPFR_RNDN); //increment xval mpfr_add(xval, xval, delT, MPFR_RNDN); flopCount += 2; } mpfr_mul(sum, sum, delT, MPFR_RNDN); flopCount ++; *integral = mpfr_get_d(sum, MPFR_RNDN); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.5666999621, "avg_line_length": 31.5919477693, "ext": "c", "hexsha": "e69b557107e522b55ebdfb8a327010c48f088652", "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/ellipsoid/ellipsoid.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/ellipsoid/ellipsoid.c", "max_line_length": 205, "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/ellipsoid/ellipsoid.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": 34438, "size": 87099 }
#include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <mpfr.h> #include <petsc.h> #include "ellipsoid.h" #include "../sphere/sphere.h" #include "ellSolv.h" double calcEnp(EllipsoidalSystem *e, Point *point, int n, int p) { //if(point->type == 'c') //cartesianToEllipsoidal(e, point); int signm = 1; int signn = 1; if(point->x2 < 0) signm = -1; if(point->x3 < 0) signn = -1; double eL, eM, eN; calcLame(e, n, p, point->x1, signm, signn, &eL); calcLame(e, n, p, point->x2, signm, signn, &eM); calcLame(e, n, p, point->x3, signm, signn, &eN); return eL*eM*eN; } double calcGnp(EllipsoidalSystem *e, Point *positions, double *charges, int nCharges, int n, int p) { clock_t start, diff; int msec; start = clock(); double normConstant; calcNormalization(e, n, p, &normConstant); diff = clock() - start; msec = diff * 1000 / CLOCKS_PER_SEC; //printf("normConstant took %d seconds and %d milliseconds\n", msec/1000, msec%1000); //double normConstant = 1.0; double sum = 0; double Enp; for(int k=0; k<nCharges; ++k) { Enp = calcEnp(e, positions+k, n, p); sum += charges[k] * Enp; } sum *= (4*PETSC_PI)/((2.0*n+1.0)*normConstant); return sum; } double calcFnp(EllipsoidalSystem *e, Point *point, int n, int p) { int signm = 1; int signn = 1; if(point->x2 < 0) signm = -1; if(point->x3 < 0) signn = -1; double enpval = calcEnp(e, point, n, p); double ival; calcI(e, n, p, point->x1, signm, signn, &ival); //printf("ENP: %15.15f\nI: %15.15f\n", enpval, ival); return (2*n + 1) * enpval * ival; } void calcBnpAndCnpFromGnp(Problem *problem, int n, int p, double Gnp, double *Bnp, double *Cnp) { EllipsoidalSystem *e = problem->e; double Ea; calcLame(e, n, p, e->a, 1, 1, &Ea); double Ia; calcI(problem->e, n, p, e->a, 1, 1, &Ia); double Fa = (2*n + 1) * Ea * Ia; double EaDer; calcLameDerivative(e, n, p, e->a, 1, 1, &EaDer); double IaDer; calcIDerivative(e, n, p, e->a, 1, 1, &IaDer); double FaDer = (2*n+1) * (Ea*IaDer + EaDer*Ia); //chain rule? double e1 = problem->e1; double e2 = problem->e2; //calc Bnp double first = (Fa/Ea)*(e1 - e2)/(e1*e2); first /= (1-(e1/e2)*((EaDer*Fa)/(FaDer*Ea))); *Bnp = first*Gnp; //calc Cnp first = (e1/e2)*(EaDer/FaDer)*(*Bnp); first += (Gnp/e2); *Cnp = first; } double calcCoulomb(Problem *problem, int maxDeg, Point *r) { //FILE *fp = fopen("fnpnorm.txt", "w"); double Gnp, Fnp, Enp; double sum = 0; int count = 0; for(int n=0; n<=maxDeg; ++n) { for(int p=0; p < 2*n+1; ++p) { clock_t start = clock(), diff; Gnp = calcGnp(problem->e, problem->positions, problem->charges, problem->nCharges, n, p); diff = clock() - start; int msec = diff * 1000 / CLOCKS_PER_SEC; //printf("Gnp took %d seconds %d milliseconds\n", msec/1000, msec%1000); start = clock(); Fnp = calcFnp(problem->e, r, n, p); diff = clock() - start; msec = diff * 1000 / CLOCKS_PER_SEC; //printf("Fnp took %d seconds %d milliseconds\n\n", msec/1000, msec%1000); //fprintf(fp, "%8.8e %8.8e\n", (double)count, fabs(Fnp)); sum += (Gnp*Fnp)/problem->e1; count++; } printf("n: %d\n", n); printf("Gnp: %16.16f\n", Gnp); printf("Fnp: %16.16f\n", Fnp); //printf("enp: %16.16f\n", Enp); printf("sum: %16.16f\n", sum); } //fclose(fp); return sum; } double calcCoulombEllipsoidalGrid(Problem *problem, int maxDeg, Point *r, int nPoints, double *solution) { EllipsoidalSystem *e = problem->e; double Gnp, Bnp, Fnp, Enp, Cnp; for(int i=0; i<nPoints; ++i) solution[i] = 0; int count = 0; double *fnpvals = (double*) malloc(sizeof(double)*nPoints); for(int n=0; n<=maxDeg; ++n) { for(int p=0; p < 2*n+1; ++p) { Gnp = calcGnp(problem->e, problem->positions, problem->charges, problem->nCharges, n, p); calcBnpAndCnpFromGnp(problem, n, p, Gnp, &Bnp, &Cnp); for(int k=0; k<nPoints; ++k) { //if on exterior if(fabs(r[k].x1) >= e->a) { Fnp = calcFnp(problem->e, r+k, n, p); solution[k] += Cnp*Fnp; } else { Enp = calcEnp(problem->e, r+k, n, p); solution[k] += Bnp*Enp; if(n==3 && p==2) { printf("do we get here2\n"); printf("(%d,%d)\n", n, p); printf("Enp: %15.15f\n", Enp); printf("Bnp: %15.15f\n", Bnp); printf("\n"); } } } count++; } //printf("n: %d\n", n); //printf("Gnp: %16.16f\n", Gnp); //printf("Cnp: %16.16f\n", Cnp); //printf("Fnp: %16.16f\n", Fnp); //printf("enp: %16.16f\n", Enp); //printf("sum: %16.16f\n", solution[0]); } //fclose(fp); return solution[0]; }
{ "alphanum_fraction": 0.5704584041, "avg_line_length": 24.0408163265, "ext": "c", "hexsha": "ba3480c7e6b1dc7d406ebb0227345c0e8bf21783", "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/ellipsoid/ellSolv.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/ellipsoid/ellSolv.c", "max_line_length": 106, "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/ellipsoid/ellSolv.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": 1830, "size": 4712 }
#ifndef cloptions_h #define cloptions_h #include <petsc.h> #include "../include/structs.h" // Process general command line options PetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx app_ctx); #endif // cloptions_h
{ "alphanum_fraction": 0.7903930131, "avg_line_length": 20.8181818182, "ext": "h", "hexsha": "a905593c2f184a2b7c49afcd0d81a466519d5eda", "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/solids/include/cl-options.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/solids/include/cl-options.h", "max_line_length": 72, "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/solids/include/cl-options.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": 52, "size": 229 }
/// /// @file /// /// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University /// /// @internal 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 <starneig_config.h> #include <starneig/configuration.h> #include "sirobust-geig.h" #include "robust.h" #include "../common/common.h" #include "../common/node_internal.h" #include <starneig/gep_sm.h> #include <cblas.h> #include <stdlib.h> #include <starpu.h> __attribute__ ((visibility ("default"))) starneig_error_t starneig_GEP_SM_Eigenvectors_expert( struct starneig_eigenvectors_conf *_conf, int n, int selected[], double S[], int ldS, double T[], int ldT, double Z[], int ldZ, double X[], int ldX) { if (n < 1) return -2; if (selected == NULL) return -3; if (S == NULL) return -4; if (ldS < n) return -5; if (T == NULL) return -6; if (ldT < n) return -7; if (Z == NULL) return -8; if (ldZ < n) return -9; if (X == NULL) return -10; if (ldX < n) return -11; if (!starneig_node_initialized()) return STARNEIG_NOT_INITIALIZED; starneig_error_t ret = STARNEIG_SUCCESS; double *_X = NULL; int ld_X; // use default configuration if necessary struct starneig_eigenvectors_conf *conf; struct starneig_eigenvectors_conf local_conf; if (_conf == NULL) starneig_eigenvectors_init_conf(&local_conf); else local_conf = *_conf; conf = &local_conf; if (conf->tile_size == STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE) { conf->tile_size = MAX(64, divceil(0.016*n, 8)*8); starneig_message("Setting tile size to %d.", conf->tile_size); } else if (conf->tile_size < 8) { starneig_error("Invalid tile size."); ret = STARNEIG_INVALID_CONFIGURATION; goto cleanup; } int selected_count = 0; for (int i = 0; i < n; i++) if (selected[i]) selected_count++; { size_t ld; _X = starneig_alloc_matrix(n, selected_count, sizeof(double), &ld); ld_X = ld; } // // solve // starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_SEQUENTIAL); starneig_node_set_mode(STARNEIG_MODE_SM); starneig_node_resume_starpu(); starneig_eigvec_gen_initialize_omega(100); int _ret = starneig_eigvec_gen_sinew(n, S, ldS, T, ldT, selected, _X, ld_X, conf->tile_size, conf->tile_size); starpu_task_wait_for_all(); starneig_node_pause_starpu(); starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL); if (_ret != 0) { ret = STARNEIG_GENERIC_ERROR; goto cleanup; } // // back transformation // starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_PARALLEL); starneig_node_pause_awake_starpu(); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, selected_count, n, 1.0, Z, ldZ, _X, ld_X, 0.0, X, ldX); starneig_node_resume_awake_starpu(); starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL); cleanup: starneig_free_matrix(_X); return ret; } __attribute__ ((visibility ("default"))) starneig_error_t starneig_GEP_SM_Eigenvectors( int n, int selected[], double S[], int ldS, double T[], int ldT, double Z[], int ldZ, double X[], int ldX) { if (n < 1) return -1; if (selected == NULL) return -2; if (S == NULL) return -3; if (ldS < n) return -4; if (T == NULL) return -5; if (ldT < n) return -6; if (Z == NULL) return -7; if (ldZ < n) return -8; if (X == NULL) return -9; if (ldX < n) return -10; if (!starneig_node_initialized()) return STARNEIG_NOT_INITIALIZED; return starneig_GEP_SM_Eigenvectors_expert( NULL, n, selected, S, ldS, T, ldT, Z, ldZ, X, ldX); }
{ "alphanum_fraction": 0.650109569, "avg_line_length": 32.0233918129, "ext": "c", "hexsha": "2921eda8d05f3d38b75d960ee0f9eb050ccd67c8", "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": "src/eigenvectors/generalized/interface.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": "src/eigenvectors/generalized/interface.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": "src/eigenvectors/generalized/interface.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": 1479, "size": 5476 }
/* * particle_filters.c * * Created on: 18 Sep 2020 * Author: heine */ #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_eigen.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <Accelerate/Accelerate.h> #include "particle_filters.h" void MLbootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0, int* sample_sizes, double *worst_case_sign_ratio, double* x_hats, double *filtering_time, int* mesh_sizes, int kl, int ku, double* ab0, double* ab1, int ldab, int* ipiv0, int* ipiv1, int ldb0, int ldb1, int info, double w, double d, double E, double I, double h0, double h1, double L , double* meass, int N_meas) { int make_correction = 1; // If one ML telescoping correction is made, if 0 not. int N_levels = 2; // hard coded for now int N = 0; const char prog_bar[51] = "-------------------------------------------------"; int* minds0 = (int*)malloc(2 * N_meas * sizeof(int)); int* minds1 = minds0 + N_meas; double* obss = (double*)malloc(N_meas*sizeof(double)); double lower_bound = 0.25, upper_bound = L - 0.25; clock_t start = clock(); int bar_segment_count = 0; for (short i = 0; i < N_levels; i++) { N += sample_sizes[i]; printf("N%i = %i, ", i, sample_sizes[i]); } printf("N = %i, L0 = %i, L1 = %i\n", N, mesh_sizes[0],mesh_sizes[1]); double *X = (double*) malloc(2 * N * sizeof(double)); double W1_tmp; double* B0 = (double*) malloc(sample_sizes[0]*mesh_sizes[0]*sizeof(double)); double* B1 = (double*) malloc(sample_sizes[1]*mesh_sizes[1]*sizeof(double)); double* pred_meass0 = (double*) malloc(2 * sample_sizes[1] * N_meas * sizeof(double)); double* pred_meass1 = pred_meass0 + sample_sizes[1] * N_meas; double* W = (double*) malloc(2 * N * sizeof(double)); double* absW = W + N; short* signs = (short*) malloc(2 * N * sizeof(short)); short* signs_res = signs + N; int* ind = (int*) malloc(2 * N * sizeof(int)); int* permutation = ind + N; // needed for uniform resampling double x_hat = 0; double p_hat = 0; double* X0 = X; double* X1 = X + sample_sizes[0]; double* W0 = W; double* W1 = W + sample_sizes[0]; double* X_res = X + N; printf( "%s\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", prog_bar); fflush(stdout); /* Make copies of the band matrices as DGBSV destroys them */ double* a0_copy = (double*) malloc(ldab * mesh_sizes[0] * sizeof(double)); double* a1_copy = (double*) malloc(ldab * mesh_sizes[1] * sizeof(double)); /* * Initial sample and level indicator */ gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(rng, clock()); for (int i = 0; i < N; i++) { X[i] = gsl_ran_gaussian(rng, sig_std) + x0; // init sample W[i] = (double) 1.0 / (double) N; // init weights signs_res[i] = 1; } double normaliser = 0; double abs_normaliser = 0; // double diff; double ESS, ESSABS; // double tmp_x_hat; double positive_mass, negative_mass; // FILE* bpf_out = fopen("mlbpf_out.txt", "w"); clock_t iteration_timer; clock_t resampling_timer; clock_t level_timer_start; double level_0_particle_cost = 0; double level_1_particle_cost = 0; double rsamp_time_per_prcl = 0; worst_case_sign_ratio[0] = 100; double sign_balance; double obs_std_scale = 0.8; double intercepts[2]; double slopes[2]; int res_pos, res_neg; int dodb = 0; // Mesh point indices for the measurement locations for(int i = 0; i < N_meas; i++) { minds0[i] = (int)(meass[i] / L * (double) mesh_sizes[0]); minds1[i] = (int)(meass[i] / L * (double) mesh_sizes[1]); } /* * FILTER MAIN LOOP */ for (int n = 0; n < data_length; n++) { // Restore the destroyed band matrix array_copy(ab0, a0_copy, ldab * mesh_sizes[0]); array_copy(ab1, a1_copy, ldab * mesh_sizes[1]); iteration_timer = clock(); // start the stopwatch level_timer_start = clock(); // Extract the observations for the current time step for(int i = 0; i < N_meas; i++) obss[i] = y[n + i * data_length]; /* * Level 1 weight calculation */ /* Calculate Level 1 first, so we can estimate the bias of the observation mapping */ /* Solve the beam for level 0 mesh and sample N1 */ ebb_solve(sample_sizes[1], X1, mesh_sizes[0], B1, w, d, h0, E, I, L, kl, ku, a0_copy, ldab, ipiv0, ldb0, info, N_meas, minds0, pred_meass0); /* Solve the beam for level 1 mesh and sample N1 */ ebb_solve(sample_sizes[1], X1, mesh_sizes[1], B1, w, d, h1, E, I, L, kl, ku, a1_copy, ldab, ipiv1, ldb1, info, N_meas, minds1, pred_meass1); /* Fit a first order LS model for the error between level 0 and level 1 */ if(sample_sizes[1] > 0){ // do only if N1 > 0 ls_fit(N_meas, sample_sizes[1], X1, pred_meass0, pred_meass1, intercepts, slopes); } /* Now that we know the bias, we can evaluate the weights for level 1 */ double diff; for (int j = 0; j < sample_sizes[1]; j++) { W1[j] = 1; W1_tmp = 1; for(int k = 0; k < N_meas; k++){ /* Level 0 */ diff = obss[k] - pred_meass0[sample_sizes[1] * k + j] - intercepts[k] - slopes[k] * X1[j]; W1_tmp *= exp( - diff * diff / (double) 2.0 / (obs_std * obs_std_scale) / (obs_std * obs_std_scale)); /* Level 1 */ diff = obss[k] - pred_meass1[sample_sizes[1] * k + j]; W1[j] *= exp( - diff * diff / (double) 2.0 / obs_std / obs_std ); } W1[j] -= W1_tmp; // take the difference and... W1[j] /= (double) sample_sizes[1]; // ... normalise by sample size N1 // W1[j] = 0; /* uncomment to disable level 1 correction*/ } /* Level 0 weight calculation */ array_copy(ab0, a0_copy, ldab * mesh_sizes[0]); likelihood(X0, sample_sizes[0], obss, obs_std_scale*obs_std, mesh_sizes[0], kl, ku, a0_copy, ldab, ipiv0, ldb0, info, B0, w, d, h0, E, I, W0, L, minds0, N_meas, dodb, intercepts, slopes); // normalise by the sample size (N0) for (int i = 0; i < sample_sizes[0]; i++) W[i] /= (double)sample_sizes[0]; if(!make_correction) { for(int i = 0; i < sample_sizes[1]; i++) { W1[i] = 0; } } /* Joint normalisation of the weights */ normaliser = 0; abs_normaliser = 0; for (long i = 0; i < N; i++) { W[i] *= (double) signs_res[i]; // Take the sign into account absW[i] = fabs(W[i]); signs[i] = W[i] > 0 ? 1 : -1; normaliser += W[i]; abs_normaliser += absW[i]; } /* Normalise */ positive_mass = 0; negative_mass = 0; for (long i = 0; i < N; i++) { W[i] /= normaliser; if (W[i] > 0) { positive_mass += W[i]; } else { negative_mass += fabs(W[i]); } absW[i] /= abs_normaliser; } sign_balance = positive_mass / negative_mass; if (sign_balance < worst_case_sign_ratio[0]) { worst_case_sign_ratio[0] = sign_balance; } ESS = 0; ESSABS = 0; for (long i = 0; i < N; i++) { ESS += W[i] * W[i]; ESSABS += absW[i] * absW[i]; } ESS = (double) 1.0 / ESS; ESSABS = (double) 1.0 / ESSABS; /* Resample */ resampling_timer = clock(); resample(N, absW, ind, rng); random_permuter(permutation, N, rng); rsamp_time_per_prcl += (double) (clock() - resampling_timer) / CLOCKS_PER_SEC / (double) N; normaliser = 0; res_pos = 0; res_neg = 0; for (long i = 0; i < N; i++) { X_res[permutation[i]] = X[ind[i]]; signs_res[permutation[i]] = signs[ind[i]]; normaliser += signs[ind[i]]; if(signs[ind[i]]>0) { res_pos++; }else{ res_neg++; } } for (long i = 0; i < N; i++) { W[i] = (double) signs_res[i] / normaliser; } /* Calculate the output: posterior mean */ if(x_hats!=NULL){ x_hat = 0; for (int i = 0; i < N; i++) { x_hat += X_res[i] * W[i]; if(isnan(x_hat)){ printf("NaN detected!\n X_res[i] = %e, W[i] = %e, i = %i, normaliser = %e + = %e, - = %e\nESS=%e, res_+ =%i, res_- = %i\n", X_res[i], W[i], i,normaliser,positive_mass, negative_mass,ESS,res_pos,res_neg); fflush(stdout); getchar(); } } x_hats[n] = x_hat; /* Calculate the output: posterior variance */ p_hat = 0; for (long i = 0; i < N; i++) { diff = X_res[i] - x_hat; p_hat += diff * diff * W[i]; } } /* Mutate */ for (long i = 0; i < N; i++) { X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std); if(X[i] < lower_bound) X[i] = lower_bound + lower_bound-X[i]; if(X[i] > upper_bound) X[i] = upper_bound - (X[i]-upper_bound); } if (floor(n * (double) 50 / data_length) > bar_segment_count) { printf("█"); fflush(stdout); bar_segment_count++; } } filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length; filtering_time[1] = level_0_particle_cost / (double) data_length / (double) sample_sizes[0]; filtering_time[2] = level_1_particle_cost / (double) data_length / (double) sample_sizes[1]; filtering_time[3] = rsamp_time_per_prcl / (double) data_length / (double) N; printf(" %5.5f sec\n", filtering_time[0]); free(X); free(W); free(signs); free(ind); free(a0_copy); free(a1_copy); free(B0); free(B1); free(minds0); free(obss); free(pred_meass0); gsl_rng_free(rng); } void bootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0, int N, double* x_hats, double* p_hats, double *filtering_time, int mesh_size, int kl, int ku, double* ab, int ldab, int* ipiv, int ldb, int info, double w, double d, double E, double I, double h , double L, double *meass, int N_meas) { const char prog_bar[51] = "-------------------------------------------------"; clock_t start; int bar_segment_count = 0; printf("Basic BPF with N = %i\n", N); double *X = (double*) malloc(2 * N * sizeof(double)); double *X_res = X + N; double *W = (double*) malloc(N * sizeof(double)); int *ind = (int*) malloc(N * sizeof(int)); double* payloads = (double*) malloc(mesh_size * N * sizeof(double)); // Because DGBSV destroys the AB matrix, we need to make a copy of it double* ab_copy = (double*) malloc(ldab * mesh_size * sizeof(double)); double x_hat = 0; double p_hat = 0; double lower_bound = 0.25, upper_bound = L - 0.25; double intercepts[2] = {0,0}; double slopes[2] = {0,0}; printf( "%s\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", prog_bar); fflush(stdout); start = clock(); /* * Initial sample and level indicator */ gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus); gsl_rng_set(rng, clock()); for (int i = 0; i < N; i++) { X[i] = gsl_ran_gaussian(rng, sig_std) + x0; W[i] = (double) 1.0 / (double) N; } double normaliser = 0; double diff; double ESS; double cost_per_particle = 0; int* minds = (int*)malloc(N_meas * sizeof(int)); double* obss = (double*)malloc(N_meas * sizeof(double)); for(int i = 0; i < N_meas; i++){ minds[i] = (int)(meass[i] / L * (double) mesh_size); } /* Classic BPF main loop */ /* --------------------- */ for (int n = 0; n < data_length; n++) { /* Weight calculation */ normaliser = 0; array_copy(ab, ab_copy, ldab * mesh_size); /* * Weight calculation */ clock_t stopwatch_start = clock(); for(int i = 0; i < N_meas; i++) obss[i] = y[n + i*data_length]; likelihood(X, N, obss, obs_std, mesh_size, kl, ku, ab_copy, ldab, ipiv, ldb, info, payloads, w, d, h, E, I, W, L, minds, N_meas, 0, intercepts, slopes); clock_t stopwatch_stop = clock(); cost_per_particle += (double)(stopwatch_stop-stopwatch_start)/(double) CLOCKS_PER_SEC; // Normalise the weights normaliser = 0; for (int i = 0; i < N; i++) normaliser += W[i]; for (int i = 0; i < N; i++) W[i] /= normaliser; ESS = 0; for (int i = 0; i < N; i++) { ESS += W[i] * W[i]; } ESS = (double) 1.0 / ESS; /* Resample */ resample(N, W, ind, rng); for (int i = 0; i < N; i++) { X_res[i] = X[ind[i]]; } /* Calculate the output: posterior mean */ if(x_hats != NULL) { x_hat = 0; for (int i = 0; i < N; i++) { x_hat += X_res[i] / (double) N; } x_hats[n] = x_hat; /* Calculate the output: posterior variance */ p_hat = 0; for (int i = 0; i < N; i++) { diff = X_res[i] - x_hat; p_hat += diff * diff / (double) (N-1); } if(p_hats!=NULL) p_hats[n] = p_hat; } /* Mutate */ for (int i = 0; i < N; i++) { X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std); if(X[i] < lower_bound) X[i] = lower_bound + lower_bound-X[i]; if(X[i] > upper_bound) X[i] = upper_bound - (X[i]-upper_bound); } if (floor(n * (double) 50 / data_length) > bar_segment_count) { printf("█"); fflush(stdout); bar_segment_count++; } } filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length; filtering_time[1] = cost_per_particle / (double) data_length; filtering_time[2] = 0; filtering_time[3] = 0; printf(" %5.5f sec\n", filtering_time[0]); free(X); free(W); free(ind); free(ab_copy); free(payloads); free(minds); free(obss); gsl_rng_free(rng); } /* Computes a first order LS fit for error between level 0 and level 1 */ void ls_fit(int N_meas, int N1, double* X1, double* pred_meass0, double* pred_meass1, double* intercepts, double* slopes) { double a,b,c,d,e,f; for(int j = 0; j < N_meas; j++) { /* First order polynomial fit to the bias */ a = 0; b = 0; d = 0; e = 0; f = 0; for(int i = 0; i < N1; i++) { a++; b += X1[i]; d += X1[i] * X1[i]; e += pred_meass1[j * N1 + i] - pred_meass0[j * N1 + i]; f += X1[i] * (pred_meass1[j * N1 + i] - pred_meass0[j * N1 + i]); } c = b; intercepts[j] = (e * d - b * f) / (a * d - b * c); slopes[j] = (-c * e + a * f) / (a * d - b * c); } } void likelihood(double* x, int N, double* y, double std, int mesh_size, int kl, int ku, double* ab, int ldab, int* ipiv, int ldb, int info, double* b, double w, double d, double h, double E, double I, double* likes, double L, int* minds, int N_meas, int dodb, double* intercepts, double* slopes) { // Create the instantaneous payload create_payload(N, mesh_size, b, w, d, x, h, E, I, L); // Solve the Euler-Bernoulli beam for each particle dgbsv_(&mesh_size, &kl, &ku, &N, ab, &ldab, ipiv, b, &ldb, &info); double diff; for (int j = 0; j < N; j++) { diff = 1; likes[j] = 1; for(int k = 0; k < N_meas; k++){ diff = y[k] - b[j * mesh_size + minds[k]] - x[j]*slopes[k] - intercepts[k]; likes[j] *= exp( - diff * diff / (double) 2.0 / std / std) ; } } } void random_permuter(int *permutation, int N, gsl_rng *r) { for (int i = 0; i < N; i++) permutation[i] = i; int j; int tmp; for (int i = N - 1; i > 0; i--) { j = (int)gsl_rng_uniform_int(r, i + 1); tmp = permutation[j]; permutation[j] = permutation[i]; permutation[i] = tmp; } } void resample(int size, double *w, int *ind, gsl_rng *r) { /* Generate the exponentials */ double *e = (double*) malloc((size + 1) * sizeof(double)); double g = 0; for (int i = 0; i <= size; i++) { e[i] = gsl_ran_exponential(r, 1.0); g += e[i]; } /* Generate the uniform order statistics */ double *u = (double *) malloc((size + 1) * sizeof(double)); u[0] = 0; for (int i = 1; i <= size; i++) u[i] = u[i - 1] + e[i - 1] / g; /* Do the actual sampling with inverse cdf */ double cdf = w[0]; int j = 0; for (int i = 0; i < size; i++) { while (cdf < u[i + 1]) { j++; cdf += w[j]; } ind[i] = j; } free(e); free(u); } void create_payload(int N, int n, double *b, double w, double d, double* x, double h, double E, double I, double L) { double g = -9.81; // Gravity acceleration double scaler = h * h * h * h / (E * I); double slab_thickness = 0.20; // meters double density = 7874; // kg/ m^3 double slab_width = 0.72; // m int location_index_centre = 0, location_index_right = 0, location_index_left = 0; double deviation = slab_thickness / (double) 8; double diff; for (long j = 0; j < N;j++) { // iterate over particles for(int i = 0; i < n; i++) b[j * n + i] = g * w * d * (double)480; // Find the index corresponding to the location x location_index_centre = (int)(x[j] / L * (double) n); // Left end of the slab location_index_left = location_index_centre - ceil(slab_thickness / h / (double) 2); // make sure index is non-negative location_index_left = location_index_left < 0 ? 0 : location_index_left; // Right end of the slab location_index_right = location_index_centre + ceil(slab_thickness / h / (double) 2); // make sure index is less than mesh size location_index_right = location_index_right > n - 1 ? n - 1 : location_index_right; if(location_index_centre < 0) { printf("NEGATIVE INDEX!\n"); fflush(stdout); } // Add weight to the location for(int i = location_index_left; i <= location_index_right ; i++){ diff = x[j] - i*h; b[j * n + i] -= slab_width * slab_width * density * 9.81 * exp(- diff * diff / (double) 2 / deviation / deviation); } // Scale appropriately (there is some physical justification to this) for(int i = 0; i < n;i++) { b[j * n + i] *= scaler; } } } void ebb_solve(int N, double* x, int mesh_size, double* b, double w, double d, double h, double E, double I, double L, int kl, int ku, double *ab, int ldab, int *ipiv, int ldb, int info, int N_meas, int* minds, double* pred_measurements) { create_payload(N, mesh_size, b, w, d, x, h, E, I, L); dgbsv_(&mesh_size, &kl, &ku, &N, ab, &ldab, ipiv, b, &ldb, &info); for (int j = 0; j < N; j++) { for(int k = 0; k < N_meas; k++){ pred_measurements[N * k + j] = b[j * mesh_size + minds[k]]; } } } void array_copy(double *src, double* dst, int length) { for(int i = 0; i < length; i++) dst[i] = src[i]; }
{ "alphanum_fraction": 0.5645418751, "avg_line_length": 31.3756260434, "ext": "c", "hexsha": "6a180694b0cd0fe287b570c9c5b527658a613f67", "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": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_path": "ODE_MODEL/particle_filters.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_path": "ODE_MODEL/particle_filters.c", "max_line_length": 338, "max_stars_count": null, "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_path": "ODE_MODEL/particle_filters.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6160, "size": 18794 }
/*************************************************************************** File : FrequencyCountDialog.h Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2008 by Ion Vasilief Email (use @ for *) : ion_vasilief*yahoo.fr Description : Frequency count options dialog ***************************************************************************/ /*************************************************************************** * * * 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 FREQUENCYCOUNTDIALOG_H #define FREQUENCYCOUNTDIALOG_H #include <QDialog> #include <gsl/gsl_vector.h> class QPushButton; class DoubleSpinBox; class Table; //! Filter options dialog class FrequencyCountDialog : public QDialog { Q_OBJECT public: FrequencyCountDialog(Table *t, QWidget* parent = 0, Qt::WFlags fl = 0 ); ~FrequencyCountDialog(); private slots: bool apply(); void accept(); private: Table *d_source_table; Table *d_result_table; QString d_col_name; gsl_vector *d_col_values; int d_bins; QPushButton* buttonApply; QPushButton* buttonCancel; QPushButton* buttonOk; DoubleSpinBox* boxStart; DoubleSpinBox* boxEnd; DoubleSpinBox* boxStep; }; #endif
{ "alphanum_fraction": 0.4658433037, "avg_line_length": 38.1029411765, "ext": "h", "hexsha": "88424231156bc2e2df073b2c778fc1081ed57dad", "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/analysis/dialogs/FrequencyCountDialog.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/analysis/dialogs/FrequencyCountDialog.h", "max_line_length": 77, "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/analysis/dialogs/FrequencyCountDialog.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": 446, "size": 2591 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include <array> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "PointLight.h" namespace Library { class PointLight; class ProxyModel; } namespace Rendering { class MultiplePointLightsMaterial; class MultiplePointLightsDemo final : public Library::DrawableGameComponent { public: MultiplePointLightsDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); MultiplePointLightsDemo(const MultiplePointLightsDemo&) = delete; MultiplePointLightsDemo(MultiplePointLightsDemo&&) = default; MultiplePointLightsDemo& operator=(const MultiplePointLightsDemo&) = default; MultiplePointLightsDemo& operator=(MultiplePointLightsDemo&&) = default; ~MultiplePointLightsDemo(); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); void ToggleAnimation(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); const std::array<Library::PointLight, 4>& PointLights() const; void SetPointLight(const Library::PointLight& light, size_t index); const size_t SelectedLightIndex() const; const Library::PointLight& SelectedLight() const; void UpdateSelectedLight(const Library::PointLight& light); void SelectLight(size_t index); float SpecularPower() const; void SetSpecularPower(float power); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<MultiplePointLightsMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; std::array<std::unique_ptr<Library::ProxyModel>, 4> mProxyModels; size_t mSelectedLightIndex{ 0 }; float mModelRotationAngle{ 0.0f }; bool mAnimationEnabled{ true }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7758376593, "avg_line_length": 31.6268656716, "ext": "h", "hexsha": "523688c4e3aff74c501ac19560eadf3c8c81a4cf", "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/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.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/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.h", "max_line_length": 95, "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/4.3_Multiple_Point_Lights/MultiplePointLightsDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 521, "size": 2119 }
//This does CELL (~soma) stage of LSTM (long short-term memory) model. //This requires each neuron to have 4 input time series, Xc, Xi, Xf, Xo, //where Xc is the usual (or "cellular") input and Xi, Xf, Xo the inputs for the input, forget, output gates. //Xc, Xi, Xf, Xo are the output of separate linear IN stages (weights and baises). //In this version, these are stacked into one matrix //For dim=0: X = [Xc; Xi; Xf; Xo]; for dim=1: X = [Xc Xi Xf Xo]. //For dim=0, C[:,t] = tanh{Xc[:,t] + Uc*Y[:,t-1]} // I[:,t] = sig{Xi[:,t] + Ui*Y[:,t-1]} // F[:,t] = sig{Xf[:,t] + Uf*Y[:,t-1]} // O[:,t] = sig{Xo[:,t] + Uo*Y[:,t-1]} // H[:,t] = I[:,t].*C[:,t] + F[:,t].*H[:,t-1] // Y[:,t] = O[:,t].*tanh{H[:,t]} //with sizes Xc, Xi, Xf, Xo: N x T // Uc, Ui, Uf, Uo: N x N // Y : N x T // //For dim=1, C[t,:] = tanh{Xc[t,:] + Y[t-1,:]*Uc} // I[t,:] = sig{Xi[t,:] + Y[t-1,:]*Ui} // F[t,:] = sig{Xf[t,:] + Y[t-1,:]*Uf} // O[t,:] = sig{Xo[t,:] + Y[t-1,:]*Uo} // H[t,:] = I[t,:].*C[t,:] + F[t,:].*H[t-1,:] // Y[t,:] = O[t,:].*tanh{H[t,:]} //with sizes Xc, Xi, Xf, Xo: T x N // Uc, Ui, Uf, Uo: N x N // Y : T x N // //where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)), //I is the input gate, F is the forget gate, O is the output gate, //C is the "cell input activation vector", //H is an intermediate (hidden) vector (sometimes called the "cell state vector"), //Uc, Ui, Uf, Uo are NxN matrices, and Y is the final output (sometimes called the "hidden state vector"). //Note that, the neurons of a layer are independent only if Uc, Ui, Uf, Uo are diagonal matrices. //This is only really a CELL (~soma) stage in that case. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifdef I #undef I #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int lstm_s (float *Y, const float *X, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int lstm_d (double *Y, const double *X, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int lstm_inplace_s (float *X, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int lstm_inplace_d (double *X, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int lstm_s (float *Y, const float *X, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T; size_t nT, tN, tN4; float *C, *I, *F, *O, *H; if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_s: problem with malloc. "); perror("malloc"); return 1; } if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_s: problem with malloc. "); perror("malloc"); return 1; } if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_s: problem with malloc. "); perror("malloc"); return 1; } if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_s: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_s: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { H[n] = tanhf(X[n]) / (1.0f+expf(-X[N+n])); Y[n] = tanhf(H[n]) / (1.0f+expf(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_scopy((int)N,&X[tN4],1,C,1); cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); Y[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanhf(X[nT]) / (1.0f+expf(-X[NT+nT])); Y[nT] = tanhf(H[n]) / (1.0f+expf(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,C,1); cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); Y[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanhf(X[nT]) / (1.0f+expf(-X[NT+nT])); Y[nT] = tanhf(H[n]) / (1.0f+expf(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,C,1); cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); Y[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { H[n] = tanhf(X[n]) / (1.0f+expf(-X[N+n])); Y[n] = tanhf(H[n]) / (1.0f+expf(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_scopy((int)N,&X[tN4],1,C,1); cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); Y[tN+n] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } } else { fprintf(stderr,"error in lstm_s: dim must be 0 or 1.\n"); return 1; } return 0; } int lstm_d (double *Y, const double *X, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T; size_t nT, tN, tN4; double *C, *I, *F, *O, *H; if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_d: problem with malloc. "); perror("malloc"); return 1; } if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_d: problem with malloc. "); perror("malloc"); return 1; } if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_d: problem with malloc. "); perror("malloc"); return 1; } if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_d: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_d: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { H[n] = tanh(X[n]) / (1.0+exp(-X[N+n])); Y[n] = tanh(H[n]) / (1.0+exp(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_dcopy((int)N,&X[tN4],1,C,1); cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); Y[tN+n] = tanh(H[n]) / (1.0+exp(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanh(X[nT]) / (1.0+exp(-X[NT+nT])); Y[nT] = tanh(H[n]) / (1.0+exp(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,C,1); cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); Y[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanh(X[nT]) / (1.0+exp(-X[NT+nT])); Y[nT] = tanh(H[n]) / (1.0+exp(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,C,1); cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[t-1],(int)T,o,C,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[t-1],(int)T,o,I,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); Y[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { H[n] = tanh(X[n]) / (1.0+exp(-X[N+n])); Y[n] = tanh(H[n]) / (1.0+exp(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_dcopy((int)N,&X[tN4],1,C,1); cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&Y[tN-N],1,o,C,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&Y[tN-N],1,o,I,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&Y[tN-N],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); Y[tN+n] = tanh(H[n]) / (1.0+exp(-O[n])); } } } } else { fprintf(stderr,"error in lstm_d: dim must be 0 or 1.\n"); return 1; } return 0; } int lstm_inplace_s (float *X, const float *Uc, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; const size_t N2 = 2*N, N3 = 3*N, N4 = 4*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T; size_t nT, tN, tN4; float *C, *I, *F, *O, *H; if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_inplace_s: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { H[n] = tanhf(X[n]) / (1.0f+expf(-X[N+n])); X[n] = tanhf(H[n]) / (1.0f+expf(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_scopy((int)N,&X[tN4],1,C,1); cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&X[tN4-N4],1,o,C,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&X[tN4-N4],1,o,I,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN4-N4],1,o,F,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&X[tN4-N4],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); X[tN4+n] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanhf(X[nT]) / (1.0f+expf(-X[NT+nT])); X[nT] = tanhf(H[n]) / (1.0f+expf(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,C,1); cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&X[t-1],(int)T,o,C,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&X[t-1],(int)T,o,I,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&X[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); X[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanhf(X[nT]) / (1.0f+expf(-X[NT+nT])); X[nT] = tanhf(H[n]) / (1.0f+expf(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,C,1); cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&X[t-1],(int)T,o,C,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&X[t-1],(int)T,o,I,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&X[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); X[t+n*T] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { H[n] = tanhf(X[n]) / (1.0f+expf(-X[N+n])); X[n] = tanhf(H[n]) / (1.0f+expf(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_scopy((int)N,&X[tN4],1,C,1); cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&X[tN4-N4],1,o,C,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&X[tN4-N4],1,o,I,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN4-N4],1,o,F,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&X[tN4-N4],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanhf(C[n])/(1.0f+expf(-I[n])) + H[n]/(1.0f+expf(-F[n])); X[tN4+n] = tanhf(H[n]) / (1.0f+expf(-O[n])); } } } } else { fprintf(stderr,"error in lstm_inplace_s: dim must be 0 or 1.\n"); return 1; } return 0; } int lstm_inplace_d (double *X, const double *Uc, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; const size_t N2 = 2*N, N3 = 3*N, N4 = 4*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T; size_t nT, tN, tN4; double *C, *I, *F, *O, *H; if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_inplace_d: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { H[n] = tanh(X[n]) / (1.0+exp(-X[N+n])); X[n] = tanh(H[n]) / (1.0+exp(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_dcopy((int)N,&X[tN4],1,C,1); cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&X[tN4-N4],1,o,C,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&X[tN4-N4],1,o,I,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN4-N4],1,o,F,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&X[tN4-N4],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); X[tN4+n] = tanh(H[n]) / (1.0+exp(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanh(X[nT]) / (1.0+exp(-X[NT+nT])); X[nT] = tanh(H[n]) / (1.0+exp(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,C,1); cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uc,(int)N,&X[t-1],(int)T,o,C,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,&X[t-1],(int)T,o,I,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,&X[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); X[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { nT = n*T; H[n] = tanh(X[nT]) / (1.0+exp(-X[NT+nT])); X[nT] = tanh(H[n]) / (1.0+exp(-X[NT3+nT])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,C,1); cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&X[t-1],(int)T,o,C,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&X[t-1],(int)T,o,I,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&X[t-1],(int)T,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); X[t+n*T] = tanh(H[n]) / (1.0+exp(-O[n])); } } } else { for (size_t n=0u; n<N; ++n) { H[n] = tanh(X[n]) / (1.0+exp(-X[N+n])); X[n] = tanh(H[n]) / (1.0+exp(-X[N3+n])); } for (size_t t=1; t<T; ++t) { tN = t*N; tN4 = 4*tN; cblas_dcopy((int)N,&X[tN4],1,C,1); cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uc,(int)N,&X[tN4-N4],1,o,C,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,&X[tN4-N4],1,o,I,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN4-N4],1,o,F,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,&X[tN4-N4],1,o,O,1); for (size_t n=0u; n<N; ++n) { H[n] = tanh(C[n])/(1.0+exp(-I[n])) + H[n]/(1.0+exp(-F[n])); X[tN4+n] = tanh(H[n]) / (1.0+exp(-O[n])); } } } } else { fprintf(stderr,"error in lstm_inplace_d: dim must be 0 or 1.\n"); return 1; } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4717177559, "avg_line_length": 47.7624309392, "ext": "c", "hexsha": "8d0bdf65267a24eae6794b4cb30669f88c71ec85", "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": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_path": "c/lstm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/nn", "max_issues_repo_path": "c/lstm.c", "max_line_length": 185, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_path": "c/lstm.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "num_tokens": 9609, "size": 25935 }
// Copyright 2018 Jeremy Mason // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! \file sb_desc.c //! Contains functions that actually calculate the spherical Bessel descriptors. #include <cblas.h> // dscal #include <math.h> // pow #include <stdint.h> // uint32_t #include <stdlib.h> // abort #include "sbessel.h" // _sbessel #include "sb_desc.h" #include "sb_matrix.h" // sb_mat_malloc #include "sb_structs.h" // sb_vec #include "sb_utility.h" // SB_CHK_ERR #include "sb_vector.h" // sb_vec_calloc #include "safety.h" // Lookup tables used in get_radial_basis. Built using function in `tables.c`. static const double _u_data[10152] = { #include "unl.tbl" }; static const size_t _u_n_max = 140; static const double _c1_data[10011] = { #include "c1.tbl" }; static const size_t _c1_n_max = 140; static const double _c2_data[10011] = { #include "c2.tbl" }; static const size_t _c2_n_max = 140; /// Calculates the radial basis functions for the spherical Bessel descriptors. /// Numerical efficiency depends heavily on the lookup tables defined above, /// allowing the function to be reduced to evaluating the recursion relations. /// /// # Parameters /// - `gnl`: pointer to a matrix to hold the result /// - `r_data`: radial coordinates of the atoms /// - `n_max`: defines the number of descriptors calculated /// - `l`: order of the spherical Bessel functions /// - `n_atom`: number of atoms in the environment /// - `rc`: cutoff radius for the environment /// /// # Returns /// A copy of `gnl` static sb_mat * get_radial_basis( sb_mat * gnl, double * r_data, uint32_t l, uint32_t n_atom, double rc) { // access lookup tables directly const double * u_data = _u_data + l * (2 * _u_n_max - l + 5) / 2; const double * c1_data = _c1_data + l * (2 * _c1_n_max - l + 3) / 2; const double * c2_data = _c2_data + l * (2 * _c2_n_max - l + 3) / 2; // gnl->n_cols const size_t n_cols = gnl->n_cols; // forward declaration of variables without initializations size_t n, a; double u0, u1, u2, d0, d1, e; double * g_data; // fnl built in gnl g_data = gnl->data; for (n = 0; n < n_cols; ++n) { for (a = 0; a < n_atom; ++a) { g_data[a] = c1_data[n] * _sbessel(l, r_data[a] * u_data[n]) - c2_data[n] * _sbessel(l, r_data[a] * u_data[n + 1]); } g_data += n_atom; } sb_mat_smul(gnl, pow(rc, -1.5)); // initialize quantities used for recursion u1 = SB_SQR(u_data[0]); u2 = SB_SQR(u_data[1]); d1 = 1.; // convert to gnl g_data = gnl->data; for (n = 1; n < n_cols; ++n) { u0 = u1; u1 = u2; u2 = SB_SQR(u_data[n + 1]); e = (u0 * u2) / ((u0 + u1) * (u1 + u2)); d0 = d1; d1 = 1. - e / d0; g_data += n_atom; cblas_dscal(n_atom, 1. / sqrt(d1), g_data, 1); cblas_daxpy(n_atom, sqrt(e / (d1 * d0)), g_data - n_atom, 1, g_data, 1); } return gnl; } /// Calculates spherical Bessel descriptors for the given atomic environment. /// `desc` should contain space for the descriptors, labelled by (n, l) and /// ordered lexicographically. `disp` should contain the relative Cartesian /// coordinates of the surrouding atoms in the format `[x_1, y_1, z_1, ...]`. /// `weights` should contain the weights used in the construction of the /// neighbor density function (e.g., `[1., ...]`). `restrict` is not used to /// help with portability. /// /// # Parameters /// - `desc`: pointer to an array to hold the result /// - `disp`: pointer to an array of the relative displacements /// - `weights`: pointer to an array of the atomic weights /// - `rc`: cutoff radius for the environment /// - `n_atom`: number of atoms in the environment /// - `n_max`: defines the number of descriptors calculated /// /// # Returns /// A copy of `desc` /// /// # Performance /// The following preprocessor definitions (usually in `safety.h`) enable /// various safety checks: /// - `SAFE_MEMORY`: `desc`, `disp`, and `weights` are not `NULL` /// - `SAFE_FINITE`: `rc` is nonnegative /// /// # Warning /// You are reponsible for ensuring that enough memory is allocated for the /// relevant arrays, and should expect undefined behavior otherwise. The /// lengths should be: /// - `desc`: `(n_max + 1) * (n_max + 2) / 2` /// - `disp`: at least `3 * n_atom` /// - `weights`: at least `n_atom` /// /// # Examples /// ``` /// #include <stddef.h> // size_t /// #include <stdio.h> // printf /// #include <stdint.h> // uint32_t /// #include "sb_desc.h" // sb_descriptors /// /// /// An example where `sb_descriptors()` is used to calculate the spherical /// /// Bessel descriptors for an atomic environment containing four atoms; the /// /// first and second descriptors should be `0.031870` and `0.138078`. /// int main(void) { /// // Sets the number of descriptors returned. /// uint32_t n_max = 4; /// /// // Allocate memory for the result. /// double desc[15] = { 0. }; /// /// // Number of atoms in the environment. /// uint32_t n_atom = 4; /// /// // Displacements to the surrounding atoms in Angstroms. /// // [x_1, y_1, z_1, ...] /// double disp[12] = { /// 1.3681827, -1.3103517, -1.3131874, /// -1.5151760, 1.3360077, -1.3477119, /// -1.3989598, -1.2973683, 1.3679189, /// 1.2279369, 1.3400378, 1.4797429 /// }; /// /// // Weights for the surrounding atoms. /// double weights[4] = { 1., 1., 1., 1. }; /// /// // Cutoff radius in Angstroms. /// double rc = 3.7711; /// /// sb_descriptors(desc, disp, weights, rc, n_atom, n_max); /// /// // Output the result /// // Labelled by (n, l), ordered lexicographically /// printf("SB descriptors:\n"); /// for (size_t a = 0; a < (n_max + 1) * (n_max + 2) / 2; ++a) /// printf("%.6f\n", desc[a]); /// /// printf("Completed successfully!\n"); /// } /// ``` double * sb_descriptors( double * desc_arr, double * disp_arr, const double * weights_arr, const double rc, const uint32_t n_atom, const uint32_t n_max) { #ifdef SAFE_MEMORY SB_CHK_ERR(!desc_arr, abort(), "sb_descriptors: desc cannot be NULL"); SB_CHK_ERR(!disp_arr, abort(), "sb_descriptors: disp cannot be NULL"); SB_CHK_ERR(!weights_arr, abort(), "sb_descriptors: weights cannot be NULL"); #endif #ifdef SAFE_FINITE SB_CHK_ERR(rc < 0., abort(), "sb_descriptors: rc cannot be negative"); #endif // Check that n_max is within limit defined by tables SB_CHK_ERR(n_max > _u_n_max || n_max > _c1_n_max || n_max > _c2_n_max, abort(), "sb_descriptors: n_max above limit defined by lookup tables"); // Convert raw pointers to sb_vec and sb_mat sb_mat * disp = malloc(sizeof(sb_mat)); SB_CHK_ERR(!disp, abort(), "sb_descriptors: failed to allocate disp"); disp->n_rows = 3; disp->n_cols = n_atom; disp->n_elem = 3 * n_atom; disp->data = disp_arr; double * data1, * data2, * data3; size_t a, b; // Calculate radial coordinates sb_vec * radius = sb_vec_calloc(n_atom, 'r'); data1 = disp->data; data2 = radius->data; for (a = 0; a < n_atom; ++a) { for (b = 0; b < 3; ++b) { *data2 += SB_SQR(data1[b]); } data1 += 3; data2 += 1; } sb_vec_sqrt(radius); // Normalize displacement vectors sb_mat_vdiv(disp, radius, 'c'); sb_vec_smul(radius, 1. / rc); // Calculate angle cosines sb_mat * gamma = sb_mat_malloc(n_atom, n_atom); sb_mat_mm_mul(gamma, disp, disp, "tn"); // Legendre polynomials sb_mat * * lp = malloc((n_max + 1) * sizeof(sb_mat *)); SB_CHK_ERR(!lp, abort(), "sb_descriptors: failed to allocate lp"); for (a = 0; a <= n_max; ++a) { lp[a] = sb_mat_malloc(n_atom, n_atom); } sb_mat_set_all(lp[0], 1.); sb_mat_memcpy(lp[1], gamma); for (a = 2; a <= n_max; ++a) { // l = a sb_mat_memcpy(lp[a], gamma); sb_mat_pmul(lp[a], lp[a - 1]); sb_mat_smul(lp[a], (2. * a - 1.) / (a - 1.)); sb_mat_psub(lp[a], lp[a - 2]); sb_mat_smul(lp[a], (a - 1.) / a); } // Include multiplier here to simplify calculation below for (a = 0; a <= n_max; ++a) { // l = a sb_mat_smul(lp[a], (2. * a + 1.) / 12.566370614359172); } // Radial basis functions sb_mat * * gnl = malloc((n_max + 1) * sizeof(sb_mat *)); SB_CHK_ERR(!gnl, abort(), "sb_descriptors: failed to allocate gnl"); for (a = 0; a <= n_max; ++a) { // l = a gnl[a] = sb_mat_malloc(n_atom, n_max - a + 1); get_radial_basis(gnl[a], radius->data, a, n_atom, rc); // Scale by the weights for (b = 0; b < n_atom; ++b) { cblas_dscal(gnl[a]->n_cols, weights_arr[b], gnl[a]->data + b, n_atom); } } // radius can be used for workspace data1 = radius->data; for (a = 0; a <= n_max; ++a) { // l = a data2 = lp[a]->data; data3 = gnl[a]->data; for (b = a; b <= n_max; ++b) { // n = b cblas_dgemv(CblasColMajor, CblasNoTrans, n_atom, n_atom, 1., data2, n_atom, data3 + (b - a) * n_atom, 1, 0., data1, 1); desc_arr[b * (b + 1) / 2 + a] = cblas_ddot(n_atom, data3 + (b - a) * n_atom, 1, data1, 1); } } // Free memory for (a = 0; a <= n_max; ++a) { SB_MAT_FREE_ALL(lp[a], gnl[a]); } SB_FREE_ALL(disp, lp, gnl); SB_VEC_FREE_ALL(radius); SB_MAT_FREE_ALL(gamma); return desc_arr; }
{ "alphanum_fraction": 0.6181144068, "avg_line_length": 32.1088435374, "ext": "c", "hexsha": "eb2e3fb03e33f5f3257392acb30e70bc6b9a5e4e", "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": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_forks_repo_licenses": [ "Apache-2.0", "MIT" ], "max_forks_repo_name": "harharkh/sb_desc", "max_forks_repo_path": "src/sb_desc.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_issues_repo_issues_event_max_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-10T06:53:41.000Z", "max_issues_repo_licenses": [ "Apache-2.0", "MIT" ], "max_issues_repo_name": "harharkh/sb_desc", "max_issues_repo_path": "src/sb_desc.c", "max_line_length": 96, "max_stars_count": 13, "max_stars_repo_head_hexsha": "e2fa146692aa4417e77366ce5ba85d9fdecc2a9c", "max_stars_repo_licenses": [ "Apache-2.0", "MIT" ], "max_stars_repo_name": "harharkh/sb_desc", "max_stars_repo_path": "src/sb_desc.c", "max_stars_repo_stars_event_max_datetime": "2021-12-19T20:06:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-08T22:34:35.000Z", "num_tokens": 3058, "size": 9440 }
/** * author: Jochen K"upper * created: Jan 2002 * file: pygsl/src/statisticsmodule.c * $Id: floatmodule.c,v 1.8 2004/03/24 08:40:45 schnizer Exp $ * * " */ #include <Python.h> #include <gsl/gsl_statistics.h> #include <pygsl/error_helpers.h> #include <pygsl/block_helpers.h> /* include real functions for default data-types (double in C) */ #define STATMOD_WEIGHTED #define STATMOD_APPEND_PY_TYPE(X) X ## Float32 #define STATMOD_APPEND_PYC_TYPE(X) X ## FLOAT #define STATMOD_FUNC_EXT(X, Y) X ## _float ## Y #define STATMOD_PY_AS_C PyFloat_AsDouble #define STATMOD_C_TYPE float #include "functions.c" /* initialization */ PyGSL_STATISTICS_INIT(float, "float") /* * Local Variables: * mode: c * c-file-style: "Stroustrup" * End: */
{ "alphanum_fraction": 0.7086092715, "avg_line_length": 17.9761904762, "ext": "c", "hexsha": "3866d0671ed4692897ae5064981bf6222d6a115e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_line_length": 65, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/floatmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 218, "size": 755 }
#include <stdio.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <semaphore.h> #include <signal.h> #include <sys/stat.h> #include <sys/times.h> #include <time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "circular_buffer.h" #include "colorprint.h" bool running = true; pid_t pid; circular_buffer *addr; double total_wait_time = 0.0; double total_blocked_time = 0.0; int total_consumed_messages = 0; sem_t *sem_mem_id; sem_t *sem_pro_id; sem_t *sem_con_id; void print_stats() { struct tms cpu_times; times(&cpu_times); printf_color(1, "[cyan]Tiempo de espera total:[/cyan] [yellow]%f s[/yellow]\n", total_wait_time); printf_color(1, "[cyan]Tiempo bloqueado total:[/cyan] [yellow]%f s[/yellow]\n", total_blocked_time); printf_color(1, "[cyan]Mensajes consumidos:[/cyan] [yellow]%i[/yellow]\n", total_consumed_messages); printf_color(1, "[cyan]Tiempo de usuario:[/cyan] [yellow]%ld[/yellow]\n", (long)cpu_times.tms_utime); printf_color(1, "[cyan]Tiempo de kernel:[/cyan] [yellow]%ld[/yellow]\n", (long)cpu_times.tms_stime); } void exit_by_id() { printf_color(1, "[bb][lw][info][/lw][/bb] Consumidor finalizado por ID (aleatorio). PID: %d.\n", pid); print_stats(); } void exit_by_finalizer() { printf_color(1, "[bb][lw][info][/lw][/bb] Consumidor cerrado por finalizador. PID: %d.\n", pid); print_stats(); } void intHandler(int dummy) { printf("Finalización forzada.\n"); addr->current_consumers--; print_stats(); exit(0); } int main(int argc, char *argv[]) { signal(SIGINT, intHandler); const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_ran_poisson(r, 5); int fd; time_t rawtime; struct tm *timeinfo; // Get argv if (argc < 3) { printf_color(1, "[red][br][lw][error][/lw][/br] No se han dado todos los argumentos necesarios.[/red]\n"); return -1; } char buffer_name[strlen(argv[1])]; strcpy(buffer_name, argv[1]); int wait_time = atoi(argv[2]); // Initialize strings for semaphore names char *sem_mem_name_base = "semaphore_memory_"; char *sem_con_name_base = "semaphore_consumers_"; char *sem_prod_name_base = "semaphore_producers_"; char sem_mem_name[strlen(buffer_name) + strlen(sem_mem_name_base)]; char sem_con_name[strlen(buffer_name) + strlen(sem_con_name_base)]; char sem_prod_name[strlen(buffer_name) + strlen(sem_prod_name_base)]; strcpy(sem_mem_name, sem_mem_name_base); strcat(sem_mem_name, buffer_name); strcpy(sem_con_name, sem_con_name_base); strcat(sem_con_name, buffer_name); strcpy(sem_prod_name, sem_prod_name_base); strcat(sem_prod_name, buffer_name); pid = getpid(); printf_color(1, "[bb][lw][info][/lw][/bb] Inicializando consumidor. PID: %d.\n", pid); printf_color(1, "[bb][lw][info][/lw][/bb] Nombre de buffer dado: %s.\n", buffer_name); printf_color(1, "[bb][lw][info][/lw][/bb] Tiempo de espera promedio: %i ms.\n\n", wait_time); // get shared memory file descriptor (NOT a file) fd = shm_open(buffer_name, O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { printf_color(1, "[br][lw][error][/lw][/br] [red]El buffer no se ha inicializado.[/red]\n"); return 10; } // Get shared memory size from file descriptor struct stat finfo; fstat(fd, &finfo); off_t shared_memory_size = finfo.st_size; // map shared memory to process address space addr = mmap(NULL, shared_memory_size, PROT_WRITE, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) { printf_color(1, "[br][lw][error][/lw][/br] [red]No se ha podido asignar suficiente memoria al proceso.[/red]\n"); return 30; } // Initialize semaphores sem_mem_id = sem_open(sem_mem_name, O_CREAT, 0600, 1); if (sem_mem_id == SEM_FAILED) { perror("SEMAPHORE_MEMORY_SYNC : [sem_open] Failed\n"); } sem_pro_id = sem_open(sem_prod_name, O_CREAT, 0600, addr->buffer_size); if (sem_pro_id == SEM_FAILED) { perror("SEMAPHORE_MEMORY_SYNC : [sem_open] Failed\n"); } sem_con_id = sem_open(sem_con_name, O_CREAT, 0600, 0); if (sem_con_id == SEM_FAILED) { perror("SEMAPHORE_MEMORY_SYNC : [sem_open] Failed\n"); } sem_wait(sem_mem_id); addr->current_consumers++; addr->total_consumers++; sem_post(sem_mem_id); int current_slot = 0; long long t = 0; while (running) { t = current_timestamp(); sem_wait(sem_con_id); sem_wait(sem_mem_id); // Add to total blocked time t = current_timestamp() - t; total_blocked_time = total_blocked_time + t / 1000.0; current_slot = addr->next_message_to_consume; cbuffer_message message = consume_message(addr); total_consumed_messages++; printf_color(1, "\n[bb]--------------------------------------------[/bb]\n"); printf_color(1, "[cyan]Consumidor PID:[/cyan] [yellow]%i[/yellow]\n", pid); printf_color(1, "[cyan]Recibido mensaje del productor PID:[/cyan] [yellow]%i[/yellow]\n", message.producer_id); printf_color(1, "[cyan]Leído del slot [yellow]%i[/yellow] del buffer[/cyan]\n", current_slot); printf_color(1, "[cyan]Contenido del mensaje:[/cyan] [yellow]%i[/yellow]\n", message.content); printf_color(1, "[cyan]Número mágico:[/cyan] [yellow]%i[/yellow]\n", message.random); time(&rawtime); timeinfo = localtime(&rawtime); printf_color(1, "[cyan]Hora actual:[/cyan] [yellow]%s[/yellow]", asctime(timeinfo)); printf_color(1, "[cyan]Consumidores conectados:[/cyan] [yellow]%i[/yellow]\n", addr->current_consumers); printf_color(1, "[cyan]Productores conectados:[/cyan] [yellow]%i[/yellow]\n", addr->current_producers); printf_color(1, "[bb]--------------------------------------------[/bb]\n\n"); sem_post(sem_mem_id); sem_post(sem_pro_id); //+1 al semaforo para que consuman if (message.type == KILL_CONSUMER) { running = false; sem_wait(sem_con_id); addr->current_consumers--; sem_post(sem_mem_id); exit_by_finalizer(); } else if (message.random == pid % 6) { running = false; sem_wait(sem_con_id); addr->current_consumers--; addr->consumers_killed_by_id++; sem_post(sem_mem_id); exit_by_id(); } else { int random_wait = gsl_ran_poisson(r, wait_time); // int random_wait = gsl_ran_exponential(r,2000); printf_color(1, "[green]*********** Esperando %d ms ***********[/green]\n", random_wait); total_wait_time = total_wait_time + random_wait / 1000.0; // sleep(random_wait/1000); usleep(random_wait * 1000); } } gsl_rng_free(r); return 0; }
{ "alphanum_fraction": 0.665407855, "avg_line_length": 30.0909090909, "ext": "c", "hexsha": "264344b3df8cb25c330f3b682966d72c7c82fbac", "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": "cc296bff171b36f8cb5db230e666507b7cd25fda", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JosephTico/semaforos-bozon-circular", "max_forks_repo_path": "consumer.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "cc296bff171b36f8cb5db230e666507b7cd25fda", "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": "JosephTico/semaforos-bozon-circular", "max_issues_repo_path": "consumer.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "cc296bff171b36f8cb5db230e666507b7cd25fda", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JosephTico/semaforos-bozon-circular", "max_stars_repo_path": "consumer.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1942, "size": 6620 }
// ************************************************ // rand_helpers.h // authors: Lee Howes and David B. Thomas // // Contains support code for the random number // generation necessary for initialising the // cuda simulations correctly. // // Ziggurat code taken from Marsaglia's // paper. // ************************************************ #ifndef __rand_helpers_h #define __rand_helpers_h // RNG choices #define USE_ZIGGURAT 0 #define USE_GSL 0 #include <math.h> #include <assert.h> #if USE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif unsigned Kiss() { static unsigned z=362436069, w=521288629, jsr=123456789, jcong=380116160; z=36969*(z&65535)+(z>>16); w=18000*(w&65535)+(w>>16); unsigned mwc=(z<<16)+w; jsr^=(jsr<<17); jsr^=(jsr>>13); jsr^=(jsr<<5); jcong=69069*jcong+1234567; return (mwc^jcong)+jsr; } double Rand() { unsigned long long x=Kiss(); x=(x<<32)|Kiss(); return x*5.4210108624275221703311375920553e-20; } #if USE_GSL const gsl_rng_type **t, **t0; gsl_rng *rng; bool initialised = false; void initRand() { gsl_rng_env_setup(); t0 = gsl_rng_types_setup (); printf ("Available generators:\n"); for (t = t0; *t != 0; t++) { printf ("%s\n", (*t)->name); if( strcmp("mt19937_1999", (*t)->name) == 0 ) break; } rng = gsl_rng_alloc (*t); } double RandN() { return gsl_ran_gaussian_ziggurat (rng, 1.0); } #else #if USE_ZIGGURAT /* Period parameters */ #define CPU_MT_N 624 #define CPU_MT_M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define CPU_MT_UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define CPU_MT_LOWER_MASK 0x7fffffffUL /* least significant r bits */ // MT unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4; static unsigned long mt[CPU_MT_N]; /* the array for the state vector */ static int mti=CPU_MT_N+1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void init_genrand(unsigned long s) { mt[0]= s & 0xffffffffUL; for (mti=1; mti<CPU_MT_N; mti++) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ void init_by_array(unsigned long init_key[], int key_length) { int i, j, k; init_genrand(19650218UL); i=1; j=0; k = (CPU_MT_N>key_length ? CPU_MT_N : key_length); for (; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + init_key[j] + j; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=CPU_MT_N) { mt[0] = mt[CPU_MT_N-1]; i=1; } if (j>=key_length) j=0; } for (k=CPU_MT_N-1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i>=CPU_MT_N) { mt[0] = mt[CPU_MT_N-1]; i=1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ } /* generates a random number on [0,0xffffffff]-interval */ unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= CPU_MT_N) { /* generate N words at one time */ int kk; if (mti == CPU_MT_N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for (kk=0;kk<CPU_MT_N-CPU_MT_M;kk++) { y = (mt[kk]&CPU_MT_UPPER_MASK)|(mt[kk+1]&CPU_MT_LOWER_MASK); mt[kk] = mt[kk+CPU_MT_M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<CPU_MT_N-1;kk++) { y = (mt[kk]&CPU_MT_UPPER_MASK)|(mt[kk+1]&CPU_MT_LOWER_MASK); mt[kk] = mt[kk+(CPU_MT_M-CPU_MT_N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[CPU_MT_N-1]&CPU_MT_UPPER_MASK)|(mt[0]&CPU_MT_LOWER_MASK); mt[CPU_MT_N-1] = mt[CPU_MT_M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } double genrand_real2(void) { return genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ } double genrand_real3(void) { return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } // ZIGGURAT #define abs(X) abs((int)X) //#define SHR3 (jz=jsr, jsr^=(jsr<<13), jsr^=(jsr>>17), jsr^=(jsr<<5),jz+jsr) #define SHR3 genrand_int32() //#define UNI (.5 + (signed) SHR3 * .2328306e-9) #define UNI genrand_real3() #define RandN() (hz=SHR3, iz=hz&127, (abs(hz)<kn[iz])? hz*wn[iz] : nfix()) static unsigned long iz,jz,jsr=123456789,kn[128],ke[256]; static long hz; static float wn[128],fn[128], we[256],fe[256]; float nfix(void) { /*provides RNOR if #define cannot */ const float r = 3.442620f; static float x, y; for(;;){ x=hz*wn[iz]; if(iz==0){ do{ x=-log(UNI)*0.2904764; y=-log(UNI); } while(y+y<x*x); return (hz>0)? r+x : -r-x; } if( fn[iz]+UNI*(fn[iz-1]-fn[iz]) < exp(-.5*x*x) ) return x; hz=SHR3; iz=hz&127;if(abs(hz)<kn[iz]) return (hz*wn[iz]); } } /*--------This procedure sets the seed and creates the tables------*/ void initRand() { unsigned long jsrseed = 123456789; const double m1 = 2147483648.0, m2 = 4294967296.; double dn=3.442619855899,tn=dn,vn=9.91256303526217e-3, q; double de=7.697117470131487, te=de, ve=3.949659822581572e-3; int i; jsr=jsrseed; /* Tables for RNOR: */ q=vn/exp(-.5*dn*dn); kn[0]=(dn/q)*m1; kn[1]=0; wn[0]=q/m1; wn[127]=dn/m1; fn[0]=1.; fn[127]=exp(-.5*dn*dn); for(i=126;i>=1;i--) { dn=sqrt(-2.*log(vn/dn+exp(-.5*dn*dn))); kn[i+1]=(dn/tn)*m1; tn=dn; fn[i]=exp(-.5*dn*dn); wn[i]=dn/m1; } /* Tables for REXP */ q = ve/exp(-de); ke[0]=(de/q)*m2; ke[1]=0; we[0]=q/m2; we[255]=de/m2; fe[0]=1.; fe[255]=exp(-de); for(i=254;i>=1;i--) { de=-log(ve/de+exp(-de)); ke[i+1]= (de/te)*m2; te=de; fe[i]=exp(-de); we[i]=de/m2; } init_by_array(init, length); } #else void initRand() { } double RandN() { static bool cached=false; static double cn; if(cached){ cached=false; return cn; } double a=std::sqrt(-2*std::log(Rand())); double b=6.283185307179586476925286766559*Rand(); cn=std::sin(b)*a; cached=true; return std::cos(b)*a; } #endif // USE_ZIGGURAT #endif // USE_GSL double MakeChi2Scale(unsigned N) { const double chic1 = std::sqrt ( std::sqrt (1.0 - 1.0 / N)); const double chic2 = std::sqrt (1.0 - chic1 * chic1); return chic1+chic2*RandN(); } #endif
{ "alphanum_fraction": 0.5435788917, "avg_line_length": 26.1626297578, "ext": "h", "hexsha": "6f267e05a594ab33a4d48d430337083056ea0a26", "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": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "fodinabor/HeCBench", "max_forks_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "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": "fodinabor/HeCBench", "max_issues_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "fodinabor/HeCBench", "max_stars_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2591, "size": 7561 }
#ifdef __cplusplus extern "C" { #endif #ifndef GSL_GAUSS #define GLS_GAUSS #include <math.h> #include <gsl_math.h> #include <gsl_cdf.h> double gsl_cdf_ugaussian_P (const double x); double gsl_cdf_ugaussian_Q (const double x); double gsl_cdf_gaussian_P (const double x, const double sigma); double gsl_cdf_gaussian_Q (const double x, const double sigma); #endif // GLS_GAUSS #ifdef __cplusplus } #endif
{ "alphanum_fraction": 0.7696078431, "avg_line_length": 17.7391304348, "ext": "h", "hexsha": "55e130263a986b2868d23da7ae76a51e7b72ceca", "lang": "C", "max_forks_count": 21, "max_forks_repo_forks_event_max_datetime": "2022-01-25T11:32:19.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-31T10:04:47.000Z", "max_forks_repo_head_hexsha": "4e8c9bee568211596cdc634d15600114e75d2619", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JamesLinus/wham", "max_forks_repo_path": "src/lib/gauss.h", "max_issues_count": 39, "max_issues_repo_head_hexsha": "4e8c9bee568211596cdc634d15600114e75d2619", "max_issues_repo_issues_event_max_datetime": "2021-09-07T17:55:14.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-04T23:14:59.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "JamesLinus/wham", "max_issues_repo_path": "src/lib/gauss.h", "max_line_length": 63, "max_stars_count": 66, "max_stars_repo_head_hexsha": "4e8c9bee568211596cdc634d15600114e75d2619", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zeeev/wham", "max_stars_repo_path": "src/lib/gauss.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T14:08:24.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-10T23:33:06.000Z", "num_tokens": 118, "size": 408 }
/** * @file batchf_zdotu_sub.c * * Part of API test for Batched BLAS routines. * * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date * * @precisions normal z -> c * **/ #include <cblas.h> #include "bblas.h" #define COMPLEX void batchf_zdotu_sub( const int n, BBLAS_Complex64_t const * const * x, const int incx, BBLAS_Complex64_t const * const * y, const int incy, BBLAS_Complex64_t *dotu, const int batch_count, int *info) { /* Local variables */ int first_index = 0; int batch_iter = 0; char func_name[15] = "batchf_zdotu"; /*initialize the result */ for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { dotu[batch_iter] = (BBLAS_Complex64_t)0.0; } /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if (n < 0) { xerbla_batch(func_name, BBLAS_ERR_N, first_index); info[first_index] = BBLAS_ERR_N; } if (incx < 1) { xerbla_batch(func_name, BBLAS_ERR_INCX, first_index); info[first_index] = BBLAS_ERR_INCX; } if (incy < 1) { xerbla_batch(func_name, BBLAS_ERR_INCY, first_index); info[first_index] = BBLAS_ERR_INCY; } /* Call CBLAS */ for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { cblas_zdotu_sub( n, (void *)x[batch_iter], incx, (void *)y[batch_iter], incy, &dotu[batch_iter]); /* Successful */ } /* End fixed size for loop */ info[first_index] = BBLAS_SUCCESS; } #undef COMPLEX
{ "alphanum_fraction": 0.6426271732, "avg_line_length": 19.6582278481, "ext": "c", "hexsha": "bddbfca8ded67b5e9a83974b8e9b24c033f9f1ec", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_path": "src/batchf_zdotu.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_path": "src/batchf_zdotu.c", "max_line_length": 61, "max_stars_count": 3, "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_path": "src/batchf_zdotu.c", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "num_tokens": 509, "size": 1553 }
/* / / adkGSL.c / / homebrewed addons to gsl */ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_statistics.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include "../extern/include/f2c.h" #include "../extern/include/blaswrap.h" #include "../extern/include/clapack.h" //#include <vecLib/cblas.h> //#include <accelerate/accelerate.h> #include "adkGSL.h" #define SUM_LOG_THRESHOLD -10 //gsl_matrix_covariance-- computes sample covariance matrix and stores it in matrix cov void gsl_matrix_covariance(gsl_matrix *data, gsl_matrix *cov){ gsl_vector_view a, b; size_t i, j; double v; for (i = 0; i < data->size2; i++) { for (j = 0; j < data->size2; j++) { a = gsl_matrix_column (data, i); b = gsl_matrix_column (data, j); v = gsl_stats_covariance (a.vector.data, a.vector.stride, b.vector.data, b.vector.stride, a.vector.size); gsl_matrix_set (cov, i, j, v); } } } /*gsl_vector_includes() - returns 1 or 0 depending on result */ int gsl_vector_includes(gsl_vector *aVec, double aValue){ int i; for(i = 0; i < aVec->size; i++){ if (gsl_vector_get(aVec, i) == aValue){ return(1); } } return(0); } double gsl_vector_sum(gsl_vector *aVec, int aVecSize){ double sum; int i; sum = 0; for (i = 0; i < aVecSize; i++){ sum += gsl_vector_get(aVec, i); } return sum; } double gsl_vector_dot_product(gsl_vector *vec1, gsl_vector *vec2){ int i; double dot = 0.0; assert(vec1->size == vec2->size); for(i = 0; i < vec1->size; i++){ dot += gsl_vector_get(vec1, i) * gsl_vector_get(vec2, i); } return(dot); } void gsl_vector_outer_product(gsl_vector *vec1, gsl_vector *vec2, gsl_matrix *result){ int i,j; assert(vec1->size == result->size1 || vec2->size == result->size2); for(i = 0; i < vec1->size; i++){ for(j = 0; j < vec2->size; j++){ gsl_matrix_set(result,i,j,gsl_vector_get(vec1,i) * gsl_vector_get(vec2,j)); } } } double gsl_matrix_row_sum(gsl_matrix *mat, int iRow, int rowSize){ gsl_vector_view aRow; double sum = 0; int i; aRow = gsl_matrix_row(mat, iRow); for (i = 0; i< rowSize; i++){ sum += gsl_vector_get(&aRow.vector, i); } return sum; } /* efficiently compute log of sum of values, which themselves are stored as logs: that is, return log(sum_i exp(l_i)). The largest of the elements of l (call it maxval) is factored out, so that log(sum_i(exp(l_i))) = maxval + log(1 + sum_i(exp(l_i-maxval))), where the new sum is taken over 2 <= i < n. All of the quantities in the exp must be negative, and those smaller than some reasonable threshold can be ignored. [Thanks to David Haussler for showing me this trick]. This code was adapted from code kindly given to me by Adam Siepel */ double log_sum(gsl_vector *vec) { double maxval, expsum; int k; if (vec->size > 1){ gsl_sort_vector(vec); gsl_vector_reverse(vec); } maxval = gsl_vector_get(vec, 0); expsum = 1; k = 1; while (k < vec->size && gsl_vector_get(vec, k) - maxval > SUM_LOG_THRESHOLD){ expsum += exp(gsl_vector_get(vec, k++) - maxval); } return maxval + log(expsum); } /*the following methods are wrappers for use with LAPACK */ void set_lapack_entry(double *A, int i, int j, int nrows, double val){ A[j*nrows+i] = val; } double get_lapack_entry(double *a, int i, int j,int nrows){ printf("ha"); return a[j*nrows+i]; } /*this is meant to be a conversion utility */ double *gsl_matrix_2_lapack(gsl_matrix *m){ double *lapack_mat; int i, j; lapack_mat = malloc(m->size1 * m->size2 * sizeof(double)); for(i = 0; i < m->size1; i++){ for(j = 0; j < m->size2; j++){ set_lapack_entry(lapack_mat, i, j,m->size1, gsl_matrix_get(m, i, j)); } } return lapack_mat; } gsl_matrix *lapack_2_gsl_matrix(double *A, int nrows, int ncols){ int i, j; gsl_matrix *new; new = gsl_matrix_alloc(nrows,ncols); for(i=0;i<nrows;i++){ for(j=0;j<ncols;j++){ gsl_matrix_set(new,i,j,get_lapack_entry(A,i,j,nrows)); } } return new; } gsl_matrix *gsl_matrix_power_logs(gsl_matrix *aMatrix, int power){ gsl_matrix *powerMat, *logMat; int i, j; double x; powerMat = gsl_matrix_power(aMatrix, power); logMat = gsl_matrix_alloc(aMatrix->size1, aMatrix->size2); for(i = 0; i < aMatrix->size1; i++){ for(j = 0; j < aMatrix->size2; j++){ x = gsl_matrix_get(powerMat, i, j); gsl_matrix_set(logMat, i, j, log(x)); } } gsl_matrix_free(powerMat); return(logMat); } gsl_matrix *gsl_matrix_power(gsl_matrix *aMatrix, int power){ gsl_matrix *revect, *levect; double *dataMat, *wr, *wi, *vl, *vr, *aMat, *bMat, *cMat, *dMat, *work; int lwork, i, j, n ,info; assert(aMatrix->size1 == aMatrix->size2); n = aMatrix->size1; if (power == 1){ gsl_matrix * solMat = gsl_matrix_alloc(n, n); for(i=0; i < n; i++){ for(j = 0; j< n; j++){ gsl_matrix_set(solMat, i, j, gsl_matrix_get(aMatrix,i,j)); } } return(solMat); } //allocate space for eigenvector matrices, and other result holders levect = gsl_matrix_alloc(n, n); revect = gsl_matrix_alloc(n, n); wr = malloc(n * sizeof(double)); wi = malloc(n * sizeof(double)); vl = malloc(n * n * sizeof(double)); vr = malloc(n * n * sizeof(double)); lwork = 20 * n; work = malloc(lwork * sizeof(double)); //move data to LAPACK (col major) format dataMat = gsl_matrix_2_lapack(aMatrix); //run LAPACK routine dgeev #ifdef OSX dgeev('V','V',n, dataMat, n, wr, wi, vl, n, vr, n, work, lwork); #else dgeev_('V','V',n, dataMat, n, wr, wi, vl, n, vr, n, work, lwork, info); #endif //collect eigenvalues into matrices for(i=0; i < n; i++){ for(j = 0; j< n; j++){ gsl_matrix_set(revect, i, j, vr[j*2+i]); gsl_matrix_set(levect, j, i, vl[j*2+i]); } } /* rescale such that revect and levect are inverses */ /* see Press et al. (Numerical Recipes) for a very clear explanation of the relationship between the left and right eigenvectors */ for(i = 0; i < n; i++){ double dotProd = 0.0; /* compute dot product of row i in levect and col i in revect */ for(j = 0; j< n; j++){ dotProd += gsl_matrix_get(levect, i, j) * gsl_matrix_get(revect,j,i); } /* now rescale levect */ for(j = 0; j< n; j++){ double old = gsl_matrix_get(levect, i, j); double scaled = old / dotProd; gsl_matrix_set(levect, i, j, scaled); } } //prepare for matrix multiplication gsl_matrix * solMat = gsl_matrix_alloc(n, n); gsl_matrix * diag = gsl_matrix_alloc(n, n); gsl_matrix_set_all(diag, 0); for(j = 0; j< n; j++){ gsl_matrix_set(diag, j,j, pow(wr[j],power)); } aMat = gsl_matrix_2_lapack(diag); bMat = gsl_matrix_2_lapack(revect); cMat = malloc(n * n * sizeof(double)); //compute a^t = s^-1 * diag^t * s cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0, aMat, n, bMat, n, 0.0, cMat, n); free(bMat); bMat = gsl_matrix_2_lapack(levect); dMat = malloc(n * n * sizeof(double)); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n, 1, cMat, n, bMat, n, 0.0, dMat, n); //put results into gsl_matrix for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ gsl_matrix_set(solMat, i, j, dMat[j*n+i]); } } //cleanup gsl_matrix_free(levect); gsl_matrix_free(revect); gsl_matrix_free(diag); free(work); free(vl); free(vr); free(wi); free(wr); free(aMat); free(bMat); free(cMat); free(dMat); free(dataMat); return(solMat); } //returns the trace of a matrix-- sum of diag double gsl_matrix_trace(gsl_matrix *x){ int i; double sum = 0.0; for(i=0;i<x->size1;i++){ sum += gsl_matrix_get(x,i,i); } return(sum); } //copies the lower triangle of src in to dest, sets others to zero void gsl_matrix_lower_tri_copy(gsl_matrix *src, gsl_matrix *dest){ int i, j; assert(src->size1 == dest->size1); assert(src->size2 == dest->size2); for(i = 0; i < src->size1; i++){ for(j = 0; j < src->size2; j++){ if(i<=j){ gsl_matrix_set(dest,i,j,gsl_matrix_get(src,i,j)); } else{ gsl_matrix_set(dest,i,j,0.0); } } } } //copies the upper triangle of src in to dest, sets others to zero void gsl_matrix_upper_tri_copy(gsl_matrix *src, gsl_matrix *dest){ int i, j; assert(src->size1 == dest->size1); assert(src->size2 == dest->size2); for(i = 0; i < src->size1 ;i++){ for(j = 0; j < src->size2; j++){ if(i>=j){ gsl_matrix_set(dest,i,j,gsl_matrix_get(src,i,j)); } else{ gsl_matrix_set(dest,i,j,0.0); } } } } //zeros out everything but lower tri-- in place void gsl_matrix_lower_tri(gsl_matrix *x){ int i, j; for(i = 0; i < x->size1; i++){ for(j = 0; j < x->size2; j++){ if(i>j) gsl_matrix_set(x,i,j,0.0); } } } //zeros out everything but upper tri-- in place void gsl_matrix_upper_tri(gsl_matrix *x){ int i, j; for(i = 0; i < x->size1; i++){ for(j = 0; j < x->size2; j++){ if(i<j) gsl_matrix_set(x,i,j,0.0); } } } //fillMatrixFromArray-- fills up a matrix based on nrow and ncol given *double void fillMatrixFromArray(double *numbers, gsl_matrix *dest, int nrow, int ncol){ int i, j, count = 0; assert(nrow == dest->size1); for(i = 0; i < nrow; i++){ for(j=0;j<ncol;j++){ gsl_matrix_set(dest,i,j,numbers[count++]); } } } //fillMatrixFromArray-- fills up a matrix based on nrow and ncol given gsl_vector void fillMatrixFromVector(gsl_vector *numbers, gsl_matrix *dest, int nrow, int ncol){ int i, j, count = 0; assert(nrow == dest->size1); for(i = 0; i < nrow; i++){ for(j=0;j<ncol;j++){ gsl_matrix_set(dest,i,j,gsl_vector_get(numbers,count++)); } } } //fillArrayFromMatrix-- fills up a vector based gsl_matrix void fillArrayFromMatrix(gsl_matrix *src, gsl_vector *dest){ int i, j, count = 0; for(i = 0; i < src->size1; i++){ for(j=0;j<src->size2;j++){ gsl_vector_set(dest,count++, gsl_matrix_get(src,i,j)); } } } //fillMatrixFromCholArray-- fills up a matrix based on nrow and ncol given arraay // representing the Cholesky decomp void fillMatrixFromCholArray(double *numbers, gsl_matrix *dest, int nrow, int ncol){ int i, j, count = 0; for(i = 0; i < nrow; i++){ for(j=0;j<ncol;j++){ if(i<=j)gsl_matrix_set(dest,i,j,numbers[count++]); } } } void fillCholArrayFromMatrix(gsl_matrix *src, gsl_vector *dest){ int i, j, count = 0; for(i = 0; i < src->size1; i++){ for(j=0;j<src->size2;j++){ if(i<=j){ gsl_vector_set(dest,count++, gsl_matrix_get(src,i,j)); //printf("i:%d j: %d val: %f\n",i,j,gsl_matrix_get(src,i,j) ); } } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef OSX /*some wrappers for use with the OS X vecLib LAPACK implementation */ /*wrapper for the lapack eigensystem routine dgeev_*/ int dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl, int ldvl,double *vr, int ldvr, double *work, int lwork){ __CLPK_integer _n, _lda, _ldvl, _ldvr, _lwork, info; _n = (__CLPK_integer) n; _lda = (__CLPK_integer) lda; _ldvl =(__CLPK_integer) ldvl; _ldvr =(__CLPK_integer) ldvr; _lwork =(__CLPK_integer) lwork; dgeev_(&jobvl, &jobvr, &_n, a, &_lda, wr, wi, vl, &_ldvl, vr, &_ldvr, work, &_lwork, &info); return info; } /*wrapper for the lapack eigensystem routine dsyev_ int dsyev(char jobvl, char uplo, int n, double *a, int lda, double *w, double *work, int lwork){ __CLPK_integer _n, _lda, _lwork, info; _n = (__CLPK_integer) n; _lda = (__CLPK_integer) lda; _lwork =(__CLPK_integer) lwork; dsyev_(&jobvl, &uplo, &_n, a, &_lda, w, work, &_lwork, &info); return info; } int dgehrd(int n, int ilo, int ihi, double *a, int lda, double *tau, double *work, int lwork){ __CLPK_integer _n, _ilo, _ihi, _lda, _lwork, info; _n = (__CLPK_integer) n; _lda = (__CLPK_integer) lda; _lwork =(__CLPK_integer) lwork; _ilo =(__CLPK_integer) ilo; _ihi =(__CLPK_integer) ihi; dgehrd_(&_n, &_ilo, &_ihi, a, &_lda, tau, work, &_lwork, &info); return info; } int dgebal(char job, int n, double *a, int lda, int ilo, int ihi, double *scale){ __CLPK_integer _n, _ilo, _ihi, _lda, info; _n = (__CLPK_integer) n; _lda = (__CLPK_integer) lda; _ilo =(__CLPK_integer) ilo; _ihi =(__CLPK_integer) ihi; dgebal_(&job, &_n, a, &_lda, &_ilo, &_ihi, scale, &info); return info; } int dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork){ __CLPK_integer _n, _ilo, _ihi, _ldh, _ldz, _lwork, info; _n = (__CLPK_integer) n; _ldh = (__CLPK_integer) ldh; _ilo =(__CLPK_integer) ilo; _ihi =(__CLPK_integer) ihi; _ldz = (__CLPK_integer) ldz; _lwork = (__CLPK_integer) lwork; dhseqr_(&job, &compz, &_n, &_ilo, &_ihi, h, &_ldh, wr, wi, z,&_ldz, work, &_lwork, &info); return info; } #endif int dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl, int ldvl,double *vr, int ldvr, double *work, int lwork){ long int _n, _lda, _ldvl, _ldvr, _lwork, info; _n = n; _lda = lda; _ldvl = ldvl; _ldvr = ldvr; _lwork = lwork; dgeev_(&jobvl, &jobvr, &_n, a, &_lda, wr, wi, vl, &_ldvl, vr, &_ldvr, work, &_lwork, &info); return info; } int dsyev(char jobvl, char uplo, int n, double *a, int lda, double *w, double *work, int lwork){ long int _n, _lda, _lwork, info; _n = n; _lda = lda; _lwork = lwork; dsyev_(&jobvl, &uplo, &_n, a, &_lda, w, work, &_lwork, &info); return info; } int dgehrd(int n, int ilo, int ihi, double *a, int lda, double *tau, double *work, int lwork){ long int _n, _ilo, _ihi, _lda, _lwork, info; _n = n; _lda = lda; _lwork = lwork; _ilo = ilo; _ihi = ihi; dgehrd_(&_n, &_ilo, &_ihi, a, &_lda, tau, work, &_lwork, &info); return info; } int dgebal(char job, int n, double *a, int lda, int ilo, int ihi, double *scale){ long int _n, _ilo, _ihi, _lda, info; _n = n; _lda = lda; _ilo = ilo; _ihi = ihi; dgebal_(&job, &_n, a, &_lda, &_ilo, &_ihi, scale, &info); return info; } int dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork){ long int _n, _ilo, _ihi, _ldh, _ldz, _lwork, info; _n = n; _ldh = ldh; _ilo = ilo; _ihi = ihi; _ldz = ldz; _lwork = lwork; dhseqr_(&job, &compz, &_n, &_ilo, &_ihi, h, &_ldh, wr, wi, z,&_ldz, work, &_lwork, &info); return info; } */ #endif
{ "alphanum_fraction": 0.6271932796, "avg_line_length": 26.2651245552, "ext": "c", "hexsha": "dafcbca4c393de44f41359ffb1daced097eab7cd", "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": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "hmm/adkGSL.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_path": "hmm/adkGSL.c", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "hmm/adkGSL.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5162, "size": 14761 }
/***************************************** Emitting C Generated Code *******************************************/ #include <cblas.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <stdbool.h> /**************** Snippet ****************/ void Snippet(int x0) { int x1[6] = { 1, 2, 3, 4, 5, 6 }; int x2[6] = { 6, 5, 4, 3, 2, 1 }; int* x3 = (int*)malloc(6 * sizeof(int)); int x4 = 0; while (x4 != 6) { int x5 = x4; x3[x5] = x1[x5] + x2[x5]; x4 = x4 + 1; } int x6 = 0; while (x6 != 6) { printf("%d ", x3[x6]); x6 = x6 + 1; } int* x7 = (int*)malloc(6 * sizeof(int)); int x8 = 0; while (x8 != 6) { int x9 = x8; x7[x9] = x1[x9] - x2[x9]; x8 = x8 + 1; } int x10 = 0; while (x10 != 6) { printf("%d ", x7[x10]); x10 = x10 + 1; } int* x11 = (int*)malloc(6 * sizeof(int)); int x12 = 0; while (x12 != 6) { int x13 = x12; x11[x13] = x1[x13] * x2[x13]; x12 = x12 + 1; } int x14 = 0; while (x14 != 6) { printf("%d ", x11[x14]); x14 = x14 + 1; } int* x15 = (int*)malloc(6 * sizeof(int)); int x16 = 0; while (x16 != 6) { int x17 = x16; x15[x17] = x1[x17] / x2[x17]; x16 = x16 + 1; } int x18 = 0; while (x18 != 6) { printf("%d ", x15[x18]); x18 = x18 + 1; } } /***************************************** End of C Generated Code *******************************************/ int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s <arg>\n", argv[0]); return 0; } Snippet(atoi(argv[1])); return 0; }
{ "alphanum_fraction": 0.410976388, "avg_line_length": 21.4657534247, "ext": "c", "hexsha": "abfc0b60b3db70beec8808321197be94a3c0649c", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2022-02-03T04:45:52.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-20T12:16:10.000Z", "max_forks_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Shangyint/lms-clean", "max_forks_repo_path": "src/out/transformer/tensor2/eleBinary.check.c", "max_issues_count": 30, "max_issues_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_issues_repo_issues_event_max_datetime": "2022-01-14T21:22:03.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-10T01:17:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Shangyint/lms-clean", "max_issues_repo_path": "src/out/transformer/tensor2/eleBinary.check.c", "max_line_length": 44, "max_stars_count": 50, "max_stars_repo_head_hexsha": "46dcf45b297bb537ce90d9c787dbf3700b47d54c", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Shangyint/lms-clean", "max_stars_repo_path": "src/out/transformer/tensor2/eleBinary.check.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T04:14:18.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-19T17:19:00.000Z", "num_tokens": 620, "size": 1567 }
/* -*- linux-c -*- */ /* fewbody.c Copyright (C) 2002-2004 John M. Fregeau 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 */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/times.h> #include <unistd.h> #include <getopt.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "fewbody.h" int fb_debug = 0; fb_ret_t fewbody(fb_input_t input, fb_hier_t *hier, double *t) { int i, j, k, status, done=0, forceclassify=0, restart, restep; long clk_tck; double s, slast, sstop=FB_SSTOP, tout, h=FB_H, *y, texpand, tnew, R[3]; double Ei, E, Lint[3], Li[3], L[3], DeltaL[3]; double s2, s2prev=GSL_POSINF, s2prevprev=GSL_POSINF, s2minprev=GSL_POSINF, s2max=0.0, s2min; struct tms firsttimebuf, currtimebuf; clock_t firstclock, currclock; fb_hier_t phier; fb_ret_t retval; fb_nonks_params_t nonks_params; fb_ks_params_t ks_params; char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH], logentry[FB_MAX_LOGENTRY_LENGTH]; const gsl_odeiv_step_type *ode_type=gsl_odeiv_step_rk8pd; gsl_odeiv_step *ode_step; gsl_odeiv_control *ode_control; gsl_odeiv_evolve *ode_evolve; gsl_odeiv_system ode_sys; /* initialize a few things */ fb_init_hier(hier); retval.iclassify = 0; retval.Rmin = FB_RMIN; retval.Rmin_i = -1; retval.Rmin_j = -1; retval.Nosc = 0; strncpy(logentry, input.firstlogentry, FB_MAX_LOGENTRY_LENGTH); /* set up the perturbation tree, initially flat */ phier.nstarinit = hier->nstar; phier.nstar = hier->nstar; fb_malloc_hier(&phier); fb_init_hier(&phier); for (i=0; i<phier.nstar; i++) { fb_objcpy(&(phier.hier[phier.hi[1]+i]), &(hier->hier[hier->hi[1]+i])); } /* initialize GSL integration routine */ if (input.ks) { ode_step = gsl_odeiv_step_alloc(ode_type, 8 * (hier->nstar * (hier->nstar - 1) / 2) + 1); ode_control = gsl_odeiv_control_y_new(input.absacc, input.relacc); ode_evolve = gsl_odeiv_evolve_alloc(8 * (hier->nstar * (hier->nstar - 1) / 2) + 1); ode_sys.function = fb_ks_func; ode_sys.jacobian = NULL; ode_sys.dimension = 8 * (hier->nstar * (hier->nstar - 1) / 2) + 1; ode_sys.params = &ks_params; } else { ode_step = gsl_odeiv_step_alloc(ode_type, 6 * hier->nstar); ode_control = gsl_odeiv_control_y_new(input.absacc, input.relacc); ode_evolve = gsl_odeiv_evolve_alloc(6 * hier->nstar); ode_sys.function = fb_nonks_func; ode_sys.jacobian = fb_nonks_jac; ode_sys.dimension = 6 * hier->nstar; ode_sys.params = &nonks_params; } /* set parameters for integrator */ if (input.ks) { ks_params.nstar = hier->nstar; ks_params.kstar = ks_params.nstar*(ks_params.nstar-1)/2; fb_malloc_ks_params(&ks_params); fb_init_ks_params(&ks_params, *hier); } else { nonks_params.nstar = hier->nstar; fb_malloc_nonks_params(&nonks_params); fb_init_nonks_params(&nonks_params, *hier); } /* set the initial conditions in y_i */ if (input.ks) { y = fb_malloc_vector(8*ks_params.kstar+1); y[0] = *t; fb_euclidean_to_ks(phier.obj, y, ks_params.nstar, ks_params.kstar); s = 0.0; } else { y = fb_malloc_vector(6*nonks_params.nstar); fb_euclidean_to_nonks(phier.obj, y, nonks_params.nstar); s = *t; } /* store the initial energy and angular momentum */ Ei = fb_petot(&(hier->hier[hier->hi[1]]), hier->nstar) + fb_ketot(&(hier->hier[hier->hi[1]]), hier->nstar) + fb_einttot(&(hier->hier[hier->hi[1]]), hier->nstar); fb_angmom(&(hier->hier[hier->hi[1]]), hier->nstar, Li); fb_angmomint(&(hier->hier[hier->hi[1]]), hier->nstar, Lint); for (i=0; i<3; i++) { Li[i] += Lint[i]; } /* integrate along */ fb_dprintf("fewbody: integrating...\n"); done = 0; retval.count = 0; tout = *t; texpand = 0.0; clk_tck = sysconf(_SC_CLK_TCK); firstclock = times(&firsttimebuf); retval.tcpu = 0.0; while (*t < input.tstop && retval.tcpu < input.tcpustop && !done) { /* take one step */ slast = s; status = gsl_odeiv_evolve_apply(ode_evolve, ode_control, ode_step, &ode_sys, &s, sstop, &h, y); if (status != GSL_SUCCESS) { break; } /* set objects' positions and velocities in phier */ if (input.ks) { tnew = y[0]; fb_ks_to_euclidean(y, phier.obj, ks_params.nstar, ks_params.kstar); } else { tnew = s; fb_nonks_to_euclidean(y, phier.obj, nonks_params.nstar); } /* restart: do we need to restart the integrator? restep: do we need to repeat the last integration step? forceclassify: do we need to force a call to the classify() routine? */ restart = 0; restep = 0; forceclassify = 0; /* see if we need to expand or collapse the perturbation hierarchy */ if (fb_expand(&phier, tnew, input.tidaltol)) { texpand = tnew; s = slast; restart = 1; restep = 1; for (i=0; i<hier->nstar; i++) { for (k=0; k<3; k++) { phier.hier[phier.hi[1]+i].x[k] = hier->hier[hier->hi[1]+i].x[k]; phier.hier[phier.hi[1]+i].v[k] = hier->hier[hier->hi[1]+i].v[k]; } } fb_elkcirt(&phier, *t); } else if (tnew >= texpand && fb_collapse(&phier, tnew, input.tidaltol)) { *t = tnew; /* if there is only one object, then it's stable---force classify() */ if (phier.nobj == 1) { forceclassify = 1; } else { restart = 1; } } else { *t = tnew; } /* if we're not repeating the previous integration step, then do physics */ if (!restep) { /* trickle down so updated information is in hier */ fb_trickle(&phier, *t); for (i=0; i<hier->nstar; i++) { for (k=0; k<3; k++) { hier->hier[hier->hi[1]+i].x[k] = phier.hier[phier.hi[1]+i].x[k]; hier->hier[hier->hi[1]+i].v[k] = phier.hier[phier.hi[1]+i].v[k]; } } /* update Rmin (closest approach) */ for (i=0; i<hier->nstar-1; i++) { for (j=i+1; j<hier->nstar; j++) { for (k=0; k<3; k++) { R[k] = hier->hier[hier->hi[1]+i].x[k] - hier->hier[hier->hi[1]+j].x[k]; } if (fb_mod(R) < retval.Rmin) { retval.Rmin = fb_mod(R); retval.Rmin_i = i; retval.Rmin_j = j; } } } /* do physical collisions */ if (fb_collide(hier, input.fexp)) { /* initialize phier to a flat tree */ phier.nstar = hier->nstar; fb_init_hier(&phier); for (i=0; i<phier.nstar; i++) { fb_objcpy(&(phier.hier[phier.hi[1]+i]), &(hier->hier[hier->hi[1]+i])); } /* if there is only one object, then it's stable---force classify() */ if (phier.nobj == 1) { restart = 0; forceclassify = 1; } else { restart = 1; } } /* check for oscillations in s^2 */ /* first calculate s^2 */ s2 = 0.0; for (i=0; i<hier->nstar-1; i++) { for (j=i+1; j<hier->nstar; j++) { for (k=0; k<3; k++) { s2 += fb_sqr(hier->hier[hier->hi[1]+i].x[k] - hier->hier[hier->hi[1]+j].x[k]); } } } /* local min */ if (s2 > s2prev && s2prev < s2prevprev) { s2min = s2prev; /* increment Nosc if there is a valid oscillation */ if (s2max >= 2.0*s2minprev && s2max >= 2.0*s2min) { retval.Nosc++; fb_dprintf("fewbody: oscillation in s^2 detected: s2max/s2minprev=%g s2max/s2min=%g: Nosc=%d\n", s2max/s2minprev, s2max/s2min, retval.Nosc); s2minprev = s2min; } else { fb_dprintf("fewbody: oscillation in s^2 not big enough: s2max/s2minprev=%g s2max/s2min=%g\n", s2max/s2minprev, s2max/s2min); /* that pesky first min... */ if (s2max == 0.0) { s2minprev = s2min; } } } /* local max: just set value and wait for next min */ if (s2 < s2prev && s2prev > s2prevprev) { s2max = s2prev; } /* set previous values */ s2prevprev = s2prev; s2prev = s2; /* see if we're done */ if (retval.count % input.ncount == 0 || forceclassify) { status = fb_classify(hier, *t, input.tidaltol); retval.iclassify++; fb_dprintf("fewbody: current status: t=%.6g %s (%s)\n", *t, fb_sprint_hier(*hier, string1), fb_sprint_hier_hr(*hier, string2)); snprintf(&(logentry[strlen(logentry)]), FB_MAX_LOGENTRY_LENGTH-strlen(logentry), " current status: t=%.6g %s (%s)\n", *t, fb_sprint_hier(*hier, string1), fb_sprint_hier_hr(*hier, string2)); if (status) { done = 1; } } /* print stuff if necessary */ if (input.Dflag == 1 && (*t >= tout || done)) { tout = *t + input.dt; fb_print_story(&(hier->hier[hier->hi[1]]), hier->nstar, *t, logentry); } } /* restart integrator if necessary */ if (restart) { fb_dprintf("fewbody: restarting integrator: nobj=%d count=%ld\n", phier.nobj, retval.count); fb_free_vector(y); if (input.ks) { fb_free_ks_params(ks_params); ks_params.nstar = phier.nobj; ks_params.kstar = ks_params.nstar*(ks_params.nstar-1)/2; fb_malloc_ks_params(&ks_params); fb_init_ks_params(&ks_params, phier); y = fb_malloc_vector(8*ks_params.kstar+1); y[0] = *t; fb_euclidean_to_ks(phier.obj, y, ks_params.nstar, ks_params.kstar); } else { fb_free_nonks_params(nonks_params); nonks_params.nstar = phier.nobj; fb_malloc_nonks_params(&nonks_params); fb_init_nonks_params(&nonks_params, phier); y = fb_malloc_vector(6*nonks_params.nstar); fb_euclidean_to_nonks(phier.obj, y, nonks_params.nstar); } /* and re-allocate integrator */ gsl_odeiv_evolve_free(ode_evolve); gsl_odeiv_control_free(ode_control); gsl_odeiv_step_free(ode_step); /* re-initialize integrator */ if (input.ks) { ode_step = gsl_odeiv_step_alloc(ode_type, 8*ks_params.kstar+1); ode_control = gsl_odeiv_control_y_new(input.absacc, input.relacc); ode_evolve = gsl_odeiv_evolve_alloc(8*ks_params.kstar+1); ode_sys.dimension = 8*ks_params.kstar+1; } else { ode_step = gsl_odeiv_step_alloc(ode_type, 6*nonks_params.nstar); ode_control = gsl_odeiv_control_y_new(input.absacc, input.relacc); ode_evolve = gsl_odeiv_evolve_alloc(6*nonks_params.nstar); ode_sys.dimension = 6*nonks_params.nstar; } } /* update variables that change on every integration step */ retval.count++; currclock = times(&currtimebuf); retval.tcpu = ((double) (currtimebuf.tms_utime + currtimebuf.tms_stime - firsttimebuf.tms_utime - firsttimebuf.tms_stime))/((double) clk_tck); } /* do final classification */ retval.retval = fb_classify(hier, *t, input.tidaltol); retval.iclassify++; fb_dprintf("fewbody: current status: t=%.6g %s (%s)\n", *t, fb_sprint_hier(*hier, string1), fb_sprint_hier_hr(*hier, string2)); snprintf(&(logentry[strlen(logentry)]), FB_MAX_LOGENTRY_LENGTH-strlen(logentry), " current status: t=%.6g %s (%s)\n", *t, fb_sprint_hier(*hier, string1), fb_sprint_hier_hr(*hier, string2)); /* print final story */ if (input.Dflag == 1) { fb_print_story(&(hier->hier[hier->hi[1]]), hier->nstar, *t, logentry); } fb_dprintf("fewbody: final: phier.nobj = %d\n", phier.nobj); E = fb_petot(&(hier->hier[hier->hi[1]]), hier->nstar) + fb_ketot(&(hier->hier[hier->hi[1]]), hier->nstar) + fb_einttot(&(hier->hier[hier->hi[1]]), hier->nstar); fb_angmom(&(hier->hier[hier->hi[1]]), hier->nstar, L); fb_angmomint(&(hier->hier[hier->hi[1]]), hier->nstar, Lint); for (i=0; i<3; i++) { L[i] += Lint[i]; DeltaL[i] = L[i] - Li[i]; } /* free GSL stuff */ gsl_odeiv_evolve_free(ode_evolve); gsl_odeiv_control_free(ode_control); gsl_odeiv_step_free(ode_step); /* free our own stuff */ fb_free_vector(y); fb_free_hier(phier); if (input.ks) { fb_free_ks_params(ks_params); } else { fb_free_nonks_params(nonks_params); } /* done! */ retval.DeltaE = E-Ei; retval.DeltaEfrac = E/Ei-1.0; retval.DeltaL = fb_mod(DeltaL); retval.DeltaLfrac = fb_mod(DeltaL)/fb_mod(Li); return(retval); }
{ "alphanum_fraction": 0.6489534318, "avg_line_length": 32.4368421053, "ext": "c", "hexsha": "7afeacdb95481e055bf6fceb3788c8aeace9927c", "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": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": [ "PSF-2.0" ], "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_licenses": [ "PSF-2.0" ], "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody.c", "max_line_length": 145, "max_stars_count": null, "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": [ "PSF-2.0" ], "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4406, "size": 12326 }
/* * MotorControl.h * * Created on: 02/01/2014 * Author: james */ #ifndef MOTORCONTROL_H_ #define MOTORCONTROL_H_ #include "Arduino.h" #include "MotorControl/Motor.h" #include "MotorControl/Encoder.h" #include "MathHelper/ComponentsFromVector.h" #include "MathHelper/Vector.h" #include "MotorControl/SpeedPWMStruct.h" #include <gsl_math.h> #define oneonroot3 0.5773502691896258 #define onethird 0.3333333333333333 class MotorControl { public: MotorControl(Motor parMotors[], Encoder parEncoders[], SpeedPWMStruct speedpwmstruct); MotorControl(); float getDesiredIndividualSpeed(int motor_num, float rotation_rate); void setOverallDesiredVector(float magnitude, float angl); float getNewAimFromFeedback(float desiredSpeed, float actualSpeed); int getPWMFromSpeed(float speed); void updateMotors(); virtual ~MotorControl(); void setMotorPWM(int motorNum, int, boolean FOR) static const int clicksperrev; static const int millispersec; Motor motors[3]; Encoder encoders[3]; float getIndividualSpeed(int encoder_num); private: ComponentsFromVector motorSpeedComponents[3]; Vector overallDesiredVector; SpeedPWMStruct speedpwmstruct; static const float mtrconst; }; #endif /* MOTORCONTROL_H_ */
{ "alphanum_fraction": 0.790678659, "avg_line_length": 27.1777777778, "ext": "h", "hexsha": "e7457ee7a12e182be6bb289b2b93db20f6c85771", "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": "36e81b2ff4209ab07515329c9222796c46e97387", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JamesMBartlett/RobotSoccer", "max_forks_repo_path": "Arduino/libraries/robotLibs/MotorControl/MotorControl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "36e81b2ff4209ab07515329c9222796c46e97387", "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": "JamesMBartlett/RobotSoccer", "max_issues_repo_path": "Arduino/libraries/robotLibs/MotorControl/MotorControl.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "36e81b2ff4209ab07515329c9222796c46e97387", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JamesMBartlett/RobotSoccer", "max_stars_repo_path": "Arduino/libraries/robotLibs/MotorControl/MotorControl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 303, "size": 1223 }
#include <assert.h> #include <complex.h> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <malloc.h> #include <math.h> #include <nlopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tsvread.h" typedef struct { gsl_spline *spline; gsl_interp_accel *acc; int flags; double d; } f_param_t; double opt_func(unsigned n, const double *x, double *grad, void *f_data) { f_param_t *fparam = (f_param_t *)f_data; gsl_spline *spline_nu = fparam->spline; gsl_interp_accel *acc_nu = fparam->acc; int flags = fparam->flags; double d = fparam->d; return gsl_spline_eval(spline_nu, x[0], acc_nu); } int main(int argc, char **argv) { /* open file for reading data */ tsv_t *tsv = tsv_fread(argv[1]); if (tsv->columns != 2) { fprintf(stderr, "input file must be 2 colums tab seperated\n"); return -1; } double *x_nu = (double *)malloc(tsv->rows * sizeof(double)); double *y_nu = (double *)malloc(tsv->rows * sizeof(double)); assert(x_nu != NULL); assert(y_nu != NULL); unsigned int i; for (i = 0; i < tsv->rows; i++) { x_nu[i] = tsv->data[i][0]; y_nu[i] = tsv->data[i][1]; } gsl_interp_accel *acc_nu = gsl_interp_accel_alloc(); gsl_spline *spline_nu = gsl_spline_alloc(gsl_interp_cspline, tsv->rows); gsl_spline_init(spline_nu, x_nu, y_nu, tsv->rows); double x[1]; /* initial guess */ double lb[1]; /* lower bound */ double ub[1]; /* upper bound */ double minf = 0; lb[0] = x_nu[0]; ub[0] = x_nu[tsv->rows - 1]; x[0] = x_nu[tsv->rows / 2]; f_param_t *fparam = (f_param_t *)malloc(1 * sizeof(f_param_t)); fparam->spline = spline_nu; fparam->acc = acc_nu; fparam->flags = 0; void *fvparam; fvparam = fparam; nlopt_opt opt; opt = nlopt_create(NLOPT_LN_NELDERMEAD, 1); nlopt_set_lower_bounds(opt, lb); nlopt_set_upper_bounds(opt, ub); nlopt_set_max_objective(opt, opt_func, fvparam); nlopt_set_xtol_rel(opt, 1e-16); // nlopt_set_ftol_abs(opt,1e-6); // nlopt_set_maxtime(opt,4); int err; double max_nu; err = nlopt_optimize(opt, x, &minf); if (err < 0) { fprintf(stderr, "nlopt failed! %d\n", err); fprintf(stderr, "lower: %g\n", lb[0]); fprintf(stderr, "upper: %g\n", ub[0]); fprintf(stderr, "guess: %g\n", x[0]); if (lb[0] > ub[0]) { fprintf(stderr, "lower bigger than upper\n"); } } else { max_nu = gsl_spline_eval(spline_nu, x[0], acc_nu); printf("Maximum: %.20g %.20g \n", x[0], max_nu); } nlopt_destroy(opt); tsv_free(tsv); free(x_nu); free(y_nu); return 0; }
{ "alphanum_fraction": 0.6413713405, "avg_line_length": 25.4509803922, "ext": "c", "hexsha": "2e43b04d832d5b5bdb75d00c6ffbbe583c329bcc", "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": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AaronWebster/directdebye", "max_forks_repo_path": "extras/findmax/findmax.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "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": "AaronWebster/directdebye", "max_issues_repo_path": "extras/findmax/findmax.c", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AaronWebster/directdebye", "max_stars_repo_path": "extras/findmax/findmax.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 923, "size": 2596 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <cblas.h> #include <string.h> #include "../inc/knnring.h" knnresult kNN(double *X, double *Y, int n, int m, int d, int k){ knnresult k_nearest; //initalize the result's variable k_nearest.nidx = (int *)malloc(m*k*sizeof(int)); k_nearest.ndist = (double *)malloc(m*k*sizeof(double)); k_nearest.m = m; k_nearest.k = k; //compute the distance Matrix D double *D = compute_D(X,Y,n,m,d,k); //select k-nearest neighbors for every point in QUERY k_select(D,k_nearest.ndist, k_nearest.nidx,n,m,k); return k_nearest; } double *compute_D(double *X, double *Y, int n, int m, int d, int k){ //compute distances using //D = (X*X)ee_t - 2XY_t + ee_t(Y*Y)_t double *tempD = (double *)malloc(n*m*sizeof(double)); double *e_1 = (double *)malloc(d*m*sizeof(double)); double *XX = (double *)malloc(n*d*sizeof(double)); for(int i=0;i<d*m;i++) e_1[i]=1; for(int i=0;i<n*d;i++) XX[i] = X[i]*X[i]; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n,m,d,1,XX,d,e_1,m,0,tempD,m); free(e_1); free(XX); double *e_2 = (double *)malloc(n*d*sizeof(double)); double *YY = (double *)malloc(m*d*sizeof(double)); for(int i=0;i<n*d;i++) e_2[i]=1; for(int i=0;i<m*d;i++) YY[i] = Y[i]*Y[i]; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n,m,d,-2,X,d,Y,d,1,tempD,m); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n,m,d,1,e_2,d,YY,d,1,tempD,m); for(int i=0;i<n*m;i++) tempD[i] = sqrt(fabs(tempD[i])); free(e_2); free(YY); return tempD; } void k_select(double *D, double *ndist, int *nidx,int n, int m, int k){ for(int j=0;j<m;j++){ for(int i=0;i<k;i++){ ndist[j*k+i] = D[j+i*m]; nidx[j*k+i] = i; } //sort the initial k neighbors quick_sort(ndist,nidx,j*k,k*(j+1)-1); } //search the rest points to find it there are closer neighbors for(int j=0;j<m;j++){ for(int i=k;i<n;i++){ if(D[j+i*m] < ndist[k*(j+1)-1]){ ndist[k*(j+1)-1] = D[j+i*m]; nidx[k*(j+1)-1] = i; quick_sort(ndist,nidx,j*k,(j+1)*k-1); } } } } void quick_sort(double *k_dist, int *k_neigh, int low, int high){ if(low<high){ //actuall sorting an element int pi = partition(k_dist,k_neigh,low,high); //recursivelly call quick_sort quick_sort(k_dist,k_neigh,low,pi-1); quick_sort(k_dist,k_neigh,pi+1,high); } } int partition(double *k_dist, int *k_neigh,int low, int high){ double temp_dist; int temp_point; int checker = 0; double pivot = k_dist[high]; //printf("the pivot is %lf \n",pivot); int i = (low-1); for(int j=low;j<=high-1;j++){ if(k_dist[j]<=pivot){ /*swap the two elements*/ i=i+1; temp_dist = k_dist[i]; temp_point = k_neigh[i]; k_dist[i] = k_dist[j]; k_neigh[i] = k_neigh[j]; k_dist[j] = temp_dist; k_neigh[j] = temp_point; checker = 1; } } /* swap the pivot */ i=i+1; temp_dist = k_dist[i]; temp_point = k_neigh[i]; k_dist[i] = k_dist[high]; k_neigh[i] = k_neigh[high]; k_dist[high] = temp_dist; k_neigh[high] = temp_point; return i; } void write_to_file(char *str1, int *nidx, double *ndist, int amount, int k){ FILE *fp; //file for indexes fp = fopen(str1,"w+"); int counter = 1; for(int i=0;i<amount;i++){ fprintf(fp,"%d)%d -- %lf\n",counter,nidx[i],ndist[i]); counter ++; if((i+1)%k == 0){ fprintf(fp,"k nearest neighbors for next point \n"); counter = 1; } } fclose(fp); }
{ "alphanum_fraction": 0.6155844156, "avg_line_length": 20.625, "ext": "c", "hexsha": "505d2af2e5124f9868f7059bc89c1e3049d44755", "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/knnring_sequential.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/knnring_sequential.c", "max_line_length": 86, "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/knnring_sequential.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1223, "size": 3465 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include <map> #include "DrawableGameComponent.h" #include "FullScreenRenderTarget.h" #include "GaussianBlur.h" namespace Rendering { class DiffuseLightingDemo; class GaussianBlurDemo final : public Library::DrawableGameComponent { public: GaussianBlurDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); GaussianBlurDemo(const GaussianBlurDemo&) = delete; GaussianBlurDemo(GaussianBlurDemo&&) = default; GaussianBlurDemo& operator=(const GaussianBlurDemo&) = default; GaussianBlurDemo& operator=(GaussianBlurDemo&&) = default; ~GaussianBlurDemo(); std::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const; float BlurAmount() const; void SetBlurAmount(float blurAmount); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: std::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo; Library::FullScreenRenderTarget mRenderTarget; Library::GaussianBlur mGaussianBlur; }; }
{ "alphanum_fraction": 0.7774891775, "avg_line_length": 29.6153846154, "ext": "h", "hexsha": "2507ae58ef3b6afa001bc1eae7126a07cc8bf860", "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/7.2_Gaussian_Blurring/GaussianBlurDemo.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/7.2_Gaussian_Blurring/GaussianBlurDemo.h", "max_line_length": 88, "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/7.2_Gaussian_Blurring/GaussianBlurDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 290, "size": 1155 }
#ifndef FUNCTION_ANY_FUNCTION_H #define FUNCTION_ANY_FUNCTION_H #include "wasm_base.h" #include "wasm_value.h" #include "function/CFunction.h" #include <gsl/gsl> namespace wasm { struct AnyFunction: private std::variant< std::monostate, gsl::not_null<WasmFunction* const*>, CFunction > { using null_function_alt = std::monostate; using wasm_function_alt = gsl::not_null<WasmFunction* const*>; using c_function_alt = CFunction; using variant_type = std::variant< null_function_alt, wasm_function_alt, c_function_alt >; using variant_type::variant_type; AnyFunction() = default; AnyFunction(const AnyFunction&) = default; AnyFunction(AnyFunction&&) = default; AnyFunction& operator=(const AnyFunction&) = default; AnyFunction& operator=(AnyFunction&&) = default; void emplace_wasm_function(gsl::not_null<wasm_function_alt> func) { as_variant.emplace<wasm_function_alt>(func); } void emplace_c_function(CFunction cfunc) { as_variant().emplace<c_function_alt>(std::move(cfunc)); } void emplace_null_function() { as_variant().emplace<null_function_type>(std::monostate{}); } bool is_wasm_function() const { return std::holds_alternative<wasm_function_alt>(as_variant()); } bool is_c_function() const { return std::holds_alternative<c_function_alt>(as_variant()); } bool is_null() const { return std::holds_alternative<std::monostate>(as_variant()); } const WasmFunction* get_wasm_function() const { auto f = std::get<wasm_function_alt>(as_variant()); return *f; } WasmFunction* get_wasm_function() { return const_cast<WasmFunction*>(get_wasm_function()); } c_function_type get_c_function() const { return std::get<c_function_alt>(as_variant()); } private: variant_type& as_variant() { return static_cast<variant_type&>(*this); } const variant_type& as_variant() const { return static_cast<const variant_type&>(*this); } }; } /* namespace wasm */ #endif /* FUNCTION_ANY_FUNCTION_H */
{ "alphanum_fraction": 0.7492323439, "avg_line_length": 24.1234567901, "ext": "h", "hexsha": "c50266ae00178945597876d2f1228da3d9bde4f4", "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": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tvanslyke/wasm-cpp", "max_forks_repo_path": "include/function/AnyFunction.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "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": "tvanslyke/wasm-cpp", "max_issues_repo_path": "include/function/AnyFunction.h", "max_line_length": 68, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a56c1706e2723ece36e3642bae9e36792dbd7b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tvanslyke/wasm-cpp", "max_stars_repo_path": "include/function/AnyFunction.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 497, "size": 1954 }
//This computes the DFT (discrete Fourier transformation) along dim of matrix X. //This uses a CBLAS matrix multiplication by the DFT matrix. //This can be useful for smaller transform sizes, especially odd-length ones. //It is nice that the scaling can be included in the matrix. //This can also be useful if using only a few of the output frequencies, as given by F. //Especially useful (with modification) if can be combined with another matrix multiply. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int dft_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc); int dft_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc); int dft_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc); int dft_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc); int dft_cblas_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc) { if (dim>3u) { fprintf(stderr,"error in dft_cblas_s: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in dft_cblas_s: ndft must be >= Lx (length of vecs in X)\n"); return 1; } if (ndft<F) { fprintf(stderr,"error in dft_cblas_s: ndft must be >= F (num output freqs)\n"); return 1; } //Scaling const float s = sc ? 1.0f/sqrtf((float)(2u*ndft)) : 1.0f; if (N==0u || F==0u) {} else if (ndft==1u) { for (size_t n=N; n>0u; --n, ++X) { *Y++ = *X; *Y++ = 0.0f; } Y -= 2u*N; } else { //Initialize DFT matrix multiply (real, imag parts separate) const size_t LF = Lx * F; const float P2_N = (float)(2.0*M_PI/(double)ndft); float *DFTr, *DFTi; DFTr = (float *)aligned_alloc(sizeof(float),LF*sizeof(float)); DFTi = (float *)aligned_alloc(sizeof(float),LF*sizeof(float)); if (!DFTr) { fprintf(stderr,"error in dft_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } if (!DFTi) { fprintf(stderr,"error in dft_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DFTr, ++DFTi) { *DFTr = s; *DFTi = 0.0f; } for (size_t f=1u; f<F; ++f) { for (size_t l=0u; l<Lx; ++l) { *DFTr++ = s * cosf(P2_N*(float)f*(float)l); *DFTi++ = -s * sinf(P2_N*(float)f*(float)l); } } DFTr -= LF; DFTi -= LF; if (Lx==N) { //Matrix multiply cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTr,(int)Lx,X,1,0.0f,Y,2); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTi,(int)Lx,X,1,0.0f,&Y[1],2); //Enforce real Nyquist if (ndft%2u==0u && F>ndft/2u) { Y[ndft+1u] = 0.0f; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*F) { //Matrix multiply cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTr,(int)Lx,X,1,0.0f,Y,2); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTi,(int)Lx,X,1,0.0f,&Y[1],2); //Enforce real Nyquist if (ndft%2u==0u && F>ndft/2u) { Y[ndft+1u] = 0.0f; } } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(F-1u)) { for (size_t b=B; b>0u; --b, ++X, Y+=2) { //Matrix multiply cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTr,(int)Lx,X,(int)K,0.0f,Y,2*(int)K); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0f,DFTi,(int)Lx,X,(int)K,0.0f,&Y[1],2*(int)K); //Enforce real Nyquist //if (ndft%2u==0u && F>ndft/2u) { Y[2u*K*(ndft/2u+1u)+1u] = 0.0f; } } } } } free(DFTr); free(DFTi); } return 0; } int dft_cblas_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc) { if (dim>3u) { fprintf(stderr,"error in dft_cblas_d: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in dft_cblas_d: ndft must be >= Lx (length of vecs in X)\n"); return 1; } if (ndft<F) { fprintf(stderr,"error in dft_cblas_d: ndft must be >= F (num output freqs)\n"); return 1; } //Scaling const double s = sc ? 1.0/sqrt((double)(2u*ndft)) : 1.0; if (N==0u || F==0u) {} else if (ndft==1u) { for (size_t n=N; n>0u; --n, ++X) { *Y++ = *X; *Y++ = 0.0; } Y -= 2u*N; } else { //Initialize DFT matrix multiply const size_t LF = Lx * F; const double P2_N = 2.0*M_PI/(double)ndft; double *DFTr, *DFTi; DFTr = (double *)aligned_alloc(sizeof(double),LF*sizeof(double)); DFTi = (double *)aligned_alloc(sizeof(double),LF*sizeof(double)); if (!DFTr) { fprintf(stderr,"error in dft_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } if (!DFTi) { fprintf(stderr,"error in dft_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t l=0u; l<Lx; ++l, ++DFTr, ++DFTi) { *DFTr = s; *DFTi = 0.0; } for (size_t f=1u; f<F; ++f) { for (size_t l=0u; l<Lx; ++l) { *DFTr++ = s * cos(P2_N*(double)f*(double)l); *DFTi++ = -s * sin(P2_N*(double)f*(double)l); } } DFTr -= LF; DFTi -= LF; if (Lx==N) { //Matrix multiply cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTr,(int)Lx,X,1,0.0,Y,2); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTi,(int)Lx,X,1,0.0,&Y[1],2); //Enforce real Nyquist if (ndft%2u==0u && F>ndft/2u) { Y[ndft+1u] = 0.0f; } } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*F) { //Matrix multiply cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTr,(int)Lx,X,1,0.0,Y,2); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTi,(int)Lx,X,1,0.0,&Y[1],2); //Enforce real Nyquist if (ndft%2u==0u && F>ndft/2u) { Y[ndft+1u] = 0.0; } } } else { for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(F-1u)) { for (size_t b=B; b>0u; --b, ++X, Y+=2) { //Matrix multiply cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTr,(int)Lx,X,(int)K,0.0,Y,2*(int)K); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,1.0,DFTi,(int)Lx,X,(int)K,0.0,&Y[1],2*(int)K); //Enforce real Nyquist //if (ndft%2u==0u && F>ndft/2u) { Y[2u*K*(ndft/2u+1u)+1u] = 0.0; } } } } } free(DFTr); free(DFTi); } return 0; } int dft_cblas_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc) { if (dim>3u) { fprintf(stderr,"error in dft_cblas_c: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in dft_cblas_c: ndft must be >= Lx (length of vecs in X)\n"); return 1; } if (ndft<F) { fprintf(stderr,"error in dft_cblas_c: ndft must be >= F (num output freqs)\n"); return 1; } //Scaling const float s = sc ? 1.0f/sqrtf((float)(2u*ndft)) : 1.0f; if (N==0u || F==0u) {} else if (ndft==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X; } Y -= 2u*N; } else { //Init DFT matrix multiply const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f}; const size_t LF = Lx * F; const float P2_N = (float)(2.0*M_PI/(double)ndft); float *DFT; DFT = (float *)aligned_alloc(sizeof(float),2u*LF*sizeof(float)); if (!DFT) { fprintf(stderr,"error in dft_cblas_c: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t f=0u; f<F; ++f) { for (size_t l=0u; l<Lx; ++l) { *DFT++ = s * cosf(P2_N*(float)f*(float)l); *DFT++ = -s * sinf(P2_N*(float)f*(float)l); } } DFT -= 2u*LF; if (Lx==N) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,1,z,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*F) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,1,z,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(F-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y+=2) { //Matrix multiply cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,(int)K,z,Y,(int)K); } } } } free(DFT); } return 0; } int dft_cblas_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t ndft, const size_t F, const int sc) { if (dim>3u) { fprintf(stderr,"error in dft_cblas_z: dim must be in [0 3]\n"); return 1; } const size_t N = R*C*S*H; const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H; if (ndft<Lx) { fprintf(stderr,"error in dft_cblas_z: ndft must be >= Lx (length of vecs in X)\n"); return 1; } if (ndft<F) { fprintf(stderr,"error in dft_cblas_z: ndft must be >= F (num output freqs)\n"); return 1; } //Scaling const double s = sc ? 1.0/sqrt((double)(2u*ndft)) : 1.0; if (N==0u || F==0u) {} else if (ndft==1u) { for (size_t n=2u*N; n>0u; --n, ++X, ++Y) { *Y = *X; } Y -= 2u*N; } else { //Init DFT matrix multiply const double z[2] = {0.0,0.0}, o[2] = {1.0,0.0}; const size_t LF = Lx * F; const double P2_N = 2.0*M_PI/(double)ndft; double *DFT; DFT = (double *)aligned_alloc(sizeof(double),2u*LF*sizeof(double)); if (!DFT) { fprintf(stderr,"error in dft_cblas_z: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t f=0u; f<F; ++f) { for (size_t l=0u; l<Lx; ++l) { *DFT++ = s * cos(P2_N*(double)f*(double)l); *DFT++ = -s * sin(P2_N*(double)f*(double)l); } } DFT -= 2u*LF; if (Lx==N) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,1,z,Y,1); } else { const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u); const size_t B = (iscolmajor && dim==0u) ? C*S*H : K; const size_t V = N/Lx, G = V/B; if (K==1u && (G==1u || B==1u)) { for (size_t v=0u; v<V; ++v, Y+=2u*F) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,1,z,Y,1); } } else { for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(F-1u)) { for (size_t b=B; b>0u; --b, X+=2, Y+=2) { //Matrix multiply cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)F,(int)Lx,o,DFT,(int)Lx,X,(int)K,z,Y,(int)K); } } } } free(DFT); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4975596343, "avg_line_length": 40.1850828729, "ext": "c", "hexsha": "3d5e12937a7a5288db732d26d10c90fb639c0b27", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_path": "c/dft.cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/dsp", "max_issues_repo_path": "c/dft.cblas.c", "max_line_length": 198, "max_stars_count": 1, "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_path": "c/dft.cblas.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "num_tokens": 5102, "size": 14547 }
/* specfunc/coupling.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_coupling.h> #include "error.h" inline static int locMax3(const int a, const int b, const int c) { int d = GSL_MAX(a, b); return GSL_MAX(d, c); } inline static int locMin3(const int a, const int b, const int c) { int d = GSL_MIN(a, b); return GSL_MIN(d, c); } inline static int locMin5(const int a, const int b, const int c, const int d, const int e) { int f = GSL_MIN(a, b); int g = GSL_MIN(c, d); int h = GSL_MIN(f, g); return GSL_MIN(e, h); } /* See: [Thompson, Atlas for Computing Mathematical Functions] */ static int delta(int ta, int tb, int tc, gsl_sf_result * d) { gsl_sf_result f1, f2, f3, f4; int status = 0; status += gsl_sf_fact_e((ta + tb - tc)/2, &f1); status += gsl_sf_fact_e((ta + tc - tb)/2, &f2); status += gsl_sf_fact_e((tb + tc - ta)/2, &f3); status += gsl_sf_fact_e((ta + tb + tc)/2 + 1, &f4); if(status != 0) { OVERFLOW_ERROR(d); } d->val = f1.val * f2.val * f3.val / f4.val; d->err = 4.0 * GSL_DBL_EPSILON * fabs(d->val); return GSL_SUCCESS; } static int triangle_selection_fails(int two_ja, int two_jb, int two_jc) { return ((two_jb < abs(two_ja - two_jc)) || (two_jb > two_ja + two_jc)); } static int m_selection_fails(int two_ja, int two_jb, int two_jc, int two_ma, int two_mb, int two_mc) { return ( abs(two_ma) > two_ja || abs(two_mb) > two_jb || abs(two_mc) > two_jc || GSL_IS_ODD(two_ja + two_ma) || GSL_IS_ODD(two_jb + two_mb) || GSL_IS_ODD(two_jc + two_mc) || (two_ma + two_mb + two_mc) != 0 ); } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_coupling_3j_e (int two_ja, int two_jb, int two_jc, int two_ma, int two_mb, int two_mc, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(two_ja < 0 || two_jb < 0 || two_jc < 0) { DOMAIN_ERROR(result); } else if ( triangle_selection_fails(two_ja, two_jb, two_jc) || m_selection_fails(two_ja, two_jb, two_jc, two_ma, two_mb, two_mc) ) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { int jca = (-two_ja + two_jb + two_jc) / 2, jcb = ( two_ja - two_jb + two_jc) / 2, jcc = ( two_ja + two_jb - two_jc) / 2, jmma = ( two_ja - two_ma) / 2, jmmb = ( two_jb - two_mb) / 2, jmmc = ( two_jc - two_mc) / 2, jpma = ( two_ja + two_ma) / 2, jpmb = ( two_jb + two_mb) / 2, jpmc = ( two_jc + two_mc) / 2, jsum = ( two_ja + two_jb + two_jc) / 2, kmin = locMax3 (0, jpmb - jmmc, jmma - jpmc), kmax = locMin3 (jcc, jmma, jpmb), k, sign = GSL_IS_ODD (kmin - jpma + jmmb) ? -1 : 1, status = 0; double sum_pos = 0.0, sum_neg = 0.0, norm, term; gsl_sf_result bc1, bc2, bc3, bcn1, bcn2, bcd1, bcd2, bcd3, bcd4; status += gsl_sf_choose_e (two_ja, jcc , &bcn1); status += gsl_sf_choose_e (two_jb, jcc , &bcn2); status += gsl_sf_choose_e (jsum+1, jcc , &bcd1); status += gsl_sf_choose_e (two_ja, jmma, &bcd2); status += gsl_sf_choose_e (two_jb, jmmb, &bcd3); status += gsl_sf_choose_e (two_jc, jpmc, &bcd4); if (status != 0) { OVERFLOW_ERROR (result); } norm = sqrt (bcn1.val * bcn2.val) / sqrt (bcd1.val * bcd2.val * bcd3.val * bcd4.val * ((double) two_jc + 1.0)); for (k = kmin; k <= kmax; k++) { status += gsl_sf_choose_e (jcc, k, &bc1); status += gsl_sf_choose_e (jcb, jmma - k, &bc2); status += gsl_sf_choose_e (jca, jpmb - k, &bc3); if (status != 0) { OVERFLOW_ERROR (result); } term = bc1.val * bc2.val * bc3.val; if (sign < 0) { sum_neg += norm * term; } else { sum_pos += norm * term; } sign = -sign; } result->val = sum_pos - sum_neg; result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg); result->err += 2.0 * GSL_DBL_EPSILON * (kmax - kmin) * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_coupling_6j_INCORRECT_e(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf, gsl_sf_result * result) { return gsl_sf_coupling_6j_e(two_ja, two_jb, two_je, two_jd, two_jc, two_jf, result); } int gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if( two_ja < 0 || two_jb < 0 || two_jc < 0 || two_jd < 0 || two_je < 0 || two_jf < 0 ) { DOMAIN_ERROR(result); } else if( triangle_selection_fails(two_ja, two_jb, two_jc) || triangle_selection_fails(two_ja, two_je, two_jf) || triangle_selection_fails(two_jb, two_jd, two_jf) || triangle_selection_fails(two_je, two_jd, two_jc) ) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { gsl_sf_result n1; gsl_sf_result d1, d2, d3, d4, d5, d6; double norm; int tk, tkmin, tkmax; double phase; double sum_pos = 0.0; double sum_neg = 0.0; double sumsq_err = 0.0; int status = 0; status += delta(two_ja, two_jb, two_jc, &d1); status += delta(two_ja, two_je, two_jf, &d2); status += delta(two_jb, two_jd, two_jf, &d3); status += delta(two_je, two_jd, two_jc, &d4); if(status != GSL_SUCCESS) { OVERFLOW_ERROR(result); } norm = sqrt(d1.val) * sqrt(d2.val) * sqrt(d3.val) * sqrt(d4.val); tkmin = locMax3(0, two_ja + two_jd - two_jc - two_jf, two_jb + two_je - two_jc - two_jf); tkmax = locMin5(two_ja + two_jb + two_je + two_jd + 2, two_ja + two_jb - two_jc, two_je + two_jd - two_jc, two_ja + two_je - two_jf, two_jb + two_jd - two_jf); phase = GSL_IS_ODD((two_ja + two_jb + two_je + two_jd + tkmin)/2) ? -1.0 : 1.0; for(tk=tkmin; tk<=tkmax; tk += 2) { double term; double term_err; gsl_sf_result den_1, den_2; gsl_sf_result d1_a, d1_b; status = 0; status += gsl_sf_fact_e((two_ja + two_jb + two_je + two_jd - tk)/2 + 1, &n1); status += gsl_sf_fact_e(tk/2, &d1_a); status += gsl_sf_fact_e((two_jc + two_jf - two_ja - two_jd + tk)/2, &d1_b); status += gsl_sf_fact_e((two_jc + two_jf - two_jb - two_je + tk)/2, &d2); status += gsl_sf_fact_e((two_ja + two_jb - two_jc - tk)/2, &d3); status += gsl_sf_fact_e((two_je + two_jd - two_jc - tk)/2, &d4); status += gsl_sf_fact_e((two_ja + two_je - two_jf - tk)/2, &d5); status += gsl_sf_fact_e((two_jb + two_jd - two_jf - tk)/2, &d6); if(status != GSL_SUCCESS) { OVERFLOW_ERROR(result); } d1.val = d1_a.val * d1_b.val; d1.err = d1_a.err * fabs(d1_b.val) + fabs(d1_a.val) * d1_b.err; den_1.val = d1.val*d2.val*d3.val; den_1.err = d1.err * fabs(d2.val*d3.val); den_1.err += d2.err * fabs(d1.val*d3.val); den_1.err += d3.err * fabs(d1.val*d2.val); den_2.val = d4.val*d5.val*d6.val; den_2.err = d4.err * fabs(d5.val*d6.val); den_2.err += d5.err * fabs(d4.val*d6.val); den_2.err += d6.err * fabs(d4.val*d5.val); term = phase * n1.val / den_1.val / den_2.val; phase = -phase; term_err = n1.err / fabs(den_1.val) / fabs(den_2.val); term_err += fabs(term / den_1.val) * den_1.err; term_err += fabs(term / den_2.val) * den_2.err; if(term >= 0.0) { sum_pos += norm*term; } else { sum_neg -= norm*term; } sumsq_err += norm*norm * term_err*term_err; } result->val = sum_pos - sum_neg; result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg); result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0)); result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin + 2.0) * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_coupling_RacahW_e(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf, gsl_sf_result * result) { int status = gsl_sf_coupling_6j_e(two_ja, two_jb, two_je, two_jd, two_jc, two_jf, result); int phase_sum = (two_ja + two_jb + two_jc + two_jd)/2; result->val *= ( GSL_IS_ODD(phase_sum) ? -1.0 : 1.0 ); return status; } int gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf, int two_jg, int two_jh, int two_ji, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if( two_ja < 0 || two_jb < 0 || two_jc < 0 || two_jd < 0 || two_je < 0 || two_jf < 0 || two_jg < 0 || two_jh < 0 || two_ji < 0 ) { DOMAIN_ERROR(result); } else if( triangle_selection_fails(two_ja, two_jb, two_jc) || triangle_selection_fails(two_jd, two_je, two_jf) || triangle_selection_fails(two_jg, two_jh, two_ji) || triangle_selection_fails(two_ja, two_jd, two_jg) || triangle_selection_fails(two_jb, two_je, two_jh) || triangle_selection_fails(two_jc, two_jf, two_ji) ) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { int tk; int tkmin = locMax3(abs(two_ja-two_ji), abs(two_jh-two_jd), abs(two_jb-two_jf)); int tkmax = locMin3(two_ja + two_ji, two_jh + two_jd, two_jb + two_jf); double sum_pos = 0.0; double sum_neg = 0.0; double sumsq_err = 0.0; double phase; for(tk=tkmin; tk<=tkmax; tk += 2) { gsl_sf_result s1, s2, s3; double term; double term_err; int status = 0; status += gsl_sf_coupling_6j_e(two_ja, two_ji, tk, two_jh, two_jd, two_jg, &s1); status += gsl_sf_coupling_6j_e(two_jb, two_jf, tk, two_jd, two_jh, two_je, &s2); status += gsl_sf_coupling_6j_e(two_ja, two_ji, tk, two_jf, two_jb, two_jc, &s3); if(status != GSL_SUCCESS) { OVERFLOW_ERROR(result); } term = s1.val * s2.val * s3.val; term_err = s1.err * fabs(s2.val*s3.val); term_err += s2.err * fabs(s1.val*s3.val); term_err += s3.err * fabs(s1.val*s2.val); if(term >= 0.0) { sum_pos += (tk + 1) * term; } else { sum_neg -= (tk + 1) * term; } sumsq_err += ((tk+1) * term_err) * ((tk+1) * term_err); } phase = GSL_IS_ODD(tkmin) ? -1.0 : 1.0; result->val = phase * (sum_pos - sum_neg); result->err = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg); result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0)); result->err += 2.0 * GSL_DBL_EPSILON * (tkmax-tkmin + 2.0) * fabs(result->val); return GSL_SUCCESS; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc, int two_ma, int two_mb, int two_mc) { EVAL_RESULT(gsl_sf_coupling_3j_e(two_ja, two_jb, two_jc, two_ma, two_mb, two_mc, &result)); } double gsl_sf_coupling_6j_INCORRECT(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf) { EVAL_RESULT(gsl_sf_coupling_6j_INCORRECT_e(two_ja, two_jb, two_jc, two_jd, two_je, two_jf, &result)); } double gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf) { EVAL_RESULT(gsl_sf_coupling_6j_e(two_ja, two_jb, two_jc, two_jd, two_je, two_jf, &result)); } double gsl_sf_coupling_RacahW(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf) { EVAL_RESULT(gsl_sf_coupling_RacahW_e(two_ja, two_jb, two_jc, two_jd, two_je, two_jf, &result)); } double gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc, int two_jd, int two_je, int two_jf, int two_jg, int two_jh, int two_ji) { EVAL_RESULT(gsl_sf_coupling_9j_e(two_ja, two_jb, two_jc, two_jd, two_je, two_jf, two_jg, two_jh, two_ji, &result)); }
{ "alphanum_fraction": 0.5676907247, "avg_line_length": 30.9227272727, "ext": "c", "hexsha": "9a7140b613a3fdcf4d8015c64a6bad4aca0410ad", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/coupling.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/coupling.c", "max_line_length": 92, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/specfunc/coupling.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 4646, "size": 13606 }
#pragma once #include <chrono> #include <unordered_map> #include <vector> #include <gsl/span> #include <json.hpp> #include "Quiver/Animation/AnimationId.h" #include "Quiver/Animation/AnimationLibrary.h" #include "Quiver/Animation/AnimatorId.h" #include "Quiver/Animation/Rect.h" #include "Quiver/Graphics/ViewBuffer.h" namespace qvr { struct AnimatorTarget { ViewBuffer views; AnimatorTarget() = default; AnimatorTarget(const AnimatorTarget&) = delete; AnimatorTarget(const AnimatorTarget&&) = delete; AnimatorTarget& operator=(AnimatorTarget&) = delete; AnimatorTarget& operator=(AnimatorTarget&&) = delete; }; class AnimatorRepeatSetting { public: explicit AnimatorRepeatSetting(const int repeatCount) : m_RepeatCount(repeatCount) {} AnimatorRepeatSetting() = default; int GetRepeatCount() const { return m_RepeatCount; } static const AnimatorRepeatSetting Forever; static const AnimatorRepeatSetting Never; static const AnimatorRepeatSetting Once; static const AnimatorRepeatSetting Twice; private: int m_RepeatCount = Forever.GetRepeatCount(); }; struct AnimatorStartSetting { AnimatorStartSetting(AnimationId animationId) : m_AnimationId(animationId) {} AnimatorStartSetting( AnimationId animationId, AnimatorRepeatSetting repeatSetting) : m_AnimationId(animationId) , m_RepeatSetting(repeatSetting) {} AnimationId m_AnimationId; AnimatorRepeatSetting m_RepeatSetting; }; inline bool operator==(const AnimatorRepeatSetting& a, const AnimatorRepeatSetting& b) { return a.GetRepeatCount() == b.GetRepeatCount(); } inline bool operator!=(const AnimatorRepeatSetting& a, const AnimatorRepeatSetting& b) { return a.GetRepeatCount() != b.GetRepeatCount(); } struct AnimationLibraryEditorData; class AnimationData; class AnimatorCollection { public: auto GetAnimations() const -> const AnimationLibrary& { return animations; } AnimationId AddAnimation(const AnimationData& anim); AnimationId AddAnimation( const AnimationData& anim, const AnimationSourceInfo& animSourceInfo); bool RemoveAnimation(const AnimationId id); int GetReferenceCount(const AnimationId animation) const { if (animationReferenceCounts.count(animation) == 0) { return 0; } return animationReferenceCounts.at(animation); } AnimatorId Add( AnimatorTarget& target, const AnimatorStartSetting& startSetting); bool Remove(const AnimatorId id); bool Exists(const AnimatorId id) const { return animators.states.count(id) != 0; } int GetCount() const { return animators.states.size(); } void AnimatorGui(const AnimatorId id); bool SetAnimation( const AnimatorId animatorId, const AnimatorStartSetting& animation, const bool clearQueue = true); bool SetTarget( const AnimatorId id, AnimatorTarget& newTarget); bool SetFrame( const AnimatorId id, const int index); bool QueueAnimation( const AnimatorId animatorId, const AnimatorStartSetting& pendingAnimation); bool ClearAnimationQueue(const AnimatorId id); unsigned GetFrame(const AnimatorId animatorId) const; AnimationId GetAnimation(const AnimatorId animatorId) const; void Animate(const Animation::TimeUnit ms); private: struct AnimatorState { AnimatorState( const AnimationId animation, const int frameIndex, const int index, AnimatorTarget& target, const AnimatorRepeatSetting& repeat) : index(index) , currentFrame(frameIndex) , currentAnimation(animation) , target(&target) , repeatSetting(repeat) , repeatCount(0) {} AnimatorState() = default; int index; int currentFrame; int repeatCount; AnimationId currentAnimation; AnimatorRepeatSetting repeatSetting; AnimatorTarget* target; std::vector<AnimatorStartSetting> queuedAnimations; }; struct AnimatorState_Hot { AnimatorState_Hot( const AnimatorId animatorId, const Animation::TimeUnit timeLeft) : animatorId(animatorId) , timeLeftInFrame(timeLeft) {} Animation::TimeUnit timeLeftInFrame; AnimatorId animatorId; }; struct Animators { std::vector<AnimatorState_Hot> hotStates; std::unordered_map<AnimatorId, AnimatorState> states; AnimatorId GetNextAnimatorId(); private: AnimatorId lastId = AnimatorId::Invalid; } animators; AnimationLibrary animations; std::unordered_map<AnimationId, unsigned> animationReferenceCounts; // friends: friend void GuiControls( AnimatorCollection& animators, AnimationLibraryEditorData& editorData); friend void to_json(nlohmann::json& j, const AnimatorCollection& animators); friend void from_json(const nlohmann::json& j, AnimatorCollection& animators); }; void GuiControls(AnimatorCollection& animators, AnimationLibraryEditorData& editorData); void to_json(nlohmann::json& j, const AnimatorCollection& animators); void from_json(const nlohmann::json& j, AnimatorCollection& animators); }
{ "alphanum_fraction": 0.7735148515, "avg_line_length": 23.6487804878, "ext": "h", "hexsha": "608b23a0a25297fe58363e3abfbc9625e41a9cb3", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z", "max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rachelnertia/Quiver", "max_forks_repo_path": "Source/Quiver/Quiver/Animation/Animators.h", "max_issues_count": 46, "max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rachelnertia/Quarrel", "max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/Animators.h", "max_line_length": 88, "max_stars_count": 39, "max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rachelnertia/Quarrel", "max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/Animators.h", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z", "num_tokens": 1128, "size": 4848 }
#include <Exceptions.h> #include <Types.h> #ifndef GENERIC_API_NAMESPACE #error "Wrong usage of this header" #endif #ifndef GENERIC_API_ROUTINES_NAMESPACE #error "Wrong usage of this header" #endif #define ROUTINES_NAMESPACE namespace GENERIC_API_ROUTINES_NAMESPACE #define BLAS_NAMESPACE namespace GENERIC_API_NAMESPACE #ifndef GENERIC_API_DEFINE namespace cl { namespace routines { ROUTINES_NAMESPACE { template<MathDomain md> void Copy(MemoryBuffer&, const MemoryBuffer&) { throw NotImplementedException(); } } } // namespace routines } // namespace cl #else BLAS_NAMESPACE { #ifdef CBLAS_H #undef CBLAS_H #endif #include <cblas.h> } namespace cl { namespace routines { ROUTINES_NAMESPACE { template<MathDomain md> void Copy(MemoryBuffer & dest, const MemoryBuffer& source); template<> inline void Copy<MathDomain::Float>(MemoryBuffer & dest, const MemoryBuffer& source) { GENERIC_API_NAMESPACE::cblas_scopy(static_cast<int>(dest.size), reinterpret_cast<const float*>(source.pointer), 1, reinterpret_cast<float*>(dest.pointer), 1); } template<> inline void Copy<MathDomain::Double>(MemoryBuffer & dest, const MemoryBuffer& source) { GENERIC_API_NAMESPACE::cblas_dcopy(static_cast<int>(dest.size), reinterpret_cast<const double*>(source.pointer), 1, reinterpret_cast<double*>(dest.pointer), 1); } } } // namespace routines } // namespace cl #endif #undef GENERIC_API_DEFINE #undef GENERIC_API_NAMESPACE #undef GENERIC_API_ROUTINES_NAMESPACE #undef ROUTINES_NAMESPACE #undef BLAS_NAMESPACE
{ "alphanum_fraction": 0.7525188917, "avg_line_length": 21.1733333333, "ext": "h", "hexsha": "fe9924bd0b84167f96e153f5c57ed1e5a73d5ff4", "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": "390efb41da88245b2f5909b84213fb5839d505cf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pmontalb/CudaLight", "max_forks_repo_path": "HostRoutines/GenericBlasApiBufferInitializer.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf", "max_issues_repo_issues_event_max_datetime": "2018-03-13T12:57:46.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-04T22:26:42.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "pmontalb/CudaLight", "max_issues_repo_path": "HostRoutines/GenericBlasApiBufferInitializer.h", "max_line_length": 164, "max_stars_count": 2, "max_stars_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pmontalb/CudaLight", "max_stars_repo_path": "HostRoutines/GenericBlasApiBufferInitializer.h", "max_stars_repo_stars_event_max_datetime": "2021-11-30T23:34:21.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-25T17:54:50.000Z", "num_tokens": 388, "size": 1588 }
/* stable/stable_koutrouvelis.h * * Koutrouvelis method for parameter estimation of alpha-stable * distributions. Based on [1] and MATLAB code available in [2]. * * [1] Koutrouvelis, I. A. An Iterative Procedure for the Estimation * of the Parameters of Stable Laws Communications in Statistics * - Simulation and Computation, 1981, 10, 17-28 * [2] Mark S. Veillete. Alpha-Stable Distributions in MATLAB * http://math.bu.edu/people/mveillet/research.html * * Copyright (C) 2013. Javier Royuela del Val * Federico Simmross Wattenberg * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; If not, see <http://www.gnu.org/licenses/>. * * * Javier Royuela del Val. * E.T.S.I. Telecomunicación * Universidad de Valladolid * Paseo de Belén 15, 47002 Valladolid, Spain. * jroyval@lpi.tel.uva.es */ #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit.h> #include "stable.h" inline double sign(double x) { return ((.0 < x) - (x < .0)); } double var(const double * data, const int N) { double acum = .0, acum2 = .0; double v; int i; for(i=0;i<N;i++) { acum += data[i]; acum2 += data[i]*data[i]; } v = (1.0/(N-1.0)) * (acum2 - (1.0/N)*acum*acum); return v; } int chooseK(double,int); int chooseL(double,int); void setcovYY(const double * t, int K, int N, double alpha, double beta, double gam, double **covYY); void setcovZZ(const double * t, int K, int N, double alpha, double beta, double gam, double **covZZ); double ecfRoot(const double * data, const int N); void stable_samplecharfunc(const double* x, const unsigned int Nx, const double* t, const unsigned int Nt, gsl_complex *z); gsl_complex stable_samplecharfunc_point(const double* x, const unsigned int N, double t); int stable_fit_koutrouvelis(StableDist * dist, const double * data, const unsigned int N) { int maxiter = 10; double xTol = 0.01; double * s = NULL; gsl_complex * phi = NULL; gsl_complex * phi2 = NULL; int i; double alpha = dist->alpha; double beta = dist->beta; double sigma = dist->sigma; double mu1 = dist->mu_1; double alphaold = alpha; double mu1old = mu1; double diff = .0; double diffbest = DBL_MAX; double diffmax = .0; double alphabest = alpha; double betabest = beta; double sigmabest = sigma; double mu1best = mu1; double * t = NULL; double * w = NULL; double * y = NULL; double * p = NULL; double * t2 = NULL; double * w2 = NULL; double * y2 = NULL; double * p2 = NULL; gsl_matrix * X; gsl_matrix * covmat; gsl_vector * cvout; gsl_vector * ydat; gsl_vector * weights; int stat; double sumsq = .0; double c0 = .0, c1 = .0; double cov00 = .0, cov01 = .0, cov11 = .0; double sigmanew = 0; double **covYY;// **covZZ; double **covZZ; int iter = 0; int K,L; int row; double t_0=0; double step_u=0; double estshift; gsl_multifit_linear_workspace * linws; if (sigma == 0) { sigma = sqrt(var(data,N)); stable_setparams(dist,alpha,beta,sigma,mu1,1); } s = (double *) malloc(N*sizeof(double)); for (i=0;i<N;i++) { s[i] = (data[i]-mu1)/sigma; } covmat = gsl_matrix_alloc(2,2); cvout = gsl_vector_alloc(2); for (iter = 0; iter<maxiter; iter ++) { if (iter <= 1) { K = chooseK(alpha,N); t = (double *) realloc(t,K*sizeof(double)); p = (double *) realloc(p,K*sizeof(double)); w = (double *) realloc(w,K*sizeof(double)); y = (double *) realloc(y,K*sizeof(double)); phi = (gsl_complex*) realloc(phi,K*sizeof(gsl_complex)); for(i=0;i<K;i++) { t[i]=((double)i+1.0)*M_PI/25.0; w[i]=log(fabs(t[i])); } } if (iter==1) { covYY = (double **)malloc(K*sizeof(double *)); covYY[0] = (double*)malloc(K*K*sizeof(double)); for (row=1;row<K;row++) { covYY[row] = covYY[0] + row*K; } } stable_samplecharfunc(s,N,t,K,phi); for(i=0;i<K;i++) { y[i] = log(-2.0*gsl_complex_logabs(phi[i])); } if (iter==0) { //Use ordinary least squares regression // printf("ordls: ");fflush(stdout); stat = gsl_fit_linear (w, 1, y, 1, K, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); alpha = c1; sigmanew = pow(exp(c0)/2.0,1.0/alpha); sigma = sigma*sigmanew; // printf("stat = %d, alpha=%f, sigma=%f\n",stat,alpha,sigma); } else { //Use weighted least squares regression // printf("wls: ");fflush(stdout); setcovYY(t, K, N, alpha, beta, 1.0, covYY); for (i=0;i<K;i++) { p[i] = 1.0/covYY[i][i]; } stat = gsl_fit_wlinear(w, 1, p, 1, y, 1, K, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); alpha = c1; sigmanew = pow(exp(c0)/2.0,1.0/alpha); sigma = sigma*sigmanew; // printf("stat = %d, alpha=%f, sigma=%f\n",stat,alpha,sigma); } /*************** rescale data ******************/ // printf("rescale\n");fflush(stdout); for (i=0;i<N;i++) { s[i] = s[i]/sigmanew; } if (alpha<0) alpha = 0; if (alpha>2) alpha = 2; if (beta<-1) beta = -1; if (beta> 1) beta = 1; if (sigma<0) sigma = 0; /********** refine beta and mu **************/ // printf("refbetamu\n");fflush(stdout); if (iter <= 1) { L = chooseL(alpha,N); // printf("alpha = %f, N = %d, L = %d\n",alpha,N,L);fflush(stdout); t_0 = ecfRoot(s,N); step_u = M_PI/50; if (t_0/L<step_u) step_u = t_0/L; t2 = (double *) realloc(t2,L*sizeof(double)); p2 = (double *) realloc(p2,L*sizeof(double)); w2 = (double *) realloc(w2,L*sizeof(double)); y2 = (double *) realloc(y2,L*sizeof(double)); phi2 = (gsl_complex*)realloc(phi2,L*sizeof(gsl_complex)); for(i=0;i<L;i++) { t2[i]=((double)i+1.0)*step_u; w2[i]=sign(t2[i])*pow(fabs(t2[i]),alpha); } } if (iter==0){ // printf("multimin alloc L = %d\n",L);fflush(stdout); linws = gsl_multifit_linear_alloc (L,2); } else if (iter ==1) { //Reserve covariance matrix mem covZZ = (double **)malloc(L*sizeof(double *)); covZZ[0] = (double*)malloc(L*L*sizeof(double)); for (row=0;row<L;row++) { covZZ[row] = covZZ[0] + row*L; } gsl_multifit_linear_free(linws); linws = gsl_multifit_linear_alloc (L,2); } // printf("Second charfunc iter %d\n",iter);fflush(stdout); stable_samplecharfunc(s,N,t2,L,phi2); // printf("done\n"); for(i=0;i<L;i++) { y2[i] = gsl_complex_arg(phi2[i]); } X = gsl_matrix_alloc(L,2); ydat = gsl_vector_alloc(L); for(row=0;row<L;row++) { gsl_matrix_set(X,row,0,t2[row]); gsl_matrix_set(X,row,1,w2[row]); gsl_vector_set(ydat,row,y2[row]); } if (iter==0) { // printf("multi ordls: "); stat = gsl_multifit_linear(X,ydat,cvout,covmat,&sumsq,linws); // printf("stat = %d, beta=%f\n",stat,beta); } else { // printf("multi wls: "); setcovZZ(t2, L, N, alpha, beta, 1.0, covZZ); weights = gsl_vector_alloc(L); for (i=0;i<L;i++) { p2[i] = 1.0/covZZ[i][i]; gsl_vector_set(weights,i,p2[i]); } stat = gsl_multifit_wlinear(X,weights,ydat,cvout,covmat,&sumsq,linws); // printf("stat = %d, beta=%f\n",stat,beta); } if (alpha>1.98 || alpha < 0.05 || fabs(alpha-1.0)<0.05 || isnan(alpha)) { beta = 0.0; } else { beta = gsl_vector_get(cvout,1)/tan(alpha*M_PI*0.5); } estshift = gsl_vector_get(cvout,0); mu1 = mu1 + sigma * estshift; // printf("rem shift\n"); /*** remove estimated shift ***/ for (i=0;i<N;i++) { s[i] = s[i] - estshift; } if (isnan(alpha) || isnan(beta) || isnan(sigma) || isnan(mu1)) { iter++; break; } // printf("check conv"); /** check for convergence or blow up**/ diff = pow(alpha - alphaold,2) + pow(mu1 - mu1old,2); if (iter <= 2 && diff > diffmax) { diffmax = diff; } // else if (diff > 2.0*diffmax) { #ifdef DEBUG printf("blow up on iter %d\n",iter); #endif // break; // } // printf("check best\n"); if (fabs(diff) < diffbest) { alphabest = alpha; betabest = beta; sigmabest = sigma; mu1best = mu1; diffbest = diff; if (diff < xTol) { gsl_matrix_free(X); gsl_vector_free(ydat); if (iter>0) gsl_vector_free(weights); iter++; break; } } alphaold = alpha; mu1old = mu1; gsl_matrix_free(X); gsl_vector_free(ydat); if (iter>0) { gsl_vector_free(weights); } } if (maxiter > 0 && iter >= 0) { alpha = alphabest; beta = betabest; sigma = sigmabest; mu1 = mu1best; } if (alpha<0) alpha = 0; if (alpha>2) alpha = 2; if (beta<-1) beta = -1; if (beta> 1) beta = 1; if (sigma<0) sigma = 0; stable_setparams(dist,alpha,beta,sigma,mu1,1); free(t); free(p); free(w); free(y); free(phi); free(t2); free(p2); free(w2); free(y2); free(phi2); gsl_matrix_free(covmat); gsl_vector_free(cvout); free(s); if (iter>1) { free(covYY[0]); free(covYY); free(covZZ[0]); free(covZZ); } gsl_multifit_linear_free(linws); //printf(" iter %d diff %f a %f b %f s %f m %f\n",iter,diff,alpha,beta,sigma,dist->mu_0); return 0; } // end stable_fit_koutrouvelis int chooseK(double alpha, int N) { double a[]={1.9,1.5,1.3,1.1,.9,.7,.5,.3}; int n[] = {200, 800, 1600}; double Kmat[8][3]={{ 9, 9, 9}, {11,11,11}, {22,16,14}, {24,18,15}, {28,22,18}, {30,24,20}, {86,68,56}, {134,124,118}}; int i,j; double xi; double xj; double Kp; if (alpha < 0.3) alpha = 0.3; if (alpha > 1.9) alpha = 1.9; if (N<200) N=200; if (N>1600) N=1600; i=1; j=1; while (i<7 && a[i]>=alpha) { ++i; } while (j<2 && n[j]<=N) { ++j; } xi = 1.0 - (alpha-a[i])/(a[i-1]-a[i]); xj = 1.0 - (double)(n[j]-N)/(double)(n[j]-n[j-1]); // printf("i,j = %d, %d; xi,xj = %f, %f\n",i,j,xi,xj); /* bilinear interpolation */ Kp = xj * (xi * Kmat[i][ j ] + (1.0-xi) * Kmat[i-1][ j ] ) + (1.0-xj) * (xi * Kmat[i][j-1] + (1.0-xi) * Kmat[i-1][j-1] ); Kp = floor(Kp+.5); return (int)Kp; } int chooseL(double alpha, int N) { double a[]={1.9,1.5,1.1,.9,.7,.5,.3}; int n[] = {200, 800, 1600}; double Lmat[7][3]={{ 9,10,11}, {12,14,15}, {16,18,17}, {14,14,14}, {24,16,16}, {40,38,36}, {70,68,66}}; int i,j; double xi, xj; double Lp; if (alpha < 0.3) alpha = 0.3; if (alpha > 1.9) alpha = 1.9; if (N<200) N=200; if (N>1600) N=1600; i=1; j=1; while (i<6 && a[i]>=alpha) { ++i; } while (j<2 && n[j]<=N) { ++j; } xi = 1.0 - (alpha-a[i])/(a[i-1]-a[i]); xj = 1.0 - (double)(n[j]-N)/(double)(n[j]-n[j-1]); // printf("i,j = %d, %d; xi,xj = %f, %f\n",i,j,xi,xj); /* bilinear interpolation */ Lp = xj * (xi * Lmat[i][ j ] + (1.0-xi) * Lmat[i-1][ j ] ) + (1.0-xj) * (xi * Lmat[i][j-1] + (1.0-xi) * Lmat[i-1][j-1] ); Lp = floor(Lp + .5); return (int)Lp; } void setcovYY(const double * t, int K, int N, double alpha, double beta, double gam, double **covYY) { double w = tan(alpha*M_PI_2); double calpha = pow(gam,alpha); int j = 0, k = 0; double * talpha = (double *)malloc(K*sizeof(double)); for (j=0;j<K;j++) { talpha[j]=pow(fabs(t[j]),alpha); } double tj,tja,tk,tka; double tjmtka,tjptka,stj,stk; double A,B,D,E;//F,G,H; for (j=0;j<K;j++) { tj = t[j]; tja = talpha[j]; stj = sign(tj); for (k=0;k<K;k++) { tk = t[k]; tka = talpha[k]; stk = sign(tk); tjmtka = pow(fabs(tj-tk),alpha); tjptka = pow(fabs(tj+tk),alpha); A = calpha * (tja + tka - tjmtka); B = calpha * beta * (-tja * stj * w + tka * stk * w + tjmtka * sign(tj - tk) * w ); D = calpha * (tja + tka - tjptka); E = calpha * beta * ( tja * stj * w + tja * stk * w - tjptka * sign(tj + tk) * w ); // F = calpha * (tja + tka); // G = -calpha * tjmtka; // H = -calpha * tjptka; // printf("[j][k] = [%d][%d]",j,k);fflush(stdout); covYY[j][k] = (exp(A)*cos(B)+exp(D)*cos(E)-2.0) / ( 2.0 * N * pow(gam,2.0*alpha)*pow(fabs(tj*tk),alpha) ); // covZZ[j][k] = exp(F)*( exp(G)*cos(B)-exp(H)*cos(E) ) /(2.0*N); } } free(talpha); return; } void setcovZZ(const double * t, int K, int N, double alpha, double beta, double gam, double **covZZ) { double w = tan(alpha*M_PI_2); double calpha = pow(gam,alpha); int j = 0, k = 0; double * talpha = (double *)malloc(K*sizeof(double)); for (j=0;j<K;j++) { talpha[j]=pow(fabs(t[j]),alpha); } double tj,tja,tk,tka; double tjmtka,tjptka,stj,stk; double B,E,F,G,H; for (j=0;j<K;j++) { tj = t[j]; tja = talpha[j]; stj = sign(tj); for (k=0;k<K;k++) { tk = t[k]; tka = talpha[k]; stk = sign(tk); tjmtka = pow(fabs(tj-tk),alpha); tjptka = pow(fabs(tj+tk),alpha); // A = calpha * (tja + tka - tjmtka); B = calpha * beta * (-tja * stj * w + tka * stk * w + tjmtka * sign(tj - tk) * w ); // D = calpha * (tja + tka - tjptka); E = calpha * beta * ( tja * stj * w + tja * stk * w - tjptka * sign(tj + tk) * w ); F = calpha * (tja + tka); G = -calpha * tjmtka; H = -calpha * tjptka; // covYY[j][k] = (exp(A)*cos(B)+exp(D)*cos(E)-2.0) / ( 2.0 * N * pow(gam,2.0*alpha)*pow(fabs(tj*tk),alpha) ); covZZ[j][k] = exp(F)*( exp(G)*cos(B)-exp(H)*cos(E) ) /(2.0*N); } } free(talpha); return; } double ecfRoot(const double * data, int N) { double m=0; int i; for(i=0;i<N;i++) { m += fabs(data[i]); } m = m/N; double t = 0; gsl_complex val = stable_samplecharfunc_point(data, N, t); int iter=0; while (iter<10000 && fabs(GSL_REAL(val))>1e-3) { t += GSL_REAL(val)/m; val = stable_samplecharfunc_point(data, N, t); } return t; } gsl_complex stable_samplecharfunc_point(const double* x, const unsigned int N, double t) { unsigned int i; double zr=0.0,zi=0.0; gsl_complex z; for(i=0;i<N;i++) { zr+=cos(t*x[i]); zi+=sin(t*x[i]); } GSL_SET_COMPLEX(&z,zr/N,zi/N); return z; } void stable_samplecharfunc(const double* x, const unsigned int Nx, const double* t, const unsigned int Nt, gsl_complex *z) { unsigned int ix,it; double zr=0.0,zi=0.0,w; for(it=0;it<Nt;it++) { w = t[it]; zr = .0; zi = .0; for(ix=0;ix<Nx;ix++) { zr+=cos(w*x[ix]); zi+=sin(w*x[ix]); } // if (isnan(zr*zi) || isinf(zr*zi)) { // printf("Bad cfuncpoint: z[%d] = z(%f) = %f +i%f",it,w,zr,zi); // } GSL_SET_COMPLEX(&z[it],zr/Nx,zi/Nx); } return; }
{ "alphanum_fraction": 0.5375722543, "avg_line_length": 24.9098101266, "ext": "c", "hexsha": "bd259b36bb8a9dffeb1d1bc82542ac04eea8f7b5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "TantraLabs/gonum", "max_forks_repo_path": "stat/distuv/libs/libstable/stable/src/stable_koutrouvelis.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "TantraLabs/gonum", "max_issues_repo_path": "stat/distuv/libs/libstable/stable/src/stable_koutrouvelis.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "TantraLabs/gonum", "max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable_koutrouvelis.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5520, "size": 15743 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_linalg.h> typedef struct Vortex { double x, y; double vorticity; int active; } Vortex; /* possibly should be replaced with one function? */ double Qfield_x(double x, double y) { double r = x*x+y*y; return -y/(2*M_PI*fmax(r,1/1024/1024)); // return -y/(2*M_PI*fmax(r,1/1024)); } double Qfield_y(double x, double y) { double r = x*x+y*y; return x/(2*M_PI*fmax(r,1/1024/1024)); } double Pfield_x(double x, double y) { double r = hypot(x,y); if(r == 0) return 1.; return x/r*exp(-r); } double Pfield_y(double x, double y) { double r = hypot(x,y); if(r == 0) return 1.; return y/r*exp(-r); } double Mfield(double x, double y) { double r2= x*x+y*y; double r = sqrt(r2); if(x==0 && y==0) return 0.; return (r+1.)*exp(-r)/r2; } int VortexInBody(double x, double y) { if(x*x+y*y<1) return 1; else return 0; } int main(int argc, char **argv) { int NumberOfPanels = 12, MaxVortexes = 16500, Niterations = 200, i,j,k,m,n, iterator; double nu = 1/13, tau = 0.005/*, eps = 0.002*/, rho = 1.; double vx_inf = 1., vy_inf = 0.; double PanelNodes [NumberOfPanels][2], PanelMids [NumberOfPanels][2], PanelNorms [NumberOfPanels][2], PanelTaus [NumberOfPanels][2], PanelLength[NumberOfPanels]; double DeployPoints[NumberOfPanels][2]; Vortex InFlow[MaxVortexes], NextInFlow[MaxVortexes]; int ActiveVortexesInFLow=0; if(1)/* cylinder profile forming & deploys */ { for(i=0;i<NumberOfPanels;i++) { PanelNodes[i][0] = cos(2.*M_PI/NumberOfPanels*i); PanelNodes[i][1] = sin(2.*M_PI/NumberOfPanels*i); DeployPoints[i][0] = 1.05*PanelNodes[i][0]; DeployPoints[i][1] = 1.05*PanelNodes[i][1]; PanelNorms[i][0] = cos(2.*M_PI/NumberOfPanels*(i+0.5)); PanelNorms[i][1] = sin(2.*M_PI/NumberOfPanels*(i+0.5)); } for(i=0;i<NumberOfPanels-1;i++) { PanelMids[i][0] = (PanelNodes[i][0]+PanelNodes[i+1][0])/2; PanelMids[i][1] = (PanelNodes[i][1]+PanelNodes[i+1][1])/2; PanelTaus[i][0] = (PanelNodes[i+1][0]-PanelNodes[i][0]); PanelTaus[i][1] = (PanelNodes[i+1][1]-PanelNodes[i][1]); PanelLength[i] = sqrt(PanelTaus[i][0]*PanelTaus[i][0]+ PanelTaus[i][1]*PanelTaus[i][1]); PanelTaus[i][0] /= PanelLength[i]; PanelTaus[i][1] /= PanelLength[i]; // PanelNorms[i][0] = -PanelTaus[i][1]; // PanelNorms[i][1] = PanelTaus[i][0]; } PanelMids[NumberOfPanels-1][0] = (PanelNodes[NumberOfPanels-1][0]+PanelNodes[0][0])/2; PanelMids[NumberOfPanels-1][1] = (PanelNodes[NumberOfPanels-1][1]+PanelNodes[0][1])/2; PanelTaus[NumberOfPanels-1][0] = (PanelNodes[0][0]-PanelNodes[NumberOfPanels-1][0]); PanelTaus[NumberOfPanels-1][1] = (PanelNodes[0][1]-PanelNodes[NumberOfPanels-1][1]); PanelLength[NumberOfPanels-1] = hypot(PanelTaus[NumberOfPanels-1][0],PanelTaus[NumberOfPanels-1][1]); PanelTaus[NumberOfPanels-1][0] /= PanelLength[NumberOfPanels-1]; PanelTaus[NumberOfPanels-1][1] /= PanelLength[NumberOfPanels-1]; // PanelNorms[Np-1][0] = -PanelTaus[Np-1][1]; // PanelNorms[Np-1][1] = PanelTaus[Np-1][0]; } // defining and completing Vortex Birth Matrix gsl_matrix *OriginalVortexGenerationMatrix = gsl_matrix_alloc(NumberOfPanels+1,NumberOfPanels+1); gsl_matrix *VortexGenerationMatrix = gsl_matrix_alloc(NumberOfPanels+1,NumberOfPanels+1); for(i=0; i<NumberOfPanels; i++) { for(j=0; j<NumberOfPanels; j++) { gsl_matrix_set(VortexGenerationMatrix,i,j, PanelNorms[i][0]*Qfield_x(PanelMids[i][0]-DeployPoints[j][0], PanelMids[i][1]-DeployPoints[j][1]) +PanelNorms[i][1]*Qfield_y(PanelMids[i][0]-DeployPoints[j][0], PanelMids[i][1]-DeployPoints[j][1])); } } for(i=0;i<NumberOfPanels;i++) { gsl_matrix_set(VortexGenerationMatrix,NumberOfPanels,i,1); gsl_matrix_set(VortexGenerationMatrix,i,NumberOfPanels,1); } gsl_matrix_set(VortexGenerationMatrix,NumberOfPanels,NumberOfPanels,0); gsl_matrix_memcpy(OriginalVortexGenerationMatrix,VortexGenerationMatrix); // recieve initial aproximation for vortexes on surface gsl_vector *VelocityOnInfProjections = gsl_vector_alloc(NumberOfPanels+1); //Velocity On Infinity gsl_vector *VelocityProjections = gsl_vector_alloc(NumberOfPanels+1); //Velocity from active vortexes // gsl_vector *velocities_on_surface = gsl_vector_alloc(Np+1); //full velocity on surface = VOI + VFV gsl_vector *NewVorticities = gsl_vector_alloc(NumberOfPanels+1); for(i=0;i<NumberOfPanels;i++) { gsl_vector_set(VelocityOnInfProjections,i,-(PanelNorms[i][0]*vx_inf+PanelNorms[i][1]*vy_inf)); } gsl_vector_set(VelocityOnInfProjections,NumberOfPanels,0.); gsl_permutation * p = gsl_permutation_alloc (NumberOfPanels+1); gsl_linalg_LU_decomp(VortexGenerationMatrix,p,&k); gsl_linalg_LU_solve (VortexGenerationMatrix,p,VelocityOnInfProjections,NewVorticities); FILE *forces; forces = fopen("forces.dat","w"); for(iterator=0; iterator<Niterations; iterator++) { double f_x = 0., f_y = 0./*, M_z = 0.*/; //add generated vortexes to flow for(i=0;i<NumberOfPanels;i++) { InFlow[ActiveVortexesInFLow+i].active = 1; InFlow[ActiveVortexesInFLow+i].vorticity = gsl_vector_get(NewVorticities,i); InFlow[ActiveVortexesInFLow+i].x = DeployPoints[i][0]; InFlow[ActiveVortexesInFLow+i].y = DeployPoints[i][1]; } ActiveVortexesInFLow += NumberOfPanels; // time iteration printf("active vortexes %d\n",ActiveVortexesInFLow); for(i=0;i<ActiveVortexesInFLow;i++) { while(InFlow[i].active!=1)i++; double eps = sqrt(4/3)*PanelLength[0]/1000; double I0 = 2*M_PI*eps*eps, I1 = 0., I2_x = 0., I2_y = 0., I3_x = 0., I3_y = 0.; double u_x = vx_inf; double u_y = vy_inf; //Epsilon update if(iterator>5 && 0) { double sq1=1., sq2=1., sq3=1.; for(j=0;j<ActiveVortexesInFLow;j++) { double temp = (InFlow[i].x-InFlow[j].x)*(InFlow[i].x-InFlow[j].x) +(InFlow[i].y-InFlow[j].y)*(InFlow[i].y-InFlow[j].y); if(i!=j && temp < sq1 && InFlow[j].active==1 && InFlow[i].vorticity*InFlow[j].vorticity>0 ) { sq1 = temp; sq2 = sq1; sq3 = sq2; } } eps = sqrt( (sq1+sq2+sq3)/3 ); } //Vortex-caused part of velocity for(j=0;j<ActiveVortexesInFLow;j++) { double rx = InFlow[i].x-InFlow[j].x; double ry = InFlow[i].y-InFlow[j].y; if( InFlow[j].active==1 && i!=j /*&& fabs(rx) > 1/1024.*0.25 && fabs(ry) > 1/1024.*0.25*/ ) { u_x += InFlow[j].vorticity*Qfield_x(rx,ry); u_y += InFlow[j].vorticity*Qfield_y(rx,ry); } } //Viscous component of velocity for(j=0;j<ActiveVortexesInFLow;j++) { if( InFlow[j].active==1 ) { I2_x += InFlow[j].vorticity*Pfield_x((InFlow[i].x-InFlow[j].x)/eps,(InFlow[i].y-InFlow[j].y)/eps)/eps; I2_y += InFlow[j].vorticity*Pfield_y((InFlow[i].x-InFlow[j].x)/eps,(InFlow[i].y-InFlow[j].y)/eps)/eps; I1 += InFlow[j].vorticity*exp(-hypot((InFlow[i].x-InFlow[j].x),(InFlow[i].y-InFlow[j].y))/eps); } } for(j=0;j<NumberOfPanels;j++) { double Rr = hypot((InFlow[i].x-PanelMids[j][0]),(InFlow[i].y-PanelMids[j][1])); I3_x -= PanelNorms[j][0]*exp(-Rr/eps)*PanelLength[j]; I3_y -= PanelNorms[j][1]*exp(-Rr/eps)*PanelLength[j]; I0 -= ((InFlow[i].x-PanelMids[j][0])*PanelNorms[j][0] +(InFlow[i].y-PanelMids[j][1])*PanelNorms[j][1]) *PanelLength[j] *Mfield((InFlow[i].x-PanelMids[j][0])/eps, (InFlow[i].y-PanelMids[j][1])/eps); } // printf("%f %f\n",u_x,u_y); u_x += nu*(-I2_x/I1+I3_x/I0); u_y += nu*(-I2_y/I1+I3_y/I0); // printf("%f %f\n",u_x,u_y); if(tau*u_x < 1000 && tau*u_y < 1000 ) { NextInFlow[i].x = InFlow[i].x + tau*u_x; NextInFlow[i].y = InFlow[i].y + tau*u_y; // int minRmid = 0; //контроль протекания double Rmid = sqrt((PanelMids[0][0]-NextInFlow[i].x)*(PanelMids[0][0]-NextInFlow[i].x)+ (PanelMids[0][1]-NextInFlow[i].y)*(PanelMids[0][1]-NextInFlow[i].y)); double projectionDistOnMidVector = (PanelMids[0][0]*NextInFlow[i].x+PanelMids[0][1]*NextInFlow[i].y)/ (PanelMids[0][0]*PanelMids[0][0]+PanelMids[0][1]*PanelMids[0][1]); for(m=1;m<NumberOfPanels;m++) { double temp = sqrt((PanelMids[m][0]-NextInFlow[i].x)*(PanelMids[m][0]-NextInFlow[i].x)+ (PanelMids[m][1]-NextInFlow[i].y)*(PanelMids[m][1]-NextInFlow[i].y)); if(fmin(Rmid,temp)<Rmid) { Rmid = temp; // minRmid = m; projectionDistOnMidVector = (PanelMids[m][0]*NextInFlow[i].x+PanelMids[m][1]*NextInFlow[i].y)/ (PanelMids[m][0]*PanelMids[m][0]+PanelMids[m][1]*PanelMids[m][1]); } } // if(!VortexInBody(NextInFlow[i].x,NextInFlow[i].y)) if(projectionDistOnMidVector > 1.) { NextInFlow[i].active = InFlow[i].active; NextInFlow[i].vorticity = InFlow[i].vorticity; } else { NextInFlow[i].active = 3; NextInFlow[i].vorticity = InFlow[i].vorticity; } } else { NextInFlow[i].x = InFlow[i].x; NextInFlow[i].y = InFlow[i].y; NextInFlow[i].active = 2; NextInFlow[i].vorticity = InFlow[i].vorticity; } // if(NextInFlow[i].vorticity<0.01) } for(m = 0; m < NumberOfPanels; m++) { f_x += -rho*(gsl_vector_get(NewVorticities,m)/tau* PanelMids[m][1]); f_y += rho*(gsl_vector_get(NewVorticities,m)/tau* PanelMids[m][0]); } fprintf(forces,"%f %f %f\n",iterator*tau, f_x, f_y); //updating coords for(i=0;i<ActiveVortexesInFLow;i++) { InFlow[i] = NextInFlow[i]; } //definition of speed from vortexes after iteration double VelocityProjInControlPoint[NumberOfPanels]; for(j=0; j<NumberOfPanels; j++) VelocityProjInControlPoint[j] = PanelNorms[j][0]*vx_inf + PanelNorms[j][1]*vy_inf; for(i=0; i<ActiveVortexesInFLow; i++) { if(InFlow[i].active==1) { for(j=0; j<NumberOfPanels; j++) { VelocityProjInControlPoint[j] += (PanelNorms[j][0]*Qfield_x((PanelMids[j][0]-InFlow[i].x), (PanelMids[j][1]-InFlow[i].y)) +PanelNorms[j][1]*Qfield_y((PanelMids[j][0]-InFlow[i].x), (PanelMids[j][1]-InFlow[i].y))) *InFlow[i].vorticity; } } } for(j=0; j<NumberOfPanels; j++) gsl_vector_set(VelocityProjections,j,-VelocityProjInControlPoint[j]); gsl_vector_set(VelocityProjections,NumberOfPanels,0); gsl_matrix_memcpy(VortexGenerationMatrix, OriginalVortexGenerationMatrix); gsl_linalg_LU_decomp(VortexGenerationMatrix,p,&k); gsl_linalg_LU_solve (VortexGenerationMatrix,p,VelocityProjections,NewVorticities); if(iterator%10==0) { /* FILE *VortexesOut, *BodyOut, *averagedOut; VortexesOut = fopen("MVE_flow.dat","w"); BodyOut = fopen("MVE_body.dat","w"); averagedOut = fopen("MVE_aver.dat","w"); for(i=0;i<ActiveVortexesInFLow;i++) { if(InFlow[i].active==1) fprintf(VortexesOut,"%f %f %f\n",InFlow[i].x,InFlow[i].y,InFlow[i].vorticity); } for(i=0; i<Np; i++) fprintf(BodyOut,"%f %f\n", DeployPoints[i][0], DeployPoints[i][1]); double averagedVorticity[101][101]; for(i=0;i<ActiveVortexesInFLow;i++) { if(fabs(InFlow[i].x)<=10 && fabs(InFlow[i].y)<=10 && InFlow[i].active == 1) { averagedVorticity[(int)(50+(InFlow[i].x)/0.2)][(int)(50+(InFlow[i].y)/0.2)] += InFlow[i].vorticity*0.04; } } for(i=0;i<101;i++) { for(j=0;j<101;j++) fprintf(averagedOut,"%f %f %f\n", -10+i*0.2, -10+j*0.02, averagedVorticity[i][j]); } fclose(averagedOut); fclose(VortexesOut); fclose(BodyOut); int temp; system("screen -S gnuplot -X stuff \"replot^M\" "); scanf("%d",&temp); if(ActiveVortexesInFLow<16000) Niterations +=temp; else return 0; // system("screen -S gnuplot -X stuff \"plot \'MVE_flow.dat\' using 1:2, \'MVE_body.dat\' w line^M\" "); */ char FileName[32]; sprintf(FileName,"VelocityFiled%6.6d.dat",iterator); FILE *VelocityField; VelocityField = fopen(FileName,"w"); fprintf(VelocityField,"TITLE = \"Flow Model\"\n"); fprintf(VelocityField,"VARIABLES = \"x\", \"y\", \"vx\", \"vy\"\n"); fprintf(VelocityField,"ZONE T=\"Frame 0\", I=%d, J=%d\n", 200, 100); for(i=0;i<200;i++) { for(j=0;j<100;j++) { double vx=vx_inf, vy=vy_inf; for(n=0;n<ActiveVortexesInFLow;n++) { if(InFlow[n].active==1) { vx += InFlow[n].vorticity*Qfield_x((0.04*i-2)-InFlow[n].x, (0.04*j-2)-InFlow[n].y); vy += InFlow[n].vorticity*Qfield_y((0.04*i-2)-InFlow[n].x, (0.04*j-2)-InFlow[n].y); } } fprintf(VelocityField,"%f %f %f %f\n",0.04*i-2, 0.04*j-2, vx, vy); } } } } /* //the most interesting part: output of results FILE *VortexesOut, *BodyOut, *averagedOut; VortexesOut = fopen("MVE_flow.dat","w"); BodyOut = fopen("MVE_body.dat","w"); averagedOut = fopen("MVE_aver.dat","w"); for(i=0;i<ActiveVortexesInFLow;i++) { if(InFlow[i].active==1) fprintf(VortexesOut,"%f %f %f\n",InFlow[i].x,InFlow[i].y,InFlow[i].vorticity); } for(i=0; i<Np; i++) fprintf(BodyOut,"%f %f\n", DeployPoints[i][0], DeployPoints[i][1]); double averagedVorticity[101][101]; for(i=0;i<ActiveVortexesInFLow;i++) { if(fabs(InFlow[i].x)<=10 && fabs(InFlow[i].y)<=10 && InFlow[i].active == 1) { averagedVorticity[(int)(50+(InFlow[i].x)/0.2)][(int)(50+(InFlow[i].y)/0.2)] += InFlow[i].vorticity*0.04; } } for(i=0;i<101;i++) { for(j=0;j<101;j++) fprintf(averagedOut,"%f %f %f\n", -10+i*0.2, -10+j*0.02, averagedVorticity[i][j]); } fclose(averagedOut); fclose(VortexesOut); fclose(BodyOut); */ return 0; }
{ "alphanum_fraction": 0.5040234949, "avg_line_length": 35.395010395, "ext": "c", "hexsha": "3d49b979e5475efe79183747becd3d6ed844a251", "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": "9666c4488c611b211337c1a00f181bd75b7daf0c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "VVBondarenko/CFD_MoDV", "max_forks_repo_path": "c_src/MVE/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9666c4488c611b211337c1a00f181bd75b7daf0c", "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": "VVBondarenko/CFD_MoDV", "max_issues_repo_path": "c_src/MVE/main.c", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "9666c4488c611b211337c1a00f181bd75b7daf0c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "VVBondarenko/CFD_MoDV", "max_stars_repo_path": "c_src/MVE/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4949, "size": 17025 }
#pragma once #include <memory> #include <string> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "chainerx/backend.h" #include "chainerx/context.h" #include "chainerx/device.h" #include "chainerx/kernel_registry.h" namespace chainerx { namespace cuda { class CudaDevice; class CudaBackend; namespace cuda_internal { // Creates a device instance. // This function is meant to be used from the backend class. Never use it for other purpose. // This is defined in cuda_internal namespace in order to make it a friend of CudaDevice // class. gsl::owner<CudaDevice*> CreateDevice(CudaBackend& backend, int index); } // namespace cuda_internal class CudaBackend : public Backend { public: static constexpr const char* kDefaultName = "cuda"; static constexpr const size_t kCudnnDefaultMaxWorkspaceSize = 8 * 1024 * 1024; static constexpr const char* kCudnnMaxWorkspaceSizeEnvVarName = "CHAINERX_CUDNN_MAX_WORKSPACE_SIZE"; using Backend::Backend; std::string GetName() const override; int GetDeviceCount() const override; bool SupportsTransfer(Device& src_device, Device& dst_device) override; // TODO(hvy): Move to CudaDevice. // Sets maximum cuDNN workspace size. // This value is shared across threads. void SetCudnnMaxWorkspaceSize(size_t max_workspace_size); // TODO(hvy): Move to CudaDevice. // Gets maximum cuDNN workspace size. size_t GetCudnnMaxWorkspaceSize(); static KernelRegistry& GetGlobalKernelRegistry() { static gsl::owner<KernelRegistry*> global_kernel_registry = new KernelRegistry{}; return *global_kernel_registry; } protected: KernelRegistry& GetParentKernelRegistry() override { return GetGlobalKernelRegistry(); } private: std::unique_ptr<Device> CreateDevice(int index) override; // TODO(hvy): Move to CudaDevice. nonstd::optional<size_t> cudnn_max_workspace_size_{}; std::mutex mutex_; }; } // namespace cuda } // namespace chainerx
{ "alphanum_fraction": 0.7406847936, "avg_line_length": 27.5833333333, "ext": "h", "hexsha": "9e5742c596568078fc4e75aeb7a6448392823981", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-26T10:27:27.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:24:47.000Z", "max_forks_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tkerola/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "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": "tkerola/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "572f6eef2c3f1470911ac08332c2b5c3440edf44", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tkerola/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/cuda/cuda_backend.h", "max_stars_repo_stars_event_max_datetime": "2021-02-26T10:27:25.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-26T10:27:25.000Z", "num_tokens": 475, "size": 1986 }
/** * * @file core_cpltmg_condex.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated c Tue Jan 7 11:44:47 2014 * **/ #include <math.h> #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex32_t * * CORE_cpltmg_condexq generates the Q used in condex matrix generation * * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999898 * gallery('condex',n,4,100) * * Returns a "counter-example" matrix to a condition estimator. It has order n * and scalar parameter theta (default 100). * * LAPACK (RCOND): It is the inverse of this matrix that is a counter-example. * ******************************************************************************* * * @param[in] M * The number of rows of the matrix Q used in condex generation. M >= 0. * * @param[in] N * The number of columns of the matrix A to be generated. N >= 0. * * @param[out] Q * On entry, the M-by-3 matrix to be initialized. * On exit, the housholder reflectors required for condex generation. * * @param[in] LDQ * The leading dimension of the matrix Q. LDQ >= max(1,M). * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cpltmg_condexq = PCORE_cpltmg_condexq #define CORE_cpltmg_condexq PCORE_cpltmg_condexq #endif void CORE_cpltmg_condexq( int M, int N, PLASMA_Complex32_t *Q, int LDQ ) { PLASMA_Complex32_t tau[3]; PLASMA_Complex32_t *tQ = Q; int i; /* First column is [ 1 ... 1 ] */ for( i=0; i < M; i++, tQ++ ) *tQ = (PLASMA_Complex32_t)1.0; /* Second column is [1 0 0 ... 0] */ tQ = Q + LDQ; *tQ = (PLASMA_Complex32_t)1.; tQ++; memset( tQ, 0, (M-1) * sizeof(PLASMA_Complex32_t) ); /* Third column is (-1)^i * (1. + i / (N-1)) */ tQ = Q + 2 * LDQ; for( i=0; i<M; i++, tQ++ ) *tQ = (PLASMA_Complex32_t)( cpowf( -1.0, (float)i ) * (1.0 + (float)i/(N-1) ) ); /* Generate orthogonal projector */ LAPACKE_cgeqrf( LAPACK_COL_MAJOR, M, 3, Q, LDQ, tau ); LAPACKE_cungqr( LAPACK_COL_MAJOR, M, 3, 3, Q, LDQ, tau ); return; }
{ "alphanum_fraction": 0.5645559211, "avg_line_length": 30.4, "ext": "c", "hexsha": "7fa812ce072e8647e2b262b369763d92de8570f5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_cpltmg_condex.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_cpltmg_condex.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_cpltmg_condex.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 762, "size": 2432 }
/* multifit/gcv.c * * Copyright (C) 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * References: * * [1] P. C. Hansen, "Discrete Inverse Problems: Insight and Algorithms," * SIAM Press, 2010. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_min.h> typedef struct { const gsl_vector * S; const gsl_vector * UTy; double delta0; size_t np; gsl_vector * workp; } gcv_params; static double gcv_func(double lambda, void * params); /* gsl_multifit_linear_gcv_init() Initialize Generalized Cross Validation parameters Inputs: y - right hand side vector reg_param - (output) regularization parameters UTy - (output) U^T y delta0 - (output) delta0 work - workspace */ int gsl_multifit_linear_gcv_init(const gsl_vector * y, gsl_vector * reg_param, gsl_vector * UTy, double * delta0, gsl_multifit_linear_workspace * work) { const size_t n = y->size; if (n != work->n) { GSL_ERROR("y vector does not match workspace", GSL_EBADLEN); } else if (UTy->size != work->p) { GSL_ERROR ("UTy vector does not match workspace", GSL_EBADLEN); } else { const size_t p = work->p; gsl_matrix_view U = gsl_matrix_submatrix(work->A, 0, 0, n, p); gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); const double smax = gsl_vector_get(&S.vector, 0); const double smin = gsl_vector_get(&S.vector, p - 1); double dr; /* residual error from projection */ double normy = gsl_blas_dnrm2(y); double normUTy; /* compute projection UTy = U^T y */ gsl_blas_dgemv (CblasTrans, 1.0, &U.matrix, y, 0.0, UTy); normUTy = gsl_blas_dnrm2(UTy); /* dr = ||y||^2 - ||U^T y||^2 */ dr = (normy + normUTy) * (normy - normUTy); /* calculate regularization parameters */ gsl_multifit_linear_lreg(smin, smax, reg_param); if (n > p && dr > 0.0) *delta0 = dr; else *delta0 = 0.0; return GSL_SUCCESS; } } /* gsl_multifit_linear_gcv_curve() Calculate Generalized Cross Validation curve for a set of regularization parameters Inputs: reg_param - regularization parameters UTy - U^T y vector, size p delta0 - delta0 G - (output) GCV curve values work - workspace */ int gsl_multifit_linear_gcv_curve(const gsl_vector * reg_param, const gsl_vector * UTy, const double delta0, gsl_vector * G, gsl_multifit_linear_workspace * work) { const size_t n = work->n; const size_t p = work->p; const size_t N = reg_param->size; /* number of points on GCV curve */ if (UTy->size != p) { GSL_ERROR("UTy vector does not match workspace", GSL_EBADLEN); } else if (G->size != N) { GSL_ERROR ("size of reg_param and G vectors do not match", GSL_EBADLEN); } else { size_t i; gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p); gcv_params params; params.S = &S.vector; params.UTy = UTy; params.delta0 = delta0; params.np = n - p; params.workp = &workp.vector; for (i = 0; i < N; ++i) { double lambdai = gsl_vector_get(reg_param, i); double Gi = gcv_func(lambdai, &params); gsl_vector_set(G, i, Gi); } return GSL_SUCCESS; } } /* gsl_multifit_linear_gcv_min() Find regularization parameter which minimizes GCV curve Inputs: reg_param - regularization parameters UTy - U^T y vector, size p G - GCV curve values delta0 - delta0 lambda - (output) optimal regularization parameter work - workspace */ int gsl_multifit_linear_gcv_min(const gsl_vector * reg_param, const gsl_vector * UTy, const gsl_vector * G, const double delta0, double * lambda, gsl_multifit_linear_workspace * work) { const size_t n = work->n; const size_t p = work->p; const size_t npts = reg_param->size; /* number of points on GCV curve */ if (UTy->size != p) { GSL_ERROR("UTy vector does not match workspace", GSL_EBADLEN); } else if (G->size != npts) { GSL_ERROR ("size of reg_param and G vectors do not match", GSL_EBADLEN); } else { int status; const size_t max_iter = 500; const double tol = 1.0e-4; gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p); gcv_params params; int idxG = (int) gsl_vector_min_index(G); double a = gsl_vector_get(reg_param, GSL_MIN(idxG + 1, (int) npts - 1)); double b = gsl_vector_get(reg_param, GSL_MAX(idxG - 1, 0)); double m = gsl_vector_get(reg_param, idxG); size_t iter = 0; gsl_function F; /* XXX FIXME */ gsl_min_fminimizer *min_workspace_p; if (idxG == 0 || idxG == ((int)npts - 1)) { /* the minimum is an endpoint of the curve, no need to search */ *lambda = m; return GSL_SUCCESS; } /* XXX FIXME */ min_workspace_p = gsl_min_fminimizer_alloc(gsl_min_fminimizer_brent); params.S = &S.vector; params.UTy = UTy; params.delta0 = delta0; params.np = n - p; params.workp = &workp.vector; F.function = gcv_func; F.params = &params; gsl_min_fminimizer_set(min_workspace_p, &F, m, a, b); do { iter++; status = gsl_min_fminimizer_iterate(min_workspace_p); a = gsl_min_fminimizer_x_lower(min_workspace_p); b = gsl_min_fminimizer_x_upper(min_workspace_p); status = gsl_min_test_interval(a, b, 0.0, tol); } while (status == GSL_CONTINUE && iter < max_iter); if (status == GSL_SUCCESS) *lambda = gsl_min_fminimizer_minimum(min_workspace_p); else status = GSL_EMAXITER; gsl_min_fminimizer_free(min_workspace_p); return status; } } /* gsl_multifit_linear_gcv_calc() Calculate GCV function G(lambda) for given lambda Inputs: reg_param - regularization parameters UTy - U^T y vector, size p delta0 - delta0 G - (output) GCV curve values work - workspace */ double gsl_multifit_linear_gcv_calc(const double lambda, const gsl_vector * UTy, const double delta0, gsl_multifit_linear_workspace * work) { const size_t n = work->n; const size_t p = work->p; if (UTy->size != p) { GSL_ERROR_VAL("UTy vector does not match workspace", GSL_EBADLEN, 0.0); } else { gsl_vector_view S = gsl_vector_subvector(work->S, 0, p); gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p); gcv_params params; double G; params.S = &S.vector; params.UTy = UTy; params.delta0 = delta0; params.np = n - p; params.workp = &workp.vector; G = gcv_func(lambda, &params); return G; } } /* gsl_multifit_linear_gcv() Calculate Generalized Cross Validation curve for a set of regularization parameters Inputs: y - right hand side vector reg_param - (output) regularization parameters G - (output) GCV curve values lambda - (output) optimal regularization parameter which minimizes GCV curve G_lambda - (output) G(lambda) value at optimal parameter work - workspace */ int gsl_multifit_linear_gcv(const gsl_vector * y, gsl_vector * reg_param, gsl_vector * G, double * lambda, double * G_lambda, gsl_multifit_linear_workspace * work) { const size_t n = y->size; const size_t N = G->size; /* number of points on GCV curve */ if (n != work->n) { GSL_ERROR("y vector does not match workspace", GSL_EBADLEN); } else if (reg_param->size != N) { GSL_ERROR ("size of reg_param and G vectors do not match", GSL_EBADLEN); } else { int status; const size_t p = work->p; gsl_vector_view UTy = gsl_vector_subvector(work->xt, 0, p); double delta0; status = gsl_multifit_linear_gcv_init(y, reg_param, &UTy.vector, &delta0, work); if (status) return status; status = gsl_multifit_linear_gcv_curve(reg_param, &UTy.vector, delta0, G, work); if (status) return status; status = gsl_multifit_linear_gcv_min(reg_param, &UTy.vector, G, delta0, lambda, work); if (status) return status; *G_lambda = gsl_multifit_linear_gcv_calc(*lambda, &UTy.vector, delta0, work); return GSL_SUCCESS; } } static double gcv_func(double lambda, void * params) { gcv_params * par = (gcv_params *) params; const gsl_vector *S = par->S; const gsl_vector *UTy = par->UTy; double delta0 = par->delta0; size_t np = par->np; gsl_vector *workp = par->workp; const size_t p = S->size; size_t i; double lambda_sq = lambda * lambda; double G, d, norm; double sumf = 0.0; /* compute workp = 1 - filter_factors */ for (i = 0; i < p; ++i) { double si = gsl_vector_get(S, i); double fi = lambda_sq / (si * si + lambda_sq); gsl_vector_set(workp, i, fi); sumf += fi; } d = (double)np + sumf; gsl_vector_mul(workp, UTy); norm = gsl_blas_dnrm2(workp); G = (norm*norm + delta0) / (d * d); return G; }
{ "alphanum_fraction": 0.5952512424, "avg_line_length": 27.3015075377, "ext": "c", "hexsha": "2b28535e870b1affffb5935e28826606e2d708b7", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/gcv.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/gcv.c", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multifit/gcv.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": 2911, "size": 10866 }
#ifndef _MATH_FUNCTIONS_H_ #define _MATH_FUNCTIONS_H_ extern "C" { #include <cblas.h> } #include <math.h> #include <xmmintrin.h> //#include <omp.h> #include <cublas_v2.h> #include "arena.h" void cpu_rearrange(int batch_size, int input_dim, int num_blocks, const float *T, float *X); void gpu_rearrange(int batcch_size, int input_dim, int num_blocks, const float *T, float *X); void svd2x2(const float a[4], float u[4], float s[2], float v[4]); void matmulcomplex2x2(const float A[8], const float B[8], float C[8]); void conjugate_transpose2x2(float M[8]); void conjugate_transpose2x2(const float M[8], float R[8]); void cpu_complex_modulus_interleaved_relu(int M, int N, const float *X, const float* b, float* Y); void cpu_permute_forward(int N, const float*X, const int* PI, float* Y); void cpu_permute_backward(int N, const float*X, const int* PI, float* Y); void cpu_diag_gemm(int M, int N, float alpha, const float* X, const float* W, float beta, float *Y ); void gpu_diag_gemm(int M, int N, float alpha, const float* X, const float* W, float beta, float *Y ); void cpu_permute(int M, int N, const float* PI, const float* X, float* Y); void gpu_permute(int M, int N, const float* PI, const float* X, float* Y); float cpu_relative_error(int N, const float* grad_ptr, const float* numer_grad_ptr); void gpu_real_svd(int M, int N, float *A, float *U, float *S, float *V); void gpu_unitary_svd(int M, int N, float *A, float *U, float *S, float *V); void gpu_random_orthogonal_matrix(int N, float *W); void gpu_random_unitary_matrix(int N, float *W); void cpu_initialize_svd2x2(int N, float* W); void cpu_initialize_complexsvd2x2(int N, float* W); void cpu_initialize_unitary(int NF, int* factor_sizes, float *W); void cpu_initialize_orthogonal(int NF, int* factor_sizes, float *W); void gpu_initialize_unitary(int NF, int* factor_sizes, float *W); void gpu_initialize_orthogonal(int NF, int* factor_sizes, float *W); void cpu_initialize_glorot10(int NF, int* factor_sizes, float *W); float cpu_complexdet2x2(const float W[8], float D[2]); void cpu_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); void gpu_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); void cpu_complex_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); void cpu_real_complex_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); void gpu_complex_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); void gpu_real_complex_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int M, int N, int K, const float alpha, const float* A, const float* B, const float beta, float* C); //Y = X + a * I void gpu_apx(int N, float a, const float* X, float* Y); void gpu_complex_apx(int N, float a, const float* X, float* Y); void gpu_geam(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, int m, int n, const float *alpha, const float *A, const float *beta, const float *B, float *C); void cpu_gemv(const CBLAS_TRANSPOSE TransA, int M, int N, const float alpha, const float* A, const float* x, const float beta, float* y); void gpu_gemv(const CBLAS_TRANSPOSE TransA, int M, int N, const float alpha, const float* A, const float* x, const float beta, float* y); void cpu_axpy(int N, const float alpha, const float* X, float* Y); void gpu_axpy(int N, const float alpha, const float* X, float* Y); void gpu_complex_axpy(int N, const float alpha, const float* X, float* Y); void cpu_addscalar(int N, const float alpha, const float* X, float* Y); void gpu_addscalar(int N, const float alpha, const float* X, float* Y); void cpu_axpby(int N, const float alpha, const float* X, const float beta, float* Y); void gpu_axpby(int N, const float alpha, const float* X, const float beta, float* Y); void cpu_copy(int N, const float *X, float *Y); void gpu_copy(int N, const float *X, float *Y); void cpu_scal(int N, const float alpha, float *X); float cpu_max(int N, const float *X); int cpu_max_index(int N, const float *X); void cpu_exp(int N, const float *X, float *Y); void gpu_exp(int N, const float *X, float *Y); void cpu_dexp(int N, const float *in_data, const float *in_diff, float *out); void cpu_tanh(int N, const float *X, float *Y); void gpu_tanh(int N, const float *X, float *Y); void cpu_sin(int N, const float *X, float *Y); void gpu_sin(int N, const float *X, float *Y); void cpu_cos(int N, const float *X, float *Y); void gpu_cos(int N, const float *X, float *Y); void cpu_dtanh(int N, const float *in_data, const float *in_diff, float *out); void gpu_dtanh(int N, const float *in_data, const float *in_diff, float *out); void cpu_sigmoid(int N, const float *X, float *Y); void gpu_sigmoid(int N, const float *X, float *Y); void cpu_dsigmoid(int N, const float *in_data, const float *in_diff, float *out); void gpu_dsigmoid(int N, const float *in_data, const float *in_diff, float *out); void cpu_hadamard(int M, int N, float *X); void gpu_hadamard(int M, int N, float *X); void cpu_complex_modulus_relu(int M, int N, const float *X, const float* b, float* Y); void cpu_complex_modulus_drelu(int M, int N, const float *X, const float* b, const float* gradY, float* gradX, float* gradb); void cpu_complex_modulus_tanh(int M, int N, const float *X, const float* b, float* Y); void cpu_complex_modulus_dtanh(int M, int N, const float *X, const float* b, const float* gradY, float* gradX, float* gradb); /* From Efficient backprop, Yann Lecun, Leon Bottou 1998 */ void cpu_lecun98(int N, int fan_in, float *x); void gpu_lecun98(int N, int fan_in, float *x); /* From Understanding the diffcuilt of traing neural nets, Xavier Glorot, Yoshua Bengio : AISTATS 2010 */ void cpu_glorot10(int fan_in, int fan_out, float *x); void gpu_glorot10(int fan_in, int fan_out, float *x); /* From Delving deep into rectifiers, Kaiming He Xiangyu Zhang Shaoqing Ren Jian Sun: Arxiv 2015 */ void cpu_he15(int N, int fan_in, float *x); void cpu_allzero(int N, float *x); void cpu_normal(int N, const float mean, const float stddev, float *x); void cpu_uniform(int N, const float r1, const float r2, float *x); void gpu_uniform(int N, const float r1, const float r2, float *x); void gpu_he15(int N, int fan_in, float *x); void gpu_allzero(int N, float *x); void gpu_normal(int N, const float mean, const float stddev, float *x); void cpu_log(int N, const float *X, float *Y); void gpu_log(int N, const float *X, float *Y); void cpu_sqr(int N, const float *X, float *Y); void gpu_sqr(int N, const float *X, float *Y); void cpu_abs(int N, const float *X, float *Y); void cpu_clip(int N, const float *X, const float p, float *Y); void gpu_clip(int N, const float *X, const float p, float *Y); void cpu_pow(int N, const float *X, const float p, float *Y); void gpu_pow(int N, const float *X, const float p, float *Y); void gpu_scal(int N, const float alpha, float *X); float cpu_dot(int n, const float* x, const float* y); void cpu_add(int N, const float* a, const float* b, float* y); void gpu_add(int N, const float* a, const float* b, float* y); void gpu_mul(int N, const float* a, const float* b, float* y); void cpu_mul(int N, const float* a, const float* b, float* y); void gpu_div(int N, const float* a, const float* b, float* y); void cpu_div(int N, const float* a, const float* b, float* y); void gpu_fill(int N, const float a, float* y); void cpu_fill(int N, const float a, float* y); float cpu_max(int N, const float* y); float cpu_nrm2(int N, const float* y); float gpu_nrm2(int N, const float* y); float cpu_min(int N, const float* y); float gpu_dot(int n, const float* x, const float* y); void cpu_chi(int N, int dof, float* x); void gpu_chi(int N, int dof, float* x); void cpu_rademacher(int N, float* x); void gpu_rademacher(int N, float* x); void cpu_permutation_array(int N, float* x); void gpu_permutation_array(int N, float* x); inline void cblas_saxpby(int N, const float alpha, const float* X, int incX, const float beta, float* Y, int incY) { cblas_sscal(N, beta, Y, incY); cblas_saxpy(N, alpha, X, incX, Y, incY); } #endif
{ "alphanum_fraction": 0.6491319808, "avg_line_length": 42.3097345133, "ext": "h", "hexsha": "60a4438bf672f712d311fc272dce5af741610533", "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": "b9a8e94deeeaf867388ecdb70a42142ca93424d5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cijose/RandomFourierFeatures", "max_forks_repo_path": "src/math_functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b9a8e94deeeaf867388ecdb70a42142ca93424d5", "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": "cijose/RandomFourierFeatures", "max_issues_repo_path": "src/math_functions.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "b9a8e94deeeaf867388ecdb70a42142ca93424d5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cijose/RandomFourierFeatures", "max_stars_repo_path": "src/math_functions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2663, "size": 9562 }