Search is not available for this dataset
text
string
meta
dict
/* * utils.h * * Created on: Dec 14, 2016 * Author: hazem */ #include <cublas_v2.h> #include <curand.h> #include <stdlib.h> #include <stdio.h> #include "papi.h" #include <cblas.h> #include <pthread.h> #include <sys/mman.h> #ifndef UTILS_H_ #define UTILS_H_ float convert_to_sec(long long time_usec); float calculate_average(float* array, int repeat); void GPU_fill_rand(float *A, int nr_rows_A, int nr_cols_A); void fill_2d_matrix(float* matrix, int n, int m, float value); void print_matrix(const float *A, int nr_rows_A, int nr_cols_A); #endif /* UTILS_H_ */
{ "alphanum_fraction": 0.7172774869, "avg_line_length": 23.875, "ext": "h", "hexsha": "8e93fc443ccd38a850b57ef751c98a3055c50d34", "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": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "HazemAbdelhafez/Jetson-matrixmultiply", "max_forks_repo_path": "utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "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": "HazemAbdelhafez/Jetson-matrixmultiply", "max_issues_repo_path": "utils.h", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "809bd64b10241d5bd4c04256c1c3ee46eded3e5c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "HazemAbdelhafez/Jetson-matrixmultiply", "max_stars_repo_path": "utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 167, "size": 573 }
// Server settings and option parsing #ifndef _SETTINGS_H #define _SETTINGS_H #include <gsl/gsl_rng.h> #include <stdbool.h> // Settings the server has typedef struct _settings { int verbose; int threads; int tcpport; double dist_arg1; // normal distribution mean double dist_arg2; // normal distribution stddev bool use_dist; gsl_rng *r; } settings; void usage(void); settings settings_init(void); bool settings_parse(int argc, char **argv, settings *s); #endif
{ "alphanum_fraction": 0.7552742616, "avg_line_length": 18.96, "ext": "h", "hexsha": "cc36a72f0791afceaa3d06f49cbdbf2c742e8f92", "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": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dterei/synthetic-memcached", "max_forks_repo_path": "src/settings.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "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": "dterei/synthetic-memcached", "max_issues_repo_path": "src/settings.h", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "2db588dd7f3417a912e8ac1547cd2b51c8fd7915", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dterei/synthetic-memcached", "max_stars_repo_path": "src/settings.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 110, "size": 474 }
#pragma once #include "BoundingRegion.h" #include "Ellipsoid.h" #include "S2CellID.h" #include <CesiumGeometry/CullingResult.h> #include <CesiumGeometry/Plane.h> #include <glm/vec3.hpp> #include <gsl/span> #include <array> #include <string_view> namespace CesiumGeospatial { /** * A tile bounding volume specified as an S2 cell token with minimum and maximum * heights. The bounding volume is a k DOP. A k-DOP is the Boolean intersection * of extents along k directions. * * @param cellID The S2 cell ID. * @param minimumHeight The minimum height of the bounding volume. * @param maximumHeight The maximum height of the bounding volume. * @param ellipsoid The ellipsoid. */ class CESIUMGEOSPATIAL_API S2CellBoundingVolume final { public: S2CellBoundingVolume( const S2CellID& cellID, double minimumHeight, double maximumHeight, const Ellipsoid& ellipsoid = Ellipsoid::WGS84); /** * @brief Gets this bounding volume's cell ID. */ const S2CellID& getCellID() const { return this->_cellID; } /** * @brief Gets the minimum height of the cell. */ double getMinimumHeight() const noexcept { return this->_minimumHeight; } /** * @brief Gets the maximum height of the cell. */ double getMaximumHeight() const noexcept { return this->_maximumHeight; } /** * @brief Gets the center of this bounding volume in ellipsoid-fixed (ECEF) * coordinates. */ glm::dvec3 getCenter() const noexcept; /** * @brief Gets the either corners of the bounding volume, in ellipsoid-fixed * (ECEF) coordinates. * * @return An array of positions with a `size()` of 8. */ gsl::span<const glm::dvec3> getVertices() const noexcept; /** * @brief Determines on which side of a plane the bounding volume is located. * * @param plane The plane to test against. * @return The {@link CesiumGeometry::CullingResult} * * `Inside` if the entire region is on the side of the plane the normal is * pointing. * * `Outside` if the entire region is on the opposite side. * * `Intersecting` if the region intersects the plane. */ CesiumGeometry::CullingResult intersectPlane(const CesiumGeometry::Plane& plane) const noexcept; /** * @brief Computes the distance squared from a given position to the closest * point on this bounding volume. The position must be expressed in * ellipsoid-centered (ECEF) coordinates. * * @param position The position * @return The estimated distance squared from the bounding box to the point. * * @snippet TestOrientedBoundingBox.cpp distanceSquaredTo */ double computeDistanceSquaredToPosition(const glm::dvec3& position) const noexcept; /** * @brief Gets the six planes that bound the volume. * * @return An array of planes with a `size()` of 6. */ gsl::span<const CesiumGeometry::Plane> getBoundingPlanes() const noexcept; /** * @brief Computes the bounding begion that best fits this S2 cell volume. * * @return The bounding region. */ BoundingRegion computeBoundingRegion() const noexcept; private: S2CellID _cellID; double _minimumHeight; double _maximumHeight; glm::dvec3 _center; std::array<CesiumGeometry::Plane, 6> _boundingPlanes; std::array<glm::dvec3, 8> _vertices; }; } // namespace CesiumGeospatial
{ "alphanum_fraction": 0.7072803851, "avg_line_length": 28.9043478261, "ext": "h", "hexsha": "e8978902c7d35d9a719ae43add22260cb78da303", "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": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.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": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.h", "max_line_length": 80, "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": "CesiumGeospatial/include/CesiumGeospatial/S2CellBoundingVolume.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": 847, "size": 3324 }
#pragma once #include <d3d11.h> #include <gsl\gsl> #include "Rectangle.h" namespace Library { class TextureHelper final { public: static Point GetTextureSize(gsl::not_null<ID3D11Texture2D*> texture); static Rectangle GetTextureBounds(gsl::not_null<ID3D11Texture2D*> texture); static std::uint32_t BitsPerPixel(const DXGI_FORMAT format); TextureHelper() = delete; TextureHelper(const TextureHelper&) = delete; TextureHelper& operator=(const TextureHelper&) = delete; TextureHelper(TextureHelper&&) = delete; TextureHelper& operator=(TextureHelper&&) = delete; ~TextureHelper() = default; }; }
{ "alphanum_fraction": 0.7508090615, "avg_line_length": 26.8695652174, "ext": "h", "hexsha": "03c372930da68d0a5b3bd80407933ca1f9a84800", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/Library.Shared/TextureHelper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/Library.Shared/TextureHelper.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/Library.Shared/TextureHelper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 159, "size": 618 }
/* specfunc/test_legendre.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_legendre(void) { gsl_sf_result r; double L[256]; int s = 0; int sa; TEST_SF(s, gsl_sf_legendre_P1_e, (-0.5, &r), -0.5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P1_e, ( 0.5, &r), 0.5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P2_e, (0.0, &r), -0.5 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P2_e, (0.5, &r), -0.125, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P2_e, (1.0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P2_e, (100.0, &r), 14999.5 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P3_e, ( -0.5, &r), 0.4375, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P3_e, ( 0.5, &r), -0.4375, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P3_e, ( 1.0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_P3_e, (100.0, &r), 2.49985e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1, -0.5, &r), -0.5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1, 1.0e-8, &r), 1.0e-08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1, 0.5, &r), 0.5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (10, -0.5, &r), -0.1882286071777345, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (10, 1.0e-8, &r), -0.24609374999999864648, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (10, 0.5, &r), -0.18822860717773437500, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (10, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (99, -0.5, &r), 0.08300778172138770477, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (99, 1.0e-8, &r), -7.958923738716563193e-08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (99, 0.5, &r), -0.08300778172138770477, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (99, 0.999, &r), -0.3317727359254778874, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (99, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1000, -0.5, &r), -0.019168251091650277878, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1000, 1.0e-8, &r), 0.02522501817709828, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1000, 0.5, &r), -0.019168251091650277878, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (1000, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (4000, -0.5, &r), -0.009585404456573080972, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (4000, 0.5, &r), -0.009585404456573080972, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Pl_e, (4000, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); sa = 0; gsl_sf_legendre_Pl_array(100, 0.5, L); sa += ( test_sf_frac_diff(L[0], 1.0 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(L[10], -0.18822860717773437500 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(L[100], -0.06051802596186118687 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_legendre_Pl_array(100)"); s += sa; TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 0, -0.5, &r), -0.18822860717773437500, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 0, 1.0e-08, &r), -0.24609374999999864648, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 0, 0.5, &r), -0.18822860717773437500, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 1, -0.5, &r), -2.0066877394361256516, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 1, 1.0e-08, &r), -2.7070312499999951725e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 1, 0.5, &r), 2.0066877394361256516, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 5, -0.5, &r), -30086.169706116174977, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 5, 1.0e-08, &r), -0.0025337812499999964949, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 5, 0.5, &r), 30086.169706116174977, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (10, 5, 0.999, &r), -0.5036411489013270406, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (100, 5, -0.5, &r), -6.617107444248382171e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (100, 5, 1.0e-08, &r), 817.8987598063712851, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (100, 5, 0.5, &r), 6.617107444248382171e+08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Plm_e, (100, 5, 0.999, &r), -1.9831610803806212189e+09, TEST_TOL2, GSL_SUCCESS); sa = 0; gsl_sf_legendre_Plm_array(100, 5, 0.5, L); sa += ( test_sf_frac_diff(L[0], -460.3466286991656682 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(L[10], 38852.51334152290535 ) > TEST_TOL0 ); sa += ( test_sf_frac_diff(L[95], 6.617107444248382171e+08 ) > TEST_TOL0 ); gsl_test(sa, " gsl_sf_legendre_Plm_array(100, 5, 0.5)"); s += sa; TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 0, -0.5, &r), -0.24332702369300133776, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 0, 0.5, &r), -0.24332702369300133776, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 0, 0.999, &r), 1.2225754122797385990, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 5, -0.5, &r), -0.3725739049803293972, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 5, 1.0e-08, &r), -3.1377233589376792243e-08, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 5, 0.5, &r), 0.3725739049803293972, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 5, 0.999, &r), -6.236870674727370094e-06, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 10, -0.5, &r), 0.12876871185785724117, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 10, 0.5, &r), 0.12876871185785724117, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (10, 10, 0.999, &r), 1.7320802307583118647e-14, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (200, 1, -0.5, &r), 0.3302975570099492931, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (200, 1, 0.5, &r), -0.3302975570099492931, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_sphPlm_e, (200, 1, 0.999, &r), -1.4069792055546256912, TEST_TOL2, GSL_SUCCESS); sa = 0; gsl_sf_legendre_sphPlm_array(100, 5, 0.5, L); sa += ( test_sf_frac_diff(L[0], -0.22609703187800460722 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(L[10], 0.07452710323813558940 ) > TEST_TOL2 ); sa += ( test_sf_frac_diff(L[95], 0.25865355990880161717 ) > TEST_TOL2 ); gsl_test(s, " gsl_sf_legendre_sphPlm_array(100, 5, 0.5)"); s += sa; TEST_SF(s, gsl_sf_conicalP_half_e, (0.0, -0.5, &r), 0.8573827581049917129, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (0.0, 0.5, &r), 0.8573827581049917129, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (0.0, 2.0, &r), 0.6062611623284649811, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (0.0, 100.0, &r), 0.07979045091636735635, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (10.0, -0.5, &r), 5.345484922591867188e+08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (10.0, 0.5, &r), 15137.910380385258370, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (10.0, 2.0, &r), 0.4992680691891618544, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (10.0, 100.0, &r), -0.07272008163718195685, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, -1.0e-3, &r), 1.3347639529084185010e+136, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 1.0e-8, &r), 1.0928098010940058507e+136, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 0.5, &r), 3.895546021611205442e+90, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 10.0, &r), -0.04308567180833581268, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 100.0, &r), -0.04694669186576399194, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 1000.0, &r), 0.023698140704121273277, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (200.0, 1.0e+8, &r), -0.00006790983312124277891, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (1.0e+8, 1.1, &r), 1.1599311133054742944, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_half_e, (1.0e+8, 100.0, &r), 0.07971967557381557875, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (0.0, -0.5, &r), 1.7956982494514644808, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (0.0, 0.5, &r), 0.8978491247257322404, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (0.0, 2.0, &r), 0.7984204253272901551, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (0.0, 100.0, &r), 0.4227531369388072584, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (10.0, -0.5, &r), 5.345484922591867181e+07, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (10.0, 0.5, &r), 1513.7910356104985334, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (10.0, 2.0, &r), 0.03439243987215615642, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (10.0, 100.0, &r), 0.003283756665952609624, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, -0.5, &r), 1.7699538115312304280e+179, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 1.0e-8, &r), 5.464049005470029253e+133, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 0.5, &r), 1.9477730108056027211e+88, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 10.0, &r), 0.0012462575917716355362, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 100.0, &r), -0.0003225881344802625149, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 1000.0, &r), -0.00004330652890886567623, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (200.0, 1.0e+8, &r), 2.0943091278037078483e-07, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (1.0e+8, 1.1, &r), 2.092320445620989618e-09, 16.0*TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_mhalf_e, (1.0e+8, 100.0, &r), -3.359967833599016923e-11, 256.0*TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (0.0, -0.5, &r), 1.3728805006183501647, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (0.0, 0.5, &r), 1.0731820071493643751, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (0.0, 2.0, &r), 0.9012862993604472987, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (0.0, 100.0, &r), 0.30091748588199264556, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (10.0, -0.5, &r), 1.6795592815421804669e+08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (10.0, 0.5, &r), 4826.034132009618240, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (10.0, 2.0, &r), 0.18798468917758716146, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (10.0, 100.0, &r), -0.008622130749987962529, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (200.0, -0.5, &r), 2.502194818646823e+180, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (1000.0, 100.0, &r), 0.0017908817653497715844, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (1000.0, 1000.0, &r), -0.0006566893804926284301, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_0_e, (1000.0, 1.0e+8, &r), 2.3167213561756390068e-06, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (0.0, -0.5, &r), 0.4939371126656998499, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (0.0, 0.5, &r), 0.14933621085538265636, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (0.0, 2.0, &r), -0.13666874968871549533, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (0.0, 100.0, &r), -0.10544528203156629098, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (10.0, -0.5, &r), 1.7253802958788312520e+09, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (10.0, 0.5, &r), 46781.02294059967988, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (10.0, 2.0, &r), 0.26613342643657444400, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (10.0, 100.0, &r), -0.23281959695501029796, TEST_TOL2, GSL_SUCCESS); /* FIXME: Mathematica gets some brain-damaged numbers for * these x < 0 points. I have checked what I am doing in detail, * and it must be right because you can do it by summing * manifestly positive definite quantities. */ TEST_SF(s, gsl_sf_conicalP_1_e, (200.0, -0.999, &r), 2.71635193199341135e+270, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (200.0, -0.9, &r), 4.2952493176812905e+234, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (200.0, -0.5, &r), 5.01159205956053439e+182, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (200.0, 0.999, &r), 195733.0396081538, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (200.0, 10.0, &r), -2.9272610662414349553, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (1000.0, 100.0, &r), -1.7783258105862399857, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (1000.0, 1000.0, &r), 0.4535161075156427179, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_1_e, (1000.0, 1.0e+8, &r), 0.0009983414549874888478, TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (2, 1.0, -0.5, &r), 1.6406279287008789526, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (10, 1.0, -0.5, &r), 0.000029315266725049129448, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (20, 1.0, -0.5, &r), 7.335769429462034431e-15, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (30, 1.0, -0.5, &r), 1.3235612394267378871e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (10, 1.0, 0.5, &r), 2.7016087199857873954e-10, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (20, 1.0, 0.5, &r), 1.1782569701435933399e-24, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (30, 1.0, 0.5, &r), 3.636240588303797919e-41, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (10, 1.0, 2.0, &r), 2.4934929626284934483e-10, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (20, 1.0, 2.0, &r), 1.1284762488012616191e-24, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_sph_reg_e, (30, 100.0, 100.0, &r), -1.6757772087159526048e-64, TEST_TOL6, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (2, 1.0, -0.5, &r), 2.2048510472375258708, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (10, 1.0, -0.5, &r), 0.00007335034531618655690, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (20, 1.0, -0.5, &r), 2.5419860619212164696e-14, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (30, 1.0, -0.5, &r), 5.579714972260536827e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (10, 1.0, 0.5, &r), 1.1674078819646475282e-09, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (20, 1.0, 0.5, &r), 7.066408031229072207e-24, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (30, 1.0, 0.5, &r), 2.6541973286862588488e-40, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (10, 1.0, 2.0, &r), 1.0736109751890863051e-09, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (20, 1.0, 2.0, &r), 6.760965304863386741e-24, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_conicalP_cyl_reg_e, (30, 100.0, 100.0, &r), -4.268753482520651007e-63, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0e-06, 1.0e-06, &r), 0.9999999999998333333 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0, 0.0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0, 1.0, &r), 0.7160229153604338713 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0, 100.0, &r), -3.767437313149604566e-44 , TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0, 500.0, &r), -6.665351935878582205e-218, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (100.0, 1.0, &r), -0.004308757035378200029 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (100.0, 10.0, &r), 7.508054627912986427e-07 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1000.0, 1.0, &r), 0.0007036067909088818319 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0e+08, 1.0, &r), 7.927485371429105968e-09 , TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_0_e, (1.0e+08, 100.0, &r), -3.627118904186918957e-52 , 32.0*TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0e-06, 1.0e-06, &r), 3.333333333334222222e-07, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0, 1.0e-10, &r), 4.714045207910316829e-11, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0, 1.0, &r), 0.3397013994799344639, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0, 100.0, &r), -7.200624449531811272e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0, 500.0, &r), 4.192260336821728677e-218, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (100.0, 0.01, &r), 0.30117664944267412324 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (100.0, 1.0, &r), -0.007393833425336299309 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (100.0, 10.0, &r), -5.031062029821254982e-07 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1000.0, 0.001, &r), 0.30116875865090396421 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1000.0, 1.0, &r), -0.0004776144516074971885 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0e+08, 1.0e-08, &r), 0.30116867893975679722 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0e+08, 1.0, &r), 3.0921097047369081582e-09, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_1_e, (1.0e+08, 100.0, &r), -6.496142701296286936e-52 , 32.0*TEST_SQRT_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0e-06, 1.0e-06, &r), 1.1544011544013627977e-32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 1.0e-10, &r), 2.0224912016958766992e-52, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 1.0, &r), 0.011498635037491577728, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 5.0, &r), 0.0020696945662545205776, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 7.0, &r), -0.0017555303787488993676, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 10.0, &r), 0.00008999979724504887101, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 100.0, &r), -4.185397793298567945e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0, 500.0, &r), 1.4235113901091961263e-217, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 100.0, 0.001, &r), 9.642762597222417946e-10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 100.0, 0.002, &r), 3.0821201254308036109e-08, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 100.0, 0.01, &r), 0.00009281069019005840532, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 100.0, 1.0, &r), -0.008043100696178624653, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 100.0, 10.0, &r), -3.927678432813974207e-07, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1000.0, 0.001, &r), 0.00009256365284253254503, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1000.0, 0.01, &r), -0.05553733815473079983, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0e+08, 1.0e-08, &r), 0.00009256115861125841299, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_H3d_e, (5, 1.0e+08, 100.0, &r), -6.496143209092860765e-52 , 128.0*TEST_SQRT_TOL0, GSL_SUCCESS); #if 0 sa = 0; gsl_sf_legendre_H3d_array(100, 1.0, 3.0, L); sa += ( test_sf_frac_diff(L[ 0], gsl_sf_legendre_H3d( 0, 1.0, 3.0)) > 1.0e-12 ); sa += ( test_sf_frac_diff(L[ 1], gsl_sf_legendre_H3d( 1, 1.0, 3.0)) > 1.0e-12 ); sa += ( test_sf_frac_diff(L[ 10], gsl_sf_legendre_H3d( 10, 1.0, 3.0)) > 1.0e-12 ); sa += ( test_sf_frac_diff(L[100], gsl_sf_legendre_H3d(100, 1.0, 3.0)) > 1.0e-12 ); gsl_test(sa, " gsl_sf_legendre_H3d_array(100, 1.0, 3.0)"); s += sa; #endif /* x = -1 + 2^-16 */ TEST_SF(s, gsl_sf_legendre_Q0_e, (-0.9999847412109375, &r), -5.8917472200477175158028143531855, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, (-0.5, &r), -0.5493061443340548457, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, (-1e-10, &r), -1.000000000000000000e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, (1e-10, &r), 1.000000000000000000e-10, TEST_TOL0, GSL_SUCCESS); /* x = 1 - 2^-16 */ TEST_SF(s, gsl_sf_legendre_Q0_e, (0.9999847412109375, &r), 5.8917472200477175158028143531855, TEST_TOL4, GSL_SUCCESS); /* x = 1 + 2^-16 */ TEST_SF(s, gsl_sf_legendre_Q0_e, ( 1.0000152587890625, &r), 5.8917548494422489138325509750429, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 1.5, &r), 0.8047189562170501873, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 9.99, &r), 0.1004364599660005447, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 10.0, &r), 0.1003353477310755806, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 10.01, &r), 0.1002344395571710243, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 100, &r), 0.010000333353334762015, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q0_e, ( 1e10, &r), 1.000000000000000000e-10, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (-0.9999847412109375, &r), 4.8916573191196772369, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (-0.5, &r), -0.7253469278329725772, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (-0.01, &r), -0.9998999966664666524, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (-1e-10, &r), -0.999999999999999999, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (0.0, &r), -1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (1e-10, &r), -0.999999999999999999, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (0.0001, &r), -0.9999999899999999667, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (0.01, &r), -0.9998999966664666524, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (0.5, &r), -0.7253469278329725772, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (0.9999847412109375, &r), 4.8916573191196772369, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, (1.0000152587890625, &r), 4.8918447504867045145, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 1.5, &r), 0.20707843432557528095, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 9.99, &r), 3.360235060345441639e-3, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 10.0, &r), 3.353477310755806357e-3, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 10.01, &r), 3.346739967281953346e-3, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 100.0, &r), 3.333533347620158821e-5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Q1_e, ( 1e10, &r), 3.333333333333333333e-21, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (10, -0.5, &r), -0.29165813966586752393, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (10, 0.5, &r), 0.29165813966586752393, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (10, 1.5, &r), 0.000014714232718207477406, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (100, -0.5, &r), -0.09492507395207282096, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (100, 0.5, &r), 0.09492507395207282096, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (100, 1.5, &r), 1.1628163435044121988e-43, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (1000, -0.5, &r), -0.030105074974005303500, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (1000, 0.5, &r), 0.030105074974005303500, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_legendre_Ql_e, (1000, 1.1, &r), 1.0757258447825356443e-194, TEST_TOL3, GSL_SUCCESS); return s; }
{ "alphanum_fraction": 0.7152636234, "avg_line_length": 75.1531791908, "ext": "c", "hexsha": "d317f5c6b37a0018753a5739cd7042f35e5a8d96", "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_legendre.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_legendre.c", "max_line_length": 127, "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_legendre.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": 11460, "size": 26003 }
/* Copyright (c) 2016 PaddlePaddle 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. */ #pragma once #ifdef PADDLE_WITH_MKLML #include "paddle/fluid/platform/dynload/mklml.h" #endif #ifdef PADDLE_USE_OPENBLAS #include <cblas.h> // remove typedef in openblas #undef FLOAT #undef INT #undef SIZE #endif #include <cmath> #include <vector> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/framework/tensor.h" #include "paddle/fluid/framework/tensor_util.h" #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/enforce.h" namespace paddle { namespace operators { namespace math { template <typename DeviceContext, typename T, int Rank> struct Transpose { void operator()(const DeviceContext& context, const framework::Tensor& in, framework::Tensor* out, const std::vector<int>& axis); }; template <typename DeviceContext, typename T> struct SetConstant { void operator()(const DeviceContext& context, framework::Tensor* tensor, T num); }; template <typename Place> void set_constant_with_place(const platform::DeviceContext& context, framework::Tensor* tensor, float value); void set_constant(const platform::DeviceContext& context, framework::Tensor* tensor, float value); template <typename DeviceContext, typename T> struct RowwiseAdd { void operator()(const DeviceContext& context, const framework::Tensor& input, const framework::Tensor& vec, framework::Tensor* output); }; template <typename DeviceContext, typename T> struct ColwiseSum { void operator()(const DeviceContext& context, const framework::Tensor& input, framework::Tensor* vec); }; template <typename DeviceContext, typename T> struct RowwiseSum { void operator()(const DeviceContext& context, const framework::Tensor& input, framework::Tensor* vec); }; template <typename DeviceContext, typename T> struct RowwiseMean { void operator()(const DeviceContext& context, const framework::Tensor& input, framework::Tensor* vec); }; } // namespace math } // namespace operators } // namespace paddle
{ "alphanum_fraction": 0.7302631579, "avg_line_length": 31.4482758621, "ext": "h", "hexsha": "c63ad89e46d2c187c7e6fe6b2fe73fbbed5f4044", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2019-11-01T22:28:27.000Z", "max_forks_repo_forks_event_min_datetime": "2018-03-19T22:38:46.000Z", "max_forks_repo_head_hexsha": "7a5f3f750bcbe084796f7840ae2937925432b413", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "SnailTowardThesun/Paddle", "max_forks_repo_path": "paddle/fluid/operators/math/math_function.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "7a5f3f750bcbe084796f7840ae2937925432b413", "max_issues_repo_issues_event_max_datetime": "2018-10-15T08:57:40.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-05T20:29:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "SnailTowardThesun/Paddle", "max_issues_repo_path": "paddle/fluid/operators/math/math_function.h", "max_line_length": 79, "max_stars_count": 9, "max_stars_repo_head_hexsha": "7a5f3f750bcbe084796f7840ae2937925432b413", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "SnailTowardThesun/Paddle", "max_stars_repo_path": "paddle/fluid/operators/math/math_function.h", "max_stars_repo_stars_event_max_datetime": "2020-12-03T14:46:30.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-04T02:58:01.000Z", "num_tokens": 585, "size": 2736 }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf_expint.h> #include "ccl.h" static double einasto_norm_integrand(double x, void *params) { double alpha = *((double *)(params)); return x*x*exp(-2*(pow(x,alpha)-1)/alpha); } void ccl_einasto_norm_integral(int n_m, double *r_s, double *r_delta, double *alpha, double *norm_out,int *status) { #pragma omp parallel default(none) \ shared(n_m, r_s, r_delta, alpha, norm_out, status) { int ii; int status_this=0; gsl_function F; gsl_integration_workspace *w = gsl_integration_workspace_alloc(1000); if (w == NULL) status_this = CCL_ERROR_MEMORY; if(status_this == 0) { #pragma omp for for(ii=0;ii<n_m;ii++) { int qagstatus; double result, eresult; double x_max = r_delta[ii]/r_s[ii]; F.function = &einasto_norm_integrand; F.params = &(alpha[ii]); qagstatus = gsl_integration_qag(&F, 0, x_max, 0, 1E-4, 1000, GSL_INTEG_GAUSS31, w, &result, &eresult); if(qagstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(qagstatus, "ccl_haloprofile.c: ccl_einasto_norm_integral():"); status_this = CCL_ERROR_INTEG; result = NAN; } norm_out[ii] = 4 * M_PI * r_s[ii] * r_s[ii] * r_s[ii] * result; } } //end omp for gsl_integration_workspace_free(w); if(status_this) { #pragma omp atomic write *status = status_this; } } //end omp parallel } static double hernquist_norm_integrand(double x, void *params) { double opx=1+x; return x*x/(x*opx*opx*opx); } void ccl_hernquist_norm_integral(int n_m, double *r_s, double *r_delta, double *norm_out,int *status) { #pragma omp parallel default(none) \ shared(n_m, r_s, r_delta, norm_out, status) { int ii; int status_this=0; gsl_function F; gsl_integration_workspace *w = gsl_integration_workspace_alloc(1000); if (w == NULL) status_this = CCL_ERROR_MEMORY; if(status_this == 0) { #pragma omp for for(ii=0;ii<n_m;ii++) { int qagstatus; double result, eresult; double x_max = r_delta[ii]/r_s[ii]; F.function = &hernquist_norm_integrand; F.params = NULL; qagstatus = gsl_integration_qag(&F, 0, x_max, 0, 1E-4, 1000, GSL_INTEG_GAUSS31, w, &result, &eresult); if(qagstatus != GSL_SUCCESS) { ccl_raise_gsl_warning(qagstatus, "ccl_haloprofile.c: ccl_hernquist_norm_integral():"); status_this = CCL_ERROR_INTEG; result = NAN; } norm_out[ii] = 4 * M_PI * r_s[ii] * r_s[ii] * r_s[ii] * result; } } //end omp for gsl_integration_workspace_free(w); if(status_this) { #pragma omp atomic write *status = status_this; } } //end omp parallel }
{ "alphanum_fraction": 0.663786897, "avg_line_length": 26.4571428571, "ext": "c", "hexsha": "482ce28f5d0fab28ddf1b0ab736ee8325407df0f", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "src/ccl_haloprofile.c", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "src/ccl_haloprofile.c", "max_line_length": 89, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "src/ccl_haloprofile.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 863, "size": 2778 }
#ifndef _HistWidget_H #define _HistWidget_H #include <QWidget> #include <gsl/gsl_histogram.h> #include "src_config.h" class QwtPlot; class _HIST_EXPORT_ HistWidget : public QWidget { public: HistWidget (double xmin, double xmax, double ymin, double ymax, QWidget * parent=0, Qt::WindowFlags flags=0); virtual ~HistWidget (void); void setHistogram (const gsl_histogram * hist); private: // // Variables // QwtPlot *plot; gsl_histogram * w_hist; private: Q_OBJECT }; #endif
{ "alphanum_fraction": 0.6982591876, "avg_line_length": 16.6774193548, "ext": "h", "hexsha": "564083d016bc16e6231b83eccf79bddc9c942f71", "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": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "YuriyRusinov/Histogram", "max_forks_repo_path": "src/gui/HistWidget.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "YuriyRusinov/Histogram", "max_issues_repo_path": "src/gui/HistWidget.h", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "YuriyRusinov/Histogram", "max_stars_repo_path": "src/gui/HistWidget.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 134, "size": 517 }
/* Performing approximate Bayesian computation sequential Monte Carlo (Toni et al. 2009) for linear regression. Synthetic data is generated by `ground_truth_and_analysis.ipynb`. This script writes particles.csv, where each row corresponds to a particle and each column corresponds to a round of SMC. Defining #DEBUG_MODE will silence all writing to stdout. One may then add printf statements in the code, and perhaps write the output to file as: `./run.sh > output.txt` Parameter ordering convention: 0 - gradient 1 - intercept 2 - standard deviation Author: Juvid Aryaman */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sort_double.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_fit.h> #define N_DATA 30 #define N_PARAMETERS 3 #define N_PARTICLES 20000 #define RND gsl_rng_uniform(r) #define SEED 1 #define X_DATA_FILENAME "x.csv" #define Y_DATA_FILENAME "y.csv" // Global variables /*Define the distance threshold for every round of SMC*/ double distance_threshold_schedule[] = {7.0, 6.375, 5.75, 5.125, 4.5, 3.875, 3.25, 2.625, 2.0}; int N_ROUNDS_SMC = (int)(sizeof(distance_threshold_schedule) / sizeof(double)); #include "smc.h" #include "lin_reg.h" //#define DEBUG_MODE int main(int argc, char *argv[]) { #ifndef DEBUG_MODE printf("Threshold schedule:\n"); print_double_array(distance_threshold_schedule, N_ROUNDS_SMC); printf("\n"); #endif /* set up GSL RNG */ gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); /* end of GSL setup */ gsl_rng_set(r, SEED); ///////////////////////// /*Read data*/ ///////////////////////// FILE *data_pointer_x, *data_pointer_y; data_pointer_x = fopen(X_DATA_FILENAME, "r"); data_pointer_y = fopen(Y_DATA_FILENAME, "r"); double data_x[N_DATA]; double data_y[N_DATA]; int i, j, read_error_status_x, read_error_status_y; for (i=0; i < N_DATA; i++){ read_error_status_x = fscanf(data_pointer_x, "%lf\n", &data_x[i]); read_error_status_y = fscanf(data_pointer_y, "%lf\n", &data_y[i]); } if (read_error_status_x != 1){printf("Error reading X data\n"); return 0;} if (read_error_status_y != 1){printf("Error reading Y data\n"); return 0;} ///////////////////////// /*Initialise variables*/ ///////////////////////// /*Fit a linear model to the data, which will be used as summary statistics of the data*/ double gradient_fit_data, intercept_fit_data, sigma_fit_data, cov00, cov01, cov11, sumsq; int gsl_fit_return_value; gsl_fit_return_value = gsl_fit_linear(data_x, 1, data_y, 1, N_DATA, &intercept_fit_data, &gradient_fit_data, &cov00, &cov01, &cov11, &sumsq); if (gsl_fit_return_value != 0) {printf("Fit failed.\n"); return -1;} sigma_fit_data = sqrt(sumsq/(N_DATA-2)); #ifndef DEBUG_MODE printf("gradient ML = %.8f\n", gradient_fit_data); printf("intercept ML = %.8f\n", intercept_fit_data); printf("sigma ML = %.8f\n", sigma_fit_data); #endif /*Make a (N_PARAMETERS X N_ROUNDS_SMC X N_PARTICLES) array to store all particles at all rounds of SMC*/ double*** theta_particle; theta_particle = (double***) malloc(N_PARAMETERS * sizeof(double**)); for (i = 0; i < N_PARAMETERS; i++){ theta_particle[i] = (double**) malloc(N_ROUNDS_SMC * sizeof(double*)); } for (i = 0; i < N_PARAMETERS; i++){ for (j = 0; j < N_ROUNDS_SMC; j++){ theta_particle[i][j] = (double*) malloc(N_PARTICLES * sizeof(double)); } } double *simulated_data = (double*) malloc(N_DATA * sizeof(double)); double *distance = malloc(N_PARTICLES * sizeof(double)); double **weight; weight = (double**) malloc(N_ROUNDS_SMC * sizeof(double*)); for (i = 0; i < N_ROUNDS_SMC; i++) { weight[i] = (double*) malloc(N_PARTICLES * sizeof(double)); } double weight_normalizer = 0.0; int time_smc=0; // an index of each round of SMC int param_index_chosen, prior_violated; int particle_index; ///////////////////////// /*Perform ABC SMC*/ ///////////////////////// /*For every round of SMC*/ for (time_smc = 0; time_smc < N_ROUNDS_SMC; time_smc++) { #ifndef DEBUG_MODE printf("Round %d of SMC\n", time_smc); #endif /*Draw or perturb a particle and compute distance*/ for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) { // reset distance of particle distance[particle_index] = distance_threshold_schedule[time_smc] + 1.0; while (distance[particle_index] > distance_threshold_schedule[time_smc]) { if (time_smc == 0) { // Sample from the prior sample_prior(r, theta_particle, particle_index); } else{ /*Sample from the old weights*/ param_index_chosen = weighted_choice(r, weight[time_smc-1]); if ((param_index_chosen < 0)||(param_index_chosen >= N_PARTICLES)) { printf("Error in param_index_chosen\n"); printf("time_smc = %d\n", time_smc); return -1; } perturb_particle(r, theta_particle, time_smc, param_index_chosen, particle_index); // Check if prior support is 0 prior_violated = check_prior_violated(theta_particle, time_smc, particle_index); if(prior_violated == 1) continue; } simulate_dataset(r, theta_particle, data_x, simulated_data, time_smc, particle_index); distance[particle_index] = distance_metric_sum_abs_res(simulated_data, data_y); } } #ifndef DEBUG_MODE printf("Particles sampled.\n"); #endif /*Compute & Normalise weights. For uniform priors, and a uniform perturbation kernel, all surviving particles are weighted identically as 1/N_PARTICLES. Whilst seemingly inefficient, I keep this code here for clarity/generality. The bottleneck in computation time is the while loop above.*/ if (time_smc==0){ for (i = 0; i < N_PARTICLES; i++) weight[0][i] = 1.0;} else{ weight_normalizer = 0.0; for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) { // kernel_pdf is uniform, so is independent of the parameters weight_normalizer += weight[time_smc-1][particle_index]*kernel_pdf(); } for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) { weight[time_smc][particle_index] = prior_pdf(theta_particle, time_smc, particle_index)/weight_normalizer; } } weight_normalizer = 0.0; for (i = 0; i < N_PARTICLES; i++) weight_normalizer += weight[time_smc][i]; for (i = 0; i < N_PARTICLES; i++){ weight[time_smc][i] = weight[time_smc][i]/weight_normalizer; } } #ifndef DEBUG_MODE printf("Writing particles to file\n"); #endif write_particles_to_csv(theta_particle); char weight_filename[] = "weights.csv"; write_2d_double_array_to_csv(weight, N_ROUNDS_SMC, N_PARTICLES, weight_filename); #ifndef DEBUG_MODE printf("Done!\n"); #endif return 0; //return from main } //close main
{ "alphanum_fraction": 0.6991361335, "avg_line_length": 29.4473684211, "ext": "c", "hexsha": "710b08b3d975e8bb4988b219b1b13a7b3eadb0f1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-02T14:25:20.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-02T14:25:20.000Z", "max_forks_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jaryaman/ML_demos", "max_forks_repo_path": "Notebooks/ABC_SMC/Linear_regression/smc.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc", "max_issues_repo_issues_event_max_datetime": "2020-09-28T14:21:39.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-21T18:23:19.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jaryaman/ML_demos", "max_issues_repo_path": "Notebooks/ABC_SMC/Linear_regression/smc.c", "max_line_length": 89, "max_stars_count": 2, "max_stars_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jaryaman/ML_demos", "max_stars_repo_path": "Notebooks/ABC_SMC/Linear_regression/smc.c", "max_stars_repo_stars_event_max_datetime": "2018-07-31T16:51:10.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-28T18:14:12.000Z", "num_tokens": 1849, "size": 6714 }
#pragma once #ifndef __linux__ #error We only support Linux #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifdef __FAAS_CPP_WORKER #if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_CPP_WORKER_SRC) #error Need the source file to have __FAAS_USED_IN_BINDING defined #endif #endif #ifdef __FAAS_NODE_ADDON #if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_NODE_ADDON_SRC) #error Need the source file to have __FAAS_USED_IN_BINDING defined #endif #define __FAAS_CXX_NO_EXCEPTIONS #endif #ifdef __FAAS_PYTHON_BINDING #if !defined(__FAAS_USED_IN_BINDING) && !defined(__FAAS_PYTHON_BINDING_SRC) #error Need the source file to have __FAAS_USED_IN_BINDING defined #endif #include <Python.h> #if PY_VERSION_HEX < 0x03070000 #error FaaS Python binding requires Python 3.7+ #endif #endif // C includes #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <unistd.h> // C++ includes #include <limits> #include <atomic> #include <memory> #include <utility> #include <optional> #include <sstream> #include <string> #include <string_view> #include <functional> #include <algorithm> // STL containers #include <vector> #include <queue> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #ifdef __FAAS_CPP_WORKER #include <mutex> #endif // fmtlib #define FMT_HEADER_ONLY #include <fmt/core.h> #include <fmt/format.h> // Guidelines Support Library (GSL) #include <gsl/gsl> #include "base/diagnostic.h" #ifdef __FAAS_SRC #define __FAAS_HAVE_ABSL #endif #if defined(__FAAS_HAVE_ABSL) && !defined(__FAAS_USED_IN_BINDING) // Will not include common absl headers in source files // with __FAAS_USED_IN_BINDING defined __BEGIN_THIRD_PARTY_HEADERS #include <absl/base/call_once.h> #include <absl/flags/flag.h> #include <absl/time/time.h> #include <absl/time/clock.h> #include <absl/strings/str_cat.h> #include <absl/strings/match.h> #include <absl/strings/strip.h> #include <absl/strings/str_split.h> #include <absl/strings/numbers.h> #include <absl/strings/ascii.h> #include <absl/random/random.h> #include <absl/random/distributions.h> #include <absl/container/flat_hash_map.h> #include <absl/container/flat_hash_set.h> #include <absl/container/fixed_array.h> #include <absl/container/inlined_vector.h> #include <absl/synchronization/mutex.h> #include <absl/synchronization/notification.h> #include <absl/functional/bind_front.h> #include <absl/algorithm/container.h> __END_THIRD_PARTY_HEADERS #endif // defined(__FAAS_HAVE_ABSL) && !defined(__FAAS_USED_IN_BINDING) #include "base/macro.h" #include "base/logging.h" #include "base/std_span.h"
{ "alphanum_fraction": 0.7800075729, "avg_line_length": 23.1666666667, "ext": "h", "hexsha": "c163afb3ee34653a6783fde0fddd55e0c58298af", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2022-02-09T20:54:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-02T13:11:29.000Z", "max_forks_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jhweintraub/boki", "max_forks_repo_path": "src/base/common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "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": "jhweintraub/boki", "max_issues_repo_path": "src/base/common.h", "max_line_length": 75, "max_stars_count": 26, "max_stars_repo_head_hexsha": "65f3c713211c41329878f0057d8659a89243b388", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jhweintraub/boki", "max_stars_repo_path": "src/base/common.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:38:40.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-02T13:11:26.000Z", "num_tokens": 690, "size": 2641 }
/** * @file spectralestimator.h * @brief Speech recognition front end. * @author John McDonough, Matthias Woelfel, Kenichi Kumatani */ #ifndef SPECTRALESTIMATOR_H #define SPECTRALESTIMATOR_H #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <math.h> #include <algorithm> #include "matrix/gslmatrix.h" #include "stream/stream.h" #include "common/mlist.h" #include <stdio.h> #include <iostream> /** @brief calculate the auto-correlation vector, r, with the time-discrete signal, x[n]. Each component, r[k], represents the auto-correlation function of the input sample for lag, k. Accordingly, r[k] can be expressed as \cE{ x[n] x[n-k] }. @param const gsl_vector *samples[in] time-discrete signal which corresponds to x[n]. @param gsl_vector *autoCorrelationVector[out] auto-correlation vector which corresponds to r. @note the size of "autoCorrelationVector" should be "order+1" in order to calculate the LP model of the order, "order". */ void calcAutoCorrelationVector( const gsl_vector_float *samples, gsl_vector *autoCorrelationVector ); /** @brief calculate the linear prediction coefficients (LPC) with the Levinson-Durbin Algorithm. @param gsl_vector_float *autoCorrelationVector[in] @param gsl_vector_float *lpcs[out] lpcs[0,...,p-1] where p is the order of the model. @return prediction error @notice The estimated signal is defined as \hat{x}[n] = sum_{k=1}^p lpcs[k-1] * x[n-k]. That is different from the definition in MATLAB lpc() where it is \hat{x}(n) = 1.0 - sum_{k=1}^p lpcs(k+1) * x(n-k). */ float calcLPCswithLevinsonDurbin( gsl_vector_float *autoCorrelationVector, gsl_vector_float *lpcs ); // ----- definition for class `LPCSpectrumEstimator' ----- // /** @class calculate LPCs with the Levinson-Durbin algorithm, and estimate the LPC envelope. @note You can feed samples to this object with calcLPCs( const gsl_vector_float* samples ), and the LPCs are then computed. */ class LPCSpectrumEstimator : public VectorFloatFeatureStream { public: LPCSpectrumEstimator( const VectorFloatFeatureStreamPtr& samp, unsigned order, unsigned fftLen, const String& nm = "LPCSpectrumEstimator"); ~LPCSpectrumEstimator(); const gsl_vector_float* next(int frame_no = -5); void reset(); /** @brief get the auto-correlation vector, r[0,...,order-1], where r[k] represents the auto-correlation function of the input sample for lag, k+1. @note you have to call calcLPCs() before you call this method. */ const gsl_vector_float* getAutoCorrelationVector(){ return (const gsl_vector_float*)_r; } /** @brief get the prediction error of the LP model. @note you have to call calcLPCs() before you call this method. */ float getPredictionError(){ return _e; } /** @brief get the LPCs. @note you have to call calcLPCs() before you call this method. */ const gsl_vector_float* getLPCs(){ return _lpcs; //_vector; } gsl_vector_complex* getFTLPCs(){ return _ftlpcs; } const gsl_vector_float* calcLPCs( const gsl_vector_float* samples ); void calcLPEnvelope(); private: void complexPackedArrayUnpack(const double* halfcomplex_coefficient, gsl_vector_complex* complex_coefficient) const; private: static const double _epsilon; VectorFloatFeatureStreamPtr _samp; unsigned _order; /* the LP model of the order */ unsigned _fftLen; unsigned _fftLen2; float _e; /* prediction error */ gsl_vector_float* _r; /* _order x 1 auto-correlation vector _r[1,...,p]; See [1] */ gsl_vector* _autoCorrelation; /* (_order+1) x 1 auto-correlation vector, where the first element corresponds to the power */ gsl_vector_float* _lpcs; /* LPCs */ double* _wslpcs; /* workspace for the LPCs */ gsl_vector_complex* _ftlpcs; }; typedef Inherit<LPCSpectrumEstimator, VectorFloatFeatureStreamPtr> LPCSpectrumEstimatorPtr; // ----- definition for class `CepstralSpectrumEstimator' ----- // class CepstralSpectrumEstimator : public VectorFloatFeatureStream { public: CepstralSpectrumEstimator(const VectorComplexFeatureStreamPtr& source, unsigned order = 14, unsigned fftLen = 256, double logPadding = 1.0, const String& nm = "CepstralSpectrumEstimator"); ~CepstralSpectrumEstimator(); const gsl_vector_float* next(int frame_no = -5); void reset() { _source->reset(); VectorFloatFeatureStream::reset(); } private: VectorComplexFeatureStreamPtr _source; const unsigned _order; const unsigned _fftLen; const double _logPadding; double* _samples; gsl_vector_complex* _spectrum; gsl_vector_complex* _cepstrum; }; typedef Inherit<CepstralSpectrumEstimator, VectorFloatFeatureStreamPtr> CepstralSpectrumEstimatorPtr; // ----- definition for class `SEMNB' ----- // /** @class */ class SEMNB : public Countable { public: SEMNB( unsigned order, unsigned fftLen, const String& nm = "SEMNB"); ~SEMNB(); const gsl_vector* calcDerivativeOfDeviation( LPCSpectrumEstimatorPtr &lpcSEPtr ); virtual void reset(); const gsl_vector* getLPEnvelope() const { return _lpEnvelope; } private: void _calcEigen(); void _calcLambda_bar(); double _dLambdak_dPm(unsigned k, unsigned m); void _dLambdabar_dPm(unsigned m); void _da_dPm(unsigned m); float _dSigma_dP(const gsl_vector_float* lpcs, double epsilonp, unsigned m); double _dSp_dan(const gsl_vector_float* lpcs, unsigned m, unsigned n); double _dSp_dPm(const gsl_vector_float* lpcs, unsigned m); double _depsilonp_dPm(const gsl_vector_float* lpcs, unsigned m); void _calc_dr_dPm(unsigned m); double _dPhat_dP(const gsl_vector_float* lpcs, double epsilonp, unsigned m); const unsigned _order; const unsigned _fftLen; const unsigned _fftLen2; gsl_vector* _derivative; gsl_matrix* _R; gsl_matrix* _Rcopy; gsl_eigen_symmv_workspace* _workSpace; gsl_vector* _evalues; gsl_matrix* _evectors; gsl_vector* _lpEnvelope; gsl_vector_complex* _ftlpcs; gsl_vector* _r; gsl_vector* _dr_dPm; gsl_vector* _dak_dPm; gsl_matrix* _Lambda_bar; gsl_matrix* _dLambdamatrix; gsl_matrix* _C; gsl_matrix* _D; }; typedef refcountable_ptr<SEMNB> SEMNBPtr; #endif
{ "alphanum_fraction": 0.6939834025, "avg_line_length": 33.9095477387, "ext": "h", "hexsha": "34005d8792bec80978e1516c091a121b19870a40", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/feature/spectralestimator.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/feature/spectralestimator.h", "max_line_length": 141, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/feature/spectralestimator.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 1808, "size": 6748 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include "allvars.h" #include "proto.h" #ifdef COSMIC_RAYS #include "cosmic_rays.h" #endif #ifdef CS_MODEL #include "cs_metals.h" #endif /*! Structure for communication during the density computation. Holds data that is sent to other processors. */ static struct densdata_in { MyDouble Pos[3]; MyFloat Vel[3]; MyFloat Hsml; #ifdef VOLUME_CORRECTION MyFloat DensityOld; #endif #ifdef WINDS MyFloat DelayTime; #endif int NodeList[NODELISTLENGTH]; #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) MyFloat BPred[3]; #endif #ifdef EULERPOTENTIALS MyFloat EulerA, EulerB; #endif #ifdef CS_MODEL MyFloat DensityOld, Entropy; #endif } *DensDataIn, *DensDataGet; static struct densdata_out { MyLongDouble Rho; MyLongDouble DhsmlDensity; MyLongDouble Ngb; #ifndef NAVIERSTOKES MyLongDouble Div, Rot[3]; #else MyFloat DV[3][3]; #endif #ifdef MAGNETIC #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) MyFloat RotB[3]; #endif #ifdef TRACEDIVB MyFloat divB; #endif #endif #ifdef RADTRANSFER_FLUXLIMITER MyFloat Grad_ngamma[3]; #endif #if defined(BLACK_HOLES) MyLongDouble SmoothedEntr; #endif #ifdef CONDUCTION_SATURATION MyFloat GradEntr[3]; #endif #ifdef BLACK_HOLES MyLongDouble GasVel[3]; #endif #ifdef HYDRO_COST_FACTOR int Ninteractions; #endif #ifdef VOLUME_CORRECTION MyFloat DensityStd; #endif #ifdef EULERPOTENTIALS MyFloat dEulerA[3], dEulerB[3]; #endif } *DensDataResult, *DensDataOut; /*! \file density.c * \brief SPH density computation and smoothing length determination * * This file contains the "first SPH loop", where the SPH densities and some * auxiliary quantities are computed. There is also functionality that * corrects the smoothing length if needed. */ /*! This function computes the local density for each active SPH particle, the * number of neighbours in the current smoothing radius, and the divergence * and rotation of the velocity field. The pressure is updated as well. If a * particle with its smoothing region is fully inside the local domain, it is * not exported to the other processors. The function also detects particles * that have a number of neighbours outside the allowed tolerance range. For * these particles, the smoothing length is adjusted accordingly, and the * density() computation is called again. Note that the smoothing length is * not allowed to fall below the lower bound set by MinGasHsml (this may mean * that one has to deal with substantially more than normal number of * neighbours.) */ void density(void) { MyFloat *Left, *Right; int i, j, ndone, ndone_flag, npleft, dt_step, dummy, iter = 0; int ngrp, sendTask, recvTask, place, nexport, nimport; long long ntot; double dmax1, dmax2, fac; double timeall = 0, timecomp1 = 0, timecomp2 = 0, timecommsumm1 = 0, timecommsumm2 = 0, timewait1 = 0, timewait2 = 0; double timecomp, timecomm, timewait; double dt_entr, tstart, tend, t0, t1; double desnumngb; #ifdef COSMIC_RAYS int CRpop; #endif #if defined(NAVIERSTOKES) int k; #endif #ifdef NAVIERSTOKES double dvel[3][3]; double rotx, roty, rotz; #endif #if defined(SOFTEREQS) double a3inv; if(All.ComovingIntegrationOn) a3inv = 1 / (All.Time * All.Time * All.Time); else a3inv = 1; #endif #ifdef EULERPOTENTIALS double efak; if(All.ComovingIntegrationOn) efak = 1. / All.Time / All.HubbleParam; else efak = 1; #endif CPU_Step[CPU_DENSMISC] += measure_time(); Left = (MyFloat *) mymalloc(NumPart * sizeof(MyFloat)); Right = (MyFloat *) mymalloc(NumPart * sizeof(MyFloat)); for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) { if(density_isactive(i)) { Left[i] = Right[i] = 0; #ifdef BLACK_HOLES P[i].SwallowID = 0; #endif #if defined(BLACK_HOLES) && defined(FLTROUNDOFFREDUCTION) if(P[i].Type == 0) SphP[i].i.dInjected_BH_Energy = SphP[i].i.Injected_BH_Energy; #endif } } /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPart * sizeof(int)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct densdata_in) + sizeof(struct densdata_out) + sizemax(sizeof(struct densdata_in), sizeof(struct densdata_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); t0 = second(); desnumngb = All.DesNumNgb; /* we will repeat the whole thing for those particles where we didn't find enough neighbours */ do { i = FirstActiveParticle; /* begin with this index */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ tstart = second(); for(nexport = 0; i >= 0; i = NextActiveParticle[i]) { if(density_isactive(i)) { if(density_evaluate(i, 0, &nexport, Send_count) < 0) break; } } tend = second(); timecomp1 += timediff(tstart, tend); #ifdef MYSORT mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #else qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); #endif tstart = second(); MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); tend = second(); timewait1 += timediff(tstart, tend); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } DensDataGet = (struct densdata_in *) mymalloc(nimport * sizeof(struct densdata_in)); DensDataIn = (struct densdata_in *) mymalloc(nexport * sizeof(struct densdata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; DensDataIn[j].Pos[0] = P[place].Pos[0]; DensDataIn[j].Pos[1] = P[place].Pos[1]; DensDataIn[j].Pos[2] = P[place].Pos[2]; DensDataIn[j].Hsml = PPP[place].Hsml; #ifdef CS_MODEL DensDataIn[j].DensityOld = SphP[place].DensityOld; DensDataIn[j].Entropy = SphP[place].Entropy; #endif memcpy(DensDataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); #if defined(BLACK_HOLES) if(P[place].Type != 0) { DensDataIn[j].Vel[0] = 0; DensDataIn[j].Vel[1] = 0; DensDataIn[j].Vel[2] = 0; } else #endif { DensDataIn[j].Vel[0] = SphP[place].VelPred[0]; DensDataIn[j].Vel[1] = SphP[place].VelPred[1]; DensDataIn[j].Vel[2] = SphP[place].VelPred[2]; } #ifdef VOLUME_CORRECTION DensDataIn[j].DensityOld = SphP[place].DensityOld; #endif #ifdef EULERPOTENTIALS DensDataIn[j].EulerA = SphP[place].EulerA; DensDataIn[j].EulerB = SphP[place].EulerB; #endif #ifdef WINDS DensDataIn[j].DelayTime = SphP[place].DelayTime; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) DensDataIn[j].BPred[0] = SphP[place].BPred[0]; DensDataIn[j].BPred[1] = SphP[place].BPred[1]; DensDataIn[j].BPred[2] = SphP[place].BPred[2]; #endif } /* exchange particle data */ tstart = second(); for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the particles */ MPI_Sendrecv(&DensDataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE, recvTask, TAG_DENS_A, &DensDataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } tend = second(); timecommsumm1 += timediff(tstart, tend); myfree(DensDataIn); DensDataResult = (struct densdata_out *) mymalloc(nimport * sizeof(struct densdata_out)); DensDataOut = (struct densdata_out *) mymalloc(nexport * sizeof(struct densdata_out)); /* now do the particles that were sent to us */ tstart = second(); for(j = 0; j < nimport; j++) density_evaluate(j, 1, &dummy, &dummy); tend = second(); timecomp2 += timediff(tstart, tend); if(i < 0) ndone_flag = 1; else ndone_flag = 0; tstart = second(); MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); tend = second(); timewait2 += timediff(tstart, tend); /* get the result */ tstart = second(); for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* send the results */ MPI_Sendrecv(&DensDataResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct densdata_out), MPI_BYTE, recvTask, TAG_DENS_B, &DensDataOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct densdata_out), MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } tend = second(); timecommsumm2 += timediff(tstart, tend); /* add the result to the local particles */ tstart = second(); for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; PPP[place].n.dNumNgb += DensDataOut[j].Ngb; #ifdef HYDRO_COST_FACTOR P[place].GravCost += HYDRO_COST_FACTOR * DensDataOut[j].Ninteractions; #endif if(P[place].Type == 0) { SphP[place].d.dDensity += DensDataOut[j].Rho; SphP[place].h.dDhsmlDensityFactor += DensDataOut[j].DhsmlDensity; #ifndef NAVIERSTOKES SphP[place].v.dDivVel += DensDataOut[j].Div; SphP[place].r.dRot[0] += DensDataOut[j].Rot[0]; SphP[place].r.dRot[1] += DensDataOut[j].Rot[1]; SphP[place].r.dRot[2] += DensDataOut[j].Rot[2]; #else for(k = 0; k < 3; k++) { SphP[place].u.DV[k][0] += DensDataOut[j].DV[k][0]; SphP[place].u.DV[k][1] += DensDataOut[j].DV[k][1]; SphP[place].u.DV[k][2] += DensDataOut[j].DV[k][2]; } #endif #ifdef VOLUME_CORRECTION SphP[place].DensityStd += DensDataOut[j].DensityStd; #endif #ifdef CONDUCTION_SATURATION SphP[place].GradEntr[0] += DensDataOut[j].GradEntr[0]; SphP[place].GradEntr[1] += DensDataOut[j].GradEntr[1]; SphP[place].GradEntr[2] += DensDataOut[j].GradEntr[2]; #endif #ifdef RADTRANSFER_FLUXLIMITER SphP[place].Grad_ngamma[0] += DensDataOut[j].Grad_ngamma[0]; SphP[place].Grad_ngamma[1] += DensDataOut[j].Grad_ngamma[1]; SphP[place].Grad_ngamma[2] += DensDataOut[j].Grad_ngamma[2]; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) SphP[place].RotB[0] += DensDataOut[j].RotB[0]; SphP[place].RotB[1] += DensDataOut[j].RotB[1]; SphP[place].RotB[2] += DensDataOut[j].RotB[2]; #endif #ifdef TRACEDIVB SphP[place].divB += DensDataOut[j].divB; #endif #ifdef EULERPOTENTIALS SphP[place].dEulerA[0] += DensDataOut[j].dEulerA[0]; SphP[place].dEulerA[1] += DensDataOut[j].dEulerA[1]; SphP[place].dEulerA[2] += DensDataOut[j].dEulerA[2]; SphP[place].dEulerB[0] += DensDataOut[j].dEulerB[0]; SphP[place].dEulerB[1] += DensDataOut[j].dEulerB[1]; SphP[place].dEulerB[2] += DensDataOut[j].dEulerB[2]; #endif } #if defined(RADTRANSFER) || defined(SNIA_HEATING) if(P[place].Type == 4) P[place].DensAroundStar += DensDataOut[j].Rho; #endif #ifdef BLACK_HOLES if(P[place].Type == 5) { P[place].b1.dBH_Density += DensDataOut[j].Rho; P[place].b2.dBH_Entropy += DensDataOut[j].SmoothedEntr; P[place].b3.dBH_SurroundingGasVel[0] += DensDataOut[j].GasVel[0]; P[place].b3.dBH_SurroundingGasVel[1] += DensDataOut[j].GasVel[1]; P[place].b3.dBH_SurroundingGasVel[2] += DensDataOut[j].GasVel[2]; } #endif } tend = second(); timecomp1 += timediff(tstart, tend); myfree(DensDataOut); myfree(DensDataResult); myfree(DensDataGet); } while(ndone < NTask); #ifdef FLTROUNDOFFREDUCTION for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) if(density_isactive(i)) { PPP[i].n.NumNgb = FLT(PPP[i].n.dNumNgb); if(P[i].Type == 0) { SphP[i].d.Density = FLT(SphP[i].d.dDensity); SphP[i].h.DhsmlDensityFactor = FLT(SphP[i].h.dDhsmlDensityFactor); SphP[i].v.DivVel = FLT(SphP[i].v.dDivVel); for(j = 0; j < 3; j++) SphP[i].r.Rot[j] = FLT(SphP[i].r.dRot[j]); } #ifdef BLACK_HOLES if(P[i].Type == 5) { P[i].b1.BH_Density = FLT(P[i].b1.dBH_Density); P[i].b2.BH_Entropy = FLT(P[i].b2.dBH_Entropy); for(j = 0; j < 3; j++) P[i].b3.BH_SurroundingGasVel[j] = FLT(P[i].b3.dBH_SurroundingGasVel[j]); } #endif } #endif /* do final operations on results */ tstart = second(); for(i = FirstActiveParticle, npleft = 0; i >= 0; i = NextActiveParticle[i]) { if(density_isactive(i)) { if(P[i].Type == 0) { if(SphP[i].d.Density > 0) { #ifdef VOLUME_CORRECTION SphP[i].DensityOld = SphP[i].DensityStd; #endif SphP[i].h.DhsmlDensityFactor *= PPP[i].Hsml / (NUMDIMS * SphP[i].d.Density); if(SphP[i].h.DhsmlDensityFactor > -0.9) /* note: this would be -1 if only a single particle at zero lag is found */ SphP[i].h.DhsmlDensityFactor = 1 / (1 + SphP[i].h.DhsmlDensityFactor); else SphP[i].h.DhsmlDensityFactor = 1; #ifndef NAVIERSTOKES SphP[i].r.CurlVel = sqrt(SphP[i].r.Rot[0] * SphP[i].r.Rot[0] + SphP[i].r.Rot[1] * SphP[i].r.Rot[1] + SphP[i].r.Rot[2] * SphP[i].r.Rot[2]) / SphP[i].d.Density; SphP[i].v.DivVel /= SphP[i].d.Density; #else for(k = 0; k < 3; k++) { dvel[k][0] = SphP[i].u.DV[k][0] / SphP[i].d.Density; dvel[k][1] = SphP[i].u.DV[k][1] / SphP[i].d.Density; dvel[k][2] = SphP[i].u.DV[k][2] / SphP[i].d.Density; } SphP[i].u.s.DivVel = dvel[0][0] + dvel[1][1] + dvel[2][2]; SphP[i].u.s.StressDiag[0] = 2 * dvel[0][0] - 2.0 / 3 * SphP[i].u.s.DivVel; SphP[i].u.s.StressDiag[1] = 2 * dvel[1][1] - 2.0 / 3 * SphP[i].u.s.DivVel; SphP[i].u.s.StressDiag[2] = 2 * dvel[2][2] - 2.0 / 3 * SphP[i].u.s.DivVel; SphP[i].u.s.StressOffDiag[0] = dvel[0][1] + dvel[1][0]; /* xy */ SphP[i].u.s.StressOffDiag[1] = dvel[0][2] + dvel[2][0]; /* xz */ SphP[i].u.s.StressOffDiag[2] = dvel[1][2] + dvel[2][1]; /* yz */ #ifdef NAVIERSTOKES_BULK SphP[i].u.s.StressBulk = All.NavierStokes_BulkViscosity * SphP[i].u.s.DivVel; #endif rotx = dvel[1][2] - dvel[2][1]; roty = dvel[2][0] - dvel[0][2]; rotz = dvel[0][1] - dvel[1][0]; SphP[i].u.s.CurlVel = sqrt(rotx * rotx + roty * roty + rotz * rotz); #endif #ifdef CONDUCTION_SATURATION SphP[i].GradEntr[0] /= SphP[i].d.Density; SphP[i].GradEntr[1] /= SphP[i].d.Density; SphP[i].GradEntr[2] /= SphP[i].d.Density; #endif #ifdef RADTRANSFER_FLUXLIMITER SphP[i].Grad_ngamma[0] /= SphP[i].d.Density; SphP[i].Grad_ngamma[1] /= SphP[i].d.Density; SphP[i].Grad_ngamma[2] /= SphP[i].d.Density; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) SphP[i].RotB[0] /= SphP[i].d.Density; SphP[i].RotB[1] /= SphP[i].d.Density; SphP[i].RotB[2] /= SphP[i].d.Density; #endif #ifdef TRACEDIVB SphP[i].divB /= SphP[i].d.Density; #endif #ifdef EULERPOTENTIALS SphP[i].dEulerA[0] *= efak / SphP[i].d.Density; SphP[i].dEulerA[1] *= efak / SphP[i].d.Density; SphP[i].dEulerA[2] *= efak / SphP[i].d.Density; SphP[i].dEulerB[0] *= efak / SphP[i].d.Density; SphP[i].dEulerB[1] *= efak / SphP[i].d.Density; SphP[i].dEulerB[2] *= efak / SphP[i].d.Density; #ifdef PERIODIC SphP[i].dEulerB[2] = 1.0; #endif SphP[i].BPred[0] = SphP[i].dEulerA[1] * SphP[i].dEulerB[2] - SphP[i].dEulerA[2] * SphP[i].dEulerB[1]; SphP[i].BPred[1] = SphP[i].dEulerA[2] * SphP[i].dEulerB[0] - SphP[i].dEulerA[0] * SphP[i].dEulerB[2]; SphP[i].BPred[2] = SphP[i].dEulerA[0] * SphP[i].dEulerB[1] - SphP[i].dEulerA[1] * SphP[i].dEulerB[0]; #endif } #ifndef WAKEUP dt_step = (P[i].TimeBin ? (1 << P[i].TimeBin) : 0); #else dt_step = P[i].dt_step; #endif dt_entr = (All.Ti_Current - (P[i].Ti_begstep + dt_step / 2)) * All.Timebase_interval; #ifndef EOS_DEGENERATE #ifndef MHM #ifndef SOFTEREQS SphP[i].Pressure = (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA); #else /* use an intermediate EQS, between isothermal and the full multiphase model */ if(SphP[i].d.Density * a3inv >= All.PhysDensThresh) SphP[i].Pressure = All.FactorForSofterEQS * (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA) + (1 - All.FactorForSofterEQS) * GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU; else SphP[i].Pressure = (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA); #endif #else /* Here we use an isothermal equation of state */ SphP[i].Pressure = GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU; SphP[i].Entropy = SphP[i].Pressure / pow(SphP[i].d.Density, GAMMA); #endif #else /* call tabulated eos with physical units */ #ifdef EOS_ENERGY eos_calc_egiven2(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s, &SphP[i].temp, &SphP[i].Pressure); SphP[i].Pressure /= All.UnitPressure_in_cgs; #else eos_calc_sgiven(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s, &SphP[i].temp, &SphP[i].Pressure, &SphP[i].u); SphP[i].Pressure /= All.UnitPressure_in_cgs; #endif #endif #ifdef COSMIC_RAYS for(CRpop = 0; CRpop < NUMCRPOP; CRpop++) { CR_Particle_Update(SphP + i, CRpop); #ifndef CR_NOPRESSURE SphP[i].Pressure += CR_Comoving_Pressure(SphP + i, CRpop); #endif } #endif } #ifdef BLACK_HOLES if(P[i].Type == 5) { if(P[i].b1.BH_Density > 0) { P[i].b2.BH_Entropy /= P[i].b1.BH_Density; P[i].b3.BH_SurroundingGasVel[0] /= P[i].b1.BH_Density; P[i].b3.BH_SurroundingGasVel[1] /= P[i].b1.BH_Density; P[i].b3.BH_SurroundingGasVel[2] /= P[i].b1.BH_Density; } } #endif /* now check whether we had enough neighbours */ desnumngb = All.DesNumNgb; #ifdef BLACK_HOLES if(P[i].Type == 5) desnumngb = All.DesNumNgb * All.BlackHoleNgbFactor; #endif #ifdef RADTRANSFER if(P[i].Type == 4) desnumngb = 64;//NORM_COEFF * KERNEL_COEFF_1; /* will assign the stellar luminosity to very few (one actually) gas particles */ #endif if(PPP[i].n.NumNgb < (desnumngb - All.MaxNumNgbDeviation) || (PPP[i].n.NumNgb > (desnumngb + All.MaxNumNgbDeviation) && PPP[i].Hsml > (1.01 * All.MinGasHsml))) { /* need to redo this particle */ npleft++; if(Left[i] > 0 && Right[i] > 0) if((Right[i] - Left[i]) < 1.0e-3 * Left[i]) { /* this one should be ok */ npleft--; P[i].TimeBin = -P[i].TimeBin - 1; /* Mark as inactive */ continue; } if(PPP[i].n.NumNgb < (desnumngb - All.MaxNumNgbDeviation)) Left[i] = DMAX(PPP[i].Hsml, Left[i]); else { if(Right[i] != 0) { if(PPP[i].Hsml < Right[i]) Right[i] = PPP[i].Hsml; } else Right[i] = PPP[i].Hsml; } if(iter >= MAXITER - 10) { printf ("i=%d task=%d ID=%d Hsml=%g Left=%g Right=%g Ngbs=%g Right-Left=%g\n pos=(%g|%g|%g)\n", i, ThisTask, (int) P[i].ID, PPP[i].Hsml, Left[i], Right[i], (float) PPP[i].n.NumNgb, Right[i] - Left[i], P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]); fflush(stdout); } if(Right[i] > 0 && Left[i] > 0) PPP[i].Hsml = pow(0.5 * (pow(Left[i], 3) + pow(Right[i], 3)), 1.0 / 3); else { if(Right[i] == 0 && Left[i] == 0) endrun(8188); /* can't occur */ if(Right[i] == 0 && Left[i] > 0) { if(P[i].Type == 0 && fabs(PPP[i].n.NumNgb - desnumngb) < 0.5 * desnumngb) { fac = 1 - (PPP[i].n.NumNgb - desnumngb) / (NUMDIMS * PPP[i].n.NumNgb) * SphP[i].h.DhsmlDensityFactor; if(fac < 1.26) PPP[i].Hsml *= fac; else PPP[i].Hsml *= 1.26; } else PPP[i].Hsml *= 1.26; } if(Right[i] > 0 && Left[i] == 0) { if(P[i].Type == 0 && fabs(PPP[i].n.NumNgb - desnumngb) < 0.5 * desnumngb) { fac = 1 - (PPP[i].n.NumNgb - desnumngb) / (NUMDIMS * PPP[i].n.NumNgb) * SphP[i].h.DhsmlDensityFactor; if(fac > 1 / 1.26) PPP[i].Hsml *= fac; else PPP[i].Hsml /= 1.26; } else PPP[i].Hsml /= 1.26; } } if(PPP[i].Hsml < All.MinGasHsml) PPP[i].Hsml = All.MinGasHsml; #ifdef BLACK_HOLES if(P[i].Type == 5) if(Left[i] > All.BlackHoleMaxAccretionRadius) { /* this will stop the search for a new BH smoothing length in the next iteration */ PPP[i].Hsml = Left[i] = Right[i] = All.BlackHoleMaxAccretionRadius; } #endif } else P[i].TimeBin = -P[i].TimeBin - 1; /* Mark as inactive */ } } tend = second(); timecomp1 += timediff(tstart, tend); sumup_large_ints(1, &npleft, &ntot); if(ntot > 0) { iter++; if(iter > 0 && ThisTask == 0) { printf("ngb iteration %d: need to repeat for %d%09d particles.\n", iter, (int) (ntot / 1000000000), (int) (ntot % 1000000000)); fflush(stdout); } if(iter > MAXITER) { printf("failed to converge in neighbour iteration in density()\n"); fflush(stdout); endrun(1155); } } } while(ntot > 0); myfree(DataNodeList); myfree(DataIndexTable); myfree(Ngblist); myfree(Right); myfree(Left); #if defined(CS_MODEL) && defined(CS_FEEDBACK) double xhyd, yhel, ne, mu, energy, temp, a3inv; for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) { if(P[i].Type == 0 && P[i].EnergySN < 0) /* only gas particles should enter here */ { printf("prom 2i=%d type=%d energySN%g\n", i, P[i].Type, P[i].EnergySN); fflush(0); P[i].EnergySN = 0; } if(All.ComovingIntegrationOn) a3inv = 1 / (All.Time * All.Time * All.Time); else a3inv = 1; if(P[i].Type == 0 && (SphP[i].TempPromotion > 0 || SphP[i].DensPromotion > 0)) { xhyd = P[i].Zm[6] / P[i].Mass; yhel = (1 - xhyd) / (4. * xhyd); ne = SphP[i].Ne; mu = (1 + 4 * yhel) / (1 + yhel + ne); energy = SphP[i].Entropy * P[i].Mass / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1); /* Total Energys */ temp = GAMMA_MINUS1 / BOLTZMANN * energy / P[i].Mass * PROTONMASS * mu; temp *= All.UnitEnergy_in_cgs / All.UnitMass_in_g; /* Temperature in Kelvin */ fprintf(FdPromotion, "%g %d %g %g %g %g %g %g\n", All.Time, P[i].ID, SphP[i].DensPromotion, SphP[i].TempPromotion, SphP[i].d.Density, temp, SphP[i].da.DensityAvg, SphP[i].ea.EntropyAvg); fflush(FdPromotion); } } #endif /* mark as active again */ for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i]) if(P[i].TimeBin < 0) P[i].TimeBin = -P[i].TimeBin - 1; /* collect some timing information */ t1 = WallclockTime = second(); timeall += timediff(t0, t1); timecomp = timecomp1 + timecomp2; timewait = timewait1 + timewait2; timecomm = timecommsumm1 + timecommsumm2; CPU_Step[CPU_DENSCOMPUTE] += timecomp; CPU_Step[CPU_DENSWAIT] += timewait; CPU_Step[CPU_DENSCOMM] += timecomm; CPU_Step[CPU_DENSMISC] += timeall - (timecomp + timewait + timecomm); } /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ int density_evaluate(int target, int mode, int *nexport, int *nsend_local) { int j, n; int startnode, numngb, numngb_inbox, listindex = 0; double h, h2, fac, hinv, hinv3, hinv4; MyLongDouble rho; double wk, dwk; double dx, dy, dz, r, r2, u, mass_j; double dvx, dvy, dvz; MyLongDouble weighted_numngb; MyLongDouble dhsmlrho; #ifdef HYDRO_COST_FACTOR int ninteractions = 0; #endif #ifdef CS_MODEL double densityold, entropy = 0; #endif #ifdef BLACK_HOLES MyLongDouble gasvel[3]; #endif #ifndef NAVIERSTOKES MyLongDouble divv, rotv[3]; #else int k; double dvel[3][3]; #endif MyDouble *pos; MyFloat *vel; static MyFloat veldummy[3] = { 0, 0, 0 }; #ifdef EULERPOTENTIALS MyDouble deulera[3], deulerb[3], eulera, eulerb, dea, deb; deulera[0] = deulera[1] = deulera[2] = deulerb[0] = deulerb[1] = deulerb[2] = 0; #endif #if defined(BLACK_HOLES) MyLongDouble smoothentr; smoothentr = 0; #endif #ifdef WINDS double delaytime; #endif #ifdef VOLUME_CORRECTION double densityold, densitystd = 0; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) MyFloat *bflt; MyDouble dbx, dby, dbz; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) MyDouble rotb[3]; #endif #ifdef TRACEDIVB double divB = 0; #endif #ifdef CONDUCTION_SATURATION double gradentr[3]; gradentr[0] = gradentr[1] = gradentr[2] = 0; #endif #ifdef RADTRANSFER_FLUXLIMITER double grad_ngamma[3]; grad_ngamma[0] = grad_ngamma[1] = grad_ngamma[2] = 0; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) rotb[0] = rotb[1] = rotb[2] = 0; #endif #ifndef NAVIERSTOKES divv = rotv[0] = rotv[1] = rotv[2] = 0; #else for(k = 0; k < 3; k++) dvel[k][0] = dvel[k][1] = dvel[k][2] = 0; #endif #ifdef BLACK_HOLES gasvel[0] = gasvel[1] = gasvel[2] = 0; #endif rho = weighted_numngb = dhsmlrho = 0; if(mode == 0) { pos = P[target].Pos; h = PPP[target].Hsml; #ifdef VOLUME_CORRECTION densityold = SphP[target].DensityOld; #endif if(P[target].Type == 0) { vel = SphP[target].VelPred; #ifdef WINDS delaytime = SphP[target].DelayTime; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) bflt = SphP[target].BPred; #endif #ifdef EULERPOTENTIALS eulera = SphP[target].EulerA; eulerb = SphP[target].EulerB; #endif } else vel = veldummy; #ifdef CS_MODEL if(P[target].Type == 0) { densityold = SphP[target].DensityOld; entropy = SphP[target].Entropy; } else densityold = 0; #endif } else { pos = DensDataGet[target].Pos; vel = DensDataGet[target].Vel; h = DensDataGet[target].Hsml; #ifdef WINDS delaytime = DensDataGet[target].DelayTime; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) bflt = DensDataGet[target].BPred; #endif #ifdef VOLUME_CORRECTION densityold = DensDataGet[target].DensityOld; #endif #ifdef EULERPOTENTIALS eulera = DensDataGet[target].EulerA; eulerb = DensDataGet[target].EulerB; #endif #ifdef CS_MODEL densityold = DensDataGet[target].DensityOld; entropy = DensDataGet[target].Entropy; #endif } h2 = h * h; hinv = 1.0 / h; #ifndef TWODIMS hinv3 = hinv * hinv * hinv; #else hinv3 = hinv * hinv / boxSize_Z; #endif hinv4 = hinv3 * hinv; if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = DensDataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } numngb = 0; while(startnode >= 0) { while(startnode >= 0) { #ifdef CS_MODEL numngb_inbox = cs_ngb_treefind_variable_decoupling(&pos[0], h, target, &startnode, densityold, entropy, &vel[0], mode, nexport, nsend_local); #else numngb_inbox = ngb_treefind_variable(pos, h, target, &startnode, mode, nexport, nsend_local); #endif if(numngb_inbox < 0) return -1; for(n = 0; n < numngb_inbox; n++) { #ifdef HYDRO_COST_FACTOR ninteractions++; #endif j = Ngblist[n]; #ifdef WINDS if(SphP[j].DelayTime > 0) /* partner is a wind particle */ if(!(delaytime > 0)) /* if I'm not wind, then ignore the wind particle */ continue; #endif #ifdef BLACK_HOLES if(P[j].Mass == 0) continue; #endif dx = pos[0] - P[j].Pos[0]; dy = pos[1] - P[j].Pos[1]; dz = pos[2] - P[j].Pos[2]; #ifdef PERIODIC /* now find the closest image in the given box size */ if(dx > boxHalf_X) dx -= boxSize_X; if(dx < -boxHalf_X) dx += boxSize_X; if(dy > boxHalf_Y) dy -= boxSize_Y; if(dy < -boxHalf_Y) dy += boxSize_Y; if(dz > boxHalf_Z) dz -= boxSize_Z; if(dz < -boxHalf_Z) dz += boxSize_Z; #endif r2 = dx * dx + dy * dy + dz * dz; if(r2 < h2) { numngb++; r = sqrt(r2); u = r * hinv; if(u < 0.5) { wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); dwk = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4); } else { wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); dwk = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u); } mass_j = P[j].Mass; #ifdef VOLUME_CORRECTION rho += FLT(mass_j * wk * pow(densityold / SphP[j].DensityOld, VOLUME_CORRECTION)); densitystd += FLT(mass_j * wk); #else rho += FLT(mass_j * wk); #endif weighted_numngb += FLT(NORM_COEFF * wk / hinv3); /* 4.0/3 * PI = 4.188790204786 */ dhsmlrho += FLT(-mass_j * (NUMDIMS * hinv * wk + u * dwk)); #ifdef BLACK_HOLES smoothentr += FLT(mass_j * wk * SphP[j].Entropy); gasvel[0] += FLT(mass_j * wk * SphP[j].VelPred[0]); gasvel[1] += FLT(mass_j * wk * SphP[j].VelPred[1]); gasvel[2] += FLT(mass_j * wk * SphP[j].VelPred[2]); #endif #ifdef CONDUCTION_SATURATION if(r > 0) { gradentr[0] += mass_j * dwk * dx / r * SphP[j].Entropy; gradentr[1] += mass_j * dwk * dy / r * SphP[j].Entropy; gradentr[2] += mass_j * dwk * dz / r * SphP[j].Entropy; } #endif #ifdef RADTRANSFER_FLUXLIMITER if(r > 0) { grad_ngamma[0] += mass_j * dwk * dx / r * SphP[j].n_gamma; grad_ngamma[1] += mass_j * dwk * dy / r * SphP[j].n_gamma; grad_ngamma[2] += mass_j * dwk * dz / r * SphP[j].n_gamma; } #endif if(r > 0) { fac = mass_j * dwk / r; dvx = vel[0] - SphP[j].VelPred[0]; dvy = vel[1] - SphP[j].VelPred[1]; dvz = vel[2] - SphP[j].VelPred[2]; #ifndef NAVIERSTOKES divv += FLT(-fac * (dx * dvx + dy * dvy + dz * dvz)); rotv[0] += FLT(fac * (dz * dvy - dy * dvz)); rotv[1] += FLT(fac * (dx * dvz - dz * dvx)); rotv[2] += FLT(fac * (dy * dvx - dx * dvy)); #else dvel[0][0] -= fac * dx * dvx; dvel[0][1] -= fac * dx * dvy; dvel[0][2] -= fac * dx * dvz; dvel[1][0] -= fac * dy * dvx; dvel[1][1] -= fac * dy * dvy; dvel[1][2] -= fac * dy * dvz; dvel[2][0] -= fac * dz * dvx; dvel[2][1] -= fac * dz * dvy; dvel[2][2] -= fac * dz * dvz; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB) dbx = bflt[0] - SphP[j].BPred[0]; dby = bflt[1] - SphP[j].BPred[1]; dbz = bflt[2] - SphP[j].BPred[2]; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) rotb[0] += FLT(fac * (dz * dby - dy * dbz)); rotb[1] += FLT(fac * (dx * dbz - dz * dbx)); rotb[2] += FLT(fac * (dy * dbx - dx * dby)); #endif #ifdef TRACEDIVB divB += fac * (dbx * dx + dby * dy + dbz * dz); #endif #ifdef EULERPOTENTIALS dea = eulera - SphP[j].EulerA; deb = eulerb - SphP[j].EulerB; deulera[0] -= fac * dx * dea; deulera[1] -= fac * dy * dea; deulera[2] -= fac * dz * dea; deulerb[0] -= fac * dx * deb; deulerb[1] -= fac * dy * deb; deulerb[2] -= fac * dz * deb; #endif } } } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = DensDataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) { PPP[target].n.dNumNgb = weighted_numngb; #ifdef HYDRO_COST_FACTOR P[target].GravCost += HYDRO_COST_FACTOR * ninteractions; #endif if(P[target].Type == 0) { SphP[target].d.dDensity = rho; #ifdef VOLUME_CORRECTION SphP[target].DensityStd = densitystd; #endif SphP[target].h.dDhsmlDensityFactor = dhsmlrho; #ifndef NAVIERSTOKES SphP[target].v.dDivVel = divv; SphP[target].r.dRot[0] = rotv[0]; SphP[target].r.dRot[1] = rotv[1]; SphP[target].r.dRot[2] = rotv[2]; #else for(k = 0; k < 3; k++) { SphP[target].u.DV[k][0] = dvel[k][0]; SphP[target].u.DV[k][1] = dvel[k][1]; SphP[target].u.DV[k][2] = dvel[k][2]; } #endif #ifdef CONDUCTION_SATURATION SphP[target].GradEntr[0] = gradentr[0]; SphP[target].GradEntr[1] = gradentr[1]; SphP[target].GradEntr[2] = gradentr[2]; #endif #ifdef RADTRANSFER_FLUXLIMITER SphP[target].Grad_ngamma[0] = grad_ngamma[0]; SphP[target].Grad_ngamma[1] = grad_ngamma[1]; SphP[target].Grad_ngamma[2] = grad_ngamma[2]; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) SphP[target].RotB[0] = rotb[0]; SphP[target].RotB[1] = rotb[1]; SphP[target].RotB[2] = rotb[2]; #endif #ifdef TRACEDIVB SphP[target].divB = divB; #endif #ifdef EULERPOTENTIALS SphP[target].dEulerA[0] = deulera[0]; SphP[target].dEulerA[1] = deulera[1]; SphP[target].dEulerA[2] = deulera[2]; SphP[target].dEulerB[0] = deulerb[0]; SphP[target].dEulerB[1] = deulerb[1]; SphP[target].dEulerB[2] = deulerb[2]; #endif } #ifdef BLACK_HOLES P[target].b1.dBH_Density = rho; P[target].b2.dBH_Entropy = smoothentr; P[target].b3.dBH_SurroundingGasVel[0] = gasvel[0]; P[target].b3.dBH_SurroundingGasVel[1] = gasvel[1]; P[target].b3.dBH_SurroundingGasVel[2] = gasvel[2]; #endif #if defined(RADTRANSFER) || defined(SNIA_HEATING) if(P[target].Type == 4) P[target].DensAroundStar = rho; #endif } else { #ifdef HYDRO_COST_FACTOR DensDataResult[target].Ninteractions = ninteractions; #endif DensDataResult[target].Rho = rho; #ifdef VOLUME_CORRECTION DensDataResult[target].DensityStd = densitystd; #endif DensDataResult[target].Ngb = weighted_numngb; DensDataResult[target].DhsmlDensity = dhsmlrho; #ifndef NAVIERSTOKES DensDataResult[target].Div = divv; DensDataResult[target].Rot[0] = rotv[0]; DensDataResult[target].Rot[1] = rotv[1]; DensDataResult[target].Rot[2] = rotv[2]; #else for(k = 0; k < 3; k++) { DensDataResult[target].DV[k][0] = dvel[k][0]; DensDataResult[target].DV[k][1] = dvel[k][1]; DensDataResult[target].DV[k][2] = dvel[k][2]; } #endif #if defined(BLACK_HOLES) DensDataResult[target].SmoothedEntr = smoothentr; #endif #ifdef CONDUCTION_SATURATION DensDataResult[target].GradEntr[0] = gradentr[0]; DensDataResult[target].GradEntr[1] = gradentr[1]; DensDataResult[target].GradEntr[2] = gradentr[2]; #endif #ifdef RADTRANSFER_FLUXLIMITER DensDataResult[target].Grad_ngamma[0] = grad_ngamma[0]; DensDataResult[target].Grad_ngamma[1] = grad_ngamma[1]; DensDataResult[target].Grad_ngamma[2] = grad_ngamma[2]; #endif #if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) DensDataResult[target].RotB[0] = rotb[0]; DensDataResult[target].RotB[1] = rotb[1]; DensDataResult[target].RotB[2] = rotb[2]; #endif #ifdef TRACEDIVB DensDataResult[target].divB = divB; #endif #ifdef BLACK_HOLES DensDataResult[target].GasVel[0] = gasvel[0]; DensDataResult[target].GasVel[1] = gasvel[1]; DensDataResult[target].GasVel[2] = gasvel[2]; #endif #ifdef EULERPOTENTIALS DensDataResult[target].dEulerA[0] = deulera[0]; DensDataResult[target].dEulerA[1] = deulera[1]; DensDataResult[target].dEulerA[2] = deulera[2]; DensDataResult[target].dEulerB[0] = deulerb[0]; DensDataResult[target].dEulerB[1] = deulerb[1]; DensDataResult[target].dEulerB[2] = deulerb[2]; #endif } return 0; } int density_isactive(int n) { if(P[n].TimeBin < 0) return 0; #if defined(RADTRANSFER) || defined(SNIA_HEATING) if(P[n].Type == 4) return 1; #endif #ifdef BLACK_HOLES if(P[n].Type == 5) return 1; #endif if(P[n].Type == 0) return 1; return 0; } #ifdef NAVIERSTOKES double get_shear_viscosity(int i) { return All.NavierStokes_ShearViscosity; } #endif
{ "alphanum_fraction": 0.6163847412, "avg_line_length": 27.0311594203, "ext": "c", "hexsha": "b29cf80dee7b271782e43c20b6492467ff3b98cd", "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/density.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/density.c", "max_line_length": 129, "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/density.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13406, "size": 37303 }
#ifndef DART_COMMON_H #define DART_COMMON_H // Automatically detect libraries if possible. #if defined(__has_include) # if !defined(DART_HAS_RAPIDJSON) # define DART_HAS_RAPIDJSON __has_include(<rapidjson/reader.h>) && __has_include(<rapidjson/writer.h>) # endif # ifndef DART_HAS_YAML # define DART_HAS_YAML __has_include(<yaml.h>) # endif #endif /*----- System Includes -----*/ #include <map> #include <vector> #include <math.h> #include <gsl/gsl> #include <errno.h> #include <cstdlib> #include <stdarg.h> #include <limits.h> #include <algorithm> #if DART_HAS_RAPIDJSON #include <rapidjson/reader.h> #include <rapidjson/writer.h> #include <rapidjson/document.h> #include <rapidjson/error/en.h> #endif #if DART_HAS_YAML #include <yaml.h> #endif /*----- Local Includes -----*/ #include "shim.h" #include "meta.h" #include "support/ptrs.h" #include "support/ordered.h" /*----- System Includes with Compiler Flags -----*/ // Current version of sajson emits unused parameter // warnings on Clang. #ifdef DART_USE_SAJSON #if DART_USING_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wunused-parameter" #endif #include <sajson.h> #if DART_USING_CLANG #pragma clang diagnostic pop #endif #endif /*----- Macro Definitions -----*/ #define DART_FROM_THIS \ reinterpret_cast<gsl::byte const*>(this) #define DART_FROM_THIS_MUT \ reinterpret_cast<gsl::byte*>(this) /*----- Global Declarations -----*/ namespace dart { template <class Object> class basic_object; template <class Array> class basic_array; template <class String> class basic_string; template <class Number> class basic_number; template <class Boolean> class basic_flag; template <class Null> class basic_null; template <template <class> class RefCount> class basic_heap; template <template <class> class RefCount> class basic_buffer; template <template <class> class RefCount> class basic_packet; struct type_error : std::logic_error { type_error(char const* msg) : logic_error(msg) {} }; struct state_error : std::runtime_error { state_error(char const* msg) : runtime_error(msg) {} }; struct parse_error : std::runtime_error { parse_error(char const* msg) : runtime_error(msg) {} }; struct validation_error : std::runtime_error { validation_error(char const* msg) : runtime_error(msg) {} }; namespace detail { template <class T> struct is_dart_type : std::false_type {}; template <template <class> class RC> struct is_dart_type<dart::basic_heap<RC>> : std::true_type {}; template <template <class> class RC> struct is_dart_type<dart::basic_buffer<RC>> : std::true_type {}; template <template <class> class RC> struct is_dart_type<dart::basic_packet<RC>> : std::true_type {}; template <class T> struct is_wrapper_type : std::false_type {}; template <class T> struct is_wrapper_type<dart::basic_object<T>> : std::true_type {}; template <class T> struct is_wrapper_type<dart::basic_array<T>> : std::true_type {}; template <class T> struct is_wrapper_type<dart::basic_string<T>> : std::true_type {}; template <class T> struct is_wrapper_type<dart::basic_number<T>> : std::true_type {}; template <class T> struct is_wrapper_type<dart::basic_flag<T>> : std::true_type {}; template <class T> struct is_wrapper_type<dart::basic_null<T>> : std::true_type {}; template <class T> struct is_dart_api_type : std::false_type {}; template <template <class> class RC> struct is_dart_api_type<dart::basic_heap<RC>> : std::true_type {}; template <template <class> class RC> struct is_dart_api_type<dart::basic_buffer<RC>> : std::true_type {}; template <template <class> class RC> struct is_dart_api_type<dart::basic_packet<RC>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_object<T>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_array<T>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_string<T>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_number<T>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_flag<T>> : std::true_type {}; template <class T> struct is_dart_api_type<dart::basic_null<T>> : std::true_type {}; template <class T> struct maybe_cast_return { template <class U, class = std::enable_if_t< std::is_pointer<U>::value || is_dart_type<U>::value > > static U detect(int); template <class U> static shim::optional<U> detect(...); using type = decltype(detect<T>(0)); }; template <class T> using maybe_cast_return_t = typename maybe_cast_return<T>::type; /** * @brief * Enum encodes the type of an individual packet instance. * * @details * Internally, dart::packet manages a much larger set of types that encode ancillary information * such as precision, signedness, alignment, size, however, all internal types map onto one of those * contained in dart::packet::type, and all public API functions conceptually interact with objects * of these types. */ enum class type : uint8_t { object, array, string, integer, decimal, boolean, null }; /** * @brief * Low-level type information that encodes information about the underlying machine-type, * like precision, signedness, etc. */ enum class raw_type : uint8_t { object, array, string, small_string, big_string, short_integer, integer, long_integer, decimal, long_decimal, boolean, null }; /** * @brief * Used internally in scenarios where two dart types aren't contained within * some existing data structure, but they need to be paired together. */ template <class Packet> struct basic_pair { /*----- Lifecycle Functions -----*/ basic_pair() = default; template <class P, class = std::enable_if_t< std::is_convertible< P, Packet >::value > > basic_pair(P&& key, P&& value) : key(std::forward<P>(key)), value(std::forward<P>(value)) {} basic_pair(basic_pair const&) = default; basic_pair(basic_pair&&) = default; ~basic_pair() = default; /*----- Operators -----*/ basic_pair& operator =(basic_pair const&) = default; basic_pair& operator =(basic_pair&&) = default; /*----- Members -----*/ Packet key, value; }; template <template <class> class RefCount> using heap_pair = basic_pair<basic_heap<RefCount>>; template <template <class> class RefCount> using buffer_pair = basic_pair<basic_buffer<RefCount>>; template <template <class> class RefCount> using packet_pair = basic_pair<basic_packet<RefCount>>; /** * @brief * Helper-struct for sorting `dart::packet`s within `std::map`s. */ template <template <class> class RefCount> struct dart_comparator { using is_transparent = shim::string_view; bool operator ()(shim::string_view lhs, shim::string_view rhs) const; // Comparison between some packet type and a string template <template <template <class> class> class Packet> bool operator ()(Packet<RefCount> const& lhs, shim::string_view rhs) const; template <template <template <class> class> class Packet> bool operator ()(shim::string_view lhs, Packet<RefCount> const& rhs) const; // Comparison between a key-value pair of some packet type and a string template <template <template <class> class> class Packet> bool operator ()(basic_pair<Packet<RefCount>> const& lhs, shim::string_view rhs) const; template <template <template <class> class> class Packet> bool operator ()(shim::string_view lhs, basic_pair<Packet<RefCount>> const& rhs) const; // Comparison between two, potentially disparate, packet types template < template <template <class> class> class LhsPacket, template <template <class> class> class RhsPacket > bool operator ()(LhsPacket<RefCount> const& lhs, RhsPacket<RefCount> const& rhs) const; // Comparison between a key-value pair of some packet type and some, // potentially disparate, packet type template < template <template <class> class> class LhsPacket, template <template <class> class> class RhsPacket > bool operator ()(basic_pair<LhsPacket<RefCount>> const& lhs, RhsPacket<RefCount> const& rhs) const; template < template <template <class> class> class LhsPacket, template <template <class> class> class RhsPacket > bool operator ()(LhsPacket<RefCount> const& lhs, basic_pair<RhsPacket<RefCount>> const& rhs) const; // Comparison between a key-value pair of some packet type and // a key-value pair of some, potentially disparate, packet type. template < template <template <class> class> class LhsPacket, template <template <class> class> class RhsPacket > bool operator ()(basic_pair<LhsPacket<RefCount>> const& lhs, basic_pair<RhsPacket<RefCount>> const& rhs) const; }; struct dynamic_string_layout { bool operator ==(dynamic_string_layout const& other) const noexcept { if (len != other.len) return false; else return !strcmp(ptr.get(), other.ptr.get()); } bool operator !=(dynamic_string_layout const& other) const noexcept { return !(*this == other); } std::shared_ptr<char> ptr; size_t len; }; struct inline_string_layout { bool operator ==(inline_string_layout const& other) const noexcept { if (left != other.left) return false; else return !strcmp(buffer.data(), other.buffer.data()); } bool operator !=(inline_string_layout const& other) const noexcept { return !(*this == other); } std::array<char, sizeof(dynamic_string_layout) - sizeof(uint8_t)> buffer; uint8_t left; }; /** * @brief * Helper-struct for safely comparing objects of any type. */ struct typeless_comparator { template <class Lhs, class Rhs> bool operator ()(Lhs&& lhs, Rhs&& rhs) const noexcept; }; template <template <class> class RefCount> using buffer_refcount_type = shareable_ptr<RefCount<gsl::byte const>>; class prefix_entry; template <class> struct table_layout { using offset_type = uint32_t; static constexpr auto max_offset = std::numeric_limits<offset_type>::max(); alignas(4) little_order<offset_type> offset; alignas(4) little_order<uint8_t> type; }; template <> struct table_layout<prefix_entry> { using offset_type = uint32_t; using prefix_type = uint16_t; static constexpr auto max_offset = std::numeric_limits<offset_type>::max(); alignas(4) little_order<uint32_t> offset; alignas(1) little_order<uint8_t> type; alignas(1) little_order<uint8_t> len; alignas(2) prefix_type prefix; }; /** * @brief * Macro customizes functionality usually provided by assert(). * * @details * Not strictly necessary, but tries to provide a bit more context and * information as to why I just murdered the user's program (in production, no doubt). * * @remarks * Don't actually know if Doxygen lets you document macros, guess we'll see. */ template <class T> class vtable_entry { public: /*----- Lifecycle Functions -----*/ vtable_entry(detail::raw_type type, uint32_t offset); vtable_entry(vtable_entry const&) = default; /*----- Operators -----*/ vtable_entry& operator =(vtable_entry const&) = default; /*----- Public API -----*/ raw_type get_type() const noexcept; uint32_t get_offset() const noexcept; // This sucks, but we need it for dart::buffer::inject void adjust_offset(std::ptrdiff_t diff) noexcept; protected: /*----- Protected Members -----*/ table_layout<T> layout; }; /** * @brief * Class represents an entry in the vtable of an object. * * @details * Class wraps memory that is stored in little endian byte order, * irrespective of the native ordering of the host machine. * In other words, attempt to subvert its API at your peril. * * @remarks * Although class inherts from vtable_entry, and can be safely * be used as such, it remains a standard layout type due to some * hackery with its internals. */ class prefix_entry : public vtable_entry<prefix_entry> { public: /*----- Public Types -----*/ using prefix_type = table_layout<prefix_entry>::prefix_type; /*----- Lifecycle Functions -----*/ inline prefix_entry(detail::raw_type type, uint32_t offset, shim::string_view prefix) noexcept; prefix_entry(prefix_entry const&) = default; /*----- Operators -----*/ prefix_entry& operator =(prefix_entry const&) = default; /*----- Public API -----*/ inline int prefix_compare(shim::string_view str) const noexcept; private: /*----- Private Helpers -----*/ inline int compare_impl(char const* const str, size_t const len) const noexcept; /*----- Private Types -----*/ using storage_t = std::aligned_storage_t<sizeof(prefix_type), 4>; }; using object_entry = prefix_entry; using array_entry = vtable_entry<void>; using object_layout = table_layout<prefix_entry>; using array_layout = table_layout<void>; static_assert(std::is_standard_layout<array_entry>::value, "dart library is misconfigured"); static_assert(std::is_standard_layout<object_entry>::value, "dart library is misconfigured"); // Aliases for STL structures. template <template <class> class RefCount> using packet_elements = std::vector<refcount::owner_indirection_t<basic_heap, RefCount>>; template <template <class> class RefCount> using packet_fields = std::map< refcount::owner_indirection_t<basic_heap, RefCount>, refcount::owner_indirection_t<basic_heap, RefCount>, refcount::owner_indirection_t<dart_comparator, RefCount> >; /** * @brief * Struct represents the minimum context required to perform * an operation on a dart::buffer object. * * @details * At its core, this is what dart::buffer "is". * It just provides a nice API, and some memory safety around * this structure, which is why it's so fast. */ struct raw_element { raw_type type; gsl::byte const* buffer; }; /** * @brief * Struct is the lowest level abstraction for safe iteration over a dart::buffer * object/array. * * @details * Struct holds onto the context for what vtable entry it's currently on, * where the base of its aggregate is, and how to dereference itself. * * @remarks * ll_iterator holds onto more state than I'd like, but it's kind of unavoidable * given the fact that the vtable provides offsets from the base of the aggregate * itself and the fact that we may be iterating over values OR pairs of values. */ template <template <class> class RefCount> struct ll_iterator { /*----- Types -----*/ using value_type = raw_element; using loading_function = value_type (gsl::byte const*, size_t idx); /*----- Lifecycle Functions -----*/ ll_iterator() = delete; ll_iterator(size_t idx, gsl::byte const* base, loading_function* load_func) noexcept : idx(idx), base(base), load_func(load_func) {} ll_iterator(ll_iterator const&) = default; ll_iterator(ll_iterator&&) noexcept = default; ~ll_iterator() = default; /*----- Operators -----*/ ll_iterator& operator =(ll_iterator const&) = default; ll_iterator& operator =(ll_iterator&&) noexcept = default; bool operator ==(ll_iterator const& other) const noexcept; bool operator !=(ll_iterator const& other) const noexcept; auto operator ++() noexcept -> ll_iterator&; auto operator --() noexcept -> ll_iterator&; auto operator ++(int) noexcept -> ll_iterator; auto operator --(int) noexcept -> ll_iterator; auto operator *() const noexcept -> value_type; /*----- Members -----*/ size_t idx; gsl::byte const* base; loading_function* load_func; }; /** * @brief * Struct is the lowest level abstraction for safe iteration over a dart::heap * object/array. * * @details * Struct simply wraps an STL iterator of some type, and a way to dereference it. */ template <template <class> class RefCount> struct dn_iterator { /*----- Types -----*/ using value_type = basic_heap<RefCount>; using reference = value_type const&; using fields_deref_func = reference (typename packet_fields<RefCount>::const_iterator const&); using elements_deref_func = reference (typename packet_elements<RefCount>::const_iterator const&); struct fields_layout { fields_deref_func* deref; typename packet_fields<RefCount>::const_iterator it; }; struct elements_layout { elements_deref_func* deref; typename packet_elements<RefCount>::const_iterator it; }; using implerator = shim::variant<fields_layout, elements_layout>; /*----- Lifecycle Functions -----*/ dn_iterator() = delete; dn_iterator(typename packet_fields<RefCount>::const_iterator it, fields_deref_func* func) noexcept : impl(fields_layout {func, it}) {} dn_iterator(typename packet_elements<RefCount>::const_iterator it, elements_deref_func* func) noexcept : impl(elements_layout {func, it}) {} dn_iterator(dn_iterator const&) = default; dn_iterator(dn_iterator&&) noexcept = default; ~dn_iterator() = default; /*----- Operators -----*/ dn_iterator& operator =(dn_iterator const&) = default; dn_iterator& operator =(dn_iterator&&) noexcept = default; bool operator ==(dn_iterator const& other) const noexcept; bool operator !=(dn_iterator const& other) const noexcept; auto operator ++() noexcept -> dn_iterator&; auto operator --() noexcept -> dn_iterator&; auto operator ++(int) noexcept -> dn_iterator; auto operator --(int) noexcept -> dn_iterator; auto operator *() const noexcept -> reference; /*----- Members -----*/ implerator impl; }; template <template <class> class RefCount> using dynamic_iterator = refcount::owner_indirection_t<dn_iterator, RefCount>; /** * @brief * Class is the lowest level abstraction for safe interaction with * a dart::buffer object. * * @details * Class wraps memory that is stored in little endian byte order, * irrespective of the native ordering of the host machine. * In other words, attempt to subvert its API at your peril. */ template <template <class> class RefCount> class object { public: /*----- Lifecycle Functions -----*/ object() = delete; // JSON Constructors #ifdef DART_USE_SAJSON explicit object(sajson::value fields) noexcept; #endif #if DART_HAS_RAPIDJSON explicit object(rapidjson::Value const& fields) noexcept; #endif // Direct constructors explicit object(gsl::span<packet_pair<RefCount>> pairs) noexcept; explicit object(packet_fields<RefCount> const* fields) noexcept; // Special constructors object(object const* base, object const* incoming) noexcept; template <class Key> object(object const* base, gsl::span<Key const*> key_ptrs) noexcept; object(object const&) = delete; ~object() = delete; /*----- Operators -----*/ object& operator =(object const&) = delete; /*----- Public API -----*/ template <bool silent> bool is_valid(size_t bytes) const noexcept(silent); size_t size() const noexcept; size_t get_sizeof() const noexcept; auto begin() const noexcept -> ll_iterator<RefCount>; auto key_begin() const noexcept -> ll_iterator<RefCount>; auto end() const noexcept -> ll_iterator<RefCount>; auto key_end() const noexcept -> ll_iterator<RefCount>; template <class Callback> auto get_key(shim::string_view const key, Callback&& cb) const noexcept -> raw_element; auto get_it(shim::string_view const key) const noexcept -> ll_iterator<RefCount>; auto get_key_it(shim::string_view const key) const noexcept -> ll_iterator<RefCount>; auto get_value(shim::string_view const key) const noexcept -> raw_element; auto at_value(shim::string_view const key) const -> raw_element; static auto load_key(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type; static auto load_value(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type; /*----- Public Members -----*/ static constexpr auto alignment = sizeof(int64_t); private: /*----- Private Helpers -----*/ size_t realign(size_t guess, size_t offset) noexcept; template <class Callback> auto get_value_impl(shim::string_view const key, Callback&& cb) const -> raw_element; object_entry* vtable() noexcept; object_entry const* vtable() const noexcept; gsl::byte* raw_vtable() noexcept; gsl::byte const* raw_vtable() const noexcept; /*----- Private Members -----*/ alignas(4) little_order<uint32_t> bytes; alignas(4) little_order<uint32_t> elems; static constexpr auto header_len = sizeof(bytes) + sizeof(elems); }; static_assert(std::is_standard_layout<object<std::shared_ptr>>::value, "dart library is misconfigured"); /** * @brief * Class is the lowest level abstraction for safe interaction with * a dart::buffer array. * * @details * Class wraps memory that is stored in little endian byte order, * irrespective of the native ordering of the host machine. * In other words, attempt to subvert its API at your peril. */ template <template <class> class RefCount> class array { public: /*----- Lifecycle Functions -----*/ array() = delete; #ifdef DART_USE_SAJSON explicit array(sajson::value elems) noexcept; #endif #if DART_HAS_RAPIDJSON explicit array(rapidjson::Value const& elems) noexcept; #endif array(packet_elements<RefCount> const* elems) noexcept; array(array const&) = delete; ~array() = delete; /*----- Operators -----*/ array& operator =(array const&) = delete; /*----- Public API -----*/ template <bool silent> bool is_valid(size_t bytes) const noexcept(silent); size_t size() const noexcept; size_t get_sizeof() const noexcept; auto begin() const noexcept -> ll_iterator<RefCount>; auto end() const noexcept -> ll_iterator<RefCount>; auto get_elem(size_t index) const noexcept -> raw_element; auto at_elem(size_t index) const -> raw_element; static auto load_elem(gsl::byte const* base, size_t idx) noexcept -> typename ll_iterator<RefCount>::value_type; /*----- Public Members -----*/ static constexpr auto alignment = sizeof(int64_t); private: /*----- Private Helpers -----*/ auto get_elem_impl(size_t index, bool throw_if_absent) const -> raw_element; array_entry* vtable() noexcept; array_entry const* vtable() const noexcept; gsl::byte* raw_vtable() noexcept; gsl::byte const* raw_vtable() const noexcept; /*----- Private Members -----*/ alignas(4) little_order<uint32_t> bytes; alignas(4) little_order<uint32_t> elems; static constexpr auto header_len = sizeof(bytes) + sizeof(elems); }; static_assert(std::is_standard_layout<array<std::shared_ptr>>::value, "dart library is misconfigured"); /** * @brief * Class is the lowest level abstraction for safe interaction with * a dart::buffer string. * * @details * Class wraps memory that is stored in little endian byte order, * irrespective of the native ordering of the host machine. * In other words, attempt to subvert its API at your peril. */ template <class SizeType> class basic_string { public: /*----- Public Types -----*/ using size_type = SizeType; /*----- Lifecycle Functions -----*/ basic_string() = delete; explicit basic_string(shim::string_view strv) noexcept; explicit basic_string(char const* str, size_t len) noexcept; basic_string(basic_string const&) = delete; ~basic_string() = delete; /*----- Operators -----*/ basic_string& operator =(basic_string const&) = delete; /*----- Public API -----*/ template <bool silent> bool is_valid(size_t bytes) const noexcept(silent); size_t size() const noexcept; size_t get_sizeof() const noexcept; shim::string_view get_strv() const noexcept; static size_t static_sizeof(size_type len) noexcept; /*----- Public Members -----*/ static constexpr auto alignment = sizeof(size_type); private: /*----- Private Helpers -----*/ char* data() noexcept; char const* data() const noexcept; /*----- Private Members -----*/ alignas(alignment) little_order<size_type> len; static constexpr auto header_len = sizeof(len); }; using string = basic_string<uint16_t>; using big_string = basic_string<uint32_t>; static_assert(std::is_standard_layout<string>::value, "dart library is misconfigured"); static_assert(std::is_standard_layout<big_string>::value, "dart library is misconfigured"); /** * @brief * Class is the lowest level abstraction for safe interaction with * a dart::buffer primitive value. * * @details * Class wraps memory that is stored in little endian byte order, * irrespective of the native ordering of the host machine. * In other words, attempt to subvert its API at your peril. */ template <class T> class primitive { public: /*----- Lifecycle Functions -----*/ primitive() = delete; explicit primitive(T data) noexcept : data(data) {} primitive(primitive const&) = delete; ~primitive() = delete; /*---- Operators -----*/ primitive& operator =(primitive const&) = delete; /*----- Public API -----*/ template <bool silent> bool is_valid(size_t bytes) const noexcept(silent); size_t get_sizeof() const noexcept; T get_data() const noexcept; static size_t static_sizeof() noexcept; /*----- Public Members -----*/ static constexpr auto alignment = sizeof(T); private: /*----- Private Members -----*/ alignas(alignment) little_order<T> data; static constexpr auto header_len = sizeof(data); }; static_assert(std::is_standard_layout<primitive<int>>::value, "dart library is misconfigured"); template <template <class> class RefCount> struct buffer_builder { using buffer = basic_buffer<RefCount>; template <class Span> static auto build_buffer(Span pairs) -> buffer; static auto merge_buffers(buffer const& base, buffer const& incoming) -> buffer; template <class Spannable> static auto project_keys(buffer const& base, Spannable const& keys) -> buffer; template <class Callback> static void each_unique_pair(object<RefCount> const* base, object<RefCount> const* incoming, Callback&& cb); template <class Key, class Callback> static void project_each_pair(object<RefCount> const* base, gsl::span<Key const*> key_ptrs, Callback&& cb); template <class Span> static size_t max_bytes(Span pairs); }; // Used for tag dispatch from factory functions. struct view_tag {}; struct object_tag { static constexpr auto alignment = object<std::shared_ptr>::alignment; }; struct array_tag { static constexpr auto alignment = array<std::shared_ptr>::alignment; }; struct string_tag { static constexpr auto alignment = big_string::alignment; }; struct small_string_tag : string_tag { static constexpr auto alignment = string::alignment; }; struct big_string_tag : string_tag { static constexpr auto alignment = string_tag::alignment; }; struct integer_tag { static constexpr auto alignment = primitive<int64_t>::alignment; }; struct short_integer_tag : integer_tag { static constexpr auto alignment = primitive<int16_t>::alignment; }; struct medium_integer_tag : integer_tag { static constexpr auto alignment = primitive<int32_t>::alignment; }; struct long_integer_tag : integer_tag { static constexpr auto alignment = integer_tag::alignment; }; struct decimal_tag { static constexpr auto alignment = primitive<double>::alignment; }; struct short_decimal_tag : decimal_tag { static constexpr auto alignment = primitive<float>::alignment; }; struct long_decimal_tag : decimal_tag { static constexpr auto alignment = decimal_tag::alignment; }; struct boolean_tag { static constexpr auto alignment = primitive<bool>::alignment; }; struct null_tag { static constexpr auto alignment = 1; }; /** * @brief * Function converts between internal type information and * user-facing type information. * * @details * Dart internally has to encode significantly more complicated * type information than it publicly exposes, so this function * works as a an efficient go-between for the two. */ inline type simplify_type(raw_type type) noexcept { switch (type) { case raw_type::object: return detail::type::object; case raw_type::array: return detail::type::array; case raw_type::small_string: case raw_type::string: case raw_type::big_string: return detail::type::string; case raw_type::short_integer: case raw_type::integer: case raw_type::long_integer: return detail::type::integer; case raw_type::decimal: case raw_type::long_decimal: return detail::type::decimal; case raw_type::boolean: return detail::type::boolean; default: DART_ASSERT(type == raw_type::null); return detail::type::null; } } inline bool valid_type(raw_type type) noexcept { switch (type) { case raw_type::object: case raw_type::array: case raw_type::string: case raw_type::small_string: case raw_type::big_string: case raw_type::short_integer: case raw_type::integer: case raw_type::long_integer: case raw_type::decimal: case raw_type::long_decimal: case raw_type::boolean: case raw_type::null: return true; default: return false; } } /** * @brief * Function provides a "safe" bridge between the high level * and low level object apis. * * @details * Don't pass it null. * Tries its damndest not to invoke UB, but god knows. */ template <template <class> class RefCount> object<RefCount> const* get_object(raw_element raw) { if (simplify_type(raw.type) == type::object) { DART_ASSERT(raw.buffer != nullptr); return shim::launder(reinterpret_cast<object<RefCount> const*>(raw.buffer)); } else { throw type_error("dart::buffer is not a finalized object and cannot be accessed as such"); } } /** * @brief * Function provides a "safe" bridge between the high level * and low level array apis. * * @details * Don't pass it null. * Tries its damndest not to invoke UB, but god knows. */ template <template <class> class RefCount> array<RefCount> const* get_array(raw_element raw) { if (simplify_type(raw.type) == type::array) { DART_ASSERT(raw.buffer != nullptr); return shim::launder(reinterpret_cast<array<RefCount> const*>(raw.buffer)); } else { throw type_error("dart::buffer is not a finalized array and cannot be accessed as such"); } } /** * @brief * Function provides a "safe" bridge between the high level * and low level string apis. * * @details * Don't pass it null. * Tries its damndest not to invoke UB, but god knows. */ inline string const* get_string(raw_element raw) { if (raw.type == raw_type::small_string || raw.type == raw_type::string) { DART_ASSERT(raw.buffer != nullptr); return shim::launder(reinterpret_cast<string const*>(raw.buffer)); } else { throw type_error("dart::buffer is not a finalized string and cannot be accessed as such"); } } /** * @brief * Function provides a "safe" bridge between the high level * and low level string apis. * * @details * Don't pass it null. * Tries its damndest not to invoke UB, but god knows. */ inline big_string const* get_big_string(raw_element raw) { if (raw.type == raw_type::big_string) { DART_ASSERT(raw.buffer != nullptr); return shim::launder(reinterpret_cast<big_string const*>(raw.buffer)); } else { throw type_error("dart::buffer is not a finalized string and cannot be accessed as such"); } } /** * @brief * Function provides a "safe" bridge between the high level * and low level primitive apis. * * @details * Don't pass it null. * Tries its damndest not to invoke UB, but god knows. */ template <class T> primitive<T> const* get_primitive(raw_element raw) { auto simple = simplify_type(raw.type); if (simple == type::integer || simple == type::decimal || simple == type::boolean) { DART_ASSERT(raw.buffer != nullptr); return shim::launder(reinterpret_cast<primitive<T> const*>(raw.buffer)); } else { throw type_error("dart::buffer is not a finalized primitive and cannot be accessed as such"); } } template <template <class> class RefCount, class Callback> auto aggregate_deref(Callback&& cb, raw_element raw) -> std::common_type_t< decltype(std::forward<Callback>(cb)(std::declval<object<RefCount>&>())), decltype(std::forward<Callback>(cb)(std::declval<array<RefCount>&>())) > { switch (raw.type) { case raw_type::object: return std::forward<Callback>(cb)(*get_object<RefCount>(raw)); case raw_type::array: return std::forward<Callback>(cb)(*get_array<RefCount>(raw)); default: throw type_error("dart::buffer is not a finalized aggregate and cannot be accessed as such"); } } template <class Callback> auto string_deref(Callback&& cb, raw_element raw) -> std::common_type_t< decltype(std::forward<Callback>(cb)(std::declval<string&>())), decltype(std::forward<Callback>(cb)(std::declval<big_string&>())) > { switch (raw.type) { case raw_type::small_string: case raw_type::string: return std::forward<Callback>(cb)(*get_string(raw)); case raw_type::big_string: return std::forward<Callback>(cb)(*get_big_string(raw)); default: throw type_error("dart::buffer is not a finalized string and cannot be accessed as such"); } } template <class Callback> auto integer_deref(Callback&& cb, raw_element raw) -> std::common_type_t< decltype(std::forward<Callback>(cb)(std::declval<primitive<int16_t>&>())), decltype(std::forward<Callback>(cb)(std::declval<primitive<int32_t>&>())), decltype(std::forward<Callback>(cb)(std::declval<primitive<int64_t>&>())) > { switch (raw.type) { case raw_type::short_integer: return std::forward<Callback>(cb)(*get_primitive<int16_t>(raw)); case raw_type::integer: return std::forward<Callback>(cb)(*get_primitive<int32_t>(raw)); case raw_type::long_integer: return std::forward<Callback>(cb)(*get_primitive<int64_t>(raw)); default: throw type_error("dart::buffer is not a finalized integer and cannot be accessed as such"); } } template <class Callback> auto decimal_deref(Callback&& cb, raw_element raw) -> std::common_type_t< decltype(std::forward<Callback>(cb)(std::declval<primitive<float>&>())), decltype(std::forward<Callback>(cb)(std::declval<primitive<double>&>())) > { switch (raw.type) { case raw_type::decimal: return std::forward<Callback>(cb)(*get_primitive<float>(raw)); case raw_type::long_decimal: return std::forward<Callback>(cb)(*get_primitive<double>(raw)); default: throw type_error("dart::buffer is not a finalized decimal and cannot be accessed as such"); } } template <class Callback> auto match_generic(Callback&& cb, raw_type raw) -> std::common_type_t< decltype(std::forward<Callback>(cb)(object_tag {})), decltype(std::forward<Callback>(cb)(array_tag {})), decltype(std::forward<Callback>(cb)(small_string_tag {})), decltype(std::forward<Callback>(cb)(big_string_tag {})), decltype(std::forward<Callback>(cb)(short_integer_tag {})), decltype(std::forward<Callback>(cb)(medium_integer_tag {})), decltype(std::forward<Callback>(cb)(long_integer_tag {})), decltype(std::forward<Callback>(cb)(short_decimal_tag {})), decltype(std::forward<Callback>(cb)(long_decimal_tag {})), decltype(std::forward<Callback>(cb)(boolean_tag {})), decltype(std::forward<Callback>(cb)(null_tag {})) > { switch (raw) { case raw_type::object: return std::forward<Callback>(cb)(object_tag {}); case raw_type::array: return std::forward<Callback>(cb)(array_tag {}); case raw_type::small_string: case raw_type::string: return std::forward<Callback>(cb)(small_string_tag {}); case raw_type::big_string: return std::forward<Callback>(cb)(big_string_tag {}); case raw_type::short_integer: return std::forward<Callback>(cb)(short_integer_tag {}); case raw_type::integer: return std::forward<Callback>(cb)(medium_integer_tag {}); case raw_type::long_integer: return std::forward<Callback>(cb)(long_integer_tag {}); case raw_type::decimal: return std::forward<Callback>(cb)(short_decimal_tag {}); case raw_type::long_decimal: return std::forward<Callback>(cb)(long_decimal_tag {}); case raw_type::boolean: return std::forward<Callback>(cb)(boolean_tag {}); default: DART_ASSERT(raw == raw_type::null); return std::forward<Callback>(cb)(null_tag {}); } } template <template <class> class RefCount, class Callback> auto generic_deref(Callback&& cb, raw_element raw) -> std::common_type_t< decltype(aggregate_deref<RefCount>(std::forward<Callback>(cb), raw)), decltype(string_deref(std::forward<Callback>(cb), raw)), decltype(integer_deref(std::forward<Callback>(cb), raw)), decltype(decimal_deref(std::forward<Callback>(cb), raw)), decltype(std::forward<Callback>(cb)(std::declval<primitive<bool>&>())) > { switch (raw.type) { case raw_type::object: case raw_type::array: return aggregate_deref<RefCount>(std::forward<Callback>(cb), raw); case raw_type::small_string: case raw_type::string: case raw_type::big_string: return string_deref(std::forward<Callback>(cb), raw); case raw_type::short_integer: case raw_type::integer: case raw_type::long_integer: return integer_deref(std::forward<Callback>(cb), raw); case raw_type::decimal: case raw_type::long_decimal: return decimal_deref(std::forward<Callback>(cb), raw); case raw_type::boolean: return std::forward<Callback>(cb)(*get_primitive<bool>(raw)); default: DART_ASSERT(raw.type == raw_type::null); throw type_error("dart::buffer is null, and has no value to access"); } } // Returns the native alignment requirements of the given type. template <template <class> class RefCount> constexpr size_t alignment_of(raw_type type) noexcept { return match_generic([] (auto v) { return decltype(v)::alignment; }, type); } // Function takes a pointer and returns a pointer to the "next" (greater than OR equal to) boundary // conforming to the native alignment of the given type. // Assumes that all alignment requests are for powers of two. template <template <class> class RefCount, class T> constexpr T* align_pointer(T* ptr, raw_type type) noexcept { // Get the required alignment for a pointer of this type. auto alignment = alignment_of<RefCount>(type); // Bump forward to the next boundary of the given alignment requirement. uintptr_t offset = reinterpret_cast<uintptr_t>(ptr); return reinterpret_cast<T*>((offset + (alignment - 1)) & ~(alignment - 1)); } template <template <class> class RefCount, class T> constexpr T pad_bytes(T bytes, raw_type type) noexcept { // Get the required alignment for a pointer of this type. auto alignment = alignment_of<RefCount>(type); // Pad the given bytes to ensure its end lands on an alignment boundary. return (bytes + (alignment - 1)) & ~(alignment - 1); } template <template <class> class RefCount> size_t find_sizeof(raw_element elem) noexcept { if (elem.type != raw_type::null) { return generic_deref<RefCount>([] (auto& v) { return v.get_sizeof(); }, elem); } else { return 0; } } template <bool silent, template <class> class RefCount> bool valid_buffer(raw_element elem, size_t bytes) noexcept(silent) { // Null is a special case because it occupies zero space in the network buffer // Check if the given element has a valid type. // If we're validating against corrupted garbage it likely won't if (elem.type == raw_type::null) return true; else if (!valid_type(elem.type)) return false; // Call through to our implementation return generic_deref<RefCount>([=] (auto& v) { return v.template is_valid<silent>(bytes); }, elem); } template <template <class> class RefCount> constexpr size_t sso_bytes() { return basic_heap<RefCount>::sso_bytes; } template <template <class> class RefCount> raw_type identify_string(shim::string_view base, shim::string_view app = "") noexcept { auto total = base.size() + app.size(); if (total > std::numeric_limits<uint16_t>::max()) { return detail::raw_type::big_string; } else if (total > sso_bytes<RefCount>()) { return detail::raw_type::string; } else { return detail::raw_type::small_string; } } constexpr raw_type identify_integer(int64_t val) noexcept { if (val > INT32_MAX || val < INT32_MIN) return raw_type::long_integer; else if (val > INT16_MAX || val < INT16_MIN) return raw_type::integer; else return raw_type::short_integer; } // Returns the smallest floating point type capable of precisely representing the given // value. constexpr raw_type identify_decimal(double val) noexcept { // XXX: I'm not impressed by this check either, but I can't find any legit way // to check if a double will be precisely representable as a float. if (val != static_cast<float>(val)) return raw_type::long_decimal; else return raw_type::decimal; } // Dart is header-only, so I think the scenarios where the ABI stability of // symbol mangling will be relevant are relatively few. #if DART_USING_GCC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wnoexcept-type" #elif DART_USING_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wc++17-compat-mangling" #pragma clang diagnostic ignored "-Wc++1z-compat" #endif template <class Packet, class T> T safe_optional_access(Packet const& that, T opt, bool (Packet::* guard) () const noexcept, T (Packet::* accessor) () const) { if (!(that.*guard)()) { return opt; } else try { return (that.*accessor)(); } catch (...) { return opt; } } #if DART_USING_GCC #pragma GCC diagnostic pop #elif DART_USING_CLANG #pragma clang diagnostic pop #endif template <template <class> class RefCount, class Owner = buffer_refcount_type<RefCount>, class Callback> Owner aligned_alloc(size_t bytes, raw_type type, Callback&& cb) { // Make an aligned allocation. gsl::byte* tmp; int retval = shim::aligned_alloc(reinterpret_cast<void**>(&tmp), alignment_of<RefCount>(type), bytes); if (retval) throw std::bad_alloc(); // Associate it with an owner in case anything goes wrong. Owner ref {tmp, +[] (gsl::byte const* ptr) { shim::aligned_free(const_cast<gsl::byte*>(ptr)); }}; // Hand out mutable access and return. cb(tmp); return ref; } template <template <class> class RefCount, size_t static_elems = 8, class Spannable, class Callback> decltype(auto) sort_spannable(Spannable const& elems, Callback&& cb) { // XXX: This is necessary because I'm supporting an ANCIENT version of gsl-lite that // doesn't contain the nested type alias value_type, only element_type // Modern versions of gsl-lite, and Microsoft GSL, and std::span, include a value_type // As a fix, meta::spannable_value_type_t returns value_type if it exists, // next element_type if it exists, // and finally meta::nonesuch if neither alias exists using value_type = meta::spannable_value_type_t<Spannable>; static_assert( !std::is_same< value_type, meta::nonesuch >::value, "Sort spannable only supports types that conform to the std::span interface" ); // Check if we can perform the sorting statically. dart_comparator<RefCount> comp; auto const size = static_cast<size_t>(elems.size()); if (size <= static_elems) { // We've got enough static space, setup a local array. std::array<value_type const*, static_elems> ptrs; std::transform(std::begin(elems), std::end(elems), std::begin(ptrs), [] (auto& e) { return &e; }); // Sort the pointers and pass back to the user. std::sort(ptrs.data(), ptrs.data() + size, [&] (auto* lhs, auto* rhs) { return comp(*lhs, *rhs); }); return cb(gsl::make_span(ptrs.data(), size)); } else { // Dynamic fallback. std::vector<value_type const*> ptrs(size, nullptr); std::transform(std::begin(elems), std::end(elems), std::begin(ptrs), [] (auto& e) { return &e; }); // Sort and pass back. std::sort(std::begin(ptrs), std::end(ptrs), [&] (auto* lhs, auto* rhs) { return comp(*lhs, *rhs); }); return cb(gsl::make_span(ptrs)); } } #ifdef DART_USE_SAJSON // FIXME: Find somewhere better to put these functions. template <template <class> class RefCount> raw_type json_identify(sajson::value curr_val) { switch (curr_val.get_type()) { case sajson::TYPE_OBJECT: return raw_type::object; case sajson::TYPE_ARRAY: return raw_type::array; case sajson::TYPE_STRING: // Figure out what type of string we've been given. return identify_string<RefCount>({curr_val.as_cstring(), curr_val.get_string_length()}); case sajson::TYPE_INTEGER: return identify_integer(curr_val.get_integer_value()); case sajson::TYPE_DOUBLE: return identify_decimal(curr_val.get_double_value()); case sajson::TYPE_FALSE: case sajson::TYPE_TRUE: return raw_type::boolean; default: DART_ASSERT(curr_val.get_type() == sajson::TYPE_NULL); return raw_type::null; } } template <template <class> class RefCount> size_t json_lower(gsl::byte* buffer, sajson::value curr_val) { auto raw = json_identify<RefCount>(curr_val); switch (raw) { case raw_type::object: new(buffer) object<RefCount>(curr_val); break; case raw_type::array: new(buffer) array<RefCount>(curr_val); break; case raw_type::small_string: case raw_type::string: new(buffer) string(curr_val.as_cstring(), curr_val.get_string_length()); break; case raw_type::big_string: new(buffer) big_string(curr_val.as_cstring(), curr_val.get_string_length()); break; case raw_type::short_integer: new(buffer) primitive<int16_t>(curr_val.get_integer_value()); break; case raw_type::integer: new(buffer) primitive<int32_t>(curr_val.get_integer_value()); break; case raw_type::long_integer: new(buffer) primitive<int64_t>(curr_val.get_integer_value()); break; case raw_type::decimal: new(buffer) primitive<float>(curr_val.get_double_value()); break; case raw_type::long_decimal: new(buffer) primitive<double>(curr_val.get_double_value()); break; case raw_type::boolean: new(buffer) detail::primitive<bool>((curr_val.get_type() == sajson::TYPE_TRUE) ? true : false); break; default: DART_ASSERT(curr_val.get_type() == sajson::TYPE_NULL); break; } return detail::find_sizeof<RefCount>({raw, buffer}); } #endif #if DART_HAS_RAPIDJSON // FIXME: Find somewhere better to put these functions. template <template <class> class RefCount> raw_type json_identify(rapidjson::Value const& curr_val) { switch (curr_val.GetType()) { case rapidjson::kObjectType: return raw_type::object; case rapidjson::kArrayType: return raw_type::array; case rapidjson::kStringType: // Figure out what type of string we've been given. return identify_string<RefCount>({curr_val.GetString(), curr_val.GetStringLength()}); case rapidjson::kNumberType: // Figure out what type of number we've been given. if (curr_val.IsInt64()) return identify_integer(curr_val.GetInt64()); else return identify_decimal(curr_val.GetDouble()); case rapidjson::kTrueType: case rapidjson::kFalseType: return raw_type::boolean; default: DART_ASSERT(curr_val.IsNull()); return raw_type::null; } } template <template <class> class RefCount> size_t json_lower(gsl::byte* buffer, rapidjson::Value const& curr_val) { auto raw = json_identify<RefCount>(curr_val); switch (raw) { case raw_type::object: new(buffer) object<RefCount>(curr_val); break; case raw_type::array: new(buffer) array<RefCount>(curr_val); break; case raw_type::small_string: case raw_type::string: new(buffer) string(curr_val.GetString(), curr_val.GetStringLength()); break; case raw_type::big_string: new(buffer) big_string(curr_val.GetString(), curr_val.GetStringLength()); break; case raw_type::short_integer: new(buffer) primitive<int16_t>(curr_val.GetInt()); break; case raw_type::integer: new(buffer) primitive<int32_t>(curr_val.GetInt()); break; case raw_type::long_integer: new(buffer) primitive<int64_t>(curr_val.GetInt64()); break; case raw_type::decimal: new(buffer) primitive<float>(curr_val.GetFloat()); break; case raw_type::long_decimal: new(buffer) primitive<double>(curr_val.GetDouble()); break; case raw_type::boolean: new(buffer) detail::primitive<bool>(curr_val.GetBool()); break; default: DART_ASSERT(curr_val.IsNull()); break; } return detail::find_sizeof<RefCount>({raw, buffer}); } #endif // Helper function handles the edge case where we're working with // a view type, and we need to cast it back to an owner, ONLY IF // we are an owner ourselves. template <class MaybeView, class View> decltype(auto) view_return_indirection(View&& view) { return shim::compose_together( [] (auto&& v, std::true_type) -> decltype(auto) { return std::forward<decltype(v)>(v); }, [] (auto&& v, std::false_type) -> decltype(auto) { return std::forward<decltype(v)>(v).as_owner(); } )(std::forward<View>(view), std::is_same<std::decay_t<MaybeView>, std::decay_t<View>> {}); } template <class Packet> Packet get_nested_impl(Packet haystack, shim::string_view needle, char separator) { // Spin through the provided needle until we reach the end, or hit a leaf. auto start = needle.begin(); typename Packet::view curr = haystack; while (start < needle.end() && curr.is_object()) { // Tokenize up the needle and drag the current packet through each one. auto stop = std::find(start, needle.end(), separator); curr = curr[needle.substr(start - needle.begin(), stop - start)]; // Prepare for next iteration. stop == needle.end() ? start = stop : start = stop + 1; } // If we finished, find our final value, otherwise return null. if (start < needle.end()) return Packet::make_null(); else return view_return_indirection<Packet>(curr); } template <class Packet> std::vector<Packet> keys_impl(Packet const& that) { std::vector<Packet> packets; packets.reserve(that.size()); for (auto it = that.key_begin(); it != that.key_end(); ++it) { packets.push_back(*it); } return packets; } template <class Packet> std::vector<Packet> values_impl(Packet const& that) { std::vector<Packet> packets; packets.reserve(that.size()); for (auto entry : that) packets.push_back(std::move(entry)); return packets; } template <class T> decltype(auto) maybe_dereference(T&& maybeptr, std::true_type) { return *std::forward<T>(maybeptr); } template <class T> decltype(auto) maybe_dereference(T&& maybeptr, std::false_type) { return std::forward<T>(maybeptr); } } } // Include main header file for all implementation files. #include "../dart.h" #include "common.tcc" #endif
{ "alphanum_fraction": 0.636005442, "avg_line_length": 34.7220858896, "ext": "h", "hexsha": "7527ef370476399542e836160b4100e7ff950d59", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z", "max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Cfretz244/libdart", "max_forks_repo_path": "include/dart/common.h", "max_issues_count": 10, "max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Cfretz244/libdart", "max_issues_repo_path": "include/dart/common.h", "max_line_length": 121, "max_stars_count": 85, "max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Cfretz244/libdart", "max_stars_repo_path": "include/dart/common.h", "max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z", "num_tokens": 12933, "size": 56597 }
/// FicTrac http://rjdmoore.net/fictrac/ /// \file NLoptFunc.h /// \brief Wrapper class for NLopt. /// \author Saul Thurrowgood, Richard Moore /// \copyright CC BY-NC-SA 3.0 #pragma once #include <nlopt.h> #include <vector> /// /// C++ wrapper of the NLopt library for nonlinear optimisation, v2.2+. /// See: http://ab-initio.mit.edu/nlopt /// class NLoptFunc { public: NLoptFunc(); virtual ~NLoptFunc(); /// /// Run the optimiser. Default behaviour is to start the search at the /// position of the previous result. /// virtual nlopt_result optimize(const double *xInit=0); /// /// Sets the initial value used for the next call to optimize(), /// which assumes that call passes NULL as the xInit argument. /// void setXInit(const double *xInit); /// /// Get the optimised value. /// void getOptX(float *x); void getOptX(double *x); double getOptF(); /// /// Returns the number of objective() evaluations by the last optimisation. /// unsigned getNumEval(); /// /// Initialise the optimiser. If 'minimise' is false then the objective /// function will be maximised. /// void init(nlopt_algorithm algo, unsigned n, bool minimise=true); void setPopulation(unsigned int pop); /// /// Set initial step size. /// void setInitialStep(const double *dx); /// /// Set stopping criteria. /// void setLowerBounds(const double *lb); void setUpperBounds(const double *ub); void setLowerBounds(double lb); /// convenience: sets all to same value void setUpperBounds(double ub); void setFtol(double tol); // relative void setXtol(double tol); // absolute void setXtolRel(double tol); void setMaxEval(unsigned n); void getLowerBounds(double *lb); void getUpperBounds(double *ub); unsigned getDimension(); protected: unsigned _nEval; /// /// Objective function executed during optimisation. /// virtual double objective(unsigned n, const double *x, double *grad) = 0; private: static double _cb(unsigned n, const double *x, double *grad, void *data); nlopt_opt _opt; std::vector<double> _x; double _optF; };
{ "alphanum_fraction": 0.6870229008, "avg_line_length": 22.0631578947, "ext": "h", "hexsha": "e7c92b4650658ada47d9542507a31c0dc100b01c", "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": "bd21acf22cca8403b93862ccbcc348750f997923", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "technosap/FlyVR_TL_2E343", "max_forks_repo_path": "Unused Code/FicTrac v2.0 (Not Working Well !!)/fictrac2_source/include/NLoptFunc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd21acf22cca8403b93862ccbcc348750f997923", "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": "technosap/FlyVR_TL_2E343", "max_issues_repo_path": "Unused Code/FicTrac v2.0 (Not Working Well !!)/fictrac2_source/include/NLoptFunc.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd21acf22cca8403b93862ccbcc348750f997923", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "technosap/FlyVR_TL_2E343", "max_stars_repo_path": "Unused Code/FicTrac v2.0 (Not Working Well !!)/fictrac2_source/include/NLoptFunc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 541, "size": 2096 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_randist.h> #define TSSIZE 10 #define WL 10000 typedef struct tagInterpolant{ gsl_matrix *Bs; int *nodes; }Interpolant; /* function to create an orthonormal basis set from a training set of models */ double *create_basis(double weight, double tolerance, gsl_matrix *TS, size_t *nbases); /* function to create the empirical interpolant */ //void create_interpolant(gsl_matrix *RB, gsl_matrix **Bs, int **idxarray); Interpolant *create_interpolant(gsl_matrix *RB); /* define function to project model vector onto the training set of models */ void project_onto_basis(double dt, gsl_matrix *RB, gsl_matrix *TS, gsl_matrix *projections, gsl_matrix *projection_coefficients, int idx); /* dot product of two vectors, but with one multiplied by the weighting factor */ double weighted_dot_product(double weight, gsl_vector *a, gsl_vector *b); /* normalise a vector */ void normalise(double weight, gsl_vector *a); /* get the B_matrix */ gsl_matrix *B_matrix(gsl_matrix *V, gsl_matrix *RB); void print_shape(gsl_matrix *a); /* create ROQ weights for interpolant to calculate the data dot model terms */ gsl_vector *create_data_model_weights(gsl_matrix *B, double *data); /* calculate ROQ version of the data model dot product (where the model vector is the model just computed at the interpolant points) */ double roq_data_dot_model(gsl_vector *weights, double *model); /* create ROQ weights for interpolant to calculate the model dot model terms */ gsl_matrix *create_model_model_weights(gsl_matrix *B); /* calculate ROQ version of the model model dot product (where the model vector is the model just computed at the interpolant points) */ double roq_model_dot_model(gsl_matrix *weights, double *model); double *create_basis(double weight, double tolerance, gsl_matrix *TS, size_t *nbases){ double *RB = NULL; gsl_matrix *projections; /* projections of the basis onto the training set */ gsl_matrix *residual; gsl_matrix *projection_coeffs; gsl_vector *projection_errors; gsl_vector_view resrow; double sigma = 1.; size_t dlength = TS->size2, nts = TS->size1; size_t mindex = 0, k=0; int idx = 0; /* allocate reduced basis (initially just one model vector in length). Here we have RB just as a double array, rather than a gsl_matrix, as there is no realloc functions for GSL matrices. When wanting to use RB as a GSL matrix we will have to use matrix views. */ RB = calloc(dlength, sizeof(double)); gsl_matrix_view RBview = gsl_matrix_view_array(RB, 1, dlength); gsl_vector *firstrow = gsl_vector_calloc(dlength); gsl_matrix_get_row(firstrow, TS, 0); gsl_matrix_set_row(&RBview.matrix, 0, firstrow); gsl_vector_free(firstrow); projection_errors = gsl_vector_calloc(dlength); residual = gsl_matrix_calloc(nts, dlength); projections = gsl_matrix_calloc(nts, dlength); projection_coeffs = gsl_matrix_calloc(nts, nts); /* create reduced basis set using greedy binning Algorithm 1 of http://arxiv.org/abs/1308.3565 */ while ( sigma >= tolerance ){ if ( idx > nts-1 ){ fprintf(stderr, "Not enough training models (%zu) to produce orthonormal basis given the tolerance of %le\n", nts, tolerance); return NULL; } project_onto_basis(weight, &RBview.matrix, TS, projections, projection_coeffs, idx); gsl_matrix_memcpy(residual, TS); /* copy training set into residual */ /* get residuals by subtracting projections from training set */ gsl_matrix_sub(residual, projections); /* get projection errors */ for( k=0; k < nts; k++ ){ double err; resrow = gsl_matrix_row(residual, k); err = weighted_dot_product(weight, &resrow.vector, &resrow.vector); gsl_vector_set(projection_errors, k, err); } sigma = fabs(gsl_vector_max(projection_errors)); if ( sigma > 1e-5 ){ fprintf(stderr, "%.12lf\t%d\n", sigma, idx); } else { fprintf(stderr, "%.12le\t%d\n", sigma, idx); } if ( sigma < tolerance ) { break; } /* get index of training set with the largest projection errors */ mindex = gsl_vector_max_index( projection_errors ); gsl_vector *next_basis = gsl_vector_calloc(dlength); gsl_vector_view proj_basis = gsl_matrix_row(projections, mindex); gsl_matrix_get_row(next_basis, TS, mindex); gsl_vector_sub(next_basis, &proj_basis.vector); /* normalise vector */ normalise(weight, next_basis); idx++; /* expand reduced basis */ RB = realloc(RB, sizeof(double)*dlength*(idx+1)); /* add on next basis */ RBview = gsl_matrix_view_array(RB, idx+1, dlength); gsl_matrix_set_row(&RBview.matrix, idx, next_basis); gsl_vector_free(next_basis); } *nbases = (size_t)idx; gsl_matrix_free(projection_coeffs); gsl_matrix_free(residual); gsl_matrix_free(TS); return RB; } void project_onto_basis(double dt, gsl_matrix *RB, gsl_matrix *TS, gsl_matrix *projections, gsl_matrix *projection_coefficients, int idx){ size_t row = 0; gsl_vector_view basis = gsl_matrix_row(RB, idx); for ( row=0; row < TS->size1; row++ ){ double prod; gsl_vector_view proj = gsl_matrix_row(projections, row); gsl_vector *basisscale = gsl_vector_calloc(TS->size2); gsl_vector_view model = gsl_matrix_row(TS, row); /* get model from training set */ prod = weighted_dot_product(dt, &basis.vector, &model.vector); gsl_matrix_set(projection_coefficients, idx, row, prod); gsl_vector_memcpy(basisscale, &basis.vector); gsl_vector_scale(basisscale, prod); gsl_vector_add(&proj.vector, basisscale); gsl_vector_free(basisscale); } } double weighted_dot_product(double weight, gsl_vector *a, gsl_vector *b){ double dp; gsl_vector *weighted = gsl_vector_calloc(a->size); gsl_vector_memcpy(weighted, a); /* multiply vector by weight */ gsl_vector_scale(weighted, weight); /* get dot product */ gsl_blas_ddot(weighted, b, &dp); gsl_vector_free(weighted); return dp; } void normalise(double weight, gsl_vector *a){ double norm = gsl_blas_dnrm2(a); /* use GSL normalisation calculation function */ gsl_vector_scale(a, 1./(norm*sqrt(weight))); } gsl_matrix *B_matrix(gsl_matrix *V, gsl_matrix *RB){ /* get inverse of V */ size_t n = V->size1; gsl_matrix *invV = gsl_matrix_alloc(n, n); int signum; /* use LU decomposition to get inverse */ gsl_matrix *LU = gsl_matrix_alloc(n, n); gsl_matrix_memcpy(LU, V); gsl_permutation *p = gsl_permutation_alloc(n); gsl_linalg_LU_decomp(LU, p, &signum); gsl_linalg_LU_invert(LU, p, invV); gsl_permutation_free(p); gsl_matrix_free(LU); /* get B matrix */ gsl_matrix_view subRB = gsl_matrix_submatrix(RB, 0, 0, n, RB->size2); gsl_matrix *B = gsl_matrix_alloc(n, RB->size2); gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, invV, &subRB.matrix, 0., B); gsl_matrix_free(invV); return B; } void print_shape(gsl_matrix *a){ fprintf(stderr, "Matrix is %zu x %zu\n", a->size1, a->size2); } gsl_vector *create_data_model_weights(gsl_matrix *B, double *data){ gsl_vector_view dataview = gsl_vector_view_array(data, B->size2); /* create weights */ gsl_vector *weights = gsl_vector_alloc(B->size1); gsl_blas_dgemv(CblasNoTrans, 1.0, B, &dataview.vector, 0., weights); return weights; } double roq_data_dot_model(gsl_vector *weights, double *model){ double d_dot_m = 0.; gsl_vector_view modelview = gsl_vector_view_array(model, weights->size); gsl_blas_ddot(weights, &modelview.vector, &d_dot_m); return d_dot_m; } gsl_matrix *create_model_model_weights(gsl_matrix *B){ gsl_matrix *weights = gsl_matrix_alloc(B->size1, B->size1); size_t i=0, j=0; double ressum = 0.; for ( i=0; i<B->size1; i++ ){ for ( j=0; j<B->size1; j++ ){ gsl_vector_view Bi = gsl_matrix_row(B, i); gsl_vector_view Bj = gsl_matrix_row(B, j); gsl_blas_ddot(&Bi.vector, &Bj.vector, &ressum); gsl_matrix_set(weights, i, j, ressum); } } return weights; } double roq_model_dot_model(gsl_matrix *weights, double *model){ gsl_vector *ws = gsl_vector_alloc(weights->size1); gsl_vector_view modelview = gsl_vector_view_array(model, weights->size1); double m_dot_m = 0.; gsl_blas_dgemv(CblasTrans, 1.0, weights, &modelview.vector, 0., ws); gsl_blas_ddot(ws, &modelview.vector, &m_dot_m); return m_dot_m; } Interpolant *create_interpolant(gsl_matrix *RB){ /* now find the empirical interopolant and interpolation nodes using Algorithm 2 of http://arxiv.org/abs/1308.3565 */ size_t RBsize = RB->size1; /* reduced basis size (no. of reduced bases) */ size_t dlength = RB->size2; /* length of each base */ size_t i=1, j=0, k=0; double *V = malloc(sizeof(double)); gsl_matrix_view Vview; Interpolant *interp = malloc(sizeof(Interpolant)); int idmax = 0, newidx = 0; /* get index of maximum absolute value of first basis */ gsl_vector_view firstbasis = gsl_matrix_row(RB, 0); idmax = (int)gsl_blas_idamax(&firstbasis.vector); /* function gets index of maximum absolute value */ interp->nodes = malloc(RBsize*sizeof(int)); interp->nodes[0] = idmax; fprintf(stderr, "first index = %d\n", interp->nodes[0]); for ( i=1; i<RBsize; i++ ){ Vview = gsl_matrix_view_array(V, i, i); for ( j=0; j<i; j++ ){ for ( k=0; k<i; k++ ){ gsl_matrix_set(&Vview.matrix, k, j, gsl_matrix_get(RB, j, interp->nodes[k])); } } /* get B matrix */ gsl_matrix *B = B_matrix(&Vview.matrix, RB); /* make empirical interpolant of basis */ gsl_vector *interpolant = gsl_vector_calloc(dlength); gsl_vector *subbasis = gsl_vector_calloc(i); gsl_vector_view subview = gsl_matrix_row(RB, i); for ( k=0; k<i; k++ ){ gsl_vector_set(subbasis, k, gsl_vector_get(&subview.vector, interp->nodes[k])); } gsl_blas_dgemv(CblasTrans, 1.0, B, subbasis, 0., interpolant); /* get residuals of interpolant */ gsl_vector_sub(interpolant, &subview.vector); newidx = (int)gsl_blas_idamax(interpolant); interp->nodes[i] = newidx; fprintf(stderr, "%zu: idx[%d]\n", i, interp->nodes[i]); gsl_vector_free(subbasis); gsl_matrix_free(B); gsl_vector_free(interpolant); /* reallocate memory for V */ V = realloc(V, (i+1)*(i+1)*sizeof(double)); } /* NOTE: the above works and produces identical results to the ipython notebook */ /* get final B vector with all the indices */ Vview = gsl_matrix_view_array(V, RBsize, RBsize); for( j=0; j<RBsize; j++ ){ for( k=0; k<RBsize; k++ ){ gsl_matrix_set(&Vview.matrix, k, j, gsl_matrix_get(RB, j, interp->nodes[k])); } } interp->Bs = B_matrix(&Vview.matrix, RB); free(V); return interp; } int main(){ gsl_matrix *TS; /* the training set of waveforms */ size_t TSsize; /* the size of the training set (number of waveforms) */ size_t wl; /* the length of each waveform */ size_t k = 0, j = 0, i = 0, nbases = 0; double *RB = NULL; /* the reduced basis set */ Interpolant *interp = NULL; gsl_vector *times; double tolerance = 1e-12, sigma = 1.; /* tolerance for reduced basis generation loop */ double dt = 60.; /* model time steps */ TSsize = TSSIZE; wl = WL; /* allocate memory for training set */ TS = gsl_matrix_calloc(TSsize, wl); double fmin = -0.0001, fmax = 0.0001, f0 = 0., m0 = 0.; times = gsl_vector_alloc(wl); /* set up training set */ for ( k=0; k < TSsize; k++ ){ f0 = fmin + (double)k*(fmax-fmin)/((double)TSsize-1.); for ( j=0; j < wl; j++ ){ double tv = dt*(double)j; m0 = sin(2.*M_PI*f0*tv); gsl_vector_set(times, j, tv); gsl_matrix_set(TS, k, j, m0); } gsl_vector_view rowview = gsl_matrix_row(TS, k); normalise(dt, &rowview.vector); } if ( (RB = create_basis(dt, tolerance, TS, &nbases)) == NULL){ fprintf(stderr, "Error... problem producing basis\n"); return 1; } gsl_matrix_view RBview = gsl_matrix_view_array(RB, nbases, wl); fprintf(stderr, "%zu, %zu x %zu\n", nbases, RBview.matrix.size1, RBview.matrix.size2); //FILE *fp = fopen("test_vector.txt", "w"); //gsl_vector_view testview = gsl_matrix_row(&RBview.matrix, RBview.matrix.size1-1); //gsl_vector_fprintf(fp, &testview.vector, "%le"); //fclose(fp); /* NOTE: the above appears to be correct and gives identical values to those in the ipython notebook */ interp = create_interpolant(&RBview.matrix); /* do some timing tests */ /* create the model dot model weights */ gsl_matrix *mmw = create_model_model_weights(interp->Bs); double randf0 = -0.00004; /* a random frequency to create a model */ double *modelfull = calloc(wl, sizeof(double)); double *modelreduced = calloc(nbases, sizeof(double)); double *timesred = calloc(nbases, sizeof(double)); /* create model */ for ( i=0; i<wl; i++ ){ modelfull[i] = sin(2.*M_PI*randf0*gsl_vector_get(times, i)); } for ( i=0; i<nbases; i++ ){ modelreduced[i] = sin(2.*M_PI*randf0*gsl_vector_get(times, interp->nodes[i])); } gsl_vector_view mfview = gsl_vector_view_array(modelfull, wl); struct timespec t1, t2, t3, t4; double dt1, dt2; /* get the model model term with the full model */ double mmfull, mmred; clock_gettime(CLOCK_MONOTONIC, &t1); gsl_blas_ddot(&mfview.vector, &mfview.vector, &mmfull); clock_gettime(CLOCK_MONOTONIC, &t2); clock_gettime(CLOCK_MONOTONIC, &t3); mmred = roq_model_dot_model(mmw, modelreduced); clock_gettime(CLOCK_MONOTONIC, &t4); dt1 = (double)((t2.tv_sec + t2.tv_nsec*1.e-9) - (t1.tv_sec + t1.tv_nsec*1.e-9)); dt2 = (double)((t4.tv_sec + t4.tv_nsec*1.e-9) - (t3.tv_sec + t3.tv_nsec*1.e-9)); fprintf(stderr, "M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", mmfull, dt1, mmred, dt2, dt1/dt2); /* get the data dot model terms by generating some random data */ const gsl_rng_type *T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); double *data = calloc(wl, sizeof(double)); for ( i=0; i<wl; i++ ){ data[i] = gsl_ran_gaussian(r, 1.0); } /* create the data dot model weights */ gsl_vector *dmw = create_data_model_weights(interp->Bs, data); gsl_vector_view dataview = gsl_vector_view_array(data, wl); double dmfull, dmred; clock_gettime(CLOCK_MONOTONIC, &t1); gsl_blas_ddot(&dataview.vector, &mfview.vector, &dmfull); clock_gettime(CLOCK_MONOTONIC, &t2); clock_gettime(CLOCK_MONOTONIC, &t3); dmred = roq_data_dot_model(dmw, modelreduced); clock_gettime(CLOCK_MONOTONIC, &t4); dt1 = (double)((t2.tv_sec + t2.tv_nsec*1.e-9) - (t1.tv_sec + t1.tv_nsec*1.e-9)); dt2 = (double)((t4.tv_sec + t4.tv_nsec*1.e-9) - (t3.tv_sec + t3.tv_nsec*1.e-9)); fprintf(stderr, "D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", dmfull, dt1, dmred, dt2, dt1/dt2); /* check difference in log likelihoods */ double Lfull, Lred; Lfull = mmfull - 2.*dmfull; Lred = mmred - 2.*dmred; fprintf(stderr, "Fractional difference in log likelihoods = %lf%%\n", 100.*fabs(Lfull-Lred)/fabs(Lfull)); return 0; }
{ "alphanum_fraction": 0.6866927593, "avg_line_length": 31.7391304348, "ext": "c", "hexsha": "bd536ce9d2cb09d9b8085a5827e34f873d132388", "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": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mattpitkin/random_scripts", "max_forks_repo_path": "ROQ/roq_test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "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": "mattpitkin/random_scripts", "max_issues_repo_path": "ROQ/roq_test.c", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mattpitkin/random_scripts", "max_stars_repo_path": "ROQ/roq_test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4518, "size": 15330 }
/***************************************************************************/ /* */ /* matrix.h - Matrix class for mruby */ /* Copyright (C) 2015 Paolo Bosetti */ /* paolo[dot]bosetti[at]unitn.it */ /* Department of Industrial Engineering, University of Trento */ /* */ /* This library is free software. You can redistribute it and/or */ /* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */ /* */ /* This library 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 */ /* Artistic License 2.0 for more details. */ /* */ /* See the file LICENSE */ /* */ /***************************************************************************/ #ifndef MATRIX_H #define MATRIX_H #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/param.h> #include <time.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include "mruby.h" #include "mruby/variable.h" #include "mruby/string.h" #include "mruby/data.h" #include "mruby/class.h" #include "mruby/value.h" #include "mruby/array.h" #include "mruby/numeric.h" #include "mruby/compile.h" #define E_MATRIX_ERROR (mrb_class_get(mrb, "MatrixError")) /***********************************************\ MATRICES \***********************************************/ // Garbage collector handler, for play_data struct // if play_data contains other dynamic data, free it too! // Check it with GC.start void matrix_destructor(mrb_state *mrb, void *p_); // Utility function for getting the struct out of the wrapping IV @data void mrb_matrix_get_data(mrb_state *mrb, mrb_value self, gsl_matrix **data); void mrb_gsl_matrix_init(mrb_state *mrb); #endif // MATRIX_H
{ "alphanum_fraction": 0.4638922889, "avg_line_length": 40.85, "ext": "h", "hexsha": "d9d8cb637a964715723978128b623321e0c4c33c", "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": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_path": "src/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "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": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_path": "src/matrix.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_path": "src/matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 428, "size": 2451 }
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* 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. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include <lapacke.h> #include <phonoc_array.h> #include <phonoc_utils.h> #include <phonon4_h/real_to_reciprocal.h> static void real_to_reciprocal_elements(lapack_complex_double *fc4_rec_elem, const double q[12], const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const int *p2s, const int *s2p, const int pi0, const int pi1, const int pi2, const int pi3); /* fc4_reciprocal[num_patom, num_patom, num_patom, num_patom, 3, 3, 3, 3] */ void real_to_reciprocal4(lapack_complex_double *fc4_reciprocal, const double q[12], const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const int *p2s_map, const int *s2p_map) { int i, j, k, l, num_patom; num_patom = multiplicity->dims[1]; for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { for (k = 0; k < num_patom; k++) { for (l = 0; l < num_patom; l++) { real_to_reciprocal_elements (fc4_reciprocal + i * 81 * num_patom * num_patom * num_patom + j * 81 * num_patom * num_patom + k * 81 * num_patom + l * 81, q, fc4, shortest_vectors, multiplicity, p2s_map, s2p_map, i, j, k, l); } } } } } static void real_to_reciprocal_elements(lapack_complex_double *fc4_rec_elem, const double q[12], const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const int *p2s, const int *s2p, const int pi0, const int pi1, const int pi2, const int pi3) { int i, j, k, l, m, num_satom; lapack_complex_double phase_factor, phase_factors[3]; double fc4_rec_real[81], fc4_rec_imag[81]; int fc4_elem_address; for (i = 0; i < 81; i++) { fc4_rec_real[i] = 0; fc4_rec_imag[i] = 0; } num_satom = multiplicity->dims[0]; i = p2s[pi0]; for (j = 0; j < num_satom; j++) { if (s2p[j] != p2s[pi1]) { continue; } phase_factors[0] = get_phase_factor(q, shortest_vectors, multiplicity, pi0, j, 1); for (k = 0; k < num_satom; k++) { if (s2p[k] != p2s[pi2]) { continue; } phase_factors[1] = get_phase_factor(q, shortest_vectors, multiplicity, pi0, k, 2); for (l = 0; l < num_satom; l++) { if (s2p[l] != p2s[pi3]) { continue; } phase_factors[2] = get_phase_factor(q, shortest_vectors, multiplicity, pi0, l, 3); fc4_elem_address = (i * 81 * num_satom * num_satom * num_satom + j * 81 * num_satom * num_satom + k * 81 * num_satom + l * 81); phase_factor = phonoc_complex_prod(phase_factors[0], phase_factors[1]); phase_factor = phonoc_complex_prod(phase_factor, phase_factors[2]); for (m = 0; m < 81; m++) { fc4_rec_real[m] += lapack_complex_double_real(phase_factor) * fc4[fc4_elem_address + m]; fc4_rec_imag[m] += lapack_complex_double_imag(phase_factor) * fc4[fc4_elem_address + m]; } } } } for (i = 0; i < 81; i++) { fc4_rec_elem[i] = lapack_make_complex_double(fc4_rec_real[i], fc4_rec_imag[i]); } }
{ "alphanum_fraction": 0.6558129827, "avg_line_length": 30.5159235669, "ext": "c", "hexsha": "888c30a4cf26a4c5f98a66b9ec321fb432d4661f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-01-30T08:36:46.000Z", "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:53:25.000Z", "max_forks_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "atztogo/forcefit", "max_forks_repo_path": "c/anharmonic/phonon4/real_to_reciprocal.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "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": "atztogo/forcefit", "max_issues_repo_path": "c/anharmonic/phonon4/real_to_reciprocal.c", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "atztogo/forcefit", "max_stars_repo_path": "c/anharmonic/phonon4/real_to_reciprocal.c", "max_stars_repo_stars_event_max_datetime": "2021-07-20T23:19:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-20T23:19:49.000Z", "num_tokens": 1384, "size": 4791 }
#ifndef SEARCHPATTERNBASE_HHHHH #define SEARCHPATTERNBASE_HHHHH #include "../../SigScannerMemoryData.h" #include <vector> #include <string> #include <memory> #include <gsl/span> namespace MPSig { namespace detail { class SearchPatternBase { public: virtual ~SearchPatternBase() = default; using gsl_span_cit_t = typename gsl::span<const char>::const_iterator; using gsl_span_crit_t = typename gsl::span<const char>::const_reverse_iterator; template<typename It> struct ExecFirstResult { bool success; // If it was a success It rangeBegin; // The first valid iterator It rangeEnd; // The next depended iterator point (from which all other patterns depend on) }; // ExecFirst can look up begin to end fully, without restrictions virtual ExecFirstResult<gsl_span_cit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const = 0; virtual ExecFirstResult<gsl_span_crit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const = 0; // ExecDepend must only check the current location as it depends on a search success virtual ExecFirstResult<gsl_span_cit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const = 0; virtual ExecFirstResult<gsl_span_crit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const = 0; virtual std::unique_ptr<SearchPatternBase> Clone() const = 0; }; } } #endif
{ "alphanum_fraction": 0.6788990826, "avg_line_length": 40.5581395349, "ext": "h", "hexsha": "f2d6371678a95bf6e8d111ebace0093545819655", "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": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "KevinW1998/MultipassSigScanner", "max_forks_repo_path": "src/search/detail/SearchPatternBase.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "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": "KevinW1998/MultipassSigScanner", "max_issues_repo_path": "src/search/detail/SearchPatternBase.h", "max_line_length": 159, "max_stars_count": null, "max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "KevinW1998/MultipassSigScanner", "max_stars_repo_path": "src/search/detail/SearchPatternBase.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 396, "size": 1744 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <mpi.h> #include <StGermain/StGermain.h> #include <StgDomain/StgDomain.h> #include <StgFEM/StgFEM.h> #include <petsc.h> #include "types.h" #include "SemiLagrangianIntegrator.h" #include <assert.h> /** Textual name of this class */ const Type SemiLagrangianIntegrator_Type = "SemiLagrangianIntegrator"; SemiLagrangianIntegrator* _SemiLagrangianIntegrator_New( SEMILAGRANGIANINTEGRATOR_DEFARGS ) { SemiLagrangianIntegrator* self; /* Allocate memory */ assert( _sizeOfSelf >= sizeof(SemiLagrangianIntegrator) ); /* The following terms are parameters that have been passed into this function but are being set before being passed onto the parent */ /* This means that any values of these parameters that are passed into this function are not passed onto the parent function and so should be set to ZERO in any children of this class. */ nameAllocationType = NON_GLOBAL; self = (SemiLagrangianIntegrator*) _Stg_Component_New( STG_COMPONENT_PASSARGS ); /* General info */ self->variableList = Stg_ObjectList_New(); self->varStarList = Stg_ObjectList_New(); self->varOldList = Stg_ObjectList_New(); return self; } void* _SemiLagrangianIntegrator_Copy( void* slIntegrator, void* dest, Bool deep, Name nameExt, PtrMap* ptrMap ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; SemiLagrangianIntegrator* newSemiLagrangianIntegrator; PtrMap* map = ptrMap; Bool ownMap = False; if( !map ) { map = PtrMap_New( 10 ); ownMap = True; } newSemiLagrangianIntegrator = _Stg_Component_Copy( self, dest, deep, nameExt, map ); if( deep ) { if( (newSemiLagrangianIntegrator->velocityField = PtrMap_Find( map, self->velocityField )) == NULL ) { newSemiLagrangianIntegrator->velocityField = Stg_Class_Copy( self->velocityField, NULL, deep, nameExt, map ); PtrMap_Append( map, self->velocityField, newSemiLagrangianIntegrator->velocityField ); } } else { newSemiLagrangianIntegrator->velocityField = Stg_Class_Copy( self->velocityField, NULL, deep, nameExt, map ); } if( ownMap ) { Stg_Class_Delete( map ); } return (void*)newSemiLagrangianIntegrator; } void _SemiLagrangianIntegrator_Delete( void* slIntegrator ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; Stg_Class_Delete( self->variableList ); Stg_Class_Delete( self->varStarList ); Stg_Class_Delete( self->varOldList ); } void _SemiLagrangianIntegrator_Print( void* slIntegrator, Stream* stream ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; _Stg_Component_Print( self, stream ); Journal_PrintPointer( stream, self->velocityField ); } void* _SemiLagrangianIntegrator_DefaultNew( Name name ) { /* Variables set in this function */ SizeT _sizeOfSelf = sizeof(SemiLagrangianIntegrator); Type type = SemiLagrangianIntegrator_Type; Stg_Class_DeleteFunction* _delete = _SemiLagrangianIntegrator_Delete; Stg_Class_PrintFunction* _print = _SemiLagrangianIntegrator_Print; Stg_Class_CopyFunction* _copy = _SemiLagrangianIntegrator_Copy; Stg_Component_DefaultConstructorFunction* _defaultConstructor = _SemiLagrangianIntegrator_DefaultNew; Stg_Component_ConstructFunction* _construct = _SemiLagrangianIntegrator_AssignFromXML; Stg_Component_BuildFunction* _build = _SemiLagrangianIntegrator_Build; Stg_Component_InitialiseFunction* _initialise = _SemiLagrangianIntegrator_Initialise; Stg_Component_ExecuteFunction* _execute = _SemiLagrangianIntegrator_Execute; Stg_Component_DestroyFunction* _destroy = _SemiLagrangianIntegrator_Destroy; /* Variables that are set to ZERO are variables that will be set either by the current _New function or another parent _New function further up the hierachy */ AllocationType nameAllocationType = NON_GLOBAL /* default value NON_GLOBAL */; return (void*)_SemiLagrangianIntegrator_New( SEMILAGRANGIANINTEGRATOR_PASSARGS ); } void _SemiLagrangianIntegrator_AssignFromXML( void* slIntegrator, Stg_ComponentFactory* cf, void* data ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; Dictionary* dict; Dictionary_Entry_Value* dev; unsigned field_i; Name fieldName; FeVariable* feVariable; Stg_Component_AssignFromXML( self, cf, data, False ); self->context = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"Context", FiniteElementContext, False, data ); if( !self->context ) self->context = Stg_ComponentFactory_ConstructByName( cf, (Name)"context", FiniteElementContext, True, data ); self->velocityField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"VelocityField", FeVariable, False, NULL ); self->advectedField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"AdvectedField", FeVariable, False, NULL ); dict = Dictionary_Entry_Value_AsDictionary( Dictionary_Get( cf->componentDict, (Dictionary_Entry_Key)self->name ) ); dev = Dictionary_Get( dict, (Dictionary_Entry_Key)"fields" ); for( field_i = 0; field_i < Dictionary_Entry_Value_GetCount( dev ); field_i += 3 ) { fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i ) ); feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data ); Stg_ObjectList_Append( self->variableList, feVariable ); /* the corresponding _* field */ fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i + 1 ) ); feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data ); Stg_ObjectList_Append( self->varStarList, feVariable ); /* the corresponding old field */ fieldName = Dictionary_Entry_Value_AsString( Dictionary_Entry_Value_GetElement( dev, field_i + 2 ) ); feVariable = Stg_ComponentFactory_ConstructByName( cf, (Name)fieldName, FeVariable, True, data ); Stg_ObjectList_Append( self->varOldList, feVariable ); } // self->sle = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"SLE", Energy_SLE, False, NULL ); /* for problems with temporally evolving velocity */ self->prevVelField = Stg_ComponentFactory_ConstructByKey( cf, self->name, (Dictionary_Entry_Key)"PreviousTimeStepVelocityField", FeVariable, False, data ); if( self->prevVelField ) { EP_AppendClassHook( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), SemiLagrangianIntegrator_UpdatePreviousVelocityField, self ); EP_InsertClassHookAfter( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), "SemiLagrangianIntegrator_UpdatePreviousVelocityField", SemiLagrangianIntegrator_InitSolve, self ); } else { EP_AppendClassHook( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), SemiLagrangianIntegrator_InitSolve, self ); } // if( self->sle ) { // /** also set sle to run where required */ // EP_InsertClassHookAfter( Context_GetEntryPoint( self->context, AbstractContext_EP_UpdateClass ), "SemiLagrangianIntegrator_InitSolve", SystemLinearEquations_GetRunEPFunction(), self->sle ); // /** remember to disable the standard run at execute */ // SystemLinearEquations_SetRunDuringExecutePhase( self->sle, False); // } self->isConstructed = True; } void _SemiLagrangianIntegrator_Build( void* slIntegrator, void* data ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; FeVariable* feVariable; FeVariable* feVarOld; FeVariable* feVarStar; unsigned field_i; if(self->velocityField) Stg_Component_Build(self->velocityField, data, False); if(self->advectedField) Stg_Component_Build(self->advectedField, data, False); if(self->prevVelField) Stg_Component_Build(self->prevVelField , data, False); for( field_i = 0; field_i < self->variableList->count; field_i++ ) { feVariable = (FeVariable*) self->variableList->data[field_i]; feVarOld = (FeVariable*) self->varOldList->data[field_i]; feVarStar = (FeVariable*) self->varStarList->data[field_i]; if(feVariable) Stg_Component_Build(feVariable, data, False); if(feVarOld ) Stg_Component_Build(feVarOld , data, False); if(feVarStar ) Stg_Component_Build(feVarStar , data, False); } } void _SemiLagrangianIntegrator_Initialise( void* slIntegrator, void* data ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; FeVariable* feVariable; FeVariable* feVarOld; FeVariable* feVarStar; unsigned field_i; if(self->velocityField) Stg_Component_Initialise(self->velocityField, data, False); if(self->advectedField) Stg_Component_Initialise(self->advectedField, data, False); if(self->prevVelField) { Stg_Component_Initialise(self->prevVelField , data, False); SemiLagrangianIntegrator_UpdatePreviousVelocityField( slIntegrator, NULL ); } for( field_i = 0; field_i < self->variableList->count; field_i++ ) { feVariable = (FeVariable*) self->variableList->data[field_i]; feVarOld = (FeVariable*) self->varOldList->data[field_i]; feVarStar = (FeVariable*) self->varStarList->data[field_i]; if(feVariable) Stg_Component_Initialise(feVariable, data, False); if(feVarOld ) Stg_Component_Initialise(feVarOld , data, False); if(feVarStar ) Stg_Component_Initialise(feVarStar , data, False); } } void _SemiLagrangianIntegrator_Execute( void* slIntegrator, void* data ) { } void _SemiLagrangianIntegrator_Destroy( void* slIntegrator, void* data ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; FeVariable* feVariable; FeVariable* feVarOld; FeVariable* feVarStar; unsigned field_i; if(self->velocityField) Stg_Component_Destroy(self->velocityField, data, False); if(self->advectedField) Stg_Component_Destroy(self->advectedField, data, False); if(self->prevVelField) Stg_Component_Destroy(self->prevVelField , data, False); for( field_i = 0; field_i < self->variableList->count; field_i++ ) { feVariable = (FeVariable*) self->variableList->data[field_i]; feVarOld = (FeVariable*) self->varOldList->data[field_i]; feVarStar = (FeVariable*) self->varStarList->data[field_i]; if(feVariable) Stg_Component_Destroy(feVariable, data, False); if(feVarOld ) Stg_Component_Destroy(feVarOld , data, False); if(feVarStar ) Stg_Component_Destroy(feVarStar , data, False); } } void SemiLagrangianIntegrator_InitSolve( void* _self, void* _context ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*) _self; unsigned field_i, node_i; FeVariable* feVariable; FeVariable* feVarOld; FeVariable* feVarStar; double phi[3]; unsigned lMeshSize; FeMesh* mesh; for( field_i = 0; field_i < self->variableList->count; field_i++ ) { feVariable = (FeVariable*) self->variableList->data[field_i]; feVarStar = (FeVariable*) self->varStarList->data[field_i]; feVarOld = (FeVariable*) self->varOldList->data[field_i]; /* we're assuming that the solution vector has already been updated onto the FeVariable (in the SLE class) */ mesh = feVariable->feMesh; lMeshSize = Mesh_GetLocalSize( mesh, MT_VERTEX ); for( node_i = 0; node_i < lMeshSize; node_i++ ) { FeVariable_GetValueAtNode( feVariable, node_i, phi ); FeVariable_SetValueAtNode( feVarOld, node_i, phi ); } FeVariable_SyncShadowValues( feVarOld ); /* generate the _* field */ SemiLagrangianIntegrator_Solve( self, feVarOld, feVarStar ); } } #define INV6 0.166666666667 void IntegrateRungeKutta( FeVariable* velocityField, double dt, double* origin, double* position ) { unsigned ndims = Mesh_GetDimSize( velocityField->feMesh ); unsigned dim_i; double min[3], max[3]; double k[4][3]; double coordPrime[3]; unsigned* periodic = ((CartesianGenerator*)velocityField->feMesh->generator)->periodic; Mesh_GetGlobalCoordRange( velocityField->feMesh, min, max ); FieldVariable_InterpolateValueAt( velocityField, origin, k[0] ); for( dim_i = 0; dim_i < ndims; dim_i++ ) { coordPrime[dim_i] = origin[dim_i] - 0.5 * dt * k[0][dim_i]; PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] ); } FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[1] ); for( dim_i = 0; dim_i < ndims; dim_i++ ) { coordPrime[dim_i] = origin[dim_i] - 0.5 * dt * k[1][dim_i]; PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] ); } FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[2] ); for( dim_i = 0; dim_i < ndims; dim_i++ ) { coordPrime[dim_i] = origin[dim_i] - dt * k[2][dim_i]; PeriodicUpdate( coordPrime, min, max, dim_i, periodic[dim_i] ); } FieldVariable_InterpolateValueAt( velocityField, coordPrime, k[3] ); for( dim_i = 0; dim_i < ndims; dim_i++ ) { position[dim_i] = origin[dim_i] - INV6 * dt * ( k[0][dim_i] + 2.0 * k[1][dim_i] + 2.0 * k[2][dim_i] + k[3][dim_i] ); PeriodicUpdate( position, min, max, dim_i, periodic[dim_i] ); } } /* 2nd order acurate runge kutta algorithm for interpolating backwards in time through a temporally evolving velocity field Durran, D. "Numerical Methods for Wave Equations in Geophysical Fluid Dynamics" (1999), pages 310-313 u(t^(n+0.5)) = 1.5u(t^n) - 0.5u(t^(n-1)) x_* = x^(n+1) - 0.5*dt*u(x^(n+1),t^n) x_j^n = x^(n+1) - dt*u(x_*,t^(n+0.5)) Force term: F = 0.5*[3*S(x_j^n,t^n) - S(x_j^(n-1),t^(n-1))] */ void IntegrateRungeKutta_StgVariableVelocity( FeVariable* currVelField, FeVariable* interVelField, double dt, double* origin, double* position ) { unsigned nDims = Mesh_GetDimSize( currVelField->feMesh ); unsigned dim_i; double min[3], max[3]; double midPoint[3]; double velCurr[3], velInter[3]; CartesianGenerator* gen = (CartesianGenerator*)currVelField->feMesh->generator; Mesh_GetGlobalCoordRange( currVelField->feMesh, min, max ); FieldVariable_InterpolateValueAt( currVelField, origin, velCurr ); for( dim_i = 0; dim_i < nDims; dim_i++ ) { midPoint[dim_i] = origin[dim_i] - 0.5 * dt * velCurr[dim_i]; PeriodicUpdate( midPoint, min, max, dim_i, gen->periodic[dim_i] ); } FieldVariable_InterpolateValueAt( interVelField, midPoint, velInter ); /* 2nd order approximation of velocity at time current + dt/2 */ for( dim_i = 0; dim_i < nDims; dim_i++ ) { position[dim_i] = origin[dim_i] - dt * velInter[dim_i]; PeriodicUpdate( position, min, max, dim_i, gen->periodic[dim_i] ); } } /* for case of temporally evolving velocity field, when we need to integrate backwards in time * throught this to find our take off point */ void SemiLagrangianIntegrator_UpdatePreviousVelocityField( void* _self, void* _context ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*) _self; FeVariable* currVelField = self->velocityField; FeVariable* prevVelField = self->prevVelField; unsigned node_i; double vel[3]; for( node_i = 0; node_i < Mesh_GetLocalSize( currVelField->feMesh, MT_VERTEX ); node_i++ ) { FeVariable_GetValueAtNode( currVelField, node_i, vel ); FeVariable_SetValueAtNode( prevVelField, node_i, vel ); } FeVariable_SyncShadowValues( currVelField ); FeVariable_SyncShadowValues( prevVelField ); } /* cubic Lagrangian interpoation in 1-D */ void InterpLagrange( double x, double* coords, double (*values)[3], unsigned numdofs, double* result ) { unsigned node_i, dof_i; unsigned otherIndices[3]; unsigned otherIndexCount, otherIndex_i; double factor; for( dof_i = 0; dof_i < numdofs; dof_i++ ) result[dof_i] = 0.0; for( node_i = 0; node_i < 4; node_i++ ) { otherIndexCount = 0; for( otherIndex_i = 0; otherIndex_i < 4; otherIndex_i++ ) if( otherIndex_i != node_i ) otherIndices[otherIndexCount++] = otherIndex_i; factor = 1.0; for( otherIndex_i = 0; otherIndex_i < 3; otherIndex_i++ ) factor *= ( x - coords[otherIndices[otherIndex_i]] ) / ( coords[node_i] - coords[otherIndices[otherIndex_i]] ); for( dof_i = 0; dof_i < numdofs; dof_i++ ) { result[dof_i] += ( values[node_i][dof_i] * factor ); } } } Bool PeriodicUpdate( double* pos, double* min, double* max, unsigned dim, Bool isPeriodic ) { if( pos[dim] < min[dim] ) { pos[dim] = (isPeriodic) ? max[dim] - min[dim] + pos[dim] : min[dim]; return True; } if( pos[dim] > max[dim] ) { pos[dim] = (isPeriodic) ? min[dim] - max[dim] + pos[dim] : max[dim]; return True; } return False; } Bool BicubicInterpolatorNew( FeVariable* feVariable, FeVariable* stencilField, double* position, unsigned* sizes, double* result ) { /* Calculated the BicubicInterpolation of the feVariable at position * * Input Args: * feVariable: the field to be interpolated at `position`. * stencilField: the field of initial spline stencils for each node. * position: the position of interpolatation. * sizes: memory chunk of size = sizeof(double)*dim. * results: the interpolated value. * * * Returns Values: * True: if interpolation successful * False: position is not in 'domain' of local processor */ FeMesh* feMesh = feVariable->feMesh; unsigned nInc ; int ijk[3]; int x_i, y_i, z_i, *inc; double localMin[3], localMax[3], double_ijk[3]; Index gNode_I, lNode_I, elementIndex; double px[4], py[4], pz[4]; unsigned nodeIndex[4][4]; unsigned node_I3D[4][4][4]; unsigned nDims = Mesh_GetDimSize( feMesh ); unsigned numdofs = feVariable->dofLayout->dofCounts[0]; double ptsX[4][3], ptsY[4][3], ptsZ[4][3]; Bool inDomain = True; inDomain = Mesh_SearchElements( feMesh, position, &elementIndex ); // get the element id if (!inDomain) return False; FeMesh_GetElementNodes( feMesh, elementIndex, feVariable->inc ); // get the incidence graph (inc.) of nodes on the element nInc = IArray_GetSize( feVariable->inc ); // from inc. get the number of nodes on the element inc = IArray_GetPtr( feVariable->inc ); // get the node ids from inc. FeVariable_GetValueAtNode( stencilField, inc[0], &(double_ijk[0]) ); ijk[0] = lround(double_ijk[0]); ijk[1] = lround(double_ijk[1]); ijk[2] = lround(double_ijk[2]); /* interpolate using Lagrange's formula */ if( nDims == 2 ) { for( y_i = 0; y_i < 4; y_i++ ) for( x_i = 0; x_i < 4; x_i++ ) { gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * sizes[0]; if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ){ printf("Error in %s, trying to build an interpolation to position (%g, %g) using node %d, a non domain node, in interpolator.\n", __func__, position[0], position[1], gNode_I); abort(); } else nodeIndex[x_i][y_i] = lNode_I; } } else { for( z_i = 0; z_i < 4; z_i++ ) for( y_i = 0; y_i < 4; y_i++ ) for( x_i = 0; x_i < 4; x_i++ ) { gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * sizes[0] + ( ijk[2] + z_i ) * sizes[0] * sizes[1]; if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) { printf("Error in %s, trying to build an interpolation to position (%g, %g, %g) using node %d, a non domain node, in interpolator.\n", __func__, position[0], position[1], position[2], gNode_I); abort(); } else node_I3D[x_i][y_i][z_i] = lNode_I; } } if( nDims == 3 ) { for( x_i = 0; x_i < 4; x_i++ ) px[x_i] = Mesh_GetVertex( feMesh, node_I3D[x_i][0][0] )[0]; for( y_i = 0; y_i < 4; y_i++ ) py[y_i] = Mesh_GetVertex( feMesh, node_I3D[0][y_i][0] )[1]; for( z_i = 0; z_i < 4; z_i++ ) pz[z_i] = Mesh_GetVertex( feMesh, node_I3D[0][0][z_i] )[2]; for( z_i = 0; z_i < 4; z_i++ ) { for( y_i = 0; y_i < 4; y_i++ ) { for( x_i = 0; x_i < 4; x_i++ ) FeVariable_GetValueAtNode( feVariable, node_I3D[x_i][y_i][z_i], ptsX[x_i] ); InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] ); } InterpLagrange( position[1], py, ptsY, numdofs, ptsZ[z_i] ); } InterpLagrange( position[2], pz, ptsZ, numdofs, result ); } else { for( x_i = 0; x_i < 4; x_i++ ) px[x_i] = Mesh_GetVertex( feMesh, nodeIndex[x_i][0] )[0]; for( y_i = 0; y_i < 4; y_i++ ) py[y_i] = Mesh_GetVertex( feMesh, nodeIndex[0][y_i] )[1]; for( y_i = 0; y_i < 4; y_i++ ) { for( x_i = 0; x_i < 4; x_i++ ) FeVariable_GetValueAtNode( feVariable, nodeIndex[x_i][y_i], ptsX[x_i] ); InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] ); } InterpLagrange( position[1], py, ptsY, numdofs, result ); } return True; } Bool SemiLagrangianIntegrator_PointsAreClose( double* p1, double* p2, int dim, double rtol, double atol ) { /* check if two points are within rtol (relative tolerance) * or atol (absolute tolerance) * * Intput Parameters: * p1 : point 1 * p2 : point 2 * dim : the dimensions of points * rtol : the relative tolerance * atol : the absolute tolerance * * Return Values: * True: if points are close * False: if points are not close */ double disp[3], p2_norm, length; StGermain_VectorSubtraction(disp, p1, p2, dim); // displacement vector length = StGermain_VectorMagnitude(disp, dim); // length of vector p2_norm = StGermain_VectorMagnitude(p2, dim); // original size of p2 if (length < rtol*p2_norm + atol) return True; return False; } void SemiLagrangianIntegrator_BuildStaticStencils( FeVariable* stencilField ) { /* Function to build the node indices for cubic interpolation. * The idea is to find a record the starting node indices (ijk) for each interpolant stencil. * * **NOTE**: We never want to Sync the stencilField FeVariable shadow values, ie. * FeVariable_SyncShadowValues( stencilField ), because the field contains processor * specific ordering and Syncing with shadow space will produce erroroneous starting indicies * */ FeMesh* feMesh = stencilField->feMesh; Grid **grid; int d_i,ijk[3]; double double_ijk[3]; unsigned *sizes,try,nDims,n_i, nNodes; Index gNode_I; nDims = Mesh_GetDimSize( feMesh ); nNodes = Mesh_GetDomainSize( feMesh, MT_VERTEX ); grid = (Grid**)ExtensionManager_Get( feMesh->info, feMesh, feMesh->vertGridId ); sizes = Grid_GetSizes(*grid); for( n_i=0; n_i<nNodes; n_i++) { /* For every domain node, build the stencil starting location, ijk */ gNode_I = Mesh_DomainToGlobal( feMesh, MT_VERTEX, n_i ); Grid_Lift( *grid, gNode_I, ijk ); /* for every dim try go one node back */ for(d_i=0; d_i<nDims; d_i++) { if( ijk[d_i] == 0 ) { continue; } // skip if at 0 ijk[d_i]--; try = Grid_Project( *grid, ijk ); // if not in domain space don't go back one if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) { ijk[d_i]++; } } /* for every dim try go 3 forward */ for(d_i=0; d_i<nDims; d_i++) { ijk[d_i]+=3; // if we go off the edge, go back one if( ijk[d_i] >= sizes[d_i] ) { ijk[d_i] -= 4; continue; } try = Grid_Project( *grid, ijk ); // if not in domain space go back one, else reset if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) { ijk[d_i]-=4; } else { ijk[d_i]-=3; } } double_ijk[0] = (double)ijk[0]; double_ijk[1] = (double)ijk[1]; double_ijk[2] = (double)ijk[2]; // save ijk as the starting point FeVariable_SetValueAtNode( stencilField, n_i, &(double_ijk[0]) ); } } void SemiLagrangianIntegrator_SolveNew( FeVariable* variableField, double dt, FeVariable* velocityField, FeVariable* varStarField, FeVariable* stencilField ) { /* Function evaluates varStarField - an interpolation of variableField taken at the departure points. * Departure points are positions taken from the nodes and advected backwards along the characteristic curves. * The interpolation method used is a cubic spline and the implementation is only compatible with orthogonal meshes. * * Input Args: * feVariable: the original field to be interpolated. * dt: the time step size to go backwards along the characteristic, it should NOT be > CFL condition. * velocityField: the velocity field used to go backward. * stencilField: the field of initial spline stencils for each node. * varStarField: the resultant field of interpolated variableField taken at the departure points. * */ FeMesh* feMesh = variableField->feMesh; unsigned meshSize = Mesh_GetLocalSize( feMesh, MT_VERTEX ); unsigned nDims = Mesh_GetDimSize( feMesh ); Grid** nodegrid = (Grid**) Mesh_GetExtension( feMesh, Grid*, feMesh->vertGridId ); unsigned* sizes = Grid_GetSizes( *nodegrid ); unsigned node_I; double var[3], x_i[3], delta[3], minLength, *x_0; Bool result; Mesh_GetMinimumSeparation( feMesh, &minLength, delta ); /* sync parallel field variables to get shadow values */ FeVariable_SyncShadowValues( velocityField ); FeVariable_SyncShadowValues( variableField ); /* assume that the variable mesh is the same as the velocity mesh */ for( node_I = 0; node_I < meshSize; node_I++ ) { /* find the position back in time (u*), x_i */ x_0 = Mesh_GetVertex(feMesh, node_I); IntegrateRungeKutta( velocityField, dt, x_0, x_i ); /* if the new x_i is "close" to original node, don't Bicubuic Interpolate, take original node value */ if( SemiLagrangianIntegrator_PointsAreClose(x_i, x_0, nDims, 0, 1e-6*minLength) ) { FeVariable_GetValueAtNode( variableField, node_I, var ); } else { result = BicubicInterpolatorNew(variableField, stencilField, x_i, sizes, var); /* if BicubicInerpolator returns false, x_i was not found in domain space. * Fallback to using the node value. */ if(result == False) { FeVariable_GetValueAtNode( variableField, node_I, var ); } } FeVariable_SetValueAtNode( varStarField, node_I, var ); } /* sync interpolated values */ FeVariable_SyncShadowValues( varStarField ); } Bool BicubicInterpolator( FeVariable* feVariable, double* position, double* delta, unsigned* nNodes, double* result ) { /* Calculated the BicubicInterpolation of the feVariable at position * * Input Args: * feVariable: the field to be interpolated at `position`. * position: the position of interpolatation. * delta: memory chunk of size = sizeof(double)*dim. * nNodes: numbers of nodes in ijk representation. * results: the interpolated value. * * * Returns Values: * True: if interpolation successful * False: position is not in 'domain' of local processor */ FeMesh* feMesh = feVariable->feMesh; unsigned nInc ; int ijk[3]; int x_i, y_i, z_i, *inc; double localMin[3], localMax[3]; Index gNode_I, lNode_I, elementIndex; double px[4], py[4], pz[4]; unsigned nodeIndex[4][4]; unsigned node_I3D[4][4][4]; unsigned nDims = Mesh_GetDimSize( feMesh ); unsigned numdofs = feVariable->dofLayout->dofCounts[0]; double ptsX[4][3], ptsY[4][3], ptsZ[4][3]; Bool inDomain = True; inDomain = Mesh_SearchElements( feMesh, position, &elementIndex ); // get the element id if (!inDomain) return False; FeMesh_GetElementNodes( feMesh, elementIndex, feVariable->inc ); // get the incidence graph (inc.) of nodes on the element nInc = IArray_GetSize( feVariable->inc ); // from inc. get the number of nodes on the element inc = IArray_GetPtr( feVariable->inc ); // get the node ids from inc. if( nInc % 3 == 0 ) /* quadratic elements */ { delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0]; delta[1] = Mesh_GetVertex( feMesh, inc[3] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1]; if( nDims == 3 ) delta[2] = Mesh_GetVertex( feMesh, inc[9] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2]; } else { delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0]; delta[1] = Mesh_GetVertex( feMesh, inc[2] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1]; if( nDims == 3 ) delta[2] = Mesh_GetVertex( feMesh, inc[4] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2]; } Mesh_GetLocalCoordRange( feMesh, localMin, localMax ); gNode_I = Mesh_DomainToGlobal( feMesh, MT_VERTEX, inc[0] ); { Grid **grid; int d_i; unsigned *sizes; grid = (Grid**)ExtensionManager_Get( feMesh->info, feMesh, feMesh->vertGridId ); Grid_Lift( *grid, gNode_I, ijk ); sizes = Grid_GetSizes(*grid); if( nInc % 2 == 0 ) { unsigned try; /* for every dim try go one node back */ for(d_i=0; d_i<nDims; d_i++) { if( ijk[d_i] == 0 ) { continue; } // skip if at 0 ijk[d_i]--; try = Grid_Project( *grid, ijk ); // if not in domain space don't go back one if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) { ijk[d_i]++; } } /* for every dim try go 3 forward */ for(d_i=0; d_i<nDims; d_i++) { ijk[d_i]+=3; // if we go off the edge, go back one if( ijk[d_i] >= sizes[d_i] ) { ijk[d_i] -= 4; continue; } try = Grid_Project( *grid, ijk ); // if not in domain space go back one, else reset if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, try, &try ) ) { ijk[d_i]-=4; } else { ijk[d_i]-=3; } } } } /* interpolate using Lagrange's formula */ if( nDims == 2 ) { for( y_i = 0; y_i < 4; y_i++ ) for( x_i = 0; x_i < 4; x_i++ ) { gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * nNodes[0]; if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ){ printf("Error in BicubicInterpolator(), trying to build an interpolation to position (%g, %g) using node %d, a non domain node, in interpolator.\n", position[0], position[1], gNode_I); abort(); } else nodeIndex[x_i][y_i] = lNode_I; } } else { for( z_i = 0; z_i < 4; z_i++ ) for( y_i = 0; y_i < 4; y_i++ ) for( x_i = 0; x_i < 4; x_i++ ) { gNode_I = ijk[0] + x_i + ( ijk[1] + y_i ) * nNodes[0] + ( ijk[2] + z_i ) * nNodes[0] * nNodes[1]; if( !Mesh_GlobalToDomain( feMesh, MT_VERTEX, gNode_I, &lNode_I ) ) { printf("Error in BicubicInterpolator(), trying to build an interpolation to position (%g, %g, %g) using node %d, a non domain node, in interpolator.\n", position[0], position[1], position[2], gNode_I); abort(); } else node_I3D[x_i][y_i][z_i] = lNode_I; } } if( nDims == 3 ) { for( x_i = 0; x_i < 4; x_i++ ) px[x_i] = Mesh_GetVertex( feMesh, node_I3D[x_i][0][0] )[0]; for( y_i = 0; y_i < 4; y_i++ ) py[y_i] = Mesh_GetVertex( feMesh, node_I3D[0][y_i][0] )[1]; for( z_i = 0; z_i < 4; z_i++ ) pz[z_i] = Mesh_GetVertex( feMesh, node_I3D[0][0][z_i] )[2]; for( z_i = 0; z_i < 4; z_i++ ) { for( y_i = 0; y_i < 4; y_i++ ) { for( x_i = 0; x_i < 4; x_i++ ) FeVariable_GetValueAtNode( feVariable, node_I3D[x_i][y_i][z_i], ptsX[x_i] ); InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] ); } InterpLagrange( position[1], py, ptsY, numdofs, ptsZ[z_i] ); } InterpLagrange( position[2], pz, ptsZ, numdofs, result ); } else { for( x_i = 0; x_i < 4; x_i++ ) px[x_i] = Mesh_GetVertex( feMesh, nodeIndex[x_i][0] )[0]; for( y_i = 0; y_i < 4; y_i++ ) py[y_i] = Mesh_GetVertex( feMesh, nodeIndex[0][y_i] )[1]; for( y_i = 0; y_i < 4; y_i++ ) { for( x_i = 0; x_i < 4; x_i++ ) FeVariable_GetValueAtNode( feVariable, nodeIndex[x_i][y_i], ptsX[x_i] ); InterpLagrange( position[0], px, ptsX, numdofs, ptsY[y_i] ); } InterpLagrange( position[1], py, ptsY, numdofs, result ); } return True; } void SemiLagrangianIntegrator_Solve( void* slIntegrator, FeVariable* variableField, FeVariable* varStarField ) { SemiLagrangianIntegrator* self = (SemiLagrangianIntegrator*)slIntegrator; FiniteElementContext* context = self->context; unsigned node_I; FeMesh* feMesh = variableField->feMesh; unsigned meshSize = Mesh_GetLocalSize( feMesh, MT_VERTEX ); FeVariable* velocityField = self->velocityField; double dt = AbstractContext_Dt( context ); unsigned dim_I; unsigned nDims = Mesh_GetDimSize( feMesh ); double position[3]; double var[3]; Grid** grid = (Grid**) Mesh_GetExtension( feMesh, Grid*, feMesh->elGridId ); unsigned* sizes = Grid_GetSizes( *grid ); unsigned nNodes[3]; double delta[3]; unsigned nInc; int* inc; FeMesh_GetElementNodes( variableField->feMesh, 0, variableField->inc ); nInc = IArray_GetSize( variableField->inc ); inc = IArray_GetPtr( variableField->inc ); delta[0] = Mesh_GetVertex( feMesh, inc[1] )[0] - Mesh_GetVertex( feMesh, inc[0] )[0]; if( nInc % 3 == 0 ) /* quadratic elements */ { delta[1] = Mesh_GetVertex( feMesh, inc[3] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1]; if( nDims == 3 ) delta[2] = Mesh_GetVertex( feMesh, inc[9] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2]; for( dim_I = 0; dim_I < nDims; dim_I++ ) nNodes[dim_I] = 2 * sizes[dim_I] + 1; } else { delta[1] = Mesh_GetVertex( feMesh, inc[2] )[1] - Mesh_GetVertex( feMesh, inc[0] )[1]; if( nDims == 3 ) delta[2] = Mesh_GetVertex( feMesh, inc[4] )[2] - Mesh_GetVertex( feMesh, inc[0] )[2]; for( dim_I = 0; dim_I < nDims; dim_I++ ) nNodes[dim_I] = sizes[dim_I] + 1; } FeVariable_SyncShadowValues( velocityField ); FeVariable_SyncShadowValues( variableField ); /* assume that the variable mesh is the same as the velocity mesh */ for( node_I = 0; node_I < meshSize; node_I++ ) { /* find the position back in time (u*) */ IntegrateRungeKutta( velocityField, dt, Mesh_GetVertex(feMesh, node_I), position ); /* create a bicubic interpolation of variableField at u* */ BicubicInterpolator( variableField, position, delta, nNodes, var ); FeVariable_SetValueAtNode( varStarField, node_I, var ); } FeVariable_SyncShadowValues( varStarField ); }
{ "alphanum_fraction": 0.6416687224, "avg_line_length": 41.8383027523, "ext": "c", "hexsha": "74449ba60667dca412a76ec8b162cacbb104dcea", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_issues_count": 561, "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_line_length": 218, "max_stars_count": 116, "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_path": "underworld/libUnderworld/StgFEM/Utils/src/SemiLagrangianIntegrator.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "num_tokens": 10937, "size": 36483 }
#pragma once #include <bgfx/bgfx.h> #include <napi/napi.h> #include <gsl/gsl> #include <map> #include <optional> namespace Babylon { class VertexBuffer final { public: VertexBuffer(gsl::span<uint8_t> bytes, bool dynamic); ~VertexBuffer(); void Dispose(); void Update(Napi::Env env, gsl::span<uint8_t> bytes); bool CreateHandle(const bgfx::VertexLayout& layout); void PromoteToFloats(bgfx::AttribType::Enum attribType, uint32_t numElements, uint32_t byteOffset, uint32_t byteStride); void Set(bgfx::Encoder* encoder, uint8_t stream, uint32_t startVertex, uint32_t numVertices, bgfx::VertexLayoutHandle layoutHandle); struct InstanceVertexBufferRecord { VertexBuffer* Buffer{}; uint32_t Offset{}; uint32_t Stride{}; uint32_t ElementSize{}; }; static void BuildInstanceDataBuffer(bgfx::InstanceDataBuffer& instanceDataBuffer, const std::map<bgfx::Attrib::Enum, InstanceVertexBufferRecord>& vertexBufferInstance); private: std::optional<std::vector<uint8_t>> m_bytes{}; bool m_dynamic{}; union { bgfx::VertexBufferHandle m_handle{bgfx::kInvalidHandle}; bgfx::DynamicVertexBufferHandle m_dynamicHandle; }; bool m_disposed{}; }; }
{ "alphanum_fraction": 0.6536764706, "avg_line_length": 30.2222222222, "ext": "h", "hexsha": "59f97bd75119f382905128a5a823a3305b912168", "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": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "HarveyLijh/ReactNativeBabylon", "max_forks_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "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": "HarveyLijh/ReactNativeBabylon", "max_issues_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_line_length": 176, "max_stars_count": null, "max_stars_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "HarveyLijh/ReactNativeBabylon", "max_stars_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/VertexBuffer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 315, "size": 1360 }
/** * * @file testing_sposv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Bilel Hadri, Hatem Ltaief * @date 2010-11-15 * @generated s Tue Jan 7 11:45:18 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> #include "testing_smain.h" enum blas_order_type { blas_rowmajor = 101, blas_colmajor = 102 }; enum blas_cmach_type { blas_base = 151, blas_t = 152, blas_rnd = 153, blas_ieee = 154, blas_emin = 155, blas_emax = 156, blas_eps = 157, blas_prec = 158, blas_underflow = 159, blas_overflow = 160, blas_sfmin = 161}; enum blas_norm_type { blas_one_norm = 171, blas_real_one_norm = 172, blas_two_norm = 173, blas_frobenius_norm = 174, blas_inf_norm = 175, blas_real_inf_norm = 176, blas_max_norm = 177, blas_real_max_norm = 178 }; static void BLAS_error(char *rname, int err, int val, int x) { fprintf( stderr, "%s %d %d %d\n", rname, err, val, x ); abort(); } static void BLAS_sge_norm(enum blas_order_type order, enum blas_norm_type norm, int m, int n, const float *a, int lda, float *res) { int i, j; float anorm, v; char rname[] = "BLAS_sge_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_frobenius_norm) { anorm = 0.0f; for (j = n; j; --j) { for (i = m; i; --i) { v = a[0]; anorm += v * v; a++; } a += lda - m; } anorm = sqrt( anorm ); } else if (norm == blas_inf_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += fabsf( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static float BLAS_spow_di(float x, int n) { float rv = 1.0; if (n < 0) { n = -n; x = 1.0 / x; } for (; n; n >>= 1, x *= x) { if (n & 1) rv *= x; } return rv; } static float BLAS_sfpinfo(enum blas_cmach_type cmach) { float eps = 1.0, r = 1.0, o = 1.0, b = 2.0; int t = 53, l = 1024, m = -1021; char rname[] = "BLAS_sfpinfo"; if ((sizeof eps) == sizeof(float)) { t = 24; l = 128; m = -125; } else { t = 53; l = 1024; m = -1021; } /* for (i = 0; i < t; ++i) eps *= half; */ eps = BLAS_spow_di( b, -t ); /* for (i = 0; i >= m; --i) r *= half; */ r = BLAS_spow_di( b, m-1 ); o -= eps; /* for (i = 0; i < l; ++i) o *= b; */ o = (o * BLAS_spow_di( b, l-1 )) * b; switch (cmach) { case blas_eps: return eps; case blas_sfmin: return r; default: BLAS_error( rname, -1, cmach, 0 ); break; } return 0.0; } static int check_factorization(int, float*, float*, int, int , float); static int check_solution(int, int, float*, int, float*, float*, int, float); static int check_estimator(PLASMA_enum, int, float *, int, float *, float, float, float); int testing_sposv(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 4){ USAGE("POSV", "N LDA NRHS LDB", " - N : the size of the matrix\n" " - LDA : leading dimension of the matrix A\n" " - NRHS : number of RHS\n" " - LDB : leading dimension of the RHS B\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); int NRHS = atoi(argv[2]); int LDB = atoi(argv[3]); float eps; int info_solution, info_factorization; int u, trans1, trans2; float *A1 = (float *)malloc(LDA*N*sizeof(float)); float *A2 = (float *)malloc(LDA*N*sizeof(float)); float *B1 = (float *)malloc(LDB*NRHS*sizeof(float)); float *B2 = (float *)malloc(LDB*NRHS*sizeof(float)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)){ printf("Out of Memory \n "); return -2; } eps = BLAS_sfpinfo( blas_eps ); for(u=0; u<2; u++) { trans1 = uplo[u] == PlasmaUpper ? PlasmaTrans : PlasmaNoTrans; trans2 = uplo[u] == PlasmaUpper ? PlasmaNoTrans : PlasmaTrans; /*------------------------------------------------------------- * TESTING SPOSV */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_splgsy( (float)N, N, A1, LDA, 51 ); PLASMA_slacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_splrnt( N, NRHS, B1, LDB, 371 ); PLASMA_slacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); printf("\n"); printf("------ TESTS FOR PLASMA SPOSV ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* PLASMA SPOSV */ PLASMA_sposv(uplo[u], N, NRHS, A2, LDA, B2, LDB); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) && (info_factorization == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING SPOSV(%s) ...................... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING SPOSV(%s) ... FAILED !\n", uplostr[u]); printf("***************************************************\n"); } /*------------------------------------------------------------- * TESTING SPOTRF + SPOTRS */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_splgsy( (float)N, N, A1, LDA, 51 ); PLASMA_slacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_splrnt( N, NRHS, B1, LDB, 371 ); PLASMA_slacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); /* Plasma routines */ PLASMA_spotrf(uplo[u], N, A2, LDA); PLASMA_spotrs(uplo[u], N, NRHS, A2, LDA, B2, LDB); printf("\n"); printf("------ TESTS FOR PLASMA SPOTRF + SPOTRS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)){ printf("***************************************************\n"); printf(" ---- TESTING SPOTRF + SPOTRS (%s)............ PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("****************************************************\n"); printf(" - TESTING SPOTRF + SPOTRS (%s)... FAILED !\n", uplostr[u]); printf("****************************************************\n"); } /*------------------------------------------------------------- * TESTING SPOTRF + ZPTRSM + STRSM */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_splgsy( (float)N, N, A1, LDA, 51 ); PLASMA_slacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_splrnt( N, NRHS, B1, LDB, 371 ); PLASMA_slacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); /* PLASMA routines */ PLASMA_spotrf(uplo[u], N, A2, LDA); PLASMA_strsm(PlasmaLeft, uplo[u], trans1, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); PLASMA_strsm(PlasmaLeft, uplo[u], trans2, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); printf("\n"); printf("------ TESTS FOR PLASMA SPOTRF + STRSM + STRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)){ printf("***************************************************\n"); printf(" ---- TESTING SPOTRF + STRSM + STRSM (%s)..... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("***************************************************\n"); printf(" - TESTING SPOTRF + STRSM + STRSM (%s)... FAILED !\n", uplostr[u]); printf("***************************************************\n"); } /*------------------------------------------------------------- * TESTING ZPOCON on the last call */ { float Anorm = PLASMA_slansy( PlasmaOneNorm, uplo[u], N, A1, LDA ); float Acond; info_solution = PLASMA_spocon(uplo[u], N, A2, LDA, Anorm, &Acond); if ( info_solution == 0 ) { info_solution = check_estimator(uplo[u], N, A1, LDA, A2, Anorm, Acond, eps); } else { printf(" PLASMA_spocon returned info = %d\n", info_solution ); } if ((info_solution == 0)){ printf("***************************************************\n"); printf(" ---- TESTING SPOTRF + ZPOCON (%s) ........... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("**************************************************\n"); printf(" - TESTING SPOTRF + ZPOCON (%s) ... FAILED !\n", uplostr[u]); printf("**************************************************\n"); } } } free(A1); free(A2); free(B1); free(B2); return 0; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ static int check_factorization(int N, float *A1, float *A2, int LDA, int uplo, float eps) { float Anorm, Rnorm; float alpha; int info_factorization; int i,j; float *Residual = (float *)malloc(N*N*sizeof(float)); float *L1 = (float *)malloc(N*N*sizeof(float)); float *L2 = (float *)malloc(N*N*sizeof(float)); float *work = (float *)malloc(N*sizeof(float)); memset((void*)L1, 0, N*N*sizeof(float)); memset((void*)L2, 0, N*N*sizeof(float)); alpha= 1.0; LAPACKE_slacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_strmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } else{ LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_strmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, N, Residual, N, &Rnorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm ); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || isinf(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 60.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; } /*------------------------------------------------------------------------ * Check the accuracy of the solution of the linear system */ static int check_solution(int N, int NRHS, float *A1, int LDA, float *B1, float *B2, int LDB, float eps ) { int info_solution; float Rnorm, Anorm, Xnorm, Bnorm, result; float alpha, beta; float *work = (float *)malloc(N*sizeof(float)); alpha = 1.0; beta = -1.0; BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B2, LDB, &Xnorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm ); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Bnorm ); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, (alpha), A1, LDA, B2, LDB, (beta), B1, LDB); BLAS_sge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Rnorm ); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; } /*------------------------------------------------------------------------ * Check the accuracy of the condition estimator */ static int check_estimator(PLASMA_enum uplo, int N, float *A1, int LDA, float *A2, float Anorm, float Acond, float eps) { int info_solution; float result, Acond_lapack; float invcond, invcond_lapack; info_solution = LAPACKE_spocon(LAPACK_COL_MAJOR, lapack_const(uplo), N, A2, LDA, Anorm, &Acond_lapack); if ( info_solution != 0 ) { printf(" PLASMA_sgecon returned info = %d\n", info_solution ); return info_solution; } invcond_lapack = 1. / ( Acond_lapack ); invcond = 1. / ( Acond ); printf("============\n"); printf("Checking the condition number \n"); printf("-- Acond_plasma = %e, Acond_lapack = %e \n" "-- Ainvcond_plasma = %e, Ainvcond_lapack = %e \n", Acond, Acond_lapack, invcond, invcond_lapack ); result = fabs( Acond_lapack - Acond ) / eps; if ( result > 60. ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } return info_solution; }
{ "alphanum_fraction": 0.4891743562, "avg_line_length": 33.5647773279, "ext": "c", "hexsha": "3eb87cf08c347b9c601f0e9cfe058923674a7359", "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": "testing/testing_sposv.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": "testing/testing_sposv.c", "max_line_length": 115, "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": "testing/testing_sposv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4896, "size": 16581 }
#ifndef PyGSL_TRANSFORM_TYPES_H #define PyGSL_TRANSFORM_TYPES_H 1 /* * All different transforms are handled by only two functions. * PyGSL_transform_ * and * PyGSL_transform_2d_. * * This was done as similar functionallity is needed by all the transforms. * Copy the input data (transforms are often in place), check or allocate * help spaces. Call the function and make clean up. To allow that the * functions need to do quite some decisions to prepare all in proper order * and to do the clean up. * In this file various data types are defined. The first two are needed by the * python type which allows to allocate the proper help space and pass it to * the function. All the others are needed to store the information about the * transform. */ /* ------------------------------------------------------------------------- */ /* * One Python type is used to encapsulate all the different workspaces. This * enum allows the C Code to destinquish between the different types. */ enum pygsl_transform_space_type{ NOSPACE=0, COMPLEX_WORKSPACE, REAL_WORKSPACE, COMPLEX_WAVETABLE, REAL_WAVETABLE, HALFCOMPLEX_WAVETABLE, COMPLEX_WORKSPACE_FLOAT, REAL_WORKSPACE_FLOAT, COMPLEX_WAVETABLE_FLOAT, REAL_WAVETABLE_FLOAT, HALFCOMPLEX_WAVETABLE_FLOAT, WAVELET_WORKSPACE }; #include <pygsl/pygsl_features.h> #include <gsl/gsl_fft.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_complex_float.h> #include <gsl/gsl_fft_real_float.h> #include <gsl/gsl_fft_halfcomplex_float.h> #include <gsl/gsl_blas.h> #ifdef _PYGSL_GSL_HAS_WAVELET #define forward forward_wavelet #define backward backward_wavelet #include <gsl/gsl_wavelet.h> #include <gsl/gsl_wavelet2d.h> #undef forward #undef backward #else /* _PYGSL_GSL_HAS_WAVELET */ #endif /* _PYGSL_GSL_HAS_WAVELET */ /* * Here the corresponding union to address the pointer as the proper type. */ union pygsl_transform_space_t{ gsl_fft_complex_workspace *cws; gsl_fft_complex_wavetable *cwt; gsl_fft_real_workspace *rws; gsl_fft_real_wavetable *rwt; gsl_fft_halfcomplex_wavetable *hcwt; gsl_fft_complex_workspace_float *cwsf; gsl_fft_complex_wavetable_float *cwtf; gsl_fft_real_workspace_float *rwsf; gsl_fft_real_wavetable_float *rwtf; gsl_fft_halfcomplex_wavetable_float *hcwtf; #ifdef _PYGSL_GSL_HAS_WAVELET gsl_wavelet_workspace *wws; #endif void *v; }; /* ------------------------------------------------------------------------- */ /* * From here all data types are defined needed to guide the transform * functions. */ /* * Transformation in float or double mode */ enum pygsl_transform_mode{ MODE_DOUBLE = 1, MODE_FLOAT }; /* * Input data in ... output data in ... */ enum transform_mode{ ComplexComplex = 1, RealReal, RealHalfcomplex, HalfComplexReal }; /* * Should be renamed. Originally the transform mode would only handle the FFT. * There one only needed to destinquish between the radix. Wavelets are also a * bit different. Others to come. */ enum radix_mode{ RADIX_TWO = 1, RADIX_FREE, WAVELET }; /* * Does the basis type consist of only one machine type or two. e.g real * is SINGLE_TYPE, complex PACKED_TYPE (a real and an imaginary part). */ enum pygsl_packed_type{ SINGLE_TYPE=1, PACKED_TYPE=2 }; #define PyGSL_TRANSFORM_MODE_SWITCH(mode, double_element, float_element) \ ((mode == MODE_DOUBLE) ? double_element : float_element) typedef int transform(void * data, size_t stride, size_t N, const void *, void *); typedef int transform_r2(void * data, size_t stride, size_t N); #ifdef _PYGSL_GSL_HAS_WAVELET typedef int wavelet(const gsl_wavelet * W, double *data, size_t stride, size_t N, void *); typedef int wavelet2d(const gsl_wavelet * W, gsl_matrix *m, void *); #endif typedef void * pygsl_transform_helpn_t(int); typedef void * pygsl_transform_help_t(void *); /* * The different transform types. */ union transforms{ transform *free; transform_r2 *radix2; #ifdef _PYGSL_GSL_HAS_WAVELET wavelet *wavelet; wavelet2d *wavelet2d; #endif void *v; }; /* * Functions to construct and destruct the helpers space and the helpers table. * The user can pass them as a proper python type. If not, the proper space * will be allocated using these functions. */ struct _pygsl_transform_func_rf_s { pygsl_transform_helpn_t * space_alloc; pygsl_transform_help_t * space_free; pygsl_transform_helpn_t * table_alloc; pygsl_transform_help_t * table_free; enum pygsl_transform_space_type space_type; enum pygsl_transform_space_type table_type; }; /* * Not all transforms need additional workspace. The ones that need it will put * an instance somewhere and point the func to the approbriate initalisers. * free_space and free_table is used to store if the space and table have to be * freeded at the end of the transform. */ struct _pygsl_transform_help_rf_s{ const struct _pygsl_transform_func_rf_s *func; void * space; void * table; int free_space; int free_table; }; /* * The info about which transform, what input and output * arrays and so forth. Used by _pygsl_transform_help_s to inform the transform * function about the various properties. */ struct _pygsl_transform_info_s { /* * complex -> complex * real -> half_complex * half_complex -> real * real -> real */ enum transform_mode mode; /* float or double ? */ enum pygsl_transform_mode datatype; enum PyArray_TYPES input_array_type; enum PyArray_TYPES output_array_type; /* * Do I need to add some additional offset to the data * pointer before * calling the function. A trick needed for the real to * halfcomplex transform. */ int data_offset; /* Type of the transform. Should be renamed */ enum radix_mode radix2; /* one or two machine types make on basis type ? */ enum pygsl_packed_type packed; }; /* * Finally the struct which gathers all the information. The split up was made, as the * info struct is always needed, but not the helpers. */ struct _pygsl_transform_help_s{ struct _pygsl_transform_info_s *info; union transforms transform; struct _pygsl_transform_help_rf_s *helpers; }; typedef struct _pygsl_transform_help_s pygsl_transform_help_s; /* * The main function doing all the work. Its a function for the ffts and a * method for the wavelets! */ static PyObject * PyGSL_transform_(PyObject *self, PyObject *args, pygsl_transform_help_s *helps); /* * Currently only wavelets provide a 2 dimensional transform */ #ifdef _PYGSL_GSL_HAS_WAVELET static PyObject * PyGSL_transform_2d_(PyObject *self, PyObject *args, pygsl_transform_help_s *helps); #endif #endif /* PyGSL_TRANSFORM_TYPES_H */ /* * Local Variables: * mode: C * c-file-style: "python" * End: */
{ "alphanum_fraction": 0.7283253727, "avg_line_length": 28.6680497925, "ext": "h", "hexsha": "56be3626a51b3a0c5015704237413ce61eff325c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/transform/transformtypes.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1763, "size": 6909 }
#pragma once #include <gsl/span> #include <array> #include "halley/core/api/audio_api.h" namespace Halley { using AudioSourceData = std::array<gsl::span<AudioConfig::SampleFormat>, AudioConfig::maxChannels>; class AudioSource { public: virtual ~AudioSource() {} virtual size_t getNumberOfChannels() const = 0; virtual bool isReady() const { return true; } virtual bool getAudioData(size_t numSamples, AudioSourceData& dst) = 0; }; }
{ "alphanum_fraction": 0.7349665924, "avg_line_length": 22.45, "ext": "h", "hexsha": "22aa245b14a782a7ee9246444d2e029dfdbdc461", "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": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lye/halley", "max_forks_repo_path": "src/engine/audio/src/audio_source.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "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": "lye/halley", "max_issues_repo_path": "src/engine/audio/src/audio_source.h", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lye/halley", "max_stars_repo_path": "src/engine/audio/src/audio_source.h", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "num_tokens": 111, "size": 449 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #ifndef _DNESTVARS_H #define _DNESTVARS_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <gsl/gsl_rng.h> #include "dnest.h" enum PRIOR_TYPE {UNIFORM=0, GAUSSIAN=1, LOG=2}; /* output files */ extern FILE *fsample, *fsample_info; /* random number generator */ extern const gsl_rng_type * dnest_gsl_T; extern gsl_rng * dnest_gsl_r; typedef struct { double value; double tiebreaker; }LikelihoodType; typedef struct { LikelihoodType log_likelihood; double log_X; unsigned long long int visits, exceeds; unsigned long long int accepts, tries; }Level; extern DNestOptions options; extern char options_file[STR_MAX_LENGTH]; typedef struct { int id; void *addr; char tag[50]; int isset; }DNestPARDICT; extern void *particles; extern int dnest_size_of_modeltype; extern int particle_offset_size, particle_offset_double; // sampler extern bool save_to_disk; extern unsigned int num_threads; extern double compression; extern unsigned int regularisation; extern void *particles; extern LikelihoodType *log_likelihoods; extern unsigned int *level_assignments; // number account of unaccepted times extern unsigned int *account_unaccepts; extern int size_levels, size_levels_combine; extern Level *levels; extern Level *copies_of_levels, *levels_combine; extern LikelihoodType *all_above; extern unsigned int count_saves, num_saves, num_saves_restart; extern unsigned long long int count_mcmc_steps; extern LikelihoodType *above; extern unsigned int size_above, size_all_above; extern int dnest_flag_restart, dnest_flag_postprc, dnest_flag_sample_info, dnest_flag_limits; extern double dnest_post_temp; extern char file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH]; extern double post_logz; extern int dnest_num_params; extern char dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH]; extern double *dnest_param_range, *dnest_prior_info; extern int *dnest_prior_type; extern void *dnest_args; //the limits of parameters for each level; extern double *limits, *copies_of_limits; extern int dnest_which_particle_update; // which particle to be updated extern int dnest_which_level_update; // which level to be updated; extern int dnest_thistask, dnest_totaltask; extern int *dnest_perturb_accept; extern int dnest_root; //*********************************************** /* functions */ extern double mod(double y, double x); extern void wrap_limit(double *x, double min, double max); extern int mod_int(int y, int x); extern int dnest_cmp(const void *pa, const void *pb); extern void options_load(char *optfile, DNestOptions *opts); extern void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, double *param_range, int *prior_type, double *prior_info, char *sample_dir, char *optfile, DNestOptions *opts, void *args); extern void finalise(); extern void dnest_run(); extern void dnest_mcmc_run(); extern void update_particle(unsigned int which); extern void update_level_assignment(unsigned int which); extern double log_push(unsigned int which_level); extern bool enough_levels(Level *l, int size_l); extern void do_bookkeeping(); extern void save_levels(); extern void save_particle(); extern void save_limits(); extern void kill_lagging_particles(); extern void renormalise_visits(); extern void recalculate_log_X(); extern void dnest_postprocess(double temperature,char *optfile, DNestOptions *opts); extern void postprocess(double temperature); extern void initialize_output_file(); extern void close_output_file(); extern void dnest_save_restart(); extern void dnest_restart(); extern void dnest_restart_action(int iflag); extern void dnest_accept_action(); extern void dnest_kill_action(int i, int i_copy); extern void dnest_from_prior(void *model); extern double dnest_perturb(void *model); extern void dnest_print_particle(FILE *fp, const void *model); extern void dnest_read_particle(FILE *fp, void *model); extern void dnest_check_directory(char *sample_dir); /*=====================================================*/ // users responsible for following functions extern void (*print_particle)(FILE *fp, const void *model); extern void (*read_particle)(FILE *fp, void *model); extern void (*from_prior)(void *model); extern double (*log_likelihoods_cal)(const void *model); extern double (*log_likelihoods_cal_initial)(const void *model); extern double (*log_likelihoods_cal_restart)(const void *model); extern double (*perturb)(void *model); extern void (*restart_action)(int iflag); extern void (*accept_action)(); extern void (*kill_action)(int i, int i_copy); /*=====================================================*/ #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7569193742, "avg_line_length": 30.7777777778, "ext": "h", "hexsha": "a884224bb55920876f8a7d743f46f021f8c93978", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_path": "src/dnestvars.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_path": "src/dnestvars.h", "max_line_length": 117, "max_stars_count": 6, "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_path": "src/dnestvars.h", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "num_tokens": 1168, "size": 4986 }
#ifndef CWANNIER_PARTIALDOS_VALUES_H #define CWANNIER_PARTIALDOS_VALUES_H #include <gsl/gsl_permutation.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include "HTightBinding.h" #include "ctetra/partial.h" double** PartialDosValues(HTightBinding *Hrs, gsl_matrix *R, int na, int nb, int nc, double sigma, double **Es, double num_dos); void sort_evals_evecs(gsl_vector *energies, gsl_matrix_complex *evecs, int num_bands); #endif // CWANNIER_PARTIALDOS_VALUES_H
{ "alphanum_fraction": 0.7940663176, "avg_line_length": 31.8333333333, "ext": "h", "hexsha": "2658a51e8cb5b2d0fb2aefbae68a4ce084ad18ae", "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": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/cwannier", "max_forks_repo_path": "PartialDosValues.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "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": "tflovorn/cwannier", "max_issues_repo_path": "PartialDosValues.h", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/cwannier", "max_stars_repo_path": "PartialDosValues.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 173, "size": 573 }
/* specfunc/hermite.c * * Copyright (C) 2011, 2012, 2013, 2014, 2019 Konrad Griessinger (konradg(at)gmx.net) * Copyright (C) 2019 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. */ /*----------------------------------------------------------------------* * "The purpose of computing is insight, not numbers." - R.W. Hamming * * Hermite polynomials, Hermite functions * * and their respective arbitrary derivatives * *----------------------------------------------------------------------*/ /* TODO: * - array functions for derivatives of Hermite functions * - asymptotic approximation for derivatives of Hermite functions * - refine existing asymptotic approximations, especially around x=sqrt(2*n+1) or x=sqrt(2*n+1)*sqrt(2), respectively */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_airy.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_hermite.h> #include "error.h" #include "eval.h" #define pow2(n) (gsl_sf_pow_int(2,n)) #define RND(x) ((double) ((x >= 0) ? (int) (x + 0.5) : (int) (x - 0.5))) /* evaluates the probabilists' Hermite polynomial of order n at position x */ int gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result) { if (n < 0) { DOMAIN_ERROR(result); } else if (n == 0) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if (n == 1) { result->val = x; result->err = 0.; return GSL_SUCCESS; } else if (x == 0.0) { if (GSL_IS_ODD(n)) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* for n even, He_n(0) = (-1)^{n/2} (n - 1)!! */ int status = GSL_SUCCESS; if (n - 1 > GSL_SF_DOUBLEFACT_NMAX) /* test if (n - 1)!! will overflow */ { status = GSL_EOVRFLW; result->val = GSL_IS_ODD(n / 2) ? GSL_NEGINF : GSL_POSINF; result->err = GSL_POSINF; } else { gsl_sf_doublefact_e(n - 1, result); if (GSL_IS_ODD(n / 2)) result->val = -result->val; } return status; } } else { /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */ int status = GSL_SUCCESS; const double abs_x = fabs(x); const double thresh1 = abs_x > 1.0 ? 0.9 * GSL_DBL_MAX / abs_x : GSL_DBL_MAX; const double thresh2 = 0.9 * GSL_DBL_MAX; double p_n0 = 1.0; /* He_0(x) */ double p_n1 = x; /* He_1(x) */ double p_n = p_n1; double e_n0 = GSL_DBL_EPSILON; double e_n1 = fabs(x)*GSL_DBL_EPSILON; double e_n = e_n1; int j; for (j = 1; j < n; j++) { if (fabs(p_n1) > thresh1 || /* test if x*p_n1 will overflow */ fabs(p_n0) > thresh2 / j) /* test if j*p_n0 will overflow */ { status = GSL_EOVRFLW; break; } p_n = x*p_n1 - j*p_n0; p_n0 = p_n1; p_n1 = p_n; e_n = fabs(x)*e_n1+j*e_n0; e_n0 = e_n1; e_n1 = e_n; } result->val = p_n; result->err = e_n + fabs(result->val)*GSL_DBL_EPSILON; return status; } } double gsl_sf_hermite_prob(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_prob_e(n, x, &result)); } /* Evaluates the m-th derivative of the probabilists' Hermite polynomial of order n at position x. * The direct formula He^{(m)}_n = n!/(n-m)!*He_{n-m}(x) (where He_j(x) is the j-th probabilists' Hermite polynomial and He^{(m)}_j(x) its m-th derivative) is employed. */ int gsl_sf_hermite_prob_deriv_e(const int m, const int n, const double x, gsl_sf_result * result) { if (n < 0 || m < 0) { DOMAIN_ERROR(result); } else if (n < m) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { int status; double f = gsl_sf_choose(n,m)*gsl_sf_fact(m); gsl_sf_result He; status = gsl_sf_hermite_prob_e(n - m, x, &He); if (status == GSL_SUCCESS) { result->val = He.val*f; result->err = He.err*f + GSL_DBL_EPSILON*fabs(result->val); } else { result->val = He.val; result->err = GSL_POSINF; } return status; } } double gsl_sf_hermite_prob_deriv(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_prob_deriv_e(m, n, x, &result)); } /* evaluates the physicists' Hermite polynomial of order n at position x */ int gsl_sf_hermite_e(const int n, const double x, gsl_sf_result * result) { if (n < 0) { DOMAIN_ERROR(result); } else if (n == 0) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if (n == 1) { result->val = 2.0*x; result->err = 0.; return GSL_SUCCESS; } else if (x == 0.0) { if (GSL_IS_ODD(n)) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else { /* for n even, H_n(0) = (-2)^{n/2} (n - 1)!! */ int status = GSL_SUCCESS; int m = n >> 1; if (n - 1 > GSL_SF_DOUBLEFACT_NMAX) /* test if (n - 1)!! will overflow */ { status = GSL_EOVRFLW; result->val = GSL_IS_ODD(m) ? GSL_NEGINF : GSL_POSINF; result->err = GSL_POSINF; } else { double f = gsl_pow_int(2.0, m); gsl_sf_doublefact_e(n - 1, result); if (result->val > 0.9 * GSL_DBL_MAX / f) /* test if 2^{n/2} * (n-1)!! will overflow */ { status = GSL_EOVRFLW; result->val = GSL_IS_ODD(m) ? GSL_NEGINF : GSL_POSINF; result->err = GSL_POSINF; } else { result->val *= f; result->err *= f; if (GSL_IS_ODD(m)) result->val = -result->val; } } return status; } } else { /* upward recurrence: H_{n+1} = 2x H_n - 2n H_{n-1} */ int status = GSL_SUCCESS; const double two_x = 2.0 * x; const double abs_two_x = fabs(two_x); const double thresh1 = abs_two_x > 1.0 ? 0.9 * GSL_DBL_MAX / abs_two_x : GSL_DBL_MAX; const double thresh2 = 0.9 * GSL_DBL_MAX / 2.0; double p_n0 = 1.0; /* H_0(x) */ double p_n1 = two_x; /* H_1(x) */ double p_n = p_n1; double e_n0 = GSL_DBL_EPSILON; double e_n1 = 2.*fabs(x)*GSL_DBL_EPSILON; double e_n = e_n1; int j; for (j = 1; j <= n - 1; j++) { if (fabs(p_n1) > thresh1 || /* test if 2*x*p_n1 will overflow */ fabs(p_n0) > thresh2 / j) /* test if 2*j*p_n0 will overflow */ { status = GSL_EOVRFLW; break; } p_n = two_x*p_n1 - 2.0*j*p_n0; p_n0 = p_n1; p_n1 = p_n; e_n = 2.*(fabs(x)*e_n1+j*e_n0); e_n0 = e_n1; e_n1 = e_n; } result->val = p_n; result->err = e_n + fabs(result->val)*GSL_DBL_EPSILON; return status; } } double gsl_sf_hermite(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_e(n, x, &result)); } /* Evaluates the m-th derivative of the physicists' Hermite polynomial of order n at position x. * The direct formula H^{(m)}_n = 2**m*n!/(n-m)!*H_{n-m}(x) (where H_j(x) is the j-th physicists' Hermite polynomial and H^{(m)}_j(x) its m-th derivative) is employed. */ int gsl_sf_hermite_deriv_e(const int m, const int n, const double x, gsl_sf_result * result) { if (n < 0 || m < 0) { DOMAIN_ERROR(result); } else if (n < m) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { int status; double f = gsl_sf_choose(n,m)*gsl_sf_fact(m)*pow2(m); gsl_sf_result H; status = gsl_sf_hermite_e(n - m, x, &H); if (status == GSL_SUCCESS) { result->val = H.val*f; result->err = H.err*f + GSL_DBL_EPSILON*fabs(result->val); } else { result->val = H.val; result->err = GSL_POSINF; } return status; } } double gsl_sf_hermite_deriv(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_deriv_e(m, n, x, &result)); } /* evaluates the Hermite function of order n at position x */ int gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result) { if (n < 0) { DOMAIN_ERROR(result); } else if (x == 0.0) { if (GSL_IS_ODD(n)) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { double f = (GSL_IS_ODD(n / 2) ? -1.0 : 1.0); int j; for(j = 1; j < n; j += 2) f *= sqrt(j / (j + 1.0)); result->val = f / sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } else if (n == 0) { result->val = exp(-0.5 * x * x) / sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if (n == 1) { result->val = M_SQRT2 * x * exp(-0.5 * x * x) / sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { /* * This algorithm is based on the modified recurrence algorithm * found in the appendix of: * * B. Bunck, BIT Numerical Mathematics, 49, 281 (2009) * * Numerical tests showed that this algorithm is more stable for * large x (x > 40) than the standard recurrence relation. * Accuracy is comparable to the recurrence relation method * for small x and all n. * * See: * * https://scicomp.stackexchange.com/questions/30896/generate-high-n-quantum-harmonic-oscillator-states-numerically * * for further discussion. */ double hi2 = 1.0 / sqrt(M_SQRTPI); /* \hat{h}_0 */ double hi1 = M_SQRT2 * x * hi2; /* \hat{h}_1 */ double hi = 0.0; double sum_log_scale = 0.0; double abshi; int i; for (i = 2; i <= n; ++i) { hi = sqrt(2.0 / i) * x * hi1 - sqrt((i - 1.0) / i) * hi2; hi2 = hi1; hi1 = hi; abshi = fabs(hi); if (abshi > 1.0) { double log_scale = RND(log(abshi)); double scale = exp(-log_scale); hi *= scale; hi1 *= scale; hi2 *= scale; sum_log_scale += log_scale; } } result->val = hi * exp(-0.5 * x * x + sum_log_scale); result->err = n * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_func(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_func_e(n, x, &result)); } /* * This algorithm is based on the contour integral algorithm of: * * B. Bunck, BIT Numerical Mathematics, 49, 281 (2009) * * It has O(sqrt(n)) complexity */ int gsl_sf_hermite_func_fast_e(const int n, const double x, gsl_sf_result * result) { if (n < 1000 || x == 0.0) { /* for small n, the recurrence method is faster and more accurate */ return gsl_sf_hermite_func_e(n, x, result); } else { size_t j; const double k = sqrt(0.5*n); const size_t steps = (size_t) ceil(6.211 * sqrt(n)); const double dt = M_PI/steps; const double invn2 = 1.0/(n*n); double ex, ex_e, cs, cs_e, sn, sn2, t; gsl_sf_result lngamma; if (n < 36) { gsl_sf_lnfact_e(n, &lngamma); lngamma.val *= 0.5; lngamma.err *= 0.5; t = 0.5*n*log(n) + 0.25*M_LNPI; cs = 0.5*n; lngamma.val += cs - t; lngamma.err += (cs + t)*GSL_DBL_EPSILON; } else { /* approximate ln(gamma_{n,k}) using Stirling's formula */ lngamma.val = 0.25*log(2*n); lngamma.err = (lngamma.val + ((((invn2/3360 + 1.0/2520)*invn2 + 1.0/720)*invn2) + 1.0/24)/n)*GSL_DBL_EPSILON; lngamma.val -= ((((invn2/3360 - 1.0/2520)*invn2 + 1.0/720)*invn2) - 1.0/24)/n; } ex = exp(lngamma.val - n - 0.5*x*x - 2*x*k); cs = (GSL_IS_ODD(n) ? -1 : 1); result->val = 0.5*ex*cs; result->err = 0.5*ex*(lngamma.err + (n + 0.5*x*x + fabs(2*x*k) + 1)*GSL_DBL_EPSILON); ex = exp(lngamma.val - n - 0.5*x*x + 2*x*k); result->val += 0.5*ex; result->err += 0.5*ex*(lngamma.err + (n + 0.5*x*x + fabs(2*x*k) + 1)*GSL_DBL_EPSILON); for (j = 1; j < steps; j++) { t = j*dt; cs = cos(t); ex = exp(lngamma.val - 0.5*x*x + (2*x*k - n*cs)*cs); ex_e = ex*(lngamma.err + GSL_DBL_EPSILON*(1 + 0.5*x*x + (fabs(2*x*k) + fabs(n*cs))*fabs(cs))); sn = sin(t); sn2 = sin(2*t); cs = cos(2*x*k*sn - 0.5*n*sn2 - n*t); cs_e = GSL_MIN(1.0+fabs(cs), GSL_DBL_EPSILON*(fabs(cs) + (fabs(2*x*k*sn) + fabs(0.5*n*sn2) + n*t)*fabs(sin(2*x*k*sn - 0.5*n*sn2 - n*t)))); result->val += ex*cs; result->err += ex*cs_e + ex_e*fabs(cs) + GSL_DBL_EPSILON*fabs(ex*cs); } result->val *= M_1_PI*dt; result->err = M_1_PI*dt*result->err + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_func_fast(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_func_fast_e(n, x, &result)); } /* Evaluates all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array) { if (nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (nmax == 0) { result_array[0] = 1.0; return GSL_SUCCESS; } else if (nmax == 1) { result_array[0] = 1.0; result_array[1] = x; return GSL_SUCCESS; } else { /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */ int status = GSL_SUCCESS; const double abs_x = fabs(x); const double thresh1 = abs_x > 1.0 ? 0.9 * GSL_DBL_MAX / abs_x : GSL_DBL_MAX; const double thresh2 = 0.9 * GSL_DBL_MAX; double p_n0 = 1.0; /* He_0(x) */ double p_n1 = x; /* He_1(x) */ double p_n = p_n1; int j; result_array[0] = 1.0; result_array[1] = x; for (j = 1; j < nmax; j++) { if (fabs(p_n1) > thresh1 || /* test if x*p_n1 will overflow */ fabs(p_n0) > thresh2 / j) /* test if j*p_n0 will overflow */ { status = GSL_EOVRFLW; break; } p_n = x*p_n1 - j*p_n0; p_n0 = p_n1; p_n1 = p_n; result_array[j + 1] = p_n; } return status; } } /* Evaluates the m-th derivative of all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_array_deriv(const int m, const int nmax, const double x, double * result_array) { if (nmax < 0 || m < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (m == 0) { gsl_sf_hermite_prob_array(nmax, x, result_array); return GSL_SUCCESS; } else if (nmax < m) { int j; for (j = 0; j <= nmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (nmax == m) { int j; for (j = 0; j < m; j++) result_array[j] = 0.0; result_array[nmax] = gsl_sf_fact(m); return GSL_SUCCESS; } else if (nmax == m + 1) { int j; for (j = 0; j < m; j++) result_array[j] = 0.0; result_array[nmax-1] = gsl_sf_fact(m); result_array[nmax] = result_array[nmax-1]*(m+1)*x; return GSL_SUCCESS; } else { /* upward recurrence: He^{(m)}_{n+1} = (n+1)/(n-m+1)*(x He^{(m)}_n - n He^{(m)}_{n-1}) */ double p_n0 = gsl_sf_fact(m); /* He^{(m)}_{m}(x) */ double p_n1 = p_n0*(m+1)*x; /* He^{(m)}_{m+1}(x) */ double p_n = p_n1; int j; for (j = 0; j < m; j++) result_array[j] = 0.0; result_array[m] = p_n0; result_array[m + 1] = p_n1; for (j = m + 1; j <= nmax - 1; j++) { p_n = (x*p_n1 - j*p_n0) * (j + 1.0) / (j - m + 1.0); p_n0 = p_n1; p_n1 = p_n; result_array[j + 1] = p_n; } return GSL_SUCCESS; } } /* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the probabilists' Hermite polynomial of order n at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_deriv_array(const int mmax, const int n, const double x, double * result_array) { if (n < 0 || mmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (n == 0) { int j; result_array[0] = 1.0; for (j = 1; j <= mmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (n == 1 && mmax > 0) { int j; result_array[0] = x; result_array[1] = 1.0; for(j=2; j <= mmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (mmax == 0) { result_array[0] = gsl_sf_hermite_prob(n,x); return GSL_SUCCESS; } else if (mmax == 1) { result_array[0] = gsl_sf_hermite_prob(n,x); result_array[1] = n*gsl_sf_hermite_prob(n-1,x); return GSL_SUCCESS; } else { /* upward recurrence */ int k = GSL_MAX_INT(0, n - mmax); double p_n0 = gsl_sf_hermite_prob(k,x); /* He_k(x) */ double p_n1 = gsl_sf_hermite_prob(k+1,x); /* He_{k+1}(x) */ double p_n = p_n1; int j; for(j=n+1; j <= mmax; j++) result_array[j] = 0.0; result_array[GSL_MIN_INT(n,mmax)] = p_n0; result_array[GSL_MIN_INT(n,mmax)-1] = p_n1; for (j = GSL_MIN_INT(mmax,n)-1; j > 0; j--) { k++; p_n = x*p_n1-k*p_n0; p_n0 = p_n1; p_n1 = p_n; result_array[j - 1] = p_n; } p_n = 1.0; for (j = 1; j <= GSL_MIN_INT(n, mmax); j++) { p_n = p_n*(n-j+1); result_array[j] = p_n*result_array[j]; } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*He_j(x) with He_j being the j-th probabilists' Hermite polynomial. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to probabilists' Hermite polynomials is used. */ int gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = a[0]; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = a[0]+a[1]*x; result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*x)) ; return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + x b_{n+1} - (n+1) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for(j=n; j >= 0; j--){ btmp = b0; b0 = a[j]+x*b0-(j+1)*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(x)*e0+(j+1)*e1); e1 = etmp; } result->val = b0; result->err = e0 + fabs(b0)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_prob_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_prob_series_e(n, x, a, &result)); } /* Evaluates all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_array(const int nmax, const double x, double * result_array) { if(nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (nmax == 0) { result_array[0] = 1.0; return GSL_SUCCESS; } else if (nmax == 1) { result_array[0] = 1.0; result_array[1] = 2.0*x; return GSL_SUCCESS; } else { /* upward recurrence: H_{n+1} = 2x H_n - 2n H_{n-1} */ int status = GSL_SUCCESS; const double two_x = 2.0 * x; const double abs_two_x = fabs(two_x); const double thresh1 = abs_two_x > 1.0 ? 0.9 * GSL_DBL_MAX / abs_two_x : GSL_DBL_MAX; const double thresh2 = 0.9 * GSL_DBL_MAX / 2.0; double p_n0 = 1.0; /* H_0(x) */ double p_n1 = two_x; /* H_1(x) */ double p_n = p_n1; int j; result_array[0] = 1.0; result_array[1] = 2.0*x; for (j = 1; j < nmax; j++) { if (fabs(p_n1) > thresh1 || /* test if 2*x*p_n1 will overflow */ fabs(p_n0) > thresh2 / j) /* test if 2*j*p_n0 will overflow */ { status = GSL_EOVRFLW; } p_n = two_x*p_n1 - 2.0*j*p_n0; p_n0 = p_n1; p_n1 = p_n; result_array[j + 1] = p_n; } return status; } } /* Evaluates the m-th derivative of all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_array_deriv(const int m, const int nmax, const double x, double * result_array) { if (nmax < 0 || m < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (m == 0) { gsl_sf_hermite_array(nmax, x, result_array); return GSL_SUCCESS; } else if (nmax < m) { int j; for(j = 0; j <= nmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (nmax == m) { int j; for(j = 0; j < m; j++) result_array[j] = 0.0; result_array[nmax] = pow2(m)*gsl_sf_fact(m); return GSL_SUCCESS; } else if (nmax == m + 1) { int j; for(j = 0; j < m; j++) result_array[j] = 0.0; result_array[nmax-1] = pow2(m)*gsl_sf_fact(m); result_array[nmax] = result_array[nmax-1]*2*(m+1)*x; return GSL_SUCCESS; } else { /* upward recurrence: H^{(m)}_{n+1} = 2(n+1)/(n-m+1)*(x H^{(m)}_n - n H^{(m)}_{n-1}) */ double p_n0 = pow2(m)*gsl_sf_fact(m); /* H^{(m)}_{m}(x) */ double p_n1 = p_n0*2*(m+1)*x; /* H^{(m)}_{m+1}(x) */ double p_n; int j; for(j = 0; j < m; j++) result_array[j] = 0.0; result_array[m] = p_n0; result_array[m+1] = p_n1; for (j = m + 1; j < nmax; ++j) { p_n = (x*p_n1 - j*p_n0) * 2 * (j + 1.0) / (j - m + 1.0); p_n0 = p_n1; p_n1 = p_n; result_array[j + 1] = p_n; } return GSL_SUCCESS; } } /* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the physicists' Hermite polynomial of order n at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_deriv_array(const int mmax, const int n, const double x, double * result_array) { if (n < 0 || mmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (n == 0) { int j; result_array[0] = 1.0; for(j = 1; j <= mmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (n == 1 && mmax > 0) { int j; result_array[0] = 2*x; result_array[1] = 1.0; for (j = 2; j <= mmax; j++) result_array[j] = 0.0; return GSL_SUCCESS; } else if (mmax == 0) { result_array[0] = gsl_sf_hermite(n,x); return GSL_SUCCESS; } else if (mmax == 1) { result_array[0] = gsl_sf_hermite(n,x); result_array[1] = 2*n*gsl_sf_hermite(n - 1, x); return GSL_SUCCESS; } else { /* upward recurrence */ int k = GSL_MAX_INT(0, n - mmax); double p_n0 = gsl_sf_hermite(k, x); /* H_k(x) */ double p_n1 = gsl_sf_hermite(k + 1, x); /* H_{k+1}(x) */ double p_n = p_n1; int j; for (j = n + 1; j <= mmax; j++) result_array[j] = 0.0; result_array[GSL_MIN_INT(n,mmax)] = p_n0; result_array[GSL_MIN_INT(n,mmax)-1] = p_n1; for (j = GSL_MIN_INT(mmax, n) - 1; j > 0; j--) { k++; p_n = 2*x*p_n1 - 2*k*p_n0; p_n0 = p_n1; p_n1 = p_n; result_array[j - 1] = p_n; } p_n = 1.0; for (j = 1; j <= GSL_MIN_INT(n,mmax); j++) { p_n *= 2.0 * (n - j + 1.0); result_array[j] *= p_n; } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*H_j(x) with H_j being the j-th physicists' Hermite polynomial. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to physicists' Hermite polynomials is used. */ int gsl_sf_hermite_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = a[0]; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = a[0]+a[1]*2.*x; result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*2.*x)) ; return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + 2x b_{n+1} - 2(n+1) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for(j=n; j >= 0; j--){ btmp = b0; b0 = a[j]+2.*x*b0-2.*(j+1)*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(2.*x)*e0+2.*(j+1)*e1); e1 = etmp; } result->val = b0; result->err = e0 + fabs(b0)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_series_e(n, x, a, &result)); } /* Evaluates all Hermite functions up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array) { if (nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if (nmax == 0) { result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI); return GSL_SUCCESS; } else if (nmax == 1) { result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI); result_array[1] = result_array[0]*M_SQRT2*x; return GSL_SUCCESS; } else { /* upward recurrence: Psi_{n+1} = sqrt(2/(n+1))*x Psi_n - sqrt(n/(n+1)) Psi_{n-1} */ const double arg = -0.5 * x * x; double hi2 = 1.0 / sqrt(M_SQRTPI); double hi1 = M_SQRT2 * x * hi2; double hi = 0.0; double sum_log_scale = 0.0; double abshi; int i; result_array[0] = exp(arg) * hi2; result_array[1] = result_array[0] * M_SQRT2 * x; for (i = 2; i <= nmax; ++i) { hi = sqrt(2.0 / i) * x * hi1 - sqrt((i - 1.0) / i) * hi2; hi2 = hi1; hi1 = hi; abshi = fabs(hi); if (abshi > 1.0) { double log_scale = RND(log(abshi)); double scale = exp(-log_scale); hi *= scale; hi1 *= scale; hi2 *= scale; sum_log_scale += log_scale; } result_array[i] = hi * exp(arg + sum_log_scale); } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*Psi_j(x) with Psi_j being the j-th Hermite function. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to Hermite functions is used. */ int gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if (n < 0) { DOMAIN_ERROR(result); } else if (n == 0) { result->val = a[0]*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } else if (n == 1) { result->val = (a[0]+a[1]*M_SQRT2*x)*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = 2.*GSL_DBL_EPSILON*(fabs(a[0])+fabs(a[1]*M_SQRT2*x))*exp(-0.5*x*x)/sqrt(M_SQRTPI); return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + sqrt(2/(n+1))*x b_{n+1} - sqrt((n+1)/(n+2)) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for (j = n; j >= 0; j--) { btmp = b0; b0 = a[j]+sqrt(2./(j+1))*x*b0-sqrt((j+1.)/(j+2.))*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+sqrt(2./(j+1))*fabs(x)*e0+sqrt((j+1.)/(j+2.))*e1); e1 = etmp; } result->val = b0*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = e0 + fabs(result->val)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_func_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_func_series_e(n, x, a, &result)); } /* Evaluates the m-th derivative of the Hermite function of order n at position x. * A summation including upward recurrences is used. */ int gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result) { if(m < 0 || n < 0) { DOMAIN_ERROR(result); } else if (m == 0) { return gsl_sf_hermite_func_e(n, x, result); } else if (m == 1) { double hi2 = 1.0 / sqrt(M_SQRTPI); double hi1 = M_SQRT2 * x * hi2; double hi = 0.0; double sum_log_scale = 0.0; double abshi; int i; for (i = 2; i <= n; ++i) { hi = sqrt(2.0 / i) * x * hi1 - sqrt((i - 1.0) / i) * hi2; hi2 = hi1; hi1 = hi; abshi = fabs(hi); if (abshi > 1.0) { double log_scale = RND(log(abshi)); double scale = exp(-log_scale); hi *= scale; hi1 *= scale; hi2 *= scale; sum_log_scale += log_scale; } } /* psi'_n(x) = sqrt(2 n) psi_{n-1} - x psi_n */ result->val = (sqrt(2.0*n) * hi2 - x * hi) * exp(-0.5 * x * x + sum_log_scale); result->err = n * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { int j; double r,er,b; double h0 = 1.; double h1 = x; double eh0 = GSL_DBL_EPSILON; double eh1 = GSL_DBL_EPSILON; double p0 = 1.; double p1 = M_SQRT2*x; double ep0 = GSL_DBL_EPSILON; double ep1 = M_SQRT2*GSL_DBL_EPSILON; double f = 1.; for (j=GSL_MAX_INT(1,n-m+1);j<=n;j++) f *= sqrt(2.*j); if (m > n) { f = (GSL_IS_ODD(m-n)?-f:f); for (j=0;j<GSL_MIN_INT(n,m-n);j++) f *= (m-j)/(j+1.); } for (j=1;j<=m-n;j++) { b = x*h1-j*h0; h0 = h1; h1 = b; b = (fabs(x)*eh1+j*eh0); eh0 = eh1; eh1 = b; } b = 0.; for (j=1;j<=n-m;j++) { b = (M_SQRT2*x*p1-sqrt(j)*p0)/sqrt(j+1.); p0 = p1; p1 = b; b = (M_SQRT2*fabs(x)*ep1+sqrt(j)*ep0)/sqrt(j+1.); ep0 = ep1; ep1 = b; } b = 0.; r = 0.; er = 0.; for (j=GSL_MAX_INT(0,m-n);j<=m;j++) { r += f*h0*p0; er += eh0*fabs(f*p0)+ep0*fabs(f*h0)+GSL_DBL_EPSILON*fabs(f*h0*p0); b = x*h1-(j+1.)*h0; h0 = h1; h1 = b; b = 0.5*(fabs(x)*eh1+(j+1.)*eh0); eh0 = eh1; eh1 = b; b = (M_SQRT2*x*p1-sqrt(n-m+j+1.)*p0)/sqrt(n-m+j+2.); p0 = p1; p1 = b; b = 0.5*(M_SQRT2*fabs(x)*ep1+sqrt(n-m+j+1.)*ep0)/sqrt(n-m+j+2.); ep0 = ep1; ep1 = b; f *= -(m-j)/(j+1.)/sqrt(n-m+j+1.)*M_SQRT1_2; } result->val = r*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = er*fabs(exp(-0.5*x*x)/sqrt(M_SQRTPI)) + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_func_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_func_der_e(m, n, x, &result)); } static double H_zero_init(const int n, const int k) { double p = 1., x = 1., y = 1.; if (k == 1 && n > 50) { x = (GSL_IS_ODD(n)?1./sqrt((n-1)/6.):1./sqrt(0.5*n)); } else { p = -0.7937005259840997373758528196*gsl_sf_airy_zero_Ai(n/2-k+1); x = sqrt(2*n+1.); y = pow(2*n+1.,1/6.); x = x - p/y - 0.1*p*p/(x*y*y) + (9/280. - p*p*p*11/350.)/(x*x*x) + (p*277/12600. - gsl_sf_pow_int(p,4)*823/63000.)/gsl_sf_pow_int(x,4)/y; } p = acos(x/sqrt(2*n+1.)); y = M_PI*(-2*(n/2-k)-1.5)/(n+0.5); if(gsl_fcmp(y,sin(2.*p)-2*p,GSL_SQRT_DBL_EPSILON)==0) return x; /* initial approx sufficiently accurate */ if (y > -GSL_DBL_EPSILON) return sqrt(2*n+1.); if (p < GSL_DBL_EPSILON) p = GSL_DBL_EPSILON; if (p > M_PI_2) p = M_PI_2; if (sin(2.*p)-2*p > y){ x = GSL_MAX((sin(2.*p)-2*p-y)/4.,GSL_SQRT_DBL_EPSILON); do{ x *= 2.; p += x; } while (sin(2.*p)-2*p > y); } do { x = p; p -= (sin(2.*p)-2.*p-y)/(2.*cos(2.*p)-2.); if (p<0.||p>M_PI_2) p = M_PI_2; } while (gsl_fcmp(x,p,100*GSL_DBL_EPSILON)!=0); return sqrt(2*n+1.)*cos(p); } /* lookup table for the positive zeros of the probabilists' Hermite polynomials of order 3 through 20 */ static double He_zero_tab[99] = { 1.73205080756887729352744634151, 0.741963784302725857648513596726, 2.33441421833897723931751226721, 1.35562617997426586583052129087, 2.85697001387280565416230426401, 0.616706590192594152193686099399, 1.88917587775371067550566789858, 3.32425743355211895236183546247, 1.154405394739968127239597758838, 2.36675941073454128861885646856, 3.75043971772574225630392202571, 0.539079811351375108072461918694, 1.63651904243510799922544657297, 2.80248586128754169911301080618, 4.14454718612589433206019783917, 1.023255663789132524828148225810, 2.07684797867783010652215614374, 3.20542900285646994336567590292, 4.51274586339978266756667884317, 0.484935707515497653046233483105, 1.46598909439115818325066466416, 2.48432584163895458087625118368, 3.58182348355192692277623675546, 4.85946282833231215015516494660, 0.928868997381063940144111999584, 1.87603502015484584534137013967, 2.86512316064364499771968407254, 3.93616660712997692868589612142, 5.18800122437487094818666404539, 0.444403001944138945299732445510, 1.34037519715161672153112945211, 2.25946445100079912386492979448, 3.22370982877009747166319001956, 4.27182584793228172295999293076, 5.50090170446774760081221630899, 0.856679493519450033897376121795, 1.72541837958823916151095838741, 2.62068997343221478063807762201, 3.56344438028163409162493844661, 4.59139844893652062705231872720, 5.80016725238650030586450565322, 0.412590457954601838167454145167, 1.24268895548546417895063983219, 2.08834474570194417097139675101, 2.96303657983866750254927123447, 3.88692457505976938384755016476, 4.89693639734556468372449782879, 6.08740954690129132226890147034, 0.799129068324547999424888414207, 1.60671006902872973652322479373, 2.43243682700975804116311571682, 3.28908242439876638890856229770, 4.19620771126901565957404160583, 5.19009359130478119946445431715, 6.36394788882983831771116094427, 0.386760604500557347721047189801, 1.16382910055496477419336819907, 1.95198034571633346449212362880, 2.76024504763070161684598142269, 3.60087362417154828824902745506, 4.49295530252001124266582263095, 5.47222570594934308841242925805, 6.63087819839312848022981922233, 0.751842600703896170737870774614, 1.50988330779674075905491513417, 2.28101944025298889535537879396, 3.07379717532819355851658337833, 3.90006571719800990903311840097, 4.77853158962998382710540812497, 5.74446007865940618125547815768, 6.88912243989533223256205432938, 0.365245755507697595916901619097, 1.09839551809150122773848360538, 1.83977992150864548966395498992, 2.59583368891124032910545091458, 3.37473653577809099529779309480, 4.18802023162940370448450911428, 5.05407268544273984538327527397, 6.00774591135959752029303858752, 7.13946484914647887560975631213, 0.712085044042379940413609979021, 1.42887667607837287134157901452, 2.15550276131693514033871248449, 2.89805127651575312007902775275, 3.66441654745063847665304033851, 4.46587262683103133615452574019, 5.32053637733603803162823765939, 6.26289115651325170419416064557, 7.38257902403043186766326977122, 0.346964157081355927973322447164, 1.04294534880275103146136681143, 1.74524732081412671493067861704, 2.45866361117236775131735057433, 3.18901481655338941485371744116, 3.94396735065731626033176813604, 4.73458133404605534390170946748, 5.57873880589320115268040332802, 6.51059015701365448636289263918, 7.61904854167975829138128156060 }; /* * Computes the s-th zero the probabilists' Hermite polynomial of order n. * A Newton iteration using a continued fraction representation adapted from: * * [E.T. Whittaker (1914), On the continued fractions which represent the * functions of Hermite and other functions defined by differential equations, * Proceedings of the Edinburgh Mathematical Society, 32, 65-74] * * is performed with the initial approximation from * * [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite * functions, pp. 117-126 in D. Dominici and R. S. Maier, eds, "Special Functions * and Orthogonal Polynomials", Contemporary Mathematics, vol 471 (2008)] * * refined via the bisection method. */ int gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result) { if (n <= 0 || s < 0 || s > n/2) { DOMAIN_ERROR(result); } else if (s == 0) { if (GSL_IS_ODD(n) == 1) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } else if (n == 2) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if (n < 21) { result->val = He_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2]; result->err = GSL_DBL_EPSILON*(result->val); return GSL_SUCCESS; } else { double d = 1., x = 1., x0 = 1.; int j; x = H_zero_init(n,s) * M_SQRT2; do { x0 = x; d = 0.; for (j=1; j<n; j++) d = j/(x-d); x -= (x-d)/n; /* gsl_fcmp can be used since the smallest zero approaches 1/sqrt(n) or 1/sqrt((n-1)/3.) * for large n and thus all zeros are non-zero (except for the trivial case handled above) */ } while (gsl_fcmp(x, x0, 10*GSL_DBL_EPSILON) != 0); result->val = x; result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0); return GSL_SUCCESS; } } double gsl_sf_hermite_prob_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_prob_zero_e(n, s, &result)); } /* lookup table for the positive zeros of the physicists' Hermite polynomials of order 3 through 20 */ static double H_zero_tab[99] = { 1.22474487139158904909864203735, 0.524647623275290317884060253835, 1.65068012388578455588334111112, 0.958572464613818507112770593893, 2.02018287045608563292872408814, 0.436077411927616508679215948251, 1.335849074013696949714895282970, 2.35060497367449222283392198706, 0.816287882858964663038710959027, 1.67355162876747144503180139830, 2.65196135683523349244708200652, 0.381186990207322116854718885584, 1.157193712446780194720765779063, 1.98165675669584292585463063977, 2.93063742025724401922350270524, 0.723551018752837573322639864579, 1.46855328921666793166701573925, 2.26658058453184311180209693284, 3.19099320178152760723004779538, 0.342901327223704608789165025557, 1.03661082978951365417749191676, 1.75668364929988177345140122011, 2.53273167423278979640896079775, 3.43615911883773760332672549432, 0.656809566882099765024611575383, 1.32655708449493285594973473558, 2.02594801582575533516591283121, 2.78329009978165177083671870152, 3.66847084655958251845837146485, 0.314240376254359111276611634095, 0.947788391240163743704578131060, 1.59768263515260479670966277090, 2.27950708050105990018772856942, 3.02063702512088977171067937518, 3.88972489786978191927164274724, 0.605763879171060113080537108602, 1.22005503659074842622205526637, 1.85310765160151214200350644316, 2.51973568567823788343040913628, 3.24660897837240998812205115236, 4.10133759617863964117891508007, 0.291745510672562078446113075799, 0.878713787329399416114679311861, 1.47668273114114087058350654421, 2.09518325850771681573497272630, 2.74847072498540256862499852415, 3.46265693360227055020891736115, 4.30444857047363181262129810037, 0.565069583255575748526020337198, 1.13611558521092066631913490556, 1.71999257518648893241583152515, 2.32573248617385774545404479449, 2.96716692790560324848896036355, 3.66995037340445253472922383312, 4.49999070730939155366438053053, 0.273481046138152452158280401965, 0.822951449144655892582454496734, 1.38025853919888079637208966969, 1.95178799091625397743465541496, 2.54620215784748136215932870545, 3.17699916197995602681399455926, 3.86944790486012269871942409801, 4.68873893930581836468849864875, 0.531633001342654731349086553718, 1.06764872574345055363045773799, 1.61292431422123133311288254454, 2.17350282666662081927537907149, 2.75776291570388873092640349574, 3.37893209114149408338327069289, 4.06194667587547430689245559698, 4.87134519367440308834927655662, 0.258267750519096759258116098711, 0.776682919267411661316659462284, 1.30092085838961736566626555439, 1.83553160426162889225383944409, 2.38629908916668600026459301424, 2.96137750553160684477863254906, 3.57376906848626607950067599377, 4.24811787356812646302342016090, 5.04836400887446676837203757885, 0.503520163423888209373811765050, 1.01036838713431135136859873726, 1.52417061939353303183354859367, 2.04923170985061937575050838669, 2.59113378979454256492128084112, 3.15784881834760228184318034120, 3.76218735196402009751489394104, 4.42853280660377943723498532226, 5.22027169053748216460967142500, 0.245340708300901249903836530634, 0.737473728545394358705605144252, 1.23407621539532300788581834696, 1.73853771211658620678086566214, 2.25497400208927552308233334473, 2.78880605842813048052503375640, 3.34785456738321632691492452300, 3.94476404011562521037562880052, 4.60368244955074427307767524898, 5.38748089001123286201690041068 }; /* * Computes the s-th zero the physicists' Hermite polynomial of order n, thus also * the s-th zero of the Hermite function of order n. A Newton iteration using a continued * fraction representation adapted from: * * [E.T. Whittaker (1914), On the continued fractions which represent the functions of Hermite * and other functions defined by differential equations, Proceedings of the Edinburgh Mathematical * Society, 32, 65-74] * * An initial approximation is used from: * * [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite functions, * pp. 117-126 in D. Dominici and R. S. Maier, eds, "Special Functions and Orthogonal Polynomials", * Contemporary Mathematics, vol 471 (2008)] * * which is refined via the bisection method. */ int gsl_sf_hermite_zero_e(const int n, const int s, gsl_sf_result * result) { if (n <= 0 || s < 0 || s > n/2) { DOMAIN_ERROR(result); } else if (s == 0) { if (GSL_IS_ODD(n) == 1) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } else if (n == 2) { result->val = M_SQRT1_2; result->err = 0.; return GSL_SUCCESS; } else if (n < 21) { result->val = H_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2]; result->err = GSL_DBL_EPSILON*(result->val); return GSL_SUCCESS; } else { double d = 1., x = 1., x0 = 1.; int j; x = H_zero_init(n,s); do { x0 = x; d = 0.; for (j=1; j<n; j++) d = 2*j/(2.*x-d); x -= (2*x-d)*0.5/n; /* gsl_fcmp can be used since the smallest zero approaches 1/sqrt(n) or 1/sqrt((n-1)/3.) * for large n and thus all zeros are non-zero (except for the trivial case handled above) */ } while (gsl_fcmp(x, x0, 10*GSL_DBL_EPSILON) != 0); result->val = x; result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0); return GSL_SUCCESS; } } double gsl_sf_hermite_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_zero_e(n, s, &result)); } int gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result) { return gsl_sf_hermite_zero_e(n, s, result); } double gsl_sf_hermite_func_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_func_zero_e(n, s, &result)); } #ifndef GSL_DISABLE_DEPRECATED int gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result) { return gsl_sf_hermite_e(n, x, result); } double gsl_sf_hermite_phys(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_phys_e(n, x, &result)); } int gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result) { return gsl_sf_hermite_deriv_e(m, n, x, result); } double gsl_sf_hermite_phys_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_phys_der_e(m, n, x, &result)); } int gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array) { return gsl_sf_hermite_array(nmax, x, result_array); } int gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { return gsl_sf_hermite_series_e(n, x, a, result); } double gsl_sf_hermite_phys_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_phys_series_e(n, x, a, &result)); } int gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array) { return gsl_sf_hermite_array_deriv(m, nmax, x, result_array); } int gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array) { return gsl_sf_hermite_deriv_array(mmax, n, x, result_array); } int gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result) { return gsl_sf_hermite_zero_e(n, s, result); } double gsl_sf_hermite_phys_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_zero_e(n, s, &result)); } int gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array) { return gsl_sf_hermite_prob_array_deriv(m, nmax, x, result_array); } int gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array) { return gsl_sf_hermite_prob_deriv_array(mmax, n, x, result_array); } int gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result) { return gsl_sf_hermite_prob_deriv_e(m, n, x, result); } double gsl_sf_hermite_prob_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_prob_deriv_e(m, n, x, &result)); } #endif /* !GSL_DISABLE_DEPRECATED */
{ "alphanum_fraction": 0.59057744, "avg_line_length": 27.15532382, "ext": "c", "hexsha": "d515331c79792b8dedf579a6d11a02d563f6ee86", "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/specfunc/hermite.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/specfunc/hermite.c", "max_line_length": 260, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/hermite.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": 16856, "size": 49477 }
/** * @file bblas_daccuracy.c * * @brief BBLAS accuracy tests for double_Complex precision. * * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @generated from bblas_zaccuracy.c normal z -> d, Mon Jun 6 09:44:14 2016 **/ #endif #include "bblas_common.h" #include <lapacke.h> #include <cblas.h> #define REAL /** * bblas_dgemm_tolerance computes the forward error * @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_{\infty} + * |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f] * **/ void bblas_dgemm_tolerance(bblas_dtest_t *test, double **C_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, An, Bm, Bn, M, K, N, ldc; int max_work_size = max(test->maxK,max(test->maxM, test->maxN)); double Anorm, Bnorm, Rnorm, result; double eps = LAPACKE_dlamch_work('e'); double alpha =-1; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Temporary buffer to save (test-arrayC -C_final) */ double **C_diff; C_diff = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayC in C_diff */ bblas_dcopy_Cinit(test, C_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { M = test->M[batch_iter]; K = test->K[batch_iter]; N = test->N[batch_iter]; ldc = test->ldc[batch_iter]; if (test->transA[batch_iter] == BblasNoTrans) { Am = M; An = K; } else { Am = K; An = M; } if (test->transB[batch_iter] == BblasNoTrans) { Bm = K; Bn = N; } else { Bm = N; Bn = K; } /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { M = test->M[first_index]; K = test->K[first_index]; ldc = test->ldc[first_index]; N = test->N[first_index]; if (test->transA[first_index] == BblasNoTrans) { Am = M; An = K; } else { Am = K; An = M; } if (test->transB[first_index] == BblasNoTrans) { Bm = K; Bn = N; } else { Bm = N; Bn = K; } for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); /*Compute the relative error */ result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps); switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal: Fixed, Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(C_diff[index]); } free(C_diff); free(work); } /** * bblas_dstarmm_tolerance computes the forward error * @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_{\infty} + * |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f] * **/ void bblas_dstarmm_tolerance(bblas_dtest_t *test, double **C_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, Bm, Bn, N, ldc; int max_work_size = max(test->maxM, test->maxN); double Anorm, Bnorm, Rnorm, result; double eps = LAPACKE_dlamch_work('e'); double alpha =-1; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Temporary buffer to save (test-arrayC -C_final) */ double **C_diff; C_diff = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayC in C_diff */ bblas_dcopy_Cinit(test, C_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { N = test->N[batch_iter]; ldc = test->ldc[batch_iter]; if(test->side[batch_iter] == BblasLeft ) { Am = test->M[batch_iter]; } else { Am = test->N[batch_iter]; } Bm = test->ldb[batch_iter]; Bn = test->N[batch_iter]; /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); result = Rnorm / ((N*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { N = test->N[first_index]; ldc = test->ldc[first_index]; if(test->side[first_index] == BblasLeft ) { Am = test->M[first_index]; } else { Am = test->N[first_index]; } Bm = test->ldb[first_index]; Bn = test->N[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); /*Compute the relative error */ result = Rnorm / ((N*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps); switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal: Fixed, Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(C_diff[index]); } free(C_diff); free(work); } /** * bblas_dstark_tolerance computes the forward error * @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|A\|_1 + * |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f] * **/ void bblas_dstark_tolerance(bblas_dtest_t *test, double **C_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, An, N, K, ldc; char u; int max_work_size = max(test->maxK, test->maxN); double Anorm, ATnorm, Rnorm, result; double eps = LAPACKE_dlamch_work('e'); double alpha_norm, beta_norm; double alpha =-1; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Temporary buffer to save (test-arrayC -C_final) */ double **C_diff; C_diff = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayC in C_diff */ bblas_dcopy_Cinit(test, C_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { N = test->N[batch_iter]; K = test->K[batch_iter]; ldc = test->ldc[batch_iter]; if (test->trans[batch_iter] == BblasNoTrans) { Am = N; An = K; } else { Am = K; An = N; } if(test->uplo[batch_iter] == BblasLower ) { u = 'L'; }else { u = 'U'; } /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the one norm of A */ ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work); if (test->routine == BBLAS_HERK) { beta_norm = cabs(test->beta_herk[batch_iter]); alpha_norm = cabs(test->alpha_herk[batch_iter]); }else{ beta_norm = cabs(test->beta[batch_iter]); alpha_norm = cabs(test->alpha[batch_iter]); } result = Rnorm / ((K*alpha_norm*Anorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { N = test->N[first_index]; K = test->K[first_index]; ldc = test->ldc[first_index]; if (test->trans[first_index] == BblasNoTrans) { Am = N; An = K; } else { Am = K; An = N; } if(test->uplo[first_index] == BblasLower ) { u = 'L'; }else { u = 'U'; } for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); Rnorm = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the one norm of A */ ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work); if (test->routine == BBLAS_HERK) { beta_norm = cabs(test->beta_herk[first_index]); alpha_norm = cabs(test->alpha_herk[first_index]); }else{ beta_norm = cabs(test->beta[first_index]); alpha_norm = cabs(test->alpha[first_index]); } /*Compute the relative error */ result = Rnorm / ((K*alpha_norm*Anorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps); switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal: Fixed, Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(C_diff[index]); } free(C_diff); free(work); } /** * bblas_dstar2k_tolerance computes the forward error * @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_1 + * K|\alpha|\|B\|_{\infty}\|A\|_1 + * |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f] * **/ void bblas_dstar2k_tolerance(bblas_dtest_t *test, double **C_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, An, Bn, Bm, N, K, ldc; int max_work_size = max(test->maxK, test->maxN); double Anorm, Bnorm, ATnorm, BTnorm, Rnorm, result; double beta_norm; double eps = LAPACKE_dlamch_work('e'); double alpha =-1; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Temporary buffer to save (test-arrayC -C_final) */ double **C_diff; C_diff = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayC in C_diff */ bblas_dcopy_Cinit(test, C_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { N = test->N[batch_iter]; K = test->K[batch_iter]; ldc = test->ldc[batch_iter]; if (test->trans[batch_iter] == BblasNoTrans) { Am = N; An = K; Bn = K; } else { Am = K; An = N; Bn = N; } Bm = test->ldb[batch_iter]; /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the one norm of A */ ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); /*Compute the one norm of B */ BTnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work); if(test->routine == BBLAS_HER2K) { beta_norm = cabs(test->beta_herk[batch_iter]); }else { beta_norm = cabs(test->beta[batch_iter]); } result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*BTnorm + K*cabs(test->alpha[batch_iter])*Bnorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) //fixed size { N = test->N[first_index]; K = test->K[first_index]; ldc = test->ldc[first_index]; if (test->trans[first_index] == BblasNoTrans) { Am = N; An = K; Bn = K; } else { Am = K; An = N; Bn = N; } Bm = test->ldb[first_index]; for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute the error C - C_finial */ cblas_daxpy (ldc*N, (alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work); /*Compute the infinity norm of A */ Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the one norm of A */ ATnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm of B */ Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work); /*Compute the one norm of B */ BTnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work); if(test->routine == BBLAS_HER2K) { beta_norm = cabs(test->beta_herk[first_index]); }else { beta_norm = cabs(test->beta[first_index]); } /*Compute the relative error */ result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*BTnorm + K*cabs(test->alpha[first_index])*Bnorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps); switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal: Fixed, Target no defined\n"); exit(EXIT_FAILURE); } } }else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(C_diff[index]); } free(C_diff); free(work); } /** * bblas_dtrmm_tolerance computes the forward error * @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((|\alpha|\|A\|_{\infty}\|B\|_{\infty}N\epsilon).@f] * **/ void bblas_dtrmm_tolerance(bblas_dtest_t *test, double **B_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, An, ldb, N, M; int max_work_size = max(test->maxK, test->maxN); char u, diag; double Anorm, Rnorm, result; double eps = LAPACKE_dlamch_work('e'); double alpha =-1; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Temporary buffer to save (test-arrayB -B_final) */ double **B_diff; B_diff = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayB in B_diff */ bblas_dcopy_Binit(test, B_diff); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { N = test->N[batch_iter]; M = test->M[batch_iter]; ldb = test->ldb[batch_iter]; Am = test->lda[batch_iter]; if(test->side[batch_iter] == BblasLeft ) { An = M; }else { An = N; } if(test->uplo[batch_iter] == BblasLower ) { u = 'L'; }else { u = 'U'; } if(test->diag[batch_iter] == BblasUnit ) { diag = 'U'; }else { diag = 'N'; } /*Compute the error B - B_finial */ cblas_daxpy (ldb*N, (alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work); /*Infinity norm of the triangular matrix A */ Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am, An, test->arrayA[batch_iter], Am, work); result = Rnorm/(N*cabs(test->alpha[batch_iter])*Anorm*test->Binitnorm[batch_iter]*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) { N = test->N[first_index]; M = test->M[first_index]; ldb = test->ldb[first_index]; Am = test->lda[first_index]; if(test->side[first_index] == BblasLeft ) { An = M; }else { An = N; } if(test->uplo[first_index] == BblasLower ) { u = 'L'; }else { u = 'U'; } if(test->diag[first_index] == BblasUnit ) { diag = 'U'; }else { diag = 'N'; } for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute the error B - B_finial */ cblas_daxpy (ldb*N, (alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1); /*Compute the infinity norm associated with the error */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work); /*Infinity norm of the triangular matrix A */ Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am, An, test->arrayA[batch_iter], Am, work); result = Rnorm/(N*cabs(test->alpha[first_index])*Anorm*test->Binitnorm[batch_iter]*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } } else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(B_diff[index]); } free(B_diff); free(work); } /** * bblas_dtrsm_tolerance computes the backward error * @f[\|\alpha B - AX \|_{\infty}/((\|A\|_{\infty}\|X\| + |\alpha|\|B\|_{\infty})N\epsilon).@f] * **/ void bblas_dtrsm_tolerance(bblas_dtest_t *test, double **B_final) { /*Local variables */ int batch_count = test->batch_count; int batch_iter, first_index = 0; int Am, An, ldb, N, M; int max_work_size = max(test->maxK, test->maxN); char u, diag; double Anorm, Rnorm, result, Xnorm; double eps = LAPACKE_dlamch_work('e'); double alpha; double *work = (double *)malloc(max_work_size*sizeof(double)); /*Variable to save the residual alphaB -AX */ double **residual; residual = (double **) malloc(batch_count*sizeof(double *)); /*Make a copy of test->arrayB (X) in residual */ bblas_dcopy_Binit(test, residual); /*Variable size */ if( test->batch_opts == BBLAS_VARIABLE ) { for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { N = test->N[batch_iter]; M = test->M[batch_iter]; ldb = test->ldb[batch_iter]; Am = test->lda[batch_iter]; if(test->side[batch_iter] == BblasLeft ) { An = M; }else { An = N; } if(test->uplo[batch_iter] == BblasLower ) { u = 'L'; }else { u = 'U'; } if(test->diag[batch_iter] == BblasUnit ) { diag = 'U'; }else { diag = 'N'; } /*Compute residual <- AX (dtrmm) */ alpha = 1; cblas_dtrmm(BblasColMajor, test->side[batch_iter], test->uplo[batch_iter], test->transA[batch_iter], test->diag[batch_iter], M, N, (alpha), test->arrayA[batch_iter], test->lda[batch_iter], residual[batch_iter], ldb); /*Compute Binit = alpha Binit */ for (int index=0; index < ldb*N; index++) { test->Binit[batch_iter][index] = test->alpha[batch_iter]*test->Binit[batch_iter][index]; } /*Compute the residual <- alpha B - Ax */ alpha= -1; cblas_daxpy (ldb*N, (alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1); /*Compute the infinity norm associated with the residual */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work); /*Infinity norm of the triangular matrix A */ Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm associated with X (B) */ Xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work); result = Rnorm/(Anorm*Xnorm*N*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } }else if( test->batch_opts == BBLAS_FIXED ) { N = test->N[first_index]; M = test->M[first_index]; ldb = test->ldb[first_index]; Am = test->lda[first_index]; if(test->side[first_index] == BblasLeft ) { An = M; }else { An = N; } if(test->uplo[first_index] == BblasLower ) { u = 'L'; }else { u = 'U'; } if(test->diag[first_index] == BblasUnit ) { diag = 'U'; }else { diag = 'N'; } for( batch_iter =0; batch_iter < batch_count ; batch_iter++) { /*Compute residual <- AX (dtrmm) */ alpha = 1; cblas_dtrmm(BblasColMajor, test->side[first_index], test->uplo[first_index], test->transA[first_index], test->diag[first_index], M, N, (alpha), (const double*) test->arrayA[batch_iter], test->lda[first_index], residual[batch_iter], ldb); /*Compute Binit = alpha Binit */ for (int index=0; index < ldb*N; index++) { test->Binit[batch_iter][index] = test->alpha[first_index]*test->Binit[batch_iter][index]; } /*Compute the residual <- alpha B - Ax */ alpha = -1; cblas_daxpy (ldb*N, (alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1); /*Compute the infinity norm associated with the residual */ Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work); /*Infinity norm of the triangular matrix A */ Anorm = LAPACKE_dlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am, An, test->arrayA[batch_iter], Am, work); /*Compute the infinity norm associated with X (B) */ Xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work); result = Rnorm/(Anorm*Xnorm*N*eps); /*Compute the relative error */ switch(test->target) { case BBLAS_MKL: test->mkl_error[batch_iter] = result; break; case BBLAS_CUBLAS: case BBLAS_MAGMA: test->device_error[batch_iter] = result; break; case BBLAS_OTHER: test->other_error[batch_iter] = result; break; default: printf("In bblas_dcheck_Cfinal, Variable: Target no defined\n"); exit(EXIT_FAILURE); } } } else { bblas_error("bblas_dtesting.c", "wrong batch_opts value"); } /*Free allocated memory */ for(int index =0; index < batch_count; index++) { free(residual[index]); } free(residual); free(work); } /** * Calls bblas_dstar2k_tolerance. **/ #ifdef COMPLEX void bblas_dsyr2k_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstar2k_tolerance(test, C_final); } #endif /** * Calls bblas_dstar2k_tolerance. **/ void bblas_dsyr2k_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstar2k_tolerance(test, C_final); } /** * Calls bblas_dstark_tolerance. **/ #ifdef COMPLEX void bblas_dsyrk_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstark_tolerance(test, C_final); } #endif /** * Calls bblas_dstark_tolerance. **/ void bblas_dsyrk_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstark_tolerance(test, C_final); } /** * Calls bblas_dstarmm_tolerance. **/ #ifdef COMPLEX void bblas_dsymm_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstarmm_tolerance(test, C_final); } #endif /** * Calls bblas_dstamm_tolerance. **/ void bblas_dsymm_tolerance(bblas_dtest_t *test, double **C_final) { bblas_dstarmm_tolerance(test, C_final); }
{ "alphanum_fraction": 0.6259314456, "avg_line_length": 26.2669039146, "ext": "c", "hexsha": "7bfab0c3276ab0b46749caa1a3b143b4d94238f5", "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": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_path": "testing/bblas_daccuracy.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "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/BBLAS-ref", "max_issues_repo_path": "testing/bblas_daccuracy.c", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_path": "testing/bblas_daccuracy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9127, "size": 29524 }
/* combination/combination.c * based on permutation/permutation.c by Brian Gough * * Copyright (C) 2001 Szymon Jaroszewicz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_combination.h> size_t gsl_combination_n (const gsl_combination * c) { return c->n ; } size_t gsl_combination_k (const gsl_combination * c) { return c->k ; } size_t * gsl_combination_data (const gsl_combination * c) { return c->data ; } #ifndef HIDE_INLINE_STATIC size_t gsl_combination_get (const gsl_combination * c, const size_t i) { if (gsl_check_range) { if (i >= c->k) /* size_t is unsigned, can't be negative */ { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } } return c->data[i]; } #endif int gsl_combination_valid (gsl_combination * c) { const size_t n = c->n ; const size_t k = c->k ; size_t i, j ; if( k > n ) { GSL_ERROR("combination has k greater than n", GSL_FAILURE) ; } for (i = 0; i < k; i++) { const size_t ci = c->data[i]; if (ci >= n) { GSL_ERROR("combination index outside range", GSL_FAILURE) ; } for (j = 0; j < i; j++) { if (c->data[j] == ci) { GSL_ERROR("duplicate combination index", GSL_FAILURE) ; } if (c->data[j] > ci) { GSL_ERROR("combination indices not in increasing order", GSL_FAILURE) ; } } } return GSL_SUCCESS; } int gsl_combination_next (gsl_combination * c) { /* Replaces c with the next combination (in the standard lexicographical * ordering). Returns GSL_FAILURE if there is no next combination. */ const size_t n = c->n; const size_t k = c->k; size_t *data = c->data; size_t i; if(k == 0) { return GSL_FAILURE; } i = k - 1; while(i > 0 && data[i] == n - k + i) { i--; } if(i == 0 && data[i] == n - k) { return GSL_FAILURE; } data[i]++; for(; i < k - 1; i++) { data[i + 1] = data[i] + 1; } return GSL_SUCCESS; } int gsl_combination_prev (gsl_combination * c) { /* Replaces c with the previous combination (in the standard * lexicographical ordering). Returns GSL_FAILURE if there is no * previous combination. */ const size_t n = c->n; const size_t k = c->k; size_t *data = c->data; size_t i; if(k == 0) { return GSL_FAILURE; } i = k - 1; while(i > 0 && data[i] == data[i-1] + 1) { i--; } if(i == 0 && data[i] == 0) { return GSL_FAILURE; } data[i++]--; for(; i < k; i++) { data[i] = n - k + i; } return GSL_SUCCESS; } int gsl_combination_memcpy (gsl_combination * dest, const gsl_combination * src) { const size_t src_n = src->n; const size_t src_k = src->k; const size_t dest_n = dest->n; const size_t dest_k = dest->k; if (src_n != dest_n || src_k != dest_k) { GSL_ERROR ("combination lengths are not equal", GSL_EBADLEN); } { size_t j; for (j = 0; j < src_k; j++) { dest->data[j] = src->data[j]; } } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5825757576, "avg_line_length": 20.8421052632, "ext": "c", "hexsha": "6f8c817bd3b864c7458fb785b61e0627fb05968f", "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/combination/combination.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/combination/combination.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/combination/combination.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": 1142, "size": 3960 }
/* * 1dcol.c * * MPI code for performing parallel dense matrix-vector multiplication using 1D * columnwise partitioning. * * Written by cetinsamet -*- cetin.samet@metu.edu.tr * April, 2019 * */ #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <cblas.h> int main(int argc, char *argv[]) { int i, j; int rank, size; double minStart, maxEnd; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int N = atoi(argv[1]); int pSize = N / size; /* Initialize result vector */ double* RESULT; RESULT = (double*) malloc(N * sizeof(double)); /* Initialize local result vector */ double* locResult; locResult = (double*) malloc(N * sizeof(double)); /* Initialize matrix */ double **matrix = (double **) malloc(N * sizeof(double*)); for(i = 0; i < N; i++) { matrix[i] = (double *) malloc(N * sizeof(double)); } for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) matrix[i][j] = i + j; } /* Initialize vector */ double* vector; vector = (double*) malloc(N * sizeof(double)); for (i = 0; i < N; ++i) vector[i] = i; /* Initialize matrix */ double **p_matrix = (double **) malloc(N * sizeof(double*)); for(i = 0; i < N; i++) p_matrix[i] = (double *) malloc(pSize * sizeof(double)); for (j = 0; j < pSize; ++j) { for (i = 0; i < N; ++i) p_matrix[i][j] = matrix[i][(rank * pSize) + j]; } /* Initialize local vector */ double* p_vector; p_vector = (double*) malloc(N * sizeof(double)); for (i = 0; i < pSize; ++i) { p_vector[i] = vector[(rank * pSize) + i]; } double pStart = MPI_Wtime(); // <-- Start Time /* Calculate local dot product */ for (i = 0; i < pSize; ++i) { for (j = 0; j < N; ++j) { locResult[j] += p_matrix[j][i] * p_vector[i]; for (i = 0; i < N; ++i) MPI_Reduce(&locResult[i], &RESULT[i], 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); double pEnd = MPI_Wtime(); // <-- Stop Time MPI_Reduce(&pStart, &minStart, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&pEnd, &maxEnd, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); /* Print result */ if (rank == 0) { printf("RESULT of MATRIX-VECTOR MULTIPLICATION:\n"); for (i = 0; i < N; ++i) printf("%f ", RESULT[i]); printf("\n"); printf("Vector size: %d\tElapsed time: %f\n", N, maxEnd - minStart); } MPI_Finalize(); return 0; }
{ "alphanum_fraction": 0.5840965862, "avg_line_length": 24.2626262626, "ext": "c", "hexsha": "29eb27ba2c8352448640ee8bf577c915dc13c7af", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-04T15:06:49.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-07T20:29:30.000Z", "max_forks_repo_head_hexsha": "5aa0344816e0176c291557d9208666a5e9911860", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cetinsamet/denseMatrix-vector-multiplication", "max_forks_repo_path": "1dcol.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5aa0344816e0176c291557d9208666a5e9911860", "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": "cetinsamet/denseMatrix-vector-multiplication", "max_issues_repo_path": "1dcol.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "5aa0344816e0176c291557d9208666a5e9911860", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cetinsamet/denseMatrix-vector-multiplication", "max_stars_repo_path": "1dcol.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 779, "size": 2402 }
#include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_multifit.h> int main() { const size_t n = 1000; /* number of observations */ const size_t p = 2; /* number of model parameters */ size_t i; gsl_rng *r = gsl_rng_alloc(gsl_rng_default); gsl_matrix *X = gsl_matrix_alloc(n, p); gsl_vector *y = gsl_vector_alloc(n); for (i = 0; i < n; ++i) { /* generate first random variable u */ double ui = 5.0 * gsl_ran_gaussian(r, 1.0); /* set v = u + noise */ double vi = ui + gsl_ran_gaussian(r, 0.001); /* set y = u + v + noise */ double yi = ui + vi + gsl_ran_gaussian(r, 1.0); /* since u =~ v, the matrix X is ill-conditioned */ gsl_matrix_set(X, i, 0, ui); gsl_matrix_set(X, i, 1, vi); /* rhs vector */ gsl_vector_set(y, i, yi); } { const size_t npoints = 200; /* number of points on L-curve and GCV curve */ gsl_multifit_linear_workspace *w = gsl_multifit_linear_alloc(n, p); gsl_vector *c = gsl_vector_alloc(p); /* OLS solution */ gsl_vector *c_lcurve = gsl_vector_alloc(p); /* regularized solution (L-curve) */ gsl_vector *c_gcv = gsl_vector_alloc(p); /* regularized solution (GCV) */ gsl_vector *reg_param = gsl_vector_alloc(npoints); gsl_vector *rho = gsl_vector_alloc(npoints); /* residual norms */ gsl_vector *eta = gsl_vector_alloc(npoints); /* solution norms */ gsl_vector *G = gsl_vector_alloc(npoints); /* GCV function values */ double lambda_l; /* optimal regularization parameter (L-curve) */ double lambda_gcv; /* optimal regularization parameter (GCV) */ double G_gcv; /* G(lambda_gcv) */ size_t reg_idx; /* index of optimal lambda */ double rcond; /* reciprocal condition number of X */ double chisq, rnorm, snorm; /* compute SVD of X */ gsl_multifit_linear_svd(X, w); rcond = gsl_multifit_linear_rcond(w); fprintf(stderr, "matrix condition number = %e\n\n", 1.0 / rcond); /* unregularized (standard) least squares fit, lambda = 0 */ gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0); fprintf(stderr, "=== Unregularized fit ===\n"); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c, 0), gsl_vector_get(c, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* calculate L-curve and find its corner */ gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w); gsl_multifit_linear_lcorner(rho, eta, &reg_idx); /* store optimal regularization parameter */ lambda_l = gsl_vector_get(reg_param, reg_idx); /* regularize with lambda_l */ gsl_multifit_linear_solve(lambda_l, X, y, c_lcurve, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0) + pow(lambda_l * snorm, 2.0); fprintf(stderr, "\n=== Regularized fit (L-curve) ===\n"); fprintf(stderr, "optimal lambda: %g\n", lambda_l); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c_lcurve, 0), gsl_vector_get(c_lcurve, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* calculate GCV curve and find its minimum */ gsl_multifit_linear_gcv(y, reg_param, G, &lambda_gcv, &G_gcv, w); /* regularize with lambda_gcv */ gsl_multifit_linear_solve(lambda_gcv, X, y, c_gcv, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0) + pow(lambda_gcv * snorm, 2.0); fprintf(stderr, "\n=== Regularized fit (GCV) ===\n"); fprintf(stderr, "optimal lambda: %g\n", lambda_gcv); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c_gcv, 0), gsl_vector_get(c_gcv, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* output L-curve and GCV curve */ for (i = 0; i < npoints; ++i) { printf("%e %e %e %e\n", gsl_vector_get(reg_param, i), gsl_vector_get(rho, i), gsl_vector_get(eta, i), gsl_vector_get(G, i)); } /* output L-curve corner point */ printf("\n\n%f %f\n", gsl_vector_get(rho, reg_idx), gsl_vector_get(eta, reg_idx)); /* output GCV curve corner minimum */ printf("\n\n%e %e\n", lambda_gcv, G_gcv); gsl_multifit_linear_free(w); gsl_vector_free(c); gsl_vector_free(c_lcurve); gsl_vector_free(reg_param); gsl_vector_free(rho); gsl_vector_free(eta); gsl_vector_free(G); } gsl_rng_free(r); gsl_matrix_free(X); gsl_vector_free(y); return 0; }
{ "alphanum_fraction": 0.5952334056, "avg_line_length": 36.0070921986, "ext": "c", "hexsha": "72082067f3a0e799aa8e51e73eba83cd330e7149", "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/fitreg.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/fitreg.c", "max_line_length": 98, "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/fitreg.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": 1495, "size": 5077 }
/* To execute: * ./driver <n> # for some positive integer n * */ #include "q_incs.h" #include <lapacke.h> #include "matrix_helpers.h" #include "positive_solver.h" /* testing and benchmarking for AxEqualsB solver. * generates a random matrix A, and tests the positive semidefinite solver * by running iton AtA and tests the full solver by running it on A. * * the current method of generating random matrices isn't perfect, but it's * better than it seems because solving Ax = b is independent of any scaling * factor, so the size of the matrix is irrelevant. */ static int _bench_drop_n = 0; static int _bench_iters = 1; static bool _verbose = false; static void _print_input( double **A, double *x, double *b, int n ) { for ( int i = 0; i < n; i++ ) { fprintf(stderr, "[ "); for ( int j = 0; j < n; j++ ) { if ( j == 0 ) { fprintf(stderr, " %2d ", (int)index_symm_matrix(A, i, j)); } else { fprintf(stderr, ", %2d ", (int)index_symm_matrix(A, i, j)); } } fprintf(stderr, "] "); // print x fprintf(stderr, " [ "); fprintf(stderr, " %2d ", (int)x[i]); fprintf(stderr, "] "); // print b fprintf(stderr, " = [ "); fprintf(stderr, " %3d ", (int)b[i]); fprintf(stderr, "] "); fprintf(stderr, "\n"); } } /* assembly code to read the TSC */ static inline uint64_t _RDTSC(void) { unsigned int hi, lo; __asm__ volatile("rdtsc" : "=a" (lo), "=d" (hi)); return ((uint64_t)hi << 32) | lo; } static void _print_result(double *x_expected, double *x_returned, double *b_expected, double *b_returned, char *name, int n, double runtime, bool checker_success) { bool error = false; fprintf(stderr, "CHECKING %s RESULTS\n", name); if (_verbose) { fprintf(stderr, "x(expect), x(%s), b(expect), b(%s)\n", name, name); } for (int i=0; i < n; i++) { if (_verbose) { fprintf(stderr, " %lf, %lf, %lf, %lf", x_expected[i], x_returned[i], b_expected[i], b_returned[i]); } if ( abs(b_returned[i] - b_expected[i]) < 0.001 ) { if (_verbose) { fprintf(stderr, " %s_MATCH\n", name); } } else { error = true; if (_verbose) { fprintf(stderr, " %s_ERROR\n", name); } } } fprintf(stderr, "%s %s in %.3e cycles, checker said %s.\n\n", name, error ? "FAILED" : "SUCCEEDED", runtime, checker_success ? "SUCCEEDED" : "FAILED"); } static int _run_our_tests( double **A, double *x_expected, double *b, double **A_posdef, double *b_posdef, int n ) { int status = 0; double **A_posdef_copy = NULL; double **A_posdef_full = NULL; double *b_posdef_copy = NULL; double *b_returned = NULL; double *x_returned = NULL; uint64_t begin, total; double avg_cycles; bool checker_success; status = alloc_symm_matrix(&A_posdef_copy, n); cBYE(status); status = alloc_matrix(&A_posdef_full, n); cBYE(status); b_posdef_copy = malloc(n * sizeof(double)); return_if_malloc_failed(b_posdef_copy); b_returned = malloc(n * sizeof(double)); return_if_malloc_failed(b_returned); x_returned = malloc(n * sizeof(double)); return_if_malloc_failed(x_returned); for (int i = 0; i < n; i++) { b_posdef_copy[i] = b_posdef[i]; for(int j = 0; j < n; j++) { A_posdef_full[i][j] = index_symm_matrix(A_posdef, i, j); if (j < n - i) { A_posdef_copy[i][j] = A_posdef[i][j]; } } } // time computations for each solver total = 0; for (int i = 0; i < _bench_iters; i++) { begin = _RDTSC(); status = posdef_positive_solver(A_posdef, x_returned, b_posdef, n); cBYE(status); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_symm_matrix_vector(A_posdef, x_returned, n, b_returned); checker_success = symm_positive_solver_check(A_posdef, x_returned, b_posdef, n, 0.0); _print_result(x_expected, x_returned, b_posdef, b_returned, "POSDEF_SLOW", n, avg_cycles, checker_success); total = 0; for (int i = 0; i < _bench_iters; i++) { for (int i = 0; i < n; i++) { b_posdef_copy[i] = b_posdef[i]; for(int j = 0; j < n - i; j++) { A_posdef_copy[i][j] = A_posdef[i][j]; } } begin = _RDTSC(); status = posdef_positive_solver_fast(A_posdef_copy, x_returned, b_posdef_copy, n); cBYE(status); cBYE(status); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_symm_matrix_vector(A_posdef, x_returned, n, b_returned); checker_success = symm_positive_solver_check(A_posdef, x_returned, b_posdef, n, 0.0); _print_result(x_expected, x_returned, b_posdef, b_returned, "POSDEF_FAST", n, avg_cycles, checker_success); total = 0; for (int i = 0; i < _bench_iters; i++) { for (int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { A_posdef_full[i][j] = index_symm_matrix(A_posdef, i, j); } } begin = _RDTSC(); status = full_posdef_positive_solver(A_posdef_full, x_returned, b_posdef, n); cBYE(status); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_symm_matrix_vector(A_posdef, x_returned, n, b_returned); checker_success = symm_positive_solver_check(A_posdef, x_returned, b_posdef, n, 0.0); _print_result(x_expected, x_returned, b_posdef, b_returned, "FULL_POSDEF_SLOW", n, avg_cycles, checker_success); total = 0; for (int i = 0; i < _bench_iters; i++) { for (int i = 0; i < n; i++) { b_posdef_copy[i] = b_posdef[i]; for(int j = 0; j < n; j++) { A_posdef_full[i][j] = index_symm_matrix(A_posdef, i, j); } } begin = _RDTSC(); status = full_posdef_positive_solver_fast(A_posdef_full, x_returned, b_posdef_copy, n); cBYE(status); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_symm_matrix_vector(A_posdef, x_returned, n, b_returned); checker_success = symm_positive_solver_check(A_posdef, x_returned, b_posdef, n, 0.0); _print_result(x_expected, x_returned, b_posdef, b_returned, "FULL_POSDEF_FAST", n, avg_cycles, checker_success); total = 0; for (int i = 0; i < _bench_iters; i++) { begin = _RDTSC(); status = positive_solver(A, x_returned, b, n); cBYE(status); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_matrix_vector(A, x_returned, n, b_returned); checker_success = full_positive_solver_check(A, x_returned, b, n, 0.0); _print_result(x_expected, x_returned, b, b_returned, "FULL", n, avg_cycles, checker_success); BYE: free_matrix(A_posdef_copy, n); free_matrix(A_posdef_full, n); free_if_non_null(b_posdef_copy); free_if_non_null(b_returned); free_if_non_null(x_returned); return status; } static int _run_lapack_tests( double **A, double *x_expected, double *b, double **A_posdef, double *b_posdef, int n ) { int status = 0; lapack_int N = n; lapack_int NRHS = 1; lapack_int LDA = N; lapack_int LDB = N; double *A_unrolled = NULL; double *A_posdef_unrolled = NULL; double *b_copy = NULL; double *b_posdef_copy = NULL; double *b_returned = NULL; lapack_int *ipiv = NULL; uint64_t begin, total; double avg_cycles; bool checker_success; A_unrolled = malloc(n * n * sizeof(double)); return_if_malloc_failed(A_unrolled); A_posdef_unrolled = malloc(n * n * sizeof(double)); return_if_malloc_failed(A_posdef_unrolled); b_copy = malloc(n * sizeof(double)); return_if_malloc_failed(b_copy); b_posdef_copy = malloc(n * sizeof(double)); return_if_malloc_failed(b_posdef_copy); b_returned = malloc(n * sizeof(double)); return_if_malloc_failed(b_returned); ipiv = malloc(n * sizeof(lapack_int)); return_if_malloc_failed(ipiv); total = 0; for (int i = 0; i < _bench_iters; i++) { for (int i = 0; i < n; i++) { b_copy[i] = b[i]; for (int j = 0; j < n; j++) { A_unrolled[n * i + j] = A[i][j]; } } begin = _RDTSC(); LAPACKE_dgesv(LAPACK_COL_MAJOR, N, NRHS, A_unrolled, LDA, ipiv, b_copy, LDB); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_matrix_vector(A, b_copy, n, b_returned); checker_success = full_positive_solver_check(A, b_copy, b, n, 0.0); _print_result(x_expected, b_copy, b, b_returned, "LAPACK_FULL", n, avg_cycles, checker_success); total = 0; for (int i = 0; i < _bench_iters; i++) { for (int i = 0; i < n; i++) { b_posdef_copy[i] = b_posdef[i]; for (int j = 0; j <= i; j++) { A_posdef_unrolled[n * i + j] = A_posdef[j][i - j]; } for (int j = i + 1; j < n; j++) { A_posdef_unrolled[n * i + j] = 0; } } begin = _RDTSC(); LAPACKE_dposv(LAPACK_COL_MAJOR, 'U', N, NRHS, A_posdef_unrolled, LDA, b_posdef_copy, LDB); if (i >= _bench_drop_n) { total += _RDTSC() - begin; } } avg_cycles = (double)total / (_bench_iters - _bench_drop_n); multiply_symm_matrix_vector(A_posdef, b_posdef_copy, n, b_returned); checker_success = symm_positive_solver_check(A_posdef, b_posdef_copy, b_posdef, n, 0.0); _print_result(x_expected, b_posdef_copy, b_posdef, b_returned, "LAPACK_POSDEF", n, avg_cycles, checker_success); BYE: free_if_non_null(A_unrolled); free_if_non_null(A_posdef_unrolled); free_if_non_null(b_copy); free_if_non_null(b_posdef_copy); free_if_non_null(b_returned); free_if_non_null(ipiv); return status; } int main( int argc, char **argv ) { int status = 0; int n = 0; // dimension of matrices double **A = NULL; // randomly generated n * n matrix double **A_posdef = NULL; // randomly generated positive definite matrix (right now just A transpose * A) double *x_expected = NULL; // randomly generated solution double *b_posdef = NULL; // A_posdef * x_expected double *b_full = NULL; // A * x_expected srand48(_RDTSC()); bool print_usage = false, bench = false; switch ( argc ) { case 3 : if (strcmp("-vb", argv[2]) == 0 || strcmp("-bv", argv[2]) == 0) { _verbose = true; bench = true; } else if (strcmp("-v", argv[2]) == 0) { _verbose = true; } else if (strcmp("-b", argv[2]) == 0) { bench = true; } else { print_usage = true; } // fall through case 2 : n = atoi(argv[1]); break; default : print_usage = true; break; } if (print_usage || n <= 0) { printf("Usage: ./test_driver <n> [-v]\n"); printf("where n is a positive integer and -v provides verbose output.\n"); go_BYE(-1); } if (bench == true) { _bench_iters = 15; _bench_drop_n = 3; } status = alloc_matrix(&A, n); cBYE(status); status = alloc_symm_matrix(&A_posdef, n); cBYE(status); for ( int i = 0; i < n; i++ ) { for ( int j = 0; j < n; j++ ) { A[i][j] = (drand48() - 0.5) * 100; } } transpose_and_multiply(A, A_posdef, n); b_posdef = (double *) malloc(n * sizeof(double)); return_if_malloc_failed(b_posdef); b_full = (double *) malloc(n * sizeof(double)); return_if_malloc_failed(b_full); x_expected = (double *) malloc(n * sizeof(double)); return_if_malloc_failed(x_expected); // Initialize x and b for ( int i = 0; i < n; i++ ) { x_expected[i] = (lrand48() % 16) - 16/2; } multiply_symm_matrix_vector(A_posdef, x_expected, n, b_posdef); multiply_matrix_vector(A, x_expected, n, b_full); if (_verbose) { _print_input(A_posdef, x_expected, b_posdef, n); } _run_our_tests(A, x_expected, b_full, A_posdef, b_posdef, n); _run_lapack_tests(A, x_expected, b_full, A_posdef, b_posdef, n); BYE: free_matrix(A, n); free_matrix(A_posdef, n); free_if_non_null(x_expected); free_if_non_null(b_posdef); free_if_non_null(b_full); return status; }
{ "alphanum_fraction": 0.6280193237, "avg_line_length": 30.6859296482, "ext": "c", "hexsha": "94f54ea46b57579d2dbaf5176b12b0f6aee0e2d2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "subramon/qlu", "max_forks_repo_path": "OPERATORS/AX_EQUALS_B/test/test_driver.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "subramon/qlu", "max_issues_repo_path": "OPERATORS/AX_EQUALS_B/test/test_driver.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "subramon/qlu", "max_stars_repo_path": "OPERATORS/AX_EQUALS_B/test/test_driver.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3837, "size": 12213 }
#pragma once #include <bitset> #include <type_traits> #include <cuda/define_specifiers.hpp> #include <gsl-lite/gsl-lite.hpp> namespace thrustshift { namespace detail { // to be compiler independent std::bitset is used here template <typename I> int count_leading_zeros_cpu(I i) { std::bitset<sizeof(I) * 8> bs(i); static_assert(bs.size() > 0); int lz = 0; for (int bi = gsl_lite::narrow<int>(sizeof(I) * 8) - 1; bi >= 0; --bi) { if (bs[bi]) { break; } ++lz; } return lz; } template <typename I> int count_leading_zeros_gpu(I i); template<> CUDA_FD int count_leading_zeros_gpu<int>(int i) { return __clz(i); } template<> CUDA_FD int count_leading_zeros_gpu<long long int>(long long int i) { return __clzll(i); } } // namespace detail template <typename I> CUDA_FHD int count_leading_zeros(I i) { #ifdef __CUDA_ARCH__ return detail::count_leading_zeros_gpu(i); #else return detail::count_leading_zeros_cpu(i); #endif } } // namespace thrustshift
{ "alphanum_fraction": 0.7055214724, "avg_line_length": 17.7818181818, "ext": "h", "hexsha": "51c6ce93846d2fa40c7d7f0c0ab169da5a6ef797", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_path": "include/thrustshift/bit.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/bit.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/bit.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 274, "size": 978 }
#pragma once #include <stdint.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include "nn_math.h" #include "nn_utils.h" typedef struct { size_t size; uintmax_t *layers; gsl_vector **biases; gsl_matrix **weights; } nn_network; nn_network * nn_network_create(const size_t n, const uintmax_t *layers); void nn_network_destroy(nn_network *network); void nn_network_set_biases(nn_network *network, gsl_vector **biases); void nn_network_get_biases(nn_network *network, gsl_vector **biases); void nn_network_set_weights(nn_network *network, gsl_matrix **weights); void nn_network_get_weights(nn_network *network, gsl_matrix **weights); gsl_vector * nn_network_ff(nn_network *network, gsl_vector *x);
{ "alphanum_fraction": 0.7739361702, "avg_line_length": 28.9230769231, "ext": "h", "hexsha": "7f3507d789d320a005f86d619d70d142663c1ce3", "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": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mygulamali/neural-net", "max_forks_repo_path": "include/nn_network.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "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": "mygulamali/neural-net", "max_issues_repo_path": "include/nn_network.h", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "250995db0e9d555cc51dfda2f0ee6720c15fc4c4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mygulamali/neural-net", "max_stars_repo_path": "include/nn_network.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 188, "size": 752 }
/* ** t-tests ** ** G.Lohmann, Jan 2017 */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define TINY 1.0e-10 #define ABS(x) ((x) > 0 ? (x) : -(x)) #define SQR(x) ((x)*(x)) /* ** convert t to z values */ double t2z(double t,double df) { double p=0,z=0; double a,b,x; extern double gsl_sf_beta_inc(double,double,double); /* t to p */ x = df/(df+(t*t)); if (x <= 0 || x > 1) return 0; a = 0.5*df; b = 0.5; p = 0.5 * gsl_sf_beta_inc(a,b,x); /* p to z */ z = gsl_cdf_ugaussian_Qinv(p); return z; } void avevar(double *data,int n,double *a,double *v) { int j; double ave,var,nx,s,u; nx = (double)n; ave = 0; for (j=0; j<n; j++) ave += data[j]; ave /= nx; var = u = 0; for (j=0; j<n; j++) { s = data[j]-ave; u += s; var += s*s; } var=(var-u*u/nx)/(nx-1); *v = var; *a = ave; } /* welch test, unequal variance */ double welchtest(double *data1,double *data2,int n1,int n2) { double tiny=TINY; double ave1,ave2,var1,var2; double z=0,t=0,df=0; double nx1 = (double)n1; double nx2 = (double)n2; avevar(data1,n1,&ave1,&var1); if (var1 < tiny) return 0; avevar(data2,n2,&ave2,&var2); if (var2 < tiny) return 0; t = (ave1 - ave2)/sqrt(var1/nx1 + var2/nx2); df = SQR(var1/nx1+var2/nx2)/(SQR(var1/nx1)/(nx1-1)+SQR(var2/nx2)/(nx2-1)); z = t2z((double) t,(double) df); if (t < 0) z = -z; return z; } /* paired twosample test */ double paired_ttest(double *data1,double *data2,int n) { int j; double ave,var,tiny=TINY; for (j=0; j<n; j++) { data1[j] -= data2[j]; } avevar(data1,n,&ave,&var); if (var < tiny) return 0; double nx = (double)n; double df = nx-1.0; double t = sqrt(nx) * ave/sqrt(var); double z = t2z(t,df); if (t < 0) z = -z; return z; } /* paired twosample test */ double xtest2(double *data1,double *data2,int n) { int j; double nx,ave1,ave2,var1,var2,sd,u,df,cov; double tiny=TINY; double t=0,z=0; avevar(data1,n,&ave1,&var1); avevar(data2,n,&ave2,&var2); if (var1 < tiny || var2 < tiny) return 0; nx = (double)n; df = nx-1; cov = 0; for (j=0; j<n; j++) cov += (data1[j]-ave1)*(data2[j]-ave2); cov /= df; t = 0; u = (var1+var2-2.0*cov); if (u < tiny) return 0; sd = sqrt(u/nx); if (sd < tiny) return 0; t = (double)(ave1-ave2)/sd; z = t2z(t,df); if (t < 0) z = -z; return z; } /* twosample t-test, pooled variance */ double ttest2(double *data1,double *data2,int n1,int n2) { int j; double nx1,nx2,ave1,ave2,sd,s1,s2,df; double tiny=TINY; double t=0,z=0; nx1 = (double)n1; nx2 = (double)n2; ave1 = ave2 = 0; for (j=0; j<n1; j++) ave1 += data1[j]; for (j=0; j<n2; j++) ave2 += data2[j]; if (ABS(ave1) < tiny) return 0; if (ABS(ave2) < tiny) return 0; ave1 /= nx1; ave2 /= nx2; s1 = 0; for (j=0; j<n1; j++) s1 += SQR(data1[j]-ave1); s2 = 0; for (j=0; j<n2; j++) s2 += SQR(data2[j]-ave2); df = nx1 + nx2 - 2.0; sd = sqrt((1.0/nx1 + 1.0/nx2) * (s1+s2)/df); if (sd < tiny) return 0; t = (double)(ave1-ave2)/sd; z = t2z(t,df); if (t < 0) z = -z; return z; } /* onesample t-test */ double ttest1(double *data,int n) { double ave=0,var=0,tiny=TINY; avevar(data,n,&ave,&var); if (var < tiny) return 0; double nx = (double)n; double df = nx-1.0; double t = sqrt(nx) * ave/sqrt(var); double z = t2z(t,df); if (t < 0) z = -z; return z; }
{ "alphanum_fraction": 0.5579893288, "avg_line_length": 18.546875, "ext": "c", "hexsha": "62d9c72ad6adf058406b1df82171833a3d03f0a3", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/utils/ttest.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/utils/ttest.c", "max_line_length": 76, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/utils/ttest.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 1481, "size": 3561 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "tests.h" void test_swap (void) { const double flteps = 1e-4, dbleps = 1e-6; { int N = 1; float X[] = { 0.539f }; int incX = 1; float Y[] = { -0.262f }; int incY = -1; float expected1[] = { -0.262f }; float expected2[] = { 0.539f }; cblas_sswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], flteps, "sswap(case 88)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], flteps, "sswap(case 89)"); } }; }; { int N = 1; double X[] = { 0.906 }; int incX = 1; double Y[] = { 0.373 }; int incY = -1; double expected1[] = { 0.373 }; double expected2[] = { 0.906 }; cblas_dswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], dbleps, "dswap(case 90)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], dbleps, "dswap(case 91)"); } }; }; { int N = 1; float X[] = { -0.316f, -0.529f }; int incX = 1; float Y[] = { -0.313f, 0.363f }; int incY = -1; float expected1[] = { -0.313f, 0.363f }; float expected2[] = { -0.316f, -0.529f }; cblas_cswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], flteps, "cswap(case 92) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], flteps, "cswap(case 92) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], flteps, "cswap(case 93) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], flteps, "cswap(case 93) imag"); }; }; }; { int N = 1; double X[] = { 0.512, -0.89 }; int incX = 1; double Y[] = { -0.225, -0.511 }; int incY = -1; double expected1[] = { -0.225, -0.511 }; double expected2[] = { 0.512, -0.89 }; cblas_zswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], dbleps, "zswap(case 94) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], dbleps, "zswap(case 94) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], dbleps, "zswap(case 95) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], dbleps, "zswap(case 95) imag"); }; }; }; { int N = 1; float X[] = { 0.336f }; int incX = -1; float Y[] = { -0.431f }; int incY = 1; float expected1[] = { -0.431f }; float expected2[] = { 0.336f }; cblas_sswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], flteps, "sswap(case 96)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], flteps, "sswap(case 97)"); } }; }; { int N = 1; double X[] = { 0.764 }; int incX = -1; double Y[] = { -0.293 }; int incY = 1; double expected1[] = { -0.293 }; double expected2[] = { 0.764 }; cblas_dswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], dbleps, "dswap(case 98)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], dbleps, "dswap(case 99)"); } }; }; { int N = 1; float X[] = { -0.239f, 0.361f }; int incX = -1; float Y[] = { 0.149f, 0.347f }; int incY = 1; float expected1[] = { 0.149f, 0.347f }; float expected2[] = { -0.239f, 0.361f }; cblas_cswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], flteps, "cswap(case 100) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], flteps, "cswap(case 100) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], flteps, "cswap(case 101) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], flteps, "cswap(case 101) imag"); }; }; }; { int N = 1; double X[] = { -0.171, -0.936 }; int incX = -1; double Y[] = { 0.495, -0.835 }; int incY = 1; double expected1[] = { 0.495, -0.835 }; double expected2[] = { -0.171, -0.936 }; cblas_zswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], dbleps, "zswap(case 102) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], dbleps, "zswap(case 102) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], dbleps, "zswap(case 103) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], dbleps, "zswap(case 103) imag"); }; }; }; { int N = 1; float X[] = { -0.405f }; int incX = -1; float Y[] = { -0.213f }; int incY = -1; float expected1[] = { -0.213f }; float expected2[] = { -0.405f }; cblas_sswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], flteps, "sswap(case 104)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], flteps, "sswap(case 105)"); } }; }; { int N = 1; double X[] = { -0.761 }; int incX = -1; double Y[] = { -0.585 }; int incY = -1; double expected1[] = { -0.585 }; double expected2[] = { -0.761 }; cblas_dswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[i], expected1[i], dbleps, "dswap(case 106)"); } }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[i], expected2[i], dbleps, "dswap(case 107)"); } }; }; { int N = 1; float X[] = { 0.853f, 0.146f }; int incX = -1; float Y[] = { 0.009f, -0.178f }; int incY = -1; float expected1[] = { 0.009f, -0.178f }; float expected2[] = { 0.853f, 0.146f }; cblas_cswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], flteps, "cswap(case 108) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], flteps, "cswap(case 108) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], flteps, "cswap(case 109) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], flteps, "cswap(case 109) imag"); }; }; }; { int N = 1; double X[] = { -0.228, 0.386 }; int incX = -1; double Y[] = { 0.988, -0.084 }; int incY = -1; double expected1[] = { 0.988, -0.084 }; double expected2[] = { -0.228, 0.386 }; cblas_zswap(N, X, incX, Y, incY); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(X[2*i], expected1[2*i], dbleps, "zswap(case 110) real"); gsl_test_rel(X[2*i+1], expected1[2*i+1], dbleps, "zswap(case 110) imag"); }; }; { int i; for (i = 0; i < 1; i++) { gsl_test_rel(Y[2*i], expected2[2*i], dbleps, "zswap(case 111) real"); gsl_test_rel(Y[2*i+1], expected2[2*i+1], dbleps, "zswap(case 111) imag"); }; }; }; }
{ "alphanum_fraction": 0.4741272251, "avg_line_length": 23.2275641026, "ext": "c", "hexsha": "accf822acac4e2f18bbae497eb6f1b7f98badb90", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_swap.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_swap.c", "max_line_length": 80, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_swap.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 2919, "size": 7247 }
// // Created by robin on 2018/9/1. // Copyright (c) 2018 Robin. All rights reserved. // #pragma once #include <ostream> #include <algorithm> #include <vector> #include <gsl/gsl> #include "arithmetic.h" namespace satz::gf2::v2 { /// @brief Polynomial over GF(2). class Polynomial { public: using int_type = int; using container_type = std::vector<int_type>; Polynomial () = default; template <typename T> Polynomial (std::initializer_list<T> degrees) : Polynomial(degrees.begin(), degrees.end()) { } template <typename InputIt> Polynomial (InputIt first, InputIt last) : deg_(first, last) { Expects(std::all_of(deg_.begin(), deg_.end(), [] (const auto& x) { return x >= 0; })); if (!std::is_sorted(deg_.begin(), deg_.end())) { std::sort(deg_.begin(), deg_.end()); } deg_.erase(std::unique(deg_.begin(), deg_.end()), deg_.end()); } static Polynomial from_ulong (unsigned long); static Polynomial from_bytes (gsl::span<uint8_t>); static Polynomial from_bytes (gsl::span<uint8_t>, int_type degree); static Polynomial make_random (int_type degree); static Polynomial make_irreducible (int_type degree); /** * @brief Return a bit representation of the coefficients. * * When the degree of this polynomial is -1, return an empty vector. * In other cases, return a bit representation with just enough bytes, * i.e., the most significant byte should be non-zero. */ [[nodiscard]] std::vector<uint8_t> to_bytes () const; explicit operator bool () const; friend bool operator == (const Polynomial& lhs, const Polynomial& rhs); friend bool operator != (const Polynomial& lhs, const Polynomial& rhs); friend bool operator < (const Polynomial& lhs, const Polynomial& rhs); friend bool operator > (const Polynomial& lhs, const Polynomial& rhs); friend bool operator <= (const Polynomial& lhs, const Polynomial& rhs); friend bool operator >= (const Polynomial& lhs, const Polynomial& rhs); Polynomial& operator ^= (const Polynomial& rhs); Polynomial& operator |= (const Polynomial& rhs); Polynomial& operator &= (const Polynomial& rhs); Polynomial& operator += (const Polynomial& rhs); Polynomial& operator -= (const Polynomial& rhs); Polynomial& operator *= (const Polynomial& rhs); Polynomial& operator %= (const Polynomial& rhs); Polynomial& operator <<= (int_type n); Polynomial& operator >>= (int_type n); friend Polynomial operator ^ (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator | (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator & (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator + (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator - (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator * (const Polynomial& lhs, const Polynomial& rhs); friend Polynomial operator % (const Polynomial& lhs, const Polynomial& rhs); Polynomial operator << (int_type n) const; Polynomial operator >> (int_type n) const; friend std::ostream& operator << (std::ostream& os, const Polynomial& obj); /** * @brief Indicates whether it is a zero polynomial. */ [[nodiscard]] bool empty () const; /** * @brief Returns the degree of the polynomial. */ [[nodiscard]] int_type degree () const; /** * @brief Returns the number of non-zero coefficients. */ [[nodiscard]] int_type nnz () const; /** * @brief Given an interger n, return whether this polynomial contains an * x^n term. * @param n */ [[nodiscard]] bool contains (int_type n) const; protected: explicit Polynomial (container_type&& v); private: container_type deg_; // `deg_` for degrees }; } namespace satz::gf2 { using namespace v2; } namespace satz { template <> const gf2::v2::Polynomial zero<gf2::v2::Polynomial> = gf2::v2::Polynomial{}; template <> const gf2::v2::Polynomial one<gf2::v2::Polynomial> = gf2::v2::Polynomial{0}; template <> const gf2::v2::Polynomial X<gf2::v2::Polynomial> = gf2::v2::Polynomial{1}; }
{ "alphanum_fraction": 0.6818950931, "avg_line_length": 31.3409090909, "ext": "h", "hexsha": "feffca0e53e62b13af13400548b118b9d0fb271b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-26T11:41:15.000Z", "max_forks_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "lie-yan/rabin-fingerprint", "max_forks_repo_path": "src/polynomial.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "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": "lie-yan/rabin-fingerprint", "max_issues_repo_path": "src/polynomial.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "834d2d52e4c5967fe4b7aa6026742cc82c6bc031", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "lie-yan/rabin-fingerprint", "max_stars_repo_path": "src/polynomial.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1014, "size": 4137 }
#ifndef INCLUDED_TELEPATH_BLAS_2_GEMV_H #define INCLUDED_TELEPATH_BLAS_2_GEMV_H #include <cblas.h> #include <complex> namespace telepath{ template< typename T > void gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, T alpha, const T* a, std::size_t lda, const T* x, std::size_t incx, T beta, T* y, std::size_t incy ); template< typename T > void gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, const T* alpha, const T* a, std::size_t lda, const T* x, std::size_t incx, const T* beta, T* y, std::size_t incy ); template<> void gemv<float>( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, float alpha, const float* a, std::size_t lda, const float* x, std::size_t incx, float beta, float* y, std::size_t incy ){ return cblas_sgemv( order, trans, m, n, alpha, a, lda, x, incx, beta, y, incy ); } template<> void gemv<double>( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, double alpha, const double* a, std::size_t lda, const double* x, std::size_t incx, double beta, double* y, std::size_t incy ){ return cblas_dgemv( order, trans, m, n, alpha, a, lda, x, incx, beta, y, incy ); } template<> void gemv<std::complex<float> >( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, const std::complex<float>* alpha, const std::complex<float>* a, std::size_t lda, const std::complex<float>* x, std::size_t incx, const std::complex<float>* beta, std::complex<float>* y, std::size_t incy ){ return cblas_cgemv( order, trans, m, n, (float*) alpha, (float*) a, lda, (float*) x, incx, (float*) beta, (float*) y, incy ); } template<> void gemv<std::complex<double> >( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, std::size_t m, std::size_t n, const std::complex<double>* alpha, const std::complex<double>* a, std::size_t lda, const std::complex<double>* x, std::size_t incx, const std::complex<double>* beta, std::complex<double>* y, std::size_t incy ){ return cblas_zgemv( order, trans, m, n, (double*) alpha, (double*) a, lda, (double*) x, incx, (double*) beta, (double*) y, incy ); } } //namespace telepath #endif
{ "alphanum_fraction": 0.6137846656, "avg_line_length": 40.1967213115, "ext": "h", "hexsha": "a8f04b0f1e2b92c09325d6840d994b95bd27f166", "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": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tbepler/telepath", "max_forks_repo_path": "include/telepath/blas/level2/gemv.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "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": "tbepler/telepath", "max_issues_repo_path": "include/telepath/blas/level2/gemv.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tbepler/telepath", "max_stars_repo_path": "include/telepath/blas/level2/gemv.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 749, "size": 2452 }
#include "ccv.h" #include "ccv_internal.h" #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif #ifdef USE_DISPATCH #include <dispatch/dispatch.h> #endif const ccv_icf_param_t ccv_icf_default_params = { .min_neighbors = 2, .threshold = 0, .step_through = 2, .flags = 0, .interval = 8, }; // this uses a look up table for cubic root computation because rgb to luv only requires data within range of 0~1 static inline float fast_cube_root(const float d) { static const float cube_root[2048] = { 0.000000e+00, 7.875788e-02, 9.922871e-02, 1.135885e-01, 1.250203e-01, 1.346741e-01, 1.431126e-01, 1.506584e-01, 1.575158e-01, 1.638230e-01, 1.696787e-01, 1.751560e-01, 1.803105e-01, 1.851861e-01, 1.898177e-01, 1.942336e-01, 1.984574e-01, 2.025087e-01, 2.064040e-01, 2.101577e-01, 2.137818e-01, 2.172870e-01, 2.206827e-01, 2.239769e-01, 2.271770e-01, 2.302894e-01, 2.333199e-01, 2.362736e-01, 2.391553e-01, 2.419692e-01, 2.447191e-01, 2.474085e-01, 2.500407e-01, 2.526186e-01, 2.551450e-01, 2.576222e-01, 2.600528e-01, 2.624387e-01, 2.647821e-01, 2.670846e-01, 2.693482e-01, 2.715743e-01, 2.737645e-01, 2.759202e-01, 2.780428e-01, 2.801334e-01, 2.821933e-01, 2.842235e-01, 2.862251e-01, 2.881992e-01, 2.901465e-01, 2.920681e-01, 2.939647e-01, 2.958371e-01, 2.976862e-01, 2.995125e-01, 3.013168e-01, 3.030998e-01, 3.048621e-01, 3.066041e-01, 3.083267e-01, 3.100302e-01, 3.117152e-01, 3.133821e-01, 3.150315e-01, 3.166639e-01, 3.182795e-01, 3.198789e-01, 3.214625e-01, 3.230307e-01, 3.245837e-01, 3.261220e-01, 3.276460e-01, 3.291559e-01, 3.306521e-01, 3.321348e-01, 3.336045e-01, 3.350613e-01, 3.365056e-01, 3.379375e-01, 3.393574e-01, 3.407656e-01, 3.421622e-01, 3.435475e-01, 3.449216e-01, 3.462850e-01, 3.476377e-01, 3.489799e-01, 3.503119e-01, 3.516339e-01, 3.529460e-01, 3.542483e-01, 3.555412e-01, 3.568248e-01, 3.580992e-01, 3.593646e-01, 3.606211e-01, 3.618689e-01, 3.631082e-01, 3.643391e-01, 3.655617e-01, 3.667762e-01, 3.679827e-01, 3.691814e-01, 3.703723e-01, 3.715556e-01, 3.727314e-01, 3.738999e-01, 3.750610e-01, 3.762151e-01, 3.773621e-01, 3.785022e-01, 3.796354e-01, 3.807619e-01, 3.818818e-01, 3.829952e-01, 3.841021e-01, 3.852027e-01, 3.862970e-01, 3.873852e-01, 3.884673e-01, 3.895434e-01, 3.906136e-01, 3.916779e-01, 3.927365e-01, 3.937894e-01, 3.948367e-01, 3.958785e-01, 3.969149e-01, 3.979458e-01, 3.989714e-01, 3.999918e-01, 4.010071e-01, 4.020171e-01, 4.030222e-01, 4.040223e-01, 4.050174e-01, 4.060076e-01, 4.069931e-01, 4.079738e-01, 4.089499e-01, 4.099212e-01, 4.108880e-01, 4.118503e-01, 4.128081e-01, 4.137615e-01, 4.147105e-01, 4.156551e-01, 4.165955e-01, 4.175317e-01, 4.184637e-01, 4.193916e-01, 4.203153e-01, 4.212351e-01, 4.221508e-01, 4.230626e-01, 4.239704e-01, 4.248744e-01, 4.257746e-01, 4.266710e-01, 4.275636e-01, 4.284525e-01, 4.293377e-01, 4.302193e-01, 4.310973e-01, 4.319718e-01, 4.328427e-01, 4.337101e-01, 4.345741e-01, 4.354346e-01, 4.362918e-01, 4.371456e-01, 4.379961e-01, 4.388433e-01, 4.396872e-01, 4.405279e-01, 4.413654e-01, 4.421997e-01, 4.430309e-01, 4.438590e-01, 4.446840e-01, 4.455060e-01, 4.463249e-01, 4.471409e-01, 4.479539e-01, 4.487639e-01, 4.495711e-01, 4.503753e-01, 4.511767e-01, 4.519752e-01, 4.527710e-01, 4.535639e-01, 4.543541e-01, 4.551415e-01, 4.559263e-01, 4.567083e-01, 4.574877e-01, 4.582644e-01, 4.590385e-01, 4.598100e-01, 4.605789e-01, 4.613453e-01, 4.621091e-01, 4.628704e-01, 4.636292e-01, 4.643855e-01, 4.651394e-01, 4.658908e-01, 4.666398e-01, 4.673865e-01, 4.681307e-01, 4.688726e-01, 4.696122e-01, 4.703494e-01, 4.710843e-01, 4.718169e-01, 4.725473e-01, 4.732754e-01, 4.740013e-01, 4.747250e-01, 4.754464e-01, 4.761657e-01, 4.768828e-01, 4.775978e-01, 4.783106e-01, 4.790214e-01, 4.797300e-01, 4.804365e-01, 4.811410e-01, 4.818434e-01, 4.825437e-01, 4.832420e-01, 4.839384e-01, 4.846327e-01, 4.853250e-01, 4.860154e-01, 4.867038e-01, 4.873902e-01, 4.880748e-01, 4.887574e-01, 4.894381e-01, 4.901170e-01, 4.907939e-01, 4.914690e-01, 4.921423e-01, 4.928137e-01, 4.934832e-01, 4.941510e-01, 4.948170e-01, 4.954812e-01, 4.961436e-01, 4.968042e-01, 4.974631e-01, 4.981203e-01, 4.987757e-01, 4.994294e-01, 5.000814e-01, 5.007317e-01, 5.013803e-01, 5.020273e-01, 5.026726e-01, 5.033162e-01, 5.039582e-01, 5.045985e-01, 5.052372e-01, 5.058743e-01, 5.065099e-01, 5.071438e-01, 5.077761e-01, 5.084069e-01, 5.090362e-01, 5.096638e-01, 5.102900e-01, 5.109145e-01, 5.115376e-01, 5.121592e-01, 5.127792e-01, 5.133978e-01, 5.140148e-01, 5.146304e-01, 5.152445e-01, 5.158572e-01, 5.164684e-01, 5.170782e-01, 5.176865e-01, 5.182934e-01, 5.188988e-01, 5.195029e-01, 5.201056e-01, 5.207069e-01, 5.213068e-01, 5.219053e-01, 5.225024e-01, 5.230982e-01, 5.236927e-01, 5.242857e-01, 5.248775e-01, 5.254679e-01, 5.260570e-01, 5.266448e-01, 5.272312e-01, 5.278164e-01, 5.284002e-01, 5.289828e-01, 5.295641e-01, 5.301442e-01, 5.307229e-01, 5.313004e-01, 5.318767e-01, 5.324517e-01, 5.330254e-01, 5.335979e-01, 5.341693e-01, 5.347394e-01, 5.353082e-01, 5.358759e-01, 5.364423e-01, 5.370076e-01, 5.375717e-01, 5.381346e-01, 5.386963e-01, 5.392569e-01, 5.398163e-01, 5.403746e-01, 5.409316e-01, 5.414876e-01, 5.420424e-01, 5.425960e-01, 5.431486e-01, 5.437000e-01, 5.442503e-01, 5.447995e-01, 5.453476e-01, 5.458946e-01, 5.464405e-01, 5.469853e-01, 5.475290e-01, 5.480717e-01, 5.486133e-01, 5.491537e-01, 5.496932e-01, 5.502316e-01, 5.507689e-01, 5.513052e-01, 5.518404e-01, 5.523747e-01, 5.529078e-01, 5.534400e-01, 5.539711e-01, 5.545012e-01, 5.550303e-01, 5.555584e-01, 5.560855e-01, 5.566117e-01, 5.571368e-01, 5.576609e-01, 5.581840e-01, 5.587062e-01, 5.592273e-01, 5.597475e-01, 5.602668e-01, 5.607851e-01, 5.613024e-01, 5.618188e-01, 5.623342e-01, 5.628487e-01, 5.633622e-01, 5.638748e-01, 5.643865e-01, 5.648973e-01, 5.654072e-01, 5.659161e-01, 5.664241e-01, 5.669311e-01, 5.674374e-01, 5.679426e-01, 5.684470e-01, 5.689505e-01, 5.694531e-01, 5.699549e-01, 5.704557e-01, 5.709556e-01, 5.714548e-01, 5.719529e-01, 5.724503e-01, 5.729468e-01, 5.734424e-01, 5.739372e-01, 5.744311e-01, 5.749242e-01, 5.754164e-01, 5.759078e-01, 5.763984e-01, 5.768881e-01, 5.773770e-01, 5.778650e-01, 5.783523e-01, 5.788387e-01, 5.793243e-01, 5.798091e-01, 5.802931e-01, 5.807762e-01, 5.812586e-01, 5.817402e-01, 5.822210e-01, 5.827010e-01, 5.831801e-01, 5.836585e-01, 5.841362e-01, 5.846130e-01, 5.850891e-01, 5.855644e-01, 5.860389e-01, 5.865127e-01, 5.869856e-01, 5.874579e-01, 5.879294e-01, 5.884001e-01, 5.888700e-01, 5.893393e-01, 5.898077e-01, 5.902755e-01, 5.907425e-01, 5.912087e-01, 5.916742e-01, 5.921390e-01, 5.926031e-01, 5.930664e-01, 5.935290e-01, 5.939909e-01, 5.944521e-01, 5.949125e-01, 5.953723e-01, 5.958313e-01, 5.962896e-01, 5.967473e-01, 5.972042e-01, 5.976604e-01, 5.981160e-01, 5.985708e-01, 5.990250e-01, 5.994784e-01, 5.999312e-01, 6.003833e-01, 6.008347e-01, 6.012855e-01, 6.017355e-01, 6.021850e-01, 6.026337e-01, 6.030817e-01, 6.035291e-01, 6.039758e-01, 6.044219e-01, 6.048673e-01, 6.053120e-01, 6.057562e-01, 6.061996e-01, 6.066424e-01, 6.070846e-01, 6.075261e-01, 6.079670e-01, 6.084072e-01, 6.088468e-01, 6.092858e-01, 6.097241e-01, 6.101618e-01, 6.105989e-01, 6.110353e-01, 6.114712e-01, 6.119064e-01, 6.123410e-01, 6.127750e-01, 6.132084e-01, 6.136411e-01, 6.140732e-01, 6.145048e-01, 6.149357e-01, 6.153660e-01, 6.157957e-01, 6.162249e-01, 6.166534e-01, 6.170813e-01, 6.175086e-01, 6.179354e-01, 6.183616e-01, 6.187872e-01, 6.192122e-01, 6.196365e-01, 6.200604e-01, 6.204836e-01, 6.209063e-01, 6.213284e-01, 6.217499e-01, 6.221709e-01, 6.225913e-01, 6.230111e-01, 6.234304e-01, 6.238490e-01, 6.242672e-01, 6.246848e-01, 6.251017e-01, 6.255182e-01, 6.259341e-01, 6.263494e-01, 6.267643e-01, 6.271785e-01, 6.275922e-01, 6.280054e-01, 6.284180e-01, 6.288301e-01, 6.292416e-01, 6.296526e-01, 6.300631e-01, 6.304730e-01, 6.308824e-01, 6.312913e-01, 6.316996e-01, 6.321074e-01, 6.325147e-01, 6.329215e-01, 6.333277e-01, 6.337335e-01, 6.341386e-01, 6.345433e-01, 6.349475e-01, 6.353511e-01, 6.357543e-01, 6.361569e-01, 6.365590e-01, 6.369606e-01, 6.373618e-01, 6.377624e-01, 6.381625e-01, 6.385621e-01, 6.389612e-01, 6.393598e-01, 6.397579e-01, 6.401555e-01, 6.405526e-01, 6.409492e-01, 6.413454e-01, 6.417410e-01, 6.421362e-01, 6.425309e-01, 6.429250e-01, 6.433188e-01, 6.437120e-01, 6.441047e-01, 6.444970e-01, 6.448888e-01, 6.452801e-01, 6.456710e-01, 6.460613e-01, 6.464512e-01, 6.468406e-01, 6.472296e-01, 6.476181e-01, 6.480061e-01, 6.483937e-01, 6.487808e-01, 6.491674e-01, 6.495536e-01, 6.499393e-01, 6.503246e-01, 6.507094e-01, 6.510937e-01, 6.514776e-01, 6.518611e-01, 6.522441e-01, 6.526266e-01, 6.530087e-01, 6.533904e-01, 6.537716e-01, 6.541524e-01, 6.545327e-01, 6.549126e-01, 6.552920e-01, 6.556710e-01, 6.560495e-01, 6.564277e-01, 6.568054e-01, 6.571826e-01, 6.575595e-01, 6.579359e-01, 6.583118e-01, 6.586874e-01, 6.590625e-01, 6.594372e-01, 6.598114e-01, 6.601852e-01, 6.605586e-01, 6.609316e-01, 6.613042e-01, 6.616763e-01, 6.620481e-01, 6.624194e-01, 6.627903e-01, 6.631607e-01, 6.635308e-01, 6.639005e-01, 6.642697e-01, 6.646385e-01, 6.650070e-01, 6.653750e-01, 6.657426e-01, 6.661098e-01, 6.664766e-01, 6.668430e-01, 6.672090e-01, 6.675746e-01, 6.679398e-01, 6.683046e-01, 6.686690e-01, 6.690330e-01, 6.693966e-01, 6.697598e-01, 6.701226e-01, 6.704850e-01, 6.708471e-01, 6.712087e-01, 6.715700e-01, 6.719308e-01, 6.722913e-01, 6.726514e-01, 6.730111e-01, 6.733705e-01, 6.737294e-01, 6.740879e-01, 6.744461e-01, 6.748039e-01, 6.751614e-01, 6.755184e-01, 6.758750e-01, 6.762313e-01, 6.765872e-01, 6.769428e-01, 6.772979e-01, 6.776527e-01, 6.780071e-01, 6.783612e-01, 6.787149e-01, 6.790682e-01, 6.794212e-01, 6.797737e-01, 6.801260e-01, 6.804778e-01, 6.808293e-01, 6.811804e-01, 6.815312e-01, 6.818815e-01, 6.822316e-01, 6.825813e-01, 6.829306e-01, 6.832796e-01, 6.836282e-01, 6.839765e-01, 6.843244e-01, 6.846719e-01, 6.850191e-01, 6.853660e-01, 6.857125e-01, 6.860586e-01, 6.864043e-01, 6.867498e-01, 6.870949e-01, 6.874397e-01, 6.877841e-01, 6.881282e-01, 6.884719e-01, 6.888152e-01, 6.891583e-01, 6.895010e-01, 6.898433e-01, 6.901854e-01, 6.905270e-01, 6.908684e-01, 6.912094e-01, 6.915500e-01, 6.918904e-01, 6.922303e-01, 6.925700e-01, 6.929094e-01, 6.932484e-01, 6.935870e-01, 6.939254e-01, 6.942633e-01, 6.946011e-01, 6.949384e-01, 6.952754e-01, 6.956121e-01, 6.959485e-01, 6.962845e-01, 6.966202e-01, 6.969556e-01, 6.972907e-01, 6.976255e-01, 6.979599e-01, 6.982940e-01, 6.986278e-01, 6.989613e-01, 6.992944e-01, 6.996273e-01, 6.999598e-01, 7.002920e-01, 7.006239e-01, 7.009555e-01, 7.012867e-01, 7.016177e-01, 7.019483e-01, 7.022786e-01, 7.026086e-01, 7.029384e-01, 7.032678e-01, 7.035969e-01, 7.039256e-01, 7.042542e-01, 7.045823e-01, 7.049102e-01, 7.052377e-01, 7.055650e-01, 7.058919e-01, 7.062186e-01, 7.065449e-01, 7.068710e-01, 7.071967e-01, 7.075222e-01, 7.078474e-01, 7.081722e-01, 7.084967e-01, 7.088210e-01, 7.091449e-01, 7.094686e-01, 7.097920e-01, 7.101150e-01, 7.104378e-01, 7.107603e-01, 7.110825e-01, 7.114044e-01, 7.117260e-01, 7.120473e-01, 7.123684e-01, 7.126891e-01, 7.130095e-01, 7.133297e-01, 7.136496e-01, 7.139692e-01, 7.142885e-01, 7.146075e-01, 7.149262e-01, 7.152447e-01, 7.155629e-01, 7.158808e-01, 7.161984e-01, 7.165157e-01, 7.168328e-01, 7.171495e-01, 7.174660e-01, 7.177821e-01, 7.180981e-01, 7.184138e-01, 7.187291e-01, 7.190442e-01, 7.193590e-01, 7.196736e-01, 7.199879e-01, 7.203019e-01, 7.206156e-01, 7.209290e-01, 7.212422e-01, 7.215551e-01, 7.218677e-01, 7.221801e-01, 7.224922e-01, 7.228040e-01, 7.231156e-01, 7.234268e-01, 7.237378e-01, 7.240486e-01, 7.243591e-01, 7.246693e-01, 7.249793e-01, 7.252890e-01, 7.255983e-01, 7.259076e-01, 7.262164e-01, 7.265251e-01, 7.268335e-01, 7.271415e-01, 7.274494e-01, 7.277570e-01, 7.280643e-01, 7.283714e-01, 7.286782e-01, 7.289847e-01, 7.292911e-01, 7.295971e-01, 7.299029e-01, 7.302084e-01, 7.305137e-01, 7.308187e-01, 7.311234e-01, 7.314279e-01, 7.317322e-01, 7.320362e-01, 7.323400e-01, 7.326434e-01, 7.329467e-01, 7.332497e-01, 7.335525e-01, 7.338549e-01, 7.341572e-01, 7.344592e-01, 7.347609e-01, 7.350624e-01, 7.353637e-01, 7.356647e-01, 7.359655e-01, 7.362660e-01, 7.365662e-01, 7.368662e-01, 7.371660e-01, 7.374656e-01, 7.377649e-01, 7.380639e-01, 7.383628e-01, 7.386613e-01, 7.389597e-01, 7.392578e-01, 7.395556e-01, 7.398532e-01, 7.401506e-01, 7.404477e-01, 7.407446e-01, 7.410412e-01, 7.413377e-01, 7.416338e-01, 7.419298e-01, 7.422255e-01, 7.425209e-01, 7.428162e-01, 7.431112e-01, 7.434059e-01, 7.437005e-01, 7.439948e-01, 7.442889e-01, 7.445827e-01, 7.448763e-01, 7.451697e-01, 7.454628e-01, 7.457558e-01, 7.460485e-01, 7.463409e-01, 7.466331e-01, 7.469251e-01, 7.472169e-01, 7.475084e-01, 7.477998e-01, 7.480908e-01, 7.483817e-01, 7.486723e-01, 7.489627e-01, 7.492529e-01, 7.495428e-01, 7.498326e-01, 7.501221e-01, 7.504114e-01, 7.507005e-01, 7.509893e-01, 7.512779e-01, 7.515663e-01, 7.518545e-01, 7.521424e-01, 7.524302e-01, 7.527177e-01, 7.530050e-01, 7.532921e-01, 7.535789e-01, 7.538656e-01, 7.541520e-01, 7.544382e-01, 7.547241e-01, 7.550099e-01, 7.552955e-01, 7.555808e-01, 7.558660e-01, 7.561509e-01, 7.564356e-01, 7.567201e-01, 7.570043e-01, 7.572884e-01, 7.575722e-01, 7.578558e-01, 7.581393e-01, 7.584225e-01, 7.587055e-01, 7.589883e-01, 7.592708e-01, 7.595532e-01, 7.598354e-01, 7.601173e-01, 7.603990e-01, 7.606806e-01, 7.609619e-01, 7.612430e-01, 7.615239e-01, 7.618046e-01, 7.620851e-01, 7.623653e-01, 7.626454e-01, 7.629253e-01, 7.632049e-01, 7.634844e-01, 7.637637e-01, 7.640427e-01, 7.643216e-01, 7.646002e-01, 7.648786e-01, 7.651569e-01, 7.654349e-01, 7.657127e-01, 7.659904e-01, 7.662678e-01, 7.665451e-01, 7.668221e-01, 7.670989e-01, 7.673756e-01, 7.676520e-01, 7.679282e-01, 7.682042e-01, 7.684801e-01, 7.687557e-01, 7.690312e-01, 7.693064e-01, 7.695814e-01, 7.698563e-01, 7.701310e-01, 7.704054e-01, 7.706797e-01, 7.709538e-01, 7.712276e-01, 7.715013e-01, 7.717748e-01, 7.720481e-01, 7.723212e-01, 7.725941e-01, 7.728668e-01, 7.731394e-01, 7.734116e-01, 7.736838e-01, 7.739558e-01, 7.742275e-01, 7.744991e-01, 7.747704e-01, 7.750416e-01, 7.753126e-01, 7.755834e-01, 7.758540e-01, 7.761245e-01, 7.763947e-01, 7.766647e-01, 7.769346e-01, 7.772043e-01, 7.774737e-01, 7.777431e-01, 7.780122e-01, 7.782811e-01, 7.785498e-01, 7.788184e-01, 7.790868e-01, 7.793550e-01, 7.796230e-01, 7.798908e-01, 7.801584e-01, 7.804259e-01, 7.806932e-01, 7.809603e-01, 7.812271e-01, 7.814939e-01, 7.817604e-01, 7.820268e-01, 7.822930e-01, 7.825589e-01, 7.828248e-01, 7.830904e-01, 7.833558e-01, 7.836211e-01, 7.838862e-01, 7.841511e-01, 7.844158e-01, 7.846804e-01, 7.849448e-01, 7.852090e-01, 7.854730e-01, 7.857369e-01, 7.860005e-01, 7.862641e-01, 7.865273e-01, 7.867905e-01, 7.870535e-01, 7.873163e-01, 7.875788e-01, 7.878413e-01, 7.881036e-01, 7.883657e-01, 7.886276e-01, 7.888893e-01, 7.891509e-01, 7.894123e-01, 7.896735e-01, 7.899345e-01, 7.901954e-01, 7.904561e-01, 7.907166e-01, 7.909770e-01, 7.912372e-01, 7.914972e-01, 7.917571e-01, 7.920167e-01, 7.922763e-01, 7.925356e-01, 7.927948e-01, 7.930537e-01, 7.933126e-01, 7.935712e-01, 7.938297e-01, 7.940881e-01, 7.943462e-01, 7.946042e-01, 7.948620e-01, 7.951197e-01, 7.953772e-01, 7.956345e-01, 7.958916e-01, 7.961487e-01, 7.964054e-01, 7.966621e-01, 7.969186e-01, 7.971749e-01, 7.974311e-01, 7.976871e-01, 7.979429e-01, 7.981986e-01, 7.984541e-01, 7.987095e-01, 7.989646e-01, 7.992196e-01, 7.994745e-01, 7.997292e-01, 7.999837e-01, 8.002381e-01, 8.004923e-01, 8.007463e-01, 8.010002e-01, 8.012539e-01, 8.015075e-01, 8.017609e-01, 8.020141e-01, 8.022672e-01, 8.025202e-01, 8.027729e-01, 8.030255e-01, 8.032780e-01, 8.035302e-01, 8.037823e-01, 8.040344e-01, 8.042861e-01, 8.045378e-01, 8.047893e-01, 8.050406e-01, 8.052918e-01, 8.055428e-01, 8.057937e-01, 8.060444e-01, 8.062950e-01, 8.065454e-01, 8.067956e-01, 8.070457e-01, 8.072957e-01, 8.075454e-01, 8.077950e-01, 8.080446e-01, 8.082938e-01, 8.085430e-01, 8.087921e-01, 8.090409e-01, 8.092896e-01, 8.095381e-01, 8.097866e-01, 8.100348e-01, 8.102829e-01, 8.105308e-01, 8.107786e-01, 8.110263e-01, 8.112738e-01, 8.115211e-01, 8.117683e-01, 8.120154e-01, 8.122622e-01, 8.125089e-01, 8.127556e-01, 8.130020e-01, 8.132483e-01, 8.134944e-01, 8.137404e-01, 8.139862e-01, 8.142319e-01, 8.144775e-01, 8.147229e-01, 8.149682e-01, 8.152133e-01, 8.154582e-01, 8.157030e-01, 8.159477e-01, 8.161922e-01, 8.164365e-01, 8.166808e-01, 8.169249e-01, 8.171688e-01, 8.174126e-01, 8.176562e-01, 8.178997e-01, 8.181431e-01, 8.183863e-01, 8.186293e-01, 8.188722e-01, 8.191150e-01, 8.193576e-01, 8.196001e-01, 8.198425e-01, 8.200847e-01, 8.203267e-01, 8.205686e-01, 8.208104e-01, 8.210521e-01, 8.212935e-01, 8.215349e-01, 8.217760e-01, 8.220171e-01, 8.222581e-01, 8.224988e-01, 8.227395e-01, 8.229799e-01, 8.232203e-01, 8.234605e-01, 8.237006e-01, 8.239405e-01, 8.241804e-01, 8.244200e-01, 8.246595e-01, 8.248989e-01, 8.251381e-01, 8.253772e-01, 8.256162e-01, 8.258550e-01, 8.260937e-01, 8.263323e-01, 8.265706e-01, 8.268089e-01, 8.270471e-01, 8.272851e-01, 8.275229e-01, 8.277607e-01, 8.279983e-01, 8.282357e-01, 8.284730e-01, 8.287102e-01, 8.289472e-01, 8.291842e-01, 8.294209e-01, 8.296576e-01, 8.298941e-01, 8.301305e-01, 8.303667e-01, 8.306028e-01, 8.308387e-01, 8.310746e-01, 8.313103e-01, 8.315458e-01, 8.317813e-01, 8.320166e-01, 8.322517e-01, 8.324867e-01, 8.327217e-01, 8.329564e-01, 8.331911e-01, 8.334256e-01, 8.336599e-01, 8.338942e-01, 8.341283e-01, 8.343623e-01, 8.345962e-01, 8.348299e-01, 8.350635e-01, 8.352969e-01, 8.355302e-01, 8.357634e-01, 8.359964e-01, 8.362294e-01, 8.364622e-01, 8.366948e-01, 8.369274e-01, 8.371598e-01, 8.373921e-01, 8.376243e-01, 8.378563e-01, 8.380882e-01, 8.383200e-01, 8.385516e-01, 8.387831e-01, 8.390145e-01, 8.392458e-01, 8.394769e-01, 8.397079e-01, 8.399388e-01, 8.401695e-01, 8.404002e-01, 8.406307e-01, 8.408611e-01, 8.410913e-01, 8.413214e-01, 8.415514e-01, 8.417813e-01, 8.420110e-01, 8.422406e-01, 8.424702e-01, 8.426995e-01, 8.429288e-01, 8.431579e-01, 8.433869e-01, 8.436158e-01, 8.438445e-01, 8.440731e-01, 8.443016e-01, 8.445300e-01, 8.447582e-01, 8.449863e-01, 8.452144e-01, 8.454422e-01, 8.456700e-01, 8.458977e-01, 8.461251e-01, 8.463526e-01, 8.465798e-01, 8.468069e-01, 8.470340e-01, 8.472609e-01, 8.474877e-01, 8.477143e-01, 8.479409e-01, 8.481673e-01, 8.483936e-01, 8.486198e-01, 8.488458e-01, 8.490717e-01, 8.492976e-01, 8.495233e-01, 8.497488e-01, 8.499743e-01, 8.501996e-01, 8.504249e-01, 8.506500e-01, 8.508750e-01, 8.510998e-01, 8.513246e-01, 8.515491e-01, 8.517737e-01, 8.519981e-01, 8.522223e-01, 8.524465e-01, 8.526706e-01, 8.528944e-01, 8.531182e-01, 8.533419e-01, 8.535655e-01, 8.537889e-01, 8.540123e-01, 8.542355e-01, 8.544586e-01, 8.546816e-01, 8.549044e-01, 8.551272e-01, 8.553498e-01, 8.555723e-01, 8.557947e-01, 8.560170e-01, 8.562392e-01, 8.564612e-01, 8.566832e-01, 8.569050e-01, 8.571267e-01, 8.573483e-01, 8.575698e-01, 8.577912e-01, 8.580124e-01, 8.582336e-01, 8.584546e-01, 8.586755e-01, 8.588963e-01, 8.591169e-01, 8.593375e-01, 8.595580e-01, 8.597783e-01, 8.599985e-01, 8.602186e-01, 8.604387e-01, 8.606585e-01, 8.608783e-01, 8.610980e-01, 8.613176e-01, 8.615370e-01, 8.617563e-01, 8.619756e-01, 8.621947e-01, 8.624136e-01, 8.626326e-01, 8.628513e-01, 8.630700e-01, 8.632885e-01, 8.635070e-01, 8.637253e-01, 8.639436e-01, 8.641617e-01, 8.643796e-01, 8.645976e-01, 8.648154e-01, 8.650330e-01, 8.652506e-01, 8.654680e-01, 8.656853e-01, 8.659026e-01, 8.661197e-01, 8.663368e-01, 8.665537e-01, 8.667705e-01, 8.669872e-01, 8.672037e-01, 8.674202e-01, 8.676366e-01, 8.678529e-01, 8.680690e-01, 8.682851e-01, 8.685010e-01, 8.687168e-01, 8.689325e-01, 8.691481e-01, 8.693637e-01, 8.695791e-01, 8.697944e-01, 8.700095e-01, 8.702246e-01, 8.704396e-01, 8.706545e-01, 8.708693e-01, 8.710839e-01, 8.712984e-01, 8.715129e-01, 8.717272e-01, 8.719414e-01, 8.721556e-01, 8.723696e-01, 8.725836e-01, 8.727974e-01, 8.730111e-01, 8.732247e-01, 8.734382e-01, 8.736516e-01, 8.738649e-01, 8.740780e-01, 8.742912e-01, 8.745041e-01, 8.747170e-01, 8.749298e-01, 8.751425e-01, 8.753550e-01, 8.755675e-01, 8.757799e-01, 8.759921e-01, 8.762043e-01, 8.764163e-01, 8.766283e-01, 8.768401e-01, 8.770519e-01, 8.772635e-01, 8.774751e-01, 8.776865e-01, 8.778979e-01, 8.781091e-01, 8.783202e-01, 8.785312e-01, 8.787422e-01, 8.789530e-01, 8.791637e-01, 8.793744e-01, 8.795849e-01, 8.797953e-01, 8.800057e-01, 8.802159e-01, 8.804260e-01, 8.806360e-01, 8.808460e-01, 8.810558e-01, 8.812655e-01, 8.814751e-01, 8.816847e-01, 8.818941e-01, 8.821034e-01, 8.823127e-01, 8.825217e-01, 8.827308e-01, 8.829397e-01, 8.831486e-01, 8.833573e-01, 8.835659e-01, 8.837745e-01, 8.839829e-01, 8.841912e-01, 8.843995e-01, 8.846076e-01, 8.848156e-01, 8.850236e-01, 8.852314e-01, 8.854392e-01, 8.856469e-01, 8.858544e-01, 8.860618e-01, 8.862692e-01, 8.864765e-01, 8.866837e-01, 8.868908e-01, 8.870977e-01, 8.873046e-01, 8.875114e-01, 8.877181e-01, 8.879247e-01, 8.881311e-01, 8.883376e-01, 8.885438e-01, 8.887501e-01, 8.889562e-01, 8.891622e-01, 8.893681e-01, 8.895739e-01, 8.897797e-01, 8.899853e-01, 8.901908e-01, 8.903963e-01, 8.906016e-01, 8.908069e-01, 8.910121e-01, 8.912171e-01, 8.914221e-01, 8.916270e-01, 8.918318e-01, 8.920364e-01, 8.922410e-01, 8.924455e-01, 8.926499e-01, 8.928543e-01, 8.930585e-01, 8.932626e-01, 8.934667e-01, 8.936706e-01, 8.938744e-01, 8.940782e-01, 8.942819e-01, 8.944854e-01, 8.946889e-01, 8.948923e-01, 8.950956e-01, 8.952988e-01, 8.955019e-01, 8.957049e-01, 8.959078e-01, 8.961107e-01, 8.963134e-01, 8.965160e-01, 8.967186e-01, 8.969210e-01, 8.971235e-01, 8.973257e-01, 8.975279e-01, 8.977300e-01, 8.979320e-01, 8.981339e-01, 8.983358e-01, 8.985375e-01, 8.987392e-01, 8.989407e-01, 8.991421e-01, 8.993436e-01, 8.995448e-01, 8.997460e-01, 8.999471e-01, 9.001482e-01, 9.003491e-01, 9.005499e-01, 9.007506e-01, 9.009513e-01, 9.011519e-01, 9.013523e-01, 9.015527e-01, 9.017531e-01, 9.019532e-01, 9.021534e-01, 9.023534e-01, 9.025534e-01, 9.027532e-01, 9.029530e-01, 9.031526e-01, 9.033523e-01, 9.035518e-01, 9.037512e-01, 9.039505e-01, 9.041498e-01, 9.043489e-01, 9.045479e-01, 9.047469e-01, 9.049459e-01, 9.051446e-01, 9.053434e-01, 9.055420e-01, 9.057405e-01, 9.059390e-01, 9.061373e-01, 9.063356e-01, 9.065338e-01, 9.067319e-01, 9.069299e-01, 9.071279e-01, 9.073257e-01, 9.075235e-01, 9.077212e-01, 9.079187e-01, 9.081162e-01, 9.083136e-01, 9.085110e-01, 9.087082e-01, 9.089054e-01, 9.091024e-01, 9.092994e-01, 9.094964e-01, 9.096932e-01, 9.098899e-01, 9.100866e-01, 9.102831e-01, 9.104796e-01, 9.106760e-01, 9.108723e-01, 9.110685e-01, 9.112647e-01, 9.114607e-01, 9.116567e-01, 9.118526e-01, 9.120483e-01, 9.122441e-01, 9.124397e-01, 9.126353e-01, 9.128307e-01, 9.130261e-01, 9.132214e-01, 9.134166e-01, 9.136118e-01, 9.138068e-01, 9.140018e-01, 9.141967e-01, 9.143915e-01, 9.145862e-01, 9.147808e-01, 9.149753e-01, 9.151698e-01, 9.153642e-01, 9.155585e-01, 9.157528e-01, 9.159469e-01, 9.161409e-01, 9.163349e-01, 9.165288e-01, 9.167226e-01, 9.169164e-01, 9.171100e-01, 9.173036e-01, 9.174970e-01, 9.176905e-01, 9.178838e-01, 9.180770e-01, 9.182702e-01, 9.184632e-01, 9.186562e-01, 9.188492e-01, 9.190420e-01, 9.192348e-01, 9.194274e-01, 9.196200e-01, 9.198125e-01, 9.200049e-01, 9.201973e-01, 9.203895e-01, 9.205818e-01, 9.207739e-01, 9.209659e-01, 9.211578e-01, 9.213497e-01, 9.215415e-01, 9.217332e-01, 9.219248e-01, 9.221163e-01, 9.223078e-01, 9.224992e-01, 9.226905e-01, 9.228818e-01, 9.230729e-01, 9.232640e-01, 9.234550e-01, 9.236459e-01, 9.238367e-01, 9.240275e-01, 9.242182e-01, 9.244088e-01, 9.245993e-01, 9.247897e-01, 9.249801e-01, 9.251704e-01, 9.253606e-01, 9.255507e-01, 9.257408e-01, 9.259307e-01, 9.261206e-01, 9.263105e-01, 9.265002e-01, 9.266899e-01, 9.268795e-01, 9.270689e-01, 9.272584e-01, 9.274477e-01, 9.276370e-01, 9.278262e-01, 9.280154e-01, 9.282044e-01, 9.283934e-01, 9.285822e-01, 9.287710e-01, 9.289598e-01, 9.291484e-01, 9.293370e-01, 9.295255e-01, 9.297140e-01, 9.299023e-01, 9.300906e-01, 9.302788e-01, 9.304669e-01, 9.306549e-01, 9.308429e-01, 9.310308e-01, 9.312186e-01, 9.314064e-01, 9.315941e-01, 9.317816e-01, 9.319692e-01, 9.321566e-01, 9.323440e-01, 9.325313e-01, 9.327185e-01, 9.329057e-01, 9.330927e-01, 9.332797e-01, 9.334666e-01, 9.336535e-01, 9.338402e-01, 9.340270e-01, 9.342135e-01, 9.344001e-01, 9.345866e-01, 9.347730e-01, 9.349593e-01, 9.351455e-01, 9.353317e-01, 9.355178e-01, 9.357038e-01, 9.358898e-01, 9.360756e-01, 9.362615e-01, 9.364472e-01, 9.366328e-01, 9.368184e-01, 9.370039e-01, 9.371893e-01, 9.373747e-01, 9.375600e-01, 9.377452e-01, 9.379303e-01, 9.381154e-01, 9.383004e-01, 9.384854e-01, 9.386702e-01, 9.388550e-01, 9.390397e-01, 9.392243e-01, 9.394089e-01, 9.395934e-01, 9.397778e-01, 9.399621e-01, 9.401464e-01, 9.403306e-01, 9.405147e-01, 9.406988e-01, 9.408827e-01, 9.410667e-01, 9.412505e-01, 9.414343e-01, 9.416180e-01, 9.418016e-01, 9.419851e-01, 9.421686e-01, 9.423520e-01, 9.425353e-01, 9.427186e-01, 9.429018e-01, 9.430850e-01, 9.432680e-01, 9.434510e-01, 9.436339e-01, 9.438167e-01, 9.439995e-01, 9.441822e-01, 9.443648e-01, 9.445474e-01, 9.447299e-01, 9.449123e-01, 9.450946e-01, 9.452769e-01, 9.454591e-01, 9.456412e-01, 9.458233e-01, 9.460053e-01, 9.461872e-01, 9.463691e-01, 9.465508e-01, 9.467326e-01, 9.469142e-01, 9.470958e-01, 9.472773e-01, 9.474587e-01, 9.476401e-01, 9.478214e-01, 9.480026e-01, 9.481838e-01, 9.483649e-01, 9.485459e-01, 9.487268e-01, 9.489077e-01, 9.490886e-01, 9.492693e-01, 9.494500e-01, 9.496306e-01, 9.498111e-01, 9.499916e-01, 9.501719e-01, 9.503523e-01, 9.505326e-01, 9.507128e-01, 9.508929e-01, 9.510729e-01, 9.512529e-01, 9.514329e-01, 9.516127e-01, 9.517925e-01, 9.519722e-01, 9.521519e-01, 9.523315e-01, 9.525110e-01, 9.526904e-01, 9.528698e-01, 9.530491e-01, 9.532284e-01, 9.534075e-01, 9.535866e-01, 9.537657e-01, 9.539447e-01, 9.541236e-01, 9.543024e-01, 9.544812e-01, 9.546599e-01, 9.548386e-01, 9.550171e-01, 9.551957e-01, 9.553741e-01, 9.555525e-01, 9.557307e-01, 9.559090e-01, 9.560872e-01, 9.562653e-01, 9.564433e-01, 9.566213e-01, 9.567992e-01, 9.569771e-01, 9.571549e-01, 9.573326e-01, 9.575102e-01, 9.576878e-01, 9.578653e-01, 9.580427e-01, 9.582201e-01, 9.583974e-01, 9.585747e-01, 9.587519e-01, 9.589290e-01, 9.591061e-01, 9.592831e-01, 9.594600e-01, 9.596368e-01, 9.598137e-01, 9.599904e-01, 9.601671e-01, 9.603436e-01, 9.605201e-01, 9.606966e-01, 9.608730e-01, 9.610494e-01, 9.612256e-01, 9.614019e-01, 9.615780e-01, 9.617541e-01, 9.619301e-01, 9.621060e-01, 9.622819e-01, 9.624578e-01, 9.626336e-01, 9.628092e-01, 9.629849e-01, 9.631604e-01, 9.633359e-01, 9.635113e-01, 9.636867e-01, 9.638621e-01, 9.640373e-01, 9.642125e-01, 9.643876e-01, 9.645627e-01, 9.647377e-01, 9.649126e-01, 9.650874e-01, 9.652622e-01, 9.654370e-01, 9.656116e-01, 9.657863e-01, 9.659608e-01, 9.661353e-01, 9.663097e-01, 9.664841e-01, 9.666584e-01, 9.668326e-01, 9.670068e-01, 9.671809e-01, 9.673550e-01, 9.675289e-01, 9.677029e-01, 9.678767e-01, 9.680505e-01, 9.682242e-01, 9.683979e-01, 9.685715e-01, 9.687451e-01, 9.689186e-01, 9.690920e-01, 9.692653e-01, 9.694387e-01, 9.696119e-01, 9.697851e-01, 9.699582e-01, 9.701312e-01, 9.703043e-01, 9.704772e-01, 9.706500e-01, 9.708228e-01, 9.709955e-01, 9.711683e-01, 9.713409e-01, 9.715135e-01, 9.716859e-01, 9.718584e-01, 9.720308e-01, 9.722031e-01, 9.723753e-01, 9.725475e-01, 9.727197e-01, 9.728917e-01, 9.730637e-01, 9.732357e-01, 9.734076e-01, 9.735794e-01, 9.737512e-01, 9.739228e-01, 9.740945e-01, 9.742661e-01, 9.744377e-01, 9.746091e-01, 9.747805e-01, 9.749519e-01, 9.751231e-01, 9.752944e-01, 9.754655e-01, 9.756366e-01, 9.758077e-01, 9.759787e-01, 9.761496e-01, 9.763204e-01, 9.764913e-01, 9.766620e-01, 9.768327e-01, 9.770033e-01, 9.771739e-01, 9.773444e-01, 9.775148e-01, 9.776852e-01, 9.778556e-01, 9.780258e-01, 9.781960e-01, 9.783661e-01, 9.785362e-01, 9.787063e-01, 9.788762e-01, 9.790462e-01, 9.792160e-01, 9.793859e-01, 9.795555e-01, 9.797252e-01, 9.798949e-01, 9.800645e-01, 9.802339e-01, 9.804034e-01, 9.805728e-01, 9.807421e-01, 9.809114e-01, 9.810806e-01, 9.812497e-01, 9.814188e-01, 9.815878e-01, 9.817568e-01, 9.819257e-01, 9.820946e-01, 9.822634e-01, 9.824321e-01, 9.826008e-01, 9.827695e-01, 9.829381e-01, 9.831066e-01, 9.832750e-01, 9.834434e-01, 9.836118e-01, 9.837800e-01, 9.839482e-01, 9.841164e-01, 9.842845e-01, 9.844526e-01, 9.846206e-01, 9.847885e-01, 9.849564e-01, 9.851242e-01, 9.852920e-01, 9.854597e-01, 9.856274e-01, 9.857950e-01, 9.859625e-01, 9.861299e-01, 9.862974e-01, 9.864647e-01, 9.866320e-01, 9.867993e-01, 9.869665e-01, 9.871337e-01, 9.873008e-01, 9.874678e-01, 9.876347e-01, 9.878017e-01, 9.879685e-01, 9.881353e-01, 9.883021e-01, 9.884688e-01, 9.886354e-01, 9.888020e-01, 9.889685e-01, 9.891350e-01, 9.893014e-01, 9.894677e-01, 9.896340e-01, 9.898003e-01, 9.899665e-01, 9.901326e-01, 9.902986e-01, 9.904646e-01, 9.906306e-01, 9.907965e-01, 9.909624e-01, 9.911281e-01, 9.912939e-01, 9.914596e-01, 9.916252e-01, 9.917908e-01, 9.919563e-01, 9.921218e-01, 9.922872e-01, 9.924526e-01, 9.926178e-01, 9.927831e-01, 9.929483e-01, 9.931134e-01, 9.932785e-01, 9.934435e-01, 9.936085e-01, 9.937734e-01, 9.939383e-01, 9.941031e-01, 9.942678e-01, 9.944325e-01, 9.945971e-01, 9.947617e-01, 9.949263e-01, 9.950907e-01, 9.952552e-01, 9.954196e-01, 9.955838e-01, 9.957481e-01, 9.959123e-01, 9.960765e-01, 9.962406e-01, 9.964046e-01, 9.965686e-01, 9.967325e-01, 9.968964e-01, 9.970602e-01, 9.972240e-01, 9.973878e-01, 9.975514e-01, 9.977150e-01, 9.978786e-01, 9.980421e-01, 9.982055e-01, 9.983689e-01, 9.985323e-01, 9.986956e-01, 9.988588e-01, 9.990220e-01, 9.991851e-01, 9.993482e-01, 9.995112e-01, 9.996742e-01, 9.998372e-01, 1.000000e+00, }; int i = (int)(d * 2047); assert(i >= 0 && i < 2048); return cube_root[i]; } static inline void _ccv_rgb_to_luv(const float r, const float g, const float b, float* pl, float* pu, float* pv) { const float x = 0.412453f * r + 0.35758f * g + 0.180423f * b; const float y = 0.212671f * r + 0.71516f * g + 0.072169f * b; const float z = 0.019334f * r + 0.119193f * g + 0.950227f * b; const float x_n = 0.312713f, y_n = 0.329016f; const float uv_n_divisor = -2.f * x_n + 12.f * y_n + 3.f; const float u_n = 4.f * x_n / uv_n_divisor; const float v_n = 9.f * y_n / uv_n_divisor; const float uv_divisor = ccv_max((x + 15.f * y + 3.f * z), FLT_EPSILON); const float u = 4.f * x / uv_divisor; const float v = 9.f * y / uv_divisor; const float y_cube_root = fast_cube_root(y); const float l_value = ccv_max(0.f, ((116.f * y_cube_root) - 16.f)); const float u_value = 13.f * l_value * (u - u_n); const float v_value = 13.f * l_value * (v - v_n); // L in [0, 100], U in [-134, 220], V in [-140, 122] *pl = l_value * (255.f / 100.f); *pu = (u_value + 134.f) * (255.f / (220.f + 134.f)); *pv = (v_value + 140.f) * (255.f / (122.f + 140.f)); } // generating the integrate channels features (which combines the grayscale, gradient magnitude, and 6-direction HOG) void ccv_icf(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type) { int ch = CCV_GET_CHANNEL(a->type); assert(ch == 1 || ch == 3); int nchr = (ch == 1) ? 8 : 10; ccv_declare_derived_signature(sig, a->sig != 0, ccv_sign_with_literal("ccv_icf"), a->sig, CCV_EOF_SIGN); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | nchr, CCV_32F | nchr, sig); ccv_object_return_if_cached(, db); ccv_dense_matrix_t* ag = 0; ccv_dense_matrix_t* mg = 0; ccv_gradient(a, &ag, 0, &mg, 0, 1, 1); float* agp = ag->data.f32; float* mgp = mg->data.f32; float* dbp = db->data.f32; ccv_zero(db); int i, j, k; unsigned char* a_ptr = a->data.u8; float magnitude_scaling = 1 / sqrtf(2); // regularize it to 0~1 if (ch == 1) { #define for_block(_, _for_get) \ for (i = 0; i < a->rows; i++) \ { \ for (j = 0; j < a->cols; j++) \ { \ dbp[0] = _for_get(a_ptr, j, 0); \ dbp[1] = mgp[j] * magnitude_scaling; \ float agr = (ccv_clamp(agp[j] <= 180 ? agp[j] : agp[j] - 180, 0, 179.99) / 180.0) * 6; \ int ag0 = (int)agr; \ int ag1 = ag0 < 5 ? ag0 + 1 : 0; \ agr = agr - ag0; \ dbp[2 + ag0] = dbp[1] * (1 - agr); \ dbp[2 + ag1] = dbp[1] * agr; \ dbp += 8; \ } \ a_ptr += a->step; \ agp += a->cols; \ mgp += a->cols; \ } ccv_matrix_getter(a->type, for_block); #undef for_block } else { // color one, luv, gradient magnitude, and 6-direction HOG #define for_block(_, _for_get) \ for (i = 0; i < a->rows; i++) \ { \ for (j = 0; j < a->cols; j++) \ { \ _ccv_rgb_to_luv(_for_get(a_ptr, j * ch, 0) / 255.0, \ _for_get(a_ptr, j * ch + 1, 0) / 255.0, \ _for_get(a_ptr, j * ch + 2, 0) / 255.0, \ dbp, dbp + 1, dbp + 2); \ float agv = agp[j * ch]; \ float mgv = mgp[j * ch]; \ for (k = 1; k < ch; k++) \ { \ if (mgp[j * ch + k] > mgv) \ { \ mgv = mgp[j * ch + k]; \ agv = agp[j * ch + k]; \ } \ } \ dbp[3] = mgv * magnitude_scaling; \ float agr = (ccv_clamp(agv <= 180 ? agv : agv - 180, 0, 179.99) / 180.0) * 6; \ int ag0 = (int)agr; \ int ag1 = ag0 < 5 ? ag0 + 1 : 0; \ agr = agr - ag0; \ dbp[4 + ag0] = dbp[3] * (1 - agr); \ dbp[4 + ag1] = dbp[3] * agr; \ dbp += 10; \ } \ a_ptr += a->step; \ agp += a->cols * ch; \ mgp += a->cols * ch; \ } ccv_matrix_getter(a->type, for_block); #undef for_block } ccv_matrix_free(ag); ccv_matrix_free(mg); } static inline float _ccv_icf_run_feature(ccv_icf_feature_t* feature, float* ptr, int cols, int ch, int x, int y) { float c = feature->beta; int q; for (q = 0; q < feature->count; q++) c += (ptr[(feature->sat[q * 2 + 1].x + x + 1 + (feature->sat[q * 2 + 1].y + y + 1) * cols) * ch + feature->channel[q]] - ptr[(feature->sat[q * 2].x + x + (feature->sat[q * 2 + 1].y + y + 1) * cols) * ch + feature->channel[q]] + ptr[(feature->sat[q * 2].x + x + (feature->sat[q * 2].y + y) * cols) * ch + feature->channel[q]] - ptr[(feature->sat[q * 2 + 1].x + x + 1 + (feature->sat[q * 2].y + y) * cols) * ch + feature->channel[q]]) * feature->alpha[q]; return c; } static inline int _ccv_icf_run_weak_classifier(ccv_icf_decision_tree_t* weak_classifier, float* ptr, int cols, int ch, int x, int y) { float c = _ccv_icf_run_feature(weak_classifier->features, ptr, cols, ch, x, y); if (c > 0) { if (!(weak_classifier->pass & 0x1)) return 1; return _ccv_icf_run_feature(weak_classifier->features + 2, ptr, cols, ch, x, y) > 0; } else { if (!(weak_classifier->pass & 0x2)) return 0; return _ccv_icf_run_feature(weak_classifier->features + 1, ptr, cols, ch, x, y) > 0; } } #ifdef HAVE_GSL static void _ccv_icf_randomize_feature(gsl_rng* rng, ccv_size_t size, int minimum, ccv_icf_feature_t* feature, int grayscale) { feature->count = gsl_rng_uniform_int(rng, CCV_ICF_SAT_MAX) + 1; assert(feature->count <= CCV_ICF_SAT_MAX); int i; feature->beta = 0; for (i = 0; i < feature->count; i++) { int x0, y0, x1, y1; do { x0 = gsl_rng_uniform_int(rng, size.width); x1 = gsl_rng_uniform_int(rng, size.width); y0 = gsl_rng_uniform_int(rng, size.height); y1 = gsl_rng_uniform_int(rng, size.height); } while ((ccv_max(x0, x1) - ccv_min(x0, x1) + 1) * (ccv_max(y0, y1) - ccv_min(y0, y1) + 1) < (minimum + 1) * (minimum + 1) || (ccv_max(x0, x1) - ccv_min(x0, x1) + 1) < minimum || (ccv_max(y0, y1) - ccv_min(y0, y1) + 1) < minimum); feature->sat[i * 2].x = ccv_min(x0, x1); feature->sat[i * 2].y = ccv_min(y0, y1); feature->sat[i * 2 + 1].x = ccv_max(x0, x1); feature->sat[i * 2 + 1].y = ccv_max(y0, y1); feature->channel[i] = gsl_rng_uniform_int(rng, grayscale ? 8 : 10); // 8-channels for grayscale, and 10-channels for rgb assert(feature->channel[i] >= 0 && feature->channel[i] < (grayscale ? 8 : 10)); feature->alpha[i] = gsl_rng_uniform(rng) / (float)((feature->sat[i * 2 + 1].x - feature->sat[i * 2].x + 1) * (feature->sat[i * 2 + 1].y - feature->sat[i * 2].y + 1)); } } static void _ccv_icf_check_params(ccv_icf_new_param_t params) { assert(params.size.width > 0 && params.size.height > 0); assert(params.deform_shift >= 0); assert(params.deform_angle >= 0); assert(params.deform_scale >= 0 && params.deform_scale < 1); assert(params.feature_size > 0); assert(params.acceptance > 0 && params.acceptance < 1.0); } static ccv_dense_matrix_t* _ccv_icf_capture_feature(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_decimal_pose_t pose, ccv_size_t size, ccv_margin_t margin, float deform_angle, float deform_scale, float deform_shift) { float rotate_x = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.pitch; float rotate_y = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.yaw; float rotate_z = (deform_angle * 2 * gsl_rng_uniform(rng) - deform_angle) * CCV_PI / 180 + pose.roll; float scale = gsl_rng_uniform(rng); // to make the scale evenly distributed, for example, when deforming of 1/2 ~ 2, we want it to distribute around 1, rather than any average of 1/2 ~ 2 scale = (1 + deform_scale * scale) / (1 + deform_scale * (1 - scale)); float scale_ratio = sqrtf((float)(size.width * size.height) / (pose.a * pose.b * 4)); float m00 = cosf(rotate_z) * scale; float m01 = cosf(rotate_y) * sinf(rotate_z) * scale; float m02 = (deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) / scale_ratio + pose.x + (margin.right - margin.left) / scale_ratio - image->cols * 0.5; float m10 = (sinf(rotate_y) * cosf(rotate_z) - cosf(rotate_x) * sinf(rotate_z)) * scale; float m11 = (sinf(rotate_y) * sinf(rotate_z) + cosf(rotate_x) * cosf(rotate_z)) * scale; float m12 = (deform_shift * 2 * gsl_rng_uniform(rng) - deform_shift) / scale_ratio + pose.y + (margin.bottom - margin.top) / scale_ratio - image->rows * 0.5; float m20 = (sinf(rotate_y) * cosf(rotate_z) + sinf(rotate_x) * sinf(rotate_z)) * scale; float m21 = (sinf(rotate_y) * sinf(rotate_z) - sinf(rotate_x) * cosf(rotate_z)) * scale; float m22 = cosf(rotate_x) * cosf(rotate_y); ccv_dense_matrix_t* b = 0; ccv_perspective_transform(image, &b, 0, m00, m01, m02, m10, m11, m12, m20, m21, m22); ccv_dense_matrix_t* resize = 0; // have 1px border around the grayscale image because we need these to compute correct gradient feature ccv_size_t scale_size = { .width = (int)((size.width + margin.left + margin.right + 2) / scale_ratio + 0.5), .height = (int)((size.height + margin.top + margin.bottom + 2) / scale_ratio + 0.5), }; assert(scale_size.width > 0 && scale_size.height > 0); ccv_slice(b, (ccv_matrix_t**)&resize, 0, (int)(b->rows * 0.5 - (size.height + margin.top + margin.bottom + 2) / scale_ratio * 0.5 + 0.5), (int)(b->cols * 0.5 - (size.width + margin.left + margin.right + 2) / scale_ratio * 0.5 + 0.5), scale_size.height, scale_size.width); ccv_matrix_free(b); b = 0; if (scale_ratio > 1) ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_INTER_CUBIC); else ccv_resample(resize, &b, 0, size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_INTER_AREA); ccv_matrix_free(resize); return b; } typedef struct { uint8_t correct:1; double weight; float rate; } ccv_icf_example_state_t; typedef struct { uint8_t classifier:1; uint8_t positives:1; uint8_t negatives:1; uint8_t features:1; uint8_t example_state:1; uint8_t precomputed:1; } ccv_icf_classifier_cascade_persistence_state_t; typedef struct { uint32_t index; float value; } ccv_icf_value_index_t; typedef struct { ccv_function_state_reserve_field; int i; int bootstrap; ccv_icf_new_param_t params; ccv_icf_classifier_cascade_t* classifier; ccv_array_t* positives; ccv_array_t* negatives; ccv_icf_feature_t* features; ccv_size_t size; ccv_margin_t margin; ccv_icf_example_state_t* example_state; uint8_t* precomputed; ccv_icf_classifier_cascade_persistence_state_t x; } ccv_icf_classifier_cascade_state_t; static void _ccv_icf_write_classifier_cascade_state(ccv_icf_classifier_cascade_state_t* state, const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/state", directory); FILE* w = fopen(filename, "w+"); fprintf(w, "%d %d %d\n", state->line_no, state->i, state->bootstrap); fprintf(w, "%d %d %d\n", state->params.feature_size, state->size.width, state->size.height); fprintf(w, "%d %d %d %d\n", state->margin.left, state->margin.top, state->margin.right, state->margin.bottom); fclose(w); int i, q; if (!state->x.positives) { snprintf(filename, 1024, "%s/positives", directory); w = fopen(filename, "wb+"); fwrite(&state->positives->rnum, sizeof(state->positives->rnum), 1, w); fwrite(&state->positives->rsize, sizeof(state->positives->rsize), 1, w); for (i = 0; i < state->positives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(state->positives, i); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); fwrite(a, 1, state->positives->rsize, w); } fclose(w); state->x.positives = 1; } if (!state->x.negatives) { assert(state->negatives->rsize == state->positives->rsize); snprintf(filename, 1024, "%s/negatives", directory); w = fopen(filename, "wb+"); fwrite(&state->negatives->rnum, sizeof(state->negatives->rnum), 1, w); fwrite(&state->negatives->rsize, sizeof(state->negatives->rsize), 1, w); for (i = 0; i < state->negatives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(state->negatives, i); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); fwrite(a, 1, state->negatives->rsize, w); } fclose(w); state->x.negatives = 1; } if (!state->x.features) { snprintf(filename, 1024, "%s/features", directory); w = fopen(filename, "w+"); for (i = 0; i < state->params.feature_size; i++) { ccv_icf_feature_t* feature = state->features + i; fprintf(w, "%d %a\n", feature->count, feature->beta); for (q = 0; q < feature->count; q++) fprintf(w, "%d %a %d %d %d %d\n", feature->channel[q], feature->alpha[q], feature->sat[q * 2].x, feature->sat[q * 2].y, feature->sat[q * 2 + 1].x, feature->sat[q * 2 + 1].y); } fclose(w); state->x.features = 1; } if (!state->x.example_state) { snprintf(filename, 1024, "%s/example_state", directory); w = fopen(filename, "w+"); for (i = 0; i < state->positives->rnum + state->negatives->rnum; i++) fprintf(w, "%u %la %a\n", (uint32_t)state->example_state[i].correct, state->example_state[i].weight, state->example_state[i].rate); fclose(w); state->x.example_state = 1; } if (!state->x.precomputed) { size_t step = (3 * (state->positives->rnum + state->negatives->rnum) + 3) & -4; snprintf(filename, 1024, "%s/precomputed", directory); w = fopen(filename, "wb+"); fwrite(state->precomputed, 1, step * state->params.feature_size, w); fclose(w); state->x.precomputed = 1; } if (!state->x.classifier) { snprintf(filename, 1024, "%s/cascade", directory); ccv_icf_write_classifier_cascade(state->classifier, filename); state->x.classifier = 1; } } static void _ccv_icf_read_classifier_cascade_state(const char* directory, ccv_icf_classifier_cascade_state_t* state) { char filename[1024]; state->line_no = state->i = 0; state->bootstrap = 0; snprintf(filename, 1024, "%s/state", directory); FILE* r = fopen(filename, "r"); if (r) { int feature_size; fscanf(r, "%d %d %d", &state->line_no, &state->i, &state->bootstrap); fscanf(r, "%d %d %d", &feature_size, &state->size.width, &state->size.height); fscanf(r, "%d %d %d %d", &state->margin.left, &state->margin.top, &state->margin.right, &state->margin.bottom); assert(feature_size == state->params.feature_size); fclose(r); } int i, q; snprintf(filename, 1024, "%s/positives", directory); r = fopen(filename, "rb"); state->x.precomputed = state->x.features = state->x.example_state = state->x.classifier = state->x.positives = state->x.negatives = 1; if (r) { int rnum, rsize; fread(&rnum, sizeof(rnum), 1, r); fread(&rsize, sizeof(rsize), 1, r); state->positives = ccv_array_new(rsize, rnum, 0); ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)alloca(rsize); for (i = 0; i < rnum; i++) { fread(a, 1, rsize, r); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); ccv_array_push(state->positives, a); } fclose(r); } snprintf(filename, 1024, "%s/negatives", directory); r = fopen(filename, "rb"); if (r) { int rnum, rsize; fread(&rnum, sizeof(rnum), 1, r); fread(&rsize, sizeof(rsize), 1, r); state->negatives = ccv_array_new(rsize, rnum, 0); ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)alloca(rsize); for (i = 0; i < rnum; i++) { fread(a, 1, rsize, r); assert(a->rows == state->size.height + state->margin.top + state->margin.bottom + 2 && a->cols == state->size.width + state->margin.left + state->margin.right + 2); ccv_array_push(state->negatives, a); } fclose(r); } snprintf(filename, 1024, "%s/features", directory); r = fopen(filename, "r"); if (r) { state->features = (ccv_icf_feature_t*)ccmalloc(state->params.feature_size * sizeof(ccv_icf_feature_t)); for (i = 0; i < state->params.feature_size; i++) { ccv_icf_feature_t* feature = state->features + i; fscanf(r, "%d %a", &feature->count, &feature->beta); for (q = 0; q < feature->count; q++) fscanf(r, "%d %a %d %d %d %d", &feature->channel[q], &feature->alpha[q], &feature->sat[q * 2].x, &feature->sat[q * 2].y, &feature->sat[q * 2 + 1].x, &feature->sat[q * 2 + 1].y); } fclose(r); } snprintf(filename, 1024, "%s/example_state", directory); r = fopen(filename, "r"); if (r) { state->example_state = (ccv_icf_example_state_t*)ccmalloc((state->positives->rnum + state->negatives->rnum) * sizeof(ccv_icf_example_state_t)); for (i = 0; i < state->positives->rnum + state->negatives->rnum; i++) { uint32_t correct; double weight; float rate; fscanf(r, "%u %la %a", &correct, &weight, &rate); state->example_state[i].correct = correct; state->example_state[i].weight = weight; state->example_state[i].rate = rate; } fclose(r); } else state->example_state = 0; snprintf(filename, 1024, "%s/precomputed", directory); r = fopen(filename, "rb"); if (r) { size_t step = (3 * (state->positives->rnum + state->negatives->rnum) + 3) & -4; state->precomputed = (uint8_t*)ccmalloc(sizeof(uint8_t) * state->params.feature_size * step); fread(state->precomputed, 1, step * state->params.feature_size, r); fclose(r); } else state->precomputed = 0; snprintf(filename, 1024, "%s/cascade", directory); state->classifier = ccv_icf_read_classifier_cascade(filename); if (!state->classifier) { state->classifier = (ccv_icf_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_classifier_cascade_t)); state->classifier->count = 0; state->classifier->grayscale = state->params.grayscale; state->classifier->weak_classifiers = (ccv_icf_decision_tree_t*)ccmalloc(sizeof(ccv_icf_decision_tree_t) * state->params.weak_classifier); } else { if (state->classifier->count < state->params.weak_classifier) state->classifier->weak_classifiers = (ccv_icf_decision_tree_t*)ccrealloc(state->classifier->weak_classifiers, sizeof(ccv_icf_decision_tree_t) * state->params.weak_classifier); } } #define less_than(s1, s2, aux) ((s1).value < (s2).value) static CCV_IMPLEMENT_QSORT(_ccv_icf_precomputed_ordering, ccv_icf_value_index_t, less_than) #undef less_than static inline void _ccv_icf_3_uint8_to_1_uint1_1_uint23(uint8_t* u8, uint8_t* u1, uint32_t* uint23) { *u1 = (u8[0] >> 7); *uint23 = (((uint32_t)(u8[0] & 0x7f)) << 16) | ((uint32_t)(u8[1]) << 8) | u8[2]; } static inline uint32_t _ccv_icf_3_uint8_to_1_uint23(uint8_t* u8) { return (((uint32_t)(u8[0] & 0x7f)) << 16) | ((uint32_t)(u8[1]) << 8) | u8[2]; } static inline void _ccv_icf_1_uint1_1_uint23_to_3_uint8(uint8_t u1, uint32_t u23, uint8_t* u8) { u8[0] = ((u1 << 7) | (u23 >> 16)) & 0xff; u8[1] = (u23 >> 8) & 0xff; u8[2] = u23 & 0xff; } static float _ccv_icf_run_feature_on_example(ccv_icf_feature_t* feature, ccv_dense_matrix_t* a) { ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); float c = _ccv_icf_run_feature(feature, ptr, sat->cols, ch, 1, 1); ccv_matrix_free(sat); return c; } static uint8_t* _ccv_icf_precompute_features(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives) { int i, j; // we use 3 bytes to represent the sorted index, and compute feature result (float) on fly size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; uint8_t* precomputed = (uint8_t*)ccmalloc(sizeof(uint8_t) * feature_size * step); ccv_icf_value_index_t* sortkv = (ccv_icf_value_index_t*)ccmalloc(sizeof(ccv_icf_value_index_t) * (positives->rnum + negatives->rnum)); printf(" - precompute features using %uM memory temporarily\n", (uint32_t)((sizeof(float) * (positives->rnum + negatives->rnum) * feature_size + sizeof(uint8_t) * feature_size * step) / (1024 * 1024))); float* featval = (float*)ccmalloc(sizeof(float) * feature_size * (positives->rnum + negatives->rnum)); ccv_disable_cache(); // clean up cache so we have enough space to run it #ifdef USE_DISPATCH dispatch_semaphore_t sema = dispatch_semaphore_create(1); dispatch_apply(positives->rnum + negatives->rnum, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i) { #else for (i = 0; i < positives->rnum + negatives->rnum; i++) { #endif #ifdef USE_DISPATCH dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); #endif if (i % 37 == 0 || i == positives->rnum + negatives->rnum - 1) // don't flush too fast FLUSH(" - precompute %d features through %d%% (%d / %d) examples", feature_size, (int)(i + 1) * 100 / (positives->rnum + negatives->rnum), (int)i + 1, positives->rnum + negatives->rnum); #ifdef USE_DISPATCH dispatch_semaphore_signal(sema); int j; #endif ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(i < positives->rnum ? positives : negatives, i < positives->rnum ? i : i - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); for (j = 0; j < feature_size; j++) { ccv_icf_feature_t* feature = features + j; float c = _ccv_icf_run_feature(feature, ptr, sat->cols, ch, 1, 1); assert(isfinite(c)); featval[(size_t)j * (positives->rnum + negatives->rnum) + i] = c; } ccv_matrix_free(sat); #ifdef USE_DISPATCH }); dispatch_release(sema); #else } #endif printf("\n"); uint8_t* computed = precomputed; float* pfeatval = featval; for (i = 0; i < feature_size; i++) { if (i % 37 == 0 || i == feature_size - 1) // don't flush too fast FLUSH(" - precompute %d examples through %d%% (%d / %d) features", positives->rnum + negatives->rnum, (i + 1) * 100 / feature_size, i + 1, feature_size); for (j = 0; j < positives->rnum + negatives->rnum; j++) sortkv[j].value = pfeatval[j], sortkv[j].index = j; _ccv_icf_precomputed_ordering(sortkv, positives->rnum + negatives->rnum, 0); // the first flag denotes if the subsequent one are equal to the previous one (if so, we have to skip both of them) for (j = 0; j < positives->rnum + negatives->rnum - 1; j++) _ccv_icf_1_uint1_1_uint23_to_3_uint8(sortkv[j].value == sortkv[j + 1].value, sortkv[j].index, computed + j * 3); j = positives->rnum + negatives->rnum - 1; _ccv_icf_1_uint1_1_uint23_to_3_uint8(0, sortkv[j].index, computed + j * 3); computed += step; pfeatval += positives->rnum + negatives->rnum; } ccfree(featval); ccfree(sortkv); printf("\n - features are precomputed on examples and will occupy %uM memory\n", (uint32_t)((feature_size * step) / (1024 * 1024))); return precomputed; } typedef struct { uint32_t pass; double weigh[4]; int first_feature; uint8_t* lut; } ccv_icf_decision_tree_cache_t; static inline float _ccv_icf_compute_threshold_between(ccv_icf_feature_t* feature, uint8_t* computed, ccv_array_t* positives, ccv_array_t* negatives, int index0, int index1) { float c[2]; uint32_t b[2] = { _ccv_icf_3_uint8_to_1_uint23(computed + index0 * 3), _ccv_icf_3_uint8_to_1_uint23(computed + index1 * 3), }; ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(b[0] < positives->rnum ? positives : negatives, b[0] < positives->rnum ? b[0] : b[0] - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place c[0] = _ccv_icf_run_feature_on_example(feature, a); a = (ccv_dense_matrix_t*)ccv_array_get(b[1] < positives->rnum ? positives : negatives, b[1] < positives->rnum ? b[1] : b[1] - positives->rnum); a->data.u8 = (unsigned char*)(a + 1); // re-host the pointer to the right place c[1] = _ccv_icf_run_feature_on_example(feature, a); return (c[0] + c[1]) * 0.5; } static inline void _ccv_icf_example_correct(ccv_icf_example_state_t* example_state, uint8_t* computed, uint8_t* lut, int leaf, ccv_array_t* positives, ccv_array_t* negatives, int start, int end) { int i; for (i = start; i <= end; i++) { uint32_t index = _ccv_icf_3_uint8_to_1_uint23(computed + i * 3); if (!lut || lut[index] == leaf) example_state[index].correct = (index < positives->rnum); } } typedef struct { int error_index; double error_rate; double weigh[2]; int count[2]; } ccv_icf_first_feature_find_t; static ccv_icf_decision_tree_cache_t _ccv_icf_find_first_feature(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_feature_t* feature) { int i; assert(feature != 0); ccv_icf_decision_tree_cache_t intermediate_cache; double aweigh0 = 0, aweigh1 = 0; for (i = 0; i < positives->rnum; i++) aweigh1 += example_state[i].weight, example_state[i].correct = 0; // assuming positive examples we get wrong for (i = positives->rnum; i < positives->rnum + negatives->rnum; i++) aweigh0 += example_state[i].weight, example_state[i].correct = 1; // assuming negative examples we get right size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; ccv_icf_first_feature_find_t* feature_find = (ccv_icf_first_feature_find_t*)ccmalloc(sizeof(ccv_icf_first_feature_find_t) * feature_size); parallel_for(i, feature_size) { ccv_icf_first_feature_find_t min_find = { .error_rate = 1.0, .error_index = 0, .weigh = {0, 0}, .count = {0, 0}, }; double weigh[2] = {0, 0}; int count[2] = {0, 0}; int j; uint8_t* computed = precomputed + step * i; for (j = 0; j < positives->rnum + negatives->rnum; j++) { uint8_t skip; uint32_t index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &index); conditional_assert(j == positives->rnum + negatives->rnum - 1, !skip); assert(index >= 0 && index < positives->rnum + negatives->rnum); weigh[index < positives->rnum] += example_state[index].weight; assert(example_state[index].weight > 0); assert(weigh[0] <= aweigh0 + 1e-10 && weigh[1] <= aweigh1 + 1e-10); ++count[index < positives->rnum]; if (skip) // the current index is equal to the next one, we cannot differentiate, therefore, skip continue; double error_rate = ccv_min(weigh[0] + aweigh1 - weigh[1], weigh[1] + aweigh0 - weigh[0]); assert(error_rate > 0); if (error_rate < min_find.error_rate) { min_find.error_index = j; min_find.error_rate = error_rate; min_find.weigh[0] = weigh[0]; min_find.weigh[1] = weigh[1]; min_find.count[0] = count[0]; min_find.count[1] = count[1]; } } feature_find[i] = min_find; } parallel_endfor ccv_icf_first_feature_find_t best = { .error_rate = 1.0, .error_index = -1, .weigh = {0, 0}, .count = {0, 0}, }; int feature_index = 0; for (i = 0; i < feature_size; i++) if (feature_find[i].error_rate < best.error_rate) { best = feature_find[i]; feature_index = i; } ccfree(feature_find); *feature = features[feature_index]; uint8_t* computed = precomputed + step * feature_index; intermediate_cache.lut = (uint8_t*)ccmalloc(positives->rnum + negatives->rnum); assert(best.error_index < positives->rnum + negatives->rnum - 1 && best.error_index >= 0); if (best.weigh[0] + aweigh1 - best.weigh[1] < best.weigh[1] + aweigh0 - best.weigh[0]) { for (i = 0; i < positives->rnum + negatives->rnum; i++) intermediate_cache.lut[_ccv_icf_3_uint8_to_1_uint23(computed + i * 3)] = (i <= best.error_index); feature->beta = _ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // revert the sign of alpha, after threshold is computed for (i = 0; i < feature->count; i++) feature->alpha[i] = -feature->alpha[i]; intermediate_cache.weigh[0] = aweigh0 - best.weigh[0]; intermediate_cache.weigh[1] = aweigh1 - best.weigh[1]; intermediate_cache.weigh[2] = best.weigh[0]; intermediate_cache.weigh[3] = best.weigh[1]; intermediate_cache.pass = 3; if (best.count[0] == 0) intermediate_cache.pass &= 2; // only positive examples in the right, no need to build right leaf if (best.count[1] == positives->rnum) intermediate_cache.pass &= 1; // no positive examples in the left, no need to build left leaf if (!(intermediate_cache.pass & 1)) // mark positives in the right as correct, if we don't have right leaf _ccv_icf_example_correct(example_state, computed, 0, 0, positives, negatives, 0, best.error_index); } else { for (i = 0; i < positives->rnum + negatives->rnum; i++) intermediate_cache.lut[_ccv_icf_3_uint8_to_1_uint23(computed + i * 3)] = (i > best.error_index); feature->beta = -_ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); intermediate_cache.weigh[0] = best.weigh[0]; intermediate_cache.weigh[1] = best.weigh[1]; intermediate_cache.weigh[2] = aweigh0 - best.weigh[0]; intermediate_cache.weigh[3] = aweigh1 - best.weigh[1]; intermediate_cache.pass = 3; if (best.count[0] == negatives->rnum) intermediate_cache.pass &= 2; // only positive examples in the right, no need to build right leaf if (best.count[1] == 0) intermediate_cache.pass &= 1; // no positive examples in the left, no need to build left leaf if (!(intermediate_cache.pass & 1)) // mark positives in the right as correct if we don't have right leaf _ccv_icf_example_correct(example_state, computed, 0, 0, positives, negatives, best.error_index + 1, positives->rnum + negatives->rnum - 1); } intermediate_cache.first_feature = feature_index; return intermediate_cache; } typedef struct { int error_index; double error_rate; double weigh[2]; } ccv_icf_second_feature_find_t; static double _ccv_icf_find_second_feature(ccv_icf_decision_tree_cache_t intermediate_cache, int leaf, ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_feature_t* feature) { size_t step = (3 * (positives->rnum + negatives->rnum) + 3) & -4; uint8_t* lut = intermediate_cache.lut; double* aweigh = intermediate_cache.weigh + leaf * 2; ccv_icf_second_feature_find_t* feature_find = (ccv_icf_second_feature_find_t*)ccmalloc(sizeof(ccv_icf_second_feature_find_t) * feature_size); parallel_for(i, feature_size) { ccv_icf_second_feature_find_t min_find = { .error_rate = 1.0, .error_index = 0, .weigh = {0, 0}, }; double weigh[2] = {0, 0}; uint8_t* computed = precomputed + step * i; int j, k; for (j = 0; j < positives->rnum + negatives->rnum; j++) { uint8_t skip; uint32_t index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &index); conditional_assert(j == positives->rnum + negatives->rnum - 1, !skip); assert(index >= 0 && index < positives->rnum + negatives->rnum); // only care about part of the data if (lut[index] == leaf) { uint8_t leaf_skip = 0; for (k = j + 1; skip; k++) { uint32_t new_index; _ccv_icf_3_uint8_to_1_uint1_1_uint23(computed + j * 3, &skip, &new_index); // if the next equal one is the same leaf, we cannot distinguish them, skip if ((leaf_skip = (lut[new_index] == leaf))) break; conditional_assert(k == positives->rnum + negatives->rnum - 1, !skip); } weigh[index < positives->rnum] += example_state[index].weight; if (leaf_skip) continue; assert(example_state[index].weight > 0); assert(weigh[0] <= aweigh[0] + 1e-10 && weigh[1] <= aweigh[1] + 1e-10); double error_rate = ccv_min(weigh[0] + aweigh[1] - weigh[1], weigh[1] + aweigh[0] - weigh[0]); if (error_rate < min_find.error_rate) { min_find.error_index = j; min_find.error_rate = error_rate; min_find.weigh[0] = weigh[0]; min_find.weigh[1] = weigh[1]; } } } feature_find[i] = min_find; } parallel_endfor ccv_icf_second_feature_find_t best = { .error_rate = 1.0, .error_index = -1, .weigh = {0, 0}, }; int i; int feature_index = 0; for (i = 0; i < feature_size; i++) if (feature_find[i].error_rate < best.error_rate) { best = feature_find[i]; feature_index = i; } ccfree(feature_find); *feature = features[feature_index]; uint8_t* computed = precomputed + step * feature_index; assert(best.error_index < positives->rnum + negatives->rnum - 1 && best.error_index >= 0); if (best.weigh[0] + aweigh[1] - best.weigh[1] < best.weigh[1] + aweigh[0] - best.weigh[0]) { feature->beta = _ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // revert the sign of alpha, after threshold is computed for (i = 0; i < feature->count; i++) feature->alpha[i] = -feature->alpha[i]; // mark everything on the right properly _ccv_icf_example_correct(example_state, computed, lut, leaf, positives, negatives, 0, best.error_index); return best.weigh[1] + aweigh[0] - best.weigh[0]; } else { feature->beta = -_ccv_icf_compute_threshold_between(feature, computed, positives, negatives, best.error_index, best.error_index + 1); // mark everything on the right properly _ccv_icf_example_correct(example_state, computed, lut, leaf, positives, negatives, best.error_index + 1, positives->rnum + negatives->rnum - 1); return best.weigh[0] + aweigh[1] - best.weigh[1]; } } static double _ccv_icf_find_best_weak_classifier(ccv_icf_feature_t* features, int feature_size, ccv_array_t* positives, ccv_array_t* negatives, uint8_t* precomputed, ccv_icf_example_state_t* example_state, ccv_icf_decision_tree_t* weak_classifier) { // we are building the specific depth-2 decision tree ccv_icf_decision_tree_cache_t intermediate_cache = _ccv_icf_find_first_feature(features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features); // find the left feature // for the pass, 10 is the left branch, 01 is the right branch weak_classifier->pass = intermediate_cache.pass; double rate = 0; if (weak_classifier->pass & 0x2) rate += _ccv_icf_find_second_feature(intermediate_cache, 0, features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features + 1); else rate += intermediate_cache.weigh[0]; // the negative weights covered by first feature // find the right feature if (weak_classifier->pass & 0x1) rate += _ccv_icf_find_second_feature(intermediate_cache, 1, features, feature_size, positives, negatives, precomputed, example_state, weak_classifier->features + 2); else rate += intermediate_cache.weigh[3]; // the positive weights covered by first feature ccfree(intermediate_cache.lut); return rate; } static ccv_array_t* _ccv_icf_collect_validates(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* validatefiles, int grayscale) { ccv_array_t* validates = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), validatefiles->rnum, 0); int i; // collect tests for (i = 0; i < validatefiles->rnum; i++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(validatefiles, i); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, file_info->pose, size, margin, 0, 0, 0); feature->sig = 0; ccv_array_push(validates, feature); ccv_matrix_free(feature); ccv_matrix_free(image); } return validates; } static ccv_array_t* _ccv_icf_collect_positives(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* posfiles, int posnum, float deform_angle, float deform_scale, float deform_shift, int grayscale) { ccv_array_t* positives = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), posnum, 0); int i, j, q; // collect positives (with random deformation) for (i = 0; i < posnum;) { FLUSH(" - collect positives %d%% (%d / %d)", (i + 1) * 100 / posnum, i + 1, posnum); double ratio = (double)(posnum - i) / posfiles->rnum; for (j = 0; j < posfiles->rnum && i < posnum; j++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(posfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } for (q = 0; q < ratio; q++) if (q < (int)ratio || gsl_rng_uniform(rng) <= ratio - (int)ratio) { FLUSH(" - collect positives %d%% (%d / %d)", (i + 1) * 100 / posnum, i + 1, posnum); ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, file_info->pose, size, margin, deform_angle, deform_scale, deform_shift); feature->sig = 0; ccv_array_push(positives, feature); ccv_matrix_free(feature); ++i; if (i >= posnum) break; } ccv_matrix_free(image); } } printf("\n"); return positives; } static uint64_t* _ccv_icf_precompute_classifier_cascade(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* positives) { int step = ((cascade->count - 1) >> 6) + 1; uint64_t* precomputed = (uint64_t*)ccmalloc(sizeof(uint64_t) * positives->rnum * step); uint64_t* result = precomputed; int i, j; for (i = 0; i < positives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)(ccv_array_get(positives, i)); a->data.u8 = (uint8_t*)(a + 1); ccv_dense_matrix_t* icf = 0; ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); for (j = 0; j < cascade->count; j++) if (_ccv_icf_run_weak_classifier(cascade->weak_classifiers + j, ptr, sat->cols, ch, 1, 1)) precomputed[j >> 6] |= (1UL << (j & 63)); else precomputed[j >> 6] &= ~(1UL << (j & 63)); ccv_matrix_free(sat); precomputed += step; } return result; } #define less_than(s1, s2, aux) ((s1) > (s2)) static CCV_IMPLEMENT_QSORT(_ccv_icf_threshold_rating, float, less_than) #undef less_than static void _ccv_icf_classifier_cascade_soft_with_validates(ccv_array_t* validates, ccv_icf_classifier_cascade_t* cascade, double min_accept) { int i, j; int step = ((cascade->count - 1) >> 6) + 1; uint64_t* precomputed = _ccv_icf_precompute_classifier_cascade(cascade, validates); float* positive_rate = (float*)ccmalloc(sizeof(float) * validates->rnum); uint64_t* computed = precomputed; for (i = 0; i < validates->rnum; i++) { positive_rate[i] = 0; for (j = 0; j < cascade->count; j++) { uint64_t accept = computed[j >> 6] & (1UL << (j & 63)); positive_rate[i] += cascade->weak_classifiers[j].weigh[!!accept]; } computed += step; } _ccv_icf_threshold_rating(positive_rate, validates->rnum, 0); float threshold = positive_rate[ccv_min((int)(min_accept * (validates->rnum + 0.5) - 0.5), validates->rnum - 1)]; ccfree(positive_rate); computed = precomputed; // compute the final acceptance per validates / negatives with final threshold uint64_t* acceptance = (uint64_t*)cccalloc(((validates->rnum - 1) >> 6) + 1, sizeof(uint64_t)); int true_positives = 0; for (i = 0; i < validates->rnum; i++) { float rate = 0; for (j = 0; j < cascade->count; j++) { uint64_t accept = computed[j >> 6] & (1UL << (j & 63)); rate += cascade->weak_classifiers[j].weigh[!!accept]; } if (rate >= threshold) { acceptance[i >> 6] |= (1UL << (i & 63)); ++true_positives; } else acceptance[i >> 6] &= ~(1UL << (i & 63)); computed += step; } printf(" - at threshold %f, true positive rate: %f%%\n", threshold, (float)true_positives * 100 / validates->rnum); float* rate = (float*)cccalloc(validates->rnum, sizeof(float)); for (j = 0; j < cascade->count; j++) { computed = precomputed; for (i = 0; i < validates->rnum; i++) { uint64_t correct = computed[j >> 6] & (1UL << (j & 63)); rate[i] += cascade->weak_classifiers[j].weigh[!!correct]; computed += step; } float threshold = FLT_MAX; // find a threshold that keeps all accepted validates still acceptable for (i = 0; i < validates->rnum; i++) { uint64_t correct = acceptance[i >> 6] & (1UL << (i & 63)); if (correct && rate[i] < threshold) threshold = rate[i]; } cascade->weak_classifiers[j].threshold = threshold - 1e-10; } ccfree(rate); ccfree(acceptance); ccfree(precomputed); } typedef struct { ccv_point_t point; float sum; } ccv_point_with_sum_t; static void _ccv_icf_bootstrap_negatives(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* negatives, gsl_rng* rng, ccv_array_t* bgfiles, int negnum, int grayscale, int spread, ccv_icf_param_t params) { #ifdef USE_DISPATCH __block int i; #else int i; #endif #ifdef USE_DISPATCH __block int fppi = 0, is = 0; #else int fppi = 0, is = 0; #endif int t = 0; for (i = 0; i < negnum;) { double ratio = (double)(negnum - i) / bgfiles->rnum; #ifdef USE_DISPATCH dispatch_semaphore_t sem = dispatch_semaphore_create(1); dispatch_apply(bgfiles->rnum, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t j) { #else size_t j; for (j = 0; j < bgfiles->rnum; j++) { #endif int k, x, y, q, p; ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccmalloc(ccv_compute_dense_matrix_size(cascade->size.height + 2, cascade->size.width + 2, (grayscale ? CCV_C1 : CCV_C3) | CCV_8U)); #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i >= negnum || (spread && ratio < 1 && gsl_rng_uniform(rng) > ratio)) { ccfree(a); #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); return; #else continue; #endif } FLUSH(" - bootstrap negatives %d%% (%d / %d) [%u / %d] %s", (i + 1) * 100 / negnum, i + 1, negnum, (uint32_t)(j + 1), bgfiles->rnum, spread ? "" : "without statistic balancing"); #ifdef USE_DISPATCH gsl_rng* crng = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(crng, gsl_rng_get(rng)); dispatch_semaphore_signal(sem); #else gsl_rng* crng = rng; #endif ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(bgfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); return; #else continue; #endif } if (ccv_max(image->rows, image->cols) < 800 || image->rows <= (cascade->size.height - cascade->margin.top - cascade->margin.bottom) || image->cols <= (cascade->size.width - cascade->margin.left - cascade->margin.right)) // background is too small, blow it up to next scale { ccv_dense_matrix_t* blowup = 0; ccv_sample_up(image, &blowup, 0, 0, 0); ccv_matrix_free(image); image = blowup; } if (image->rows <= (cascade->size.height - cascade->margin.top - cascade->margin.bottom) || image->cols <= (cascade->size.width - cascade->margin.left - cascade->margin.right)) // background is still too small, abort { ccv_matrix_free(image); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); return; #else continue; #endif } double scale = pow(2., 1. / (params.interval + 1.)); int next = params.interval + 1; int scale_upto = (int)(log(ccv_min((double)image->rows / (cascade->size.height - cascade->margin.top - cascade->margin.bottom), (double)image->cols / (cascade->size.width - cascade->margin.left - cascade->margin.right))) / log(scale) - DBL_MIN) + 1; ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)ccmalloc(scale_upto * sizeof(ccv_dense_matrix_t*)); memset(pyr, 0, scale_upto * sizeof(ccv_dense_matrix_t*)); #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif ++is; // how many images are scanned #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif if (t % 2 != 0) ccv_flip(image, 0, 0, CCV_FLIP_X); if (t % 4 >= 2) ccv_flip(image, 0, 0, CCV_FLIP_Y); pyr[0] = image; for (q = 1; q < ccv_min(params.interval + 1, scale_upto); q++) ccv_resample(pyr[0], &pyr[q], 0, (int)(pyr[0]->rows / pow(scale, q)), (int)(pyr[0]->cols / pow(scale, q)), CCV_INTER_AREA); for (q = next; q < scale_upto; q++) ccv_sample_down(pyr[q - next], &pyr[q], 0, 0, 0); for (q = 0; q < scale_upto; q++) { #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i >= negnum) { #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif ccv_matrix_free(pyr[q]); continue; } #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif ccv_dense_matrix_t* bordered = 0; ccv_border(pyr[q], (ccv_matrix_t**)&bordered, 0, cascade->margin); ccv_matrix_free(pyr[q]); ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); assert(sat->rows == bordered->rows + 1 && sat->cols == bordered->cols + 1); int ch = CCV_GET_CHANNEL(sat->type); float* ptr = sat->data.f32 + sat->cols * ch; ccv_array_t* seq = ccv_array_new(sizeof(ccv_point_with_sum_t), 64, 0); for (y = 1; y < sat->rows - cascade->size.height - 2; y += params.step_through) { for (x = 1; x < sat->cols - cascade->size.width - 2; x += params.step_through) { int pass = 1; float sum = 0; for (p = 0; p < cascade->count; p++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + p; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, x, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_point_with_sum_t point; point.point = ccv_point(x - 1, y - 1); point.sum = sum; ccv_array_push(seq, &point); } } ptr += sat->cols * ch * params.step_through; } ccv_matrix_free(sat); // shuffle negatives so that we don't have too biased negatives #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif fppi += seq->rnum; // how many detections we have in total #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif if (seq->rnum > 0) { gsl_ran_shuffle(crng, ccv_array_get(seq, 0), seq->rnum, seq->rsize); /* so that we at least collect 10 from each scale */ for (p = 0; p < (spread ? ccv_min(10, seq->rnum) : seq->rnum); p++) // collect enough negatives from this scale { a = ccv_dense_matrix_new(cascade->size.height + 2, cascade->size.width + 2, (grayscale ? CCV_C1 : CCV_C3) | CCV_8U, a, 0); ccv_point_with_sum_t* point = (ccv_point_with_sum_t*)ccv_array_get(seq, p); ccv_slice(bordered, (ccv_matrix_t**)&a, 0, point->point.y, point->point.x, a->rows, a->cols); assert(bordered->rows >= point->point.y + a->rows && bordered->cols >= point->point.x + a->cols); a->sig = 0; // verify the data we sliced is worthy negative ccv_dense_matrix_t* icf = 0; ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); int pass = 1; float sum = 0; for (k = 0; k < cascade->count; k++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + k; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } ccv_matrix_free(sat); if (pass) { #ifdef USE_DISPATCH dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); #endif if (i < negnum) ccv_array_push(negatives, a); ++i; if (i >= negnum) { #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif break; } #ifdef USE_DISPATCH dispatch_semaphore_signal(sem); #endif } } } ccv_array_free(seq); ccv_matrix_free(bordered); } ccfree(pyr); ccfree(a); #ifdef USE_DISPATCH gsl_rng_free(crng); }); dispatch_release(sem); #else } #endif if ((double)fppi / is <= (double)negnum / bgfiles->rnum) // if the targeted negative per image is bigger than our fppi, we don't prob anymore spread = 0; ++t; if (t > (spread ? 4 : 3) && !spread) // we've go over 4 or 3 transformations (original, flip x, flip y, flip x & y, [and original again]), and nothing we can do now break; } printf("\n"); } static ccv_array_t* _ccv_icf_collect_negatives(gsl_rng* rng, ccv_size_t size, ccv_margin_t margin, ccv_array_t* bgfiles, int negnum, float deform_angle, float deform_scale, float deform_shift, int grayscale) { ccv_array_t* negatives = ccv_array_new(ccv_compute_dense_matrix_size(size.height + margin.top + margin.bottom + 2, size.width + margin.left + margin.right + 2, CCV_8U | (grayscale ? CCV_C1 : CCV_C3)), negnum, 0); int i, j, q; // randomly collect negatives (with random deformation) for (i = 0; i < negnum;) { FLUSH(" - collect negatives %d%% (%d / %d)", (i + 1) * 100 / negnum, i + 1, negnum); double ratio = (double)(negnum - i) / bgfiles->rnum; for (j = 0; j < bgfiles->rnum && i < negnum; j++) { ccv_file_info_t* file_info = (ccv_file_info_t*)ccv_array_get(bgfiles, j); ccv_dense_matrix_t* image = 0; ccv_read(file_info->filename, &image, CCV_IO_ANY_FILE | (grayscale ? CCV_IO_GRAY : CCV_IO_RGB_COLOR)); if (image == 0) { printf("\n - %s: cannot be open, possibly corrupted\n", file_info->filename); continue; } double max_scale_ratio = ccv_min((double)image->rows / size.height, (double)image->cols / size.width); if (max_scale_ratio <= 0.5) // too small to be interesting continue; for (q = 0; q < ratio; q++) if (q < (int)ratio || gsl_rng_uniform(rng) <= ratio - (int)ratio) { FLUSH(" - collect negatives %d%% (%d / %d)", (i + 1) * 100 / negnum, i + 1, negnum); ccv_decimal_pose_t pose; double scale_ratio = gsl_rng_uniform(rng) * (max_scale_ratio - 0.5) + 0.5; pose.a = size.width * 0.5 * scale_ratio; pose.b = size.height * 0.5 * scale_ratio; pose.x = gsl_rng_uniform_int(rng, ccv_max((int)(image->cols - pose.a * 2 + 1.5), 1)) + pose.a; pose.y = gsl_rng_uniform_int(rng, ccv_max((int)(image->rows - pose.b * 2 + 1.5), 1)) + pose.b; pose.roll = pose.pitch = pose.yaw = 0; ccv_dense_matrix_t* feature = _ccv_icf_capture_feature(rng, image, pose, size, margin, deform_angle, deform_scale, deform_shift); feature->sig = 0; ccv_array_push(negatives, feature); ccv_matrix_free(feature); ++i; if (i >= negnum) break; } ccv_matrix_free(image); } } printf("\n"); return negatives; } #ifdef USE_SANITY_ASSERTION static double _ccv_icf_rate_weak_classifier(ccv_icf_decision_tree_t* weak_classifier, ccv_array_t* positives, ccv_array_t* negatives, ccv_icf_example_state_t* example_state) { int i; double rate = 0; for (i = 0; i < positives->rnum + negatives->rnum; i++) { ccv_dense_matrix_t* a = (ccv_dense_matrix_t*)ccv_array_get(i < positives->rnum ? positives : negatives, i < positives->rnum ? i : i - positives->rnum); a->data.u8 = (uint8_t*)(a + 1); // re-host the pointer to the right place ccv_dense_matrix_t* icf = 0; // we have 1px padding around the image ccv_icf(a, &icf, 0); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); float* ptr = sat->data.f32; int ch = CCV_GET_CHANNEL(sat->type); if (i < positives->rnum) { if (_ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1)) { assert(example_state[i].correct); rate += example_state[i].weight; } else { assert(!example_state[i].correct); } } else { if (!_ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, 1, 1)) { assert(example_state[i].correct); rate += example_state[i].weight; } else { assert(!example_state[i].correct); } } ccv_matrix_free(sat); } return rate; } #endif #endif ccv_icf_classifier_cascade_t* ccv_icf_classifier_cascade_new(ccv_array_t* posfiles, int posnum, ccv_array_t* bgfiles, int negnum, ccv_array_t* validatefiles, const char* dir, ccv_icf_new_param_t params) { #ifdef HAVE_GSL _ccv_icf_check_params(params); assert(posfiles->rnum > 0); assert(bgfiles->rnum > 0); assert(posnum > 0 && negnum > 0); printf("with %d positive examples and %d negative examples\n" "positive examples are going to be collected from %d positive images\n" "negative examples are are going to be collected from %d background images\n", posnum, negnum, posfiles->rnum, bgfiles->rnum); printf("use color? %s\n", params.grayscale ? "no" : "yes"); printf("feature pool size : %d\n" "weak classifier count : %d\n" "soft cascade acceptance : %lf\n" "minimum dimension of ICF feature : %d\n" "number of bootstrap : %d\n" "distortion on translation : %f\n" "distortion on rotation : %f\n" "distortion on scale : %f\n" "learn ICF classifier cascade at size %dx%d with margin (%d,%d,%d,%d)\n" "------------------------\n", params.feature_size, params.weak_classifier, params.acceptance, params.min_dimension, params.bootstrap, params.deform_shift, params.deform_angle, params.deform_scale, params.size.width, params.size.height, params.margin.left, params.margin.top, params.margin.right, params.margin.bottom); gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); // we will keep all states inside this structure for easier save / resume across process // this should work better than ad-hoc one we used in DPM / BBF implementation ccv_icf_classifier_cascade_state_t z; z.params = params; ccv_function_state_begin(_ccv_icf_read_classifier_cascade_state, z, dir); z.classifier->grayscale = params.grayscale; z.size = params.size; z.margin = params.margin; z.classifier->size = ccv_size(z.size.width + z.margin.left + z.margin.right, z.size.height + z.margin.top + z.margin.bottom); z.features = (ccv_icf_feature_t*)ccmalloc(sizeof(ccv_icf_feature_t) * params.feature_size); // generate random features for (z.i = 0; z.i < params.feature_size; z.i++) _ccv_icf_randomize_feature(rng, z.classifier->size, params.min_dimension, z.features + z.i, params.grayscale); z.x.features = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.positives = _ccv_icf_collect_positives(rng, z.size, z.margin, posfiles, posnum, params.deform_angle, params.deform_scale, params.deform_shift, params.grayscale); z.x.positives = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.negatives = _ccv_icf_collect_negatives(rng, z.size, z.margin, bgfiles, negnum, params.deform_angle, params.deform_scale, params.deform_shift, params.grayscale); z.x.negatives = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); for (z.bootstrap = 0; z.bootstrap <= params.bootstrap; z.bootstrap++) { z.example_state = (ccv_icf_example_state_t*)ccmalloc(sizeof(ccv_icf_example_state_t) * (z.negatives->rnum + z.positives->rnum)); memset(z.example_state, 0, sizeof(ccv_icf_example_state_t) * (z.negatives->rnum + z.positives->rnum)); for (z.i = 0; z.i < z.positives->rnum + z.negatives->rnum; z.i++) z.example_state[z.i].weight = (z.i < z.positives->rnum) ? 0.5 / z.positives->rnum : 0.5 / z.negatives->rnum; z.x.example_state = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); z.precomputed = _ccv_icf_precompute_features(z.features, params.feature_size, z.positives, z.negatives); z.x.precomputed = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); for (z.i = 0; z.i < params.weak_classifier; z.i++) { z.classifier->count = z.i + 1; printf(" - boost weak classifier %d of %d\n", z.i + 1, params.weak_classifier); int j; ccv_icf_decision_tree_t weak_classifier; double rate = _ccv_icf_find_best_weak_classifier(z.features, params.feature_size, z.positives, z.negatives, z.precomputed, z.example_state, &weak_classifier); assert(rate > 0.5); // it has to be better than random chance #ifdef USE_SANITY_ASSERTION double confirm_rate = _ccv_icf_rate_weak_classifier(&weak_classifier, z.positives, z.negatives, z.example_state); #endif double alpha = sqrt((1 - rate) / rate); double beta = 1.0 / alpha; double c = log(rate / (1 - rate)); weak_classifier.weigh[0] = -c; weak_classifier.weigh[1] = c; weak_classifier.threshold = 0; double reweigh = 0; for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++) { z.example_state[j].weight *= (z.example_state[j].correct) ? alpha : beta; z.example_state[j].rate += weak_classifier.weigh[!((j < z.positives->rnum) ^ z.example_state[j].correct)]; reweigh += z.example_state[j].weight; } reweigh = 1.0 / reweigh; #ifdef USE_SANITY_ASSERTION printf(" - on all examples, best feature at rate %lf, confirm rate %lf\n", rate, confirm_rate); #else printf(" - on all examples, best feature at rate %lf\n", rate); #endif // balancing the weight to sum 1.0 for (j = 0; j < z.positives->rnum + z.negatives->rnum; j++) z.example_state[j].weight *= reweigh; z.classifier->weak_classifiers[z.i] = weak_classifier; // compute the threshold at given acceptance float threshold = z.example_state[0].rate; for (j = 1; j < z.positives->rnum; j++) if (z.example_state[j].rate < threshold) threshold = z.example_state[j].rate; int true_positives = 0, false_positives = 0; for (j = 0; j < z.positives->rnum; j++) if (z.example_state[j].rate >= threshold) ++true_positives; for (j = z.positives->rnum; j < z.positives->rnum + z.negatives->rnum; j++) if (z.example_state[j].rate >= threshold) ++false_positives; printf(" - at threshold %f, true positive rate: %f%%, false positive rate: %f%% (%d)\n", threshold, (float)true_positives * 100 / z.positives->rnum, (float)false_positives * 100 / z.negatives->rnum, false_positives); printf(" - first feature :\n"); for (j = 0; j < weak_classifier.features[0].count; j++) printf(" - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[0].channel[j], weak_classifier.features[0].sat[j * 2].x, weak_classifier.features[0].sat[j * 2].y, weak_classifier.features[0].sat[j * 2 + 1].x, weak_classifier.features[0].sat[j * 2 + 1].y); if (weak_classifier.pass & 0x2) { printf(" - second feature, on left :\n"); for (j = 0; j < weak_classifier.features[1].count; j++) printf(" - | - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[1].channel[j], weak_classifier.features[1].sat[j * 2].x, weak_classifier.features[1].sat[j * 2].y, weak_classifier.features[1].sat[j * 2 + 1].x, weak_classifier.features[1].sat[j * 2 + 1].y); } if (weak_classifier.pass & 0x1) { printf(" - second feature, on right :\n"); for (j = 0; j < weak_classifier.features[2].count; j++) printf(" - | - %d - (%d, %d) - (%d, %d)\n", weak_classifier.features[2].channel[j], weak_classifier.features[2].sat[j * 2].x, weak_classifier.features[2].sat[j * 2].y, weak_classifier.features[2].sat[j * 2 + 1].x, weak_classifier.features[2].sat[j * 2 + 1].y); } z.classifier->count = z.i + 1; // update count z.classifier->size = ccv_size(z.size.width + z.margin.left + z.margin.right, z.size.height + z.margin.top + z.margin.bottom); z.classifier->margin = z.margin; if (z.i + 1 < params.weak_classifier) { z.x.example_state = 0; z.x.classifier = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); } } if (z.bootstrap < params.bootstrap) // collecting negatives, again { // free expensive memory ccfree(z.example_state); z.example_state = 0; ccfree(z.precomputed); z.precomputed = 0; _ccv_icf_classifier_cascade_soft_with_validates(z.positives, z.classifier, 1); // assuming perfect score, what's the soft cascading will be int exists = z.negatives->rnum; int spread_policy = z.bootstrap < 2; // we don't spread bootstrapping anymore after the first two bootstrappings // try to boostrap half negatives from perfect scoring _ccv_icf_bootstrap_negatives(z.classifier, z.negatives, rng, bgfiles, (negnum + 1) / 2, params.grayscale, spread_policy, params.detector); int leftover = negnum - (z.negatives->rnum - exists); if (leftover > 0) { // if we cannot get enough negative examples, now will use the validates data set to extract more ccv_array_t* validates = _ccv_icf_collect_validates(rng, z.size, z.margin, validatefiles, params.grayscale); _ccv_icf_classifier_cascade_soft_with_validates(validates, z.classifier, params.acceptance); ccv_array_free(validates); _ccv_icf_bootstrap_negatives(z.classifier, z.negatives, rng, bgfiles, leftover, params.grayscale, spread_policy, params.detector); } printf(" - after %d bootstrapping, learn with %d positives and %d negatives\n", z.bootstrap + 1, z.positives->rnum, z.negatives->rnum); z.classifier->count = 0; // reset everything z.x.negatives = 0; } else { z.x.example_state = 0; z.x.classifier = 0; ccv_function_state_resume(_ccv_icf_write_classifier_cascade_state, z, dir); } } if (z.precomputed) ccfree(z.precomputed); if (z.example_state) ccfree(z.example_state); ccfree(z.features); ccv_array_free(z.positives); ccv_array_free(z.negatives); gsl_rng_free(rng); ccv_function_state_finish(); return z.classifier; #else assert(0 && "ccv_icf_classifier_cascade_new requires GSL library support"); return 0; #endif } void ccv_icf_classifier_cascade_soft(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* posfiles, double acceptance) { #ifdef HAVE_GSL printf("with %d positive examples\n" "going to accept %.2lf%% positive examples\n", posfiles->rnum, acceptance * 100); ccv_size_t size = ccv_size(cascade->size.width - cascade->margin.left - cascade->margin.right, cascade->size.height - cascade->margin.top - cascade->margin.bottom); printf("use color? %s\n", cascade->grayscale ? "no" : "yes"); printf("compute soft cascading thresholds for ICF classifier cascade at size %dx%d with margin (%d,%d,%d,%d)\n" "------------------------\n", size.width, size.height, cascade->margin.left, cascade->margin.top, cascade->margin.right, cascade->margin.bottom); gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); /* collect positives */ double weigh[2] = { 0, 0 }; int i; for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; weigh[0] += weak_classifier->weigh[0]; weigh[1] += weak_classifier->weigh[1]; } weigh[0] = 1 / fabs(weigh[0]), weigh[1] = 1 / fabs(weigh[1]); for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; weak_classifier->weigh[0] = weak_classifier->weigh[0] * weigh[0]; weak_classifier->weigh[1] = weak_classifier->weigh[1] * weigh[1]; } ccv_array_t* validates = _ccv_icf_collect_validates(rng, size, cascade->margin, posfiles, cascade->grayscale); /* compute soft cascading thresholds */ _ccv_icf_classifier_cascade_soft_with_validates(validates, cascade, acceptance); ccv_array_free(validates); gsl_rng_free(rng); #else assert(0 && "ccv_icf_classifier_cascade_soft requires GSL library support"); #endif } static void _ccv_icf_read_classifier_cascade_with_fd(FILE* r, ccv_icf_classifier_cascade_t* cascade) { cascade->type = CCV_ICF_CLASSIFIER_TYPE_A; fscanf(r, "%d %d %d %d", &cascade->count, &cascade->size.width, &cascade->size.height, &cascade->grayscale); fscanf(r, "%d %d %d %d", &cascade->margin.left, &cascade->margin.top, &cascade->margin.right, &cascade->margin.bottom); cascade->weak_classifiers = (ccv_icf_decision_tree_t*)ccmalloc(sizeof(ccv_icf_decision_tree_t) * cascade->count); int i, q; for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; fscanf(r, "%u %a %a %a", &weak_classifier->pass, &weak_classifier->weigh[0], &weak_classifier->weigh[1], &weak_classifier->threshold); fscanf(r, "%d %a", &weak_classifier->features[0].count, &weak_classifier->features[0].beta); for (q = 0; q < weak_classifier->features[0].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[0].channel[q], &weak_classifier->features[0].alpha[q], &weak_classifier->features[0].sat[q * 2].x, &weak_classifier->features[0].sat[q * 2].y, &weak_classifier->features[0].sat[q * 2 + 1].x, &weak_classifier->features[0].sat[q * 2 + 1].y); if (weak_classifier->pass & 0x2) { fscanf(r, "%d %a", &weak_classifier->features[1].count, &weak_classifier->features[1].beta); for (q = 0; q < weak_classifier->features[1].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[1].channel[q], &weak_classifier->features[1].alpha[q], &weak_classifier->features[1].sat[q * 2].x, &weak_classifier->features[1].sat[q * 2].y, &weak_classifier->features[1].sat[q * 2 + 1].x, &weak_classifier->features[1].sat[q * 2 + 1].y); } if (weak_classifier->pass & 0x1) { fscanf(r, "%d %a", &weak_classifier->features[2].count, &weak_classifier->features[2].beta); for (q = 0; q < weak_classifier->features[2].count; q++) fscanf(r, "%d %a %d %d %d %d", &weak_classifier->features[2].channel[q], &weak_classifier->features[2].alpha[q], &weak_classifier->features[2].sat[q * 2].x, &weak_classifier->features[2].sat[q * 2].y, &weak_classifier->features[2].sat[q * 2 + 1].x, &weak_classifier->features[2].sat[q * 2 + 1].y); } } } static void _ccv_icf_write_classifier_cascade_with_fd(ccv_icf_classifier_cascade_t* cascade, FILE* w) { int i, q; fprintf(w, "%d %d %d %d\n", cascade->count, cascade->size.width, cascade->size.height, cascade->grayscale); fprintf(w, "%d %d %d %d\n", cascade->margin.left, cascade->margin.top, cascade->margin.right, cascade->margin.bottom); for (i = 0; i < cascade->count; i++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + i; fprintf(w, "%u %a %a %a\n", weak_classifier->pass, weak_classifier->weigh[0], weak_classifier->weigh[1], weak_classifier->threshold); fprintf(w, "%d %a\n", weak_classifier->features[0].count, weak_classifier->features[0].beta); for (q = 0; q < weak_classifier->features[0].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[0].channel[q], weak_classifier->features[0].alpha[q], weak_classifier->features[0].sat[q * 2].x, weak_classifier->features[0].sat[q * 2].y, weak_classifier->features[0].sat[q * 2 + 1].x, weak_classifier->features[0].sat[q * 2 + 1].y); if (weak_classifier->pass & 0x2) { fprintf(w, "%d %a\n", weak_classifier->features[1].count, weak_classifier->features[1].beta); for (q = 0; q < weak_classifier->features[1].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[1].channel[q], weak_classifier->features[1].alpha[q], weak_classifier->features[1].sat[q * 2].x, weak_classifier->features[1].sat[q * 2].y, weak_classifier->features[1].sat[q * 2 + 1].x, weak_classifier->features[1].sat[q * 2 + 1].y); } if (weak_classifier->pass & 0x1) { fprintf(w, "%d %a\n", weak_classifier->features[2].count, weak_classifier->features[2].beta); for (q = 0; q < weak_classifier->features[2].count; q++) fprintf(w, "%d %a\n%d %d %d %d\n", weak_classifier->features[2].channel[q], weak_classifier->features[2].alpha[q], weak_classifier->features[2].sat[q * 2].x, weak_classifier->features[2].sat[q * 2].y, weak_classifier->features[2].sat[q * 2 + 1].x, weak_classifier->features[2].sat[q * 2 + 1].y); } } } ccv_icf_classifier_cascade_t* ccv_icf_read_classifier_cascade(const char* filename) { FILE* r = fopen(filename, "r"); ccv_icf_classifier_cascade_t* cascade = 0; if (r) { cascade = (ccv_icf_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_classifier_cascade_t)); _ccv_icf_read_classifier_cascade_with_fd(r, cascade); fclose(r); } return cascade; } void ccv_icf_write_classifier_cascade(ccv_icf_classifier_cascade_t* cascade, const char* filename) { FILE* w = fopen(filename, "w+"); if (w) { _ccv_icf_write_classifier_cascade_with_fd(cascade, w); fclose(w); } } void ccv_icf_classifier_cascade_free(ccv_icf_classifier_cascade_t* classifier) { ccfree(classifier->weak_classifiers); ccfree(classifier); } ccv_icf_multiscale_classifier_cascade_t* ccv_icf_read_multiscale_classifier_cascade(const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/multiscale", directory); FILE* r = fopen(filename, "r"); if (r) { int octave = 0, count = 0, grayscale = 0; fscanf(r, "%d %d %d", &octave, &count, &grayscale); fclose(r); ccv_icf_multiscale_classifier_cascade_t* classifier = (ccv_icf_multiscale_classifier_cascade_t*)ccmalloc(sizeof(ccv_icf_multiscale_classifier_cascade_t) + sizeof(ccv_icf_classifier_cascade_t) * count); classifier->type = CCV_ICF_CLASSIFIER_TYPE_B; classifier->octave = octave; classifier->count = count; classifier->grayscale = grayscale; classifier->cascade = (ccv_icf_classifier_cascade_t*)(classifier + 1); int i; for (i = 0; i < count; i++) { snprintf(filename, 1024, "%s/cascade-%d", directory, i + 1); r = fopen(filename, "r"); if (r) { ccv_icf_classifier_cascade_t* cascade = classifier->cascade + i; _ccv_icf_read_classifier_cascade_with_fd(r, cascade); fclose(r); } } return classifier; } return 0; } void ccv_icf_write_multiscale_classifier_cascade(ccv_icf_multiscale_classifier_cascade_t* classifier, const char* directory) { char filename[1024]; snprintf(filename, 1024, "%s/multiscale", directory); FILE* w = fopen(filename, "w+"); fprintf(w, "%d %d %d\n", classifier->octave, classifier->count, classifier->grayscale); fclose(w); int i; for (i = 0; i < classifier->count; i++) { snprintf(filename, 1024, "%s/cascade-%d", directory, i + 1); w = fopen(filename, "w+"); _ccv_icf_write_classifier_cascade_with_fd(classifier->cascade + i, w); fclose(w); } } void ccv_icf_multiscale_classifier_cascade_free(ccv_icf_multiscale_classifier_cascade_t* classifier) { int i; for (i = 0; i < classifier->count; i++) ccfree(classifier->cascade[i].weak_classifiers); ccfree(classifier); } static int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data) { const ccv_comp_t* r1 = (const ccv_comp_t*)_r1; const ccv_comp_t* r2 = (const ccv_comp_t*)_r2; int distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5); return r2->classification.id == r1->classification.id && r2->rect.x <= r1->rect.x + distance && r2->rect.x >= r1->rect.x - distance && r2->rect.y <= r1->rect.y + distance && r2->rect.y >= r1->rect.y - distance && r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) && (int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width && r2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) && (int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height; } static void _ccv_icf_detect_objects_with_classifier_cascade(ccv_dense_matrix_t* a, ccv_icf_classifier_cascade_t** cascades, int count, ccv_icf_param_t params, ccv_array_t* seq[]) { int i, j, k, q, x, y; int scale_upto = 1; for (i = 0; i < count; i++) scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (cascades[i]->size.height - cascades[i]->margin.top - cascades[i]->margin.bottom), (double)a->cols / (cascades[i]->size.width - cascades[i]->margin.left - cascades[i]->margin.right))) / log(2.) - DBL_MIN) + 1); ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto); pyr[0] = a; for (i = 1; i < scale_upto; i++) { pyr[i] = 0; ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0); } for (i = 0; i < scale_upto; i++) { // run it for (j = 0; j < count; j++) { double scale_ratio = pow(2., 1. / (params.interval + 1)); double scale = 1; ccv_icf_classifier_cascade_t* cascade = cascades[j]; for (k = 0; k <= params.interval; k++) { int rows = (int)(pyr[i]->rows / scale + 0.5); int cols = (int)(pyr[i]->cols / scale + 0.5); if (rows < cascade->size.height || cols < cascade->size.width) break; ccv_dense_matrix_t* image = k == 0 ? pyr[i] : 0; if (k > 0) ccv_resample(pyr[i], &image, 0, rows, cols, CCV_INTER_AREA); ccv_dense_matrix_t* bordered = 0; ccv_border(image, (ccv_matrix_t**)&bordered, 0, cascade->margin); if (k > 0) ccv_matrix_free(image); rows = bordered->rows; cols = bordered->cols; ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_matrix_free(bordered); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); int ch = CCV_GET_CHANNEL(sat->type); float* ptr = sat->data.f32; for (y = 0; y < rows; y += params.step_through) { if (y >= sat->rows - cascade->size.height - 1) break; for (x = 0; x < cols; x += params.step_through) { if (x >= sat->cols - cascade->size.width - 1) break; int pass = 1; float sum = 0; for (q = 0; q < cascade->count; q++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + q; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, x, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_comp_t comp; comp.rect = ccv_rect((int)((x + 0.5) * scale * (1 << i) - 0.5), (int)((y + 0.5) * scale * (1 << i) - 0.5), (cascade->size.width - cascade->margin.left - cascade->margin.right) * scale * (1 << i), (cascade->size.height - cascade->margin.top - cascade->margin.bottom) * scale * (1 << i)); comp.neighbors = 1; comp.classification.id = j + 1; comp.classification.confidence = sum; ccv_array_push(seq[j], &comp); } } ptr += sat->cols * ch * params.step_through; } ccv_matrix_free(sat); scale *= scale_ratio; } } } for (i = 1; i < scale_upto; i++) ccv_matrix_free(pyr[i]); } static void _ccv_icf_detect_objects_with_multiscale_classifier_cascade(ccv_dense_matrix_t* a, ccv_icf_multiscale_classifier_cascade_t** multiscale_cascade, int count, ccv_icf_param_t params, ccv_array_t* seq[]) { int i, j, k, q, x, y, ix, iy, py; assert(multiscale_cascade[0]->count % multiscale_cascade[0]->octave == 0); ccv_margin_t margin = multiscale_cascade[0]->cascade[multiscale_cascade[0]->count - 1].margin; for (i = 1; i < count; i++) { assert(multiscale_cascade[i]->count % multiscale_cascade[i]->octave == 0); assert(multiscale_cascade[i - 1]->grayscale == multiscale_cascade[i]->grayscale); assert(multiscale_cascade[i - 1]->count == multiscale_cascade[i]->count); assert(multiscale_cascade[i - 1]->octave == multiscale_cascade[i]->octave); ccv_icf_classifier_cascade_t* cascade = multiscale_cascade[i]->cascade + multiscale_cascade[i]->count - 1; margin.top = ccv_max(margin.top, cascade->margin.top); margin.right = ccv_max(margin.right, cascade->margin.right); margin.bottom = ccv_max(margin.bottom, cascade->margin.bottom); margin.left = ccv_max(margin.left, cascade->margin.left); } int scale_upto = 1; for (i = 0; i < count; i++) scale_upto = ccv_max(scale_upto, (int)(log(ccv_min((double)a->rows / (multiscale_cascade[i]->cascade[0].size.height - multiscale_cascade[i]->cascade[0].margin.top - multiscale_cascade[i]->cascade[0].margin.bottom), (double)a->cols / (multiscale_cascade[i]->cascade[0].size.width - multiscale_cascade[i]->cascade[0].margin.left - multiscale_cascade[i]->cascade[0].margin.right))) / log(2.) - DBL_MIN) + 2 - multiscale_cascade[i]->octave); ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * scale_upto); pyr[0] = a; for (i = 1; i < scale_upto; i++) { pyr[i] = 0; ccv_sample_down(pyr[i - 1], &pyr[i], 0, 0, 0); } for (i = 0; i < scale_upto; i++) { ccv_dense_matrix_t* bordered = 0; ccv_border(pyr[i], (ccv_matrix_t**)&bordered, 0, margin); ccv_dense_matrix_t* icf = 0; ccv_icf(bordered, &icf, 0); ccv_matrix_free(bordered); ccv_dense_matrix_t* sat = 0; ccv_sat(icf, &sat, 0, CCV_PADDING_ZERO); ccv_matrix_free(icf); int ch = CCV_GET_CHANNEL(sat->type); assert(CCV_GET_DATA_TYPE(sat->type) == CCV_32F); // run it for (j = 0; j < count; j++) { double scale_ratio = pow(2., (double)multiscale_cascade[j]->octave / multiscale_cascade[j]->count); int starter = i > 0 ? multiscale_cascade[j]->count - (multiscale_cascade[j]->count / multiscale_cascade[j]->octave) : 0; double scale = pow(scale_ratio, starter); for (k = starter; k < multiscale_cascade[j]->count; k++) { ccv_icf_classifier_cascade_t* cascade = multiscale_cascade[j]->cascade + k; int rows = (int)(pyr[i]->rows / scale + cascade->margin.top + 0.5); int cols = (int)(pyr[i]->cols / scale + cascade->margin.left + 0.5); int top = margin.top - cascade->margin.top; int right = margin.right - cascade->margin.right; int bottom = margin.bottom - cascade->margin.bottom; int left = margin.left - cascade->margin.left; if (sat->rows - top - bottom <= cascade->size.height || sat->cols - left - right <= cascade->size.width) break; float* ptr = sat->data.f32 + top * sat->cols * ch; for (y = 0, iy = py = top; y < rows; y += params.step_through) { iy = (int)((y + 0.5) * scale + top); if (iy >= sat->rows - cascade->size.height - 1) break; if (iy > py) { ptr += sat->cols * ch * (iy - py); py = iy; } for (x = 0; x < cols; x += params.step_through) { ix = (int)((x + 0.5) * scale + left); if (ix >= sat->cols - cascade->size.width - 1) break; int pass = 1; float sum = 0; for (q = 0; q < cascade->count; q++) { ccv_icf_decision_tree_t* weak_classifier = cascade->weak_classifiers + q; int c = _ccv_icf_run_weak_classifier(weak_classifier, ptr, sat->cols, ch, ix, 0); sum += weak_classifier->weigh[c]; if (sum < weak_classifier->threshold) { pass = 0; break; } } if (pass) { ccv_comp_t comp; comp.rect = ccv_rect((int)((x + 0.5) * scale * (1 << i)), (int)((y + 0.5) * scale * (1 << i)), (cascade->size.width - cascade->margin.left - cascade->margin.right) << i, (cascade->size.height - cascade->margin.top - cascade->margin.bottom) << i); comp.neighbors = 1; comp.classification.id = j + 1; comp.classification.confidence = sum; ccv_array_push(seq[j], &comp); } } } scale *= scale_ratio; } } ccv_matrix_free(sat); } for (i = 1; i < scale_upto; i++) ccv_matrix_free(pyr[i]); } ccv_array_t* ccv_icf_detect_objects(ccv_dense_matrix_t* a, void* cascade, int count, ccv_icf_param_t params) { assert(count > 0); int i, j, k; int type = *(((int**)cascade)[0]); for (i = 1; i < count; i++) { // check all types to be the same assert(*(((int**)cascade)[i]) == type); } ccv_array_t** seq = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * count); for (i = 0; i < count; i++) seq[i] = ccv_array_new(sizeof(ccv_comp_t), 64, 0); switch (type) { case CCV_ICF_CLASSIFIER_TYPE_A: _ccv_icf_detect_objects_with_classifier_cascade(a, (ccv_icf_classifier_cascade_t**)cascade, count, params, seq); break; case CCV_ICF_CLASSIFIER_TYPE_B: _ccv_icf_detect_objects_with_multiscale_classifier_cascade(a, (ccv_icf_multiscale_classifier_cascade_t**)cascade, count, params, seq); break; } ccv_array_t* result_seq = ccv_array_new(sizeof(ccv_comp_t), 64, 0); ccv_array_t* seq2 = ccv_array_new(sizeof(ccv_comp_t), 64, 0); for (k = 0; k < count; k++) { /* the following code from OpenCV's haar feature implementation */ if(params.min_neighbors == 0) { for (i = 0; i < seq[k]->rnum; i++) { ccv_comp_t* comp = (ccv_comp_t*)ccv_array_get(seq[k], i); ccv_array_push(result_seq, comp); } } else { ccv_array_t* idx_seq = 0; ccv_array_clear(seq2); // group retrieved rectangles in order to filter out noise int ncomp = ccv_array_group(seq[k], &idx_seq, _ccv_is_equal_same_class, 0); ccv_comp_t* comps = (ccv_comp_t*)cccalloc(sizeof(ccv_comp_t), ncomp + 1); // count number of neighbors for (i = 0; i < seq[k]->rnum; i++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq[k], i); int idx = *(int*)ccv_array_get(idx_seq, i); comps[idx].classification.id = r1.classification.id; if (r1.classification.confidence > comps[idx].classification.confidence || comps[idx].neighbors == 0) { comps[idx].rect = r1.rect; comps[idx].classification.confidence = r1.classification.confidence; } ++comps[idx].neighbors; } // calculate average bounding box for (i = 0; i < ncomp; i++) { int n = comps[i].neighbors; if (n >= params.min_neighbors) ccv_array_push(seq2, comps + i); } // filter out large object rectangles contains small object rectangles for (i = 0; i < seq2->rnum; i++) { ccv_comp_t* r2 = (ccv_comp_t*)ccv_array_get(seq2, i); int distance = (int)(ccv_min(r2->rect.width, r2->rect.height) * 0.25 + 0.5); for (j = 0; j < seq2->rnum; j++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq2, j); if (i != j && abs(r1.classification.id) == r2->classification.id && r1.rect.x >= r2->rect.x - distance && r1.rect.y >= r2->rect.y - distance && r1.rect.x + r1.rect.width <= r2->rect.x + r2->rect.width + distance && r1.rect.y + r1.rect.height <= r2->rect.y + r2->rect.height + distance && // if r1 (the smaller one) is better, mute r2 (r2->classification.confidence <= r1.classification.confidence && r2->neighbors < r1.neighbors)) { r2->classification.id = -r2->classification.id; break; } } } // filter out small object rectangles inside large object rectangles for (i = 0; i < seq2->rnum; i++) { ccv_comp_t r1 = *(ccv_comp_t*)ccv_array_get(seq2, i); if (r1.classification.id > 0) { int flag = 1; for (j = 0; j < seq2->rnum; j++) { ccv_comp_t r2 = *(ccv_comp_t*)ccv_array_get(seq2, j); int distance = (int)(ccv_min(r2.rect.width, r2.rect.height) * 0.25 + 0.5); if (i != j && abs(r1.classification.id) == abs(r2.classification.id) && r1.rect.x >= r2.rect.x - distance && r1.rect.y >= r2.rect.y - distance && r1.rect.x + r1.rect.width <= r2.rect.x + r2.rect.width + distance && r1.rect.y + r1.rect.height <= r2.rect.y + r2.rect.height + distance && // if r2 is better, we mute r1 (r2.classification.confidence > r1.classification.confidence || r2.neighbors >= r1.neighbors)) { flag = 0; break; } } if (flag) ccv_array_push(result_seq, &r1); } } ccv_array_free(idx_seq); ccfree(comps); } ccv_array_free(seq[k]); } ccv_array_free(seq2); return result_seq; }
{ "alphanum_fraction": 0.6773727005, "avg_line_length": 49.6036745407, "ext": "c", "hexsha": "340eaabc5f6f37f467dd9f61739a4afc228828e6", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2019-11-01T06:45:47.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-16T05:51:21.000Z", "max_forks_repo_head_hexsha": "364e1504dfd1fe743d38164d78927c0e04c222fc", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "liuliu/klaus", "max_forks_repo_path": "ccv/ccv/ccv_icf.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "364e1504dfd1fe743d38164d78927c0e04c222fc", "max_issues_repo_issues_event_max_datetime": "2015-10-26T02:24:59.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-13T17:44:20.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "liuliu/klaus", "max_issues_repo_path": "ccv/ccv/ccv_icf.c", "max_line_length": 455, "max_stars_count": 63, "max_stars_repo_head_hexsha": "364e1504dfd1fe743d38164d78927c0e04c222fc", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "liuliu/klaus", "max_stars_repo_path": "ccv/ccv/ccv_icf.c", "max_stars_repo_stars_event_max_datetime": "2020-12-27T19:04:10.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T03:00:56.000Z", "num_tokens": 46034, "size": 113394 }
#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> double R_vir_NFW(double M_vir, double z, int mode, cosmo_info **cosmo) { double c_vir; double R_vir; set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir); return (R_vir); }
{ "alphanum_fraction": 0.700265252, "avg_line_length": 23.5625, "ext": "c", "hexsha": "adeecc2e84e386d2348aa9ae9e2888fdb1b7c40d", "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/R_vir_NFW.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/R_vir_NFW.c", "max_line_length": 72, "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/R_vir_NFW.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": 132, "size": 377 }
/* * Gsl_blas_dgemv: test gsl_blas_dgemv (matrix . vector) * * Copyright (c) 2012 Jérémie Decock * * Required: GSL library (libgsl0-dev) * Usage: gcc gsl_blas_dgemv.c -lgsl -lgslcblas -lm * or: gcc gsl_blas_dgemv.c $(pkg-config --libs gsl) */ #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> void main() { gsl_vector * v = gsl_vector_alloc(3); gsl_vector * r = gsl_vector_alloc(3); gsl_matrix * m = gsl_matrix_alloc(3, 3); gsl_vector_set_all(v, 2.0); gsl_matrix_set_all(m, 3.0); gsl_blas_dgemv(CblasNoTrans, 1.0, m, v, 0.0, r); gsl_vector_fprintf(stdout, r, "%f"); gsl_vector_free(v); gsl_vector_free(r); gsl_matrix_free(m); }
{ "alphanum_fraction": 0.6279683377, "avg_line_length": 21.6571428571, "ext": "c", "hexsha": "9b7012b02c02ebb1bb1507ffc3448894f30ec9f7", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_path": "c/gsl/blas/gsl_blas_dgemv.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_path": "c/gsl/blas/gsl_blas_dgemv.c", "max_line_length": 56, "max_stars_count": 23, "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_path": "c/gsl/blas/gsl_blas_dgemv.c", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "num_tokens": 250, "size": 758 }
/** * * @file testing_zgemm.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Emmanuel Agullo * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #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> #include "testing_zmain.h" #undef REAL #define COMPLEX static int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K, PLASMA_Complex64_t alpha, PLASMA_Complex64_t *A, int LDA, PLASMA_Complex64_t *B, int LDB, PLASMA_Complex64_t beta, PLASMA_Complex64_t *Cref, PLASMA_Complex64_t *Cplasma, int LDC); int testing_zgemm(int argc, char **argv) { /* Check for number of arguments*/ if ( argc != 8) { USAGE("GEMM", "alpha beta M N K LDA LDB LDC", " - alpha : alpha coefficient\n" " - beta : beta coefficient\n" " - M : number of rows of matrices A and C\n" " - N : number of columns of matrices B and C\n" " - K : number of columns of matrix A / number of rows of matrix B\n" " - LDA : leading dimension of matrix A\n" " - LDB : leading dimension of matrix B\n" " - LDC : leading dimension of matrix C\n"); return -1; } PLASMA_Complex64_t alpha = (PLASMA_Complex64_t) atol(argv[0]); PLASMA_Complex64_t beta = (PLASMA_Complex64_t) atol(argv[1]); int M = atoi(argv[2]); int N = atoi(argv[3]); int K = atoi(argv[4]); int LDA = atoi(argv[5]); int LDB = atoi(argv[6]); int LDC = atoi(argv[7]); double eps; int info_solution; int i, j, ta, tb; int LDAxK = LDA*max(M,K); int LDBxN = LDB*max(K,N); int LDCxN = LDC*N; PLASMA_Complex64_t *A = (PLASMA_Complex64_t *)malloc(LDAxK*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *B = (PLASMA_Complex64_t *)malloc(LDBxN*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *C = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *Cinit = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t)); PLASMA_Complex64_t *Cfinal = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t)); /* Check if unable to allocate memory */ if ((!A)||(!B)||(!Cinit)||(!Cfinal)){ printf("Out of Memory \n "); return -2; } eps = LAPACKE_dlamch_work('e'); printf("\n"); printf("------ TESTS FOR PLASMA ZGEMM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", M, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 10.\n"); /*---------------------------------------------------------- * TESTING ZGEMM */ /* Initialize A, B, C */ LAPACKE_zlarnv_work(IONE, ISEED, LDAxK, A); LAPACKE_zlarnv_work(IONE, ISEED, LDBxN, B); LAPACKE_zlarnv_work(IONE, ISEED, LDCxN, C); #ifdef COMPLEX for (ta=0; ta<3; ta++) { for (tb=0; tb<3; tb++) { #else for (ta=0; ta<2; ta++) { for (tb=0; tb<2; tb++) { #endif for ( i = 0; i < M; i++) for ( j = 0; j < N; j++) Cinit[LDC*j+i] = C[LDC*j+i]; for ( i = 0; i < M; i++) for ( j = 0; j < N; j++) Cfinal[LDC*j+i] = C[LDC*j+i]; /* PLASMA ZGEMM */ PLASMA_zgemm(trans[ta], trans[tb], M, N, K, alpha, A, LDA, B, LDB, beta, Cfinal, LDC); /* Check the solution */ info_solution = check_solution(trans[ta], trans[tb], M, N, K, alpha, A, LDA, B, LDB, beta, Cinit, Cfinal, LDC); if (info_solution == 0) { printf("***************************************************\n"); printf(" ---- TESTING ZGEMM (%s, %s) ............... PASSED !\n", transstr[ta], transstr[tb]); printf("***************************************************\n"); } else { printf("************************************************\n"); printf(" - TESTING ZGEMM (%s, %s) ... FAILED !\n", transstr[ta], transstr[tb]); printf("************************************************\n"); } } } #ifdef _UNUSED_ }} #endif free(A); free(B); free(C); free(Cinit); free(Cfinal); return 0; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K, PLASMA_Complex64_t alpha, PLASMA_Complex64_t *A, int LDA, PLASMA_Complex64_t *B, int LDB, PLASMA_Complex64_t beta, PLASMA_Complex64_t *Cref, PLASMA_Complex64_t *Cplasma, int LDC) { int info_solution; double Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm, Rnorm, result; double eps; PLASMA_Complex64_t beta_const; double *work = (double *)malloc(max(K,max(M, N))* sizeof(double)); int Am, An, Bm, Bn; beta_const = -1.0; if (transA == PlasmaNoTrans) { Am = M; An = K; } else { Am = K; An = M; } if (transB == PlasmaNoTrans) { Bm = K; Bn = N; } else { Bm = N; Bn = K; } Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Am, An, A, LDA, work); Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Bm, Bn, B, LDB, work); Cinitnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work); Cplasmanorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cplasma, LDC, work); cblas_zgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC); Clapacknorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work); cblas_zaxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1); Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work); eps = LAPACKE_dlamch_work('e'); printf("Rnorm %e, Anorm %e, Bnorm %e, Cinitnorm %e, Cplasmanorm %e, Clapacknorm %e\n", Rnorm, Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm); result = Rnorm / ((Anorm + Bnorm + Cinitnorm) * N * eps); printf("============\n"); printf("Checking the norm of the difference against reference ZGEMM \n"); printf("-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo+||C||_oo).N.eps) = %e \n", result); if ( isnan(Rnorm) || isinf(Rnorm) || isnan(result) || isinf(result) || (result > 10.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else { printf("-- The solution is CORRECT ! \n"); info_solution= 0 ; } free(work); return info_solution; }
{ "alphanum_fraction": 0.5404616609, "avg_line_length": 36.0669856459, "ext": "c", "hexsha": "165503a2b08e2ad8c58a7a263ec370bfa8139723", "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": "testing/testing_zgemm.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": "testing/testing_zgemm.c", "max_line_length": 115, "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": "testing/testing_zgemm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2341, "size": 7538 }
#ifndef AMICI_VECTOR_H #define AMICI_VECTOR_H #include <vector> #include <type_traits> #include <amici/exception.h> #include <nvector/nvector_serial.h> #include <gsl/gsl-lite.hpp> namespace amici { /** Since const N_Vector is not what we want */ using const_N_Vector = std::add_const<typename std::remove_pointer<N_Vector>::type *>::type; /** AmiVector class provides a generic interface to the NVector_Serial struct */ class AmiVector { public: /** * @brief Default constructor */ AmiVector() = default; /** Creates an std::vector<realtype> and attaches the * data pointer to a newly created N_Vector_Serial. * Using N_VMake_Serial ensures that the N_Vector * module does not try to deallocate the data vector * when calling N_VDestroy_Serial * @brief empty constructor * @param length number of elements in vector */ explicit AmiVector(const long int length) : vec_(static_cast<decltype(vec_)::size_type>(length), 0.0), nvec_(N_VMake_Serial(length, vec_.data())) {} /** Moves data from std::vector and constructs an nvec that points to the * data * @brief constructor from std::vector, * @param rvec vector from which the data will be moved */ explicit AmiVector(std::vector<realtype> rvec) : vec_(std::move(rvec)), nvec_(N_VMake_Serial(static_cast<long int>(vec_.size()), vec_.data())) {} /** Copy data from gsl::span and constructs a vector * @brief constructor from gsl::span, * @param rvec vector from which the data will be copied */ explicit AmiVector(gsl::span<realtype> rvec) : AmiVector(std::vector<realtype>(rvec.begin(), rvec.end())) {} /** * @brief copy constructor * @param vold vector from which the data will be copied */ AmiVector(const AmiVector &vold) : vec_(vold.vec_) { nvec_ = N_VMake_Serial(static_cast<long int>(vold.vec_.size()), vec_.data()); } /** * @brief move constructor * @param other vector from which the data will be moved */ AmiVector(AmiVector&& other) noexcept : nvec_(nullptr) { vec_ = std::move(other.vec_); synchroniseNVector(); } /** * @brief destructor */ ~AmiVector(); /** * @brief copy assignment operator * @param other right hand side * @return left hand side */ AmiVector &operator=(AmiVector const &other); /** * @brief data accessor * @return pointer to data array */ realtype *data(); /** * @brief const data accessor * @return const pointer to data array */ const realtype *data() const; /** * @brief N_Vector accessor * @return N_Vector */ N_Vector getNVector(); /** * @brief N_Vector accessor * @return N_Vector */ const_N_Vector getNVector() const; /** * @brief Vector accessor * @return Vector */ std::vector<realtype> const &getVector() const; /** * @brief returns the length of the vector * @return length */ int getLength() const; /** * @brief resets the Vector by filling with zero values */ void reset(); /** * @brief changes the sign of data elements */ void minus(); /** * @brief sets all data elements to a specific value * @param val value for data elements */ void set(realtype val); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ realtype &operator[](int pos); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ realtype &at(int pos); /** * @brief accessor to data elements of the vector * @param pos index of element * @return element */ const realtype &at(int pos) const; /** * @brief copies data from another AmiVector * @param other data source */ void copy(const AmiVector &other); private: /** main data storage */ std::vector<realtype> vec_; /** N_Vector, will be synchronised such that it points to data in vec */ N_Vector nvec_ {nullptr}; /** * @brief reconstructs nvec such that data pointer points to vec data array */ void synchroniseNVector(); }; /** * @brief AmiVectorArray class. * * Provides a generic interface to arrays of NVector_Serial structs */ class AmiVectorArray { public: /** * @brief Default constructor */ AmiVectorArray() = default; /** * Creates an std::vector<realype> and attaches the * data pointer to a newly created N_VectorArray * using CloneVectorArrayEmpty ensures that the N_Vector * module does not try to deallocate the data vector * when calling N_VDestroyVectorArray_Serial * @brief empty constructor * @param length_inner length of vectors * @param length_outer number of vectors */ AmiVectorArray(long int length_inner, long int length_outer); /** * @brief copy constructor * @param vaold object to copy from */ AmiVectorArray(const AmiVectorArray &vaold); ~AmiVectorArray() = default; /** * @brief copy assignment operator * @param other right hand side * @return left hand side */ AmiVectorArray &operator=(AmiVectorArray const &other); /** * @brief accessor to data of AmiVector elements * @param pos index of AmiVector * @return pointer to data array */ realtype *data(int pos); /** * @brief const accessor to data of AmiVector elements * @param pos index of AmiVector * @return const pointer to data array */ const realtype *data(int pos) const; /** * @brief accessor to elements of AmiVector elements * @param ipos inner index in AmiVector * @param jpos outer index in AmiVectorArray * @return element */ realtype &at(int ipos, int jpos); /** * @brief const accessor to elements of AmiVector elements * @param ipos inner index in AmiVector * @param jpos outer index in AmiVectorArray * @return element */ const realtype &at(int ipos, int jpos) const; /** * @brief accessor to NVectorArray * @return N_VectorArray */ N_Vector *getNVectorArray(); /** * @brief accessor to NVector element * @param pos index of corresponding AmiVector * @return N_Vector */ N_Vector getNVector(int pos); /** * @brief const accessor to NVector element * @param pos index of corresponding AmiVector * @return N_Vector */ const_N_Vector getNVector(int pos) const; /** * @brief accessor to AmiVector elements * @param pos index of AmiVector * @return AmiVector */ AmiVector &operator[](int pos); /** * @brief const accessor to AmiVector elements * @param pos index of AmiVector * @return const AmiVector */ const AmiVector &operator[](int pos) const; /** * @brief length of AmiVectorArray * @return length */ int getLength() const; /** * @brief resets every AmiVector in AmiVectorArray */ void reset(); /** * @brief flattens the AmiVectorArray to a vector in row-major format * @param vec vector into which the AmiVectorArray will be flattened. Must * have length equal to number of elements. */ void flatten_to_vector(std::vector<realtype> &vec) const; /** * @brief copies data from another AmiVectorArray * @param other data source */ void copy(const AmiVectorArray &other); private: /** main data storage */ std::vector<AmiVector> vec_array_; /** * N_Vector array, will be synchronised such that it points to * respective elements in the vec_array */ std::vector<N_Vector> nvec_array_; }; } // namespace amici namespace gsl { /** * @brief Create span from N_Vector * @param nv * @return */ inline span<realtype> make_span(N_Vector nv) { return span<realtype>(N_VGetArrayPointer(nv), N_VGetLength_Serial(nv)); } } // namespace gsl #endif /* AMICI_VECTOR_H */
{ "alphanum_fraction": 0.6279294516, "avg_line_length": 25.0848484848, "ext": "h", "hexsha": "b49a143d60733b22edcdf7f7471c941438d7e314", "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": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "lcontento/AMICI", "max_forks_repo_path": "include/amici/vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "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": "lcontento/AMICI", "max_issues_repo_path": "include/amici/vector.h", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "7a1dc5ed1299273b3670239f5d614eec835f1299", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "lcontento/AMICI", "max_stars_repo_path": "include/amici/vector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2096, "size": 8278 }
#ifndef BAYESIAN_MERGE_H #define BAYESIAN_MERGE_H #include <vector> #include <multi/GaussianDistribution.h> #include <gsl/gsl_linalg.h> using namespace std; namespace openworld { class BayesianMerge { public: // modifies means in-place to assure maximum likelihood static void mergeGaussianHierarchy(vector<GaussianDistribution*> lows, GaussianDistribution* high) { vector<double> A, b; for (unsigned ii = 0; ii < lows.size(); ii++) { for (unsigned jj = 0; jj < lows.size(); jj++) { if (ii == jj) A.push_back(1 / lows[ii]->getVariance() + 1 / high->getVariance()); else A.push_back(1 / high->getVariance()); } b.push_back(lows[ii]->getMean() / lows[ii]->getVariance() + high->getMean() / high->getVariance()); } gsl_matrix_view Amat = gsl_matrix_view_array(A.data(), lows.size(), lows.size()); gsl_vector_view bmat = gsl_vector_view_array(b.data(), lows.size()); gsl_vector* x = gsl_vector_alloc(lows.size()); int s; gsl_permutation* p = gsl_permutation_alloc(lows.size()); gsl_linalg_LU_decomp(&Amat.matrix, p, &s); gsl_linalg_LU_solve(&Amat.matrix, p, &bmat.vector, x); double meansum = 0; for (unsigned ii = 0; ii < lows.size(); ii++) { meansum += gsl_vector_get(x, ii); lows[ii]->setMean(gsl_vector_get(x, ii)); } high->setMean(meansum); gsl_permutation_free(p); gsl_vector_free(x); } }; } #endif
{ "alphanum_fraction": 0.6126714566, "avg_line_length": 28.8867924528, "ext": "h", "hexsha": "afaba62567f9b9374ec8de2a2e49207435706c2d", "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": "fcd51a705f3a57100680b911347cbf189998d264", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jrising/openworld", "max_forks_repo_path": "multi/BayesianMerge.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "fcd51a705f3a57100680b911347cbf189998d264", "max_issues_repo_issues_event_max_datetime": "2015-12-05T00:33:30.000Z", "max_issues_repo_issues_event_min_datetime": "2015-12-05T00:33:30.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jrising/openworld", "max_issues_repo_path": "multi/BayesianMerge.h", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "fcd51a705f3a57100680b911347cbf189998d264", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jrising/openworld", "max_stars_repo_path": "multi/BayesianMerge.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 405, "size": 1531 }
/* * Copyright 2008-2014 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cusp/complex.h> #include <cblas.h> #define CUSP_CBLAS_COMPLEX_DEFS_1(FUNC_MACRO) \ FUNC_MACRO(cusp::complex<float> , float , c) \ FUNC_MACRO(cusp::complex<double>, double, z) #define CUSP_CBLAS_COMPLEX_DEFS_2(FUNC_MACRO) \ FUNC_MACRO(cusp::complex<float> , float , sc) \ FUNC_MACRO(cusp::complex<double>, double, dz) #define CUSP_CBLAS_COMPLEX_DEFS_3(FUNC_MACRO) \ FUNC_MACRO(cusp::complex<float> , float , cs) \ FUNC_MACRO(cusp::complex<double>, double, zd) #define CUSP_CBLAS_COMPLEX_AMAX(T,V,name) \ template<int dummy> \ int amax( const int n, const T* X, const int incX ) \ { \ return cblas_i##name##amax(n, (const V*) X, incX); \ } #define CUSP_CBLAS_COMPLEX_ASUM(T,V,name) \ template<int dummy> \ V asum( const int n, const T* X, const int incX ) \ { \ return cblas_##name##asum(n, (const V*) X, incX); \ } #define CUSP_CBLAS_COMPLEX_AXPY(T,V,name) \ template<int dummy> \ void axpy( const int n, const T alpha, const T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##axpy(n, (const V*) &alpha, (const V*) X, incX, (V*) Y, incY); \ } #define CUSP_CBLAS_COMPLEX_COPY(T,V,name) \ template<int dummy> \ void copy( const int n, const T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##copy(n, (const V*) X, incX, (V*) Y, incY); \ } // #define CUSP_CBLAS_COMPLEX_DOTC(T,V,name) // T dotc( const int n, const T* X, const int incX, const T* Y, const int incY ) // { // typedef typename thrust::detail::eval_if< // thrust::detail::is_same<V,float>::value, // thrust::detail::identity_<openblas_complex_float>, // thrust::detail::identity_<openblas_complex_double> // >::type Cmplx; // Cmplx z; // cblas_##name##dotc_sub(n, (const V*) X, incX, (const V*) Y, incY, &z); // return T(z.real, z.imag); // } // // #define CUSP_CBLAS_COMPLEX_DOTU(T,V,name) // T dotu( const int n, const T* X, const int incX, const T* Y, const int incY ) // { // typedef typename thrust::detail::eval_if< // thrust::detail::is_same<V,float>::value, // thrust::detail::identity_<openblas_complex_float>, // thrust::detail::identity_<openblas_complex_double> // >::type Cmplx; // Cmplx z; // cblas_##name##dotu_sub(n, (const V*) X, incX, (const V*) Y, incY, &z); // return T(z.real, z.imag); // } #define CUSP_CBLAS_COMPLEX_NRM2(T,V,name) \ template<int dummy> \ V nrm2( const int n, const T* X, const int incX ) \ { \ return cblas_##name##nrm2(n, (const V*) X, incX); \ } #define CUSP_CBLAS_COMPLEX_SCAL(T,V,name) \ template<int dummy> \ void scal( const int n, const V alpha, T* X, const int incX ) \ { \ cblas_##name##scal(n, alpha, (V*) X, incX); \ } #define CUSP_CBLAS_COMPLEX_SWAP(T,V,name) \ template<int dummy> \ void swap( const int n, T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##swap(n, (V*) X, incX, (V*) Y, incY); \ } #define CUSP_CBLAS_COMPLEX_GEMV(T,V,name) \ template<int dummy> \ void gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, \ int m, int n, T alpha, const T* A, int lda, \ const T* x, int incx, T beta, T* y, int incy) \ { \ cblas_##name##gemv(order, trans, m, n, (const V*) &alpha, (const V*) A, lda, \ (const V*) x, incx, (const V*) &beta, (V*) y, incy); \ } #define CUSP_CBLAS_COMPLEX_GERC(T,V,name) \ template<int dummy> \ void ger( CBLAS_ORDER order, int m, int n, T alpha, const T* x, int incx, \ const T* y, int incy, T* A, int lda) \ { \ cblas_##name##gerc(order, m, n, (const V*) &alpha, \ (const V*) x, incx, (const V*) y, incy, \ (V*) A, lda); \ } #define CUSP_CBLAS_COMPLEX_HEMV(T,V,name) \ template<int dummy> \ void hemv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ int n, T alpha, const T* A, int lda, \ const T* x, int incx, T beta, T* y, int incy) \ { \ cblas_##name##hemv(order, uplo, n, (const V*) &alpha, (const V*) A, lda, \ (const V*) x, incx, (const V*) &beta, (V*) y, incy); \ } #define CUSP_CBLAS_COMPLEX_HER(T,V,name) \ template<int dummy> \ void her( CBLAS_ORDER order, CBLAS_UPLO uplo, \ int n, const V alpha, const T* x, int incx, T* A, int lda) \ { \ cblas_##name##her(order, uplo, n, alpha, \ (const V*) x, incx, (V*) A, lda); \ } #define CUSP_CBLAS_COMPLEX_TRMV(T,V,name) \ template<int dummy> \ void trmv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int n, const T* A, int lda, T* x, int incx) \ { \ cblas_##name##trmv(order, uplo, trans, diag, n, \ (const V*) A, lda, (V*) x, incx); \ } #define CUSP_CBLAS_COMPLEX_TRSV(T,V,name) \ template<int dummy> \ void trsv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int n, const T* A, int lda, T* x, int incx) \ { \ cblas_##name##trsv(order, uplo, trans, diag, n, \ (const V*) A, lda, (V*) x, incx); \ } #define CUSP_CBLAS_COMPLEX_GEMM(T,V,name) \ template<int dummy> \ void gemm( CBLAS_ORDER order, \ CBLAS_TRANSPOSE transa, CBLAS_TRANSPOSE transb, \ int m, int n, int k, T alpha, const T* A, int lda, \ const T* B, int ldb, T beta, T* C, int ldc) \ { \ cblas_##name##gemm(order, transa, transb, \ m, n, k, (const V*) &alpha, (const V*) A, lda, \ (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \ } #define CUSP_CBLAS_COMPLEX_SYMM(T,V,name) \ template<int dummy> \ void symm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ int m, int n, T alpha, const T* A, int lda, \ const T* B, int ldb, T beta, T* C, int ldc) \ { \ cblas_##name##symm(order, side, uplo, m, n, \ (const V*) &alpha, (const V*) A, lda, \ (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \ } #define CUSP_CBLAS_COMPLEX_SYRK(T,V,name) \ template<int dummy> \ void syrk( CBLAS_ORDER order, \ CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \ int n, int k, T alpha, const T* A, int lda, \ T beta, T* C, int ldc) \ { \ cblas_##name##syrk(order, uplo, trans, n, k, \ (const V*) &alpha, (const V*) A, lda, \ (const V*) &beta, (V*) C, ldc); \ } #define CUSP_CBLAS_COMPLEX_SYR2K(T,V,name) \ template<int dummy> \ void syr2k( CBLAS_ORDER order, \ CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \ int n, int k, T& alpha, const T* A, int lda, \ const T* B, int ldb, T& beta, T* C, int ldc) \ { \ cblas_##name##syr2k(order, uplo, trans, n, k, \ (const V*) &alpha, (const V*) A, lda, \ (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \ } #define CUSP_CBLAS_COMPLEX_TRMM(T,V,name) \ template<int dummy> \ void trmm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int m, int n, T alpha, const T* A, int lda, \ T* B, int ldb) \ { \ cblas_##name##trmm(order, side, uplo, trans, diag, m, n, \ (const V*) &alpha, (const V*) A, lda, (V*) B, ldb); \ } #define CUSP_CBLAS_COMPLEX_TRSM(T,V,name) \ template<int dummy> \ void trsm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int m, int n, T alpha, const T* A, int lda, \ T* B, int ldb) \ { \ cblas_##name##trsm(order, side, uplo, trans, diag, m, n, \ (const V*) &alpha, (const V*) A, lda, (V*) B, ldb); \ } namespace cusp { namespace system { namespace cpp { namespace detail { namespace cblas { // LEVEL 1 CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_AMAX); CUSP_CBLAS_COMPLEX_DEFS_2(CUSP_CBLAS_COMPLEX_ASUM); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_AXPY); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_COPY); // CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_DOTC); CUSP_CBLAS_COMPLEX_DEFS_2(CUSP_CBLAS_COMPLEX_NRM2); CUSP_CBLAS_COMPLEX_DEFS_3(CUSP_CBLAS_COMPLEX_SCAL); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SWAP); // LEVEL 2 CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GEMV); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GERC); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_HEMV); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_HER); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRMV); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRSV); // LEVEL 3 CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GEMM); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYMM); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYRK); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYR2K); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRMM); CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRSM); } // end namespace cblas } // end namespace detail } // end namespace cpp } // end namespace system } // end namespace cusp
{ "alphanum_fraction": 0.3526011561, "avg_line_length": 60.9501779359, "ext": "h", "hexsha": "47f25bc0cd22c897f9ab62469681440c3d5e8d1a", "lang": "C", "max_forks_count": 106, "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z", "max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "njh19/cusplibrary", "max_forks_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_issues_count": 41, "max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "njh19/cusplibrary", "max_issues_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_line_length": 93, "max_stars_count": 270, "max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Raman-sh/cusplibrary", "max_stars_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z", "num_tokens": 3445, "size": 17127 }
///////////////// //example25.5.c ///////////////// #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> #include <math.h> typedef struct{ double g;//gravity double M;//mass of the car double m;//mass of the load double r;//length of the rope double C;//damping coefficient double F;//input force proportional to torque double T;//tension to the rope double x,x0;//x position of the load double y,y0;//y position of the load double X;//X position of the car double a;//angle (theta) double dx,dx0; double dy,dy0; double dX,dX0; double dr; double da,da0; double ddx; double ddy; double ddX; double ddr; double dda; double dXmax; double ddXmax; double Fmax;//Force double h; int nh; double _h; int _dim; double *_y; double *_y_err; double *_dydt_in; double *_dydt_out; const gsl_odeiv_step_type *_T; gsl_odeiv_step *_s; gsl_odeiv_system _sys; double _t; } CRANE; #define dim_crane 4 int cranefunc (double t, const double y[], double f[], void *params) { CRANE *c = (CRANE *)params; //y[0]=crane.p, y[1]=crane.da, y[2]=crane.X, y[3]=crane.dX f[0] = y[1]; f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; f[2] = y[3]; // f[3] = c->ddX; f[3] = (c->F+c->T*sin(y[0]))/c->M; return GSL_SUCCESS; } //////////////// #define square(x) ((x)*(x)) CRANE crane; int initialize() { crane.Fmax=20.0;//check// crane.Fmax=30;//check // crane.dXmax=1.0; crane.dXmax=1.0; crane.ddXmax=0.2; crane.g=9.8; crane.M=100; crane.m=20;//10;//10;//20 crane.r=5;//5; crane.C=1;//5; crane.dr=crane.ddr=0; crane.x0=0; crane.y0=crane.r; crane.dX0=crane.dx0=crane.dy0=crane.da0=0; #ifdef CRANESUB // crane.Fmax=_crane_Fmax;//check// crane.Fmax=30;//check crane.m=_crane_m; crane.C=_crane_C; crane.r=_crane_r; crane.h=AP_tS; crane.dXmax=_crane_dXmax; if(_AP_umax>0) AP_u_max=crane.Fmax=_AP_umax; else AP_u_max=crane.Fmax; AP_u_min=-AP_u_max; // starttime=0; // totaltime=100;// totaltime=40; // totaltime=50;// totaltime=40; // int kmax=totaltime/AP_tS; // _rr=(double*)malloc(kmax*sizeof(double)); rr=AP_r=_AP_r;//10 // int k;for(k=0;k<kmax;k++) _rr[k]=AP_r;//10; rr_kyoyou=_rr_kyoyou; // p=(double *)malloc(buffsize*sizeof(double)); C_MODE=11; // iteration=_iteration; // fprintf(stdout,"?????????iteration=%d\n",_iteration); #else crane.h=0.01; #endif crane.nh=10; crane.F=crane.a=crane.da=crane.dda=0; crane.T=crane.m*crane.g; crane._h=crane.h/crane.nh;//0.001 crane._dim=4; if(crane._y==NULL){ crane._y=(double*)malloc(crane._dim*sizeof(double)); crane._y_err=(double*)malloc(crane._dim*sizeof(double)); crane._dydt_in=(double*)malloc(crane._dim*sizeof(double)); crane._dydt_out=(double*)malloc(crane._dim*sizeof(double)); } crane._T= gsl_odeiv_step_rk4; crane._s= gsl_odeiv_step_alloc (crane._T, crane._dim); crane._sys= (gsl_odeiv_system){cranefunc, NULL, crane._dim, &crane}; crane._t=crane._y[0]=crane._y[1]=crane._y[2]=crane._y[3]=0; int i;for(i=0;i<crane._dim;i++) crane._dydt_in[i]=0; GSL_ODEIV_FN_EVAL(&(crane._sys), crane._t, crane._y, crane._dydt_in); return(0); } #ifndef CRANESUB char *fn="crane2io.dat"; FILE *fp; #endif//#ifndef CRANESUB double plant(double uu) { // crane.F=uu; if(uu>crane.Fmax) uu=crane.Fmax; else if(uu<-crane.Fmax) uu=-crane.Fmax; int n; for(n=0;n<crane.nh;n++){ crane.F=uu;// if(crane.dX>=crane.dXmax && crane.F>0) crane.F=0; else if(crane.dX<=-crane.dXmax && crane.F<0) crane.F=0; int status = gsl_odeiv_step_apply (crane._s, crane._t, crane._h, crane._y, crane._y_err, crane._dydt_in, crane._dydt_out, &crane._sys); if (status != GSL_SUCCESS) break; int i;for(i=0;i<dim_crane;i++) crane._dydt_in[i]=crane._dydt_out[i]; crane._t+=crane._h; crane.a =crane._y[0]; crane.da =crane._y[1]; crane.X =crane._y[2]; crane.dX =crane._y[3]; crane.x =crane.X+crane.r * sin(crane.a); crane.y =crane.r*cos(crane.a); crane.dx=(crane.x-crane.x0)/crane._h; crane.dy=(crane.y-crane.y0)/crane._h; crane.ddx=(crane.dx-crane.dx0)/crane._h; crane.ddy=(crane.dy-crane.dy0)/crane._h; crane.T=crane.m*sqrt(square(crane.ddx)+square(crane.ddy-crane.g)); crane.ddX=(crane.dX-crane.dX0)/crane._h; // crane.F=crane.M*crane.ddX-crane.T*sin(crane.a); crane.dda=(crane.da-crane.da0)/crane._h; /* crane.dda=(-2*crane.dr*crane.da-crane.g*sin(crane.a)-ddX[n]*cos(crane.a))/crane.r; */ crane.x0=crane.x; crane.y0=crane.y; crane.dx0=crane.dx; crane.dy0=crane.dy; crane.da0=crane.da; crane.dX0=crane.dX; } #ifndef CRANESUB fprintf(fp,"%.7e %.7e %.7e", crane._t,crane._y[0],crane._y[1]);//crane.a,crane.da fprintf(fp," %.7e %.7e %.7e" ,crane.X,crane.dX,crane.ddX); fprintf(fp," %.7e %.7e %.7e" ,crane.x,crane.dx,crane.ddx); fprintf(fp," %.7e %.7e %.7e" ,crane.y,crane.dy,crane.ddy); fprintf(fp," %.7e %.7e" ,crane.T,crane.F); fprintf(fp,"\n"); #endif return(crane.x); // return(crane.X); } #ifndef CRANESUB int main (void) { // CRANE crane; crane.g=9.8; crane.M=100; crane.m=20; crane.r=5; crane.dr=crane.ddr=0; //////////////////////////////////////////////////// /// method 2 /// /// input F /// /// output p,x,y,X,... /// //////////////////////////////////////////////////// double h;//,hh=0.1; //result for different h /*gnuplot set style data lines;n=1; n=n+1;plot "crane1io.dat" using 1:n, "crane2io.dat" using 1:n;print "n=",n #strange at n=9(ddx),12(ddy),13(T) */ //////////////////////////////////////////////////// /// read F /// //////////////////////////////////////////////////// char *fn1="crane1io.dat"; FILE *fp1=fopen(fn1,"r"); int n4; #define buffsize 512 char buff[buffsize]; int n0; fgets(buff,buffsize,fp1); sscanf(buff,"#%lf%d%d%lf%lf%lf%lf",&h,&n0,&n4,&crane.M,&crane.m,&crane.r,&crane.C); crane.h=h; double t4=n4*h; double *F =(double*)malloc(sizeof(double)*(n4+1)); // int M=n4+1;double *F =(double*)malloc(sizeof(double)*M); // double *ddX=(double*)malloc(sizeof(double)*M); int n; double t; // double dx0=0,dy0=0,dX0=0,da0=0; // double x0=0,y0=crane.r; fgets(buff,buffsize,fp1); for(n=0;n<n4;n++){// double _x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14; fgets(buff,buffsize,fp1); sscanf(buff,"%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf", &_x1,&_x2,&_x3,&_x4,&_x5,&_x6,&_x7,&_x8,&_x9,&_x10,&_x11,&_x12,&_x13,&_x14); F[n]=_x14; } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// initialize(); fp=fopen(fn,"w"); for(t=0;t<t4;t+=crane.h){ n=t/crane.h; plant(F[n]); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn); gsl_odeiv_step_free (crane._s); return 0; } #endif
{ "alphanum_fraction": 0.5767268716, "avg_line_length": 28.1124031008, "ext": "c", "hexsha": "3efe09b76ecbcd7c594bd8f06c3c08cf1f4e62df", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "1021/mspc/crane2sub.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "1021/mspc/crane2sub.c", "max_line_length": 95, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "1021/mspc/crane2sub.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2719, "size": 7253 }
/** @file */ #ifndef __CCL_UTILS_H_INCLUDED__ #define __CCL_UTILS_H_INCLUDED__ #include <gsl/gsl_spline.h> #define CCL_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define CCL_MAX(a, b) (((a) > (b)) ? (a) : (b)) CCL_BEGIN_DECLS /** * Compute bin edges of N-1 linearly spaced bins on the interval [xmin,xmax] * @param xmin minimum value of spacing * @param xmax maximum value of spacing * @param N number of bins plus one (number of bin edges) * @return x, bin edges in range [xmin, xmax] */ double * ccl_linear_spacing(double xmin, double xmax, int N); /** * Compute bin edges of N-1 logarithmically and then linearly spaced bins on the interval [xmin,xmax] * @param xminlog minimum value of spacing * @param xmin value when logarithmical ends and linear spacing begins * @param xmax maximum value of spacing * @param Nlin number of linear bins plus one (number of bin edges) * @param Nlog number of logarithmic bins plus one (number of bin edges) * @return x, bin edges in range [xminlog, xmax] */ double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlin, int Nlog); /** * Compute bin edges of N-1 logarithmically spaced bins on the interval [xmin,xmax] * @param xmin minimum value of spacing * @param xmax maximum value of spacing * @param N number of bins plus one (number of bin edges) * @return x, bin edges in range [xmin, xmax] */ double * ccl_log_spacing(double xmin, double xmax, int N); //Returns array of N logarithmically-spaced values between xmin and xmax double ccl_j_bessel(int l,double x); //Spherical Bessel function of order l (adapted from CAMB) CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7222562845, "avg_line_length": 33.9791666667, "ext": "h", "hexsha": "9b74e4ad7a7f124f539f54c7232adf9f45417c89", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_path": "include/ccl_utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "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": "benediktdiemer/CCL", "max_issues_repo_path": "include/ccl_utils.h", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_path": "include/ccl_utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 438, "size": 1631 }
/* histogram/get2d.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram2d.h> #include "find.c" double gsl_histogram2d_get (const gsl_histogram2d * h, const size_t i, const size_t j) { const size_t nx = h->nx; const size_t ny = h->ny; if (i >= nx) { GSL_ERROR_VAL ("index i lies outside valid range of 0 .. nx - 1", GSL_EDOM, 0); } if (j >= ny) { GSL_ERROR_VAL ("index j lies outside valid range of 0 .. ny - 1", GSL_EDOM, 0); } return h->bin[i * ny + j]; } int gsl_histogram2d_get_xrange (const gsl_histogram2d * h, const size_t i, double *xlower, double *xupper) { const size_t nx = h->nx; if (i >= nx) { GSL_ERROR ("index i lies outside valid range of 0 .. nx - 1", GSL_EDOM); } *xlower = h->xrange[i]; *xupper = h->xrange[i + 1]; return GSL_SUCCESS; } int gsl_histogram2d_get_yrange (const gsl_histogram2d * h, const size_t j, double *ylower, double *yupper) { const size_t ny = h->ny; if (j >= ny) { GSL_ERROR ("index j lies outside valid range of 0 .. ny - 1", GSL_EDOM); } *ylower = h->yrange[j]; *yupper = h->yrange[j + 1]; return GSL_SUCCESS; } int gsl_histogram2d_find (const gsl_histogram2d * h, const double x, const double y, size_t * i, size_t * j) { int status = find (h->nx, h->xrange, x, i); if (status) { GSL_ERROR ("x not found in range of h", GSL_EDOM); } status = find (h->ny, h->yrange, y, j); if (status) { GSL_ERROR ("y not found in range of h", GSL_EDOM); } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6435185185, "avg_line_length": 23.2941176471, "ext": "c", "hexsha": "88a08e2917f93b3fd9e785c3b393c0e6306fbe80", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.c", "max_line_length": 79, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/get2d.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": 721, "size": 2376 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef scenegraph_979fc7df_3f68_4a38_9dea_5eed6d400c98_h #define scenegraph_979fc7df_3f68_4a38_9dea_5eed6d400c98_h #include <gslib/type.h> #include <gslib/tree.h> #include <ariel/config.h> __ariel_begin__ class scene_node { public: //typedef gs::string string; typedef const string* sntype; typedef void* snptr; typedef snptr (*fnaccess)(int); typedef void (*fndestroy)(snptr); protected: sntype _tag; snptr _ptr; string _key; fndestroy _del; public: /* sntype declaration */ #define declare_sntype(snt) \ static sntype snt; #include <ariel\snt.h> #undef declare_sntype static void register_sntypes(); public: scene_node() { reset(); } scene_node(const gchar* name) { reset(); set_key(name); } scene_node(const gchar* name, sntype tag, snptr ptr, fndestroy del = 0) { set_key(name); bind(tag, ptr, del); } ~scene_node() { destroy(); reset(); } void reset() { _tag = sn_void; _ptr = 0; _del = 0; } void destroy() { if(_ptr && _del) _del(_ptr); } sntype get_type() const { return _tag; } snptr get_ptr() const { return _ptr; } const gchar* get_name() const { return _key.c_str(); } const string& get_key() const { return _key; } void set_destroy(fndestroy del) { _del = del; } void set_nodestroy() { set_destroy(0); } void set_key(const gchar* key) { _key.assign(key); } void bind(sntype tag, snptr ptr, fndestroy del = 0) { _tag = tag; _ptr = ptr; set_destroy(del); } void rebind(sntype tag, snptr ptr, fndestroy del = 0) { destroy(); bind(tag, ptr, del); } scene_node& operator=(const scene_node& that) { _tag = that._tag; _ptr = that._ptr; _key = that._key; _del = that._del; const_cast<scene_node&>(that)._del = 0; return *this; } }; struct scene_key { const gchar* _key; scene_key() { _key = 0; } scene_key(const gchar* k) { _key = k; } scene_key(const scene_node* n) { _key = n->get_name(); } }; class scene_graph { public: struct snkey_hash { size_t operator()(const scene_key& key) const { return string_hash(key._key); } }; struct snkey_equal { bool operator()(const scene_key& k1, const scene_key& k2) const { return string_hash(k1._key) == string_hash(k2._key); } }; typedef tree<scene_node> sntree; typedef sntree::wrapper wrapper; typedef sntree::iterator iterator; typedef sntree::const_iterator const_iterator; typedef unordered_map<scene_key, scene_node*, snkey_hash, snkey_equal> sntable; typedef scene_node::sntype sntype; typedef scene_node::snptr snptr; typedef scene_node::fndestroy fndestroy; public: template<class castop, int bias, class castp> static castop fbop_cast(castp ptr) { return ptr ? reinterpret_cast<castop>(((int)ptr) + bias) : 0; } template<class castop, class castp> static castop fbop_cast(castp ptr, int bias) { return ptr ? reinterpret_cast<castop>(((int)ptr) + bias) : 0; } static int wrapper_node_bias() { static wrapper inst; static const int bias = (int)&inst - ((int)inst.get_ptr()); return bias; } static wrapper* node_to_wrapper(scene_node* ptr) { return fbop_cast<wrapper*>(ptr, -wrapper_node_bias()); } static const wrapper* node_to_wrapper(const scene_node* ptr) { return fbop_cast<const wrapper*>(ptr, -wrapper_node_bias()); } static scene_node* iter_to_node(iterator i) { return i.get_ptr(); } static const scene_node* iter_to_node(const_iterator i) { return i.get_ptr(); } static iterator node_to_iter(scene_node* ptr) { return iterator(node_to_wrapper(ptr)); } static const_iterator node_to_iter(const scene_node* ptr) { return const_iterator(node_to_wrapper(ptr)); } public: scene_graph(); virtual ~scene_graph() {} public: scene_node* get_root_node() { return iter_to_node(_sntree.get_root()); } const scene_node* get_root_node() const { return iter_to_node(_sntree.get_root()); } bool is_node_attached(const scene_node* node) const { return node && _sntree.is_mine(node_to_iter(node)); } sntree* get_node_tree(const scene_node* node); const sntree* get_node_tree(const scene_node* node) const; void fix_node(scene_node* old, scene_node* new1); void map_node(scene_node* node, const gchar* name); void unmap_node(scene_node* node); public: virtual scene_node* create_node(sntype tag = scene_node::sn_void, snptr ptr = 0, fndestroy del = 0); virtual scene_node* create_node(const gchar* name, sntype tag = scene_node::sn_void, snptr ptr = 0, fndestroy del = 0); virtual scene_node* attach_node(scene_node* parent, scene_node* node); virtual scene_node* detach_node(scene_node* node); virtual void destroy_node(scene_node* node); virtual void clear_miscs(); protected: sntree _sntree; sntree _miscs; sntable _sntable; }; __ariel_end__ #endif
{ "alphanum_fraction": 0.6536185708, "avg_line_length": 33.9742268041, "ext": "h", "hexsha": "d3e8582e32f58d4fb534141a328c990b670934fa", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/scenemgr.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/scenemgr.h", "max_line_length": 130, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/scenemgr.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 1709, "size": 6591 }
/* rng/r250.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> /* This is a shift-register random number generator. The sequence is x_n = x_{n-103} ^ x_{n-250} ("^" means XOR) defined on 32-bit words. The first 250 elements x_1 .. x_250 are first initialized as x_n = s_n, where s_n = (69069*s_{n-1}) mod 2^32 and s_0=s is the user-supplied seed. To ensure that the sequence does not lie on a subspace we force 32 of the entries to be linearly independent. We take the 32 elements x[3], x[10], x[17], x[24], ..., 213 and apply the following operations, x[3] &= 11111111111111111111111111111111 x[3] |= 10000000000000000000000000000000 x[10] &= 01111111111111111111111111111111 x[10] |= 01000000000000000000000000000000 x[17] &= 00111111111111111111111111111111 x[17] |= 00100000000000000000000000000000 .... ... x[206] &= 00000000000000000000000000000111 x[206] |= 00000000000000000000000000000100 x[213] &= 00000000000000000000000000000011 x[213] |= 00000000000000000000000000000010 x[220] &= 00000000000000000000000000000001 x[220] |= 00000000000000000000000000000001 i.e. if we consider the bits of the 32 elements as forming a 32x32 array then we are setting the diagonal bits of the array to one and masking the lower triangle below the diagonal to zero. With this initialization procedure the theoretical value of x_{10001} is 1100653588 for s = 1 (Actually I got this by running the original code). The subscript 10001 means (1) seed the generator with s = 1 and then do 10000 actual iterations. The period of this generator is about 2^250. The algorithm works for any number of bits. It is implemented here for 32 bits. From: S. Kirkpatrick and E. Stoll, "A very fast shift-register sequence random number generator", Journal of Computational Physics, 40, 517-526 (1981). */ static inline unsigned long int r250_get (void *vstate); static double r250_get_double (void *vstate); static void r250_set (void *state, unsigned long int s); typedef struct { int i; unsigned long x[250]; } r250_state_t; static inline unsigned long int r250_get (void *vstate) { r250_state_t *state = (r250_state_t *) vstate; unsigned long int k; int j; int i = state->i; if (i >= 147) { j = i - 147; } else { j = i + 103; } k = state->x[i] ^ state->x[j]; state->x[i] = k; if (i >= 249) { state->i = 0; } else { state->i = i + 1; } return k; } static double r250_get_double (void *vstate) { return r250_get (vstate) / 4294967296.0 ; } static void r250_set (void *vstate, unsigned long int s) { r250_state_t *state = (r250_state_t *) vstate; int i; if (s == 0) s = 1; /* default seed is 1 */ state->i = 0; #define LCG(n) ((69069 * n) & 0xffffffffUL) for (i = 0; i < 250; i++) /* Fill the buffer */ { s = LCG (s); state->x[i] = s; } { /* Masks for turning on the diagonal bit and turning off the leftmost bits */ unsigned long int msb = 0x80000000UL; unsigned long int mask = 0xffffffffUL; for (i = 0; i < 32; i++) { int k = 7 * i + 3; /* Select a word to operate on */ state->x[k] &= mask; /* Turn off bits left of the diagonal */ state->x[k] |= msb; /* Turn on the diagonal bit */ mask >>= 1; msb >>= 1; } } return; } static const gsl_rng_type r250_type = {"r250", /* name */ 0xffffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (r250_state_t), &r250_set, &r250_get, &r250_get_double}; const gsl_rng_type *gsl_rng_r250 = &r250_type;
{ "alphanum_fraction": 0.6588733022, "avg_line_length": 26.573964497, "ext": "c", "hexsha": "aa25e4b27a7b30b4059bea513701c111e07b8f80", "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/rng/r250.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/rng/r250.c", "max_line_length": 72, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/r250.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": 1412, "size": 4491 }
/* linalg/ql.c * * Copyright (C) 2019 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_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> /* Factorise a general M x N matrix A into * * A = Q L * * where Q is orthogonal (M x M) and L is lower triangular (M x N). * * 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. * * 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 = [A(1,N-k+i), A(2,N-k+i), ... , A(M-k+i,N-k+i), 1, 0, ..., 0] * * This storage scheme is the same as in LAPACK. */ /* gsl_linalg_QL_decomp() Perform QL decomposition of a matrix A Inputs: A - M-by-N matrix tau - (output) Householder coefficients, length N Notes: 1) The K = MIN(M, N) Householder scalars are stored in tau(N-K+1:N) on output; the rest of tau is used as temporary workspace */ int gsl_linalg_QL_decomp (gsl_matrix * A, gsl_vector * tau) { const size_t M = A->size1; const size_t N = A->size2; if (tau->size != N) { GSL_ERROR ("size of tau must be N", GSL_EBADLEN); } else { const size_t K = GSL_MIN(M, N); size_t i; for (i = 0; i < K; i++) { /* compute the Householder transformation to annihilate the (N-K+i)-th column of the matrix */ gsl_vector_view c = gsl_matrix_subcolumn (A, N - i - 1, 0, M - i); double * alpha = gsl_matrix_ptr(A, M - i - 1, N - i - 1); double tau_j = gsl_linalg_householder_transform2 (alpha, &(c.vector)); /* apply the transformation to A(1:M-i,1:N-i-2) from the left */ if (i + 1 < N) { gsl_vector_view work = gsl_vector_subvector(tau, 0, N - i - 1); gsl_matrix_view m = gsl_matrix_submatrix (A, 0, 0, M - i, N - i - 1); double tmp = *alpha; *alpha = 1.0; gsl_linalg_householder_left (tau_j, &(c.vector), &(m.matrix), &work.vector); *alpha = tmp; } gsl_vector_set (tau, N - i - 1, tau_j); } return GSL_SUCCESS; } } /* form the orthogonal matrix Q from the packed QL matrix */ int gsl_linalg_QL_unpack (const gsl_matrix * QL, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * L) { const size_t M = QL->size1; const size_t N = QL->size2; if (Q->size1 != M || Q->size2 != M) { GSL_ERROR ("Q matrix must be M x M", GSL_ENOTSQR); } else if (L->size1 != M || L->size2 != N) { GSL_ERROR ("L matrix must be M x N", GSL_ENOTSQR); } else if (tau->size != N) { GSL_ERROR ("size of tau must be N", GSL_EBADLEN); } else { const size_t K = GSL_MIN(M, N); size_t i; /* initialize Q to the identity */ gsl_matrix_set_identity (Q); for (i = 0; i < K; ++i) { gsl_vector_const_view h = gsl_matrix_const_subcolumn (QL, N - K + i, 0, M - K + i + 1); gsl_matrix_view m = gsl_matrix_submatrix (Q, 0, 0, M - K + i + 1, M - K + i + 1); gsl_vector_view work = gsl_matrix_subcolumn(L, 0, 0, M - K + i + 1); double ti = gsl_vector_get (tau, N - K + i); double * ptr = gsl_matrix_ptr((gsl_matrix *) QL, M - K + i, N - K + i); double tmp = *ptr; *ptr = 1.0; gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector); *ptr = tmp; } /* form the left triangular matrix L from a packed QL matrix */ gsl_matrix_set_zero(L); if (M >= N) { gsl_matrix_const_view src = gsl_matrix_const_submatrix(QL, M - N, 0, N, N); gsl_matrix_view dest = gsl_matrix_submatrix(L, M - N, 0, N, N); gsl_matrix_tricpy(CblasLower, CblasNonUnit, &dest.matrix, &src.matrix); } else { gsl_matrix_const_view src1 = gsl_matrix_const_submatrix(QL, 0, 0, M, N - M); gsl_matrix_view dest1 = gsl_matrix_submatrix(L, 0, 0, M, N - M); gsl_matrix_const_view src2 = gsl_matrix_const_submatrix(QL, 0, N - M, M, M); gsl_matrix_view dest2 = gsl_matrix_submatrix(L, 0, N - M, M, M); gsl_matrix_memcpy(&dest1.matrix, &src1.matrix); gsl_matrix_tricpy(CblasLower, CblasNonUnit, &dest2.matrix, &src2.matrix); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5977757183, "avg_line_length": 31.0057471264, "ext": "c", "hexsha": "0fcabb0ec953cd30e236ceefa192b3e0c274542d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.c", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.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": 1590, "size": 5395 }
/*==================BEGIN ASF AUTO-GENERATED DOCUMENTATION==================*/ /* ABOUT EDITING THIS DOCUMENTATION: If you wish to edit the documentation for this program, you need to change the following defines. For the short ones (like ASF_NAME_STRING) this is no big deal. However, for some of the longer ones, such as ASF_COPYRIGHT_STRING, it can be a daunting task to get all the newlines in correctly, etc. In order to help you with this task, there is a tool, edit_man_header. The tool *only* works with this portion of the code, so fear not. It will scan in defines of the format #define ASF_<something>_STRING between the two auto-generated documentation markers, format them for a text editor, run that editor, allow you to edit the text in a clean manner, and then automatically generate these defines, formatted appropriately. The only warning is that any text between those two markers and not part of one of those defines will not be preserved, and that all of this auto-generated code will be at the top of the source file. Save yourself the time and trouble, and use edit_man_header. :) */ #define ASF_NAME_STRING \ "asf_geocode" #define ASF_USAGE_STRING \ " "ASF_NAME_STRING" -p <projection name> <<projection parameters>>\n"\ " [-force] [-resample-method <method>] [-height <height>]\n"\ " [-datum <datum>] [-pixel-size <pixel size>] [-band <band_id | all>]\n"\ " [-log <file>] [-write-proj-file <file>] [-read-proj-file <file>]\n"\ " [-save-mapping] [-background <value>] [-quiet] [-license]\n"\ " [-version] [-help]\n"\ " <in_base_name> <out_base_name>\n"\ "\n"\ " Use the -help option for more projection parameter controls.\n" #define ASF_DESCRIPTION_STRING \ " This program takes a map projected or an unprojected (ground\n"\ " range) image in the ASF internal format and geocodes it,\n"\ " i.e. swizzles it around into one of the standard projections used\n"\ " for maps (universal transverse mercator, polar stereo, etc). The\n"\ " output is a new image in ASF internal format.\n" #define ASF_INPUT_STRING \ " Most of the \"options\" are actually required. The specification\n"\ " of a certain projection type implies that all the parameters\n"\ " required to fully specify a projection of that type be included.\n"\ "\n"\ " This must be an ASF internal format image base name.\n" #define ASF_OUTPUT_STRING \ " The base name of the geocoded image to produce.\n" #define ASF_OPTIONS_STRING \ "%s"\ "\n"\ " -save-mapping\n"\ " Creates two additional files during geocoding. One will contain\n"\ " the line number from which the pixel was obtained from the\n"\ " original file, the other the sample numbers. Together, these\n"\ " define the mapping of pixels performed by the geocoding.\n"\ "\n"\ " -log <log file>\n"\ " Output will be written to a specified log file.\n"\ "\n"\ " -quiet\n"\ " Supresses all non-essential output.\n"\ "\n"\ " -license\n"\ " Print copyright and license for this software then exit.\n"\ "\n"\ " -version\n"\ " Print version and copyright then exit.\n"\ "\n"\ " -help\n"\ " Print a help page and exit.\n" #define ASF_EXAMPLES_STRING \ " To map project an image with centerpoint at -147 degrees\n"\ " longitude and average height 466 meters into universal transverse\n"\ " mercator projection, with one pixel 50 meters on a side:\n"\ "\n"\ " "ASF_NAME_STRING" -p utm --central-meridian -147.0 --height 466\n"\ " input_image output_image\n"\ "\n"\ " To geocode one band within an image file, you specify the selected band\n"\ " with the -band option, and the selected band MUST be one of which appears\n"\ " in the list of available bands as noted in the 'bands' item found in the\n"\ " 'general' (first) block in the metadata file. For example, if 'bands'\n"\ " contains \"01,02,03,04\", then you could specify a band_id, e.g. \"-band 02\"\n"\ " etc on the command line. The same applies to band lists, such\n"\ " as \"HH,HV,VH,VV\" or just \"03\" etc.\n"\ "\n"\ " "ASF_NAME_STRING" -p utm -band HV file outfile_HV\n" #define ASF_LIMITATIONS_STRING \ " May fail badly if bad projection parameters are supplied for the\n"\ " area in the image.\n" #define ASF_SEE_ALSO_STRING \ " asf_import, asf_export\n" /*===================END ASF AUTO-GENERATED DOCUMENTATION===================*/ #include <asf_contact.h> #include <asf_license.h> // Standard libraries. #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // Libraries from packages outside ASF. #include <glib.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_statistics_double.h> // Libraries developed at ASF. #include <asf.h> #include <asf_nan.h> #include <asf_meta.h> #include <asf_raster.h> #include "float_image.h" #include <libasf_proj.h> #include <spheroids.h> #include <asf_contact.h> // Headers used by this program. #include "asf_geocode.h" // Print minimalistic usage info & exit static void print_usage(void) { asfPrintStatus("\n" "Usage:\n" ASF_USAGE_STRING "\n"); exit(EXIT_FAILURE); } // Print the help info & exit static void print_help(void) { asfPrintStatus( "\n" "Tool name:\n " ASF_NAME_STRING "\n\n" "Usage:\n" ASF_USAGE_STRING "\n" "Description:\n" ASF_DESCRIPTION_STRING "\n" "Input:\n" ASF_INPUT_STRING "\n" "Output:\n"ASF_OUTPUT_STRING "\n" "Options:\n" ASF_OPTIONS_STRING "\n" "Examples:\n" ASF_EXAMPLES_STRING "\n" "Limitations:\n" ASF_LIMITATIONS_STRING "\n" "See also:\n" ASF_SEE_ALSO_STRING "\n" "Contact:\n" ASF_CONTACT_STRING "\n" "Version:\n " SVN_REV " (part of " TOOL_SUITE_NAME " " MAPREADY_VERSION_STRING ")\n\n", geocode_projection_options_help()); exit(EXIT_FAILURE); } // Main routine. int main (int argc, char **argv) { int force_flag = FALSE; int debug_dump = FALSE; char band_id[256]=""; char *in_base_name, *out_base_name; in_base_name = (char *) MALLOC(sizeof(char)*255); out_base_name = (char *) MALLOC(sizeof(char)*255); // Get the projection parameters from the command line. projection_type_t projection_type; // Terrain height to assume. Defaults to 0 (no height correction) double average_height = 0.0; // Pixel size to use for output image, in projection coordinate // units. This variable corresponds to a "private" // (i.e. undocumented, so users don't fiddle with it) option. // NOTE: Setting the pixel size to a negative number results in the // code to pick a pixel size from the metadata double pixel_size = -1; // Datum to use in the target projection datum_type_t datum; spheroid_type_t spheroid; // Method to use to resample images. resample_method_t resample_method; // Value to put in the region outside the image double background_val = 0.0; // Should we save the mapping files? int save_map_flag; if (detect_flag_options(argc, argv, "-help", "--help", "-h", NULL)) { print_help(); } // Detect & Process logging arguments if ((logflag = detect_string_options(argc, argv, logFile, "-log", "--log", NULL))) { fLog = fopen (logFile, "a"); if ( fLog == NULL ) { // Couldn't open the log file, so just don't do logging. logflag = FALSE; } } quietflag = detect_flag_options(argc, argv, "-quiet", "--quiet", NULL); save_map_flag = extract_flag_options(&argc, &argv, "-save-mapping", "--save_mapping", NULL); handle_license_and_version_args(argc, argv, ASF_NAME_STRING); asfSplashScreen(argc, argv); project_parameters_t *pp = get_geocode_options (&argc, &argv, &projection_type, &average_height, &pixel_size, &datum, &spheroid, &resample_method, &force_flag, band_id); if (!pp && projection_type != LAT_LONG_PSEUDO_PROJECTION) { print_usage(); } // The argument at which the filenames start int arg_num = 1; if (detect_flag_options(argc, argv, "-debug", NULL)) { debug_dump=TRUE; ++arg_num; } if (!extract_double_options(&argc, &argv, &background_val, "--background", "-background", NULL)) { strcpy(in_base_name, argv[arg_num]); meta_parameters *meta = meta_read(in_base_name); background_val = meta->general->no_data; asfPrintStatus("Extracted no data value (%f) out of the metadata.\n", meta->general->no_data); meta_free(meta); } if (ISNAN(background_val)) background_val = DEFAULT_NO_DATA_VALUE; // Get non-option command line arguments. if ( argc != 3 && !debug_dump ) { int ii; int bad_arg = FALSE; for (ii = 0; ii < argc; ++ii) { if (argv[ii][0] == '-') { bad_arg = TRUE; asfPrintStatus("Unrecognized argument: %s\n", argv[ii]); } } if (!bad_arg) fprintf (stderr, "Wrong number of arguments\n"); print_usage (); } strcpy (in_base_name, argv[arg_num]); strcpy (out_base_name, argv[arg_num + 1]); // Strip .img and also check to make sure input and output // base names are not the same char *ext = findExt(in_base_name); if (ext && strncmp(ext, ".img", 4) == 0) *ext = '\0'; ext = findExt(out_base_name); if (ext && strncmp(ext, ".img", 4) == 0) *ext = '\0'; char msg[512]; sprintf(msg,"Input and output basenames cannot be the same:\n" " Input base name : %s\n" " Output base name: %s\n", in_base_name, out_base_name); if (strcmp(in_base_name, out_base_name) == 0) asfPrintError(msg); // Call library function that does the actual work asf_geocode(pp, projection_type, force_flag, resample_method, average_height, datum, pixel_size, band_id, in_base_name, out_base_name, (float)background_val, save_map_flag); // Close Log, if needed if (logflag) FCLOSE (fLog); exit (EXIT_SUCCESS); }
{ "alphanum_fraction": 0.6639760837, "avg_line_length": 34.9651567944, "ext": "c", "hexsha": "8c26ce6ff5373d076bc55bb78d0780de25761154", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/asf_geocode/asf_geocode.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/asf_geocode/asf_geocode.c", "max_line_length": 95, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/asf_geocode/asf_geocode.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 2636, "size": 10035 }
/* multifit_nlin/gsl_multifit_nlin.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MULTIFIT_NLIN_H__ #define __GSL_MULTIFIT_NLIN_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.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 int gsl_multifit_gradient (const gsl_matrix * J, const gsl_vector * f, gsl_vector * g); int gsl_multifit_covar (const gsl_matrix * J, const double epsrel, gsl_matrix * covar); int gsl_multifit_covar_QRPT (gsl_matrix * r, gsl_permutation * perm, const double epsrel, gsl_matrix * covar); /* Definition of vector-valued functions with parameters based on gsl_vector */ struct gsl_multifit_function_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); size_t n; /* number of functions */ size_t p; /* number of independent variables */ void * params; }; typedef struct gsl_multifit_function_struct gsl_multifit_function ; #define GSL_MULTIFIT_FN_EVAL(F,x,y) (*((F)->f))(x,(F)->params,(y)) typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n, size_t p); int (*set) (void *state, gsl_multifit_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); int (*iterate) (void *state, gsl_multifit_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); void (*free) (void *state); } gsl_multifit_fsolver_type; typedef struct { const gsl_multifit_fsolver_type * type; gsl_multifit_function * function ; gsl_vector * x ; gsl_vector * f ; gsl_vector * dx ; void *state; } gsl_multifit_fsolver; gsl_multifit_fsolver * gsl_multifit_fsolver_alloc (const gsl_multifit_fsolver_type * T, size_t n, size_t p); void gsl_multifit_fsolver_free (gsl_multifit_fsolver * s); int gsl_multifit_fsolver_set (gsl_multifit_fsolver * s, gsl_multifit_function * f, const gsl_vector * x); int gsl_multifit_fsolver_iterate (gsl_multifit_fsolver * s); int gsl_multifit_fsolver_driver (gsl_multifit_fsolver * s, const size_t maxiter, const double epsabs, const double epsrel); const char * gsl_multifit_fsolver_name (const gsl_multifit_fsolver * s); gsl_vector * gsl_multifit_fsolver_position (const gsl_multifit_fsolver * s); /* Definition of vector-valued functions and gradient with parameters based on gsl_vector */ struct gsl_multifit_function_fdf_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); int (* df) (const gsl_vector * x, void * params, gsl_matrix * df); int (* fdf) (const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix *df); size_t n; /* number of functions */ size_t p; /* number of independent variables */ void * params; /* user parameters */ size_t nevalf; /* number of function evaluations */ size_t nevaldf; /* number of Jacobian evaluations */ }; typedef struct gsl_multifit_function_fdf_struct gsl_multifit_function_fdf ; typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n, size_t p); int (*set) (void *state, const gsl_vector * wts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx); int (*iterate) (void *state, const gsl_vector * wts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx); int (*gradient) (void *state, gsl_vector * g); int (*jac) (void *state, gsl_matrix * J); void (*free) (void *state); } gsl_multifit_fdfsolver_type; typedef struct { const gsl_multifit_fdfsolver_type * type; gsl_multifit_function_fdf * fdf ; gsl_vector * x; /* parameter values x */ gsl_vector * f; /* residual vector f(x) */ gsl_vector * dx; /* step dx */ gsl_vector * g; /* gradient J^T f */ gsl_vector * sqrt_wts; /* sqrt(wts) */ size_t niter; /* number of iterations performed */ void *state; } gsl_multifit_fdfsolver; gsl_multifit_fdfsolver * gsl_multifit_fdfsolver_alloc (const gsl_multifit_fdfsolver_type * T, size_t n, size_t p); int gsl_multifit_fdfsolver_set (gsl_multifit_fdfsolver * s, gsl_multifit_function_fdf * fdf, const gsl_vector * x); int gsl_multifit_fdfsolver_wset (gsl_multifit_fdfsolver * s, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_vector * wts); int gsl_multifit_fdfsolver_iterate (gsl_multifit_fdfsolver * s); int gsl_multifit_fdfsolver_driver (gsl_multifit_fdfsolver * s, const size_t maxiter, const double xtol, const double gtol, const double ftol, int *info); int gsl_multifit_fdfsolver_jac (gsl_multifit_fdfsolver * s, gsl_matrix * J); void gsl_multifit_fdfsolver_free (gsl_multifit_fdfsolver * s); const char * gsl_multifit_fdfsolver_name (const gsl_multifit_fdfsolver * s); gsl_vector * gsl_multifit_fdfsolver_position (const gsl_multifit_fdfsolver * s); gsl_vector * gsl_multifit_fdfsolver_residual (const gsl_multifit_fdfsolver * s); size_t gsl_multifit_fdfsolver_niter (const gsl_multifit_fdfsolver * s); int gsl_multifit_eval_wf(gsl_multifit_function_fdf *fdf, const gsl_vector *x, const gsl_vector *wts, gsl_vector *y); int gsl_multifit_eval_wdf(gsl_multifit_function_fdf *fdf, const gsl_vector *x, const gsl_vector *wts, gsl_matrix *dy); int gsl_multifit_fdfsolver_test (const gsl_multifit_fdfsolver * s, const double xtol, const double gtol, const double ftol, int *info); int gsl_multifit_test_delta (const gsl_vector * dx, const gsl_vector * x, double epsabs, double epsrel); int gsl_multifit_test_gradient (const gsl_vector * g, double epsabs); int gsl_multifit_fdfsolver_dif_df(const gsl_vector *x, const gsl_vector *wts, gsl_multifit_function_fdf *fdf, const gsl_vector *f, gsl_matrix *J); int gsl_multifit_fdfsolver_dif_fdf(const gsl_vector *x, gsl_multifit_function_fdf *fdf, gsl_vector *f, gsl_matrix *J); typedef struct { size_t n; /* number of (original) residuals */ size_t p; /* number of model parameters */ double lambda; /* damping parameter */ const gsl_vector *L_diag; /* diagonal damping matrix or NULL */ const gsl_matrix *L; /* general damping matrix or NULL */ gsl_vector *f; /* function values for finite diff J */ gsl_vector *wts; /* weight vector for augmented system */ gsl_multifit_fdfsolver * s; gsl_multifit_function_fdf *fdf; /* user defined fdf */ gsl_multifit_function_fdf fdftik; /* Tikhonov modified fdf */ } gsl_multifit_fdfridge; gsl_multifit_fdfridge * gsl_multifit_fdfridge_alloc (const gsl_multifit_fdfsolver_type * T, const size_t n, const size_t p); void gsl_multifit_fdfridge_free(gsl_multifit_fdfridge *work); const char *gsl_multifit_fdfridge_name(const gsl_multifit_fdfridge * w); gsl_vector *gsl_multifit_fdfridge_position (const gsl_multifit_fdfridge * w); gsl_vector *gsl_multifit_fdfridge_residual (const gsl_multifit_fdfridge * w); size_t gsl_multifit_fdfridge_niter (const gsl_multifit_fdfridge * w); int gsl_multifit_fdfridge_set (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const double lambda); int gsl_multifit_fdfridge_wset (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const double lambda, const gsl_vector * wts); int gsl_multifit_fdfridge_set2 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_vector * lambda); int gsl_multifit_fdfridge_wset2 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_vector * lambda, const gsl_vector * wts); int gsl_multifit_fdfridge_set3 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_matrix * L); int gsl_multifit_fdfridge_wset3 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_matrix * L, const gsl_vector * wts); int gsl_multifit_fdfridge_iterate (gsl_multifit_fdfridge * w); int gsl_multifit_fdfridge_driver (gsl_multifit_fdfridge * w, const size_t maxiter, const double xtol, const double gtol, const double ftol, int *info); /* extern const gsl_multifit_fsolver_type * gsl_multifit_fsolver_gradient; */ GSL_VAR const gsl_multifit_fdfsolver_type * gsl_multifit_fdfsolver_lmsder; GSL_VAR const gsl_multifit_fdfsolver_type * gsl_multifit_fdfsolver_lmder; GSL_VAR const gsl_multifit_fdfsolver_type * gsl_multifit_fdfsolver_lmniel; __END_DECLS #endif /* __GSL_MULTIFIT_NLIN_H__ */
{ "alphanum_fraction": 0.6235801708, "avg_line_length": 41.1485507246, "ext": "h", "hexsha": "b0dd06e796b1785d2b5f9fb42bdde1ca8ac0aaea", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.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/gsl_multifit_nlin.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.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/gsl_multifit_nlin.h", "max_line_length": 116, "max_stars_count": 7, "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_multifit_nlin.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 2800, "size": 11357 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_linalg.h> #include "../include/run_svd.h" int main(void) { FILE *fp = fopen("./data/my_data.csv", "r"); if (fp == NULL) { perror("Unable to open file!"); exit(1); } int m = 4; int n = 5; char chunk[128]; const char s[2] = ","; int i = 0; int j = 0; gsl_matrix *mat = gsl_matrix_alloc(m, n); while (fgets(chunk, sizeof(chunk), fp) != NULL) { char *token; token = strtok(chunk, s); while (token != NULL) { double x = atof(token); gsl_matrix_set(mat, i, j, x); j = (j + 1) % n; if (j == 0) { i = (i + 1) % m; } token = strtok(NULL, s); } } printf("a_matrix\n"); pretty_print(mat); int result = run_svd(mat); fclose(fp); return result; }
{ "alphanum_fraction": 0.5340253749, "avg_line_length": 17, "ext": "c", "hexsha": "abf2bfbe9b406bf294c2e5d08cb2af19937923e9", "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": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "paul-reiners/getting-smaller", "max_forks_repo_path": "src/c/src/project.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "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": "paul-reiners/getting-smaller", "max_issues_repo_path": "src/c/src/project.c", "max_line_length": 51, "max_stars_count": null, "max_stars_repo_head_hexsha": "c1b9f0a0e72d7f92b9ce84aa111c063efcac1241", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "paul-reiners/getting-smaller", "max_stars_repo_path": "src/c/src/project.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 274, "size": 867 }
#ifndef S3D_CV_DISPARITY_DISPARITY_ANALYZER_STAN_H #define S3D_CV_DISPARITY_DISPARITY_ANALYZER_STAN_H #include <s3d/disparity/disparity_analyzer.h> #include "s3d/cv/features/match_finder_surf.h" #include "s3d/multiview/sampson_distance_function.h" #include "s3d/multiview/stan_fundamental_matrix_solver.h" #include "s3d/multiview/stan_results.h" #include "s3d/robust/ransac.h" #include "s3d/robust/lmeds.h" #include "s3d/utilities/math.h" #include "s3d/utilities/eigen.h" #include <opencv2/core/types.hpp> #include <gsl/gsl> namespace s3d { struct StanAlignment; class MatchFinderCV; class MatchFinderSurf; class DisparityAnalyzerSTAN : public DisparityAnalyzer { public: // can alternatively use Lmeds using RansacAlgorithmSTAN = s3d::robust::Lmeds<s3d::StanFundamentalMatrixSolver, s3d::SampsonDistanceFunction>; struct Results { explicit Results(); void updateParameters(double minDisparity, double maxDisparity, float widthRatio, RansacAlgorithmSTAN::ModelType model); void updatePoints(const std::vector<Eigen::Vector2d>& bestPtsLeft, const std::vector<Eigen::Vector2d>& bestPtsRight, std::vector<double> disparities, float widthRatio, float resizeRatio); StanResults stan; double minDisparityPercent{}; double maxDisparityPercent{}; std::vector<float> disparitiesPercent{}; }; DisparityAnalyzerSTAN(); gsl::owner<DisparityAnalyzerSTAN*> clone() const override; void setMatchFinder(std::unique_ptr<MatchFinderCV> matchFinder); void setMaxNumberOfFeatures(int maxNumberOfFeatures); bool analyze(const cv::Mat& left, const cv::Mat& right); bool analyze(const Image<uint8_t>& left, const Image<uint8_t>& right) override; const std::vector<float>& getDisparitiesPercent() const override; const std::vector<Eigen::Vector2f>& getFeaturePointsLeft() const override; const std::vector<Eigen::Vector2f>& getFeaturePointsRight() const override; void setMinimumNumberOfInliers(int minNbInliers); // outputs Results results; private: MatchFinder::Matches findMatches(const cv::Mat& left, const cv::Mat& right); bool enoughMatches(int nbOfMatches); RansacAlgorithmSTAN createRansac(Size imageSize); std::unique_ptr<MatchFinderCV> matchFinder_{std::make_unique<MatchFinderCV>()}; int minNbInliers_{4}; }; } // namespace s3d #endif // S3D_CV_DISPARITY_DISPARITY_ANALYZER_STAN_H
{ "alphanum_fraction": 0.728492502, "avg_line_length": 31.675, "ext": "h", "hexsha": "ed932d220a796a0d9a3b755edde920e4adae9744", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/core/cv/include/s3d/cv/disparity/disparity_analyzer_stan.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/core/cv/include/s3d/cv/disparity/disparity_analyzer_stan.h", "max_line_length": 89, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/core/cv/include/s3d/cv/disparity/disparity_analyzer_stan.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 656, "size": 2534 }
/* * This file is part of the ProVANT simulator project. * Licensed under the terms of the MIT open source license. More details at * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md */ /** * @file sdf_parser.h * @brief This file contains the declaration of the SDFParser class. * * @author Júnio Eduardo de Morais Aquino */ #ifndef PROVANT_SDF_READER_H #define PROVANT_SDF_READER_H #include <sdf/sdf.hh> #include <gsl/gsl> #include "sdf_status.h" /** * @brief The SDFParser class is a helper class to read properties from a SDF * Element object. * * This class is specially usefull during the loading of Gazebo plugins where * is necessary to read parameters from the plugin SDF description. * * A SDF (Simulation Description Format) Element, is a specialized XML element * that may contain attributes and child elements, as any other XML element * can. * * Gazebo provides a SDF Reader, but many times it has a confusing syntax and * very lax documentation, which is very hard to understand and discourages the * usage of the SDF class to read its own elements. * * As there were many instances in the ProVANT Simulator source code that * users and developers were using the now depreacted XMLRead class to read the * values of SDF elements, this class was designed as a substitution for the * XMLRead class, that wraps the methods provided by gazebo into well documented * and tested methods. * * So far, this class provides methods to check the existence, and returns the * string values of attributes and elements. In the future, it is very likely * that this class will also contain methods to read the values of elements in * other types, checking for adequate conversion and validity. * * @todo It turns out that is really hard to create SDF elements in memory * in order to do the testing of this class, so by now THIS CLASS IS UNTESTED! * It is imperative that we develop tests for this class. The tests are not * hard to create, the problem is that it creating SDF descriptions in memory * throws a series of undocumented errors and leads the test executable to a * segmentation fault, rendering the test procedure unfeasible. */ class SDFParser { public: /** * @brief Construct a new SDFParser object and initializes the SDF pointer. * * @param sdf SDF element to read data from. */ SDFParser(sdf::ElementPtr sdf); /** * @brief Destroy the SDFParser object. * Releases the shared pointer to the SDF element. */ virtual ~SDFParser(); /** * @brief Get the SDF ptr from which this class reads data from. * @return sdf::ElementPtr */ virtual sdf::ElementPtr GetElementPtr() const; /** * @brief Checks if the SDF contain an attribute with the specified name. * * Attributes are data specific to a element, that are usually strings. * For example, the following XML element: * @code{.xml} * <test type="example"> * <other_data/> * </test> * @endcode * * Contains an attribute named type and with value example. * * Usage example: * Suppose a plugin SDF description as follows: * @code{.xml} * <plugin name="example" filename="provant_simulator_step_plugin"> * <plugin_data/> * </plugin> * @endcode * * Assuming this plugin was read, the following code has res=true, because * the plugin contains an attribute "name". * @code{.cpp} * SDFParser reader(_sdf); * bool res = reader.HasAttribute("name"); * @endcode * * And the following code results in res=false, because the plugin does not * contain an attribute "type". * @code{.cpp} * SDFParser reader(_sdf); * bool res = reader.HasAttribute("type"); * @endcode * * @param name * @return true If the SDF element contains an attribute with the specified * name. * @return false Otherwise. */ virtual bool HasAttribute(const std::string& name) const; /** * @brief Checks if the SDF has an element with the specified name. * * Usage example: * Suppose a plugin SDF description as follows: * @code{.xml} * <plugin name="example" filename="provant_simulator_step_plugin"> * <plugin_data/> * </plugin> * @endcode * * Assuming this plugin was read, the following code has res=true, because * the plugin contains an element "plugin_data". * @code{.cpp} * SDFParser reader(_sdf); * bool res = reader.HasElement("plugin_data"); * @endcode * * And the following code results in res=false, because the plugin does not * contain an attribute "type". * @code{.cpp} * SDFParser reader(_sdf); * bool res = reader.HasElement("type"); * @endcode * * @param name Name of the element to look for. * @return true If the SDF contains an element with the specified name. * @return false Otherwise. */ virtual bool HasElement(const std::string& name) const; /** * @brief Get an attribute value. * * This checks if an attribute with the specified value exists, and if it * exists, copies its value to the value parameter. * * If the attribute does not exists, or any other occurs, an SDFStatus with an * error and a message describing the problem is returned, and the value is * left emtpy. * * @param name Name of the attribute to return. * @param value Buffer string that will contain the value of the attribute with the specified name. * @return SDFStatus that informs the status of the operation. If the * attribute is found and returned, a OkStatus object is returned, in the case * the attribute does not exist an AttributeNotFoundError object is returned, * containing an error status and a message informing the problem. */ virtual SDFStatus GetAttributeValue(const std::string& name, gsl::not_null<std::string*> value) const noexcept; /** * @brief Get an attribute value. * * This method checks if an attribute with the specified name exists, and if * it exists, returns its value. * * @param name Name of the attribute to locate. * @return std::string Value of the attribute. * @throw AttributeNotFoundError If an attribute with the specifed name does * not exist. */ virtual std::string GetAttributeValue(const std::string& name) const; /** * @brief Get the text value of a SDF element. * * Check if an element with the specified name exists, and if it exists, * copies its value to the value parameter. * * If an element with the specified name does not exist, or any other * error occurs, the value string is left empty, and a SDFStatus error is * returned with a message identifying the problem. * * @param name Name of the element to read the value. * @param value Buffer string that will contain the value of the element * @return SDFStatus that informs the status of the operation. If at least one * element with the specified name exists, a OkStatus object is returned. * In case an error occurs, an object identifying the problem is returned * with an errors status and a message describing the problem. */ virtual SDFStatus GetElementText(const std::string& name, gsl::not_null<std::string*> value) const noexcept; /** * @brief Get the text value of a SDF element. * * Check if an element with the specified name exists, and return is value. * * @sa GetElementText(const std::string& name, std::string* value) * * @param name Name of the element to read the value. * @return std::string Content of the element. * @throw ElementNotFoundError if the element cannot be found as a child of * the SDF element this class reads from. */ virtual std::string GetElementText(const std::string& name) const; /** * @brief Get the value of a boolean SDF element. * * The valid options are: * For true elements: true in any case combination, or 1. * For false elements: false in any case combinatation, or 0. * * @sa GetElementBool(const std::string&) * * @param name Name of the element to read. * @param value Content of the element. * @return SDFStatus Status of the parse operation. If the element was found * and had a valid value, an OKStatus is returned, otherwise an object * containing and error status and error message is returned. */ virtual SDFStatus GetElementBool(const std::string& name, gsl::not_null<bool*> value) const noexcept; /** * @brief Get the value of a boolean SDF element. * * The valid options are: * For true elements: true in any case combination, or 1. * For false elements: false in any case combinatation, or 0. * * @sa GetElementBool(const std::string&, gsl::not_null<int*>) * * @param name Name of the element to read. * @return Value of the element. * @throw SDFStatus exception in case the element is not found or has * invalid content, ie. content that cannot be parsed as a boolean. */ virtual bool GetElementBool(const std::string& name) const; /** * @brief Get the value of a int SDF element. * * This method can read integer values in the binary (0b), octal (0), decimal * (no prefix), or hexadecimal (0x) formats, identified by their prefixes. * It can also parse signed values with either a - or + signal. * * @sa GetElementInt(const std::string&) * * @param name Name of the element to read. * @param value Value of the element. * @return SDFStatus Status of the parse operation. If the element was found * and had a valid value, an OKStatus is returned, otherwise an object * containing and error status and error message is returned. */ virtual SDFStatus GetElementInt(const std::string& name, gsl::not_null<int*> value) const noexcept; /** * @brief Get the value of a int SDF element. * * This method can read integer values in the binary (0b), octal (0), decimal * (no prefix), or hexadecimal (0x) bases, identified by their prefixes. * It can also parse signed values with either a - or + signal. * * @sa GetElementInt(const std::string&, gsl::not_null<int*>) * * @param name Name of the element to read. * @return int Value of the element. * @throw SDFStatus exception in case the element is not found or has * invalid content, ie. content that cannot be parsed as an integer such as * string, or if the value of the element is beyond the current platform limits * for an integer value. */ virtual int GetElementInt(const std::string& name) const; /** * @brief Get the value of an unsigned int SDF element. * * This method can read unsigned integer values in the binary (0b), octal(0), * decimal (no prefix) or hexadecimal (0x) bases. * In case this methods find a signed integer, it returns an error. * * @sa GetElementUnsignedInt(const std::string&) * * @param name Name of the element to read. * @param value Value of the element. * @return SDFStatus Status of the parse operation. If the element was found * and had a valid value, an OKStatus is returned, otherwise an object * containing and error status and error message is returned. */ virtual SDFStatus GetElementUnsignedInt(const std::string& name, gsl::not_null<unsigned int*> value) const noexcept; /** * @brief Get the value of an unsigned int SDF element. * * This method can read unsigned integer values in the binary (0b), octal(0), * decimal (no prefix) or hexadecimal (0x) bases. * In case this methods find a signed integer, it throws an exception. * * @sa GetElementUnsignedInt(const std::string&, gsl::not_null<unsigned int*>) * * @param name Name of the element to read. * @return unsigned int Value of the element. * @throws SDFStatus exception in case the element is not found or has * invalid content, ie. content that cannot be parsed as an integer such as * string, if the value is signed, or if the value is beyond the limits of an * unsigned integer for the current platform. */ virtual unsigned int GetElementUnsignedInt(const std::string& name) const; /** * @brief Get the value of a single precision (float) SDF Element. * * This method can read real values as single precision floating point values * (float). It is also possible to read floats specified in the hexadecimal * format with the 0x prefix. * * @sa GetElementFloat(const std::string&) * * @param name Name of the element to read. * @param value Value of the element. * @return SDFStatus Status of the parse operation. If the element was found * and had a valid value, an OKStatus is returned, otherwise an object * containing and error status and error message is returned. */ virtual SDFStatus GetElementFloat(const std::string& name, gsl::not_null<float*> value) const noexcept; /** * @brief Get the value of a single precision (float) SDF Element. * * This method can read real values as single precision floating point values * (float). It is also possible to read floats specified in the hexadecimal * format with the 0x prefix. * * @sa GetElementFloat(const std::string&, gsl::not_null<float*>) * * @param name Name of the element to read. * @return float Value of the element. * @throws SDFStatus exception in case the element is not found or has * invalid content, ie. content that cannot be parsed as a float or is beyond * the limits of a float for the current platform. */ virtual float GetElementFloat(const std::string& name) const; /** * @brief Get the value of a double precision floating point (double) SDF Element. * * This method can read real values as double precision floating point values * (double). It is also possible to read doubles specified in the hexadecimal * format with the 0x prefix. * * @sa GetElementDouble(const std::string&) * * @param name Name of the element to read. * @param value Value of the element. * @return SDFStatus Status of the parse operation. If the element was found * and had a valid value, an OKStatus is returned, otherwise an object * containing and error status and error message is returned. */ virtual SDFStatus GetElementDouble(const std::string& name, gsl::not_null<double*> value) const noexcept; /** * @brief Get the value of a double precision floating point (double) SDF Element. * * This method can read real values as double precision floating point values * (double). It is also possible to read doubles specified in the hexadecimal * format with the 0x prefix. * * @sa GetElementDouble(const std::string&, gsl::not_null<double*>) * * @param name Name of the element to read. * @return double Value of the element. * @throws SDFStatus exception in case the element is not found or has * invalid content, ie. content that cannot be parsed as a double or is beyond * the limits of a double for the current platform. */ virtual double GetElementDouble(const std::string& name) const; private: //! Stores the pointer of the SDF from which this class reads the values of attributes and elements. sdf::ElementPtr _sdf; }; #endif // PROVANT_SDF_READER_H
{ "alphanum_fraction": 0.7039153856, "avg_line_length": 39.8481675393, "ext": "h", "hexsha": "40478c4979082a102eb2e3b4e0ce86b67de5fba0", "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": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Guiraffo/ProVANT_Simulator", "max_forks_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "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": "Guiraffo/ProVANT_Simulator", "max_issues_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Guiraffo/ProVANT_Simulator", "max_stars_repo_path": "provant_simulator_utils/provant_simulator_sdf_parser/include/provant_simulator_sdf_parser/sdf_parser.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3772, "size": 15222 }
/* -- MAGMA (version 2.5.4) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date October 2020 */ #ifndef MAGMA_TYPES_H #define MAGMA_TYPES_H #include <stdint.h> #include <assert.h> // for backwards compatability #ifdef HAVE_clAmdBlas #define HAVE_clBLAS #endif // each implementation of MAGMA defines HAVE_* appropriately. #if ! defined(HAVE_CUBLAS) && ! defined(HAVE_clBLAS) && ! defined(HAVE_MIC) #define HAVE_CUBLAS #endif // ============================================================================= // C99 standard defines __func__. Some older compilers use __FUNCTION__. // Note __func__ in C99 is not a macro, so ifndef __func__ doesn't work. #if __STDC_VERSION__ < 199901L #ifndef __func__ #if __GNUC__ >= 2 || _MSC_VER >= 1300 #define __func__ __FUNCTION__ #else #define __func__ "<unknown>" #endif #endif #endif // ============================================================================= // To use int64_t, link with mkl_intel_ilp64 or similar (instead of mkl_intel_lp64). // Similar to magma_int_t we declare magma_index_t used for row/column indices in sparse #if defined(MAGMA_ILP64) || defined(MKL_ILP64) typedef long long int magma_int_t; // MKL uses long long int, not int64_t #else typedef int magma_int_t; #endif typedef int magma_index_t; typedef unsigned int magma_uindex_t; // Define new type that the precision generator will not change (matches PLASMA) typedef double real_Double_t; // ============================================================================= // define types specific to implementation (CUDA, OpenCL, MIC) // define macros to deal with complex numbers #if defined(HAVE_CUBLAS) // include cublas_v2.h, unless cublas.h has already been included, e.g., via magma.h #ifndef CUBLAS_H_ #include <cuda.h> // for CUDA_VERSION #include <cublas_v2.h> #endif #include <cusparse_v2.h> #ifdef __cplusplus extern "C" { #endif // opaque queue structure struct magma_queue; typedef struct magma_queue* magma_queue_t; typedef cudaEvent_t magma_event_t; typedef magma_int_t magma_device_t; // Half precision in CUDA #if defined(__cplusplus) && CUDA_VERSION >= 7500 #include <cuda_fp16.h> typedef __half magmaHalf; #else // use short for cuda older than 7.5 // corresponding routines would not work anyway since there is no half precision typedef short magmaHalf; #endif // CUDA_VERSION >= 7500 typedef cuDoubleComplex magmaDoubleComplex; typedef cuFloatComplex magmaFloatComplex; cudaStream_t magma_queue_get_cuda_stream ( magma_queue_t queue ); cublasHandle_t magma_queue_get_cublas_handle ( magma_queue_t queue ); cusparseHandle_t magma_queue_get_cusparse_handle( magma_queue_t queue ); /// @addtogroup magma_complex /// @{ #define MAGMA_Z_MAKE(r,i) make_cuDoubleComplex(r, i) ///< @return complex number r + i*sqrt(-1). #define MAGMA_Z_REAL(a) (a).x ///< @return real component of a. #define MAGMA_Z_IMAG(a) (a).y ///< @return imaginary component of a. #define MAGMA_Z_ADD(a, b) cuCadd(a, b) ///< @return (a + b). #define MAGMA_Z_SUB(a, b) cuCsub(a, b) ///< @return (a - b). #define MAGMA_Z_MUL(a, b) cuCmul(a, b) ///< @return (a * b). #define MAGMA_Z_DIV(a, b) cuCdiv(a, b) ///< @return (a / b). #define MAGMA_Z_ABS(a) cuCabs(a) ///< @return absolute value, |a| = sqrt( real(a)^2 + imag(a)^2 ). #define MAGMA_Z_ABS1(a) (fabs((a).x) + fabs((a).y)) ///< @return 1-norm absolute value, | real(a) | + | imag(a) |. #define MAGMA_Z_CONJ(a) cuConj(a) ///< @return conjugate of a. #define MAGMA_C_MAKE(r,i) make_cuFloatComplex(r, i) #define MAGMA_C_REAL(a) (a).x #define MAGMA_C_IMAG(a) (a).y #define MAGMA_C_ADD(a, b) cuCaddf(a, b) #define MAGMA_C_SUB(a, b) cuCsubf(a, b) #define MAGMA_C_MUL(a, b) cuCmulf(a, b) #define MAGMA_C_DIV(a, b) cuCdivf(a, b) #define MAGMA_C_ABS(a) cuCabsf(a) #define MAGMA_C_ABS1(a) (fabsf((a).x) + fabsf((a).y)) #define MAGMA_C_CONJ(a) cuConjf(a) /// @} // end group magma_complex #ifdef __cplusplus } #endif #elif defined(HAVE_clBLAS) #include <clBLAS.h> #ifdef __cplusplus extern "C" { #endif typedef cl_command_queue magma_queue_t; typedef cl_event magma_event_t; typedef cl_device_id magma_device_t; typedef short magmaHalf; // placeholder until FP16 is supported typedef DoubleComplex magmaDoubleComplex; typedef FloatComplex magmaFloatComplex; cl_command_queue magma_queue_get_cl_queue( magma_queue_t queue ); #define MAGMA_Z_MAKE(r,i) doubleComplex(r,i) #define MAGMA_Z_REAL(a) (a).s[0] #define MAGMA_Z_IMAG(a) (a).s[1] #define MAGMA_Z_ADD(a, b) MAGMA_Z_MAKE((a).s[0] + (b).s[0], (a).s[1] + (b).s[1]) #define MAGMA_Z_SUB(a, b) MAGMA_Z_MAKE((a).s[0] - (b).s[0], (a).s[1] - (b).s[1]) #define MAGMA_Z_MUL(a, b) ((a) * (b)) #define MAGMA_Z_DIV(a, b) ((a) / (b)) #define MAGMA_Z_ABS(a) magma_cabs(a) #define MAGMA_Z_ABS1(a) (fabs((a).s[0]) + fabs((a).s[1])) #define MAGMA_Z_CONJ(a) MAGMA_Z_MAKE((a).s[0], -(a).s[1]) #define MAGMA_C_MAKE(r,i) floatComplex(r,i) #define MAGMA_C_REAL(a) (a).s[0] #define MAGMA_C_IMAG(a) (a).s[1] #define MAGMA_C_ADD(a, b) MAGMA_C_MAKE((a).s[0] + (b).s[0], (a).s[1] + (b).s[1]) #define MAGMA_C_SUB(a, b) MAGMA_C_MAKE((a).s[0] - (b).s[0], (a).s[1] - (b).s[1]) #define MAGMA_C_MUL(a, b) ((a) * (b)) #define MAGMA_C_DIV(a, b) ((a) / (b)) #define MAGMA_C_ABS(a) magma_cabsf(a) #define MAGMA_C_ABS1(a) (fabsf((a).s[0]) + fabsf((a).s[1])) #define MAGMA_C_CONJ(a) MAGMA_C_MAKE((a).s[0], -(a).s[1]) #ifdef __cplusplus } #endif #elif defined(HAVE_MIC) #include <complex> #ifdef __cplusplus extern "C" { #endif typedef int magma_queue_t; typedef int magma_event_t; typedef int magma_device_t; typedef short magmaHalf; // placeholder until FP16 is supported typedef std::complex<float> magmaFloatComplex; typedef std::complex<double> magmaDoubleComplex; #define MAGMA_Z_MAKE(r, i) std::complex<double>(r,i) #define MAGMA_Z_REAL(x) (x).real() #define MAGMA_Z_IMAG(x) (x).imag() #define MAGMA_Z_ADD(a, b) ((a)+(b)) #define MAGMA_Z_SUB(a, b) ((a)-(b)) #define MAGMA_Z_MUL(a, b) ((a)*(b)) #define MAGMA_Z_DIV(a, b) ((a)/(b)) #define MAGMA_Z_ABS(a) abs(a) #define MAGMA_Z_ABS1(a) (fabs((a).real()) + fabs((a).imag())) #define MAGMA_Z_CONJ(a) conj(a) #define MAGMA_C_MAKE(r, i) std::complex<float> (r,i) #define MAGMA_C_REAL(x) (x).real() #define MAGMA_C_IMAG(x) (x).imag() #define MAGMA_C_ADD(a, b) ((a)+(b)) #define MAGMA_C_SUB(a, b) ((a)-(b)) #define MAGMA_C_MUL(a, b) ((a)*(b)) #define MAGMA_C_DIV(a, b) ((a)/(b)) #define MAGMA_C_ABS(a) abs(a) #define MAGMA_C_ABS1(a) (fabs((a).real()) + fabs((a).imag())) #define MAGMA_C_CONJ(a) conj(a) #ifdef __cplusplus } #endif #else #error "One of HAVE_CUBLAS, HAVE_clBLAS, or HAVE_MIC must be defined. For example, add -DHAVE_CUBLAS to CFLAGS, or #define HAVE_CUBLAS before #include <magma.h>. In MAGMA, this happens in Makefile." #endif #ifdef __cplusplus extern "C" { #endif #define MAGMA_Z_EQUAL(a,b) (MAGMA_Z_REAL(a)==MAGMA_Z_REAL(b) && MAGMA_Z_IMAG(a)==MAGMA_Z_IMAG(b)) #define MAGMA_Z_NEGATE(a) MAGMA_Z_MAKE( -MAGMA_Z_REAL(a), -MAGMA_Z_IMAG(a)) #define MAGMA_C_EQUAL(a,b) (MAGMA_C_REAL(a)==MAGMA_C_REAL(b) && MAGMA_C_IMAG(a)==MAGMA_C_IMAG(b)) #define MAGMA_C_NEGATE(a) MAGMA_C_MAKE( -MAGMA_C_REAL(a), -MAGMA_C_IMAG(a)) #define MAGMA_D_MAKE(r,i) (r) #define MAGMA_D_REAL(x) (x) #define MAGMA_D_IMAG(x) (0.0) #define MAGMA_D_ADD(a, b) ((a) + (b)) #define MAGMA_D_SUB(a, b) ((a) - (b)) #define MAGMA_D_MUL(a, b) ((a) * (b)) #define MAGMA_D_DIV(a, b) ((a) / (b)) #define MAGMA_D_ABS(a) ((a)>0 ? (a) : -(a)) #define MAGMA_D_ABS1(a) ((a)>0 ? (a) : -(a)) #define MAGMA_D_CONJ(a) (a) #define MAGMA_D_EQUAL(a,b) ((a) == (b)) #define MAGMA_D_NEGATE(a) (-a) #define MAGMA_S_MAKE(r,i) (r) #define MAGMA_S_REAL(x) (x) #define MAGMA_S_IMAG(x) (0.0) #define MAGMA_S_ADD(a, b) ((a) + (b)) #define MAGMA_S_SUB(a, b) ((a) - (b)) #define MAGMA_S_MUL(a, b) ((a) * (b)) #define MAGMA_S_DIV(a, b) ((a) / (b)) #define MAGMA_S_ABS(a) ((a)>0 ? (a) : -(a)) #define MAGMA_S_ABS1(a) ((a)>0 ? (a) : -(a)) #define MAGMA_S_CONJ(a) (a) #define MAGMA_S_EQUAL(a,b) ((a) == (b)) #define MAGMA_S_NEGATE(a) (-a) #define MAGMA_Z_ZERO MAGMA_Z_MAKE( 0.0, 0.0) #define MAGMA_Z_ONE MAGMA_Z_MAKE( 1.0, 0.0) #define MAGMA_Z_HALF MAGMA_Z_MAKE( 0.5, 0.0) #define MAGMA_Z_NEG_ONE MAGMA_Z_MAKE(-1.0, 0.0) #define MAGMA_Z_NEG_HALF MAGMA_Z_MAKE(-0.5, 0.0) #define MAGMA_C_ZERO MAGMA_C_MAKE( 0.0, 0.0) #define MAGMA_C_ONE MAGMA_C_MAKE( 1.0, 0.0) #define MAGMA_C_HALF MAGMA_C_MAKE( 0.5, 0.0) #define MAGMA_C_NEG_ONE MAGMA_C_MAKE(-1.0, 0.0) #define MAGMA_C_NEG_HALF MAGMA_C_MAKE(-0.5, 0.0) #define MAGMA_D_ZERO ( 0.0) #define MAGMA_D_ONE ( 1.0) #define MAGMA_D_HALF ( 0.5) #define MAGMA_D_NEG_ONE (-1.0) #define MAGMA_D_NEG_HALF (-0.5) #define MAGMA_S_ZERO ( 0.0) #define MAGMA_S_ONE ( 1.0) #define MAGMA_S_HALF ( 0.5) #define MAGMA_S_NEG_ONE (-1.0) #define MAGMA_S_NEG_HALF (-0.5) #ifndef CBLAS_SADDR #define CBLAS_SADDR(a) &(a) #endif // for MAGMA_[CZ]_ABS double magma_cabs ( magmaDoubleComplex x ); float magma_cabsf( magmaFloatComplex x ); #if defined(HAVE_clBLAS) // OpenCL uses opaque memory references on GPU typedef cl_mem magma_ptr; typedef cl_mem magmaInt_ptr; typedef cl_mem magmaIndex_ptr; typedef cl_mem magmaFloat_ptr; typedef cl_mem magmaDouble_ptr; typedef cl_mem magmaFloatComplex_ptr; typedef cl_mem magmaDoubleComplex_ptr; typedef cl_mem magma_const_ptr; typedef cl_mem magmaInt_const_ptr; typedef cl_mem magmaIndex_const_ptr; typedef cl_mem magmaFloat_const_ptr; typedef cl_mem magmaDouble_const_ptr; typedef cl_mem magmaFloatComplex_const_ptr; typedef cl_mem magmaDoubleComplex_const_ptr; #else // MIC and CUDA use regular pointers on GPU typedef void *magma_ptr; typedef magma_int_t *magmaInt_ptr; typedef magma_index_t *magmaIndex_ptr; typedef magma_uindex_t *magmaUIndex_ptr; typedef float *magmaFloat_ptr; typedef double *magmaDouble_ptr; typedef magmaFloatComplex *magmaFloatComplex_ptr; typedef magmaDoubleComplex *magmaDoubleComplex_ptr; typedef magmaHalf *magmaHalf_ptr; typedef void const *magma_const_ptr; typedef magma_int_t const *magmaInt_const_ptr; typedef magma_index_t const *magmaIndex_const_ptr; typedef magma_uindex_t const *magmaUIndex_const_ptr; typedef float const *magmaFloat_const_ptr; typedef double const *magmaDouble_const_ptr; typedef magmaFloatComplex const *magmaFloatComplex_const_ptr; typedef magmaDoubleComplex const *magmaDoubleComplex_const_ptr; typedef magmaHalf const *magmaHalf_const_ptr; #endif // ============================================================================= // MAGMA constants // ----------------------------------------------------------------------------- #define MAGMA_VERSION_MAJOR 2 #define MAGMA_VERSION_MINOR 5 #define MAGMA_VERSION_MICRO 4 // stage is "svn", "beta#", "rc#" (release candidate), or blank ("") for final release #define MAGMA_VERSION_STAGE "" #define MagmaMaxGPUs 8 #define MagmaMaxAccelerators 8 #define MagmaMaxSubs 16 // trsv template parameter #define MagmaBigTileSize 1000000 // ----------------------------------------------------------------------------- // Return codes // LAPACK argument errors are < 0 but > MAGMA_ERR. // MAGMA errors are < MAGMA_ERR. /// @addtogroup magma_error_codes /// @{ #define MAGMA_SUCCESS 0 ///< operation was successful #define MAGMA_ERR -100 ///< unspecified error #define MAGMA_ERR_NOT_INITIALIZED -101 ///< magma_init() was not called #define MAGMA_ERR_REINITIALIZED -102 // unused #define MAGMA_ERR_NOT_SUPPORTED -103 ///< not supported on this GPU #define MAGMA_ERR_ILLEGAL_VALUE -104 // unused #define MAGMA_ERR_NOT_FOUND -105 ///< file not found #define MAGMA_ERR_ALLOCATION -106 // unused #define MAGMA_ERR_INTERNAL_LIMIT -107 // unused #define MAGMA_ERR_UNALLOCATED -108 // unused #define MAGMA_ERR_FILESYSTEM -109 // unused #define MAGMA_ERR_UNEXPECTED -110 // unused #define MAGMA_ERR_SEQUENCE_FLUSHED -111 // unused #define MAGMA_ERR_HOST_ALLOC -112 ///< could not malloc CPU host memory #define MAGMA_ERR_DEVICE_ALLOC -113 ///< could not malloc GPU device memory #define MAGMA_ERR_CUDASTREAM -114 // unused #define MAGMA_ERR_INVALID_PTR -115 ///< can't free invalid pointer #define MAGMA_ERR_UNKNOWN -116 ///< unspecified error #define MAGMA_ERR_NOT_IMPLEMENTED -117 ///< not implemented yet #define MAGMA_ERR_NAN -118 ///< NaN (not-a-number) detected // some MAGMA-sparse errors #define MAGMA_SLOW_CONVERGENCE -201 #define MAGMA_DIVERGENCE -202 #define MAGMA_NONSPD -203 #define MAGMA_ERR_BADPRECOND -204 #define MAGMA_NOTCONVERGED -205 // When adding error codes, please add to interface_cuda/error.cpp // map cusparse errors to magma errors #define MAGMA_ERR_CUSPARSE -3000 #define MAGMA_ERR_CUSPARSE_NOT_INITIALIZED -3001 #define MAGMA_ERR_CUSPARSE_ALLOC_FAILED -3002 #define MAGMA_ERR_CUSPARSE_INVALID_VALUE -3003 #define MAGMA_ERR_CUSPARSE_ARCH_MISMATCH -3004 #define MAGMA_ERR_CUSPARSE_MAPPING_ERROR -3005 #define MAGMA_ERR_CUSPARSE_EXECUTION_FAILED -3006 #define MAGMA_ERR_CUSPARSE_INTERNAL_ERROR -3007 #define MAGMA_ERR_CUSPARSE_MATRIX_TYPE_NOT_SUPPORTED -3008 #define MAGMA_ERR_CUSPARSE_ZERO_PIVOT -3009 /// @} // end group magma_error_codes // ----------------------------------------------------------------------------- // parameter constants // numbering is consistent with CBLAS and PLASMA; see plasma/include/plasma.h // also with lapack_cwrapper/include/lapack_enum.h // see http://www.netlib.org/lapack/lapwrapc/ typedef enum { MagmaFalse = 0, MagmaTrue = 1 } magma_bool_t; typedef enum { MagmaRowMajor = 101, MagmaColMajor = 102 } magma_order_t; // Magma_ConjTrans is an alias for those rare occasions (zlarfb, zun*, zher*k) // where we want Magma_ConjTrans to convert to MagmaTrans in precision generation. typedef enum { MagmaNoTrans = 111, MagmaTrans = 112, MagmaConjTrans = 113, Magma_ConjTrans = MagmaConjTrans } magma_trans_t; typedef enum { MagmaUpper = 121, MagmaLower = 122, MagmaFull = 123, /* lascl, laset */ MagmaHessenberg = 124 /* lascl */ } magma_uplo_t; typedef magma_uplo_t magma_type_t; /* lascl */ typedef enum { MagmaNonUnit = 131, MagmaUnit = 132 } magma_diag_t; typedef enum { MagmaLeft = 141, MagmaRight = 142, MagmaBothSides = 143 /* trevc */ } magma_side_t; typedef enum { MagmaOneNorm = 171, /* lange, lanhe */ MagmaRealOneNorm = 172, MagmaTwoNorm = 173, MagmaFrobeniusNorm = 174, MagmaInfNorm = 175, MagmaRealInfNorm = 176, MagmaMaxNorm = 177, MagmaRealMaxNorm = 178 } magma_norm_t; typedef enum { MagmaDistUniform = 201, /* latms */ MagmaDistSymmetric = 202, MagmaDistNormal = 203 } magma_dist_t; typedef enum { MagmaHermGeev = 241, /* latms */ MagmaHermPoev = 242, MagmaNonsymPosv = 243, MagmaSymPosv = 244 } magma_sym_t; typedef enum { MagmaNoPacking = 291, /* latms */ MagmaPackSubdiag = 292, MagmaPackSupdiag = 293, MagmaPackColumn = 294, MagmaPackRow = 295, MagmaPackLowerBand = 296, MagmaPackUpeprBand = 297, MagmaPackAll = 298 } magma_pack_t; typedef enum { MagmaNoVec = 301, /* geev, syev, gesvd */ MagmaVec = 302, /* geev, syev */ MagmaIVec = 303, /* stedc */ MagmaAllVec = 304, /* gesvd, trevc */ MagmaSomeVec = 305, /* gesvd, trevc */ MagmaOverwriteVec = 306, /* gesvd */ MagmaBacktransVec = 307 /* trevc */ } magma_vec_t; typedef enum { MagmaRangeAll = 311, /* syevx, etc. */ MagmaRangeV = 312, MagmaRangeI = 313 } magma_range_t; typedef enum { MagmaQ = 322, /* unmbr, ungbr */ MagmaP = 323 } magma_vect_t; typedef enum { MagmaForward = 391, /* larfb */ MagmaBackward = 392 } magma_direct_t; typedef enum { MagmaColumnwise = 401, /* larfb */ MagmaRowwise = 402 } magma_storev_t; typedef enum { MagmaHybrid = 701, MagmaNative = 702 } magma_mode_t; // ----------------------------------------------------------------------------- // sparse typedef enum { Magma_CSR = 611, Magma_ELLPACKT = 612, Magma_ELL = 613, Magma_DENSE = 614, Magma_BCSR = 615, Magma_CSC = 616, Magma_HYB = 617, Magma_COO = 618, Magma_ELLRT = 619, Magma_SPMVFUNCTION = 620, Magma_SELLP = 621, Magma_ELLD = 622, Magma_CSRLIST = 623, Magma_CSRD = 624, Magma_CSRL = 627, Magma_CSRU = 628, Magma_CSRCOO = 629, Magma_CUCSR = 630, Magma_COOLIST = 631, Magma_CSR5 = 632 } magma_storage_t; typedef enum { Magma_CG = 431, Magma_CGMERGE = 432, Magma_GMRES = 433, Magma_BICGSTAB = 434, Magma_BICGSTABMERGE = 435, Magma_BICGSTABMERGE2 = 436, Magma_JACOBI = 437, Magma_GS = 438, Magma_ITERREF = 439, Magma_BCSRLU = 440, Magma_PCG = 441, Magma_PGMRES = 442, Magma_PBICGSTAB = 443, Magma_PASTIX = 444, Magma_ILU = 445, Magma_ICC = 446, Magma_PARILU = 447, Magma_PARIC = 448, Magma_BAITER = 449, Magma_LOBPCG = 450, Magma_NONE = 451, Magma_FUNCTION = 452, Magma_IDR = 453, Magma_PIDR = 454, Magma_CGS = 455, Magma_PCGS = 456, Magma_CGSMERGE = 457, Magma_PCGSMERGE = 458, Magma_TFQMR = 459, Magma_PTFQMR = 460, Magma_TFQMRMERGE = 461, Magma_PTFQMRMERGE = 462, Magma_QMR = 463, Magma_PQMR = 464, Magma_QMRMERGE = 465, Magma_PQMRMERGE = 466, Magma_BOMBARD = 490, Magma_BOMBARDMERGE = 491, Magma_PCGMERGE = 492, Magma_BAITERO = 493, Magma_IDRMERGE = 494, Magma_PBICGSTABMERGE = 495, Magma_PARICT = 496, Magma_CUSTOMIC = 497, Magma_CUSTOMILU = 498, Magma_PIDRMERGE = 499, Magma_BICG = 500, Magma_BICGMERGE = 501, Magma_PBICG = 502, Magma_PBICGMERGE = 503, Magma_LSQR = 504, Magma_PARILUT = 505, Magma_ISAI = 506, Magma_CUSOLVE = 507, Magma_VBJACOBI = 508, Magma_PARDISO = 509, Magma_SYNCFREESOLVE= 510, Magma_ILUT = 511 } magma_solver_type; typedef enum { Magma_CGSO = 561, Magma_FUSED_CGSO = 562, Magma_MGSO = 563 } magma_ortho_t; typedef enum { Magma_CPU = 571, Magma_DEV = 572 } magma_location_t; typedef enum { Magma_GENERAL = 581, Magma_SYMMETRIC = 582 } magma_symmetry_t; typedef enum { Magma_ORDERED = 591, Magma_DIAGFIRST = 592, Magma_UNITY = 593, Magma_VALUE = 594 } magma_diagorder_t; typedef enum { Magma_DCOMPLEX = 501, Magma_FCOMPLEX = 502, Magma_DOUBLE = 503, Magma_FLOAT = 504 } magma_precision; typedef enum { Magma_NOSCALE = 511, Magma_UNITROW = 512, Magma_UNITDIAG = 513, Magma_UNITCOL = 514, Magma_UNITROWCOL = 515, // to be deprecated Magma_UNITDIAGCOL = 516, // to be deprecated } magma_scale_t; typedef enum { Magma_SOLVE = 801, Magma_SETUPSOLVE = 802, Magma_APPLYSOLVE = 803, Magma_DESTROYSOLVE = 804, Magma_INFOSOLVE = 805, Magma_GENERATEPREC = 806, Magma_PRECONDLEFT = 807, Magma_PRECONDRIGHT = 808, Magma_TRANSPOSE = 809, Magma_SPMV = 810 } magma_operation_t; typedef enum { Magma_PREC_SS = 900, Magma_PREC_SST = 901, Magma_PREC_HS = 902, Magma_PREC_HST = 903, Magma_PREC_SH = 904, Magma_PREC_SHT = 905, Magma_PREC_XHS_H = 910, Magma_PREC_XHS_HTC = 911, Magma_PREC_XHS_161616 = 912, Magma_PREC_XHS_161616TC = 913, Magma_PREC_XHS_161632TC = 914, Magma_PREC_XSH_S = 915, Magma_PREC_XSH_STC = 916, Magma_PREC_XSH_163232TC = 917, Magma_PREC_XSH_323232TC = 918, Magma_REFINE_IRSTRS = 920, Magma_REFINE_IRDTRS = 921, Magma_REFINE_IRGMSTRS = 922, Magma_REFINE_IRGMDTRS = 923, Magma_REFINE_GMSTRS = 924, Magma_REFINE_GMDTRS = 925, Magma_REFINE_GMGMSTRS = 926, Magma_REFINE_GMGMDTRS = 927, Magma_PREC_HD = 930, } magma_refinement_t; typedef enum { Magma_MP_BASE_SS = 950, Magma_MP_BASE_DD = 951, Magma_MP_BASE_XHS = 952, Magma_MP_BASE_XSH = 953, Magma_MP_BASE_XHD = 954, Magma_MP_BASE_XDH = 955, Magma_MP_ENABLE_DFLT_MATH = 960, Magma_MP_ENABLE_TC_MATH = 961, Magma_MP_SGEMM = 962, Magma_MP_HGEMM = 963, Magma_MP_GEMEX_I32_O32_C32 = 964, Magma_MP_GEMEX_I16_O32_C32 = 965, Magma_MP_GEMEX_I16_O16_C32 = 966, Magma_MP_GEMEX_I16_O16_C16 = 967, Magma_MP_TC_SGEMM = 968, Magma_MP_TC_HGEMM = 969, Magma_MP_TC_GEMEX_I32_O32_C32 = 970, Magma_MP_TC_GEMEX_I16_O32_C32 = 971, Magma_MP_TC_GEMEX_I16_O16_C32 = 972, Magma_MP_TC_GEMEX_I16_O16_C16 = 973, } magma_mp_type_t; // When adding constants, remember to do these steps as appropriate: // 1) add magma_xxxx_const() converter below and in control/constants.cpp // 2a) add to magma2lapack_constants[] in control/constants.cpp // 2b) update min & max here, which are used to check bounds for magma2lapack_constants[] // 2c) add lapack_xxxx_const() converter below and in control/constants.cpp #define Magma2lapack_Min MagmaFalse // 0 #define Magma2lapack_Max MagmaRowwise // 402 // ----------------------------------------------------------------------------- // string constants for calling Fortran BLAS and LAPACK // todo: use translators instead? lapack_const_str( MagmaUpper ) #define MagmaRowMajorStr "Row" #define MagmaColMajorStr "Col" #define MagmaNoTransStr "NoTrans" #define MagmaTransStr "Trans" #define MagmaConjTransStr "ConjTrans" #define Magma_ConjTransStr "ConjTrans" #define MagmaUpperStr "Upper" #define MagmaLowerStr "Lower" #define MagmaFullStr "Full" #define MagmaNonUnitStr "NonUnit" #define MagmaUnitStr "Unit" #define MagmaLeftStr "Left" #define MagmaRightStr "Right" #define MagmaBothSidesStr "Both" #define MagmaOneNormStr "1" #define MagmaTwoNormStr "2" #define MagmaFrobeniusNormStr "Fro" #define MagmaInfNormStr "Inf" #define MagmaMaxNormStr "Max" #define MagmaForwardStr "Forward" #define MagmaBackwardStr "Backward" #define MagmaColumnwiseStr "Columnwise" #define MagmaRowwiseStr "Rowwise" #define MagmaNoVecStr "NoVec" #define MagmaVecStr "Vec" #define MagmaIVecStr "IVec" #define MagmaAllVecStr "All" #define MagmaSomeVecStr "Some" #define MagmaOverwriteVecStr "Overwrite" // ----------------------------------------------------------------------------- // Convert LAPACK character constants to MAGMA constants. // This is a one-to-many mapping, requiring multiple translators // (e.g., "N" can be NoTrans or NonUnit or NoVec). magma_bool_t magma_bool_const ( char lapack_char ); magma_order_t magma_order_const ( char lapack_char ); magma_trans_t magma_trans_const ( char lapack_char ); magma_uplo_t magma_uplo_const ( char lapack_char ); magma_diag_t magma_diag_const ( char lapack_char ); magma_side_t magma_side_const ( char lapack_char ); magma_norm_t magma_norm_const ( char lapack_char ); magma_dist_t magma_dist_const ( char lapack_char ); magma_sym_t magma_sym_const ( char lapack_char ); magma_pack_t magma_pack_const ( char lapack_char ); magma_vec_t magma_vec_const ( char lapack_char ); magma_range_t magma_range_const ( char lapack_char ); magma_vect_t magma_vect_const ( char lapack_char ); magma_direct_t magma_direct_const( char lapack_char ); magma_storev_t magma_storev_const( char lapack_char ); // ----------------------------------------------------------------------------- // Convert MAGMA constants to LAPACK(E) constants. // The generic lapack_const_str works for all cases, but the specific routines // (e.g., lapack_trans_const) do better error checking. // magma defines lapack_const_str, which returns char* to call lapack (Fortran interface). // plasma defines lapack_const, which is roughly the same as MAGMA's lapacke_const // (returns a char instead of char*) to call lapacke (C interface). const char* lapack_const_str ( int magma_const ); const char* lapack_bool_const ( magma_bool_t magma_const ); const char* lapack_order_const ( magma_order_t magma_const ); const char* lapack_trans_const ( magma_trans_t magma_const ); const char* lapack_uplo_const ( magma_uplo_t magma_const ); const char* lapack_diag_const ( magma_diag_t magma_const ); const char* lapack_side_const ( magma_side_t magma_const ); const char* lapack_norm_const ( magma_norm_t magma_const ); const char* lapack_dist_const ( magma_dist_t magma_const ); const char* lapack_sym_const ( magma_sym_t magma_const ); const char* lapack_pack_const ( magma_pack_t magma_const ); const char* lapack_vec_const ( magma_vec_t magma_const ); const char* lapack_range_const ( magma_range_t magma_const ); const char* lapack_vect_const ( magma_vect_t magma_const ); const char* lapack_direct_const( magma_direct_t magma_const ); const char* lapack_storev_const( magma_storev_t magma_const ); static inline char lapacke_const ( int magma_const ) { return *lapack_const_str ( magma_const ); } static inline char lapacke_bool_const ( magma_bool_t magma_const ) { return *lapack_bool_const ( magma_const ); } static inline char lapacke_order_const ( magma_order_t magma_const ) { return *lapack_order_const ( magma_const ); } static inline char lapacke_trans_const ( magma_trans_t magma_const ) { return *lapack_trans_const ( magma_const ); } static inline char lapacke_uplo_const ( magma_uplo_t magma_const ) { return *lapack_uplo_const ( magma_const ); } static inline char lapacke_diag_const ( magma_diag_t magma_const ) { return *lapack_diag_const ( magma_const ); } static inline char lapacke_side_const ( magma_side_t magma_const ) { return *lapack_side_const ( magma_const ); } static inline char lapacke_norm_const ( magma_norm_t magma_const ) { return *lapack_norm_const ( magma_const ); } static inline char lapacke_dist_const ( magma_dist_t magma_const ) { return *lapack_dist_const ( magma_const ); } static inline char lapacke_sym_const ( magma_sym_t magma_const ) { return *lapack_sym_const ( magma_const ); } static inline char lapacke_pack_const ( magma_pack_t magma_const ) { return *lapack_pack_const ( magma_const ); } static inline char lapacke_vec_const ( magma_vec_t magma_const ) { return *lapack_vec_const ( magma_const ); } static inline char lapacke_range_const ( magma_range_t magma_const ) { return *lapack_range_const ( magma_const ); } static inline char lapacke_vect_const ( magma_vect_t magma_const ) { return *lapack_vect_const ( magma_const ); } static inline char lapacke_direct_const( magma_direct_t magma_const ) { return *lapack_direct_const( magma_const ); } static inline char lapacke_storev_const( magma_storev_t magma_const ) { return *lapack_storev_const( magma_const ); } // ----------------------------------------------------------------------------- // Convert MAGMA constants to clBLAS constants. #if defined(HAVE_clBLAS) clblasOrder clblas_order_const( magma_order_t order ); clblasTranspose clblas_trans_const( magma_trans_t trans ); clblasUplo clblas_uplo_const ( magma_uplo_t uplo ); clblasDiag clblas_diag_const ( magma_diag_t diag ); clblasSide clblas_side_const ( magma_side_t side ); #endif // ----------------------------------------------------------------------------- // Convert MAGMA constants to CUBLAS constants. #if defined(CUBLAS_V2_H_) cublasOperation_t cublas_trans_const ( magma_trans_t trans ); cublasFillMode_t cublas_uplo_const ( magma_uplo_t uplo ); cublasDiagType_t cublas_diag_const ( magma_diag_t diag ); cublasSideMode_t cublas_side_const ( magma_side_t side ); #endif // ----------------------------------------------------------------------------- // Convert MAGMA constants to CBLAS constants. #if defined(HAVE_CBLAS) #include <cblas.h> enum CBLAS_ORDER cblas_order_const ( magma_order_t order ); enum CBLAS_TRANSPOSE cblas_trans_const ( magma_trans_t trans ); enum CBLAS_UPLO cblas_uplo_const ( magma_uplo_t uplo ); enum CBLAS_DIAG cblas_diag_const ( magma_diag_t diag ); enum CBLAS_SIDE cblas_side_const ( magma_side_t side ); #endif #ifdef __cplusplus } #endif #endif // MAGMA_TYPES_H
{ "alphanum_fraction": 0.6217909973, "avg_line_length": 36.6375291375, "ext": "h", "hexsha": "aab2929f067d83f8557c782b41dc7137b526c33d", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-03-27T00:50:27.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T13:23:36.000Z", "max_forks_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "klast/magma", "max_forks_repo_path": "include/magma_types.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_issues_repo_issues_event_max_datetime": "2021-03-28T06:19:59.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-27T20:00:25.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "klast/magma", "max_issues_repo_path": "include/magma_types.h", "max_line_length": 202, "max_stars_count": 4, "max_stars_repo_head_hexsha": "cfb849621be6f697288e995831ec3c9e84530d9d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "klast/magma", "max_stars_repo_path": "include/magma_types.h", "max_stars_repo_stars_event_max_datetime": "2021-12-10T11:41:23.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-04T13:31:18.000Z", "num_tokens": 9103, "size": 31435 }
#pragma once #include <gsl/span> namespace miner { template<class T, std::ptrdiff_t Extent = gsl::dynamic_extent> using span = gsl::span<T, Extent>; template<std::ptrdiff_t Extent = gsl::dynamic_extent> using ByteSpan = span<uint8_t, Extent>; template<std::ptrdiff_t Extent = gsl::dynamic_extent> using cByteSpan = span<const uint8_t, Extent>; }
{ "alphanum_fraction": 0.6931216931, "avg_line_length": 25.2, "ext": "h", "hexsha": "bea4b89e75728338eb68c475579ea41bcaf8842a", "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": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "oldas1/Riner", "max_forks_repo_path": "src/common/Span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "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": "oldas1/Riner", "max_issues_repo_path": "src/common/Span.h", "max_line_length": 66, "max_stars_count": null, "max_stars_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "oldas1/Riner", "max_stars_repo_path": "src/common/Span.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 99, "size": 378 }
/* Copyright [2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __MM_PLUGIN_ITF_H__ #define __MM_PLUGIN_ITF_H__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-function" #define PUBLIC __attribute__((__visibility__("default"))) #if defined(__cplusplus) #pragma GCC diagnostic ignored "-Weffc++" #include <common/byte_span.h> #include <gsl/span> #include <functional> #endif #include <stdlib.h> #include <assert.h> #if defined(__cplusplus) extern "C" { #endif typedef int status_t; typedef void * mm_plugin_heap_t; typedef void (*request_memory_callback_t)(void * param, size_t alignment, size_t size_hint, void * addr_hint); typedef void (*release_memory_callback_t)(void * param, void * addr, size_t size); /** * Initialize mm library * * @return S_OK, E_FAIL */ status_t mm_plugin_init(); /** * Create a heap instance * * @param params Constructor parameters (e.g., JSON) * @param root_ptr Root point for persistent heaps * @param out_heap Heap context * * @return S_OK, E_FAIL */ status_t mm_plugin_create(const char * params, void * root_ptr, mm_plugin_heap_t * out_heap); /** * Delete a heap instance * * @param heap Heap context to destroy * * @return S_OK, E_INVAL, E_FAIL */ status_t mm_plugin_destroy(mm_plugin_heap_t heap); /** * Add (slab) region of memory to fuel the allocator. The passthru * allocator does not need this as it takes directly from the OS. * * @param heap Heap context * @param region_base Pointer to beginning of region * @param region_size Region length in bytes * * @return E_NOT_IMPL, S_OK, E_FAIL, E_INVAL */ status_t mm_plugin_add_managed_region(mm_plugin_heap_t heap, void * region_base, size_t region_size); /** * Query memory regions being used by the allocator * * @param heap Heap context * @param region_id Index counting from 0 * @param [out] Base address of region * @param [out] Size of region in bytes * * @return S_MORE (continue to next region id), S_OK (done), E_INVAL */ status_t mm_plugin_query_managed_region(mm_plugin_heap_t heap, unsigned region_id, void** out_region_base, size_t* out_region_size); /** * Register callback the allocator can use to request more memory * * @param heap Heap context * @param callback Call back function pointer * @param param Optional parameter which will be pass to callback function * * @return E_NOT_IMPL, S_OK */ status_t mm_plugin_register_callback_request_memory(mm_plugin_heap_t heap, request_memory_callback_t callback, void * param); /** * Allocate a region of memory without alignment or hint * * @param heap Heap context * @param Length in bytes * @param [out] Pointer to allocated region * * @return S_OK or E_FAIL */ status_t mm_plugin_allocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr); /** * Allocation region of memory that is aligned * * @param heap Heap context * @param n Size of region in bytes * @param alignment Alignment in bytes * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region * * @return S_OK, E_FAIL, E_INVAL (depending on implementation) */ status_t mm_plugin_aligned_allocate(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr); /** * Special case for EASTL * * @param heap Heap context * @param n Size of region in bytes * @param alignment Alignment in bytes * @param offset Offset from start of region to location within region which satisfies alignment * @param out_ptr Address if [in] nullptr, [out] pointer to allocated region * * @return */ status_t mm_plugin_aligned_allocate_offset(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr); /** * Free a previously allocated region of memory with length known * * @param heap Heap context * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr * @param size Length of region in bytes * * @return S_OK or E_INVAL; */ status_t mm_plugin_deallocate(mm_plugin_heap_t heap, void ** ptr, size_t size); /** * Free previously allocated region without known length * * @param heap Heap context * @param ptr Address of [in] pointer to previously allocated region, [out] nullptr * * @return S_OK */ status_t mm_plugin_deallocate_without_size(mm_plugin_heap_t heap, void ** ptr); /** * Allocate region and zero memory * * @param heap Heap context * @param size Size of region in bytes * @param ptr [out] Pointer to allocated region * * @return S_OK */ status_t mm_plugin_callocate(mm_plugin_heap_t heap, size_t n, void ** out_ptr); /* The POSIX realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc(), or realloc(). If the area pointed to was moved, a free(ptr) is done. */ /** * Resize an existing allocation * * @param heap Heap context * @param in_out_ptr Address of pointer to [in] existing allocated region, [out] new reallocated region or null if unable to reallocate * @param size New size in bytes * * * @return S_OK */ status_t mm_plugin_reallocate(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size); /** * Get the number of usable bytes in block pointed to by ptr. The * allocator *may* not have this information and should then return * E_NOT_IMPL. Returned size may be larger than requested allocation * * @param heap Heap context * @param ptr Pointer to block base * @param out_ptr [out] Number of bytes in allocated block * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_usable_size(mm_plugin_heap_t heap, void * ptr, size_t * out_size); /** * Inject an allocation back into the allocator (reconstituing) * * @param heap Heap context * @param ptr Pointer to region of memory to mark allocated * @param size Size of region in bytes * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_inject_allocation(mm_plugin_heap_t heap, void * ptr, size_t size); /** * Report bytes remaining * * @param bytes_remaining Bytes remaining for allocation * * @return S_OK, E_NOT_IMPL */ status_t mm_plugin_bytes_remaining(mm_plugin_heap_t heap, size_t *bytes_remaining); /** * Get debugging information * * @param heap Heap context */ void mm_plugin_debug(mm_plugin_heap_t heap); /** * Check for crash consistency libccpm behavior) * * @return non-zero iff the root_ptr parameter of mm_plugin_create is interpreted as a struct ccpm_params *. */ int mm_plugin_is_crash_consistent(mm_plugin_heap_t heap); /** * Check for inject_allocation capability * * @return non-zero iff mm_plugin_inject_allocation is implemented */ int mm_plugin_can_inject_allocation(mm_plugin_heap_t heap); /** * Function pointer table for all methods * */ typedef struct tag_mm_plugin_function_table_t { status_t (*mm_plugin_init)(); status_t (*mm_plugin_create)(const char * params, void * root_ptr , mm_plugin_heap_t * out_heap); status_t (*mm_plugin_destroy)(mm_plugin_heap_t heap); status_t (*mm_plugin_add_managed_region)(mm_plugin_heap_t heap, void * region_base, size_t region_size); status_t (*mm_plugin_query_managed_region)(mm_plugin_heap_t heap, unsigned region_id, void** out_region_base, size_t* out_region_size); status_t (*mm_plugin_register_callback_request_memory)(mm_plugin_heap_t heap, request_memory_callback_t callback, void * param); status_t (*mm_plugin_allocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr); status_t (*mm_plugin_aligned_allocate)(mm_plugin_heap_t heap, size_t n, size_t alignment, void ** out_ptr); status_t (*mm_plugin_aligned_allocate_offset)(mm_plugin_heap_t heap, size_t n, size_t alignment, size_t offset, void ** out_ptr); status_t (*mm_plugin_deallocate)(mm_plugin_heap_t heap, void ** ptr, size_t size); status_t (*mm_plugin_deallocate_without_size)(mm_plugin_heap_t heap, void ** ptr); status_t (*mm_plugin_callocate)(mm_plugin_heap_t heap, size_t n, void ** out_ptr); status_t (*mm_plugin_reallocate)(mm_plugin_heap_t heap, void ** in_out_ptr, size_t size); status_t (*mm_plugin_usable_size)(mm_plugin_heap_t heap, void * ptr, size_t * out_size); status_t (*mm_plugin_bytes_remaining)(mm_plugin_heap_t heap, size_t * bytes_remaining); void (*mm_plugin_debug)(mm_plugin_heap_t heap); status_t (*mm_plugin_inject_allocation)(mm_plugin_heap_t heap, void * ptr, size_t size); int (*mm_plugin_is_crash_consistent)(mm_plugin_heap_t heap); int (*mm_plugin_can_inject_allocation)(mm_plugin_heap_t heap); } mm_plugin_function_table_t; #if defined(__cplusplus) } #endif #if defined(__cplusplus) #include <dlfcn.h> #include <string> #include <stdio.h> #include <stdexcept> #define LOAD_SYMBOL(X) _ft.X = reinterpret_cast<decltype(_ft.X)>(dlsym(_module, # X)); assert(_ft.X) /** * C++ wrapper on C-based plugin API * */ class MM_plugin_wrapper { public: MM_plugin_wrapper(const std::string& plugin_path, const std::string& config = "", void * root_ptr = nullptr) { assert(plugin_path.empty() == false); _module = dlopen(plugin_path.c_str(), RTLD_NOW | RTLD_NODELETE); // RTLD_DEEPBIND | if(_module == nullptr) { char err[1024]; sprintf(err, "%s\n", dlerror()); throw std::invalid_argument(err); } LOAD_SYMBOL(mm_plugin_init); LOAD_SYMBOL(mm_plugin_create); LOAD_SYMBOL(mm_plugin_add_managed_region); LOAD_SYMBOL(mm_plugin_query_managed_region); LOAD_SYMBOL(mm_plugin_register_callback_request_memory); LOAD_SYMBOL(mm_plugin_allocate); LOAD_SYMBOL(mm_plugin_aligned_allocate); LOAD_SYMBOL(mm_plugin_aligned_allocate_offset); LOAD_SYMBOL(mm_plugin_deallocate); LOAD_SYMBOL(mm_plugin_deallocate_without_size); LOAD_SYMBOL(mm_plugin_callocate); LOAD_SYMBOL(mm_plugin_reallocate); LOAD_SYMBOL(mm_plugin_usable_size); LOAD_SYMBOL(mm_plugin_debug); LOAD_SYMBOL(mm_plugin_destroy); LOAD_SYMBOL(mm_plugin_inject_allocation); LOAD_SYMBOL(mm_plugin_bytes_remaining); LOAD_SYMBOL(mm_plugin_is_crash_consistent); LOAD_SYMBOL(mm_plugin_can_inject_allocation); // dlclose(_module); /* create heap instance */ _ft.mm_plugin_create(config.c_str(), root_ptr, &_heap); } MM_plugin_wrapper(const MM_plugin_wrapper &) = delete; MM_plugin_wrapper(MM_plugin_wrapper && other) noexcept : _module(std::move(other._module)) , _ft(std::move(other._ft)) , _heap(std::move(other._heap)) { other._heap = nullptr; } virtual ~MM_plugin_wrapper() noexcept { if ( _heap ) { _ft.mm_plugin_destroy(_heap); } } /* forwarding in liners */ inline status_t init() noexcept { return _ft.mm_plugin_init(); } inline status_t add_managed_region(void * region_base, size_t region_size) noexcept { return _ft.mm_plugin_add_managed_region(_heap, region_base, region_size); } inline status_t query_managed_region(unsigned region_id, void** out_region_base, size_t* out_region_size) noexcept { return _ft.mm_plugin_query_managed_region(_heap, region_id, out_region_base, out_region_size); } inline status_t register_callback_request_memory(request_memory_callback_t callback, void * param) noexcept { return _ft.mm_plugin_register_callback_request_memory(_heap, callback, param); } inline status_t allocate(size_t n, void ** out_ptr) noexcept { return _ft.mm_plugin_allocate(_heap, n, out_ptr); } inline status_t aligned_allocate(size_t n, size_t alignment, void ** out_ptr) noexcept { return _ft.mm_plugin_aligned_allocate(_heap, n, alignment, out_ptr); } inline status_t aligned_allocate_offset(size_t n, size_t alignment, size_t offset, void ** out_ptr) noexcept { return _ft.mm_plugin_aligned_allocate_offset(_heap, n, alignment, offset, out_ptr); } inline status_t deallocate(void ** ptr, size_t size) noexcept { return _ft.mm_plugin_deallocate(_heap, ptr, size); } inline status_t deallocate_without_size(void ** ptr) noexcept { return _ft.mm_plugin_deallocate_without_size(_heap, ptr); } inline status_t callocate(size_t n, void ** out_ptr) noexcept { return _ft.mm_plugin_callocate(_heap, n, out_ptr); } inline status_t reallocate(void ** in_out_ptr, size_t size) noexcept { return _ft.mm_plugin_reallocate(_heap, in_out_ptr, size); } inline status_t usable_size(void * ptr, size_t * out_size) noexcept { return _ft.mm_plugin_usable_size(_heap, ptr, out_size); } inline status_t bytes_remaining(size_t *bytes_remaining) const noexcept { return _ft.mm_plugin_bytes_remaining(_heap, bytes_remaining); } inline void debug(mm_plugin_heap_t heap) noexcept { return _ft.mm_plugin_debug(_heap); } inline status_t inject_allocation(void * ptr, size_t size) noexcept { return _ft.mm_plugin_inject_allocation(_heap, ptr, size); } inline int is_crash_consistent() noexcept { return _ft.mm_plugin_is_crash_consistent(_heap); } inline int can_inject_allocation() noexcept { return _ft.mm_plugin_can_inject_allocation(_heap); } private: void * _module; mm_plugin_function_table_t _ft; #if 0 /* intention, but we avoid appealing to moveable_ptr */ common::moveable_ptr<void> _heap; #else void * _heap; #endif }; #include <limits> #include <new> /** * Standard C++ allocator wrapper * */ template <class T> class MM_plugin_cxx_allocator { public: using value_type = T; using pointer = value_type*; using const_pointer = typename std::pointer_traits<pointer>::template rebind<value_type const>; using void_pointer = typename std::pointer_traits<pointer>::template rebind<void>; using const_void_pointer = typename std::pointer_traits<pointer>::template rebind<const void>; using difference_type = typename std::pointer_traits<pointer>::difference_type; using size_type = std::make_unsigned_t<difference_type>; template <class U> struct rebind {typedef MM_plugin_cxx_allocator<U> other;}; MM_plugin_cxx_allocator(MM_plugin_wrapper& wrapper) noexcept : _wrapper(wrapper) { } template <class U> MM_plugin_cxx_allocator(MM_plugin_cxx_allocator<U> const& a_) noexcept : _wrapper(a_._wrapper) {} pointer allocate(std::size_t n) { pointer p = nullptr; auto status = _wrapper.allocate(n*sizeof(value_type), reinterpret_cast<void**>(&p)); if(status != 0) throw std::bad_alloc(); return p; } void deallocate(pointer p, std::size_t n) noexcept { _wrapper.deallocate(reinterpret_cast<void**>(&p), n); } pointer allocate(std::size_t n, const_void_pointer) { return allocate(n); } template <class U, class ...Args> void construct(U* p, Args&& ...args) { ::new(p) U(std::forward<Args>(args)...); } template <class U> void destroy(U* p) noexcept { p->~U(); } std::size_t max_size() const noexcept { return std::numeric_limits<size_type>::max(); } MM_plugin_cxx_allocator select_on_container_copy_construction() const { return *this; } using propagate_on_container_copy_assignment = std::false_type; using propagate_on_container_move_assignment = std::false_type; using propagate_on_container_swap = std::false_type; using is_always_equal = std::is_empty<MM_plugin_cxx_allocator>; MM_plugin_wrapper& _wrapper; }; template <class T, class U> bool operator==(MM_plugin_cxx_allocator<T> const&, MM_plugin_cxx_allocator<U> const&) noexcept { return true; } template <class T, class U> bool operator!=(MM_plugin_cxx_allocator<T> const& x, MM_plugin_cxx_allocator<U> const& y) noexcept { return !(x == y); } #undef LOAD_SYMBOL #endif #pragma GCC diagnostic pop #endif // __MM_PLUGIN_ITF_H__
{ "alphanum_fraction": 0.6860420014, "avg_line_length": 32.4003590664, "ext": "h", "hexsha": "f2a16d84033022745de7d811fcc27af341309846", "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/mm/mm_plugin_itf.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/mm/mm_plugin_itf.h", "max_line_length": 137, "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/mm/mm_plugin_itf.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": 4318, "size": 18047 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_ccopy (const int N, const void *X, const int incX, void *Y, const int incY) { #define BASE float #include "source_copy_c.h" #undef BASE }
{ "alphanum_fraction": 0.6808510638, "avg_line_length": 18.0769230769, "ext": "c", "hexsha": "c4716dd0968d7ae5b8415a28b830203238cd0957", "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/ccopy.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/ccopy.c", "max_line_length": 65, "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/ccopy.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": 72, "size": 235 }
/** * @file iftCommon.h * @brief Common definitions and functions to remaining modules. */ #ifndef IFT_COMMON_H #define IFT_COMMON_H #ifdef __cplusplus extern "C" { #endif #include <stdarg.h> #include <assert.h> #include <cblas.h> #include <ctype.h> #include <dirent.h> #include <float.h> #include <libgen.h> #include <limits.h> #include <math.h> #include <mm_malloc.h> #include <regex.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #ifdef __linux #include <dirent.h> #include <omp.h> #endif #if !defined(__APPLE__) #include <malloc.h> #endif #if defined(__linux) #endif #include "iftBasicDataTypes.h" #include "iftMemory.h" #include "iftDialog.h" #include "iftString.h" /** * Common definitions */ #ifndef PI #define PI IFT_PI #endif typedef enum ift_axis_order { XYZ, XZY, YXZ, YZX, ZXY, ZYX } iftAxisOrder; #define IFT_RANDOM_SEED (unsigned int) 213344 #define IFT_MAXWEIGHT 4095.0 #define IFT_AXIS_X 0 #define IFT_AXIS_Y 1 #define IFT_AXIS_Z 2 #define IFT_PI 3.14159265358979323846 #define IFT_INTERIOR 0 #define IFT_EXTERIOR 1 #define IFT_BOTH 2 #define IFT_WHITE 0 #define IFT_GRAY 1 #define IFT_BLACK 2 #define IFT_NIL -1 #define IFT_INCREASING 1 #define IFT_DECREASING 0 #define IFT_EPSILON 1E-07 #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif /** * Common operations */ #ifndef iftMax #define iftMax(x,y) (((x) > (y))?(x):(y)) #endif #ifndef iftMin #define iftMin(x,y) (((x) < (y))?(x):(y)) #endif #define iftRound(x) ((x < 0)?(int)(x-0.5):(int)(x+0.5)) #define iftSign(x) ((x >= 0)?1:-1) /** @brief Euclidean Distance between voxels or points */ #define iftPointDistance(u,v) (sqrtf((u.x-v.x)*(u.x-v.x)+(u.y-v.y)*(u.y-v.y)+(u.z-v.z)*(u.z-v.z))) /** @brief Euclidean Distance between voxels or porints */ #define iftVoxelDistance(u,v) iftPointDistance(u,v) /** @brief Computes the Squared Distance between two voxels or points */ #define iftSquaredVoxelDistance(u,v) ((u.x-v.x)*(u.x-v.x)+(u.y-v.y)*(u.y-v.y)+(u.z-v.z)*(u.z-v.z)) /* @brief Computes the Smooth Euclidean Distances from a pre-computed Squared Euclidean distance among 26-neighbors * @param squared_dist The pre-computed Squared Euclidean Distance among 26-neighbors. The details are in N. Kiryati and G. Sze kely, "Estimating shortest paths and minimal distances on digitized three-dimensional surfaces," Pattern Recognition, vol. 26, pp. 1623-1637, 1993. * @return The resulting Smooth Euclidean Distance */ #define iftSmoothEuclideanDistance(squared_dist) ((fabs(squared_dist-1)<1.0e-6)? 0.9016 : (fabs(squared_dist-2)<1.0e-6)? 1.289 : 1.615 ) /** * @brief Converts a Point to a Voxel * @author Samuel * @date May 24, 2016 */ #define iftPointToVoxel(point) ((iftVoxel) {(int) (point).x, (int) (point).y, (int) (point).z}) /** * @brief Converts a Voxel to a Point * @author Samuel * @date May 24, 2016 */ #define iftVoxelToPoint(v) ((iftPoint) {(v).x, (v).y, (v).z}) #define iftImageCenter(img) ((iftVoxel){((img)->xsize - 1)/2, ((img)->ysize - 1)/2, ((img)->zsize - 1)/2}) /** @brief Constant used to align memory */ #define IFT_MEMORY_ALIGNMENT 16 /** * @brief Init the GPU devices. * @warning If not called, the GPU devices will be started in the first call for a GPU function. * @author Peixinho */ void iftStartGPU(); /** * @brief Stop the GPU devices. * @author Peixinho */ void iftStopGPU(); /** * @brief Checks if the long positive number is prime or not. * @author Samuel Martins * @date Jan 17th, 2016 * @note Based on https://en.wikipedia.org/wiki/Primality_test */ bool iftIsPrime(long n); /** * @brief Computes a fast power for small integer exponents. * @param base * @param b * @return Returns base^b * @author Peixinho * @date May, 2016 * @warning The funcion is faster upto b=10, after that the regular function pow is called. */ double iftFastPow(double base, unsigned b); /** * @brief Prints a Float array on stdout of lentgh <n>. */ void iftPrintFloatArray(float* v, int n); /** * @brief Prints a Double array on stdout of lentgh <n>. */ void iftPrintDoubleArray(double* v, int n); /** * @brief Prints an Integer array on stdout of lentgh <n>. */ void iftPrintIntArray(int* v, int n); /** * @brief Returns a random integer number between low and high. */ int iftRandomInteger (int low, int high); /** * @brief Randomly selects nelems of the set [low, high] */ int *iftRandomIntegers (int low, int high, int nelems); /** * @brief Randomly selects a normal distributed (N(0,1)) float number */ float iftRandomNormalFloat(void); /** * @brief Returns initial time */ timer *iftTic(void); /** * @brief Returns final time */ timer *iftToc(void); /** * @brief Prints the computational time from tstart to tend, as obtained by iftTic() and iftToc() functions. */ void iftPrintCompTime(timer *tstart, timer *tend, const char *msg, ...); /** * @brief Computes the difference in ms from the initial time to the final time. * * @param tic The initial time. * @param toc The final time. * * @return The computed time difference in milliseconds. * * @warning The memory allocated for <tic> and <toc> is freed inside this function. */ float iftCompTime(timer *tic, timer *toc); /** * @brief Returns a string with the formatted time: days hours mins secs ms. * * @author Samuel * * Given a time in ms, this function returns a formatted time: days hours mins secs ms. * The runtime in MILISECONDS can be obtained with the function iftCompTime(timer *tic, timer *toc). * * @param runtime Time in ms. * @return The formatted time. */ char *iftFormattedTime(float runtime); /** * @brief Prints the runtime in the following format: days hours mins secs ms. * * @author Samuel Martins * @date October 23, 2015 * @sa iftFormattedTime() * * Given a time in ms, this function prints the runtime following the format: days hours mins secs ms. * The runtime in MILISECONDS can be obtained with the function iftCompTime(timer *tic, timer *toc). * * @param runtime Time in ms. */ void iftPrintFormattedTime(float runtime); /** * @brief Writes a timer to a given file, using the following format %s: %f, where %s is the * given information corresponding to the time and %f is the current time in milliseconds. * * @param tic is freed by the function. */ void iftWriteTimerToFile(const char *filename, const char *information, timer *tic); /** * @brief Generates seed for rand(), used in iftRandomInteger. */ void iftRandomSeed(unsigned int); /** * @brief Returns the factorial of a number or NIL in case of overflow */ long double iftFactorial(int n); /** * @brief Returns the limit to avoid overflow in factorial computation */ int iftFactorialLimit(void); void iftUnitNorm(float *feats, int nelems); void iftNormalizeFeatures(float *feats, int nelems); float iftSquaredFeatDistance(float *A, float *B, int n); float iftFeatDistance(float *A, float *B, int n); /** * @brief Computes the Manhattan Distance between two arrays of float considering the sinal, ie., * wihout the module between the feature difference: dist = (b[0]-a[0]) + (b[1]-a[1]) + ... */ float iftSignedManhattanDistance(float *A, float *B, int n); /** * @brief Computes the log(val) in the specified base. * @author Peixinho */ double iftLog(double val, double base); /** * @brief Returns the Central Voxel from the Bounding Box * @author Samuel Martins * @date Mar 15, 2016 * @ingroup Geometry */ iftVoxel iftCenterFromBoundingBox(iftBoundingBox bb); /** * @brief Vector operations defined as macros so that iftVoxels, iftVectors, and iftPoints may be used interchangeably. */ /** * @brief Subtracts point vec1 from vec2 (it works for iftVectors/iftVoxels/iftPoints). * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorSub(vec1, vec2) {(vec1).x - (vec2).x, (vec1).y - (vec2).y, (vec1).z - (vec2).z} /** * @brief Adds points vec1 and vec2 (it works for iftVectors/iftVoxels/iftPoints). * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorSum(vec1, vec2) {(vec1).x + (vec2).x, (vec1).y + (vec2).y, (vec1).z + (vec2).z} /** * @brief Computes the cross product between two voxels, points, or vectors. * * @author Thiago Vallin Spina (changed the macro function's name) * @date Mar 04, 2016 * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorCrossProd(a, b) {(a).y*(b).z - (a).z*(b).y, (a).z*(b).x - (a).x*(b).z, (a).x*(b).y - (a).y*(b).x} /** * @brief Computes the inner product between two voxels, points, or vectors. * * @author Thiago Vallin Spina (changed the macro function's name) * @date Mar 04, 2016 * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorInnerProduct(a, b) (((a).x*(b).x + (a).y*(b).y + (a).z*(b).z)) /** * @brief Computes the Vector Magnitude from a voxel or point * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * */ #define iftVectorMagnitude(v) (sqrtf(iftVectorInnerProduct((v),(v)))) /** * @brief Returns the XY angle of a 2D vector * @author Peixinho * @date April, 2016 * @ingroup Geometry */ #define iftVectorXYAngle(v) ( (atan2(v.y, v.x)+IFT_PI) * (180.0/IFT_PI) ) /** * @brief Rounds a vector to integer coordinates. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorRound(vec1) {iftRound((vec1).x), iftRound((vec1).y), iftRound((vec1).z)} /** * @brief Multiplies a vector by an scalar. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorScalarProd(vec, s) {(vec).x*(s), (vec).y*(s), (vec).z*(s)} /** * @brief Adds an scalar to a vector. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ #define iftVectorScalarSum(vec, s) {(vec).x+(s), (vec).y+(s), (vec).z+(s)} /** * @brief Divides a vector by an scalar. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @return The vector divided by the scalar, or the vector itself if the scalar is close to 0.0 * * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint. */ iftVector iftVectorScalarDiv(iftVector vec, double s); /** * @brief Verifies if a vector has coordinates (0, 0, 0). * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ #define iftIsNullVector(vec) (iftAlmostZero((vec).x) && iftAlmostZero((vec).y) && iftAlmostZero((vec).z)) /** * @brief Verifies if three points, voxels, or vectors are collinear. * * This is achieved by testing if the cross product between the vectors P1->P2 and P1->P3 is Null (0,0,0). * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ #define iftCollinearPoints(P1, P2, P3) (iftIsNullVector((iftVector)iftVectorCrossProd((iftVector)iftVectorSub((P2), (P1)), (iftVector)iftVectorSub((P3), (P1))))) /** * @brief Tests if two iftVoxels are equal * * @author Thiago Vallin Spina * @date Apr 19, 2016 * * @param u1 The first voxel * @param u2 The second voxel * @return True if their coordinates are the same */ bool iftVoxelsAreEqual(iftVoxel u1, iftVoxel u2); /** * @brief Computes the mean voxel * * @author Thiago Vallin Spina * @date May 1, 2016 * * @param u1 The first voxel * @param u2 The second voxel * @return The mean voxel (u1 + u2) / 2 */ iftVoxel iftMeanVoxel(iftVoxel u1, iftVoxel u2); /** * @brief Tests if two iftPoints/iftVectors are equal * * @author Thiago Vallin Spina * @date Apr 19, 2016 * * @param u1 The first point/vector * @param u2 The second point/vector * @return True if their coordinates are (almost) the same */ #define iftVectorsAreEqual(u1, u2) (iftAlmostZero((u1).x-(u2).x) && iftAlmostZero((u1).y-(u2).y) && \ iftAlmostZero((u1).z-(u2).z)) /** * @brief Normalizes a vector if its norm is greater than 0.0, otherwise returns the vector itself. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ iftVector iftNormalizeVector(iftVector v); /** * @brief Projects vector U onto vector V. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry * * @warning If vector V has norm close to 0.0 the function issues and iftError. */ iftVector iftProjectVector(iftVector U, iftVector V); /** * @brief Returns the distance between P0 and the line from P1 to P2, whose size is P1P2 * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ double iftVoxelLineDist2D(iftVoxel P0, iftVoxel P1, iftVoxel P2, double P1P2); /** * @brief Given the vector from P1 to P0, returns the voxel projected on the line between P1 and P2. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ iftVoxel iftClosestVoxelOnLine2D(iftVoxel P0, iftVoxel P1, iftVoxel P2); /** * @brief Returns the position of P0 with respect to the line from P1 to P2. * * Negative values indicate left side, 0 indicates on the line, * and positive values indicate right side. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * @ingroup Geometry */ int iftVoxelLinePosition2D(iftVoxel P0, iftVoxel P1, iftVoxel P2); /** * @brief Computes the circle's area given a radius. * * @author Thiago Vallin Spina * @date Mar 04, 2016 * * @ingroup Geometry */ static inline double iftCircleArea(double r) { return (r*r)*IFT_PI; } /* @brief Gets rid of the carriage return and the line feed characteres introduced by DOS systems when reading * strings from ASCII files. * * @author Alexandre Xavier Falcao * * @param line The string in which all carriage return characters are removed. */ void iftRemoveCarriageReturn(char *line); /** * @brief Evaluates the sigmoid function, with x = value. * * @param alfa Controls the decay of the function. * @author Renzo Phellan */ float iftSigmoidalValue(float value, float alfa); void iftVerifyToken(FILE *fp, char *token, char *function); void iftReadIntValue(FILE *fp, int *value, char *token, char *function); void iftReadIntValues(FILE *fp, int **value, int nvalues, char *token, char *function); void iftWriteIntValue(FILE *fp, int value, char *token); void iftWriteIntValues(FILE *fp, int *value, int nvalues, char *token); void iftReadFloatValue(FILE *fp, float *value, char *token, char *function); void iftReadFloatValues(FILE *fp, float **value, int nvalues, char *token, char *function); void iftWriteFloatValue(FILE *fp, float value, char *token); void iftWriteFloatValues(FILE *fp, float *value, int nvalues, char *token); void iftReadDoubleValue(FILE *fp, double *value, char *token, char *function); void iftReadDoubleValues(FILE *fp, double **value, int nvalues, char *token, char *function); void iftWriteDoubleValue(FILE *fp, double value, char *token); void iftWriteDoubleValues(FILE *fp, double *value, int nvalues, char *token); void iftSkipComments(FILE *fp); /* These functions are currently used to communicate with numpy */ void iftWriteRawIntArray(char *filename, int *array, int n); int* iftReadRawIntArray(char *filename, int n); /** * @brief Computes the mean value of a float array. */ float iftMean(float *x, int n); /** * @brief Computes the variance of a float array. */ float iftVar(float *x, int n); /** * @brief Computes the covariance of float arrays. */ float iftCov(float *x, float *y, int n); /** * @brief Tests if a real (float/double) number is zero. It should be used for comparisons if two floats are equal. * * @author Thiago Vallin Spina */ int iftAlmostZero(double x); /** * @brief Computes the mod operation of <a> by <n>. If the mod value is negative, it is placed within [0,n-1]. */ int iftSafeMod(int a, int n); /** * @brief Gets an Integer Array with the Unique Elements from an Input Array. * * Ex: Given the array = [1, 2, 3, 4, 4, 3, 2, 1], with size n = 8, the resulting array of unique elements will be: * [1, 2, 3, 4] * * @param array Input Int Array to be scanned. * @param n Number of Elements from the Input Int Array. * @return An Integer Array with the Unique Elements from <b>array</b>. */ iftIntArray *iftIntArrayUnique(const int *array, int n); /** * @brief Counts the Number of Unique Elements from an array. * * @param array Integer Array whose Number of Unique Elements will be counted. * @param n Array Size. * @return The number of Unique Elements. */ int iftCountUniqueIntElems(const int *array, int n); /** * @brief This function finds the most suitable normalization value to be used during image color/feature conversion/normalization. * * It is afunction of the most common number of bits in imaging sensors. It assumes that these values are in {1, 8, 10, * 12, 16, 24, 32} bits per voxel. * * @author Alexandre Xavier Falcao. * * @param maxval The maximum value of an image, for instance. */ int iftNormalizationValue(int maxval); /** * @brief Converts a number in radians to degrees. * * @author Thiago Vallin Spina */ static inline double iftDegrees(double rad) { return rad * 180.0 / IFT_PI; } /** * @brief Converts a number in degrees to radians. * * @author Thiago Vallin Spina */ static inline double iftRadians(double deg) { return deg * IFT_PI / 180.0; } /** * @brief Converts a negative radian number to positive. * * @author Thiago Vallin Spina */ static inline double iftNegativeToPositiveRadians(double rad) { return (rad < 0) ? 2 * IFT_PI + rad : rad; } /** * @brief Converts a negative degree number to positive. * * @author Thiago Vallin Spina */ static inline double iftNegativeToPositiveDegrees(double deg) { return (deg < 0) ? 360.0+deg : deg; } /** * @brief Compute the index of the element in vector x with minimum value * * @param x Float vector. * @param n Size of the vectors. * @return index. */ int iftArgmin(const int *x, int n); /** * @brief Compute the index of the element in vector x with maximum value * * @param x Float vector. * @param n Size of the vectors. * @return index. */ int iftArgmax(const int *x, int n); /** * @brief Compute the index of the element in vector x with minimum value * * @param x Float vector. * @param n Size of the vectors. * @return index. */ int iftFArgmin(const float *x, int n); /** * @brief Compute the index of the element in vector x with maximum value * * @param x Float vector. * @param n Size of the vectors. * @return index. */ int iftFArgmax(const float *x, int n); /** * @brief Compute the index of the element in vector x with minimum value * * @param x Double vector. * @param n Size of the vectors. * @return index. */ int iftDArgmin(const double *x, int n); /** * @brief Compute the index of the element in vector x with maximum value * * @param x Double vector. * @param n Size of the vectors. * @return index. */ int iftDArgmax(const double *x, int n); /** * @brief Finds the index of <elem> in array <x> and returns it. * * @author Peixinho * * @param x Unsorted array of elements. * @param n The size of the array. * @param elem The elem to be found. * * @return The element's index in <x> or NIL if not found */ int iftFindIntArrayElementIndex(int *x, int n, int elem); /** * @brief Compute the Gaussian Probability Density Function for a set of values. * @author Samuel Martins * @date May 12, 2016 * * @param vals Array of Values to compute the Gaussian PDF. * @param n_vals Number of values. * @param mean Mean used to compute the Gaussian PDF. * @param stdev Standard Deviation used to compute the Gaussian PDF. * @return Array of probabilities, one for each input value. */ double *iftGaussPDF(double *vals, size_t n_vals, double mean, double stdev); /** * @brief Compute the Cumulative Density of the (Gaussian) PDF (Normal Distribution) in a Random Variable with value x. * @author Samuel Martins * @date May 12, 2016 * * It gives the Area under the Probability Density Function (Normal Distribution) from minus infinity to x. \n * Then, it also describes the probability that a random variable X takes on a value less than or * equal to a number x. \n * * @param x Value from the Random Variable to compute the CDF. * @param mean Mean used to compute the Gaussian PDF. * @param stdev Standard Deviation used to compute the Gaussian PDF. * @return The area under the PDF from minus to x. */ double iftCDF(double x, double mean, double stdev); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.6921803302, "avg_line_length": 27.3821243523, "ext": "h", "hexsha": "c3c8ed3a7450801acac310db25c67a87ef2d2b89", "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": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Fabio-Kubo/processamento-imagens", "max_forks_repo_path": "include/iftCommon.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "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": "Fabio-Kubo/processamento-imagens", "max_issues_repo_path": "include/iftCommon.h", "max_line_length": 275, "max_stars_count": null, "max_stars_repo_head_hexsha": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Fabio-Kubo/processamento-imagens", "max_stars_repo_path": "include/iftCommon.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6140, "size": 21139 }
#ifndef IFT_COMMON_H_ #define IFT_COMMON_H_ #include <omp.h> #include <stdlib.h> #include <stdio.h> #if !defined(__APPLE__) #include <malloc.h> #endif #include <math.h> #include <string.h> #include <limits.h> #include <float.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <assert.h> #include <cblas.h> #include <dirent.h> #include <regex.h> /* * Common data types */ #define INFINITY_INT INT_MAX #define INFINITY_FLT FLT_MAX #define INFINITY_DBL DBL_MAX #define INFINITY_LDBL LDBL_MAX typedef struct timeval timer; typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long long ullong; typedef struct ift_band { float *val; } iftBand; typedef struct ift_vector { float x,y,z; } iftVector, iftPoint; typedef struct ift_voxel { int x,y,z; } iftVoxel; typedef struct ift_dcomplex { double r; double i; } iftComplex; typedef struct file_list { char **filesRoutes; char **filesNames; int n; } fileList; typedef struct ift_name_metric_pair { char *name; float metric; } iftNameMetricPair; /** * Common definitions */ #define IFT_RANDOM_SEED (unsigned int) 213344 #define MAXWEIGHT 4095.0 #define AXIS_X 0 #define AXIS_Y 1 #define AXIS_Z 2 #define PI 3.1415926536 #define INTERIOR 0 #define EXTERIOR 1 #define BOTH 2 #define WHITE 0 #define GRAY 1 #define BLACK 2 #define NIL -1 #define INCREASING 1 #define DECREASING 0 #define Epsilon 1E-05 /** * Common operations */ #ifndef MAX #define MAX(x,y) (((x) > (y))?(x):(y)) #endif #ifndef MIN #define MIN(x,y) (((x) < (y))?(x):(y)) #endif #define ROUND(x) ((x < 0)?(int)(x-0.5):(int)(x+0.5)) #define SIGN(x) ((x >= 0)?1:-1) /** * Common functions to allocate memory */ char *iftAllocCharArray(int n); uchar *iftAllocUCharArray(int n); short *iftAllocShortArray(int n); ushort *iftAllocUShortArray(int n); uint *iftAllocUIntArray(int n); ullong *iftAllocULLongArray(int n); int *iftAllocIntArray(int n); float *iftAllocFloatArray(int n); double *iftAllocDoubleArray(int n); iftComplex *iftAllocComplexArray(int n); long double *iftAllocLongDoubleArray(int n); void iftPrintFloatArray(float* v, int n); /** * Error messages */ #define MSG1 "Cannot allocate memory space" #define MSG2 "Cannot open file" /** * Error message msg is printed in function func and the program * exits abnormally. */ void iftError(char *msg,char *func); /** * Warning message msg is printed in function func and the program * continues. */ void iftWarning(char *msg,char *func); /** * The contents of a and b are interchanged. */ void iftSwitchValues(int *a, int *b); void iftSSwitchValues(char *a, char *b, int size); void iftFSwitchValues(float *a, float *b); void iftDSwitchValues(double *a, double *b); void iftSwitchVoxels(iftVoxel *u, iftVoxel *v); /** * Returns a random integer number between low and high. */ int iftRandomInteger (int low, int high); /* * Randomly selects nelems of the set [low, high] */ int *iftRandomIntegers (int low, int high, int nelems); /** * Randomly selects a normal distributed (N(0,1)) float number */ float iftRandomNormalFloat(void); /** * Returns the distance between P0 and the line from P1 to P2, whose * size is P1P2 */ float iftVoxelLineDist2D(iftVoxel P0, iftVoxel P1, iftVoxel P2, float P1P2); /** * Returns the position of P0 with respect to the line from P1 to * P2. Negative values indicate left side, 0 indicates on the line, * and positive values indicate right side. */ int iftVoxelLinePosition2D (iftVoxel P0, iftVoxel P1, iftVoxel P2); /** * Returns initial time */ timer *iftTic(void); /** * Returns final time */ timer *iftToc(void); /** * Computes the difference in ms from the initial time to the final time */ float iftCompTime(timer *tic, timer *toc); /** * Generates seed for rand(), used in iftRandomInteger. */ void iftRandomSeed(unsigned int); /** * Returns the factorial of a number or NIL in case of overflow */ long double iftFactorial(int n); /** * Returns the limit to avoid overflow in factorial computation */ int iftFactorialLimit(void); float iftVoxelDistance(iftVoxel u, iftVoxel v); int iftSquaredVoxelDistance(iftVoxel u, iftVoxel v); float iftPointDistance(iftPoint u, iftPoint v); int iftVoxelSquareDistance(iftVoxel u, iftVoxel v); float iftInnerProduct(iftVector a, iftVector b); iftVector iftCrossProduct(iftVector a, iftVector b); char iftCollinearPoints(iftPoint P1, iftPoint P2, iftPoint P3); char iftCollinearVoxels(iftVoxel P1, iftVoxel P2, iftVoxel P3); iftVector iftNormalizeVector(iftVector v); void iftNormalizeFloatArray(float *array, int nelems); float iftVectorMagnitude(iftVector v); void iftRemoveCarriageReturn(char *token); /* useful to get rid of the carriage return and the line feed characteres introduced by DOS systems when reading strings from ASCII files */ void iftWriteFloatArray(float *v, int size, char *filename); float *iftReadFloatArray(char *filename, int *size); /** * Evaluates the sigmoid function, with x = value. * Alfa controls the decay of the function. */ float iftSigmoidalValue(float value, float alfa); void iftVerifyToken(FILE *fp, char *token, char *function); void iftReadIntValue(FILE *fp, int *value, char *token, char *function); void iftReadIntValues(FILE *fp, int **value, int nvalues, char *token, char *function); void iftWriteIntValue(FILE *fp, int value, char *token); void iftWriteIntValues(FILE *fp, int *value, int nvalues, char *token); void iftReadFloatValue(FILE *fp, float *value, char *token, char *function); void iftReadFloatValues(FILE *fp, float **value, int nvalues, char *token, char *function); void iftWriteFloatValue(FILE *fp, float value, char *token); void iftWriteFloatValues(FILE *fp, float *value, int nvalues, char *token); void iftReadDoubleValue(FILE *fp, double *value, char *token, char *function); void iftReadDoubleValues(FILE *fp, double **value, int nvalues, char *token, char *function); void iftWriteDoubleValue(FILE *fp, double value, char *token); void iftWriteDoubleValues(FILE *fp, double *value, int nvalues, char *token); void iftSkipComments(FILE *fp); char iftVoxelsAreEqual(iftVoxel u1, iftVoxel u2); char iftPointsAreEqual(iftPoint u1, iftPoint u2); /** * Common function to handle arrays */ void iftCopyFloatArray(float *array1, float *array2, int nelems); void iftCopyIntArray(int *array1, int *array2, int nelems); int *iftMergeIntArray(int *array1, int n1, int *array2, int n2, int *nelems); int *iftIntArrayOfUniqueElemsTransform(int *array, int *n); fileList *iftCreateFileList(void); void iftDestroyFileList(fileList **list); fileList *iftGetFiles(char *dirname, char *type); /* These functions are currently used to communicate with numpy */ void iftWriteRawIntArray(char *filename, int *array, int n); int* iftReadRawIntArray(char *filename, int n); float iftMean(float *x, int n); float iftVar(float *x, int n); float iftCov(float *x, float *y, int n); int iftAlmostZero(float x); #endif
{ "alphanum_fraction": 0.7062850883, "avg_line_length": 23.8660130719, "ext": "h", "hexsha": "34dc8eda690326abe44c5894296ccfb73e44d121", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-11-20T22:53:06.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-20T22:53:06.000Z", "max_forks_repo_head_hexsha": "ad2419f3204bcbeec90f3c5c651d3a35b7dd0d27", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rphellan/4DASLMRAVirtualPhantoms", "max_forks_repo_path": "IFTVessel/include/iftCommon.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad2419f3204bcbeec90f3c5c651d3a35b7dd0d27", "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": "rphellan/4DASLMRAVirtualPhantoms", "max_issues_repo_path": "IFTVessel/include/iftCommon.h", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad2419f3204bcbeec90f3c5c651d3a35b7dd0d27", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rphellan/4DASLMRAVirtualPhantoms", "max_stars_repo_path": "IFTVessel/include/iftCommon.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2074, "size": 7303 }
#pragma once #include <nextalign/nextalign.h> #include <gsl/string_span> #include <string> #include "../nextalign_private.h" #include "../utils/to_underlying.h" using NucleotideSequenceSpan = SequenceSpan<Nucleotide>; Nucleotide toNucleotide(char nuc); char nucToChar(Nucleotide nuc); inline std::ostream& operator<<(std::ostream& os, const Nucleotide& nucleotide) { os << std::string{to_underlying(nucleotide)}; return os; }
{ "alphanum_fraction": 0.7505720824, "avg_line_length": 20.8095238095, "ext": "h", "hexsha": "c52dbaf93398e7fd4dc3a00c1b0fb403ee7748d6", "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": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "davidcroll/nextclade", "max_forks_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "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": "davidcroll/nextclade", "max_issues_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "davidcroll/nextclade", "max_stars_repo_path": "packages/nextalign/src/alphabet/nucleotides.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 114, "size": 437 }
#ifndef QR_H #define QR_H #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> /** * Computes, stores, and maintains a QR decomposition of a gsl_matrix. * * A matrix-pointer is passed to the QR on construction. This pointer is kept through * the life-time of the QR object (but ownership is not assumed). If the contents * of the matrix is changed, the QR can be update to reflect the change using the * abstract UpdateFromMatrix function. This is not automatically done on construction. */ class QR{ protected: const int m, n; ///< Dimensions of matrix /** Decomposes M into U*S*V^t. */ QR(gsl_matrix* M); public: /** * Constructs a QR object. If MKL is available it will be an MKLQR and if GSL * is available it will be GSLQR */ static QR* createQR(gsl_matrix* M); virtual ~QR(); /** Update Q and R to reflect the decomposition of the matrix. */ virtual void updateFromMatrix() = 0; /** Print the QR to standard out */ void print() const; gsl_matrix* getMatrix() const; gsl_matrix* getQ() const; gsl_matrix* getR() const; protected: gsl_matrix * const m_matrix; gsl_matrix * const m_Q; gsl_matrix * const m_R; }; #endif
{ "alphanum_fraction": 0.6965572458, "avg_line_length": 23.1296296296, "ext": "h", "hexsha": "ba59678b86199dd3f7f4c664f88d183e41cbecf3", "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": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_path": "src/math/QR.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_path": "src/math/QR.h", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_path": "src/math/QR.h", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "num_tokens": 329, "size": 1249 }
#pragma once #include <gsl/gsl_vector.h> #include "BooleanNodes.h" #include "BooleanDAG.h" #include <map> #include "SymbolicEvaluator.h" #include "ConflictGenerator.h" #include <iostream> #include "Util.h" class SmartConflictGenerator: public ConflictGenerator { SymbolicEvaluator* eval; map<int, int>& imap; BooleanDAG* dag; set<int>& ignoredBoolNodes; set<int>& ctrlNodes; vector<set<int>> dependentInputs; vector<set<int>> dependentCtrls; public: ConflictGenerator(SymbolicEvaluator* eval_, map<int, int>& imap_, BooleanDAG* dag_, set<int>& ignoredBoolNodes_, set<int>& ctrlNodes_): eval(eval_), imap(imap_), dag(dag_), ignoredBoolNodes(ignoredBoolNodes_), ctrlNodes(ctrlNodes_) { // process the dag and collect dependencies for (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) { bool_node* n = *node_it; set<int> inputs; set<int> ctrls; const vector<bool_node*>& parents = n->parents(); for (int i = 0; i < parents.size(); i++) { bool_node* parent = parents[i]; set<int>& parentInputs = dependentInputs[parent->id]; set<int>& parentCtrls = dependentCtrls[parent->id]; if (parent->getOtype() == OutType::BOOL) { if (ignoredBoolNodes.find(parent->id) == ignoredBoolNodes.end()) { inputs.insert(parent->id); //inputs.insert(parentInputs.begin(), parentInputs.end()); } } else { inputs.insert(parentInputs.begin(), parentInputs.end()); ctrls.insert(parentCtrls.begin(), parentCtrls.end()); } if (ctrlNodes.find(parent->id) != ctrlNodes.end()) { ctrls.insert(parent->id); } } dependentInputs.push_back(inputs); dependentCtrls.push_back(ctrls); } } bool isConflict(set<int> influentialControls, set<int> myControls) { for (int i : influentialControls) { if (myControls.find(i) != myControls.end()) { return true; } } return false; } virtual vector<pair<int, int>> getConflicts(gsl_vector* state, vector<vector<int>>& allInputs, vector<int>& instanceIds, int rowid, int colid) { vector<pair<int, int>> conflicts; for (int i = 0; i < allInputs.size(); i++) { const map<int, int>& nodeValsMap = Util::getNodeToValMap(imap, allInputs[i]); eval->run(state, nodeValsMap); // First, find a failing node bool_node* failedNode = NULL; for (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) { bool_node* n = *node_it; if (n->type == bool_node::ASSERT) { if (!eval->check(n->mother, 1)) { failedNode = n; break; } } if (n->getOtype() == OutType::BOOL) { auto it = nodeValsMap.find(n->id); if (it != nodeValsMap.end()) { int val = it->second; if (!eval->check(n, val)) { failedNode = n; break; } } } } Assert(failedNode != NULL, "No conflict?"); cout << failedNode->lprint() << endl; set<int> conflictNodes; // First, add all dependent inputs set<int>& depInputs = dependentInputs[failedNode->id]; conflictNodes.insert(depInputs.begin(), depInputs.end()); cout << "Dep inputs:" << endl; for (auto it = depInputs.begin(); it != depInputs.end(); it++) { cout << (*dag)[(*it)]->lprint() << endl; } set<int>& depCtrls = dependentCtrls[failedNode->id]; cout << "Dep ctrls:" << endl; for (auto it = depCtrls.begin(); it != depCtrls.end(); it++) { cout << (*dag)[(*it)]->lprint() << endl; } // Next, collect all boolean nodes that are influenced by the controls that affect the failed node for (BooleanDAG::iterator node_it = dag->begin(); node_it != dag->end(); ++node_it) { bool_node* n = *node_it; if (n->type == bool_node::ASSERT) { if (isConflict(depCtrls, dependentCtrls[n->id])) { conflictNodes.insert(n->id); } } if (n->getOtype() == OutType::BOOL) { if (isConflict(depCtrls, dependentCtrls[n->id])) { conflictNodes.insert(n->id); } } } cout << "Final conflict nodes" << endl; //conflictNodes.insert(colid); // Process the conflicts for (int j = 0; j < imap.size(); j++) { if (allInputs[i][j] != EMPTY) { if (ignoredBoolNodes.find(imap[j]) == ignoredBoolNodes.end()) { if (imap[j] < 0 || conflictNodes.find(imap[j]) != conflictNodes.end()) { if (imap[j] >= 0) { cout << (*dag)[imap[j]]->lprint() << " " << allInputs[i][j] << endl; } conflicts.push_back(make_pair(instanceIds[i], j)); } } } } } return conflicts; } };
{ "alphanum_fraction": 0.6156724631, "avg_line_length": 30.6959459459, "ext": "h", "hexsha": "026c62ead6c9da2ba25c134f5ddaea8af6ac1ae5", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_line_length": 234, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/ConflictGenerators/SmartConflictGenerator.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 1289, "size": 4543 }
/* statistics/gsl_statistics_long_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_STATISTICS_LONG_DOUBLE_H__ #define __GSL_STATISTICS_LONG_DOUBLE_H__ #include <stddef.h> #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS GSL_EXPORT double gsl_stats_long_double_mean (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_variance (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_sd (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_variance_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_sd_with_fixed_mean (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_absdev (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_skew (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_kurtosis (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_lag1_autocorrelation (const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_covariance (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n); GSL_EXPORT double gsl_stats_long_double_variance_m (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_sd_m (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_absdev_m (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_skew_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_long_double_kurtosis_m_sd (const long double data[], const size_t stride, const size_t n, const double mean, const double sd); GSL_EXPORT double gsl_stats_long_double_lag1_autocorrelation_m (const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_covariance_m (const long double data1[], const size_t stride1,const long double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2); /* DEFINED FOR FLOATING POINT TYPES ONLY */ GSL_EXPORT double gsl_stats_long_double_wmean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wvariance (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wsd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wvariance_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_wsd_with_fixed_mean (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double mean); GSL_EXPORT double gsl_stats_long_double_wabsdev (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wskew (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wkurtosis (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_wvariance_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_long_double_wsd_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_long_double_wabsdev_m (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean); GSL_EXPORT double gsl_stats_long_double_wskew_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd); GSL_EXPORT double gsl_stats_long_double_wkurtosis_m_sd (const long double w[], const size_t wstride, const long double data[], const size_t stride, const size_t n, const double wmean, const double wsd); /* END OF FLOATING POINT TYPES */ GSL_EXPORT double gsl_stats_long_double_pvariance (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2); GSL_EXPORT double gsl_stats_long_double_ttest (const long double data1[], const size_t stride1, const size_t n1, const long double data2[], const size_t stride2, const size_t n2); GSL_EXPORT long double gsl_stats_long_double_max (const long double data[], const size_t stride, const size_t n); GSL_EXPORT long double gsl_stats_long_double_min (const long double data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_long_double_minmax (long double * min, long double * max, const long double data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_long_double_max_index (const long double data[], const size_t stride, const size_t n); GSL_EXPORT size_t gsl_stats_long_double_min_index (const long double data[], const size_t stride, const size_t n); GSL_EXPORT void gsl_stats_long_double_minmax_index (size_t * min_index, size_t * max_index, const long double data[], const size_t stride, const size_t n); GSL_EXPORT double gsl_stats_long_double_median_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n) ; GSL_EXPORT double gsl_stats_long_double_quantile_from_sorted_data (const long double sorted_data[], const size_t stride, const size_t n, const double f) ; __END_DECLS #endif /* __GSL_STATISTICS_LONG_DOUBLE_H__ */
{ "alphanum_fraction": 0.8030530189, "avg_line_length": 77.2315789474, "ext": "h", "hexsha": "74ca27e819cbb51a71f35fac3da0c39817ce1010", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_line_length": 207, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_long_double.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1758, "size": 7337 }
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cblas.h> int max(int x, int y){ if(x > y) return x; else return y; } void PrintMatrix(float* pMatrix, const size_t nR, const size_t nC, const CBLAS_ORDER Order) { unsigned int i, j; if (Order == CblasRowMajor) { for (i = 0; i < nR; i++) { for (j = 0; j < nC; j++) { printf("%f \t ", pMatrix[i * nC + j]); // !!! } printf("\n"); // !!! } } else { for (i = 0; i < nR; i++) { for (j = 0; j < nC; j++) { printf("%f \t ", pMatrix[i + j* nR ]); // !!! } printf("\n"); // !!! } } printf("\n"); // !!! } int main(void) { const int m = 4; const int n = 5; const int k = 1; float A[] = { 8, 4, 7, 3, 5, 1, 1, 3, 2, 1, 2, 3, 2, 0, 1, 1, 2, 3, 4, 1}; float B[5] = { -1, 2, -1, 1, 2 }; float alpha = 1.0, beta = 0.0; int lda, ldb, ldc; float * C = (float*) malloc(m * k * sizeof(float)); for (int i = 0; i < m*k; i++) C[i] = 0.0; //working cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, A, n, B, k, beta, C, k); //lda = max(1,n); ldb = max(1,k); ldc = max(1,k); // refer manual and switch n and k //cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m,k,n, alpha, A, lda, B, ldb, beta, C, ldc); // working cblas_sgemv(CblasColMajor, CblasNoTrans, m, n, alpha, A, m, B, k, beta, C, k); // working cblas_sgemv(CblasColMajor, CblasTrans, m, n, alpha, A, m, B, k, beta, C, k); lda = max(1,n); ldb = max(1,n); ldc = max(1,m); // refer manual and switch n and k cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, m,k,n, alpha, A, lda, B, ldb, beta, C, ldc); PrintMatrix(C, m, k, CblasRowMajor); free(C); return 0; }
{ "alphanum_fraction": 0.4986623863, "avg_line_length": 29.203125, "ext": "c", "hexsha": "8d87c1d2b11d0710ae74838b6cccd194e1dd081c", "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": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_forks_repo_licenses": [ "Naumen", "Condor-1.1", "MS-PL" ], "max_forks_repo_name": "ramcn/flappie-x-cpp", "max_forks_repo_path": "2test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Naumen", "Condor-1.1", "MS-PL" ], "max_issues_repo_name": "ramcn/flappie-x-cpp", "max_issues_repo_path": "2test.c", "max_line_length": 105, "max_stars_count": 1, "max_stars_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_stars_repo_licenses": [ "Naumen", "Condor-1.1", "MS-PL" ], "max_stars_repo_name": "ramcn/flappie-x-cpp", "max_stars_repo_path": "2test.c", "max_stars_repo_stars_event_max_datetime": "2020-01-16T17:15:21.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:21.000Z", "num_tokens": 708, "size": 1869 }
/* rng/taus113.c * Copyright (C) 2002 Atakan Gurkan * Based on the file taus.c which has the notice * 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. */ /* This is a maximally equidistributed combined, collision free Tausworthe generator, with a period ~2^{113}. The sequence is, x_n = (z1_n ^ z2_n ^ z3_n ^ z4_n) b = (((z1_n << 6) ^ z1_n) >> 13) z1_{n+1} = (((z1_n & 4294967294) << 18) ^ b) b = (((z2_n << 2) ^ z2_n) >> 27) z2_{n+1} = (((z2_n & 4294967288) << 2) ^ b) b = (((z3_n << 13) ^ z3_n) >> 21) z3_{n+1} = (((z3_n & 4294967280) << 7) ^ b) b = (((z4_n << 3) ^ z4_n) >> 12) z4_{n+1} = (((z4_n & 4294967168) << 13) ^ b) computed modulo 2^32. In the formulas above '^' means exclusive-or (C-notation), not exponentiation. The algorithm is for 32-bit integers, hence a bitmask is used to clear all but least significant 32 bits, after left shifts, to make the code work on architectures where integers are 64-bit. The generator is initialized with zi = (69069 * z{i+1}) MOD 2^32 where z0 is the seed provided During initialization a check is done to make sure that the initial seeds have a required number of their most significant bits set. After this, the state is passed through the RNG 10 times to ensure the state satisfies a recurrence relation. References: P. L'Ecuyer, "Tables of Maximally-Equidistributed Combined LFSR Generators", Mathematics of Computation, 68, 225 (1999), 261--269. http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe Generators", Mathematics of Computation, 65, 213 (1996), 203--213. http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps the online version of the latter contains corrections to the print version. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> #define LCG(n) ((69069UL * n) & 0xffffffffUL) #define MASK 0xffffffffUL static inline unsigned long int taus113_get (void *vstate); static double taus113_get_double (void *vstate); static void taus113_set (void *state, unsigned long int s); typedef struct { unsigned long int z1, z2, z3, z4; } taus113_state_t; static inline unsigned long taus113_get (void *vstate) { taus113_state_t *state = (taus113_state_t *) vstate; unsigned long b1, b2, b3, b4; b1 = ((((state->z1 << 6UL) & MASK) ^ state->z1) >> 13UL); state->z1 = ((((state->z1 & 4294967294UL) << 18UL) & MASK) ^ b1); b2 = ((((state->z2 << 2UL) & MASK) ^ state->z2) >> 27UL); state->z2 = ((((state->z2 & 4294967288UL) << 2UL) & MASK) ^ b2); b3 = ((((state->z3 << 13UL) & MASK) ^ state->z3) >> 21UL); state->z3 = ((((state->z3 & 4294967280UL) << 7UL) & MASK) ^ b3); b4 = ((((state->z4 << 3UL) & MASK) ^ state->z4) >> 12UL); state->z4 = ((((state->z4 & 4294967168UL) << 13UL) & MASK) ^ b4); return (state->z1 ^ state->z2 ^ state->z3 ^ state->z4); } static double taus113_get_double (void *vstate) { return taus113_get (vstate) / 4294967296.0; } static void taus113_set (void *vstate, unsigned long int s) { taus113_state_t *state = (taus113_state_t *) vstate; if (!s) s = 1UL; /* default seed is 1 */ state->z1 = LCG (s); if (state->z1 < 2UL) state->z1 += 2UL; state->z2 = LCG (state->z1); if (state->z2 < 8UL) state->z2 += 8UL; state->z3 = LCG (state->z2); if (state->z3 < 16UL) state->z3 += 16UL; state->z4 = LCG (state->z3); if (state->z4 < 128UL) state->z4 += 128UL; /* Calling RNG ten times to satify recurrence condition */ taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); taus113_get (state); return; } static const gsl_rng_type taus113_type = { "taus113", /* name */ 0xffffffffUL, /* RAND_MAX */ 0, /* RAND_MIN */ sizeof (taus113_state_t), &taus113_set, &taus113_get, &taus113_get_double }; const gsl_rng_type *gsl_rng_taus113 = &taus113_type; /* Rules for analytic calculations using GNU Emacs Calc: (used to find the values for the test program) [ LCG(n) := n * 69069 mod (2^32) ] [ b1(x) := rsh(xor(lsh(x, 6), x), 13), q1(x) := xor(lsh(and(x, 4294967294), 18), b1(x)), b2(x) := rsh(xor(lsh(x, 2), x), 27), q2(x) := xor(lsh(and(x, 4294967288), 2), b2(x)), b3(x) := rsh(xor(lsh(x, 13), x), 21), q3(x) := xor(lsh(and(x, 4294967280), 7), b3(x)), b4(x) := rsh(xor(lsh(x, 3), x), 12), q4(x) := xor(lsh(and(x, 4294967168), 13), b4(x)) ] [ S([z1,z2,z3,z4]) := [q1(z1), q2(z2), q3(z3), q4(z4)] ] */
{ "alphanum_fraction": 0.6358507734, "avg_line_length": 32.5147928994, "ext": "c", "hexsha": "04da6a893f3928e7a2c67215eaa69180b0f8c937", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/taus113.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/taus113.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/rng/taus113.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": 1921, "size": 5495 }
// tcc -lgsl -lglut -lGL -run gsl_opengl.c // clang -lgsl -framework GLUT -framework OpenGL gsl_opengl.c #include <gsl/gsl_qrng.h> #include <GL/glut.h> // #pragma comment(lib,"glut32") // #pragma comment(lib,"gsl") // #pragma comment(lib,"opengl32") // #pragma comment(lib,"freeglut") void glutInitialize() { glClearColor(1,1,1,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(-1,-1,0); glScalef(2,2,1); glViewport(0,0,512,512); glPointSize(3.0); } void Display() { glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); const int n = 100; gsl_qrng* qrng = gsl_qrng_alloc(gsl_qrng_sobol,2); glBegin(GL_POINTS); glColor3f(0,0,1); for( int i=0; i<n; i++ ) { double s[2]; gsl_qrng_get(qrng,s); glVertex3f(s[0],s[1],0.0); } glEnd(); gsl_qrng_free(qrng); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE); glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-512)/2, (glutGet(GLUT_SCREEN_HEIGHT)-640)/2); glutInitWindowSize(512,512); glutCreateWindow("GSL Quasi Random Number Generator"); glutInitialize(); glutDisplayFunc(Display); glutMainLoop(); return 0; }
{ "alphanum_fraction": 0.6485884101, "avg_line_length": 24.9259259259, "ext": "c", "hexsha": "1ee76ee421ad4339ff940dbadeb6717de8ef7af9", "lang": "C", "max_forks_count": 29, "max_forks_repo_forks_event_max_datetime": "2021-12-24T01:51:03.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-10T13:25:54.000Z", "max_forks_repo_head_hexsha": "f860268f0eea7e87abab6272bc1d22f2781df4ce", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jack9603301/MiscRecord", "max_forks_repo_path": "Sources/CLibrary/GSL/gsl_opengl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f860268f0eea7e87abab6272bc1d22f2781df4ce", "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": "jack9603301/MiscRecord", "max_issues_repo_path": "Sources/CLibrary/GSL/gsl_opengl.c", "max_line_length": 62, "max_stars_count": 27, "max_stars_repo_head_hexsha": "1566c98f2f5aa0563dc0c52ca6598a15ae9bb860", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wurui1994/MiscRecord", "max_stars_repo_path": "Sources/CLibrary/GSL/gsl_opengl.c", "max_stars_repo_stars_event_max_datetime": "2021-07-30T13:02:00.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-19T09:15:36.000Z", "num_tokens": 408, "size": 1346 }
/* ** compute edge densities ** ** G.Lohmann, Feb 2015 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_histogram.h> #include "viaio/Vlib.h" #include "viaio/VImage.h" #include "viaio/mu.h" #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ #define SQR(x) ((x) * (x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) extern void GetRank(float *data,gsl_vector *v,gsl_permutation *perm,gsl_permutation *rank); extern float EdgeCorr(const float *data1,const float *data2,int,int); int GetAddr(VImage mapimage,int bi,int ri,int ci,int m,int k,int l) { int b = bi+m; int r = ri+k; int c = ci+l; if (b < 0 || r < 0 || c < 0) return -1; if (b >= VImageNBands(mapimage) || r >= VImageNRows(mapimage) || c >= VImageNColumns(mapimage)) return -1; int ii = (long)VPixel(mapimage,b,r,c,VInteger); return ii; } int VEdgeNeigbours(size_t id,VImage map,VImage mapimage,int adjdef,int *x) { int nslices = VImageNBands(mapimage); int nrows = VImageNRows(mapimage); int ncols = VImageNColumns(mapimage); int bi = VPixel(map,0,0,id,VShort); int ri = VPixel(map,0,1,id,VShort); int ci = VPixel(map,0,2,id,VShort); if (bi < 1 || bi >= nslices-2) return 0; if (ri < 1 || ri >= nrows-2) return 0; if (ci < 1 || ci >= ncols-2) return 0; int wn=1,rad2=0; if (adjdef == 3) { wn = 2; rad2 = 2*2; } int n=0; int k,l,m; for (m=-wn; m<=wn; m++) { for (k=-wn; k<=wn; k++) { for (l=-wn; l<=wn; l++) { int jj = GetAddr(mapimage,bi,ri,ci,m,k,l); if (jj < 0) continue; /* outside of brain mask */ if (adjdef == 0) { /* 6 adjacency */ if (ABS(m)+ABS(k)+ABS(l) > 1) continue; } if (adjdef == 1) { /* 18-adjacency */ if (ABS(m) > 0 && ABS(k) > 0 && ABS(l) > 0) continue; } if (adjdef == 3) { /* sphere */ if (m*m + k*k + l*l > rad2) continue; } x[n] = jj; n++; } } } return n; } void VCheckImage(VImage src) { VAttrList out_list = VCreateAttrList(); VAppendAttr(out_list,"image",NULL,VImageRepn,src); FILE *out_file = fopen("test.v","w"); VWriteFile (out_file, out_list); } size_t EdgeDensity(float *E,int *I,int *J,size_t nedges_estimated, gsl_histogram *TedHist,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2, VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float zthreshold, int nperm,int numperm,int step,float noise_cutoff,int metric) { size_t i; size_t nvox=SNR1->size1; int nt=SNR1->size2; size_t progress=0; int rad2 = (int)(elength*elength); float tiny=1.0e-6; gsl_set_error_handler_off (); int iisel=4; /* size of neighbourhood */ int nadj=0; if (adjdef == 0) nadj = 7; else if (adjdef == 1) nadj = 19; else if (adjdef == 2) nadj = 27; else if (adjdef == 3) nadj = 33; else VError(" illegal adjdef %d",adjdef); size_t nedges=0; int minadj = 1; /* histogram init */ size_t nbins = gsl_histogram_bins (TedHist); double hmax = gsl_histogram_max (TedHist); double hmin = gsl_histogram_min (TedHist); #pragma omp parallel for shared(nedges,progress,TedHist,E,I,J) schedule(dynamic) for (i=0; i<nvox; i+=step) { if (i%1000 == 0) fprintf(stderr," %ld000\r",(long)progress++); int bi = (int)VPixel(map,0,0,i,VShort); int ri = (int)VPixel(map,0,1,i,VShort); int ci = (int)VPixel(map,0,2,i,VShort); int iselect=0; int roiflagi = 0; if (roi != NULL) { if (VGetPixel(roi,bi,ri,ci) > 0.5) roiflagi = 1; } const float *datax1 = gsl_matrix_float_const_ptr(SNR1,i,0); const float *datax2 = gsl_matrix_float_const_ptr(SNR2,i,0); int *x = (int *) VCalloc(nadj,sizeof(int)); int *y = (int *) VCalloc(nadj,sizeof(int)); gsl_histogram *tmphist = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (tmphist,hmin,hmax); gsl_histogram_reset(tmphist); int nadjx = VEdgeNeigbours(i,map,mapimage,adjdef,x); if (nadjx < minadj) continue; size_t j=0; for (j=0; j<i; j+=step) { int bj = (int)VPixel(map,0,0,j,VShort); int rj = (int)VPixel(map,0,1,j,VShort); int cj = (int)VPixel(map,0,2,j,VShort); int d = SQR(bi-bj) + SQR(ri-rj) + SQR(ci-cj); if (d < rad2) continue; int roiflagj = 0; if (roi != NULL) { if (VGetPixel(roi,bj,rj,cj) > 0.5) roiflagj = 1; if (roiflagi + roiflagj != 1) continue; } const float *datay1 = gsl_matrix_float_const_ptr(SNR1,j,0); const float *datay2 = gsl_matrix_float_const_ptr(SNR2,j,0); /* edge z-value */ double z1 = EdgeCorr(datax1,datay1,nt,metric); double z2 = EdgeCorr(datax2,datay2,nt,metric); double z = (z1-z2); if (z < zthreshold) continue; int nadjy = VEdgeNeigbours(j,map,mapimage,adjdef,y); if (nadjy < minadj) continue; /* use every 'step' value, only when estimating noise cutoff, i.e. step > 1 */ if (iselect%iisel == 0 && step > 1) { iselect = 0; } else if (iselect%iisel != 0 && step > 1) { iselect++; continue; } /* inspect local neighbourhood */ int r,s; double kx=0.0,nx=0.0; for (s=0; s<nadjx; s++) { size_t ii = (size_t) x[s]; int bii = (int)VPixel(map,0,0,ii,VShort); int rii = (int)VPixel(map,0,1,ii,VShort); int cii = (int)VPixel(map,0,2,ii,VShort); const float *dataxx1 = gsl_matrix_float_const_ptr(SNR1,ii,0); const float *dataxx2 = gsl_matrix_float_const_ptr(SNR2,ii,0); for (r=0; r<nadjy; r++) { size_t jj = (size_t) y[r]; int bjj = (int)VPixel(map,0,0,jj,VShort); int rjj = (int)VPixel(map,0,1,jj,VShort); int cjj = (int)VPixel(map,0,2,jj,VShort); int d2 = SQR(bii-bjj) + SQR(rii-rjj) + SQR(cii-cjj); if (d2 < rad2) continue; const float *datayy1 = gsl_matrix_float_const_ptr(SNR1,jj,0); const float *datayy2 = gsl_matrix_float_const_ptr(SNR2,jj,0); /* edge z-value */ double z1 = EdgeCorr(dataxx1,datayy1,nt,metric); double z2 = EdgeCorr(dataxx2,datayy2,nt,metric); double z = (z1-z2); if (ABS(z) < tiny) continue; if (z > zthreshold) kx++; nx++; } } if (nx < 1.0) continue; double ted = kx/nx; if (ted < hmin) ted = hmin; if (ted > hmax-tiny) ted = hmax-tiny; gsl_histogram_increment (tmphist,ted); if (E == NULL) continue; if (nperm != numperm) continue; if (ted < noise_cutoff) continue; #pragma omp critical { if (nedges >= nedges_estimated) { VError(" alloc, nedges_estimated: %lu",nedges_estimated); } E[nedges] = ted; /* task-based edge density */ I[nedges] = i; /* voxel address i */ J[nedges] = j; /* voxel address j */ nedges++; } } #pragma omp critical { gsl_histogram_add (TedHist,tmphist); } gsl_histogram_free (tmphist); VFree(x); VFree(y); } return nedges; } /* estimate number of truly needed edges */ size_t EstimateEdges(float *E,int *I,int *J,size_t old_estimate, gsl_histogram *TedHist,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2, VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float zthr, float noise_cutoff,int metric) { float tmp_cutoff = -1.0; int step = 2; int nperm=0,numperm=1; gsl_histogram_reset(TedHist); EdgeDensity(E,I,J,old_estimate,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,elength,zthr, nperm,numperm,step,tmp_cutoff,metric); double sd = gsl_histogram_sigma (TedHist); if (sd < 1.0e-6) VError(" stdev of TedHist: %f",sd); size_t i0 = 0; if (gsl_histogram_find (TedHist,(double)noise_cutoff,&i0) != GSL_SUCCESS) VError (" err finding noise cutoff index, %f",noise_cutoff); size_t hbins = gsl_histogram_bins(TedHist); gsl_histogram_pdf *cdf = gsl_histogram_pdf_alloc(hbins); gsl_histogram_pdf_init (cdf,TedHist); double qx = 1.0 - cdf->sum[i0]; if (qx > 1) qx = 1.0; size_t new_estimate = (size_t) (qx*(double)old_estimate); gsl_histogram_reset(TedHist); gsl_histogram_pdf_free (cdf); return new_estimate; }
{ "alphanum_fraction": 0.6179802075, "avg_line_length": 27.9566666667, "ext": "c", "hexsha": "825dd4f856f104dc11350345c52ad4745330c3b0", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/ted/vted/EdgeDensity.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/ted/vted/EdgeDensity.c", "max_line_length": 108, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/ted/vted/EdgeDensity.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2866, "size": 8387 }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 GSL_SPAN_H #define GSL_SPAN_H #include <gsl/gsl_assert> // for Expects #include <gsl/gsl_byte> // for byte #include <gsl/gsl_util> // for narrow_cast, narrow #include <algorithm> // for lexicographical_compare #include <array> // for array #include <cstddef> // for ptrdiff_t, size_t, nullptr_t #include <iterator> // for reverse_iterator, distance, random_access_... #include <limits> #include <stdexcept> #include <type_traits> // for enable_if_t, declval, is_convertible, inte... #include <utility> #include <memory> // for std::addressof #ifdef _MSC_VER #pragma warning(push) // turn off some warnings that are noisy about our Expects statements #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4702) // unreachable code // Turn MSVC /analyze rules that generate too much noise. TODO: fix in the tool. #pragma warning(disable : 26495) // uninitalized member when constructor calls constructor #pragma warning(disable : 26446) // parser bug does not allow attributes on some templates #if _MSC_VER < 1910 #pragma push_macro("constexpr") #define constexpr /*constexpr*/ #define GSL_USE_STATIC_CONSTEXPR_WORKAROUND #endif // _MSC_VER < 1910 #endif // _MSC_VER // See if we have enough C++17 power to use a static constexpr data member // without needing an out-of-line definition #if !(defined(__cplusplus) && (__cplusplus >= 201703L)) #define GSL_USE_STATIC_CONSTEXPR_WORKAROUND #endif // !(defined(__cplusplus) && (__cplusplus >= 201703L)) // GCC 7 does not like the signed unsigned missmatch (size_t ptrdiff_t) // While there is a conversion from signed to unsigned, it happens at // compiletime, so the compiler wouldn't have to warn indiscriminently, but // could check if the source value actually doesn't fit into the target type // and only warn in those cases. #if __GNUC__ > 6 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" #endif namespace gsl { // [views.constants], constants constexpr const std::ptrdiff_t dynamic_extent = -1; template <class ElementType, std::ptrdiff_t Extent = dynamic_extent> class span; // implementation details namespace details { template <class T> struct is_span_oracle : std::false_type { }; template <class ElementType, std::ptrdiff_t Extent> struct is_span_oracle<gsl::span<ElementType, Extent>> : std::true_type { }; template <class T> struct is_span : public is_span_oracle<std::remove_cv_t<T>> { }; template <class T> struct is_std_array_oracle : std::false_type { }; template <class ElementType, std::size_t Extent> struct is_std_array_oracle<std::array<ElementType, Extent>> : std::true_type { }; template <class T> struct is_std_array : public is_std_array_oracle<std::remove_cv_t<T>> { }; template <std::ptrdiff_t From, std::ptrdiff_t To> struct is_allowed_extent_conversion : public std::integral_constant<bool, From == To || From == gsl::dynamic_extent || To == gsl::dynamic_extent> { }; template <class From, class To> struct is_allowed_element_type_conversion : public std::integral_constant<bool, std::is_convertible<From (*)[], To (*)[]>::value> { }; template <class Span, bool IsConst> class span_iterator { using element_type_ = typename Span::element_type; public: #ifdef _MSC_VER // Tell Microsoft standard library that span_iterators are checked. using _Unchecked_type = typename Span::pointer; #endif using iterator_category = std::random_access_iterator_tag; using value_type = std::remove_cv_t<element_type_>; using difference_type = typename Span::index_type; using reference = std::conditional_t<IsConst, const element_type_, element_type_>&; using pointer = std::add_pointer_t<reference>; span_iterator() = default; constexpr span_iterator(const Span* span, typename Span::index_type idx) noexcept : span_(span), index_(idx) {} friend span_iterator<Span, true>; template <bool B, std::enable_if_t<!B && IsConst>* = nullptr> constexpr span_iterator(const span_iterator<Span, B>& other) noexcept : span_iterator(other.span_, other.index_) {} GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute constexpr reference operator*() const { Expects(index_ != span_->size()); return *(span_->data() + index_); } constexpr pointer operator->() const { Expects(index_ != span_->size()); return span_->data() + index_; } constexpr span_iterator& operator++() { Expects(0 <= index_ && index_ != span_->size()); ++index_; return *this; } constexpr span_iterator operator++(int) { auto ret = *this; ++(*this); return ret; } constexpr span_iterator& operator--() { Expects(index_ != 0 && index_ <= span_->size()); --index_; return *this; } constexpr span_iterator operator--(int) { auto ret = *this; --(*this); return ret; } constexpr span_iterator operator+(difference_type n) const { auto ret = *this; return ret += n; } friend constexpr span_iterator operator+(difference_type n, span_iterator const& rhs) { return rhs + n; } constexpr span_iterator& operator+=(difference_type n) { Expects((index_ + n) >= 0 && (index_ + n) <= span_->size()); index_ += n; return *this; } constexpr span_iterator operator-(difference_type n) const { auto ret = *this; return ret -= n; } constexpr span_iterator& operator-=(difference_type n) { return *this += -n; } constexpr difference_type operator-(span_iterator rhs) const { Expects(span_ == rhs.span_); return index_ - rhs.index_; } constexpr reference operator[](difference_type n) const { return *(*this + n); } constexpr friend bool operator==(span_iterator lhs, span_iterator rhs) noexcept { return lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_; } constexpr friend bool operator!=(span_iterator lhs, span_iterator rhs) noexcept { return !(lhs == rhs); } constexpr friend bool operator<(span_iterator lhs, span_iterator rhs) noexcept { return lhs.index_ < rhs.index_; } constexpr friend bool operator<=(span_iterator lhs, span_iterator rhs) noexcept { return !(rhs < lhs); } constexpr friend bool operator>(span_iterator lhs, span_iterator rhs) noexcept { return rhs < lhs; } constexpr friend bool operator>=(span_iterator lhs, span_iterator rhs) noexcept { return !(rhs > lhs); } #ifdef _MSC_VER // MSVC++ iterator debugging support; allows STL algorithms in 15.8+ // to unwrap span_iterator to a pointer type after a range check in STL // algorithm calls friend constexpr void _Verify_range(span_iterator lhs, span_iterator rhs) noexcept { // test that [lhs, rhs) forms a valid range inside an STL algorithm Expects(lhs.span_ == rhs.span_ // range spans have to match && lhs.index_ <= rhs.index_); // range must not be transposed } constexpr void _Verify_offset(const difference_type n) const noexcept { // test that the iterator *this + n is a valid range in an STL // algorithm call Expects((index_ + n) >= 0 && (index_ + n) <= span_->size()); } GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute constexpr pointer _Unwrapped() const noexcept { // after seeking *this to a high water mark, or using one of the // _Verify_xxx functions above, unwrap this span_iterator to a raw // pointer return span_->data() + index_; } // Tell the STL that span_iterator should not be unwrapped if it can't // validate in advance, even in release / optimized builds: #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) static constexpr const bool _Unwrap_when_unverified = false; #else static constexpr bool _Unwrap_when_unverified = false; #endif GSL_SUPPRESS(con.3) // NO-FORMAT: attribute // TODO: false positive constexpr void _Seek_to(const pointer p) noexcept { // adjust the position of *this to previously verified location p // after _Unwrapped index_ = p - span_->data(); } #endif protected: const Span* span_ = nullptr; std::ptrdiff_t index_ = 0; }; template <std::ptrdiff_t Ext> class extent_type { public: using index_type = std::ptrdiff_t; static_assert(Ext >= 0, "A fixed-size span must be >= 0 in size."); constexpr extent_type() noexcept {} template <index_type Other> constexpr extent_type(extent_type<Other> ext) { static_assert(Other == Ext || Other == dynamic_extent, "Mismatch between fixed-size extent and size of initializing data."); Expects(ext.size() == Ext); } constexpr extent_type(index_type size) { Expects(size == Ext); } constexpr index_type size() const noexcept { return Ext; } }; template <> class extent_type<dynamic_extent> { public: using index_type = std::ptrdiff_t; template <index_type Other> explicit constexpr extent_type(extent_type<Other> ext) : size_(ext.size()) {} explicit constexpr extent_type(index_type size) : size_(size) { Expects(size >= 0); } constexpr index_type size() const noexcept { return size_; } private: index_type size_; }; template <class ElementType, std::ptrdiff_t Extent, std::ptrdiff_t Offset, std::ptrdiff_t Count> struct calculate_subspan_type { using type = span<ElementType, Count != dynamic_extent ? Count : (Extent != dynamic_extent ? Extent - Offset : Extent)>; }; } // namespace details // [span], class template span template <class ElementType, std::ptrdiff_t Extent> class span { public: // constants and types using element_type = ElementType; using value_type = std::remove_cv_t<ElementType>; using index_type = std::ptrdiff_t; using pointer = element_type*; using reference = element_type&; using iterator = details::span_iterator<span<ElementType, Extent>, false>; using const_iterator = details::span_iterator<span<ElementType, Extent>, true>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using size_type = index_type; #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) static constexpr const index_type extent{Extent}; #else static constexpr index_type extent{Extent}; #endif // [span.cons], span constructors, copy, assignment, and destructor template <bool Dependent = false, // "Dependent" is needed to make "std::enable_if_t<Dependent || Extent <= 0>" SFINAE, // since "std::enable_if_t<Extent <= 0>" is ill-formed when Extent is greater than 0. class = std::enable_if_t<(Dependent || Extent <= 0)>> constexpr span() noexcept : storage_(nullptr, details::extent_type<0>()) {} constexpr span(pointer ptr, index_type count) : storage_(ptr, count) {} constexpr span(pointer firstElem, pointer lastElem) : storage_(firstElem, std::distance(firstElem, lastElem)) {} template <std::size_t N> constexpr span(element_type (&arr)[N]) noexcept : storage_(KnownNotNull{std::addressof(arr[0])}, details::extent_type<N>()) {} template <std::size_t N, class = std::enable_if_t<(N > 0)>> constexpr span(std::array<std::remove_const_t<element_type>, N>& arr) noexcept : storage_(KnownNotNull{arr.data()}, details::extent_type<N>()) { } constexpr span(std::array<std::remove_const_t<element_type>, 0>&) noexcept : storage_(static_cast<pointer>(nullptr), details::extent_type<0>()) { } template <std::size_t N, class = std::enable_if_t<(N > 0)>> constexpr span(const std::array<std::remove_const_t<element_type>, N>& arr) noexcept : storage_(KnownNotNull{arr.data()}, details::extent_type<N>()) { } constexpr span(const std::array<std::remove_const_t<element_type>, 0>&) noexcept : storage_(static_cast<pointer>(nullptr), details::extent_type<0>()) { } // NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the requirement // on Container to be a contiguous sequence container. template <class Container, class = std::enable_if_t< !details::is_span<Container>::value && !details::is_std_array<Container>::value && std::is_convertible<typename Container::pointer, pointer>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> constexpr span(Container& cont) : span(cont.data(), narrow<index_type>(cont.size())) {} template <class Container, class = std::enable_if_t< std::is_const<element_type>::value && !details::is_span<Container>::value && std::is_convertible<typename Container::pointer, pointer>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> constexpr span(const Container& cont) : span(cont.data(), narrow<index_type>(cont.size())) {} constexpr span(const span& other) noexcept = default; template < class OtherElementType, std::ptrdiff_t OtherExtent, class = std::enable_if_t< details::is_allowed_extent_conversion<OtherExtent, Extent>::value && details::is_allowed_element_type_conversion<OtherElementType, element_type>::value>> constexpr span(const span<OtherElementType, OtherExtent>& other) : storage_(other.data(), details::extent_type<OtherExtent>(other.size())) {} ~span() noexcept = default; constexpr span& operator=(const span& other) noexcept = default; // [span.sub], span subviews template <std::ptrdiff_t Count> constexpr span<element_type, Count> first() const { Expects(Count >= 0 && Count <= size()); return {data(), Count}; } template <std::ptrdiff_t Count> GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute constexpr span<element_type, Count> last() const { Expects(Count >= 0 && size() - Count >= 0); return {data() + (size() - Count), Count}; } template <std::ptrdiff_t Offset, std::ptrdiff_t Count = dynamic_extent> GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute constexpr auto subspan() const -> typename details::calculate_subspan_type<ElementType, Extent, Offset, Count>::type { Expects((Offset >= 0 && size() - Offset >= 0) && (Count == dynamic_extent || (Count >= 0 && Offset + Count <= size()))); return {data() + Offset, Count == dynamic_extent ? size() - Offset : Count}; } constexpr span<element_type, dynamic_extent> first(index_type count) const { Expects(count >= 0 && count <= size()); return {data(), count}; } constexpr span<element_type, dynamic_extent> last(index_type count) const { return make_subspan(size() - count, dynamic_extent, subspan_selector<Extent>{}); } constexpr span<element_type, dynamic_extent> subspan(index_type offset, index_type count = dynamic_extent) const { return make_subspan(offset, count, subspan_selector<Extent>{}); } // [span.obs], span observers constexpr index_type size() const noexcept { return storage_.size(); } constexpr index_type size_bytes() const noexcept { return size() * narrow_cast<index_type>(sizeof(element_type)); } constexpr bool empty() const noexcept { return size() == 0; } // [span.elem], span element access GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute constexpr reference operator[](index_type idx) const { Expects(CheckRange(idx, storage_.size())); return data()[idx]; } constexpr reference at(index_type idx) const { return this->operator[](idx); } constexpr reference operator()(index_type idx) const { return this->operator[](idx); } constexpr pointer data() const noexcept { return storage_.data(); } // [span.iter], span iterator support constexpr iterator begin() const noexcept { return {this, 0}; } constexpr iterator end() const noexcept { return {this, size()}; } constexpr const_iterator cbegin() const noexcept { return {this, 0}; } constexpr const_iterator cend() const noexcept { return {this, size()}; } constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{cend()}; } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator{cbegin()}; } #ifdef _MSC_VER // Tell MSVC how to unwrap spans in range-based-for constexpr pointer _Unchecked_begin() const noexcept { return data(); } constexpr pointer _Unchecked_end() const noexcept { GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute return data() + size(); } #endif // _MSC_VER private: static bool CheckRange(index_type idx, index_type size) { // Optimization: // // idx >= 0 && idx < size // => // static_cast<size_t>(idx) < static_cast<size_t>(size) // // because size >=0 by span construction, and negative idx will // wrap around to a value always greater than size when casted. // check if we have enough space to wrap around if (sizeof(index_type) <= sizeof(size_t)) { return narrow_cast<size_t>(idx) < narrow_cast<size_t>(size); } else { return idx >= 0 && idx < size; } } // Needed to remove unnecessary null check in subspans struct KnownNotNull { pointer p; }; // this implementation detail class lets us take advantage of the // empty base class optimization to pay for only storage of a single // pointer in the case of fixed-size spans template <class ExtentType> class storage_type : public ExtentType { public: // KnownNotNull parameter is needed to remove unnecessary null check // in subspans and constructors from arrays template <class OtherExtentType> constexpr storage_type(KnownNotNull data, OtherExtentType ext) : ExtentType(ext), data_(data.p) { Expects(ExtentType::size() >= 0); } template <class OtherExtentType> constexpr storage_type(pointer data, OtherExtentType ext) : ExtentType(ext), data_(data) { Expects(ExtentType::size() >= 0); Expects(data || ExtentType::size() == 0); } constexpr pointer data() const noexcept { return data_; } private: pointer data_; }; storage_type<details::extent_type<Extent>> storage_; // The rest is needed to remove unnecessary null check // in subspans and constructors from arrays constexpr span(KnownNotNull ptr, index_type count) : storage_(ptr, count) {} template <std::ptrdiff_t CallerExtent> class subspan_selector { }; template <std::ptrdiff_t CallerExtent> span<element_type, dynamic_extent> make_subspan(index_type offset, index_type count, subspan_selector<CallerExtent>) const { const span<element_type, dynamic_extent> tmp(*this); return tmp.subspan(offset, count); } GSL_SUPPRESS(bounds.1) // NO-FORMAT: attribute span<element_type, dynamic_extent> make_subspan(index_type offset, index_type count, subspan_selector<dynamic_extent>) const { Expects(offset >= 0 && size() - offset >= 0); if (count == dynamic_extent) { return {KnownNotNull{data() + offset}, size() - offset}; } Expects(count >= 0 && size() - offset >= count); return {KnownNotNull{data() + offset}, count}; } }; #if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND) template <class ElementType, std::ptrdiff_t Extent> constexpr const typename span<ElementType, Extent>::index_type span<ElementType, Extent>::extent; #endif // [span.comparison], span comparison operators template <class ElementType, std::ptrdiff_t FirstExtent, std::ptrdiff_t SecondExtent> constexpr bool operator==(span<ElementType, FirstExtent> l, span<ElementType, SecondExtent> r) { return std::equal(l.begin(), l.end(), r.begin(), r.end()); } template <class ElementType, std::ptrdiff_t Extent> constexpr bool operator!=(span<ElementType, Extent> l, span<ElementType, Extent> r) { return !(l == r); } template <class ElementType, std::ptrdiff_t Extent> constexpr bool operator<(span<ElementType, Extent> l, span<ElementType, Extent> r) { return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end()); } template <class ElementType, std::ptrdiff_t Extent> constexpr bool operator<=(span<ElementType, Extent> l, span<ElementType, Extent> r) { return !(l > r); } template <class ElementType, std::ptrdiff_t Extent> constexpr bool operator>(span<ElementType, Extent> l, span<ElementType, Extent> r) { return r < l; } template <class ElementType, std::ptrdiff_t Extent> constexpr bool operator>=(span<ElementType, Extent> l, span<ElementType, Extent> r) { return !(l < r); } namespace details { // if we only supported compilers with good constexpr support then // this pair of classes could collapse down to a constexpr function // we should use a narrow_cast<> to go to std::size_t, but older compilers may not see it as // constexpr // and so will fail compilation of the template template <class ElementType, std::ptrdiff_t Extent> struct calculate_byte_size : std::integral_constant<std::ptrdiff_t, static_cast<std::ptrdiff_t>(sizeof(ElementType) * static_cast<std::size_t>(Extent))> { }; template <class ElementType> struct calculate_byte_size<ElementType, dynamic_extent> : std::integral_constant<std::ptrdiff_t, dynamic_extent> { }; } // namespace details // [span.objectrep], views of object representation template <class ElementType, std::ptrdiff_t Extent> span<const byte, details::calculate_byte_size<ElementType, Extent>::value> as_bytes(span<ElementType, Extent> s) noexcept { GSL_SUPPRESS(type.1) // NO-FORMAT: attribute return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()}; } template <class ElementType, std::ptrdiff_t Extent, class = std::enable_if_t<!std::is_const<ElementType>::value>> span<byte, details::calculate_byte_size<ElementType, Extent>::value> as_writeable_bytes(span<ElementType, Extent> s) noexcept { GSL_SUPPRESS(type.1) // NO-FORMAT: attribute return {reinterpret_cast<byte*>(s.data()), s.size_bytes()}; } // // make_span() - Utility functions for creating spans // template <class ElementType> constexpr span<ElementType> make_span(ElementType* ptr, typename span<ElementType>::index_type count) { return span<ElementType>(ptr, count); } template <class ElementType> constexpr span<ElementType> make_span(ElementType* firstElem, ElementType* lastElem) { return span<ElementType>(firstElem, lastElem); } template <class ElementType, std::size_t N> constexpr span<ElementType, N> make_span(ElementType (&arr)[N]) noexcept { return span<ElementType, N>(arr); } template <class Container> constexpr span<typename Container::value_type> make_span(Container& cont) { return span<typename Container::value_type>(cont); } template <class Container> constexpr span<const typename Container::value_type> make_span(const Container& cont) { return span<const typename Container::value_type>(cont); } template <class Ptr> constexpr span<typename Ptr::element_type> make_span(Ptr& cont, std::ptrdiff_t count) { return span<typename Ptr::element_type>(cont, count); } template <class Ptr> constexpr span<typename Ptr::element_type> make_span(Ptr& cont) { return span<typename Ptr::element_type>(cont); } // Specialization of gsl::at for span template <class ElementType, std::ptrdiff_t Extent> constexpr ElementType& at(span<ElementType, Extent> s, index i) { // No bounds checking here because it is done in span::operator[] called below return s[i]; } } // namespace gsl #ifdef _MSC_VER #if _MSC_VER < 1910 #undef constexpr #pragma pop_macro("constexpr") #endif // _MSC_VER < 1910 #pragma warning(pop) #endif // _MSC_VER #if __GNUC__ > 6 #pragma GCC diagnostic pop #endif // __GNUC__ > 6 #endif // GSL_SPAN_H
{ "alphanum_fraction": 0.6422151241, "avg_line_length": 34.0810126582, "ext": "h", "hexsha": "b356ee90ff90ec1ce970341296a7eb6797026029", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z", "max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Redchards/CVRP", "max_forks_repo_path": "include/gsl/span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "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": "Redchards/CVRP", "max_issues_repo_path": "include/gsl/span.h", "max_line_length": 100, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Redchards/CVRP", "max_stars_repo_path": "include/gsl/span.h", "max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z", "num_tokens": 6022, "size": 26924 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_ #define SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_ #include "core/Primitive.h" #include "core/typeutil.h" #include <gsl/gsl> #include <string_view> namespace sq::test { SQ_ND Primitive to_primitive(PrimitiveString &&v); SQ_ND Primitive to_primitive(const PrimitiveString &v); SQ_ND Primitive to_primitive(std::string_view v); SQ_ND Primitive to_primitive(gsl::czstring<> v); SQ_ND Primitive to_primitive(PrimitiveInt v); SQ_ND Primitive to_primitive(int v); SQ_ND Primitive to_primitive(PrimitiveFloat v); SQ_ND Primitive to_primitive(PrimitiveBool v); SQ_ND Primitive to_primitive(PrimitiveNull v); } // namespace sq::test #endif // SQ_INCLUDE_GUARD_core_test_Primitive_test_util_h_
{ "alphanum_fraction": 0.6856561546, "avg_line_length": 32.7666666667, "ext": "h", "hexsha": "85e96e0580364d763a8dfec4bb1d2ad7ad7c3eaa", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/core/test/include/test/Primitive_test_util.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 203, "size": 983 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_min.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_spline.h> // #include "mex.h" #ifndef verbose #define verbose 0 #endif /* $ ./fwhm > interp.dat $ graph -T ps < interp.dat > interp.ps */ struct dbg_data { double xm; // location of maxima double ym; // value at maxima double xleft; double xright; }; FILE * logFile; // my_f and my_f_params defines the interpolation function that the // root-finding functions are run on struct my_f_params { gsl_spline * spline; gsl_interp_accel * acc; double offset; // shifts the function }; double my_f(double , void * ); int findmin(double , double , gsl_spline *, gsl_interp_accel * , size_t , double * , double * ); static void createGaussian(double * , double * , size_t , double ); int fwhm(double * , double * , size_t , double * ); double my_f(double x, void * p) { struct my_f_params * params = (struct my_f_params*) p; #if verbose > 0 printf("f(%f) + %f= ", x, params->offset); fflush(stdout); #endif double y = -gsl_spline_eval(params->spline, x, params->acc) + params->offset; #if verbose > 0 printf("%f\n", y); fflush(stdout); #endif return(y); } int findmin(double a, double b, gsl_spline *spline, gsl_interp_accel * acc, size_t N, double * xm, double * ym) { // a, b: range of function int iter = 0, max_iter = 100; double m = 0; // expected location of minima int status; const gsl_min_fminimizer_type *T; gsl_min_fminimizer *s; struct my_f_params f_params; f_params.spline = spline; f_params.acc = acc; f_params.offset = 0; gsl_function F; F.function = &my_f; F.params = (void *) &f_params; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc (T); if(gsl_min_fminimizer_set (s, &F, m, a, b) == GSL_EINVAL) { // If no minima is enclosed ... i.e. the value at (a+b)/2 isn't lower than at a and b gsl_min_fminimizer_free(s); return 1; } #if verbose > 0 fflush(stdout); printf("Interval: [%f, %f]\n", a, b); double m_expected = -10; printf ("method: '%s'\n", gsl_min_fminimizer_name (s)); printf ("%5s [%9s, %9s] %9s %10s %9s\n", "iter", "lower", "upper", "min", "err", "err(est)"); printf ("%5d [%.7f, %.7f] %.7f %+.7f %.7f\n", iter, a, b, m, m - m_expected, b - a); #endif do { iter++; status = gsl_min_fminimizer_iterate (s); a = gsl_min_fminimizer_x_lower (s); b = gsl_min_fminimizer_x_upper (s); status = gsl_min_test_interval (a, b, 0.001, 0.0); #if verbose > 0 float m = gsl_min_fminimizer_x_minimum (s); if (status == GSL_SUCCESS) { printf ("Converged:\n"); } else { printf("No convergence %d\n", status); } printf ("%5d [%.7f, %.7f] " "%.7f %+.7f %.7f\n", iter, a, b, m, m - m_expected, b - a); #endif } while (status == GSL_CONTINUE && iter < max_iter); xm[0] = (a+b)/2; ym[0] = my_f(xm[0], &f_params); gsl_min_fminimizer_free(s); #if verbose > 0 printf("Status: %d\n", status); #endif return status; } int fwhm(double * x, double * y, size_t N, double * w) { int useLog = 0; if(verbose) { useLog = 1; } if(useLog) { logFile = fopen("/tmp/fwhmlog", "w"); } #ifndef debug gsl_set_error_handler_off(); #endif int N2 = (N-1)/2; // even number // Set up interpolation gsl_interp_accel *acc = gsl_interp_accel_alloc(); // Neccessary? gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, N); gsl_spline_init(spline, x, y, N); // See that the correct value is given at x=0 #if verbose > 0 printf("y[%f] = %f\n", x[N2], gsl_spline_eval(spline, x[N2], acc)); fflush(stdout); #endif // Find position of max, i.e., centre in [xmin, xmax] double xmin = -2.5; double xmax = 2.501; double xm = 10e99; double ym = 10e99; #if verbose > 0 printf("calling findmin\n"); fflush(stdout); #endif if( findmin(xmin, xmax, spline, acc, N, &xm, &ym) ) { #if verbose > 0 printf("Could not find the position of the maxima!\n"); #endif gsl_spline_free (spline); gsl_interp_accel_free (acc); if(useLog) { fclose(logFile); } return 1; } if(useLog) { fprintf(logFile, "xm: %f, ym: %f\n", xm, ym); } #if verbose > 0 printf("-> Minima: f(%f) = %f\n", xm, ym); #endif // Determine background double bg = (y[0]+y[N-1])/2; #if verbose > 0 printf("Background level: %f\n", bg); #endif if(useLog) { fprintf(logFile, "bg: %f\n", bg); } if(bg <= ym) { fprintf(logFile, "stopping, bg <= tm\n"); if(useLog) { fclose(logFile); } gsl_spline_free (spline); gsl_interp_accel_free (acc); return 1; } // Find intersection .5*(max-bg) for each side // ROOT FINDING const gsl_root_fsolver_type * Tsolve = gsl_root_fsolver_bisection; gsl_root_fsolver * rsolve = gsl_root_fsolver_alloc(Tsolve); // Search for left and right intersections double intersections[2]; intersections[0] = 0; intersections[1] = 0; for(int dire = 0; dire<2; dire++) { // Search in range [x_lo, x_hi] double x_lo; double x_hi; if(dire==0) { x_lo = -N2; x_hi = xm; } if(dire==1) { x_lo = xm; x_hi = N2; } struct my_f_params f_params; f_params.spline = spline; f_params.acc = acc; f_params.offset = (bg+(-ym-bg)/2); if(useLog) { fprintf(logFile, "x_lo: %f x_hi: %f\n", x_lo, x_hi); fprintf(logFile, "offset: %f, bg: %f, ym: %f\n", f_params.offset, bg, ym); } gsl_function F; F.function = &my_f; F.params = (void *) &f_params; /* * Function: int gsl_root_fsolver_set (gsl_root_fsolver * s, gsl_function * f, double x_lower, double x_upper) * This function initializes, or reinitializes, an existing solver s to use the function f and the initial * search interval [x_lower, x_upper] */ int status = gsl_root_fsolver_set(rsolve, &F, x_lo, x_hi); size_t iter = 0; size_t max_iter = 10; #if verbose > 0 double r_expected = (x_lo+x_hi)/2; printf ("using %s method\n", gsl_root_fsolver_name (rsolve)); printf ("%5s [%9s, %9s] %9s %10s %9s\n", "iter", "lower", "upper", "root", "err", "err(est)"); #endif do { iter++; status = gsl_root_fsolver_iterate (rsolve); // update bounds x_lo = gsl_root_fsolver_x_lower (rsolve); x_hi = gsl_root_fsolver_x_upper (rsolve); // see if converged status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001); #if verbose > 0 double r = gsl_root_fsolver_root (rsolve); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5lu [%.7f, %.7f] %.7f %+.7f %.7f\n", iter, x_lo, x_hi, r, r - r_expected, x_hi - x_lo); #endif } while (status == GSL_CONTINUE && iter < max_iter); #if verbose > 0 printf("Found intersection at %f\n", (x_lo+x_hi)/2); #endif intersections[dire] = (x_lo+x_hi)/2; if(useLog) { fprintf(logFile, "intersection %d: %f\n", dire, (x_lo+x_hi)/2); } } gsl_root_fsolver_free(rsolve); // Clean up gsl_spline_free (spline); gsl_interp_accel_free (acc); // fwhm: right-left positions w[0] = intersections[1] - intersections[0]; if(useLog) { fclose(logFile); } return 0; // Ok } static void createGaussian( double * x, double * y, size_t N, double x0) { /* Create a gaussian shaped test signal, y * over the domain x * x0 is the offset from center * */ int N2 = (N-1)/2; // middle element for(int kk=0; kk<N; kk++) { double p = 2*((double) kk - N2)/N; // [-1,1]; p = (p*3-x0); y[kk] = exp(-p*p); x[kk] = kk-N2; // Set x to pixel position from centre #if verbose>0 printf("%f %f\n", x[kk], y[kk]); #endif } } int main(int argc, char ** argv) { int N = 11; // Size of test signal double * y = malloc(N*sizeof(double)); double * x = malloc(N*sizeof(double)); memset(x, 0, N*sizeof(double)); memset(y, 0, N*sizeof(double)); createGaussian(x,y, N, 0); double w = -1; // output if(1){ for(double delta = -1; delta <=1; delta +=0.1) { createGaussian(x,y, N, delta); if(fwhm(x, y, N, &w)) { printf("Error: Could not calculate fwhm!\n"); } printf("offset: % .2f pixels, fwhm: %f pixels\n", delta, w); } } for(int kk = 0; kk<N; kk++) { y[kk] = 0; } if(1){ printf("constant y\n"); if(fwhm(x, y, N, &w)) { printf("# Error!\n"); free(y); free(x); return(1); } } free(y); free(x); return(0); }
{ "alphanum_fraction": 0.5703271285, "avg_line_length": 22.4727722772, "ext": "c", "hexsha": "77ed09f76abace455214f53e8f180356f121f333", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elgw/dotter", "max_forks_repo_path": "common/mex/fwhm1d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elgw/dotter", "max_issues_repo_path": "common/mex/fwhm1d.c", "max_line_length": 115, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elgw/dotter", "max_stars_repo_path": "common/mex/fwhm1d.c", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "num_tokens": 2869, "size": 9079 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include "ccl.h" /* BCM correction */ // See Schneider & Teyssier (2015) for details of the model. double ccl_bcm_model_fka(ccl_cosmology * cosmo, double k, double a, int *status) { double fkz; double b0; double bfunc, bfunc4; double kg; double gf,scomp; double kh; double z; z = 1./a - 1.; kh = k / cosmo->params.h; b0 = 0.105*cosmo->params.bcm_log10Mc - 1.27; bfunc = b0 / (1. + pow(z/2.3, 2.5)); bfunc4 = (1-bfunc) * (1-bfunc) * (1-bfunc) * (1-bfunc); kg = 0.7 * bfunc4 * pow(cosmo->params.bcm_etab, -1.6); gf = bfunc / (1 + pow(kh/kg, 3.)) + 1. - bfunc; //k in h/Mpc scomp = 1 + (kh / cosmo->params.bcm_ks) * (kh / cosmo->params.bcm_ks); //k in h/Mpc fkz = gf * scomp; return fkz; } void ccl_bcm_correct(ccl_cosmology *cosmo, ccl_f2d_t *psp, int *status) { size_t nk, na; double *x, *z, *y2d=NULL; //Find lk array if(psp->fk != NULL) { nk = psp->fk->size; x = psp->fk->x; } else { nk = psp->fka->interp_object.xsize; x = psp->fka->xarr; } //Find a array if(psp->fa != NULL) { na = psp->fa->size; z = psp->fa->x; } else { na = psp->fka->interp_object.ysize; z = psp->fka->yarr; } //Allocate pka array y2d = malloc(nk * na * sizeof(double)); if (y2d == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_bcm.c: ccl_bcm_correct(): " "memory allocation\n"); } if (*status == 0) { for (int j = 0; j<na; j++) { for (int i=0; i<nk; i++) { if (*status == 0) { double pk = ccl_f2d_t_eval(psp, x[i], z[j], cosmo, status); double fbcm = ccl_bcm_model_fka(cosmo, exp(x[i]), z[j], status); if(psp->is_log) y2d[j*nk + i] = log(pk*fbcm); else y2d[j*nk + i] = pk*fbcm; } } } } if (*status == 0) { gsl_spline2d *fka = gsl_spline2d_alloc(gsl_interp2d_bicubic, nk, na); if (fka == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_bcm.c: ccl_bcm_correct(): " "memory allocation\n"); } if(*status == 0) { int spstatus = gsl_spline2d_init(fka, x, z, y2d, nk, na); if(spstatus) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_bcm.c: ccl_bcm_correct(): " "Error initializing spline\n"); } } if(*status == 0) { if(psp->fa != NULL) gsl_spline_free(psp->fa); if(psp->fk != NULL) gsl_spline_free(psp->fk); if(psp->fka != NULL) gsl_spline2d_free(psp->fka); psp->fka = fka; psp->is_factorizable = 0; psp->is_k_constant = 0; psp->is_a_constant = 0; } else gsl_spline2d_free(fka); } free(y2d); }
{ "alphanum_fraction": 0.5235160558, "avg_line_length": 25.9075630252, "ext": "c", "hexsha": "b442cfe194715fbd2d053de07754b47f0f4052b1", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "src/ccl_bcm.c", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "src/ccl_bcm.c", "max_line_length": 85, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "src/ccl_bcm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 1067, "size": 3083 }
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file rk_4_2.c * \brief Source file to optimize Runge-Kutta 4 steps 2nd order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_4_2.h" #define DEBUG_RK_4_2 0 ///< macro to debug. /** * Function to obtain the coefficients of a 4 steps 2nd order Runge-Kutta * method. */ int rk_tb_4_2 (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t4 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; t3 (tb) = r[3]; b31 (tb) = r[4]; b32 (tb) = r[5]; b41 (tb) = r[6]; b42 (tb) = r[7]; b43 (tb) = (0.5L - b41 (tb) * t1 (tb) - b42 (tb) * t2 (tb)) / t3 (tb); if (isnan (b43 (tb))) return 0; rk_b_4 (tb); #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 4 steps 2nd order, 3rd order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_4_2t (Optimize * optimize) ///< Optimize struct. { long double *tb, *r; #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t4 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; t3 (tb) = r[3]; b31 (tb) = r[4]; b32 (tb) = r[5]; b41 (tb) = r[6]; b42 (tb) = (1.L / 3.L - 0.5L * t3 (tb) - b41 (tb) * t1 (tb) * (t1 (tb) - t3 (tb))) / (t2 (tb) * (t2 (tb) - t3 (tb))); if (isnan (b42 (tb))) return 0; b43 (tb) = (0.5L - b41 (tb) * t1 (tb) - b42 (tb) * t2 (tb)) / t3 (tb); if (isnan (b43 (tb))) return 0; rk_b_4 (tb); #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2t: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 4 steps 1st-2nd order Runge-Kutta * pair. */ int rk_tb_4_2p (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2p: start\n"); #endif if (!rk_tb_4_2 (optimize)) return 0; tb = optimize->coefficient; e41 (tb) = e42 (tb) = 0.L; rk_e_4 (tb); #if DEBUG_RK_4_2 rk_print_e (optimize, "rk_tb_4_2p", stderr); fprintf (stderr, "rk_tb_4_2p: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 4 steps 1st-2nd order, 1st-3rd order * in equations depending only in time, Runge-Kutta method. */ int rk_tb_4_2tp (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_4_2 fprintf (stderr, "rk_tb_4_2tp: start\n"); #endif if (!rk_tb_4_2t (optimize)) return 0; tb = optimize->coefficient; e41 (tb) = e42 (tb) = 0.L; rk_e_4 (tb); #if DEBUG_RK_4_2 rk_print_tb (optimize, "rk_tb_4_2tp", stderr); fprintf (stderr, "rk_tb_4_2pt: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 4 steps 2nd order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_4_2 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_4_2 fprintf (stderr, "rk_objective_tb_4_2: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b43 (tb) < 0.L) o += b43 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb)))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_4_2 fprintf (stderr, "rk_objective_tb_4_2: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_4_2: end\n"); #endif return o; } /** * Function to calculate the objective function of a 4 steps 2nd order, 3rd * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_4_2t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_4_2 fprintf (stderr, "rk_objective_tb_4_2t: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b42 (tb) < 0.L) o += b42 (tb); if (b43 (tb) < 0.L) o += b43 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb)))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_4_2 fprintf (stderr, "rk_objective_tb_4_2t: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_4_2t: end\n"); #endif return o; }
{ "alphanum_fraction": 0.6381893529, "avg_line_length": 25.5040650407, "ext": "c", "hexsha": "6aadac489054525052d1e29ae27056ea84786647", "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": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ode", "max_forks_repo_path": "rk_4_2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/ode", "max_issues_repo_path": "rk_4_2.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ode", "max_stars_repo_path": "rk_4_2.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2217, "size": 6274 }
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_integration.h> #include <fastpm/libfastpm.h> #include <fastpm/logging.h> #define LENGTH_FERMI_DIRAC_TABLE 4000 //sets the length of the table on which CDF //will be evaluated #define MAX_FERMI_DIRAC 20.0 //Upper limit of F-D distribution in units of // p/T #define NEXT(n, i) (((n) + (i)/(n)) >> 1) // Needed for Healpix routine //needed for healpix unsigned int isqrt(int number) { unsigned int n = 1; unsigned int n1 = NEXT(n, number); while(abs(n1 - n) > 1) { n = n1; n1 = NEXT(n, number); } while(n1*n1 > number) n1--; return n1; } //Converts from pixel number to unit vector (needed for healpix) void pix2vec (int pix, double *vec, int n_side) { double z, phi; int nside_ = n_side; long ncap_=nside_*(nside_-1)*2; long npix_=12*nside_*nside_; double fact2_ = 4./npix_; if (pix<ncap_) /* North Polar cap */ { int iring = (int)(0.5*(1+isqrt(1+2*pix))); /* counted from North pole */ int iphi = (pix+1) - 2*iring*(iring-1); z = 1.0 - (iring*iring)*fact2_; phi = (iphi-0.5) * 0.5*M_PI/iring; } else if (pix<(npix_-ncap_)) /* Equatorial region */ { double fact1_ = (nside_<<1)*fact2_; int ip = pix - ncap_; int iring = ip/(4*nside_) + nside_; /* counted from North pole */ int iphi = ip%(4*nside_) + 1; /* 1 if iring+nside is odd, 1/2 otherwise */ double fodd = ((iring+nside_)&1) ? 1 : 0.5; int nl2 = 2*nside_; z = (nl2-iring)*fact1_; phi = (iphi-fodd) * M_PI/nl2; } else /* South Polar cap */ { int ip = npix_ - pix; int iring = (int)(0.5*(1+isqrt(2*ip-1))); /* counted from South pole */ int iphi = 4*iring + 1 - (ip - 2*iring*(iring-1)); z = -1.0 + (iring*iring)*fact2_; phi = (iphi-0.5) * 0.5*M_PI/iring; } double v[3]; v[0] = sin(acos(z))*cos(phi); v[1] = sin(acos(z))*sin(phi); v[2] = z; /* rotate the vector to break degeneracy with grid axes */ vec[0] = 0.5*v[0] -0.5*v[1] +0.70710678*v[2]; vec[1] = 0.85355339*v[0] +0.14644661*v[1] -0.5*v[2]; vec[2] = 0.14644661*v[0] +0.85355339*v[1] +0.5*v[2]; } /* make params struct for functions we will integrate with gsl */ typedef struct kernel_params { double m[3]; int n; } kernel_params; double fermi_dirac_kernel_vol_1(double x) { /* Functional form of FD distribution for 1 particle over the full volume (i.e. no *x^2) */ return 1. / (exp(x) + 1); } double fermi_dirac_kernel_vol(double x, void * p) { /* FD kernel in the case of multiple particles over the full volume (i.e. no *x^2) */ struct kernel_params * params = (struct kernel_params *)p; double result = fermi_dirac_kernel_vol_1(x); // only loop from i=1. i=0 term has been included in result already (r=1) for(int i = 1; i < params->n; i ++) { double r = params->m[i] / params->m[0]; result += (r*r*r*r) * fermi_dirac_kernel_vol_1(x * r); } return result; } /* now define the 1D kernel and moments */ double fermi_dirac_kernel(double x, void * p) { return x*x * fermi_dirac_kernel_vol(x, p); } /* Samples the low velocity end more effectively */ double low_vel_kernel(double x, void * p) { return x * fermi_dirac_kernel_vol(x, p); } /* Needed for calculatin the velocity dispersion */ double fermi_dirac_dispersion(double x, void * p) { return x*x*x*x * fermi_dirac_kernel_vol(x, p); } void divide_fd(double *vel_table, double *mass, kernel_params * params, int n_shells, int lvk) { double fermi_dirac_vel_ncdm[LENGTH_FERMI_DIRAC_TABLE]; double fermi_dirac_cdf_ncdm[LENGTH_FERMI_DIRAC_TABLE]; //stores CDF int i,j; double v_bin,u,bin_average,bin_mass; double vel_edges[n_shells]; double result,error; gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); gsl_function F,G,H; if(lvk) F.function = &low_vel_kernel; else F.function = &fermi_dirac_kernel; G.function = &fermi_dirac_kernel; H.function = &fermi_dirac_dispersion; F.params = (void*) params; G.params = (void*) params; H.params = (void*) params; // Initialize the CDF table for(i = 0; i < LENGTH_FERMI_DIRAC_TABLE; i++){ fermi_dirac_vel_ncdm[i] = MAX_FERMI_DIRAC * i / (LENGTH_FERMI_DIRAC_TABLE - 1.0); gsl_integration_qags (&F, 0, fermi_dirac_vel_ncdm[i], 0,1e-7 , 1000, w, &result, &error); fermi_dirac_cdf_ncdm[i] = result; } //Normalize to 1 for(i = 0; i < LENGTH_FERMI_DIRAC_TABLE; i++) fermi_dirac_cdf_ncdm[i] /= fermi_dirac_cdf_ncdm[LENGTH_FERMI_DIRAC_TABLE - 1]; //Define the edges of the velocity bins (lower edge held to 0) for(i=0;i<n_shells;i++){ v_bin = (i+1)/(n_shells*1.0); j=0; while(j < LENGTH_FERMI_DIRAC_TABLE - 2) if(v_bin > fermi_dirac_cdf_ncdm[j + 1]) j++; else break; u = (v_bin - fermi_dirac_cdf_ncdm[j]) / (fermi_dirac_cdf_ncdm[j + 1] - fermi_dirac_cdf_ncdm[j]); vel_edges[i] = fermi_dirac_vel_ncdm[j] * (1 - u) + fermi_dirac_vel_ncdm[j + 1] * u; } //Get the bin velocities and bin masses double total_mass; gsl_integration_qags (&G, 0, fermi_dirac_vel_ncdm[LENGTH_FERMI_DIRAC_TABLE-1], 0, 1e-7, 1000, w, &result, &error); total_mass = result; for(i=0;i<n_shells;i++){ //Special case for lowest bin - left edge has to be zero if (i==0){ gsl_integration_qags (&H, 0,vel_edges[i], 0, 1e-7, 1000, w, &result, &error); bin_average = result; gsl_integration_qags (&G, 0, vel_edges[i], 0, 1e-7, 1000, w, &result, &error); bin_average /= result; bin_mass = result/total_mass; } else{ gsl_integration_qags (&H, vel_edges[i-1], vel_edges[i], 0, 1e-7, 1000, w, &result, &error); bin_average = result; gsl_integration_qags (&G, vel_edges[i-1], vel_edges[i], 0, 1e-7, 1000, w, &result, &error); bin_average /= result; bin_mass = result/total_mass; } vel_table[i] = sqrt(bin_average); mass[i] = bin_mass; } } void divide_sphere_healpix(double *vec_table, int n_side) //so is the direction totally fixed? could we rotate the divisions relative to north pole (i.e. relative to the box)? { int i,k; double v_sq[3]; for(k=0;k<3;k++) v_sq[k] = 0.; // Get unit vectors for all pixels for(i=0;i<12*n_side*n_side;i++){ pix2vec(i,&vec_table[i*3],n_side); for(k=0;k<3;k++) v_sq[k] += vec_table[i*3+k]*vec_table[i*3+k]; } // Isotropize the velocity dispersion - important for low n_side [should we remove this if for high n_side???] for(k=0;k<3;k++){ v_sq[k] /= 12*n_side*n_side; v_sq[k] /= 1./3.; // Set each direction to have 1/3 of total dispersion } for(i=0;i<12*n_side*n_side;i++) for(k=0;k<3;k++) vec_table[i*3+k] /= sqrt(v_sq[k]); } void divide_sphere_fibonacci(double *vec_table, int n_side) { int n_fibonacci = n_side; double lat, lon; int i, j; //int N_tot = 2 * n_fibonacci + 1; for (i=-n_fibonacci;i<n_fibonacci+1;i++){ lat = asin(2.0*i/(2.0*n_fibonacci+1)); lon = 2.0*M_PI*i*2.0/(1.0+sqrt(5.0)); j = i + n_fibonacci; vec_table[j*3+0] = cos(lat)*cos(lon); vec_table[j*3+1] = cos(lat)*sin(lon); vec_table[j*3+2] = sin(lat); } } void divide_sphere(FastPMncdmSphereScheme ncdm_sphere_scheme, double *vec_table, int n_side) { switch (ncdm_sphere_scheme){ case FASTPM_NCDM_SPHERE_HEALPIX: divide_sphere_healpix(vec_table, n_side); break; case FASTPM_NCDM_SPHERE_FIBONACCI: divide_sphere_fibonacci(vec_table, n_side); break; default: fastpm_raise(-1, "Wrong ncdm sphere scheme.\n"); } } static void _fastpm_ncdm_init_fill(FastPMncdmInitData* nid); //create and fill the table FastPMncdmInitData* fastpm_ncdm_init_create( double BoxSize, FastPMCosmology * c, double z, int n_shells, int n_side, int lvk, FastPMncdmSphereScheme ncdm_sphere_scheme) { FastPMncdmInitData* nid = malloc(sizeof(nid[0])); nid->BoxSize = BoxSize; nid->m_ncdm_sum = 0; for(int i = 0; i < c->N_ncdm; i ++) { nid->m_ncdm[i] = c->m_ncdm[i]; nid->m_ncdm_sum += c->m_ncdm[i]; } nid->n_ncdm = c->N_ncdm; nid->Omega_ncdm = c->Omega_ncdm; nid->z = z; fastpm_info("ncdm reference redshift = %g\n", z); nid->n_shells = n_shells; nid->n_side = n_side; nid->lvk = lvk; nid->ncdm_sphere_scheme = ncdm_sphere_scheme; /* this is the total number of velocity vectors produced */ switch (ncdm_sphere_scheme){ case FASTPM_NCDM_SPHERE_HEALPIX: nid->n_sphere = 12 * n_side * n_side; break; case FASTPM_NCDM_SPHERE_FIBONACCI: nid->n_sphere = 2 * n_side + 1; break; default: fastpm_raise(-1, "Wrong ncdm sphere scheme.\n"); } nid->n_split = n_shells * nid->n_sphere; /* recall vel is a pointer to a 3 element array so lets make into multidim array of dim (n_split x 3) */ //for now store all (3) neutrinos in the same nid table. nid->vel = calloc(nid->n_split, sizeof(double[3])); nid->mass = calloc(nid->n_split, sizeof(double)); //a 1d array to store all the masses _fastpm_ncdm_init_fill(nid); return nid; } //free the table void fastpm_ncdm_init_free(FastPMncdmInitData* nid) { free(nid->vel); free(nid->mass); free(nid); } //append the table static void _fastpm_ncdm_init_fill(FastPMncdmInitData* nid) { int n_ncdm = nid->n_ncdm; int n_shells = nid->n_shells; int n_side = nid->n_side; int n_sphere = nid->n_sphere; int lvk = nid->lvk; double *vel_table, *vec_table, *masstab; vel_table = malloc(sizeof(double)*n_shells); /* masstab is the distribution integrated per shell, sums to 1 */ masstab = calloc(n_shells,sizeof(double)); vec_table = malloc(sizeof(double)*n_sphere*3); /* define the kernel params for dividing fd */ kernel_params* params = malloc(sizeof(params[0])); for(int i = 0; i < n_ncdm; i ++) { params->m[i] = nid->m_ncdm[i]; } params->n = n_ncdm; divide_fd(vel_table, masstab, params, n_shells, lvk); divide_sphere(nid->ncdm_sphere_scheme, vec_table, n_side); /* velocity_conversion_factor converts the dimless exponent in the FD distribution to velocity in FastPM units: conjugate momentum (a^2 xdot, where x is comoving dist). kTc = 50.3 eV/c^2 km/s */ double m0 = nid->m_ncdm[0]; double velocity_conversion_factor = 50.3 / m0 / HubbleConstant; int i, j, d; int s = 0; //row num (s for split index) for(i = 0; i < n_sphere; i ++){ for(j = 0; j < n_shells; j ++){ /* define mass st sum over split gives 1 */ nid->mass[s] = masstab[j] / n_sphere; for(d = 0; d < 3; d ++){ nid->vel[s][d] = vel_table[j] * vec_table[i*3 + d] * velocity_conversion_factor; } s++; } } free(vel_table); free(masstab); free(vec_table); } void fastpm_split_ncdm(FastPMncdmInitData * nid, FastPMStore * src, FastPMStore * dest, MPI_Comm comm) { /* Takes store src and splits according to the ncdm init data, and uses this to populate an dest store. src is fully populated after calling the setup_lpt func, but dest has only been init'd. */ dest->np = src->np * nid->n_split; // FIXME: ? Is proc imbalance an issue that needs to be accounted for? if(dest->np > dest->np_upper) { fastpm_raise(-1, "exceeding limit on the number limit of particles for the ncdm species \n"); } size_t np_total = fastpm_store_get_np_total(src, comm); //np_total is num of UNsplit ncdms /* avg mass of UNsplit ncdm site */ double M0 = nid->Omega_ncdm * FASTPM_CRITICAL_DENSITY * pow(nid->BoxSize, 3) / np_total; double Mestate = M0 / nid->n_ncdm; fastpm_info("average mass of a ncdm particle is %g\n", Mestate); /* copy and amend meta-data */ memmove(&dest->meta, &src->meta, sizeof(src->meta)); dest->meta.M0 = 0.; /* will have a mass per particle */ /* Compute the factor used to displace ncdm so that the expanded spheres almost touch. This assumes the largest speed particle is in the final entry of vel table */ int n_shells = nid->n_shells; int n_sphere = nid->n_sphere; double vthm_max = 0; for (int d = 0; d < 3; d ++) vthm_max += nid->vel[n_sphere*n_shells-1][d]*nid->vel[n_sphere*n_shells-1][d]; vthm_max = sqrt(vthm_max); double disp_factor = 0.5 * nid->BoxSize / nid->n_ncdm / vthm_max * (n_shells - 1) / n_shells; ptrdiff_t i, s, d; ptrdiff_t r = 0; //row index of dest int c; double vthm; for(i = 0; i < src->np; i ++) { //loop thru each src particle for(s = 0; s < nid->n_split; s ++) { //loop thru split velocities /* copy all cols el by el */ for(c = 0; c < 32; c ++) { if (!dest->columns[c] || !src->columns[c]) continue; size_t elsize = dest->_column_info[c].elsize; memcpy(dest->columns[c] + r * elsize, src->columns[c] + i * elsize, elsize); } /* give id, mass and add thm vel */ dest->id[r] = s * src->meta._q_size + src->id[i]; dest->mass[r] = nid->mass[s] * M0; // ensures sum over split gives M0 for(d = 0; d < 3; d ++){ vthm = nid->vel[s][d]; dest->v[r][d] = vthm; dest->x[r][d] += vthm * disp_factor; if (dest->q) dest->q[r][d] += vthm * disp_factor; } r ++; } } }
{ "alphanum_fraction": 0.5841276419, "avg_line_length": 31.5424836601, "ext": "c", "hexsha": "eda9190ced87fd44d8c352bc6a8cbd7ac749ac3d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/libfastpm/thermalvelocity.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/libfastpm/thermalvelocity.c", "max_line_length": 176, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/libfastpm/thermalvelocity.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4486, "size": 14478 }
#ifndef ALE_INCLUDE_ALE_H #define ALE_INCLUDE_ALE_H #include <nlohmann/json.hpp> #include <string> #include <vector> #include <gsl/gsl_interp.h> #include <nlohmann/json.hpp> using json = nlohmann::json; namespace ale { /// Interpolation enum for defining different methods of interpolation enum interpolation { /// Interpolate using linear interpolation linear, /// Interpolate using spline interpolation spline }; /** *@brief Get the position of the spacecraft at a given time based on a set of coordinates, and their associated times *@param coords A vector of double vectors of coordinates *@param times A double vector of times *@param time Time to observe the spacecraft's position at *@param interp Interpolation type *@return A vector double of the spacecrafts position */ std::vector<double> getPosition(std::vector<std::vector<double>> coords, std::vector<double> times, double time, interpolation interp); /** *@brief Get the velocity of the spacecraft at a given time based on a set of coordinates, and their associated times *@param coords A vector of double vectors of coordinates *@param times A double vector of times *@param time Time to observe the spacecraft's velocity at *@param interp Interpolation type *@return A vector double of the spacecrafts velocity */ std::vector<double> getVelocity(std::vector<std::vector<double>> coords, std::vector<double> times, double time, const interpolation interp); /** *@brief Get the position of the spacecraft at a given time based on a derived function from a set of coeffcients *@param coeffs A vector of double vector of coeffcients *@param time Time to observe the spacecraft's position at *@return A vector double of the spacecrafts position */ std::vector<double> getPosition(std::vector<std::vector<double>> coeffs, double time); /** *@brief Get the velocity of the spacecraft at a given time based on a derived function from a set of coeffcients *@param coeffs A vector of double vector of coeffcients *@param time Time to observe the spacecraft's velocity at *@return A vector double of the spacecrafts velocity */ std::vector<double> getVelocity(std::vector<std::vector<double>> coeffs, double time); /** *@brief Get the rotation of the spacecraft at a given time based on a set of rotations, and their associated times *@param rotations A vector of double vector of rotations *@param times A double vector of times *@param time Time to observe the spacecraft's rotation at *@param interp Interpolation type *@return A vector double of the spacecrafts rotation */ std::vector<double> getRotation(std::vector<std::vector<double>> rotations, std::vector<double> times, double time, interpolation interp); /** *@brief Get the angular velocity of the spacecraft at a given time based on a set of rotations, and their associated times *@param rotations A vector of double vector of rotations *@param times A double vector of times *@param time Time to observe the spacecraft's angular velocity at *@param interp Interpolation type *@return A vector double of the spacecrafts angular velocity */ std::vector<double> getAngularVelocity(std::vector<std::vector<double>> rotations, std::vector<double> times, double time, interpolation interp); /** *@brief Get the rotation of the spacecraft at a given time based on a derived function from a set of coeffcients *@param coeffs A vector of double vector of coeffcients *@param time Time to observe the spacecraft's rotation at *@return A vector double of the spacecrafts rotation */ std::vector<double> getRotation(std::vector<std::vector<double>> coeffs, double time); /** *@brief Get the angular velocity of the spacecraft at a given time based on a derived function from a set of coeffcients *@param coeffs A vector of double vector of coeffcients *@param time Time to observe the spacecraft's angular velocity at *@return A vector double of the spacecrafts angular velocity */ std::vector<double> getAngularVelocity(std::vector<std::vector<double>> coeffs, double time); /** *@brief Generates a derivatives in respect to time from a polynomial constructed using the given coeffcients, time, and derivation number *@param coeffs A double vector of coefficients can be any number of coefficients *@param time Time to use when deriving *@param d The order of the derivative to generate (Currently supports 0, 1, and 2) *@return Evalutation of the given polynomial as a double */ double evaluatePolynomial(std::vector<double> coeffs, double time, int d); /** *@brief Interpolates the spacecrafts position along a path generated from a set of points, times, and a time of observation *@param points A double vector of points *@param times A double vector of times *@param time A double to use as the time of observation *@param interp An interpolation enum dictating what type of interpolation to use *@param d The order of the derivative to generate when interpolating (Currently supports 0, 1, and 2) *@return */ double interpolate(std::vector<double> points, std::vector<double> times, double time, interpolation interp, int d); std::string loads(std::string filename, std::string props="", std::string formatter="usgscsm", bool verbose=true); json load(std::string filename, std::string props="", std::string formatter="usgscsm", bool verbose=true); } #endif // ALE_H
{ "alphanum_fraction": 0.6995408944, "avg_line_length": 45.2384615385, "ext": "h", "hexsha": "fb7841ba50cbb6831dfab782f1e50232453b3c8a", "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": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "kaitlyndlee/ale", "max_forks_repo_path": "include/ale.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "kaitlyndlee/ale", "max_issues_repo_path": "include/ale.h", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "kaitlyndlee/ale", "max_stars_repo_path": "include/ale.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1254, "size": 5881 }
#include <gsl/gsl_rng.h> double GrowthFactor(double astart, double aend); void print_spec(void); int FatalError(int errnum); void displacement_fields(void); void initialize_ffts(void); void set_units(void); void assemble_particles(void); void free_ffts(void); double fnl(double x); int find_files(char *fname); void assemble_grid(void); void read_power_table(void); double periodic_wrap(double x); double PowerSpec(double kmag); double PowerSpec_Efstathiou(double k); double PowerSpec_EH(double k); double PowerSpec_Tabulated(double k); double PowerSpec_DM_2ndSpecies(double k); double PowerSpec_Tabulated2nd(double k); void initialize_powerspectrum(void); double GrowthFactor(double astart, double aend); double growth(double a); double growth_int(double, void *param); double qromb(double (*func)(double), double a, double b); double sigma2_int(double k, void *param); double TopHatSigma2(double R); double F_Omega(double a); void combine_particle_data(void); int compare_logk(const void *a, const void *b); void write_particle_data(void); void read_parameterfile(char *fname); void read_glass(char *fname); double tk_eh(double k); size_t my_fread(void *ptr, size_t size, size_t nmemb, FILE * stream); size_t my_fwrite(void *ptr, size_t size, size_t nmemb, FILE * stream); void save_local_data(void); void add_WDM_thermal_speeds(float *vel); int compare_type(const void *a, const void *b); double get_fermi_dirac_vel_nu(void); void fermi_dirac_init_nu(void); void add_NU_thermal_speeds(float *vel);
{ "alphanum_fraction": 0.7729624838, "avg_line_length": 26.2033898305, "ext": "h", "hexsha": "5469979848c83c5d2dfa26c97b8fb7fb541a4166", "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/N-GenIC/proto.h", "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/N-GenIC/proto.h", "max_line_length": 70, "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/N-GenIC/proto.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 391, "size": 1546 }
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <assert.h> #include <math.h> #if __INTEL_COMPILER #include "mkl.h" #else #include <gsl/gsl_cblas.h> #endif #include "defs.h" #include "utils.h" #include "progressbar.h" long naive(const double * restrict x1, const double * restrict y1, const int N, double * restrict d) { long numcomputed=0; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { double *dist = d + i*N + j; const double *y0 = (const double *) &y1[j*NDIM]; const double *x0 = (const double *) &x1[i*NDIM]; const double dx = x0[0] - y0[0]; const double dy = x0[1] - y0[1]; const double dz = x0[2] - y0[2]; #ifndef SQRT_DIST *dist = dx*dx + dy*dy + dz*dz; #else *dist = sqrt(dx*dx + dy*dy + dz*dz); #endif } numcomputed+=N; } return numcomputed; } long chunked(const double * restrict x1, const double * restrict y1, const int N, double * restrict d) { long numcomputed = 0; const int block_size = 16; for(int i=0;i<N;i+=block_size) { const int block_size1 = (N-i) > block_size ? block_size:(N-i); for(int j=0;j<N;j+=block_size) { const int block_size2 = (N-j) > block_size ? block_size:(N-j); for(int ii=0;ii<block_size1;ii++) { const long index = (i+ii)*(long) N + j; double *dist = (double *) &d[index]; for(int jj=0;jj<block_size2;jj++) { const double *y0 = (const double *) (&y1[(j+jj)*NDIM]); const double *x0 = (const double *) (&x1[(i+ii)*NDIM]); const double dx = x0[0] - y0[0]; const double dy = x0[1] - y0[1]; const double dz = x0[2] - y0[2]; const double sqr_ds = dx*dx + dy*dy + dz*dz; #ifndef SQRT_DIST dist[jj] = sqr_ds; #else dist[jj] = sqrt(sqr_ds); #endif } numcomputed += block_size2; } } } return numcomputed; } long compiler_vectorized_chunked(const double * restrict x1, const double * restrict y1, const int N, double * restrict d) { long numcomputed = 0; const int block_size = 4; for(int i=0;i<N;i++) { int j; for(j=0;j<=(N-block_size);j+=block_size){ double *dist = &d[i*N + j]; for(int jj=0;jj<block_size;jj++) { const double *y0 = (const double *) (&y1[(j+jj)*NDIM]); const double *x0 = (const double *) (&x1[i*NDIM]); const double dx = x0[0] - y0[0]; const double dy = x0[1] - y0[1]; const double dz = x0[2] - y0[2]; dist[jj] = dx*dx + dy*dy + dz*dz; } numcomputed+=block_size; } double *dist = (double *) &d[i*N + j]; for(int jj=0;j<N;jj++,j++) { const double *y0 = (const double *) (&y1[j*NDIM]); const double *x0 = (const double *) (&x1[i*NDIM]); const double dx = x0[0] - y0[0]; const double dy = x0[1] - y0[1]; const double dz = x0[2] - y0[2]; dist[jj] = dx*dx + dy*dy + dz*dz; numcomputed++; } } #ifdef SQRT_DIST for(long index=0;index<numcomputed;index++){ d[index] = sqrt(d[index]); } #endif return numcomputed; } long blas_computed(const double * restrict x1, const double * restrict y1, const int N, double * restrict d) { long numcomputed = (long) N * (long) N; const double alpha = -2.0; /* struct timeval t0,t1; */ /* gettimeofday(&t0,NULL); */ cblas_dgemm(CblasRowMajor,CblasNoTrans, CblasTrans, N, N, NDIM, alpha, x1, NDIM , y1, NDIM, 0.0, d, N); /* gettimeofday(&t1,NULL); */ /* printf(" \t\t cblas_time = %6.2lf ms\n",1e3*(t1.tv_sec-t0.tv_sec) + 1e-3*(t1.tv_usec - t0.tv_usec)); */ double *x0 = (double *) x1; for(int i=0;i<N;i++){ const double sqr_x0_norm = x0[0]*x0[0] + x0[1]*x0[1] + x0[2]*x0[2]; for(int j=0;j<N;j++) { const double *y0 = (const double *) &y1[j*NDIM]; const double sqr_y0_norm = y0[0]*y0[0] + y0[1]*y0[1] + y0[2]*y0[2]; double *dist = (double *) &d[i*N + j]; *dist += (sqr_x0_norm + sqr_y0_norm); #ifdef SQRT_DIST *dist = sqrt(*dist); #endif } x0 += NDIM; } return numcomputed; } long check_result(double *dist, const double *x, const double *y, const int N) { int bad=0; int numbadprinted=0; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { const double *tmp_x = (const double *) &(x[i*NDIM]); const double *tmp_y = (const double *) &(y[j*NDIM]); double sqr_ds = 0.0; for(int k=0;k<NDIM;k++) { const double dx = tmp_x[k] - tmp_y[k]; sqr_ds += dx*dx; } const long index = i*(long) N + j; const double this_dist = dist[index]; #ifdef SQRT_DIST const double d = sqrt(sqr_ds); #else const double d = sqr_ds; #endif if(fabs(d - this_dist) > 1e-8) { if(numbadprinted < 20) { fprintf(stderr,"i = %d j = %d d = %0.8lf this_dist = %0.8lf \n",i,j,d,this_dist); numbadprinted++; } bad++; } } } return bad; } int main(int argc, char **argv) { int numpart = 0; if(argc > 1 ) { numpart = atoi(argv[1]); } else { numpart = NELEMENTS; } const size_t numbytes = NDIM*numpart; double *x = calloc(sizeof(*x), numbytes); double *y = calloc(sizeof(*y), numbytes); const long totnpairs = (long) numpart * (long) numpart; double *dist = calloc(sizeof(*dist), totnpairs); assert(x != NULL && y != NULL && dist != NULL && "memory allocation failed"); const char allfunction_names[][MAXLEN] = {"naive","chunked","compiler_vectorized_chunked","blas_computed"}; const int ntests = sizeof(allfunction_names)/(sizeof(char)*MAXLEN); long (*allfunctions[]) (const double * restrict, const double * restrict, const int, double * restrict) = {naive, chunked,compiler_vectorized_chunked,blas_computed}; srand(seed); double function_best_mean_time[ntests],function_sigma_time[ntests],function_best_time_in_ms[ntests],function_best_mcycles[ntests]; int function_niterations[ntests]; for(int i=0;i<ntests;i++) { function_best_mean_time[i] = 1e16; function_sigma_time[i] = 0.0; function_best_time_in_ms[i] = 1e16; function_best_mcycles[i] = 1e16; } #ifndef SQRT_DIST const long totflop = (long) numpart * (long) numpart * (8); #else const long totflop = (long) numpart * (long) numpart * (8 + 10); //some hand-wavy thing saying that sqrt is 10 flop #endif if(clustered_data == 0) { fill_array(x, numpart); fill_array(y, numpart); } else { assert(numpart <= max_galaxy_in_source_file && "Clustered data does not contain enough galaxies..please reduce numpart in defs.h"); assert(NDIM == 3 && "Clustered galaxy data contains *exactly* 3 spatial dimensions"); read_ascii(x, numpart, source_galaxy_file); read_ascii(y, numpart, source_galaxy_file); } const int64_t totniterations = repeat*ntests*(int64_t) max_niterations; int64_t numdone = 0; int interrupted=0; fprintf(stderr,"# Running benchmarks with N = %05d particles\n",numpart); init_my_progressbar(totniterations, &interrupted); for(int irep=0;irep<repeat;irep++) { for(int i=0;i<ntests;i++) { struct timeval t0,t1; double sum_x=0.0, sum_sqr_x=0.0; //warm-up gettimeofday(&t0,NULL); long ncomputed = (allfunctions[i]) (x, y, numpart, dist); gettimeofday(&t1,NULL); //check-result long numbad = check_result(dist, x, y, numpart); if(numbad != 0 || ncomputed != totnpairs) { fprintf(stderr,"ERROR: In function `%s' Number of incorrectly calculated distances = %ld out of a total of (%ld) possible pairs. Npairs computed = %ld\n", allfunction_names[i],numbad, totnpairs, ncomputed); goto cleanup; } double best_time_in_ms=1e16, best_time_in_megacycles=1e16; uint64_t start_cycles, end_cycles; const int64_t numdone_before_iter_loop = numdone; for(int iter=0;iter<max_niterations;iter++) { gettimeofday(&t0,NULL); start_cycles = rdtsc(); (allfunctions[i]) (x, y, numpart, dist); end_cycles = rdtsc(); gettimeofday(&t1,NULL); numdone++; my_progressbar(numdone,&interrupted); const double this_time_in_ms = 1e3*(t1.tv_sec-t0.tv_sec) + 1e-3*(t1.tv_usec - t0.tv_usec); if(this_time_in_ms < best_time_in_ms) best_time_in_ms = this_time_in_ms; const double this_time_in_megacycles = (end_cycles - start_cycles)/(1024.*1024.); if(this_time_in_megacycles < best_time_in_megacycles) best_time_in_megacycles = this_time_in_megacycles; sum_sqr_x += this_time_in_ms*this_time_in_ms; sum_x += this_time_in_ms; if(max_niterations <= 10) { printf(" %-35s %0.2lf \n",allfunction_names[i], this_time_in_ms); } if(best_time_in_ms < function_best_time_in_ms[i]) { function_best_time_in_ms[i] = best_time_in_ms; } if(best_time_in_megacycles < function_best_mcycles[i]) { function_best_mcycles[i] = best_time_in_megacycles; } const double mean_time = sum_x/(iter+1.0); const double sigma_time = sqrt(sum_sqr_x/(iter+1.0) - mean_time*mean_time); if(mean_time < function_best_mean_time[i]) { function_best_mean_time[i] = mean_time; } function_niterations[i] = iter + 1; function_sigma_time[i] = sigma_time; //If the std.dev is small compared to typical runtime and //the code has run for more than XXX milli-seconds, then break if(sigma_time/mean_time < convergence_ratio && sum_x >= 300 && iter >= 5) { numdone = numdone_before_iter_loop + max_niterations; break; } } }//i loop over ntests }//irep loop over nrepeats finish_myprogressbar(&interrupted); printf("#######################################################\n"); printf("## Function Time (ms) \n"); printf("#######################################################\n"); for(int i=0;i<ntests;i++) { const double mean_time = function_best_mean_time[i]; const double sigma_time = function_sigma_time[i]; const double gflops = (double) totflop/(1e-3*mean_time)/1e9; const double best_time_in_ms = function_best_time_in_ms[i]; const double best_time_in_megacycles = function_best_mcycles[i]; const int actual_niterations = function_niterations[i]; printf(ANSI_COLOR_RED "# %-35s %6.2lf +- %5.2lf " ANSI_COLOR_GREEN " (best -- %6.2lf ms, %6.2lf Mcycles) " ANSI_COLOR_RESET "," ANSI_COLOR_BLUE " %5.2lf GFlops [%04d iterations]" ANSI_COLOR_RESET "\n", allfunction_names[i], mean_time, sigma_time, best_time_in_ms, best_time_in_megacycles, gflops, actual_niterations); } cleanup: { free((void *) x);free((void *) y);free((void *) dist); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.6381145954, "avg_line_length": 31.6932515337, "ext": "c", "hexsha": "056afdaaac36902db9a4548f32820e793a28c446", "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": "3adb81b004ef08f43b9b3840ad2d4275b3b20448", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "manodeep/pairwise", "max_forks_repo_path": "all_pairwise/pairwise.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3adb81b004ef08f43b9b3840ad2d4275b3b20448", "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": "manodeep/pairwise", "max_issues_repo_path": "all_pairwise/pairwise.c", "max_line_length": 210, "max_stars_count": null, "max_stars_repo_head_hexsha": "3adb81b004ef08f43b9b3840ad2d4275b3b20448", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "manodeep/pairwise", "max_stars_repo_path": "all_pairwise/pairwise.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3308, "size": 10332 }
// Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> // LICENCE available at https://www.gnu.org/software/gsl/doc/html/gpl.html #ifndef TRIDIAG_H_ #define TRIDIAG_H_ #include <gsl/gsl_errno.h> #include <cstdlib> #include <iostream> #include <vector> namespace GSL { int solve_tridiag_nonsym(const std::vector<double>& diag, const std::vector<double>& abovediag, const std::vector<double>& belowdiag, const std::vector<double>& rhs, std::vector<double>& x, size_t N); int gsl_linalg_solve_tridiag(const std::vector<double>& diag, const std::vector<double>& abovediag, const std::vector<double>& belowdiag, const std::vector<double>& rhs, std::vector<double>& solution); } // namespace GSL #endif // TRIDIAG_H_
{ "alphanum_fraction": 0.6465005931, "avg_line_length": 35.125, "ext": "h", "hexsha": "678bff63533de87e9ae866ae4a1d4accd97aaab1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-03T01:14:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-03T01:14:08.000Z", "max_forks_repo_head_hexsha": "a134947f22b67506f4f6583f3358d5d18be39b2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carmeloevoli/SelfTevHalos", "max_forks_repo_path": "include/tridiag.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a134947f22b67506f4f6583f3358d5d18be39b2f", "max_issues_repo_issues_event_max_datetime": "2021-07-07T10:03:41.000Z", "max_issues_repo_issues_event_min_datetime": "2021-07-05T14:04:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carmeloevoli/SelfTevHalos", "max_issues_repo_path": "include/tridiag.h", "max_line_length": 118, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a134947f22b67506f4f6583f3358d5d18be39b2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "carmeloevoli/SelfTevHalos", "max_stars_repo_path": "include/tridiag.h", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:54:08.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-03T01:13:52.000Z", "num_tokens": 199, "size": 843 }
/* * 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 scale decoder * @file ScaleDecoderStream.cpp */ #pragma once #include "../../libutilities/Common.h" #include "../../libutilities/DataConvertUtility.h" #include "../../libutilities/FixedBytes.h" #include "Common.h" #include "FixedWidthIntegerCodec.h" #include <boost/multiprecision/cpp_int.hpp> #include <boost/optional.hpp> #include <boost/variant.hpp> #include <array> #include <gsl/span> namespace bcos { namespace codec { namespace scale { class ScaleDecoderStream { public: // special tag to differentiate decoding streams from others static constexpr auto is_decoder_stream = true; explicit ScaleDecoderStream(gsl::span<byte const> span); /** * @brief scale-decodes pair of values * @tparam F first value type * @tparam S second value type * @param p pair of values to decode * @return reference to stream */ template <class F, class S> ScaleDecoderStream& operator>>(std::pair<F, S>& p) { static_assert(!std::is_reference_v<F> && !std::is_reference_v<S>); return *this >> const_cast<std::remove_const_t<F>&>(p.first) // NOLINT >> const_cast<std::remove_const_t<S>&>(p.second); // NOLINT } /** * @brief scale-decoding of tuple * @tparam T enumeration of tuples types * @param v reference to tuple * @return reference to stream */ template <class... T> ScaleDecoderStream& operator>>(std::tuple<T...>& v) { if constexpr (sizeof...(T) > 0) { decodeElementOfTuple<0>(v); } return *this; } /** * @brief scale-decoding of variant * @tparam T enumeration of various types * @param v reference to variant * @return reference to stream */ template <class... Ts> ScaleDecoderStream& operator>>(boost::variant<Ts...>& v) { // first byte means type index uint8_t type_index = 0u; *this >> type_index; // decode type index // ensure that index is in [0, types_count) if (type_index >= sizeof...(Ts)) { BOOST_THROW_EXCEPTION( ScaleDecodeException() << errinfo_comment("exception for WRONG_TYPE_INDEX")); } tryDecodeAsOneOfVariant<0>(v, type_index); return *this; } /** * @brief scale-decodes shared_ptr value * @tparam T value type * @param v value to decode * @return reference to stream */ template <class T> ScaleDecoderStream& operator>>(std::shared_ptr<T>& v) { using mutableT = std::remove_const_t<T>; static_assert(std::is_default_constructible_v<mutableT>); v = std::make_shared<mutableT>(); return *this >> const_cast<mutableT&>(*v); // NOLINT } /** * @brief scale-decodes unique_ptr value * @tparam T value type * @param v value to decode * @return reference to stream */ template <class T> ScaleDecoderStream& operator>>(std::unique_ptr<T>& v) { using mutableT = std::remove_const_t<T>; static_assert(std::is_default_constructible_v<mutableT>); v = std::make_unique<mutableT>(); return *this >> const_cast<mutableT&>(*v); // NOLINT } /** * @brief scale-encodes any integral type including bool * @tparam T integral type * @param v value of integral type * @return reference to stream */ template <typename T, typename I = std::decay_t<T>, typename = std::enable_if_t<std::is_integral<I>::value>> ScaleDecoderStream& operator>>(T& v) { // check bool if constexpr (std::is_same<I, bool>::value) { v = decodeBool(); return *this; } // check byte if constexpr (sizeof(T) == 1u) { v = nextByte(); return *this; } // decode any other integer v = decodeInteger<I>(*this); return *this; } /** * @brief scale-decodes any optional value * @tparam T type of optional value * @param v optional value reference * @return reference to stream */ template <class T> ScaleDecoderStream& operator>>(boost::optional<T>& v) { using mutableT = std::remove_const_t<T>; static_assert(std::is_default_constructible_v<mutableT>); // optional bool is special case of optional values // it is encoded as one byte instead of two // as described in specification if constexpr (std::is_same<mutableT, bool>::value) { v = decodeOptionalBool(); return *this; } // detect if optional has value bool has_value = false; *this >> has_value; if (!has_value) { v.reset(); return *this; } // decode value v.emplace(); return *this >> const_cast<mutableT&>(*v); // NOLINT } ScaleDecoderStream& operator>>(u256& v); /** * @brief scale-decodes compact integer value * @param v compact integer reference * @return */ ScaleDecoderStream& operator>>(CompactInteger& v); ScaleDecoderStream& operator>>(s256& v) { u256 unsignedValue; *this >> unsignedValue; v = u2s(unsignedValue); return *this; } template <unsigned N> ScaleDecoderStream& operator>>(FixedBytes<N>& fixedData) { bytes decodedData; *this >> decodedData; if (decodedData.size() < FixedBytes<N>::size) { BOOST_THROW_EXCEPTION(ScaleDecodeException() << errinfo_comment( "exception for invalid FixedBytes, expected size:" + std::to_string(FixedBytes<N>::size) + ", decoded data size:" + std::to_string(decodedData.size()))); } fixedData = FixedBytes<N>(decodedData.data(), FixedBytes<N>::ConstructorType::FromPointer); return *this; } /** * @brief decodes vector of items * @tparam T item type * @param v reference to vector * @return reference to stream */ template <class T> ScaleDecoderStream& operator>>(std::vector<T>& v) { using mutableT = std::remove_const_t<T>; using size_type = typename std::list<T>::size_type; static_assert(std::is_default_constructible_v<mutableT>); CompactInteger size{0u}; *this >> size; auto item_count = size.convert_to<size_type>(); std::vector<mutableT> vec; try { vec.resize(item_count); } catch (const std::bad_alloc&) { BOOST_THROW_EXCEPTION( ScaleDecodeException() << errinfo_comment("exception for TOO_MANY_ITEMS: " + std::to_string(item_count))); } if constexpr (sizeof(T) == 1u) { vec.assign(m_currentIterator, m_currentIterator + item_count); m_currentIterator += item_count; m_currentIndex += item_count; } else { for (size_type i = 0u; i < item_count; ++i) { *this >> vec[i]; } } v = std::move(vec); return *this; } /** * @brief decodes map of pairs * @tparam T item type * @tparam F item type * @param m reference to map * @return reference to stream */ template <class T, class F> ScaleDecoderStream& operator>>(std::map<T, F>& m) { using mutableT = std::remove_const_t<T>; static_assert(std::is_default_constructible_v<mutableT>); using mutableF = std::remove_const_t<F>; static_assert(std::is_default_constructible_v<mutableF>); using size_type = typename std::map<T, F>::size_type; CompactInteger size{0u}; *this >> size; auto item_count = size.convert_to<size_type>(); std::map<mutableT, mutableF> map; for (size_type i = 0u; i < item_count; ++i) { std::pair<mutableT, mutableF> p; *this >> p; map.emplace(std::move(p)); } m = std::move(map); return *this; } /** * @brief decodes collection of items * @tparam T item type * @param v reference to collection * @return reference to stream */ template <class T> ScaleDecoderStream& operator>>(std::list<T>& v) { using mutableT = std::remove_const_t<T>; using size_type = typename std::list<T>::size_type; static_assert(std::is_default_constructible_v<mutableT>); CompactInteger size{0u}; *this >> size; auto item_count = size.convert_to<size_type>(); std::list<T> lst; try { lst.reserve(item_count); } catch (const std::bad_alloc&) { BOOST_THROW_EXCEPTION(ScaleDecodeException() << errinfo_comment( "exception for TOO_MANY_ITEMS" + std::to_string(item_count))); } for (size_type i = 0u; i < item_count; ++i) { lst.emplace_back(); *this >> lst.back(); } v = std::move(lst); return *this; } /** * @brief decodes array of items * @tparam T item type * @tparam size of the array * @param a reference to the array * @return reference to stream */ template <class T, size_t size> ScaleDecoderStream& operator>>(std::array<T, size>& a) { using mutableT = std::remove_const_t<T>; for (size_t i = 0u; i < size; ++i) { *this >> const_cast<mutableT&>(a[i]); // NOLINT } return *this; } /** * @brief decodes string from stream * @param v value to decode * @return reference to stream */ ScaleDecoderStream& operator>>(std::string& v); /** * @brief hasMore Checks whether n more bytes are available * @param n Number of bytes to check * @return True if n more bytes are available and false otherwise */ bool hasMore(uint64_t n) const; /** * @brief takes one byte from stream and * advances current byte iterator by one * @return current byte */ uint8_t nextByte() { if (!hasMore(1)) { BOOST_THROW_EXCEPTION(ScaleDecodeException() << errinfo_comment("nextByte exception for NOT_ENOUGH_DATA")); } ++m_currentIndex; return *m_currentIterator++; } using SizeType = gsl::span<const byte>::size_type; gsl::span<byte const> span() const { return m_span; } SizeType currentIndex() const { return m_currentIndex; } private: bool decodeBool(); /** * @brief special case of optional values as described in specification * @return boost::optional<bool> value */ boost::optional<bool> decodeOptionalBool(); template <size_t I, class... Ts> void decodeElementOfTuple(std::tuple<Ts...>& v) { using T = std::remove_const_t<std::tuple_element_t<I, std::tuple<Ts...>>>; *this >> const_cast<T&>(std::get<I>(v)); // NOLINT if constexpr (sizeof...(Ts) > I + 1) { decodeElementOfTuple<I + 1>(v); } } template <size_t I, class... Ts> void tryDecodeAsOneOfVariant(boost::variant<Ts...>& v, size_t i) { using T = std::remove_const_t<std::tuple_element_t<I, std::tuple<Ts...>>>; static_assert(std::is_default_constructible_v<T>); if (I == i) { T val; *this >> val; v = std::forward<T>(val); return; } if constexpr (sizeof...(Ts) > I + 1) { tryDecodeAsOneOfVariant<I + 1>(v, i); } } private: gsl::span<byte const> m_span; gsl::span<byte const>::const_iterator m_currentIterator; SizeType m_currentIndex; }; } // namespace scale } // namespace codec } // namespace bcos
{ "alphanum_fraction": 0.5750234448, "avg_line_length": 29.2814645309, "ext": "h", "hexsha": "9cc31c52b27a1096d9b588c9e3596ab4b5840f3d", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.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-framework/libcodec/scale/ScaleDecoderStream.h", "max_issues_count": 267, "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_path": "bcos-framework/libcodec/scale/ScaleDecoderStream.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-framework/libcodec/scale/ScaleDecoderStream.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3085, "size": 12796 }
/* tt.h: / This file contains everything related to the tensor_train struct */ #ifndef TENSOR_TRAIN_H #define TENSOR_TRAIN_H #include <lapacke.h> #include <mpi.h> #include "tensor.h" typedef struct tensor_train { int d; // dimension of tensor int* n; // tensor size of each dimension int* r; // tensor-train ranks double** trains; // array of pointers storing the address of the trains } tensor_train; tensor_train* TT_init(const int d, const int* restrict n); tensor_train* TT_init_rank(const int d, const int* restrict n, const int* restrict r); tensor_train* TT_copy(tensor_train* X); void TT_free(tensor_train* sim); void TT_print(tensor_train* tt); // Broadcast a tensor train to all nodes void tt_broadcast(MPI_Comm comm, tensor_train* tt); // Find how much the tensor_train has compressed the tensor double get_compression(const tensor_train* tt); #endif
{ "alphanum_fraction": 0.7230098146, "avg_line_length": 27.7878787879, "ext": "h", "hexsha": "00831f3de6f9493502a87223286e71436795ec29", "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": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_path": "include/tt.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "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": "SidShi/Parallel_TT_sketching", "max_issues_repo_path": "include/tt.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_path": "include/tt.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 215, "size": 917 }
#ifndef __GSL_MATRIX_H__ #define __GSL_MATRIX_H__ #include <gsl/matrix/gsl_matrix_double.h> #endif /* __GSL_MATRIX_H__ */
{ "alphanum_fraction": 0.7857142857, "avg_line_length": 14, "ext": "h", "hexsha": "c138aef7f486c014f6d7997aa12930225f33cfc1", "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": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "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": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_line_length": 41, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/gsl_matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 36, "size": 126 }
/*! Implementation of the class `Solver`. * \file solver.h */ #if !defined(SOLVER_H) #define SOLVER_H #include <petsc.h> /** * \class Solver * \brief Super class for an iterative solver. */ class Solver { public: virtual ~Solver(){ } virtual PetscErrorCode create(const Mat &A) = 0; virtual PetscErrorCode solve(Vec &x, Vec &b) = 0; virtual PetscErrorCode getIters(PetscInt &iters) = 0; }; // Solver #endif
{ "alphanum_fraction": 0.6737089202, "avg_line_length": 16.3846153846, "ext": "h", "hexsha": "b4923e3087b94ff8be745453b4deda864dc9ab1f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-25T13:27:55.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-10T08:53:34.000Z", "max_forks_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hietwll/PetIBM", "max_forks_repo_path": "src/utilities/solvers/solver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "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": "hietwll/PetIBM", "max_issues_repo_path": "src/utilities/solvers/solver.h", "max_line_length": 55, "max_stars_count": 1, "max_stars_repo_head_hexsha": "53cb87f2bf28a182119b4db7e86c4d62246e2952", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hietwll/PetIBM", "max_stars_repo_path": "src/utilities/solvers/solver.h", "max_stars_repo_stars_event_max_datetime": "2020-07-12T13:37:47.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-12T13:37:47.000Z", "num_tokens": 119, "size": 426 }
/* multifit/fdfridge.c * * Copyright (C) 2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_blas.h> static int fdfridge_f(const gsl_vector * x, void * params, gsl_vector * f); static int fdfridge_df(const gsl_vector * x, void * params, gsl_matrix * J); gsl_multifit_fdfridge * gsl_multifit_fdfridge_alloc (const gsl_multifit_fdfsolver_type * T, const size_t n, const size_t p) { gsl_multifit_fdfridge * work; work = calloc(1, sizeof(gsl_multifit_fdfridge)); if (work == NULL) { GSL_ERROR_VAL("failed to allocate workspace", GSL_ENOMEM, 0); } work->s = gsl_multifit_fdfsolver_alloc (T, n + p, p); if (work->s == NULL) { gsl_multifit_fdfridge_free(work); GSL_ERROR_VAL("failed to allocate space for fdfsolver", GSL_ENOMEM, 0); } work->wts = gsl_vector_alloc(n + p); if (work->wts == NULL) { gsl_multifit_fdfridge_free(work); GSL_ERROR_VAL("failed to allocate space for weight vector", GSL_ENOMEM, 0); } work->f = gsl_vector_alloc(n); if (work->f == NULL) { gsl_multifit_fdfridge_free(work); GSL_ERROR_VAL("failed to allocate space for f vector", GSL_ENOMEM, 0); } work->n = n; work->p = p; work->lambda = 0.0; /* initialize weights to 1 (for augmented portion of vector) */ gsl_vector_set_all(work->wts, 1.0); return work; } /* gsl_multifit_fdfridge_alloc() */ void gsl_multifit_fdfridge_free(gsl_multifit_fdfridge *work) { if (work->s) gsl_multifit_fdfsolver_free(work->s); if (work->wts) gsl_vector_free(work->wts); if (work->f) gsl_vector_free(work->f); free(work); } const char * gsl_multifit_fdfridge_name(const gsl_multifit_fdfridge * w) { return gsl_multifit_fdfsolver_name(w->s); } gsl_vector * gsl_multifit_fdfridge_position (const gsl_multifit_fdfridge * w) { return gsl_multifit_fdfsolver_position(w->s); } gsl_vector * gsl_multifit_fdfridge_residual (const gsl_multifit_fdfridge * w) { return gsl_multifit_fdfsolver_residual(w->s); } size_t gsl_multifit_fdfridge_niter (const gsl_multifit_fdfridge * w) { return w->s->niter; } int gsl_multifit_fdfridge_set (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const double lambda) { return gsl_multifit_fdfridge_wset(w, f, x, lambda, NULL); } /* gsl_multifit_fdfridge_set() */ int gsl_multifit_fdfridge_wset (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const double lambda, const gsl_vector * wts) { const size_t n = w->n; const size_t p = w->p; if (n != f->n || p != f->p) { GSL_ERROR ("function size does not match solver", GSL_EBADLEN); } else if (p != x->size) { GSL_ERROR ("vector length does not match solver", GSL_EBADLEN); } else if (wts != NULL && n != wts->size) { GSL_ERROR ("weight vector length does not match solver", GSL_EBADLEN); } else { int status; gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n); /* save user defined fdf */ w->fdf = f; /* build modified fdf for Tikhonov terms */ w->fdftik.f = &fdfridge_f; w->fdftik.df = &fdfridge_df; w->fdftik.n = n + p; /* add p for Tikhonov terms */ w->fdftik.p = p; w->fdftik.params = (void *) w; /* store damping parameter */ w->lambda = lambda; w->L = NULL; if (wts) { /* copy weight vector into user portion of w->wts */ gsl_vector_memcpy(&wv.vector, wts); status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts); } else { status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL); } /* update function/Jacobian evaluations */ f->nevalf = w->fdftik.nevalf; f->nevaldf = w->fdftik.nevaldf; return status; } } /* gsl_multifit_fdfridge_wset() */ int gsl_multifit_fdfridge_set2 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_vector * lambda) { return gsl_multifit_fdfridge_wset2(w, f, x, lambda, NULL); } /* gsl_multifit_fdfridge_set2() */ int gsl_multifit_fdfridge_wset2 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_vector * lambda, const gsl_vector * wts) { const size_t n = w->n; const size_t p = w->p; if (n != f->n || p != f->p) { GSL_ERROR ("function size does not match solver", GSL_EBADLEN); } else if (p != x->size) { GSL_ERROR ("vector length does not match solver", GSL_EBADLEN); } else if (lambda->size != p) { GSL_ERROR ("lambda vector size does not match solver", GSL_EBADLEN); } else if (wts != NULL && n != wts->size) { GSL_ERROR ("weight vector length does not match solver", GSL_EBADLEN); } else { int status; gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n); /* save user defined fdf */ w->fdf = f; w->fdf->nevalf = 0; w->fdf->nevaldf = 0; /* build modified fdf for Tikhonov terms */ w->fdftik.f = &fdfridge_f; w->fdftik.df = &fdfridge_df; w->fdftik.n = n + p; /* add p for Tikhonov terms */ w->fdftik.p = p; w->fdftik.params = (void *) w; /* store damping matrix */ w->lambda = 0.0; w->L_diag = lambda; w->L = NULL; if (wts) { /* copy weight vector into user portion */ gsl_vector_memcpy(&wv.vector, wts); status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts); } else { status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL); } /* update function/Jacobian evaluations */ f->nevalf = w->fdftik.nevalf; f->nevaldf = w->fdftik.nevaldf; return status; } } /* gsl_multifit_fdfridge_wset2() */ int gsl_multifit_fdfridge_set3 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_matrix * L) { return gsl_multifit_fdfridge_wset3(w, f, x, L, NULL); } /* gsl_multifit_fdfridge_set3() */ int gsl_multifit_fdfridge_wset3 (gsl_multifit_fdfridge * w, gsl_multifit_function_fdf * f, const gsl_vector * x, const gsl_matrix * L, const gsl_vector * wts) { const size_t n = w->n; const size_t p = w->p; if (n != f->n || p != f->p) { GSL_ERROR ("function size does not match solver", GSL_EBADLEN); } else if (p != x->size) { GSL_ERROR ("vector length does not match solver", GSL_EBADLEN); } else if (L->size2 != p) { GSL_ERROR ("L matrix size2 does not match solver", GSL_EBADLEN); } else if (wts != NULL && n != wts->size) { GSL_ERROR ("weight vector length does not match solver", GSL_EBADLEN); } else { int status; gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n); /* save user defined fdf */ w->fdf = f; w->fdf->nevalf = 0; w->fdf->nevaldf = 0; /* build modified fdf for Tikhonov terms */ w->fdftik.f = &fdfridge_f; w->fdftik.df = &fdfridge_df; w->fdftik.n = n + p; /* add p for Tikhonov terms */ w->fdftik.p = p; w->fdftik.params = (void *) w; /* store damping matrix */ w->lambda = 0.0; w->L_diag = NULL; w->L = L; if (wts) { /* copy weight vector into user portion */ gsl_vector_memcpy(&wv.vector, wts); status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts); } else { status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL); } /* update function/Jacobian evaluations */ f->nevalf = w->fdftik.nevalf; f->nevaldf = w->fdftik.nevaldf; return status; } } /* gsl_multifit_fdfridge_wset3() */ int gsl_multifit_fdfridge_iterate (gsl_multifit_fdfridge * w) { int status = gsl_multifit_fdfsolver_iterate(w->s); /* update function/Jacobian evaluations */ w->fdf->nevalf = w->fdftik.nevalf; w->fdf->nevaldf = w->fdftik.nevaldf; return status; } int gsl_multifit_fdfridge_driver (gsl_multifit_fdfridge * w, const size_t maxiter, const double xtol, const double gtol, const double ftol, int *info) { int status = gsl_multifit_fdfsolver_driver(w->s, maxiter, xtol, gtol, ftol, info); return status; } /* gsl_multifit_fdfridge_driver() */ /* fdfridge_f() Callback function to provide residuals, including extra p Tikhonov terms. The residual vector will have the form: f~ = [ f ] [ \lambda x ] where f is the user supplied residuals, x are the model parameters, and \lambda is the Tikhonov damping parameter Inputs: x - model parameters (size p) params - pointer to fdfridge workspace f - (output) (n+p) vector to store f~ */ static int fdfridge_f(const gsl_vector * x, void * params, gsl_vector * f) { int status; gsl_multifit_fdfridge *w = (gsl_multifit_fdfridge *) params; const size_t n = w->n; const size_t p = w->p; gsl_vector_view f_user = gsl_vector_subvector(f, 0, n); gsl_vector_view f_tik = gsl_vector_subvector(f, n, p); /* call user callback function to get residual vector f */ status = gsl_multifit_eval_wf(w->fdf, x, NULL, &f_user.vector); if (status) return status; if (w->L_diag) { /* store diag(L_diag) x in Tikhonov portion of f~ */ gsl_vector_memcpy(&f_tik.vector, x); gsl_vector_mul(&f_tik.vector, w->L_diag); } else if (w->L) { /* store Lx in Tikhonov portion of f~ */ gsl_blas_dgemv(CblasNoTrans, 1.0, w->L, x, 0.0, &f_tik.vector); } else { /* store \lambda x in Tikhonov portion of f~ */ gsl_vector_memcpy(&f_tik.vector, x); gsl_vector_scale(&f_tik.vector, w->lambda); } return GSL_SUCCESS; } /* fdfridge_f() */ static int fdfridge_df(const gsl_vector * x, void * params, gsl_matrix * J) { int status; gsl_multifit_fdfridge *w = (gsl_multifit_fdfridge *) params; const size_t n = w->n; const size_t p = w->p; gsl_matrix_view J_user = gsl_matrix_submatrix(J, 0, 0, n, p); gsl_matrix_view J_tik = gsl_matrix_submatrix(J, n, 0, p, p); gsl_vector_view diag = gsl_matrix_diagonal(&J_tik.matrix); /* compute Jacobian */ if (w->fdf->df) status = gsl_multifit_eval_wdf(w->fdf, x, NULL, &J_user.matrix); else { /* compute f(x) and then finite difference Jacobian */ status = gsl_multifit_eval_wf(w->fdf, x, NULL, w->f); status += gsl_multifit_fdfsolver_dif_df(x, NULL, w->fdf, w->f, &J_user.matrix); } if (status) return status; if (w->L_diag) { /* store diag(L_diag) in Tikhonov portion of J */ gsl_matrix_set_zero(&J_tik.matrix); gsl_vector_memcpy(&diag.vector, w->L_diag); } else if (w->L) { /* store L in Tikhonov portion of J */ gsl_matrix_memcpy(&J_tik.matrix, w->L); } else { /* store \lambda I_p in Tikhonov portion of J */ gsl_matrix_set_zero(&J_tik.matrix); gsl_vector_set_all(&diag.vector, w->lambda); } return GSL_SUCCESS; } /* fdfridge_df() */
{ "alphanum_fraction": 0.5937766081, "avg_line_length": 28.0238611714, "ext": "c", "hexsha": "eeb710c399da2fd51aa789813ba8dbd804b0d209", "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/fdfridge.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/fdfridge.c", "max_line_length": 81, "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/fdfridge.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": 3770, "size": 12919 }
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_ #define LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_ #include <glog/logging.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <jansson.h> #include <stdint.h> #include <array> #include <string> #include <vector> #include "common/c_math/vec3.h" #include "lib/json_load/json_load_or_die.h" // TODO: Put this under the lib namespace. namespace json_load { // Utility class for loading JSON arrays into various vector and array // structures such as Vec3, gsl_vector, and gsl_matrix. class JsonArrayLoader { public: JsonArrayLoader(int32_t num_rows, int32_t num_cols, json_t *root) : root_(CHECK_NOTNULL(root)), num_rows_(num_rows), num_cols_(num_cols), matrix_buffer_(num_rows), buffer_(0) { CHECK_LT(0, num_rows); CHECK_LT(0, num_cols); } virtual ~JsonArrayLoader() {} template <int32_t rank> void LoadVector(const std::string &field_name, const std::array<int32_t, rank> &dims, gsl_vector *dest) { CHECK_NOTNULL(dest); int32_t size = 1; for (int32_t i = 0; i < rank; ++i) size *= dims[i]; CHECK_EQ(size, dest->size); LoadBuffer(field_name, size, &buffer_); CopyVector(buffer_, dest); } void LoadVector(const std::string &field_name, gsl_vector *dest) { LoadVector<1>(field_name, {{static_cast<int32_t>(dest->size)}}, dest); } void LoadVec3(const std::string &field_name, Vec3 *dest) { LoadBuffer(field_name, 3, &buffer_); dest->x = buffer_[0]; dest->y = buffer_[1]; dest->z = buffer_[2]; } void LoadMatrix(const std::string &field_name, gsl_matrix *dest) { CHECK_NOTNULL(dest); json_t *field = json_load::LoadFieldOrDie(root_, field_name); CHECK(json_is_array(field)); LoadMatrixFromField(field, dest); } protected: void LoadMatrixFromField(json_t *field, gsl_matrix *dest) { for (int32_t i = 0; i < num_rows_; ++i) { json_t *slice = json_array_get(field, i); CHECK(json_is_array(slice)); CHECK_EQ(num_cols_, json_array_size(slice)); json_load::LoadArray1D_DoubleOrDie(slice, num_cols_, &matrix_buffer_[i]); for (int32_t j = 0; j < num_cols_; ++j) { gsl_matrix_set(dest, i, j, matrix_buffer_[i][j]); } } } json_t *root_; private: void LoadBuffer(const std::string &field_name, int32_t size, std::vector<double> *buffer) { CHECK_NOTNULL(buffer); json_t *array = json_load::LoadFieldOrDie(root_, field_name); CHECK(json_is_array(array)); CHECK_EQ(size, json_array_size(array)); json_load::LoadArray1D_DoubleOrDie(array, size, buffer); } void CopyVector(const std::vector<double> &buffer, gsl_vector *dest) { CHECK_NOTNULL(dest); CHECK_EQ(buffer.size(), dest->size); for (uint32_t i = 0U; i < buffer.size(); ++i) { gsl_vector_set(dest, i, buffer[i]); } } const int32_t num_rows_; const int32_t num_cols_; std::vector<std::vector<double>> matrix_buffer_; std::vector<double> buffer_; DISALLOW_COPY_AND_ASSIGN(JsonArrayLoader); }; } // namespace json_load #endif // LIB_JSON_LOAD_JSON_ARRAY_LOADER_H_
{ "alphanum_fraction": 0.6893255443, "avg_line_length": 28.9692307692, "ext": "h", "hexsha": "75f0c5d5cbb6dd4106482c84956bebec6eaf2a99", "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/json_load/json_array_loader.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "lib/json_load/json_array_loader.h", "max_line_length": 79, "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/json_load/json_array_loader.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 991, "size": 3766 }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #ifndef EIGEN_GSL_HELPER #define EIGEN_GSL_HELPER #include <Eigen/Core> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_poly.h> namespace Eigen { template<typename Scalar, bool IsComplex = NumTraits<Scalar>::IsComplex> struct GslTraits { typedef gsl_matrix* Matrix; typedef gsl_vector* Vector; static Matrix createMatrix(int rows, int cols) { return gsl_matrix_alloc(rows,cols); } static Vector createVector(int size) { return gsl_vector_alloc(size); } static void free(Matrix& m) { gsl_matrix_free(m); m=0; } static void free(Vector& m) { gsl_vector_free(m); m=0; } static void prod(const Matrix& m, const Vector& v, Vector& x) { gsl_blas_dgemv(CblasNoTrans,1,m,v,0,x); } static void cholesky(Matrix& m) { gsl_linalg_cholesky_decomp(m); } static void cholesky_solve(const Matrix& m, const Vector& b, Vector& x) { gsl_linalg_cholesky_solve(m,b,x); } static void eigen_symm(const Matrix& m, Vector& eval, Matrix& evec) { gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc(m->size1); Matrix a = createMatrix(m->size1, m->size2); gsl_matrix_memcpy(a, m); gsl_eigen_symmv(a,eval,evec,w); gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_eigen_symmv_free(w); free(a); } static void eigen_symm_gen(const Matrix& m, const Matrix& _b, Vector& eval, Matrix& evec) { gsl_eigen_gensymmv_workspace * w = gsl_eigen_gensymmv_alloc(m->size1); Matrix a = createMatrix(m->size1, m->size2); Matrix b = createMatrix(_b->size1, _b->size2); gsl_matrix_memcpy(a, m); gsl_matrix_memcpy(b, _b); gsl_eigen_gensymmv(a,b,eval,evec,w); gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_eigen_gensymmv_free(w); free(a); } template<class EIGEN_VECTOR, class EIGEN_ROOTS> static void eigen_poly_solve(const EIGEN_VECTOR& poly, EIGEN_ROOTS& roots ) { const int deg = poly.size()-1; double *z = new double[2*deg]; double *a = new double[poly.size()]; for( int i=0; i<poly.size(); ++i ){ a[i] = poly[i]; } gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc (poly.size()); gsl_poly_complex_solve(a, poly.size(), w, z); gsl_poly_complex_workspace_free (w); for( int i=0; i<deg; ++i ) { roots[i].real() = z[2*i]; roots[i].imag() = z[2*i+1]; } delete[] a; delete[] z; } }; template<typename Scalar> struct GslTraits<Scalar,true> { typedef gsl_matrix_complex* Matrix; typedef gsl_vector_complex* Vector; static Matrix createMatrix(int rows, int cols) { return gsl_matrix_complex_alloc(rows,cols); } static Vector createVector(int size) { return gsl_vector_complex_alloc(size); } static void free(Matrix& m) { gsl_matrix_complex_free(m); m=0; } static void free(Vector& m) { gsl_vector_complex_free(m); m=0; } static void cholesky(Matrix& m) { gsl_linalg_complex_cholesky_decomp(m); } static void cholesky_solve(const Matrix& m, const Vector& b, Vector& x) { gsl_linalg_complex_cholesky_solve(m,b,x); } static void prod(const Matrix& m, const Vector& v, Vector& x) { gsl_blas_zgemv(CblasNoTrans,gsl_complex_rect(1,0),m,v,gsl_complex_rect(0,0),x); } static void eigen_symm(const Matrix& m, gsl_vector* &eval, Matrix& evec) { gsl_eigen_hermv_workspace * w = gsl_eigen_hermv_alloc(m->size1); Matrix a = createMatrix(m->size1, m->size2); gsl_matrix_complex_memcpy(a, m); gsl_eigen_hermv(a,eval,evec,w); gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_eigen_hermv_free(w); free(a); } static void eigen_symm_gen(const Matrix& m, const Matrix& _b, gsl_vector* &eval, Matrix& evec) { gsl_eigen_genhermv_workspace * w = gsl_eigen_genhermv_alloc(m->size1); Matrix a = createMatrix(m->size1, m->size2); Matrix b = createMatrix(_b->size1, _b->size2); gsl_matrix_complex_memcpy(a, m); gsl_matrix_complex_memcpy(b, _b); gsl_eigen_genhermv(a,b,eval,evec,w); gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_eigen_genhermv_free(w); free(a); } }; template<typename MatrixType> void convert(const MatrixType& m, gsl_matrix* &res) { // if (res) // gsl_matrix_free(res); res = gsl_matrix_alloc(m.rows(), m.cols()); for (int i=0 ; i<m.rows() ; ++i) for (int j=0 ; j<m.cols(); ++j) gsl_matrix_set(res, i, j, m(i,j)); } template<typename MatrixType> void convert(const gsl_matrix* m, MatrixType& res) { res.resize(int(m->size1), int(m->size2)); for (int i=0 ; i<res.rows() ; ++i) for (int j=0 ; j<res.cols(); ++j) res(i,j) = gsl_matrix_get(m,i,j); } template<typename VectorType> void convert(const VectorType& m, gsl_vector* &res) { if (res) gsl_vector_free(res); res = gsl_vector_alloc(m.size()); for (int i=0 ; i<m.size() ; ++i) gsl_vector_set(res, i, m[i]); } template<typename VectorType> void convert(const gsl_vector* m, VectorType& res) { res.resize (m->size); for (int i=0 ; i<res.rows() ; ++i) res[i] = gsl_vector_get(m, i); } template<typename MatrixType> void convert(const MatrixType& m, gsl_matrix_complex* &res) { res = gsl_matrix_complex_alloc(m.rows(), m.cols()); for (int i=0 ; i<m.rows() ; ++i) for (int j=0 ; j<m.cols(); ++j) { gsl_matrix_complex_set(res, i, j, gsl_complex_rect(m(i,j).real(), m(i,j).imag())); } } template<typename MatrixType> void convert(const gsl_matrix_complex* m, MatrixType& res) { res.resize(int(m->size1), int(m->size2)); for (int i=0 ; i<res.rows() ; ++i) for (int j=0 ; j<res.cols(); ++j) res(i,j) = typename MatrixType::Scalar( GSL_REAL(gsl_matrix_complex_get(m,i,j)), GSL_IMAG(gsl_matrix_complex_get(m,i,j))); } template<typename VectorType> void convert(const VectorType& m, gsl_vector_complex* &res) { res = gsl_vector_complex_alloc(m.size()); for (int i=0 ; i<m.size() ; ++i) gsl_vector_complex_set(res, i, gsl_complex_rect(m[i].real(), m[i].imag())); } template<typename VectorType> void convert(const gsl_vector_complex* m, VectorType& res) { res.resize(m->size); for (int i=0 ; i<res.rows() ; ++i) res[i] = typename VectorType::Scalar( GSL_REAL(gsl_vector_complex_get(m, i)), GSL_IMAG(gsl_vector_complex_get(m, i))); } } #endif // EIGEN_GSL_HELPER
{ "alphanum_fraction": 0.6947368421, "avg_line_length": 35.234741784, "ext": "h", "hexsha": "d6172d2ffc96ae2ce68bcd4f6699d49f21e343e7", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/gsl_helper.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/gsl_helper.h", "max_line_length": 119, "max_stars_count": 31, "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/gsl_helper.h", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "num_tokens": 2186, "size": 7505 }
/** * * @file qwrapper_zgemm.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @author Mathieu Faverge * @author Jakub Kurzak * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <cblas.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_zgemm(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t *B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, C, INOUT, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ void QUARK_CORE_zgemm2( Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t *B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, C, INOUT | LOCALITY | GATHERV, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemm_quark = PCORE_zgemm_quark #define CORE_zgemm_quark PCORE_zgemm_quark #endif void CORE_zgemm_quark(Quark *quark) { PLASMA_enum transA; PLASMA_enum transB; int m; int n; int k; PLASMA_Complex64_t alpha; PLASMA_Complex64_t *A; int lda; PLASMA_Complex64_t *B; int ldb; PLASMA_Complex64_t beta; PLASMA_Complex64_t *C; int ldc; quark_unpack_args_13(quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); cblas_zgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, CBLAS_SADDR(alpha), A, lda, B, ldb, CBLAS_SADDR(beta), C, ldc); } /***************************************************************************//** * **/ void QUARK_CORE_zgemm_f2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t *B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t *C, int ldc, PLASMA_Complex64_t *fake1, int szefake1, int flag1, PLASMA_Complex64_t *fake2, int szefake2, int flag2) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_f2_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*nb*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1, sizeof(PLASMA_Complex64_t)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemm_f2_quark = PCORE_zgemm_f2_quark #define CORE_zgemm_f2_quark PCORE_zgemm_f2_quark #endif void CORE_zgemm_f2_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex64_t alpha; PLASMA_Complex64_t *A; int LDA; PLASMA_Complex64_t *B; int LDB; PLASMA_Complex64_t beta; PLASMA_Complex64_t *C; int LDC; void *fake1, *fake2; quark_unpack_args_15(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC, fake1, fake2); cblas_zgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_zgemm_p2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t **B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t *C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_p2_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t*), B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*ldc*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemm_p2_quark = PCORE_zgemm_p2_quark #define CORE_zgemm_p2_quark PCORE_zgemm_p2_quark #endif void CORE_zgemm_p2_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex64_t alpha; PLASMA_Complex64_t *A; int LDA; PLASMA_Complex64_t **B; int LDB; PLASMA_Complex64_t beta; PLASMA_Complex64_t *C; int LDC; quark_unpack_args_13(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC); cblas_zgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, *B, LDB, CBLAS_SADDR(beta), C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_zgemm_p3(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t *B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t **C, int ldc) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_p3_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t)*ldb*nb, B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t*), C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemm_p3_quark = PCORE_zgemm_p3_quark #define CORE_zgemm_p3_quark PCORE_zgemm_p3_quark #endif void CORE_zgemm_p3_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex64_t alpha; PLASMA_Complex64_t *A; int LDA; PLASMA_Complex64_t *B; int LDB; PLASMA_Complex64_t beta; PLASMA_Complex64_t **C; int LDC; quark_unpack_args_13(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC); cblas_zgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), *C, LDC); } /***************************************************************************//** * **/ void QUARK_CORE_zgemm_p2f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, int transB, int m, int n, int k, int nb, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t **B, int ldb, PLASMA_Complex64_t beta, PLASMA_Complex64_t *C, int ldc, PLASMA_Complex64_t *fake1, int szefake1, int flag1) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_zgemm_p2f1_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*lda*nb, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t*), B, INPUT, sizeof(int), &ldb, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*ldc*nb, C, INOUT | LOCALITY, sizeof(int), &ldc, VALUE, sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemm_p2f1_quark = PCORE_zgemm_p2f1_quark #define CORE_zgemm_p2f1_quark PCORE_zgemm_p2f1_quark #endif void CORE_zgemm_p2f1_quark(Quark* quark) { PLASMA_enum transA; PLASMA_enum transB; int M; int N; int K; PLASMA_Complex64_t alpha; PLASMA_Complex64_t *A; int LDA; PLASMA_Complex64_t **B; int LDB; PLASMA_Complex64_t beta; PLASMA_Complex64_t *C; int LDC; void *fake1; quark_unpack_args_14(quark, transA, transB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC, fake1); cblas_zgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, *B, LDB, CBLAS_SADDR(beta), C, LDC); }
{ "alphanum_fraction": 0.485308872, "avg_line_length": 38.3351648352, "ext": "c", "hexsha": "2f625acb2ef781cb526a5438afbcf95cb21616ec", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_zgemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_zgemm.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_zgemm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3814, "size": 13954 }
#pragma once #include "halley/utils/utils.h" #include "halley/text/halleystring.h" #include <memory> #include <gsl/span> #include "halley/resources/resource_data.h" namespace Halley { enum class AssetType; class Deserializer; class Serializer; class AssetDatabase; class ResourceData; class ResourceDataReader; struct AssetPackHeader { std::array<char, 8> identifier; std::array<char, 16> iv; uint64_t assetDbStartPos; uint64_t dataStartPos; void init(size_t assetDbSize); }; class AssetPack { public: AssetPack(); AssetPack(const AssetPack& other) = delete; AssetPack(AssetPack&& other) noexcept; AssetPack(std::unique_ptr<ResourceDataReader> reader, const String& encryptionKey = "", bool preLoad = false); ~AssetPack(); AssetPack& operator=(const AssetPack& other) = delete; AssetPack& operator=(AssetPack&& other) noexcept; AssetDatabase& getAssetDatabase(); const AssetDatabase& getAssetDatabase() const; Bytes& getData(); const Bytes& getData() const; Bytes writeOut() const; std::unique_ptr<ResourceData> getData(const String& asset, AssetType type, bool stream); void readToMemory(); void encrypt(const String& key); void decrypt(const String& key); void readData(size_t pos, gsl::span<gsl::byte> dst); std::unique_ptr<ResourceDataReader> extractReader(); private: std::unique_ptr<AssetDatabase> assetDb; std::unique_ptr<ResourceDataReader> reader; std::atomic<bool> hasReader; std::mutex readerMutex; size_t dataOffset = 0; Bytes data; std::array<char, 16> iv; }; class PackDataReader final : public ResourceDataReader { public: PackDataReader(AssetPack& pack, size_t startPos, size_t fileSize); size_t size() const override; int read(gsl::span<gsl::byte> dst) override; void seek(int64_t pos, int whence) override; size_t tell() const override; void close() override; private: AssetPack& pack; const size_t startPos; const size_t fileSize; size_t curPos = 0; mutable std::mutex mutex; }; }
{ "alphanum_fraction": 0.7261553589, "avg_line_length": 24.8048780488, "ext": "h", "hexsha": "2eaa56e3e8accab2c50da1f099b35c39bd137336", "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": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "code-disaster/halley", "max_forks_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.h", "max_issues_count": 53, "max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "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": "code-disaster/halley", "max_issues_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.h", "max_line_length": 112, "max_stars_count": 3262, "max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "code-disaster/halley", "max_stars_repo_path": "src/engine/core/include/halley/core/resources/asset_pack.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": 527, "size": 2034 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_ssbmv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const int K, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY) { #define BASE float #include "source_sbmv.h" #undef BASE }
{ "alphanum_fraction": 0.7066666667, "avg_line_length": 25, "ext": "c", "hexsha": "bd8ca470b0d5221b8705f1ff57e37b7cfd686f71", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/ssbmv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/ssbmv.c", "max_line_length": 70, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/ssbmv.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": 112, "size": 375 }
#if !defined(INDENTCLASSIFIER_H_INCLUDED) #define INDENTCLASSIFIER_H_INCLUDED #include "FileEnumerator.h" #include "Utils.h" #include <filesystem> #include <gsl/gsl> #include <iosfwd> #include <map> #include <string> /// \brief IndentType contains the enum constants that indicate the type of /// indentation for a line of text or a text file. enum class IndentType { space, ///< Indents consist entirely of spaces tab, ///< Indents consist entirely of tabs javadocTab, ///< Indents are entirely tabs or tabs followed by exactly one space and asterisk, as in a tab-indented JavaDoc comment javadocLeft, ///< Indented exactly one space followed by an asterisk, as in an unindented JavaDoc comment (single-line only) mixed, ///< Indents are mixed tabs and spaces, or some are tabs and others are spaces indeterminate ///< Refers to lines with no whitespace indent }; using LineTypeCounts = ::std::map<IndentType, size_t>; /// \brief The same as lineTypeCounts.at(indentType) except that it returns zero /// if the map does not contain an entry for indentType. size_t get(const LineTypeCounts& lineTypeCounts, IndentType indentType); class IndentClassifier { public: static int usage(::std::ostream& strm, const ::std::string& progName, const char* pMsg); IndentClassifier(::gsl::span<const char*const> args); int run() const; IndentClassifier(const IndentClassifier&) = delete; IndentClassifier& operator=(const IndentClassifier&) = delete; IndentClassifier(IndentClassifier&&) = delete; IndentClassifier& operator=(IndentClassifier&&) = delete; PRIVATE_EXCEPT_IN_TEST: using Path = ::std::filesystem::path; void processFile(const Path& p) const; static char indicatorLetter(IndentType iType); static ::std::string displayPath(const Path& p); /// \brief Scans the input stream and counts lines of the various indent types. static LineTypeCounts scanFile(const Path& p); static LineTypeCounts scanFile(::std::istream& in, bool isJavaFile); static IndentType classifyLine(const ::std::string& line, bool isJavaFile); static IndentType classifyFile(const LineTypeCounts& lineTypeCounts); FileEnumerator m_fileEnumerator; }; #endif // INDENTCLASSIFIER_H_INCLUDED
{ "alphanum_fraction": 0.7670920693, "avg_line_length": 35.3870967742, "ext": "h", "hexsha": "6d1bd83a38410648cbcb48dd15cc89a10ce27d3a", "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": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_path": "IndentClassifier.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "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": "IanEmmons/CmdLineUtil", "max_issues_repo_path": "IndentClassifier.h", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_path": "IndentClassifier.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 523, "size": 2194 }
#ifndef IBS_HPP #define IBS_HPP #include <array> #include <assert.h> #include <memory> #include <vector> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include "jspec2/force.h" #include "jspec2/rate.h" class Lattice; class IonBeam; enum class IBSModel {MARTINI, BM, BMC, BMZ}; class IBSSolver { protected: double log_c_ = 0.0; //Coulomb logarithm. double k_ = 0.0; //Coupling rate in transverse directions. bool cache_invalid = true; bool ibs_by_element = false; //Calculate and output the ibs rate contribution element by element. void ibs_coupling(double &rx, double &ry, double k, double emit_x, double emit_y); void ibs_by_element_sddshead(std::ofstream& outfile, int n_element); public: double log_c() const { return log_c_; } double k() const { return k_; } void set_k(double x) { k_ = x; } void set_log_c(double x) { log_c_ = x; } void set_ibs_by_element(bool b) {ibs_by_element = b;} void invalidate_cache() { cache_invalid = true; } IBSSolver(double log_c, double k); virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) = 0; }; class IBSSolver_Martini : public IBSSolver { private: struct TrigonometryStorageUV { double sin_u2_cos_v2; double g1; double g2_1; double g2_2; }; struct TrigonometryStorageV { double sin_v; double cos_v; }; struct TrigonometryStorageU { double sin_u; double sin_u2; double cos_u2; double g3; std::vector<TrigonometryStorageUV> uv; }; struct OpticalStorage { double a; double b2; double c2; double d2; double dtld; double k1; double k2; double k3; }; int nu_ = 0; //Grid number in u direction. int nv_ = 0; //Grid number in v direction. int nz_ = 0; //Grid number in z direction. // Scratch variables for IBS calculation (Martini model) std::vector<double> sigma_xbet, sigma_xbetp, sigma_y, sigma_yp; std::vector<TrigonometryStorageU> storage_u; std::vector<TrigonometryStorageV> storage_v; std::vector<OpticalStorage> storage_opt; std::vector<double> f1, f2, f3; void bunch_size(const Lattice &lattice, const IonBeam &beam); void abcdk(const Lattice &lattice, const IonBeam &beam); void coef_f(); void f(); double coef_a(const Lattice &lattice, const IonBeam &beam) const; public: int nu() const { return nu_; } int nv() const { return nv_; } int nz() const { return nz_; } void set_nu(int nu) { assert(nu>0&&"Wrong value of nu in IBS parameters!"); nu_ = nu; invalidate_cache(); } void set_nv(int nv) { assert(nv>0&&"Wrong value of nv in IBS parameters!"); nv_ = nv; invalidate_cache(); } void set_nz(int nz) { assert(nz>0&&"Wrong value of nz in IBS parameters!"); nz_ = nz; invalidate_cache(); } IBSSolver_Martini(int nu, int nv, int nz, double log_c, double k); virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override; }; class IBSSolver_BM : public IBSSolver { private: struct OpticalStorage { //variables only depends on the TWISS parameters and the energy. double phi; double dx2; //D_x * D_x double dx_betax_phi_2; // D_x * D_x / (beta_x * beta_x) + phi * phi double sqrt_betay; // sqrt(beta_y) double gamma_phi_2; // gamma * gamma * phi * phi }; struct Kernels { double psi; double sx; double sp; double sxp; double inv_sigma; }; // Scratch variables for IBS calculation (Bjorken-Mtingwa model using Sergei Nagitsev's formula) std::vector<OpticalStorage> optical_strage; std::vector<Kernels> kernels; void init_fixed_var(const Lattice &lattice, const IonBeam &beam); void calc_kernels(const Lattice &lattice, const IonBeam &beam); double coef_bm(const Lattice &lattice, const IonBeam &beam) const; public: IBSSolver_BM(double log_c, double k); virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override; }; class IBSSolver_BMZ : public IBSSolver { private: int nt_; //Number of steps for integration. struct optcl{ double phi_x2; double phi_y2; double hx; double hy; double dx_2_over_beta_x; double dy_2_over_beta_y; double beta_x_over_hx; double hy_beta_x_over_hx; double beta_phi_x2; double beta_phi_y2; double hy_over_beta_y; }; std::vector<optcl> optical; double factor = 3; void init_optical(const Lattice &lattice); double calc_abc(const Lattice &lattice, const IonBeam& beam, int i, double& a, double& b, double& c, double& ax, double& bx, double& ay, double& by,double& al, double& bl); double coef(const Lattice &lattice, const IonBeam &beam) const; void calc_integral(double a, double b, double c, double ax, double bx, double ay, double by, double al, double bl, double& ix, double& iy, double& is, int nt, double u); public: IBSSolver_BMZ(int nt, double log_c, double k); void set_nt(int n){assert(n>0&&"Wrong value of nt in IBS parameters!"); nt_ = n; invalidate_cache();} virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override; void set_factor(double x){factor = x;} }; class IBSSolver_BM_Complete : public IBSSolver { private: int nt_; double inv_ex; double inv_ey; double inv_dp2; double gamma; double gamma2; double factor = 3; struct Itgrl{ double lambda; double lambda_sqrt; double ct; // ct = 1/(1-t)^2 }; struct Optc { double phix; double phiy; double hx; double hy; }; std::vector<Optc> optc; std::vector<Itgrl> itgrl; void init_optc(const Lattice &lattice); double det(std::array<std::array<double, 3>,3>& l); double inv(std::array<std::array<double, 3>,3>& l, std::array<std::array<double, 3>,3>& v); double trace(std::array<std::array<double, 3>,3>& l){return l[0][0]+l[1][1]+l[2][2];} void calc_l(const Lattice& lattice, int i, std::array<std::array<double, 3>,3>& lh, std::array<std::array<double, 3>,3>& lv, std::array<std::array<double, 3>,3>& ls); void calc_itgl(int i, std::array<std::array<double, 3>,3>& ii, std::array<std::array<double, 3>,3>& l, std::array<std::array<double, 3>,3>& ll, std::array<std::array<double, 3>,3>& lh, std::array<std::array<double, 3>,3>& lv, std::array<std::array<double, 3>,3>& ls); void calc_beam_const(const IonBeam& beam); double coef(const Lattice &lattice, const IonBeam &beam) const; public: IBSSolver_BM_Complete(int nt, double log_c, double k); void set_factor(double x){factor = x;} virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override; }; // //class IBSSolver_BMZ2 : public IBSSolver { //private: // int nt_; //Number of steps for integration. // struct itgrl{ // double lambda; //// double lambda_2; //// double lambda_3; // double lambda_sqrt; // double ct; // ct = 1/(1-t)^2 // }; // double gamma_2; // double gamma_2_inv; // double gamma_4; // double emit_x_inv; // double emit_y_inv; // double emit_x2_inv; // double emit_y2_inv; // // struct optcl{ // double phi_x; // double phi_y; // double dx_2_over_beta_x; // double dy_2_over_beta_y; // }; // std::vector<itgrl> integral; // std::vector<optcl> optical; // struct debug { // double a, b, c, ax, bx, ay, by, al, bl, ix, iy, is; // }; // std::vector<debug> my_debug; // // gsl_integration_workspace *gw; // // size_t limit = 100; // double espabs = 1e-12; // double esprel = 1e-3; // struct P{ // double a; // double b; // double c; // double ai; // double bi; // }p; //// double core(double q, void* params); // //// void init_integral(int n); // void init_optical(const Lattice &lattice); // double calc_abc(const Lattice &lattice, const Beam& beam, int i, double& a, double& b, double& c, // double& ax, double& bx, double& ay, double& by,double& al, double& bl, double& scale); // double coef(const Lattice &lattice, const Beam &beam) const; // void calc_integral(double a, double b, double c, double ax, double bx, double ay, double by, double al, // double bl, double& ix, double& iy, double& is, int nt, std::vector<itgrl>& g); //public: // IBSSolver_BMZ(int nt, double log_c, double k); // set_nt(int n){assert(n>0&&"Wrong value of nt in IBS parameters!"); nt_ = n; invalidate_cache();} // virtual void rate(const Lattice &lattice, const Beam &beam, double &rx, double &ry, double &rs); // // ~IBSSolver_BMZ(){gsl_integration_workspace_free(gw);}; // //}; // // // //}; #endif
{ "alphanum_fraction": 0.6212420452, "avg_line_length": 34.2631578947, "ext": "h", "hexsha": "90cc444633f6fec3f8dd31558572ae6bd80811ca", "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": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "mbruker/jspec2-python", "max_forks_repo_path": "include/jspec2/ibs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "mbruker/jspec2-python", "max_issues_repo_path": "include/jspec2/ibs.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "mbruker/jspec2-python", "max_stars_repo_path": "include/jspec2/ibs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2570, "size": 9114 }
/* C code for actionAngle calculations */ #ifndef __GALPY_ACTIONANGLE_H__ #define __GALPY_ACTIONANGLE_H__ #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 #include <Python.h> #endif #include <stdbool.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_spline.h> #include "interp_2d.h" /* Macro for dealing with potentially unused variables due to OpenMP */ /* If we're not using GNU C, elide __attribute__ if it doesn't exist*/ #ifndef __has_attribute // Compatibility with non-clang compilers. #define __has_attribute(x) 0 #endif #if defined(__GNUC__) || __has_attribute(unused) # define UNUSED __attribute__((unused)) #else # define UNUSED /*NOTHING*/ #endif /* Structure declarations */ struct pragmasolver{ gsl_root_fsolver *s; }; #ifdef __cplusplus } #endif #endif /* actionAngle.h */
{ "alphanum_fraction": 0.7428924598, "avg_line_length": 21.2894736842, "ext": "h", "hexsha": "bffc8d7bb91305e7c2edfb9f537253fe08d686e3", "lang": "C", "max_forks_count": 110, "max_forks_repo_forks_event_max_datetime": "2021-12-28T07:56:49.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-08T10:57:24.000Z", "max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_issues_count": 269, "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:42:08.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:31.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "gusbeane/galpy", "max_issues_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_line_length": 72, "max_stars_count": 147, "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngle.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:47:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:06:17.000Z", "num_tokens": 210, "size": 809 }
/* * Test the effective difference of a single bit changing on the input. * * This test uses random data as input. A hash is calculates. A bit is * changed on the input at one location. Another hash is calculated. * Both hashes are XOR'ed and sent to output as a binary stream. This * is repeated until the output length is reached. */ #include "hash_bbt.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdint.h> #include <stdio.h> #include <string.h> #define HASH_PARAMS bbt_table_1 extern struct bbt_hash_patterns HASH_PARAMS; #define HASH_INPUT_SZ 32 int main(int argc, char **argv) { if (argc < 4) { printf("Usage: %s <outfile> <bit position> <output size> <numeric random seed>\n", argv[0]); return 1; } unsigned argPos = 1; FILE *outfile = fopen(argv[argPos++], "w"); unsigned long int bitPos = strtoul(argv[argPos++], NULL, 10); if (bitPos > ((8*HASH_INPUT_SZ)-1)) { fprintf(stderr, "ERROR: bitPos too large. Beyond end of buffer length.\n"); return 1; } unsigned long int outputLength = strtoul(argv[argPos++], NULL, 10); unsigned long int seed = strtoul(argv[argPos++], NULL, 10); unsigned char hashInput[HASH_INPUT_SZ]; gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937); /* Mersenne Twister */ gsl_rng_set(rng, seed); bbt_hash_ctxt hc; bbt_hash_init(&hc, &(HASH_PARAMS)); unsigned bitIndex = bitPos/8; unsigned bitShift = 7 - (bitPos%8); bbt_hash_t bitMask = ((bbt_hash_t)1) << bitShift; printf("Bit change at index %u and shift %u.\n", bitIndex, bitShift); for (unsigned outputWritten = 0; outputWritten < outputLength;) { unsigned char *p = hashInput; for (unsigned i = 0; i < HASH_INPUT_SZ; i++) { *p = gsl_rng_get(rng) & 0xFF; p++; } bbt_hash_t hashA; bbt_hash_t hashB; bbt_hash_calc(&hc, hashInput, HASH_INPUT_SZ); hashA = bbt_hash_getHash(&hc); bbt_hash_reset(&hc); hashInput[bitIndex] = hashInput[bitIndex] ^ bitMask; bbt_hash_calc(&hc, hashInput, HASH_INPUT_SZ); hashB = bbt_hash_getHash(&hc); bbt_hash_reset(&hc); bbt_hash_t hashCombined = hashA ^ hashB; for (unsigned i = 0; i < sizeof(bbt_hash_t); i++) { fputc(hashCombined & 0xFF, outfile); hashCombined = hashCombined >> 8; outputWritten++; } } fclose(outfile); gsl_rng_free(rng); return 0; }
{ "alphanum_fraction": 0.6937882765, "avg_line_length": 25.9772727273, "ext": "c", "hexsha": "7121ed16bfae208034504fa93b82dba980fb89e4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonkanderson/BitBalancedTableHash", "max_forks_repo_path": "tests/entropy_tests/test7_oneBit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonkanderson/BitBalancedTableHash", "max_issues_repo_path": "tests/entropy_tests/test7_oneBit.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonkanderson/BitBalancedTableHash", "max_stars_repo_path": "tests/entropy_tests/test7_oneBit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 678, "size": 2286 }
/* * maths_base.h * ecosstat_project * * Created by Karim Benabed on 23/06/09. * Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved. * */ #ifndef __MATHS_BASE_H #define __MATHS_BASE_H #include <stdio.h> #include <stdlib.h> #include <math.h> #if 0 #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_int.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #endif #ifdef __PLANCK__ #include "HL2_likely/tools/errorlist.h" #include "HL2_likely/tools/io.h" #else #include "errorlist.h" #include "io.h" #endif #define math_base -300 #define math_negative -1 + math_base #define math_singularValue -2 + math_base #define math_tooManySteps -3 + math_base #define math_underflow -4 + math_base #define math_infnan -5 + math_base #define math_wrongValue -6 + math_base #define math_alloc -7 + math_base #define math_interpoloutofrange -8 + math_base #define math_interpol2small -9 + math_base #define math_interpol2big -10 + math_base #define math_stackTooSmall -11 + math_base #define math_overflow -12 + math_base #define math_unknown -13 + math_base typedef double my_complex[2]; /* Mathematical constants */ #define pi 3.14159265358979323846 #define pi_sqr 9.86960440108935861883 #define twopi 6.28318530717958647693 #define ln2 0.69314718 #define ln2pi 1.837877066409 #define arcmin 2.90888208665721580e-4 #define arcsec 4.84813681e-6 /* Confidence levels, = erf({1,2,3}/sqrt(2)) */ #define conf_68 0.6827 #define conf_90 0.9000 #define conf_95 0.9545 #define conf_99 0.9973 /* Small numbers */ #define EPSILON 1.0e-5 #define EPSILON1 1.0e-8 #define EPSILON2 1.0e-18 /* Square of the absolute value of x (=|x|^2) */ #define ABSSQR(x) ((x)[0]*(x)[0] + (x)[1]*(x)[1]) /* Scalar product (x,y) */ #define SP(x,y) ((x)[0]*(y)[0]+(x)[1]*(y)[1]) #endif
{ "alphanum_fraction": 0.6875965003, "avg_line_length": 24.2875, "ext": "h", "hexsha": "cf6b0519dc420f5ed2e9cae70e72c4dfb6dce20a", "lang": "C", "max_forks_count": 78, "max_forks_repo_forks_event_max_datetime": "2022-02-01T01:57:31.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-21T13:11:54.000Z", "max_forks_repo_head_hexsha": "928bb41f1248baf0854b4b13e8b51bbea15f8d68", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lshuns/montepython_KV450", "max_forks_repo_path": "wrapper_wmap_v4p1/src/minipmc/maths_base.h", "max_issues_count": 263, "max_issues_repo_head_hexsha": "928bb41f1248baf0854b4b13e8b51bbea15f8d68", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:45:48.000Z", "max_issues_repo_issues_event_min_datetime": "2018-05-20T21:58:11.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lshuns/montepython_KV450", "max_issues_repo_path": "wrapper_wmap_v4p1/src/minipmc/maths_base.h", "max_line_length": 74, "max_stars_count": 69, "max_stars_repo_head_hexsha": "928bb41f1248baf0854b4b13e8b51bbea15f8d68", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lshuns/montepython_KV450", "max_stars_repo_path": "wrapper_wmap_v4p1/src/minipmc/maths_base.h", "max_stars_repo_stars_event_max_datetime": "2022-03-11T06:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-20T07:38:33.000Z", "num_tokens": 616, "size": 1943 }
#include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <galpy_potentials.h> // MovingObjectPotential // 3 arguments: amp, t0, tf void constrain_range(double * d) { // Constrains index to be within interpolation range if (*d < 0) *d = 0.0; if (*d > 1) *d = 1.0; } double MovingObjectPotentialRforce(double R,double z, double phi, double t, struct potentialArg * potentialArgs){ double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist,RF; double * args= potentialArgs->args; //Get args amp= *args; t0= *(args+1); tf= *(args+2); d_ind= (t-t0)/(tf-t0); x= R*cos(phi); y= R*sin(phi); constrain_range(&d_ind); // Interpolate x, y, z obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind, *(potentialArgs->acc1d+1)); obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind, *(potentialArgs->acc1d+2)); Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5); // Calculate R force RF= calcRforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist; } double MovingObjectPotentialzforce(double R,double z,double phi, double t, struct potentialArg * potentialArgs){ double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist; double * args= potentialArgs->args; //Get args amp= *args; t0= *(args+1); tf= *(args+2); d_ind= (t-t0)/(tf-t0); x= R*cos(phi); y= R*sin(phi); constrain_range(&d_ind); // Interpolate x, y, z obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind, *(potentialArgs->acc1d+1)); obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind, *(potentialArgs->acc1d+2)); Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5); // Calculate z force return -amp * calczforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); } double MovingObjectPotentialphiforce(double R,double z,double phi, double t, struct potentialArg * potentialArgs){ double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist,RF; double * args= potentialArgs->args; //Get args amp= *args; t0= *(args+1); tf= *(args+2); d_ind= (t-t0)/(tf-t0); x= R*cos(phi); y= R*sin(phi); constrain_range(&d_ind); // Interpolate x, y, z obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind, *(potentialArgs->acc1d+1)); obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind, *(potentialArgs->acc1d+2)); Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5); // Calculate phiforce RF= calcRforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist; } double MovingObjectPotentialPlanarRforce(double R, double phi, double t, struct potentialArg * potentialArgs){ double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF; double * args= potentialArgs->args; //Get args amp= *args; t0= *(args+1); tf= *(args+2); d_ind= (t-t0)/(tf-t0); x= R*cos(phi); y= R*sin(phi); constrain_range(&d_ind); // Interpolate x, y obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind, *(potentialArgs->acc1d+1)); Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5); // Calculate R force RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist; } double MovingObjectPotentialPlanarphiforce(double R, double phi, double t, struct potentialArg * potentialArgs){ double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF; double * args= potentialArgs->args; // Get args amp= *args; t0= *(args+1); tf= *(args+2); d_ind= (t-t0)/(tf-t0); x= R*cos(phi); y= R*sin(phi); constrain_range(&d_ind); // Interpolate x, y obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d); obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind, *(potentialArgs->acc1d+1)); Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5); // Calculate phiforce RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped, potentialArgs->wrappedPotentialArg); return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist; }
{ "alphanum_fraction": 0.6744337979, "avg_line_length": 33.7647058824, "ext": "c", "hexsha": "dee65196a6f1f4469b290f71e3742415325b17ab", "lang": "C", "max_forks_count": 110, "max_forks_repo_forks_event_max_datetime": "2021-12-28T07:56:49.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-08T10:57:24.000Z", "max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_issues_count": 269, "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:42:08.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:31.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "gusbeane/galpy", "max_issues_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_line_length": 79, "max_stars_count": 147, "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:47:41.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:06:17.000Z", "num_tokens": 1566, "size": 4592 }
//IN method. //Linear transformation (weights only, no biases) of Ni inputs to No outputs. //This version uses CBLAS //Input X has Ni neurons and output Y has No neurons. //The vecs of length Ni are always contiguous in memory, such that: //If col-major: Y[:,l] = W' * X[:,l] //where: //X has size Ni x L //Y has size No x L //W has size Ni x No //If row-major: Y[l,:] = X[l,:] * W' //X has size L x Ni //Y has size L x No //W has size No x Ni //For a different set-up that allows linear transformation of vecs in //any orientation, use the linear function from math. //I retain the for loop through L for compatibility with real-time streaming. #include <cblas.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int linear_cblas_s (float *Y, const float *X, const float *W, const size_t Ni, const size_t No, const size_t L); int linear_cblas_d (double *Y, const double *X, const double *W, const size_t Ni, const size_t No, const size_t L); int linear_cblas_c (float *Y, const float *X, const float *W, const size_t Ni, const size_t No, const size_t L); int linear_cblas_z (double *Y, const double *X, const double *W, const size_t Ni, const size_t No, const size_t L); int linear_cblas_s (float *Y, const float *X, const float *W, const size_t Ni, const size_t No, const size_t L) { for (size_t l=L; l>0u; --l, X+=Ni, Y+=No) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0f,W,(int)Ni,X,1,0.0f,Y,1); } return 0; } int linear_cblas_d (double *Y, const double *X, const double *W, const size_t Ni, const size_t No, const size_t L) { for (size_t l=L; l>0u; --l, X+=Ni, Y+=No) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,1.0,W,(int)Ni,X,1,0.0,Y,1); } return 0; } int linear_cblas_c (float *Y, const float *X, const float *W, const size_t Ni, const size_t No, const size_t L) { const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f}; for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No) { cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,z,Y,1); } return 0; } int linear_cblas_z (double *Y, const double *X, const double *W, const size_t Ni, const size_t No, const size_t L) { const double z[2] = {0.0,0.0}, o[2] = {1.0,0.0}; for (size_t l=L; l>0u; --l, X+=2u*Ni, Y+=2u*No) { cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)No,(int)Ni,o,W,(int)Ni,X,1,z,Y,1); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.6504854369, "avg_line_length": 27.4666666667, "ext": "c", "hexsha": "f852a9a33c3875682bc438c55007e9408b43df7d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_path": "c/linear.cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/nn", "max_issues_repo_path": "c/linear.cblas.c", "max_line_length": 115, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_path": "c/linear.cblas.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "num_tokens": 867, "size": 2472 }
/*---------------------------------------------------------------------------- / / Filename: fits_wavelet.c / Author: Jay Billings / Author's email: jayjaybillings@gmail.com / Description: This program will perform a Debauchies wavelet transform on / an input image and turn off the wavelet coefficients up to / a certain percentage of the total size. / / Usage: / ./fits_wavelet <image> <limit> / / <image> should be an image in FITS format and <limit> / should be a number between 0.0 and 1.0. / / Output: / filtered_<image> / / The output image is also in the FITS format and is readily / viewable in FV, available from the NASA website, or the / Sky Image Processor, useable as a java applet from Dr. / John Simonetti, Virginia Tech, / / http://www.phys.vt.edu/~jhs/SIP. / / This code requires the CFITSIO library and the GNU Scientific / Library. Both are freely available on the internet. This code / compiles fine with gcc-4.1.2 using / / gcc -o fits_wavelet fits_wavelet.c -lm -lgsl -lgslcblas / -lcfitiso / / Copyright (c) 2008 Jay Jay Billings / / 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 / / The license is also available at: / / http://www.gnu.org/copyleft/gpl.html . / / Date: 2008/03/24 / *///-------------------------------------------------------------------------- #include <string.h> #include <stdio.h> #include <fitsio.h> #include <gsl/gsl_wavelet.h> #include <gsl/gsl_sort.h> #include <math.h> void read_image(double *,char *,int []); void write_image(double *, char *, int []); int main(int argc, char *argv[]) { int i, j, size[3], a; double f, limit, *pixels, *pixels_copy; gsl_wavelet *w; gsl_wavelet_workspace *work; size_t *p; // Check to make sure that the inputs are OK. if (argc < 3) { printf("You need to specify a file! \n\nUsage: "); printf("\t fits_wavelet <input_file> <limit>\n\n"); exit(0); } f = atof(argv[2]); if (f >= 1.0) { printf("The limit must be between 0.0 and 1.0!\n\n"); printf("Try something else! (Like 0.85...)\n"); exit(0); } // Allocate some storage arrays. The maximum size is currently // set at 1024*1024, or 2^20, initilized to zero. if (!(pixels = calloc(1024*1024,sizeof(double)))) { printf("Memory allocation error\n"); exit(0); } if (!(pixels_copy = calloc(1024*1024,sizeof(double)))) { printf("Memory allocation error\n"); exit(0); } if (!(p = malloc(1024*1024*sizeof(size_t)))) { printf("Memory allocation error\n"); exit(0); } // Read the image into the pixels array. read_image(pixels,argv[1],size); // Allocate the wavelet workspace. w = gsl_wavelet_alloc(gsl_wavelet_daubechies,20); work = gsl_wavelet_workspace_alloc(1024*1024); // Perform the wavelet transfer. gsl_wavelet_transform_forward(w,pixels,1,1024,work); // Make a copy of the pixels array and sort it. for (i = 0; i < size[2]; ++i) { pixels_copy[i] = fabs(pixels[i]); } gsl_sort_index(p,pixels_copy,1,size[0]*size[1]); // Loop over the wavelet coefficients and turn them off // up to a certain limit. limit = (double) size[2] * f; for (i = 0; i < (int) limit; ++i) { pixels[p[i]] = 0.0; } // Perform the inverse transform. gsl_wavelet_transform_inverse(w,pixels,1,1024,work); // Write the image. write_image(pixels,argv[1],size); // Free all the memory and exit. gsl_wavelet_free(w); gsl_wavelet_workspace_free(work); free(pixels);free(pixels_copy);free(p); return 0; } // This subroutine was adapted from documentation provided on the FITSIO website. void read_image(double *pixels_vector, char *filename, int size[3]) { fitsfile *fptr; /* FITS file pointer, defined in fitsio.h */ int status = 0; /* CFITSIO status value MUST be initialized to zero! */ int bitpix, naxis, ii, anynul,a; long naxes[2] = {1,1}, fpixel[2] = {1,1}; double *pixels; char format[20], hdformat[20]; /*if (argc != 2) { printf("Usage: imlist filename[ext][section filter] \n"); printf("\n"); printf("List the the pixel values in a FITS image \n"); printf("\n"); printf("Example: \n"); printf(" imlist image.fits - list the whole image\n"); printf(" imlist image.fits[100:110,400:410] - list a section\n"); printf(" imlist table.fits[2][bin (x,y) = 32] - list the pixels in\n"); printf(" an image constructed from a 2D histogram of X and Y\n"); printf(" columns in a table with a binning factor = 32\n"); return(0); }*/ if (!fits_open_file(&fptr, filename, READONLY, &status)) { if (!fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status) ) { if (naxis > 2 || naxis == 0) printf("Error: only 1D or 2D images are supported\n"); else { /* get memory for 1 row */ if (!(pixels = malloc(naxes[0] * sizeof(double)))) { printf("Memory allocation error\n"); exit(0); } if (bitpix > 0) { /* set the default output format string */ strcpy(hdformat, " %7d"); strcpy(format, " %7.0f"); } else { strcpy(hdformat, " %15d"); strcpy(format, " %15.5f"); } //printf("\n "); /* print column header */ //for (ii = 1; ii <= naxes[0]; ii++) // printf(hdformat, ii); //printf("\n"); /* terminate header line */ /* loop over all the rows in the image, top to bottom */ a = 0; for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--) { if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL, pixels, NULL, &status) ) /* read row of pixels */ break; /* jump out of loop on error */ // printf(" %4d \n",fpixel[1]); /* print row number */ for (ii = 0; ii < naxes[0]; ii++) { pixels_vector[a] = pixels[ii]; // printf(format, pixels_vector[a]); /* print each value */ // printf(" %d\n",a); /* terminate line */ ++a; } } size[0] = naxes[0]; size[1] = naxes[1]; size[2] = naxes[0]*naxes[1]; free(pixels); } } fits_close_file(fptr, &status); } if (status) { fits_report_error(stderr, status); /* print any error message */ exit(0); } //return(status); return; } void write_image(double *pixels_vector, char *f1, int size[3]) { fitsfile *infptr, *outfptr; /* FITS file pointer, defined in fitsio.h */ int status = 0; /* CFITSIO status value MUST be initialized to zero! */ int ii = 1; char f2[200]; long size_l[2], fpixel[2] = {1,1}; void *pix_ptr = &pixels_vector; size_l[0] = (long) size[0]; size_l[1] = (long) size[1]; sprintf(f2,"filtered_%s",f1); /* Create the output file */ if (!fits_create_file(&outfptr, f2, &status) ) { if (!fits_create_img(outfptr,32,2,size_l,&status)) { if (!fits_write_pix(outfptr,TDOUBLE,fpixel,(long) size[2],pixels_vector \ ,&status)) { if (status == END_OF_FILE) status = 0; } //printf("Write status: %d \n",status); } fits_close_file(outfptr, &status); } return; }
{ "alphanum_fraction": 0.5511343805, "avg_line_length": 34.1071428571, "ext": "c", "hexsha": "30713b59b3364bdf697ad342ad205e9891aef586", "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": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jayjaybillings/jayjaybillings.github.io", "max_forks_repo_path": "tools/fits_wavelet/fits_wavelet.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "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": "jayjaybillings/jayjaybillings.github.io", "max_issues_repo_path": "tools/fits_wavelet/fits_wavelet.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "b4b74ea5f7e0a015897522e40d6366b7702a32cd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jayjaybillings/jayjaybillings.github.io", "max_stars_repo_path": "tools/fits_wavelet/fits_wavelet.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2302, "size": 8595 }
/*! \file interp.h \brief Functions for interpolation to initialize the root solver */ // used by the gsl interpolation functions #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sort_double.h> #ifndef REAL_TYPEDEF #define REAL_TYPEDEF #ifndef single // compiler option determines variable size typedef double REAL; #else typedef float REAL; #endif #endif #define N_INTERP_POINTS 3 #define NEAREST_TOL 1.0e-3 #define MIN_IDX(indices,values) ((values[0] < values[1]) ? indices[0]:indices[1]) #define DISTANCE(x1,y1,x2,y2) hypot(x1-x2,y1-y2) #define MAXIMUM(x,y) ((x) > (y) ? (x) : (y)) // interpolation functions REAL interpBetw2ptsDist(REAL distx_x0,REAL f0,REAL f1,REAL distx1_x0); int cartesianToCylindrical(int npts,REAL R[],REAL Z[],REAL zeta[],REAL x[],REAL y[],REAL z[]); int interp2d(int nx,int nxi,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[],REAL yi[],REAL zi[],REAL wi[]); int find_nearestn(int nclosest,int nx,int nxi,size_t idx_closest[nx][nclosest],REAL x[],REAL y[],REAL xi[],REAL yi[]); int calc_slopes(double mx[],double my[],size_t idxs[],double x[],double y[],double z[]); // legacy functions used by previous versions of the root finder int interp(REAL y[],REAL xi[],REAL si[],int ny,int nxi); int interpxy(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi); int interpgsl(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi); int find_nearest(int nx,int xirows,int xicols,int xi_idx_below[],int yi_idx_below[],REAL x[],REAL y[],REAL xi[][xicols],REAL yi[][xicols]); int interpReg2d(int nx,int xirows,int xicols,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[][xicols],REAL yi[][xicols],REAL zi[][xicols],REAL wi[][xicols]); // --- local function definitions //! Linear interpolation using two points to a third point /*! Uses the distance between the two known points ``distx1_x0'' = (x1-x0), the distance between the unknown point to a known point ``distx_x0'' = (x-x0), and the values of the function at x1 and x0 (f1 = f(x1),f2 = f(x2)), to find the value at x: f= f(x). */ REAL interpBetw2ptsDist(REAL distx_x0,REAL f0,REAL f1,REAL distx1_x0){ REAL f = (f1-f0)/distx1_x0*distx_x0 + f0; return f; } //! Converts cartesian coordinates (x,y,z) to cylindrical coordinates (R,Z,zeta) int cartesianToCylindrical(int npts,REAL R[],REAL Z[],REAL zeta[],REAL x[],REAL y[],REAL z[]){ int i; for(i=0;i<npts;i++){ R[i]=hypot(x[i],z[i]); Z[i]=y[i]; zeta[i]=-atan2(z[i],x[i]); // negative because in forming right-hand coord system } // x: radially out, y: vertically up, z: toroidal // esi routines give theta going clockwise, // a: out in minor radius, gives z and theta antiparallel return 0; } //! Finds the nearest n points on a grid of (xi,yi) for each point (x,y) int find_nearestn(int nclosest,int nx,int nxi,size_t idx_closest[nx][nclosest],REAL x[],REAL y[],REAL xi[],REAL yi[]){ double dist[nxi],d01,d02,d12,hyp; int point,i,n_temp; size_t *closest_pts; size_t *idx_closest_pt; #if DEBUG fprintf(stderr,"point, d01, d02, d12, hyp, collinear\n"); #endif for(point=0;point<nx;point++){ // loop for each x,y for(i=0;i<nxi;i++){ // find the distance between (x,y) and all the (xi,yi) // dist[i]=sqrt((x[point]-xi[i])*(x[point]-xi[i])+(y[point]-yi[i])*(y[point]-yi[i])); dist[i]=DISTANCE(x[point],y[point],xi[i],yi[i]); } idx_closest_pt=idx_closest[point]; gsl_sort_smallest_index(idx_closest_pt,nclosest,dist,1,nxi);// find the nearest xi // make sure they aren't collinear d01=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[1]],yi[idx_closest_pt[1]]); d02=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]); d12=DISTANCE(xi[idx_closest_pt[1]],yi[idx_closest_pt[1]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]); // hyp = fmax(fmax(d01,d02),d12); hyp = MAXIMUM(MAXIMUM(d01,d02),d12); n_temp = nclosest; while((d01+d02+d12-2.0*hyp < NEAREST_TOL) && (nclosest < nxi)){ // loop until the points aren't collinear n_temp++; closest_pts = (size_t *)malloc(sizeof(size_t)*n_temp); gsl_sort_smallest_index(closest_pts,n_temp,dist,1,nxi);// find the nearest xi idx_closest_pt[2]=closest_pts[n_temp-1]; d02=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]); d12=DISTANCE(xi[idx_closest_pt[1]],yi[idx_closest_pt[1]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]); //hyp = fmax(fmax(d01,d02),d12); hyp = MAXIMUM(MAXIMUM(d01,d02),d12); free(closest_pts); } #if DEBUG fprintf(stderr,"%d, %g, %g, %g, %g, %g\n",point,d01,d02,d12,hyp,2.0*hyp-d01-d02-d12); #endif } // for(i=0;i<xirows*xicols;i++){ // fprintf(stderr,"xi yi\n"); // fprintf(stderr,"%g, %g\n",xi[0][i],yi[0][i]); // } // for(i=0;i<nx;i++){ // fprintf(stderr,"x, xi_below, y, ,yi_below\n"); // fprintf(stderr,"%g, %g, %g, %g\n",x[i],xi[xi_idx_below[i]][0],y[i],yi[0][yi_idx_below[i]]); // } return 0; } //! Calculates the slopes (mx,my) for three points (x,y) which each have function value z /*! these three points are have the indices idxs */ int calc_slopes(double mx[],double my[],size_t idxs[],double x[],double y[],double z[]){ size_t i,ip1,ip2,j,jp1,jp2; double dx[N_INTERP_POINTS],dy[N_INTERP_POINTS],dz[N_INTERP_POINTS]; for(j=0;j<N_INTERP_POINTS;j++){ ip1 = idxs[(size_t)fmod(j+1,N_INTERP_POINTS)]; ip2 = idxs[(size_t)fmod(j+2,N_INTERP_POINTS)]; dx[j] = x[ip1]-x[ip2]; dy[j] = y[ip1]-y[ip2]; dz[j] = z[ip1]-z[ip2]; } for(j=0;j<N_INTERP_POINTS;j++){ jp1 = (size_t)fmod(j+1,N_INTERP_POINTS); jp2 = (size_t)fmod(j+2,N_INTERP_POINTS); i = idxs[j]; ip1 = idxs[jp1]; ip2 = idxs[jp2]; mx[j] = -1.0*(y[i]*dz[j]+y[ip1]*dz[jp1]+y[ip2]*dz[jp2]); mx[j]/=(x[i]*dy[j]+x[ip1]*dy[jp1]+x[ip2]*dy[jp2]); my[j] = -1.0*(x[i]*dz[j]+x[ip1]*dz[jp1]+x[ip2]*dz[jp2]); my[j]/=(y[i]*dx[j]+y[ip1]*dx[jp1]+y[ip2]*dx[jp2]); } return 0; } //! High-level 2d interpolation function /*! Given values zi = f(xi,yi) and wi = g(xi,yi) on an arbitrary, irregular grid (xi,yi) finds the values at (x,y). The method is to find the nearest 3 grid points for each (x,y), then linearly interpolate (triangulation). */ int interp2d(int nx,int nxi,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[],REAL yi[],REAL zi[],REAL wi[]){ int point; size_t *idxs; double mxi[N_INTERP_POINTS],myi[N_INTERP_POINTS],a,b,c; // find the indices of the 3 (xi,yi) closest to x,y size_t idx_closest[nx][N_INTERP_POINTS]; find_nearestn(N_INTERP_POINTS,nx,nxi,idx_closest,x,y,xi,yi); // loop around points for(point=0;point<nx;point++){ idxs = idx_closest[point]; // first get z // calculate the slopes (mx,my) for the nearest 3 points calc_slopes(mxi,myi,idxs,xi,yi,zi); // linear interp at each nearest point a = zi[idxs[0]] + mxi[0]*(x[point]-xi[idxs[0]]) + myi[0]*(y[point]-yi[idxs[0]]); b = zi[idxs[1]] + mxi[1]*(x[point]-xi[idxs[1]]) + myi[1]*(y[point]-yi[idxs[1]]); c = zi[idxs[2]] + mxi[2]*(x[point]-xi[idxs[2]]) + myi[2]*(y[point]-yi[idxs[2]]); // average to get the best guess z[point] = (a+b+c)/3.0; // next get w // calculate the slopes (mx,my) for the nearest 3 points calc_slopes(mxi,myi,idxs,xi,yi,wi); // linear interp at each nearest point a = wi[idxs[0]] + mxi[0]*(x[point]-xi[idxs[0]]) + myi[0]*(y[point]-yi[idxs[0]]); b = wi[idxs[1]] + mxi[1]*(x[point]-xi[idxs[1]]) + myi[1]*(y[point]-yi[idxs[1]]); c = wi[idxs[2]] + mxi[2]*(x[point]-xi[idxs[2]]) + myi[2]*(y[point]-yi[idxs[2]]); // average to get the best guess w[point] = (a+b+c)/3.0; } return 0; } // --- legacy functions int interp(REAL y[],REAL xi[],REAL si[],int ny,int nxi){ int i,j; // printf("interp:\n%10s,%10s,%10s,%10s,%10s\n","q_orig","q_final","q_i","q_i+1","s_i"); for(i=0;i<ny;i++){ for(j=0;j<nxi-1;j++) if(xi[j+1] > y[i]) break; //printf("%10g,",y[i]); y[i] = xi[j] + si[j]*(y[i]-xi[j]); //printf("%10g,%10g,%10g,%10g\n",y[i],xi[j],xi[j+1],si[j]); } return 0; } int interpxy(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi){ int i,j; REAL si[nxi-1]; // use linear interpolation //printf("\nstheta:"); for(i=0;i<nxi-1;i++){ si[i] = (yi[i+1]-yi[i])/(xi[i+1]-xi[i]); //printf("%g,",si[i]); } si[nxi-2] = si[0]; //printf("\n"); //printf("interp:\n%10s,%10s,%10s,%10s,%10s\n","q_orig","q_final","q_i","q_i+1","s_i"); for(i=0;i<nx;i++){ for(j=0;j<nxi-1;j++) if(xi[j+1] > x[i]) break; //printf("%10g,",x[i]); y[i] = yi[j] + si[j]*(x[i]-xi[j]); //printf("%10g,%10g,%10g,%10g\n",y[i],xi[j],xi[j+1],si[j]); } return 0; } // interpolate the array x[] of size nx // on the grid xi[],y[i] of size nxi int interpgsl(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi){ // make sure periodic // yi[nxi-1]=yi[0]; // xi[nxi-1]=-xi[0]; gsl_interp_accel *acc = gsl_interp_accel_alloc (); const gsl_interp_type *t = gsl_interp_cspline; gsl_spline *spline = gsl_spline_alloc (t, nxi); int i; gsl_spline_init (spline, xi, yi, nxi); //printf("\ninterpgsl:\n"); for (i = 0; i < nx; i++) { y[i] = gsl_spline_eval (spline, x[i], acc); //printf ("%g, %g\n", x[i], y[i]); } gsl_spline_free (spline); gsl_interp_accel_free (acc); return 0; } int find_nearest1d(int nx,int nxi,int nnearest,int stride,size_t xi_idx[nx][nnearest],REAL x[],REAL xi[]){ int i,j; REAL xerr[nxi]; for(i=0;i<nx;i++){ for(j=0;j<nxi;j++){ xerr[j]=fabs(x[i]-xi[j*stride]); } gsl_sort_smallest_index(xi_idx[i],nnearest,xerr,stride,nxi);// find the n nearest xi } return 0; } // xi varies slowly (each row), yi varies quickly (each col) int find_nearest(int nx,int xirows,int xicols,int xi_idx_below[],int yi_idx_below[],REAL x[],REAL y[],REAL xi[][xicols],REAL yi[][xicols]){ size_t nearest2_idxs[2]; double nearest2_vals[2],xerr[xirows],yerr[xirows]; int i,j; for(i=0;i<nx;i++){ // loop for each x,y for(j=0;j<xirows;j++){ // find the error between x and all the xi xerr[j]=fabs(x[i]-xi[j][0]); } gsl_sort_smallest_index(nearest2_idxs,2,xerr,1,xirows);// find the two nearest xi nearest2_vals[0] = xi[nearest2_idxs[0]][0]; nearest2_vals[1] = xi[nearest2_idxs[1]][0]; xi_idx_below[i] = MIN_IDX(nearest2_idxs,nearest2_vals); // this is the nearest xi less than x for(j=0;j<xicols;j++){ // find the error between y and all the yi yerr[j]=fabs(y[i]-yi[0][j]); } gsl_sort_smallest_index(nearest2_idxs,2,yerr,1,xicols);// find the two nearest yi nearest2_vals[0] = yi[0][nearest2_idxs[0]]; nearest2_vals[1] = yi[0][nearest2_idxs[1]]; yi_idx_below[i] = MIN_IDX(nearest2_idxs,nearest2_vals); // this is the nearest yi less than y } return 0; } // limitation: assumes regularly-spaced grids xi and yi int interpReg2d(int nx,int xirows,int xicols,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[][xicols],REAL yi[][xicols],REAL zi[][xicols],REAL wi[][xicols]){ int i,j; // form the matrix of of slopes for y interpolation double slopeziyi[xirows][xicols-1],slopewiyi[xirows][xicols-1]; double invdi; for(i=0;i<xirows;i++){ for(j=0;j<xicols-1;j++){ invdi = 1.0/(yi[i][j+1]-yi[i][j]); slopeziyi[i][j] = (zi[i][j+1]-zi[i][j])*invdi; slopewiyi[i][j] = (wi[i][j+1]-wi[i][j])*invdi; } } // find the indices of the nearest points (xi[i],yi[j]); note always exists (xi[i+1],yi[j+1]) int xi_idx_below[nx],yi_idx_below[nx]; find_nearest(nx,xirows,xicols,xi_idx_below,yi_idx_below,x,y,xi,yi); // for fixed x, interpolate in y double a,b,dist_y_yi,x_frac; for(i=0;i<nx;i++){ dist_y_yi=y[i]-yi[0][yi_idx_below[i]]; x_frac = (x[i]-xi[xi_idx_below[i]][0])/(xi[xi_idx_below[i]+1][0]-xi[xi_idx_below[i]][0]); // compute z[i] // for fixed xi = i, interpolate in y between yi[j] and yi[j+1] a = slopeziyi[xi_idx_below[i]][yi_idx_below[i]]*dist_y_yi + zi[xi_idx_below[i]][yi_idx_below[i]]; // for fixed xi = i+1, interpolate in y between yi[j] and yi[j+1] b = slopeziyi[xi_idx_below[i]+1][yi_idx_below[i]]*dist_y_yi + zi[xi_idx_below[i]+1][yi_idx_below[i]]; // now interpolate in x between xi[i] and xi[i+1] z[i] = (b-a)*x_frac + a; // compute w[i] // for fixed xi = i, interpolate in y between yi[j] and yi[j+1] a = slopewiyi[xi_idx_below[i]][yi_idx_below[i]]*dist_y_yi + wi[xi_idx_below[i]][yi_idx_below[i]]; // for fixed xi = i+1, interpolate in y between yi[j] and yi[j+1] b = slopewiyi[xi_idx_below[i]+1][yi_idx_below[i]]*dist_y_yi + wi[xi_idx_below[i]+1][yi_idx_below[i]]; // now interpolate in x between xi[i] and xi[i+1] w[i] = (b-a)*x_frac + a; } return 0; }
{ "alphanum_fraction": 0.6171821306, "avg_line_length": 36.9915254237, "ext": "h", "hexsha": "21cfc1616cd0269155cfc0ccb62bc9772f9ec341", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2020-01-10T03:38:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-29T12:35:59.000Z", "max_forks_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "justthepython/Synthetic-Diagnostics-Platform", "max_forks_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236", "max_issues_repo_issues_event_max_datetime": "2016-05-11T17:18:36.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-11T12:58:00.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "justthepython/Synthetic-Diagnostics-Platform", "max_issues_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_line_length": 154, "max_stars_count": 5, "max_stars_repo_head_hexsha": "870120d3fd14b2a3c89c6e6e85625d1e9109a2de", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "LeiShi/Synthetic-Diagnostics-Platform", "max_stars_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_stars_repo_stars_event_max_datetime": "2021-02-24T02:47:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-16T22:08:19.000Z", "num_tokens": 4539, "size": 13095 }
#ifndef UTIL_H_ #define UTIL_H_ #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <time.h> /* * constants */ #define TYPE_REQ 1 #define TYPE_REQ_FOLLOW 2 #define TYPE_RES 0 #define NB_MBUF 8191 #define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM) #define MBUF_CACHE_SIZE 32 #define MAX_BURST_SIZE 32 #define MAX_LCORES 32 #define NB_RXD 128 // RX descriptors #define NB_TXD 512 // TX descriptors #define RX_QUEUE_PER_LCORE 4 #define IP_SRC "10.1.0.12" #define IP_DST "10.1.0.1" #define CLIENT_PORT 11234 #define SERVICE_PORT 1234 static const struct rte_eth_conf port_conf = { .rxmode = { .max_rx_pkt_len = ETHER_MAX_LEN, .split_hdr_size = 0, .header_split = 0, // Header Split disabled .hw_ip_checksum = 0, // IP checksum offload disabled .hw_vlan_filter = 0, // VLAN filtering disabled .jumbo_frame = 0, // Jumbo Frame Support disabled .hw_strip_crc = 0, // CRC stripped by hardware }, .txmode = { .mq_mode = ETH_MQ_TX_NONE, }, }; /* * custom types */ /********* Misc *********/ // Get current time in ns uint64_t get_cur_ns() { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); uint64_t t = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec; return t; } // For storing results typedef struct LatencyResults_ { uint64_t *sjrn_times; uint64_t *sjrn_times_short; uint64_t *sjrn_times_long; uint64_t *work_ratios; uint64_t *work_ratios_short; uint64_t *work_ratios_long; uint32_t (*queue_lengths)[3]; size_t count; size_t count_short; size_t count_long; } LatencyResults; /********* Distributions *********/ // Exponential Distribution typedef struct ExpDist_ { gsl_rng *r; double mu; uint64_t cur_ns; } ExpDist; void init_exp_dist(ExpDist *exp_dist, double mu) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc(T); uint64_t cur_ns = get_cur_ns(); ExpDist temp_exp_dist = {r, mu, cur_ns}; memcpy(exp_dist, &temp_exp_dist, sizeof(ExpDist)); } uint64_t exp_dist_next_arrival_ns(ExpDist *exp_dist) { exp_dist->cur_ns += gsl_ran_exponential(exp_dist->r, exp_dist->mu); return exp_dist->cur_ns; } uint64_t exp_dist_work_ns(ExpDist *exp_dist) { return gsl_ran_exponential(exp_dist->r, exp_dist->mu); } void free_exp_dist(const ExpDist *exp_dist) { gsl_rng_free(exp_dist->r); free((void *)exp_dist); } // Lognormal Distribution typedef struct LognormalDist_ { gsl_rng *r; double mu; double sigma; } LognormalDist; void init_lognormal_dist(LognormalDist *lognormal_dist, double mu, double sigma) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc(T); LognormalDist temp_lognormal_dist = {r, mu, sigma}; memcpy(lognormal_dist, &temp_lognormal_dist, sizeof(LognormalDist)); } uint64_t lognormal_dist_work_ns(LognormalDist *lognormal_dist) { return gsl_ran_lognormal(lognormal_dist->r, lognormal_dist->mu, lognormal_dist->sigma); } void free_lognormal_dist(LognormalDist *lognormal_dist) { gsl_rng_free(lognormal_dist->r); free((void *)lognormal_dist); } // Bimodal Distribution typedef struct BimodalDist_ { gsl_rng *r; uint64_t work_1; uint64_t work_2; double ratio; } BimodalDist; void init_bimodal_dist(BimodalDist *bimodal_dist, uint64_t work_1_ns, uint64_t work_2_ns, double ratio) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc(T); BimodalDist temp_bimodal_dist = {r, work_1_ns, work_2_ns, ratio}; memcpy(bimodal_dist, &temp_bimodal_dist, sizeof(BimodalDist)); } uint64_t bimodal_dist_work_ns(BimodalDist *bimodal_dist) { double num = gsl_ran_flat(bimodal_dist->r, 0.0, 1.0); if (num < bimodal_dist->ratio) { return bimodal_dist->work_1; } else { return bimodal_dist->work_2; } } void free_bimodal_dist(BimodalDist *bimodal_dist) { gsl_rng_free(bimodal_dist->r); free((void *)bimodal_dist); } // Trimodal Distribution typedef struct TrimodalDist_ { gsl_rng *r; uint64_t work_1; uint64_t work_2; uint64_t work_3; double ratio1; double ratio2; } TrimodalDist; void init_trimodal_dist(TrimodalDist *trimodal_dist, uint64_t work_1_ns, uint64_t work_2_ns, uint64_t work_3_ns, double ratio1, double ratio2) { gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *r = gsl_rng_alloc(T); TrimodalDist temp_trimodal_dist = { r, work_1_ns, work_2_ns, work_3_ns, ratio1, ratio2, }; memcpy(trimodal_dist, &temp_trimodal_dist, sizeof(TrimodalDist)); } uint64_t trimodal_dist_work_ns(TrimodalDist *trimodal_dist) { double num = gsl_ran_flat(trimodal_dist->r, 0.0, 1.0); if (num < trimodal_dist->ratio1) { return trimodal_dist->work_1; } else if (num < trimodal_dist->ratio1 + trimodal_dist->ratio2) { return trimodal_dist->work_2; } else { return trimodal_dist->work_3; } } void free_trimodal_dist(TrimodalDist *trimodal_dist) { gsl_rng_free(trimodal_dist->r); free((void *)trimodal_dist); } typedef struct Message_ { uint8_t recir_flag; uint8_t core_idx; uint8_t type; uint16_t seq_num; uint32_t queue_length[3]; uint16_t client_id; uint32_t req_id; uint32_t pkts_length; uint64_t run_ns; uint64_t gen_ns; } __attribute__((__packed__)) Message; struct mbuf_table { uint32_t len; struct rte_mbuf *m_table[MAX_BURST_SIZE]; }; struct lcore_configuration { uint32_t vid; // virtual core id uint32_t port; // one port uint32_t tx_queue_id; // one TX queue uint32_t n_rx_queue; // number of RX queues uint32_t rx_queue_list[RX_QUEUE_PER_LCORE]; // list of RX queues struct mbuf_table tx_mbufs; // mbufs to hold TX queue } __rte_cache_aligned; /* * global variables */ uint32_t enabled_port_mask = 1; uint32_t enabled_ports[RTE_MAX_ETHPORTS]; uint32_t n_enabled_ports = 0; uint32_t n_rx_queues = 0; uint32_t n_lcores = 0; struct rte_mempool *pktmbuf_pool = NULL; struct ether_addr port_eth_addrs[RTE_MAX_ETHPORTS]; struct lcore_configuration lcore_conf[MAX_LCORES]; uint8_t header_template[sizeof(struct ether_hdr) + sizeof(struct ipv4_hdr) + sizeof(struct udp_hdr)]; /* * functions for generation */ // send packets, drain TX queue static void send_pkt_burst(uint32_t lcore_id) { struct lcore_configuration *lconf = &lcore_conf[lcore_id]; struct rte_mbuf **m_table = (struct rte_mbuf **)lconf->tx_mbufs.m_table; uint32_t n = lconf->tx_mbufs.len; uint32_t ret = rte_eth_tx_burst(lconf->port, lconf->tx_queue_id, m_table, lconf->tx_mbufs.len); if (unlikely(ret < n)) { do { rte_pktmbuf_free(m_table[ret]); } while (++ret < n); } lconf->tx_mbufs.len = 0; } // put packet into TX queue static void enqueue_pkt(uint32_t lcore_id, struct rte_mbuf *mbuf) { struct lcore_configuration *lconf = &lcore_conf[lcore_id]; lconf->tx_mbufs.m_table[lconf->tx_mbufs.len++] = mbuf; // enough packets in TX queue if (unlikely(lconf->tx_mbufs.len == MAX_BURST_SIZE)) { send_pkt_burst(lcore_id); } } /* * functions for initialization */ // init header template static void init_header_template(void) { memset(header_template, 0, sizeof(header_template)); struct ether_hdr *eth = (struct ether_hdr *)header_template; struct ipv4_hdr *ip = (struct ipv4_hdr *)((uint8_t *)eth + sizeof(struct ether_hdr)); struct udp_hdr *udp = (struct udp_hdr *)((uint8_t *)ip + sizeof(struct ipv4_hdr)); uint32_t pkt_len = sizeof(header_template) + sizeof(Message); // eth header eth->ether_type = rte_cpu_to_be_16(ETHER_TYPE_IPv4); struct ether_addr src_addr = { .addr_bytes = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; struct ether_addr dst_addr = { .addr_bytes = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55}}; ether_addr_copy(&src_addr, &eth->s_addr); ether_addr_copy(&dst_addr, &eth->d_addr); // ip header char src_ip[] = IP_SRC; char dst_ip[] = IP_DST; int st1 = inet_pton(AF_INET, src_ip, &(ip->src_addr)); int st2 = inet_pton(AF_INET, dst_ip, &(ip->dst_addr)); if (st1 != 1 || st2 != 1) { fprintf(stderr, "inet_pton() failed.Error message: %s %s", strerror(st1), strerror(st2)); exit(EXIT_FAILURE); } ip->total_length = rte_cpu_to_be_16(pkt_len - sizeof(struct ether_hdr)); ip->version_ihl = 0x45; ip->type_of_service = 0; ip->packet_id = 0; ip->fragment_offset = 0; ip->time_to_live = 64; ip->next_proto_id = IPPROTO_UDP; uint32_t ip_cksum; uint16_t *ptr16 = (uint16_t *)ip; ip_cksum = 0; ip_cksum += ptr16[0]; ip_cksum += ptr16[1]; ip_cksum += ptr16[2]; ip_cksum += ptr16[3]; ip_cksum += ptr16[4]; ip_cksum += ptr16[6]; ip_cksum += ptr16[7]; ip_cksum += ptr16[8]; ip_cksum += ptr16[9]; ip_cksum = ((ip_cksum & 0xffff0000) >> 16) + (ip_cksum & 0x0000ffff); if (ip_cksum > 65535) { ip_cksum -= 65535; } ip_cksum = (~ip_cksum) & 0x0000ffff; if (ip_cksum == 0) { ip_cksum = 0xffff; } ip->hdr_checksum = (uint16_t)ip_cksum; // udp header udp->src_port = htons(CLIENT_PORT); udp->dst_port = htons(SERVICE_PORT); udp->dgram_len = rte_cpu_to_be_16(pkt_len - sizeof(struct ether_hdr) - sizeof(struct ipv4_hdr)); udp->dgram_cksum = 0; } // check link status static void check_link_status(void) { const uint32_t check_interval_ms = 100; const uint32_t check_iterations = 90; uint32_t i, j; struct rte_eth_link link; for (i = 0; i < check_iterations; i++) { uint8_t all_ports_up = 1; for (j = 0; j < n_enabled_ports; j++) { uint32_t portid = enabled_ports[j]; memset(&link, 0, sizeof(link)); rte_eth_link_get_nowait(portid, &link); if (link.link_status) { printf("\tport %u link up - speed %u Mbps - %s\n", portid, link.link_speed, (link.link_duplex == ETH_LINK_FULL_DUPLEX) ? "full-duplex" : "half-duplex"); } else { all_ports_up = 0; } } if (all_ports_up == 1) { printf("check link status finish: all ports are up\n"); break; } else if (i == check_iterations - 1) { printf("check link status finish: not all ports are up\n"); } else { rte_delay_ms(check_interval_ms); } } } // initialize all status static void init(void) { uint32_t i, j; // create mbuf pool printf("create mbuf pool\n"); pktmbuf_pool = rte_mempool_create( "mbuf_pool", NB_MBUF, MBUF_SIZE, MBUF_CACHE_SIZE, sizeof(struct rte_pktmbuf_pool_private), rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL, rte_socket_id(), 0); if (pktmbuf_pool == NULL) { rte_exit(EXIT_FAILURE, "cannot init mbuf pool\n"); } // determine available ports printf("create enabled ports\n"); uint32_t n_total_ports = 0; n_total_ports = rte_eth_dev_count(); if (n_total_ports == 0) { rte_exit(EXIT_FAILURE, "cannot detect ethernet ports\n"); } if (n_total_ports > RTE_MAX_ETHPORTS) { n_total_ports = RTE_MAX_ETHPORTS; } // get info for each enabled port struct rte_eth_dev_info dev_info; n_enabled_ports = 0; printf("\tports: "); for (i = 0; i < n_total_ports; i++) { if ((enabled_port_mask & (1 << i)) == 0) { continue; } enabled_ports[n_enabled_ports++] = i; rte_eth_dev_info_get(i, &dev_info); printf("%u ", i); } printf("\n"); // find number of active lcores printf("create enabled cores\n\tcores: "); n_lcores = 0; for (i = 0; i < MAX_LCORES; i++) { if (rte_lcore_is_enabled(i)) { n_lcores++; printf("%u ", i); } } // ensure numbers are correct if (n_lcores % n_enabled_ports != 0) { rte_exit(EXIT_FAILURE, "number of cores (%u) must be multiple of ports (%u)\n", n_lcores, n_enabled_ports); } uint32_t rx_queues_per_lcore = RX_QUEUE_PER_LCORE; uint32_t rx_queues_per_port = rx_queues_per_lcore * n_lcores / n_enabled_ports; uint32_t tx_queues_per_port = n_lcores / n_enabled_ports; if (rx_queues_per_port < rx_queues_per_lcore) { rte_exit(EXIT_FAILURE, "rx_queues_per_port (%u) must be >= rx_queues_per_lcore (%u)\n", rx_queues_per_port, rx_queues_per_lcore); } // assign each lcore some RX queues and a port printf("set up %d RX queues per port and %d TX queues per port\n", rx_queues_per_port, tx_queues_per_port); uint32_t portid_offset = 0; uint32_t rx_queue_id = 0; uint32_t tx_queue_id = 0; uint32_t vid = 0; for (i = 0; i < MAX_LCORES; i++) { if (rte_lcore_is_enabled(i)) { lcore_conf[i].vid = vid++; lcore_conf[i].n_rx_queue = rx_queues_per_lcore; for (j = 0; j < rx_queues_per_lcore; j++) { lcore_conf[i].rx_queue_list[j] = rx_queue_id++; } lcore_conf[i].port = enabled_ports[portid_offset]; lcore_conf[i].tx_queue_id = tx_queue_id++; if (rx_queue_id % rx_queues_per_port == 0) { portid_offset++; rx_queue_id = 0; tx_queue_id = 0; } } } // initialize each port for (portid_offset = 0; portid_offset < n_enabled_ports; portid_offset++) { uint32_t portid = enabled_ports[portid_offset]; int32_t ret = rte_eth_dev_configure(portid, rx_queues_per_port, tx_queues_per_port, &port_conf); if (ret < 0) { rte_exit(EXIT_FAILURE, "cannot configure device: err=%d, port=%u\n", ret, portid); } rte_eth_macaddr_get(portid, &port_eth_addrs[portid]); // initialize RX queues for (i = 0; i < rx_queues_per_port; i++) { ret = rte_eth_rx_queue_setup( portid, i, NB_RXD, rte_eth_dev_socket_id(portid), NULL, pktmbuf_pool); if (ret < 0) { rte_exit(EXIT_FAILURE, "rte_eth_rx_queue_setup: err=%d, port=%u\n", ret, portid); } } // initialize TX queues for (i = 0; i < tx_queues_per_port; i++) { ret = rte_eth_tx_queue_setup(portid, i, NB_TXD, rte_eth_dev_socket_id(portid), NULL); if (ret < 0) { rte_exit(EXIT_FAILURE, "rte_eth_tx_queue_setup: err=%d, port=%u\n", ret, portid); } } // start device ret = rte_eth_dev_start(portid); if (ret < 0) { rte_exit(EXIT_FAILURE, "rte_eth_dev_start: err=%d, port=%u\n", ret, portid); } rte_eth_promiscuous_enable(portid); char mac_buf[ETHER_ADDR_FMT_SIZE]; ether_format_addr(mac_buf, ETHER_ADDR_FMT_SIZE, &port_eth_addrs[portid]); printf("initiaze queues and start port %u, MAC address:%s\n", portid, mac_buf); } if (!n_enabled_ports) { rte_exit(EXIT_FAILURE, "all available ports are disabled. Please set portmask.\n"); } check_link_status(); init_header_template(); } /* * misc */ static uint64_t timediff_in_us(uint64_t new_t, uint64_t old_t) { return (new_t - old_t) * 1000000UL / rte_get_tsc_hz(); } #endif // UTIL_H_
{ "alphanum_fraction": 0.6599243116, "avg_line_length": 28.5932835821, "ext": "h", "hexsha": "c891bc64c58f0d295eb026e9d5175b461a9b7fd2", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-05-27T03:07:26.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-19T16:28:10.000Z", "max_forks_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "netx-repo/RackSched", "max_forks_repo_path": "client_code/r2p2-client/util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "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": "netx-repo/RackSched", "max_issues_repo_path": "client_code/r2p2-client/util.h", "max_line_length": 80, "max_stars_count": 15, "max_stars_repo_head_hexsha": "ba3a4c4dfc100701df4733462dc83dec0d6851fd", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "netx-repo/RackSched", "max_stars_repo_path": "client_code/r2p2-client/util.h", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:14:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-30T18:20:39.000Z", "num_tokens": 4541, "size": 15326 }
// // mcmc_solar.c // // // Created by Juan Pablo Molano on 11/11/15. // // #include <stdio.h> #include <stdlib.h> #include <time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> #define USAGE "./mcmc_solar.x n_burn n_steps" //------------------------------------------------------------------------------------------------------------ float *load_matrix(char *filename, int *n, int *m); void get_data( float *array , float *x, int n_row); float *reserva(int n); void print_data(float *array, float *array2, float *array3, float *array4 , float *array5 , float *array6 , float *array7 , float *array8, int n_puntos); void get_patch( float *array, float *x , int n_row); void my_model( float *x_obs, float *array, float a, float b, float c , float d, int n_row); float likelihood(float *y_obs, float *y_model, int n_row); int min_likelihood( float *array , int n_row); //------------------------------------------------------------------------------------------------------------ int main(int argc, char **argv){ float *matrix , *tim, *man, *count, *a_walk, *b_walk, *c_walk, *d_walk, *l_walk, *y_init, *y_prime, *best_y; srand48(time(NULL)); float a_prime, b_prime, c_prime, d_prime, l_prime, l_init, gamma, alpha, beta , best_a , best_b, best_c, best_d; int n_row, n_cols , i, rlin = 0; a_walk = reserva(atof(argv[1])+atof(argv[2])); b_walk = reserva(atof(argv[1])+atof(argv[2])); c_walk = reserva(atof(argv[1])+atof(argv[2])); d_walk = reserva(atof(argv[1])+atof(argv[2])); l_walk = reserva(atof(argv[1])+atof(argv[2])); y_init = reserva(n_row); y_prime = reserva(n_row); a_walk[0] = drand48(); b_walk[0] = drand48(); c_walk[0] = drand48(); d_walk[0] = drand48(); matrix = load_matrix( "sol.dat" , &n_row, &n_cols); man = reserva( n_row); tim = reserva(n_row); man = reserva(n_row); best_y = reserva( n_row); get_data( matrix , tim , n_row); get_patch( matrix , man , n_row); for (i=0;i<n_row;i++) { if (man[i] == -99) { man[i] = 0.0; } } my_model( tim , y_init , a_walk[0] , b_walk[0] , c_walk[0] , d_walk[0] , n_row ); l_walk[0] = likelihood( man , y_init, n_row); const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i=0; i < atof(argv[1]) + atof(argv[2]); i++) { a_prime = gsl_ran_gaussian(r, 0.1) + a_walk[i]; b_prime = gsl_ran_gaussian(r, 0.1) + b_walk[i]; c_prime = gsl_ran_gaussian(r, 0.1) + c_walk[i]; d_prime = gsl_ran_gaussian(r, 0.1) + d_walk[i]; my_model( tim, y_init, a_walk[i], b_walk[i], c_walk[i], d_walk[i], n_row); my_model(tim, y_prime ,a_prime, b_prime, c_prime, d_prime, n_row); l_prime = likelihood( man, y_prime , n_row); l_init = likelihood( man, y_init , n_row); gamma = l_init - l_prime; if (gamma>=0.0) { a_walk[i+1] = a_prime; b_walk[i+1] = b_prime; c_walk[i+1] = c_prime; d_walk[i+1] = d_prime; l_walk[i+1] = l_prime; } else{ beta = drand48(); alpha = exp(gamma); if (beta <= alpha) { a_walk[i+1] = a_prime; b_walk[i+1] = b_prime; c_walk[i+1] = c_prime; d_walk[i+1] = d_prime; l_walk[i+1] = l_prime; } else{ a_walk[i+1] = a_walk[i]; b_walk[i+1] = b_walk[i]; c_walk[i+1] = c_walk[i]; d_walk[i+1] = d_walk[i]; l_walk[i+1] = l_init; } } } i = min_likelihood( l_walk , n_row); best_a = a_walk[i]; best_b = b_walk[i]; best_c = c_walk[i]; best_d = d_walk[i]; my_model( tim , best_y , best_a, best_b , best_c , best_d , n_row); print_data( tim , man, l_walk , a_walk , b_walk , c_walk , d_walk , best_y, n_row); gsl_rng_free (r); return 0; } //------------------------------------------------------------------------------------------------------------ float *load_matrix(char *filename, int *n, int *m){ float *matrix; FILE *in; int n_row = 4632, n_cols = 5; int i; int j; if(!(in=fopen(filename, "r"))){ printf("Problem opening file %s\n", filename); exit(1); } matrix = malloc(n_row * n_cols * sizeof(float)); for(i=0;i<n_row;i++){ for(j=0;j<n_cols;j++){ fscanf(in, "%f", &matrix[i*n_cols + j]); } } *n = n_row; *m = n_cols; return matrix; } //------------------------------------------------------------------------------------------------------------ void get_data( float *array , float *x , int n_row){ int i,j; for(i=0;i<n_row;i++){ x[i] = array[i*5] + array[i*5 + 1]/12 + array[i*5 + 2]/365; } } //------------------------------------------------------------------------------------------------------------ void get_patch( float *array, float *x , int n_row){ int i,j; for(i=0;i<n_row;i++){ x[i] = array[i*5 + 3]; } } //------------------------------------------------------------------------------------------------------------ float *reserva(int n){ float *array; int i; if(!(array = malloc(n * sizeof(float)))){ printf("Problema en reserva\n"); exit(1); } for(i=0;i<n ;i++){ array[i] = 0.0; } return array; } //------------------------------------------------------------------------------------------------------------ void print_data(float *array, float *array2 , float *array3 , float *array4 , float *array5 , float *array6, float *array7, float *array8 , int n_puntos){ int i; for(i=0;i<n_puntos;i++){ printf("%f \t %f \t %f \t %f \t %f \t %f \t %f \t %f \n", array[i] , array2[i] , array3[i] , array4[i] , array5[i] , array6[i], array7[i], array8[i]); } } //------------------------------------------------------------------------------------------------------------ float likelihood(float *y_obs, float *y_model, int n_row){ int i; float c=0; for (i=0; i<n_row; i++) { c = c + ( y_obs[i] - y_model[i]); } c = (1.0/2.0)*pow(c,2); return c; } //------------------------------------------------------------------------------------------------------------ void my_model( float *x_obs, float *array , float a, float b, float c , float d, int n_row){ int i; for (i=0; i<n_row; i++) { array[i] = a*cos((2*3.141592653589793/d)*x_obs[i] + b) + c; } } //------------------------------------------------------------------------------------------------------------ int min_likelihood( float *array , int n_row){ int i; int ind = 0; for(i = 1; i < n_row; i ++){ if ( array[i] < ind) { ind = i; } } return ind; }
{ "alphanum_fraction": 0.4328808446, "avg_line_length": 27.1115241636, "ext": "c", "hexsha": "22af08b2800513687a9365020246da89cbd47c3c", "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": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JuanMolano/Hw7", "max_forks_repo_path": "solar/mcmc_solar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa", "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": "JuanMolano/Hw7", "max_issues_repo_path": "solar/mcmc_solar.c", "max_line_length": 158, "max_stars_count": null, "max_stars_repo_head_hexsha": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JuanMolano/Hw7", "max_stars_repo_path": "solar/mcmc_solar.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2004, "size": 7293 }