Search is not available for this dataset
text
string
meta
dict
#pragma once #define QT_IS_BROKEN #define QAPPLICATION_CLASS QApplication // for SingleApplication // Windows #include <Windows.h> #include <SetupAPI.h> #include <winioctl.h> #include <BluetoothAPIs.h> #include <Bthioctl.h> #include <Dbt.h> #include <Hidsdi.h> #include <shellapi.h> #include <Xinput.h> // STL #include <array> #include <chrono> #include <cmath> #include <cstdint> #include <deque> #include <functional> #include <iomanip> #include <list> #include <map> #include <memory> #include <mutex> #include <optional> #include <sstream> #include <string> #include <thread> #include <unordered_map> // Qt #include <QDialog> #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtWidgets> #include <singleapplication.h> // GSL #include <gsl/span> // better-enums #include <enum.h> // fmt #include <fmt/format.h> // libhid #include <hid_handle.h> #include <hid_instance.h> #include <hid_util.h> // ViGEm #include <ViGEm/Client.h> #include <ViGEm/Common.h> #include <ViGEm/km/BusShared.h> #include "MapCache.h" #include "average.h" #include "AxisOptions.h" #include "Bluetooth.h" #include "busenum.h" #include "ConnectionType.h" #include "DeviceIdleOptions.h" #include "DeviceProfile.h" #include "DeviceProfileCache.h" #include "DevicePropertiesDialog.h" #include "DeviceSettings.h" #include "DeviceSettingsCommon.h" #include "Ds4AutoLightColor.h" #include "Ds4Color.h" #include "Ds4Device.h" #include "Ds4DeviceManager.h" #include "Ds4Input.h" #include "Ds4InputData.h" #include "Ds4ItemModel.h" #include "Ds4LightOptions.h" #include "Ds4Output.h" #include "Ds4TouchRegion.h" #include "enums.h" #include "Event.h" #include "gmath.h" #include "InputMap.h" #include "InputSimulator.h" #include "JsonData.h" #include "KeyboardSimulator.h" #include "Latency.h" #include "lock.h" #include "Logger.h" #include "MainWindow.h" #include "MouseSimulator.h" #include "pathutil.h" #include "Pressable.h" #include "ProfileEditorDialog.h" #include "program.h" #include "Settings.h" #include "Stopwatch.h" #include "stringutil.h" #include "Trackball.h" #include "Vector2.h" #include "Vector3.h" #include "XInputGamepad.h"
{ "alphanum_fraction": 0.7430167598, "avg_line_length": 19.7064220183, "ext": "h", "hexsha": "437e5c40f8c9b214f6b8d457e150e27c03e61fba", "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": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SonicFreak94/ds4wizard", "max_forks_repo_path": "ds4wizard-cpp/pch.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SonicFreak94/ds4wizard", "max_issues_repo_path": "ds4wizard-cpp/pch.h", "max_line_length": 64, "max_stars_count": 7, "max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SonicFreak94/ds4wizard", "max_stars_repo_path": "ds4wizard-cpp/pch.h", "max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z", "num_tokens": 552, "size": 2148 }
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * **/ #ifndef ICL_CORE_LAPACK_H #define ICL_CORE_LAPACK_H #ifdef PLASMA_WITH_MKL #include <mkl_cblas.h> #include <mkl_lapacke.h> // MKL LAPACKE doesn't provide LAPACK_GLOBAL macro, so define it here. // MKL provides all 3 name manglings (foo, foo_, FOO); pick foo_. #ifndef LAPACK_GLOBAL #define LAPACK_GLOBAL(lcname,UCNAME) lcname##_ #endif #else #include <cblas.h> #include <lapacke.h> // Intel mkl_cblas.h does: typedef enum {...} CBLAS_ORDER; // Netlib cblas.h does: enum CBLAS_ORDER {...}; // OpenBLAS cblas.h does: typedef enum CBLAS_ORDER {...} CBLAS_ORDER; // We use (CBLAS_ORDER), so add these typedefs for Netlib. #ifndef OPENBLAS_VERSION typedef enum CBLAS_ORDER CBLAS_ORDER; typedef enum CBLAS_TRANSPOSE CBLAS_TRANSPOSE; typedef enum CBLAS_UPLO CBLAS_UPLO; typedef enum CBLAS_DIAG CBLAS_DIAG; typedef enum CBLAS_SIDE CBLAS_SIDE; #endif #endif #include "core_lapack_s.h" #include "core_lapack_d.h" #include "core_lapack_c.h" #include "core_lapack_z.h" #endif // ICL_CORE_LAPACK_H
{ "alphanum_fraction": 0.7020576132, "avg_line_length": 27, "ext": "h", "hexsha": "6c50c72cee8ca5dbee28cd601b96453d236a8e02", "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": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "NLAFET/plasma", "max_forks_repo_path": "include/core_lapack.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "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": "NLAFET/plasma", "max_issues_repo_path": "include/core_lapack.h", "max_line_length": 74, "max_stars_count": 9, "max_stars_repo_head_hexsha": "92648b6c0ede8beb70f40b97a6ab45ae80820ca3", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "NLAFET/plasma", "max_stars_repo_path": "include/core_lapack.h", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:55:50.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-07T11:21:44.000Z", "num_tokens": 378, "size": 1215 }
#pragma once #include "iobserver.h" #include "irequest.h" #include <gsl/pointers> #include <atomic> #include <vector> #include <Windows.h> namespace died { namespace observer { namespace callback { unsigned WINAPI start_thread_proc(LPVOID); VOID CALLBACK terminate_proc(__in ULONG_PTR); VOID CALLBACK add_directory_proc(__in ULONG_PTR); } } class observer_impl final : public iobserver { public: observer_impl(idirectory_watcher*); // diable copy observer_impl(observer_impl const&) = delete; observer_impl& operator=(observer_impl const&) = delete; // interface private: unsigned int do_inc_request() final; unsigned int do_dec_request() final; idirectory_watcher* do_get_watcher() const final; private: void run(); bool terminated() const; bool empty_request() const; bool add_directory(irequest* pBlock); void request_termination(); friend unsigned WINAPI observer::callback::start_thread_proc(LPVOID); friend VOID CALLBACK observer::callback::terminate_proc(__in ULONG_PTR); friend VOID CALLBACK observer::callback::add_directory_proc(__in ULONG_PTR); private: gsl::not_null<idirectory_watcher*> mDirWatcher; std::atomic_bool mTerminated{}; std::atomic_uint mOutstandingRequests{}; std::vector<gsl::not_null<irequest*>> mBlocks; }; }
{ "alphanum_fraction": 0.7536231884, "avg_line_length": 24.2777777778, "ext": "h", "hexsha": "bbf72f12d2c2a63b8f03ea23237d0d358318af30", "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": "37fb2022fb27952db294b253fe2817d4548817bc", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "pvthuyet/file-watcher-demo", "max_forks_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "37fb2022fb27952db294b253fe2817d4548817bc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "pvthuyet/file-watcher-demo", "max_issues_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "37fb2022fb27952db294b253fe2817d4548817bc", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "pvthuyet/file-watcher-demo", "max_stars_repo_path": "FileWatcherDemo/file_activity/observer_impl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 320, "size": 1311 }
#include <stdio.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h>
{ "alphanum_fraction": 0.7297297297, "avg_line_length": 18.5, "ext": "c", "hexsha": "6b9a98cc0bc42c35a2221baf7a33325ed079ba71", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/multiminhead.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/multiminhead.c", "max_line_length": 29, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/multiminhead.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": 24, "size": 74 }
#pragma once #include <string_view> #include <gsl/span> #include <spirv_cross.hpp> namespace glslang { class TShader; } namespace Babylon { class ShaderCompiler { public: ShaderCompiler(); ~ShaderCompiler(); struct ShaderInfo { std::unique_ptr<const spirv_cross::Compiler> Compiler; gsl::span<uint8_t> Bytes; }; void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function<void(ShaderInfo, ShaderInfo)> onCompiled); protected: // Invert dFdy operands similar to bgfx_shader.sh // https://github.com/bkaradzic/bgfx/blob/7be225bf490bb1cd231cfb4abf7e617bf35b59cb/src/bgfx_shader.sh#L44-L45 // https://github.com/bkaradzic/bgfx/blob/7be225bf490bb1cd231cfb4abf7e617bf35b59cb/src/bgfx_shader.sh#L62-L65 static void InvertYDerivativeOperands(glslang::TShader& shader); }; }
{ "alphanum_fraction": 0.6874328679, "avg_line_length": 26.6, "ext": "h", "hexsha": "9cf0d126cffce4d3585e87caa8798d562c579624", "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": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zloop1982/BabylonNative", "max_forks_repo_path": "Library/Source/ShaderCompiler.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "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": "zloop1982/BabylonNative", "max_issues_repo_path": "Library/Source/ShaderCompiler.h", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc15fbde9eb8df3f72d4d14aa8f896341005aea2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zloop1982/BabylonNative", "max_stars_repo_path": "Library/Source/ShaderCompiler.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 256, "size": 931 }
#ifndef GUARD_QDWF_H #define GUARD_QDWF_H #include "Numerics/Spline3D/Config.h" #include "Numerics/Spline3D/uGrid1D.h" #include "Numerics/Spline3D/CubicSpline.h" #include "Optimize/VarList.h" #include <gsl/gsl_sf_airy.h> #include <math.h> #include <iostream> using namespace std; class QDwf { std::vector<double> X; std::vector<double> sigx; std::vector<double> a; double sigy;//var double Y0;//var double z0;//var double Ez;//var double VB; double zB; double kappa; double EL; double psiB; double onethird; double fac1,fac2; uGrid1D* m_grid; CubicSpline* m_spline; gsl_mode_t mode; int funcz(double z) { double denom = gsl_sf_airy_Ai(z,mode); double numer = fac2*gsl_sf_airy_Ai_deriv(z,mode); double xsign = numer-denom*kappa; if(xsign < 0 ) { return -1; } else { return 1; } } inline double zprime(double z) { return fac2*(z-z0-EL/Ez); } public: typedef double value_type; QDwf() { VB = 24.535; zB = 9.1854; // z0 = 10.6858; // Ez = 2.2; Ez = 2.04866; z0 = 10.8049; // sigxr = 0.08; // xr = 80.72; sigy = 0.107; Y0 = 25.3; /// set the x parameters int nxp = 1; a.resize(nxp); sigx.resize(nxp); X.resize(nxp); a[0] = 1.00000; sigx[0] = 0.08; X[0] = 80.628; // a[1] = 1.00e-4; sigx[1] = 0.08; X[1] = 62; /* a[0] = 1.00000; sigx[0] = 0.08; X[0] = 80.628; a[1] = 0.08260; sigx[1] = 0.08; X[1] = 76.000; a[2] = 2.17e-4; sigx[2] = 0.04; X[2] = 67.000; */ /// optimised parameters /* a[0] = 1.00000; sigx[0] = 0.092403; X[0] = 80.569; a[1] = 0.071703; sigx[1] = 0.18445; X[1] = 76.064; a[2] = 2.86e-3; sigx[2] = 0.052224; X[2] = 67.000; sigy = 0.11112; Y0 = 25.167; */ onethird = 1.0/3.0; reset(); cout << "Airy Solved: " << EL << '\t' << kappa << '\t' << psiB << endl; /* /// create and initialise the uniform one-dimensional uGrid1D if( !m_grid ) m_grid = new uGrid1D; double zstart = zB; double zend = 16.00; int npts = 1000; m_grid->init(zstart,zend,npts); /// create and initialise the CubicSpline if(!m_spline) m_spline = new CubicSpline(m_grid); for(int i = 0; i < npts; i++){ double z = m_grid->m_coord[i]; double zz = zprime(z); //(*m_spline)(i) = gsl_sf_airy_Ai(zz,mode);//evaluate(z); m_spline->F(i)[0] = gsl_sf_airy_Ai(zz,mode); m_spline->F(i)[1] = fac2*gsl_sf_airy_Ai_deriv(zz,mode); } */ } template<class T1> void put(xmlNodePtr cur, VarRegistry<T1>& vlist) { // vlist.add("C_sigxr",&sigxr,1); // vlist.add("C_xr",&xr,1); vlist.add("C_X",&X[0],1); vlist.add("C_sigx",&sigx[0],1); vlist.add("C_a",&a[0],1); vlist.add("C_sigy",&sigy,1); vlist.add("C_Y0",&Y0,1); vlist.add("C_Ez",&Ez,1); vlist.add("C_z0",&z0,1); } void reset(); inline void set_point(const posvec_t& r) {} inline double evaluate(const posvec_t& r, posvec_t& gradf, double& lapf) { int nsize = sigx.size(); /// \f$\Psi_{x}\f$ sum of Gaussians double psix = 0.0,gfx=0.0,lfx=0.0; for(int i = 0; i < nsize; i++) { double x = r[0] - X[i]; double sx = sigx[i] * x; double sxx = sx * x; double phix = a[i] * exp(-sxx); psix += phix; gfx += -2 * sx * phix; lfx += -2 * sigx[i] * ( 1.0 - 2.0 * sxx ) * phix; } /// \f$\Psi_{y}\f$ single Gaussian double y = r[1] - Y0; double sy = sigy * y; double syy = sy * y; double psiy = exp(-syy); double gfy = - 2 * sy * psiy; double lfy = - 2 * sigy * ( 1.0 - 2.0 * syy ) * psiy; /// \f$\Psi_{z}\f$ AiryAi with exponential tail double z = r[2]; double psiz,gfz,lfz; if( z <= zB ) { psiz = psiB * exp ( kappa * ( z - zB ) ); gfz = kappa * psiz; lfz = kappa * gfz; } else { psiz = m_spline->evaluate(z,gfz,lfz); } double psi = psix * psiy * psiz; gradf[0] = gfx * psiy * psiz; gradf[1] = psix * gfy * psiz; gradf[2] = psix * gfy * psiz; lapf = lfx * psiy * psiz + psix * lfy * psiz + psix * psiy * lfz; return psi; } }; #endif
{ "alphanum_fraction": 0.5295768062, "avg_line_length": 22.5105263158, "ext": "h", "hexsha": "b79ef9be38dfec857043de2beef4f4f92e0f99aa", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2021-03-02T22:09:15.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-26T22:11:51.000Z", "max_forks_repo_head_hexsha": "d23c850dce914e2d80cae733670820812a1edeee", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "FeiyangJin/hclib", "max_forks_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/QDwf.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "d23c850dce914e2d80cae733670820812a1edeee", "max_issues_repo_issues_event_max_datetime": "2020-08-26T00:11:43.000Z", "max_issues_repo_issues_event_min_datetime": "2015-06-15T20:38:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "FeiyangJin/hclib", "max_issues_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/QDwf.h", "max_line_length": 69, "max_stars_count": 55, "max_stars_repo_head_hexsha": "d23c850dce914e2d80cae733670820812a1edeee", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "FeiyangJin/hclib", "max_stars_repo_path": "test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/QDwf.h", "max_stars_repo_stars_event_max_datetime": "2022-02-27T16:27:46.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-28T01:32:58.000Z", "num_tokens": 1695, "size": 4277 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2003-2018 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #ifndef OBITFARRAY_H #define OBITFARRAY_H #include "Obit.h" #include "ObitErr.h" #include "ObitInfoList.h" #include "ObitThread.h" #if HAVE_GSL==1 /* GSL stuff */ #include <gsl/gsl_randist.h> #endif /* HAVE_GSL */ /*-------- Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitFArray.h * ObitFArray numeric array class definition. * * This class is derived from the #Obit class. * Related functions are in the * \link ObitFArrayUtil.h ObitFArrayUtil * \endlink module. * * This class is for creating and manipulating a Array as a memory resident * multidimensional rectangular array of floats. * Elements are stored in order of the increasing axis order (the reverse of the * usual c definition). * Except as noted, magic value blanking is supported (OBIT_MAGIC). * * \section ObitFArrayaccess Creators and Destructors * An ObitFArray will usually be created using ObitFArrayCreate which allows * specifying a name for the object as well as dimensionality of the array. * * A copy of a pointer to an ObitFArray should always be made using the * #ObitFArrayRef function which updates the reference count in the object. * Then whenever freeing an ObitFArray or changing a pointer, the function * #ObitFArrayUnref will decrement the reference count and destroy the object * when the reference count hits 0. * There is no explicit destructor. */ /*--------------Class definitions-------------------------------------*/ /** ObitFArray Class structure. */ typedef struct { #include "ObitFArrayDef.h" /* this class definition */ } ObitFArray; /*----------------- Macroes ---------------------------*/ /** * Macro to unreference (and possibly destroy) an ObitFArray * returns a ObitFArray*. * in = object to unreference */ #define ObitFArrayUnref(in) ObitUnref (in) /** * Macro to reference (update reference count) an ObitFArray. * returns a ObitFArray*. * in = object to reference */ #define ObitFArrayRef(in) ObitRef (in) /** * Macro to determine if an object is the member of this or a * derived class. * Returns TRUE if a member, else FALSE * in = object to reference */ #define ObitFArrayIsA(in) ObitIsA (in, ObitFArrayGetClass()) /** Maximum ObitFArray number of dimensions */ #ifndef MAXFARRAYDIM #define MAXFARRAYDIM 10 #endif /*---------------Public functions---------------------------*/ /** Public: Class initializer. */ void ObitFArrayClassInit (void); /** Public: Default Constructor. */ ObitFArray* newObitFArray (gchar* name); /** Public: Create/initialize ObitFArray structures */ ObitFArray* ObitFArrayCreate (gchar* name, olong ndim, olong *naxis); /** Typedef for definition of class pointer structure */ typedef void (*ObitFArrayCreateFP) (gchar* name, olong ndim, olong *naxis); /** Public: ClassInfo pointer */ gconstpointer ObitFArrayGetClass (void); /** Public: Copy (deep) constructor. */ ObitFArray* ObitFArrayCopy (ObitFArray *in, ObitFArray *out, ObitErr *err); /** Public: Copy structure. */ void ObitFArrayClone (ObitFArray *in, ObitFArray *out, ObitErr *err); /** Public: Copy Subarray constructor. */ ObitFArray* ObitFArraySubArr (ObitFArray *in, olong *blc, olong *trc, ObitErr *err); typedef ObitFArray* (*ObitFArraySubArrFP) (ObitFArray *in, olong *blc, olong *trc, ObitErr *err); /** Public: Transpose constructor. */ ObitFArray* ObitFArrayTranspose (ObitFArray *in, olong *order, ObitErr *err); typedef ObitFArray* (*ObitFArrayTransposeFP) (ObitFArray *in, olong *order, ObitErr *err); /** Public: Are two FArrays of compatable geometry. */ gboolean ObitFArrayIsCompatable (ObitFArray *in1, ObitFArray *in2); typedef gboolean (*ObitFArrayIsCompatableFP) (ObitFArray *in1, ObitFArray *in2); /** Public: Reallocate/initialize ObitFArray structures */ ObitFArray* ObitFArrayRealloc (ObitFArray* in, olong ndim, olong *naxis); typedef void (*ObitFArrayReallocFP) (ObitFArray* in, olong ndim, olong *naxis); /** Public: return pointer to a specified element */ ofloat* ObitFArrayIndex (ObitFArray* in, olong *pos); typedef ofloat* (*ObitFArrayIndexFP) (ObitFArray* in, olong *pos); /** Public: Find Maximum value in an ObitFArray */ ofloat ObitFArrayMax (ObitFArray* in, olong *pos); typedef ofloat (*ObitFArrayMaxFP) (ObitFArray* in, olong *pos); /** Public: Find Maximum abs value in an ObitFArray */ ofloat ObitFArrayMaxAbs (ObitFArray* in, olong *pos); typedef ofloat (*ObitFArrayMaxAbsFP) (ObitFArray* in, olong *pos); /** Public: Find Minimum value in an ObitFArray */ ofloat ObitFArrayMin (ObitFArray* in, olong *pos); typedef ofloat (*ObitFArrayMinFP) (ObitFArray* in, olong *pos); /** Public: Replace blanks in an ObitFArray */ void ObitFArrayDeblank (ObitFArray* in, ofloat scalar); typedef void (*ObitFArrayDeblankFP) (ObitFArray* in, ofloat scalar); /** Public: RMS of pixel distribution from histogram */ ofloat ObitFArrayRMS (ObitFArray* in); typedef ofloat (*ObitFArrayRMSFP) (ObitFArray* in); /** Public: RMS of pixel distribution. */ ofloat ObitFArrayRawRMS (ObitFArray* in); typedef ofloat (*ObitFArrayRawRMSFP) (ObitFArray* in); /** Public: RMS of pixel about zero. */ ofloat ObitFArrayRMS0 (ObitFArray* in); typedef ofloat (*ObitFArrayRMS0FP) (ObitFArray* in); /** Public: Function for combining planes of multi frequency images */ ofloat ObitFArrayRMS0ST (ObitFArray* in); typedef ofloat (*ObitFArrayRMS0STFP) (ObitFArray* in); /** Public: RMS of pixel in potentially quantized image. */ ofloat ObitFArrayRMSQuant (ObitFArray* in); typedef ofloat (*ObitFArrayRMSQuantFP) (ObitFArray* in); /** Public: Determine quantization and offset in an image */ void ObitFArrayQuant (ObitFArray* in, ofloat *quant, ofloat *zero); typedef void (*ObitFArrayQuantFP) (ObitFArray* in, ofloat *quant, ofloat *zero); /** Public: Mode of pixel distribution. */ ofloat ObitFArrayMode (ObitFArray* in); typedef ofloat (*ObitFArrayModeFP) (ObitFArray* in); /** Public: Mean of pixel distribution. */ ofloat ObitFArrayMean (ObitFArray* in); typedef ofloat (*ObitFArrayMeanFP) (ObitFArray* in); /** Public: fill elements of an FArray */ void ObitFArrayFill (ObitFArray* in, ofloat scalar); typedef void (*ObitFArrayFillFP) (ObitFArray* in, ofloat scalar); /** Public: negate elements of an FArray */ void ObitFArrayNeg (ObitFArray* in); typedef void (*ObitFArrayNegFP) (ObitFArray* in); /** Public: taks absolute value of elements of an FArray */ void ObitFArrayAbs (ObitFArray* in); typedef void (*ObitFArrayAbsFP) (ObitFArray* in); /** Public: sine of elements of an FArray */ void ObitFArraySin (ObitFArray* in); typedef void (*ObitFArraySinFP) (ObitFArray* in); /** Public: cosine of elements of an FArray */ void ObitFArrayCos (ObitFArray* in); typedef void (*ObitFArrayCosFP) (ObitFArray* in); /** Public: sine/cosine of elements of an FArray */ void ObitFArraySinCos (ObitFArray* in, ObitFArray* outS, ObitFArray* outC); typedef void (*ObitFArraySinCosFP) (ObitFArray* in, ObitFArray* outS, ObitFArray* outC); /** Public: square root of elements of an FArray */ void ObitFArraySqrt (ObitFArray* in); typedef void (*ObitFArraySqrtFP) (ObitFArray* in); /** Public: sum elements of an FArray */ ofloat ObitFArraySum (ObitFArray* in); typedef ofloat (*ObitFArraySumFP) (ObitFArray* in); /** Public: number of valid elements in an FArray */ olong ObitFArrayCount (ObitFArray* in); typedef olong (*ObitFArrayCountFP) (ObitFArray* in); /** Public: Add a scalar to elements of an FArray */ void ObitFArraySAdd (ObitFArray* in, ofloat scalar); typedef void (*ObitFArraySAddFP) (ObitFArray* in, ofloat scalar); /** Public: Multiply elements of an FArray by a scalar*/ void ObitFArraySMul (ObitFArray* in, ofloat scalar); typedef void (*ObitFArraySMulFP) (ObitFArray* in, ofloat scalar); /** Public: Divide elements of an FArray into a scalar*/ void ObitFArraySDiv (ObitFArray* in, ofloat scalar); typedef void (*ObitFArraySDivFP) (ObitFArray* in, ofloat scalar); /** Public: Clip elements of an FArray outside of a given range */ void ObitFArrayClip (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal); typedef void (*ObitFArrayClipFP) (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal); /** Public: Clip elements of an FArray inside of a given range */ void ObitFArrayInClip (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal); typedef void (*ObitFArrayInClipFP) (ObitFArray* in, ofloat minVal, ofloat maxVal, ofloat newVal); /** Public: Blank elements of an array where another is blanked */ void ObitFArrayBlank (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayBlankFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Get larger elements of two FArrays */ void ObitFArrayMaxArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayMaxArrFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Get lesser elements of two FArrays */ void ObitFArrayMinArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayMinArrFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Get more extreme elements of two FArrays */ void ObitFArrayExtArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayExtArrFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Sum nonblanked elements of two FArrays */ void ObitFArraySumArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArraySumArrFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Average nonblanked elements of two FArrays */ void ObitFArrayAvgArr (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayAvgArrFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Add elements of two FArrays */ void ObitFArrayAdd (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayAddFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Abs Add elements of two FArrays */ void ObitFArrayAddAbs (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayAddAbsFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Subtract elements of two FArrays */ void ObitFArraySub (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArraySubFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: copy elements from one FArray to another */ void ObitFArrayCopyData (ObitFArray* in, ObitFArray* out); typedef void (*ObitFArrayCopyDataFP) (ObitFArray* in1, ObitFArray* out); /** Public: Give the elements of one array the sign of the other */ void ObitFArraySign (ObitFArray* in1, ObitFArray* in2); typedef void (*ObitFArraySignFP) (ObitFArray* in1, ObitFArray* in2); /** Public: Multiply elements of two FArrays */ void ObitFArrayMul (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayMulFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Divide elements of two FArrays */ void ObitFArrayDiv (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayDivFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Divide elements of two FArrays with clipping*/ void ObitFArrayDivClip (ObitFArray* in1, ObitFArray* in2, ofloat minVal, ObitFArray* out); typedef void (*ObitFArrayDivClipFP) (ObitFArray* in1, ObitFArray* in2, ofloat minVal, ObitFArray* out); /** Public: "Dot" product to two arrays */ ofloat ObitFArrayDot (ObitFArray* in1, ObitFArray* in2); typedef ofloat (*ObitFArrayDotFP) (ObitFArray* in1, ObitFArray* in2); /** Public: Multiply a 2D array by a Col vector * Row vector */ void ObitFArrayMulColRow (ObitFArray* in, ObitFArray* row, ObitFArray* col, ObitFArray* out); typedef void (*ObitFArrayMulColRowFP) (ObitFArray* in, ObitFArray* row, ObitFArray* col, ObitFArray* out); /** Public: Convert a 1D "center at edges" array to proper order */ void ObitFArray1DCenter (ObitFArray* in); typedef void (*ObitFArray1DCenterFP) (ObitFArray* in); /** Public: Convert a 2D "center at edges" array to proper order */ void ObitFArray2DCenter (ObitFArray* in); typedef void (*ObitFArray2DCenterFP) (ObitFArray* in); /** Public: inplace invert a symmetric 2D array */ void ObitFArray2DSymInv (ObitFArray* in, olong *ierr); typedef void (*ObitFArray2DSymInvFP) (ObitFArray* in, olong *ierr); /** Public: Make 2-D Circular Gaussian in FArray */ void ObitFArray2DCGauss (ObitFArray* in, olong Cen[2], ofloat FWHM); typedef void (*ObitFArray2DCGaussFP) (ObitFArray* in, olong Cen[2], ofloat FWHM); /** Public: Make 2-D Eliptical Gaussian in FArray */ void ObitFArray2DEGauss (ObitFArray* in, ofloat amp, ofloat Cen[2], ofloat GauMod[3]); typedef void (*ObitFArray2DEGaussFP) (ObitFArray* in, ofloat amp, ofloat Cen[2], ofloat GauMod[3] ); /** Public: Shift and Add scaled array */ void ObitFArrayShiftAdd (ObitFArray* in1, olong *pos1, ObitFArray* in2, olong *pos2, ofloat scalar, ObitFArray* out); typedef void (*ObitFArrayShiftAddFP) (ObitFArray* in1, olong *pos1, ObitFArray* in2, olong *pos2, ofloat scalar, ObitFArray* out); /** Public: Shift and Add scaled array, no threading */ void ObitFArrayShiftAddNT (ObitFArray* in1, olong *pos1, ObitFArray* in2, olong *pos2, ofloat scalar, ObitFArray* out); /** Public: Zero pad an array */ void ObitFArrayPad (ObitFArray* in, ObitFArray* out, ofloat factor); typedef void (*ObitFArrayPadFP) (ObitFArray* in, ObitFArray* out, ofloat factor); /** Public: Convolve a list of Gaussians onto an FArray */ void ObitFArrayConvGaus (ObitFArray* in, ObitFArray* list, olong ncomp, ofloat gauss[3]); typedef void (*ObitFArrayConvGausFP) (ObitFArray* in, ObitFArray* list, olong ncomp, ofloat gauss[3]); /** Public: Select elements in an FArray by increment */ void ObitFArraySelInc (ObitFArray* in, ObitFArray* out, olong *blc, olong *trc, olong* inc, ObitErr *err); typedef void (*ObitFArraySelIncFP) (ObitFArray* in, ObitFArray* out, olong *blc, olong *trc, olong* inc, ObitErr *err); /** Public: return histogram of elements in an FArray */ ObitFArray* ObitFArrayHisto (ObitFArray* in, olong n, ofloat min, ofloat max); typedef ObitFArray* (*ObitFArrayHistoFP) (ObitFArray* in, olong n, ofloat min, ofloat max); /** Public: exponentiate elements in an FArray */ void ObitFArrayExp (ObitFArray* in, ObitFArray* out); typedef void (*ObitFArrayExpFP) (ObitFArray* in, ObitFArray* out); /** Public: natural log of elements in an FArray */ void ObitFArrayLog (ObitFArray* in, ObitFArray* out); typedef void (*ObitFArrayLogFP) (ObitFArray* in, ObitFArray* out); /** Public: natural log of elements in an FArray */ void ObitFArrayPow (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); typedef void (*ObitFArrayPowFP) (ObitFArray* in1, ObitFArray* in2, ObitFArray* out); /** Public: Gaussian distributed random numbers */ ofloat ObitFArrayRandom (ofloat mean, ofloat sigma); typedef ofloat (*ObitFArrayRandomFP) (ofloat mean, ofloat sigma); /** Public: Fill with Gaussian distributed random numbers */ void ObitFArrayRandomFill (ObitFArray* in, ofloat mean, ofloat sigma); typedef void (*ObitFArrayRandomFillFP) (ObitFArray* in, ofloat mean, ofloat sigma); /*----------- ClassInfo Structure -----------------------------------*/ /** * ClassInfo Structure. * Contains class name, a pointer to any parent class * (NULL if none) and function pointers. */ typedef struct { #include "ObitFArrayClassDef.h" } ObitFArrayClassInfo; #endif /* OBITFARRAY_H */
{ "alphanum_fraction": 0.6912240841, "avg_line_length": 42.5241545894, "ext": "h", "hexsha": "d34e31ac397ad4e07e4e64986789e212ce6169e2", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_line_length": 92, "max_stars_count": 5, "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_path": "ObitSystem/Obit/include/ObitFArray.h", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "num_tokens": 5359, "size": 17605 }
// Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef COMMON_H #define COMMON_H #include <cmath> #include <optional> #include <yato/array_view.h> //#define CHECK_ASSERT #include <training/system/Errors.h> #include <training/system/Name.h> #include <training/system/TypeHalf.h> #include <training/system/Types.h> #include <map> #include <utility> #if defined(_BLAS) && !defined(_BLAS_ENHANCE) extern "C" { #include <cblas.h> } #else #ifndef OPENBLAS_CONST #define OPENBLAS_CONST const #endif typedef enum CBLAS_TRANSPOSE { CblasNoTrans = 111, CblasTrans = 112, CblasConjTrans = 113, CblasConjNoTrans = 114 } CBLAS_TRANSPOSE; typedef enum CBLAS_UPLO { CblasUpper = 121, CblasLower = 122 } CBLAS_UPLO; #endif #ifdef CHECK_ASSERT #define CHECK_NEAR ASSERT_NEAR #else #define CHECK_NEAR EXPECT_NEAR #endif #define RAUL_E 2.71828182845904523536 // e #define RAUL_LOG2E 1.44269504088896340736 // log2(e) #define RAUL_LOG10E 0.434294481903251827651 // log10(e) #define RAUL_LN2 0.693147180559945309417 // ln(2) #define RAUL_LN10 2.30258509299404568402 // ln(10) #define RAUL_PI 3.14159265358979323846 // pi #define RAUL_PI_2 1.57079632679489661923 // pi/2 #define RAUL_PI_4 0.785398163397448309616 // pi/4 #define RAUL_1_PI 0.318309886183790671538 // 1/pi #define RAUL_2_PI 0.636619772367581343076 // 2/pi #define RAUL_2_SQRTPI 1.12837916709551257390 // 2/sqrt(pi) #define RAUL_SQRT2_PI 0.79788456080286535588 // sqrt(2/pi) #define RAUL_SQRT2 1.41421356237309504880 // sqrt(2) #define RAUL_SQRT1_2 0.707106781186547524401 // 1/sqrt(2) #define GELU_CONST 0.044715 namespace raul { enum class Limit : int { Left = 0, Middle = 1, Right = 2 }; enum class Dimension : int { Default = -1, Batch = 0, Depth = 1, Height = 2, Width = 3 }; #if defined(_MSC_VER) #define INLINE __forceinline #else #define INLINE __attribute__((always_inline)) #endif template<typename Type> class TensorImpl; typedef TensorImpl<dtype> Tensor; typedef TensorImpl<half> TensorFP16; #if defined(ANDROID) #define TOMMTYPE(var) static_cast<typename MM::type>(var) #else #define TOMMTYPE(var) castHelper<typename MM::type>::cast(var) #endif using shape = yato::dimensionality<4U, size_t>; } // raul namespace namespace raul { enum class NetworkMode { Train = 0, Test = 1, TrainCheckpointed = 2 }; enum class CompressionMode { NONE = -1, FP16 = 0, INT8 = 1 }; enum class CalculationMode { DETERMINISTIC = 0, #if defined(_OPENMP) FAST = 1, #endif }; /** * @brief Hardware target platform * */ enum class ExecutionTarget { CPU = 0, CPUFP16 = 1 }; /** * @brief Hardware target platform per layer * * \note Might override execution target for workflow, useful for mixed precision */ enum class LayerExecutionTarget { Default = -1, // use same as ExecutionTarget CPU = 0, // from this point enums should be aligned with ExecutionTarget (due to LayerExecutionTarget = static_cast<ExecutionTarget>(enum)) CPUFP16 = 1 }; /** * @brief Memory allocation mode */ enum class AllocationMode { STANDARD, POOL }; enum class DeclarationType { Tensor = 0, Shape = 1, // Alias = 2 }; class OpenclInitializer; class Common { public: // generate vector of random index permutation of [0..n-1] static void generate_permutation(size_t n, std::vector<size_t>& ind_vector, unsigned int seed = 0); /* * [cols x rows] * A[k x m] * B[n x k] * C[n x m] * https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm * C = alpha * A * B + beta * C * bOffset - in elements (not bytes) */ static void gemm(OPENBLAS_CONST CBLAS_TRANSPOSE transA, OPENBLAS_CONST CBLAS_TRANSPOSE transB, size_t m, size_t n, size_t k, OPENBLAS_CONST dtype alpha, OPENBLAS_CONST dtype* a, OPENBLAS_CONST dtype* b, OPENBLAS_CONST dtype beta, dtype* c); static void gemm(OPENBLAS_CONST CBLAS_TRANSPOSE transA, OPENBLAS_CONST CBLAS_TRANSPOSE transB, size_t m, size_t n, size_t k, OPENBLAS_CONST dtype alpha, OPENBLAS_CONST half* a, OPENBLAS_CONST half* b, OPENBLAS_CONST dtype beta, half* c); /** * @brief : Basic Linear Algebra Subroutine y = y + ax * * \f[ * \vec{y} = \vec{y} + \alpha * \vec{x}, * \f] * * @param n The number of elements in vectors x and y. * @param sa The scalar alpha. * @param sx The vector x of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incx| \f$. * @param incx The stride for vector x. Specified as: an integer. It can have any value. * @param sy The vector y of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incy| \f$. * @param incy The stride for vector y. * @param xOffset The offset for vector x. * @param yOffset The offset for vector y. * @return The vector y, containing the results of the computation. */ static void axpy(size_t n, OPENBLAS_CONST dtype sa, OPENBLAS_CONST dtype* sx, size_t incx, dtype* sy, size_t incy, size_t xOffset = 0, size_t yOffset = 0); static void axpy(size_t n, OPENBLAS_CONST dtype sa, OPENBLAS_CONST half* sx, size_t incx, half* sy, size_t incy, size_t xOffset = 0, size_t yOffset = 0); /** * @brief : Basic Linear Algebra Subroutine y = ax + by * * \f[ * \vec{y} = \alpha \vec{x} + \beta \vec{y}, * \f] * * @param n The number of elements in vectors x and y. * @param alpha The scalar alpha. * @param x The vector x of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incx| \f$. * @param incx The stride for vector x. Specified as: an integer. It can have any value. * @param beta The scalar beta. * @param y The vector y of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incy| \f$. * @param incy The stride for vector y. * @param xOffset The offset for vector x. * @param yOffset The offset for vector y. * @return The vector y, containing the results of the computation. */ static int axpby(OPENBLAS_CONST size_t n, OPENBLAS_CONST dtype alpha, OPENBLAS_CONST dtype* x, OPENBLAS_CONST size_t incx, OPENBLAS_CONST dtype beta, dtype* y, OPENBLAS_CONST size_t incy, size_t xOffset, size_t yOffset); static int axpby(OPENBLAS_CONST size_t n, OPENBLAS_CONST dtype alpha, OPENBLAS_CONST half* x, OPENBLAS_CONST size_t incx, OPENBLAS_CONST dtype beta, half* y, OPENBLAS_CONST size_t incy, size_t xOffset, size_t yOffset); /** * @brief : Basic Linear Algebra Subroutine y = alpha * a * x + beta * y * * Vector by vector element wise multiplication * * \f[ * \vec{y} = \alpha \vec{a} \vec{x} + \beta \vec{y}, * \f] * * @param n The number of elements in vectors x and y. * @param alpha The scalar alpha. * @param a The vector of length n. * @param x The vector x of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incx| \f$. * @param incx The stride for vector x. Specified as: an integer. It can have any value. * @param beta The scalar beta. * @param y The vector y of length n. Specified as: a one-dimensional array of (at least) length \f$ 1+(n-1)|incy| \f$. * @param incy The stride for vector y. */ static void hadamard(OPENBLAS_CONST size_t n, OPENBLAS_CONST dtype alpha, OPENBLAS_CONST dtype* a, OPENBLAS_CONST dtype* x, OPENBLAS_CONST size_t incx, OPENBLAS_CONST dtype beta, dtype* y, OPENBLAS_CONST size_t incy); static dtype dot(size_t n, OPENBLAS_CONST dtype* sx, size_t incx, OPENBLAS_CONST dtype* sy, size_t incy); static void scal(size_t n, OPENBLAS_CONST dtype sa, dtype* sx, size_t incx); static void transpose(Tensor& tensor, size_t cols); static void transpose(TensorFP16& tensor, size_t cols); /* * memory for dst should be allocated externaly */ static void addPadding1D(const dtype* src, dtype* dst, size_t srcChannels, size_t srcSize, size_t dstSize, bool reversedOrder = false); template<typename T> static void addPadding2D(const T* src, T* dst, size_t srcChannels, size_t srcWidth, size_t srcHeight, size_t dstWidth, size_t dstHeight) { if ((dstWidth >= srcWidth) && (dstHeight >= srcHeight)) { size_t padWidth = dstWidth - srcWidth; size_t padHeight = dstHeight - srcHeight; size_t leftPad = padWidth / 2; // size_t rightPad = padWidth - leftPad; size_t topPad = padHeight / 2; size_t bottomPad = padHeight - topPad; for (size_t d = 0; d < srcChannels; ++d) { // top for (size_t y = 0; y < topPad; ++y) { for (size_t x = 0; x < dstWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt); } } for (size_t y = topPad; y < topPad + srcHeight; ++y) { // left for (size_t x = 0; x < leftPad; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt); } // src for (size_t x = leftPad; x < leftPad + srcWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = src[d * srcWidth * srcHeight + srcWidth * (y - topPad) + x - leftPad]; } // right for (size_t x = leftPad + srcWidth; x < dstWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt); } } // bottom for (size_t y = dstHeight - bottomPad; y < dstHeight; ++y) { for (size_t x = 0; x < dstWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = static_cast<T>(0.0_dt); } } } } } /* * memory for dst should be allocated externaly */ static void removePadding1D(const dtype* src, dtype* dst, size_t srcChannels, size_t srcSize, size_t dstSize, bool reversedOrder = false, bool overwrite = true); template<typename T> static void removePadding2D(const T* src, T* dst, size_t srcChannels, size_t srcWidth, size_t srcHeight, size_t dstWidth, size_t dstHeight, bool overwrite = true) { if ((dstWidth <= srcWidth) && (dstHeight <= srcHeight)) { size_t padWidth = srcWidth - dstWidth; size_t padHeight = srcHeight - dstHeight; size_t leftPad = padWidth / 2; // size_t rightPad = padWidth - leftPad; size_t topPad = padHeight / 2; // size_t bottomPad = padHeight - topPad; if (overwrite) { for (size_t d = 0; d < srcChannels; ++d) { for (size_t y = 0; y < dstHeight; ++y) { for (size_t x = 0; x < dstWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] = src[d * srcWidth * srcHeight + srcWidth * (y + topPad) + x + leftPad]; } } } } else { for (size_t d = 0; d < srcChannels; ++d) { for (size_t y = 0; y < dstHeight; ++y) { for (size_t x = 0; x < dstWidth; ++x) { dst[d * dstWidth * dstHeight + dstWidth * y + x] += src[d * srcWidth * srcHeight + srcWidth * (y + topPad) + x + leftPad]; } } } } } } /* * paddingWidth, paddingHeight - zero padding added for both sides of the input * memory for matrix should be allocated externaly */ template<typename T> static void im2col(const T* image, size_t imageWidth, size_t imageHeight, size_t imageChannels, size_t filterWidth, size_t filterHeight, size_t strideWidth, size_t strideHeight, size_t paddingWidth, size_t paddingHeight, T* matrix, bool reversedOrder = false); static size_t im2colOutputSize(size_t imageWidth, size_t imageHeight, size_t imageChannels, size_t filterWidth, size_t filterHeight, size_t strideWidth, size_t strideHeight, size_t paddingWidth, size_t paddingHeight, size_t dilationWidth, size_t dilationHeight); /* * paddingWidth, paddingHeight - zero padding added for both sides of the input * memory for image should be allocated externaly */ template<typename T> static void col2im(const T* matrix, size_t imageWidth, size_t imageHeight, size_t imageChannels, size_t filterWidth, size_t filterHeight, size_t strideWidth, size_t strideHeight, size_t paddingWidth, size_t paddingHeight, T* image, bool reversedOrder = false, bool zeroOutput = true); /* * Rectified Linear Unit */ template<typename T> static T ReLU(T x) { return std::max(static_cast<T>(0), x); } template<typename T> static T ReLU6(T x) { return std::min(std::max(static_cast<T>(0), x), static_cast<T>(6.0_dt)); } template<typename T> static void ReLU(const T& in, T& out) { std::transform(in.begin(), in.end(), out.begin(), [&](typename T::type val) -> typename T::type { return ReLU(val); }); } template<typename T> static void ReLU6(const T& in, T& out) { std::transform(in.begin(), in.end(), out.begin(), [&](typename T::type val) -> typename T::type { return ReLU6(val); }); } template<typename T> static void ReLUBackward(const T& out, const T& delta, T& prevDelta) { #if defined(_OPENMP) #pragma omp parallel for #endif for (size_t q = 0; q < prevDelta.size(); ++q) { prevDelta[q] += (out[q] > static_cast<typename T::type>(0)) ? delta[q] : static_cast<typename T::type>(0); } } template<typename T> static void ReLU6Backward(const T& out, const T& delta, T& prevDelta) { #if defined(_OPENMP) #pragma omp parallel for #endif for (size_t q = 0; q < prevDelta.size(); ++q) { prevDelta[q] += (out[q] > static_cast<typename T::type>(0) && out[q] < static_cast<typename T::type>(6.0f)) ? delta[q] : static_cast<typename T::type>(0); } } /* * Gaussian error linear unit * @see https://arxiv.org/abs/1606.08415 */ static dtype GeLU_Erf(dtype x); static dtype GeLU_Tanh(dtype x); /* * Hard Sigmoid */ template<typename T> static T HSigmoid(T x) { return static_cast<T>(ReLU6(TODTYPE(x) + 3.0_dt) / 6.0_dt); } /* * Hard Swish */ template<typename T> static T HSwish(T x) { return x * HSigmoid(x); } static dtype sign(dtype x) { return TODTYPE((0.0_dt < x) - (x < 0.0_dt)); } template<typename T, typename U> static void copyView(const T& view_from, U& view_to, const bool overwrite = false) { auto retLhs = [](typename T::value_type& lhs, [[maybe_unused]] typename T::value_type& rhs) { return lhs; }; auto copyViewImpl = [](const T& view_from, U& view_to, auto&& func) { for (size_t i1 = 0; i1 < view_from.size(0); ++i1) { for (size_t i2 = 0; i2 < view_from.size(1); ++i2) { for (size_t i3 = 0; i3 < view_from.size(2); ++i3) { for (size_t i4 = 0; i4 < view_from.size(3); ++i4) { view_to[i1][i2][i3][i4] = func(view_from[i1][i2][i3][i4], view_to[i1][i2][i3][i4]); } } } } }; if (overwrite) { copyViewImpl(view_from, view_to, retLhs); } else { copyViewImpl(view_from, view_to, std::plus<typename T::value_type>()); } } template<typename T> static void unpack4D(const T& src, T& dst, Dimension dir, size_t index, const Name& layerType, const Name& layerName, bool overwrite) { auto input4d = src.get4DView(); auto inputDims = yato::dims(src.getDepth(), src.getHeight(), src.getWidth()); auto outputDims = dst.getShape(); const typename T::type* startEl = nullptr; switch (dir) { case Dimension::Depth: startEl = &input4d[0][index][0][0]; break; case Dimension::Height: startEl = &input4d[0][0][index][0]; break; default: throw std::runtime_error(layerType + "[" + layerName + "]: unpack4D unknown dim"); } auto srcView = yato::array_view_4d<const typename T::type>(startEl, outputDims, inputDims); auto outputView = dst.get4DView(); Common::copyView(srcView, outputView, overwrite); } template<typename T> static void pack4D(const T& src, T& dst, Dimension dir, size_t index, const Name& layerType, const Name& layerName, bool overwrite) { auto output4d = dst.get4DView(); yato::dimensionality<3U, size_t> concatDims(dst.getDepth(), dst.getHeight(), dst.getWidth()); auto srcView = src.get4DView(); typename T::type* startEl = nullptr; switch (dir) { case Dimension::Depth: startEl = &output4d[0][index][0][0]; break; case Dimension::Height: startEl = &output4d[0][0][index][0]; break; default: throw std::runtime_error(layerType + "[" + layerName + "]: pack4D unknown dim"); } auto dstView = yato::array_view_4d<typename T::type>(startEl, src.getShape(), concatDims); Common::copyView(srcView, dstView, overwrite); } /* * Upper triangle of a rectangular array */ template<typename T> static void triu(T* data, size_t nrows, size_t ncols, int diag = 0) { size_t i = 0; int cols = (int)ncols; int rows = (int)nrows; for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c, ++i) { if (c - r - diag < 0) { data[i] = static_cast<T>(0); } } } } /* * Applies a 1D convolution over an input signal composed of several input planes. * Supports 2 modes: * 1. PyTorch style: Input[N, C, 1, L1] (or [N, 1, C, L1]) -> Output[N, FILTERS, 1, L2] (or [N, 1, FILTERS, L2]) * 2. TensorFlow style: Input[N, L1, 1, C] (or [N, 1, L1, C]) -> Output[N, L2, 1, FILTERS] (or [N, 1, L2, FILTERS]) * Output is not zeroed prior to convolution (operator += is used) */ static void conv1d(const dtype* input, dtype* output, const dtype* kernel, const dtype* bias, size_t batchSize, size_t inputSize, size_t inputChannels, size_t outputSize, size_t outputChannels, size_t kernelSize, size_t padding, size_t stride, size_t dilation = 1U, size_t groups = 1U, bool tfStyle = false); /* * Applies 2D convolution over input tensor, all channels convolved * Output is not zeroed prior to convolution (operator += is used) */ template<typename T> static void conv2d(const T* input, T* output, const T* kernel, const T* bias, size_t batchSize, size_t inputWidth, size_t inputHeight, size_t inputChannels, size_t outputWidth, size_t outputHeight, size_t outputChannels, size_t kernelWidth, size_t kernelHeight, size_t paddingW, size_t paddingH, size_t strideW, size_t strideH, size_t dilationW = 1U, size_t dilationH = 1U, size_t groups = 1U) { auto inputs3D = yato::array_view_3d<T>(const_cast<T*>(input), yato::dims(batchSize, inputChannels, inputHeight * inputWidth)); auto outputs3D = yato::array_view_3d<T>(output, yato::dims(batchSize, outputChannels, outputHeight * outputWidth)); auto kernelsWeights4D = yato::array_view_4d<T>(const_cast<T*>(kernel), yato::dims(outputChannels, inputChannels / groups, kernelHeight, kernelWidth)); for (size_t q = 0; q < batchSize; ++q) { for (size_t d = 0; d < outputChannels; ++d) { std::fill(outputs3D[q][d].begin(), outputs3D[q][d].end(), static_cast<T>(0.0_dt)); } size_t inputWidthPadded = inputWidth + 2 * paddingW; size_t inputHeightPadded = inputHeight + 2 * paddingH; std::vector<T> inputPadded(inputChannels * inputHeightPadded * inputWidthPadded); Common::addPadding2D(&inputs3D[q][0][0], inputPadded.data(), inputChannels, inputWidth, inputHeight, inputWidthPadded, inputHeightPadded); auto inputPadded2D = yato::view(inputPadded).reshape(yato::dims(inputChannels, inputHeightPadded * inputWidthPadded)); for (size_t group = 0; group < groups; ++group) { for (size_t kernelIndex = 0; kernelIndex < outputChannels / groups; ++kernelIndex) { for (size_t d = 0; d < inputChannels / groups; ++d) { for (size_t oy = 0; oy < outputHeight; ++oy) { for (size_t ox = 0; ox < outputWidth; ++ox) { for (size_t ky = 0; ky < kernelHeight; ++ky) { for (size_t kx = 0; kx < kernelWidth; ++kx) { outputs3D[q][kernelIndex + group * outputChannels / groups][oy * outputWidth + ox] += kernelsWeights4D[kernelIndex + group * outputChannels / groups][d][ky][kx] * inputPadded2D[d + group * inputChannels / groups][oy * inputWidthPadded * strideH + ky * dilationH * inputWidthPadded + ox * strideW + kx * dilationW]; } } } } } } } } if (bias) { for (size_t q = 0; q < batchSize; ++q) { for (size_t kernelIndex = 0; kernelIndex < outputChannels; ++kernelIndex) { for (size_t oy = 0; oy < outputHeight; ++oy) { for (size_t ox = 0; ox < outputWidth; ++ox) { outputs3D[q][kernelIndex][oy * outputWidth + ox] += bias[kernelIndex]; } } } } } } template<typename T = dtype, typename Iterator> static void arange(Iterator begin, Iterator end, T start = static_cast<T>(0), T step = static_cast<T>(1)) { auto val = start; for (auto p = begin; p != end; ++p) { *p = static_cast<std::remove_reference_t<decltype(*p)>>(val); val += step; } } template<typename T = dtype, typename Iterable> static void arange(Iterable& i, T start = static_cast<T>(0), T step = static_cast<T>(1)) { return arange(i.begin(), i.end(), start, step); } static void replaceAll(std::string& str, const std::string& srcSubstr, const std::string& tgtSubstr) { size_t start_pos = 0; while ((start_pos = str.find(srcSubstr, start_pos)) != std::string::npos) { str.replace(start_pos, srcSubstr.length(), tgtSubstr); start_pos += tgtSubstr.length(); // srcSubstr could be a substring of tgtSubstr } } static bool startsWith(const std::string& str, const std::string& srcSubstr) { return (str.rfind(srcSubstr, 0) == 0); } static std::vector<std::string> split(const std::string& string, char delimeter); /* * @see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html */ template<typename T> static bool shapeIsBroadcastable(const T& from, const T& to) { const auto n = to.dimensions_num(); for (size_t i = 0; i < n; ++i) { if (from[i] != to[i] && from[i] != 1U && to[i] != 1U) { return false; } } return true; } static bool endsWith(std::string const& value, std::string const& ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } static shape getStrides(const shape& tensor_shape); static shape offsetToIndexes(size_t offset, const shape& strides); static size_t indexesToOffset(const shape& indexes, const shape& strides); }; template<class T> bool if_equals(const std::string&& error, const T val1, const T val2) { if (val1 != val2) { throw(std::runtime_error(error)); } return val1 == val2; } } // raul namespace #endif // COMMON_H
{ "alphanum_fraction": 0.533324233, "avg_line_length": 34.926102503, "ext": "h", "hexsha": "7afdb9731074bcdc6461c9829d2e1a3060d1bee4", "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": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "steelONIONknight/bolt", "max_forks_repo_path": "training/src/compiler/training/base/common/Common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "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": "steelONIONknight/bolt", "max_issues_repo_path": "training/src/compiler/training/base/common/Common.h", "max_line_length": 195, "max_stars_count": null, "max_stars_repo_head_hexsha": "9bd3d08f2abb14435ca3ad0179889e48fa7e9b47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "steelONIONknight/bolt", "max_stars_repo_path": "training/src/compiler/training/base/common/Common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7228, "size": 29303 }
#pragma once #include "rev/Utilities.h" #include <algorithm> #include <cstddef> #include <glm/glm.hpp> #include <gsl/gsl_assert> #include <gsl/span> #include <limits> #include <vector> namespace rev { template <typename PointType> struct WeightedControlPoint { PointType point; typename PointType::value_type weight; }; template <typename PointType> class NurbsCurve { public: using ControlPointType = WeightedControlPoint<PointType>; using ValueType = typename PointType::value_type; NurbsCurve(size_t order, gsl::span<const ValueType> knots, gsl::span<const ControlPointType> controlPoints) : _order(order) , _knots(knots.begin(), knots.end()) , _controlPoints(controlPoints.begin(), controlPoints.end()) { Expects(order > 1); Expects(static_cast<size_t>(controlPoints.size()) >= order); Expects(knots.size() == (controlPoints.size() + order)); } ValueType getStart() const { return _knots.front(); } ValueType getEnd() const { return _knots.back(); } PointType operator[](ValueType position) const { auto knotsBegin = _knots.begin(); auto knotsEnd = _knots.end(); auto spanStart = std::lower_bound(knotsBegin, knotsEnd, position); size_t controlPointIndex = std::distance(knotsBegin, spanStart); if (controlPointIndex == 0) { // Before the first knot. Just return the value of the first control // point. return _controlPoints.front().point; } if (spanStart == knotsEnd) { // We're past the last knot. Just return the value of the last control // point. return _controlPoints.back().point; } size_t controlPointsToProcess = _order; size_t controlPointCount = _controlPoints.size(); if (controlPointIndex > controlPointCount) { controlPointsToProcess -= (controlPointIndex - controlPointCount); } PointType numerator{ 0 }; ValueType denominator{ 0 }; do { controlPointIndex--; auto& controlPoint = _controlPoints[controlPointIndex]; ValueType weightedBasis = basisValue(position, controlPointIndex, _order) * controlPoint.weight; numerator += weightedBasis * _controlPoints[controlPointIndex].point; denominator += weightedBasis; controlPointsToProcess--; } while (controlPointIndex && controlPointsToProcess); return numerator / denominator; } private: ValueType basisValue(ValueType position, size_t controlPointIndex, size_t order) const { auto& controlPoint = _controlPoints[controlPointIndex]; ValueType firstKnot = _knots[controlPointIndex]; ValueType lastKnot = _knots[controlPointIndex + order]; if (order == 2) { // Triangle function ValueType middleKnot = _knots[controlPointIndex + 1]; if (position < middleKnot) { return rampUp(position, firstKnot, middleKnot); } else { return rampDown(position, middleKnot, lastKnot); } } else { size_t lowerOrder = order - 1; ValueType secondKnot = _knots[controlPointIndex + 1]; ValueType secondToLastKnot = _knots[controlPointIndex + lowerOrder]; ValueType result{ 0 }; if (position < secondToLastKnot) { result += rampUp(position, firstKnot, secondToLastKnot) * basisValue(position, controlPointIndex, lowerOrder); } if (position > secondKnot) { result += rampDown(position, secondKnot, lastKnot) * basisValue(position, controlPointIndex + 1, lowerOrder); } return result; } } ValueType rampUp(ValueType value, ValueType bottom, ValueType top) const { if (nearEqual(top, bottom)) { return 0.5; } return (value - bottom) / (top - bottom); } ValueType rampDown(ValueType value, ValueType bottom, ValueType top) const { if (nearEqual(top, bottom)) { return 0.5; } return (top - value) / (top - bottom); } size_t _order; std::vector<ValueType> _knots; std::vector<ControlPointType> _controlPoints; }; } // namespace rev
{ "alphanum_fraction": 0.6167192429, "avg_line_length": 33.3684210526, "ext": "h", "hexsha": "529b665a111198535de3bb2285fcabbcd4d1ff51", "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": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "eyebrowsoffire/rev", "max_forks_repo_path": "engine/include/rev/NurbsCurve.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "eyebrowsoffire/rev", "max_issues_repo_path": "engine/include/rev/NurbsCurve.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "eyebrowsoffire/rev", "max_stars_repo_path": "engine/include/rev/NurbsCurve.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1011, "size": 4438 }
// // Created by karl_ on 2020-5-3. // #include <stdlib.h> #include <math.h> #include <cblas.h> #include <core/color-space.h> #include <imgproc/histogram-equalization.h> // ref: https://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf static void histeq(double const *src, double *dst, size_t area, unsigned range) { unsigned *cdf; size_t i; cdf = calloc(range, sizeof(unsigned)); for (i = 0; i < area; ++i) { cdf[(int) (src[i] * range)] += 1; } for (i = 1; i < range; ++i) { cdf[i] += cdf[i - 1]; } for (i = 0; i < area; ++i) { dst[i] = floor((double) (range - 1) * cdf[(int) (src[i] * range)] / area) / range; } free(cdf); } gboolean imgproc_histogram_equalization(CoreImage *src, CoreImage **dst) { gdouble *src_data_cast = NULL; gdouble *dst_data_cast = NULL; gpointer src_data, dst_data; CoreSize *size = NULL; guint8 channel; gsize i, area; CoreColorSpace color_space; CorePixelType pixel_type; gdouble range, inv_range; g_return_val_if_fail(src != NULL, FALSE); g_return_val_if_fail(dst != NULL, FALSE); /* TODO: impl. for multiple channels */ channel = core_image_get_channel(src); g_return_val_if_fail(channel == 1, FALSE); src = g_object_ref(src); src_data = core_image_get_data(src); size = core_image_get_size(src); area = core_size_get_area(size); color_space = core_image_get_color_space(src); pixel_type = core_image_get_pixel_type(src); range = core_pixel_get_range(pixel_type); inv_range = 1.0 / range; /* cast to double and normalize pixel data to [0, 1] */ if (core_pixel_is_double(pixel_type)) { src_data_cast = src_data; } else if (core_pixel_is_uint8(pixel_type)) { src_data_cast = g_malloc(sizeof(gdouble) * area); for (i = 0; i < area; ++i) { src_data_cast[i] = ((guint8 *) src_data)[i] * inv_range; } } else { g_return_val_if_fail(FALSE, FALSE); } dst_data_cast = g_malloc(sizeof(gdouble) * area); /* run the algorithm */ histeq(src_data_cast, dst_data_cast, area, 256); /* cast back to uchar */ if (core_pixel_is_double(pixel_type)) { /* exactly do nothing */ } else if (core_pixel_is_uint8(pixel_type)) { /* reuse allocated memory */ for (i = 0; i < area; ++i) { ((guint8 *) dst_data_cast)[i] = dst_data_cast[i] * 255.0; } } else { g_return_val_if_fail(FALSE, FALSE); } dst_data = dst_data_cast; if (core_pixel_is_uint8(pixel_type)) { /* release useless memory, can be removed for speed */ dst_data = g_realloc(dst_data, sizeof(guint8) * area); } if (*dst == NULL) { *dst = core_image_new_with_data(dst_data, color_space, pixel_type, size, FALSE); } else { core_image_assign_data(*dst, dst_data, color_space, pixel_type, size, FALSE); } /* free allocated additional memory */ if (core_pixel_is_uint8(pixel_type)) { g_free(src_data_cast); } g_object_unref(size); g_object_unref(src); return TRUE; }
{ "alphanum_fraction": 0.6034535924, "avg_line_length": 31.4854368932, "ext": "c", "hexsha": "31586ad8c4d99e8454b1feb9ad0c6bd2fed6adcc", "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": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_forks_repo_path": "imgproc/histogram-equalization.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "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": "zhengbanbufengbi/EasyPhotoshop", "max_issues_repo_path": "imgproc/histogram-equalization.c", "max_line_length": 91, "max_stars_count": 1, "max_stars_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_stars_repo_path": "imgproc/histogram-equalization.c", "max_stars_repo_stars_event_max_datetime": "2020-05-30T14:58:05.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-30T14:58:05.000Z", "num_tokens": 873, "size": 3243 }
/* Copyright [2019, 2020] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CCPM_AREATOP_ALLOCATOR_H__ #define __CCPM_AREATOP_ALLOCATOR_H__ #include "atomic_word.h" #include "list_item.h" #include <ccpm/interfaces.h> #include <common/byte_span.h> #include <gsl/pointers> #include <array> #include <cstddef> #include <ios> // ios_base::fmtflags, ostream #include <vector> namespace ccpm { struct level_hints { private: /* Each level has a list for every possible number of contiguous free elements. * of contiguous free elements. * Since "contiguous" free elements do not span a word, that is one list * for every possible contiguous size in a word. * The list at element n locates an area_ctl with has maximal runs of exactly * n+1 free elements, */ using free_ctls_t = std::array<list_item, alloc_states_per_word>; free_ctls_t _free_ctls; free_ctls_t::size_type find_free_ctl_ix(unsigned min_run_length) const; free_ctls_t::size_type tier_ix_from_run_length(unsigned run_length) const; public: unsigned _ct_alloc_probe_success; unsigned _ct_alloc_probe_failure; unsigned _ct_subdivision; public: static constexpr auto size() { return alloc_states_per_word; } /* return smallest tier index which has an area with * run length >= min_run_length * If no such tier, return sub_states_per_word. */ auto find_free_ctl(unsigned min_run_length_) const -> const list_item * { return & _free_ctls[find_free_ctl_ix(min_run_length_)]; } auto find_free_ctl(unsigned min_run_length_) -> list_item * { return & _free_ctls[find_free_ctl_ix(min_run_length_)]; } const auto *tier_from_run_length(unsigned run_length_) const { return & _free_ctls[tier_ix_from_run_length(run_length_)]; } auto *tier_from_run_length(unsigned run_length_) { return & _free_ctls[tier_ix_from_run_length(run_length_)]; } const auto *tier_end() const { return &_free_ctls[alloc_states_per_word]; } /* Find the longest run length less than mac_run_length. * Used for tracing, when find_free_ctl_ix has failed to * find a long enough run */ free_ctls_t::size_type find_mac_ctl_ix(unsigned mac_run_length) const; level_hints() : _free_ctls() , _ct_alloc_probe_success(0) , _ct_alloc_probe_failure(0) , _ct_subdivision(0) {} using level_ix_t = std::uint8_t; void print( std::ostream &o_ , level_ix_t level_ , std::ios_base::fmtflags // size_format_ ) const; }; struct area_ctl; /* * Location of non-persisted items for a single "region" managed by the crash-consistent allocator. * Persisted items are keps in an area_ctl, which is in persistent memory. */ struct area_top { private: using level_ix_t = std::uint8_t; using byte_span = common::byte_span; using persist_type = gsl::not_null<ccpm::persister *>; area_ctl *_ctl; std::size_t _bytes_free; bool _all_restored; unsigned _trace_level; std::ostream *_o; using level_hints_vec = std::vector<level_hints>; level_hints_vec _level; unsigned _ct_allocation; byte_span _region; /* for get_region only */ area_top( // persist_type persist area_ctl *ctl , unsigned trace_level , byte_span iov , std::ostream &o ); area_top(const area_top &) = delete; area_top &operator=(const area_top &) = delete; void allocate_strategy_1( persist_type persist_ , void * & ptr_ , std::size_t bytes , std::size_t alignment , level_hints_vec::iterator level_ , unsigned run_length ); bool allocate_recovery_1(); bool allocate_recovery_2(persist_type persist, level_hints_vec::iterator level); bool trace_coarse() const { return 0 < _trace_level; } bool trace_fine() const { return 1 < _trace_level; } public: /* Initial area_ctl */ explicit area_top( persist_type persist , byte_span iov , unsigned trace_level , std::ostream &o ); /* Restored area_ctl */ explicit area_top( persist_type persist , byte_span iov , const ownership_callback_t &resolver , unsigned trace_level , std::ostream &o ); ~area_top(); bool includes(const void *addr) const; /* Free byte count. Required by users */ std::size_t bytes_free() const; byte_span get_region() const { return _region; } void allocate( persist_type persist , void * & ptr, std::size_t bytes , std::size_t alignment ); void deallocate( persist_type persist , void * & ptr, std::size_t bytes ); void print( std::ostream &o , std::ios_base::fmtflags size_format ) const; void print_ctls( std::ostream *o_ , std::ios_base::fmtflags format_ ) const; level_ix_t height() const { return level_ix_t(_level.size()); } void set_root(const byte_span & iov, persist_type persist); byte_span get_root() const; /* * called by area_ctl to add area_ctl a, at level level_ix, with a longest * free run (consecutive free elements) of free_run, to _level, which is the * non-persistent catalog of area_ctl items. */ void remove_from_chain(area_ctl *a, level_ix_t level_ix, unsigned longest_run); void restore_to_chain(area_ctl *a, level_ix_t level_ix, unsigned run_length); bool contains(const void *p) const; bool is_in_chain( const area_ctl *a , level_ix_t level_ix , unsigned run_length ) const; }; } #endif
{ "alphanum_fraction": 0.7218622101, "avg_line_length": 26.8990825688, "ext": "h", "hexsha": "21840f94503ff1a37723b0ddcda5d0e937472f30", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_path": "src/lib/libccpm/src/area_top.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_path": "src/lib/libccpm/src/area_top.h", "max_line_length": 100, "max_stars_count": 60, "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_path": "src/lib/libccpm/src/area_top.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 1611, "size": 5864 }
#ifndef __CROSSBOW_BLAS_H_ #define __CROSSBOW_BLAS_H_ #include <cblas.h> #include <jni.h> void blas_init (int size, int bufferSize); void blas_free (); enum CBLAS_TRANSPOSE getCblasTrans (const char *); void *getObjectBufferAddress (JNIEnv *, jobject, int); #endif /* __CROSSBOW_BLAS_H_ */
{ "alphanum_fraction": 0.7542087542, "avg_line_length": 17.4705882353, "ext": "h", "hexsha": "f294f1d044d46a548328aeb545586f768858983e", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:13:09.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-20T14:56:41.000Z", "max_forks_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lsds/Crossbow", "max_forks_repo_path": "clib-multigpu/BLAS.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_issues_repo_issues_event_max_datetime": "2021-12-14T21:16:53.000Z", "max_issues_repo_issues_event_min_datetime": "2019-01-18T07:31:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "lsds/Crossbow", "max_issues_repo_path": "clib-multigpu/BLAS.h", "max_line_length": 54, "max_stars_count": 50, "max_stars_repo_head_hexsha": "d4441b35315f9f7d48293fe81faaf21e1ca48002", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lsds/Crossbow", "max_stars_repo_path": "clib-multigpu/BLAS.h", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:42:51.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-09T14:30:41.000Z", "num_tokens": 82, "size": 297 }
#ifndef __INS_C_H__ #define __INS_C_H__ /********************************* TRICK HEADER ******************************* PURPOSE: (Describe the INS Module On Board, Error equations based on Zipfel, Figure 10.27, space stabilized INS with GPS updates) LIBRARY DEPENDENCY: ((../src/gnc_var.c) (../src/Ins_c.c) (../../cad/src/global_constants.c) (../src/dm_delta_ut.c)) *******************************************************************************/ #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <math.h> #include <stdio.h> #include "cad_utility_c.h" #include "math_utility_c.h" #include "time_utility_c.h" extern const double __DM_sec2r; extern const double __DM_arcsec2r; extern const double __WEII3; extern const double __SMAJOR_AXIS; extern const double __GM; extern const double __WEII3; extern const double ___PI; extern const double __EPS; extern const double __DEG; extern const double __RAD; /** INS Variables **/ /* Matrix */ extern gsl_matrix *WEII; extern gsl_matrix *TBIC; extern gsl_matrix *TDCI; extern gsl_matrix *TEIC; extern gsl_matrix *TBDC; extern gsl_matrix *TBICI; extern gsl_matrix *TLI; /* Vector */ extern gsl_vector *EVBI; extern gsl_vector *EVBID; extern gsl_vector *ESBI; extern gsl_vector *ESBID; extern gsl_vector *RICI; extern gsl_vector *RICID; extern gsl_vector *TBIC_Q; extern gsl_vector *TBIDC_Q; extern gsl_vector *SBIIC; extern gsl_vector *VBIIC; extern gsl_vector *SBEEC; extern gsl_vector *VBEEC; extern gsl_vector *WBICI; extern gsl_vector *EGRAVI; extern gsl_vector *VBECD; extern gsl_vector *INS_I_ATT_ERR; extern gsl_vector *TESTV; extern gsl_vector *TMP_old; extern gsl_vector *VBIIC_old; extern gsl_vector *POS_ERR; extern gsl_vector *GRAVGI; extern gsl_vector *TBDCQ; extern gsl_vector *VBIIC_old_old; extern gsl_vector *PHI_C; extern gsl_vector *DELTA_VEL_C; extern gsl_vector *PHI_LOW_C; extern gsl_vector *PHI_HIGH_C; /* Double */ extern double dbic; extern double dvbec; extern double alphacx; extern double betacx; extern double thtvdcx; extern double psivdcx; extern double alppcx; extern double phipcx; extern double loncx; extern double latcx; extern double altc; extern double phibdcx; extern double thtbdcx; extern double psibdcx; extern double ins_pos_err; extern double ins_vel_err; extern double ins_tilt_err; extern double ins_pose_err; extern double ins_vele_err; extern double ins_phi_err; extern double ins_tht_err; extern double ins_psi_err; /* Unsigned int */ extern unsigned int gpsupdate; extern unsigned int liftoff; extern unsigned int ideal; extern GPS_TIME gpstime; extern UTC_TIME utctime; /*******************/ #ifdef __cplusplus extern "C" { #endif int load_location(double lonx, double latx, double alt); int load_angle(double yaw, double roll, double pitch, GPS_TIME gps_time); int load_geodetic_velocity(double alpha0x, double beta0x, double dvbe); int calculate_INS_derived_TEI(GPS_TIME gps, gsl_matrix *TEIC); int AccelHarmonic(const gsl_vector *SBII, double CS[21][21], int n_max, int m_max, const gsl_matrix *TEIC, gsl_vector *acc_out); int DCM_2_Euler_angle(const gsl_matrix *TBD, double *phibdc, double *thtbdc, double *psibdc); int calculate_INS_derived_phip(gsl_vector *VBECB, double *phipc); int calculate_INS_derived_thtvd(gsl_vector *VBECD, double *thtvd); int calculate_INS_derived_psivd(gsl_vector *VBECD, double *psivd); int calculate_INS_derived_alpp(gsl_vector *VBECB, double *alpp); int calculate_INS_derived_beta(gsl_vector *VBECB, double *beta); int calculate_INS_derived_alpha(gsl_vector *VBECB, double *alpha); int build_VBEB(double _alpha0x, double _beta0x, double _dvbe, gsl_vector *VBEB); int INS_update(const double int_step, double *dvbec, unsigned int liftoff, double *alphacx, double *betacx , double *alppcx, double *phipcx, double *loncx, double *latcx, double *altc, double *psivdcx, double *thtvdcx , double *phibdc, double *thtbdc, double *psibdc , gsl_vector *PHI, gsl_vector *DELTA_VEL , gsl_vector *PHI_HIGH, gsl_vector *PHI_LOW, GPS_TIME gps, gsl_matrix *TEIC , gsl_vector *SBIIC, gsl_vector *VBIIC, gsl_vector *VBIIC_old, gsl_vector *GRAVGI, gsl_matrix *TBIC, gsl_vector *SBEEC , gsl_vector *VBEEC, gsl_matrix *WEII, gsl_matrix *TLI, gsl_matrix *TDCI , gsl_matrix *TBICI, gsl_matrix *TBDC, gsl_vector *TBDCQ); int INS_init(GPS_TIME gps_time); int INS_alloc(); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7237929535, "avg_line_length": 34.5714285714, "ext": "h", "hexsha": "f1fc4e904c6f0a96c65e1565e2db858bcf613323", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_path": "models/gnc/include/Ins_c.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_path": "models/gnc/include/Ins_c.h", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_path": "models/gnc/include/Ins_c.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1253, "size": 4598 }
/* * Assignment 4, Question 5 matvec implementation in C using MPI. * * Copyright (C) 2015, Jonathan Gillett (100437638) * All rights reserved. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cblas.h> #include <mpi.h> // Minimum of two values #define min(a, b) (((a) < (b)) ? (a) : (b)) // Define process 0 as MASTER #define MASTER 0 // Message tags #define REQUEST 1 #define REPLY 2 // Master process, divides up the matrix into rows for computation by slaves void master(int n_proc, int n_rows, int n_cols) { // 0. Allocate space for arrays as needed to compute y = A*x double *x = (double *) malloc(n_cols*sizeof(double)); double *y = (double *) malloc(n_rows*sizeof(double)); double *z = (double *) malloc(n_rows*sizeof(double)); double *A = (double *) malloc(n_rows*n_cols*sizeof(double)); double *sub = (double *) malloc(n_cols*sizeof(double)); double ans = 0.0; int n_sent = 0, row = 0, sender = 0; MPI_Status status; // 1. Define data A (n_rows x n_cols matrix) and x (n_cols x 1 vector) for (int i = 0; i < n_cols; ++i) { x[i] = i+1; } for (int i = 0; i < n_rows; ++i) { for (int j = 0; j < n_cols; ++j) { A[(i*n_cols)+j] = i+1; } } // 2. Broadcast vector x to all processes MPI_Bcast(x, n_cols, MPI_DOUBLE, MASTER, MPI_COMM_WORLD); // 3. Send first rows to other processes for (int i = 1; i < min(n_rows+1, n_proc); ++i) { memcpy((void *) sub, (void *) &A[n_sent*n_cols], n_cols * sizeof(double)); MPI_Send(sub, n_cols, MPI_DOUBLE, i, n_sent, MPI_COMM_WORLD); n_sent++; } // Now loop over remaining rows, receiving dot products computed for (int i = 0; i < n_rows; ++i) { // Receive a computed inner product from one of the processes MPI_Recv(&ans, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); sender = status.MPI_SOURCE; row = status.MPI_TAG; y[row] = ans; // Either send another row back to sender or send final y=Ax // along with a tag to signal completion. if (n_sent < n_rows) { memcpy((void *) sub, (void *) &A[n_sent*n_cols], n_cols * sizeof(double)); MPI_Send(sub, n_cols, MPI_DOUBLE, sender, n_sent, MPI_COMM_WORLD); n_sent++; } // Inform sender that there is no more work else { MPI_Send(y, n_rows, MPI_DOUBLE, sender, n_rows+1, MPI_COMM_WORLD); } } printf("Finished!\n"); // Calculate the norm to verify ||y-Ax|| is correct cblas_dgemv(CblasRowMajor, CblasNoTrans, n_rows, n_cols, 1.0, A, n_cols, x, 1, 0.0, z, 1); for (int i = 0; i < n_rows; ++i) { y[i] -= z[i]; } printf("Check: ||y-Ax|| = %f\n", cblas_dnrm2(n_rows, y, 1)); free(x); free(y); free(z); free(A); free(sub); } // Slave process computes inner product and returns result to master process void slave(int proc_id, int n_rows, int n_cols) { // Allocate arrays for receiving and sending rows & dot products double *x = (double *) malloc(n_cols*sizeof(double)); double *my_row = (double *) malloc(n_cols*sizeof(double)); double ans = 0.0; int row = 0; MPI_Status status; // 1. Receive vector x from master process MPI_Bcast(x, n_cols, MPI_DOUBLE, MASTER, MPI_COMM_WORLD); // Receive row to calculate from master process MPI_Recv(my_row, n_cols, MPI_DOUBLE, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status); row = status.MPI_TAG; while (row < n_rows) { // Compute inner product and return result to master process ans = cblas_ddot(n_cols, my_row, 1, x, 1); MPI_Send(&ans, 1, MPI_DOUBLE, MASTER, row, MPI_COMM_WORLD); // Receive new row from master MPI_Recv(my_row, n_cols, MPI_DOUBLE, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status); row = status.MPI_TAG; } } int main(int argc, char *argv[]) { int proc_id; // Process ID number int n_proc; // Number of processes int n_rows = 1000; // Number of rows int n_cols = 1000; // Number of columns // Initialize MPI MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &n_proc); MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); if (n_proc == 1) { puts("Error: requires two or more processes (no work will be done)."); MPI_Finalize(); exit(1); } if (proc_id == MASTER) { master(n_proc, n_rows, n_cols); } else { slave(proc_id, n_rows, n_cols); } MPI_Finalize(); return 0; }
{ "alphanum_fraction": 0.5990225244, "avg_line_length": 31.3733333333, "ext": "c", "hexsha": "83ed710e839fc1d7bca56cfd184de326fa73e92d", "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": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gnu-user/mcsc-6030-assignments", "max_forks_repo_path": "Assignment-04/Question-05/matvec.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "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": "gnu-user/mcsc-6030-assignments", "max_issues_repo_path": "Assignment-04/Question-05/matvec.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gnu-user/mcsc-6030-assignments", "max_stars_repo_path": "Assignment-04/Question-05/matvec.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1342, "size": 4706 }
#include <stdio.h> #include <gsl/gsl_combination.h> void print_all_combinations ( size_t n, size_t k ); int main (void) { gsl_combination * c; size_t i; printf("all subsets of {0,1,2,3} by size (lex. order)\n") ; for(i = 0; i <= 4; i++) { c = gsl_combination_calloc (4, i); do { printf("{"); gsl_combination_fprintf (stdout, c, " %u"); printf(" }\n"); } while (gsl_combination_next(c) == GSL_SUCCESS); gsl_combination_free(c); } printf("all subsets of {1,2,3,4} by size (reverse lex. order)\n") ; for(i = 0; i <= 4; i++) { c = gsl_combination_alloc (4, i) ; gsl_combination_init_last(c) ; do { printf("{"); gsl_combination_fprintf (stdout, c, " %u"); printf(" }\n"); } while (gsl_combination_prev(c) == GSL_SUCCESS); gsl_combination_free(c); } printf("\n"); print_all_combinations(5, 3); print_all_combinations(5, 0); print_all_combinations(5, 5); print_all_combinations(1, 1); print_all_combinations(3, 1); return 0; } void print_all_combinations (size_t n, size_t k) { gsl_combination * c = gsl_combination_calloc (n, k); printf("combinations %u choose %u\n", n, k); do { gsl_combination_fprintf (stdout, c, " %u"); printf("\n"); } while (gsl_combination_next(c) == GSL_SUCCESS); do { gsl_combination_fprintf (stdout, c, " %u"); printf("\n"); } while (gsl_combination_prev(c) == GSL_SUCCESS); printf("\n"); gsl_combination_free(c); }
{ "alphanum_fraction": 0.5773584906, "avg_line_length": 21.7808219178, "ext": "c", "hexsha": "b5dac224e235c7131f4a44934bf14947913e3ca9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/combination/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/combination/demo.c", "max_line_length": 69, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/combination/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 488, "size": 1590 }
/* * Reinforcement Learning Book / Exercise 4.7 * * $ sudo apt-get install libgsl-dev libgsl2 * $ gcc car_rental2.c -lgsl -lgslcblas -lm -o car_rental2 */ #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_randist.h> #define Size 20 #define Iteration 100 #define Rent1_mean 3 #define Rent2_mean 4 #define Return1_mean 3 #define Return2_mean 2 // Global variables float value[Size + 1][Size + 1]; int policy[Size + 1][Size + 1]; void show_value(){ printf("["); for (int c1 = 0; c1 <= Size; c1++) { printf("["); for (int c2 = 0; c2 <= Size; c2++) { printf("%3.0f", value[c1][c2]); if (c2 < Size) { printf(", "); } } printf("]"); if (c1 < Size) { printf(",\n "); } } printf("]\n"); } void show_policy(){ printf("["); for (int c1 = 0; c1 <= Size; c1++) { printf("["); for (int c2 = 0; c2 <= Size; c2++) { printf("%2d", policy[c1][c2]); if (c2 < Size) { printf(", "); } } printf("]"); if (c1 < Size) { printf(",\n "); } } printf("]\n"); } float calc_q_val(int c1, int c2, int a){ float q_val = 0; int _c1, _c2; float c1_rent_prob, c2_rent_prob, c1_return_prob, c2_return_prob, prob; // Moving cars c1 -= a; c2 += a; if (a > 0) { q_val -= 2*(a-1); } else { q_val -= 2*abs(a); } if (c1 > 10) q_val -= 4; if (c2 > 10) q_val -= 4; for (int c1_rent = 0; c1_rent <= c1; c1_rent++) { for (int c2_rent = 0; c2_rent <= c2; c2_rent++) { for (int c1_return = 0; c1_return <= Size-(c1-c1_rent); c1_return++) { for (int c2_return = 0; c2_return <= Size-(c2-c2_rent); c2_return++) { _c1 = c1 - c1_rent + c1_return; _c2 = c2 - c2_rent + c2_return; if (c1_rent == c1) { c1_rent_prob = 1; for (int n = 0; n < c1_rent; n++) { c1_rent_prob -= gsl_ran_poisson_pdf(n, Rent1_mean); } } else { c1_rent_prob = gsl_ran_poisson_pdf(c1_rent, Rent1_mean); } if (c2_rent == c2) { c2_rent_prob = 1; for (int n = 0; n < c2_rent; n++) { c2_rent_prob -= gsl_ran_poisson_pdf(n, Rent2_mean); } } else { c2_rent_prob = gsl_ran_poisson_pdf(c2_rent, Rent2_mean); } if (c1_return == Size-(c1-c1_rent)) { c1_return_prob = 1; for (int n = 0; n < c1_return; n++) { c1_return_prob -= gsl_ran_poisson_pdf(n, Return1_mean); } } else { c1_return_prob = gsl_ran_poisson_pdf(c1_return, Return1_mean); } if (c2_return == Size-(c2-c2_rent)) { c2_return_prob = 1; for (int n = 0; n < c2_return; n++) { c2_return_prob -= gsl_ran_poisson_pdf(n, Return2_mean); } } else { c2_return_prob = gsl_ran_poisson_pdf(c2_return, Return2_mean); } prob = c1_rent_prob * c2_rent_prob * c1_return_prob * c2_return_prob; q_val += prob * (10 * (c1_rent + c2_rent) + 0.9 * value[_c1][_c2]); } } } } return q_val; } int min(int a, int b){ if (a < b) { return a; } else { return b; } } void run() { float q_val; float value_update; int policy_update; for (int c1 = 0; c1 <= Size; c1++) { for (int c2 = 0; c2 <= Size; c2++) { value[c1][c2] = 0; policy[c1][c2] = 0; } } printf("# Iteration 0\n"); show_policy(); show_value(); for (int i = 1; i < Iteration; i++) { for (int c1 = 0; c1 <= Size; c1++) { for (int c2 = 0; c2 <= Size; c2++) { int update = 0; for (int a = -min(c2, 5); a <= min(c1, 5); a++) { q_val = calc_q_val(c1, c2, a); if (update == 0 || q_val > value_update) { value_update = q_val; policy_update = a; update = 1; } } value[c1][c2] = value_update; policy[c1][c2] = policy_update; } } printf("# Iteration %d\n", i); show_policy(); show_value(); } } int main() { run(); }
{ "alphanum_fraction": 0.4175757576, "avg_line_length": 27.0491803279, "ext": "c", "hexsha": "085c0253e5e4263108ad663e0d3a6a62e8ecae9c", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-01-11T12:46:22.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-22T06:19:14.000Z", "max_forks_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "enakai00/rl_book_solutions", "max_forks_repo_path": "Chapter04/car_rental2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "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": "enakai00/rl_book_solutions", "max_issues_repo_path": "Chapter04/car_rental2.c", "max_line_length": 89, "max_stars_count": 13, "max_stars_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "enakai00/rl_book_solutions", "max_stars_repo_path": "Chapter04/car_rental2.c", "max_stars_repo_stars_event_max_datetime": "2021-03-25T17:40:11.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-06T13:36:32.000Z", "num_tokens": 1395, "size": 4950 }
#include <glib.h> #include <gsl/gsl_rng.h> #include <stdlib.h> #include "util.h" hash_t *hash_create () { return (char*) g_hash_table_new(g_direct_hash, g_direct_equal); } void hash_set (hash_t *table, size_t key, size_t value) { g_hash_table_replace((GHashTable*)table, (gpointer)key, (gpointer)value); } size_t hash_get (hash_t *table, size_t key, size_t value) { size_t orig_key; size_t result; if (g_hash_table_lookup_extended((GHashTable*)table, (gpointer)key, (gpointer*)&orig_key, (gpointer*)&result)) { return result; } return value; } void hash_clear (hash_t *table) { return g_hash_table_remove_all((GHashTable*)table); } void hash_destroy (hash_t *table) { return g_hash_table_destroy((GHashTable*)table); } gsl_rng *r = 0; size_t random_range (size_t lo, size_t hi) { if (!r) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; r = gsl_rng_alloc (T); } size_t n = hi - lo; return lo + gsl_rng_uniform_int(r, n);//todo this range might not be big enough/type issues may occur here. } double random_uniform () { if (!r) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; r = gsl_rng_alloc (T); } return gsl_rng_uniform(r); } void random_choose (size_t *samples, size_t n, size_t lo, size_t hi) { hash_t *table = hash_create(); for (size_t i = 0; i < n; i++) { size_t j = random_range(lo, hi); samples[i] = hash_get(table, j, j); hash_set(table, j, hash_get(table, lo, lo)); lo++; } hash_destroy(table); } int size_t_cmp(const void *a, const void *b) { const size_t *ia = (const size_t *)a; const size_t *ib = (const size_t *)b; return *ia - *ib; } void quicksort(size_t *stuff, size_t n) { if (n < 2) return; size_t pivot = stuff[n / 2]; size_t i, j; for (i = 0, j = n - 1; ; i++, j--) { while (stuff[i] < pivot) i++; while (stuff[j] > pivot) j--; if (i >= j) break; size_t temp = stuff[i]; stuff[i] = stuff[j]; stuff[j] = temp; } quicksort(stuff, i); quicksort(stuff + i, n - i); } void sort (size_t *stuff, size_t n) { //quicksort(stuff, n); qsort(stuff, n, sizeof(size_t), size_t_cmp); } size_t search (const size_t *stuff, size_t lo, size_t hi, size_t key) { size_t len = hi - lo; size_t half; size_t mid; while (len > 0) { half = len >> 1; mid = lo + half; if (stuff[mid] >= key) { len = half; } else { lo = mid; lo++; len = len - half - 1; } } return lo; } size_t search_strict (const size_t *stuff, size_t lo, size_t hi, size_t key) { size_t len = hi - lo; size_t half; size_t mid; while (len > 0) { half = len >> 1; mid = lo + half; if (stuff[mid] > key) { len = half; } else { lo = mid; lo++; len = len - half - 1; } } return lo; }
{ "alphanum_fraction": 0.606092437, "avg_line_length": 21.4736842105, "ext": "c", "hexsha": "a1384745c2d480e631c6e6848b6ebcafac22a7a7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_forks_repo_path": "src/util.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_issues_repo_path": "src/util.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "src/util.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 914, "size": 2856 }
#pragma once #include "tino/backends/backends.h" #include "tino/backends/tensor_wrappers.h" #include "tino/utils/macros.h" #ifdef TINO_OPENBLAS_READY #include <cblas.h> #endif namespace tino { namespace core { class context; } namespace backends { namespace blas { enum class layout_t { #ifdef TINO_OPENBLAS_READY RowMajor = CblasRowMajor, ColumnMajor = CblasColMajor #else RowMajor, ColumnMajor #endif }; enum class trans_t { #ifdef TINO_OPENBLAS_READY NoTrans = CblasNoTrans, Trans = CblasTrans #else NoTrans, Trans #endif }; template <typename T> struct blasOpts { T alpha = (T)0; T beta = (T)0; layout_t layout = layout_t::RowMajor; trans_t trans_a = trans_t::NoTrans; trans_t trans_b = trans_t::NoTrans; }; template <typename T> tensor2d<T>& blas_gemm(core::context& ctx, const blasOpts<T>& blas_opts, tensor2d<T>& A, tensor2d<T>& B, tensor2d<T>& C) {} template <> tensor2d<float>& blas_gemm(core::context& ctx, const blasOpts<float>& blas_opts, tensor2d<float>& A, tensor2d<float>& B, tensor2d<float>& C) { #ifdef TINO_OPENBLAS_READY const int M = blas_opts.trans_a == trans_t::NoTrans ? A.template shape<1>() : A.template shape<0>(); const int N = blas_opts.trans_b == trans_t::NoTrans ? B.template shape<0>() : B.template shape<1>(); const int K = blas_opts.trans_a == trans_t::NoTrans ? A.template shape<0>() : A.template shape<1>(); const int lda = blas_opts.trans_a == trans_t::NoTrans ? K : M; const int ldb = blas_opts.trans_b == trans_t::NoTrans ? N : K; const int ldc = N; cblas_sgemm(static_cast<CBLAS_LAYOUT>(blas_opts.layout), static_cast<CBLAS_TRANSPOSE>(blas_opts.trans_a), static_cast<CBLAS_TRANSPOSE>(blas_opts.trans_b), M, N, K, blas_opts.alpha, A.data(), lda, B.data(), ldb, blas_opts.beta, C.data(), ldc); #else std::cerr << "invalid backend: OpenBLAS" << std::endl; std::exit(1); #endif TINO_MAYBE_UNUSED(ctx); TINO_MAYBE_UNUSED(blas_opts); TINO_MAYBE_UNUSED(A); TINO_MAYBE_UNUSED(B); TINO_MAYBE_UNUSED(C); return C; } } // namespace blas } // namespace backends } // namespace tino
{ "alphanum_fraction": 0.5644054878, "avg_line_length": 29.8181818182, "ext": "h", "hexsha": "b52775d2972960134b8a65369a9701bc2f593f3e", "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": "ea47bd485e7b6be11e8481eff8fd2e7826fb1ef5", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Senseirn/tino", "max_forks_repo_path": "tino/backends/blas/blas_wrappers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ea47bd485e7b6be11e8481eff8fd2e7826fb1ef5", "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": "Senseirn/tino", "max_issues_repo_path": "tino/backends/blas/blas_wrappers.h", "max_line_length": 148, "max_stars_count": null, "max_stars_repo_head_hexsha": "ea47bd485e7b6be11e8481eff8fd2e7826fb1ef5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Senseirn/tino", "max_stars_repo_path": "tino/backends/blas/blas_wrappers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 657, "size": 2624 }
/* multifit_nlinear/fdf.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * Copyright (C) 2015, 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit_nlinear.h> gsl_multifit_nlinear_workspace * gsl_multifit_nlinear_alloc (const gsl_multifit_nlinear_type * T, const gsl_multifit_nlinear_parameters * params, const size_t n, const size_t p) { gsl_multifit_nlinear_workspace * w; if (n < p) { GSL_ERROR_VAL ("insufficient data points, n < p", GSL_EINVAL, 0); } w = calloc (1, sizeof (gsl_multifit_nlinear_workspace)); if (w == 0) { GSL_ERROR_VAL ("failed to allocate space for multifit workspace", GSL_ENOMEM, 0); } w->x = gsl_vector_calloc (p); if (w->x == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0); } w->f = gsl_vector_calloc (n); if (w->f == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0); } w->dx = gsl_vector_calloc (p); if (w->dx == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0); } w->g = gsl_vector_alloc (p); if (w->g == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for g", GSL_ENOMEM, 0); } w->J = gsl_matrix_alloc(n, p); if (w->J == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for Jacobian", GSL_ENOMEM, 0); } w->sqrt_wts_work = gsl_vector_calloc (n); if (w->sqrt_wts_work == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for weights", GSL_ENOMEM, 0); } w->state = (T->alloc)(params, n, p); if (w->state == 0) { gsl_multifit_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for multifit state", GSL_ENOMEM, 0); } w->type = T; w->fdf = NULL; w->niter = 0; w->params = *params; return w; } void gsl_multifit_nlinear_free (gsl_multifit_nlinear_workspace * w) { RETURN_IF_NULL (w); if (w->state) (w->type->free) (w->state); if (w->dx) gsl_vector_free (w->dx); if (w->x) gsl_vector_free (w->x); if (w->f) gsl_vector_free (w->f); if (w->sqrt_wts_work) gsl_vector_free (w->sqrt_wts_work); if (w->g) gsl_vector_free (w->g); if (w->J) gsl_matrix_free (w->J); free (w); } gsl_multifit_nlinear_parameters gsl_multifit_nlinear_default_parameters(void) { gsl_multifit_nlinear_parameters params; params.trs = gsl_multifit_nlinear_trs_lm; params.scale = gsl_multifit_nlinear_scale_more; params.solver = gsl_multifit_nlinear_solver_qr; params.fdtype = GSL_MULTIFIT_NLINEAR_FWDIFF; params.factor_up = 3.0; params.factor_down = 2.0; params.avmax = 0.75; params.h_df = GSL_SQRT_DBL_EPSILON; params.h_fvv = 0.02; return params; } int gsl_multifit_nlinear_init (const gsl_vector * x, gsl_multifit_nlinear_fdf * fdf, gsl_multifit_nlinear_workspace * w) { return gsl_multifit_nlinear_winit(x, NULL, fdf, w); } int gsl_multifit_nlinear_winit (const gsl_vector * x, const gsl_vector * wts, gsl_multifit_nlinear_fdf * fdf, gsl_multifit_nlinear_workspace * w) { const size_t n = w->f->size; if (n != fdf->n) { GSL_ERROR ("function size does not match workspace", GSL_EBADLEN); } else if (w->x->size != x->size) { GSL_ERROR ("vector length does not match workspace", GSL_EBADLEN); } else if (wts != NULL && n != wts->size) { GSL_ERROR ("weight vector length does not match workspace", GSL_EBADLEN); } else { size_t i; /* initialize counters for function and Jacobian evaluations */ fdf->nevalf = 0; fdf->nevaldf = 0; fdf->nevalfvv = 0; w->fdf = fdf; gsl_vector_memcpy(w->x, x); w->niter = 0; if (wts) { w->sqrt_wts = w->sqrt_wts_work; for (i = 0; i < n; ++i) { double wi = gsl_vector_get(wts, i); gsl_vector_set(w->sqrt_wts, i, sqrt(wi)); } } else { w->sqrt_wts = NULL; } return (w->type->init) (w->state, w->sqrt_wts, w->fdf, w->x, w->f, w->J, w->g); } } int gsl_multifit_nlinear_iterate (gsl_multifit_nlinear_workspace * w) { int status = (w->type->iterate) (w->state, w->sqrt_wts, w->fdf, w->x, w->f, w->J, w->g, w->dx); w->niter++; return status; } double gsl_multifit_nlinear_avratio (const gsl_multifit_nlinear_workspace * w) { return (w->type->avratio) (w->state); } /* gsl_multifit_nlinear_driver() Iterate the nonlinear least squares solver until completion Inputs: maxiter - maximum iterations to allow xtol - tolerance in step x gtol - tolerance in gradient ftol - tolerance in ||f|| callback - callback function to call each iteration callback_params - parameters to pass to callback function info - (output) info flag on why iteration terminated 1 = stopped due to small step size ||dx| 2 = stopped due to small gradient 3 = stopped due to small change in f GSL_ETOLX = ||dx|| has converged to within machine precision (and xtol is too small) GSL_ETOLG = ||g||_inf is smaller than machine precision (gtol is too small) GSL_ETOLF = change in ||f|| is smaller than machine precision (ftol is too small) w - workspace Return: GSL_SUCCESS if converged GSL_MAXITER if maxiter exceeded without converging GSL_ENOPROG if no accepted step found on first iteration */ int gsl_multifit_nlinear_driver (const size_t maxiter, const double xtol, const double gtol, const double ftol, void (*callback)(const size_t iter, void *params, const gsl_multifit_nlinear_workspace *w), void *callback_params, int *info, gsl_multifit_nlinear_workspace * w) { int status; size_t iter = 0; /* call user callback function prior to any iterations * with initial system state */ if (callback) callback(iter, callback_params, w); do { status = gsl_multifit_nlinear_iterate (w); /* * If the solver reports no progress on the first iteration, * then it didn't find a single step to reduce the * cost function and more iterations won't help so return. * * If we get a no progress flag on subsequent iterations, * it means we did find a good step in a previous iteration, * so continue iterating since the solver has now reset * mu to its initial value. */ if (status == GSL_ENOPROG && iter == 0) { *info = status; return GSL_EMAXITER; } ++iter; if (callback) callback(iter, callback_params, w); /* test for convergence */ status = gsl_multifit_nlinear_test(xtol, gtol, ftol, info, w); } while (status == GSL_CONTINUE && iter < maxiter); /* * the following error codes mean that the solution has converged * to within machine precision, so record the error code in info * and return success */ if (status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG) { *info = status; status = GSL_SUCCESS; } /* check if max iterations reached */ if (iter >= maxiter && status != GSL_SUCCESS) status = GSL_EMAXITER; return status; } /* gsl_multifit_nlinear_driver() */ gsl_matrix * gsl_multifit_nlinear_jac (const gsl_multifit_nlinear_workspace * w) { return w->J; } const char * gsl_multifit_nlinear_name (const gsl_multifit_nlinear_workspace * w) { return w->type->name; } gsl_vector * gsl_multifit_nlinear_position (const gsl_multifit_nlinear_workspace * w) { return w->x; } gsl_vector * gsl_multifit_nlinear_residual (const gsl_multifit_nlinear_workspace * w) { return w->f; } size_t gsl_multifit_nlinear_niter (const gsl_multifit_nlinear_workspace * w) { return w->niter; } int gsl_multifit_nlinear_rcond (double *rcond, const gsl_multifit_nlinear_workspace * w) { int status = (w->type->rcond) (rcond, w->state); return status; } const char * gsl_multifit_nlinear_trs_name (const gsl_multifit_nlinear_workspace * w) { return w->params.trs->name; } /* gsl_multifit_nlinear_eval_f() Compute residual vector y with user callback function, and apply weighting transform if given: y~ = sqrt(W) y Inputs: fdf - callback function x - model parameters swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn)) set to NULL for unweighted fit y - (output) (weighted) residual vector y_i = sqrt(w_i) f_i where f_i is unweighted residual */ int gsl_multifit_nlinear_eval_f(gsl_multifit_nlinear_fdf *fdf, const gsl_vector *x, const gsl_vector *swts, gsl_vector *y) { int s = ((*((fdf)->f)) (x, fdf->params, y)); ++(fdf->nevalf); /* y <- sqrt(W) y */ if (swts) gsl_vector_mul(y, swts); return s; } /* gsl_multifit_nlinear_eval_df() Compute Jacobian matrix J with user callback function, and apply weighting transform if given: J~ = sqrt(W) J Inputs: x - model parameters f - residual vector f(x) swts - weight matrix W = diag(w1,w2,...,wn) set to NULL for unweighted fit h - finite difference step size fdtype - finite difference method fdf - callback function df - (output) (weighted) Jacobian matrix df = sqrt(W) df where df is unweighted Jacobian work - workspace for finite difference, size n */ int gsl_multifit_nlinear_eval_df(const gsl_vector *x, const gsl_vector *f, const gsl_vector *swts, const double h, const gsl_multifit_nlinear_fdtype fdtype, gsl_multifit_nlinear_fdf *fdf, gsl_matrix *df, gsl_vector *work) { int status; if (fdf->df) { /* call user-supplied function */ status = ((*((fdf)->df)) (x, fdf->params, df)); ++(fdf->nevaldf); /* J <- sqrt(W) J */ if (swts) { const size_t n = swts->size; size_t i; for (i = 0; i < n; ++i) { double swi = gsl_vector_get(swts, i); gsl_vector_view v = gsl_matrix_row(df, i); gsl_vector_scale(&v.vector, swi); } } } else { /* use finite difference Jacobian approximation */ status = gsl_multifit_nlinear_df(h, fdtype, x, swts, fdf, f, df, work); } return status; } /* gsl_multifit_nlinear_eval_fvv() Compute second direction derivative vector yvv with user callback function, and apply weighting transform if given: yvv~ = sqrt(W) yvv Inputs: h - step size for finite difference, if needed x - model parameters, size p v - unscaled geodesic velocity vector, size p f - residual vector f(x), size n J - Jacobian matrix J(x), n-by-p swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn)) set to NULL for unweighted fit fdf - callback function yvv - (output) (weighted) second directional derivative vector yvv_i = sqrt(w_i) fvv_i where f_i is unweighted work - workspace, size p */ int gsl_multifit_nlinear_eval_fvv(const double h, const gsl_vector *x, const gsl_vector *v, const gsl_vector *f, const gsl_matrix *J, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, gsl_vector *yvv, gsl_vector *work) { int status; if (fdf->fvv != NULL) { /* call user-supplied function */ status = ((*((fdf)->fvv)) (x, v, fdf->params, yvv)); ++(fdf->nevalfvv); /* yvv <- sqrt(W) yvv */ if (swts) gsl_vector_mul(yvv, swts); } else { /* use finite difference approximation */ status = gsl_multifit_nlinear_fdfvv(h, x, v, f, J, swts, fdf, yvv, work); } return status; }
{ "alphanum_fraction": 0.5884461009, "avg_line_length": 27.25, "ext": "c", "hexsha": "fc0c1134b1e440e6d66d3f4711014dee62400cef", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdf.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdf.c", "max_line_length": 87, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/fdf.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": 3737, "size": 13952 }
#pragma once #include <gsl/span> #include <array> #include "halley/core/api/audio_api.h" namespace Halley { class AudioSource { public: virtual ~AudioSource() {} virtual uint8_t getNumberOfChannels() const = 0; virtual size_t getSamplesLeft() const = 0; virtual bool isReady() const { return true; } virtual bool getAudioData(size_t numSamples, AudioMultiChannelSamples dst) = 0; }; }
{ "alphanum_fraction": 0.7306733167, "avg_line_length": 21.1052631579, "ext": "h", "hexsha": "cc09a0588dcdf29104ebe2acde8d3b0574599edb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/engine/audio/include/halley/audio/audio_source.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 103, "size": 401 }
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <php.h> #include <cblas.h> #include <lapacke.h> #include "php_ext.h" #include "kernel/operators.h" void tensor_matmul(zval * return_value, zval * a, zval * b) { unsigned int i, j; Bucket * row; zval rowC, c; zend_zephir_globals_def * zephir_globals = ZEPHIR_VGLOBAL; openblas_set_num_threads(zephir_globals->num_threads); zend_array * aHat = Z_ARR_P(a); zend_array * bHat = Z_ARR_P(b); Bucket * ba = aHat->arData; Bucket * bb = bHat->arData; unsigned int m = zend_array_count(aHat); unsigned int p = zend_array_count(bHat); unsigned int n = zend_array_count(Z_ARR(bb[0].val)); double * va = emalloc(m * p * sizeof(double)); double * vb = emalloc(n * p * sizeof(double)); double * vc = emalloc(m * n * sizeof(double)); for (i = 0; i < m; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < p; ++j) { va[i * p + j] = zephir_get_doubleval(&row[j].val); } } for (i = 0; i < p; ++i) { row = Z_ARR(bb[i].val)->arData; for (j = 0; j < n; ++j) { vb[i * n + j] = zephir_get_doubleval(&row[j].val); } } cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, p, 1.0, va, p, vb, n, 0.0, vc, n); array_init_size(&c, m); for (i = 0; i < m; ++i) { array_init_size(&rowC, n); for (j = 0; j < n; ++j) { add_next_index_double(&rowC, vc[i * n + j]); } add_next_index_zval(&c, &rowC); } RETVAL_ARR(Z_ARR(c)); efree(va); efree(vb); efree(vc); } void tensor_dot(zval * return_value, zval * a, zval * b) { unsigned int i; zend_array * aHat = Z_ARR_P(a); zend_array * bHat = Z_ARR_P(b); Bucket * ba = aHat->arData; Bucket * bb = bHat->arData; unsigned int n = zend_array_count(aHat); double sigma = 0.0; for (i = 0; i < n; ++i) { sigma += zephir_get_doubleval(&ba[i].val) * zephir_get_doubleval(&bb[i].val); } RETVAL_DOUBLE(sigma); } void tensor_inverse(zval * return_value, zval * a) { unsigned int i, j; Bucket * row; zval rowB, b; zend_zephir_globals_def * zephir_globals = ZEPHIR_VGLOBAL; openblas_set_num_threads(zephir_globals->num_threads); zend_array * aHat = Z_ARR_P(a); Bucket * ba = aHat->arData; unsigned int n = zend_array_count(aHat); double * va = emalloc(n * n * sizeof(double)); for (i = 0; i < n; ++i) { row = Z_ARR(ba[i].val)->arData; for (j = 0; j < n; ++j) { va[i * n + j] = zephir_get_doubleval(&row[j].val); } } lapack_int status; int pivots[n]; status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } status = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, va, n, pivots); if (status != 0) { RETURN_NULL(); } array_init_size(&b, n); for (i = 0; i < n; ++i) { array_init_size(&rowB, n); for (j = 0; j < n; ++j) { add_next_index_double(&rowB, va[i * n + j]); } add_next_index_zval(&b, &rowB); } RETVAL_ARR(Z_ARR(b)); efree(va); }
{ "alphanum_fraction": 0.5519580635, "avg_line_length": 21.3355263158, "ext": "c", "hexsha": "53c62228a83df7cfa4b4272508a82e0f645b667b", "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": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "remicollet/Tensor", "max_forks_repo_path": "ext/include/linear_algebra.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "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": "remicollet/Tensor", "max_issues_repo_path": "ext/include/linear_algebra.c", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "remicollet/Tensor", "max_stars_repo_path": "ext/include/linear_algebra.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1050, "size": 3243 }
#pragma once /* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \defgroup ioda_cxx_layout Groups and Data Layout * \brief Public API for ioda::Group, ioda::ObsGroup, and data layout policies. * \ingroup ioda_cxx_api * * @{ * \file Group.h * \brief Interfaces for ioda::Group and related classes. */ #include <gsl/gsl-lite.hpp> #include <map> #include <memory> #include <string> #include <vector> #include "ioda/Attributes/Has_Attributes.h" #include "ioda/Types/Has_Types.h" #include "ioda/Variables/FillPolicy.h" #include "ioda/Variables/Has_Variables.h" #include "ioda/defs.h" namespace ioda { class Group; namespace Engines { struct Capabilities; } // namespace Engines namespace detail { class Group_Base; class Group_Backend; /// \brief Hidden base class to prevent constructor confusion. /// \ingroup ioda_cxx_layout /// \note enable_shared_from_this is a hint to pybind11. class IODA_DL Group_Base { std::shared_ptr<Group_Backend> backend_; protected: Group_Base(std::shared_ptr<Group_Backend>); public: virtual ~Group_Base(); std::shared_ptr<Group_Backend> getBackend() const { return backend_; } /// Get capabilities of the Engine backing this Group virtual ::ioda::Engines::Capabilities getCapabilities() const; /// \brief Get the fill value policy used for Variables within this Group /// \details The backend has to be consulted for this operation. Storage of this policy is /// backend-dependent. virtual FillValuePolicy getFillValuePolicy() const; /// \brief List all one-level child groups in this group /// \details This function exists to provide the same calling semantics as /// vars.list() and atts.list(). It is useful for human exploration of the contents /// of a Group. /// \returns A vector of strings listing the child groups. The strings are unordered. /// \see listObjects if you need to enumerate both Groups and Variables, or /// if you want to do a recursive search. This function is more sophisticated, and /// depending on the backend it may be faster than recursive calls to /// list() and vars.list(). std::vector<std::string> list() const; /// Same as list(). Uniform semantics with atts() and vars(). inline std::vector<std::string> groups() const { return list(); } /// \brief List all objects (groups + variables) within this group /// \param recurse indicates whether the search should be one-level or recursive. If /// multiple possible paths exist for an object, only one is actually returned. /// \param filter allows you to search for only a certain type of object, such as a /// Group or Variable. /// \returns a map of ObjectTypes. Each mapping contains a vector of strings indicating /// object names. If a filter is provided, then this map only contains the filtered /// object type. Otherwise, the map always has vectors for each element of ObjectType /// (Group, Variable, etc.), although these vectors may be empty if no object of a /// certain type is found. /// \todo This function should list all *distinct* objects. In the future, this will mean /// that 1) hard-linked duplicate objects will only be listed once, 2) soft /// links pointing to the same object will only be traversed once, and /// 3) multiple external links to the same object will only be traversed once. /// If you would want to list *indistinct* objects, then there will be a /// listLinks function. /// \todo Once links are implemented, add an option to auto-resolve /// soft and external links. virtual std::map<ObjectType, std::vector<std::string>> listObjects(ObjectType filter = ObjectType::Ignored, bool recurse = false) const; template <ObjectType objectClass> std::vector<std::string> listObjects(bool recurse = false) const { return listObjects(objectClass, recurse)[objectClass]; } /// Does a group exist at the specified path? /// \param name is the group name. /// \returns true if a group does exist. /// \return false if a group does not exist. virtual bool exists(const std::string& name) const; /// \brief Create a group /// \param name is the group name. /// \returns an invalid handle on failure. (i.e. return.isGroup() == false). /// \returns a scoped handle to the group on success. virtual Group create(const std::string& name); /// \brief Open a group /// \returns an invalid handle if an error occurred. (i.e. return.isGroup() == false). /// \returns a scoped handle to the group upon success. /// \note It is possible to have multiple handles opened for the group /// simultaneously. /// \param name is the name of the child group to open. virtual Group open(const std::string& name) const; /// Use this to access the metadata for the group / ObsSpace. Has_Attributes atts; /// Use this to access named data types. Has_Types types; /// Use this to access variables Has_Variables vars; }; class IODA_DL Group_Backend : public Group_Base { public: virtual ~Group_Backend(); /// Default fill value policy is NETCDF4. Overridable on a per-backend basis. FillValuePolicy getFillValuePolicy() const override; /// @} protected: Group_Backend(); }; } // namespace detail /** \brief Groups are a new implementation of ObsSpaces. * \ingroup ioda_cxx_layout * * \see \ref Groups for a examples. * * A group can be thought of as a folder that contains Variables and Metadata. * A group can also contain child groups, allowing for our ObsSpaces to exist in a * nested tree-like structure, which removes the need for having an ObsSpaceContainer. * * Groups are implemented in several backends, such as the in-memory IODA store, the HDF5 disk * backend, the HDF5 in-memory backend, the ATLAS backend, et cetera. The root Group is mounted * using one of these backends (probably as a File object, which is a special type of Group), * and additional backends may be mounted into the tree structure. * * \throws std::logic_error if the backend handle points to something other than a group. * \throws std::logic_error if the backend handle is invalid. * \throws std::logic_error if any error has occurred. * \author Ryan Honeyager (honeyage@ucar.edu) **/ class IODA_DL Group : public detail::Group_Base { public: Group(); Group(std::shared_ptr<detail::Group_Backend>); virtual ~Group(); }; } // namespace ioda /// @}
{ "alphanum_fraction": 0.7047191011, "avg_line_length": 38.1428571429, "ext": "h", "hexsha": "e93aec95a372e6208f3101e321ff85c7f1b396ad", "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": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "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": "NOAA-EMC/ioda", "max_issues_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_path": "src/engines/ioda/include/ioda/Group.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1586, "size": 6675 }
#pragma once #include <gsl\gsl> #include <winrt\base.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "DynamicLODMaterial.h" #include "MatrixHelper.h" namespace Rendering { class DynamicLODDemo final : public Library::DrawableGameComponent { public: DynamicLODDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); DynamicLODDemo(const DynamicLODDemo&) = delete; DynamicLODDemo(DynamicLODDemo&&) = default; DynamicLODDemo& operator=(const DynamicLODDemo&) = default; DynamicLODDemo& operator=(DynamicLODDemo&&) = default; ~DynamicLODDemo(); int MaxTessellationFactor() const; void SetMaxTessellationFactor(int maxTessellationFactor); DirectX::XMFLOAT2 TessellationDistances() const; void SetTessellationDistances(DirectX::XMFLOAT2 tessellationDistances); void SetTessellationDistances(float minTessellationDistance, float maxTessellationDistance); virtual void Initialize() override; virtual void Draw(const Library::GameTime& gameTime) override; private: DynamicLODMaterial mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::size_t mIndexCount{ 0 }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7820710974, "avg_line_length": 32.35, "ext": "h", "hexsha": "5f3d8402df4e6ad09ed5d5837c3adcabe772fe5e", "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/10.4_Dynamic_LOD/DynamicLODDemo.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/10.4_Dynamic_LOD/DynamicLODDemo.h", "max_line_length": 94, "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/10.4_Dynamic_LOD/DynamicLODDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 359, "size": 1294 }
/* filter/test.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_test.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_filter.h> /* compare two vectors */ static void compare_vectors(const double tol, const gsl_vector * v, const gsl_vector * expected, const char * desc) { const size_t n = v->size; size_t i; for (i = 0; i < n; ++i) { double vi = gsl_vector_get(v, i); double ui = gsl_vector_get(expected, i); gsl_test_rel(vi, ui, tol, "%s i=%zu", desc, i); } } /* generate random vector with elements in [-1,1] */ static void random_vector(gsl_vector * v, gsl_rng * r) { size_t i; for (i = 0; i < v->size; ++i) { double vi = 2.0 * gsl_rng_uniform(r) - 1.0; /* in [-1,1] */ gsl_vector_set(v, i, vi); } } #include "test_impulse.c" #include "test_gaussian.c" #include "test_median.c" #include "test_rmedian.c" int main() { gsl_rng * r = gsl_rng_alloc(gsl_rng_default); test_gaussian(r); test_impulse(r); test_median(r); test_rmedian(r); gsl_rng_free(r); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.6769911504, "avg_line_length": 24.5060240964, "ext": "c", "hexsha": "2318e02905dd508bf69d818ffb6d3e5999e271dc", "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/filter/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/filter/test.c", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/filter/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": 570, "size": 2034 }
/** @file */ #ifndef __CCL_NEUTRINOS_H_INCLUDED__ #define __CCL_NEUTRINOS_H_INCLUDED__ #include <gsl/gsl_spline.h> #include <gsl/gsl_const_mksa.h> // maximum number of species #define CCL_MAX_NU_SPECIES 3 // limits for the precomputed spline of phase // space diagram in MNU/T #define CCL_NU_MNUT_MIN 1e-4 #define CCL_NU_MNUT_MAX 500 // and number of points #define CCL_NU_MNUT_N 1000 // The combination of constants required in Omeganuh2 #define NU_CONST ( \ 8. * pow(M_PI,5) *pow((ccl_constants.KBOLTZ/ ccl_constants.HPLANCK),3)* \ ccl_constants.KBOLTZ/(15. *pow( ccl_constants.CLIGHT,3))* \ (8. * M_PI * ccl_constants.GNEWT) / \ (3. * 100.*100.*1000.*1000. /ccl_constants.MPC_TO_METER /ccl_constants.MPC_TO_METER * ccl_constants.CLIGHT * ccl_constants.CLIGHT)) CCL_BEGIN_DECLS typedef enum ccl_neutrino_mass_splits{ ccl_nu_normal=0, ccl_nu_inverted=1, ccl_nu_equal=2, ccl_nu_sum=3, ccl_nu_single=4 } ccl_neutrino_mass_splits; /** * Returns density of one neutrino species at a scale factor a. * Users are encouraged to access this quantity via the function ccl_omega_x. * @param a Scale factor * @param Neff The effective number of species with neutrino mass mnu. * @param mnu Pointer to array containing neutrino mass (can be 0). * @param T_CMB Temperature of the CMB * @param status Status flag. 0 if there are no errors, nonzero otherwise. * For specific cases see documentation for ccl_error.c * @return OmNuh2 Fractional energy density of neutrions with mass mnu, multiplied by h squared. */ double ccl_Omeganuh2(double a, int N_nu_mass, double* mnu, double T_CMB, int * status); /** * Returns mass of one neutrino species at a scale factor a. * @param a Scale factor * @param Neff The effective number of species with neutrino mass mnu. * @param OmNuh2 Fractional energy density of neutrions with mass mnu, multiplied by h squared. (can be 0). * @param T_CMB Temperature of the CMB * @param status Status flag. 0 if there are no errors, nonzero otherwise. * For specific cases see documentation for ccl_error.c * @return Mnu Neutrino mass [eV]. */ double* ccl_nu_masses(double OmNuh2, ccl_neutrino_mass_splits mass_split, double T_CMB, int * status); CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7602155366, "avg_line_length": 36.5081967213, "ext": "h", "hexsha": "a1594a9d5c73c243e0152757bab88eb55656ce85", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "include/ccl_neutrinos.h", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "include/ccl_neutrinos.h", "max_line_length": 134, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "include/ccl_neutrinos.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 675, "size": 2227 }
/* roots/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, 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_test.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_ieee_utils.h> #include "roots.h" #include "test.h" /* stopping parameters */ const double EPSREL = (10 * GSL_DBL_EPSILON); const double EPSABS = (10 * GSL_DBL_EPSILON); const unsigned int MAX_ITERATIONS = 150; void my_error_handler (const char *reason, const char *file, int line, int err); #define WITHIN_TOL(a, b, epsrel, epsabs) \ ((fabs((a) - (b)) < (epsrel) * GSL_MIN(fabs(a), fabs(b)) + (epsabs))) int main (void) { gsl_function F_sin, F_cos, F_func1, F_func2, F_func3, F_func4, F_func5, F_func6; gsl_function_fdf FDF_sin, FDF_cos, FDF_func1, FDF_func2, FDF_func3, FDF_func4, FDF_func5, FDF_func6; const gsl_root_fsolver_type * fsolver[4] ; const gsl_root_fdfsolver_type * fdfsolver[4] ; const gsl_root_fsolver_type ** T; const gsl_root_fdfsolver_type ** S; gsl_ieee_env_setup(); fsolver[0] = gsl_root_fsolver_bisection; fsolver[1] = gsl_root_fsolver_brent; fsolver[2] = gsl_root_fsolver_falsepos; fsolver[3] = 0; fdfsolver[0] = gsl_root_fdfsolver_newton; fdfsolver[1] = gsl_root_fdfsolver_secant; fdfsolver[2] = gsl_root_fdfsolver_steffenson; fdfsolver[3] = 0; F_sin = create_function (sin_f) ; F_cos = create_function (cos_f) ; F_func1 = create_function (func1) ; F_func2 = create_function (func2) ; F_func3 = create_function (func3) ; F_func4 = create_function (func4) ; F_func5 = create_function (func5) ; F_func6 = create_function (func6) ; FDF_sin = create_fdf (sin_f, sin_df, sin_fdf) ; FDF_cos = create_fdf (cos_f, cos_df, cos_fdf) ; FDF_func1 = create_fdf (func1, func1_df, func1_fdf) ; FDF_func2 = create_fdf (func2, func2_df, func2_fdf) ; FDF_func3 = create_fdf (func3, func3_df, func3_fdf) ; FDF_func4 = create_fdf (func4, func4_df, func4_fdf) ; FDF_func5 = create_fdf (func5, func5_df, func5_fdf) ; FDF_func6 = create_fdf (func6, func6_df, func6_fdf) ; gsl_set_error_handler (&my_error_handler); for (T = fsolver ; *T != 0 ; T++) { test_f (*T, "sin(x) [3, 4]", &F_sin, 3.0, 4.0, M_PI); test_f (*T, "sin(x) [-4, -3]", &F_sin, -4.0, -3.0, -M_PI); test_f (*T, "sin(x) [-1/3, 1]", &F_sin, -1.0 / 3.0, 1.0, 0.0); test_f (*T, "cos(x) [0, 3]", &F_cos, 0.0, 3.0, M_PI / 2.0); test_f (*T, "cos(x) [-3, 0]", &F_cos, -3.0, 0.0, -M_PI / 2.0); test_f (*T, "x^20 - 1 [0.1, 2]", &F_func1, 0.1, 2.0, 1.0); test_f (*T, "sqrt(|x|)*sgn(x)", &F_func2, -1.0 / 3.0, 1.0, 0.0); test_f (*T, "x^2 - 1e-8 [0, 1]", &F_func3, 0.0, 1.0, sqrt (1e-8)); test_f (*T, "x exp(-x) [-1/3, 2]", &F_func4, -1.0 / 3.0, 2.0, 0.0); test_f (*T, "(x - 1)^7 [0.9995, 1.0002]", &F_func6, 0.9995, 1.0002, 1.0); test_f_e (*T, "invalid range check [4, 0]", &F_sin, 4.0, 0.0, M_PI); test_f_e (*T, "invalid range check [1, 1]", &F_sin, 1.0, 1.0, M_PI); test_f_e (*T, "invalid range check [0.1, 0.2]", &F_sin, 0.1, 0.2, M_PI); } for (S = fdfsolver ; *S != 0 ; S++) { test_fdf (*S,"sin(x) {3.4}", &FDF_sin, 3.4, M_PI); test_fdf (*S,"sin(x) {-3.3}", &FDF_sin, -3.3, -M_PI); test_fdf (*S,"sin(x) {0.5}", &FDF_sin, 0.5, 0.0); test_fdf (*S,"cos(x) {0.6}", &FDF_cos, 0.6, M_PI / 2.0); test_fdf (*S,"cos(x) {-2.5}", &FDF_cos, -2.5, -M_PI / 2.0); test_fdf (*S,"x^{20} - 1 {0.9}", &FDF_func1, 0.9, 1.0); test_fdf (*S,"x^{20} - 1 {1.1}", &FDF_func1, 1.1, 1.0); test_fdf (*S,"sqrt(|x|)*sgn(x) {1.001}", &FDF_func2, 0.001, 0.0); test_fdf (*S,"x^2 - 1e-8 {1}", &FDF_func3, 1.0, sqrt (1e-8)); test_fdf (*S,"x exp(-x) {-2}", &FDF_func4, -2.0, 0.0); test_fdf_e (*S,"max iterations x -> +Inf, x exp(-x) {2}", &FDF_func4, 2.0, 0.0); test_fdf_e (*S,"max iterations x -> -Inf, 1/(1 + exp(-x)) {0}", &FDF_func5, 0.0, 0.0); } test_fdf (gsl_root_fdfsolver_steffenson, "(x - 1)^7 {0.9}", &FDF_func6, 0.9, 1.0); /* now summarize the results */ exit (gsl_test_summary ()); } /* Using gsl_root_bisection, find the root of the function pointed to by f, using the interval [lower_bound, upper_bound]. Check if f succeeded and that it was accurate enough. */ void test_f (const gsl_root_fsolver_type * T, const char * description, gsl_function *f, double lower_bound, double upper_bound, double correct_root) { int status; size_t iterations = 0; double r, a, b; double x_lower, x_upper; gsl_root_fsolver * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s, f, x_lower, x_upper) ; do { iterations++ ; gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root(s); a = gsl_root_fsolver_x_lower(s); b = gsl_root_fsolver_x_upper(s); if (a > b) gsl_test (GSL_FAILURE, "interval is invalid (%g,%g)", a, b); if (r < a || r > b) gsl_test (GSL_FAILURE, "r lies outside interval %g (%g,%g)", r, a, b); status = gsl_root_test_interval (a,b, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (status, "%s, %s (%g obs vs %g expected) ", gsl_root_fsolver_name(s), description, gsl_root_fsolver_root(s), correct_root); if (iterations == MAX_ITERATIONS) { gsl_test (GSL_FAILURE, "exceeded maximum number of iterations"); } /* check the validity of the returned result */ if (!WITHIN_TOL (r, correct_root, EPSREL, EPSABS)) { gsl_test (GSL_FAILURE, "incorrect precision (%g obs vs %g expected)", r, correct_root); } gsl_root_fsolver_free(s); } void test_f_e (const gsl_root_fsolver_type * T, const char * description, gsl_function *f, double lower_bound, double upper_bound, double correct_root) { int status; size_t iterations = 0; double x_lower, x_upper; gsl_root_fsolver * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_root_fsolver_alloc(T); status = gsl_root_fsolver_set(s, f, x_lower, x_upper) ; gsl_test (status != GSL_EINVAL, "%s (set), %s", T->name, description); if (status == GSL_EINVAL) { gsl_root_fsolver_free(s); return ; } do { iterations++ ; gsl_root_fsolver_iterate (s); x_lower = gsl_root_fsolver_x_lower(s); x_upper = gsl_root_fsolver_x_lower(s); status = gsl_root_test_interval (x_lower, x_upper, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (!status, "%s, %s", gsl_root_fsolver_name(s), description, gsl_root_fsolver_root(s) - correct_root); gsl_root_fsolver_free(s); } void test_fdf (const gsl_root_fdfsolver_type * T, const char * description, gsl_function_fdf *fdf, double root, double correct_root) { int status; size_t iterations = 0; double prev = 0 ; gsl_root_fdfsolver * s = gsl_root_fdfsolver_alloc(T); gsl_root_fdfsolver_set (s, fdf, root) ; do { iterations++ ; prev = gsl_root_fdfsolver_root(s); gsl_root_fdfsolver_iterate (s); status = gsl_root_test_delta(gsl_root_fdfsolver_root(s), prev, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (status, "%s, %s (%g obs vs %g expected) ", gsl_root_fdfsolver_name(s), description, gsl_root_fdfsolver_root(s), correct_root); if (iterations == MAX_ITERATIONS) { gsl_test (GSL_FAILURE, "exceeded maximum number of iterations"); } /* check the validity of the returned result */ if (!WITHIN_TOL (gsl_root_fdfsolver_root(s), correct_root, EPSREL, EPSABS)) { gsl_test (GSL_FAILURE, "incorrect precision (%g obs vs %g expected)", gsl_root_fdfsolver_root(s), correct_root); } gsl_root_fdfsolver_free(s); } void test_fdf_e (const gsl_root_fdfsolver_type * T, const char * description, gsl_function_fdf *fdf, double root, double correct_root) { int status; size_t iterations = 0; double prev = 0 ; gsl_root_fdfsolver * s = gsl_root_fdfsolver_alloc(T); status = gsl_root_fdfsolver_set (s, fdf, root) ; gsl_test (status, "%s (set), %s", T->name, description); do { iterations++ ; prev = gsl_root_fdfsolver_root(s); gsl_root_fdfsolver_iterate (s); status = gsl_root_test_delta(gsl_root_fdfsolver_root(s), prev, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (!status, "%s, %s", gsl_root_fdfsolver_name(s), description, gsl_root_fdfsolver_root(s) - correct_root); gsl_root_fdfsolver_free(s); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err); }
{ "alphanum_fraction": 0.6286838918, "avg_line_length": 31.3544303797, "ext": "c", "hexsha": "2651d225f7a0701e1f3362b41873c083b9bc9a6e", "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/roots/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/roots/test.c", "max_line_length": 92, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/roots/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": 3298, "size": 9908 }
// A cascade of IntegralHOGDetectors. // // Copyright 2012 Mark Desnoyer (mdesnoyer@gmail.com) #ifndef __HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__ #define __HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__ #include <ros/ros.h> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <functional> #include <vector> #include <string> #include <queue> #include <limits> #include <cmath> #include <opencv2/core/core.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include <gsl/gsl_multimin.h> #include "hog_detector/integral_hog_cascade.h" #include "hog_detector/integral_hog_detector.h" #include "hog_detector/interpolation.h" namespace hog_detector { // Class to calculate the various time components of the cascade class IntegralCascadeTimeCalculator { public: // Creates the calculator based on text files with timing data (in seconds) // // integralHistTime - single line with the time // fillBlockCacheTime - lines of <blockW>,<blockH>,<time> // svmEvalTime - lines of <descriptorSize>,<subWinW>,<subWinH>,<time/window> // trueHogTime - lines of <nWindows>,<time> IntegralCascadeTimeCalculator(const std::string& integralHistTime, const std::string& fillBlockCacheTime, const std::string& svmEvalTime, const std::string& trueHogTime); // Time to compute the integral histogram double GetIntegralHistTime() const { return integralHistTime_; } // Time to fill the block cache for a given block size double GetFillCacheTime(const cv::Size& blockSize) const; // Time to do the svm evaluation of a single window double GetSVMEvalTime(int descriptorSize) const; // Time to compute the full HOG detector on N windows double GetTrueHogTime(int nWindows) const; int GetMaxWindows() const { return maxWindows_; } double GetMaxHogTime() const { return GetTrueHogTime(GetMaxWindows()); } private: double integralHistTime_; boost::unordered_map<cv::Size, double> cacheFillTime_; boost::scoped_ptr<Interpolator> svmTime_; boost::scoped_ptr<Interpolator> trueHogTime_; int maxWindows_; }; class IntegralHogCascadeTrainer { public: // Constructor // // timeCalculator - takes ownership of it IntegralHogCascadeTrainer(IntegralCascadeTimeCalculator* timeCalculator, const cv::Size& winSize); // Add a candidate IntegralHogDetector. void AddCandidateDetector(IntegralHogDetector::Ptr detector) { if (detector->winSize() == winSize_) { detectorIdx_[detector.get()] = detectors_.size(); detectors_.push_back(detector); } else { ROS_WARN_STREAM("The detector has the wrong window size: (" << winSize_.width << "," << winSize_.height << ") vs. (" << detector->winSize().width << "," << detector->winSize().height << ")"); } } // Trains the cascade detector // // Inputs: // filenames - Filenames of images to train with. Uses the center // winSize window in the image. // labels - Labels for all the images. 1 is positive, -1 is negative // budget - Processing budget in seconds (average per/frame) // missCost - The cost of a miss // falsePosCost - The cost of a false positive // fracNegSampled - fraction of the number of negative examples we're // actually training with. So the number of negative // samples seen by this class is trueNegs/fracNegSampled void Train(const std::vector<std::string>& filenames, const std::vector<float>& labels, float budget, float missCost, float falsePosCost); // Train using the supermodular-submodular approach void TrainSupSub(const std::vector<std::string>& filenames, const std::vector<float>& label, float missCost, float falsePosCost, float timeCostPerError, // time is per seconds float fracNegSampled); // Training can also be done by adding one image at a time and then // calling TrainWithLoadedData void AddImageForTraining(const cv::Mat& image, const std::vector<cv::Rect>& rois, float label); void TrainWithLoadedData(float budget, float missCost, float falsePosCost); void TrainSupSubWithLoadedData(float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled); const IntegralHogCascade* cascade() const { return cascade_.get(); } private: // Structure to hold the score and selected threshold for a given detector struct DetectorStats { DetectorStats(float _score, float _thresh, unsigned int _detectorIdx) : score(_score), thresh(_thresh), detectorIdx(_detectorIdx) {} // Sort primarily based on the score bool operator<(const DetectorStats& other) const { if (fequal(score, other.score)) { if (detectorIdx == other.detectorIdx) { return thresh < other.thresh; } return detectorIdx < other.detectorIdx; } return score < other.score; } bool operator==(const DetectorStats& other) const { return detectorIdx == other.detectorIdx && fequal(score, other.score) && fequal(thresh, other.thresh); } bool operator>(const DetectorStats& other) const {return other < *this;} bool fequal(float a, float b, float ep=std::numeric_limits<float>::epsilon()*100) const { return std::fabs(a-b) < ep; } float score; float thresh; unsigned int detectorIdx; }; // Number of images being trained on int nImages_; cv::Size winSize_; boost::scoped_ptr<IntegralCascadeTimeCalculator> timeCalculator_; // All the possible detectors std::vector<IntegralHogDetector::Ptr> detectors_; // Scores of the training images for all the detectors. Each row is // a different detector and each column is a different training // image. cv::Mat_<float> scores_; // Labels for all the loaded images cv::Mat_<float> labels_; // Inverse index from the detector to its index in scores_ and labels_ boost::unordered_map<IntegralHogDetector*, int> detectorIdx_; // The trained cascade boost::scoped_ptr<IntegralHogCascade> cascade_; // The true sum of the number of images given that the negatives are // sampled more sparsely. double trueImageSum_; void LoadImagesForTraining(const std::vector<std::string>& filenames, const std::vector<float>& labels); // Trains a cascade using a greedy metric. // // Inputs: // budget - Time budget in seconds, // mistCost - Cost of a miss // falsePosCost - Cost of a false positive // metric - The metric to use // // Outputs: // cascade - The trained cascade // returns - Total cost of the cascade template <typename T> float TrainUsingGreedyMetric(float budget, float missCost, float falsePosCost, T metric, IntegralHogCascade* cascade); // Two different metrics for selecting the next best detector. // // Inputs: // missCost - Cost of a miss // falsePosCost - Cost of a false positive // inputWindows - - Boolean matrix identifying which training windows are // still in play. Will be updated // allocatedTime - The time already allocated. Will be updated after this // selection // cacheSizesUsed - Set of cache sizes used. Will be updated after this // selection. // // Returns: // pair of threshold and index of the selected detector std::pair<float, int> SelectBestDetectorIgnoringTime( float missCost, float falsePosCost, cv::Mat& inputWindows, float& allocatedTime, boost::unordered_set<cv::Size>& cacheSizesUsed); std::pair<float, int> SelectBestDetectorPerTime( float missCost, float falsePosCost, cv::Mat& inputWindows, float& allocatedTime, boost::unordered_set<cv::Size>& cacheSizesUsed); // Updates all the tracking data for when a detector is chosen void ChooseDetector(int detectorI, float thresh, cv::Mat& inputWindows, float& allocatedTime, boost::unordered_set<cv::Size>& cacheSizesUsed); // Selects the best detector that is under budget void SelectBestDetectorUnderBudget( float budget, float missCost, float falsePosCost, const cv::Mat& inputWindows, float allocatedTime, const boost::unordered_set<cv::Size>& cacheSizesUsed, float* thresh, int* chosenDetector, float* cost); // Selects the best detector according to an approximate submodular measure that is tight at cascade. // // Inputs: // missCost - Cost of a miss // falsePosCost - Cost of a false positive // timeCostPerError - Conversion factor for 1s of processing time compared // to an error. // cascade - The best cascade so far. The approximation is tight at // this point. // winPastCascade - Boolean vector specifying the windows that pass the cascade // // Outputs: // thresh - Threshold of the detector to choose // chosenDetector - Index of the chosen detector // returns - The delta cost for the added detector typedef std::priority_queue<DetectorStats, std::vector<DetectorStats>, std::greater<DetectorStats> > DetectorQueue; float SelectBestDetectorApprox( float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, const IntegralHogCascade& cascade, const cv::Mat& winPastApproxCascade, DetectorQueue* detectorQueue, float* thresh, int* chosenDetector); // Compute the bayes risk for a given threshold on a set of images // whose scores are curScores. double ComputeBayesRisk(const cv::Mat& inputWindows, const cv::Mat_<float>& curScores, float thresh, double missCost, double falsePosCost); double ComputeProcessingTimeForDetector( float fracInputWindows, int detectorI, const boost::unordered_set<cv::Size>& cacheSizesUsed); // For the SupSub proceedure find the cascade that minimizes the // approximate cost. The cost is approximate because the D_a and C_M // terms are approximated by an upper bound. // // Inputs: // missCost - Cost of a miss // falsePosCost - Cost of a false positive, already adjusted with // fracNegSampled // timeCostPerError - Conversion factor for 1s of processing time compared // to an error. // bestCascade - The best cascade so far. The approximation is tight at // this point. // fracNegSampled - fraction of the number of negative examples we're // actually training with. So the number of negative // samples seen by this class is trueNegs/fracNegSampled // // Outputs: // bestCascade - An update // Returns - The true cost of the best cascade (not the approximate cost) float MinimizeApproxCost(float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, boost::scoped_ptr<IntegralHogCascade>* ioCascade); // Computes the total cost of the cascade double ComputeTotalCost(float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, const IntegralHogCascade& cascade); // Initializes the data for computing the approximate submodular cost. // // Inputs: // missCost - Cost of a miss // falsePosCost - Cost of a false positive // timeCostPerError - Conversion factor for 1s of processing time compared // to an error. // fracNegSampled - fraction of the number of negative examples we're // actually training with. So the number of negative // samples seen by this class is trueNegs/fracNegSampled // cascade - The cascade to approximate to // // Outputs: // removeCosts - Map for each stage for the change in cost if it is removed // pastCascade - Vector specifying which entries got past the cascade from // rows in scores_ void InitializeApproxSubCost( float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, const IntegralHogCascade& cascade, boost::unordered_map<IntegralHogCascade::Stage, float>* removeCosts, cv::Mat* pastCascade); float CalculateDeltaForRemovingStage( float falsePosCost, float timeCostPerError, float fracNegSampled, const IntegralHogCascade& cascade, const boost::unordered_map<IntegralHogCascade::Stage, float>& approxCosts, const IntegralHogCascade::Stage& stage); // Find the best approximate cost for a given detector. // // missCost, falsePosCost, timeCostPerError, fraceNegSampled - // relative weights for the costs. // scores - score of the detector evaluated on each candidate region // usefulPassApproxCascade - usefule regions that pass the approx cascade // falsePosWins - False positive windows from the current cascade // windowsPassed - Windows that pass the current cascade // usefulWindows - Windows that are positives for training // notUsefuleWindows - Windows that are negatives for training // // Returns: Pair of <cost, bestThreshold> std::pair<float, float> GetBestApproxCost( unsigned int detectorIdx, float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, double baseHogTime, float nPassedApproxCascade, const cv::Mat& usefulPassApproxCascade, const cv::Mat& falsePosWins, const cv::Mat& windowsPassed, const cv::Mat& usefulWindows, const cv::Mat& notUsefulWindows); }; // Class that finds the threshold to minimize the cost of a filter class DeltaMinimizer { public: DeltaMinimizer(); ~DeltaMinimizer(); // Minimizes the cost of adding a current detector // // Inputs: // missCost, falsePosCost, timeCostPerError, fraceNegSampled - // relative weights for the costs. // scores - score of the detector evaluated on each candidate region // usefulPassApproxCascade - usefule regions that pass the approx cascade // falsePosWins - False positive windows from the current cascade // windowsPassed - Windows that pass the current cascade // usefulWindows - Windows that are positives for training // notUsefuleWindows - Windows that are negatives for training // timeCalculator - To calculate the time // cpuDelta - cpu cost to run this detector float MinimizeCost(float missCost, float falsePosCost, float timeCostPerError, float fracNegSampled, int nImages, float trueImageSum, double baseHogTime, const cv::Mat_<float>& scores, const cv::Mat& usefulPassApproxCascade, const cv::Mat& falsePosWins, const cv::Mat& windowsPassed, const cv::Mat& usefulWindows, const cv::Mat& notUsefulWindows, const IntegralCascadeTimeCalculator* timeCalculator, float cpuDelta); float bestCost() const { return bestCost_; } float bestThresh() const { return bestThresh_; } // Evaluates the cost function and its derivative with respect to // the number of entries filtered. Public because gsl is old and // needs acess to this. void EvalWithDeriv(const gsl_vector* nFiltered, void* params, double* val, gsl_vector* derivs) const; double EvalCost(const gsl_vector* nFiltered, void* params) const; void EvalDeriv(const gsl_vector* nFiltered, void* params, gsl_vector* derivs) const; private: float bestCost_; float bestThresh_; // Used for the minimization gsl_multimin_fdfminimizer* minimizer_; gsl_multimin_function_fdf minFunc_; // Data used for the calculator double cpuDelta_; // Map from the number of new windows thresholded to the threshold. boost::scoped_ptr<Interpolator> thresholdInterpolator_; // Interpolator for the cost of extra misses with a given threshold boost::scoped_ptr<Interpolator> missCostInterpolator_; // Interpolator for the cost of the false positives relative to the // number of new windows thresholded. boost::scoped_ptr<Interpolator> falsePosInterpolator_; // Interpolator for the HOG time delta boost::scoped_ptr<Interpolator> hogTimeInterpolator_; void RunMinimization(double minWindowsThreshed, double maxWindowsThreshed, double startPoint, double firstStep, float* bestCost, float* bestThresh); }; } // namespace #endif //__HOG_DETECTOR_INTEGRAL_HOG_CASCADE_TRAINER_H__
{ "alphanum_fraction": 0.6618672152, "avg_line_length": 37.5579399142, "ext": "h", "hexsha": "f5954100f1ffdf56947cb93a1f174dd8787ba5b8", "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": "a595ca718d0cda277726894a3105815cef000475", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MRSD2018/reefbot-1", "max_forks_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "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": "MRSD2018/reefbot-1", "max_issues_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "a595ca718d0cda277726894a3105815cef000475", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MRSD2018/reefbot-1", "max_stars_repo_path": "hog_detector/include/hog_detector/integral_hog_cascade_trainer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3936, "size": 17502 }
/*************************************************************************************** * Multivariate Normal density function and random number generator * Multivariate Student t density function and random number generator * Wishart random number generator * Using GSL -> www.gnu.org/software/gsl * * Copyright (C) 2006 Ralph dos Santos Silva * * 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 * * AUTHOR * Ralph dos Santos Silva, [EMAIL PROTECTED] * March, 2006 ***************************************************************************************/ #include <math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "../hmm/adkGSL.h" #include "mvnorm_gsl.h" /*****************************************************************************************************************/ /*****************************************************************************************************************/ int rmvnorm(const gsl_rng *r, const int n, const gsl_vector *mean, const gsl_matrix *var, gsl_vector *result){ /* multivariate normal distribution random number generator */ /* * n dimension of the random vetor * mean vector of means of size n * var variance matrix of dimension n x n * result output variable with a sigle random vector normal distribution generation */ int k; gsl_matrix *work = gsl_matrix_alloc(n,n); gsl_matrix_memcpy(work,var); gsl_linalg_cholesky_decomp(work); for(k=0; k<n; k++) gsl_vector_set( result, k, gsl_ran_ugaussian(r) ); gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit, work, result); gsl_vector_add(result,mean); gsl_matrix_free(work); return 0; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ int rmvnorm_prealloc(const gsl_rng *r, const int n, const gsl_vector *mean, const gsl_matrix *var, gsl_matrix *work, gsl_vector *result){ /* multivariate normal distribution random number generator */ /* * n dimension of the random vetor * mean vector of means of size n * var variance matrix of dimension n x n * result output variable with a sigle random vector normal distribution generation */ int k; gsl_matrix_memcpy(work,var); gsl_linalg_cholesky_decomp(work); for(k=0; k<n; k++) gsl_vector_set( result, k, gsl_ran_ugaussian(r) ); gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit, work, result); gsl_vector_add(result,mean); return 0; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ double dmvnorm(const int n, const gsl_vector *x, const gsl_vector *mean, const gsl_matrix *var){ /* multivariate normal density function */ /* * n dimension of the random vetor * mean vector of means of size n * var variance matrix of dimension n x n */ int s; double ax,ay; gsl_vector *ym, *xm; gsl_matrix *work = gsl_matrix_alloc(n,n), *winv = gsl_matrix_alloc(n,n); gsl_permutation *p = gsl_permutation_alloc(n); gsl_matrix_memcpy( work, var ); gsl_linalg_LU_decomp( work, p, &s ); gsl_linalg_LU_invert( work, p, winv ); ax = gsl_linalg_LU_det( work, s ); gsl_matrix_free( work ); gsl_permutation_free( p ); xm = gsl_vector_alloc(n); gsl_vector_memcpy( xm, x); gsl_vector_sub( xm, mean ); ym = gsl_vector_alloc(n); gsl_blas_dsymv(CblasUpper,1.0,winv,xm,0.0,ym); gsl_matrix_free( winv ); gsl_blas_ddot( xm, ym, &ay); gsl_vector_free(xm); gsl_vector_free(ym); ay = exp(-0.5*ay)/sqrt( pow((2*M_PI),n)*ax ); return ay; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ int rmvt(const gsl_rng *r, const int n, const gsl_vector *location, const gsl_matrix *scale, const int dof, gsl_vector *result){ /* multivariate Student t distribution random number generator */ /* * n dimension of the random vetor * location vector of locations of size n * scale scale matrix of dimension n x n * dof degrees of freedom * result output variable with a single random vector normal distribution generation */ int k; gsl_matrix *work = gsl_matrix_alloc(n,n); double ax = 0.5*dof; ax = gsl_ran_gamma(r,ax,(1/ax)); /* gamma distribution */ gsl_matrix_memcpy(work,scale); gsl_matrix_scale(work,(1/ax)); /* scaling the matrix */ gsl_linalg_cholesky_decomp(work); for(k=0; k<n; k++) gsl_vector_set( result, k, gsl_ran_ugaussian(r) ); gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit, work, result); gsl_vector_add(result, location); gsl_matrix_free(work); return 0; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ double dmvt(const int n, const gsl_vector *x, const gsl_vector *location, const gsl_matrix *scale, const int dof){ /* multivariate Student t density function */ /* * n dimension of the random vetor * location vector of locations of size n * scale scale matrix of dimension n x n * dof degrees of freedom */ int s; double ax,ay,az=0.5*(dof + n); gsl_vector *ym, *xm; gsl_matrix *work = gsl_matrix_alloc(n,n), *winv = gsl_matrix_alloc(n,n); gsl_permutation *p = gsl_permutation_alloc(n); gsl_matrix_memcpy( work, scale ); gsl_linalg_LU_decomp( work, p, &s ); gsl_linalg_LU_invert( work, p, winv ); ax = gsl_linalg_LU_det( work, s ); gsl_matrix_free( work ); gsl_permutation_free( p ); xm = gsl_vector_alloc(n); gsl_vector_memcpy( xm, x); gsl_vector_sub( xm, location ); ym = gsl_vector_alloc(n); gsl_blas_dsymv(CblasUpper,1.0,winv,xm,0.0,ym); gsl_matrix_free( winv ); gsl_blas_ddot( xm, ym, &ay); gsl_vector_free(xm); gsl_vector_free(ym); ay = pow((1+ay/dof),-az)*gsl_sf_gamma(az)/(gsl_sf_gamma(0.5*dof)*sqrt( pow((dof*M_PI),n)*ax )); return ay; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ int rwishart(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, gsl_matrix *work, gsl_matrix *output){ /* Wishart distribution random number generator */ /* * n gives the dimension of the random matrix * dof degrees of freedom * scale scale matrix of dimension n x n * result output variable with a single random matrix Wishart distribution generation */ int k,l; for(k=0; k<scale->size1; k++){ gsl_matrix_set( work, k, k, sqrt( gsl_ran_chisq( r, (dof-k) ) ) ); for(l=0; l<k; l++){ gsl_matrix_set( work, k, l, gsl_ran_ugaussian(r) ); } } gsl_matrix_memcpy(output,scale); gsl_linalg_cholesky_decomp(output); gsl_blas_dtrmm(CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,1.0,output,work); gsl_blas_dsyrk(CblasUpper,CblasNoTrans,1.0,work,0.0,output); return 0; } // ADK additions from here on /*****************************************************************************************************************/ /*****************************************************************************************************************/ double dmvnorm_prealloc(const int n, const gsl_vector *x, const gsl_vector *mean, const gsl_matrix *var, gsl_matrix *work, gsl_matrix *winv, gsl_vector *ym, gsl_vector *xm, gsl_permutation *p){ /* multivariate normal density function */ /* * n dimension of the random vetor * mean vector of means of size n * var variance matrix of dimension n x n * * added this prealloc version to cut down on memory calls */ int s; double ax,ay; gsl_matrix_memcpy( work, var ); gsl_linalg_LU_decomp( work, p, &s ); gsl_linalg_LU_invert( work, p, winv ); ax = gsl_linalg_LU_det( work, s ); gsl_vector_memcpy( xm, x); gsl_vector_sub( xm, mean ); gsl_blas_dsymv(CblasUpper,1.0,winv,xm,0.0,ym); gsl_blas_ddot( xm, ym, &ay); ay = exp(-0.5*ay)/sqrt( pow((2*M_PI),n)*ax ); return ay; } /*****************************************************************************************************************/ /*****************************************************************************************************************/ double dInverseWishart(const gsl_matrix *x, const gsl_matrix *sigma, const double dof, gsl_matrix *work, gsl_matrix *winv, gsl_permutation *p){ double denom, num; int s, d, i; double detSig,detX,trace; //get det of both matrices, take inverse of X gsl_matrix_memcpy( work, sigma ); gsl_linalg_LU_decomp( work, p, &s ); detSig = gsl_linalg_LU_det( work, s ); gsl_matrix_memcpy( work, x ); gsl_linalg_LU_decomp( work, p, &s ); detX = gsl_linalg_LU_det( work, s ); gsl_linalg_LU_invert( work, p, winv ); //get product of gamma's for denominator; calc denom d = x->size1; denom = 1.0; denom *= pow(2,(d*dof/2.0)) * mv_gamma_func(dof/2.0, d); //multiply x by inverse of sigma and take trace gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0, sigma, winv,0.0, work); trace = gsl_matrix_trace(work); num = pow(detSig, dof / 2.0) * pow(detX , (-dof-d-1)/ 2.0) * exp(-0.5 * trace); return(num/denom); } /*****************************************************************************************************************/ //rwishartGelman-- uses alg described in Gelman et al appendix void rwishartGelman(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, gsl_matrix *work,gsl_matrix *work2, gsl_vector *mean,gsl_vector *xm, gsl_matrix *output){ /* Wishart distribution random number generator */ /* * n gives the dimension of the random matrix * dof degrees of freedom * scale scale matrix of dimension n x n * result output variable with a single random matrix Wishart distribution generation */ int i; gsl_vector_set_all(mean,0.0); gsl_matrix_set_all(output,0.0); for(i = 0; i < dof; i++){ gsl_vector_set_all(xm,0); rmvnorm_prealloc(r, n, mean, scale, work, xm); gsl_vector_outer_product(xm,xm,work2); gsl_matrix_add(output,work2); } } //rwishartOdellFeiveson-- uses alg of Odell and Feiveson void rwishartOdellFeiveson(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, gsl_matrix *work,gsl_matrix *work2, gsl_vector *mean,gsl_vector *xm, gsl_matrix *output){ /* Wishart distribution random number generator */ /* * n gives the dimension of the random matrix * dof degrees of freedom * scale scale matrix of dimension n x n * result output variable with a single random matrix Wishart distribution generation */ int i,j, k; double sum, tmp; gsl_vector_set_all(mean,0.0); gsl_matrix_set_all(output,0.0); for(j=0;j<n;j++){ gsl_vector_set(mean,j,gsl_ran_chisq(r,dof-j)); for(i=0;i<j;i++){ gsl_matrix_set(work,i,j,gsl_ran_ugaussian(r)); } } //set up B matrix in work2 gsl_matrix_set(work2,0,0,gsl_vector_get(mean,0)); for(j=0;j<n;j++){ for(i=0;i<j;i++){ if(i==0){ tmp = sqrt(gsl_vector_get(mean,j)) * gsl_matrix_get(work,0,j); gsl_matrix_set(work2,0,j,tmp); } else{ tmp = sqrt(gsl_vector_get(mean,i)) * gsl_matrix_get(work,i,j); for(k=0;k<i;k++){ tmp += gsl_matrix_get(work,k,i) * gsl_matrix_get(work,k,j); } gsl_matrix_set(work2,i,j,tmp); } } tmp = gsl_vector_get(mean,j); for(k=0;k<j;k++){ tmp += gsl_matrix_get(work,k,j) * gsl_matrix_get(work,k,j); } gsl_matrix_set(work2,j,j,tmp); } gsl_matrix_memcpy(output,scale); gsl_linalg_cholesky_decomp(output); gsl_blas_dtrmm(CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,1.0,output,work2); gsl_blas_dtrmm(CblasRight,CblasUpper,CblasNoTrans,CblasNonUnit,1.0,work2,output); } //mv_gamma_func -- returns the multivariate gamma function double mv_gamma_func(double a, double d){ double val = 1.0; int i; for(i=1;i<=d;i++){ val *= gsl_sf_gamma(a- (0.5 * (i-1))); } val *= pow(M_PI,(d*(d-1)/4.0)); return(val); }
{ "alphanum_fraction": 0.6019093449, "avg_line_length": 35.0108695652, "ext": "c", "hexsha": "47baae4c127cc069c8beeb54e1bdd1a64ae68a5b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/pgLib", "max_forks_repo_path": "mvnorm_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/pgLib", "max_issues_repo_path": "mvnorm_gsl.c", "max_line_length": 137, "max_stars_count": 3, "max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/pgLib", "max_stars_repo_path": "mvnorm_gsl.c", "max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z", "num_tokens": 3362, "size": 12884 }
/*************************************************************************** File : Fit.h Project : QtiPlot -------------------------------------------------------------------- Copyright : (C) 2006 by Ion Vasilief Email (use @ for *) : ion_vasilief*yahoo.fr Description : Fit base class ***************************************************************************/ /*************************************************************************** * * * 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 FIT_H #define FIT_H #include <QObject> #include "../ApplicationWindow.h" #include "Filter.h" #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_multimin.h> class Table; class Matrix; //! Fit base class class Fit : public Filter { Q_OBJECT public: typedef double (*fit_function_simplex)(const gsl_vector *, void *); typedef int (*fit_function)(const gsl_vector *, void *, gsl_vector *); typedef int (*fit_function_df)(const gsl_vector *, void *, gsl_matrix *); typedef int (*fit_function_fdf)(const gsl_vector *, void *, gsl_vector *, gsl_matrix *); enum Algorithm{ScaledLevenbergMarquardt, UnscaledLevenbergMarquardt, NelderMeadSimplex}; enum WeightingMethod{NoWeighting, Instrumental, Statistical, Dataset}; enum FitType{BuiltIn = 0, Plugin = 1, User = 2}; Fit(ApplicationWindow *parent, Graph *g = 0, const QString& name = QString()); Fit(ApplicationWindow *parent, Table *t, const QString& name = QString()); ~Fit(); //! Actually does the fit. Should be reimplemented in derived classes. virtual void fit(); virtual bool run(){fit(); return true;}; //! Sets the data set to be used for weighting bool setWeightingData(WeightingMethod w, const QString& colName = QString::null); void setDataCurve(int curve, double start, double end); bool setDataFromTable(Table *t, const QString& xColName, const QString& yColName, int from = 1, int to = -1); QString resultFormula(){return d_result_formula;}; QString formula(){return d_formula;}; virtual void setFormula(const QString&){}; int numParameters(){return d_p;}; QStringList parameterNames(){return d_param_names;}; virtual void setParametersList(const QStringList&){}; void setParameterExplanations(const QStringList& lst){d_param_explain = lst;}; double initialGuess(int parIndex){return gsl_vector_get(d_param_init, parIndex);}; void setInitialGuess(int parIndex, double val){gsl_vector_set(d_param_init, parIndex, val);}; void setInitialGuesses(double *x_init); virtual void guessInitialValues(){}; void setParameterRange(int parIndex, double left, double right); void setAlgorithm(Algorithm s){d_solver = s;}; //! Specifies weather the result of the fit is a function curve void generateFunction(bool yes, int points = 100); //! Output string added to the plot as a new legend virtual QString legendInfo(); //! Returns a vector with the fit results double* results(){return d_results;}; //! Returns a vector with the fit residuals double* residuals(); //! Plot residuals and display data values in a column QwtPlotCurve* showResiduals(); void showPredictionLimits(double confidenceLevel); void showConfidenceLimits(double confidenceLevel); //! Lower Confidence Limit double lcl(int parIndex, double confidenceLevel); //! Upper Confidence Limit double ucl(int parIndex, double confidenceLevel); //! Returns a vector with the standard deviations of the results double* errors(); //! Returns the sum of squares of the residuals from the best-fit line double chiSquare() {return chi_2;}; //! Returns R^2 double rSquare(); //! Returns adjusted R^2 double adjustedRSquare(){return d_adjusted_r_square;}; //! Returns the Residual Sum of Squares double rss(){return d_rss;}; //! Returns the Root Mean Squared Error double rmse(){return sqrt(d_rss/(d_n - d_p));}; //! Specifies wheather the errors must be scaled with sqrt(chi_2/dof) void scaleErrors(bool yes = true){d_scale_errors = yes;}; Table* parametersTable(const QString& tableName); void writeParametersToTable(Table *t, bool append = false); Matrix* covarianceMatrix(const QString& matrixName); bool save(const QString& fileName); bool load(const QString& fileName); FitType type(){return d_fit_type;}; void setType(FitType t){d_fit_type = t;}; QString fileName(){return d_file_name;}; void setFileName(const QString& fn){d_file_name = fn;}; //! Frees the memory allocated for the X and Y data sets void freeMemory(); //! Calculates the data for the output fit curve virtual double eval(double *, double){return 0.0;}; private: void init(); //! Pointer to the GSL multifit minimizer (for simplex algorithm) gsl_multimin_fminimizer * fitSimplex(gsl_multimin_function f, int &iterations, int &status); //! Pointer to the GSL multifit solver gsl_multifit_fdfsolver * fitGSL(gsl_multifit_function_fdf f, int &iterations, int &status); //! Customs and stores the fit results according to the derived class specifications. Used by exponential fits. virtual void customizeFitResults(){}; protected: //! Allocates the memory for the fit workspace void initWorkspace(int par); //! Frees the memory allocated for the fit workspace void freeWorkspace(); //! Adds the result curve as a FunctionCurve to the plot, if d_gen_function = true virtual FunctionCurve * insertFitFunctionCurve(const QString& name, double *x, double *y, int penWidth = 1); //! Adds the result curve to the plot virtual void generateFitCurve(); //! Calculates the data for the output fit curve and store itin the X an Y vectors virtual void calculateFitCurveData(double *X, double *Y) {Q_UNUSED(X) Q_UNUSED(Y)}; //! Output string added to the result log virtual QString logFitInfo(int iterations, int status); fit_function d_f; fit_function_df d_df; fit_function_fdf d_fdf; fit_function_simplex d_fsimplex; //! Number of fit parameters int d_p; //! Initial guesses for the fit parameters gsl_vector *d_param_init; /*! \brief Tells whether the fitter uses non-linear/simplex fitting * with an initial parameters set, that must be freed in the destructor. */ bool is_non_linear; //! weighting data set used for the fit double *d_w; //! Names of the fit parameters QStringList d_param_names; //! Stores a list of short explanations for the significance of the fit parameters QStringList d_param_explain; //! Specifies weather the result curve is a FunctionCurve or a normal curve with the same x values as the fit data bool d_gen_function; //! Algorithm type Algorithm d_solver; //! The fit formula given on input QString d_formula; //! The result fit formula, where the fit parameters are replaced with the calculated values. QString d_result_formula; //! Covariance matrix gsl_matrix *covar; //! The kind of weighting to be performed on the data WeightingMethod d_weighting; //! The name of the weighting dataset QString weighting_dataset; //! Stores the result parameters double *d_results; //! Stores standard deviations of the result parameters double *d_errors; //! Stores fit residuals double *d_residuals; //! The sum of squares of the residuals from the best-fit line double chi_2; //! Residual sum of squares double d_rss; //! Adjusted R^2 double d_adjusted_r_square; //! Specifies wheather the errors must be scaled with sqrt(chi_2/dof) bool d_scale_errors; //! Table window used for the output of fit parameters Table *d_param_table; //! Matrix window used for the output of covariance matrix Matrix *d_cov_matrix; FitType d_fit_type; //! Path of the XML file where the user stores the fit model QString d_file_name; //! Stores the left limits of the research interval for the result parameters double *d_param_range_left; //! Stores the right limits of the research interval for the result parameters double *d_param_range_right; }; #endif
{ "alphanum_fraction": 0.6528409692, "avg_line_length": 35.1338289963, "ext": "h", "hexsha": "99feb4e564be453410786d11ebf4e8950b2cac05", "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/Fit.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/Fit.h", "max_line_length": 116, "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/Fit.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": 2149, "size": 9451 }
#pragma once #include <type_traits> #include <gsl/gsl> #include "sly/macros.h" #include "sly/types.h" template <class T> struct is_unique_ptr : std::false_type {}; template <class T, class D> struct is_unique_ptr<std::unique_ptr<T, D>> : std::true_type {}; template <class T> struct unique_ptr_type {}; template <class T, class D> struct unique_ptr_type<std::unique_ptr<T, D>> { using type = std::unique_ptr<T, D>; using underlying_type = T; using delete_type = D; }; template <class T> struct is_shared_ptr : std::false_type {}; template <class T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {}; template <typename T> struct is_indexable : std::false_type { }; template <typename T, typename A> struct is_indexable<std::vector<T, A>> : std::true_type { }; template <typename T, std::size_t N> struct is_indexable<std::array<T, N>> : std::true_type { }; namespace sly { typedef s32 StatusCode; typedef const char* ErrorMessage; static const StatusCode SUCCESS = (StatusCode)0; static const StatusCode UNKNOWN = (StatusCode)-1; template <typename T, typename = typename std::is_reference<T>::type> struct retval { }; template <typename T> struct retval<T, std::false_type> { public: using type = T; using type_pointer = typename std::remove_reference<T>::type*; using type_reference = typename std::remove_reference<T>::type&; //using unique_ptr = typename is_unique_ptr<T>::value; retval(T value) : _value(std::move(value)), _statusCode(SUCCESS) {} retval(StatusCode code) : _statusCode(code) {} //retval(const retval&) = delete; retval& operator =(const retval&) = delete; ~retval() = default; template <class V, typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr> V to() const { return reinterpret_cast<V>(_value.get()); } template <class V, typename Y = T, typename std::enable_if_t<!is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr> V to() const { return reinterpret_cast<V>(_value); } template<typename V> operator V() const { return to<V>(); } type result() { return _value; } type_reference ref() { return _value; } template <typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr> operator type_reference() const { return *_value.get(); } template <typename Y = T, typename std::enable_if_t<is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr> operator typename unique_ptr_type<Y>::underlying_type&() { return *_value.get(); } template <typename Y = T, typename std::enable_if_t<!is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr> operator type() { return result(); } template <typename Y = T, typename std::enable_if_t<std::is_pointer<Y>::value || is_unique_ptr<Y>::value || is_shared_ptr<Y>::value>* = nullptr> type_reference operator->() { return _value; } template <typename Y = T, typename std::enable_if_t<!std::is_pointer<Y>::value && !is_unique_ptr<Y>::value && !is_shared_ptr<Y>::value>* = nullptr> type_pointer operator->() { return &_value; } //template <typename N, typename Y = T, typename std::enable_if_t<std::is_pointer<Y>::value || is_unique_ptr<Y>::value || is_shared_ptr<Y>::value || is_indexable<Y>::value>* = nullptr> template<typename N> auto operator[](const N index) { return _value[index]; } StatusCode statusCode() const { return _statusCode; } bool_t succeeded() { return statusCode() == SUCCESS; } bool_t failed() { return statusCode() != SUCCESS; } template<typename X> X as() { return (X)result; } private: StatusCode _statusCode; T _value; }; template <typename T> struct retval<T, std::true_type> { public: using type = T; using type_pointer = typename std::remove_reference<T>::type*; retval(T value) : _value(std::addressof(value)), _statusCode(SUCCESS) {} retval(StatusCode code) : _statusCode(code), _value(nullptr) {} retval(const retval&) = delete; retval& operator =(const retval&) = delete; ~retval() = default; T result() { return *_value; } operator T() { return result(); } type_pointer operator->() { return _value; } StatusCode statusCode() const { return _statusCode; } bool_t succeeded() { return statusCode() == SUCCESS; } bool_t failed() { return statusCode() != SUCCESS; } template<typename X> X as() { return (X)result(); } private: StatusCode _statusCode; type_pointer _value; }; template <> struct retval<void, std::false_type> { public: retval() : _statusCode(SUCCESS) {} retval(StatusCode code) : _statusCode(code) {} retval(const retval&) = delete; retval& operator =(const retval&) = delete; ~retval() = default; void value() const { } StatusCode statusCode() const { return _statusCode; } bool_t succeeded() { return statusCode() == SUCCESS; } bool_t failed() { return statusCode() != SUCCESS; } template<typename X> X as() { return (X)result; } private: StatusCode _statusCode; }; template <typename T> retval<T> value(const T& value) { auto result = retval<T> ( std::move(value) ) ; return result; } template <typename T> retval<T&> reference(T& value) { return retval<T&> ( value ); } retval<void> success(); retval<void> failed(); template <typename T> retval<T> failed(StatusCode statusCode, ErrorMessage message) { Expects(statusCode != SUCCESS); return retval<T> { statusCode }; } template <typename T> retval<T> failed() { return retval<T> { UNKNOWN }; } }
{ "alphanum_fraction": 0.5898352502, "avg_line_length": 28.4690265487, "ext": "h", "hexsha": "31581302f884224fdc5efb9b19a31f86367b93d8", "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": "9216cf04a78f1d41af01186489ba6680b9641229", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Gibbeon/sly", "max_forks_repo_path": "slycore/include/sly/retval.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "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": "Gibbeon/sly", "max_issues_repo_path": "slycore/include/sly/retval.h", "max_line_length": 192, "max_stars_count": null, "max_stars_repo_head_hexsha": "9216cf04a78f1d41af01186489ba6680b9641229", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Gibbeon/sly", "max_stars_repo_path": "slycore/include/sly/retval.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1511, "size": 6434 }
#include <stdlib.h> #include <math.h> #include <gsl/gsl_spmatrix.h> #include <assert.h> #include "graph_struct.h" // pour améliorer la complexité: // -> Les matrices de graph sont symétriques, on peut donc n'effectuer les opérations lors de la création du graph que sur une moitié de celui-ci // -> Faire l'attribution des couleurs en même temps que la matrice d'adjacence struct graph_t* graph__empty (int vertices){ struct graph_t* g = malloc(sizeof(*g)); g -> num_vertices = vertices; g -> t = gsl_spmatrix_alloc(vertices, vertices); g -> o = gsl_spmatrix_alloc(2, vertices); return g; } struct graph_t* graph_copy(struct graph_t * g){ struct graph_t *copy = malloc(sizeof(struct graph_t)); copy -> num_vertices = g -> num_vertices; copy -> o = gsl_spmatrix_alloc(2, g->num_vertices); gsl_spmatrix_memcpy(copy -> o, g -> o); copy -> t = gsl_spmatrix_alloc(g -> num_vertices, g -> num_vertices); gsl_spmatrix_memcpy(copy -> t, g -> t); return copy; } struct graph_t* make_graph(int m, char c){ struct graph_t* g; switch (c){ case 'c' : g = square_graph__empty(m); return g; case 't': g = triangular_graph__empty(m); return g; case 'h': g = hexa_graph__empty(m); return g; default: return NULL; } } struct graph_t* square_graph__empty(int m){ int vertices = (m+1) * (m+1); struct graph_t* g = graph__empty (vertices); int line_length = m+1; for (int i = 0; i < vertices; i++){ int index = i%line_length; // Adds right links if (index+1 < line_length) gsl_spmatrix_set(g -> t, i, i+1, 1); // Adds left links if (index-1 >= 0) gsl_spmatrix_set(g -> t, i, i-1, 1); // Adds down links if (i+line_length < vertices) gsl_spmatrix_set(g -> t, i, i+line_length, 1); // Adds up links if (i-line_length >= 0) gsl_spmatrix_set(g -> t, i, i-line_length, 1); } // Ownership of initial boxes for (int i = 0; i < line_length-1; i++){ gsl_spmatrix_set(g -> o, 0, i, 1); gsl_spmatrix_set(g -> o, 0, vertices-1-i, 1); gsl_spmatrix_set(g -> o, 1, (i+1)*line_length, 1); gsl_spmatrix_set(g -> o, 1, vertices-1-(i+1)*line_length, 1); } return g; } struct graph_t* triangular_graph__empty(int m){ int num_vertices = 6 * m * m; struct graph_t* g = graph__empty(num_vertices); int first_vertice_row=0; int row = 0; while(row < m){ //Edges in a row for(int vertice = first_vertice_row; vertice < first_vertice_row + m + row; vertice++){ gsl_spmatrix_set(g -> t, vertice, vertice + m + row, 1); gsl_spmatrix_set(g -> t, vertice + m + row, vertice, 1); gsl_spmatrix_set(g -> t, vertice, vertice + m + row + 1, 1); gsl_spmatrix_set(g -> t, vertice + m + row + 1, vertice, 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - (vertice + m + row), num_vertices - 1 - vertice, 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - vertice, num_vertices - 1 - (vertice + m + row ), 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - (vertice + m + row + 1), num_vertices - 1 - vertice, 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - vertice, num_vertices-1 - (vertice + m + row + 1), 1); } //Edges between 2 rows for(int vertice = first_vertice_row + m + row; vertice <= first_vertice_row + 2*(m + row); vertice++){ gsl_spmatrix_set(g -> t, vertice, vertice + m + row + 1, 1); gsl_spmatrix_set(g -> t, vertice + m + row + 1, vertice, 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - vertice, num_vertices - 1 - (vertice + m + row + 1), 1); gsl_spmatrix_set(g -> t, num_vertices - 1 - (vertice + m + row + 1), num_vertices - 1 - vertice, 1); } row++; first_vertice_row += 2*m + row*(row+1)/2; } //black starting tiles for(int vertice = 0; vertice < m; vertice ++){ gsl_spmatrix_set(g -> o, BLACK, vertice, 1); gsl_spmatrix_set(g -> o, BLACK, vertice + m + 1, 1); gsl_spmatrix_set(g -> o, BLACK, num_vertices - 1 - vertice, 1); gsl_spmatrix_set(g -> o, BLACK, num_vertices - 1 - (vertice + m + 1), 1); } for(int row = 1; row < m/2 ; row++){ gsl_spmatrix_set(g -> o, BLACK, m-1 + 2*row*m + row*(row+1), 1); gsl_spmatrix_set(g -> o, BLACK, m-1 + 2*row*m + row*(row+1) + m + row + 1, 1); gsl_spmatrix_set(g -> o, BLACK, num_vertices - 1 - (m-1 + 2*row*m + row*(row+1)), 1); gsl_spmatrix_set(g -> o, BLACK, num_vertices - 1 - (m-1 + 2*row*m + row*(row+1) + m + row + 1), 1); } //white starting tiles for(int row = 0; row < m; row++){ gsl_spmatrix_set(g -> o, WHITE, m + 2*row*m + row*(row+1), 1); gsl_spmatrix_set(g -> o, WHITE, m + 2*row*m + row*(row+1) + m + row + 1, 1); gsl_spmatrix_set(g -> o, WHITE, num_vertices - 1 - (m + 2*row*m + row*(row+1)), 1); gsl_spmatrix_set(g -> o, WHITE, num_vertices - 1 - (m + 2*row*m + row*(row+1) + m + row + 1), 1); } for(int row = m/2+1; row < m; row++){ gsl_spmatrix_set(g -> o, WHITE, m-1 + 2*row*m + row*(row+1), 1); gsl_spmatrix_set(g -> o, WHITE, m-1 + 2*row*m + row*(row+1) - (m + row), 1); gsl_spmatrix_set(g -> o, WHITE, num_vertices - 1 - (m-1 + 2*row*m + row*(row+1)), 1); gsl_spmatrix_set(g -> o, WHITE, num_vertices - 1 - (m-1 + 2*row*m + row*(row+1) - (m + row)),1); } return g; } struct graph_t* hexa_graph__empty(int m){ int vertices = (m+1) * (m+1); struct graph_t* g = graph__empty (vertices); int line_length = m+1; for (int i = 0; i < vertices; i++){ int index = i%line_length; // Adds right links if (index+1 < line_length) gsl_spmatrix_set(g -> t, i, i+1, 1); // Adds left links if (index-1 >= 0) gsl_spmatrix_set(g -> t, i, i-1, 1); // Adds down links if (i/line_length < line_length-1 && index > 0) gsl_spmatrix_set(g -> t, i, i+line_length - 1, 1); if (i+line_length < vertices && i/line_length < line_length-1) gsl_spmatrix_set(g -> t, i, i+line_length, 1); // Adds up links if (i/m > 0 && index < line_length-1) gsl_spmatrix_set(g -> t, i, i-line_length + 1, 1); if (i-line_length >= 0 && i/line_length > 0) gsl_spmatrix_set(g -> t, i, i-line_length, 1); // Ownership of initial boxes for (int i = 0; i < line_length-1; i++){ gsl_spmatrix_set(g -> o, 0, i, 1); gsl_spmatrix_set(g -> o, 0, vertices-1-i, 1); gsl_spmatrix_set(g -> o, 1, (i+1)*line_length, 1); // Pour m = 3, l_l = 4 : 4, 8, 12 gsl_spmatrix_set(g -> o, 1, vertices-1-(i+1)*line_length, 1); // } } return g; } void add__move_to_graph (struct graph_t* g, int vertice, int player){ assert (g != NULL); gsl_spmatrix_set(g -> o, player, vertice, 1); } int get__box_owner (struct graph_t* g, int vertice){ for (int p = 0; p < 2; p++){ if (gsl_spmatrix_get(g -> o, p, vertice) == 1) return p; } return EMPTY_BOX; } void graph__free (struct graph_t* g){ assert (g != NULL); gsl_spmatrix_free(g -> o); gsl_spmatrix_free(g -> t); free(g); } void print_graph (struct graph_t* g, char c){ switch (c){ case 'c' : square_graph__print (g); break; case 't': triangular_graph__print (g); break; case 'h': hexa_graph__print (g); break; default: printf("Don't find this type of graph\n"); break; } } void square_graph__print (struct graph_t* g){ assert (g != NULL); int n = sqrt(g -> num_vertices); for (int i = 0; i < n; i++){ printf("\t"); for (int j = 0; j < n; j++){ int box_owner = get__box_owner (g, i*n + j); if (box_owner == 0) printf("\033[34;01m■ \033[00m"); else if (box_owner == 1) printf("\033[31;01m■ \033[00m"); else printf("■ "); } printf("\n"); } } void triangular_graph__print (struct graph_t* g){(void) g;} void hexa_graph__print (struct graph_t* g){ assert (g != NULL); int n = sqrt(g -> num_vertices); char space[1000] = ""; for (int i = 0; i < n; i++){ printf("\t%s", space); for (int space = 0; space < i; space++){ printf(" "); } for (int j = 0; j < n; j++){ int box_owner = get__box_owner (g, i*n + j); if (box_owner == 0) printf("\033[34;01m⬢ \033[00m"); else if (box_owner == 1) printf("\033[31;01m⬢ \033[00m"); else printf("⬢ "); } printf("\n"); } }
{ "alphanum_fraction": 0.5839635098, "avg_line_length": 30.741697417, "ext": "c", "hexsha": "589eb4a44b7dcf9930d551428958cf1a5654f7ea", "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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "src/graph_struct.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "ielomariala/Hex-Game", "max_issues_repo_path": "src/graph_struct.c", "max_line_length": 145, "max_stars_count": null, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "src/graph_struct.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2951, "size": 8331 }
/** * * @file example_dgelqf.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 using LQ factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated d Tue Jan 7 11:45:20 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> #ifndef max #define max(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif int check_orthogonality(int, int, int, double*); int check_factorization(int, int, double*, double*, int, double*); int IONE=1; int ISEED[4] = {0,0,0,1}; /* initial seed for dlarnv() */ int main () { int cores = 2; int M = 10; int N = 15; int LDA = 10; int K = min(M, N); int info; int info_ortho, info_factorization; int i,j; int LDAxN = LDA*N; double *A1 = (double *)malloc(LDA*N*sizeof(double)); double *A2 = (double *)malloc(LDA*N*sizeof(double)); double *Q = (double *)malloc(LDA*N*sizeof(double)); PLASMA_desc *T; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!Q)){ printf("Out of Memory \n "); return EXIT_SUCCESS; } /* Plasma Initialization */ PLASMA_Init(cores); printf("-- PLASMA is initialized to run on %d cores. \n",cores); /* Allocate T */ PLASMA_Alloc_Workspace_dgelqf(M, N, &T); /* Initialize A1 and A2 */ LAPACKE_dlarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i] ; /* Factorization QR of the matrix A2 */ info = PLASMA_dgelqf(M, N, A2, LDA, T); /* Building the economy-size Q */ memset((void*)Q, 0, LDA*N*sizeof(double)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; PLASMA_dorglq(M, N, K, A2, LDA, T, Q, LDA); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q); info_factorization = check_factorization(M, N, A1, A2, LDA, Q); if ((info_ortho != 0)|(info_factorization != 0)|(info != 0)) printf("-- Error in DGELQF example ! \n"); else printf("-- Run of DGELQF example successful ! \n"); free(A1); free(A2); free(Q); free(T); PLASMA_Finalize(); return EXIT_SUCCESS; } /*------------------------------------------------------------------- * Check the orthogonality of Q */ int check_orthogonality(int M, int N, int LDQ, double *Q) { double alpha, beta; double normQ; int info_ortho; int i; int minMN = min(M, N); double eps; double *work = (double *)malloc(minMN*sizeof(double)); eps = LAPACKE_dlamch_work('e'); alpha = 1.0; beta = -1.0; /* Build the idendity matrix USE DLASET?*/ double *Id = (double *) malloc(minMN*minMN*sizeof(double)); memset((void*)Id, 0, minMN*minMN*sizeof(double)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (double)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_dsyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); normQ = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'u', minMN, Id, minMN, work); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n",normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ int check_factorization(int M, int N, double *A1, double *A2, int LDA, double *Q) { double Anorm, Rnorm; double alpha, beta; int info_factorization; int i,j; double eps; eps = LAPACKE_dlamch_work('e'); double *Ql = (double *)malloc(M*N*sizeof(double)); double *Residual = (double *)malloc(M*N*sizeof(double)); double *work = (double *)malloc(max(M,N)*sizeof(double)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ double *R = (double *)malloc(N*N*sizeof(double)); memset((void*)R, 0, N*N*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M); free(R); } else { /* Extract the L */ double *L = (double *)malloc(M*M*sizeof(double)); memset((void*)L, 0, M*M*sizeof(double)); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(double)); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M); free(L); } /* Compute the Residual */ for (i = 0; i < M; i++) for (j = 0 ; j < N; j++) Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i]; Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Residual, M, work); Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A2, LDA, work); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; }
{ "alphanum_fraction": 0.5554175722, "avg_line_length": 28.1310043668, "ext": "c", "hexsha": "38ee3505ef66e1f604f1baaa05616e42cfda5ffe", "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_dgelqf.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_dgelqf.c", "max_line_length": 110, "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_dgelqf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2093, "size": 6442 }
// // mcrat.h // Global header file for all of MCRaT // // Created by Tyler Parsotan on 7/23/21. // //define on and off for switches #define ON 1 #define OFF 0 //define switches for MCRaT to continue a simulation 'c' or initalize a simulation #define INITALIZE 'i' #define CONTINUE 'c' //define the codes for the different types of hydro simulations that we can use #define FLASH 0 #define PLUTO_CHOMBO 1 #define PLUTO 2 //have separate compiler directive for file type #define RIKEN 3 //need to replace this when done testing, just keeping it in the background for now and minimize its effect //define PLUTO file types here #define FILE_DBL 0 #define FILE_FLT 1 #define FILE_DBL_H5 2 #define FILE_FLT_H5 3 #define FILE_VTK 4 //define types of simulations that can be run #define SCIENCE 0 #define CYLINDRICAL_OUTFLOW 1 #define SPHERICAL_OUTFLOW 2 #define STRUCTURED_SPHERICAL_OUTFLOW 3 //define the geometries that we can handle #define CARTESIAN 0 //2D, 3D #define SPHERICAL 1 //2D, 3D #define CYLINDRICAL 2 //2D #define POLAR 3 //only in 3D, technically Cylindrical coordinates but PLUTO calls this POLAR //define the hydro dimensions that we can handle #define TWO 0 #define TWO_POINT_FIVE 1 #define THREE 2 //define the types of things that we can assume for the thermal synchrotron emission and how we calculate the B field #define INTERNAL_E 0 #define TOTAL_E 1 #define SIMULATION 2 //need to add this to statement below to take care of defaults //define photon types #define INJECTED_PHOTON 'i' #define COMPTONIZED_PHOTON 'k' #define CS_POOL_PHOTON 'p' #define UNABSORBED_CS_PHOTON 'c' #define REBINNED_PHOTON 'r' extern const double C_LIGHT; extern const double A_RAD; extern const double PL_CONST; extern const double K_B; extern const double M_P; extern const double THOM_X_SECT; extern const double M_EL; extern const double FINE_STRUCT; extern const double CHARGE_EL; extern const double R_EL; #define STR_BUFFER 2000 struct photon { char type; //was the photon injected as blackbody or wien, 'i', or was it emitted as cyclo-synchrotron or was it a cyclo-synchrotron photon that was compton scattered double p0; //E/c, 4 momentum is in lab frame double p1; // p_x double p2; //p_y double p3; //p_z double comv_p0; //E/c, 4 momentum is in comoving frame double comv_p1; // p_x double comv_p2; //p_y double comv_p3; //p_z double r0; //x in MCRaT coordinates these get saved double r1; //y double r2; //z double s0; //stokes I always 1 double s1; //stokes Q/I +1 is in positive y_tilde coordinate (z_hat X photon 4 momentum) double s2; //stokes U/I double s3; //Stokes V/I double num_scatt; double weight; //each photon should have equal weight, sp this shouldnt matter, weight in mc.par file but across injections can have varying weights int nearest_block_index; //index that allows for extraction of information of the hydro grid block that the photon si located within } ; //structure to hold photon information struct hydro_dataframe { /* Coordinate System | Coordinate unit vector order (r0,r1,r2)/(v0,v1,v2) 3D Cartesian | x, y, z 3D Spherical | r, theta, phi 3D Polar | r, phi, z 2D Cartesian | x, z 2D Cylindrical | r, z (phi) //in PLUTO its possible to save 3D vectors in 2.5 dims where the final unit vector is phi hat 2D Spherical | r, theta, (phi) */ int num_elements; //number of elements in each array double *r0; //coodinates in hydro coodinate system that user provides, double *r1; double *r2; double *r0_size;//size of fluid elements double *r1_size; double *r2_size; double *r;//spherical coordinates of fluid elements for photon injection, mdifying fluid value purposes double *theta; double *v0; //velocity in hydro coordinate system double *v1; double *v2; double *dens; double *dens_lab; double *pres; double *temp; double *gamma; double *B0; //magentic field in hydro coordinate system double *B1; double *B2; //also hold global simulation information double r0_domain[2]; //holds min and max values of r0 coordinates for hydro sim double r1_domain[2]; double r2_domain[2]; double fps; //frames per second of the simulation int scatt_frame_number; int inj_frame_number; int last_frame; int increment_inj_frame; //the change in between each injection frame which may change if different number of fps is used in each portion of hydro code int increment_scatt_frame; //same as above expect for frames that photons are acattered in }; // structure to hold all information for a given hydro simulation //include all libraries needed #include "hdf5.h" #include "mpi.h" #include <omp.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_histogram2d.h> #include <gsl/gsl_integration.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <sys/types.h> #include <sys/stat.h> #include <glob.h> #include <unistd.h> #include <dirent.h> #include <math.h> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> //include all other header files in mcrat #include "mcrat_input.h" #include "mclib.h" #include "mclib_riken.h" #include "mclib_pluto.h" #include "mclib_flash.h" #include "mc_cyclosynch.h" #include "geometry.h" #include "mcrat_scattering.h" #include "mcrat_io.h" //set default hydro v scale to be the speed of light #define HYDRO_V_SCALE C_LIGHT //take care of hydro scales in pressure, magnetic field, etc #define HYDRO_P_SCALE HYDRO_D_SCALE*HYDRO_V_SCALE*HYDRO_V_SCALE #if B_FIELD_CALC==SIMULATION #define HYDRO_B_SCALE sqrt(4*M_PI*HYDRO_P_SCALE) #endif //take care of default PLUTO file types here #ifdef PLUTO #ifndef PLUTO_FILETYPE #define PLUTO_FILETYPE FILE_DBL #endif #endif //take care of synchrotron defaults here #ifdef CYCLOSYNCHROTRON_SWITCH //if the percentage of max photon that will be used to create the energy bins isnt defined, define it to be 10%, also applies to emiting synch photons #ifndef CYCLOSYNCHROTRON_REBIN_E_PERC #define CYCLOSYNCHROTRON_REBIN_E_PERC 0.1 #endif //if the polar angle bins that the rebinned synch photons isnt defined use 0.5 degree increments by default #ifndef CYCLOSYNCHROTRON_REBIN_ANG #define CYCLOSYNCHROTRON_REBIN_ANG 0.5 #endif //if the azimuthal angle bins that the rebinned synch photons isnt defined use 0.5 degree increments by default #ifndef CYCLOSYNCHROTRON_REBIN_ANG_PHI #define CYCLOSYNCHROTRON_REBIN_ANG_PHI 10 //0.5 #endif //if the user hasnt defined anything for how to calculate the B field, assume that they want it calculated from the total energy #ifndef B_FIELD_CALC #define B_FIELD_CALC TOTAL_E #endif //it is defined therefore see if EPSILON_B has been set and B_FIELD_CALC != SIMULATION #if B_FIELD_CALC == TOTAL_E || B_FIELD_CALC == INTERNAL_E //see if epsilon_b has been set #ifndef EPSILON_B //if not set it to be 0.5 by default #define EPSILON_B 0.5 #endif #endif #else //if its not defined set it to be off by default #define CYCLOSYNCHROTRON_SWITCH OFF #endif //take care of stokes switch and comv_switch and save_type defaults too #ifndef STOKES_SWITCH #define STOKES_SWITCH OFF #endif #ifndef COMV_SWITCH #define COMV_SWITCH OFF #endif #ifndef SAVE_TYPE #define SAVE_TYPE OFF #endif //throw errors during compilation if other switches are not defined #ifndef SIM_SWITCH #error Need to define hydro simulation type in mcrat_input.h file using SIM_SWITCH #endif #ifndef DIMENSIONS #error Need to define hydro simulation dimensions in mcrat_input.h file using DIMENSIONS (should be set to two for this version of MCRaT) #endif #ifndef GEOMETRY #error Need to define hydro simulation geometry in mcrat_input.h file using GEOMETRY #endif #ifndef HYDRO_L_SCALE #error Need to define hydro simulation length scaling in mcrat_input.h file using HYDRO_L_SCALE #endif #ifndef HYDRO_D_SCALE #error Need to define hydro simulation density scaling in mcrat_input.h file using HYDRO_D_SCALE #endif #ifndef MCPAR #error Need to define name of MCRaT parameter file in mcrat_input.h file using MCPAR (it is typically called mc.par, see e.g. the MCRaT manual) #endif
{ "alphanum_fraction": 0.7195190471, "avg_line_length": 32.8376383764, "ext": "h", "hexsha": "93c7d7694d43e974aa93418276f1e76157cc24ec", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_head_hexsha": "d5f8519e5c66eb2c25258e5ee9240a9219059a96", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lazzati-astro/MCRaT", "max_forks_repo_path": "Src/mcrat.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d5f8519e5c66eb2c25258e5ee9240a9219059a96", "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": "lazzati-astro/MCRaT", "max_issues_repo_path": "Src/mcrat.h", "max_line_length": 170, "max_stars_count": 4, "max_stars_repo_head_hexsha": "d5f8519e5c66eb2c25258e5ee9240a9219059a96", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lazzati-astro/MCRaT", "max_stars_repo_path": "Src/mcrat.h", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "num_tokens": 2478, "size": 8899 }
#pragma once #include "halley/text/halleystring.h" #include "halley/utils/utils.h" #include <gsl/span> namespace Halley { class Path { public: Path(); Path(const char* name); Path(const std::string& name); Path(const String& name); Path(const Path& other) = default; Path(Path&& other) noexcept = default; Path& operator=(const Path& other) = default; Path& operator=(Path&& other) noexcept = default; Path& operator=(const std::string& other); Path& operator=(const String& other); Path getRoot() const; Path getFront(size_t n) const; Path getFilename() const; Path getStem() const; String getExtension() const; String getString() const; String getNativeString() const; String toString() const; size_t getNumberPaths() const; Path dropFront(int numberFolders) const; Path parentPath() const; Path replaceExtension(String newExtension) const; Path operator/(const char* other) const; Path operator/(const Path& other) const; Path operator/(const String& other) const; Path operator/(const std::string& other) const; bool operator==(const char* other) const; bool operator==(const String& other) const; bool operator==(const Path& other) const; bool operator!=(const Path& other) const; bool operator<(const Path& other) const; std::string string() const; static void writeFile(const Path& path, gsl::span<const gsl::byte> data); static void writeFile(const Path& path, const Bytes& data); static void writeFile(const Path& path, const String& data); static Bytes readFile(const Path& path); static void removeFile(const Path& path); Path makeRelativeTo(const Path& path) const; Path changeRelativeRoot(const Path& currentParent, const Path& newParent) const; bool isDirectory() const; bool isFile() const; bool isAbsolute() const; bool isEmpty() const; private: Vector<String> pathParts; void normalise(); void setPath(const String& value); explicit Path(Vector<String> parts); }; using TimestampedPath = std::pair<Path, int64_t>; }
{ "alphanum_fraction": 0.7142857143, "avg_line_length": 25.9620253165, "ext": "h", "hexsha": "7f83b6fffd240f2048f3fb368c4875f059a211fc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/engine/utils/include/halley/file/path.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "amrezzd/halley", "max_issues_repo_path": "src/engine/utils/include/halley/file/path.h", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/engine/utils/include/halley/file/path.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 508, "size": 2051 }
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lib/util/random_matrix.h" #include <assert.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_vector.h> #include <stdint.h> #include "common/c_math/linalg.h" void MatArrRandomGaussian(int32_t nr, int32_t nc, const gsl_rng *rng, double *d) { for (int32_t i = 0; i < nr; ++i) { for (int32_t j = 0; j < nc; ++j) { d[i*nc + j] = gsl_ran_gaussian(rng, 1.0); } } } void MatArrRandomOrthogonal(int32_t n, const gsl_rng *rng, double *d) { MatArrRandomGaussian(n, n, rng, d); gsl_matrix *Q = gsl_matrix_alloc((size_t)n, (size_t)n); gsl_matrix *R = gsl_matrix_alloc((size_t)n, (size_t)n); gsl_vector *tau = gsl_vector_alloc((size_t)n); gsl_matrix_view A = gsl_matrix_view_array(d, (size_t)n, (size_t)n); gsl_linalg_QR_decomp(&A.matrix, tau); gsl_linalg_QR_unpack(&A.matrix, tau, Q, R); gsl_matrix_memcpy(&A.matrix, Q); gsl_vector_free(tau); gsl_matrix_free(R); gsl_matrix_free(Q); } void MatArrRandomWithRank(int32_t nr, int32_t nc, int32_t rank, const gsl_rng *rng, double *d) { assert(rank <= nr && rank <= nc); MatArrZero(nr, nc, d); double *u = (double *)malloc((size_t)nr * sizeof(*d)); double *v = (double *)malloc((size_t)nc * sizeof(*d)); for (int32_t k = 0; k < rank; ++k) { MatArrRandomGaussian(1, nr, rng, u); MatArrRandomGaussian(1, nc, rng, v); for (int32_t i = 0; i < nr; ++i) { for (int32_t j = 0; j < nc; ++j) { d[i*nc + j] += u[i] * v[j]; } } } free(u); free(v); }
{ "alphanum_fraction": 0.6497302158, "avg_line_length": 30.0540540541, "ext": "c", "hexsha": "bccab2b3bf2704f908ff1e7d8c56e635edfe64f3", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "lib/util/random_matrix.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "lib/util/random_matrix.c", "max_line_length": 75, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "lib/util/random_matrix.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 678, "size": 2224 }
#pragma once #include <gsl.h> #include <boost/graph/graph_traits.hpp> #include <boost/range/adaptor/filtered.hpp> #include "VesselForestData.h" namespace crimson { struct ActiveVesselsFilter { ActiveVesselsFilter() = default; ActiveVesselsFilter(const VesselForestData* owner) : _owner(owner) { } bool operator()(const VesselForestData::VesselPathUIDType& uid) const { return _owner->getVesselUsedInBlending(uid); } private: const VesselForestData* _owner = nullptr; }; struct ActiveBooleanOperationsFilter { ActiveBooleanOperationsFilter() = default; ActiveBooleanOperationsFilter(const VesselForestData* owner) : _owner(owner) { } bool operator()(const VesselForestData::BooleanOperationInfo& bop) const { return _owner->getVesselUsedInBlending(bop.vessels.first) && _owner->getVesselUsedInBlending(bop.vessels.second); } private: const VesselForestData* _owner; }; struct OutEdgeIteratorFilter { OutEdgeIteratorFilter() = default; OutEdgeIteratorFilter(const VesselForestData::VesselPathUIDType* uid) : _uid(uid) { } bool operator()(const VesselForestData::BooleanOperationInfo& bop) const { return bop.vessels.first == *_uid || bop.vessels.second == *_uid; } private: const VesselForestData::VesselPathUIDType* _uid = nullptr; }; struct ExtractOutEdgeFromBooleanOperationInfo { ExtractOutEdgeFromBooleanOperationInfo() = default; ExtractOutEdgeFromBooleanOperationInfo(const VesselForestData::VesselPathUIDType* sourceVertexUID) : _sourceVertexUID(sourceVertexUID) { } VesselForestData::VesselPathUIDPair operator()(const VesselForestData::BooleanOperationInfo& bop) const { if (*_sourceVertexUID == bop.vessels.first) { return bop.vessels; } Expects(*_sourceVertexUID == bop.vessels.second); return std::make_pair(bop.vessels.second, bop.vessels.first); } private: const VesselForestData::VesselPathUIDType* _sourceVertexUID; }; } // namespace crimson namespace boost { template <> struct graph_traits<crimson::VesselForestData> { ///////////////////////////////// // Graph concept ///////////////////////////////// using vertex_descriptor = crimson::VesselForestData::VesselPathUIDType; using edge_descriptor = crimson::VesselForestData::VesselPathUIDPair; using directed_category = boost::undirected_tag; using edge_parallel_category = boost::disallow_parallel_edge_tag; struct traversal_category : boost::vertex_list_graph_tag, boost::incidence_graph_tag { }; ///////////////////////////////// // Incidence graph concept ///////////////////////////////// using out_edge_iterator = boost::transform_iterator< crimson::ExtractOutEdgeFromBooleanOperationInfo, boost::filter_iterator< crimson::OutEdgeIteratorFilter, boost::filter_iterator<crimson::ActiveBooleanOperationsFilter, crimson::VesselForestData::BooleanOperationContainerType::const_iterator>>>; using degree_size_type = std::size_t; // out_edges(v, g) // source(e, g) // target(e, g) // out_degree(v, g) ///////////////////////////////// // Vertex list graph concept ///////////////////////////////// using vertex_iterator = boost::filter_iterator<crimson::ActiveVesselsFilter, crimson::VesselForestData::VesselPathUIDContainerType::const_iterator>; using vertices_size_type = crimson::VesselForestData::VesselPathUIDContainerType::size_type; // vertices(g) // num_vertices(g) static vertex_descriptor null_vertex() { return {}; } }; } // namespace boost namespace crimson { inline boost::graph_traits<crimson::VesselForestData>::vertex_descriptor source(const boost::graph_traits<crimson::VesselForestData>::edge_descriptor& e, const crimson::VesselForestData& g) { return e.first; } inline boost::graph_traits<crimson::VesselForestData>::vertex_descriptor target(const boost::graph_traits<crimson::VesselForestData>::edge_descriptor& e, const crimson::VesselForestData& g) { return e.second; } inline std::pair<boost::graph_traits<crimson::VesselForestData>::out_edge_iterator, boost::graph_traits<crimson::VesselForestData>::out_edge_iterator> out_edges(const boost::graph_traits<crimson::VesselForestData>::vertex_descriptor& v, const crimson::VesselForestData& g) { auto filtIter1 = boost::make_filter_iterator(crimson::ActiveBooleanOperationsFilter{&g}, g.getBooleanOperations().begin(), g.getBooleanOperations().end()); auto endFiltIter1 = boost::make_filter_iterator(crimson::ActiveBooleanOperationsFilter{&g}, g.getBooleanOperations().end(), g.getBooleanOperations().end()); auto filtIter2 = boost::make_filter_iterator(crimson::OutEdgeIteratorFilter{&v}, filtIter1, endFiltIter1); auto endFiltIter2 = boost::make_filter_iterator(crimson::OutEdgeIteratorFilter{&v}, endFiltIter1, endFiltIter1); return {boost::make_transform_iterator(filtIter2, crimson::ExtractOutEdgeFromBooleanOperationInfo{&v}), boost::make_transform_iterator(endFiltIter2, crimson::ExtractOutEdgeFromBooleanOperationInfo{&v})}; } inline boost::graph_traits<crimson::VesselForestData>::degree_size_type out_degree(const boost::graph_traits<crimson::VesselForestData>::vertex_descriptor& v, const crimson::VesselForestData& g) { auto iterPair = out_edges(v, g); return static_cast<boost::graph_traits<crimson::VesselForestData>::degree_size_type>( std::distance(iterPair.first, iterPair.second)); } inline std::pair<boost::graph_traits<crimson::VesselForestData>::vertex_iterator, boost::graph_traits<crimson::VesselForestData>::vertex_iterator> vertices(const crimson::VesselForestData& g) { auto iter = boost::make_filter_iterator(crimson::ActiveVesselsFilter{&g}, g.getVessels().begin(), g.getVessels().end()); auto endIter = boost::make_filter_iterator(crimson::ActiveVesselsFilter{&g}, g.getVessels().end(), g.getVessels().end()); return {iter, endIter}; } inline boost::graph_traits<crimson::VesselForestData>::vertices_size_type num_vertices(const crimson::VesselForestData& g) { auto iterPair = vertices(g); return static_cast<boost::graph_traits<crimson::VesselForestData>::vertices_size_type>( std::distance(iterPair.first, iterPair.second)); } // static void _test_vertex_list_graph_concept() //{ // BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<crimson::VesselForestData>)); // BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept<crimson::VesselForestData>)); //} } // namespace crimson
{ "alphanum_fraction": 0.7027737226, "avg_line_length": 36.6310160428, "ext": "h", "hexsha": "219a18a052a50b232a961f9faab9cd3f7fe956e7", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_line_length": 127, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Modules/VesselTree/DataManagement/VesselForestDataGraphTraits.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 1615, "size": 6850 }
#pragma once #include <cstdint> #include <functional> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "chainerx/array_body.h" #include "chainerx/array_fwd.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/graph.h" #include "chainerx/macro.h" #include "chainerx/shape.h" namespace chainerx { class BackwardContext; class Device; using BackwardFunction = std::function<void(BackwardContext&)>; namespace internal { class ArrayNode; class OpNode; struct ArrayProps { explicit ArrayProps(const Array& array); explicit ArrayProps(const ArrayNode& array_node); explicit ArrayProps(const ArrayBody& array_body); Shape shape; Dtype dtype; Device& device; }; class OpNodeBackwardEntry { public: OpNodeBackwardEntry(OpNode& op_node, std::vector<size_t> input_array_node_indices, BackwardFunction backward_func); OpNode& op_node() const { return op_node_; } size_t input_array_node_count() const { return input_array_node_indices_.size(); } const std::vector<size_t>& input_array_node_indices() const { return input_array_node_indices_; } const BackwardFunction& backward_func() const { return backward_func_; } private: friend class OpNode; OpNode& op_node_; // The index mapping from local (this backward function) to global (op node). // Can be unset if the input array does not require grad. std::vector<size_t> input_array_node_indices_; BackwardFunction backward_func_; }; // Creates an output array node at the specified index and adds edges between the output array node and the op node. // Undefined behavior if the output array node already exists. // This function is used by BackwardContext::GetRetainedOutput(). std::shared_ptr<ArrayNode> FabricateOutputArrayNode(std::shared_ptr<OpNode> op_node, size_t output_array_node_index); class OpNode { public: // Creates a new op node that has output array nodes corresponding to the given outputs. static std::shared_ptr<OpNode> CreateWithOutputArrayNodes( std::string name, BackpropId backprop_id, size_t input_count, const std::vector<ConstArrayRef>& outputs); OpNode(const OpNode&) = delete; OpNode(OpNode&&) = delete; OpNode& operator=(const OpNode&) = delete; OpNode& operator=(OpNode&&) = delete; OpNodeBackwardEntry& RegisterBackwardFunction( std::vector<std::tuple<size_t, std::shared_ptr<ArrayNode>>> input_array_nodes, BackwardFunction backward_func); // Adds links to input array nodes of other graphs. // The size of the vector must be equal to the number of inputs. void AddEdgesToInputArrayNodesOfOuterGraph( const BackpropId& outer_backprop_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_input_array_nodes); // Adds links to output array nodes of other graphs. // The size of the vector must be equal to the number of outputs. void AddEdgesToOutputArrayNodesOfOuterGraph( const BackpropId& outer_backprop_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_output_array_nodes); void Unchain() { backward_entries_.clear(); std::fill(input_array_nodes_.begin(), input_array_nodes_.end(), std::shared_ptr<ArrayNode>{}); AssertConsistency(); } bool HasInputArrayNode(size_t input_index) const { return input_array_nodes_[input_index] != nullptr; } std::string name() const { return name_; } std::vector<std::shared_ptr<ArrayNode>>& input_array_nodes(); const std::vector<std::shared_ptr<ArrayNode>>& input_array_nodes() const; gsl::span<OpNodeBackwardEntry> backward_entries() { return backward_entries_; } gsl::span<const OpNodeBackwardEntry> backward_entries() const { return backward_entries_; } size_t input_array_node_count() const { return input_array_nodes_.size(); } size_t output_array_node_count() const { return output_array_props_.size(); } int64_t rank() const { return rank_; } BackpropId backprop_id() const { return backprop_id_; } const ArrayProps& GetOutputArrayProps(size_t i) const { CHAINERX_ASSERT(i < output_array_props_.size()); return output_array_props_[i]; } // Returns the list of output array nodes on "this" graph. const std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>>& output_array_nodes() const { return output_array_nodes_; } // Returns the list of output array nodes on "this" graph. std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>>& output_array_nodes() { return output_array_nodes_; } // Returns the input array nodes of all graphs. const std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>>& outer_graphs_input_array_nodes() const { return outer_graphs_input_array_nodes_; } // Returns the output array nodes of all graphs. const std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>>& outer_graphs_output_array_nodes() const { return outer_graphs_output_array_nodes_; } private: OpNode(std::string name, BackpropId backprop_id, size_t input_array_node_count); void AssertConsistency() const; std::string name_; // Backprop ID. // Backprop ID is also held in the first entry of output_array_nodes_, but the reference to it may be invalidated, whereas this member // is stable during the lifetime of this OpNode instance. BackpropId backprop_id_; int64_t rank_{0}; // List of input array nodes. std::vector<std::shared_ptr<ArrayNode>> input_array_nodes_; // List of output array nodes of this graph. std::vector<nonstd::optional<std::weak_ptr<ArrayNode>>> output_array_nodes_; // List of input/output array nodes of outer graphs. // Outer graphs refer to graphs with lower ordinals. // Each entry is a pair of backprop ID and list of input/output array nodes. std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>> outer_graphs_input_array_nodes_; std::vector<std::tuple<BackpropId, std::vector<std::shared_ptr<ArrayNode>>>> outer_graphs_output_array_nodes_; // Array props of output array nodes. This is used for creating dummy gradients. std::vector<ArrayProps> output_array_props_; std::vector<OpNodeBackwardEntry> backward_entries_; }; } // namespace internal } // namespace chainerx
{ "alphanum_fraction": 0.7361906235, "avg_line_length": 36.308988764, "ext": "h", "hexsha": "d2668613609bbd5553084346eb4cf5a25752b1dc", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-05-28T22:43:34.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-28T22:43:34.000Z", "max_forks_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nolfwin/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/op_node.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088", "max_issues_repo_issues_event_max_datetime": "2019-05-15T07:12:49.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-14T15:45:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "nolfwin/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/op_node.h", "max_line_length": 138, "max_stars_count": 1, "max_stars_repo_head_hexsha": "15d475f54fc39587abd7264808c5e4b33782df9e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yuhonghong66/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/op_node.h", "max_stars_repo_stars_event_max_datetime": "2019-02-14T09:18:32.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-14T09:18:32.000Z", "num_tokens": 1510, "size": 6463 }
/* eigen/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_test.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_complex_math.h> #include "gsl_eigen.h" gsl_matrix * create_hilbert_matrix(int size) { int 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_random_symm_matrix(int size) { int i, j; unsigned long k = 1; gsl_matrix * m = gsl_matrix_alloc(size, size); for(i=0; i<size; i++) { for(j=i; j<size; j++) { double x; k = (69069 * k + 1) & 0xffffffffUL; x = k / 4294967296.0; gsl_matrix_set(m, i, j, x); gsl_matrix_set(m, j, i, x); } } return m; } gsl_matrix_complex * create_random_herm_matrix(int size) { int i, j; unsigned long k = 1; gsl_matrix_complex * m = gsl_matrix_complex_alloc(size, size); for(i=0; i<size; i++) { for(j=i; j<size; j++) { gsl_complex z; k = (69069 * k + 1) & 0xffffffffUL; GSL_REAL(z) = k / 4294967296.0; k = (69069 * k + 1) & 0xffffffffUL; GSL_IMAG(z) = (i == j) ? 0 : k / 4294967296.0; gsl_matrix_complex_set(m, i, j, z); gsl_matrix_complex_set(m, j, i, gsl_complex_conjugate(z)); } } return m; } void test_eigen_results (size_t N, const gsl_matrix * m, const gsl_vector * eval, const gsl_matrix * evec, const char * desc, const char * desc2) { size_t i,j; gsl_vector * x = gsl_vector_alloc(N); gsl_vector * y = gsl_vector_alloc(N); /* check eigenvalues */ for (i = 0; i < N; i++) { double ei = gsl_vector_get (eval, i); gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); gsl_vector_memcpy(x, &vi.vector); /* compute y = m x (should = lambda v) */ gsl_blas_dgemv (CblasNoTrans, 1.0, m, x, 0.0, y); for (j = 0; j < N; j++) { double xj = gsl_vector_get (x, j); double yj = gsl_vector_get (y, j); gsl_test_rel(yj, ei * xj, 1e8 * GSL_DBL_EPSILON, "%s, eigenvalue(%d,%d), %s", desc, i, j, desc2); } } /* check eigenvectors are orthonormal */ for (i = 0; i < N; i++) { gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); double nrm_v = gsl_blas_dnrm2(&vi.vector); gsl_test_rel (nrm_v, 1.0, N * GSL_DBL_EPSILON, "%s, normalized(%d), %s", desc, i, desc2); } for (i = 0; i < N; i++) { gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); for (j = i + 1; j < N; j++) { gsl_vector_const_view vj = gsl_matrix_const_column(evec, j); double vivj; gsl_blas_ddot (&vi.vector, &vj.vector, &vivj); gsl_test_abs (vivj, 0.0, N * GSL_DBL_EPSILON, "%s, orthogonal(%d,%d), %s", desc, i, j, desc2); } } gsl_vector_free(x); gsl_vector_free(y); } void test_eigenvalues (size_t N, const gsl_vector *eval, const gsl_vector * eval2, const char * desc, const char * desc2) { size_t i; for (i = 0; i < N; i++) { double ei = gsl_vector_get (eval, i); double e2i = gsl_vector_get (eval2, i); gsl_test_rel(ei, e2i, GSL_DBL_EPSILON, "%s, direct eigenvalue(%d), %s", desc, i, desc2); } } void test_eigen_complex_results (size_t N, const gsl_matrix_complex * m, const gsl_vector * eval, const gsl_matrix_complex * evec, const char * desc, const char * desc2) { size_t i,j; gsl_vector_complex * x = gsl_vector_complex_alloc(N); gsl_vector_complex * y = gsl_vector_complex_alloc(N); /* check eigenvalues */ for (i = 0; i < N; i++) { double ei = gsl_vector_get (eval, i); gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i); gsl_vector_complex_memcpy(x, &vi.vector); /* compute y = m x (should = lambda v) */ gsl_blas_zgemv (CblasNoTrans, GSL_COMPLEX_ONE, m, x, GSL_COMPLEX_ZERO, y); for (j = 0; j < N; j++) { gsl_complex xj = gsl_vector_complex_get (x, j); gsl_complex yj = gsl_vector_complex_get (y, j); gsl_test_rel(GSL_REAL(yj), ei * GSL_REAL(xj), 1e8*GSL_DBL_EPSILON, "%s, eigenvalue(%d,%d), real, %s", desc, i, j, desc2); gsl_test_rel(GSL_IMAG(yj), ei * GSL_IMAG(xj), 1e8*GSL_DBL_EPSILON, "%s, eigenvalue(%d,%d), imag, %s", desc, i, j, desc2); } } /* check eigenvectors are orthonormal */ for (i = 0; i < N; i++) { gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i); double nrm_v = gsl_blas_dznrm2(&vi.vector); gsl_test_rel (nrm_v, 1.0, N * GSL_DBL_EPSILON, "%s, normalized(%d), %s", desc, i, desc2); } for (i = 0; i < N; i++) { gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i); for (j = i + 1; j < N; j++) { gsl_vector_complex_const_view vj = gsl_matrix_complex_const_column(evec, j); gsl_complex vivj; gsl_blas_zdotc (&vi.vector, &vj.vector, &vivj); gsl_test_abs (gsl_complex_abs(vivj), 0.0, N * GSL_DBL_EPSILON, "%s, orthogonal(%d,%d), %s", desc, i, j, desc2); } } gsl_vector_complex_free(x); gsl_vector_complex_free(y); } void test_eigen_symm(const char * desc, const gsl_matrix * m) { size_t N = m->size1; gsl_matrix * A = gsl_matrix_alloc(N, N); gsl_matrix * evec = gsl_matrix_alloc(N, N); gsl_vector * eval = gsl_vector_alloc(N); gsl_vector * eval2 = gsl_vector_alloc(N); gsl_eigen_symm_workspace * w1 = gsl_eigen_symm_alloc (N); gsl_eigen_symmv_workspace * w2 = gsl_eigen_symmv_alloc (N); gsl_matrix_memcpy(A, m); gsl_eigen_symmv(A, eval, evec, w2); test_eigen_results (N, m, eval, evec, desc, "unsorted"); gsl_matrix_memcpy(A, m); gsl_eigen_symm(A, eval2, w1); test_eigenvalues (N, eval, eval2, desc, "unsorted"); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC); test_eigen_results (N, m, eval, evec, desc, "val/asc"); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_DESC); test_eigen_results (N, m, eval, evec, desc, "val/desc"); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); test_eigen_results (N, m, eval, evec, desc, "abs/asc"); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_DESC); test_eigen_results (N, m, eval, evec, desc, "abs/desc"); gsl_eigen_symm_free (w1); gsl_eigen_symmv_free (w2); gsl_matrix_free(A); gsl_matrix_free(evec); gsl_vector_free(eval); gsl_vector_free(eval2); } void test_eigen_herm(const char * desc, const gsl_matrix_complex * m) { size_t N = m->size1; gsl_matrix_complex * A = gsl_matrix_complex_alloc(N, N); gsl_matrix_complex * evec = gsl_matrix_complex_alloc(N, N); gsl_vector * eval = gsl_vector_alloc(N); gsl_vector * eval2 = gsl_vector_alloc(N); gsl_eigen_herm_workspace * w1 = gsl_eigen_herm_alloc (N); gsl_eigen_hermv_workspace * w2 = gsl_eigen_hermv_alloc (N); gsl_matrix_complex_memcpy(A, m); gsl_eigen_hermv(A, eval, evec, w2); test_eigen_complex_results (N, m, eval, evec, desc, "unsorted"); gsl_matrix_complex_memcpy(A, m); gsl_eigen_herm(A, eval2, w1); test_eigenvalues (N, eval, eval2, desc, "unsorted"); gsl_eigen_hermv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC); test_eigen_complex_results (N, m, eval, evec, desc, "val/asc"); gsl_eigen_hermv_sort (eval, evec, GSL_EIGEN_SORT_VAL_DESC); test_eigen_complex_results (N, m, eval, evec, desc, "val/desc"); gsl_eigen_hermv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); test_eigen_complex_results (N, m, eval, evec, desc, "abs/asc"); gsl_eigen_hermv_sort (eval, evec, GSL_EIGEN_SORT_VAL_DESC); test_eigen_complex_results (N, m, eval, evec, desc, "abs/desc"); gsl_eigen_herm_free (w1); gsl_eigen_hermv_free (w2); gsl_matrix_complex_free(A); gsl_matrix_complex_free(evec); gsl_vector_free(eval); gsl_vector_free(eval2); } void test_eigen_jacobi(const char * desc, const gsl_matrix * m) { size_t N = m->size1; unsigned int nrot; gsl_matrix * A = gsl_matrix_alloc(N, N); gsl_matrix * evec = gsl_matrix_alloc(N, N); gsl_vector * eval = gsl_vector_alloc(N); gsl_matrix_memcpy(A, m); gsl_eigen_jacobi(A, eval, evec, 1000, &nrot); gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); test_eigen_results (N, m, eval, evec, desc, ""); gsl_matrix_free(A); gsl_matrix_free(evec); gsl_vector_free(eval); } int test_invert_jacobi(void) { int s = 0; int i, j; gsl_matrix * hminv = gsl_matrix_alloc(10, 10); gsl_matrix * id = gsl_matrix_alloc(10, 10); /* 10x10 Hilbert matrix */ gsl_matrix * hm = create_hilbert_matrix(10); gsl_eigen_invert_jacobi(hm, hminv, 1000); /* gsl_linalg_matmult(hm, hminv, id); */ gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, hm, hminv, 0.0, id); for(i=0; i<10; i++) { for(j=0; j<10; j++) { double delta_ij = ( i == j ? 1.0 : 0.0 ); double id_ij = gsl_matrix_get(id, i, j); int rs = ( fabs(id_ij - delta_ij) > 5.0e-3 ); s += rs; } } gsl_matrix_free(hm); gsl_matrix_free(hminv); gsl_matrix_free(id); return s; } int main() { gsl_matrix *rs10 = create_random_symm_matrix (10); gsl_matrix_complex *rh10 = create_random_herm_matrix (10); double r[] = { 0, 0, -1, 0, 0, 1, 0, 1, -1, 0, 0, 0, 0, 1, 0, 0 }; double c[] = { 0,0, 0,0, -1,0, 0,0, 0,0, 1,0, 0,0, 1,0, -1,0, 0,0, 0,0, 0,0, 0,0, 1,0, 0,0, 0,0 }; gsl_matrix_view s4 = gsl_matrix_view_array (r, 4, 4); gsl_matrix_complex_view h4 = gsl_matrix_complex_view_array (c, 4, 4); gsl_ieee_env_setup (); test_eigen_symm("symm(4)", &s4.matrix); test_eigen_herm("herm(4)", &h4.matrix); test_eigen_symm("symm(10)", rs10); test_eigen_herm("herm(10)", rh10); /* gsl_matrix *h5 = create_hilbert_matrix (5); */ /* test_eigen_jacobi("hilbert(5)", h5); */ /* test_invert_jacobi(); */ /* gsl_matrix_free (h5); */ gsl_matrix_complex_free (rh10); gsl_matrix_free (rs10); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.621784104, "avg_line_length": 29.0025641026, "ext": "c", "hexsha": "c48e1bd528632bc94c741bc9fccca1ca4332eae6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/eigen/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/eigen/test.c", "max_line_length": 82, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/eigen/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": 3662, "size": 11311 }
#ifndef PROBABILITY_MODEL_H #define PROBABILITY_MODEL_H #include <vector> #include <gsl/gsl_sf_gamma.h> #include "data_input.h" using namespace std; class probability_model { public: probability_model( unsigned long int end, unsigned long int diff); virtual ~probability_model(); virtual double calculate_log_likelihood( const unsigned long int & position1, const unsigned long int & position2 ) = 0; virtual double calculate_log_likelihood( const vector< double > & ) = 0; unsigned long int get_diff() {return m_diff;} virtual void print_data() = 0; //virtual double calculate_total_log_likelihood() = 0; void get_cumulative_sufficient_data(const unsigned long int & time, vector< double > & sufficient_data); virtual void get_number_of_observations(const vector< double > & sufficient_stats, double & number_of_observations) = 0; // calculate the number of observations given a set of sufficient statistics unsigned long int m_end; unsigned long int m_diff; data_input * m_data; }; probability_model::probability_model( unsigned long int end, unsigned long int diff ):m_end( end ), m_diff( diff){ } probability_model::~probability_model(){ } void probability_model::get_cumulative_sufficient_data(const unsigned long int & time, vector< double > & sufficient_data){ m_data->get_cumulative_data_row(time, sufficient_data); } #endif
{ "alphanum_fraction": 0.7404047453, "avg_line_length": 36.7435897436, "ext": "h", "hexsha": "398053ba203acb95375643df4a8d8fde0c636515", "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": "759724c67f12db9155f83dd7dd8f63d526ecbd79", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AlexanderDBolton/Regimes_RJMCMC", "max_forks_repo_path": "Code/basic_probability_model.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "759724c67f12db9155f83dd7dd8f63d526ecbd79", "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": "AlexanderDBolton/Regimes_RJMCMC", "max_issues_repo_path": "Code/basic_probability_model.h", "max_line_length": 202, "max_stars_count": null, "max_stars_repo_head_hexsha": "759724c67f12db9155f83dd7dd8f63d526ecbd79", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AlexanderDBolton/Regimes_RJMCMC", "max_stars_repo_path": "Code/basic_probability_model.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 307, "size": 1433 }
# ifndef CELL_CYCLE_H # define CELL_CYCLE_H #include <vector> #include <deque> #include <string> #include <memory> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> using namespace std; #define CONSTANT_PHASE 0 #define EXPONENTIAL_PHASE 1 #endif ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// class cell_cycle{//Class containing behaviour related to cell_cycle. //////////// ////////// private: int cell_state; // current state of the cycle double time_state; // current time in the state of the cycle double time_cycle; // total time in this cell_cycle double currentPhaseDuration; // time for the next phase vector<double> state_durations; // array with the cell states durations vector<int> state_types; // array with the cell phases types (exponential, uniform, ... ) int divisions; // number of divisions so far int num_states; // total number of cell phases included bool divide_material; // flag to see if the species in the cell are dividied after cell division gsl_rng * rng; // allocator for the rng generator public: cell_cycle(){ // default constructor is a constructor with empty info time_state = 0; time_cycle = 0; divisions = 0; cell_state = 0; num_states = 0; rng= gsl_rng_alloc (gsl_rng_mt19937); gsl_rng_set (rng,::time(NULL)*getpid()); } void addCellPhase(double duration, int type_phase){ cout<<"Adding Cell Phase of duration"<< duration<<" \n"; state_durations.push_back(duration); state_types.push_back(type_phase); num_states++; if (num_states == 1){// if this is the first state set, also use it for the current cell cycle time getPhaseDuration(); } cout<<"Cell Phase added\n"; } void ResetCellCycle(){ time_state = 0; time_cycle = 0; cell_state = 0; getPhaseDuration(); divisions = 0; divide_material = false; } // cell_cycle(int nstates,float duration, int type){ // // The default constructor generates n cycle phases with same duration of certain type // time_state = 0; // time_cycle = 0; // divisions = 0; // cell_state = 0; // num_states = nstates; // state_durations = new double[num_states]; // state_types = new int[num_states]; // for(int i=0;i<nstates;i++){ // state_durations[i] = duration; // state_types[i] = type; // } // } void setPhaseDuration(int phase, double duration, int type_phase){ state_durations[phase] = duration; state_types[phase] = type_phase; } double getPhaseDuration(){ // compute the value of the time for the next phase and store it in NextPhaseTime to avoid recomputing if (state_types[cell_state] == CONSTANT_PHASE){ currentPhaseDuration = state_durations[cell_state]; } else if (state_types[cell_state] == EXPONENTIAL_PHASE){ currentPhaseDuration = state_durations[cell_state] * log(1.0/gsl_rng_uniform_pos(rng)); } // cout<<"Next Phase duration: "<<currentPhaseDuration<<'\n'; return currentPhaseDuration; } double getTimeForNextCellPhase(){ return currentPhaseDuration - time_state; } int AdvanceNextPhase(){ cell_state++; if (cell_state==num_states){// if the cell reaches the final state cell_state = 0; time_cycle = 0; } time_state = 0; getPhaseDuration(); if (cell_state == 0){ // if we are dividing divisions += 1; divide_material = true; } else{ divide_material = false; } return cell_state; } bool MaterialIsDivided(){ return divide_material; } void updateCelltime(double time){ time_cycle += time; time_state += time; } void setCellCyclePositionTime(int phase, double time){ cell_state = phase; time_state = time; time_cycle = time; } void printCellProperties(){ cout<<"total states "<<num_states<<'\n'; cout<<"of duration "; for (auto d: state_durations){ cout << d << ' ';}; cout<<"\n of type"; for (auto d: state_types){ cout << d << ' ';}; cout<<'\n'; } int getCellPhase(){ return cell_state; } double getPhaseTime(){ return time_state; } void PrintState(){ cout<< "cell state: "<<cell_state<< " time_state: "<<time_state<<'\n'; cout<< "currentPhaseDuration: "<<currentPhaseDuration<<'\n'; printCellProperties(); cout<< "time cell has divided: "<<divisions<<'\n'; cout<< "cell is ready for division: "<< divide_material<<'\n'; } };
{ "alphanum_fraction": 0.6505675495, "avg_line_length": 26.9041916168, "ext": "h", "hexsha": "16d685cf338263b957cdb7d4d4c9ef7bbed5b8c0", "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": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "2piruben/langil", "max_forks_repo_path": "cell_cycle.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "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": "2piruben/langil", "max_issues_repo_path": "cell_cycle.h", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "2piruben/langil", "max_stars_repo_path": "cell_cycle.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1189, "size": 4493 }
#include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sum.h> #define N 20 int main (void) { double t[N]; double sum_accel, err; double sum = 0; int n; gsl_sum_levin_u_workspace * w = gsl_sum_levin_u_alloc (N); const double zeta_2 = M_PI * M_PI / 6.0; /* terms for zeta(2) = \sum_{n=1}^{\infty} 1/n^2 */ for (n = 0; n < N; n++) { double np1 = n + 1.0; t[n] = 1.0 / (np1 * np1); sum += t[n]; } gsl_sum_levin_u_accel (t, N, w, &sum_accel, &err); printf ("term-by-term sum = % .16f using %d terms\n", sum, N); printf ("term-by-term sum = % .16f using %zu terms\n", w->sum_plain, w->terms_used); printf ("exact value = % .16f\n", zeta_2); printf ("accelerated sum = % .16f using %zu terms\n", sum_accel, w->terms_used); printf ("estimated error = % .16f\n", err); printf ("actual error = % .16f\n", sum_accel - zeta_2); gsl_sum_levin_u_free (w); return 0; }
{ "alphanum_fraction": 0.55, "avg_line_length": 20.8333333333, "ext": "c", "hexsha": "65dacc96557f0c78f2d93d927ebf3fd6d3e83099", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/sum.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/sum.c", "max_line_length": 57, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/sum.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": 362, "size": 1000 }
#pragma once #include <memory> #include <string> #include <gsl/gsl> #include "chainerx/backend.h" #include "chainerx/device.h" #include "chainerx/kernel_registry.h" namespace chainerx { namespace native { class NativeDevice; class NativeBackend; namespace native_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 internal namespace in order to make it a friend of NativeDevice // class. NativeDevice* CreateDevice(NativeBackend& backend, int index); } // namespace native_internal class NativeBackend : public Backend { public: static constexpr const char* kDefaultName = "native"; using Backend::Backend; std::string GetName() const override; int GetDeviceCount() const override; bool SupportsTransfer(Device& src_device, Device& dst_device) override; 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; }; } // namespace native } // namespace chainerx
{ "alphanum_fraction": 0.7473363775, "avg_line_length": 24.3333333333, "ext": "h", "hexsha": "cb9ab4b2ff9e88987e59618b36d86e97d9f9c0cc", "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/native/native_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/native/native_backend.h", "max_line_length": 92, "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/native/native_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": 282, "size": 1314 }
#ifndef _fim_h_included_ #define _fim_h_included_ #include <assert.h> #include <stdlib.h> #include <algorithm> #include <cctype> #include <fstream> #include <functional> #include <iostream> #include <map> #include <numeric> #include <set> #include <sstream> #include <vector> #include <sstream> #include <string> #include <boost/config.hpp> #include <boost/foreach.hpp> #include <boost/random.hpp> #include <boost/shared_ptr.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <boost/numeric/ublas/io.hpp> #include <jsc/bioinfo/gene_anno.hpp> #include <jsc/util/log.hpp> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "splicing_graph.h" #include "read.h" #include "linalg.h" #include "accessible_read_starts.h" using namespace std; using namespace boost; using namespace boost::numeric; using namespace jsc::bioinfo; using namespace jsc::util; class FIM { public: FIM () { ofim_call_count = 0; } double get_ofim_call_count() const { return ofim_call_count; }; static double estimate_mle_variance( ublas::matrix<double> const & I) { return estimate_mle_variance_by_diag(I); } static double estimate_mle_variance_by_diag( ublas::matrix<double> const & I) { unsigned long K = I.size1() + 1; double sum = 0; for (unsigned long p = 0; p < K - 1; ++p) { sum += 1.0 / I(p,p); } return sum; } static double estimate_mle_variance_by_inv( ublas::matrix<double> const & I) { assert(I.size1() == I.size2()); L_(debug) << I; ublas::matrix<double> inv = ublas::zero_matrix<double>(I.size1(), I.size1()); linalg::invert_matrix(I, inv); L_(debug) << inv; unsigned long K = I.size1() + 1; double sum = 0; for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { sum += inv(p,q); } sum += inv(p,p); } return sum; } static void print_fim_for_R(ostream & os, ublas::matrix<double> I) { unsigned long K = I.size1() + 1; for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { os << I(p,q) << "\t"; } os << endl; } } static void print_fim_diag_for_R(ostream & os, ublas::matrix<double> I) { unsigned long K = I.size1() + 1; os << "("; for (unsigned long p = 0; p < K - 1; ++p) { os << I(p,p) << ","; } os << ")"; os << endl; } ublas::matrix<double> bruteforce_fim(shared_ptr<Read> readp, vector<double> const & iso_probs) { L_(debug) << "FIM::bruteforce_fim"; reset_ofim_call_count(); shared_ptr<AccessibleReadStarts> ars = readp->get_ARS(); unsigned long K = ars->get_num_isoforms(); ublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1); for (unsigned long k = 0; k < K; ++k) { if (iso_probs[k] == 0) { continue; } ublas::matrix<int> sign; L_(debug) << "Possible Isoform #" << k << ": Generating reads with starts from 0 to " << ars->get_iso_ARS_total_length(k) << " in ARS"; for (unsigned long a = 0; a < ars->get_iso_ARS_total_length(k); ++a) { // generate a read starting from a in ARS readp->generate_read(k, ars->ARStart2IsoStart(k, a)); double G = readp->prob_generated_by_iso(k); double log_scaler = log(G) + log(iso_probs[k]); ublas::matrix<double> m = ofim(readp, iso_probs, sign); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { if (sign(p,q) > 0) { m(p,q) = exp(m(p,q) + log_scaler); } else if (sign(p,q) < 0) { m(p,q) = - exp(m(p,q) + log_scaler); } else { // m(p,q) must be zero, no need to perform scaling } assert(!isinf(m(p,q)) && !isnan(m(p,q))); } } I += m; } } return I; } ublas::matrix<double> fast_fim(shared_ptr<Read> readp, vector<double> const & iso_probs) { L_(debug) << "FIM::fast_fim"; reset_ofim_call_count(); shared_ptr<AccessibleReadStarts> ars = readp->get_ARS(); unsigned long K = ars->get_num_isoforms(); ublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1); for (unsigned long k = 0; k < K; ++k) { if (iso_probs[k] == 0) { continue; } ublas::matrix<int> sign; L_(debug) << "Possible Isoform #" << k << ": Generating reads with starts from 0 to " << ars->get_iso_ARS_total_length(k) << " in ARS"; unsigned long a = 0; while (a < ars->get_iso_ARS_total_length(k)) { // generate a read starting from a readp->generate_read(k, ars->ARStart2IsoStart(k, a)); unsigned long N_overlapping_exons = readp->exon_indices.size(); unsigned long N_eq_samples = min( ars->exon_lengths[readp->exon_indices[0]] - readp->start_at_first_exon, ars->exon_lengths[readp->exon_indices[N_overlapping_exons - 1]] - readp->end_at_last_exon + 1); while ( (a + N_eq_samples - 1 >= ars->get_iso_ARS_total_length(k)) || (ars->ARStart2IsoStart(k, a + N_eq_samples - 1) != (ars->ARStart2IsoStart(k, a) + N_eq_samples - 1)) ){ N_eq_samples--; } double G = readp->prob_generated_by_iso(k); ublas::matrix<double> m = ofim(readp, iso_probs, sign); bool zero_scaler = ((G == 0) || (iso_probs[k] == 0)); double log_scaler = log(N_eq_samples) + log(G) + log(iso_probs[k]); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { if (zero_scaler) { m(p,q) = 0; } else if (sign(p,q) > 0) { m(p,q) = exp(m(p,q) + log_scaler); } else if (sign(p,q) < 0) { m(p,q) = - exp(m(p,q) + log_scaler); } else { // m(p,q) must be zero, no need to perform scaling } assert(!isinf(m(p,q)) && !isnan(m(p,q))); } } I += m; a += N_eq_samples; } } return I; } ublas::matrix<double> faster_fim(shared_ptr<Read> readp, vector<double> const & iso_probs) { L_(debug) << "FIM::faster_fim"; reset_ofim_call_count(); shared_ptr<AccessibleReadStarts> ars = readp->get_ARS(); unsigned long K = ars->get_num_isoforms(); ublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1); vector<interval_list<long > > covered_sample_starts; for (unsigned long k = 0; k < K; ++k) { interval_list<long> il; covered_sample_starts.push_back(il); } for (unsigned long k = 0; k < K; ++k) { if (iso_probs[k] == 0) { continue; } unsigned long a = covered_sample_starts[k].find_min_uncovered(0); L_(debug) << "Possible Isoform #" << k << ": Generating reads with starts from " << a << " to " << ars->get_iso_ARS_total_length(k) << " in ARS"; while (a < ars->get_iso_ARS_total_length(k)) { // generate a read starting from a readp->generate_read(k, ars->ARStart2IsoStart(k, a)); unsigned long N_overlapping_exons = readp->exon_indices.size(); unsigned long N_eq_samples = min( ars->exon_lengths[readp->exon_indices[0]] - readp->start_at_first_exon, ars->exon_lengths[readp->exon_indices[N_overlapping_exons - 1]] - readp->end_at_last_exon + 1); while ( (a + N_eq_samples - 1 >= ars->get_iso_ARS_total_length(k)) || (ars->ARStart2IsoStart(k, a + N_eq_samples - 1) != (ars->ARStart2IsoStart(k, a) + N_eq_samples - 1)) ){ N_eq_samples--; } ublas::matrix<int> sign; ublas::matrix<double> m = ofim(readp, iso_probs, sign); double G = readp->prob_generated_by_iso(k); double scaler = G * N_eq_samples * iso_probs[k]; if (covered_sample_starts[k].compute_overlap(a, a + N_eq_samples) > 0) { L_(debug2) << "Cov for iso # " << k << ": " << covered_sample_starts[k]; L_(error) << "Overlap > 0!"; } covered_sample_starts[k].add_interval(a, a + N_eq_samples); L_(debug2) << "Adding [" << a << "," << (a + N_eq_samples) << ") to possible isoform #" << k; for (unsigned long j = 0; j < K; ++j) { if (j == k) continue; long first_matching_idx = is_connected_exons_compatible_with_isoform( readp->exon_indices, ars->iso_exon_indices[j]); if (first_matching_idx >= 0) { double G_j = readp->prob_generated_by_iso(j); scaler += G_j * N_eq_samples * iso_probs[j]; unsigned long a2 = readp->start_at_first_exon + ars->iso_exon_total_lengths[j][first_matching_idx] - ars->exon_lengths[readp->exon_indices[0]]; a2 = ars->IsoStart2ARStart(j, a2); if (covered_sample_starts[j].compute_overlap(a2, a2 + N_eq_samples) > 0) { L_(debug2) << "Cov for iso # " << j << ": " << covered_sample_starts[j]; L_(error) << "Overlap > 0!"; } covered_sample_starts[j].add_interval(a2, a2 + N_eq_samples); L_(debug2) << "Adding [" << a2 << "," << (a2 + N_eq_samples) << ") to possible isoform #" << j; } } double log_scaler = log(scaler); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { if (sign(p,q) > 0) { m(p,q) = exp(m(p,q) + log_scaler); } else if (sign(p,q) < 0) { m(p,q) = - exp(m(p,q) + log_scaler); } else { // m(p,q) must be zero, no need to perform scaling } assert(!isinf(m(p,q)) && !isnan(m(p,q))); } } I += m; a = covered_sample_starts[k].find_min_uncovered(0); } } return I; } protected: void reset_ofim_call_count() { ofim_call_count = 0; }; // \mathfrak{I}_{s}^{(m)}(\Theta) ublas::matrix<double> ofim(shared_ptr<const Read> readp, vector<double> const & iso_probs, ublas::matrix<int> & sign) { ++ofim_call_count; shared_ptr<AccessibleReadStarts> ars = readp->get_ARS(); unsigned long K = ars->get_num_isoforms(); ublas::matrix<double> m = ublas::zero_matrix<double>(K-1,K-1); sign = ublas::zero_matrix<int>(K-1, K-1); vector<double> v_delta_G(K, 0); for (unsigned long k = 0; k < K; ++k) { if (readp->is_compatible_with_iso(k)) { v_delta_G[k] = readp->prob_generated_by_iso(k); } } double sum = 0; for (unsigned long k = 0; k < K; ++k) { if (v_delta_G[k] > 0 && iso_probs[k] > 0) { sum += iso_probs[k] * v_delta_G[k]; } } assert(sum > 0); double log_prod = log(sum) + log(sum); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { m(p,q) = (v_delta_G[p] - v_delta_G[K - 1])* (v_delta_G[q] - v_delta_G[K - 1]); if (m(p,q) != 0) { sign(p,q) = m(p,q) > 0 ? 1 : -1; if (m(p,q) < 0) { m(p,q) = - m(p,q); } m(p,q) = log(m(p,q)) - log_prod; } } } if (readp->exon_indices[0] == 0 && readp->start_at_first_exon == 2730) { L_(info) << *readp << " " << m(0,0) << " " << sign(0,0); } return m; } private: double ofim_call_count; }; #endif
{ "alphanum_fraction": 0.580866426, "avg_line_length": 29.6256684492, "ext": "h", "hexsha": "67af9c9695e3c256c206f2a9f704104cd9693d31", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_path": "common/fim.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_path": "common/fim.h", "max_line_length": 178, "max_stars_count": 7, "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_path": "common/fim.h", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "num_tokens": 3685, "size": 11080 }
/* linalg/ptlq.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * Copyright (C) 2004 Joerg Wensch, modifications for LQ. * * 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 <string.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_linalg.h> #include "apply_givens.c" /* The purpose of this package is to speed up QR-decomposition for large matrices. Because QR-decomposition is column oriented, but GSL uses a row-oriented matrix format, there can considerable speedup obtained by computing the LQ-decomposition of the transposed matrix instead. This package provides LQ-decomposition and related algorithms. */ /* Factorise a general N x M matrix A into * * P A = L Q * * where Q is orthogonal (M x M) and L is lower triangular (N x M). * When A is rank deficient, r = rank(A) < n, then the permutation is * used to ensure that the lower n - r columns of L are zero and the first * l rows of Q form an orthonormal basis for the rows of A. * * Q is stored as a packed set of Householder transformations in the * strict upper triangular part of the input matrix. * * L is stored in the diagonal and lower triangle of the input matrix. * * P: column j of P is column k of the identity matrix, where k = * permutation->data[j] * * The full matrix for Q can be obtained as the product * * Q = Q_k .. Q_2 Q_1 * * where k = MIN(M,N) and * * Q_i = (I - tau_i * v_i * v_i') * * and where v_i is a Householder vector * * v_i = [1, m(i,i+1), m(i,i+2), ... , m(i,M)] * * This storage scheme is the same as in LAPACK. See LAPACK's * dgeqpf.f for details. * */ int gsl_linalg_PTLQ_decomp (gsl_matrix * A, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm) { const size_t N = A->size1; const size_t M = A->size2; if (tau->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN); } else if (p->size != N) { GSL_ERROR ("permutation size must be N", GSL_EBADLEN); } else if (norm->size != N) { GSL_ERROR ("norm size must be N", GSL_EBADLEN); } else { size_t i; *signum = 1; gsl_permutation_init (p); /* set to identity */ /* Compute column norms and store in workspace */ for (i = 0; i < N; i++) { gsl_vector_view c = gsl_matrix_row (A, i); double x = gsl_blas_dnrm2 (&c.vector); gsl_vector_set (norm, i, x); } for (i = 0; i < GSL_MIN (M, N); i++) { /* Bring the column of largest norm into the pivot position */ double max_norm = gsl_vector_get(norm, i); size_t j, kmax = i; for (j = i + 1; j < N; j++) { double x = gsl_vector_get (norm, j); if (x > max_norm) { max_norm = x; kmax = j; } } if (kmax != i) { gsl_matrix_swap_rows (A, i, kmax); gsl_permutation_swap (p, i, kmax); gsl_vector_swap_elements(norm,i,kmax); (*signum) = -(*signum); } /* Compute the Householder transformation to reduce the j-th column of the matrix to a multiple of the j-th unit vector */ { gsl_vector_view c = gsl_matrix_subrow (A, i, i, M - i); double tau_i = gsl_linalg_householder_transform (&c.vector); gsl_vector_set (tau, i, tau_i); /* Apply the transformation to the remaining columns */ if (i + 1 < N) { gsl_matrix_view m = gsl_matrix_submatrix (A, i +1, i, N - (i+1), M - i); gsl_linalg_householder_mh (tau_i, &c.vector, &m.matrix); } } /* Update the norms of the remaining columns too */ if (i + 1 < M) { for (j = i + 1; j < N; j++) { double x = gsl_vector_get (norm, j); if (x > 0.0) { double y = 0; double temp= gsl_matrix_get (A, j, i) / x; if (fabs (temp) >= 1) y = 0.0; else y = x * sqrt (1 - temp * temp); /* recompute norm to prevent loss of accuracy */ if (fabs (y / x) < sqrt (20.0) * GSL_SQRT_DBL_EPSILON) { gsl_vector_view c = gsl_matrix_subrow (A, j, i + 1, M - (i + 1)); y = gsl_blas_dnrm2 (&c.vector); } gsl_vector_set (norm, j, y); } } } } return GSL_SUCCESS; } } int gsl_linalg_PTLQ_decomp2 (const gsl_matrix * A, gsl_matrix * q, gsl_matrix * r, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm) { const size_t N = A->size1; const size_t M = A->size2; if (q->size1 != M || q->size2 !=M) { GSL_ERROR ("q must be M x M", GSL_EBADLEN); } else if (r->size1 != N || r->size2 !=M) { GSL_ERROR ("r must be N x M", GSL_EBADLEN); } else if (tau->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN); } else if (p->size != N) { GSL_ERROR ("permutation size must be N", GSL_EBADLEN); } else if (norm->size != N) { GSL_ERROR ("norm size must be N", GSL_EBADLEN); } gsl_matrix_memcpy (r, A); gsl_linalg_PTLQ_decomp (r, tau, p, signum, norm); /* FIXME: aliased arguments depends on behavior of unpack routine! */ gsl_linalg_LQ_unpack (r, tau, q, r); return GSL_SUCCESS; } /* Solves the system x^T A = b^T using the P^T L Q factorisation, z^T L = b^T Q^T x = P z; to obtain x. Based on SLATEC code. */ int gsl_linalg_PTLQ_solve_T (const gsl_matrix * QR, const gsl_vector * tau, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x) { if (QR->size1 != QR->size2) { GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR); } else if (QR->size2 != p->size) { GSL_ERROR ("matrix size must match permutation size", GSL_EBADLEN); } else if (QR->size2 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (QR->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { gsl_vector_memcpy (x, b); gsl_linalg_PTLQ_svx_T (QR, tau, p, x); return GSL_SUCCESS; } } int gsl_linalg_PTLQ_svx_T (const gsl_matrix * LQ, const gsl_vector * tau, const gsl_permutation * p, gsl_vector * x) { if (LQ->size1 != LQ->size2) { GSL_ERROR ("LQ matrix must be square", GSL_ENOTSQR); } else if (LQ->size2 != p->size) { GSL_ERROR ("matrix size must match permutation size", GSL_EBADLEN); } else if (LQ->size1 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* compute sol = b^T Q^T */ gsl_linalg_LQ_vecQT (LQ, tau, x); /* Solve L^T x = sol, storing x inplace in sol */ gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x); gsl_permute_vector_inverse (p, x); return GSL_SUCCESS; } } int gsl_linalg_PTLQ_LQsolve_T (const gsl_matrix * Q, const gsl_matrix * L, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x) { if (Q->size1 != Q->size2 || L->size1 != L->size2) { return GSL_ENOTSQR; } else if (Q->size1 != p->size || Q->size1 != L->size1 || Q->size1 != b->size) { return GSL_EBADLEN; } else { /* compute b' = Q b */ gsl_blas_dgemv (CblasNoTrans, 1.0, Q, b, 0.0, x); /* Solve L^T x = b', storing x inplace */ gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, L, x); /* Apply permutation to solution in place */ gsl_permute_vector_inverse (p, x); return GSL_SUCCESS; } } int gsl_linalg_PTLQ_Lsolve_T (const gsl_matrix * LQ, const gsl_permutation * p, const gsl_vector * b, gsl_vector * x) { if (LQ->size1 != LQ->size2) { GSL_ERROR ("LQ matrix must be square", GSL_ENOTSQR); } else if (LQ->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (LQ->size2 != x->size) { GSL_ERROR ("matrix size must match x size", GSL_EBADLEN); } else if (p->size != x->size) { GSL_ERROR ("permutation size must match x size", GSL_EBADLEN); } else { /* Copy x <- b */ gsl_vector_memcpy (x, b); /* Solve L^T x = b, storing x inplace */ gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x); gsl_permute_vector_inverse (p, x); return GSL_SUCCESS; } } int gsl_linalg_PTLQ_Lsvx_T (const gsl_matrix * LQ, const gsl_permutation * p, gsl_vector * x) { if (LQ->size1 != LQ->size2) { GSL_ERROR ("LQ matrix must be square", GSL_ENOTSQR); } else if (LQ->size2 != x->size) { GSL_ERROR ("matrix size must match x size", GSL_EBADLEN); } else if (p->size != x->size) { GSL_ERROR ("permutation size must match x size", GSL_EBADLEN); } else { /* Solve L^T x = b, storing x inplace */ gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x); gsl_permute_vector_inverse (p, x); return GSL_SUCCESS; } } /* Update a P^T L Q factorisation for P A= L Q , A' = A + v u^T, PA' = PA + Pv u^T * P^T L' Q' = P^T LQ + v u^T * = P^T (L + (P v) u^T Q^T) Q * = P^T (L + (P v) w^T) Q * * where w = Q^T u. * * Algorithm from Golub and Van Loan, "Matrix Computations", Section * 12.5 (Updating Matrix Factorizations, Rank-One Changes) */ int gsl_linalg_PTLQ_update (gsl_matrix * Q, gsl_matrix * L, const gsl_permutation * p, const gsl_vector * v, gsl_vector * w) { if (Q->size1 != Q->size2 || L->size1 != L->size2) { return GSL_ENOTSQR; } else if (L->size1 != Q->size2 || v->size != Q->size2 || w->size != Q->size2) { return GSL_EBADLEN; } else { size_t j, k; const size_t N = Q->size1; const size_t M = Q->size2; double w0; /* Apply Given's rotations to reduce w to (|w|, 0, 0, ... , 0) J_1^T .... J_(n-1)^T w = +/- |w| e_1 simultaneously applied to L, H = J_1^T ... J^T_(n-1) L so that H is upper Hessenberg. (12.5.2) */ for (k = M - 1; k > 0; k--) { double c, s; double wk = gsl_vector_get (w, k); double wkm1 = gsl_vector_get (w, k - 1); gsl_linalg_givens (wkm1, wk, &c, &s); gsl_linalg_givens_gv (w, k - 1, k, c, s); apply_givens_lq (M, N, Q, L, k - 1, k, c, s); } w0 = gsl_vector_get (w, 0); /* Add in v w^T (Equation 12.5.3) */ for (j = 0; j < N; j++) { double lj0 = gsl_matrix_get (L, j, 0); size_t p_j = gsl_permutation_get (p, j); double vj = gsl_vector_get (v, p_j); gsl_matrix_set (L, j, 0, lj0 + w0 * vj); } /* Apply Givens transformations L' = G_(n-1)^T ... G_1^T H Equation 12.5.4 */ for (k = 1; k < N; k++) { double c, s; double diag = gsl_matrix_get (L, k - 1, k - 1); double offdiag = gsl_matrix_get (L, k - 1, k ); gsl_linalg_givens (diag, offdiag, &c, &s); apply_givens_lq (M, N, Q, L, k - 1, k, c, s); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.534464313, "avg_line_length": 26.8706365503, "ext": "c", "hexsha": "8c3e74630803bab6d8d430697663827c7b3c8a57", "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/linalg/ptlq.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/linalg/ptlq.c", "max_line_length": 149, "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/linalg/ptlq.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": 3821, "size": 13086 }
/* matrix/gsl_matrix_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_FLOAT_H__ #define __GSL_MATRIX_FLOAT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_float.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; float * data; gsl_block_float * block; int owner; } gsl_matrix_float; typedef struct { gsl_matrix_float matrix; } _gsl_matrix_float_view; typedef _gsl_matrix_float_view gsl_matrix_float_view; typedef struct { gsl_matrix_float matrix; } _gsl_matrix_float_const_view; typedef const _gsl_matrix_float_const_view gsl_matrix_float_const_view; /* Allocation */ GSL_FUN gsl_matrix_float * gsl_matrix_float_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_float * gsl_matrix_float_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_float * gsl_matrix_float_alloc_from_block (gsl_block_float * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix_float * gsl_matrix_float_alloc_from_matrix (gsl_matrix_float * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector_float * gsl_vector_float_alloc_row_from_matrix (gsl_matrix_float * m, const size_t i); GSL_FUN gsl_vector_float * gsl_vector_float_alloc_col_from_matrix (gsl_matrix_float * m, const size_t j); GSL_FUN void gsl_matrix_float_free (gsl_matrix_float * m); /* Views */ GSL_FUN _gsl_matrix_float_view gsl_matrix_float_submatrix (gsl_matrix_float * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_float_view gsl_matrix_float_row (gsl_matrix_float * m, const size_t i); GSL_FUN _gsl_vector_float_view gsl_matrix_float_column (gsl_matrix_float * m, const size_t j); GSL_FUN _gsl_vector_float_view gsl_matrix_float_diagonal (gsl_matrix_float * m); GSL_FUN _gsl_vector_float_view gsl_matrix_float_subdiagonal (gsl_matrix_float * m, const size_t k); GSL_FUN _gsl_vector_float_view gsl_matrix_float_superdiagonal (gsl_matrix_float * m, const size_t k); GSL_FUN _gsl_vector_float_view gsl_matrix_float_subrow (gsl_matrix_float * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_float_view gsl_matrix_float_subcolumn (gsl_matrix_float * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_float_view gsl_matrix_float_view_array (float * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_float_view gsl_matrix_float_view_array_with_tda (float * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_float_view gsl_matrix_float_view_vector (gsl_vector_float * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_float_view gsl_matrix_float_view_vector_with_tda (gsl_vector_float * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_float_const_view gsl_matrix_float_const_submatrix (const gsl_matrix_float * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_row (const gsl_matrix_float * m, const size_t i); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_column (const gsl_matrix_float * m, const size_t j); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_diagonal (const gsl_matrix_float * m); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_subdiagonal (const gsl_matrix_float * m, const size_t k); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_superdiagonal (const gsl_matrix_float * m, const size_t k); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_subrow (const gsl_matrix_float * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_float_const_view gsl_matrix_float_const_subcolumn (const gsl_matrix_float * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_float_const_view gsl_matrix_float_const_view_array (const float * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_float_const_view gsl_matrix_float_const_view_array_with_tda (const float * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_float_const_view gsl_matrix_float_const_view_vector (const gsl_vector_float * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_float_const_view gsl_matrix_float_const_view_vector_with_tda (const gsl_vector_float * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_float_set_zero (gsl_matrix_float * m); GSL_FUN void gsl_matrix_float_set_identity (gsl_matrix_float * m); GSL_FUN void gsl_matrix_float_set_all (gsl_matrix_float * m, float x); GSL_FUN int gsl_matrix_float_fread (FILE * stream, gsl_matrix_float * m) ; GSL_FUN int gsl_matrix_float_fwrite (FILE * stream, const gsl_matrix_float * m) ; GSL_FUN int gsl_matrix_float_fscanf (FILE * stream, gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_fprintf (FILE * stream, const gsl_matrix_float * m, const char * format); GSL_FUN int gsl_matrix_float_memcpy(gsl_matrix_float * dest, const gsl_matrix_float * src); GSL_FUN int gsl_matrix_float_swap(gsl_matrix_float * m1, gsl_matrix_float * m2); GSL_FUN int gsl_matrix_float_swap_rows(gsl_matrix_float * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_float_swap_columns(gsl_matrix_float * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_float_swap_rowcol(gsl_matrix_float * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_float_transpose (gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_transpose_memcpy (gsl_matrix_float * dest, const gsl_matrix_float * src); GSL_FUN float gsl_matrix_float_max (const gsl_matrix_float * m); GSL_FUN float gsl_matrix_float_min (const gsl_matrix_float * m); GSL_FUN void gsl_matrix_float_minmax (const gsl_matrix_float * m, float * min_out, float * max_out); GSL_FUN void gsl_matrix_float_max_index (const gsl_matrix_float * m, size_t * imax, size_t *jmax); GSL_FUN void gsl_matrix_float_min_index (const gsl_matrix_float * m, size_t * imin, size_t *jmin); GSL_FUN void gsl_matrix_float_minmax_index (const gsl_matrix_float * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_FUN int gsl_matrix_float_isnull (const gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_ispos (const gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_isneg (const gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_isnonneg (const gsl_matrix_float * m); GSL_FUN int gsl_matrix_float_add (gsl_matrix_float * a, const gsl_matrix_float * b); GSL_FUN int gsl_matrix_float_sub (gsl_matrix_float * a, const gsl_matrix_float * b); GSL_FUN int gsl_matrix_float_mul_elements (gsl_matrix_float * a, const gsl_matrix_float * b); GSL_FUN int gsl_matrix_float_div_elements (gsl_matrix_float * a, const gsl_matrix_float * b); GSL_FUN int gsl_matrix_float_scale (gsl_matrix_float * a, const double x); GSL_FUN int gsl_matrix_float_add_constant (gsl_matrix_float * a, const double x); GSL_FUN int gsl_matrix_float_add_diagonal (gsl_matrix_float * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_float_get_row(gsl_vector_float * v, const gsl_matrix_float * m, const size_t i); GSL_FUN int gsl_matrix_float_get_col(gsl_vector_float * v, const gsl_matrix_float * m, const size_t j); GSL_FUN int gsl_matrix_float_set_row(gsl_matrix_float * m, const size_t i, const gsl_vector_float * v); GSL_FUN int gsl_matrix_float_set_col(gsl_matrix_float * m, const size_t j, const gsl_vector_float * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL float gsl_matrix_float_get(const gsl_matrix_float * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float x); GSL_FUN INLINE_DECL float * gsl_matrix_float_ptr(gsl_matrix_float * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN float gsl_matrix_float_get(const gsl_matrix_float * 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_float_set(gsl_matrix_float * m, const size_t i, const size_t j, const float 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 float * gsl_matrix_float_ptr(gsl_matrix_float * 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 (float *) (m->data + (i * m->tda + j)) ; } INLINE_FUN const float * gsl_matrix_float_const_ptr(const gsl_matrix_float * 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 float *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_FLOAT_H__ */
{ "alphanum_fraction": 0.6460455362, "avg_line_length": 37.1922005571, "ext": "h", "hexsha": "3793a89e0d95e8e9a9b72763ee1999eabc8b3222", "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_float.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_float.h", "max_line_length": 133, "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_float.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3177, "size": 13352 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp.h> static double fun(double x) { return x + cos(x * x); } int main(void) { const double a = 1.0; const double b = 10.0; const int steps = 10; double xi, yi, x[100], y[100], dx; FILE *input, *output; int i; const gsl_interp_type *ts[] = { gsl_interp_linear, gsl_interp_polynomial, gsl_interp_cspline, gsl_interp_cspline_periodic, gsl_interp_akima, gsl_interp_akima_periodic, gsl_interp_steffen, }; char *tsn[] = { "gsl_interp_linear.txt", "gsl_interp_polynomial.txt", "gsl_interp_cspline.txt", "gsl_interp_cspline_periodic.txt", "gsl_interp_akima.txt", "gsl_interp_akima_periodic.txt", "gsl_interp_steffen.txt", }; int tsc = sizeof(ts) / sizeof(const gsl_interp_type *); input = fopen("wartosci.txt", "w"); dx = (b - a) / (double) steps; for (i = 0; i <= steps; ++i) { x[i] = a + (double) i * dx + 0.5 * sin((double) i * dx); y[i] = fun(x[i]); fprintf(input, "%g %g\n", x[i], y[i]); } for (i = 0; i < tsc; i++) { output = fopen(tsn[i], "w"); gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(ts[i], steps + 1); gsl_spline_init(spline, x, y, steps + 1); for (xi = a; xi <= b; xi += 0.01) { yi = gsl_spline_eval(spline, xi, acc); fprintf(output, "%g %g\n", xi, yi); } gsl_spline_free(spline); gsl_interp_accel_free(acc); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5433070866, "avg_line_length": 29.1475409836, "ext": "c", "hexsha": "4a43f0907743d2a81879d0fc99daa84bdafb9f84", "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": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_path": "lab2/interpolacja.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "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": "mistyfiky/agh-mownit", "max_issues_repo_path": "lab2/interpolacja.c", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_path": "lab2/interpolacja.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 515, "size": 1778 }
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cblas.h> #include <stdio.h> int main() { double A[ 6 ] = { 1.0, 2.0, 1.0, -3.0, 4.0, -1.0 }; double B[ 6 ] = { 1.0, 2.0, 1.0, -3.0, 4.0, -1.0 }; double C[ 9 ] = { 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 }; int i = 0; cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans, 3, 3, 2, 1, A, 3, B, 3, 2, C, 3 ); for( i = 0; i < 9; i++ ) { printf( "%lf ", C[ i ] ); } printf( "\n" ); }
{ "alphanum_fraction": 0.6318359375, "avg_line_length": 29.2571428571, "ext": "c", "hexsha": "275da67cf30ef070c10787983b69afc60bf36d28", "lang": "C", "max_forks_count": 188, "max_forks_repo_forks_event_max_datetime": "2022-03-17T06:46:43.000Z", "max_forks_repo_forks_event_min_datetime": "2016-11-29T22:58:11.000Z", "max_forks_repo_head_hexsha": "042b6215818db0e2a784e72c7e054167dcefcd2a", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "sthagen/stdlib", "max_forks_repo_path": "deps/test/openblas/test_install.c", "max_issues_count": 435, "max_issues_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:43:17.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-07T18:12:45.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "ghalimi/stdlib", "max_issues_repo_path": "deps/test/openblas/test_install.c", "max_line_length": 89, "max_stars_count": 3428, "max_stars_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "ghalimi/stdlib", "max_stars_repo_path": "deps/test/openblas/test_install.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:32:13.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:48:46.000Z", "num_tokens": 381, "size": 1024 }
#ifndef CWANNIER_EVCACHE_H #define CWANNIER_EVCACHE_H #include <stdbool.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "input.h" #include "ecache.h" #include "submesh.h" typedef struct { int na; int nb; int nc; int num_bands; int G_order[3]; int G_neg[3]; UEInputFn UEfn; gsl_vector **energies; gsl_matrix_complex **evecs; } EvecCache; EvecCache* init_EvecCache(int na, int nb, int nc, int num_bands, int G_order[3], int G_neg[3], UEInputFn UEfn); void free_EvecCache(EvecCache *evCache); void EvecCache_MinMaxVals(EvecCache *evCache, double *emin, double *emax); EnergyCache* copy_to_Ecache(EvecCache *evCache); #endif //CWANNIER_EVCACHE_H
{ "alphanum_fraction": 0.724822695, "avg_line_length": 22.03125, "ext": "h", "hexsha": "6495ee6f56fe097b98c811f544340a0458456b60", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "evcache.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "evcache.h", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "evcache.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 218, "size": 705 }
#if !defined (STATISTICS_H) #define STATISTICS_H #include <iostream> #include <fstream> #include <string> #include <cmath> #include <vector> #include <algorithm> #include "Rand.h" #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_bessel.h> using namespace std; const int XMAX = 600; const long double EXPXMAX = exp((double)XMAX); const long double EXP = exp(1.0); double Beta(double t, double x, double Itot); double Gaussian(double x, double mean, double var); long double Poisson(int lambda, int k); void Statistics(const vector<double>& data, double& ave, double& squareave, double& var); void Statistics(const vector<double>& data, double& max, double& min, double& ave, double& var, double& error); void Statistics(const vector<int>& data, double& max, double& min, double& ave, double& var, double& error); void Statistics(const vector<int>& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave); //void Statistics(const vector<int>& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave, double& x1inverseave); void Statistics(const vector<int>& data, double& Xmin, double& Xmax, double& X1inverseave, // <1/(X+1)> double& logXave, // < logX > double& Xsrave, // < X^0.5 > double& Xave, // < X > double& X2ave ); // < x^2 > void moment(const vector<int>& data, double &ave, double &adev, double &sdev, double &var, double &skew, double &curt); void StatisticalDispersion(vector<int>& X, double& H7, double& H8, double& H9, double& H10); double GetXsecondmin(const vector<double>& data, double Xmin); void Statistics(const vector<double>& data, double& min, double& Q1, double& Q2, double& Q3, double& max, double& ave, double& var, double& error, ofstream& fout1, ofstream& fout2); void Binning(const vector<double>& data, int B, vector<double>& Binsize, vector<double>& Q); int GetBinIndex(const double& x, const vector<double>& Q); #endif
{ "alphanum_fraction": 0.6949152542, "avg_line_length": 35.8214285714, "ext": "h", "hexsha": "d089733de2c2a07a7650ace59eb7404e53e74e0e", "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": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "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": "spxuw/RFIM", "max_issues_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_line_length": 152, "max_stars_count": null, "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 572, "size": 2006 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <math.h> #include <gsl/gsl_math.h> #ifdef INVARIANCETEST #define DO_NOT_REDEFINE_MPI_COMM_WORLD #endif #include "allvars.h" #include "proto.h" /*! \file main.c * \brief start of the program */ /*! * This function initializes the MPI communication packages, and sets * cpu-time counters to 0. Then begrun() is called, which sets up * the simulation either from IC's or from restart files. Finally, * run() is started, the main simulation loop, which iterates over * the timesteps. */ int main(int argc, char **argv) { int i; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &ThisTask); MPI_Comm_size(MPI_COMM_WORLD, &NTask); #ifdef INVARIANCETEST World_ThisTask = ThisTask; World_NTask = NTask; if(World_NTask != (INVARIANCETEST_SIZE1 + INVARIANCETEST_SIZE2)) { printf("wrong number of procs for invariance-test\n"); MPI_Finalize(); /* clean up & finalize MPI */ return 0; } if(World_ThisTask < INVARIANCETEST_SIZE1) Color = 0; else Color = 1; MPI_Comm_split(MPI_COMM_WORLD, Color, 0, &MPI_CommLocal); MPI_Comm_rank(MPI_CommLocal, &ThisTask); MPI_Comm_size(MPI_CommLocal, &NTask); #endif for(PTask = 0; NTask > (1 << PTask); PTask++); if(argc < 2) { if(ThisTask == 0) { printf("Parameters are missing.\n"); printf("Call with <ParameterFile> [<RestartFlag>] [<RestartSnapNum>]\n"); } endrun(0); } strcpy(ParameterFile, argv[1]); if(argc >= 3) RestartFlag = atoi(argv[2]); else RestartFlag = 0; if(argc >= 4) RestartSnapNum = atoi(argv[3]); else RestartSnapNum = -1; /* initialize CPU-time/Wallclock-time measurement */ for(i = 0; i < CPU_PARTS; i++) All.CPU_Sum[i] = CPU_Step[i] = 0; CPUThisRun = 0; WallclockTime = second(); begrun(); /* set-up run */ run(); /* main simulation loop */ MPI_Finalize(); /* clean up & finalize MPI */ return 0; } /* ---------------------------------------------------------------------- The rest of this file contains documentation for compiling and running the code, in a format appropriate for 'doxygen'. ---------------------------------------------------------------------- */ /*! \mainpage Reference documentation of GADGET-2 \author Volker Springel \n Max-Planck-Institute for Astrophysics \n Garching, Germany \n volker@mpa-garching.mpg.de \n \n \section install Compilation GADGET-2 needs the following non-standard libraries for compilation: - \b MPI - the Message Passing Interface (version 1.0 or higher). Many vendor supplied versions exist, in addition to excellent open source implementations, e.g. MPICH (http://www-unix.mcs.anl.gov/mpi/mpich/) or LAM (http://www.lam-mpi.org/). - \b GSL - the GNU scientific library. This open-source package can be obtained at http://www.gnu.org/software/gsl, for example. GADGET only needs this library for a few very simple cosmological integrations at start-up. - \b FFTW - the <em>Fastest Fourier Transform in the West</em>. This open-source package can be obtained at http://www.fftw.org, for example. It is only needed for simulations that use the TreePM algorithm. Note that FFTW needs to be compiled with parallel support enabled. This can be achieved by passing the option <b>--enable-mpi</b> to the configure script. When at it, you might as well add <b>--enable-type-prefix</b> to obtain the libraries in both a single and double precision version. If this has not been done, you should set the option \b NOTYPEPREFIX_FFTW in GADGET's \ref Gadget-Makefile "Makefile". Note that if any of the above libraries is not installed in standard locations on your system, the \ref Gadget-Makefile "Makefile" provided with the code may need slight adjustments. Similarly, compiler options, particularly with respect to optimisations, may need adjustment to the C-compiler that is used. Finally, the \ref Gadget-Makefile "Makefile" contains a number of compile-time options that need to be set appropriately for the type of simulation that is simulated. The provided makefile is compatible with GNU-make, i.e. typing \b make or \b gmake should then build the executable <b>P-Gadget2<b>. If your site does not have GNU-make, get it, or write your own makefile. \section howtorun Running the code In order to start the code, a \ref parameterfile "parameterfile" needs to be specified. */ /*! \page parameterfile Parameterfile of GADGET-2 - \b ViscositySourceScaling \n Parameter for dynamic viscosity (e.g. 2.5) - \b ViscosityDecayLength \n Parameter for dynamic viscosity (e.g. 2.0) - \b ViscosityAlphaMin \n Parameter for dynamic viscosity (e.g. 0.01) - \b ViscosityAlphaMin \n value for w of equation of state (e.g. -0.4) - \b DarkEnergyFile \n file containing z and w(z) (e.g. wz_0.83_RP.txt) - \b VelIniScale \n factor to rescale v_ini (e.g. 1.10) */ /*! \page Gadget-Makefile Makefile of GADGET-2 There are a number of new types of simulations that can be run with GADGET-2, most importantly some that use different variants of the TreePM algorithm. A schematic overview of these simulation-types is given in Table 1. The TreePM algorithm is switched on by passing the desired PM mesh-size at compile time via the makefile to the code. The relevant parameter is \b PMGRID, see below. Using an explicit force split, the long-range force is then computed with Fourier techniques, while the short-range force is done with the tree. Because the tree needs only be walked locally, a speed-up can arise, particularly for near to homogeneous particle distributions, but not only restricted to them. Periodic and non-periodic boundary conditions are implemented. In the latter case, the code will internally compute FFTs of size \b 2*PMGRID in order to allow for the required zero-padding. Pure SPH simulations can also be run in periodic boxes whose x-dimension is an integer multiple of the dimensions in the y- and z-directions. This can be useful for hydrodynamic test calculations, e.g. shock tubes in 3D. Many aspects of these new features are controlled with compile-time options in the makefile rather than by the parameterfile. This was done in order to allow the generation of highly optimised binaries by the compiler, even when the underlying source allows for many different ways to run the code. Unfortunately, this technique has the disadvantage that different simulations may require different binaries of GADGET. If several simulations are run concurrently, there is hence the danger that a simulation is started/resumed with the `wrong' binary. Note that while GADGET checks the plausibility of some of the most important code options, this is not done for all of them. To minimise the risk of using the wrong code for a simulation, my recommendation is therefore to produce a separate executable for each simulation that is run. For example, a good strategy is to make a copy of the whole code together with its makefile in the output directory of each simulation run, and then to use this copy to compile the code and to run the simulation. The makefile contains a dummy list of all available compile-time code options, with most of them commented out by default. To activate a certain feature, the corresponding parameter should be commented in, and given the desired value, where appropriate. At the beginning of the makefile, there is also a brief explanation of each of the options. <b>Important Note:</b>Whenever you change one of the makefile options described below, a full recompilation of the code is necessary. To guarantee that this is done, you should give the command <b>make clean</b>, which will erase all object files, followed by <b>make</b>. \section secmake1 Options that describe the physics of the simulation - \b PERIODIC \n Set this if you want to have periodic boundary conditions. - \b COOLING \n This enables radiative cooling and heating. It also enables an external UV background which is read from a file called <em>TREECOOL</em>. - \b SFR \n This enables star formation using an effective multiphase models. This option requires cooling. - \b METALS \n This activates the tracking of metal enrichment in gas and stars. Note that cooling by metal-lines is not yet included in the code. - \b STELLARAGE \n This stores the formation times of each star particle, and includes this information in snapshot files. - \b WINDS \n This activates galactic winds. Requires star formation. - \b ISOTROPICWINDS \n This makes the wind isotropic. If not set, the wind is spawned in an axial way. Requires winds to be activated. - \b NOGRAVITY \n This switches off gravity. Makes only sense for pure SPH simulations in non-expanding space. - \b LONG_X/Y/Z \n These options can be used together with PERIODIC and NOGRAVITY only. When set, the options define numerical factors that can be used to distorts the periodic simulation cube into a parallelepiped of arbitrary aspect ratio. This can be useful for idealized SPH tests. - \b TWODIMS \n This effectively switches of one dimension in SPH, i.e. the code follows only 2d hydrodynamics in the xy-, yz-, or xz-plane. This only works with NOGRAVITY, and if all coordinates of the third axis are exactly equal. Can be useful for idealized SPH tests. - \b SPH_BND_PARTICLES \n If this is set, particles with a particle-ID equal to zero do not receive any SPH acceleration. This can be useful for idealized SPH tests, where these particles represent fixed "walls". \section secmake2 Options that affect SPH - \b NOFIXEDMASSINKERNEL \n If set, the number of SPH particles in the kernel is kept constant instead of the mass contained in the kernel. - \b NOGRADHSML \n If activated, an SPH equation of motion without \f$\nabla h\f$-correction factors is used. Note, for the default `entropy'-formulation of SPH (Springel and Hernquist, 2002, MNRAS, 333, 649), the switches <b>NOFIXEDMASSINKERNEL</b> and <b>NOGRADHSML</b> should <em>not</em> be set. - \b NOVISCOSITYLIMITER \n If this is set, there is no explicit upper limit on the viscosity. In the default version, this limiter will try to protect against possible particle `reflections', which may in principle occur for poor timestepping in the presence of strong shocks. \section secmake3 Options for the numerical algorithms - \b PMGRID=128 \n This enables the TreePM method, i.e. the long-range force is computed with a PM-algorithm, and the short range force with the tree. The parameter has to be set to the size of the mesh that should be used, e.g.~64, 96, 128, etc. The mesh dimensions need not necessarily be a power of two, but the FFT is fastest for such a choice. Note: If the simulation is not in a periodic box, then a FFT method for vacuum boundaries is employed, using a mesh with dimension twice that specified by <b>PMGRID</b>. - \b PLACEHIGHRESREGION=1+8 \n If this option is set (will only work together with \b PMGRID, then the long range force is computed in two stages: One Fourier-grid is used to cover the whole simulation volume, allowing the computation of the large-scale force. A second Fourier mesh is placed on the region occupied by `high-resolution' particles, allowing the computation of an intermediate-scale force. Finally, the force on very small scales is computed by the tree. This procedure can be useful for `zoom-simulations', where the majority of particles (the high-res particles) are occupying only a small fraction of the volume. To activate this option, the parameter needs to be set to an integer that encodes the particle types that make up the high-res particles in the form of a bit mask. For example, if types 0, 1, and 4 are the high-res particles, then the parameter should be set to <b>PLACEHIGHRESREGION=1+2+16</b>, i.e. to the sum \f$2^0+2^1+2^4\f$. The spatial region covered by the high-res grid is determined automatically from the initial conditions. Note: If a periodic box is used, the high-res zone may not intersect the box boundaries. - \b ENLARGEREGION=1.1 \n The spatial region covered by the high-res zone normally has a fixed size during the simulation, which initially is set to the smallest region that encompasses all high-res particles. Normally, the simulation will be interrupted, if high-res particles leave this region in the course of the run. However, by setting this parameter to a value larger than one, the high-res region can be expanded. For example, setting it to 1.4 will enlarge its side-length by 40% (it remains centred on the high-res particles). Hence, with such a setting, the high-res region may expand or move by a limited amount. If in addition \b SYNCHRONIZATION is activated, then the code will be able to continue even if high-res particles leave the initial high-res grid. In this case, the code will update the size and position of the grid that is placed onto the high-resolution region automatically. To prevent that this potentially happens every single PM step, one should nevertheless assign a value slightly larger than 1 to \b ENLARGEREGION. - \b DOUBLEPRECISION \n This makes the code store and compute internal particle data in double precision. Note that output files are nevertheless written by converting the values that are saved to single precision. - \b NOTREERND \n If this is not set, the tree construction will succeed even when there are a few particles at identical locations. This is done by `rerouting' particles once the node-size has fallen below \f$10^{-3}\f$ of the softening length. When this option is activated, this will be suppressed and the tree construction will always fail if there are particles at extremely close or identical coordinates. - \b NOSTOP_WHEN_BELOW_MINTIMESTEP \n If this is activated, the code will not terminate when the timestep falls below the value of \b MinSizeTimestep specified in the parameterfile. This is useful for runs where one wants to enforce a constant timestep for all particles. This can be done by activating this option, and by setting \b MinSizeTimestep} and \b MaxSizeTimestep to an equal value. - \b NOPMSTEPADJUSTMENT \n When this is set, the long-range timestep for the PM force computation is always determined by \b MaxSizeTimeStep. Otherwise, it is set to the minimum of \b MaxSizeTimeStep and the timestep obtained for the maximum long-range force with an effective softening scale equal to the PM smoothing-scale. \section secmake4 Architecture specific options - \b T3E \n The code assumes that \b sizeof(int)=4 holds. A few machines (like Cray T3E) have \b sizeof(int)=8. In this case, set the T3E flag. - \b NOTYPEPREFIX_FFTW \n If this is set, the fftw-header/libraries are accessed without type prefix (adopting whatever was chosen as default at compile-time of fftw). Otherwise, the type prefix 'd' for double-precision is used. \section secmake5 Input options - \b MOREPARAMS \n Activate this to allow a set of additional parameters in the parameterfile which control the star formation and feedback sector. This option must be activated when star formation is switched on. \section secmake6 Output options - \b OUTPUTPOTENTIAL \n This will force the code to compute gravitational potentials for all particles each time a snapshot file is generated. These values are then included in the snapshot files. Note that the computation of the values of the potential costs additional time. - \b OUTPUTACCELERATION \n This will include the physical acceleration of each particle in snapshot files. - \b OUTPUTCHANGEOFENTROPY \n This will include the rate of change of entropy of gas particles in snapshot files. - \b OUTPUTTIMESTEP \n This will include the timesteps actually taken by each particle in the snapshot files. \section secmake7 Miscellaneous options - \b PEANOHILBERT \n This is a tuning option. When set, the code will bring the particles into Peano-Hilbert order after each domain decomposition. This improves cache utilisation and performance. - \b WALLCLOCK \n If set, a wallclock timer is used by the code to measure internal time consumption (see cpu-log file). Otherwise, a timer that measures consumed processor ticks is used. - \b FORCETEST=0.01 \n This can be set to check the force accuracy of the code, and is only included as a debugging option. The option needs to be set to a number between 0 and 1 (e.g. 0.01), which specifies the fraction of randomly chosen particles for which at each timestep forces by direct summation are computed. The normal tree-forces and the `correct' direct summation forces are then collected in a file \b forcetest.txt for later inspection. Note that the simulation itself is unaffected by this option, but it will of course run much(!) slower, particularly if <b> FORCETEST*NumPart*NumPart</b> \f$>>\f$ \b NumPart. Note: Particle IDs must be set to numbers \f$>=1\f$ for this option to work. */
{ "alphanum_fraction": 0.7406662837, "avg_line_length": 38.2637362637, "ext": "c", "hexsha": "2e5d3d9655cfb9bbbd6c43e32c6c070e1a2c2a62", "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/main.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/main.c", "max_line_length": 79, "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/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4436, "size": 17410 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> #define NMAX 100 double f (double x, void *params); double f (double x, void *params) { double n = *(double *) params; double f = exp (-x) * pow (x, n); return f; } void integralGen (int nmin, int nmax, double vals[]); void integralGen (int nmin, int nmax, double vals[]) { double result, error; double a = 0., b = 1.; double abserr = 1.e-9, relerr = 1.e-9; double n; size_t np = 1000; gsl_integration_workspace *w = gsl_integration_workspace_alloc (np); gsl_function F; F.function = &f; for (int i = nmin; i <= nmax; i++) { n = (double) i; F.params = &n; gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15, w, &result, &error); vals[i] = result; } gsl_integration_workspace_free (w); }
{ "alphanum_fraction": 0.5900900901, "avg_line_length": 21.1428571429, "ext": "c", "hexsha": "cacee6151909f4903a3d3bb7ad443c1dd85dfd6f", "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": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hrwhitelock/hw07", "max_forks_repo_path": "gslInt.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "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": "hrwhitelock/hw07", "max_issues_repo_path": "gslInt.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "fe6323433f9d5736a2b9e0a4e681a5954d8489d7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hrwhitelock/hw07", "max_stars_repo_path": "gslInt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 272, "size": 888 }
/* eigen/jacobi.c * * Copyright (C) 2004 Brian Gough, 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. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> /* Algorithm 8.4.3 - Cyclic Jacobi. Golub & Van Loan, Matrix Computations */ static inline double symschur2 (gsl_matrix * A, size_t p, size_t q, double *c, double *s) { double Apq = gsl_matrix_get (A, p, q); if (Apq != 0.0) { double App = gsl_matrix_get (A, p, p); double Aqq = gsl_matrix_get (A, q, q); double tau = (Aqq - App) / (2.0 * Apq); double t, c1; if (tau >= 0.0) { t = 1.0 / (tau + hypot (1.0, tau)); } else { t = -1.0 / (-tau + hypot (1.0, tau)); } c1 = 1.0 / hypot (1.0, t); *c = c1; *s = t * c1; } else { *c = 1.0; *s = 0.0; } /* reduction in off(A) is 2*(A_pq)^2 */ return fabs (Apq); } inline static void apply_jacobi_L (gsl_matrix * A, size_t p, size_t q, double c, double s) { size_t j; const size_t N = A->size2; /* Apply rotation to matrix A, A' = J^T A */ for (j = 0; j < N; j++) { double Apj = gsl_matrix_get (A, p, j); double Aqj = gsl_matrix_get (A, q, j); gsl_matrix_set (A, p, j, Apj * c - Aqj * s); gsl_matrix_set (A, q, j, Apj * s + Aqj * c); } } inline static void apply_jacobi_R (gsl_matrix * A, size_t p, size_t q, double c, double s) { size_t i; const size_t M = A->size1; /* Apply rotation to matrix A, A' = A J */ for (i = 0; i < M; i++) { double Aip = gsl_matrix_get (A, i, p); double Aiq = gsl_matrix_get (A, i, q); gsl_matrix_set (A, i, p, Aip * c - Aiq * s); gsl_matrix_set (A, i, q, Aip * s + Aiq * c); } } inline static double norm (gsl_matrix * A) { size_t i, j, M = A->size1, N = A->size2; double sum = 0.0, scale = 0.0, ssq = 1.0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { double Aij = gsl_matrix_get (A, i, j); if (Aij != 0.0) { double ax = fabs (Aij); if (scale < ax) { ssq = 1.0 + ssq * (scale / ax) * (scale / ax); scale = ax; } else { ssq += (ax / scale) * (ax / scale); } } } } sum = scale * sqrt (ssq); return sum; } int gsl_eigen_jacobi (gsl_matrix * a, gsl_vector * eval, gsl_matrix * evec, unsigned int max_rot, unsigned int *nrot) { size_t i, p, q; const size_t M = a->size1, N = a->size2; double red, redsum = 0.0; if (M != N) { GSL_ERROR ("eigenproblem requires square matrix", GSL_ENOTSQR); } else if (M != evec->size1 || M != evec->size2) { GSL_ERROR ("eigenvector matrix must match input matrix", GSL_EBADLEN); } else if (M != eval->size) { GSL_ERROR ("eigenvalue vector must match input matrix", GSL_EBADLEN); } gsl_vector_set_zero (eval); gsl_matrix_set_identity (evec); for (i = 0; i < max_rot; i++) { double nrm = norm (a); if (nrm == 0.0) break; for (p = 0; p < N; p++) { for (q = p + 1; q < N; q++) { double c, s; red = symschur2 (a, p, q, &c, &s); redsum += red; /* Compute A <- J^T A J */ apply_jacobi_L (a, p, q, c, s); apply_jacobi_R (a, p, q, c, s); /* Compute V <- V J */ apply_jacobi_R (evec, p, q, c, s); } } } *nrot = i; for (p = 0; p < N; p++) { double ep = gsl_matrix_get (a, p, p); gsl_vector_set (eval, p, ep); } if (i == max_rot) { return GSL_EMAXITER; } return GSL_SUCCESS; } int gsl_eigen_invert_jacobi (const gsl_matrix * a, gsl_matrix * ainv, unsigned int max_rot) { if (a->size1 != a->size2 || ainv->size1 != ainv->size2) { GSL_ERROR("jacobi method requires square matrix", GSL_ENOTSQR); } else if (a->size1 != ainv->size2) { GSL_ERROR ("inverse matrix must match input matrix", GSL_EBADLEN); } { const size_t n = a->size2; size_t i,j,k; unsigned int nrot = 0; int status; gsl_vector * eval = gsl_vector_alloc(n); gsl_matrix * evec = gsl_matrix_alloc(n, n); gsl_matrix * tmp = gsl_matrix_alloc(n, n); gsl_matrix_memcpy (tmp, a); status = gsl_eigen_jacobi(tmp, eval, evec, max_rot, &nrot); for(i=0; i<n; i++) { for(j=0; j<n; j++) { double ainv_ij = 0.0; for(k = 0; k<n; k++) { double f = 1.0 / gsl_vector_get(eval, k); double vik = gsl_matrix_get (evec, i, k); double vjk = gsl_matrix_get (evec, j, k); ainv_ij += vik * vjk * f; } gsl_matrix_set (ainv, i, j, ainv_ij); } } gsl_vector_free(eval); gsl_matrix_free(evec); gsl_matrix_free(tmp); if (status) { return status; } else { return GSL_SUCCESS; } } }
{ "alphanum_fraction": 0.5147204763, "avg_line_length": 23.2538461538, "ext": "c", "hexsha": "7f4a4dc78ec82e70a76c7aa51fcb8058da30a101", "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/eigen/jacobi.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/eigen/jacobi.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/eigen/jacobi.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": 1905, "size": 6046 }
/* specfunc/gsl_sf_dilog.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #ifndef __GSL_SF_DILOG_H__ #define __GSL_SF_DILOG_H__ #include <gsl/gsl_sf_result.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 /* Real part of DiLogarithm(x), for real argument. * In Lewin's notation, this is Li_2(x). * * Li_2(x) = - Re[ Integrate[ Log[1-s] / s, {s, 0, x}] ] * * Note that Im[Li_2(x)] = { 0 for x <= 1, -Pi*log(x) for x > 1 } */ int gsl_sf_dilog_e(const double x, gsl_sf_result * result); double gsl_sf_dilog(const double x); /* DiLogarithm(z), for complex argument z = r Exp[i theta]. */ int gsl_sf_complex_dilog_e(const double r, double theta, gsl_sf_result * result_re, gsl_sf_result * result_im); __END_DECLS #endif /* __GSL_SF_DILOG_H__ */
{ "alphanum_fraction": 0.7131001778, "avg_line_length": 28.593220339, "ext": "h", "hexsha": "6c64e3dfef362aca7cca09e2533763c54961cea3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_dilog.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_dilog.h", "max_line_length": 111, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_dilog.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 473, "size": 1687 }
#include <assert.h> #include <time.h> #include <stdlib.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include "utils/utils.h" #include "utils/compress.h" #include "rule.h" #define DIRICHLET 1 #define D_CONST .4 void populate_buf(uint64_t grule_size, uint8_t* rule_array, char* rule_buf) { /* Populate buffer with newly created rule */ for (uint64_t v = 0; v < grule_size; v++) { sprintf(&rule_buf[v], "%"PRIu8, rule_array[v]); } rule_buf[grule_size] = '\0'; } /** * Symmetrize the rule by setting all the states and their symmetries to having * the same output. */ void symmetrize_rule(uint64_t grule_size, uint8_t rule_array[grule_size], int states, int horizon) { int side = 2 * horizon + 1; int neigh_size = side * side - 1; uint32_t position_180; uint32_t position_90; uint32_t position_270; uint32_t position_vflip; uint32_t position_hflip; uint32_t position_dflip; uint32_t position_aflip; /* grule_size can be very big, this array is better on the heap */ /* Keep track of already seen positions with book-keeping */ uint8_t* book_keep = calloc(grule_size, sizeof(uint8_t)); int pos; for (uint64_t i = 0; i < grule_size; ++i) { /* Skip already seen positions when looping through the rule */ if (book_keep[i] == 1) { continue; } position_180 = 0; position_90 = 0; position_270 = 0; position_vflip = 0; position_hflip = 0; position_dflip = 0; position_aflip = 0; /* Create the representation of the symmetrized position by swapping the states in its number representation. */ for (int p = 0; p < neigh_size + 1; ++p) { /* 180° rotation */ position_180 += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, neigh_size - p)) % states); /* 90° rotation */ pos = (neigh_size - side + 1 - (side * (p%side)) + p/side); position_90 += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, pos)) % states); /* 270° rotation */ position_270 += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, neigh_size - pos)) % states); /* Vertical flip */ pos = (side * (p / side)) + (side - 1 - (p % 3)); position_vflip += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, pos)) % states); /* Horizontal flip */ if (p/side < side/2) { pos = (p - side + neigh_size + 1)%(neigh_size + 1); } else if (p/side > side/2) { pos = (p + side)%(neigh_size + 1); } else { pos = p; } position_hflip += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, pos)) % states); /* Diagonal flip */ pos = neigh_size - ((p % side) * side + (p / side)); position_dflip += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, pos)) % states); /* Antidiagonal flip */ pos = ((p % side) * side + (p / side)); position_aflip += (uint32_t)ipow(states, p) * ((i / (uint32_t)ipow(states, pos)) % states); } /* Add all seen positions to the book to not process them again */ book_keep[i] = 1; book_keep[position_180] = 1; book_keep[position_90] = 1; book_keep[position_270] = 1; book_keep[position_vflip] = 1; book_keep[position_hflip] = 1; book_keep[position_dflip] = 1; book_keep[position_aflip] = 1; rule_array[position_180] = rule_array[i]; rule_array[position_90] = rule_array[i]; rule_array[position_270] = rule_array[i]; rule_array[position_vflip] = rule_array[i]; rule_array[position_hflip] = rule_array[i]; rule_array[position_dflip] = rule_array[i]; rule_array[position_aflip] = rule_array[i]; } free(book_keep); } /** * @brief Build a rule from the provided command-line arguments. * @param grule_size The size of the rule. * @param rule_array The array holding the rule. * @param rule_buf A mirror buffer containing a string representation of the * rule. * @param rule_arg The string from which the rule is read. * @param states Number of expected states in the rule. */ void build_rule_from_args(uint64_t grule_size, uint8_t rule_array[grule_size], char rule_buf[grule_size + 1], char* rule_arg, int states) { /* Rule is given in base-(states - 1) format */ for (uint64_t s = 0 ; s < grule_size; ++s) { rule_array[s] = rule_arg[s] - '0'; rule_buf[s] = rule_arg[s]; assert(rule_array[s] < states); } rule_buf[grule_size] = '\0'; } /** * Simple double comparison function used for sorting in the rule generation * function. */ int comp (const void * elem1, const void * elem2) { float f = *((float*)elem1); float s = *((float*)elem2); return (f > s) - (f < s); } /** * Generate a random general rule. The rule is written to rule_array and a * string representation is also saved in rule_buf. */ void generate_general_rule(uint64_t grule_size, uint8_t rule_array[grule_size], char rule_buf[grule_size + 1], int states, int horizon) { int inc; /* Choose lambda parameter at random as well as the proportion of transitions to other states */ double alphas[states]; double theta[states], lambda[states - 1], rand_num; /* This method samples the transition probability simplex according to a Dirichlet distribution with parameter D_CONST */ if (DIRICHLET == 1) { const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); time_t t; gsl_rng_set(r, (unsigned long)time(&t)); for (int i = 0; i < states; ++i) { alphas[i] = D_CONST; } gsl_ran_dirichlet(r, states, alphas, theta); lambda[0] = theta[0]; for (int i = 1; i < states - 1; ++i) { lambda[i] = theta[i] + lambda[i - 1]; } gsl_rng_free(r); } /* Second method that samples the simplex uniformly */ else { for (int i = 0; i < states - 1; ++i) { lambda[i] = ((double)rand() / (double)((unsigned)RAND_MAX + 1)); } qsort(lambda, sizeof(lambda)/sizeof(*lambda), sizeof(*lambda), comp); } for (uint64_t v = 0; v < grule_size; v++) { /* Assign the rule to the first state that passes the test */ rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1); inc = 0; while (lambda[inc] < rand_num && inc < states - 1) { ++inc; } rule_array[v] = (uint8_t)inc; } symmetrize_rule(grule_size, rule_array, states, horizon); populate_buf(grule_size, rule_array, rule_buf); } void cross_breed(uint64_t grule_size, uint8_t* parent_rule_A, uint8_t* parent_rule_B, uint8_t* child, char rule_buf[grule_size], double rate, int horizon, int states) { for (uint64_t i = 0; i < grule_size; ++i) { double rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1); child[i] = (rate > rand_num) ? parent_rule_A[i]: parent_rule_B[i]; } perturb_rule(grule_size, child, rule_buf, states, horizon, 0.05); } void perturb_rule(uint64_t grule_size, uint8_t rule_array[grule_size], char rule_buf[grule_size + 1], int states, int horizon, double rate) { for (uint64_t v = 0; v < grule_size; ++v) { /* Perturb transisition outcome with probability rate */ double rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1); if (rand_num < rate) { rule_array[v] += (1 + rand() % (states - 1)); rule_array[v] %= states; } } symmetrize_rule(grule_size, rule_array, states, horizon); populate_buf(grule_size, rule_array, rule_buf); } void make_map(struct Options2D* opts, char* rule_buf, int step) { FILE* dic_file; char* fname; asprintf(&fname, "%s/map/%lu.map", opts->data_dir_name, hash(rule_buf)); dic_file = fopen(fname, "w+"); if (dic_file == NULL) { fprintf(stderr, "Error while opening map file %s.", fname); exit(1); } fprintf(dic_file, "%s", rule_buf); fclose(dic_file); free(fname); sprintf(rule_buf, "%lu", hash(rule_buf)); printf("%i: Rule %s\n", step, rule_buf); } void generate_totalistic_rule(uint64_t rule_size, uint8_t rule_array[rule_size], char rule_buf[rule_size + 1], int states) { unsigned long rule_number = 0UL; for (uint64_t s = 0 ; s < rule_size; ++s) { rule_array[s] = rand() % states; rule_number += rule_array[s] * ipow(states, s); if (states >= 3) { rule_buf[s] = '0' + rule_array[s]; } } if (states == 2) { sprintf(rule_buf, "%lu", rule_number); } }
{ "alphanum_fraction": 0.6104950269, "avg_line_length": 29.6508474576, "ext": "c", "hexsha": "4b351d9d246395d6c0abaf1c20d27cc7b1b8045b", "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": "7e877c917f83bdd5032959205564ca06928b1a6c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "smearle/evolving-structures-in-complex-systems", "max_forks_repo_path": "src/automaton/rule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c", "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": "smearle/evolving-structures-in-complex-systems", "max_issues_repo_path": "src/automaton/rule.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "smearle/evolving-structures-in-complex-systems", "max_stars_repo_path": "src/automaton/rule.c", "max_stars_repo_stars_event_max_datetime": "2021-07-12T05:38:21.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-12T05:38:21.000Z", "num_tokens": 2538, "size": 8747 }
#ifndef _UI_HELPERS_H_ #define _UI_HELPERS_H_ #define OEMRESOURCE #include <algorithm> #include <functional> #include <memory> #include <optional> #include <span> #include <string> #include <type_traits> #include <unordered_map> #include <vector> #include <ppl.h> #include <gsl/gsl> #include <range/v3/all.hpp> // Included before windows.h, because pfc.h includes winsock2.h #include "../pfc/pfc.h" #include <windows.h> #include <WindowsX.h> #include <SHLWAPI.H> #include <vssym32.h> #include <uxtheme.h> #include <shldisp.h> #include <ShlObj.h> #include <gdiplus.h> #include <Usp10.h> #include <CommonControls.h> #include <intsafe.h> #include <wil/resource.h> #include "../mmh/stdafx.h" #ifndef RECT_CX #define RECT_CX(rc) ((rc).right - (rc).left) #endif #ifndef RECT_CY #define RECT_CY(rc) ((rc).bottom - (rc).top) #endif #include "literals.h" #include "handle.h" #include "win32_helpers.h" #include "ole.h" #include "dialog.h" #include "dpi.h" #include "container_window.h" #include "message_hook.h" #include "trackbar.h" #include "solid_fill.h" #include "theming.h" #include "gdi.h" #include "text_drawing.h" #include "list_view/list_view.h" #include "drag_image.h" #include "info_box.h" #include "menu.h" #include "ole/data_object.h" #include "ole/enum_format_etc.h" #endif
{ "alphanum_fraction": 0.722007722, "avg_line_length": 17.7397260274, "ext": "h", "hexsha": "1722810d842bc2a46d44ec3b772f72fea536ffb2", "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": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "msquared2/ui_helpers", "max_forks_repo_path": "stdafx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "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": "msquared2/ui_helpers", "max_issues_repo_path": "stdafx.h", "max_line_length": 63, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ca7ff26e8f444b7caaf45bd6282c212250e7c41", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "msquared2/ui_helpers", "max_stars_repo_path": "stdafx.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 352, "size": 1295 }
// Copyright Twitch Interactive, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT #pragma once #include <gsl/span> #include <vector> namespace Twitch::Utility { class OutputByteStream { public: void reserve(size_t size) { _data.reserve(size); } template<typename ValueType, typename ArgType> void write(const ArgType &arg) { size_t startSize = _data.size(); size_t valueSize = sizeof(ValueType); ValueType value = static_cast<ValueType>(arg); _data.resize(startSize + valueSize); memcpy_s(_data.data() + startSize, _data.size() - startSize, &value, valueSize); } void writeBytes(gsl::span<const uint8_t> bytes) { size_t startSize = _data.size(); _data.resize(startSize + bytes.size()); memcpy_s(_data.data() + startSize, _data.size() - startSize, bytes.data(), bytes.size()); } std::vector<uint8_t> consume() { return std::move(_data); } private: std::vector<uint8_t> _data; }; class InputByteStream { public: InputByteStream(gsl::span<const uint8_t> data) : _data(std::move(data)) { } template<typename ValueType> ValueType read() { ValueType value; size_t valueSize = sizeof(ValueType); memcpy_s(&value, sizeof(value), _data.data() + _currentPosition, valueSize); _currentPosition += valueSize; return value; } void readBytes(gsl::span<uint8_t> bytes) { memcpy_s(bytes.data(), bytes.size(), _data.data() + _currentPosition, bytes.size()); _currentPosition += bytes.size(); } gsl::span<const uint8_t> readBytesView(size_t size) { gsl::span<const uint8_t> bytesView = _data.subspan(_currentPosition, size); _currentPosition += size; return bytesView; } size_t remainingSize() const { return _data.size() - _currentPosition; } private: gsl::span<const uint8_t> _data; size_t _currentPosition = 0; }; } // namespace Twitch::Utility
{ "alphanum_fraction": 0.6324662813, "avg_line_length": 24.7142857143, "ext": "h", "hexsha": "b13fd9a049b94a8422ccd78d95de5feb8b1fbdb8", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-08-10T21:55:56.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-02T17:34:48.000Z", "max_forks_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LaudateCorpus1/libsoundtrackutil", "max_forks_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_issues_repo_issues_event_max_datetime": "2021-08-10T21:56:07.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-10T21:56:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "twitchtv/libsoundtrackutil", "max_issues_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_line_length": 97, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a0e0e022669afbf2f4fdb3914817a67606b4c320", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LaudateCorpus1/libsoundtrackutil", "max_stars_repo_path": "libsoundtrackutil/include/libsoundtrackutil/ByteStream.h", "max_stars_repo_stars_event_max_datetime": "2021-10-11T01:10:56.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-14T00:51:56.000Z", "num_tokens": 504, "size": 2076 }
/* * Copyright 2016 Maikel Nadolski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HMM_ALGORITHM_H_ #define HMM_ALGORITHM_H_ #include <map> #include <range/v3/core.hpp> #include <range/v3/algorithm.hpp> #include <range/v3/view/map.hpp> #include <range/v3/view/unique.hpp> #include <gsl_util.h> #include "maikel/hmm/algorithm/forward.h" #include "maikel/hmm/algorithm/backward.h" #include "maikel/hmm/algorithm/baum_welch.h" namespace maikel { template <class SymbolType, class IndexType> // requires UnsignedIntegral<I> bool is_bijective_index_map(std::map<SymbolType,IndexType> const& map) { IndexType max_index = ranges::max( map | ranges::view::values ); std::vector<std::size_t> histogram(max_index+1); for (IndexType index : map|ranges::view::values) ++histogram[index]; return ranges::all_of(histogram, [](std::size_t count){ return count == 1; }); } template <class T> using ValueType = typename std::remove_reference<T>::type::value_type; template <class Index, class Range, class T = ranges::range_value_t<Range>> std::map<T,Index> map_from_symbols(Range&& range) { std::map<T,Index> symbols_to_index; Index index { 0 }; ranges::for_each(range | ranges::view::unique, [&symbols_to_index,&index](T const& s){ symbols_to_index[s] = index++; }); Ensures(is_bijective_index_map(symbols_to_index)); return symbols_to_index; } } #endif /* HMM_ALGORITHM_H_ */
{ "alphanum_fraction": 0.7031327698, "avg_line_length": 31.9206349206, "ext": "h", "hexsha": "f030b91134c63ad26ce9cd07bfe829a288adf8c7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_path": "include/maikel/hmm/algorithm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_path": "include/maikel/hmm/algorithm.h", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_path": "include/maikel/hmm/algorithm.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "num_tokens": 504, "size": 2011 }
/// @file rainbow-gen-userpk.c /// @brief A command-line tool for generating the user public keys. #include <rainbow_keypair.h> #include <stdlib.h> #include <stdio.h> #include <api.h> #include <utils.h> #include <string.h> #include <blas.h> int main(int argc, char **argv) { printf("%s\n", CRYPTO_ALGNAME); printf("msk size: %lu\n", CRYPTO_MASTER_SECRET_KEY_BYTES); printf("mpk size: %lu\n", CRYPTO_MASTER_PUBLIC_KEY_BYTES); printf("hash size: %d\n", _HASH_LEN); printf("signature size: %d\n\n", CRYPTO_BYTES); if (4 != argc) { printf("Usage:\n\n\trainbow-gen-userpk mpk_file_name identity upk_file_name\n\n"); return -1; } //malloc upk uint8_t *_mpk = malloc(CRYPTO_MASTER_PUBLIC_KEY_BYTES); FILE *fp; unsigned r; fp = fopen( argv[1] , "r"); if( NULL == fp ) { printf("fail to open master key file.\n"); return -1; } r = byte_fget(fp, _mpk, CRYPTO_MASTER_PUBLIC_KEY_BYTES); fclose(fp); if (CRYPTO_MASTER_PUBLIC_KEY_BYTES != r) { printf("fail to load key file.\n"); return -1; } unsigned char * _identity = malloc((_ID+1)/2); r = 0; generate_identity_hash(_identity, (unsigned char *) argv[2], strlen(argv[2])); if( NULL == _identity ) { printf("fail to create identity hash.\n"); return -1; } printf("identity hash: "); for(unsigned i = 0; i<_ID; i++){ printf("%hhu ",gf16v_get_ele(_identity,i)); } printf("\n\n"); uint8_t *_upk = malloc(sizeof(upk_t)); //calculate usk with mpk and ID int re = calculate_upk((upk_t *) _upk, (mpk_t *) _mpk, _identity); if (0 != re) { printf("%s generate user-public-key fails.\n", CRYPTO_ALGNAME); return -1; } //write upk to disk fp = fopen(argv[3], "w+"); if (NULL == fp) { printf("fail to open user public key file.\n"); return -1; } byte_fdump(fp, CRYPTO_ALGNAME " user-public-key", _upk, sizeof(upk_t)); //pk speichern und beschriften fclose(fp); //free upk and rest free(_mpk); free(_identity); free(_upk); return 0; }
{ "alphanum_fraction": 0.5967517401, "avg_line_length": 25.3529411765, "ext": "c", "hexsha": "c7b6f43178044fbfc1129ebafd72007f35bc3672", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-18T14:16:30.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-18T14:16:30.000Z", "max_forks_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mnmuser/ibs-rainbow", "max_forks_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "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": "mnmuser/ibs-rainbow", "max_issues_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_line_length": 106, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mnmuser/ibs-rainbow", "max_stars_repo_path": "Reference_Implementation/rainbow-gen-userpk.c", "max_stars_repo_stars_event_max_datetime": "2020-09-21T15:43:47.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-21T15:43:47.000Z", "num_tokens": 630, "size": 2155 }
#include <stdio.h> #include <stdlib.h> #include <math.h> //#include <cem.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> void least_square_solver(double *matA, int n_row, int n_col, double *y, double *sol_x) { int i, j, k, tmp; double sum; gsl_matrix * A = gsl_matrix_alloc (n_row,n_col); gsl_matrix * V = gsl_matrix_alloc (n_col,n_col); gsl_vector * S = gsl_vector_alloc (n_col); gsl_vector * work = gsl_vector_alloc (n_col); // gsl_matrix * U = gsl_matrix_alloc (n_row-1,n_col_ids); gsl_vector * b = gsl_vector_alloc (n_row); gsl_vector * x = gsl_vector_alloc (n_col); /* //printf A and b FILE *fpA, *fpU, *fpb; fpA = fopen("A.dat","w"); fpU = fopen("U.dat","w"); fpb = fopen("b.dat","w");*/ // need to copy matA to A, y to b! for (i=0;i<n_row;i++) { for (j=0; j<n_col; j++) { gsl_matrix_set (A, i, j, *(matA+i*n_col+j)); } gsl_vector_set (b, i, y[i]); } /* for (i=0;i<n_row;i++) { for (j=0; j<n_col; j++) { fprintf(fpA,"%f ", gsl_matrix_get (A, i, j)); } fprintf(fpA,"\n"); fprintf(fpb,"%f\n", gsl_vector_get(b,i)); }*/ gsl_linalg_SV_decomp(A, V, S, work); // on output, A is replaced by U! /* for (i=0;i<n_row;i++) { for (j=0; j<n_col; j++) { fprintf(fpU,"%f ", *(matA+i*n_col+j)); } fprintf(fpU,"\n"); }*/ gsl_linalg_SV_solve (A, V, S, b, x); // So, A should be used instead of U, here. for (i=0;i<n_col;i++) { sol_x[i] = gsl_vector_get(x,i); } gsl_matrix_free(A); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(b); gsl_vector_free(x); }
{ "alphanum_fraction": 0.5470752089, "avg_line_length": 28.9516129032, "ext": "c", "hexsha": "852a5037e0d85dff7a4dd208304b3df9e9686f30", "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": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "eunseok-lee/spin_atom_CE3", "max_forks_repo_path": "src_findcluster3/least_square_solver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "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": "eunseok-lee/spin_atom_CE3", "max_issues_repo_path": "src_findcluster3/least_square_solver.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "eunseok-lee/spin_atom_CE3", "max_stars_repo_path": "src_findcluster3/least_square_solver.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 571, "size": 1795 }
#pragma once #include <gsl/span> #include <memory> #include <qbuffer.h> #include <qthread.h> #if QT_VERSION >= 0x060000 #include <QtMultimedia/QAudioSink> #else #include <QtMultimedia/QAudioOutput> #endif namespace contour { class Audio: public QObject { Q_OBJECT public: Audio(); ~Audio() override; signals: void play(int volume, int duration, std::vector<int> const& notes); private slots: void handleStateChanged(QAudio::State state); void handlePlayback(int volume, int duration, std::vector<int> const& notes); private: void fillBuffer(int volume, int duration, gsl::span<const int> notes); std::vector<std::int16_t> createMusicalNote(double volume, int duration, int note_) noexcept; QByteArray byteArray_; QBuffer audioBuffer_; QThread soundThread_; #if QT_VERSION >= 0x060000 std::unique_ptr<QAudioSink> audio; #else std::unique_ptr<QAudioOutput> audio; #endif }; } // namespace contour
{ "alphanum_fraction": 0.712371134, "avg_line_length": 22.0454545455, "ext": "h", "hexsha": "d2055f663374c1b55ef02729b85a64b925e8c60a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_path": "src/contour/Audio.h", "max_issues_count": 69, "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_path": "src/contour/Audio.h", "max_line_length": 97, "max_stars_count": 4, "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_path": "src/contour/Audio.h", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "num_tokens": 246, "size": 970 }
/* rng/rng.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_rng.h> gsl_rng * gsl_rng_alloc (const gsl_rng_type * T) { gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng)); if (r == 0) { GSL_ERROR_VAL ("failed to allocate space for rng struct", GSL_ENOMEM, 0); }; r->state = malloc (T->size); if (r->state == 0) { free (r); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for rng state", GSL_ENOMEM, 0); }; r->type = T; gsl_rng_set (r, gsl_rng_default_seed); /* seed the generator */ return r; } int gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src) { if (dest->type != src->type) { GSL_ERROR ("generators must be of the same type", GSL_EINVAL); } memcpy (dest->state, src->state, src->type->size); return GSL_SUCCESS; } gsl_rng * gsl_rng_clone (const gsl_rng * q) { gsl_rng *r = (gsl_rng *) malloc (sizeof (gsl_rng)); if (r == 0) { GSL_ERROR_VAL ("failed to allocate space for rng struct", GSL_ENOMEM, 0); }; r->state = malloc (q->type->size); if (r->state == 0) { free (r); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for rng state", GSL_ENOMEM, 0); }; r->type = q->type; memcpy (r->state, q->state, q->type->size); return r; } void gsl_rng_set (const gsl_rng * r, unsigned long int seed) { (r->type->set) (r->state, seed); } unsigned long int gsl_rng_max (const gsl_rng * r) { return r->type->max; } unsigned long int gsl_rng_min (const gsl_rng * r) { return r->type->min; } const char * gsl_rng_name (const gsl_rng * r) { return r->type->name; } size_t gsl_rng_size (const gsl_rng * r) { return r->type->size; } void * gsl_rng_state (const gsl_rng * r) { return r->state; } void gsl_rng_print_state (const gsl_rng * r) { size_t i; unsigned char *p = (unsigned char *) (r->state); const size_t n = r->type->size; for (i = 0; i < n; i++) { /* FIXME: we're assuming that a char is 8 bits */ printf ("%.2x", *(p + i)); } } void gsl_rng_free (gsl_rng * r) { RETURN_IF_NULL (r); free (r->state); free (r); }
{ "alphanum_fraction": 0.62077597, "avg_line_length": 20.6193548387, "ext": "c", "hexsha": "87ea74c134291a4669d008b6c9e23fd2fc016b20", "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/rng/rng.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/rng/rng.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/rng/rng.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": 927, "size": 3196 }
// // likelihood.h // EpiGenMCMC // // Created by Lucy Li on 13/04/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #ifndef __EpiGenMCMC__likelihood__ #define __EpiGenMCMC__likelihood__ #include <vector> #include <stdio.h> #include <limits> #include <gsl/gsl_cdf.h> #include "parameter.h" class Likelihood { public: Likelihood(); double binomial_lik(double, double, int, int, int, int, bool); double binomial_lik(double, double, std::vector<double>::iterator, int, int, int, int, int, bool); double coalescent_lik(std::vector<double>::iterator, std::vector<double>::iterator, std::vector<double>::iterator, std::vector<double>::iterator, std::vector<double>::iterator, int, int, int, bool); }; #endif /* defined(__EpiGenMCMC__likelihood__) */
{ "alphanum_fraction": 0.7176616915, "avg_line_length": 29.7777777778, "ext": "h", "hexsha": "a1761d9353b79fa8463bcddf34daca3c06d2f43a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-16T22:17:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-13T16:20:40.000Z", "max_forks_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lucymli/EpiGenMCMC", "max_forks_repo_path": "src/likelihood.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_issues_repo_issues_event_max_datetime": "2021-01-15T04:48:15.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:49:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lucymli/EpiGenMCMC", "max_issues_repo_path": "src/likelihood.h", "max_line_length": 202, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lucymli/EpiGenMCMC", "max_stars_repo_path": "src/likelihood.h", "max_stars_repo_stars_event_max_datetime": "2020-04-09T16:14:41.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-01T09:55:40.000Z", "num_tokens": 226, "size": 804 }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Portions Copyright (c) Microsoft Corporation #pragma once #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <gsl/gsl> #include "core/common/common.h" #include "core/framework/callback.h" #include "core/platform/env_time.h" #include "core/platform/telemetry.h" #include "core/session/onnxruntime_c_api.h" // for ORTCHAR_T #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif namespace onnxruntime { #ifdef _WIN32 using PIDType = unsigned long; using FileOffsetType = int64_t; #else using PIDType = pid_t; using FileOffsetType = off_t; #endif /// \brief An interface used by the onnxruntime implementation to /// access operating system functionality like the filesystem etc. /// /// Callers may wish to provide a custom Env object to get fine grain /// control. /// /// All Env implementations are safe for concurrent access from /// multiple threads without any external synchronization. class Env { public: virtual ~Env() = default; /// \brief Returns a default environment suitable for the current operating /// system. /// /// Sophisticated users may wish to provide their own Env /// implementation instead of relying on this default environment. /// /// The result of Default() belongs to this library and must never be deleted. static const Env& Default(); virtual int GetNumCpuCores() const = 0; /// \brief Returns the number of micro-seconds since the Unix epoch. virtual uint64_t NowMicros() const { return env_time_->NowMicros(); } /// \brief Returns the number of seconds since the Unix epoch. virtual uint64_t NowSeconds() const { return env_time_->NowSeconds(); } /// Sleeps/delays the thread for the prescribed number of micro-seconds. /// On Windows, it's the min time to sleep, not the actual one. virtual void SleepForMicroseconds(int64_t micros) const = 0; /** * Gets the length of the specified file. */ virtual common::Status GetFileLength( const ORTCHAR_T* file_path, size_t& length) const = 0; /** * Copies the content of the file into the provided buffer. * @param file_path The path to the file. * @param offset The file offset from which to start reading. * @param length The length in bytes to read. * @param buffer The buffer in which to write. */ virtual common::Status ReadFileIntoBuffer( const ORTCHAR_T* file_path, FileOffsetType offset, size_t length, gsl::span<char> buffer) const = 0; using MappedMemoryPtr = std::unique_ptr<char[], OrtCallbackInvoker>; /** * Maps the content of the file into memory. * This is a copy-on-write mapping, so any changes are not written to the * actual file. * @param file_path The path to the file. * @param offset The file offset from which to start the mapping. * @param length The length in bytes of the mapping. * @param[out] mapped_memory A smart pointer to the mapped memory which * unmaps the memory (unless release()'d) when destroyed. */ virtual common::Status MapFileIntoMemory( const ORTCHAR_T* file_path, FileOffsetType offset, size_t length, MappedMemoryPtr& mapped_memory) const = 0; #ifdef _WIN32 //Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0; #endif //Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileClose(int fd) const = 0; //This functions is always successful. It can't fail. virtual PIDType GetSelfPid() const = 0; // \brief Load a dynamic library. // // Pass "library_filename" to a platform-specific mechanism for dynamically // loading a library. The rules for determining the exact location of the // library are platform-specific and are not documented here. // // On success, returns a handle to the library in "*handle" and returns // OK from the function. // Otherwise returns nullptr in "*handle" and an error status from the // function. virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0; virtual common::Status UnloadDynamicLibrary(void* handle) const = 0; // \brief Get a pointer to a symbol from a dynamic library. // // "handle" should be a pointer returned from a previous call to LoadDynamicLibrary. // On success, store a pointer to the located symbol in "*symbol" and return // OK from the function. Otherwise, returns nullptr in "*symbol" and an error // status from the function. virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0; // \brief build the name of dynamic library. // // "name" should be name of the library. // "version" should be the version of the library or NULL // returns the name that LoadDynamicLibrary() can use virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0; // \brief returns a provider that will handle telemetry on the current platform virtual const Telemetry& GetTelemetryProvider() const = 0; protected: Env(); private: ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env); EnvTime* env_time_ = EnvTime::Default(); }; } // namespace onnxruntime
{ "alphanum_fraction": 0.7197341351, "avg_line_length": 37.3905325444, "ext": "h", "hexsha": "d6b20e00d44b5e52e68bf9290d1c75c8568ae712", "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": "4d32050f784fc73d065bb030e937bd45ac86ff32", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nrandell/onnxruntime", "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4d32050f784fc73d065bb030e937bd45ac86ff32", "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": "nrandell/onnxruntime", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_line_length": 117, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4d32050f784fc73d065bb030e937bd45ac86ff32", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nrandell/onnxruntime", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-25T10:26:57.000Z", "num_tokens": 1504, "size": 6319 }
/* -*- mode: C; c-basic-offset: 4 -*- */ /* ex: set shiftwidth=4 tabstop=4 expandtab: */ /* * Copyright (c) 2018-2019, Colorado School of Mines * All rights reserved. * * Author(s): Neil T. Dantam <ndantam@miens.edu> * Georgia Tech Humanoid Robotics Lab * Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu> * * * This file is provided under the following "BSD-style" License: * * * 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. * * 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. * */ #ifndef AMINO_MAT_H #define AMINO_MAT_H #include <cblas.h> /** * @file mat.h * * Block matrix descriptors and linear algebra operations. * */ typedef size_t aa_la_size; /** * Descriptor for a vector. */ struct aa_dvec { aa_la_size len; ///< Number of elements in vector double *data; ///< Pointer to data aa_la_size inc; ///< Increment between successive vector elements }; /** * Descriptor for a block matrix. */ struct aa_dmat { aa_la_size rows; ///< number of rows in matrix aa_la_size cols; ///< number of columns double *data; ///< Pointer to matrix data aa_la_size ld; ///< Leading dimension of matrix }; #define AA_DVEC_REF(v,i) ((v)->data[(i) * (v)->inc]) /** * Reference a matrix entry. * * @param M matrix * @param i row * @param j column */ #define AA_DMAT_REF(M,i,j) (((M)->data)[(M)->ld*(j) + (i)]) typedef void (aa_la_err_fun)( const char *message ); AA_API void aa_la_err( const char *message ); AA_API void aa_la_set_err( aa_la_err_fun *fun ); /** * BLAS arguments for a vector */ #define AA_VEC_ARGS(X) (X->data), ((int)(X->inc)) /** * BLAS arguments for a matrix */ #define AA_MAT_ARGS(X) (X->data), ((int)(X->ld)) /* Construction */ /** * Fill in a vector descriptor. * * @param len Number of elements in vector * @param data Pointer to vector data * @param inc Increment between sucessive elements */ static inline struct aa_dvec AA_DVEC_INIT( size_t len, double *data, size_t inc ) { struct aa_dvec vec; vec.len = len; vec.data = data; vec.inc = inc; return vec; } /** * Fill in a vector descriptor. * * @param vec Pointer to descriptor * @param len Number of elements in vector * @param data Pointer to vector data * @param inc Increment between sucessive elements */ AA_API void aa_dvec_view( struct aa_dvec *vec, size_t len, double *data, size_t inc ); /** * Fill in a matrix descriptor. * * @param mat Pointer to descriptor * @param rows Number of rows in matrix * @param cols Number of colums in matrix * @param data Pointer to vector data * @param ld Leading dimension of matrix */ AA_API void aa_dmat_view( struct aa_dmat *mat, size_t rows, size_t cols, double *data, size_t ld ); /** * View a block of a matrix. */ AA_API void aa_dmat_view_block( struct aa_dmat *dst, const struct aa_dmat *src, size_t row_start, size_t col_start, size_t rows, size_t cols ); /** * View a slice of a vector. */ AA_API void aa_dvec_slice( const struct aa_dvec *src, size_t start, size_t stop, size_t step, struct aa_dvec *dst ); /** * View a block of a matrix. */ AA_API void aa_dmat_block( const struct aa_dmat *src, size_t row_start, size_t col_start, size_t row_end, size_t col_end, struct aa_dmat *dst ); /** * View a row of a matrix as a vector. */ AA_API void aa_dmat_row_vec( const struct aa_dmat *src, size_t row, struct aa_dvec *dst ); /** * View a column of a matrix as a vector. */ AA_API void aa_dmat_col_vec( const struct aa_dmat *src, size_t col, struct aa_dvec *dst ); /** * View the diagonal of a matrix as a vector. */ AA_API void aa_dmat_diag_vec( const struct aa_dmat *src, struct aa_dvec *dst ); /** * Fill in a matrix descriptor. * * @param rows Number of rows in matrix * @param cols Number of colums in matrix * @param data Pointer to vector data * @param ld Leading dimension of matrix */ static inline struct aa_dmat AA_DMAT_INIT( size_t rows, size_t cols, double *data, size_t ld ) { struct aa_dmat mat; mat.rows = rows; mat.cols = cols; mat.data = data; mat.ld = ld; return mat; } #define AA_MAT_DIAG(VEC,MAT) \ aa_dvec_view((VEC), (MAT)->cols, (MAT)->data, 1+(MAT)->ld); /** * Region-allocate a vector. * * When finished, pop the descriptor. */ AA_API struct aa_dvec * aa_dvec_alloc( struct aa_mem_region *reg, size_t len ); /** * Duplicate vector out of region * * When finished, pop the descriptor. */ AA_API struct aa_dvec * aa_dvec_dup( struct aa_mem_region *reg, const struct aa_dvec *src); /** * Duplicate matrix out of region * * When finished, pop the descriptor. */ AA_API struct aa_dmat * aa_dmat_dup( struct aa_mem_region *reg, const struct aa_dmat *src); /** * Region-allocate a matrix. * * When finished, pop the descriptor. */ AA_API struct aa_dmat * aa_dmat_alloc( struct aa_mem_region *reg, size_t rows, size_t cols ); /** * Heap-allocate a vector. * * The descriptor and data are contained in a single malloc()'ed block. * When finished, call free() on the descriptor. */ AA_API struct aa_dvec * aa_dvec_malloc( size_t len ); /** * Heap-allocate a matrix. * * The descriptor and data are contained in a single malloc()'ed block. * When finished, call free() on the descriptor. */ AA_API struct aa_dmat * aa_dmat_malloc( size_t rows, size_t cols ); /** * Zero a vector. */ AA_API void aa_dvec_zero( struct aa_dvec *vec ); /** * Fill a vector. */ AA_API void aa_dvec_set( struct aa_dvec *vec, double alpha ); /** * Fill a matrix diagonal and off-diagonal elements. * * @param[in] A The matrix to fill * @param[in] alpha off-diagonal entries of A * @param[in] beta diagonal entries of A */ AA_API void aa_dmat_set( struct aa_dmat *A, double alpha, double beta ); /** * Zero a matrix. */ AA_API void aa_dmat_zero( struct aa_dmat *mat ); /* Level 1 BLAS */ /** * Swap x and y * * \f[ \mathbf{x} \leftrightarrow \mathbf{y} \f] */ AA_API void aa_dvec_swap( struct aa_dvec *x, struct aa_dvec *y ); /** * Scale x by alpha. * * \f[ \mathbf{x} \leftarrow \alpha \mathbf{x} \f] */ AA_API void aa_dvec_scal( double alpha, struct aa_dvec *x ); /** * Increment x by alpha. * * \f[ \mathbf{x} \leftarrow \alpha + \mathbf{x} \f] */ AA_API void aa_dvec_inc( double alpha, struct aa_dvec *x ); /** * Copy x to y. * * \f[ \mathbf{y} \leftarrow \mathbf{x} \f] */ AA_API void aa_dvec_copy( const struct aa_dvec *x, struct aa_dvec *y ); /** * Alpha x plus y. * * \f[ \mathbf{y} \leftarrow \alpha \mathbf{x} + \mathbf{y} \f] */ AA_API void aa_dvec_axpy( double a, const struct aa_dvec *x, struct aa_dvec *y ); /** * Dot product * * \f[ \mathbf{x}^T \mathbf{y} \f] */ AA_API double aa_dvec_dot( const struct aa_dvec *x, struct aa_dvec *y ); /** * Euclidean Norm * * \f[ \left\Vert \mathbf{x} \right\Vert_2 \f] */ AA_API double aa_dvec_nrm2( const struct aa_dvec *x ); /* Level 2 BLAS */ /** * General Matrix-Vector multiply * * \f[ \mathbf{y} \leftarrow \alpha \mathbf{A}^{\rm op} \mathbf{x} + \beta \mathbf{y} \f] */ AA_API void aa_dmat_gemv( CBLAS_TRANSPOSE trans, double alpha, const struct aa_dmat *A, const struct aa_dvec *x, double beta, struct aa_dvec *y ); /* Level 3 BLAS */ /** * General Matrix-Matrix multiply * * \f[ \mathbf{y} \leftarrow \alpha \mathbf{A}^{\rm opA} \mathbf{B}^\rm{opB} + \beta \mathbf{C} \f] */ AA_API void aa_dmat_gemm( CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, double alpha, const struct aa_dmat *A, const struct aa_dmat *B, double beta, struct aa_dmat *C ); /* LAPACK */ /** * Copies all or part of a two-dimensional matrix A to another * matrix B. * * @param[in] UPLO * Specifies the part of the matrix A to be copied to B. * - = 'U': Upper triangular part * - = 'L': Lower triangular part * - Otherwise: All of the matrix A * * @param[in] A * dimension (LDA,N) * The m by n matrix A. If UPLO = 'U', only the upper triangle * or trapezoid is accessed; if UPLO = 'L', only the lower * triangle or trapezoid is accessed. * * @param[out] B * dimension (LDB,N) * On exit, B = A in the locations specified by UPLO. * */ AA_API void aa_dmat_lacpy( const char uplo[1], const struct aa_dmat *A, struct aa_dmat *B ); /* Matrix/Vector Functions */ /** * sum-square-differences of two vectors */ AA_API double aa_dvec_ssd( const struct aa_dvec *x, const struct aa_dvec *y); /** * Y += alpha * X */ AA_API void aa_dmat_axpy( double alpha, const struct aa_dmat *X, struct aa_dmat *Y); /** * sum-square-differences of two matrices */ AA_API double aa_dmat_ssd( const struct aa_dmat *x, const struct aa_dmat *y); /** * Scale the matrix A by alpha */ AA_API void aa_dmat_scal( struct aa_dmat *A, double alpha ); /** * Increment the matrix A by alpha */ AA_API void aa_dmat_inc( struct aa_dmat *A, double alpha ); /** * Euclidean Norm */ AA_API double aa_dmat_nrm2( const struct aa_dmat *x ); /** * Matrix transpose. */ AA_API void aa_dmat_trans( const struct aa_dmat *A, struct aa_dmat *At); /** * Matrix inverse, in-place. */ AA_API int aa_dmat_inv( struct aa_dmat *A); /** * Pseudo-inverse. * * Singular values less than tol are ignored. If tol < 0, then a sane * default is used. */ AA_API int aa_dmat_pinv( const struct aa_dmat *A, double tol, struct aa_dmat *As); /** * Damped pseudo-inverse. */ AA_API int aa_dmat_dpinv( const struct aa_dmat *A, double k, struct aa_dmat *As); /** * Dead-zone damped pseudo-inverse. */ AA_API int aa_dmat_dzdpinv( const struct aa_dmat *A, double s_min, struct aa_dmat *As); /** * Copy a matrix */ AA_API void aa_dmat_copy( const struct aa_dmat *A, struct aa_dmat *B); #endif /* AMINO_MAT_H */
{ "alphanum_fraction": 0.6545294635, "avg_line_length": 22.5148514851, "ext": "h", "hexsha": "0008d427c393320d16ac649e2ffa32af8be611c7", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2022-02-22T01:32:20.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-05T18:55:14.000Z", "max_forks_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dyalab/amino", "max_forks_repo_path": "include/amino/mat.h", "max_issues_count": 28, "max_issues_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_issues_repo_issues_event_max_datetime": "2021-03-22T23:43:23.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-18T20:54:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dyalab/amino", "max_issues_repo_path": "include/amino/mat.h", "max_line_length": 100, "max_stars_count": 32, "max_stars_repo_head_hexsha": "e3063ceeeed7d1a3d55fc0d3071c9aacb4466b22", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dyalab/amino", "max_stars_repo_path": "include/amino/mat.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:49:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-02T20:06:09.000Z", "num_tokens": 3161, "size": 11370 }
/* vector/gsl_vector_uchar.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_UCHAR_H__ #define __GSL_VECTOR_UCHAR_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_uchar.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; unsigned char *data; gsl_block_uchar *block; int owner; } gsl_vector_uchar; typedef struct { gsl_vector_uchar vector; } _gsl_vector_uchar_view; typedef _gsl_vector_uchar_view gsl_vector_uchar_view; typedef struct { gsl_vector_uchar vector; } _gsl_vector_uchar_const_view; typedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view; /* Allocation */ GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n); GSL_FUN gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n); GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_uchar_free (gsl_vector_uchar * v); /* Views */ GSL_FUN _gsl_vector_uchar_view gsl_vector_uchar_view_array (unsigned char *v, size_t n); GSL_FUN _gsl_vector_uchar_view gsl_vector_uchar_view_array_with_stride (unsigned char *base, size_t stride, size_t n); GSL_FUN _gsl_vector_uchar_const_view gsl_vector_uchar_const_view_array (const unsigned char *v, size_t n); GSL_FUN _gsl_vector_uchar_const_view gsl_vector_uchar_const_view_array_with_stride (const unsigned char *base, size_t stride, size_t n); GSL_FUN _gsl_vector_uchar_view gsl_vector_uchar_subvector (gsl_vector_uchar *v, size_t i, size_t n); GSL_FUN _gsl_vector_uchar_view gsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_uchar_const_view gsl_vector_uchar_const_subvector (const gsl_vector_uchar *v, size_t i, size_t n); GSL_FUN _gsl_vector_uchar_const_view gsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_FUN void gsl_vector_uchar_set_zero (gsl_vector_uchar * v); GSL_FUN void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x); GSL_FUN int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i); GSL_FUN int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v, const char *format); GSL_FUN int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src); GSL_FUN int gsl_vector_uchar_reverse (gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w); GSL_FUN int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j); GSL_FUN unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v); GSL_FUN unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v); GSL_FUN void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out); GSL_FUN size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v); GSL_FUN size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v); GSL_FUN void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax); GSL_FUN int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b); GSL_FUN int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b); GSL_FUN int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b); GSL_FUN int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b); GSL_FUN int gsl_vector_uchar_scale (gsl_vector_uchar * a, const unsigned char x); GSL_FUN int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x); GSL_FUN int gsl_vector_uchar_axpby (const unsigned char alpha, const gsl_vector_uchar * x, const unsigned char beta, gsl_vector_uchar * y); GSL_FUN unsigned char gsl_vector_uchar_sum (const gsl_vector_uchar * a); GSL_FUN int gsl_vector_uchar_equal (const gsl_vector_uchar * u, const gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_isnull (const gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_ispos (const gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_isneg (const gsl_vector_uchar * v); GSL_FUN int gsl_vector_uchar_isnonneg (const gsl_vector_uchar * v); GSL_FUN INLINE_DECL unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x); GSL_FUN INLINE_DECL unsigned char * gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i); GSL_FUN INLINE_DECL const unsigned char * gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN unsigned char * gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (unsigned char *) (v->data + i * v->stride); } INLINE_FUN const unsigned char * gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const unsigned char *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_UCHAR_H__ */
{ "alphanum_fraction": 0.6948611931, "avg_line_length": 34.8353909465, "ext": "h", "hexsha": "8b29abf33e4733c9c42001f4dd9e0be73a7e62c0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.h", "max_line_length": 139, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_uchar.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": 2158, "size": 8465 }
// // Created by chris on 07.05.21. // #pragma once #include <gsl/gsl_errno.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #include <numeric> #include <vector> class test { public: int n; }; /** * Calculates autocorrelation with FFT * @param vec * @return *//* std::vector<double> ac(const std::vector<double> &vec){ std::vector<double> fftReturn=vec; gsl_fft_real_wavetable *real; gsl_fft_halfcomplex_wavetable *hc; gsl_fft_real_workspace *work; //FFT work = gsl_fft_real_workspace_alloc(vec.size()); real = gsl_fft_real_wavetable_alloc(vec.size()); gsl_fft_real_transform(&fftReturn[0], 1, vec.size(), real, work); gsl_fft_real_wavetable_free(real); hc = gsl_fft_halfcomplex_wavetable_alloc(vec.size()); gsl_fft_halfcomplex_inverse(&fftReturn[0], 1, vec.size(), hc, work); gsl_fft_halfcomplex_wavetable_free(hc); return fftReturn; }*/ /** * @tparam T * @param vec * @return maximum element of given vector */ template<typename T> T max(const std::vector<T> &vec) { T maxVal = vec[0]; for (int i = 1; i < vec.size(); ++i) { maxVal = std::max(maxVal, vec[i]); } return maxVal; } /** * @tparam T * @param vec * @return minimum element of given vector */ template<typename T> T min(const std::vector<T> &vec) { T minVal = vec[0]; for (int i = 1; i < vec.size(); ++i) { minVal = std::min(minVal, vec[i]); } return minVal; } /** * Calculates the arithmetic mean of given vector-elements * @tparam T * @param vec * @return the arithmetic mean */ template<typename T> T mean(const std::vector<T> &vec) { return std::accumulate(vec.begin(), vec.end(), 0.0)/vec.size(); } /** * Calculates the arithmetic mean of given vector-of-vector-of-elements * @tparam T * @param vec vector of vector of elements (tensor of rank 2) * @return the arithmetic mean of all values */ template<typename T> T mean(const std::vector<std::vector<T>> &vec) { std::vector<T> firstMeans; firstMeans.reserve(vec.size()); for(auto &i:vec){ firstMeans.push_back(mean(i)); } return mean(firstMeans); } /** * Calculates the standard deviation of given vector-elements * @tparam T * @param vec * @return standard deviation */ template<typename T> T stdev(const std::vector<T> &vec) { T summation=0; const T vec_mean=mean(vec); for (size_t i = 0; i < vec.size(); ++i) { summation+=pow(vec[i]-vec_mean,2); } return sqrt(summation*1.0/(vec.size()-1)); } /** * Calculates the autocorrelation-function of given data-sample * @tparam T * @param vec of data-sample with length n * @return autocorrelation-function in vector with length n/2 */ template<typename T> std::vector<T> autoCorr(const std::vector<T> &vec) { float mean = std::accumulate(vec.begin(), vec.end(), 0.0f) / vec.size(); std::vector<T> autocorrelation(vec.size() / 2); for (size_t t = 0; t < autocorrelation.size(); t++) { float n = 0; // Numerator float d = 0; // Denominator for (size_t i = 0; i < vec.size() - t; i++) { float xim = vec[i] - mean; n += xim * (vec[(i + t) % vec.size()] - mean); d += xim * xim; } autocorrelation[t] = n / d; } return autocorrelation; } /** * normalizes given vector call by reference * @tparam T * @param vec vector which should be normalized */ template<typename T> void normalize(std::vector<T> &vec) { const T vec_max = max(vec); for (T &i : vec) { i /= 1.0 * vec_max; } }
{ "alphanum_fraction": 0.6258351893, "avg_line_length": 23.6315789474, "ext": "h", "hexsha": "45ea1cc93268284a480e0600ebb91b68790ca588", "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": "ededd743fe6d8418894ae230a9783c7db114d7e2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_forks_repo_path": "Projects/HelloWorld/test.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "ededd743fe6d8418894ae230a9783c7db114d7e2", "max_issues_repo_issues_event_max_datetime": "2021-05-15T12:57:24.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-15T12:57:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_issues_repo_path": "Projects/HelloWorld/test.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "ededd743fe6d8418894ae230a9783c7db114d7e2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_stars_repo_path": "Projects/HelloWorld/test.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1014, "size": 3592 }
#ifndef WASM_INSTRUCTION_H #define WASM_INSTRUCTION_H #include <cstddef> #include <cstring> #include <cstdint> #include <type_traits> #include <array> #include <bitset> #include <optional> #include <variant> #include <algorithm> #include <iosfwd> #include <ostream> #include <iomanip> #include <gsl/span> #include <gsl/gsl> #include "wasm_base.h" namespace wasm { namespace opc { enum class OpCode: wasm_ubyte_t { // BLOCK INSTRUCTIONS BLOCK = 0x02u, LOOP = 0x03u, BR = 0x0cu, BR_IF = 0x0du, BR_TABLE = 0x0eu, IF = 0x04u, ELSE = 0x05u, END = 0x0bu, RETURN = 0x0fu, UNREACHABLE = 0x00u, // BASIC INSTRUCTIONS NOP = 0x01u, DROP = 0x1au, I32_CONST = 0x41u, I64_CONST = 0x42u, F32_CONST = 0x43u, F64_CONST = 0x44u, GET_LOCAL = 0x20u, SET_LOCAL = 0x21u, TEE_LOCAL = 0x22u, GET_GLOBAL = 0x23u, SET_GLOBAL = 0x24u, SELECT = 0x1bu, CALL = 0x10u, CALL_INDIRECT = 0x11u, // INTEGER ARITHMETIC INSTRUCTIONS // int32 I32_ADD = 0x6au, I32_SUB = 0x6bu, I32_MUL = 0x6cu, I32_DIV_S = 0x6du, I32_DIV_U = 0x6eu, I32_REM_S = 0x6fu, I32_REM_U = 0x70u, I32_AND = 0x71u, I32_OR = 0x72u, I32_XOR = 0x73u, I32_SHL = 0x74u, I32_SHR_S = 0x75u, I32_SHR_U = 0x76u, I32_ROTL = 0x77u, I32_ROTR = 0x78u, I32_CLZ = 0x67u, I32_CTZ = 0x68u, I32_POPCNT = 0x69u, I32_EQZ = 0x45u, // int64 I64_ADD = 0x7cu, I64_SUB = 0x7du, I64_MUL = 0x7eu, I64_DIV_S = 0x7fu, I64_DIV_U = 0x80u, I64_REM_S = 0x81u, I64_REM_U = 0x82u, I64_AND = 0x83u, I64_OR = 0x84u, I64_XOR = 0x85u, I64_SHL = 0x86u, I64_SHR_S = 0x87u, I64_SHR_U = 0x88u, I64_ROTL = 0x89u, I64_ROTR = 0x8au, I64_CLZ = 0x79u, I64_CTZ = 0x7au, I64_POPCNT = 0x7bu, I64_EQZ = 0x50u, // FLOATING POINT ARITHMETIC INSTRUCTIONS // float32 F32_ADD = 0x92u, F32_SUB = 0x93u, F32_MUL = 0x94u, F32_DIV = 0x95u, F32_SQRT = 0x91u, F32_MIN = 0x96u, F32_MAX = 0x97u, F32_CEIL = 0x8du, F32_FLOOR = 0x8eu, F32_TRUNC = 0x8fu, F32_NEAREST = 0x90u, F32_ABS = 0x8bu, F32_NEG = 0x8cu, F32_COPYSIGN = 0x98u, // float64 F64_ADD = 0xa0u, F64_SUB = 0xa1u, F64_MUL = 0xa2u, F64_DIV = 0xa3u, F64_SQRT = 0x9fu, F64_MIN = 0xa4u, F64_MAX = 0xa5u, F64_CEIL = 0x9bu, F64_FLOOR = 0x9cu, F64_TRUNC = 0x9du, F64_NEAREST = 0x9eu, F64_ABS = 0x99u, F64_NEG = 0x9au, F64_COPYSIGN = 0xa6u, // INTEGER COMPARISON INSTRUCTIONS // int32 I32_EQ = 0x46u, I32_NE = 0x47u, I32_LT_S = 0x48u, I32_LT_U = 0x49u, I32_GT_S = 0x4au, I32_GT_U = 0x4bu, I32_LE_S = 0x4cu, I32_LE_U = 0x4du, I32_GE_S = 0x4eu, I32_GE_U = 0x4fu, // int64 I64_EQ = 0x51u, I64_NE = 0x52u, I64_LT_S = 0x53u, I64_LT_U = 0x54u, I64_GT_S = 0x55u, I64_GT_U = 0x56u, I64_LE_S = 0x57u, I64_LE_U = 0x58u, I64_GE_S = 0x59u, I64_GE_U = 0x5au, // FLOATING POINT COMPARISON INSTRUCTIONS // float32 F32_EQ = 0x5bu, F32_NE = 0x5cu, F32_LT = 0x5du, F32_GT = 0x5eu, F32_LE = 0x5fu, F32_GE = 0x60u, // float64 F64_EQ = 0x61u, F64_NE = 0x62u, F64_LT = 0x63u, F64_GT = 0x64u, F64_LE = 0x65u, F64_GE = 0x66u, // CONVERSION INSTRUCTIONS // to int32 I32_WRAP = 0xa7u, I32_TRUNC_F32_S = 0xa8u, I32_TRUNC_F32_U = 0xa9u, I32_TRUNC_F64_S = 0xaau, I32_TRUNC_F64_U = 0xabu, I32_REINTERPRET_F32 = 0xbcu, // to int64 I64_EXTEND_S = 0xacu, I64_EXTEND_U = 0xadu, I64_TRUNC_F32_S = 0xaeu, I64_TRUNC_F32_U = 0xafu, I64_TRUNC_F64_S = 0xb0u, I64_TRUNC_F64_U = 0xb1u, I64_REINTERPRET_F64 = 0xbdu, // to float32 F32_DEMOTE = 0xb6u, F32_CONVERT_I32_S = 0xb2u, F32_CONVERT_I32_U = 0xb3u, F32_CONVERT_I64_S = 0xb4u, F32_CONVERT_I64_U = 0xb5u, F32_REINTERPRET_I32 = 0xbeu, // to float64 F64_PROMOTE = 0xbbu, F64_CONVERT_I32_S = 0xb7u, F64_CONVERT_I32_U = 0xb8u, F64_CONVERT_I64_S = 0xb9u, F64_CONVERT_I64_U = 0xbau, F64_REINTERPRET_I64 = 0xbfu, // LOAD AND STORE INSTRUCTIONSu I32_LOAD = 0x28u, I64_LOAD = 0x29u, F32_LOAD = 0x2au, F64_LOAD = 0x2bu, I32_LOAD8_S = 0x2cu, I32_LOAD8_U = 0x2du, I32_LOAD16_S = 0x2eu, I32_LOAD16_U = 0x2fu, I64_LOAD8_S = 0x30u, I64_LOAD8_U = 0x31u, I64_LOAD16_S = 0x32u, I64_LOAD16_U = 0x33u, I64_LOAD32_S = 0x34u, I64_LOAD32_U = 0x35u, I32_STORE = 0x36u, I64_STORE = 0x37u, F32_STORE = 0x38u, F64_STORE = 0x39u, I32_STORE8 = 0x3au, I32_STORE16 = 0x3bu, I64_STORE8 = 0x3cu, I64_STORE16 = 0x3du, I64_STORE32 = 0x3eu, // MEMORY INSTRUCTIONS GROW_MEMORY = 0x40u, CURRENT_MEMORY = 0x3fu, }; template <template <OpCode> class TemplateVis, class Vis> decltype(auto) visit_opcode_template(Vis&& visitor) { switch(opcode()) { /// CONTROL FLOW OPS case OpCode::UNREACHABLE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::UNREACHABLE>{}); case OpCode::NOP: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::NOP>{}); case OpCode::BLOCK: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BLOCK>{}); case OpCode::LOOP: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::LOOP>{}); case OpCode::IF: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::IF>{}); case OpCode::ELSE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::ELSE>{}); case OpCode::END: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::END>{}); case OpCode::BR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR>{}); case OpCode::BR_IF: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR_IF>{}); case OpCode::BR_TABLE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::BR_TABLE>{}); case OpCode::RETURN: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::RETURN>{}); case OpCode::CALL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CALL>{}); case OpCode::CALL_INDIRECT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CALL_INDIRECT>{}); /// PARAMETRIC OPS case OpCode::DROP: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::DROP>{}); case OpCode::SELECT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SELECT>{}); case OpCode::GET_LOCAL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GET_LOCAL>{}); case OpCode::SET_LOCAL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SET_LOCAL>{}); case OpCode::TEE_LOCAL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::TEE_LOCAL>{}); case OpCode::GET_GLOBAL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GET_GLOBAL>{}); case OpCode::SET_GLOBAL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::SET_GLOBAL>{}); /// MEMORY OPS // load case OpCode::I32_LOAD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD>{}); case OpCode::I64_LOAD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD>{}); case OpCode::F32_LOAD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LOAD>{}); case OpCode::F64_LOAD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LOAD>{}); // i32 extending loads case OpCode::I32_LOAD8_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD8_S>{}); case OpCode::I32_LOAD8_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD8_U>{}); case OpCode::I32_LOAD16_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD16_S>{}); case OpCode::I32_LOAD16_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LOAD16_U>{}); // i64 extending loads case OpCode::I64_LOAD8_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD8_S>{}); case OpCode::I64_LOAD8_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD8_U>{}); case OpCode::I64_LOAD16_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD16_S>{}); case OpCode::I64_LOAD16_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD16_U>{}); case OpCode::I64_LOAD32_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD32_S>{}); case OpCode::I64_LOAD32_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LOAD32_U>{}); // store case OpCode::I32_STORE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE>{}); case OpCode::I64_STORE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE>{}); case OpCode::F32_STORE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_STORE>{}); case OpCode::F64_STORE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_STORE>{}); // i32 wrapping stores case OpCode::I32_STORE8: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE8>{}); case OpCode::I32_STORE16: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_STORE16>{}); // i64 wrapping stores case OpCode::I64_STORE8: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE8>{}); case OpCode::I64_STORE16: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE16>{}); case OpCode::I64_STORE32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_STORE32>{}); // misc case OpCode::CURRENT_MEMORY: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::CURRENT_MEMORY>{}); case OpCode::GROW_MEMORY: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::GROW_MEMORY>{}); /// CONST OPERATIONS case OpCode::I32_CONST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CONST>{}); case OpCode::I64_CONST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CONST>{}); case OpCode::F32_CONST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONST>{}); case OpCode::F64_CONST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONST>{}); /// COMPARISON OPERATIONS // i32 comparisons case OpCode::I32_EQZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_EQZ>{}); case OpCode::I32_EQ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_EQ>{}); case OpCode::I32_NE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_NE>{}); case OpCode::I32_LT_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LT_S>{}); case OpCode::I32_LT_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LT_U>{}); case OpCode::I32_GT_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GT_S>{}); case OpCode::I32_GT_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GT_U>{}); case OpCode::I32_LE_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LE_S>{}); case OpCode::I32_LE_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_LE_U>{}); case OpCode::I32_GE_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GE_S>{}); case OpCode::I32_GE_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_GE_U>{}); // i64 comparisons case OpCode::I64_EQZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EQZ>{}); case OpCode::I64_EQ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EQ>{}); case OpCode::I64_NE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_NE>{}); case OpCode::I64_LT_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LT_S>{}); case OpCode::I64_LT_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LT_U>{}); case OpCode::I64_GT_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GT_S>{}); case OpCode::I64_GT_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GT_U>{}); case OpCode::I64_LE_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LE_S>{}); case OpCode::I64_LE_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_LE_U>{}); case OpCode::I64_GE_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GE_S>{}); case OpCode::I64_GE_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_GE_U>{}); // f32 comparisons case OpCode::F32_EQ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_EQ>{}); case OpCode::F32_NE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NE>{}); case OpCode::F32_LT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LT>{}); case OpCode::F32_GT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_GT>{}); case OpCode::F32_LE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_LE>{}); case OpCode::F32_GE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_GE>{}); // f64 comparisons case OpCode::F64_EQ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_EQ>{}); case OpCode::F64_NE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NE>{}); case OpCode::F64_LT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LT>{}); case OpCode::F64_GT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_GT>{}); case OpCode::F64_LE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_LE>{}); case OpCode::F64_GE: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_GE>{}); /// NUMERIC OPERATIONS // i32 operations case OpCode::I32_CLZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CLZ>{}); case OpCode::I32_CTZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_CTZ>{}); case OpCode::I32_POPCNT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_POPCNT>{}); case OpCode::I32_ADD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ADD>{}); case OpCode::I32_SUB: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SUB>{}); case OpCode::I32_MUL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_MUL>{}); case OpCode::I32_DIV_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_DIV_S>{}); case OpCode::I32_DIV_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_DIV_U>{}); case OpCode::I32_REM_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_REM_S>{}); case OpCode::I32_REM_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_REM_U>{}); case OpCode::I32_AND: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_AND>{}); case OpCode::I32_OR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_OR>{}); case OpCode::I32_XOR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_XOR>{}); case OpCode::I32_SHL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHL>{}); case OpCode::I32_SHR_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHR_S>{}); case OpCode::I32_SHR_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_SHR_U>{}); case OpCode::I32_ROTL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ROTL>{}); case OpCode::I32_ROTR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_ROTR>{}); // i64 operations case OpCode::I64_CLZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CLZ>{}); case OpCode::I64_CTZ: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_CTZ>{}); case OpCode::I64_POPCNT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_POPCNT>{}); case OpCode::I64_ADD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ADD>{}); case OpCode::I64_SUB: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SUB>{}); case OpCode::I64_MUL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_MUL>{}); case OpCode::I64_DIV_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_DIV_S>{}); case OpCode::I64_DIV_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_DIV_U>{}); case OpCode::I64_REM_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_REM_S>{}); case OpCode::I64_REM_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_REM_U>{}); case OpCode::I64_AND: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_AND>{}); case OpCode::I64_OR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_OR>{}); case OpCode::I64_XOR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_XOR>{}); case OpCode::I64_SHL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHL>{}); case OpCode::I64_SHR_S: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHR_S>{}); case OpCode::I64_SHR_U: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_SHR_U>{}); case OpCode::I64_ROTL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ROTL>{}); case OpCode::I64_ROTR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_ROTR>{}); // f32 operations case OpCode::F32_ABS: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_ABS>{}); case OpCode::F32_NEG: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NEG>{}); case OpCode::F32_CEIL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CEIL>{}); case OpCode::F32_FLOOR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_FLOOR>{}); case OpCode::F32_TRUNC: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_TRUNC>{}); case OpCode::F32_NEAREST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_NEAREST>{}); case OpCode::F32_SQRT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_SQRT>{}); case OpCode::F32_ADD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_ADD>{}); case OpCode::F32_SUB: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_SUB>{}); case OpCode::F32_MUL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MUL>{}); case OpCode::F32_DIV: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_DIV>{}); case OpCode::F32_MIN: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MIN>{}); case OpCode::F32_MAX: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_MAX>{}); case OpCode::F32_COPYSIGN: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_COPYSIGN>{}); // f64 operations case OpCode::F64_ABS: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_ABS>{}); case OpCode::F64_NEG: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NEG>{}); case OpCode::F64_CEIL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CEIL>{}); case OpCode::F64_FLOOR: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_FLOOR>{}); case OpCode::F64_TRUNC: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_TRUNC>{}); case OpCode::F64_NEAREST: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_NEAREST>{}); case OpCode::F64_SQRT: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_SQRT>{}); case OpCode::F64_ADD: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_ADD>{}); case OpCode::F64_SUB: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_SUB>{}); case OpCode::F64_MUL: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MUL>{}); case OpCode::F64_DIV: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_DIV>{}); case OpCode::F64_MIN: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MIN>{}); case OpCode::F64_MAX: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_MAX>{}); case OpCode::F64_COPYSIGN: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_COPYSIGN>{}); /// CONVERSION OPERATIONS case OpCode::I32_WRAP_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_WRAP_I64>{}); // float-to-int32 tuncating conversion case OpCode::I32_TRUNC_S_F32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_S_F32>{}); case OpCode::I32_TRUNC_U_F32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_U_F32>{}); case OpCode::I32_TRUNC_S_F64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_S_F64>{}); case OpCode::I32_TRUNC_U_F64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I32_TRUNC_U_F64>{}); // int32-to-int64 extending conversion case OpCode::I64_EXTEND_S_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EXTEND_S_I32>{}); case OpCode::I64_EXTEND_U_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_EXTEND_U_I32>{}); // float-to-int64 truncating conversion case OpCode::I64_TRUNC_S_F32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_S_F32>{}); case OpCode::I64_TRUNC_U_F32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_U_F32>{}); case OpCode::I64_TRUNC_S_F64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_S_F64>{}); case OpCode::I64_TRUNC_U_F64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::I64_TRUNC_U_F64>{}); // int-to-float32 conversion case OpCode::F32_CONVERT_S_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_S_I32>{}); case OpCode::F32_CONVERT_U_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_U_I32>{}); case OpCode::F32_CONVERT_S_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_S_I64>{}); case OpCode::F32_CONVERT_U_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_CONVERT_U_I64>{}); // float64-to-float32 demoting conversion case OpCode::F32_DEMOTE_F64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F32_DEMOTE_F64>{}); // int-to-float64 conversion case OpCode::F64_CONVERT_S_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_S_I32>{}); case OpCode::F64_CONVERT_U_I32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_U_I32>{}); case OpCode::F64_CONVERT_S_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_S_I64>{}); case OpCode::F64_CONVERT_U_I64: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_CONVERT_U_I64>{}); // float32-to-float64 promoting conversion case OpCode::F64_PROMOTE_F32: return std::invoke(std::forward<Vis>(visitor), TemplateVis<OpCode::F64_PROMOTE_F32>{}); default: assert(false); } } template <LanguageType LT> using language_type_constant_t = std::integral_constant<LanguageType, LT>; template <class Vis> decltype(auto) visit_opcode(Vis&& visitor) { return visit_opcode_template<language_type_constant_t>(visitor); } inline constexpr const std::array<OpCode, 168u> all_opcodes { OpCode::UNREACHABLE, OpCode::NOP, OpCode::BLOCK, OpCode::LOOP, OpCode::IF, OpCode::ELSE, OpCode::END, OpCode::BR, OpCode::BR_IF, OpCode::BR_TABLE, OpCode::RETURN, OpCode::CALL, OpCode::CALL_INDIRECT, OpCode::DROP, OpCode::SELECT, OpCode::GET_LOCAL, OpCode::SET_LOCAL, OpCode::TEE_LOCAL, OpCode::GET_GLOBAL, OpCode::SET_GLOBAL, OpCode::I32_LOAD, OpCode::I64_LOAD, OpCode::F32_LOAD, OpCode::F64_LOAD, OpCode::I32_LOAD8_S, OpCode::I32_LOAD8_U, OpCode::I32_LOAD16_S, OpCode::I32_LOAD16_U, OpCode::I64_LOAD8_S, OpCode::I64_LOAD8_U, OpCode::I64_LOAD16_S, OpCode::I64_LOAD16_U, OpCode::I64_LOAD32_S, OpCode::I64_LOAD32_U, OpCode::I32_STORE, OpCode::I64_STORE, OpCode::F32_STORE, OpCode::F64_STORE, OpCode::I32_STORE8, OpCode::I32_STORE16, OpCode::I64_STORE8, OpCode::I64_STORE16, OpCode::I64_STORE32, OpCode::CURRENT_MEMORY, OpCode::GROW_MEMORY, OpCode::I32_CONST, OpCode::I64_CONST, OpCode::F32_CONST, OpCode::F64_CONST, OpCode::I32_EQZ, OpCode::I32_EQ, OpCode::I32_NE, OpCode::I32_LT_S, OpCode::I32_LT_U, OpCode::I32_GT_S, OpCode::I32_GT_U, OpCode::I32_LE_S, OpCode::I32_LE_U, OpCode::I32_GE_S, OpCode::I32_GE_U, OpCode::I64_EQZ, OpCode::I64_EQ, OpCode::I64_NE, OpCode::I64_LT_S, OpCode::I64_LT_U, OpCode::I64_GT_S, OpCode::I64_GT_U, OpCode::I64_LE_S, OpCode::I64_LE_U, OpCode::I64_GE_S, OpCode::I64_GE_U, OpCode::F32_EQ, OpCode::F32_NE, OpCode::F32_LT, OpCode::F32_GT, OpCode::F32_LE, OpCode::F32_GE, OpCode::F64_EQ, OpCode::F64_NE, OpCode::F64_LT, OpCode::F64_GT, OpCode::F64_LE, OpCode::F64_GE, OpCode::I32_CLZ, OpCode::I32_CTZ, OpCode::I32_POPCNT, OpCode::I32_ADD, OpCode::I32_SUB, OpCode::I32_MUL, OpCode::I32_DIV_S, OpCode::I32_DIV_U, OpCode::I32_REM_S, OpCode::I32_REM_U, OpCode::I32_AND, OpCode::I32_OR, OpCode::I32_XOR, OpCode::I32_SHL, OpCode::I32_SHR_S, OpCode::I32_SHR_U, OpCode::I32_ROTL, OpCode::I32_ROTR, OpCode::I64_CLZ, OpCode::I64_CTZ, OpCode::I64_POPCNT, OpCode::I64_ADD, OpCode::I64_SUB, OpCode::I64_MUL, OpCode::I64_DIV_S, OpCode::I64_DIV_U, OpCode::I64_REM_S, OpCode::I64_REM_U, OpCode::I64_AND, OpCode::I64_OR, OpCode::I64_XOR, OpCode::I64_SHL, OpCode::I64_SHR_S, OpCode::I64_SHR_U, OpCode::I64_ROTL, OpCode::I64_ROTR, OpCode::F32_ABS, OpCode::F32_NEG, OpCode::F32_CEIL, OpCode::F32_FLOOR, OpCode::F32_TRUNC, OpCode::F32_NEAREST, OpCode::F32_SQRT, OpCode::F32_ADD, OpCode::F32_SUB, OpCode::F32_MUL, OpCode::F32_DIV, OpCode::F32_MIN, OpCode::F32_MAX, OpCode::F32_COPYSIGN, OpCode::F64_ABS, OpCode::F64_NEG, OpCode::F64_CEIL, OpCode::F64_FLOOR, OpCode::F64_TRUNC, OpCode::F64_NEAREST, OpCode::F64_SQRT, OpCode::F64_ADD, OpCode::F64_SUB, OpCode::F64_MUL, OpCode::F64_DIV, OpCode::F64_MIN, OpCode::F64_MAX, OpCode::F64_COPYSIGN, OpCode::I32_WRAP_I64, OpCode::I32_TRUNC_S_F32, OpCode::I32_TRUNC_U_F32, OpCode::I32_TRUNC_S_F64, OpCode::I32_TRUNC_U_F64, OpCode::I64_EXTEND_S_I32, OpCode::I64_EXTEND_U_I32, OpCode::I64_TRUNC_S_F32, OpCode::I64_TRUNC_U_F32, OpCode::I64_TRUNC_S_F64, OpCode::I64_TRUNC_U_F64, OpCode::F32_CONVERT_S_I32, OpCode::F32_CONVERT_U_I32, OpCode::F32_CONVERT_S_I64, OpCode::F32_CONVERT_U_I64, OpCode::F32_DEMOTE_F64, OpCode::F64_CONVERT_S_I32, OpCode::F64_CONVERT_U_I32, OpCode::F64_CONVERT_S_I64, OpCode::F64_CONVERT_U_I64, OpCode::F64_PROMOTE_F32 }; namespace detail { const std::bitset<256>& opcode_mask() { static const std::bitset<256> bs {[]() -> std::bitset<256> { using int_type = std::underlying_type_t<OpCode>; std::bitset<256> tmp; for(OpCode op: all_opcodes) tmp.set(static_cast<std::size_t>(op)); return tmp; }()}; return bs; } const std::array<const char*, 256>& opcode_names() { static const std::array<const char*, 256> names { [](){ // immediately-invoked lambda std::array<const char*, 256> tmp; tmp.fill(nullptr); using int_type = std::underlying_type_t<OpCode>; tmp[static_cast<int_type>(OpCode::BLOCK)] = "block"; tmp[static_cast<int_type>(OpCode::LOOP)] = "loop"; tmp[static_cast<int_type>(OpCode::BR)] = "br"; tmp[static_cast<int_type>(OpCode::BR_IF)] = "br_if"; tmp[static_cast<int_type>(OpCode::BR_TABLE)] = "br_table"; tmp[static_cast<int_type>(OpCode::IF)] = "if"; tmp[static_cast<int_type>(OpCode::ELSE)] = "else"; tmp[static_cast<int_type>(OpCode::END)] = "end"; tmp[static_cast<int_type>(OpCode::RETURN)] = "return"; tmp[static_cast<int_type>(OpCode::UNREACHABLE)] = "unreachable"; tmp[static_cast<int_type>(OpCode::NOP)] = "nop"; tmp[static_cast<int_type>(OpCode::DROP)] = "drop"; tmp[static_cast<int_type>(OpCode::I32_CONST)] = "i32.const"; tmp[static_cast<int_type>(OpCode::I64_CONST)] = "i64.const"; tmp[static_cast<int_type>(OpCode::F32_CONST)] = "f32.const"; tmp[static_cast<int_type>(OpCode::F64_CONST)] = "f64.const"; tmp[static_cast<int_type>(OpCode::GET_LOCAL)] = "get_local"; tmp[static_cast<int_type>(OpCode::SET_LOCAL)] = "set_local"; tmp[static_cast<int_type>(OpCode::TEE_LOCAL)] = "tee_local"; tmp[static_cast<int_type>(OpCode::GET_GLOBAL)] = "get_global"; tmp[static_cast<int_type>(OpCode::SET_GLOBAL)] = "set_global"; tmp[static_cast<int_type>(OpCode::SELECT)] = "select"; tmp[static_cast<int_type>(OpCode::CALL)] = "call"; tmp[static_cast<int_type>(OpCode::CALL_INDIRECT)] = "call_indirect"; tmp[static_cast<int_type>(OpCode::I32_ADD)] = "i32.add"; tmp[static_cast<int_type>(OpCode::I32_SUB)] = "i32.sub"; tmp[static_cast<int_type>(OpCode::I32_MUL)] = "i32.mul"; tmp[static_cast<int_type>(OpCode::I32_DIV_S)] = "i32.div_s"; tmp[static_cast<int_type>(OpCode::I32_DIV_U)] = "i32.div_u"; tmp[static_cast<int_type>(OpCode::I32_REM_S)] = "i32.rem_s"; tmp[static_cast<int_type>(OpCode::I32_REM_U)] = "i32.rem_u"; tmp[static_cast<int_type>(OpCode::I32_AND)] = "i32.and"; tmp[static_cast<int_type>(OpCode::I32_OR)] = "i32.or"; tmp[static_cast<int_type>(OpCode::I32_XOR)] = "i32.xor"; tmp[static_cast<int_type>(OpCode::I32_SHL)] = "i32.shl"; tmp[static_cast<int_type>(OpCode::I32_SHR_S)] = "i32.shr_s"; tmp[static_cast<int_type>(OpCode::I32_SHR_U)] = "i32.shr_u"; tmp[static_cast<int_type>(OpCode::I32_ROTL)] = "i32.rotl"; tmp[static_cast<int_type>(OpCode::I32_ROTR)] = "i32.rotr"; tmp[static_cast<int_type>(OpCode::I32_CLZ)] = "i32.clz"; tmp[static_cast<int_type>(OpCode::I32_CTZ)] = "i32.ctz"; tmp[static_cast<int_type>(OpCode::I32_POPCNT)] = "i32.popcnt"; tmp[static_cast<int_type>(OpCode::I32_EQZ)] = "i32.eqz"; tmp[static_cast<int_type>(OpCode::I64_ADD)] = "i64.add"; tmp[static_cast<int_type>(OpCode::I64_SUB)] = "i64.sub"; tmp[static_cast<int_type>(OpCode::I64_MUL)] = "i64.mul"; tmp[static_cast<int_type>(OpCode::I64_DIV_S)] = "i64.div_s"; tmp[static_cast<int_type>(OpCode::I64_DIV_U)] = "i64.div_u"; tmp[static_cast<int_type>(OpCode::I64_REM_S)] = "i64.rem_s"; tmp[static_cast<int_type>(OpCode::I64_REM_U)] = "i64.rem_u"; tmp[static_cast<int_type>(OpCode::I64_AND)] = "i64.and"; tmp[static_cast<int_type>(OpCode::I64_OR)] = "i64.or"; tmp[static_cast<int_type>(OpCode::I64_XOR)] = "i64.xor"; tmp[static_cast<int_type>(OpCode::I64_SHL)] = "i64.shl"; tmp[static_cast<int_type>(OpCode::I64_SHR_S)] = "i64.shr_s"; tmp[static_cast<int_type>(OpCode::I64_SHR_U)] = "i64.shr_u"; tmp[static_cast<int_type>(OpCode::I64_ROTL)] = "i64.rotl"; tmp[static_cast<int_type>(OpCode::I64_ROTR)] = "i64.rotr"; tmp[static_cast<int_type>(OpCode::I64_CLZ)] = "i64.clz"; tmp[static_cast<int_type>(OpCode::I64_CTZ)] = "i64.ctz"; tmp[static_cast<int_type>(OpCode::I64_POPCNT)] = "i64.popcnt"; tmp[static_cast<int_type>(OpCode::I64_EQZ)] = "i64.eqz"; tmp[static_cast<int_type>(OpCode::F32_ADD)] = "f32.add"; tmp[static_cast<int_type>(OpCode::F32_SUB)] = "f32.sub"; tmp[static_cast<int_type>(OpCode::F32_MUL)] = "f32.mul"; tmp[static_cast<int_type>(OpCode::F32_DIV)] = "f32.div"; tmp[static_cast<int_type>(OpCode::F32_SQRT)] = "f32.sqrt"; tmp[static_cast<int_type>(OpCode::F32_MIN)] = "f32.min"; tmp[static_cast<int_type>(OpCode::F32_MAX)] = "f32.max"; tmp[static_cast<int_type>(OpCode::F32_CEIL)] = "f32.ceil"; tmp[static_cast<int_type>(OpCode::F32_FLOOR)] = "f32.floor"; tmp[static_cast<int_type>(OpCode::F32_TRUNC)] = "f32.trunc"; tmp[static_cast<int_type>(OpCode::F32_NEAREST)] = "f32.nearest"; tmp[static_cast<int_type>(OpCode::F32_ABS)] = "f32.abs"; tmp[static_cast<int_type>(OpCode::F32_NEG)] = "f32.neg"; tmp[static_cast<int_type>(OpCode::F32_COPYSIGN)] = "f32.copysign"; tmp[static_cast<int_type>(OpCode::F64_ADD)] = "f64.add"; tmp[static_cast<int_type>(OpCode::F64_SUB)] = "f64.sub"; tmp[static_cast<int_type>(OpCode::F64_MUL)] = "f64.mul"; tmp[static_cast<int_type>(OpCode::F64_DIV)] = "f64.div"; tmp[static_cast<int_type>(OpCode::F64_SQRT)] = "f64.sqrt"; tmp[static_cast<int_type>(OpCode::F64_MIN)] = "f64.min"; tmp[static_cast<int_type>(OpCode::F64_MAX)] = "f64.max"; tmp[static_cast<int_type>(OpCode::F64_CEIL)] = "f64.ceil"; tmp[static_cast<int_type>(OpCode::F64_FLOOR)] = "f64.floor"; tmp[static_cast<int_type>(OpCode::F64_TRUNC)] = "f64.trunc"; tmp[static_cast<int_type>(OpCode::F64_NEAREST)] = "f64.nearest"; tmp[static_cast<int_type>(OpCode::F64_ABS)] = "f64.abs"; tmp[static_cast<int_type>(OpCode::F64_NEG)] = "f64.neg"; tmp[static_cast<int_type>(OpCode::F64_COPYSIGN)] = "f64.copysign"; tmp[static_cast<int_type>(OpCode::I32_EQ)] = "i32.eq"; tmp[static_cast<int_type>(OpCode::I32_NE)] = "i32.ne"; tmp[static_cast<int_type>(OpCode::I32_LT_S)] = "i32.lt_s"; tmp[static_cast<int_type>(OpCode::I32_LT_U)] = "i32.lt_u"; tmp[static_cast<int_type>(OpCode::I32_GT_S)] = "i32.gt_s"; tmp[static_cast<int_type>(OpCode::I32_GT_U)] = "i32.gt_u"; tmp[static_cast<int_type>(OpCode::I32_LE_S)] = "i32.le_s"; tmp[static_cast<int_type>(OpCode::I32_LE_U)] = "i32.le_u"; tmp[static_cast<int_type>(OpCode::I32_GE_S)] = "i32.ge_s"; tmp[static_cast<int_type>(OpCode::I32_GE_U)] = "i32.ge_u"; tmp[static_cast<int_type>(OpCode::I64_EQ)] = "i64.eq"; tmp[static_cast<int_type>(OpCode::I64_NE)] = "i64.ne"; tmp[static_cast<int_type>(OpCode::I64_LT_S)] = "i64.lt_s"; tmp[static_cast<int_type>(OpCode::I64_LT_U)] = "i64.lt_u"; tmp[static_cast<int_type>(OpCode::I64_GT_S)] = "i64.gt_s"; tmp[static_cast<int_type>(OpCode::I64_GT_U)] = "i64.gt_u"; tmp[static_cast<int_type>(OpCode::I64_LE_S)] = "i64.le_s"; tmp[static_cast<int_type>(OpCode::I64_LE_U)] = "i64.le_u"; tmp[static_cast<int_type>(OpCode::I64_GE_S)] = "i64.ge_s"; tmp[static_cast<int_type>(OpCode::I64_GE_U)] = "i64.ge_u"; tmp[static_cast<int_type>(OpCode::F32_EQ)] = "f32.eq"; tmp[static_cast<int_type>(OpCode::F32_NE)] = "f32.ne"; tmp[static_cast<int_type>(OpCode::F32_LT)] = "f32.lt"; tmp[static_cast<int_type>(OpCode::F32_GT)] = "f32.gt"; tmp[static_cast<int_type>(OpCode::F32_LE)] = "f32.le"; tmp[static_cast<int_type>(OpCode::F32_GE)] = "f32.ge"; tmp[static_cast<int_type>(OpCode::F64_EQ)] = "f64.eq"; tmp[static_cast<int_type>(OpCode::F64_NE)] = "f64.ne"; tmp[static_cast<int_type>(OpCode::F64_LT)] = "f64.lt"; tmp[static_cast<int_type>(OpCode::F64_GT)] = "f64.gt"; tmp[static_cast<int_type>(OpCode::F64_LE)] = "f64.le"; tmp[static_cast<int_type>(OpCode::F64_GE)] = "f64.ge"; tmp[static_cast<int_type>(OpCode::I32_WRAP)] = "i32.wrap/i64"; tmp[static_cast<int_type>(OpCode::I32_TRUNC_F32_S)] = "i32.trunc_s/f32"; tmp[static_cast<int_type>(OpCode::I32_TRUNC_F32_U)] = "i32.trunc_u/f32"; tmp[static_cast<int_type>(OpCode::I32_TRUNC_F64_S)] = "i32.trunc_s/f64"; tmp[static_cast<int_type>(OpCode::I32_TRUNC_F64_U)] = "i32.trunc_u/f64"; tmp[static_cast<int_type>(OpCode::I32_REINTERPRET_F32)] = "i32.reinterpret/f32"; tmp[static_cast<int_type>(OpCode::I64_EXTEND_S)] = "i64.extend_s/i32"; tmp[static_cast<int_type>(OpCode::I64_EXTEND_U)] = "i64.extend_u/i32"; tmp[static_cast<int_type>(OpCode::I64_TRUNC_F32_S)] = "i64.trunc_s/f32"; tmp[static_cast<int_type>(OpCode::I64_TRUNC_F32_U)] = "i64.trunc_u/f32"; tmp[static_cast<int_type>(OpCode::I64_TRUNC_F64_S)] = "i64.trunc_s/f64"; tmp[static_cast<int_type>(OpCode::I64_TRUNC_F64_U)] = "i64.trunc_u/f64"; tmp[static_cast<int_type>(OpCode::I64_REINTERPRET_F64)] = "i64.reinterpret/f64"; tmp[static_cast<int_type>(OpCode::F32_DEMOTE)] = "f32.demote/f64"; tmp[static_cast<int_type>(OpCode::F32_CONVERT_I32_S)] = "f32.convert_s/i32"; tmp[static_cast<int_type>(OpCode::F32_CONVERT_I32_U)] = "f32.convert_u/i32"; tmp[static_cast<int_type>(OpCode::F32_CONVERT_I64_S)] = "f32.convert_s/i64"; tmp[static_cast<int_type>(OpCode::F32_CONVERT_I64_U)] = "f32.convert_u/i64"; tmp[static_cast<int_type>(OpCode::F32_REINTERPRET_I32)] = "f32.reinterpret/i32"; tmp[static_cast<int_type>(OpCode::F64_PROMOTE)] = "f64.promote"; tmp[static_cast<int_type>(OpCode::F64_CONVERT_I32_S)] = "f64.convert_s/i32"; tmp[static_cast<int_type>(OpCode::F64_CONVERT_I32_U)] = "f64.convert_u/i32"; tmp[static_cast<int_type>(OpCode::F64_CONVERT_I64_S)] = "f64.convert_s/i64"; tmp[static_cast<int_type>(OpCode::F64_CONVERT_I64_U)] = "f64.convert_u/i64"; tmp[static_cast<int_type>(OpCode::F64_REINTERPRET_I64)] = "f64.reinterpret/i64"; tmp[static_cast<int_type>(OpCode::I32_LOAD)] = "i32.load"; tmp[static_cast<int_type>(OpCode::I64_LOAD)] = "i64.load"; tmp[static_cast<int_type>(OpCode::F32_LOAD)] = "f32.load"; tmp[static_cast<int_type>(OpCode::F64_LOAD)] = "f64.load"; tmp[static_cast<int_type>(OpCode::I32_LOAD8_S)] = "i32.load8_s"; tmp[static_cast<int_type>(OpCode::I32_LOAD8_U)] = "i32.load8_u"; tmp[static_cast<int_type>(OpCode::I32_LOAD16_S)] = "i32.load16_s"; tmp[static_cast<int_type>(OpCode::I32_LOAD16_U)] = "i32.load16_u"; tmp[static_cast<int_type>(OpCode::I64_LOAD8_S)] = "i64.load8_s"; tmp[static_cast<int_type>(OpCode::I64_LOAD8_U)] = "i64.load8_u"; tmp[static_cast<int_type>(OpCode::I64_LOAD16_S)] = "i64.load16_s"; tmp[static_cast<int_type>(OpCode::I64_LOAD16_U)] = "i64.load16_u"; tmp[static_cast<int_type>(OpCode::I64_LOAD32_S)] = "i64.load32_s"; tmp[static_cast<int_type>(OpCode::I64_LOAD32_U)] = "i64.load32_u"; tmp[static_cast<int_type>(OpCode::I32_STORE)] = "i32.store"; tmp[static_cast<int_type>(OpCode::I64_STORE)] = "i64.store"; tmp[static_cast<int_type>(OpCode::F32_STORE)] = "f32.store"; tmp[static_cast<int_type>(OpCode::F64_STORE)] = "f64.store"; tmp[static_cast<int_type>(OpCode::I32_STORE8)] = "i32.store8"; tmp[static_cast<int_type>(OpCode::I32_STORE16)] = "i32.store16"; tmp[static_cast<int_type>(OpCode::I64_STORE8)] = "i64.store8"; tmp[static_cast<int_type>(OpCode::I64_STORE16)] = "i64.store16"; tmp[static_cast<int_type>(OpCode::I64_STORE32)] = "i64.store32"; tmp[static_cast<int_type>(OpCode::GROW_MEMORY)] = "grow_memory"; tmp[static_cast<int_type>(OpCode::CURRENT_MEMORY)] = "current_memory"; return tmp; }()/* invoke lambda */}; /* names */ return names; } } /* namespace detail */ std::ostream& operator<<(std::ostream& os, OpCode oc) { const char* name = detail::opcode_names()[static_cast<unsigned>(oc)]; if(not name) { os << "bad_opcode(0x" << std::hex << std::setw(2) << std::setfill('0'); os << static_cast<unsigned>(oc) << ')'; } else { os << name; } return os; } [[gnu::pure]] inline bool opcode_exists(std::underlying_type_t<OpCode> oc) { return detail::opcode_mask().test(oc); } namespace detail { template <class It> [[gnu::pure]] std::tuple<wasm_uint32_t, wasm_uint32_t, It> read_memory_immediate(It first, It last) { alignas(wasm_uint32_t) char buff1[sizeof(wasm_uint32_t)]; alignas(wasm_uint32_t) char buff2[sizeof(wasm_uint32_t)]; wasm_uint32_t flags; wasm_uint32_t offset; for(auto& chr: buff1) { assert(first != last); chr = *first++; } for(auto& chr: buff2) { assert(first != last); chr = *first++; } std::memcpy(&flags, buff1, sizeof(flags)); std::memcpy(&offset, buff1, sizeof(offset)); return std::make_tuple(flags, offset, first); } template <class T, class It> [[gnu::pure]] std::pair<T, It> read_serialized_immediate(It first, It last) { static_assert(std::is_trivially_copyable_v<T>); T value; alignas(T) char buff[sizeof(T)]; for(auto& chr: buff) { assert(first != last); chr = *first++; } std::memcpy(&value, buff, sizeof(value)); return std::make_pair(value, first); } } /* namespace detail */ struct BadOpcodeError: public std::logic_error { BadOpcodeError(OpCode op, const char* msg): std::logic_error(msg), opcode(op) { } const OpCode opcode; }; template <class It, class Visitor> decltype(auto) visit_opcode(Visitor visitor, It first, It last) { assert(first != last); OpCode op; auto pos = first; using value_type = typename std::iterator_traits<It>::value_type; using underlying_type = std::underlying_type_t<OpCode>; if constexpr(not std::is_same_v<value_type, OpCode>) { value_type opcode = *pos++; op = static_cast<OpCode>(opcode); assert(static_cast<value_type>(op) == opcode); } else { op = *pos++; } // Handling the invalid opcode case is optional. if constexpr(std::is_invocable_v<Visitor, OpCode, std::nullopt_t>) { if(not opcode_exists(static_cast<underlying_type>(op))) { return visitor( first, last, pos, op, BadOpcodeError(op, "Given op is not a valid WASM opcode.") ); } } else { if(not opcode_exists(static_cast<underlying_type>(op))) assert(false); } if(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32) { wasm_uint32_t flags, offset; std::tie(flags, offset, pos) = detail::read_memory_immediate(pos, last); return visitor(first, last, pos, op, flags, offset); } else if( (op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL) or (op == OpCode::CALL or op == OpCode::CALL_INDIRECT) or (op == OpCode::BR or op == OpCode::BR_IF) or (op == OpCode::ELSE) ) { wasm_uint32_t value; std::tie(value, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); return visitor(first, last, pos, op, value); } else if(op == OpCode::BLOCK or op == OpCode::IF) { assert(first != last); LanguageType tp = static_cast<LanguageType>(*first++); wasm_uint32_t label; std::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); return visitor(first, last, pos, op, tp, label); } else if(op == OpCode::LOOP) { assert(first != last); LanguageType tp = static_cast<LanguageType>(*first++); return visitor(first, last, pos, op, tp); } else if(op == OpCode::BR_TABLE) { wasm_uint32_t len; std::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); auto base = pos; std::advance(pos, (1 + len) * sizeof(wasm_uint32_t)); return visitor(first, last, pos, op, base, len); } switch(op) { case OpCode::I32_CONST: { wasm_sint32_t v; std::tie(v, pos) = detail::read_serialized_immediate<wasm_sint32_t>(pos, last); return visitor(first, last, pos, op, v); break; } case OpCode::I64_CONST: { wasm_sint64_t v; std::tie(v, pos) = detail::read_serialized_immediate<wasm_sint64_t>(pos, last); return visitor(first, last, pos, op, v); break; } case OpCode::F32_CONST: { wasm_float32_t v; std::tie(v, pos) = detail::read_serialized_immediate<wasm_float32_t>(pos, last); return visitor(first, last, pos, op, v); break; } case OpCode::F64_CONST: { wasm_float64_t v; std::tie(v, pos) = detail::read_serialized_immediate<wasm_float64_t>(pos, last); return visitor(first, last, pos, op, v); break; } default: return visitor(op, first, pos, last); } assert(false and "Internal Error: All cases should have been handled by this point."); } struct MemoryImmediate: public std::pair<const wasm_uint32_t, const wasm_uint32_t> { using std::pair<const wasm_uint32_t, const wasm_uint32_t>::pair; }; wasm_uint32_t flags(const MemoryImmediate& immed) { return immed.first; } wasm_uint32_t offset(const MemoryImmediate& immed) { return immed.second; } struct BlockImmediate: public std::pair<const LanguageType, const wasm_uint32_t> { using std::pair<const LanguageType, const wasm_uint32_t>::pair; }; gsl::span<const LanguageType> signature(const BlockImmediate& immed) { if(immed.first == LanguageType::BLOCK) return gsl::span<const LanguageType>(); return gsl::span<const LanguageType>(&(immed.first), 1u); } std::size_t arity(const BlockImmediate& immed) { return signature(immed).size(); } wasm_uint32_t offset(const BlockImmediate& immed) { return immed.second; } struct IfImmediate: public std::tuple<const LanguageType, const wasm_uint32_t, const wasm_uint32_t> { using std::tuple<const LanguageType, const wasm_uint32_t, const wasm_uint32_t>::pair; }; wasm_uint32_t else_offset(const IfImmediate& immed) { return std::get<2u>(immed); } wasm_uint32_t end_offset(const IfImmediate& immed) { return std::get<1u>(immed); } gsl::span<const LanguageType> signature(const IfImmediate& immed) { if(std::get<0u>(immed) == LanguageType::BLOCK) return gsl::span<const LanguageType>(); return gsl::span<const LanguageType>(&(std::get<0u>(immed)), 1u); } std::size_t arity(const IfImmediate& immed) { return signature(immed).size(); } struct BranchTableImmediate { template <class ... T> BranchTableImmediate(T&& ... args): table_(std::forward<T>(args)...) { } wasm_uint32_t at(wasm_uint32_t idx) const { idx = std::min(std::size_t(table_.size() - 1u), std::size_t(idx)); wasm_uint32_t depth; std::memcpy(&depth, table_.data() + idx, sizeof(depth)); return depth; } private: const gsl::span<const char[sizeof(wasm_uint32_t)]> table_; }; struct WasmInstruction { using null_immediate_type = std::monostate; using i32_immediate_type = wasm_sint32_t; using i64_immediate_type = wasm_sint64_t; using f32_immediate_type = wasm_float32_t; using f64_immediate_type = wasm_float64_t; using offset_immediate_type = wasm_uint32_t; using memory_immediate_type = MemoryImmediate; using block_immediate_type = BlockImmediate; using loop_immediate_type = LanguageType; using branch_table_immediate_type = BranchTableImmediate; union immediate_type { // no immediate (most instructions) null_immediate_type null_immed; // i32.const i32_immediate_type i32_immed; // i64.const i64_immediate_type i64_immed; // f32.const f32_immediate_type f32_immed; // f64.const f64_immediate_type f64_immed; // offset: br, br_if, else (precomputed jump), call, call_indirect // get_local, set_local, tee_local, get_global, set_global offset_immediate_type offset_immed; // memory immediate: i32.load (0x28) through i64.store32 (0x3e) memory_immediate_type memory_immed; // block immediate (signature + precomputed jump): if, block block_immediate_type block_immed; // loop (signature) loop_immediate_type loop_immed; // branch table unaligned array of offset_immediate_type (native byte order) // branch depths + one default depth. branch_table_immediate_type br_table_immed; }; using tagged_immediate_type = std::variant< null_immediate_type, i32_immediate_type, i64_immediate_type, f32_immediate_type, f64_immediate_type, offset_immediate_type, memory_immediate_type, block_immediate_type, loop_immediate_type, branch_table_immediate_type >; private: template <class T> struct Tag{}; void _assert_invariants() const { assert(opcode_exists(opcode)); assert(source.size() >= 1u); if(not validate(null_immediate_type{})) assert(source.size() > 1u); } bool validate(Tag<null_immediate_type>) const { _assert_invariants(); return ((opcode > OpCode::I32_EQZ) or (opcode == OpCode::UNREACHABLE) or (opcode == OpCode::NOP) or (opcode == OpCode::ELSE) or (opcode == OpCode::END) or (opcode == OpCode::RETURN) or (opcode == OpCode::DROP) or (opcode == OpCode::SELECT) or (opcode == OpCode::CURRENT_MEMORY) or (opcode == OpCode::GROW_MEMORY) ); } bool validate(Tag<offset_immediate_type>) const { _assert_invariants(); return ((op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL) or (op >= OpCode::CALL and op <= OpCode::CALL_INDIRECT) or (op >= OpCode::BR and op <= OpCode::BR_IF) or (op == OpCode::ELSE) ); } bool validate(Tag<i32_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::I32_CONST); } bool validate(Tag<i64_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::I64_CONST); } bool validate(Tag<f32_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::F32_CONST); } bool validate(Tag<f64_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::F64_CONST); } bool validate(Tag<memory_immediate_type>) const { _assert_invariants(); return (opcode >= OpCode::I32_LOAD) and (opcode >= OpCode::I64_STORE32); } bool validate(Tag<block_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::BLOCK) or (opcode == OpCode::IF); } bool validate(Tag<branch_table_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::BR_TABLE); } bool validate(Tag<loop_immediate_type>) const { _assert_invariants(); return (opcode == OpCode::LOOP); } template <class T> void assert_valid(Tag<T>) const { assert(validate(Tag<T>{})); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, null_immediate_type null_immed): source(src), opcode(op), end(end_pos), raw_immediate_{null_immed} { assert_valid(Tag<null_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, i32_immediate_type i32_immed): source(src), opcode(op), end(end_pos), raw_immediate_{i32_immed} { assert_valid(Tag<i32_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, i64_immediate_type i64_immed): source(src), opcode(op), end(end_pos), raw_immediate_{i64_immed} { assert_valid(Tag<i64_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, f32_immediate_type f32_immed): source(src), opcode(op), end(end_pos), raw_immediate_{f32_immed} { asser_valid(Tag<f32_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, f64_immediate_type f64_immed): source(src), opcode(op), end(end_pos), raw_immediate_{f64_immed} { assert_valid(Tag<f64_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, offset_immediate_type offset_immed): source(src), opcode(op), end(end_pos), raw_immediate_{offset_immed} { assert_valid(Tag<offset_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, loop_immediate_type loop_immed): source(src), opcode(op), end(end_pos), raw_immediate_{loop_immed} { assert_valid(Tag<loop_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, memory_immediate_type memory_immed): source(src), opcode(op), end(end_pos), raw_immediate_{memory_immed} { assert_valid(Tag<memory_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, block_immediate_type block_immed): source(src), opcode(op), end(end_pos), raw_immediate_{block_immed} { assert_valid(Tag<loop_immediate_type>{}); } WasmInstruction(std::string_view src, OpCode op, const char* end_pos, branch_table_immediate_type br_table_immed): source(src), opcode(op), end(end_pos), raw_immediate_{br_table_immed} { assert_valid(Tag<branch_table_immediate_type>{}); } public: const immediate_type& raw_immediate() const { return raw_immediate_; } const offset_immediate_type& offset_immed() tagged_immediate_type tagged_immediate() const { // This if() covers 20-something ops. if(opcode >= OpCode::I32_LOAD and opcode <= I64_STORE32) { return tagged_immediate_type( std::in_place_type<memory_immediate_type>, raw().memory_immed ); } switch(opcode) { // case for ops with no immediate default: assert(opcode_exists(static_cast<std::size_t>(opcode))); return tagged_immediate_type( std::in_place_type<null_immediate_type>, raw().null_immed ); // cases for block immediate case OpCode::BLOCK: [[fallthrough]]; case OpCode::IF: return tagged_immediate_type( std::in_place_type<block_immediate_type>, raw().block_immed ); // cases for uint32 immediate case OpCode::ELSE: [[fallthrough]]; case OpCode::BR: [[fallthrough]]; case OpCode::BR_IF: [[fallthrough]]; case OpCode::CALL: [[fallthrough]]; case OpCode::CALL_INDIRECT: [[fallthrough]]; case OpCode::GET_LOCAL: [[fallthrough]]; case OpCode::SET_LOCAL: [[fallthrough]]; case OpCode::TEE_LOCAL: [[fallthrough]]; case OpCode::GET_GLOBAL: [[fallthrough]]; case OpCode::SET_GLOBAL: return tagged_immediate_type( std::in_place_type<offset_immediate_type>, raw().offset_immed ); // case for loop immediate case OpCode::LOOP: return tagged_immediate_type( std::in_place_type<loop_immediate_type>, raw().loop_immed ); // case for loop immediate case OpCode::LOOP: return tagged_immediate_type( std::in_place_type<loop_immediate_type>, raw().loop_immed ); // case for br_table immediate case OpCode::BR_TABLE: return tagged_immediate_type( std::in_place_type<branch_table_immediate_type>, raw().br_table_immed ); // case for i32.const immediate case OpCode::I32_CONST: return tagged_immediate_type( std::in_place_type<i32_immediate_type>, raw().i32_immed ); // case for i64.const immediate case OpCode::I64_CONST: return tagged_immediate_type( std::in_place_type<i64_immediate_type>, raw().i64_immed ); // case for f32.const immediate case OpCode::F32_CONST: return tagged_immediate_type( std::in_place_type<f32_immediate_type>, raw().f32_immed ); // case for f64.const immediate case OpCode::F64_CONST: return tagged_immediate_type( std::in_place_type<f64_immediate_type>, raw().f64_immed ); } assert(false); } OpCode opcode() const { return opcode_; } std::string_view source() const { return source_; } std::string_view full_source() const { return std::string_view(source().data(), end_ - source().data()); } const char* end_pos() const { return end_; } const char* pos() const { return source().data(); } CodeView after() const { assert(pos() < end_pos()); assert(static_cast<std::size_t>(end_pos() - pos()) < source().size()); auto source_end = source().data() + source().size() return CodeView(source_end, end_pos() - source_end); } template <class CallStackType> CodeView execute(WasmModule& module, CallStackType& call_stack) { switch(opcode) { case OpCode::UNREACHABLE: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::UNREACHABLE>(); break; case OpCode::NOP: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::NOP>(); break; case OpCode::BLOCK: assert_valid(Tag<block_immediate_type>{}); op_func<OpCode::BLOCK>(); break; case OpCode::LOOP: assert_valid(Tag<loop_immediate_type>{}); op_func<OpCode::LOOP>(); break; case OpCode::IF: assert_valid(Tag<block_immediate_type>{}); op_func<OpCode::IF>(); break; case OpCode::ELSE: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::ELSE>(); break; case OpCode::END: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::END>( current_frame(call_stack), raw_immediate().offset_immed, *this ); break; case OpCode::BR: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::BR>( current_frame(call_stack), raw_immediate().offset_immed, *this ); break; case OpCode::BR_IF: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::BR_IF>( current_frame(call_stack), raw_immediate().offset_immed, *this ); break; case OpCode::BR_TABLE: assert_valid(Tag<branch_table_immediate_type>{}); op_func<OpCode::BR_TABLE>( call_stack, raw_immediate().branch_table_immed, *this ); break; case OpCode::RETURN: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::RETURN>(call_stack); break; case OpCode::CALL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::CALL>( call_stack, module, raw_immediate().offset_immed, *this ); break; case OpCode::CALL_INDIRECT: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::CALL_INDIRECT>( call_stack, module, raw_immediate().offset_immed, *this ); break; case OpCode::DROP: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::DROP>(current_frame(call_stack)); break; case OpCode::SELECT: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::SELECT>(current_frame(call_stack)); break; case OpCode::GET_LOCAL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::GET_LOCAL>( current_frame(call_stack), raw_immediate().offset_immed, ); break; case OpCode::SET_LOCAL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::SET_LOCAL>( current_frame(call_stack), raw_immediate().offset_immed, ); break; case OpCode::TEE_LOCAL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::TEE_LOCAL>( current_frame(call_stack), raw_immediate().offset_immed ); break; case OpCode::GET_GLOBAL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::GET_GLOBAL>( current_frame(call_stack), module, raw_immediate().offset_immed, ); break; case OpCode::SET_GLOBAL: assert_valid(Tag<offset_immediate_type>{}); op_func<OpCode::SET_GLOBAL>( current_frame(call_stack), module, raw_immediate().offset_immed, ); break; /// MEMORY OPS // load case OpCode::I32_LOAD: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_LOAD>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::F32_LOAD: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::F32_LOAD>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::F64_LOAD: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::F64_LOAD>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // i32 extending loads case OpCode::I32_LOAD8_S: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_LOAD8_S>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I32_LOAD8_U: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_LOAD8_U>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I32_LOAD16_S: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_LOAD16_S>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I32_LOAD16_U: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_LOAD16_U>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // i64 extending loads case OpCode::I64_LOAD8_S: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD8_S>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD8_U: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD8_U>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD16_S: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD16_S>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD16_U: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD16_U>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD32_S: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD32_S>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_LOAD32_U: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_LOAD32_U>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // store case OpCode::I32_STORE: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_STORE>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_STORE: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_STORE>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::F32_STORE: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::F32_STORE>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::F64_STORE: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::F64_STORE>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // i32 wrapping stores case OpCode::I32_STORE8: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_STORE8>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I32_STORE16: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I32_STORE16>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // i64 wrapping stores case OpCode::I64_STORE8: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_STORE8>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_STORE16: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_STORE16>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; case OpCode::I64_STORE32: assert_valid(Tag<memory_immediate_type>{}); const auto& immed = raw_immediate().memory_immed; op_func<OpCode::I64_STORE32>( current_frame(call_stack), module, flags(immed), offset(immed) ); break; // misc case OpCode::CURRENT_MEMORY: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::CURRENT_MEMORY>(current_frame(call_stack), module); break; case OpCode::GROW_MEMORY: assert_valid(Tag<null_immediate_type>{}); op_func<OpCode::GROW_MEMORY>(current_frame(call_stack), module); break; /// CONST OPERATIONS case OpCode::I32_CONST: assert_valid(Tag<i32_immediate_type>{}); op_func<OpCode::I32_CONST>(current_frame(call_stack), raw_immediate().i32_immed); break; case OpCode::I64_CONST: assert_valid(Tag<i64_immediate_type>{}); op_func<OpCode::I64_CONST>(current_frame(call_stack), raw_immediate().i64_immed); break; case OpCode::F32_CONST: assert_valid(Tag<f32_immediate_type>{}); op_func<OpCode::F32_CONST>(current_frame(call_stack), raw_immediate().f32_immed); break; case OpCode::F64_CONST: assert_valid(Tag<f64_immediate_type>{}); op_func<OpCode::F64_CONST>(current_frame(call_stack), raw_immediate().f32_immed); break; /// COMPARISON OPERATIONS // i32 comparisons case OpCode::I32_EQZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_EQZ>(current_frame(call_stack)); break; case OpCode::I32_EQ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_EQ>(current_frame(call_stack)); break; case OpCode::I32_NE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_NE>(current_frame(call_stack)); break; case OpCode::I32_LT_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_LT_S>(current_frame(call_stack)); break; case OpCode::I32_LT_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_LT_U>(current_frame(call_stack)); break; case OpCode::I32_GT_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_GT_S>(current_frame(call_stack)); break; case OpCode::I32_GT_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_GT_U>(current_frame(call_stack)); break; case OpCode::I32_LE_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_LE_S>(current_frame(call_stack)); break; case OpCode::I32_LE_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_LE_U>(current_frame(call_stack)); break; case OpCode::I32_GE_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_GE_S>(current_frame(call_stack)); break; case OpCode::I32_GE_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_GE_U>(current_frame(call_stack)); break; // i64 comparisons case OpCode::I64_EQZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_EQZ>(current_frame(call_stack)); break; case OpCode::I64_EQ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_EQ>(current_frame(call_stack)); break; case OpCode::I64_NE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_NE>(current_frame(call_stack)); break; case OpCode::I64_LT_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_LT_S>(current_frame(call_stack)); break; case OpCode::I64_LT_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_LT_U>(current_frame(call_stack)); break; case OpCode::I64_GT_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_GT_S>(current_frame(call_stack)); break; case OpCode::I64_GT_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_GT_U>(current_frame(call_stack)); break; case OpCode::I64_LE_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_LE_S>(current_frame(call_stack)); break; case OpCode::I64_LE_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_LE_U>(current_frame(call_stack)); break; case OpCode::I64_GE_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_GE_S>(current_frame(call_stack)); break; case OpCode::I64_GE_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_GE_U>(current_frame(call_stack)); break; // f32 comparisons case OpCode::F32_EQ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_EQ>(current_frame(call_stack)); break; case OpCode::F32_NE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_NE>(current_frame(call_stack)); break; case OpCode::F32_LT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_LT>(current_frame(call_stack)); break; case OpCode::F32_GT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_GT>(current_frame(call_stack)); break; case OpCode::F32_LE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_LE>(current_frame(call_stack)); break; case OpCode::F32_GE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_GE>(current_frame(call_stack)); break; // f64 comparisons case OpCode::F64_EQ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_EQ>(current_frame(call_stack)); break; case OpCode::F64_NE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_NE>(current_frame(call_stack)); break; case OpCode::F64_LT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_LT>(current_frame(call_stack)); break; case OpCode::F64_GT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_GT>(current_frame(call_stack)); break; case OpCode::F64_LE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_LE>(current_frame(call_stack)); break; case OpCode::F64_GE: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_GE>(current_frame(call_stack)); break; /// NUMERIC OPERATIONS // i32 operations case OpCode::I32_CLZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_CLZ>(); break; case OpCode::I32_CTZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_CTZ>(); break; case OpCode::I32_POPCNT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_POPCNT>(); break; case OpCode::I32_ADD: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_ADD>(); break; case OpCode::I32_SUB: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_SUB>(); break; case OpCode::I32_MUL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_MUL>(); break; case OpCode::I32_DIV_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_DIV_S>(); break; case OpCode::I32_DIV_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_DIV_U>(); break; case OpCode::I32_REM_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_REM_S>(); break; case OpCode::I32_REM_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_REM_U>(); break; case OpCode::I32_AND: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_AND>(); break; case OpCode::I32_OR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_OR>(); break; case OpCode::I32_XOR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_XOR>(); break; case OpCode::I32_SHL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_SHL>(); break; case OpCode::I32_SHR_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_SHR_S>(); break; case OpCode::I32_SHR_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_SHR_U>(); break; case OpCode::I32_ROTL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_ROTL>(); break; case OpCode::I32_ROTR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_ROTR>(); break; // i64 operations case OpCode::I64_CLZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_CLZ>(); break; case OpCode::I64_CTZ: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_CTZ>(); break; case OpCode::I64_POPCNT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_POPCNT>(); break; case OpCode::I64_ADD: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_ADD>(); break; case OpCode::I64_SUB: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_SUB>(); break; case OpCode::I64_MUL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_MUL>(); break; case OpCode::I64_DIV_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_DIV_S>(); break; case OpCode::I64_DIV_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_DIV_U>(); break; case OpCode::I64_REM_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_REM_S>(); break; case OpCode::I64_REM_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_REM_U>(); break; case OpCode::I64_AND: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_AND>(); break; case OpCode::I64_OR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_OR>(); break; case OpCode::I64_XOR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_XOR>(); break; case OpCode::I64_SHL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_SHL>(); break; case OpCode::I64_SHR_S: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_SHR_S>(); break; case OpCode::I64_SHR_U: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_SHR_U>(); break; case OpCode::I64_ROTL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_ROTL>(); break; case OpCode::I64_ROTR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_ROTR>(); break; // f32 operations case OpCode::F32_ABS: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_ABS>(); break; case OpCode::F32_NEG: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_NEG>(); break; case OpCode::F32_CEIL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_CEIL>(); break; case OpCode::F32_FLOOR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_FLOOR>(); break; case OpCode::F32_TRUNC: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_TRUNC>(); break; case OpCode::F32_NEAREST: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_NEAREST>(); break; case OpCode::F32_SQRT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_SQRT>(); break; case OpCode::F32_ADD: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_ADD>(); break; case OpCode::F32_SUB: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_SUB>(); break; case OpCode::F32_MUL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_MUL>(); break; case OpCode::F32_DIV: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_DIV>(); break; case OpCode::F32_MIN: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_MIN>(); break; case OpCode::F32_MAX: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_MAX>(); break; case OpCode::F32_COPYSIGN: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_COPYSIGN>(); break; // f64 operations case OpCode::F64_ABS: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_ABS>(); break; case OpCode::F64_NEG: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_NEG>(); break; case OpCode::F64_CEIL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_CEIL>(); break; case OpCode::F64_FLOOR: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_FLOOR>(); break; case OpCode::F64_TRUNC: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_TRUNC>(); break; case OpCode::F64_NEAREST: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_NEAREST>(); break; case OpCode::F64_SQRT: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_SQRT>(); break; case OpCode::F64_ADD: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_ADD>(); break; case OpCode::F64_SUB: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_SUB>(); break; case OpCode::F64_MUL: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_MUL>(); break; case OpCode::F64_DIV: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_DIV>(); break; case OpCode::F64_MIN: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_MIN>(); break; case OpCode::F64_MAX: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_MAX>(); break; case OpCode::F64_COPYSIGN: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_COPYSIGN>(); break; /// CONVERSION OPERATIONS case OpCode::I32_WRAP_I64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_WRAP_I64>(); break; // float-to-int32 tuncating conversion case OpCode::I32_TRUNC_S_F32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_TRUNC_S_F32>(); break; case OpCode::I32_TRUNC_U_F32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_TRUNC_U_F32>(); break; case OpCode::I32_TRUNC_S_F64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_TRUNC_S_F64>(); break; case OpCode::I32_TRUNC_U_F64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I32_TRUNC_U_F64>(); break; // int32-to-int64 extending conversion case OpCode::I64_EXTEND_S_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_EXTEND_S_I32>(); break; case OpCode::I64_EXTEND_U_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_EXTEND_U_I32>(); break; // float-to-int64 truncating conversion case OpCode::I64_TRUNC_S_F32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_TRUNC_S_F32>(); break; case OpCode::I64_TRUNC_U_F32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_TRUNC_U_F32>(); break; case OpCode::I64_TRUNC_S_F64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_TRUNC_S_F64>(); break; case OpCode::I64_TRUNC_U_F64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::I64_TRUNC_U_F64>(); break; // int-to-float32 conversion case OpCode::F32_CONVERT_S_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_CONVERT_S_I32>(); break; case OpCode::F32_CONVERT_U_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_CONVERT_U_I32>(); break; case OpCode::F32_CONVERT_S_I64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_CONVERT_S_I64>(); break; case OpCode::F32_CONVERT_U_I64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_CONVERT_U_I64>(); break; // float64-to-float32 demoting conversion case OpCode::F32_DEMOTE_F64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F32_DEMOTE_F64>(); break; // int-to-float64 conversion case OpCode::F64_CONVERT_S_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_CONVERT_S_I32>(); break; case OpCode::F64_CONVERT_U_I32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_CONVERT_U_I32>(); break; case OpCode::F64_CONVERT_S_I64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_CONVERT_S_I64>(); break; case OpCode::F64_CONVERT_U_I64: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_CONVERT_U_I64>(); break; // float32-to-float64 promoting conversion case OpCode::F64_PROMOTE_F32: assert_valid(Tag<null_immediate_tag>{}); op_func<OpCode::F64_PROMOTE_F32>(); break; } } private: void _assert_invariants() const { assert(opcode_exists(opcode())); assert(end_pos() > source().data()); assert(source().size() > 0u); std::visit( [](const auto& immed) { using immed_type = std::decay_t<decltype(immed)>; assert(validate(Tag<immed_type>{})); }, tagged_immediate() ); } std::pair<CodeView, const char*> jump_over_if() const { assert_valid(Tag<block_immediate_type>{}); assert(opcode() == OpCode::IF); wasm_uint32_t ofs = raw_immediate().block_immed; assert(ofs > 0u); assert(end_pos() > source().data()); auto dist = static_cast<std::size_t>(end_pos() - source().data()); assert(ofs < dist); auto dest_pos = source().data() + ofs; constexpr auto end_op = static_cast<unsigned char>(OpCode::END); constexpr auto else_op = static_cast<unsigned char>(OpCode::ELSE); if(dest_pos[-1] == end_op) { return std::make_pair(CodeView(dest_pos, end_pos()), nullptr); } else { assert(dest_pos[-(1 + static_cast<std::ptrdiff_t>(sizeof(ofs)))] == else_op); auto else_pos = dest_pos - (1 + static_cast<std::ptrdiff_t>(sizeof(ofs))); std::memcpy(&ofs, else_pos + 1, sizeof(ofs)); return std::make_pair(CodeView(dest_pos, end_pos()), else_pos + ofs); } } CodeView branch_to(const char* pos) const { assert(pos[-1] == static_cast<char>(OpCode::END)); assert(pos > source().data()); assert(pos < end_pos()); return CodeView(pos, end_pos()); } CodeView jump_over_else() const { assert_valid(Tag<offset_immediate_tag>{}); assert(opcode() == OpCode::ELSE); wasm_uint32_t ofs = raw_immediate().block_immed; assert(ofs > 0u); assert(end_pos() > source().data()); auto dist = static_cast<std::size_t>(end_pos() - source().data()); assert(ofs < dist); auto dest_pos = source().data() + ofs; assert(dest_pos[-1] == static_cast<char>(OpCode::END)); return CodeView(dest_pos, end_pos()); } using null_immediate_type = std::monostate; using i32_immediate_type = wasm_sint32_t; using i64_immediate_type = wasm_sint64_t; using f32_immediate_type = wasm_float32_t; using f64_immediate_type = wasm_float64_t; using offset_immediate_type = wasm_uint32_t; using memory_immediate_type = MemoryImmediate; using block_immediate_type = BlockImmediate; using loop_immediate_type = LanguageType; using branch_table_immediate_type = BranchTableImmediate; const i32_immediate_type& i32_immed() const; const i64_immediate_type& i64_immed() const; const f32_immediate_type& f32_immed() const; const f64_immediate_type& f64_immed() const; const offset_immediate_type& offset_immed() const; const memory_immediate_type& memory_immed() const; const memory_immediate_type& memory_immed() const; const OpCode& opcode() const { assert(source_.data().size() > 0u); assert(opcode_exists(source_.data().front())); return source_.data().front(); } struct LazyImmediate { std::size_t consumed; immediate_type; }; /// Code from which this instruction was decoded. const CodeView source_; /// Raw union of possible immediate operand alternatives, discriminated by 'this->opcode'. std::optional<const LazyImmediate> immediate_; }; struct CodeView { struct Iterator; using value_type = WasmInstruction; using pointer = WasmInstruction*; using const_pointer = const WasmInstruction*; using reference = WasmInstruction&; using const_reference = WasmInstruction&; using size_type = std::string_view::size_type; using difference_type = std::string_view::difference_type; using iterator = Iterator; using const_iterator = iterator; private: template <LanguageType LT, LanguageType ... V> static constexpr const bool match_one_of_v = ((LT == V) or ...); struct InstructionVisitor { template <class ... T> WasmInstruction operator()( const char* first, const char* last, const char* pos, OpCode op, T&& ... args ) { assert(first < pos); assert(pos <= last); return make_instr( std::string_view(first, pos - first), op, last, std::forward<T>(args)... ); } private: // Overload for instructions with immediate operands WasmInstruction make_instr(std::string_view view, OpCode op, const char* last) { return WasmInstruction(view, op, last, std::monostate()); } template < class T, /* enable overloads for the simple alternatives. */ class = std::enable_if_t< std::disjunction_v< std::is_same_v<std::decay_t<T>, wasm_uint32_t>, std::is_same_v<std::decay_t<T>, wasm_sint32_t>, std::is_same_v<std::decay_t<T>, wasm_sint64_t>, std::is_same_v<std::decay_t<T>, wasm_float32_t>, std::is_same_v<std::decay_t<T>, wasm_float64_t> > > > WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, T&& arg) { return WasmInstruction(view, op, last, std::forward<T>(arg)); } /// Loop overload WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp) { return WasmInstruction(view, op, last, tp); } /// Branch table overload WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, const char* base, wasm_uint32_t len) { assert(last > base); std::size_t byte_count = base - last; std::size_t bytes_needed = sizeof(wasm_uint32_t) * (len + 1u); assert(byte_count >= bytes_needed); // the table and 'view' should end at the same byte address assert(view.data() + view.size() == (base + (len + 1u) * sizeof(wasm_uint32_t))); using buffer_type = const char[sizeof(wasm_uint32_t)]; auto table = gsl::span<buffer_type>(reinterpret_cast<buffer_type*>(base), len + 1u); return WasmInstruction(view, op, last, table); } /// Block overload WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, LanguageType tp, wasm_uint32_t label) { return WasmInstruction(view, op, last, BlockImmediate(tp, label)); } /// Memory overload WasmInstruction make_instr(std::string_view view, OpCode op, const char* last, wasm_uint32_t flags, wasm_uint32_t offset) { return WasmInstruction(view, op, last, MemoryImmediate(flags, offset)); } /// Invalid opcode overload [[noreturn]] WasmInstruction make_instr(std::string_view, OpCode, const char*, const BadOpCodeError& err) { throw err; } }; public: struct Iterator { using value_type = CodeView::value_type; using difference_type = CodeView::difference_type; using pointer = CodeView::pointer; using reference = CodeView::value_type; using iterator_category = std::input_iterator_tag; friend bool operator==(const Iterator& left, const Iterator& right) { return left.code_ == right.code_; } friend bool operator!=(const Iterator& left, const Iterator& right) { return not (left == right); } private: gsl::not_null<CodeView*> code_; }; CodeView(const WasmFunction& func): function_(&func), code_(code(func)) { } const WasmFunction* function() const { return function_; } OpCode current_op() const { assert(ready()); return static_cast<WasmInstruction>(code_.front()); } bool done() const { return not code_.empty(); } const char* pos() const { return code_.data(); } void advance(const CodeView& other) { assert(function() == other.function()); assert(ready()); assert(code_.data() + code_.size() == other.code_.data() + other.code_.size()); assert(code_.data() < other.code_.data()); code_ = other.code_; } std::optional<WasmInstruction> next_instruction() const { if(code_.size() == 0) return std::nullopt; return visit_opcode( opcode(), [&](auto opcode) { return visit_op_impl( [&](auto first, auto pos, auto last, auto op, auto&& immed) { return WasmInstruction(*this, pos, std::forward<decltype(immed)>(immed)); }, opcode ); } ); } std::optional<CodeView> advance( WasmModule& module, WasmCallStack<T>& call_stack ) { if(code_.size() == 0) return std::nullopt; auto vis = [&](auto first, auto pos, auto last, auto op, const auto& immed) { return dispatch(call_stack, module, first, pos, last, op, immed); }; } CodeView jump(wasm_uint32_t jump_dist) const { using pair_type = std::pair<CodeView, std::optional<CodeView>>; assert(jump_dist > 0u); assert(code_.size() > jump_dist); CodeView dest = *this; dest.code_.remove_prefix(jump_dist); return dest; } private: template <class T, OpCode Op, class ImmediateType> CodeView dispatch( WasmCallStack<T>& call_stack, WasmModule& module, const char* first, const char* pos, const char* last, std::integral_constant<OpCode, Op> op, const ImmediateType& immed ) { auto after = *this; after.code_.remove_prefix(pos - first); return op_func<Op>(call_stack, module, *this, after, immed); } template <class Vis, class T, OpCode Op> decltype(auto) visit_op_impl(Vis&& visitor, std::integral_constant<OpCode, Op> op) { auto first = code_.data(); auto last = first + code_.size(); assert(first < last); assert(*first == Op); if constexpr(op >= OpCode::I32_LOAD and op <= OpCode::I64_STORE32) { auto [flags, offset, pos] = detail::read_memory_immediate(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, MemoryImmediateType(flags, offset) ); } else if constexpr( (op >= OpCode::GET_LOCAL and op <= OpCode::SET_GLOBAL) or op == OpCode::CALL or op == OpCode::CALL_INDIRECT or op == OpCode::BR or op == OpCode::BR_IF or op == OpCode::ELSE ) { auto [value, pos] = detail::read_serialized_immediate<wasm_uint32_t>(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, value ); } else if constexpr(op == OpCode::BLOCK) { auto pos = first + 1u; assert(pos < last); LanguageType tp = static_cast<LanguageType>(*pos++); wasm_uint32_t label; std::tie(label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, BlockImmediate(tp, label) ); } else if constexpr(op == OpCode::IF) { auto pos = first + 1u; assert(pos < last); LanguageType tp = static_cast<LanguageType>(*pos++); wasm_uint32_t end_label; wasm_uint32_t else_label; std::tie(end_label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); std::tie(else_label, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, IfImmediate(tp, end_label, else_label) ); } else if constexpr(op == OpCode::LOOP) { auto pos = first + 1u; assert(pos < last); LanguageType tp = static_cast<LanguageType>(*pos++); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, BlockImmediate(tp, label) ); } else if constexpr(op == OpCode::BR_TABLE) { wasm_uint32_t len; std::tie(len, pos) = detail::read_serialized_immediate<wasm_uint32_t>(pos, last); auto table_base = pos; auto table_size = (1u + len); assert(last - pos > table_size); std::advance(pos, table_size * sizeof(wasm_uint32_t)); using table_elem_type = const char[sizeof(wasm_uint32_t)]; auto table = gsl::span<table_elem_type>( reinterpret_cast<table_elem_type*>(table_base), table_size ); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, table ); } else if constexpr(Op == OpCode::I32_CONST) { auto [v, pos] = detail::read_serialized_immediate<wasm_sint32_t>(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, table ); } else if constexpr(Op == OpCode::I64_CONST) { auto [v, pos] = detail::read_serialized_immediate<wasm_sint64_t>(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, table ); } else if constexpr(Op == OpCode::F32_CONST) { auto [v, pos] = detail::read_serialized_immediate<wasm_float32_t>(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, table ); } else if constexpr(Op == OpCode::F64_CONST) { auto [v, pos] = detail::read_serialized_immediate<wasm_float64_t>(first + 1u, last); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, table ); } else { assert(opcode_exists(Op)); return std::invoke( std::forward<Vis>(visitor), first, pos, last, op, std::monostate{} ); } } bool ready() const { if(done()) return false; assert(opcode_exists(code_.front())); return true; } const WasmFunction* function_; std::string_view code_; }; } /* namespace opc */ } /* namespace wasm */ #endif /* WASM_INSTRUCTION_H */
{ "alphanum_fraction": 0.6868845755, "avg_line_length": 35.9310474755, "ext": "h", "hexsha": "5a6a27cdd1d2e69aae453730dd1a9071d370df11", "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/WasmInstruction.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/WasmInstruction.h", "max_line_length": 123, "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/WasmInstruction.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 29444, "size": 95361 }
// This matrix class is a C++ wrapper for the GNU Scientific Library // Copyright (C) ULP-IPB Strasbourg // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #ifndef _vector_float_h #define _vector_float_h #ifdef __HP_aCC #include <iostream.h> #else #include <iostream> #endif #include <gsl/gsl_math.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_blas.h> #include <gslwrap/vector_double.h> //#define NDEBUG 0 #include <assert.h> namespace gsl { #ifndef __HP_aCC using std::ostream; //using std::string; //using std::runtime_error; #endif class vector_float_view; class vector_float { protected: gsl_vector_float *gsldata; void free(){if(gsldata) gsl_vector_float_free(gsldata);gsldata=NULL;} void alloc(size_t n) {gsldata=gsl_vector_float_alloc(n);} void calloc(size_t n){gsldata=gsl_vector_float_calloc(n);} public: typedef float value_type; vector_float() : gsldata(NULL) {;} vector_float( const vector_float &other ):gsldata(NULL) {copy(other);} template<class oclass> vector_float( const oclass &other ):gsldata(NULL) {copy(other);} ~vector_float(){free();} vector_float(const size_t& n,bool clear=true) { this->gsldata = NULL; if(clear){this->calloc(n);} else {this->alloc(n);} } vector_float(const int& n,bool clear=true) { this->gsldata = NULL; if(clear){this->calloc(n);} else {this->alloc(n);} } void resize(size_t n); template <class oclass> void copy(const oclass &other) { if ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) ) return; if (!other.is_set()) { gsldata=NULL; return; } resize(other.size()); for (size_t i=0;i<size();i++) { gsl_vector_float_set(gsldata, i, (float)other[i]); } } void copy(const vector_float& other); bool is_set() const{if (gsldata) return true; else return false;} // void clone(vector_float& other); // size_t size() const {if (!gsldata) {cout << "vector_float::size vector not initialized" << endl; exit(-1);}return gsldata->size;} size_t size() const {assert (gsldata); return gsldata->size;} /** for interfacing with gsl c */ /* gsl_vector_float *gslobj() {if (!gsldata){cout << "vector_float::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */ /* const gsl_vector_float *gslobj() const {if (!gsldata){cout << "vector_float::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */ gsl_vector_float *gslobj() {assert(gsldata);return gsldata;} const gsl_vector_float *gslobj() const {assert(gsldata);return gsldata;} static vector_float_view create_vector_view( const gsl_vector_float_view &other ); // ********Accessing vector elements // Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector_float_get and gsl_vector_float_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range. // The functions for accessing the elements of a vector or matrix are defined in `gsl_vector_float.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector_float_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector_float_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off. // This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned. float get(size_t i) const {return gsl_vector_float_get(gsldata,i);} // This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked. void set(size_t i,float x){gsl_vector_float_set(gsldata,i,x);} // These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked float &operator[](size_t i) { return *gsl_vector_float_ptr(gsldata,i);} const float &operator[](size_t i) const { return *gsl_vector_float_ptr(gsldata,i);} float &operator()(size_t i) { return *gsl_vector_float_ptr(gsldata,i);} const float &operator()(size_t i) const { return *gsl_vector_float_ptr(gsldata,i);} // ***** Initializing vector elements // This function sets all the elements of the vector v to the value x. void set_all(float x){gsl_vector_float_set_all (gsldata,x);} // This function sets all the elements of the vector v to zero. void set_zero(){gsl_vector_float_set_zero (gsldata);} // This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one. int set_basis (size_t i) {return gsl_vector_float_set_basis (gsldata,i);} // **** Reading and writing vectors // The library provides functions for reading and writing vectors to a file as binary data or formatted text. // This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures. int fwrite (FILE * stream) const {return gsl_vector_float_fwrite (stream, gsldata);} // This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture. int fread (FILE * stream) {return gsl_vector_float_fread (stream, gsldata);} void load( const char *filename ); /// void save( const char *filename ) const; // This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file. int fprintf (FILE * stream, const char * format) const {return gsl_vector_float_fprintf (stream, gsldata,format) ;} // This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file. int fscanf (FILE * stream) {return gsl_vector_float_fscanf (stream, gsldata); } // ******* Vector views // In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector. // A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector_float_view and a constant vector view has the type gsl_vector_float_const_view. In both cases the elements of the view can be accessed as a gsl_vector_float using the vector component of the view object. A pointer to a vector of type gsl_vector_float * or const gsl_vector_float * can be obtained by taking the address of this component with the & operator. // These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original // vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by, // v'(i) = v->data[(offset + i)*v->stride] // where the index i runs from 0 to n-1. // The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector. // The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the // new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector. // Of course, the original vector should not be deallocated while the new vector is still in use. // The function gsl_vector_float_const_subvector is equivalent to gsl_vector_float_subvector but can be used for vectors which are declared const. vector_float_view subvector (size_t offset, size_t n); const vector_float_view subvector (size_t offset, size_t n) const; // vector_float_const_view subvector (size_t offset, size_t n) const; // class view // { // gsl_vector_float_view *gsldata; // public: // view(); // }; // view subvector(size_t offset, size_t n) // { // return view(gsl_vector_float_subvector(gsldata,offset,n); // } // const view subvector(size_t offset, size_t n) const // { // return view(gsl_vector_float_const_subvector(gsldata,offset,n); // } // Function: gsl_vector_float gsl_vector_float_subvector_with_stride (gsl_vector_float *v, size_t offset, size_t stride, size_t n) // Function: gsl_vector_float_const_view gsl_vector_float_const_subvector_with_stride (const gsl_vector_float * v, size_t offset, size_t stride, size_t n) // These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for // gsl_vector_float_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically, // the i-th element of the new vector v' is given by, // v'(i) = v->data[(offset + i*stride)*v->stride] // where the index i runs from 0 to n-1. // Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the // vector v of length n, while leaving the odd elements untouched, // gsl_vector_float_view v_even = gsl_vector_float_subvector_with_stride (v, 0, 2, n/2); // gsl_vector_float_set_zero (&v_even.vector); // A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the // following code computes the norm of odd elements of v using the BLAS routine DNRM2, // gsl_vector_float_view v_odd = gsl_vector_float_subvector_with_stride (v, 1, 2, n/2); // double r = gsl_blas_dnrm2 (&v_odd.vector); // The function gsl_vector_float_const_subvector_with_stride is equivalent to gsl_vector_float_subvector_with_stride but can be used for // vectors which are declared const. // Function: gsl_vector_float_view gsl_vector_float_complex_real (gsl_vector_float_complex *v) // Function: gsl_vector_float_const_view gsl_vector_float_complex_const_real (const gsl_vector_float_complex *v) // These functions return a vector view of the real parts of the complex vector v. // The function gsl_vector_float_complex_const_real is equivalent to gsl_vector_float_complex_real but can be used for vectors which are declared // const. // Function: gsl_vector_float_view gsl_vector_float_complex_imag (gsl_vector_float_complex *v) // Function: gsl_vector_float_const_view gsl_vector_float_complex_const_imag (const gsl_vector_float_complex *v) // These functions return a vector view of the imaginary parts of the complex vector v. // The function gsl_vector_float_complex_const_imag is equivalent to gsl_vector_float_complex_imag but can be used for vectors which are declared // const. // Function: gsl_vector_float_view gsl_vector_float_view_array (double *base, size_t n) // Function: gsl_vector_float_const_view gsl_vector_float_const_view_array (const double *base, size_t n) // These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new // vector v' is given by, // v'(i) = base[i] // where the index i runs from 0 to n-1. // The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The // original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use. // The function gsl_vector_float_const_view_array is equivalent to gsl_vector_float_view_array but can be used for vectors which are declared const. // Function: gsl_vector_float_view gsl_vector_float_view_array_with_stride (double * base, size_t stride, size_t n) // Function: gsl_vector_float_const_view gsl_vector_float_const_view_array_with_stride (const double * base, size_t stride, size_t n) // These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for // gsl_vector_float_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically, // the i-th element of the new vector v' is given by, // v'(i) = base[i*stride] // where the index i runs from 0 to n-1. // Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector // argument just as a directly allocated vector would be, using &view.vector. // The function gsl_vector_float_const_view_array_with_stride is equivalent to gsl_vector_float_view_array_with_stride but can be used for // arrays which are declared const. // ************* Copying vectors // Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category. // This function copies the elements of the vector src into the vector dest. vector_float& operator=(const vector_float& other){copy(other);return (*this);} // Function: int gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w) // This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length. // ***** Exchanging elements // The following function can be used to exchange, or permute, the elements of a vector. // Function: int gsl_vector_float_swap_elements (gsl_vector_float * v, size_t i, size_t j) // This function exchanges the i-th and j-th elements of the vector v in-place. int swap_elements (size_t i, size_t j) {return gsl_vector_float_swap_elements (gsldata, i,j);} // Function: int gsl_vector_float_reverse (gsl_vector_float * v) // This function reverses the order of the elements of the vector v. int reverse () {return gsl_vector_float_reverse (gsldata) ;} // ******* Vector operations // The following operations are only defined for real vectors. // This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length. int operator+=(const vector_float &other) {return gsl_vector_float_add (gsldata, other.gsldata);} // This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length. int operator-=(const vector_float &other) {return gsl_vector_float_sub (gsldata, other.gsldata);} // Function: int gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b) // This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length. int operator*=(const vector_float &other) {return gsl_vector_float_mul (gsldata, other.gsldata);} // This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length. int operator/=(const vector_float &other) {return gsl_vector_float_div (gsldata, other.gsldata);} // This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. int operator*=(float x) {return gsl_vector_float_scale (gsldata, x);} // Function: int gsl_vector_float_add_constant (gsl_vector_float * a, const double x) // This function adds the constant value x to the elements of the vector a, a'_i = a_i + x. int operator+=(float x) {return gsl_vector_float_add_constant (gsldata,x);} // This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i. int operator/=(float x) {return gsl_vector_float_scale (gsldata, 1/x);} // bool operators: bool operator==(const vector_float& other) const; bool operator!=(const vector_float& other) const { return (!((*this)==other));} // stream output: // friend ostream& operator<< ( ostream& os, const vector_float& vect ); /** returns sum of all the vector elements. */ float sum() const; // returns sqrt(v.t*v); double norm2() const; // **** Finding maximum and minimum elements of vectors // This function returns the maximum value in the vector v. double max() const{return gsl_vector_float_max (gsldata) ;} // Function: double gsl_vector_float_min (const gsl_vector_float * v) // This function returns the minimum value in the vector v. double min() const{return gsl_vector_float_min (gsldata) ;} // Function: void gsl_vector_float_minmax (const gsl_vector_float * v, double * min_out, double * max_out) // This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out. // This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned. size_t max_index(){return gsl_vector_float_max_index (gsldata);} // Function: size_t gsl_vector_float_min_index (const gsl_vector_float * v) // This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned. size_t min_index(){return gsl_vector_float_min_index (gsldata);} // Function: void gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax) // This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum // or maximum elements then the lowest indices are returned. // Vector properties // Function: int gsl_vector_float_isnull (const gsl_vector_float * v) // This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. }; bool isnull(){return gsl_vector_float_isnull (gsldata);} }; // When you add create a view it will stick to its with the view until you call change_view // ex: // matrix_float m(5,5); // vector_float v(5); // // ... // m.column(3) = v; //the 3rd column of the matrix m will equal v. class vector_float_view : public vector_float { public: vector_float_view(const vector_float& other) :vector_float(){init(other);} vector_float_view(const vector_float_view& other):vector_float(){init(other);} vector_float_view(const gsl_vector_float& gsl_other) : vector_float() {init_with_gsl_vector(gsl_other);} void init(const vector_float& other); void init_with_gsl_vector(const gsl_vector_float& gsl_other); void change_view(const vector_float& other){init(other);} private: }; ostream& operator<< ( ostream& os, const vector_float & vect ); // vector_type<>::type is a template interface to vector_? // it is usefull for in templated situations for getting the correct vector type #define tmp_type_is_float #ifdef tmp_type_is typedef vector vector_double; template<class T> struct vector_type {typedef vector_double type;}; template<class T> struct value_type {typedef double type;}; #else template<> struct vector_type<float> {typedef vector_float type;}; #endif #undef tmp_type_is_float } #endif// _vector_float_h
{ "alphanum_fraction": 0.7451620317, "avg_line_length": 53.849009901, "ext": "h", "hexsha": "1b3f2ff2181400f742773892a96310553c35fde0", "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": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_forks_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_forks_repo_name": "entn-at/GlottDNN", "max_forks_repo_path": "src/gslwrap/vector_float.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_issues_repo_name": "entn-at/GlottDNN", "max_issues_repo_path": "src/gslwrap/vector_float.h", "max_line_length": 693, "max_stars_count": null, "max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65", "max_stars_repo_licenses": [ "ECL-2.0", "Apache-2.0" ], "max_stars_repo_name": "entn-at/GlottDNN", "max_stars_repo_path": "src/gslwrap/vector_float.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5144, "size": 21755 }
/** * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * 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. * * @brief tars implementation for Block * @file BlockImpl.h * @author: ancelmo * @date 2021-04-20 */ #pragma once #include "BlockHeaderImpl.h" #include "TransactionImpl.h" #include "TransactionMetaDataImpl.h" #include "TransactionReceiptImpl.h" #include "bcos-tars-protocol/Common.h" #include "bcos-tars-protocol/tars/Block.h" #include "interfaces/protocol/Transaction.h" #include <bcos-framework/interfaces/crypto/CryptoSuite.h> #include <bcos-framework/interfaces/protocol/Block.h> #include <bcos-framework/interfaces/protocol/BlockHeader.h> #include <gsl/span> #include <memory> namespace bcostars { namespace protocol { class BlockImpl : public bcos::protocol::Block, public std::enable_shared_from_this<BlockImpl> { public: BlockImpl(bcos::protocol::TransactionFactory::Ptr _transactionFactory, bcos::protocol::TransactionReceiptFactory::Ptr _receiptFactory) : bcos::protocol::Block(_transactionFactory, _receiptFactory), m_inner(std::make_shared<bcostars::Block>()), x_mutex(std::make_shared<std::mutex>()) {} ~BlockImpl() override{}; void decode(bcos::bytesConstRef _data, bool _calculateHash, bool _checkSig) override; void encode(bcos::bytes& _encodeData) const override; int32_t version() const override { return m_inner->blockHeader.data.version; } void setVersion(int32_t _version) override { m_inner->blockHeader.data.version = _version; } bcos::protocol::BlockType blockType() const override { return (bcos::protocol::BlockType)m_inner->type; } // FIXME: this will cause the same blockHeader calculate hash multiple times bcos::protocol::BlockHeader::Ptr blockHeader() override; bcos::protocol::BlockHeader::ConstPtr blockHeaderConst() const override; bcos::protocol::Transaction::ConstPtr transaction(size_t _index) const override; bcos::protocol::TransactionReceipt::ConstPtr receipt(size_t _index) const override; // get transaction metaData bcos::protocol::TransactionMetaData::ConstPtr transactionMetaData(size_t _index) const override; void setBlockType(bcos::protocol::BlockType _blockType) override { m_inner->type = (int32_t)_blockType; } // set blockHeader void setBlockHeader(bcos::protocol::BlockHeader::Ptr _blockHeader) override; void setTransaction(size_t _index, bcos::protocol::Transaction::Ptr _transaction) override { m_inner->transactions[_index] = std::dynamic_pointer_cast<bcostars::protocol::TransactionImpl>(_transaction)->inner(); } void appendTransaction(bcos::protocol::Transaction::Ptr _transaction) override { m_inner->transactions.emplace_back( std::dynamic_pointer_cast<bcostars::protocol::TransactionImpl>(_transaction)->inner()); } void setReceipt(size_t _index, bcos::protocol::TransactionReceipt::Ptr _receipt) override; void appendReceipt(bcos::protocol::TransactionReceipt::Ptr _receipt) override; void appendTransactionMetaData(bcos::protocol::TransactionMetaData::Ptr _txMetaData) override; // get transactions size size_t transactionsSize() const override { return m_inner->transactions.size(); } size_t transactionsMetaDataSize() const override; // get receipts size size_t receiptsSize() const override { return m_inner->receipts.size(); } void setNonceList(bcos::protocol::NonceList const& _nonceList) override; void setNonceList(bcos::protocol::NonceList&& _nonceList) override; bcos::protocol::NonceList const& nonceList() const override; const bcostars::Block& inner() const { return *m_inner; } void setInner(const bcostars::Block& inner) { *m_inner = inner; } void setInner(bcostars::Block&& inner) { *m_inner = std::move(inner); } private: std::shared_ptr<bcostars::Block> m_inner; mutable bcos::protocol::NonceList m_nonceList; std::shared_ptr<std::mutex> x_mutex; }; } // namespace protocol } // namespace bcostars
{ "alphanum_fraction": 0.7359513994, "avg_line_length": 40.4298245614, "ext": "h", "hexsha": "6ab9dbd5957a443cb41b4652675bb24d93a8e6be", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:35:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-08T02:39:58.000Z", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_issues_count": 20, "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_issues_event_max_datetime": "2021-12-07T14:19:09.000Z", "max_issues_repo_issues_event_min_datetime": "2021-09-14T12:23:12.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_path": "bcos-tars-protocol/protocol/BlockImpl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1107, "size": 4609 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" #include "error_cblas_l3.h" void cblas_dsymm (const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) { #define BASE double #include "source_symm_r.h" #undef BASE }
{ "alphanum_fraction": 0.6715789474, "avg_line_length": 27.9411764706, "ext": "c", "hexsha": "a57c47659aa688b100d945b97148b9128645c9f7", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/dsymm.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/dsymm.c", "max_line_length": 74, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/dsymm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 131, "size": 475 }
// Framework for using a CBLAS high performance library: // General functions defined: // copy(dest, src, len) // scal(X, len, alpha): X <- alpha * X // addScal(X, Y, len, alpha): X <- X + alpha * Y // matrix_multiply(optA, optB, A, B, C, rows_op_A, cols_op_B, cols_op_A): C <- op(A) * op(B) #ifndef HIGH_PERF_H #define HIGH_PERF_H // To use a CBLAS library, e.g OpenBLAS: #if defined _OPENBLAS #define CBLAS #endif #include "settings.h" // For 'Number' definition. #if defined CBLAS #pragma message "OpenBLAS is being used." #include <cblas.h> #define ORDER CblasRowMajor // Do not modify. #define CONVERT_CST 111 // Do not modify, used for converting 'Trans' to 'CblasTrans'. #define leadingDimension(rows, cols) \ (ORDER == CblasRowMajor ? cols : rows) // float/double implementation: #if defined _FLOAT #define _copy(dest, src, len) \ cblas_scopy(len, src, 1, dest, 1) #define _scal(X, len, alpha) \ cblas_sscal(len, alpha, X, 1) #define _axpy(X, Y, len, alpha) \ cblas_saxpy(len, alpha, Y, 1, X, 1) #define _gemm(ORDER, optA, optB, rows_op_A, cols_op_B, cols_op_A, alpha, A, lda, B, ldb, beta, C, ldc) \ cblas_sgemm(ORDER, optA, optB, rows_op_A, cols_op_B, cols_op_A, alpha, A, lda, B, ldb, beta, C, ldc) #elif defined _DOUBLE #define _copy(dest, src, len) \ cblas_dcopy(len, src, 1, dest, 1) #define _scal(X, len, alpha) \ cblas_dscal(len, alpha, X, 1) #define _axpy(X, Y, len, alpha) \ cblas_daxpy(len, alpha, Y, 1, X, 1) #define _gemm(ORDER, optA, optB, rows_op_A, cols_op_B, cols_op_A, alpha, A, lda, B, ldb, beta, C, ldc) \ cblas_dgemm(ORDER, optA, optB, rows_op_A, cols_op_B, cols_op_A, alpha, A, lda, B, ldb, beta, C, ldc) #endif // CBLAS framework: #define copy(dest, src, len) \ copyVector(dest, src, len) // Not using CBLAS _copy here, since memcpy seems to be slightly faster... #define scal(X, len, alpha) \ _scal(X, len, alpha) #define addScal(X, Y, len, alpha) \ _axpy(X, Y, len, alpha) #define matrix_multiply(optA, optB, A, B, C, rows_op_A, cols_op_B, cols_op_A) \ { \ CBLAS_TRANSPOSE cblas_optA = optA + CONVERT_CST; \ CBLAS_TRANSPOSE cblas_optB = optB + CONVERT_CST; \ int lda, ldb, ldc; \ if (ORDER == CblasRowMajor) \ { \ lda = cblas_optA == CblasNoTrans ? cols_op_A : rows_op_A; \ ldb = cblas_optB == CblasNoTrans ? cols_op_B : cols_op_A; \ ldc = cols_op_B; \ } \ else \ { \ lda = cblas_optA == CblasNoTrans ? rows_op_A : cols_op_A; \ ldb = cblas_optB == CblasNoTrans ? cols_op_A : cols_op_B; \ ldc = rows_op_A; \ } \ _gemm(ORDER, cblas_optA, cblas_optB, rows_op_A, cols_op_B, cols_op_A, 1, A, lda, B, ldb, 0, C, ldc); \ } #else // Naive implementations: #pragma message "No high performance library is being used, expect slow learning." #define copy(dest, src, len) \ copyVector(dest, src, len) #define scal(X, len, alpha) \ naive_scal(X, len, alpha) #define addScal(X, Y, len, alpha) \ naive_addScal(X, Y, len, alpha) #define matrix_multiply(optA, optB, A, B, C, rows_op_A, cols_op_B, cols_op_A) \ naive_matrix_multiply(optA, optB, A, B, C, rows_op_A, cols_op_B, cols_op_A) #endif #endif
{ "alphanum_fraction": 0.6623703238, "avg_line_length": 24.8515625, "ext": "h", "hexsha": "43f64db4bc31fc26a443756baa6cc0855886a1fb", "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": "b7344dda89cb9335ea5dd55fd6ff74c87b87511e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Carath/NeuralLib", "max_forks_repo_path": "NeuralLib/src/high_perf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b7344dda89cb9335ea5dd55fd6ff74c87b87511e", "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": "Carath/NeuralLib", "max_issues_repo_path": "NeuralLib/src/high_perf.h", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "b7344dda89cb9335ea5dd55fd6ff74c87b87511e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Carath/NeuralLib", "max_stars_repo_path": "NeuralLib/src/high_perf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1124, "size": 3181 }
#pragma once #include <halley/maths/vector2.h> #include <halley/maths/rect.h> #include <memory> #include <halley/resources/resource.h> #include <halley/text/halleystring.h> #include <halley/data_structures/hash_map.h> #include <gsl/span> #include "halley/maths/vector4.h" namespace Halley { class Sprite; class Resources; class Serializer; class Deserializer; class ResourceDataStatic; class Texture; class ResourceLoader; class Material; class SpriteSheet; class SpriteSheetEntry { public: Vector2f pivot; Vector2i origPivot; Vector2f size; Rect4f coords; Vector4s trimBorder; Vector4s slices; int duration = 0; bool rotated = false; bool sliced = false; void serialize(Serializer& s) const; void deserialize(Deserializer& s); #ifdef ENABLE_HOT_RELOAD SpriteSheet* parent = nullptr; uint32_t idx = 0; #endif }; class SpriteSheetFrameTag { public: String name; int from = 0; int to = 0; void serialize(Serializer& s) const; void deserialize(Deserializer& s); }; class SpriteHotReloader { public: virtual ~SpriteHotReloader() = default; #ifdef ENABLE_HOT_RELOAD void addSprite(Sprite* sprite, uint32_t idx) const; void removeSprite(Sprite* sprite) const; void updateSpriteIndex(Sprite* sprite, uint32_t idx) const; void clearSpriteRefs(); protected: class SpritePointerHasher { public: std::size_t operator()(Sprite* ptr) const noexcept; }; mutable std::unordered_map<Sprite*, uint32_t, SpritePointerHasher> spriteRefs; #endif }; class SpriteSheet final : public Resource, public SpriteHotReloader { public: SpriteSheet(); ~SpriteSheet(); const std::shared_ptr<const Texture>& getTexture() const; const SpriteSheetEntry& getSprite(const String& name) const; const SpriteSheetEntry& getSprite(size_t idx) const; const SpriteSheetEntry* tryGetSprite(const String& name) const; const SpriteSheetEntry& getDummySprite() const; const std::vector<SpriteSheetFrameTag>& getFrameTags() const; std::vector<String> getSpriteNames() const; const HashMap<String, uint32_t>& getSpriteNameMap() const; size_t getSpriteCount() const; std::optional<size_t> getIndex(const String& name) const; bool hasSprite(const String& name) const; void loadJson(gsl::span<const gsl::byte> data); void addSprite(String name, const SpriteSheetEntry& sprite); void setTextureName(String name); std::shared_ptr<Material> getMaterial(const String& name) const; void setDefaultMaterialName(String materialName); const String& getDefaultMaterialName() const; void clearMaterialCache() const; static std::unique_ptr<SpriteSheet> loadResource(ResourceLoader& loader); constexpr static AssetType getAssetType() { return AssetType::SpriteSheet; } void reload(Resource&& resource) override; void serialize(Serializer& s) const; void deserialize(Deserializer& s); private: constexpr static int version = 1; Resources* resources = nullptr; std::vector<SpriteSheetEntry> sprites; SpriteSheetEntry dummySprite; HashMap<String, uint32_t> spriteIdx; std::vector<SpriteSheetFrameTag> frameTags; String textureName; mutable std::shared_ptr<const Texture> texture; String defaultMaterialName; mutable HashMap<String, std::weak_ptr<Material>> materials; void loadTexture(Resources& resources) const; void assignIds(); }; class SpriteResource final : public Resource, public SpriteHotReloader { public: SpriteResource(); SpriteResource(const std::shared_ptr<const SpriteSheet>& spriteSheet, size_t idx); ~SpriteResource(); const SpriteSheetEntry& getSprite() const; size_t getIdx() const; std::shared_ptr<const SpriteSheet> getSpriteSheet() const; std::shared_ptr<Material> getMaterial(const String& name) const; const String& getDefaultMaterialName() const; constexpr static AssetType getAssetType() { return AssetType::Sprite; } static std::unique_ptr<SpriteResource> loadResource(ResourceLoader& loader); void reload(Resource&& resource) override; void serialize(Serializer& s) const; void deserialize(Deserializer& s); private: std::weak_ptr<const SpriteSheet> spriteSheet; uint64_t idx = -1; Resources* resources = nullptr; }; }
{ "alphanum_fraction": 0.7539155197, "avg_line_length": 26.1739130435, "ext": "h", "hexsha": "12086994d93a2ae8458ce15407314b2fb4af43b5", "lang": "C", "max_forks_count": 193, "max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z", "max_forks_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JLouhela/halley", "max_forks_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_issues_count": 53, "max_issues_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z", "max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "JLouhela/halley", "max_issues_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_line_length": 84, "max_stars_count": 3262, "max_stars_repo_head_hexsha": "eb395c8cc5ab6fb4aa1966ce3d7a9c1b8301d587", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JLouhela/halley", "max_stars_repo_path": "src/engine/core/include/halley/core/graphics/sprite/sprite_sheet.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z", "num_tokens": 1041, "size": 4214 }
#ifndef TTT_GS_GAMESTATESTACK_H #define TTT_GS_GAMESTATESTACK_H #include "GameState.h" #include "../Utilities/Utilities.h" #include <gsl/util> #include <gsl/assert> #include <deque> #include <memory> #include <optional> namespace ttt::gs { class GameStateStack final { public: using SizeType = gsl::index; template<typename T, typename... Arg> void emplace(Arg &&...args) noexcept(std::is_nothrow_constructible_v<T, Arg...>); void pop() noexcept; void clear() noexcept; void update(); void render() const noexcept; void setBackgroundRender(const std::optional<SizeType> &index) noexcept; void setBackgroundUpdate(const std::optional<SizeType> &index) noexcept; [[nodiscard]] SizeType getSize() const noexcept; [[nodiscard]] SizeType getMaxSize() const noexcept; private: std::deque<std::unique_ptr<GameState>> gameStates; std::optional<SizeType> bgUpdateIndex; std::optional<SizeType> bgRenderIndex; SizeType popIndex{-1}; SizeType queuedForPop{0}; }; template<typename T, typename... Arg> void GameStateStack::emplace(Arg &&...args) noexcept(std::is_nothrow_constructible_v<T, Arg...>) { gameStates.emplace_back(std::make_unique<T>(std::forward<Arg>(args)...)); } inline void GameStateStack::setBackgroundUpdate(const std::optional<SizeType> &index) noexcept { Expects(!index || *index < util::getSize(gameStates)); bgUpdateIndex = index; } inline void GameStateStack::setBackgroundRender(const std::optional<SizeType> &index) noexcept { Expects(!index || *index < util::getSize(gameStates)); bgRenderIndex = index; } inline GameStateStack::SizeType GameStateStack::getSize() const noexcept { return gameStates.size(); } inline GameStateStack::SizeType GameStateStack::getMaxSize() const noexcept { return gameStates.max_size(); } } #endif
{ "alphanum_fraction": 0.7362334802, "avg_line_length": 27.5151515152, "ext": "h", "hexsha": "2430e59f0325d8ec676647e179e0733e78ce4398", "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/GameStates/GameStateStack.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/GameStates/GameStateStack.h", "max_line_length": 110, "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/GameStates/GameStateStack.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 450, "size": 1816 }
// SPDX-License-Identifier: MIT // The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018-2019, Johannes Leupolz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_ #define PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_ #include <vector> #include <gsl/span> #include <cstdint> #include <atomic> #include <stack> #include <limits> #include <functional> #include "pemc/basic/tsc_index.h" #include "pemc/basic/configuration.h" #include "pemc/basic/label.h" #include "pemc/basic/model_capacity.h" #include "pemc/basic/raw_memory.h" #include "pemc/formula/formula.h" #include "pemc/generic_traverser/i_transitions_calculator.h" #include "pemc/generic_traverser/i_pre_state_storage_modifier.h" #include "pemc/generic_traverser/i_post_state_storage_modifier.h" #include "pemc/executable_model/temporary_state_storage.h" #include "pemc/executable_model/i_choice_resolver.h" #include "pemc/executable_model/abstract_model.h" namespace pemc { class ModelExecutor : public ITransitionsCalculator { protected: std::unique_ptr<IChoiceResolver> choiceResolver; std::unique_ptr<AbstractModel> model; // Create a storage for different state vectors and a vector of transitions // that can be reused for different calculations. This should prevent garbage. TemporaryStateStorage temporaryStateStorage; std::vector<TraversalTransition> transitions; int32_t preStateStorageModifierStateVectorSize = 0; void addTransition(); public: ModelExecutor(const Configuration& conf); void setModel(std::unique_ptr<AbstractModel> _model); void setChoiceResolver(std::unique_ptr<IChoiceResolver> _choiceResolver); virtual int32_t getStateVectorSize(); virtual void setPreStateStorageModifierStateVectorSize(int32_t _preStateStorageModifierStateVectorSize); virtual gsl::span<TraversalTransition> calculateInitialTransitions(); virtual gsl::span<TraversalTransition> calculateTransitionsOfState(gsl::span<gsl::byte> state); virtual void* getCustomPayloadOfLastCalculation(); }; } #endif // PEMC_EXECUTABLE_MODEL_MODEL_EXECUTOR_H_
{ "alphanum_fraction": 0.7766153846, "avg_line_length": 37.7906976744, "ext": "h", "hexsha": "42001a2df8dee5ceb56d1bfe521ea36a46a100fe", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joleuger/pemc", "max_forks_repo_path": "pemc/executable_model/model_executor.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "joleuger/pemc", "max_issues_repo_path": "pemc/executable_model/model_executor.h", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joleuger/pemc", "max_stars_repo_path": "pemc/executable_model/model_executor.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 730, "size": 3250 }
/* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The OpenAirInterface Software Alliance licenses this file to You under the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698 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. ------------------------------------------------------------------------------- For more information about the OpenAirInterface (OAI) Software Alliance: contact@openairinterface.org */ #include <math.h> #include <cblas.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "PHY/TOOLS/tools_defs.h" #include "sim.h" #include "scm_corrmat.h" #include "common/utils/LOG/log.h" //#define DEBUG_CH #include "assertions.h" extern void print_shorts(char *s, __m128i *x); void fill_channel_desc(channel_desc_t *chan_desc, uint8_t nb_tx, uint8_t nb_rx, uint8_t nb_taps, uint8_t channel_length, double *amps, double *delays, struct complex **R_sqrt, double Td, double sampling_rate, double channel_bandwidth, double ricean_factor, double aoa, double forgetting_factor, double max_Doppler, int32_t channel_offset, double path_loss_dB, uint8_t random_aoa) { uint16_t i, j; double delta_tau; LOG_I(OCM, "[CHANNEL] Getting new channel descriptor, nb_tx %d, nb_rx %d, nb_taps %d, channel_length %d\n", nb_tx, nb_rx, nb_taps, channel_length); chan_desc->nb_tx = nb_tx; chan_desc->nb_rx = nb_rx; chan_desc->nb_taps = nb_taps; chan_desc->channel_length = channel_length; chan_desc->amps = amps; LOG_D(OCM, "[CHANNEL] Doing delays ...\n"); if(delays == NULL) { chan_desc->delays = (double *) malloc(nb_taps * sizeof(double)); delta_tau = Td / nb_taps; for(i = 0; i < nb_taps; i++) { chan_desc->delays[i] = ((double)i) * delta_tau; } } else { chan_desc->delays = delays; } chan_desc->Td = Td; chan_desc->sampling_rate = sampling_rate; chan_desc->channel_bandwidth = channel_bandwidth; chan_desc->ricean_factor = ricean_factor; chan_desc->aoa = aoa; chan_desc->random_aoa = random_aoa; chan_desc->forgetting_factor = forgetting_factor; chan_desc->channel_offset = channel_offset; chan_desc->path_loss_dB = path_loss_dB; chan_desc->first_run = 1; chan_desc->ip = 0.0; chan_desc->max_Doppler = max_Doppler; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(nb_taps * sizeof(struct complex *)); LOG_D(OCM, "[CHANNEL] Filling ch \n"); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); // allocate for up to 100 RBs, 12 samples per RB } LOG_D(OCM, "[CHANNEL] Filling a (nb_taps %d)\n", nb_taps); for(i = 0; i < nb_taps; i++) { LOG_D(OCM, "tap %d (%p,%zu)\n", i, &chan_desc->a[i], nb_tx * nb_rx * sizeof(struct complex)); chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } LOG_D(OCM, "[CHANNEL] Doing R_sqrt ...\n"); if(R_sqrt == NULL) { chan_desc->R_sqrt = (struct complex **) calloc(nb_taps, sizeof(struct complex *)); for(i = 0; i < nb_taps; i++) { chan_desc->R_sqrt[i] = (struct complex *) calloc(nb_tx * nb_rx * nb_tx * nb_rx, sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } } } else { chan_desc->R_sqrt = (struct complex **) calloc(nb_taps, sizeof(struct complex *)); for(i = 0; i < nb_taps; i++) { //chan_desc->R_sqrt[i] = (struct complex*) calloc(nb_tx*nb_rx*nb_tx*nb_rx,sizeof(struct complex)); //chan_desc->R_sqrt = (struct complex*)&R_sqrt[i][0]; /* all chan_desc share the same R_sqrt, coming from caller */ chan_desc->R_sqrt[i] = R_sqrt[0]; } } for(i = 0; i < nb_taps; i++) { for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { LOG_D(OCM, "Rsqrt[%d][%d] %f %f\n", i, j, chan_desc->R_sqrt[i][j].x, chan_desc->R_sqrt[i][j].y); } } LOG_D(OCM, "[CHANNEL] RF %f\n", chan_desc->ricean_factor); for(i = 0; i < chan_desc->nb_taps; i++) { LOG_D(OCM, "[CHANNEL] tap %d: amp %f, delay %f\n", i, chan_desc->amps[i], chan_desc->delays[i]); } chan_desc->nb_paths = 10; reset_meas(&chan_desc->random_channel); reset_meas(&chan_desc->interp_time); reset_meas(&chan_desc->interp_freq); reset_meas(&chan_desc->convolution); } double mbsfn_delays[] = {0, .03, .15, .31, .37, 1.09, 12.490, 12.52, 12.64, 12.80, 12.86, 13.58, 27.49, 27.52, 27.64, 27.80, 27.86, 28.58}; double mbsfn_amps_dB[] = {0, -1.5, -1.4, -3.6, -0.6, -7.0, -10, -11.5, -11.4, -13.6, -10.6, -17.0, -20, -21.5, -21.4, -23.6, -20.6, -27}; double scm_c_delays[] = {0, 0.0125, 0.0250, 0.3625, 0.3750, 0.3875, 0.2500, 0.2625, 0.2750, 1.0375, 1.0500, 1.0625, 2.7250, 2.7375, 2.7500, 4.6000, 4.6125, 4.6250}; double scm_c_amps_dB[] = {0.00, -2.22, -3.98, -1.86, -4.08, -5.84, -1.08, -3.30, -5.06, -9.08, -11.30, -13.06, -15.14, -17.36, -19.12, -20.64, -22.85, -24.62}; double epa_delays[] = { 0, .03, .07, .09, .11, .19, .41}; double epa_amps_dB[] = {0.0, -1.0, -2.0, -3.0, -8.0, -17.2, -20.8}; double eva_delays[] = { 0, .03, .15, .31, .37, .71, 1.09, 1.73, 2.51}; double eva_amps_dB[] = {0.0, -1.5, -1.4, -3.6, -0.6, -9.1, -7.0, -12.0, -16.9}; double etu_delays[] = { 0, .05, .12, .2, .23, .5, 1.6, 2.3, 5.0}; double etu_amps_dB[] = {-1.0, -1.0, -1.0, 0.0, 0.0, 0.0, -3.0, -5.0, -7.0}; double default_amps_lin[] = {0.3868472, 0.3094778, 0.1547389, 0.0773694, 0.0386847, 0.0193424, 0.0096712, 0.0038685}; double default_amp_lin[] = {1}; double ts_shift_delays[] = {0, 1 / 7.68}; double ts_shift_amps[] = {0, 1}; //correlation matrix for a 2x2 channel with full Tx correlation struct complex R_sqrt_22_corr_tap[16] = {{0.70711, 0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {0.70711, 0}, {0.70711, 0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {0.70711, 0} }; struct complex *R_sqrt_22_corr[1] = {R_sqrt_22_corr_tap}; //correlation matrix for a fully correlated 2x1 channel (h1==h2) struct complex R_sqrt_21_corr_tap[4] = {{0.70711, 0}, {0.70711, 0}, {0.70711, 0}, {0.70711, 0}}; struct complex *R_sqrt_21_corr[1] = {R_sqrt_21_corr_tap}; //correlation matrix for a 2x2 channel with full Tx anti-correlation struct complex R_sqrt_22_anticorr_tap[16] = {{0.70711, 0}, {0.0, 0.0}, {-0.70711, 0}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {-0.70711, 0}, {-0.70711, 0}, {0.0, 0.0}, {0.70711, 0}, {0.0, 0.0}, {0.0, 0.0}, {-0.70711, 0}, {0.0, 0.0}, {0.70711, 0} }; struct complex *R_sqrt_22_anticorr[1] = {R_sqrt_22_anticorr_tap}; //correlation matrix for a fully anti-correlated 2x1 channel (h1==-h2) struct complex R_sqrt_21_anticorr_tap[4] = {{0.70711, 0}, {-0.70711, 0}, {-0.70711, 0}, {0.70711, 0}}; struct complex *R_sqrt_21_anticorr[1] = {R_sqrt_21_anticorr_tap}; struct complex **R_sqrt_ptr2; // full correlation matrix in vectorized form for 2x2 channel, where h1 is perfectly orthogonal to h2 struct complex R_sqrt_22_orthogonal_tap[16] = {{0.70711, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0.0} }; struct complex *R_sqrt_22_orthogonal[1] = {R_sqrt_22_orthogonal_tap}; // full correlation matrix for TM4 to make orthogonal effective channel struct complex R_sqrt_22_orth_eff_ch_TM4_prec_real_tap[16] = {{0.70711, 0.0}, {0.0, 0.0}, {0.70711, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0.0}, {0.0, 0.0}, {-0.70711, 0.0}, {0.70711, 0.0}, {0.0, 0.0}, {0.70711, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {-0.70711, 0.0}, {0.0, 0.0}, {0.70711, 0.0} }; struct complex *R_sqrt_22_orth_eff_ch_TM4_prec_real[1] = {R_sqrt_22_orth_eff_ch_TM4_prec_real_tap}; struct complex R_sqrt_22_orth_eff_ch_TM4_prec_imag_tap[16] = {{0.70711, 0.0}, {0.0, 0.0}, {0.0, -0.70711}, {0.0, 0.0}, {0.0, 0.0}, {0.70711, 0.0}, {0.0, 0.0}, {0.0, 0.70711}, {0.0, -0.70711}, {0.0, 0.0}, {-0.70711, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.70711}, {0.0, 0.0}, {-0.70711, 0.0} }; struct complex *R_sqrt_22_orth_eff_ch_TM4_prec_imag[1] = {R_sqrt_22_orth_eff_ch_TM4_prec_imag_tap}; //Correlation matrix for EPA channel struct complex R_sqrt_22_EPA_low_tap[16] = {{1.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {1.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {1.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {1.0, 0.0} }; struct complex *R_sqrt_22_EPA_low[1] = {R_sqrt_22_EPA_low_tap}; struct complex R_sqrt_22_EPA_high_tap[16] = {{0.7179, 0.0}, {0.4500, 0.0}, {0.4500, 0.0}, {0.2821, 0.0}, {0.4500, 0.0}, {0.7179, 0.0}, {0.2821, 0.0}, {0.4500, 0.0}, {0.4500, 0.0}, {0.2821, 0.0}, {0.7179, 0.0}, {0.4500, 0.0}, {0.2821, 0.0}, {0.4500, 0.0}, {0.4500, 0.0}, {0.7179, 0.0} }; struct complex *R_sqrt_22_EPA_high[1] = {R_sqrt_22_EPA_high_tap}; struct complex R_sqrt_22_EPA_medium_tap[16] = {{0.8375, 0.0}, {0.5249, 0.0}, {0.1286, 0.0}, {0.0806, 0.0}, {0.5249, 0.0}, {0.8375, 0.0}, {0.0806, 0.0}, {0.1286, 0.0}, {0.1286, 0.0}, {0.0806, 0.0}, {0.8375, 0.0}, {0.5249, 0.0}, {0.0806, 0.0}, {0.1286, 0.0}, {0.5249, 0.0}, {0.8375, 0.0} }; struct complex *R_sqrt_22_EPA_medium[1] = {R_sqrt_22_EPA_medium_tap}; //Rayleigh1_orth_eff_ch_TM4 channel_desc_t *new_channel_desc_scm(uint8_t nb_tx, uint8_t nb_rx, SCM_t channel_model, double sampling_rate, double channel_bandwidth, double forgetting_factor, int32_t channel_offset, double path_loss_dB) { channel_desc_t *chan_desc = (channel_desc_t *)malloc(sizeof(channel_desc_t)); uint16_t i, j; double sum_amps; double aoa, ricean_factor, Td, maxDoppler; int channel_length, nb_taps; chan_desc->nb_tx = nb_tx; chan_desc->nb_rx = nb_rx; chan_desc->sampling_rate = sampling_rate; chan_desc->channel_bandwidth = channel_bandwidth; chan_desc->forgetting_factor = forgetting_factor; chan_desc->channel_offset = channel_offset; chan_desc->path_loss_dB = path_loss_dB; chan_desc->first_run = 1; chan_desc->ip = 0.0; LOG_I(OCM, "Channel Model (inside of new_channel_desc_scm)=%d\n\n", channel_model); switch(channel_model) { case SCM_A: LOG_W(OCM, "channel model not yet supported\n"); free(chan_desc); return(NULL); case SCM_B: LOG_W(OCM, "channel model not yet supported\n"); free(chan_desc); return(NULL); case SCM_C: chan_desc->nb_taps = 18; chan_desc->Td = 4.625; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * scm_c_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = scm_c_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); if(nb_tx == 2 && nb_rx == 2) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R22_sqrt[i][0]; } } else if(nb_tx == 2 && nb_rx == 1) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R21_sqrt[i][0]; } } else if(nb_tx == 1 && nb_rx == 2) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R12_sqrt[i][0]; } } else { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix not implemented for nb_tx==%d and nb_rx==%d, using identity\n", nb_tx, nb_rx); } } break; case SCM_D: LOG_W(OCM, "This is not the real SCM-D model! It is just SCM-C with an additional Rice factor!\n"); chan_desc->nb_taps = 18; chan_desc->Td = 4.625; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * scm_c_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = scm_c_delays; chan_desc->ricean_factor = 0.1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); if(nb_tx == 2 && nb_rx == 2) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R22_sqrt[i][0]; } } else if(nb_tx == 2 && nb_rx == 1) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R21_sqrt[i][0]; } } else if(nb_tx == 1 && nb_rx == 2) { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R12_sqrt[i][0]; } } else { for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix not implemented for nb_tx==%d and nb_rx==%d, using identity\n", nb_tx, nb_rx); } } break; case EPA: chan_desc->nb_taps = 7; chan_desc->Td = .410; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * epa_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = epa_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R22_sqrt[i][0]; } } else { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } } break; case EPA_low: chan_desc->nb_taps = 7; chan_desc->Td = .410; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * epa_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = epa_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex **)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->R_sqrt[i] = R_sqrt_22_EPA_low[0]; } } else { printf("Correlation matrices are implemented for 2 x 2 only"); } /* else { chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**)); for (i = 0; i<6; i++) { chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex)); for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } }*/ break; case EPA_high: chan_desc->nb_taps = 7; chan_desc->Td = .410; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * epa_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = epa_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex **)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->R_sqrt[i] = R_sqrt_22_EPA_high[0]; } } else { printf("Correlation matrices are implemented for 2 x 2 only"); } /* else { chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**)); for (i = 0; i<6; i++) { chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex)); for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } }*/ break; case EPA_medium: chan_desc->nb_taps = 7; chan_desc->Td = .410; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * epa_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = epa_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex **)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->R_sqrt[i] = R_sqrt_22_EPA_medium[0]; } } else { printf("Correlation matrices are implemented for 2 x 2 only"); } /* else { chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**)); for (i = 0; i<6; i++) { chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex)); for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } }*/ break; case EVA: chan_desc->nb_taps = 9; chan_desc->Td = 2.51; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * eva_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = eva_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R22_sqrt[i][0]; } } else { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } } break; case ETU: chan_desc->nb_taps = 9; chan_desc->Td = 5.0; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * etu_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = etu_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } if(nb_tx == 2 && nb_rx == 2) { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) &R22_sqrt[i][0]; } } else { chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex **)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } } break; case MBSFN: chan_desc->nb_taps = 18; chan_desc->Td = 28.58; chan_desc->channel_length = (int)(2 * chan_desc->sampling_rate * chan_desc->Td + 1 + 2 / (M_PI * M_PI) * log(4 * M_PI * chan_desc->sampling_rate * chan_desc->Td)); sum_amps = 0; chan_desc->amps = (double *) malloc(chan_desc->nb_taps * sizeof(double)); for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] = pow(10, .1 * mbsfn_amps_dB[i]); sum_amps += chan_desc->amps[i]; } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->amps[i] /= sum_amps; } chan_desc->delays = mbsfn_delays; chan_desc->ricean_factor = 1; chan_desc->aoa = 0; chan_desc->random_aoa = 0; chan_desc->ch = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->chF = (struct complex **) malloc(nb_tx * nb_rx * sizeof(struct complex *)); chan_desc->a = (struct complex **) malloc(chan_desc->nb_taps * sizeof(struct complex *)); for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->ch[i] = (struct complex *) malloc(chan_desc->channel_length * sizeof(struct complex)); } for(i = 0; i < nb_tx * nb_rx; i++) { chan_desc->chF[i] = (struct complex *) malloc(1200 * sizeof(struct complex)); } for(i = 0; i < chan_desc->nb_taps; i++) { chan_desc->a[i] = (struct complex *) malloc(nb_tx * nb_rx * sizeof(struct complex)); } chan_desc->R_sqrt = (struct complex **) malloc(6 * sizeof(struct complex *)); for(i = 0; i < 6; i++) { chan_desc->R_sqrt[i] = (struct complex *) malloc(nb_tx * nb_rx * nb_tx * nb_rx * sizeof(struct complex)); for(j = 0; j < nb_tx * nb_rx * nb_tx * nb_rx; j += (nb_tx * nb_rx + 1)) { chan_desc->R_sqrt[i][j].x = 1.0; chan_desc->R_sqrt[i][j].y = 0.0; } LOG_W(OCM, "correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n"); } break; case Rayleigh8: nb_taps = 8; Td = 0.8; channel_length = (int)11 + 2 * sampling_rate * Td; ricean_factor = 1; aoa = .03; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amps_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rice8: nb_taps = 8; Td = 0.8; channel_length = (int)11 + 2 * sampling_rate * Td; ricean_factor = 0.1; aoa = 0.7854; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amps_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 1); break; case Rayleigh1: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = .03; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh1_800: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = .03; maxDoppler = 800; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh1_corr: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = .03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 1)) { R_sqrt_ptr2 = R_sqrt_21_corr; } else if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_corr; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh1_anticorr: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = .03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 1)) //check this { R_sqrt_ptr2 = R_sqrt_21_anticorr; } else if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_anticorr; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rice1: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 0.1; aoa = 0.7854; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case AWGN: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 0.0; aoa = 0.0; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); printf("AWGN: ricean_factor %f\n", chan_desc->ricean_factor); break; case TS_SHIFT: nb_taps = 2; Td = ts_shift_delays[1]; channel_length = 10; ricean_factor = 0.0; aoa = 0.0; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, ts_shift_amps, ts_shift_delays, NULL, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); printf("TS_SHIFT: ricean_factor %f\n", chan_desc->ricean_factor); break; case Rice1_corr: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 0.1; aoa = .03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 1)) { R_sqrt_ptr2 = R_sqrt_21_corr; } else if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_corr; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 1); break; case Rice1_anticorr: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 0.1; aoa = .03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 1)) { R_sqrt_ptr2 = R_sqrt_21_anticorr; } else if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_anticorr; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 1); break; case Rayleigh1_orthogonal: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = 0.03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_orthogonal; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh1_orth_eff_ch_TM4_prec_real: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = 0.03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_real; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 1); break; case Rayleigh1_orth_eff_ch_TM4_prec_imag: nb_taps = 1; Td = 0; channel_length = 1; ricean_factor = 1; aoa = 0.03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_imag; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amp_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh8_orth_eff_ch_TM4_prec_real: if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_real; //R_sqrt_ptr2 = NULL; } else { R_sqrt_ptr2 = NULL; } nb_taps = 8; Td = 0.8; channel_length = (int)11 + 2 * sampling_rate * Td; ricean_factor = 1; aoa = .03; maxDoppler = 0; fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amps_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; case Rayleigh8_orth_eff_ch_TM4_prec_imag: nb_taps = 8; Td = 0.8; channel_length = (int)11 + 2 * sampling_rate * Td; ricean_factor = 1; aoa = .03; maxDoppler = 0; if((nb_tx == 2) && (nb_rx == 2)) { R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_imag; } else { R_sqrt_ptr2 = NULL; } fill_channel_desc(chan_desc, nb_tx, nb_rx, nb_taps, channel_length, default_amps_lin, NULL, R_sqrt_ptr2, Td, sampling_rate, channel_bandwidth, ricean_factor, aoa, forgetting_factor, maxDoppler, channel_offset, path_loss_dB, 0); break; default: LOG_W(OCM, "channel model not yet supported\n"); free(chan_desc); return(NULL); } LOG_D(OCM, "[CHANNEL] RF %f\n", chan_desc->ricean_factor); for(i = 0; i < chan_desc->nb_taps; i++) { LOG_D(OCM, "[CHANNEL] tap %d: amp %f, delay %f\n", i, chan_desc->amps[i], chan_desc->delays[i]); } chan_desc->nb_paths = 10; return(chan_desc); } void free_channel_desc_scm(channel_desc_t *ch) { // Must be made cleanly, a lot of leaks... free(ch); } int random_channel(channel_desc_t *desc, uint8_t abstraction_flag) { double s; int i, k, l, aarx, aatx; struct complex anew[NB_ANTENNAS_TX * NB_ANTENNAS_RX], acorr[NB_ANTENNAS_TX * NB_ANTENNAS_RX]; struct complex phase, alpha, beta; AssertFatal(desc->nb_tx <= NB_ANTENNAS_TX && desc->nb_rx <= NB_ANTENNAS_RX, "random_channel.c: Error: temporary buffer for channel not big enough (%d,%d)\n", desc->nb_tx, desc->nb_rx); start_meas(&desc->random_channel); for(i = 0; i < (int)desc->nb_taps; i++) { for(aarx = 0; aarx < desc->nb_rx; aarx++) { for(aatx = 0; aatx < desc->nb_tx; aatx++) { anew[aarx + (aatx * desc->nb_rx)].x = sqrt(desc->ricean_factor * desc->amps[i] / 2) * gaussdouble(0.0, 1.0); anew[aarx + (aatx * desc->nb_rx)].y = sqrt(desc->ricean_factor * desc->amps[i] / 2) * gaussdouble(0.0, 1.0); if((i == 0) && (desc->ricean_factor != 1.0)) { if(desc->random_aoa == 1) { desc->aoa = uniformrandom() * 2 * M_PI; } // this assumes that both RX and TX have linear antenna arrays with lambda/2 antenna spacing. // Furhter it is assumed that the arrays are parallel to each other and that they are far enough apart so // that we can safely assume plane wave propagation. phase.x = cos(M_PI * ((aarx - aatx) * sin(desc->aoa))); phase.y = sin(M_PI * ((aarx - aatx) * sin(desc->aoa))); anew[aarx + (aatx * desc->nb_rx)].x += phase.x * sqrt(1.0 - desc->ricean_factor); anew[aarx + (aatx * desc->nb_rx)].y += phase.y * sqrt(1.0 - desc->ricean_factor); } #ifdef DEBUG_CH printf("(%d,%d,%d) %f->(%f,%f) (%f,%f) phase (%f,%f)\n", aarx, aatx, i, desc->amps[i], anew[aarx + (aatx * desc->nb_rx)].x, anew[aarx + (aatx * desc->nb_rx)].y, desc->aoa, desc->ricean_factor, phase.x, phase.y); #endif } //aatx } //aarx /* // for debugging set a=anew; for (aarx=0;aarx<desc->nb_rx;aarx++) { for (aatx=0;aatx<desc->nb_tx;aatx++) { desc->a[i][aarx+(aatx*desc->nb_rx)].x = anew[aarx+(aatx*desc->nb_rx)].x; desc->a[i][aarx+(aatx*desc->nb_rx)].y = anew[aarx+(aatx*desc->nb_rx)].y; printf("anew(%d,%d) = %f+1j*%f\n",aatx,aarx,anew[aarx+(aatx*desc->nb_rx)].x, anew[aarx+(aatx*desc->nb_rx)].y); } } */ //apply correlation matrix //compute acorr = R_sqrt[i] * anew alpha.x = 1.0; alpha.y = 0.0; beta.x = 0.0; beta.y = 0.0; cblas_zgemv(CblasRowMajor, CblasNoTrans, desc->nb_tx * desc->nb_rx, desc->nb_tx * desc->nb_rx, (void *) &alpha, (void *) desc->R_sqrt[i / 3], desc->nb_rx * desc->nb_tx, (void *) anew, 1, (void *) &beta, (void *) acorr, 1); /* for (aarx=0;aarx<desc->nb_rx;aarx++) { for (aatx=0;aatx<desc->nb_tx;aatx++) { desc->a[i][aarx+(aatx*desc->nb_rx)].x = acorr[aarx+(aatx*desc->nb_rx)].x; desc->a[i][aarx+(aatx*desc->nb_rx)].y = acorr[aarx+(aatx*desc->nb_rx)].y; printf("tap %d, acorr1(%d,%d) = %f+1j*%f\n",i,aatx,aarx,acorr[aarx+(aatx*desc->nb_rx)].x, acorr[aarx+(aatx*desc->nb_rx)].y); } } */ if(desc->first_run == 1) { cblas_zcopy(desc->nb_tx * desc->nb_rx, (void *) acorr, 1, (void *) desc->a[i], 1); } else { // a = alpha*acorr+beta*a // a = beta*a // a = a+alpha*acorr alpha.x = sqrt(1 - desc->forgetting_factor); alpha.y = 0; beta.x = sqrt(desc->forgetting_factor); beta.y = 0; cblas_zscal(desc->nb_tx * desc->nb_rx, (void *) &beta, (void *) desc->a[i], 1); cblas_zaxpy(desc->nb_tx * desc->nb_rx, (void *) &alpha, (void *) acorr, 1, (void *) desc->a[i], 1); // desc->a[i][aarx+(aatx*desc->nb_rx)].x = (sqrt(desc->forgetting_factor)*desc->a[i][aarx+(aatx*desc->nb_rx)].x) + sqrt(1-desc->forgetting_factor)*anew.x; // desc->a[i][aarx+(aatx*desc->nb_rx)].y = (sqrt(desc->forgetting_factor)*desc->a[i][aarx+(aatx*desc->nb_rx)].y) + sqrt(1-desc->forgetting_factor)*anew.y; } /* for (aarx=0;aarx<desc->nb_rx;aarx++) { for (aatx=0;aatx<desc->nb_tx;aatx++) { //desc->a[i][aarx+(aatx*desc->nb_rx)].x = acorr[aarx+(aatx*desc->nb_rx)].x; //desc->a[i][aarx+(aatx*desc->nb_rx)].y = acorr[aarx+(aatx*desc->nb_rx)].y; printf("tap %d, a(%d,%d) = %f+1j*%f\n",i,aatx,aarx,desc->a[i][aarx+(aatx*desc->nb_rx)].x, desc->a[i][aarx+(aatx*desc->nb_rx)].y); } } */ } //nb_taps stop_meas(&desc->random_channel); //memset((void *)desc->ch[aarx+(aatx*desc->nb_rx)],0,(int)(desc->channel_length)*sizeof(struct complex)); if(abstraction_flag == 0) { start_meas(&desc->interp_time); for(aarx = 0; aarx < desc->nb_rx; aarx++) { for(aatx = 0; aatx < desc->nb_tx; aatx++) { if(desc->channel_length == 1) { desc->ch[aarx + (aatx * desc->nb_rx)][0].x = desc->a[0][aarx + (aatx * desc->nb_rx)].x; desc->ch[aarx + (aatx * desc->nb_rx)][0].y = desc->a[0][aarx + (aatx * desc->nb_rx)].y; } else { for(k = 0; k < (int)desc->channel_length; k++) { desc->ch[aarx + (aatx * desc->nb_rx)][k].x = 0.0; desc->ch[aarx + (aatx * desc->nb_rx)][k].y = 0.0; for(l = 0; l < desc->nb_taps; l++) { if((k - (desc->delays[l]*desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET) == 0) { s = 1.0; } else s = sin(M_PI * (k - (desc->delays[l] * desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET)) / (M_PI * (k - (desc->delays[l] * desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET)); desc->ch[aarx + (aatx * desc->nb_rx)][k].x += s * desc->a[l][aarx + (aatx * desc->nb_rx)].x; desc->ch[aarx + (aatx * desc->nb_rx)][k].y += s * desc->a[l][aarx + (aatx * desc->nb_rx)].y; // printf("l %d : desc->ch.x %f\n",l,desc->a[l][aarx+(aatx*desc->nb_rx)].x); } //nb_taps #ifdef DEBUG_CH k = 0; printf("(%d,%d,%d)->(%f,%f)\n", k, aarx, aatx, desc->ch[aarx + (aatx * desc->nb_rx)][k].x, desc->ch[aarx + (aatx * desc->nb_rx)][k].y); #endif } } //channel_length } //aatx } //aarx stop_meas(&desc->interp_time); } if(desc->first_run == 1) { desc->first_run = 0; } return (0); } double N_RB2sampling_rate(uint16_t N_RB) { double sampling_rate; switch(N_RB) { case 6: sampling_rate = 1.92; break; case 25: sampling_rate = 7.68; break; case 50: sampling_rate = 15.36; break; case 100: sampling_rate = 30.72; break; default: AssertFatal(1 == 0, "Unknown N_PRB %d", N_RB); } return(sampling_rate); } double N_RB2channel_bandwidth(uint16_t N_RB) { double channel_bandwidth; switch(N_RB) { case 6: channel_bandwidth = 1.25; break; case 25: channel_bandwidth = 5.00; break; case 50: channel_bandwidth = 10.00; break; case 100: channel_bandwidth = 20.00; break; default: LOG_E(PHY, "Unknown N_PRB\n"); return(-1); } return(channel_bandwidth); } #ifdef RANDOM_CHANNEL_MAIN #define sampling_rate 5.0 #define Td 2.0 main(int argc, char **argv) { double amps[8] = {.8, .2, .1, .04, .02, .01, .005}; struct complex ch[(int)(1 + 2 * sampling_rate * Td)], phase; int i; randominit(); phase.x = 1.0; phase.y = 0; random_channel(amps, Td, 8, sampling_rate, ch, (double)1.0, &phase); /* for (i=0;i<(11+2*sampling_rate*Td);i++){ printf("%f + sqrt(-1)*%f\n",ch[i].x,ch[i].y); } */ } #endif
{ "alphanum_fraction": 0.4323179646, "avg_line_length": 40.0646135266, "ext": "c", "hexsha": "aac0752252e9da9fed222ed7ad60e76fe289391b", "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": "93e5617d68431a477e803af2fa66290fd52470d2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AManTw/oai5g", "max_forks_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "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": "AManTw/oai5g", "max_issues_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c", "max_line_length": 227, "max_stars_count": null, "max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AManTw/oai5g", "max_stars_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 17191, "size": 66347 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <opencv2\core.hpp> #include <gsl\gsl> namespace mage { namespace clouds { void ComputeCharacteristics( gsl::span<const cv::Point3f> points, std::vector<cv::Vec3f>& normals, gsl::span<const size_t> mapIds, std::vector<float>& effectiveDissimilarities, std::vector<float>& distanceScores, std::vector<float>& homogeneityScores, const size_t maxN); void MollifyNormals( gsl::span<const cv::Point3f> points, gsl::span<cv::Vec3f> normals, const float normalScale, const float spatialScale, const size_t iterations, const size_t maxN); void RepositionPointSets( gsl::span<cv::Point3f> toReposition, gsl::span<cv::Vec3f> normals, const float stepi, const size_t iterations, const float lambda, const float solverSigmaS, const float mollSigmaS, const float mollSigmaN, const size_t maxN); struct Knn final { Knn(gsl::span<const cv::Point3f> points); Knn(gsl::span<const cv::Vec3f> points); ~Knn(); Knn& operator=(Knn&& other); void Query(const cv::Vec3f& point, const size_t N, std::vector<size_t>& indexes) const; private: struct Impl; std::unique_ptr<Impl> m_impl; }; } }
{ "alphanum_fraction": 0.5573047859, "avg_line_length": 27.8596491228, "ext": "h", "hexsha": "2af8c212f3eba2081be692f45d2edad13193e50d", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Clouds/DeNoising.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Clouds/DeNoising.h", "max_line_length": 99, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Clouds/DeNoising.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 364, "size": 1588 }
#pragma once #include "Availability.h" #include "Library.h" #include "OctreeTileID.h" #include "TileAvailabilityFlags.h" #include <gsl/span> #include <cstddef> #include <memory> #include <vector> namespace CesiumGeometry { class CESIUMGEOMETRY_API OctreeAvailability final { public: /** * @brief Constructs a new instance. * * @param subtreeLevels The number of levels in each subtree. * @param maximumLevel The index of the maximum level in this tileset. */ OctreeAvailability(uint32_t subtreeLevels, uint32_t maximumLevel) noexcept; /** * @brief Determines the currently known availability status of the given * tile. * * @param tileID The {@link CesiumGeometry::OctreeTileID} for the tile. * * @return The {@link TileAvailabilityFlags} for this tile encoded into a * uint8_t. */ uint8_t computeAvailability(const OctreeTileID& tileID) const noexcept; /** * @brief Attempts to add an availability subtree into the existing overall * availability tree. * * @param tileID The {@link CesiumGeometry::OctreeTileID} for the tile. * @param newSubtree The {@link CesiumGeometry::AvailabilitySubtree} to add. * * @return Whether the insertion was successful. */ bool addSubtree( const OctreeTileID& tileID, AvailabilitySubtree&& newSubtree) noexcept; /** * @brief Determines the currently known availability status of the given * tile. * * Priming with a known parent subtree node avoids the need to traverse the * entire availability tree so far. The node must have a loaded subtree * * @param tileID The tile ID to get the availability for. * @param pNode The subtree node to look for the tileID in. The tileID should * be within this subtree node. * * @return The {@link TileAvailabilityFlags} for this tile encoded into a * uint8_t. */ uint8_t computeAvailability( const OctreeTileID& tileID, const AvailabilityNode* pNode) const noexcept; /** * @brief Attempts to add a child subtree node onto the given parent node. * * Priming with a known parent subtree node avoids the need to traverse the * entire availability tree so far. If the parent node is nullptr and the * tile ID indicates this is the root tile, the subtree will be attached to * the root. * * @param tileID The root tile's ID of the subtree we are trying to add. * @param pParentNode The parent subtree node. The tileID should fall exactly * at the end of this parent subtree. * * @return The newly created node if the insertion was successful, nullptr * otherwise. */ AvailabilityNode* addNode(const OctreeTileID& tileID, AvailabilityNode* pParentNode) noexcept; /** * @brief Attempts to add a loaded subtree onto the given node. * * The node must have been created earlier from a call to addNode. * * @param pNode The node on which to add the subtree. * @param newSubtree The new subtree to add. * * @return Whether the insertion was successful. */ bool addLoadedSubtree( AvailabilityNode* pNode, AvailabilitySubtree&& newSubtree) noexcept; /** * @brief Find the child node index corresponding to this tile ID and parent * node. * * Attempts to find the child node for the tile with the given ID and parent * node. The parent node is used to speed up the search significantly. Note * that if the given tile ID does not correspond exactly to an immediate * child node of the parent node, nullptr will be returned. If a tileID * outside the given parent node's subtree is given, an incorrect child index * may be returned. * * @param tileID The tile ID of the child node we are looking for. * @param pParentNode The immediate parent to the child node we are looking * for. * @return The child node index if found, std::nullopt otherwise. */ std::optional<uint32_t> findChildNodeIndex( const OctreeTileID& tileID, const AvailabilityNode* pParentNode) const; /** * @brief Find the child node corresponding to this tile ID and parent node. * * Attempts to find the child node for the tile with the given ID and parent * node. The parent node is used to speed up the search significantly. Note * that if the given tile ID does not correspond exactly to an immediate * child node of the parent node, nullptr will be returned. If a tileID * outside the given parent node's subtree is given, an incorrect child index * may be returned. * * @param tileID The tile ID of the child node we are looking for. * @param pParentNode The immediate parent to the child node we are looking * for. * @return The child node if found, nullptr otherwise. */ AvailabilityNode* findChildNode( const OctreeTileID& tileID, AvailabilityNode* pParentNode) const; /** * @brief Gets the number of levels in each subtree. */ constexpr inline uint32_t getSubtreeLevels() const noexcept { return this->_subtreeLevels; } /** * @brief Gets the index of the maximum level in this implicit tileset. */ constexpr inline uint32_t getMaximumLevel() const noexcept { return this->_maximumLevel; } /** * @brief Gets a pointer to the root subtree node of this implicit tileset. */ AvailabilityNode* getRootNode() noexcept { return this->_pRoot.get(); } private: uint32_t _subtreeLevels; uint32_t _maximumLevel; uint32_t _maximumChildrenSubtrees; std::unique_ptr<AvailabilityNode> _pRoot; }; } // namespace CesiumGeometry
{ "alphanum_fraction": 0.7120503597, "avg_line_length": 33.696969697, "ext": "h", "hexsha": "2fd8e9943753ad9bbc1e664e1a5f0d328242b759", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_line_length": 79, "max_stars_count": 154, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "CesiumGeometry/include/CesiumGeometry/OctreeAvailability.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 1347, "size": 5560 }
static const char help[] = "Solves obstacle problem in 2D using SNESVI. Option prefix -obs_.\n" "The obstacle problem is a free boundary problem for the Poisson equation\n" "in which the solution u(x,y) is constrained to be above the obstacle psi(x,y):\n" " - Lap u = f, u >= psi.\n" "Equivalently it is a variational inequality (VI), complementarity problem\n" "(CP), or an inequality-constrained minimization. The example here is\n" "on the square (-2,2)^2 and has known exact solution. Because of the\n" "constraint, the problem is nonlinear but the code reuses the residual and\n" "Jacobian evaluation code for the Poisson equation in ch6/.\n\n"; #include <petsc.h> #include "../ch6/poissonfunctions.h" // z = psi(x,y) is the hemispherical obstacle, but made C^1 with "skirt" at r=r0 PetscReal psi(PetscReal x, PetscReal y) { const PetscReal r = x * x + y * y, r0 = 0.9, psi0 = PetscSqrtReal(1.0 - r0*r0), dpsi0 = - r0 / psi0; if (r <= r0) { return PetscSqrtReal(1.0 - r); } else { return psi0 + dpsi0 * (r - r0); } } /* This exact solution solves a 1D radial free-boundary problem for the Laplace equation, on the interval 0 < r < 2, with hemispherical obstacle psi(r) = / sqrt(1 - r^2), r < 1 \ -1, otherwise The Laplace equation applies where u(r) > psi(r), u''(r) + r^-1 u'(r) = 0 with boundary conditions including free b.c.s at an unknown location r = a: u(a) = psi(a), u'(a) = psi'(a), u(2) = 0 The solution is u(r) = - A log(r) + B on r > a. The boundary conditions can then be reduced to a root-finding problem for a: a^2 (log(2) - log(a)) = 1 - a^2 The solution is a = 0.697965148223374 (giving residual 1.5e-15). Then A = a^2*(1-a^2)^(-0.5) and B = A*log(2) are as given below in the code. */ PetscReal u_exact(PetscReal x, PetscReal y) { const PetscReal afree = 0.697965148223374, A = 0.680259411891719, B = 0.471519893402112; PetscReal r; r = PetscSqrtReal(x * x + y * y); return (r <= afree) ? psi(x,y) // active set; on the obstacle : - A * PetscLogReal(r) + B; // solves laplace eqn } // boundary conditions from exact solution PetscReal g_fcn(PetscReal x, PetscReal y, PetscReal z, void *ctx) { return u_exact(x,y); } // we solve Laplace's equation with f = 0 PetscReal zero(PetscReal x, PetscReal y, PetscReal z, void *ctx) { return 0.0; } extern PetscErrorCode FormUExact(DMDALocalInfo*, Vec); extern PetscErrorCode GetActiveSet(SNES, DMDALocalInfo*, Vec, Vec, PetscInt*, PetscReal*); extern PetscErrorCode FormBounds(SNES, Vec, Vec); int main(int argc,char **argv) { PetscErrorCode ierr; DM da, da_after; SNES snes; KSP ksp; Vec u_initial, u, u_exact, Xl, Xu; PoissonCtx user; const PetscReal aexact = 0.697965148223374; SNESConvergedReason reason; PetscInt snesit, kspit; PetscReal error1,errorinf,actarea,exactarea,areaerr; DMDALocalInfo info; char dumpname[256] = "dump.dat"; PetscBool dumpbinary = PETSC_FALSE; ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"obs_","options to obstacle","");CHKERRQ(ierr); ierr = PetscOptionsString("-dump_binary", "filename for saving solution AND OBSTACLE in PETSc binary format", "obstacle.c",dumpname,dumpname,sizeof(dumpname),&dumpbinary); CHKERRQ(ierr); ierr = PetscOptionsEnd();CHKERRQ(ierr); ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR, 3,3, // override with -da_grid_x,_y PETSC_DECIDE,PETSC_DECIDE, // num of procs in each dim 1,1,NULL,NULL, // dof = 1 and stencil width = 1 &da);CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(da,-2.0,2.0,-2.0,2.0,-1.0,-1.0);CHKERRQ(ierr); user.cx = 1.0; user.cy = 1.0; user.cz = 1.0; user.g_bdry = &g_fcn; user.f_rhs = &zero; user.addctx = NULL; ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr); ierr = SNESSetDM(snes,da);CHKERRQ(ierr); ierr = SNESSetApplicationContext(snes,&user);CHKERRQ(ierr); // set the SNES type to a variational inequality (VI) solver of reduced-space // (RS) type ierr = SNESSetType(snes,SNESVINEWTONRSLS);CHKERRQ(ierr); ierr = SNESVISetComputeVariableBounds(snes,&FormBounds);CHKERRQ(ierr); // reuse residual and jacobian from ch6/ ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)Poisson2DFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDASNESSetJacobianLocal(da, (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr); ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr); ierr = KSPSetType(ksp,KSPCG); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes);CHKERRQ(ierr); // initial iterate is zero for simplicity ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr); ierr = VecSet(u_initial,0.0); CHKERRQ(ierr); /* solve and get solution, DM after solution*/ ierr = SNESSolve(snes,NULL,u_initial);CHKERRQ(ierr); ierr = VecDestroy(&u_initial); CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr); ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); /* do not destroy u */ ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr); ierr = VecDuplicate(u,&Xl); CHKERRQ(ierr); ierr = VecDuplicate(u,&Xu); CHKERRQ(ierr); ierr = FormBounds(snes,Xl,Xu); CHKERRQ(ierr); /* save solution to binary file if requested */ if (dumpbinary) { PetscViewer dumpviewer; ierr = PetscPrintf(PETSC_COMM_WORLD, "writing u,psi in binary format to %s ...\n",dumpname); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,dumpname,FILE_MODE_WRITE,&dumpviewer); CHKERRQ(ierr); ierr = VecView(u,dumpviewer); CHKERRQ(ierr); ierr = VecView(Xl,dumpviewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&dumpviewer); CHKERRQ(ierr); } /* compute final performance measures */ ierr = SNESGetConvergedReason(snes,&reason); CHKERRQ(ierr); if (reason <= 0) { ierr = PetscPrintf(PETSC_COMM_WORLD, "WARNING: SNES not converged ... use -snes_converged_reason to check\n"); CHKERRQ(ierr); } ierr = SNESGetIterationNumber(snes,&snesit); CHKERRQ(ierr); ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr); ierr = KSPGetIterationNumber(ksp,&kspit); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "done on %d x %d grid ... %s, SNES iters = %d, last KSP iters = %d\n", info.mx,info.my,SNESConvergedReasons[reason],snesit,kspit); CHKERRQ(ierr); /* compare to exact */ ierr = GetActiveSet(snes,&info,u,Xl,NULL,&actarea); CHKERRQ(ierr); exactarea = PETSC_PI * aexact * aexact; areaerr = PetscAbsReal(actarea - exactarea) / exactarea; ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr); ierr = FormUExact(&info,u_exact); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); /* u <- u - u_exact */ ierr = VecNorm(u,NORM_1,&error1); CHKERRQ(ierr); error1 /= (PetscReal)info.mx * (PetscReal)info.my; ierr = VecNorm(u,NORM_INFINITY,&errorinf); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "errors: av |u-uexact| = %.3e, |u-uexact|_inf = %.3e, active area error = %.3f%%\n", error1,errorinf,100.0*areaerr); CHKERRQ(ierr); VecDestroy(&u_exact); VecDestroy(&Xl); VecDestroy(&Xu); SNESDestroy(&snes); return PetscFinalize(); } PetscErrorCode GetActiveSet(SNES snes, DMDALocalInfo *info, Vec u, Vec Xl, PetscInt *act, PetscReal *actarea) { PetscErrorCode ierr; Vec F; const PetscReal *au, *aXl, *aF, zerotol = 1.0e-8; // see petsc/src/snes/impls/vi/vi.c for value PetscReal dx, dy; PetscInt i,n,lact,gact; dx = 4.0 / (PetscReal)(info->mx-1); dy = 4.0 / (PetscReal)(info->my-1); ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr); ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr); ierr = VecGetArrayRead(Xl,&aXl); CHKERRQ(ierr); ierr = SNESGetFunction(snes,&F,NULL,NULL); CHKERRQ(ierr); /* do not destroy F */ ierr = VecGetArrayRead(F,&aF); CHKERRQ(ierr); lact = 0; for (i=0; i<n; i++) { if ((au[i] <= aXl[i] + zerotol) && (aF[i] > 0.0)) lact++; } ierr = VecRestoreArrayRead(u,&au);CHKERRQ(ierr); ierr = VecRestoreArrayRead(Xl,&aXl);CHKERRQ(ierr); ierr = VecRestoreArrayRead(F,&aF); CHKERRQ(ierr); ierr = MPI_Allreduce(&lact,&gact,1,MPIU_INT,MPIU_SUM,PetscObjectComm((PetscObject)snes));CHKERRQ(ierr); if (act) { *act = gact; } if (actarea) { *actarea = dx * dy * gact; } return 0; } PetscErrorCode FormUExact(DMDALocalInfo *info, Vec u) { PetscErrorCode ierr; PetscInt i,j; PetscReal **au, dx, dy, x, y; dx = 4.0 / (PetscReal)(info->mx-1); dy = 4.0 / (PetscReal)(info->my-1); ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr); for (j=info->ys; j<info->ys+info->ym; j++) { y = -2.0 + j * dy; for (i=info->xs; i<info->xs+info->xm; i++) { x = -2.0 + i * dx; au[j][i] = u_exact(x,y); } } ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr); return 0; } //STARTBOUNDS // for call-back: tell SNESVI we want psi <= u < +infinity PetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) { PetscErrorCode ierr; DM da; DMDALocalInfo info; PetscInt i, j; PetscReal **aXl, dx, dy, x, y; ierr = SNESGetDM(snes,&da);CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); dx = 4.0 / (PetscReal)(info.mx-1); dy = 4.0 / (PetscReal)(info.my-1); ierr = DMDAVecGetArray(da, Xl, &aXl);CHKERRQ(ierr); for (j=info.ys; j<info.ys+info.ym; j++) { y = -2.0 + j * dy; for (i=info.xs; i<info.xs+info.xm; i++) { x = -2.0 + i * dx; aXl[j][i] = psi(x,y); } } ierr = DMDAVecRestoreArray(da, Xl, &aXl);CHKERRQ(ierr); ierr = VecSet(Xu,PETSC_INFINITY);CHKERRQ(ierr); return 0; } //ENDBOUNDS
{ "alphanum_fraction": 0.6386603427, "avg_line_length": 39.4312977099, "ext": "c", "hexsha": "be061410d5a76612c9aff49e47698ef95c07da0c", "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/ch12/obstacle.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/ch12/obstacle.c", "max_line_length": 105, "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/ch12/obstacle.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": 3317, "size": 10331 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> void test_matmul(){ int i, j; gsl_matrix * m1 = gsl_matrix_alloc(10, 4); gsl_matrix * m2 = gsl_matrix_alloc(10, 4); for(i=0; i<10; i++){ for(j=0; j<4; j++){ gsl_matrix_set(m1, i, j, rand() % 10); } } for(i=0; i<10; i++){ for(j=0; j<4; j++){ gsl_matrix_set(m2, i, j, rand() % 10); } } printf("m1 before matmul:\n"); for (i = 0; i < 10; i++){ for (j = 0; j < 4; j++){ printf ("%g ", gsl_matrix_get (m1, i, j)); } printf("\n"); } gsl_matrix * result = gsl_matrix_alloc(4, 4); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, m1, m2, 0.0, result); printf("m1 after matmul:\n"); for (i = 0; i < 10; i++){ for (j = 0; j < 4; j++){ printf ("%g ", gsl_matrix_get (m1, i, j)); } printf("\n"); } printf("matmul result:\n"); for (i = 0; i < 4; i++){ for (j = 0; j < 4; j++){ printf ("%g ", gsl_matrix_get (result, i, j)); } printf("\n"); } // gsl_matrix_fprintf(stdout, result, "%g"); gsl_matrix_free(m1); gsl_matrix_free(m2); gsl_matrix_free(result); } void test_mat_inverse(){ int i, j; double m1_data[] = {4, 7, 2, 6}; gsl_matrix_view m1 = gsl_matrix_view_array(m1_data, 2, 2); int s; gsl_permutation * p1 = gsl_permutation_alloc(2); gsl_matrix * m1_inv = gsl_matrix_alloc(2, 2); gsl_linalg_LU_decomp(&m1.matrix, p1, &s); gsl_linalg_LU_invert(&m1.matrix, p1, m1_inv); printf("Inverse of 2x2 matrix:\n"); for (i = 0; i < 2; i++){ for (j = 0; j < 2; j++){ printf ("%g ", gsl_matrix_get (m1_inv, i, j)); } printf("\n"); } double m2_data[] = {7, 2, 1, 0, 3, -1, -3, 4, -2}; gsl_matrix_view m2 = gsl_matrix_view_array(m2_data, 3, 3); gsl_permutation * p2 = gsl_permutation_alloc(3); gsl_matrix * m2_inv = gsl_matrix_alloc(3, 3); gsl_linalg_LU_decomp(&m2.matrix, p2, &s); gsl_linalg_LU_invert(&m2.matrix, p2, m2_inv); printf("Inverse of 3x3 matrix:\n"); for (i = 0; i < 3; i++){ for (j = 0; j < 3; j++){ printf ("%g ", gsl_matrix_get (m2_inv, i, j)); } printf("\n"); } double m3_data[] = {6, 4, 2, 8, 1, 3, 5, 7, 2, 3, 5, 6, 4, 2, 6, 3}; gsl_matrix_view m3 = gsl_matrix_view_array(m3_data, 4, 4); gsl_permutation * p3 = gsl_permutation_alloc(4); gsl_matrix * m3_inv = gsl_matrix_alloc(4, 4); gsl_linalg_LU_decomp(&m3.matrix, p3, &s); gsl_linalg_LU_invert(&m3.matrix, p3, m3_inv); printf("Inverse of 4x4 matrix:\n"); for (i = 0; i < 4; i++){ for (j = 0; j < 4; j++){ printf ("%g ", gsl_matrix_get (m3_inv, i, j)); } printf("\n"); } // gsl_matrix_fprintf(stdout, m3_inv, "%g"); } int main(){ test_matmul(); //test_mat_inverse(); }
{ "alphanum_fraction": 0.5003103662, "avg_line_length": 26.6280991736, "ext": "c", "hexsha": "41dbc8d1ceeed59b67af4feb8a53d06d0de4af21", "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": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexbstl/ffp_minvar", "max_forks_repo_path": "test/test_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "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": "alexbstl/ffp_minvar", "max_issues_repo_path": "test/test_gsl.c", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexbstl/ffp_minvar", "max_stars_repo_path": "test/test_gsl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1106, "size": 3222 }
/* rng/fishman2x.c * * 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. */ /* * This generator is taken from * * Donald E. Knuth * The Art of Computer Programming * Volume 2 * Third Edition * Addison-Wesley * Page 108 * * It is called "Fishman - L'Ecuyer" * * This implementation copyright (C) 2001 Carlo Perassi * and (C) 2003 Heiko Bauke. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> /* Fishman */ #define AAA_F 48271UL #define MMM_F 0x7fffffffUL /* 2 ^ 31 - 1 */ #define QQQ_F 44488UL #define RRR_F 3399UL /* L'Ecuyer */ #define AAA_L 40692UL #define MMM_L 0x7fffff07UL /* 2 ^ 31 - 249 */ #define QQQ_L 52774UL #define RRR_L 3791UL static inline unsigned long int ran_get (void *vstate); static double ran_get_double (void *vstate); static void ran_set (void *state, unsigned long int s); typedef struct { unsigned long int x; unsigned long int y; unsigned long int z; } ran_state_t; static inline unsigned long int ran_get (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; long int y, r; r = RRR_F * (state->x / QQQ_F); y = AAA_F * (state->x % QQQ_F) - r; if (y < 0) y += MMM_F; state->x = y; r = RRR_L * (state->y / QQQ_L); y = AAA_L * (state->y % QQQ_L) - r; if (y < 0) y += MMM_L; state->y = y; state->z = (state->x > state->y) ? (state->x - state->y) : MMM_F + state->x - state->y; return state->z; } static double ran_get_double (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; return ran_get (state) / 2147483647.0; } static void ran_set (void *vstate, unsigned long int s) { ran_state_t *state = (ran_state_t *) vstate; if ((s % MMM_F) == 0 || (s % MMM_L) == 0) s = 1; /* default seed is 1 */ state->x = s % MMM_F; state->y = s % MMM_L; state->z = (state->x > state->y) ? (state->x - state->y) : MMM_F + state->x - state->y; return; } static const gsl_rng_type ran_type = { "fishman2x", /* name */ MMM_F - 1, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (ran_state_t), &ran_set, &ran_get, &ran_get_double }; const gsl_rng_type *gsl_rng_fishman2x = &ran_type;
{ "alphanum_fraction": 0.6380919461, "avg_line_length": 23.7131147541, "ext": "c", "hexsha": "afe0c2794ad603fe1ef18e0cdeb5453a93ff5ddc", "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/rng/fishman2x.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/rng/fishman2x.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/rng/fishman2x.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": 2893 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <mpfr.h> #include <petsc.h> #include "../ellipsoid/ellipsoid.h" #include "../ellipsoid/ellSolv.h" #include "../constants.h" #include "testFunctions.h" #undef __FUNCT__ #define __FUNCT__ "main" PetscErrorCode main(int argc, char **argv) { PetscErrorCode ierr; EllipsoidalSystem e; PetscInt prec = 64; PetscReal a = 3.0; PetscReal b = 2.0; PetscReal c = 1.0; double doubleEnp; mpfr_t x; mpfr_t mpfrEnp; PetscFunctionBeginUser; ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr); ierr = PetscLogDefaultBegin();CHKERRQ(ierr); mpfr_inits(mpfrEnp, x, NULL); ierr = initEllipsoidalSystem(&e, a, b, c, prec);CHKERRQ(ierr); mpfr_set_d(x, 1.0, MPFR_RNDN); //calculate with double ierr = calcLame(&e, 3, 4, 1.0, 1, 1, &doubleEnp); //calculate with high precision ierr = CalcLameMPFR(&e, 3, 4, x, 1, 1, &mpfrEnp); printf("Enp(double): %18.18f\n", doubleEnp); printf("Enp(mpfr): %18.18f\n", mpfr_get_d(mpfrEnp, MPFR_RNDN)); mpfr_clears(mpfrEnp, x, NULL); ierr = PetscFinalize();CHKERRQ(ierr); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.676369863, "avg_line_length": 22.4615384615, "ext": "c", "hexsha": "68941ae944984d2103b05f5eade6ccb890f8b914", "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/examples/ex2.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/examples/ex2.c", "max_line_length": 67, "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/examples/ex2.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": 398, "size": 1168 }
/* $Header$ */ /* ncks -- netCDF Kitchen Sink */ /* Purpose: Extract (subsets of) variables from a netCDF file Print them to screen, copy them to another file, or regrid them Since 2015 ncks has also been the back-end to the ncremap regridder, meaning that ncks implements the regridder API and functionality, though all of that is a segregable component of ncks. The regridder is really just an API and that ncks implements */ /* Copyright (C) 1995--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. 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 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* URL: https://github.com/nco/nco/tree/master/src/nco/ncks.c Usage: ncks ~/nco/data/in.nc ncks -v one ~/nco/data/in.nc ncks ~/nco/data/in.nc ~/foo.nc ncks -O -4 ~/nco/data/in.nc ~/foo.nc ncks -v one ~/nco/data/in.nc ~/foo.nc ncks -p /ZENDER/tmp -l /data/zender/tmp h0001.nc ~/foo.nc ncks -s "%+16.10f\n" -H -C -v three_dmn_var ~/nco/data/in.nc ncks -H -v fl_nm,fl_nm_arr ~/nco/data/in.nc ncks -H -C -u -d wvl,'0.4 micron','0.7 micron' -v wvl ~/nco/data/in.nc ncks -H -d fl_dim,1 -d char_dim,6,12 -v fl_nm,fl_nm_arr ~/nco/data/in.nc ncks -H -m -v char_var_nul,char_var_space,char_var_multinul ~/nco/data/in.nc ncks -H -C -v three_dmn_rec_var -d time,,,2 ~/nco/data/in.nc ncks -H -C -v lon -d lon,3,1 ~/nco/data/in.nc ncks -M -p http://thredds-test.ucar.edu/thredds/dodsC/testdods in.nc ncks -O -v one -p http://thredds-testa.ucar.edu/thredds/dodsC/testdods in.nc ~/foo.nc ncks -O -G foo ~/nco/data/in.nc ~/foo.nc ncks -O -G :-5 -v v7 ~/nco/data/in_grp.nc ~/foo.nc ncks -O -G level3name:-5 -v v7 ~/nco/data/in_grp.nc ~/foo.nc ncks -O -v time ~/in_grp.nc ~/foo.nc ncks -O --sysconf ~/in_grp.nc ~/foo.nc ncks -C --xml_spr_chr=', ' -v two_dmn_rec_var_sng ~/nco/data/in.nc ncks --cdl -v one_dmn_rec_var ~/nco/data/in.nc ncks --jsn -C -v one_dmn_rec_var ~/nco/data/in.nc ncks --jsn -C -m -v one_dmn_rec_var ~/nco/data/in_grp.nc ncks -O -4 --ppc ppc_dbl=1 --ppc ppc_flt,ppc_big=4 ~/nco/data/in.nc ~/foo.nc ncks -O --ppc ppc_dbl=1 --ppc '/g1/ppc.?',/g1/g1g1/ppc_dbl=4 ~/nco/data/in_grp.nc ~/foo.nc ncks -O -m -M -v Snow_Cover_Monthly_CMG ${DATA}/hdf/MOD10CM.A2007001.005.2007108111758.hdf */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <assert.h> /* assert() */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* atof, atoi, malloc, getopt */ #include <string.h> /* strcmp() */ #include <sys/stat.h> /* stat() */ #include <time.h> /* machine time */ #ifndef _MSC_VER # include <unistd.h> /* POSIX stuff */ #endif #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ #ifdef I18N # include <langinfo.h> /* nl_langinfo() */ # include <libintl.h> /* Internationalization i18n */ # include <locale.h> /* Locale setlocale() */ # define _(sng) gettext (sng) # define gettext_noop(sng) (sng) # define N_(sng) gettext_noop(sng) #endif /* I18N */ /* Supply stub gettext() function in case i18n failed */ #ifndef _LIBINTL_H # define gettext(foo) foo #endif /* _LIBINTL_H */ /* 3rd party vendors */ #include <netcdf.h> /* netCDF definitions and C library */ #ifdef ENABLE_MPI # include <mpi.h> /* MPI definitions */ # include <netcdf_par.h> /* Parallel netCDF definitions */ # include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ #ifdef ENABLE_GSL #include <gsl/gsl_errno.h> #endif /* Personal headers */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ #include "nco.h" int main(int argc,char **argv) { char **fl_lst_abb=NULL; /* Option a */ char **fl_lst_in; char **gaa_arg=NULL; /* [sng] Global attribute arguments */ char **grp_lst_in=NULL; char **rgr_arg=NULL; /* [sng] Regridding arguments */ char **trr_arg=NULL; /* [sng] Terraref arguments */ char **var_lst_in=NULL; char **xtn_lst_in=NULL; /* [sng] Extensive variables */ char *aux_arg[NC_MAX_DIMS]; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *dlm_sng=NULL; char *fl_bnr=NULL; /* [sng] Unformatted binary output file */ char *fl_in=NULL; char *fl_in_dpl=NULL; /* [sng] Duplicate of fl_in */ char *fl_in_stub=NULL; /* [sng] Filename component of fl_in */ char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL_CEWI; char *fl_prn=NULL; /* [sng] Formatted text output file */ char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *flt_sng=NULL; /* [sng] Filter string */ char *fmt_val=NULL; /* [sng] Format string for variable values */ char *lmt_arg[NC_MAX_DIMS]; char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *ppc_arg[NC_MAX_VARS]; /* [sng] PPC arguments */ char *rec_dmn_nm=NULL; /* [sng] Record dimension name */ char *rec_dmn_nm_fix=NULL; /* [sng] Record dimension name (Original input name without _fix prefix) */ char *rgr_in=NULL; /* [sng] File containing fields to be regridded */ char *rgr_grd_src=NULL; /* [sng] File containing input grid */ char *rgr_grd_dst=NULL; /* [sng] File containing destination grid */ char *rgr_hrz=NULL; /* [sng] File containing horizontal coordinate grid */ char *rgr_map=NULL; /* [sng] File containing mapping weights from source to destination grid */ char *rgr_out=NULL; /* [sng] File containing regridded fields */ char *rgr_var=NULL; /* [sng] Variable for special regridding treatment */ char *rgr_vrt=NULL; /* [sng] File containing vertical coordinate grid */ char *smr_fl_sz_sng=NULL; /* [sng] String describing estimated file size */ char *smr_sng=NULL; /* [sng] File summary string */ char *smr_xtn_sng=NULL; /* [sng] File extended summary string */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ char *spr_chr=NULL; /* [sng] Separator for XML character types */ char *spr_nmr=NULL; /* [sng] Separator for XML numeric types */ char *trr_in=NULL; /* [sng] File containing raw Terraref imagery */ char *trr_wxy=NULL; /* [sng] Terraref dimension sizes */ char trv_pth[]="/"; /* [sng] Root path of traversal tree */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567aABb:CcD:d:FG:g:HhL:l:MmOo:Pp:qQrRs:t:uVv:X:xz-:"; cnk_sct cnk; /* [sct] Chunking structure */ #if defined(__cplusplus) || defined(PGI_CC) ddra_info_sct ddra_info; ddra_info.flg_ddra=False; #else /* !__cplusplus */ ddra_info_sct ddra_info={.flg_ddra=False}; #endif /* !__cplusplus */ double wgt_vld_thr=NC_MIN_DOUBLE; /* [frc] Weight threshold for valid destination value */ extern char *optarg; extern int optind; FILE *fp_bnr=NULL; /* [fl] Unformatted binary output file handle */ FILE *fp_prn=NULL; /* [fl] Formatted text output file handle */ gpe_sct *gpe=NULL; /* [sng] Group Path Editing (GPE) structure */ int *in_id_arr; /* [id] netCDF file IDs used by OpenMP code */ int JSN_ATT_FMT=0; /* [enm] JSON format for netCDF attributes: 0 (no object, only data), 1 (data only for string, char, int, and floating-point types, otherwise object), 2 (always object) */ int JSN_VAR_FMT=2; /* [flg] JSON format for netCDF variables: 0 (no type except for user-defined types), 1 (type for non-default types), 2 (always type) */ nco_bool JSN_DATA_BRK=True; /* [flg] JSON format for netCDF variables: 0 (no brackets), 1 (bracket inner dimensions of multi-dimensional data) */ int abb_arg_nbr=0; int att_glb_nbr; int att_grp_nbr; int att_var_nbr; int aux_nbr=0; /* [nbr] Number of auxiliary coordinate hyperslabs specified */ int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int dmn_nbr_fl; int dmn_rec_fl; int dt_fmt=fmt_dt_nil; int fl_in_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Input file format */ int fl_nbr=0; int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int grp_dpt_fl; /* [nbr] Maximum group depth (root = 0) */ int grp_lst_in_nbr=0; /* [nbr] Number of groups explicitly specified by user */ int grp_nbr_fl; int idx; int in_id; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int opt; int ppc_nbr=0; /* [nbr] Number of PPC arguments */ int rgr_nbr=0; /* [nbr] Number of regridding arguments */ int trr_nbr=0; /* [nbr] Number of TERRAREF arguments */ int rcd=NC_NOERR; /* [rcd] Return code */ int srt_mth=0; /* [enm] Sort method [0=ascending, 1=descending] */ int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; int var_nbr_fl; int var_udt_fl; int xtn_nbr=0; /* [nbr] Number of extensive variables */ int xtr_nbr=0; /* [nbr] xtr_nbr will not otherwise be set for -c with no -v */ md5_sct *md5=NULL; /* [sct] MD5 configuration */ nco_bool ALPHABETIZE_OUTPUT=True; /* Option a */ nco_bool CHK_MAP=False; /* [flg] Check map-file quality */ nco_bool CHK_NAN=False; /* [flg] Check for NaNs */ nco_bool CPY_GRP_METADATA; /* [flg] Copy group metadata (attributes) */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option x */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool EXTRACT_CLL_MSR=True; /* [flg] Extract cell_measures variables */ nco_bool EXTRACT_FRM_TRM=True; /* [flg] Extract formula_terms variables */ nco_bool FL_RTR_RMT_LCN; nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_NOCLOBBER=False; /* Option no-clobber */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool GRP_VAR_UNN=False; /* [flg] Select union of specified groups and variables */ nco_bool GRP_XTR_VAR_XCL=False; /* [flg] Extract matching groups, exclude matching variables */ nco_bool HAVE_LIMITS=False; /* [flg] Are there user limits? (-d) */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool LST_RNK_GE2=False; /* [flg] Print extraction list of rank >= 2 variables */ nco_bool LST_XTR=False; /* [flg] Print extraction list */ nco_bool MSA_USR_RDR=False; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ nco_bool PRN_CDL=False; /* [flg] Print CDL */ nco_bool PRN_HDN=False; /* [flg] Print hidden attributes */ nco_bool PRN_UDT=False; /* [flg] Print non-atomic variables */ nco_bool PRN_SRM=False; /* [flg] Print ncStream */ nco_bool PRN_JSN=False; /* [flg] Print JSON */ nco_bool PRN_TRD=False; /* [flg] Print traditional */ nco_bool PRN_XML=False; /* [flg] Print XML (NcML) */ nco_bool PRN_XML_LOCATION=True; /* [flg] Print XML location tag */ nco_bool PRN_DMN_IDX_CRD_VAL=True; /* [flg] Print leading dimension/coordinate indices/values Option Q */ nco_bool PRN_DMN_UNITS=True; /* [flg] Print dimensional units Option u */ nco_bool PRN_DMN_VAR_NM=True; /* [flg] Print dimension/variable names */ nco_bool PRN_DMN_UNITS_TGL=False; /* [flg] Toggle print dimensional units Option u */ nco_bool PRN_GLB_METADATA=False; /* [flg] Print global metadata */ nco_bool PRN_GLB_METADATA_TGL=False; /* [flg] Toggle print global metadata Option M */ nco_bool PRN_MSS_VAL_BLANK=True; /* [flg] Print missing values as blanks */ nco_bool PRN_QUENCH=False; /* [flg] Quench (turn-off) all printing to screen */ nco_bool PRN_VAR_DATA=False; /* [flg] Print variable data */ nco_bool PRN_VAR_DATA_TGL=False; /* [flg] Toggle print variable data Option H */ nco_bool PRN_VAR_METADATA=False; /* [flg] Print variable metadata */ nco_bool PRN_VAR_METADATA_TGL=False; /* [flg] Toggle print variable metadata Option m */ nco_bool PRN_CLN_LGB=False; /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ nco_bool PRN_VRB=False; /* [flg] Print data and metadata by default */ nco_bool RETAIN_ALL_DIMS=False; /* [flg] Retain all dimensions */ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_area_wgt=False; /* [flg] Area-weight map-file statistics */ nco_bool flg_dmm_in=False; /* [flg] Make dummy input file */ nco_bool flg_frac_b_nrm=False; /* [flg] Normalize map-file weights when frac_b >> 1 */ nco_bool flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ nco_bool flg_rgr=False; /* [flg] Regrid */ nco_bool flg_s1d=False; /* [flg] Unpack sparse-1D CLM/ELM variables */ nco_bool flg_trr=False; /* [flg] Terraref */ nco_dmn_dne_t *flg_dne=NULL; /* [lst] Flag to check if input dimension -d "does not exist" */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ trv_tbl_sct *trv_tbl=NULL; /* [lst] Traversal table */ #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Comm mpi_cmm=MPI_COMM_WORLD; /* [prc] Communicator */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"area_wgt",no_argument,0,0}, /* [flg] Area-weight map-file statistics */ {"bld",no_argument,0,0}, /* [sng] Build-engine */ {"build_engine",no_argument,0,0}, /* [sng] Build-engine */ {"calendar",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ {"cln_lgb",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ {"prn_cln_lgb",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ {"prn_lgb",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ {"timestamp",no_argument,0,0}, /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ {"cdl",no_argument,0,0}, /* [flg] Print CDL */ {"cll_msr",no_argument,0,0}, /* [flg] Extract cell_measures variables */ {"cell_measures",no_argument,0,0}, /* [flg] Extract cell_measures variables */ {"no_cll_msr",no_argument,0,0}, /* [flg] Do not extract cell_measures variables */ {"no_cell_measures",no_argument,0,0}, /* [flg] Do not extract cell_measures variables */ {"frm_trm",no_argument,0,0}, /* [flg] Extract formula_terms variables */ {"formula_terms",no_argument,0,0}, /* [flg] Extract formula_terms variables */ {"no_frm_trm",no_argument,0,0}, /* [flg] Do not extract formula_terms variables */ {"no_formula_terms",no_argument,0,0}, /* [flg] Do not extract formula_terms variables */ {"chk_map",no_argument,0,0}, /* [flg] Check map-file quality */ {"check_map",no_argument,0,0}, /* [flg] Check map-file quality */ {"chk_nan",no_argument,0,0}, /* [flg] Check file for NaNs */ {"check_nan",no_argument,0,0}, /* [flg] Check file for NaNs */ {"nan",no_argument,0,0}, /* [flg] Check file for NaNs */ {"NaN",no_argument,0,0}, /* [flg] Check file for NaNs */ {"clean",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"mmr_cln",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"dirty",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"mmr_drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"cmp",no_argument,0,0}, {"compiler",no_argument,0,0}, {"copyright",no_argument,0,0}, {"cpy",no_argument,0,0}, {"dmm_in_mk",no_argument,0,0}, /* [flg] Make dummy input file */ {"fl_dmm",no_argument,0,0}, /* [flg] Make dummy input file */ {"license",no_argument,0,0}, {"hdf4",no_argument,0,0}, /* [flg] Treat file as HDF4 */ {"hdn",no_argument,0,0}, /* [flg] Print hidden attributes */ {"hidden",no_argument,0,0}, /* [flg] Print hidden attributes */ {"help",no_argument,0,0}, {"hlp",no_argument,0,0}, {"hpss_try",no_argument,0,0}, /* [flg] Search HPSS for unfound files */ {"id",no_argument,0,0}, /* [flg] Print normally hidden information, like file, group, and variable IDs */ {"lbr",no_argument,0,0}, {"library",no_argument,0,0}, {"lst_rnk_ge2",no_argument,0,0}, /* [flg] Print extraction list of rank >= 2 variables */ {"lst_xtr",no_argument,0,0}, /* [flg] Print extraction list */ {"frac_b_nrm",no_argument,0,0}, /* [flg] Normalize map-file weights when frac_b >> 1 */ {"md5_dgs",no_argument,0,0}, /* [flg] Perform MD5 digests */ {"md5_digest",no_argument,0,0}, /* [flg] Perform MD5 digests */ {"md5_wrt_att",no_argument,0,0}, /* [flg] Write MD5 digests as attributes */ {"md5_write_attribute",no_argument,0,0}, /* [flg] Write MD5 digests as attributes */ {"mpi_implementation",no_argument,0,0}, {"msa_usr_rdr",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ {"msa_user_order",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ {"no_abc",no_argument,0,0}, {"no-abc",no_argument,0,0}, {"no_alphabetize",no_argument,0,0}, {"no-alphabetize",no_argument,0,0}, {"no_blank",no_argument,0,0}, /* [flg] Print numeric missing values */ {"no-blank",no_argument,0,0}, /* [flg] Print numeric missing values */ {"noblank",no_argument,0,0}, /* [flg] Print numeric missing values */ {"no_clb",no_argument,0,0}, {"noclobber",no_argument,0,0}, {"no-clobber",no_argument,0,0}, {"no_clobber",no_argument,0,0}, {"no_dmn_var_nm",no_argument,0,0}, /* [flg] Omit variable and dimension names and indices but print all values */ {"no_nm_prn",no_argument,0,0}, /* [flg] Omit variable and dimension names and indices but print all values */ {"ntm",no_argument,0,0}, /* [flg] Print non-atomic variables */ {"nonatomic",no_argument,0,0}, /* [flg] Print non-atomic variables */ {"udt",no_argument,0,0}, /* [flg] Print non-atomic variables */ {"user_defined_types",no_argument,0,0}, /* [flg] Print non-atomic variables */ {"rad",no_argument,0,0}, /* [flg] Retain all dimensions */ {"retain_all_dimensions",no_argument,0,0}, /* [flg] Retain all dimensions */ {"orphan_dimensions",no_argument,0,0}, /* [flg] Retain all dimensions */ {"rph_dmn",no_argument,0,0}, /* [flg] Retain all dimensions */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"secret",no_argument,0,0}, {"shh",no_argument,0,0}, {"srm",no_argument,0,0}, /* [flg] Print ncStream */ {"s1d",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */ {"sparse",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */ {"unpack_sparse",no_argument,0,0}, /* [flg] Unpack sparse-1D CLM/ELM variables */ {"sysconf",no_argument,0,0}, /* [flg] Perform sysconf() test */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"intersection",no_argument,0,0}, /* [flg] Select intersection of specified groups and variables */ {"nsx",no_argument,0,0}, /* [flg] Select intersection of specified groups and variables */ {"union",no_argument,0,0}, /* [flg] Select union of specified groups and variables */ {"unn",no_argument,0,0}, /* [flg] Select union of specified groups and variables */ {"grp_xtr_var_xcl",no_argument,0,0}, /* [flg] Extract matching groups, exclude matching variables */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, {"jsn",no_argument,0,0}, /* [flg] Print JSON */ {"json",no_argument,0,0}, /* [flg] Print JSON */ {"trd",no_argument,0,0}, /* [flg] Print traditional */ {"traditional",no_argument,0,0}, /* [flg] Print traditional */ {"w10",no_argument,0,0}, /* [flg] Print JSON */ {"w10n",no_argument,0,0}, /* [flg] Print JSON */ {"xml",no_argument,0,0}, /* [flg] Print XML (NcML) */ {"ncml",no_argument,0,0}, /* [flg] Print XML (NcML) */ {"xml_no_location",no_argument,0,0}, /* [flg] Omit XML location tag */ {"ncml_no_location",no_argument,0,0}, /* [flg] Omit XML location tag */ /* Long options with argument, no short option counterpart */ {"baa",required_argument,0,0}, /* [enm] Bit-Adjustment Algorithm */ {"bit_alg",required_argument,0,0}, /* [enm] Bit-Adjustment Algorithm */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"bsa",required_argument,0,0}, /* [enm] Binary byte-swap algorithm */ {"byte_swap",required_argument,0,0}, /* [enm] Binary byte-swap algorithm */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_csh",required_argument,0,0}, /* [B] Chunk cache size in bytes */ {"chunk_cache",required_argument,0,0}, /* [B] Chunk cache size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"dt_fmt",required_argument,0,0}, /* [enm] Date format for CDL output with --cal */ {"date_format",required_argument,0,0}, /* [enm] Date format for CDL output with --cal */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"fix_rec_dmn",required_argument,0,0}, /* [sng] Fix record dimension */ {"no_rec_dmn",required_argument,0,0}, /* [sng] Fix record dimension */ {"fl_prn",required_argument,0,0}, /* [sng] Formatted text output file */ {"file_print",required_argument,0,0}, /* [sng] Formatted text output file */ {"prn_fl",required_argument,0,0}, /* [sng] Formatted text output file */ {"print_file",required_argument,0,0}, /* [sng] Formatted text output file */ {"ccr",required_argument,0,0}, /* [sng] CCR codec name */ {"cdc",required_argument,0,0}, /* [sng] CCR codec name */ {"codec",required_argument,0,0}, /* [sng] CCR codec name */ {"flt",required_argument,0,0}, /* [sng] Filter string */ {"filter",required_argument,0,0}, /* [sng] Filter string */ {"fmt_val",required_argument,0,0}, /* [sng] Format string for variable values */ {"val_fmt",required_argument,0,0}, /* [sng] Format string for variable values */ {"value_format",required_argument,0,0}, /* [sng] Format string for variable values */ {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"jsn_fmt",required_argument,0,0}, /* [enm] JSON format */ {"jsn_format",required_argument,0,0}, /* [enm] JSON format */ {"json_fmt",required_argument,0,0}, /* [enm] JSON format */ {"json_format",required_argument,0,0}, /* [enm] JSON format */ {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"mk_rec_dmn",required_argument,0,0}, /* [sng] Name of record dimension in output */ {"mk_rec_dim",required_argument,0,0}, /* [sng] Name of record dimension in output */ {"mta_dlm",required_argument,0,0}, /* [sng] Multi-argument delimiter */ {"dlm_mta",required_argument,0,0}, /* [sng] Multi-argument delimiter */ {"ppc",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */ {"precision_preserving_compression",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */ {"quantize",required_argument,0,0}, /* [nbr] Precision-preserving compression, i.e., number of total or decimal significant digits */ {"rgr",required_argument,0,0}, /* [sng] Regridding */ {"regridding",required_argument,0,0}, /* [sng] Regridding */ {"rgr_in",required_argument,0,0}, /* [sng] File containing fields to be regridded */ {"rgr_grd_src",required_argument,0,0}, /* [sng] File containing input grid */ {"grd_src",required_argument,0,0}, /* [sng] File containing input grid */ {"src_grd",required_argument,0,0}, /* [sng] File containing input grid */ {"rgr_grd_dst",required_argument,0,0}, /* [sng] File containing destination grid */ {"dst_grd",required_argument,0,0}, /* [sng] File containing destination grid */ {"grd_dst",required_argument,0,0}, /* [sng] File containing destination grid */ {"rgr_map",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */ {"map_file",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */ {"map_fl",required_argument,0,0}, /* [sng] File containing mapping weights from source to destination grid */ {"rgr_hrz",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */ {"hrz_fl",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */ {"hrz_crd",required_argument,0,0}, /* [sng] File containing horizontal coordinate grid */ {"rgr_rnr",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */ {"rgr_var",required_argument,0,0}, /* I [sng] Variable for special regridding treatment */ {"rgr_vrt",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */ {"vrt_fl",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */ {"vrt_crd",required_argument,0,0}, /* [sng] File containing vertical coordinate grid */ {"rnr_thr",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */ {"renormalize",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */ {"renormalization_threshold",required_argument,0,0}, /* [flg] Renormalize destination values by valid area */ {"trr",required_argument,0,0}, /* [sng] Terraref */ {"terraref",required_argument,0,0}, /* [sng] Terraref */ {"trr_in",required_argument,0,0}, /* [sng] File containing raw Terraref imagery */ {"trr_wxy",required_argument,0,0}, /* [sng] Terraref dimension sizes */ {"tst_udunits",required_argument,0,0}, {"xml_spr_chr",required_argument,0,0}, /* [flg] Separator for XML character types */ {"xml_spr_nmr",required_argument,0,0}, /* [flg] Separator for XML numeric types */ {"xtn_var_lst",required_argument,0,0}, /* [sng] Extensive variables */ {"extensive",required_argument,0,0}, /* [sng] Extensive variables */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"abc",no_argument,0,'a'}, {"alphabetize",no_argument,0,'a'}, {"append",no_argument,0,'A'}, {"apn",no_argument,0,'A'}, {"bnr",required_argument,0,'b'}, {"binary",required_argument,0,'b'}, {"binary-file",required_argument,0,'b'}, {"fl_bnr",required_argument,0,'b'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"data",required_argument,0,'H'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"gpe",required_argument,0,'G'}, /* [sng] Group Path Edit (GPE) */ {"grp",required_argument,0,'g'}, {"group",required_argument,0,'g'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"hieronymus",no_argument,0,'H'}, /* fxm: need better mnemonic for -H */ {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"lcl",required_argument,0,'l'}, {"local",required_argument,0,'l'}, {"metadata",no_argument,0,'m'}, {"mtd_lcl",no_argument,0,'m'}, {"metadata_local",no_argument,0,'m'}, {"Metadata",no_argument,0,'M'}, {"Mtd",no_argument,0,'M'}, {"mtd_glb",no_argument,0,'M'}, {"metadata_global",no_argument,0,'M'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"output",required_argument,0,'o'}, {"fl_out",required_argument,0,'o'}, {"print",required_argument,0,'P'}, {"prn",required_argument,0,'P'}, {"path",required_argument,0,'p'}, {"quench",no_argument,0,'q'}, {"quiet",no_argument,0,'Q'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"spinlock",no_argument,0,'S'}, /* [flg] Suspend with signal handler to facilitate debugging */ {"sng_fmt",required_argument,0,'s'}, {"string",required_argument,0,'s'}, {"thr_nbr",required_argument,0,'t'}, {"threads",required_argument,0,'t'}, {"omp_num_threads",required_argument,0,'t'}, {"units",no_argument,0,'u'}, {"val_var",no_argument,0,'V'}, /* [flg] Print variable values only */ {"variable",required_argument,0,'v'}, {"auxiliary",required_argument,0,'X'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"lbr_rcd",no_argument,0,0}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef _LIBINTL_H setlocale(LC_ALL,""); /* LC_ALL sets all localization tokens to same value */ bindtextdomain("nco","/home/zender/share/locale"); /* ${LOCALEDIR} is e.g., /usr/share/locale */ /* MO files should be in ${LOCALEDIR}/es/LC_MESSAGES */ textdomain("nco"); /* PACKAGE is name of program or library */ #endif /* not _LIBINTL_H */ /* Start timer and save command line */ ddra_info.tmr_flg=nco_tmr_srt; rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); ddra_info.tmr_flg=nco_tmr_mtd; cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* MPI I/O: Either Parallel netCDF (PnetCDF) or HDF5-based export NETCDF_ROOT=/usr/local/parallel;export NETCDF_INC=/usr/local/parallel/include;export NETCDF_LIB=/usr/local/parallel/lib;export NETCDF4_ROOT=/usr/local/parallel; cd ~/nco/bld;make MPI=Y;cd - LD_LIBRARY_PATH=/usr/local/parallel/lib\:${LD_LIBRARY_PATH} ldd `which ncks` ncks -O -5 ~/nco/data/in.nc ~/foo.nc # PnetCDF mpiexec -n 1 ncks -O -4 ~/nco/data/in.nc ~/foo.nc # HDF5 od -An -c -N4 ~/foo.nc */ #ifdef ENABLE_MPI /* MPI Initialization */ if(False) (void)fprintf(stdout,gettext("%s: WARNING Compiled with MPI\n"),nco_prg_nm); MPI_Init(&argc,&argv); MPI_Comm_size(mpi_cmm,&prc_nbr); MPI_Comm_rank(mpi_cmm,&prc_rnk); #endif /* !ENABLE_MPI */ /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"baa") || !strcmp(opt_crr,"bit_alg")){ nco_baa_cnv=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif baa */ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif bfr_sz */ if(!strcmp(opt_crr,"bsa") || !strcmp(opt_crr,"byte_swap")){ nco_bnr_cnv=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif bnr */ if(!strcmp(opt_crr,"bld") || !strcmp(opt_crr,"build_engine")){ const char bld_ngn[]=TKN2SNG(NCO_BUILDENGINE); // [sng] Build-engine (void)fprintf(stdout,"%s\n",bld_ngn); nco_exit(EXIT_SUCCESS); } /* endif "bld" */ if(!strcmp(opt_crr,"dt_fmt") || !strcmp(opt_crr,"date_format")){ dt_fmt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); } /* !dt_fmt */ if(!strcmp(opt_crr,"calendar") || !strcmp(opt_crr,"cln_lgb") || !strcmp(opt_crr,"prn_cln_lgb") || !strcmp(opt_crr,"prn_lgb") || !strcmp(opt_crr,"timestamp")) PRN_CLN_LGB=True; /* [flg] Print UDUnits-formatted calendar dates/times human-legibly */ if(!strcmp(opt_crr,"chk_map") || !strcmp(opt_crr,"check_map")) CHK_MAP=True; /* [flg] Check map-file quality */ if(!strcmp(opt_crr,"chk_nan") || !strcmp(opt_crr,"check_nan") || !strcmp(opt_crr,"nan") || !strcmp(opt_crr,"NaN")) CHK_NAN=True; /* [flg] Check for NaNs */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_csh") || !strcmp(opt_crr,"chunk_cache")){ cnk_csh_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_csh */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk_dmn */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_scl */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk_map */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk_plc */ if(!strcmp(opt_crr,"cll_msr") || !strcmp(opt_crr,"cell_measures")) EXTRACT_CLL_MSR=True; /* [flg] Extract cell_measures variables */ if(!strcmp(opt_crr,"no_cll_msr") || !strcmp(opt_crr,"no_cell_measures")) EXTRACT_CLL_MSR=False; /* [flg] Do not extract cell_measures variables */ if(!strcmp(opt_crr,"frm_trm") || !strcmp(opt_crr,"formula_terms")) EXTRACT_FRM_TRM=True; /* [flg] Extract formula_terms variables */ if(!strcmp(opt_crr,"no_frm_trm") || !strcmp(opt_crr,"no_formula_terms")) EXTRACT_FRM_TRM=False; /* [flg] Do not extract formula_terms variables */ if(!strcmp(opt_crr,"cmp") || !strcmp(opt_crr,"compiler")){ (void)fprintf(stdout,"%s\n",nco_cmp_get()); nco_exit(EXIT_SUCCESS); } /* endif "cmp" */ if(!strcmp(opt_crr,"cpy") || !strcmp(opt_crr,"copyright") || !strcmp(opt_crr,"license")){ (void)nco_cpy_prn(); nco_exit(EXIT_SUCCESS); } /* endif "copyright" */ if(!strcmp(opt_crr,"cdl")) PRN_CDL=True; /* [flg] Print CDL */ if(!strcmp(opt_crr,"trd") || !strcmp(opt_crr,"traditional")) PRN_TRD=True; /* [flg] Print traditional */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"dmm_in_mk") || !strcmp(opt_crr,"fl_dmm")) flg_dmm_in=True; /* [flg] Make dummy input file */ if(!strcmp(opt_crr,"fix_rec_dmn") || !strcmp(opt_crr,"no_rec_dmn")){ const char fix_pfx[]="fix_"; /* [sng] Prefix string to fix dimension */ rec_dmn_nm=(char *)nco_malloc((strlen(fix_pfx)+strlen(optarg)+1L)*sizeof(char)); rec_dmn_nm=strcpy(rec_dmn_nm,fix_pfx); rec_dmn_nm=strcat(rec_dmn_nm,optarg); rec_dmn_nm_fix=strdup(optarg); } /* !fix_rec_dmn */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"fl_prn") || !strcmp(opt_crr,"file_print") || !strcmp(opt_crr,"prn_fl") || !strcmp(opt_crr,"print_file")) fl_prn=(char *)strdup(optarg); if(!strcmp(opt_crr,"flt") || !strcmp(opt_crr,"filter")){ flt_sng=(char *)strdup(optarg); /* [fnc] Parse filter string and exit */ if(flt_sng) nco_flt_prs(flt_sng); } /* !flt */ if(!strcmp(opt_crr,"ccr") || !strcmp(opt_crr,"cdc") || !strcmp(opt_crr,"codec")){ nco_flt_glb=nco_flt_sng2enm(optarg); (void)fprintf(stdout,"%s: INFO %s reports user-specified filter string translates to CCR string \"%s\"<.\n",nco_prg_nm,nco_prg_nm,nco_flt_enm2sng((nco_flt_typ_enm)nco_flt_glb_get())); nco_exit(EXIT_SUCCESS); } /* !ccr */ if(!strcmp(opt_crr,"fmt_val") || !strcmp(opt_crr,"val_fmt") || !strcmp(opt_crr,"value_format")) fmt_val=(char *)strdup(optarg); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* !gaa */ if(!strcmp(opt_crr,"hdf4")) nco_fmt_xtn=nco_fmt_xtn_hdf4; /* [enm] Treat file as HDF4 */ if(!strcmp(opt_crr,"hdn") || !strcmp(opt_crr,"hidden")) PRN_HDN=True; /* [flg] Print hidden attributes */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"help") || !strcmp(opt_crr,"hlp")){ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); } /* endif "help" */ if(!strcmp(opt_crr,"hpss_try")) HPSS_TRY=True; /* [flg] Search HPSS for unfound files */ if(!strcmp(opt_crr,"lbr") || !strcmp(opt_crr,"library")){ (void)nco_lbr_vrs_prn(); nco_exit(EXIT_SUCCESS); } /* endif "lbr" */ if(!strcmp(opt_crr,"lbr_rcd")) nco_exit_lbr_rcd(); if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"lst_rnk_ge2") || !strcmp(opt_crr,"rank_ge2")) LST_RNK_GE2=True; /* [flg] Print extraction list of rank >= 2 variables */ if(!strcmp(opt_crr,"lst_xtr") || !strcmp(opt_crr,"xtr_lst")) LST_XTR=True; /* [flg] Print extraction list */ if(!strcmp(opt_crr,"mk_rec_dmn") || !strcmp(opt_crr,"mk_rec_dim")){ if(strchr(optarg,',')){ (void)fprintf(stdout,"%s: ERROR record dimension name %s contains a comma and appears to be a list\n",nco_prg_nm_get(),optarg); (void)fprintf(stdout,"%s: HINT --mk_rec_dmn currently accepts only one dimension name as an argument (relaxing this limit is TODO nco1129, let us know if this is important to you). To change multiple dimensions into record dimensions, run ncks multiple times and change one dimension each time. Be sure the output file format is netCDF4.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* endif */ rec_dmn_nm=strdup(optarg); } /* !mk_rec_dmn */ if(!strcmp(opt_crr,"mpi_implementation")){ (void)fprintf(stdout,"%s\n",nco_mpi_get()); nco_exit(EXIT_SUCCESS); } /* endif "mpi" */ if(!strcmp(opt_crr,"md5_dgs") || !strcmp(opt_crr,"md5_digest")){ if(!md5) md5=nco_md5_ini(); md5->dgs=True; if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO Will perform MD5 digests of input and output hyperslabs\n",nco_prg_nm_get()); } /* endif "md5_dgs" */ if(!strcmp(opt_crr,"md5_wrt_att") || !strcmp(opt_crr,"md5_write_attribute")){ if(!md5) md5=nco_md5_ini(); md5->wrt=md5->dgs=True; if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"%s: INFO Will write MD5 digests as attributes\n",nco_prg_nm_get()); } /* endif "md5_wrt_att" */ if(!strcmp(opt_crr,"msa_usr_rdr") || !strcmp(opt_crr,"msa_user_order")) MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ if(!strcmp(opt_crr,"mta_dlm") || !strcmp(opt_crr,"dlm_mta")) nco_mta_dlm_set(optarg); if(!strcmp(opt_crr,"no_abc") || !strcmp(opt_crr,"no-abc") || !strcmp(opt_crr,"no_alphabetize") || !strcmp(opt_crr,"no-alphabetize")) ALPHABETIZE_OUTPUT=False; if(!strcmp(opt_crr,"no_blank") || !strcmp(opt_crr,"no-blank") || !strcmp(opt_crr,"noblank")) PRN_MSS_VAL_BLANK=!PRN_MSS_VAL_BLANK; if(!strcmp(opt_crr,"no_clb") || !strcmp(opt_crr,"no-clobber") || !strcmp(opt_crr,"no_clobber") || !strcmp(opt_crr,"noclobber")) FORCE_NOCLOBBER=!FORCE_NOCLOBBER; if(!strcmp(opt_crr,"no_nm_prn") || !strcmp(opt_crr,"no_dmn_var_nm")) PRN_DMN_VAR_NM=False; /* endif "no_nm_prn" */ if(!strcmp(opt_crr,"ntm") || !strcmp(opt_crr,"nonatomic") || !strcmp(opt_crr,"udt") || !strcmp(opt_crr,"user_defined_types")) PRN_UDT=True; /* [flg] Print non-atomic variables */ if(!strcmp(opt_crr,"ppc") || !strcmp(opt_crr,"precision_preserving_compression") || !strcmp(opt_crr,"quantize")) ppc_arg[ppc_nbr++]=(char *)strdup(optarg); if(!strcmp(opt_crr,"rad") || !strcmp(opt_crr,"retain_all_dimensions") || !strcmp(opt_crr,"orphan_dimensions") || !strcmp(opt_crr,"rph_dmn")) RETAIN_ALL_DIMS=True; if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"area_wgt") || !strcmp(opt_crr,"area_weight")){ flg_area_wgt=True; CHK_MAP=True; } /* !area_wgt */ if(!strcmp(opt_crr,"frac_b_nrm")){ flg_frac_b_nrm=True; CHK_MAP=True; } /* !frac_b_nrm */ if(!strcmp(opt_crr,"rgr") || !strcmp(opt_crr,"regridding")){ flg_rgr=True; rgr_arg=(char **)nco_realloc(rgr_arg,(rgr_nbr+1)*sizeof(char *)); rgr_arg[rgr_nbr++]=(char *)strdup(optarg); } /* endif "rgr" */ if(!strcmp(opt_crr,"rgr_in")) rgr_in=(char *)strdup(optarg); if(!strcmp(opt_crr,"rgr_grd_src") || !strcmp(opt_crr,"grd_src") || !strcmp(opt_crr,"src_grd")) rgr_grd_src=(char *)strdup(optarg); if(!strcmp(opt_crr,"rgr_grd_dst") || !strcmp(opt_crr,"grd_dst") || !strcmp(opt_crr,"dst_grd")) rgr_grd_dst=(char *)strdup(optarg); if(!strcmp(opt_crr,"rgr_map") || !strcmp(opt_crr,"map_file") || !strcmp(opt_crr,"map_fl")){ flg_rgr=True; rgr_map=(char *)strdup(optarg); } /* endif rgr_map */ if(!strcmp(opt_crr,"hrz_fl") || !strcmp(opt_crr,"hrz_crd") || !strcmp(opt_crr,"rgr_hrz")){ flg_s1d=flg_rgr=True; rgr_hrz=(char *)strdup(optarg); } /* !vrt_fl */ if(!strcmp(opt_crr,"vrt_fl") || !strcmp(opt_crr,"vrt_crd") || !strcmp(opt_crr,"rgr_vrt")){ flg_rgr=True; rgr_vrt=(char *)strdup(optarg); } /* !vrt_fl */ if(!strcmp(opt_crr,"rnr_thr") || !strcmp(opt_crr,"rgr_rnr") || !strcmp(opt_crr,"renormalize") || !strcmp(opt_crr,"renormalization_threshold")){ wgt_vld_thr=strtod(optarg,&sng_cnv_rcd); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtod",sng_cnv_rcd); } /* endif rgr_rnr */ if(!strcmp(opt_crr,"rgr_var")){ flg_rgr=True; rgr_var=(char *)strdup(optarg); } /* !rgr_var */ if(!strcmp(opt_crr,"secret") || !strcmp(opt_crr,"scr") || !strcmp(opt_crr,"shh")){ (void)fprintf(stdout,"Hidden/unsupported NCO options:\nBit-Adjustment Alg.\t--baa, --bit_alg\nBuild-engine\t\t--bld, --build_engine\nByte-swap algorithm\t--bsa, --byte_swap\nCompiler used\t\t--cmp, --compiler\nCopyright\t\t--cpy, --copyright, --license\nHidden functions\t--scr, --shh, --secret\nLibrary used\t\t--lbr, --library\nLog level\t\t--log_lvl, --log_level\nList rank >= 2 vars\t--lst_rnk_ge2\nList extracted vars\t--lst_xtr\nMemory clean\t\t--mmr_cln, --cln, --clean\nMemory dirty\t\t--mmr_drt, --drt, --dirty\nMPI implementation\t--mpi_implementation\nNo-clobber files\t--no_clb, --no-clobber\nPseudonym\t\t--pseudonym, -Y (ncra only)\nSpinlock\t\t--spinlock\nStreams\t\t\t--srm\nSysconf\t\t\t--sysconf\nTest UDUnits\t\t--tst_udunits,'units_in','units_out','cln_sng'? \nVersion\t\t\t--vrs, --version\n\n"); nco_exit(EXIT_SUCCESS); } /* endif "shh" */ if(!strcmp(opt_crr,"srm")) PRN_SRM=True; /* [flg] Print ncStream */ if(!strcmp(opt_crr,"s1d") || !strcmp(opt_crr,"sparse") || !strcmp(opt_crr,"unpack_sparse")) flg_s1d=flg_rgr=True; /* [flg] Unpack sparse-1D CLM/ELM variables */ if(!strcmp(opt_crr,"sysconf")){ long maxrss; /* [B] Maximum resident set size */ maxrss=nco_mmr_usg_prn((int)0); maxrss+=0; /* CEWI */ nco_exit(EXIT_SUCCESS); } /* endif "sysconf" */ if(!strcmp(opt_crr,"trr") || !strcmp(opt_crr,"terraref")){ flg_trr=True; trr_arg=(char **)nco_realloc(trr_arg,(trr_nbr+1)*sizeof(char *)); trr_arg[trr_nbr++]=(char *)strdup(optarg); } /* endif "trr" */ if(!strcmp(opt_crr,"trr_in")){trr_in=(char *)strdup(optarg);flg_trr=True;} if(!strcmp(opt_crr,"trr_wxy")){trr_wxy=(char *)strdup(optarg);flg_trr=True;} if(!strcmp(opt_crr,"tst_udunits")){ /* Use this feature with, e.g., ncks --tst_udunits='5 meters',centimeters ~/nco/data/in.nc ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',standard ~/nco/data/in.nc ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',360_day ~/nco/data/in.nc ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',365_day ~/nco/data/in.nc ncks --tst_udunits='0 days since 1918-11-11','days since 1939-09-09',366_day ~/nco/data/in.nc */ char *cp; char **args; double crr_val; #ifndef ENABLE_UDUNITS (void)fprintf(stdout,"%s: Build NCO with UDUnits support to use this option\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); #endif /* !ENABLE_UDUNITS */ cp=strdup(optarg); args=nco_lst_prs_1D(cp,",",&lmt_nbr); nco_cln_clc_dbl_org(args[0],args[1],(lmt_nbr > 2 ? nco_cln_get_cln_typ(args[2]) : cln_nil),&crr_val); (void)fprintf(stdout,"Value+Units in=%s, units out=%s, time-difference (for dates) or value-conversion (for non-dates) = %f\n",args[0],args[1],crr_val); if(cp) cp=(char *)nco_free(cp); nco_exit(EXIT_SUCCESS); } /* endif "tst_udunits" */ if(!strcmp(opt_crr,"unn") || !strcmp(opt_crr,"union")) GRP_VAR_UNN=True; if(!strcmp(opt_crr,"nsx") || !strcmp(opt_crr,"intersection")) GRP_VAR_UNN=False; if(!strcmp(opt_crr,"grp_xtr_var_xcl")){ EXCLUDE_INPUT_LIST=True; GRP_XTR_VAR_XCL=True; } /* endif "grp_xtr_var_xcl" */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"jsn_fmt") || !strcmp(opt_crr,"json_format") || !strcmp(opt_crr,"json_fmt") || !strcmp(opt_crr,"jsn_format")){ PRN_JSN=True; JSN_ATT_FMT=(int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); if(JSN_ATT_FMT >= 4) JSN_DATA_BRK=False; /* [flg] Print JSON with bracket data */ JSN_ATT_FMT%=4; /* 20161221: Valid values are 0,1,2 */ if(JSN_ATT_FMT == 3) JSN_ATT_FMT=2; JSN_VAR_FMT=JSN_ATT_FMT; } /* !jsn_att_fmt */ if(!strcmp(opt_crr,"jsn") || !strcmp(opt_crr,"json") || !strcmp(opt_crr,"w10") || !strcmp(opt_crr,"w10n")) PRN_JSN=True; /* [flg] Print JSON */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; if(!strcmp(opt_crr,"xml") || !strcmp(opt_crr,"ncml")) PRN_XML=True; /* [flg] Print XML (NcML) */ if(!strcmp(opt_crr,"xml_no_location") || !strcmp(opt_crr,"ncml_no_location")){PRN_XML_LOCATION=False;PRN_XML=True;} /* [flg] Print XML location tag */ if(!strcmp(opt_crr,"xml_spr_chr")){spr_chr=(char *)strdup(optarg);PRN_XML=True;} /* [flg] Separator for XML character types */ if(!strcmp(opt_crr,"xml_spr_nmr")){spr_nmr=(char *)strdup(optarg);PRN_XML=True;} /* [flg] Separator for XML numeric types */ if(!strcmp(opt_crr,"xtn_var_lst") || !strcmp(opt_crr,"extensive")){ /* Extensive variables */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); xtn_lst_in=nco_lst_prs_2D(optarg_lcl,",",&xtn_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); } /* !xtn */ } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'a': /* Do not alphabetize output */ ALPHABETIZE_OUTPUT=False; (void)fprintf(stderr,"%s: WARNING the ncks '-a', '--abc', and '--alphabetize' switches are misleadingly named because they turn-off the default alphabetization. These switches are deprecated as of NCO 4.7.1 and will soon be deleted. Instead, please use the new long options --no_abc, --no-abc, --no_alphabetize, or --no-alphabetize, all of which turn-off the default alphabetization.\n",nco_prg_nm_get()); break; case 'b': /* Set file for binary output */ fl_bnr=(char *)strdup(optarg); break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=!EXTRACT_ASSOCIATED_COORDINATES; break; case 'c': /* Add all coordinates to extraction list? */ EXTRACT_ALL_COORDINATES=True; break; case 'D': /* Debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; HAVE_LIMITS=True; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'G': /* Apply Group Path Editing (GPE) to output group */ gpe=nco_gpe_prs_arg(optarg); /* fl_out_fmt=NC_FORMAT_NETCDF4; */ break; case 'g': /* Copy group argument for later processing */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); grp_lst_in=nco_lst_prs_2D(optarg_lcl,",",&grp_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); break; case 'H': /* Toggle printing data to screen */ PRN_VAR_DATA_TGL=True; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'm': /* Toggle printing variable metadata to screen */ PRN_VAR_METADATA_TGL=True; break; case 'M': /* Toggle printing global metadata to screen */ PRN_GLB_METADATA_TGL=True; break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'P': /* Print data to screen, maximal verbosity */ PRN_VRB=True; EXTRACT_ASSOCIATED_COORDINATES=!EXTRACT_ASSOCIATED_COORDINATES; break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'q': /* [flg] Quench (turn-off) all printing to screen */ PRN_QUENCH=True; /* [flg] Quench (turn-off) all printing to screen */ break; case 'Q': /* Turn off printing of dimension indices and coordinate values */ PRN_DMN_IDX_CRD_VAL=!PRN_DMN_IDX_CRD_VAL; break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(stdout,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 's': /* User-specified delimiter string for traditional printed output */ PRN_TRD=True; /* [flg] Print traditional */ dlm_sng=(char *)strdup(optarg); break; case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'u': /* Toggle printing dimensional units */ PRN_DMN_UNITS_TGL=True; break; case 'V': /* Print variable values only (same as -Q --no_nm_prn) */ PRN_DMN_IDX_CRD_VAL=False; PRN_DMN_VAR_NM=False; break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr=var_lst_in_nbr; break; case 'X': /* Copy auxiliary coordinate argument for later processing */ aux_arg[aux_nbr]=(char *)strdup(optarg); aux_nbr++; MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ HAVE_LIMITS=True; break; case 'x': /* Exclude rather than extract groups and variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case 'z': /* Print absolute path of all input variables then exit */ trv_tbl_prn(trv_tbl); goto close_and_free; break; case '?': /* Question mark means unrecognized option, print proper usage then EXIT_FAILURE */ (void)fprintf(stdout,"%s: ERROR in command-line syntax/options. Missing or unrecognized option. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ /* 20170107: Unlike all other operators, ncks may benefit from setting chunk cache when input file (not output file) is netCDF4 because there is anecdotal evidence that ncdump netCDF4 print speed may be improved by cache adjustments. We cannot verify whether input, output, or both file formats are netCDF4 because nco_set_chunk_cache() must be called before opening file(s). Setting this for netCDF3 library is harmless and calls a no-op stub function */ /* Set/report global chunk cache */ rcd+=nco_cnk_csh_ini(cnk_csh_byt); #ifdef _LANGINFO_H /* Internationalization i18n Linux Journal 200211 p. 57--59 http://www.linuxjournal.com/article/6176 Fedora: http://fedoraproject.org/wiki/How_to_do_I18N_through_gettext cd ~/nco/bld;make I18N=Y cd ~/nco/bld;xgettext --default-domain=nco --join-existing -o ../po/nco.pot ../src/nco/ncks.c ../src/nco/ncra.c for LL in fr es; do mkdir -p ~/share/locale/${LL}/LC_MESSAGES msgfmt ~/nco/po/${LL}/nco.po -o ~/nco/po/${LL}/nco.mo /bin/cp ~/nco/po/${LL}/nco.mo ~/share/locale/${LL}/LC_MESSAGES # sudo /bin/cp ~/nco/po/${LL}/nco.mo /usr/share/locale/${LL}/LC_MESSAGES done export LOCALEDIR=${HOME}/share/locale LC_ALL=en ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc LANG=en_GB.utf8 LANGUAGE=en_GB:en:fr_FR:fr LC_ALL=en_GB.utf8 ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc LANG=es ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc LANG=fr_FR.utf8 LANGUAGE=fr_FR:fr:en_GB:en LC_ALL=fr_FR.utf8 ncks -D 1 -O ~/nco/data/in.nc ~/foo.nc */ if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stdout,gettext("%s: I18N Current charset = %s\n"),nco_prg_nm,nl_langinfo(CODESET)); if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stdout,gettext("%s: I18N This text may appear in a foreign language\n"),nco_prg_nm); #endif /* !_LANGINFO_H */ #if defined(ENABLE_GSL) gsl_set_error_handler_off(); #endif /* !ENABLE_GSL */ /* Initialize traversal table */ (void)trv_tbl_init(&trv_tbl); /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Initialize thread information */ if(flg_rgr) thr_nbr=nco_openmp_ini(thr_nbr); else thr_nbr=nco_openmp_ini((int)1); in_id_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); trv_tbl->thr_nbr=thr_nbr; trv_tbl->in_id_arr=in_id_arr; /* Parse filename */ fl_in=nco_fl_nm_prs(fl_in,0,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); /* Make dummy input file (this step must precede nco_fl_mk_lcl()) */ if(flg_dmm_in) nco_fl_dmm_mk(fl_in); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); fl_in_dpl=strdup(fl_in); #ifdef WIN32 const char sls_chr='\\'; /* [chr] Slash character */ #else /* !WIN32 */ const char sls_chr='/'; /* [chr] Slash character */ #endif /* !WIN32 */ fl_in_stub=strrchr(fl_in_dpl,sls_chr); if(fl_in_stub) fl_in_stub++; else fl_in_stub=fl_in_dpl; /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,in_id_arr+thr_idx); in_id=in_id_arr[0]; /* Construct GTT (Group Traversal Table), check -v and -g input names and create extraction list */ (void)nco_bld_trv_tbl(in_id,trv_pth,lmt_nbr,lmt_arg,aux_nbr,aux_arg,MSA_USR_RDR,FORTRAN_IDX_CNV,grp_lst_in,grp_lst_in_nbr,var_lst_in,xtr_nbr,EXTRACT_ALL_COORDINATES,GRP_VAR_UNN,GRP_XTR_VAR_XCL,EXCLUDE_INPUT_LIST,EXTRACT_ASSOCIATED_COORDINATES,EXTRACT_CLL_MSR,EXTRACT_FRM_TRM,nco_pck_plc_nil,&flg_dne,trv_tbl); if(ALPHABETIZE_OUTPUT) trv_tbl_srt(srt_mth,trv_tbl); /* [fnc] Print extraction list and exit */ if(LST_XTR) nco_xtr_lst(trv_tbl); /* [fnc] Print extraction list of N>=D variables and exit */ if(LST_RNK_GE2) nco_xtr_ND_lst(trv_tbl); /* Were all user-specified dimensions found? */ (void)nco_chk_dmn(lmt_nbr,flg_dne); /* Get number of variables, dimensions, and global attributes in file */ (void)trv_tbl_inq(&att_glb_nbr,&att_grp_nbr,&att_var_nbr,&dmn_nbr_fl,&dmn_rec_fl,&grp_dpt_fl,&grp_nbr_fl,&var_udt_fl,&var_nbr_fl,trv_tbl); /* Make output and input files consanguinous */ (void)nco_inq_format(in_id,&fl_in_fmt); if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt; if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)omp_set_num_threads((int)0); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr) (void)fprintf(stdout,"%s: MPI process rank %d reports %d process%s\n",nco_prg_nm,prc_rnk,prc_nbr,(prc_nbr == 1) ? "" : "es"); /* Roll call */ (void)fprintf(stdout,"%s: MPI process rank %d reports %d process%s\n",nco_prg_nm,prc_rnk,prc_nbr,(prc_nbr == 1) ? "" : "es"); #endif /* !ENABLE_MPI */ /* We now have final list of variables to extract. Phew. */ if(fl_out){ /* Copy everything (all data and metadata) to output file by default */ if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=False; else PRN_VAR_DATA=True; if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=False; else PRN_VAR_METADATA=True; if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=False; else PRN_GLB_METADATA=True; if(FORCE_APPEND){ /* When appending, do not copy global metadata by default */ if(var_lst_in) PRN_GLB_METADATA=False; else PRN_GLB_METADATA=True; if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=!PRN_GLB_METADATA; } /* !FORCE_APPEND */ }else{ /* !fl_out */ /* Only input file is specified, so print it */ if(PRN_VRB || (!PRN_VAR_DATA_TGL && !PRN_VAR_METADATA_TGL && !PRN_GLB_METADATA_TGL)){ /* Verbose printing simply means assume user wants deluxe frills by default */ if(PRN_DMN_UNITS_TGL) PRN_DMN_UNITS=False; else PRN_DMN_UNITS=True; if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=False; else PRN_VAR_DATA=True; if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=False; else PRN_VAR_METADATA=True; /* Assume user wants global metadata unless variable extraction is invoked */ if(var_lst_in == NULL) PRN_GLB_METADATA=True; if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=!PRN_GLB_METADATA; }else{ /* end if PRN_VRB */ /* Default is to print data and metadata to screen if output file is not specified */ if(PRN_DMN_UNITS_TGL) PRN_DMN_UNITS=True; else PRN_DMN_UNITS=False; if(PRN_VAR_DATA_TGL) PRN_VAR_DATA=True; else PRN_VAR_DATA=False; if(PRN_VAR_METADATA_TGL) PRN_VAR_METADATA=True; else PRN_VAR_METADATA=False; if(PRN_GLB_METADATA_TGL) PRN_GLB_METADATA=True; else PRN_GLB_METADATA=False; } /* !PRN_VRB */ /* PRN_QUENCH turns off all printing to screen */ if(PRN_QUENCH) PRN_VAR_DATA=PRN_VAR_METADATA=PRN_GLB_METADATA=False; } /* !fl_out */ if(fl_bnr && !fl_out){ /* Native binary files depend on writing netCDF file to enter generic I/O logic */ (void)fprintf(stdout,"%s: ERROR Native binary files cannot be written unless netCDF output filename also specified.\nHINT: Repeat command with dummy netCDF file specified for output file (e.g., -o foo.nc)\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* endif fl_bnr */ if(flg_rgr && !fl_out){ (void)fprintf(stdout,"%s: ERROR Regridding requested but no output file specified\nHINT: Specify output file with \"-o fl_out\" or as last argument\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* !flg_rgr */ if(gpe){ if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"%s: INFO Group Path Edit (GPE) feature enabled\n",nco_prg_nm_get()); if(fl_out && fl_out_fmt != NC_FORMAT_NETCDF4 && nco_dbg_lvl >= nco_dbg_std) (void)fprintf(stderr,"%s: WARNING Group Path Edit (GPE) requires netCDF4 output format in most cases (except flattening) but user explicitly requested output format = %s. This command will fail if the output file requires netCDF4 features like groups, non-atomic types, or multiple record dimensions. However, it _will_ autoconvert netCDF4 atomic types (e.g., NC_STRING, NC_UBYTE...) to netCDF3 atomic types (e.g., NC_CHAR, NC_SHORT...).\n",nco_prg_nm_get(),nco_fmt_sng(fl_out_fmt)); } /* !gpe */ /* Terraref */ if(flg_trr){ char *trr_out; trr_sct *trr_nfo; trr_out=(char *)strdup(fl_out); trr_nfo=nco_trr_ini(cmd_ln,dfl_lvl,trr_arg,trr_nbr,trr_in,trr_out,trr_wxy); (void)nco_trr_read(trr_nfo); /* Free Terraref structure */ trr_nfo=nco_trr_free(trr_nfo); if(trr_wxy) trr_wxy=(char *)nco_free(trr_wxy); nco_exit_gracefully(); return EXIT_SUCCESS; } /* !Terraref */ if(fl_out){ /* Output file was specified so PRN_ tokens refer to (meta)data copying */ int out_id; /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt; /* Regridding */ if(flg_rgr){ rgr_sct *rgr_nfo; /* Initialize regridding structure */ rgr_in=(char *)strdup(fl_in); rgr_out=(char *)strdup(fl_out); rgr_nfo=nco_rgr_ini(cmd_ln,in_id,rgr_arg,rgr_nbr,rgr_in,rgr_out,rgr_grd_src,rgr_grd_dst,rgr_hrz,rgr_map,rgr_var,rgr_vrt,wgt_vld_thr,xtn_lst_in,xtn_nbr); rgr_nfo->fl_out_fmt=fl_out_fmt; rgr_nfo->dfl_lvl=dfl_lvl; rgr_nfo->hdr_pad=hdr_pad; rgr_nfo->flg_area_out=EXTRACT_CLL_MSR; /* [flg] Add area to output */ rgr_nfo->flg_s1d=flg_s1d; /* [flg] Unpack sparse-1D CLM/ELM variables */ rgr_nfo->flg_uio=SHARE_CREATE; rgr_nfo->fl_out_tmp=nco_fl_out_open(rgr_nfo->fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Copy Global Metadata */ rgr_nfo->out_id=out_id; rgr_nfo->thr_nbr=thr_nbr; nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ (void)nco_att_cpy(in_id,out_id,NC_GLOBAL,NC_GLOBAL,PCK_ATT_CPY); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); char att_sng_ttl[]="title"; /* [sng] NUG-documented title string */ char *att_ttl_val=NULL; att_ttl_val=nco_char_att_get(in_id,NC_GLOBAL,att_sng_ttl); //(void)fprintf(stdout,"%s: DEBUG input title attribute is: %s\n",nco_prg_nm_get(),att_ttl_val); if(!att_ttl_val || (att_ttl_val && (!strcmp(att_ttl_val,"UNSET")))){ /* Panoply prints the value of global attribute "title", if any, in its file selector menu Otherwise it prints "UNSET", which is ... unsettling NUG and CF endorse "title" as a global attribute that succinctly describes file contents Construct a useful value when none exists in input 20210609: "Regridded version of "+fl_in_stub */ att_ttl_val=(char *)nco_realloc(att_ttl_val,(strlen(fl_in_stub)+21L+1L)*sizeof(char)); att_ttl_val=strcpy(att_ttl_val,"Regridded version of "); att_ttl_val=strcat(att_ttl_val,fl_in_stub); rcd=nco_char_att_put(out_id,NULL,att_sng_ttl,att_ttl_val); //(void)fprintf(stdout,"%s: DEBUG output title attribute is: %s\n",nco_prg_nm_get(),att_ttl_val); if(att_ttl_val) att_ttl_val=(char *)nco_free(att_ttl_val); } /* !att_ttl_val */ /* Generate grids/maps or regrid horizontally/vertically */ rcd=nco_rgr_ctl(rgr_nfo,trv_tbl); /* Change from NCO_NOERR to NC_NOERR */ rcd=NC_NOERR; /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(rgr_nfo->fl_out,rgr_nfo->fl_out_tmp,out_id); /* Free regridding structure */ rgr_nfo=nco_rgr_free(rgr_nfo); } /* endif !flg_rgr */ if(!flg_rgr){ /* Initialize, decode, and set PPC information */ if(ppc_nbr > 0) nco_ppc_ini(in_id,&dfl_lvl,fl_out_fmt,ppc_arg,ppc_nbr,trv_tbl); /* Verify output file format supports requested actions */ (void)nco_fl_fmt_vet(fl_out_fmt,cnk_nbr,dfl_lvl); /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Initialize chunking from user-specified inputs */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) rcd+=nco_cnk_ini(in_id,fl_out,cnk_arg,cnk_nbr,cnk_map,cnk_plc,cnk_csh_byt,cnk_min_byt,cnk_sz_byt,cnk_sz_scl,&cnk); /* Define extracted groups, variables, and attributes in output file */ CPY_GRP_METADATA=PRN_GLB_METADATA; (void)nco_xtr_dfn(in_id,out_id,&cnk,dfl_lvl,gpe,md5,CPY_GRP_METADATA,PRN_VAR_METADATA,RETAIN_ALL_DIMS,nco_pck_plc_nil,rec_dmn_nm,trv_tbl); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in,in_id,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr) if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); #endif /* !ENABLE_MPI */ /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ /* [fnc] Open unformatted binary data file for writing */ if(fl_bnr) fp_bnr=nco_bnr_open(fl_bnr,"w"); /* Timestamp end of metadata setup and disk layout */ rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); ddra_info.tmr_flg=nco_tmr_rgl; /* Write extracted data to output file */ if(PRN_VAR_DATA) (void)nco_xtr_wrt(in_id,out_id,gpe,fp_bnr,md5,HAVE_LIMITS,trv_tbl); /* [fnc] Close unformatted binary data file */ if(fp_bnr) (void)nco_bnr_close(fp_bnr,fl_bnr); if(nco_dbg_lvl_get() == 14){ (void)nco_wrt_trv_tbl(in_id,trv_tbl,True); (void)nco_wrt_trv_tbl(out_id,trv_tbl,True); } /* endif dbg */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); } /* flg_rgr */ }else{ /* !fl_out */ nco_bool ALPHA_BY_FULL_GROUP=False; /* [flg] Print alphabetically by full group */ nco_bool ALPHA_BY_STUB_GROUP=True; /* [flg] Print alphabetically by stub group */ char *sfx_ptr; /* Update all GTT dimensions with hyperslabbed size */ (void)nco_dmn_trv_msa_tbl(in_id,rec_dmn_nm,trv_tbl); /* No output file was specified so PRN_ tokens refer to screen printing */ prn_fmt_sct prn_flg; /* Printing defaults to stdout */ prn_flg.fp_out=stdout; PRN_CDL=PRN_CDL || !(PRN_TRD || PRN_XML || PRN_JSN); // 20170817 prn_flg.cdl=PRN_CDL; prn_flg.trd=PRN_TRD; prn_flg.jsn=PRN_JSN; prn_flg.srm=PRN_SRM; prn_flg.xml=PRN_XML; if((prn_flg.cdl || prn_flg.xml) && nco_dbg_lvl >= nco_dbg_std) prn_flg.nfo_xtr=True; else prn_flg.nfo_xtr=False; prn_flg.new_fmt=(PRN_CDL || PRN_JSN || PRN_SRM || PRN_XML); prn_flg.hdn=PRN_HDN; prn_flg.udt=PRN_UDT; prn_flg.rad=RETAIN_ALL_DIMS; /* CDL must print filename stub (filename without path or suffix) */ if(prn_flg.cdl || prn_flg.xml){ sfx_ptr=strrchr(fl_in_stub,'.'); if(sfx_ptr) *sfx_ptr='\0'; prn_flg.fl_stb=fl_in_stub; } /* endif CDL */ /* JSON and XML need filename (unless location will be omitted) */ if(prn_flg.xml || prn_flg.jsn) prn_flg.fl_in=fl_in; prn_flg.spr_nmr=spr_nmr; prn_flg.spr_chr=spr_chr; prn_flg.xml_lcn=PRN_XML_LOCATION; prn_flg.gpe=gpe; prn_flg.md5=md5; prn_flg.ndn=0; /* Initialize for prn_flg->trd */ prn_flg.spc_per_lvl=2; prn_flg.sxn_fst=2; prn_flg.var_fst=2; prn_flg.tab=4; prn_flg.nbr_zro=0; if(nco_dbg_lvl >= nco_dbg_scl) prn_flg.fll_pth=True; else prn_flg.fll_pth=False; if(prn_flg.xml) prn_flg.nwl_pst_val=False; else prn_flg.nwl_pst_val=True; prn_flg.dlm_sng=dlm_sng; if(PRN_CLN_LGB && dt_fmt == fmt_dt_nil) dt_fmt=fmt_dt_sht; prn_flg.cdl_fmt_dt=dt_fmt; prn_flg.fl_out_fmt=fl_out_fmt; prn_flg.fmt_val=fmt_val; prn_flg.ALPHA_BY_FULL_GROUP=ALPHA_BY_FULL_GROUP; prn_flg.ALPHA_BY_STUB_GROUP=ALPHA_BY_STUB_GROUP; prn_flg.FORTRAN_IDX_CNV=FORTRAN_IDX_CNV; prn_flg.PRN_DMN_IDX_CRD_VAL=PRN_DMN_IDX_CRD_VAL; prn_flg.PRN_DMN_UNITS=PRN_DMN_UNITS; prn_flg.PRN_DMN_VAR_NM=PRN_DMN_VAR_NM; prn_flg.PRN_GLB_METADATA=PRN_GLB_METADATA; prn_flg.PRN_MSS_VAL_BLANK=PRN_MSS_VAL_BLANK; prn_flg.PRN_VAR_DATA=PRN_VAR_DATA; prn_flg.PRN_VAR_METADATA=PRN_VAR_METADATA; prn_flg.PRN_CLN_LGB=PRN_CLN_LGB; /* Derived formats */ if(prn_flg.cdl){ prn_flg.PRN_DMN_UNITS=True; prn_flg.PRN_DMN_VAR_NM=True; prn_flg.PRN_MSS_VAL_BLANK=True; } /* endif */ if(prn_flg.jsn){ /* In JSON numeric notation, a terminal decimal place, like 0. and 20., is invalid---correct is 0.0, 20.0 */ prn_flg.nbr_zro=1; /* JSON numerical arrays have no notion of missing values */ prn_flg.PRN_MSS_VAL_BLANK=False; prn_flg.jsn_data_brk=JSN_DATA_BRK; prn_flg.jsn_var_fmt=JSN_VAR_FMT; }else { /* endif JSON */ prn_flg.jsn_att_fmt=0; prn_flg.jsn_data_brk=False; prn_flg.jsn_var_fmt=2; } /* !JSON */ if(prn_flg.xml) prn_flg.PRN_MSS_VAL_BLANK=False; /* File summary */ if(PRN_GLB_METADATA){ prn_flg.smr_sng=smr_sng=(char *)nco_malloc((strlen(fl_in)+300L*sizeof(char))); /* [sng] File summary string */ smr_xtn_sng=(char *)nco_malloc(300L*sizeof(char)); /* [sng] File extended summary string */ if(nco_dbg_lvl > nco_dbg_std) (void)sprintf(smr_xtn_sng," (representation of extended/underlying filetype %s)",nco_fmt_xtn_sng(nco_fmt_xtn_get())); else smr_xtn_sng[0]='\0'; (void)sprintf(smr_sng,"Summary of %s: filetype = %s%s, %i groups (max. depth = %i), %i dimensions (%i fixed, %i record), %i variables (%i atomic, %i user-defined types), %i attributes (%i global, %i group, %i variable)",fl_in,nco_fmt_sng(fl_in_fmt),smr_xtn_sng,grp_nbr_fl,grp_dpt_fl,trv_tbl->nbr_dmn,trv_tbl->nbr_dmn-dmn_rec_fl,dmn_rec_fl,var_nbr_fl,var_nbr_fl-var_udt_fl,var_udt_fl,att_glb_nbr+att_grp_nbr+att_var_nbr,att_glb_nbr,att_grp_nbr,att_var_nbr); if(nco_dbg_lvl > nco_dbg_std){ prn_flg.smr_fl_sz_sng=smr_fl_sz_sng=(char *)nco_malloc(300L*sizeof(char)); /* [sng] String describing estimated file size */ (void)nco_fl_sz_est(smr_fl_sz_sng,trv_tbl); } /* !dbg */ } /* endif summary */ if(fl_prn){ if((fp_prn=fopen(fl_prn,"w")) == NULL){ (void)fprintf(stderr,"%s: ERROR unable to open formatted output file %s\n",nco_prg_nm_get(),fl_prn); nco_exit(EXIT_FAILURE); } /* !fp_prn */ prn_flg.fp_out=fp_prn; } /* !fl_prn */ if(!prn_flg.new_fmt){ /* Traditional printing order/format always used prior to 201307 */ if(PRN_GLB_METADATA){ int dmn_ids_rec[NC_MAX_DIMS]; /* [ID] Record dimension IDs array */ int nbr_rec_lcl; /* [nbr] Number of record dimensions visible in root */ /* Get unlimited dimension information from input file/group */ rcd=nco_inq_unlimdims(in_id,&nbr_rec_lcl,dmn_ids_rec); if(nbr_rec_lcl > 0){ char dmn_nm[NC_MAX_NAME]; long rec_dmn_sz; for(int rec_idx=0;rec_idx<nbr_rec_lcl;rec_idx++){ (void)nco_inq_dim(in_id,dmn_ids_rec[rec_idx],dmn_nm,&rec_dmn_sz); (void)fprintf(prn_flg.fp_out,"Root record dimension %d: name = %s, size = %li\n",rec_idx,dmn_nm,rec_dmn_sz); } /* end loop over rec_idx */ (void)fprintf(stdout,"\n"); } /* NCO_REC_DMN_UNDEFINED */ /* Print group attributes recursively */ (void)nco_prn_att_trv(in_id,&prn_flg,trv_tbl); } /* !PRN_GLB_METADATA */ if(PRN_VAR_METADATA) (void)nco_prn_xtr_mtd(in_id,&prn_flg,trv_tbl); if(PRN_VAR_DATA) (void)nco_prn_xtr_val(in_id,&prn_flg,trv_tbl); }else{ if(CHK_MAP){ /* Check map-file quality */ nco_map_chk(fl_in,flg_area_wgt,flg_frac_b_nrm); goto close_and_free; } /* !CHK_MAP */ if(CHK_NAN){ /* Check floating-point fields for NaNs */ nco_chk_nan(in_id,trv_tbl); goto close_and_free; } /* !CHK_NAN */ /* New file dump format(s) developed 201307 for CDL, JSN, SRM, TRD, XML */ if(PRN_SRM){ /* Stream printing is pre-alpha. Great project for volunteers! */ nco_srm_hdr(); goto close_and_free; } /* !PRN_SRM */ if(ALPHA_BY_FULL_GROUP || ALPHA_BY_STUB_GROUP){ /* Print CDL, JSN, TRD, and XML formats */ if(prn_flg.jsn) rcd+=nco_prn_jsn(in_id,trv_pth,&prn_flg,trv_tbl); else if(prn_flg.xml) rcd+=nco_prn_xml(in_id,trv_pth,&prn_flg,trv_tbl); else if(prn_flg.cdl || prn_flg.trd) rcd+=nco_prn_cdl_trd(in_id,trv_pth,&prn_flg,trv_tbl); }else{ /* Place-holder for other options for organization/alphabetization */ if(PRN_VAR_METADATA) (void)nco_prn_xtr_mtd(in_id,&prn_flg,trv_tbl); if(PRN_VAR_DATA) (void)nco_prn_xtr_val(in_id,&prn_flg,trv_tbl); } /* end if */ } /* endif new format */ if(fl_prn){ rcd=fclose(fp_prn); if(rcd != 0){ (void)fprintf(stderr,"%s: ERROR unable to close formatted output file %s\n",nco_prg_nm_get(),fl_prn); nco_exit(EXIT_FAILURE); } /* !fp_prn */ } /* !fl_prn */ } /* !fl_out */ /* goto close_and_free */ close_and_free: /* Close input netCDF files */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_arr[thr_idx]); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncks-specific memory */ if(fl_bnr) fl_bnr=(char *)nco_free(fl_bnr); if(fl_in_dpl) fl_in_dpl=(char *)nco_free(fl_in_dpl); if(fl_prn) fl_prn=(char *)nco_free(fl_prn); if(flt_sng) flt_sng=(char *)nco_free(flt_sng); if(rec_dmn_nm) rec_dmn_nm=(char *)nco_free(rec_dmn_nm); /* NCO-generic clean-up */ /* Free individual strings/arrays */ if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_in) fl_in=(char *)nco_free(fl_in); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); if(in_id_arr) in_id_arr=(int *)nco_free(in_id_arr); if(spr_nmr) spr_nmr=(char *)nco_free(spr_nmr); if(spr_chr) spr_chr=(char *)nco_free(spr_chr); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(grp_lst_in_nbr > 0) grp_lst_in=nco_sng_lst_free(grp_lst_in,grp_lst_in_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]); for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); for(idx=0;idx<ppc_nbr;idx++) ppc_arg[idx]=(char *)nco_free(ppc_arg[idx]); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0 && (fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC)) cnk.cnk_dmn=(cnk_dmn_sct **)nco_cnk_lst_free(cnk.cnk_dmn,cnk_nbr); trv_tbl_free(trv_tbl); for(idx=0;idx<lmt_nbr;idx++) flg_dne[idx].dim_nm=(char *)nco_free(flg_dne[idx].dim_nm); if(flg_dne) flg_dne=(nco_dmn_dne_t *)nco_free(flg_dne); if(gpe) gpe=(gpe_sct *)nco_gpe_free(gpe); if(md5) md5=(md5_sct *)nco_md5_free(md5); if(rec_dmn_nm_fix) rec_dmn_nm_fix=(char *)nco_free(rec_dmn_nm_fix); if(smr_sng) smr_sng=(char *)nco_free(smr_sng); if(smr_fl_sz_sng) smr_fl_sz_sng=(char *)nco_free(smr_fl_sz_sng); if(smr_xtn_sng) smr_xtn_sng=(char *)nco_free(smr_xtn_sng); } /* !flg_mmr_cln */ #ifdef ENABLE_MPI MPI_Finalize(); #endif /* !ENABLE_MPI */ /* End timer */ ddra_info.tmr_flg=nco_tmr_end; /* [enm] Timer flag */ rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); if(rcd != NC_NOERR) nco_err_exit(rcd,"main"); nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
{ "alphanum_fraction": 0.6789398397, "avg_line_length": 54.3533501896, "ext": "c", "hexsha": "c5f079a93d1f0cda45c47a12e4a470cfd393881b", "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": "bec69956bcf5a8ea8cb2b2116badc6bf95e1c625", "max_forks_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_forks_repo_name": "merjatoelle/nco", "max_forks_repo_path": "src/nco/ncks.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bec69956bcf5a8ea8cb2b2116badc6bf95e1c625", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_issues_repo_name": "merjatoelle/nco", "max_issues_repo_path": "src/nco/ncks.c", "max_line_length": 825, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e77123be96876ed8e63f71e9721ff00e42693c9b", "max_stars_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_stars_repo_name": "rkouznetsov/nco", "max_stars_repo_path": "src/nco/ncks.c", "max_stars_repo_stars_event_max_datetime": "2021-09-20T08:05:14.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-20T08:05:14.000Z", "num_tokens": 26993, "size": 85987 }
#ifndef KCLUSTER_H #define KCLUSTER_H #include <iostream> #include <vector> #include <gsl/gsl_combination.h> #include "kSphere.h" #include "kMath.h" class kCluster { private: double r = 1.0; // the radii of the spheres double r0 = 10.0; // the radii of the bourndary. Use a setter (set_boundary) to adjust. public: std::vector<kSphere> Sphere; void setBoundary(double _r0) { r0 = _r0; } double getBoundary() { return r0; } double mesum() { double tmp; double result = 0.0; // sum of the sqaured distances between all spheres for (std::size_t j = 0; j < Sphere.size(); j++) { for (std::size_t i = 0; i < j; i++) { tmp = kMath::v3abs(kMath::v3diff(Sphere[i].pos, Sphere[j].pos)); result += (tmp * tmp); } } return result; } // inverts the position of the spheres in the cluster which have there indices in the list of // indices. int invert(std::vector<size_t> Indice) { for (size_t i = 0; i < Indice.size(); i++) { Sphere[Indice[i]].pos.x = -Sphere[Indice[i]].pos.x; Sphere[Indice[i]].pos.y = -Sphere[Indice[i]].pos.y; Sphere[Indice[i]].pos.z = -Sphere[Indice[i]].pos.z; } return 0; } // returns a list of k indices (in a vector) which indicate the k spheres from the main // cluster // which represent the smallest potential energy among all posible groups of k spheres. std::vector<size_t> minU(size_t k, double r, double r0) { double pe0; double pe1 = std::numeric_limits<double>::max(); std::vector<kSphere> S0; std::vector<size_t> tmp; std::vector<size_t> result; size_t n = Sphere.size(); tmp.resize(k); result.resize(k); S0.resize(k); gsl_combination *c0 = gsl_combination_calloc(n, k); do { for (size_t i = 0; i < k; i++) { S0[i] = Sphere[c0->data[i]]; tmp[i] = c0->data[i]; } pe0 = pe(tmp, r, r0); // keep hold of the smallest potential on each iteration of the combinations. if (pe0 < pe1) { pe1 = pe0; result = tmp; } } while (gsl_combination_next(c0) == GSL_SUCCESS); gsl_combination_free(c0); return result; } // returns a list of k indices (in a vector) which indicate the k spheres from the main cluster // which represent the largest potential energy among all posible groups of k spheres. std::vector<size_t> maxU(size_t k, double r, double r0) { double pe0; double pe1 = std::numeric_limits<double>::max(); std::vector<kSphere> S0; std::vector<size_t> tmp; std::vector<size_t> result; size_t n = Sphere.size(); tmp.resize(k); result.resize(k); S0.resize(k); gsl_combination *c0 = gsl_combination_calloc(n, k); do { std::cout << "-> "; for (size_t i = 0; i < k; i++) { S0[i] = Sphere[c0->data[i]]; tmp[i] = c0->data[i]; } pe0 = pe(tmp, r, r0); // keep hold of the smallest potential on each iteration of the combinations. if (pe0 > pe1) { pe1 = pe0; result = tmp; } } while (gsl_combination_next(c0) == GSL_SUCCESS); gsl_combination_free(c0); return result; } // TODO: write comment! double d0_mag(kSphere a, double r, double r0) { double tmp = kMath::v3abs(a.pos) + r; if (tmp > r0) { return tmp - r0; } else { return 0.0; } } // The d0 vector is a vector pointing from its position to the origin so just the negative of the // postion with the magnitude found in d0_mag to use the d0_mag we will need to first unitize the // d0 "deformation" vector. v3 d0_vec(kSphere a, double r, double r0) { return kMath::v3scale(kMath::v3unit(a.pos), d0_mag(a, r, r0)); } // TODO: write comment! static v3 d2_vec(kSphere a, kSphere b, double r) { v3 v; v = kMath::v3scale(kMath::v3unit(kMath::v3diff(a.pos, b.pos)), d2_mag(a, b, r)); return v; } // TODO: write comment! static double d2_mag(kSphere a, kSphere b, double r) { double tmp = kMath::v3abs(kMath::v3diff(a.pos, b.pos)) / 2.0; // tmp will equal 0 if a == b. if (tmp < r && tmp != 0.0) { // second condition to ensure that for a = b, 0 // is returned. return r - tmp; } else { return 0.0; } } // TODO: write comment! double pe(double r, double r0) { double sum0 = 0.0; double sum2 = 0.0; for (std::size_t i = 0; i < Sphere.size(); i++) { sum0 += d0_mag(Sphere[i], r, r0); } for (std::size_t j = 0; j < Sphere.size(); j++) { for (std::size_t i = 0; i < Sphere.size(); i++) { if (i != j) { sum2 += d0_mag(Sphere[i], r, r0); } } } return sum0 + sum2; } // Potential Energy function which takes indices for the Sphere list to evaluate over. In stead of // the entire list. double pe(std::vector<size_t> Index, double r, double r0) { double sum0 = 0.0; double sum2 = 0.0; for (std::size_t i = 0; i < Index.size(); i++) { sum0 += d0_mag(Sphere[Index[i]], r, r0); } for (std::size_t j = 0; j < Index.size(); j++) { for (std::size_t i = 0; i < Index.size(); i++) { if (i != j) { sum2 += d2_mag(Sphere[Index[i]], Sphere[Index[j]], r); } } } return sum0 + sum2; } // The gradient of the potential for a single sphere (against all others and the boundary). v3 gradpe(size_t i, double r, double r0) { v3 u; v3 v; u = d0_vec(Sphere[i], r, r0); for (std::size_t j = 0; j < Sphere.size(); j++) { // TODO: test to check if we need the following condition which should // probalby be covered by d2_vec. if (i != j) { // I dont think we need to test here if d2_vec is working // correctly ... test v = d2_vec(Sphere[i], Sphere[j], r); } else { v.x = 0.0; v.y = 0.0; v.z = 0.0; } u.x += v.x; u.y += v.y; u.z += v.z; } return u; } // move the position to the next frame. void update(double r, double r0, double h) { v3 tmp; for (size_t i = 0; i < Sphere.size(); i++) { tmp = gradpe(i, r, r0); Sphere[i].pos.x -= h * tmp.x; Sphere[i].pos.y -= h * tmp.y; Sphere[i].pos.z -= h * tmp.z; } // std::cout << "size: " << tmp.x << std::endl; } // generic print function for the cluster. // TODO: override the << operator instead. void print() { for (size_t i = 0; i < Sphere.size(); i++) { std::cout << Sphere[i].pos.x << " " << Sphere[i].pos.y << " " << Sphere[i].pos.z << std::endl; } std::cout << std::endl; } // TODO: write comment! kCluster(size_t size, double _r) { r = _r; // I moved the radius from kSphere to here (kCluster) since we are using equal size // spheres. r0 is given an large default value but will need to be adjusted for // each configuration size and sphere radius. for (size_t i = 0; i < size; i++) { Sphere.push_back(kSphere()); } // minU(4, 0.5, 1.2); } // Copy Constructor. kCluster(const kCluster &obj) { // All we need to do (for the moment at least) is copy the Sphere vector. // Im hoping that this copies the values and not the addresses. Check! Sphere = obj.Sphere; } // TODO: write comment! void operator=(const kCluster &obj) { Sphere = obj.Sphere; } // TODO: write comment! ~kCluster() {} }; #endif
{ "alphanum_fraction": 0.5714668812, "avg_line_length": 28.6846153846, "ext": "h", "hexsha": "415262e6207657e5ad0c8e3940506247675506c8", "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": "138f8db813d88392b9eba422d7a3f3daeda2dd0f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrejoe/kbm", "max_forks_repo_path": "kbm/kCluster.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "138f8db813d88392b9eba422d7a3f3daeda2dd0f", "max_issues_repo_issues_event_max_datetime": "2015-07-08T22:42:04.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-08T22:42:04.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrejoe/kbm", "max_issues_repo_path": "kbm/kCluster.h", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "138f8db813d88392b9eba422d7a3f3daeda2dd0f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrejoe/kbm", "max_stars_repo_path": "kbm/kCluster.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2289, "size": 7458 }
/**************************************************************************** * Moreno2011Cell.h - defines cell_param struct - i.e. Cell * * Based on code from Moreno et al. 2011 * * Created on: Sep 30, 2014 * Author: Anthony Varghese ***************************************************************************/ #ifndef CELL_H_ #define CELL_H_ #define M_PI 3.14159265358979323846 /* pi - needed if using -std=c++11 */ #include <cmath> #include <gsl/gsl_blas.h> namespace cellmodel{ class Cells; } enum NaChannelMMSolver{ NotUsed, Iterative, LUDecomp }; class Moreno2011Cell { public: Moreno2011Cell(); virtual ~Moreno2011Cell(); Moreno2011Cell(const Moreno2011Cell& source); Moreno2011Cell& operator=(const Moreno2011Cell& rhs); void setParams(const double* par); void setXpos(unsigned int p){ pos_x = p; } void Copy(const Moreno2011Cell& in); void setEnvironment( cellmodel::Cells* env ); void setState(double* newstate) { for (unsigned int i = 0; i < nstates; i++) state[i] = newstate[i]; } /* * Calling method is responsible for allocating Y array */ void getState(double* Y) { for (unsigned int i = 0; i < nstates; i++) Y[i] = state[i]; } /* * Calling method is responsible for allocating dYdt array */ void getRates(double* dYdt) { for (unsigned int i = 0; i < nstates; i++) dYdt[i] = rates[i]; } void Calculate_Points(double t); double CalculateCurrents(double t); double CalculateCurrents(double t, const double Vx); void Calculate_All(const double t); void SetInitialConditions(); void Calculate_Reset(double t); void setI_stimulus(double t); void updatedVdt(const double Iaxnm1, const double Iaxnp1){ dV_old = dVdt; I_axnm1 = Iaxnm1; I_axnp1 = Iaxnp1; I_axial = Iaxnp1 + Iaxnm1; dVdt = -I_axial - I_total; // Rate of change of Vm } double getV() const { return V; } double getdVdt()const { return dVdt; } double getI_total()const { return I_total; } void setV (const double Vnew) { V = Vnew; } void setdVdt(const double dVdtnew){ dVdt = dVdtnew; } /* * Forward Euler update of V */ void fe_updateV(const double dt) { V = V + dVdt * dt; } double getI_K1() const { return I_K1; } double getI_Na() const { return I_Na; } double getI_axnm1() const { return I_axnm1; } double getI_axnp1() const { return I_axnp1; } double getI_axial() const { return I_axial; } // Na Channel States double getNaClosed()const { return C1 + C2 + C3; } double getNaIC23() const { return IC2 + IC3; } double getNaIF() const { return IF; } double getNaOS() const { return OS; } double getNaO() const { return O; } double getNaDClosed() const { return DC1 + DC2 + DC3; } double getNaDIC23() const { return DIC2 + DIC3; } double getNaDIF() const { return DIF; } double getNaDOS() const { return DOS; } double getNaDO() const { return DO; } double getNaDIM1() const { return DIM1; } double getNaD_Closed() const { return D_C1 + D_C2 + D_C3; } double getNaD_IC23()const { return D_IC2 + D_IC3; } double getNaD_IF() const { return D_IF; } double getNaD_OS() const { return D_OS; } double getNaD_O() const { return D_O; } double getNaD_IM1() const { return D_IM1; } /* * computeRushLarsenStepState * - take a time step using Rush Larsen for gating variables * and semi-implicit for Markov State models * Calling method is responsible for allocating Y array */ void computeRushLarsenStepState( const double t, const double dt ); /* * computeRushLarsen2StepState * - take a time step using Second-order Rush Larsen for all states * and semi-implicit for Markov State models * Calling method is responsible for allocating Y array */ void computeRushLarsen2StepState( const double t, const double dt, const int step, const double Vhalf ); // Indices into the state array static const unsigned int nNaChFirstState = 0; // Number of states for Na Channel Markov state model: static const unsigned int nNaChLastState = 29; static const unsigned int nNaChStates = nNaChLastState + 1; // start of gating variables: static const unsigned int ngatem = nNaChStates; static const unsigned int nLastState = ngatem + 20; // last state // Currently, the cell transmembrane potential is the last state static const unsigned int nV = nLastState; static const unsigned int nstates = nV + 1; // Total number of states // Cell States double state[nstates]; // state variables for integration double peak_slope, t_min, V_min, t_thr, V_thr, t_max, V_max, t_EAD, V_EAD; double t_EAD2, V_EAD2, t_90, V_90, dV_old; bool flag2; double APD_90, DI, L_EAD; // To measure the work involved in the iterations: int MarkovIterations; double MarkovIterationError; private: // Need a pointer back to the container class to // find out conditions like waitTime, drug conc, etc. cellmodel::Cells* cellenv = nullptr; /**************************************************************************** Universal Constants *****************************************************************************/ static constexpr double R = 8314.472; // J/mol*K static constexpr double T = 310; // K static constexpr double F = 96485.3415; static constexpr double RTF = R*T/F; // const double Cm = 2.0; // uF/ cm^2 -- not used anywhere static constexpr double CAP = 0.185; // Cellular capacitance static constexpr double rho = 162; // ohm*cm // Channel conductances - these can be set externally // used to be: // static constexpr double G_Na = 15.0; //27.5 //18.5 double G_Na = 15.0; // 15.0 in Moreno et al 2011 double GK1 = 5.405; // 5.405 in Moreno et al 2011 // Ion Valences static constexpr double z_Na = 1; // Valence of Na static constexpr double z_Ca = 2; // Valence of Ca static constexpr double z_K = 1; // Valence of K //Cell Geometry static constexpr double pi = M_PI; // Should be 3.141592 static constexpr double S_cg = 0.2; // Surface to volume ratio (um^-1) //Intracellular volumes static constexpr double V_cyto=0.016404; //16404 uL static constexpr double V_sr=0.001094; static constexpr double V_ss=0.00005468; // initial conditions of ion concentrations static constexpr double Na_out = 140; static constexpr double Ca_out = 2.0; static constexpr double K_out = 5.4; static constexpr double Vmin_default = 0.0; // mV - a "large" value so that minimums (expected to be < 0) can be detected static constexpr double Vthr_default = -90.0; // mV - a "low" value so that the threshold can be detected bool initializedExternally = false; static const NaChannelMMSolver NaChanSolver = Iterative; // LUDecomp; // Iterative; // Arrays for each cell: double rates[nstates]; // rates of change of state - derivative // Total number of currents and auxilliary values: static const unsigned int naux = 26; double currents[naux]; int Cell_type; unsigned int pos_x=0; // unsigned int pos_y=0, pos_z=0; // Position of cell in 3-d // Na Channel constants static constexpr double Q10 = 3; // This does not work in clang, ok in gcc //static constexpr double Tfactor = 1.0/(pow(Q10, (37.0-(T-273))/10.0)); static constexpr double pH = 7.4; // Na channel markov state model - the individual states are only needed for outputs double &IC3 = state[ 0], &IC2 = state[1]; double &IF = state[ 2], &IM1 = state[3]; double &IM2 = state[ 4], &C3 = state[5]; double &C2 = state[ 6], &O = state[7]; double &OS = state[ 8], &C1 = state[9]; double &DIC3 = state[10], &DIC2 = state[11]; double &DIF = state[12], &DIM1 = state[13]; double &DIM2 = state[14], &DC3 = state[15]; double &DC2 = state[16], &DO = state[17]; double &DOS = state[18], &DC1 = state[19]; double &D_IC3 = state[20], &D_IC2 = state[21]; double &D_IF = state[22], &D_IM1 = state[23]; double &D_IM2 = state[24], &D_C3 = state[25]; double &D_C2 = state[26], &D_O = state[27]; double &D_OS = state[28], &D_C1 = state[29]; double &V = state[ngatem + 20]; // Gating variables double &m = state[ngatem], &h = state[ngatem + 1]; double &j = state[ngatem + 2]; double &d = state[ngatem + 3], &f = state[ngatem + 4]; double &f2 = state[ngatem + 5], &f_Ca = state[ngatem + 6]; double &r = state[ngatem + 7], &s = state[ngatem + 8]; double &xr1 = state[ngatem + 9], &xr2 = state[ngatem + 10]; double &xs = state[ngatem + 11]; double &R_bar = state[ngatem + 12]; double &mL = state[ngatem + 13], &hL = state[ngatem + 14]; double &Ca_in = state[ngatem + 15], &Ca_sr = state[ngatem + 16]; double &Ca_ss = state[ngatem + 17]; double &Na_in = state[ngatem + 18], &K_in = state[ngatem + 19]; double &dVdt = rates[ngatem + 20]; // old gating variable values before half-step in 2nd order Rush Larsen double oldgates[20]; double &oldm = oldgates[0], &oldh = oldgates[1]; double &oldj = oldgates[2]; double &oldd = oldgates[3], &oldf = oldgates[4]; double &oldf2 = oldgates[5], &oldf_Ca = oldgates[6]; double &oldr = oldgates[7], &olds = oldgates[8]; double &oldxr1 = oldgates[9], &oldxr2 = oldgates[10]; double &oldxs = oldgates[11]; double &oldR_bar = oldgates[12]; double &oldmL = oldgates[13], &oldhL = oldgates[14]; double &oldCa_in = oldgates[15], &oldCa_sr = oldgates[16]; double &oldCa_ss = oldgates[17]; double &oldNa_in = oldgates[18], &oldK_in = oldgates[19]; // Currents and auxilliary values - anything that may be useful to print out for plotting double &I_total = currents[0]; double &I_axial = currents[1]; double &I_axnm1 = currents[2], &I_axnp1 = currents[3]; double &I_stim = currents[4]; double &I_Na = currents[5], &I_Na_L = currents[6]; double &mI_Na = currents[7], &I_Na_b = currents[8]; double &I_Ca_L = currents[9], &I_Ca_b = currents[10]; double &I_Kr = currents[11], &I_Ks = currents[12]; double &I_K1 = currents[13], &I_Kp = currents[14]; double &I_to = currents[15]; double &I_Na_Ca = currents[16], &I_Na_K = currents[17]; double &I_p_Ca = currents[18]; double &I_Na_ion_total = currents[19]; double &I_Ca_ion_total = currents[20]; double &I_K_ion_total = currents[21]; double &I_tr = currents[22], &I_leak = currents[23]; double &I_up = currents[24], &I_rel = currents[25]; // RATES // Na channel markov state model double &dIC3 = rates[ 0], &dIC2 = rates[1]; double &dIF = rates[ 2], &dIM1 = rates[3]; double &dIM2 = rates[ 4], &dC3 = rates[5]; double &dC2 = rates[ 6], &dO = rates[7]; double &dOS = rates[ 8], &dC1 = rates[9]; double &dDIC3 = rates[10], &dDIC2 = rates[11]; double &dDIF = rates[12], &dDIM1 = rates[13]; double &dDIM2 = rates[14], &dDC3 = rates[15]; double &dDC2 = rates[16], &dDO = rates[17]; double &dDOS = rates[18], &dDC1 = rates[19]; double &dD_IC3 = rates[20], &dD_IC2 = rates[21]; double &dD_IF = rates[22], &dD_IM1 = rates[23]; double &dD_IM2 = rates[24], &dD_C3 = rates[25]; double &dD_C2 = rates[26], &dD_O = rates[27]; double &dD_OS = rates[28], &dD_C1 = rates[29]; // Gating variable rates double &dm = rates[ngatem ], &dh = rates[ngatem + 1]; double &dj = rates[ngatem + 2]; double &dd = rates[ngatem + 3], &df = rates[ngatem + 4]; double &df2 = rates[ngatem + 5], &df_Ca = rates[ngatem + 6]; double &dr = rates[ngatem + 7], &ds = rates[ngatem + 8]; double &dxr1 = rates[ngatem + 9], &dxr2 = rates[ngatem + 10]; double &dxs = rates[ngatem + 11]; double &dR_bar = rates[ngatem + 12]; double &dmL = rates[ngatem + 13], &dhL = rates[ngatem + 14]; double &dCa_in = rates[ngatem + 15], &dCa_sr = rates[ngatem + 16]; double &dCa_ss = rates[ngatem + 17]; double &dNa_in = rates[ngatem + 18], &dK_in = rates[ngatem + 19]; // Cell data points - markers of cell function double I_total_old, dI_total, dI_total_old, t_I_total, I_total_pt; double V_I_total; bool flagI_total, flag_EAD, flag_EAD2; double t_90_old; double CV, CV_EAD; // The temporary array is used for a modified-Newton iteration to solve // for the markov channel state variables. static const unsigned int i3 = 0, i2 = 1, iF = 2, im = 3, iM = 4, c3 = 5, c2 = 6, op = 7, oS = 8, c1 = 9; static const unsigned int di3 = 10, di2 = 11, diF = 12, dim = 13, diM = 14, dc3 = 15, dc2 = 16, dop = 17, doS = 18, dc1 = 19; static const unsigned int Di3 = 20, Di2 = 21, DiF = 22, Dim = 23, DiM = 24, Dc3 = 25, Dc2 = 26, Dop = 27, DoS = 28, Dc1 = 29; // BLAS vectors and methods to allocate, free and copy them gsl_vector* Yn = nullptr; gsl_vector* Ynph = nullptr; gsl_vector* Ynp1 = nullptr; gsl_vector* Ynp1i= nullptr; gsl_vector* DiagonalAn = nullptr; gsl_vector* DiagonalAnInv = nullptr; gsl_matrix* OffDiagonalAn = nullptr; void allocTemps(); void freeTemps(); void copyTemps(const Moreno2011Cell& source); /********************************************************************************************************* Current Function Prototypes *********************************************************************************************************/ void WT_SCN5A_Initial_Conditions(); void WT_SCN5A_Lidocaine(); void WT_SCN5A_Flecainide(); void checkNaChannelStates(); void calcI_total(double t); void calcI_Na(double t); //Fast sodium current void calcI_Na_L(); void calcI_K1(); //Time independent potassium current void calcI_Kp(); //Plateau K current, time independent, K_out insensitive void calcI_Na_Ca(); //Sodium calcium exchanger void calcI_Na_K(); //Sodium potassium pump void calcI_Ca_L(); //L type calcium channel Ca contribution void calcI_Kr(); //Rapid rectifier void calcI_Ks(); //Slow rectifier void calcI_to(); //Transient outward current void calcI_p_Ca(); //Sarcolemmal calcium pump void calcI_Ca_b(); //Calcium background current void calcI_Na_b(); //Sodium background current void calcI_tr(); void calcI_leak(); //Leak from SR void calcI_up(); //Uptake to SR void calcI_rel(); //Release from SR //Dynamic Concentrations void Calculate_Na_in(); //Dynamic [Na] in Myoplasm void Calculate_K_in(); //Dynamic [K] in Myoplasm void Calculate_Ca_in(); //Dynamic [Ca] in Myoplasm void Calculate_Ca_sr(); //Dynamic [Ca] in JSR void Calculate_Ca_ss(); //Dynamic [Ca] in NSR // Semi-implicit and Rush-Larsen struct NaChannelParameters{ double pKa, portion, diffusion, drug_charged, drug_neutral, drug_distance, kd0, kd_open; double a11, a12, a13, b11, b12, b13, a3, b3, a2, b2, a4, b4, a5, b5, ax, bx, ax1, bx1, a13c,a22, b33, a33, a44, b44, a55, b55, ax2, a13n, a_22, b_33, a_44,b_44, a_55, b_55, kon, koff, kcoff, kcon, b13c,b22, k_on, k_off, ki_on, ki_off, kc_on, kc_off, a_33, b13n, b_22, bx2; void Initialize( cellmodel::Cells* cellenv ); void ComputeVDepTerms(const double V, cellmodel::Cells* env ); void set_NaCh_Matrices( gsl_matrix* M, gsl_vector* D); }; NaChannelParameters NaChParams; static constexpr double tolerance = 1e-7; void semi_impl_I_Na(double t, const double dt); //Fast sodium current void semi_impl_WT_SCN5A(const double dt); void semi_impl_WT_SCN5A_LU(const double dt); void exponential_I_Na1(double t, const double dt); void exponential_I_Na2(double t, const double dt, const double Vhalf); void rush_I_Na_L(const double dt); void rush_I_Ca_L(const double dt); //L type calcium channel Ca contribution void rush_I_Kr(const double dt); //Rapid rectifier void rush_I_Ks(const double dt); //Slow rectifier void rush_I_to(const double dt); //Transient outward current void rush_I_rel(const double dt); //Release from SR void rush_Na_in(const double dt); //Dynamic [Na] in Myoplasm void rush_K_in(const double dt); //Dynamic [K] in Myoplasm void rush_Ca_in(const double dt); //Dynamic [Ca] in Myoplasm void rush_Ca_sr(const double dt); //Dynamic [Ca] in JSR void rush_Ca_ss(const double dt); //Dynamic [Ca] in NSR // Old code - not used and not needed - new code is working void semi_impl_WT_SCN5A_Lidocaine(const double dt); void semi_impl_WT_SCN5A_Flecainide(const double dt); void set_NaCh_Matrices( gsl_matrix* M, gsl_vector* D, const double a11, const double a12, const double a13, const double b11, const double b12, const double b13, const double a3, const double b3, const double a2, const double b2, const double a4, const double b4, const double a5, const double b5, const double ax, const double bx, const double ax1,const double bx1, const double a13c, const double a22, const double b33,const double a33, const double a44, const double b44, const double a55,const double b55, const double ax2, const double a13n, const double a_22, const double b_33, const double a_44, const double b_44, const double a_55, const double b_55, const double kon, const double koff, const double kcoff, const double kcon, const double b13c, const double b22, const double k_on, const double k_off, const double ki_on, const double ki_off,const double kc_on, const double kc_off, const double a_33, const double b13n, const double b_22, const double bx2 ); double MCtemp[nNaChStates]; double &mIC3 = MCtemp[ 0], &mIC2 = MCtemp[1]; double &mIF = MCtemp[ 2], &mIM1 = MCtemp[3]; double &mIM2 = MCtemp[ 4], &mC3 = MCtemp[5]; double &mC2 = MCtemp[ 6], &mO = MCtemp[7]; double &mOS = MCtemp[ 8], &mC1 = MCtemp[9]; double &mDIC3 = MCtemp[10], &mDIC2 = MCtemp[11]; double &mDIF = MCtemp[12], &mDIM1 = MCtemp[13]; double &mDIM2 = MCtemp[14], &mDC3 = MCtemp[15]; double &mDC2 = MCtemp[16], &mDO = MCtemp[17]; double &mDOS = MCtemp[18], &mDC1 = MCtemp[19]; double &mD_IC3 = MCtemp[20], &mD_IC2 = MCtemp[21]; double &mD_IF = MCtemp[22], &mD_IM1 = MCtemp[23]; double &mD_IM2 = MCtemp[24], &mD_C3 = MCtemp[25]; double &mD_C2 = MCtemp[26], &mD_O = MCtemp[27]; double &mD_OS = MCtemp[28], &mD_C1 = MCtemp[29]; void semi_impl_WT_SCN5A_Lidocaine_compare_BLAS_old(const double dt); void semi_impl_WT_SCN5A_Flecainide_old (const double dt); }; #endif /* CELL_H_ */
{ "alphanum_fraction": 0.6646042363, "avg_line_length": 39.1703056769, "ext": "h", "hexsha": "59e2418bb5a78a5babd572394538604ee8a4f1d3", "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": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AnthonyVa/Cardcell", "max_forks_repo_path": "src/cell/Moreno2011Cell.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "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": "AnthonyVa/Cardcell", "max_issues_repo_path": "src/cell/Moreno2011Cell.h", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AnthonyVa/Cardcell", "max_stars_repo_path": "src/cell/Moreno2011Cell.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6052, "size": 17940 }
#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 RADTRANSFER #ifdef EDDINGTON_TENSOR_STARS static struct stardata_in { MyDouble Pos[3], Density, Mass; MyFloat Hsml; int NodeList[NODELISTLENGTH]; } *StarDataIn, *StarDataGet; #endif void star_density(void) { int j; #ifdef EDDINGTON_TENSOR_STARS int i, dummy; int ngrp, sendTask, recvTask, place, nexport, nimport, ndone, ndone_flag; #endif /* clear Je in all gas particles */ for(j = 0; j < N_gas; j++) { if(P[j].Type == 0) SphP[j].Je = 0; #ifdef SFR if(P[j].Type == 0) { SphP[j].Je += SphP[j].Sfr * All.IonizingLumPerSFR * (PROTONMASS / (P[j].Mass * All.UnitMass_in_g / All.HubbleParam)) * All.UnitTime_in_s / All.HubbleParam; printf("ET get_JE ID: %d Proc %d", P[j].ID, ThisTask); } #endif } #ifdef EDDINGTON_TENSOR_STARS /* 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) + 2 * sizeof(struct stardata_in))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); i = FirstActiveParticle; /* beginn with this index */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ for(nexport = 0; i >= 0; i = NextActiveParticle[i]) { if(P[i].Type == 4) { if(star_density_evaluate(i, 0, &nexport, Send_count) < 0) break; } } #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 MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); 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]; } } StarDataGet = (struct stardata_in *) mymalloc(nimport * sizeof(struct stardata_in)); StarDataIn = (struct stardata_in *) mymalloc(nexport * sizeof(struct stardata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; StarDataIn[j].Pos[0] = P[place].Pos[0]; StarDataIn[j].Pos[1] = P[place].Pos[1]; StarDataIn[j].Pos[2] = P[place].Pos[2]; StarDataIn[j].Hsml = PPP[place].Hsml; StarDataIn[j].Density = P[place].DensAroundStar; StarDataIn[j].Mass = P[place].Mass; memcpy(StarDataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange particle data */ 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(&StarDataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct stardata_in), MPI_BYTE, recvTask, TAG_DENS_A, &StarDataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct stardata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(StarDataIn); /* now do the particles that were sent to us */ for(j = 0; j < nimport; j++) star_density_evaluate(j, 1, &dummy, &dummy); /* check whether this is the last iteration */ if(i < 0) ndone_flag = 1; else ndone_flag = 0; MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); myfree(StarDataGet); } while(ndone < NTask); myfree(DataNodeList); myfree(DataIndexTable); myfree(Ngblist); #endif //for EDDINGTON_TENSOR_STARS } #ifdef EDDINGTON_TENSOR_STARS /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ int star_density_evaluate(int target, int mode, int *nexport, int *nsend_local) { int j, n, numngb; int startnode, listindex = 0; double h, hinv, h2, mass_j, weight, hinv3; double wk, mass, density, lum; double dx, dy, dz, r, r2, u, a3inv; MyDouble *pos; #ifdef PERIODIC double boxsize, boxhalf; boxsize = All.BoxSize; boxhalf = 0.5 * All.BoxSize; #endif if(All.ComovingIntegrationOn) a3inv = 1.0 / (All.Time * All.Time * All.Time); else a3inv = 1.0; if(mode == 0) { pos = P[target].Pos; h = PPP[target].Hsml; density = P[target].DensAroundStar; mass = P[target].Mass; } else { pos = StarDataGet[target].Pos; h = StarDataGet[target].Hsml; density = StarDataGet[target].Density; mass = StarDataGet[target].Mass; } h2 = h * h; hinv = 1.0 / h; hinv3 = hinv * hinv * hinv; lum = mass * All.IonizingLumPerSolarMass * (PROTONMASS / SOLAR_MASS) * All.UnitTime_in_s / All.HubbleParam; if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = StarDataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } while(startnode >= 0) { while(startnode >= 0) { numngb = ngb_treefind_variable(pos, h, target, &startnode, mode, nexport, nsend_local); if(numngb < 0) return -1; for(n = 0; n < numngb; n++) { j = Ngblist[n]; dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC 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; r = sqrt(r2); if(r2 < h2) { u = r * hinv; if(u < 0.5) wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); else wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); } else wk = 0; mass_j = P[j].Mass; weight = mass_j * wk / density; SphP[j].Je += lum * weight / mass_j; } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = StarDataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } return 0; } #endif #endif
{ "alphanum_fraction": 0.6087574637, "avg_line_length": 23.3687707641, "ext": "c", "hexsha": "1c378ea0604bcbb4ca60224dd8b634d0c1663a77", "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/get_Je.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/get_Je.c", "max_line_length": 109, "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/get_Je.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2288, "size": 7034 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_sf_bessel.h> int main(void) { double x = 5.0; printf("J0(%g) = %.18e\n", x, gsl_sf_bessel_J0(x)); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.625, "avg_line_length": 17.4545454545, "ext": "c", "hexsha": "165f235c4380500eb245d56c4f9101ed467b9271", "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": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "liujiamingustc/phd", "max_forks_repo_path": "awesome/c_cpp/cpp-cheat/cmake/shared_lib_external/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "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": "liujiamingustc/phd", "max_issues_repo_path": "awesome/c_cpp/cpp-cheat/cmake/shared_lib_external/main.c", "max_line_length": 55, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "liujiamingustc/phd", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/cmake/shared_lib_external/main.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z", "num_tokens": 65, "size": 192 }
#pragma once #include <gsl/gsl> #include <boost/noncopyable.hpp> namespace hash_calculator { class FileMapper : private boost::noncopyable { public: FileMapper(int fd, size_t startPosition, size_t maxBufsize); ~FileMapper(); void* getPtr(size_t currentPosition, size_t offset) const; void mapping(); void remapping(size_t startPosition, size_t offset); private: int m_fd; size_t m_startPosition; size_t m_maxBufsize; void* m_ptr; }; } // hash_calculator
{ "alphanum_fraction": 0.7183098592, "avg_line_length": 17.75, "ext": "h", "hexsha": "9f295507c5b2392d9d0db753caa75c84d0365e04", "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": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "nicledomaS/HashCalculator", "max_forks_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "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": "nicledomaS/HashCalculator", "max_issues_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "4708824e2ddde1fc7c330711ae7939c57556cb7d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "nicledomaS/HashCalculator", "max_stars_repo_path": "modules/hash_calculator/src/FileMapper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 125, "size": 497 }
#pragma once #include <gsl/gsl_bspline.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_statistics.h> #include <vector> #include <utility> #include <cmath> class BSplineFit { public: BSplineFit(const BSplineFit&); BSplineFit(); ~BSplineFit(); void initialize(unsigned dataSize, std::vector<double> datax, std::vector<double> datay, unsigned orderBSpline, unsigned nBreak); void freeAll(); void solve_system(); double calculateY(double x); std::vector<double> calculateY(std::vector<double> x); std::vector<double> getConfidentInterval(double level = 0.95); std::vector<double> getBoudaryPolyCoef(double boundaryPos); std::vector<double> getfittedPara(); //return in the order of {orderBSpline, dataSize, nBreak, nBasis} std::vector<unsigned> getBSplinePara(); std::pair<double, double> getxlim(); static std::vector<double> calculateY(unsigned orderBSpline, unsigned nBreak, std::pair<double, double> xlim, std::vector<double> coef, std::vector<double> xpts); private: private: bool emptyStart; std::vector<double> datax, datay; // datax should be sorted in the ascending order gsl_matrix* X; // design matrix in linear least square regression, dataSize x nBasis, each row is evaluated for the same x with different basis function gsl_vector* y; // datay for fitting gsl_vector* coef; // coefficient in front of basis function gsl_matrix* cov; // variance-covariance matrix of linear regression, cov = RSS/(dataSize-nBasis) * (X^T*X)^(-1), RSS is called chisq in GSL // where RSS is the sum of square residual = sum(yi-\hat{yi})^2, RSS/(dataSize-nBasis) = s^2, the unbiased estimator of system variance gsl_vector* B; // Bspline vector for a particular point x, to facilitate eval inside functions double RSS, TSS, Rsq; std::vector<double> confi95; std::vector<double> leftPoly, rightPoly; gsl_bspline_workspace* bw; gsl_multifit_linear_workspace* mw; unsigned orderBSpline; // order of B spline, gives a polynomial of order = orderBSpline-1 unsigned dataSize; // number of data points to be fit unsigned nBreak; // number of break points, including left and right end points unsigned nBasis; // number of basis function in the interval = nbreak - 2 + orderBSpline // note this is the same as the number of parameter in the final linear least square fitting // when orderBSpline = 1, nBasis = nBreak-1, i.e. nBreak-1 step function fill // in each interval. When orderBSpline increase, the basis function number also increase // since the basis function is now extending over several interval and the left/right boundary will // see tails of basis function whose center point is outside the total range };
{ "alphanum_fraction": 0.7520630158, "avg_line_length": 41.65625, "ext": "h", "hexsha": "36ff975bc69dc2115d3218f453122747bbc9bfac", "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": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/Source/AnalogInput/BSplineFit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/Source/AnalogInput/BSplineFit.h", "max_line_length": 153, "max_stars_count": null, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/Source/AnalogInput/BSplineFit.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 686, "size": 2666 }
// Precompiled headers go in here #pragma once // Standard Library Header #include <format> #include <fstream> #include <memory> #include <stdexcept> #include <random> #include <algorithm> #include <utility> #include <mutex> #include <shared_mutex> #include <execution> #include <optional> #include <iostream> // Data structures #include <string> #include <vector> #include <array> // GSL: Guidelines Support Library //#include <gsl/gsl> // Extern libs #include "fmt/core.h" #include "nlohmann/json.hpp" // My #include "Enums.h" #include "RandomNumbers.h" #include "Statistics.h" #include "Disease/Disease.h" #include "Disease/Infection.h" #include "Person/Person.h" #include "Places/Places.h" #include "Places/Community.h" #include "Simulation/MeasureTime.h"
{ "alphanum_fraction": 0.737254902, "avg_line_length": 19.125, "ext": "h", "hexsha": "90ee10abfdc30d8bc4122e129e2e4f659c823e5c", "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": "8653f260660322e140fa390ce64dbd1b0346125a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Neithari/DiseaseSpreadSimulator", "max_forks_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "8653f260660322e140fa390ce64dbd1b0346125a", "max_issues_repo_issues_event_max_datetime": "2022-03-27T01:01:01.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-24T01:19:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Neithari/DiseaseSpreadSimulator", "max_issues_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_line_length": 35, "max_stars_count": null, "max_stars_repo_head_hexsha": "8653f260660322e140fa390ce64dbd1b0346125a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Neithari/DiseaseSpreadSimulator", "max_stars_repo_path": "src/DiseaseSpreadSimulator/pch.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 180, "size": 765 }
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <numpy/arrayobject.h> #include <lapacke.h> /* DGESVD prototype */ extern void LAPACK_dgesvd( char* jobu, char* jobvt, int* m, int* n, double* a, int* lda, double* s, double* u, int* ldu, double* vt, int* ldvt, double* work, int* lwork, int* info ); double** An(double *pi, double *x, int labs, int dims); double** A(double **PI, double **X, int labs, int dims, int n_pool); double** Fisher(double *pi, double *x, double sigma, int labs, int dims); static char estVar_docstring[] = "Calculate the A and Fisher matrix."; static PyObject *varRedu_estVar(PyObject *self, PyObject *args); static PyMethodDef module_methods[] = { {"estVar", varRedu_estVar, METH_VARARGS, estVar_docstring}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_variance_reduction", /* m_name */ "This module provides calculate A and Fisher matrix using C.", /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; PyMODINIT_FUNC PyInit__variance_reduction(void){ PyObject *m = PyModule_Create(&moduledef); if(m==NULL){ return NULL; } /* Load 'numpy' */ import_array(); return m; } double* matrix_mul(double* a, double* b, int m1, int n1, int m2, int n2){ double *ret = (double*) malloc(m1 * n2 * sizeof(double)); if(n1 != m2){ return NULL; } for(int i=0; i<m1; i++) for(int j=0; j<n2; j++){ double temp = 0.0; for(int p=0; p<n1; p++) temp += a[i*n1 + p] * b[p*n2 + j]; ret[i*n2 + j] = temp; } return ret; } void pinv(double** X, int labs, int dims){ int m = labs*dims, n = labs*dims, lda = labs*dims, ldu = labs*dims, ldvt = labs*dims, lwork, info; double wkopt; double *work; double *s = (double*) malloc(labs*dims * sizeof(double)); double *u = (double*) malloc(labs*dims * labs*dims * sizeof(double)); double *vt = (double*) malloc(labs*dims * labs*dims * sizeof(double)); double *a = (double*) malloc(labs*dims * labs*dims * sizeof(double)); for(int i=0; i<m; i++) for(int j=0; j<n; j++) a[i*labs*dims + j] = X[i][j]; /* Query and allocate the optimal workspace */ lwork = -1; LAPACK_dgesvd("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &wkopt, &lwork, &info); lwork = (int)wkopt; work = (double*)malloc( lwork*sizeof(double) ); /* Compute SVD */ LAPACK_dgesvd("All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, &info); /* Check for convergence */ if(info > 0) { printf("The algorithm computing SVD failed to converge. %d\n", info); } if(info < 0) { printf("Has illegal value. %d\n", info); } int numSigular = 0; double *si = (double*) malloc(labs*dims * labs*dims * sizeof(double)); memset(si, 0, labs*dims * labs*dims * sizeof(double)); for(int i=0; i<ldu; i++){ if(s[i] > 1e-30){ si[i*ldu + i] = 1.0 / s[i]; numSigular += 1; }else{ si[i+ldu + i] = 0.0; } } /* calculating transpose */ double *ret = matrix_mul(vt, si, labs*dims, numSigular, numSigular, numSigular); double *ret_pinv = matrix_mul(ret, u, labs*dims, numSigular, numSigular, labs*dims); for(int i=0; i<m; i++) for(int j=0; j<n; j++) X[i][j] = ret_pinv[i*n + j]; free(ret); free(ret_pinv); free(work); free(a); free(s); free(vt); free(u); free(si); return; } static PyObject *varRedu_estVar(PyObject *self, PyObject *args) { int dims, n_pool, labs, sigma; PyObject *PI_obj, *X_obj, *ePI_obj, *eX_obj; if (!PyArg_ParseTuple(args, "dOOOO", &sigma, &PI_obj, &X_obj, &ePI_obj, &eX_obj)) return NULL; PyArrayObject *PI_array = (PyArrayObject*)PyArray_FROM_OTF(PI_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); PyArrayObject *X_array = (PyArrayObject*)PyArray_FROM_OTF(X_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); PyArrayObject *ePI_array = (PyArrayObject*)PyArray_FROM_OTF(ePI_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); PyArrayObject *eX_array = (PyArrayObject*)PyArray_FROM_OTF(eX_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (PI_array == NULL || X_array == NULL || ePI_array == NULL || eX_array == NULL) { Py_XDECREF(PI_array); Py_XDECREF(X_array); Py_XDECREF(ePI_array); Py_XDECREF(eX_array); return NULL; } labs = (int)PyArray_DIM(PI_array, 1); n_pool = (int)PyArray_DIM(X_array, 0); dims = (int)PyArray_DIM(X_array, 1); double **PI = (double**) malloc(n_pool * sizeof(double*)); double **X = (double**) malloc(n_pool * sizeof(double*)); for(int i=0; i<n_pool; i++){ PI[i] = (double*) malloc(labs * sizeof(double)); X[i] = (double*) malloc(dims * sizeof(double)); } for(int i=0; i<n_pool; i++){ for(int j=0; j<labs; j++){ PI[i][j] = *(double*)PyArray_GETPTR2(PI_array, i, j); } for(int j=0; j<dims; j++){ X[i][j] = *(double*)PyArray_GETPTR2(X_array, i, j); } } double *ePI = (double*) PyArray_DATA(ePI_array); double *eX = (double*) PyArray_DATA(eX_array); double **retF = Fisher(ePI, eX, sigma, labs, dims); double **retA = A(PI, X, labs, dims, n_pool); pinv(retF, labs, dims); /* calculates the trace of the multiply of pinv(F) and A */ double score = 0.0; for(int i=0; i<dims*labs; i++){ for(int k=0; k<dims*labs; k++){ score += retA[i][k] * retF[k][i]; } } Py_DECREF(PI_array); Py_DECREF(X_array); Py_DECREF(ePI_array); Py_DECREF(eX_array); PyObject* ret = Py_BuildValue("d", score); for(int i=0; i<n_pool; i++){ free(PI[i]); free(X[i]); } free(PI); free(X); for(int i=0; i<labs*dims; i++){ free(retF[i]); free(retA[i]); } free(retF); free(retA); return ret; } double** An(double *pi, double *x, int labs, int dims){ double **g = (double**) malloc(labs*dims * sizeof(double*)); for(int i=0; i<labs*dims; i++){ g[i] = (double*) malloc(labs * sizeof(double)); memset(g[i], 0, labs * sizeof(double)); } for(int p=0; p<labs; p++) for(int i=0; i<dims; i++){ for(int c=0; c<labs; c++) if(p == c) g[p*dims + i][c] = pi[p] * (1.0-pi[p]) * x[i]; else g[p*dims + i][c] = -1.0 * pi[p] * pi[c] * x[i]; } double **an = (double**) malloc(labs*dims * sizeof(double*)); for(int i=0; i<labs*dims; i++){ an[i] = (double*) malloc(labs*dims * sizeof(double)); memset(an[i], 0, labs*dims * sizeof(double)); } for(int p=0; p<labs; p++) for(int i=0; i<dims; i++) for(int q=0; q<labs; q++) for(int j=0; j<dims; j++){ /* inner product */ double tmp = 0.0; for(int k=0; k<labs; k++){ tmp += g[p*dims + i][k] * g[q*dims + j][k]; } an[p*dims + i][q*dims + j] = tmp; } for(int i=0; i<labs*dims; i++) free(g[i]); free(g); return an; } double** A(double **PI, double **X, int labs, int dims, int n_pool){ double **ret = (double**) malloc(labs*dims * sizeof(double*)); for(int i=0; i<labs*dims; i++){ ret[i] = (double*) malloc(labs*dims * sizeof(double)); memset(ret[i], 0, labs*dims * sizeof(double)); } for(int n=0; n<n_pool; n++){ double **an = An(PI[n], X[n], labs, dims); for(int p=0; p<labs; p++) for(int i=0; i<dims; i++) for(int q=0; q<labs; q++) for(int j=0; j<dims; j++) ret[p*dims + i][q*dims + j] += an[p*dims + i][q*dims + j]; for(int i=0; i<labs*dims; i++) free(an[i]); free(an); } return ret; } double** Fisher(double *pi, double *x, double sigma, int labs, int dims){ double **ret = (double**) malloc(labs*dims * sizeof(double*)); for(int i=0; i<labs*dims; i++){ ret[i] = (double*) malloc(labs*dims * sizeof(double*)); memset(ret[i], 0, labs*dims * sizeof(double)); } for(int p=0; p<labs; p++) for(int i=0; i<dims; i++) for(int q=0; q<labs; q++) for(int j=0; j<dims; j++){ if(p == q && i == j) ret[p*dims + i][q*dims + j] = x[i]*x[i]*pi[p]*(1.0-pi[p]) + 1.0/sigma*sigma; else if(p == q && i != j) ret[p*dims + i][q*dims + j] = x[i]*x[j]*pi[p]*(1.0-pi[p]); else ret[p*dims + i][q*dims + j] = x[i]*x[j]*pi[p]*pi[q]; } return ret; }
{ "alphanum_fraction": 0.5190947666, "avg_line_length": 31.6931034483, "ext": "c", "hexsha": "85a3e9f6f0921ad68f037dfa3f004477526f0cf8", "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": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "crowdEEG/libact", "max_forks_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "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": "crowdEEG/libact", "max_issues_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_line_length": 106, "max_stars_count": 3, "max_stars_repo_head_hexsha": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "crowdEEG/libact", "max_stars_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_stars_repo_stars_event_max_datetime": "2021-10-18T11:16:02.000Z", "max_stars_repo_stars_event_min_datetime": "2017-11-23T05:56:38.000Z", "num_tokens": 2871, "size": 9191 }
/* specfunc/test_dilog.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" int test_dilog(void) { gsl_sf_result r; gsl_sf_result r1, r2; int s = 0; /* real dilog */ TEST_SF(s, gsl_sf_dilog_e, (-3.0, &r), -1.9393754207667089531, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (-0.5, &r), -0.4484142069236462024, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (-0.001, &r), -0.0009997501110486510834, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (0.1, &r), 0.1026177910993911, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (0.7, &r), 0.8893776242860387386, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (1.0, &r), 1.6449340668482260, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (1.5, &r), 2.3743952702724802007, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (2.0, &r), 2.4674011002723397, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, ( 5.0, &r), 1.7837191612666306277, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, ( 11.0, &r), 0.3218540439999117111, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (12.59, &r), 0.0010060918167266208634, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (12.595, &r), 0.00003314826006436236810, TEST_TOL5, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (13.0, &r), -0.07806971248458575855, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (20.0, &r), -1.2479770861745251168, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (150.0, &r), -9.270042702348657270, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_dilog_e, (1100.0, &r), -21.232504073931749553, TEST_TOL0, GSL_SUCCESS); /* complex dilog */ /* FIXME: probably need more tests here... * also need to work on accuracy for r->1; need to * adjust the switch-over point I suppose. */ TEST_SF_2(s, gsl_sf_complex_dilog_e, (1.00001, M_PI/2.0, &r1, &r2), -0.20562022409960237363, TEST_TOL1, 0.91597344814458309320, TEST_TOL1, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.99999, M_PI/2.0, &r1, &r2), -0.20561329262779687646, TEST_TOL0, 0.91595774018131512060, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.991, M_PI/2.0, &r1, &r2), -0.20250384721077806127, TEST_TOL0, 0.90888544355846447810, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.98, M_PI/2.0, &r1, &r2), -0.19871638377785918403, TEST_TOL2, 0.90020045882981847610, TEST_TOL2, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.95, M_PI/2.0, &r1, &r2), -0.18848636456893572091, TEST_TOL1, 0.87633754133420277830, TEST_TOL1, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.8, M_PI/2.0, &r1, &r2), -0.13980800855429037810, TEST_TOL0, 0.75310609092419884460, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.5, M_PI/2.0, &r1, &r2), -0.05897507442156586346, TEST_TOL0, 0.48722235829452235710, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.01, M_PI/2.0, &r1, &r2), -0.000024999375027776215378, TEST_TOL3, 0.009999888892888684820, TEST_TOL3, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (10.0, M_PI/2.0, &r1, &r2), -3.0596887943287347304, TEST_TOL0, 3.7167814930680685900, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (100.0, M_PI/2.0, &r1, &r2), -11.015004738293824854, TEST_TOL0, 7.2437843013083534970, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.99, M_PI/8.0, &r1, &r2), 1.0571539648820244720, TEST_TOL0, 0.7469145254610851318, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.99, M_PI/64.0, &r1, &r2), 1.5381800285902999666, TEST_TOL0, 0.1825271634987756651, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_complex_dilog_e, (0.9, 3.0*M_PI/4.0, &r1, &r2), -0.6062840301356530985, TEST_TOL1, 0.4836632833122775721, TEST_TOL1, GSL_SUCCESS); return s; }
{ "alphanum_fraction": 0.6645890144, "avg_line_length": 40.109375, "ext": "c", "hexsha": "d1ff3fdd1f866d6e46f0c4bec74b79a963018d09", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/test_dilog.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/test_dilog.c", "max_line_length": 95, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/test_dilog.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": 1903, "size": 5134 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_vector_double.h> #ifndef UTILS_H #define UTILS_H #define max int get_nlines(char *); void print_gsl_vector(gsl_vector *); void print_intarray(int *, int); gsl_vector *vector_sub(gsl_vector *, gsl_vector *); double vector_dist(gsl_vector *, gsl_vector *); gsl_vector **load_vectors_from_file(char *, int); int **permutations(int); int factorial(int); double min(double, double); void crit_err(char *); #endif
{ "alphanum_fraction": 0.7537473233, "avg_line_length": 23.35, "ext": "h", "hexsha": "78f3c64e0f41f04de8919e52b8f6a8bc7aacc6b3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kjchalup/algorithm_design", "max_forks_repo_path": "skiena/utils/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kjchalup/algorithm_design", "max_issues_repo_path": "skiena/utils/utils.h", "max_line_length": 51, "max_stars_count": null, "max_stars_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kjchalup/algorithm_design", "max_stars_repo_path": "skiena/utils/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 114, "size": 467 }
#ifndef REACHOBJMULTIDEMO_H #define REACHOBJMULTIDEMO_H #include <cstdlib> #include <ctime> #include <vector> #include <yarp/sig/all.h> #include <yarp/os/all.h> #include <yarp/dev/all.h> #include <yarp/math/Math.h> #include <iCub/iKin/iKinFwd.h> #include <iCub/ctrl/math.h> #include <gsl/gsl_math.h> #include "reachObjMultiDemo_IDL.h" class reachObjMultiDemo : public yarp::os::RFModule, public reachObjMultiDemo_IDL { protected: yarp::os::RpcServer rpcPort; yarp::dev::IPositionControl* posArm; yarp::dev::IVelocityControl* velArm; yarp::dev::ITorqueControl * itrqArm; yarp::dev::IEncoders* encsArm; yarp::dev::IControlMode* iCtrlArm; yarp::dev::IControlLimits* iCtrlLimArm; yarp::dev::IPositionControl* posRightArm; yarp::dev::IVelocityControl* velRightArm; yarp::dev::ITorqueControl* itrqRightArm; yarp::dev::IEncoders* encsRightArm; yarp::dev::IControlMode* iCtrlRightArm; yarp::dev::IControlLimits* iCtrlLimRightArm; yarp::dev::IPositionControl* posTorso; yarp::dev::IVelocityControl* velTorso; yarp::dev::ITorqueControl* itrqTorso; yarp::dev::IEncoders* encsTorso; yarp::dev::IControlMode* iCtrlTorso; yarp::dev::IControlLimits* iCtrlLimTorso; iCub::iKin::iCubArm* arm; yarp::sig::Vector qA; yarp::dev::IGazeControl* igaze; int contextGaze; yarp::dev::ICartesianControl *iCartCtrlR; yarp::dev::ICartesianControl *iCartCtrl; yarp::dev::PolyDriver torsoDev; yarp::dev::PolyDriver rightArmDev; yarp::dev::PolyDriver headDev; yarp::dev::PolyDriver rightCartDev; yarp::sig::Vector encodersRightArm; yarp::sig::Vector encodersTorso; std::string part; //!< Should be "left_arm" or "right_arm" std::string robot; //!< Should be "icub" or "icubSim" double period; std::string name; bool changeTipFrame; //!< bool useFakeTarget; bool useHandAngle; yarp::sig::Vector fakeTarget; double tiltAngle, yawAngle; yarp::sig::Vector new_command_arm; yarp::sig::Vector new_command_head; double start_command_arm[16]; //!< Start command for the 16 arm joints double away_command_arm[16]; //!< Away command for the 16 arm joints yarp::sig::Vector start_command_head; //!< Target for head in start position double neck_range_min[3]; double neck_range_max[3]; double minLimArm[16]; double maxLimArm[16]; bool hasCommand; bool hasTarget; yarp::os::BufferedPort<yarp::os::Bottle> cmdJointsPort; yarp::os::Bottle *cmdJointsBottle; yarp::sig::Vector cmdJointsAng; yarp::os::BufferedPort<yarp::os::Bottle> objPosDimPort; yarp::os::Bottle *objPoseDimBottle; yarp::sig::Vector objPoseDim; yarp::os::BufferedPort<yarp::os::Bottle> tactilePort; yarp::os::Bottle *tactileBottle; yarp::os::BufferedPort<yarp::os::Bottle> targetDumpedData; //!< buffered port of dumped target data yarp::os::Stamp ts; yarp::sig::Vector joints_arm_min, joints_arm_max; yarp::os::RpcClient rpcToMotorBabbling; yarp::os::RpcClient rpcToLearning; bool init_right_arm(); //!< Create PolyDriver for left arm bool initRobot(); // bool moveHeadToStartPos(bool ranPos); bool moveHeadToCentralPos(); bool moveArmToStartPos(const std::string &partName); bool moveArmAway(const std::string &partName); bool gotoStartPos(bool moveAway); bool reachTarget(); void updateArmChain(const yarp::sig::Vector &q, yarp::sig::Vector &xEE_t); bool sendCmdBabbling(); bool sendCmdLearningPredict(); bool sendCmdLearningMove(const int &id, const std::string &partName); std::vector<int> reprTaxelsForearm_sim = {3, 15, 27, 39, 51, 75, 87, 183, 207, 255, 291, 303, 315, 339, 351}; //23 taxels std::vector<int> reprTaxelsHandL = {3, 15, 27, 39, 51, 99, 101, 109, 122, 134}; std::vector<int> reprTaxelsHandR = {3, 15, 39, 51, 101, 118, 137}; public: bool configure(yarp::os::ResourceFinder &rf); bool interruptModule(); bool close(); bool attach(yarp::os::RpcServer &source); double getPeriod(); bool updateModule(); // reachBallDemo(); //Thrift bool home_arms() { bool ok = false; // ok = moveArmToStartPos("left"); ok = moveArmToStartPos("right"); if (ok) yDebug("[%s] Moved all arms home sucessfully!!",name.c_str()); else yDebug("[%s] Failed moving all arms home!!",name.c_str()); return ok; } bool home_all() { bool ok = false; ok = moveHeadToCentralPos(); ok = ok & home_arms(); if (ok) yDebug("[%s] Moved all parts home sucessfully!!",name.c_str()); else yDebug("[%s] Failed moving all parts home!!",name.c_str()); return ok; } bool reach(bool _useCalib) { yDebug("[%s] Start reaching the target",name.c_str()); hasCommand = true; // if (hasTarget) // return reachTarget(); // else // { // yWarning("[%s] No target", name.c_str()); // return false; // } } bool babble_then_reach(int32_t _id, const std::string &_part) { bool ok = sendCmdBabbling(); yarp::os::Time::delay(3); ok = ok & sendCmdLearningPredict(); yarp::os::Time::delay(1); if (_id==-1) // reach all taxel of part { // if (_part=="b" or _part=="both") // { // for (int i=0; i<=reprTaxelsHandR.size(); i++) // { // sendCmdLearningMove(reprTaxelsHandR[i], "h"); // } // } // else if (_part=="h" or _part=="hand") // { // } // else if (_part=="a" or _part=="arm") // { // } } else ok = ok & sendCmdLearningMove(_id,_part); return ok; } bool set_tilt_angle(const double _ang) { tiltAngle = _ang; return true; } double get_tilt_angle() { return tiltAngle; } bool set_yaw_angle(const double _ang) { yawAngle = _ang; return true; } double get_yaw_angle() { return yawAngle; } bool enable_hand_angle() { useHandAngle = true; return true; } bool disable_hand_angle() { useHandAngle = false; return true; } }; #endif // REACHBALLDEMO_H
{ "alphanum_fraction": 0.5487484442, "avg_line_length": 29.1572580645, "ext": "h", "hexsha": "82b027f4ebe908cf6612325d37bde4ba02efbcfe", "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": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "robotology/visuomotor-learning", "max_forks_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "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": "robotology/visuomotor-learning", "max_issues_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_line_length": 118, "max_stars_count": 2, "max_stars_repo_head_hexsha": "d9e3919b8ff69ea9e4652ee882f323d5786b74af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "robotology/visuomotor-learning", "max_stars_repo_path": "modules/reachObjMultiDemo/reachObjMultiDemo.h", "max_stars_repo_stars_event_max_datetime": "2021-04-16T11:38:25.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-01T16:04:51.000Z", "num_tokens": 1983, "size": 7231 }
/* * Copyright 2008-2016 Jan Gasthaus * * 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 RANDOM_H_ #define RANDOM_H_ #include <gsl/gsl_rng.h> #include <vector> #include <cassert> #include <algorithm> // for lower_bound // only for debugging #include <iostream> #include "libplump/utils.h" namespace gatsby { namespace libplump { /******************************************************************************* * RANDOM NUMBER GENERATION AND SAMPLING BASED ON GSL ******************************************************************************/ /** * Initialize global RNG. * * This function has to be called before using any of the sampling functions. * * The RNG type and seed are determined by the environment variables * GSL_RNG_TYPE and GSL_RNG_SEED. */ void init_rng(); /** * Free the global RNG. */ void free_rng(); /** * Returns true with probability true_prob. */ bool coin(double true_prob); /** * Returns a uniform integer between 0 and max-1. */ long int uniform_int(long int max); /** * Sample from a discrete distribution on 0,...,MAX with the given PDF. * * The probability if returning x for x \in 0,...,MAX is given by * pdf[x] / (\sum_{i=0,...,end_pos} pdf[i]) * i.e. pdf is normalized so that the sum of all elements up to and including * element end_pos is 1. * * Algorithm: * 1) Compute CDF; normalizing constant Z = CDF[end_pos] * 2) Sample z ~ Uniform(0,Z) * 3) find the smallest element x of CDF that is larger than i using binary * search * 4) return x * * Complexity: O(log MAX) */ int sample_unnormalized_pdf(std::vector<double> pdf, int end_pos = 0); //////////////////////////////////////////////////////////////////////////////// ////////////////////// INLINE FUNCTION DEFINITIONS //////////////////////// //////////////////////////////////////////////////////////////////////////////// extern gsl_rng* global_rng; /** * Returns true with probability true_prob. */ inline bool coin(double true_prob) { return (true_prob>gsl_rng_uniform(global_rng)); } /** * Returns a uniform integer between 0 and max-1. */ inline long int uniform_int(long int max) { return gsl_rng_uniform_int(global_rng, max); } /** * Sample from a discrete distribution on 0,...,MAX with the given PDF. * * The probability if returning x for x \in 0,...,MAX is given by * pdf[x] / (\sum_{i=0,...,end_pos} pdf[i]) * i.e. pdf is normalized so that the sum of all elements up to and including * element end_pos is 1. * * Algorithm: * 1) Compute CDF; normalizing constant Z = CDF[end_pos] * 2) Sample z ~ Uniform(0,Z) * 3) find the smallest element x of CDF that is larger than i using binary * search * 4) return x * * Complexity: O(log MAX) */ inline int sample_unnormalized_pdf(std::vector<double> pdf, int end_pos) { assert(pdf.size() > 0); assert(end_pos < pdf.size()); assert(end_pos >= 0); // if end_pos == 0, use entire vector if (end_pos == 0) { end_pos = pdf.size()-1; } // compute CDF (inplace) for (int i = 0; i < end_pos; ++i) { assert(pdf[i] >= 0); pdf[i+1] += pdf[i]; } assert(pdf[end_pos] > 0); // sample pos ~ Unigorm(0,Z) double z = gsl_rng_uniform_pos(global_rng)*pdf[end_pos]; assert((z >= 0) && (z <= pdf[end_pos])); // Perform binary search for z using std::lower_bound. // lower_bound(begin, end, x) returns the first element within [begin,end) // that is equal or larger than x. int x = std::lower_bound(pdf.begin(), pdf.begin() + end_pos + 1, z) - pdf.begin(); assert(x == 0 || pdf[x-1] != pdf[x]); assert(x < pdf.size()); return x; } } } // namespace gatsby::libplump #endif // RANDOM_H_
{ "alphanum_fraction": 0.6015898995, "avg_line_length": 27.4166666667, "ext": "h", "hexsha": "f9d9d0cab5c76c71013fff9806ff905eac87370e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z", "max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jgasthaus/libPLUMP", "max_forks_repo_path": "src/libplump/random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "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": "jgasthaus/libPLUMP", "max_issues_repo_path": "src/libplump/random.h", "max_line_length": 80, "max_stars_count": 13, "max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jgasthaus/libPLUMP", "max_stars_repo_path": "src/libplump/random.h", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z", "num_tokens": 1045, "size": 4277 }
#ifndef TEST_COMMAND_INCLUDE #define TEST_COMMAND_INCLUDE #include <memory> #include <string> #include <vector> #include <gsl/gsl> #include "statement.h" #include "yaml.h" namespace execHelper { namespace test { namespace baseUtils { using CommandKey = std::string; using CommandKeys = std::vector<CommandKey>; using Statements = std::vector<std::shared_ptr<Statement>>; class TestCommand { public: TestCommand(CommandKey commandKey, Statements initialStatements = {}) noexcept; std::shared_ptr<Statement> operator[](size_t index) const noexcept; Statements::const_iterator begin() const noexcept; Statements::const_iterator end() const noexcept; size_t size() const noexcept; std::string get() const noexcept; unsigned int getNbOfStatements() const noexcept; unsigned int getNumberOfStatementExecutions() const noexcept; // Returns the sum of executions of all statements void add(std::shared_ptr<Statement> statement) noexcept; void resetExecutions() noexcept; void write(gsl::not_null<YamlWriter*> yaml) const noexcept; private: std::string m_command; Statements m_statements; }; using Commands = std::vector<TestCommand>; template <typename T, typename... Args> inline std::shared_ptr<Statement> createStatement(Args... args) noexcept { return std::static_pointer_cast<Statement>(std::make_shared<T>(args...)); } } // namespace baseUtils } // namespace test } // namespace execHelper #endif /* TEST_COMMAND_INCLUDE */
{ "alphanum_fraction": 0.7338603426, "avg_line_length": 27.6, "ext": "h", "hexsha": "9a66d64882016e7c9aca631b2c47496cd1071a4f", "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/base-utils/include/base-utils/testCommand.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/base-utils/include/base-utils/testCommand.h", "max_line_length": 77, "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/base-utils/include/base-utils/testCommand.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": 329, "size": 1518 }
/* * Copyright 2017 Daniel Eachern Huang * * 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 AUGUR_MCMCLIB_H #define AUGUR_MCMCLIB_H #include "augur_util.h" #include "augur_math.h" #include "augur_vecop.h" #include "augur_blkop.h" #include "augur_blkstk.h" #include "augur_dist.h" #include <augur_iface.h> #include <math.h> #include <gsl/gsl_rng.h> typedef struct mcmc { AugurMod_t curr; AugurMod_t prop; AugurAux_t aux; int accept; double currLL; double propLL; double eps; double L; double leapLen; double deltaMax; int nutsalloc; } mcmc_t; mcmc_t MCMC; gsl_rng* h_rng; void dump_state(mcmc_t state) { printf("currLL: %f\n", state.currLL); printf("propLL: %f\n", state.propLL); printf("eps: %f\n", state.eps); printf("leapLen: %f\n", state.leapLen); printf("L: %f\n", state.L); } // double modObjFn(AugurMod_t curr, AugurAux_t aux); EXTERNC void mcmcStep(); /* void acceptAlways() { MCMC.currLL = modObjFn(MCMC.curr, MCMC.aux); } */ /** * Returns TRUE if we should accept, FALSE if we should reject. */ Bool_t augur_mcmc_ar( double auxll , double (*objFn)(AugurAux_t, AugurMod_t) ) { double currll = objFn(MCMC.aux, MCMC.curr); double propll = objFn(MCMC.aux, MCMC.prop); double u = gsl_rng_uniform(h_rng); if (augur_log(u) < propll - currll + auxll) { return TRUE; } else { return FALSE; } } /** * Returns TRUE if we should accept, FALSE if we should reject. */ __HOSTORDEV__ Bool_t augur_mcmc_ar_idx ( double auxll , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , double (*objFn)(AugurAux_t, AugurMod_t) ) { double currll = objFn(aux, curr); double propll = objFn(aux, prop); // double u = gsl_rng_uniform(h_rng); double u = augur_std_uniform_sample(aux.rng); if (augur_log(u) < propll - currll + auxll) { return TRUE; } else { return FALSE; } } int acceptReject(double auxLL, double (*objFn)(AugurAux_t, AugurMod_t)) { MCMC.propLL = objFn(MCMC.aux, MCMC.prop); double u = gsl_rng_uniform(h_rng); // printf("currLL: %f propLL: %f auxLL: %f ar: %d\n", MCMC.currLL, MCMC.propLL, auxLL, log(u) < MCMC.propLL - MCMC.currLL + auxLL); if (log(u) < MCMC.propLL - MCMC.currLL + auxLL) { MCMC.accept += 1; AugurMod_t tmp = MCMC.curr; MCMC.curr = MCMC.prop; MCMC.prop = tmp; // double tmp2 = MCMC.currLL; MCMC.currLL = MCMC.propLL; // MCMC.propLL = tmp2; return 1; } else { return 0; } } void swapCurrProp(double (*objFn)(AugurAux_t, AugurMod_t)) { MCMC.propLL = objFn(MCMC.aux, MCMC.prop); AugurMod_t tmp = MCMC.curr; MCMC.curr = MCMC.prop; MCMC.prop = tmp; double tmp2 = MCMC.currLL; MCMC.currLL = MCMC.propLL; MCMC.propLL = tmp2; } void initMcmc() { const gsl_rng_type * T; gsl_rng_env_setup(); T = gsl_rng_default; h_rng = gsl_rng_alloc (T); // MCMC.curr = curr; // MCMC.prop = prop; // MCMC.aux = aux; MCMC.accept = 0; // MCMC.currLL = objFn(MCMC.aux, MCMC.curr); MCMC.propLL = MCMC.currLL; MCMC.eps = 1.0; MCMC.L = 20; MCMC.leapLen = 10.0; MCMC.deltaMax = 1000.0; MCMC.nutsalloc = 0; return; } EXTERNC void setHmcParams(double eps, double leapLen) { MCMC.eps = eps; MCMC.leapLen = leapLen; } EXTERNC void setHmcParams2(double eps, int L) { MCMC.eps = eps; MCMC.L = L; } #define max(x, y) ( x < y ? y : x) double h_sample_uniform(gsl_rng* rng, double left, double right) { double u = gsl_rng_uniform(rng); return left + u * (right - left); } /** * Metropololis-within-gibbs Kernel. (Note it is host/dev code) */ __HOSTORDEV__ void augur_mcmc_mwg ( AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , double* llCorrect , void (*proposal)(AugurAux_t, AugurMod_t, AugurMod_t) , void (*swap)(AugurAux_t, AugurMod_t, AugurMod_t, int) , double (*objFn)(AugurAux_t, AugurMod_t) ) { proposal(aux, curr, prop); if (augur_mcmc_ar_idx(*llCorrect, aux, curr, prop, objFn)) { // Accept, so copy proposal theta into current theta (maintain invariant) swap(aux, curr, prop, 0); } else { // Reject, so copy current theta into proposal theta (maintain invariant) swap(aux, curr, prop, 1); } } /** * Gradient checking. (Call from host code) */ void h_augur_chk_grad ( AugurMemLoc_t loc, AugurBlk_t* pt, AugurBlk_t* grad , AugurAux_t aux, AugurMod_t curr , double (*objFn)(AugurAux_t, AugurMod_t) ) { double eps = 10e-8; printf("Evaluating gradient at point:\n"); h_augur_blk_dump(loc, pt); for (uint_t i = 0; i < pt->num_blks; i++) { switch (pt->typs[i]) { case AUGUR_DBL: { // TODO break; } case AUGUR_VEC: { AugurFlatVec_t* fvec = (AugurFlatVec_t*) pt->blks[i]; for (int j = 0; j < fvec->base_elems; j++) { h_augur_flat_vec_basis_add(loc, fvec, j, eps); double plus = objFn(aux, curr); h_augur_flat_vec_basis_add(loc, fvec, j, -2.0 * eps); double minus = objFn(aux, curr); double fin_diff = (plus - minus) / (2.0 * eps); double ad; h_augur_flat_vec_getd_idx(loc, &ad, (AugurFlatVec_t*) (grad->blks[i]), j); printf("plus: %f, minus: %f\n", plus, minus); printf("auto-diff: %f, finite-diff: %f, error: %f\n", ad, fin_diff, ad - fin_diff); h_augur_flat_vec_basis_add(loc, fvec, j, eps); } break; } case AUGUR_MAT: { AugurMat_t* mat = (AugurMat_t*) pt->blks[i]; for (int j = 0; j < mat->row * mat->col; j++) { h_augur_mat_basis_add(loc, mat, j, eps); double plus = objFn(aux, curr); h_augur_mat_basis_add(loc, mat, j, -2.0 * eps); double minus = objFn(aux, curr); double fin_diff = (plus - minus) / (2.0 * eps); double ad; h_augur_mat_getd_idx(loc, &ad, (AugurMat_t*) (grad->blks[i]), j); printf("auto-diff: %f, finite-diff: %f, error: %f\n", ad, fin_diff, ad - fin_diff); h_augur_mat_basis_add(loc, mat, j, eps); } break; } default: { // TODO break; } } } } /** * Calls a gradient function. (Call from host code) * * The struct curr contains "the point" we are evaluating gradfn at. * The result of the gradient computation is in grad, which is part of * the struct aux. */ void h_augur_mcmc_call_grad ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t curr , AugurBlk_t* grad , void (*gradfn)(AugurAux_t, AugurMod_t) ) { h_augur_blk_zero(loc, grad); gradfn(aux, curr); } /** * The struct curr contains pt, "the point" we are evaluating gradfn at. */ void h_augur_mcmc_chkcall_grad ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t curr , AugurBlk_t* grad , void (*gradfn)(AugurAux_t, AugurMod_t) , AugurBlk_t* pt , double (*objfn) (AugurAux_t, AugurMod_t) , Bool_t f_chkgrad ) { h_augur_mcmc_call_grad(loc, aux, curr, grad, gradfn); if (f_chkgrad) { h_augur_chk_grad(loc, pt, grad, aux, curr, objfn); } } /** * Leapfrog simulation. (Call from host code) * * Leapfrog with (POSITIVE) gradient of log-likelihood of objfn. * (Signs are important!!) * * theta0 / thetaStar: initial / proposal point * grad: result of gradient * p0 / pStar: initial / proposal momentum * * mod.thetaStar = thetaStar * aux.grad = grad * * gradfn(aux, mod) evaluates gradient at thetaStar, putting result in grad * */ void h_augur_mcmc_leapfrog1 ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t mod , AugurBlk_t* grad, AugurBlk_t* thetaStar, AugurBlk_t* pStar , void (*gradfn)(AugurAux_t, AugurMod_t) , double stepsize ) { // Simulate Hamiltonian dynamics first half step of momentum // pStar = p0 + stepsize / 2.0 * d_like(x, thetaStar) h_augur_mcmc_call_grad(loc, aux, mod, grad, gradfn); h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad); // Full step for position // Position: thetaStar = thetaStar + stepsize * pStar h_augur_blk_scale_plus(loc, thetaStar, thetaStar, stepsize, pStar); // Simulate last half step of momentum // pStar = pStar + stepsize / 2.0 * d_like(x, thetaStar) h_augur_mcmc_call_grad(loc, aux, mod, grad, gradfn); h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad); } /** * Leapfrog simulation. (Call from host code) * * Leapfrog with (POSITIVE) gradient of log-likelihood of objfn. * (Signs are important!!) * * theta0 / thetaStar: initial / proposal point * grad: result of gradient * p0 / pStar: initial / proposal momentum * * curr.theta0 = theta0, prop.theta0 = thetaStar, aux.grad = grad * * gradfn(aux, curr) evaluates gradient at theta0, putting result in grad * gradfn(aux, prop) evaluates gradient at thetaStar, putting result in grad * */ void h_augur_mcmc_leapfrog ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , AugurBlk_t* theta0, AugurBlk_t* thetaStar , AugurBlk_t* grad, AugurBlk_t* p0, AugurBlk_t* pStar , void (*gradfn)(AugurAux_t, AugurMod_t) , double (*objfn) (AugurAux_t, AugurMod_t) , double stepsize, int simsteps ) { // Simulate Hamiltonian dynamics first half step of momentum // pStar = p0 + stepsize / 2.0 * d_like(x, theta0) h_augur_mcmc_call_grad(loc, aux, curr, grad, gradfn); h_augur_blk_scale_plus(loc, pStar, p0, stepsize / 2.0, grad); // Simulate full steps for (uint_t l = 0; l < simsteps; l++) { // Full step for position // Position: thetaStar = thetaStar + stepsize * pStar h_augur_blk_scale_plus(loc, thetaStar, thetaStar, stepsize, pStar); // Move momentum except at last step if (l != simsteps-1) { // Momentum: pStar = pStar + stepsize * d_like(x, thetaStar) h_augur_mcmc_call_grad(loc, aux, prop, grad, gradfn); h_augur_blk_scale_plus(loc, pStar, pStar, stepsize, grad); } } // Simulate last half step of momentum // pStar = pStar + stepsize / 2.0 * d_like(x, thetaStar) h_augur_mcmc_call_grad(loc, aux, prop, grad, gradfn); h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad); } /** * Hamiltonian Monte Carlo Kernel. (Call from host code) * * Suppose this kernel moves blk = [p_1, .., p_n]. * Then we have the following equalities on the inputs: * * curr.blk = theta0 * prop.blk = thetaStar * * For compositionality, we maintain the invariant that: * curr.blk = prop.blk */ void h_augur_mcmc_hmc ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , AugurBlk_t* theta0, AugurBlk_t* thetaStar , AugurBlk_t* grad, AugurBlk_t* p0, AugurBlk_t* pStar , double simlen, double eps , void (*computeGrad)(AugurAux_t, AugurMod_t) , double (*objFn)(AugurAux_t, AugurMod_t) ) { // Initialize momentum h_augur_blk_randn(aux.rng, p0); // Randomize simsteps double scale_eps = h_augur_uniform_sample(h_rng, 0.8, 1.2); double stepsize = scale_eps * eps; double s = h_augur_uniform_sample(h_rng, 0.9, 1.1); uint_t simsteps = augur_max(1, round(s * simlen / stepsize)); // Simulate Hamiltonian dynamics with Leapfrog method h_augur_mcmc_leapfrog(loc, aux, curr, prop, theta0, thetaStar, grad, p0, pStar, computeGrad, objFn, stepsize, simsteps); // Compute correction double initMomLL = h_augur_blk_dot(loc, p0, p0) / 2.0; double propMomLL = h_augur_blk_dot(loc, pStar, pStar) / 2.0; double auxll = initMomLL - propMomLL; // After trajectory, compute whether we should accept or reject if (augur_mcmc_ar(auxll, objFn)) { // Accept, so copy proposal theta into current theta (for invariant) h_augur_blk_cpy(loc, theta0, thetaStar); } else { // Reject, so copy current theta into proposal theta (for invariant) h_augur_blk_cpy(loc, thetaStar, theta0); } } /** * Elliptical Slice Sampling Kernel. (Note it is host/dev code) * * Suppose this kernel moves param = currTheta. * Then we have the following equalities on the inputs: * * curr.param = currTheta * prop.param = propTheta * * For compositionality, we maintain the invariant that: * curr.param = prop.param */ __HOSTORDEV__ void augur_mcmc_eslice ( AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , AugurVec_t* curr_theta, AugurVec_t* prop_theta , AugurVec_t* mean, AugurMat_t* cov , AugurMat_t* L, AugurVec_t* nu , double (*objfn)(AugurAux_t, AugurMod_t) ) { augur_mvnormal_sample(aux.rng, nu, mean, cov, L, nu); double u = augur_std_uniform_sample(aux.rng); double log_y = objfn(aux, curr) + augur_log(u); double theta = augur_uniform_sample(aux.rng, 0.0, 2.0 * AUGUR_PI); double theta_min = theta - 2.0 * AUGUR_PI; double theta_max = theta; while (TRUE) { double diff = theta_max - theta_min; if (diff < 1e-8) { // Maintain invariant that curr == prop augur_vec_cpy(prop_theta, curr_theta); break; } // propSt = (currSt - mean) * cos(theta) + (nu - mean) * sin(theta) + mean; for (uint_t i = 0; i < prop_theta->elems; i++) { double mean_i = AUGUR_VEC_GETD(mean, i); double a = (AUGUR_VEC_GETD(curr_theta, i) - mean_i) * augur_cos(theta); double b = (AUGUR_VEC_GETD(nu, i) - mean_i) * augur_sin(theta); AUGUR_VEC_SETD(prop_theta, i, a + b + mean_i); } double prop_ll = objfn(aux, prop); if (prop_ll > log_y) { // Maintain invariant that curr == prop augur_vec_cpy(curr_theta, prop_theta); break; } // Shrink bracket if (theta < 0) { theta_min = theta; } else { theta_max = theta; } theta = augur_uniform_sample(aux.rng, theta_min, theta_max); } } /** * Reflective Slice Kernel. (Call from host code) * * Suppose this kernel moves blk = [p_1, .., p_n]. * Then we have the following equalities on the inputs: * * curr.blk = theta0 * prop.blk = thetaStar * * For compositionality, we maintain the invariant that: * curr.blk = prop.blk */ void h_augur_mcmc_refl_slice ( AugurMemLoc_t loc , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , AugurBlk_t* theta0, AugurBlk_t* thetaProp , AugurBlk_t* grad, AugurBlk_t* p0 , double simlen, double eps , void (*computeGrad)(AugurAux_t, AugurMod_t) , double (*objFn)(AugurAux_t, AugurMod_t) ) { // Initialize momentum h_augur_blk_randn(aux.rng, p0); // Compute slice level double z = objFn(aux, curr) - gsl_ran_exponential(h_rng, 1.0); int cond = 0; double stepsize = eps; uint_t simsteps = augur_max(1, round(simlen / stepsize)); for (int i = 0 ; i < simsteps; i++) { // Take scaled-step in direction of momentum h_augur_blk_scale_plus(loc, thetaProp, thetaProp, stepsize, p0); cond = objFn(aux, prop) < z; if (cond) { // Reflect (outside version) if we leave slice // Compute grad at outside point h_augur_blk_zero(loc, grad); computeGrad(aux, prop); // Compute reflection and update direction double angle1 = h_augur_blk_dot(loc, p0, grad); double angle2 = h_augur_blk_dot(loc, grad, grad); double scale = angle1 / angle2; h_augur_blk_scale_plus(loc, p0, p0, -2.0 * scale, grad); } } if (!cond) { // Copy if we are in slice h_augur_blk_cpy(loc, theta0, thetaProp); } } /* NUTS */ typedef enum NutsDir { NUTS_MINUS = 0, NUTS_PLUS = 1, } NutsDir_t; typedef struct NutsRet { int n; int s; } NutsRet_t; typedef struct NutsRT { AugurBlk_t* work; AugurBlkStk_t* theta_prop_stk; AugurBlkStk_t* theta_stk; AugurBlkStk_t* mom_stk; } NutsRT_t; typedef struct NutsInfo { AugurAux_t aux; AugurMod_t mod; AugurBlk_t* grad; double (*modObjFn)(AugurAux_t, AugurMod_t); void (*computeGrad)(AugurAux_t, AugurMod_t); double stepsize; double logu; } NutsInfo_t; int h_augur_nuts_update_s(AugurMemLoc_t loc, int s, AugurBlk_t* work, AugurBlk_t* theta_plus, AugurBlk_t* mom_plus, AugurBlk_t* theta_minus, AugurBlk_t* mom_minus) { if (s == 1) { h_augur_blk_minus(loc, work, theta_plus, theta_minus); int ut1 = augur_indicator(h_augur_blk_dot(loc, work, mom_plus) >= 0.0); int ut2 = augur_indicator(h_augur_blk_dot(loc, work, mom_minus) >= 0.0); if (ut1 && ut2) { return 1; } } return 0; } /** * info.mod.theta = theta (gradient is always evaluated at latest value of theta) * * Invariants: * Suppose dir = PLUS, then: * * theta: latest value of theta^+ * mom: latest value of mom^+ */ NutsRet_t h_augur_nuts_build_tree ( AugurMemLoc_t loc, NutsInfo_t* info , NutsRT_t* rt , AugurBlk_t* shape , AugurBlk_t* theta, AugurBlk_t* mom, int j, NutsDir_t dir , int tab) { if (j == 0) { // Simulate (updates theta, mom) h_augur_mcmc_leapfrog1(loc, info->aux, info->mod, info->grad, theta, mom, info->computeGrad, info->stepsize); // Update return value augur_blk_stk_push(loc, rt->theta_prop_stk, shape, theta); // Check stopping condition NutsRet_t ret; double ll = info->modObjFn(info->aux, info->mod) - 0.5 * h_augur_blk_dot(loc, mom, mom); ret.n = augur_indicator(info->logu <= ll); ret.s = augur_indicator(info->logu < MCMC.deltaMax + ll); return ret; } else { // Build left subtree NutsRet_t left = h_augur_nuts_build_tree(loc, info, rt, shape, theta, mom, j - 1, dir, tab+2); // Build right subtree (if we should keep going) if (left.s == 1) { // Save "left"-most if (j == 1) { augur_blk_stk_push(loc, rt->theta_stk, shape, theta); augur_blk_stk_push(loc, rt->mom_stk, shape, mom); } NutsRet_t right = h_augur_nuts_build_tree(loc, info, rt, shape, theta, mom, j - 1, dir, tab+2); // Propogate proposal with probability proportional to size of subtrees AugurBlk_t* prop1 = augur_blk_stk_pop(rt->theta_prop_stk); AugurBlk_t* prop2 = augur_blk_stk_pop(rt->theta_prop_stk); double bias = ((double) right.n) / (left.n + right.n); if (h_augur_bernoulli_sample(h_rng, bias) == 0) { augur_blk_stk_push(loc, rt->theta_prop_stk, shape, prop2); } else { augur_blk_stk_push(loc, rt->theta_prop_stk, shape, prop1); } augur_blk_stk_dump(loc, rt->theta_prop_stk); // Propogate tree size left.n += right.n; // Check u-turn AugurBlk_t* theta_minus; AugurBlk_t* mom_minus; AugurBlk_t* theta_plus; AugurBlk_t* mom_plus; switch (dir) { case NUTS_MINUS: { theta_plus = augur_blk_stk_peek(rt->theta_stk); mom_plus = augur_blk_stk_peek(rt->mom_stk); theta_minus = theta; mom_minus = mom; break; } case NUTS_PLUS: { theta_minus = augur_blk_stk_peek(rt->theta_stk); mom_minus = augur_blk_stk_peek(rt->mom_stk); theta_plus = theta; mom_plus = mom; break; } } left.s = h_augur_nuts_update_s(loc, right.s, rt->work, theta_plus, mom_plus, theta_minus, mom_minus); // Pop "left"-most if (j > 1) { augur_blk_stk_pop(rt->theta_stk); augur_blk_stk_pop(rt->mom_stk); } } return left; } } /** * No-U-Turn Kernel. (Call from host code) * * Suppose this kernel moves blk = [p_1, .., p_n]. * Then we have the following equalities on the inputs: * * curr.blk = theta0 * prop.blk = thetaStar * * For compositionality, we maintain the invariant that: * curr.blk = prop.blk */ void h_augur_mcmc_nuts ( AugurMemLoc_t loc, AugurAux_t aux, AugurMod_t curr, AugurMod_t prop , AugurBlk_t* theta0, AugurBlk_t* theta_prop , AugurBlk_t* grad, AugurBlk_t* work , AugurBlk_t* theta_minus, AugurBlk_t* mom_minus , AugurBlk_t* theta_plus, AugurBlk_t* mom_plus , AugurBlk_t* shape , double stepsize , void (*computeGrad)(AugurAux_t, AugurMod_t) , double (*modObjFn)(AugurAux_t, AugurMod_t) ) { // Initialize simulation values h_augur_blk_cpy(loc, theta_minus, theta0); h_augur_blk_randn(aux.rng, mom_minus); h_augur_blk_cpy(loc, theta_plus, theta0); h_augur_blk_cpy(loc, mom_plus, mom_minus); // Initialize info NutsInfo_t info; info.aux = aux; info.mod = prop; info.grad = grad; info.modObjFn = modObjFn; info.computeGrad = computeGrad; info.logu = modObjFn(aux, curr) - 0.5 * h_augur_blk_dot(loc, mom_minus, mom_minus) - gsl_ran_exponential(h_rng, 1.0); // Initialize auxilliary nuts runtime values NutsRT_t rt; rt.work = work; AugurBlkStk_t theta_prop_stk = augur_blk_stk_stk_alloc(); AugurBlkStk_t theta_stk = augur_blk_stk_stk_alloc(); AugurBlkStk_t mom_stk = augur_blk_stk_stk_alloc(); rt.theta_prop_stk = &theta_prop_stk; rt.theta_stk = &theta_stk; rt.mom_stk = &mom_stk; int n = 1; int j = 0; int s = 1; while (TRUE) { NutsRet_t nuts_ret; augur_blk_stk_reset(rt.theta_stk); augur_blk_stk_reset(rt.mom_stk); if (h_augur_bernoulli_sample(h_rng, 0.5)) { info.stepsize = -stepsize; h_augur_blk_cpy(loc, theta_prop, theta_minus); nuts_ret = h_augur_nuts_build_tree(loc, &info, &rt, shape, theta_prop, mom_minus, j, NUTS_MINUS, 0); h_augur_blk_cpy(loc, theta_minus, theta_prop); } else { info.stepsize = stepsize; h_augur_blk_cpy(loc, theta_prop, theta_plus); nuts_ret = h_augur_nuts_build_tree(loc, &info, &rt, shape, theta_prop, mom_plus, j, NUTS_PLUS, 0); h_augur_blk_cpy(loc, theta_plus, theta_prop); } AugurBlk_t* theta_prop_p = augur_blk_stk_pop(rt.theta_prop_stk); Bool_t f_cpy = FALSE; if (nuts_ret.s == 1) { double bias = augur_min(1.0, ((double) nuts_ret.n) / n); if (h_augur_bernoulli_sample(h_rng, bias) == 1) { // Update proposal h_augur_blk_cpy(loc, theta_prop, theta_prop_p); f_cpy = TRUE; } } n += nuts_ret.n; s = h_augur_nuts_update_s(loc, nuts_ret.s, rt.work, theta_plus, mom_plus, theta_minus, mom_minus); j += 1; if (s != 1) { // Maintain invariant if (f_cpy) { h_augur_blk_cpy(loc, theta0, theta_prop); } else { h_augur_blk_cpy(loc, theta_prop, theta0); } break; } } } #endif
{ "alphanum_fraction": 0.6596188869, "avg_line_length": 28.8998716303, "ext": "h", "hexsha": "ebc916a9f95dc7fb34b02de18e6364e82688ed24", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-02-18T20:17:36.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-10T21:55:18.000Z", "max_forks_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rjnw/augurv2", "max_forks_repo_path": "cbits/augur_mcmclib.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_issues_repo_issues_event_max_datetime": "2017-09-20T19:38:00.000Z", "max_issues_repo_issues_event_min_datetime": "2017-09-20T19:18:13.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rjnw/augurv2", "max_issues_repo_path": "cbits/augur_mcmclib.h", "max_line_length": 165, "max_stars_count": 14, "max_stars_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rjnw/augurv2", "max_stars_repo_path": "cbits/augur_mcmclib.h", "max_stars_repo_stars_event_max_datetime": "2020-12-18T15:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-06T19:51:00.000Z", "num_tokens": 7335, "size": 22513 }
/* * applyForceToolFrame.h * * Created on: Sep 11, 2015 * Author: mas */ #ifndef APPLY_FORCE_TOOLFRAME_H_ #define APPLY_FORCE_TOOLFRAME_H_ #include <cmath> #include <barrett/units.h> #include <barrett/systems.h> #include <barrett/products/product_manager.h> #include <libconfig.h++> #include <barrett/detail/ca_macro.h> #include <barrett/cdlbt/calgrav.h> #include <barrett/systems/abstract/system.h> #include <barrett/systems/abstract/single_io.h> #include <barrett/systems/kinematics_base.h> #include <barrett/math/kinematics.h> #include <stdio.h> #include <iostream> #include <string> #include <cstdlib> // For std::atexit() #include <barrett/os.h> // For btsleep() #include <barrett/math.h> // For barrett::math::saturate() #include <Eigen/Dense> #include <Eigen/Core> #include <barrett/standard_main_function.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #define BARRETT_SMF_VALIDATE_ARGS #include <barrett/standard_main_function.h> using namespace barrett; using namespace systems; using systems::connect; BARRETT_UNITS_FIXED_SIZE_TYPEDEFS; template<size_t DOF> class applyForceToolFrame : public systems::System { BARRETT_UNITS_TEMPLATE_TYPEDEFS(DOF); // IO (inputs) public: Input<cp_type> CpInput; // cart pos. input Input<Eigen::Quaterniond> OrnInput; // orientation input (quaternion) Input<cf_type> FtInput; // cart force input (in tool frame) Input<ct_type> TtInput; // cart torque input (in tool frame) // IO (outputs) public: Output<cf_type> CFOutput; // output Cartesian forces (in base frame) Output<ct_type> CTOutput; // output Cartesian torque (in base frame) protected: typename Output<cf_type>::Value* cfOutputValue; typename Output<ct_type>::Value* ctOutputValue; public: cf_type computedF; // can be used to display later in the program ct_type computedT; // can be used to display later in the program public: applyForceToolFrame( const std::string& sysName = "applyForceToolFrame") : System(sysName), CpInput(this), OrnInput(this), FtInput(this) , TtInput(this) , CFOutput(this, &cfOutputValue), CTOutput(this, &ctOutputValue) { } virtual ~applyForceToolFrame() { this->mandatoryCleanUp(); } protected: cf_type cf; ct_type ct; cf_type ForceTool; ct_type TorqueTool; cp_type Xcurr; Eigen::Quaterniond OrnCurr; virtual void operate() { Xcurr = CpInput.getValue(); // current Cart. Pose OrnCurr = OrnInput.getValue(); // current tool Orientation (quaternion) ForceTool = FtInput.getValue(); // desired tool force TorqueTool = TtInput.getValue(); // desired tool torque OrnCurr.x() = - OrnCurr.x(); // wam quaternion imaginary part in negative OrnCurr.y() = - OrnCurr.y(); // wam quaternion imaginary part in negative OrnCurr.z() = - OrnCurr.z(); // wam quaternion imaginary part in negative //**************************************** // gsl_matrix* RotMat = gsl_matrix_alloc (3,3); // gsl_vector* Ft = gsl_vector_alloc(3); // Force in tool frame // gsl_vector* Tt = gsl_vector_alloc(3); // Torque in tool frame // // gsl_vector* Fb = gsl_vector_alloc(3); // Force in base frame // gsl_vector* Tb = gsl_vector_alloc(3); // Torque in base frame // // // RotMat = [ 1 - 2*( OrnCurr.y()*OrnCurr.y() + OrnCurr.z()*OrnCurr.z() ) , 2*(OrnCurr.x()*OrnCurr.y() - OrnCurr.w()*OrnCurr.z()) , 2*(OrnCurr.w()*OrnCurr.y() + OrnCurr.x()*OrnCurr.z()) ; // // 2*(OrnCurr.x()*OrnCurr.y() + OrnCurr.w()*OrnCurr.z()) , 1 - 2*(OrnCurr.x()^2 + OrnCurr.z()^2) , 2*(OrnCurr.y()*OrnCurr.z() - OrnCurr.w()*OrnCurr.x()) ; // // 2*(OrnCurr.x()*OrnCurr.z() - OrnCurr.w()*OrnCurr.y()) , 2*(OrnCurr.w()*OrnCurr.x() + OrnCurr.y()*OrnCurr.z()) , 1 - 2*(OrnCurr.x()^2 + OrnCurr.y()^2) ] ; // // gsl_matrix_set(RotMat, 0 , 0 , 1 - 2*(OrnCurr.y()*OrnCurr.y() + OrnCurr.z()*OrnCurr.z()) ); // gsl_matrix_set(RotMat, 0 , 1 , 2*(OrnCurr.x()*OrnCurr.y() - OrnCurr.w()*OrnCurr.z()) ); // gsl_matrix_set(RotMat, 0 , 2 , 2*(OrnCurr.w()*OrnCurr.y() + OrnCurr.x()*OrnCurr.z()) ); // // gsl_matrix_set(RotMat, 1 , 0 , 2*(OrnCurr.x()*OrnCurr.y() + OrnCurr.w()*OrnCurr.z()) ); // gsl_matrix_set(RotMat, 1 , 1 , 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.z()*OrnCurr.z()) ); // gsl_matrix_set(RotMat, 1 , 2 , 2*(OrnCurr.y()*OrnCurr.z() - OrnCurr.w()*OrnCurr.x()) ); // // gsl_matrix_set(RotMat, 2 , 0 , 2*(OrnCurr.x()*OrnCurr.z() - OrnCurr.w()*OrnCurr.y()) ); // gsl_matrix_set(RotMat, 2 , 1 , 2*(OrnCurr.w()*OrnCurr.x() + OrnCurr.y()*OrnCurr.z()) ); // gsl_matrix_set(RotMat, 2 , 2 , 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.y()*OrnCurr.y()) ); // // // // for (int i = 0; i<3 ; i++) // { // gsl_vector_set (Ft , i , ForceTool[i] ) ; // gsl_vector_set (Tt , i , TorqueTool[i] ) ; // } // // gsl_blas_dgemv(CblasNoTrans, 1.0, RotMat, Ft, 0.0, Fb); // Fb = 1.0 * RotMat * Ft + 0.0 // gsl_blas_dgemv(CblasNoTrans, 1.0, RotMat, Tt, 0.0, Tb); // Tb = 1.0 * RotMat * Tt + 0.0 // // for (int i = 0; i<3 ; i++) // { // cf[i] = gsl_vector_get ( Fb , i ); // ct[i] = gsl_vector_get ( Tb , i ); // } //**************************************** cf[0] = ( 1 - 2*(OrnCurr.y()*OrnCurr.y() + OrnCurr.z()*OrnCurr.z()) ) * ForceTool[0] + ( 2*(OrnCurr.x()*OrnCurr.y() - OrnCurr.w()*OrnCurr.z()) ) * ForceTool[1] + ( 2*(OrnCurr.w()*OrnCurr.y() + OrnCurr.x()*OrnCurr.z()) ) * ForceTool[2] ; cf[1] = ( 2*(OrnCurr.x()*OrnCurr.y() + OrnCurr.w()*OrnCurr.z()) ) * ForceTool[0] + ( 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.z()*OrnCurr.z()) ) * ForceTool[1] + ( 2*(OrnCurr.y()*OrnCurr.z() - OrnCurr.w()*OrnCurr.x()) ) * ForceTool[2] ; cf[2] = ( 2*(OrnCurr.x()*OrnCurr.z() - OrnCurr.w()*OrnCurr.y()) ) * ForceTool[0] + ( 2*(OrnCurr.w()*OrnCurr.x() + OrnCurr.y()*OrnCurr.z()) ) * ForceTool[1] + ( 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.y()*OrnCurr.y()) ) * ForceTool[2] ; //**************************************** ct[0] = ( 1 - 2*(OrnCurr.y()*OrnCurr.y() + OrnCurr.z()*OrnCurr.z()) ) * TorqueTool[0] + ( 2*(OrnCurr.x()*OrnCurr.y() - OrnCurr.w()*OrnCurr.z()) ) * TorqueTool[1] + ( 2*(OrnCurr.w()*OrnCurr.y() + OrnCurr.x()*OrnCurr.z()) ) * TorqueTool[2] ; ct[1] = ( 2*(OrnCurr.x()*OrnCurr.y() + OrnCurr.w()*OrnCurr.z()) ) * TorqueTool[0] + ( 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.z()*OrnCurr.z()) ) * TorqueTool[1] + ( 2*(OrnCurr.y()*OrnCurr.z() - OrnCurr.w()*OrnCurr.x()) ) * TorqueTool[2] ; ct[2] = ( 2*(OrnCurr.x()*OrnCurr.z() - OrnCurr.w()*OrnCurr.y()) ) * TorqueTool[0] + ( 2*(OrnCurr.w()*OrnCurr.x() + OrnCurr.y()*OrnCurr.z()) ) * TorqueTool[1] + ( 1 - 2*(OrnCurr.x()*OrnCurr.x() + OrnCurr.y()*OrnCurr.y()) ) * TorqueTool[2] ; //**************************************** computedF = cf; computedT = ct; cfOutputValue->setData(&cf); ctOutputValue->setData(&ct); } private: DISALLOW_COPY_AND_ASSIGN(applyForceToolFrame); }; #endif /*APPLY_FORCE_TOOLFRAME_H_*/
{ "alphanum_fraction": 0.5879383272, "avg_line_length": 40.4917127072, "ext": "h", "hexsha": "c24232a2f194591b1638c0b5490aac298d3ce6bf", "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": "bcb5cd806ce7c796cfff27f267974c988c5f77ad", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ualberta-robotics/wam_bringup", "max_forks_repo_path": "include/wam_bringup/tool_force_application.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcb5cd806ce7c796cfff27f267974c988c5f77ad", "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": "ualberta-robotics/wam_bringup", "max_issues_repo_path": "include/wam_bringup/tool_force_application.h", "max_line_length": 206, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bcb5cd806ce7c796cfff27f267974c988c5f77ad", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ualberta-robotics/wam_bringup", "max_stars_repo_path": "include/wam_bringup/tool_force_application.h", "max_stars_repo_stars_event_max_datetime": "2021-03-13T02:12:58.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T02:12:58.000Z", "num_tokens": 2442, "size": 7329 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gbpLib.h> #include <gbpMath.h> #include <gbpCosmo_core.h> #include <gbpCosmo_NFW_etc.h> #include <gsl/gsl_sf_expint.h> // FFT of NFW profile from White '01 double rho_NFW_fft(double k, double M_vir, double z, int mode, cosmo_info **cosmo) { double c_vir; double R_vir; double r_s; double z_k; double g_c; double rho_o; double x1; double x2; double Ci1; double Ci2; double Si1; double Si2; double r_val; set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir); r_s = R_vir / c_vir; z_k = k * r_s; g_c = 1. / (log(1. + c_vir) - c_vir / (1. + c_vir)); rho_o = M_vir * g_c / (FOUR_PI * r_s * r_s * r_s); x1 = 1. + c_vir; x2 = c_vir * z_k; Ci1 = gsl_sf_Ci((1. + c_vir) * z_k); Si1 = gsl_sf_Si((1. + c_vir) * z_k); Ci2 = gsl_sf_Ci(z_k); Si2 = gsl_sf_Si(z_k); r_val = (FOUR_PI * rho_o * r_s * r_s * r_s / M_vir) * (cos(z_k) * (Ci1 - Ci2) + sin(z_k) * (Si1 - Si2) - sin(c_vir * z_k) / (z_k * (1. + c_vir))); return (r_val); }
{ "alphanum_fraction": 0.5758122744, "avg_line_length": 28.4102564103, "ext": "c", "hexsha": "14d1c041609e0172852b3c36591647741a52077c", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.c", "max_line_length": 150, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 444, "size": 1108 }
#include <stdio.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> int main(void) { double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6}; double median, upperq, lowerq; printf ("Original dataset: %g, %g, %g, %g, %g\n", data[0], data[1], data[2], data[3], data[4]); gsl_sort (data, 1, 5); printf ("Sorted dataset: %g, %g, %g, %g, %g\n", data[0], data[1], data[2], data[3], data[4]); median = gsl_stats_median_from_sorted_data (data, 1, 5); upperq = gsl_stats_quantile_from_sorted_data (data, 1, 5, 0.75); lowerq = gsl_stats_quantile_from_sorted_data (data, 1, 5, 0.25); printf ("The median is %g\n", median); printf ("The upper quartile is %g\n", upperq); printf ("The lower quartile is %g\n", lowerq); return 0; }
{ "alphanum_fraction": 0.475, "avg_line_length": 27.027027027, "ext": "c", "hexsha": "2780f673d940c973da9689f15b4e3ba2fa4308b0", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/statsort.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/statsort.c", "max_line_length": 54, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/statsort.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": 300, "size": 1000 }
#pragma once #define UPCA_ARCH_H #include <memory> #include <vector> #include <stdint.h> #include <gsl/gsl> namespace upca { namespace arch { namespace detail { template <typename Reason> struct null_resolver { struct null_type { friend std::ostream &operator<<(std::ostream &os, const null_type &) { return os; } }; static null_type resolve(const std::string &) { throw std::runtime_error(Reason::reason); } }; template <typename TIMESTAMP, typename REASON> struct basic_pmu { using resolver_type = upca::arch::detail::null_resolver<REASON>; template <typename T> basic_pmu(const T &) {} uint64_t timestamp_begin() { return TIMESTAMP::timestamp(); } uint64_t timestamp_end() { return TIMESTAMP::timestamp(); } gsl::span<uint64_t>::index_type start(gsl::span<uint64_t>) { return 0; } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t>) { return 0; } }; } // namespace detail template <typename ARCH> class arch_common_base final { private: ptrdiff_t offset_ = 0; const ptrdiff_t slice_; ARCH arch_; template <typename T> friend class resolver; public: using resolver_type = typename ARCH::resolver_type; template <typename C> arch_common_base(const C &pmcs, const unsigned external_pmcs = 0) : slice_(gsl::narrow<ptrdiff_t>(pmcs.size() + external_pmcs)), arch_(pmcs) {} gsl::span<uint64_t>::index_type start(gsl::span<uint64_t> output) { const auto count = arch_.start(output.subspan(1, slice_ - 1)); output[0] = arch_.timestamp_begin(); return count + 1; } gsl::span<uint64_t>::index_type stop(gsl::span<uint64_t> output) { output[0] = arch_.timestamp_end() - output[0]; const auto count = arch_.stop(output.subspan(1, slice_ - 1)); return count + 1; } }; } // namespace arch } // namespace upca #ifdef __aarch64__ # include "aarch64.h" using pmu = upca::arch::arch_common_base<upca::arch::aarch64::pmu>; #elif defined(__ARM_ARCH_7A__) # include "aarch32.h" using pmu = upca::arch::arch_common_base<upca::arch::aarch32::pmu>; #elif defined(__sparc) # include "sparc.h" using pmu = upca::arch::arch_common_base<upca::arch::sparc::pmu>; #elif defined(__x86_64__) # include "x86_64.h" /* MCK can be either: * - mck_rawmsr for raw MSR access via rdmsr/wrmsr mcK syscalls * - mck_mckmsr for PMU programmed via mcK pmc_* syscalls * * LINUX can be any of: * - linux_perf for using perf * - linux_jevents for using jevents * - linux_rawmsr for raw MSR access using /dev/cpu/N/msr */ #ifdef JEVENTS_FOUND using pmu = upca::arch::arch_common_base<upca::arch::x86_64::x86_linux_mckernel< upca::arch::x86_64::mck_mckmsr, upca::arch::x86_64::linux_rawmsr>>; #else using pmu = upca::arch::arch_common_base<upca::arch::x86_64::x86_64_pmu>; #endif #elif defined(__bgq__) # include "bgq.h" using pmu = upca::arch::arch_common_base<upca::arch::bgq::pmu>; #elif defined(__ppc__) || defined(_ARCH_PPC) || defined(__PPC__) # include "ppc.h" using pmu = upca::arch::arch_common_base<upca::arch::ppc::pmu>; #else #error "Unkown/Unsupported architecture" #endif
{ "alphanum_fraction": 0.7023540793, "avg_line_length": 24.0387596899, "ext": "h", "hexsha": "130ec6179623232a81ca629a80c1c3d3a552537c", "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": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hannesweisbach/ucpa", "max_forks_repo_path": "include/upca/arch/arch.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "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": "hannesweisbach/ucpa", "max_issues_repo_path": "include/upca/arch/arch.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hannesweisbach/ucpa", "max_stars_repo_path": "include/upca/arch/arch.h", "max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z", "num_tokens": 926, "size": 3101 }