Search is not available for this dataset
text
string
meta
dict
/** * * @file testing_zgetmi.c * * PLASMA testings module * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * This program tests the implementation of the inplace format * conversion based on the GKK algorithm by Gustavson, Karlsson, * Kagstrom. * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * * @precisions normal z -> c d s * * Purpose : * Test the in place matrix transposition with the 6 different * formats of input. **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <lapacke.h> #include <plasma.h> #include "testing_zmain.h" static int check_solution(int m, int n, int mb, int nb, PLASMA_Complex64_t *A, PLASMA_Complex64_t *B, int (*mapA)(int, int, int, int, int, int)) { int i, j; for( j=0; j<n; j++) { for (i=0; i<m; i++) { if (A[ mapA(m, n, mb, nb, i, j) ] != B[ mapA(n, m, mb, nb, j, i) ] ) { return -1; } } } return 0; } int testing_zgetmi(int argc, char **argv){ PLASMA_Complex64_t *A, *B; int m, n, mb, nb; int i, ret, size; /* Check for number of arguments*/ if (argc != 4){ USAGE("GETMI", "M N MB NB ntdbypb with \n", " - M : the number of rows of the matrix \n" " - N : the number of columns of the matrix \n" " - MB : the number of rows of each block \n" " - NB : the number of columns of each block \n"); return -1; } m = atoi(argv[0]); n = atoi(argv[1]); mb = atoi(argv[2]); nb = atoi(argv[3]); size = m*n*sizeof(PLASMA_Complex64_t); A = (PLASMA_Complex64_t *)malloc(size); B = (PLASMA_Complex64_t *)malloc(size); LAPACKE_zlarnv_work(1, ISEED, m*n, A); for(i=0; i<6; i++) { memcpy(B, A, size); printf(" - TESTING ZGETMI (%4s) ...", formatstr[i]); ret = PLASMA_zgetmi( m, n, A, format[i], mb, nb ); if (ret != PLASMA_SUCCESS) { printf("Failed\n"); continue; } if ( check_solution(m, n, mb, nb, B, A, (int (*)(int, int, int, int, int, int))formatmap[i]) == 0 ) printf("............ PASSED !\n"); else printf("... FAILED !\n"); } free( A ); free( B ); return 0; }
{ "alphanum_fraction": 0.5142972211, "avg_line_length": 26.414893617, "ext": "c", "hexsha": "020c5fccb772cdb44cbc3c0b935cc1f4593c5e5e", "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_zgetmi.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_zgetmi.c", "max_line_length": 87, "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_zgetmi.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 760, "size": 2483 }
#include<iostream> #include<string.h> #include<vector> #include<set> #include<algorithm> #include<fstream> #include<cstdlib> #include<time.h> #include<iterator> #include<sys/time.h> #include<stdio.h> #include<numeric> #include <stdexcept> #include<math.h> #include<limits> #include<random> #include<ctime> #include<map> #include<omp.h> #include <gsl/gsl_rng.h> #include<pthread.h> #include<chrono> extern int GenNum; extern std::vector<int> ArgPop; //double PopulationFitnessTable = new double[numberofSNPs*diploidSize]; extern int popSize; extern double RecombRate; extern double MutationRate; extern int m; extern int epiflag; extern int ChromLen;
{ "alphanum_fraction": 0.7296511628, "avg_line_length": 21.5, "ext": "h", "hexsha": "788d04b3927cce11e947cc79aa985fd223e0691e", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2018-01-05T18:00:15.000Z", "max_forks_repo_forks_event_min_datetime": "2016-09-28T09:50:26.000Z", "max_forks_repo_head_hexsha": "c079b17cba77a52ee84dce8950fd40438b597f6b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "SimRA-ARG/SimRA", "max_forks_repo_path": "fwdSimRa/headers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c079b17cba77a52ee84dce8950fd40438b597f6b", "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": "SimRA-ARG/SimRA", "max_issues_repo_path": "fwdSimRa/headers.h", "max_line_length": 72, "max_stars_count": 13, "max_stars_repo_head_hexsha": "c079b17cba77a52ee84dce8950fd40438b597f6b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "SimRA-ARG/SimRA", "max_stars_repo_path": "fwdSimRa/headers.h", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:16:41.000Z", "max_stars_repo_stars_event_min_datetime": "2016-03-22T10:34:34.000Z", "num_tokens": 165, "size": 688 }
#ifndef POINT3_H__ #define POINT3_H__ #include <cassert> #include <algorithm> #include <iostream> #include <vector> #include <cmath> #include <float.h> /* If you want to use the methods that project 2x2 or 3x3 matrices onto the closest 2D/3D rotation, or similarity, or rotation restricted to a 2D plane in 3D, you need to use a Singular Values Decomposition. We provide implementation of this, using the GNU Scientific Library. Uncomment #define __USE_GSL_FOR_MAT33 */ #define __USE_GSL_FOR_MAT33 #define __USE_OPENGL_METHODS_ON_POINT3 #ifdef __USE_GSL_FOR_MAT33 #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> // you need to add the following libraries to your project : gsl, gslcblas #endif #ifdef __USE_OPENGL_METHODS_ON_POINT3 #include <GL/gl.h> #endif template< typename T > class point3 { public: typedef T type_t; point3< T >( T x_ , T y_ , T z_) { v[0] = x_; v[1] = y_; v[2] = z_; } template< class point_t > point3< T >( point_t const & p ) { v[0] = (T)(p[0]); v[1] = (T)(p[1]); v[2] = (T)(p[2]); } point3< T >(){v[0] = 0; v[1] = 0; v[2] = 0;} inline T x() const {return v[0];} inline T y() const {return v[1];} inline T z() const {return v[2];} inline T operator [] (unsigned int c) const { return v[c]; } inline T & operator [] (unsigned int c) { return v[c]; } static point3<T> Zero() { return point3<T>(0,0,0); } void setZero() { v[0] = 0; v[1] = 0; v[2] = 0; } // You cannot template over anything here, but maybe you could template over typename T2 for operator += (const point3< T2 > & other) void operator += (const point3< T > & other) { v[0] += other.x(); v[1] += other.y(); v[2] += other.z(); } void operator -= (const point3< T > & other) { v[0] -= other.x(); v[1] -= other.y(); v[2] -= other.z(); } // This is going to create problems if the compiler needs to resolve umbiguous casts, but it's the cleaner way to do it void operator *= (int s) { v[0] *= s; v[1] *= s; v[2] *= s; } void operator *= (unsigned int s) { v[0] *= s; v[1] *= s; v[2] *= s; } void operator *= (float s) { v[0] *= s; v[1] *= s; v[2] *= s; } void operator *= (double s) { v[0] *= s; v[1] *= s; v[2] *= s; } void operator /= (int s) { v[0] /= s; v[1] /= s; v[2] /= s; } void operator /= (unsigned int s) { v[0] /= s; v[1] /= s; v[2] /= s; } void operator /= (float s) { v[0] /= s; v[1] /= s; v[2] /= s; } void operator /= (double s) { v[0] /= s; v[1] /= s; v[2] /= s; } point3<T> getOrthogonal() const { if( v[0] == 0 ) { return point3<T>( 0 , v[2] , -v[1] ); } else if( v[1] == 0 ) { return point3<T>( v[2] , 0 , -v[0] ); } return point3<T>( v[1] , -v[0] , 0 ); } T sqrnorm() const { return v[0]*v[0]+v[1]*v[1]+v[2]*v[2]; } T norm() const { return sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); } void normalize() { T _n = norm(); v[0] /= _n; v[1] /= _n; v[2] /= _n; } void setNorm( T newNorm ) { T _factor = newNorm / norm(); v[0] *= _factor; v[1] *= _factor; v[2] *= _factor; } inline static T dot( const point3< T > & p1 , const point3< T > & p2 ) { return p1.x() * p2.x() + p1.y() * p2.y() + p1.z() * p2.z(); } inline static point3< T > cross( const point3< T > & p1 , const point3< T > & p2 ) { return point3< T >( p1.y() * p2.z() - p1.z() * p2.y(), p1.z() * p2.x() - p1.x() * p2.z(), p1.x() * p2.y() - p1.y() * p2.x() ); } // inline static point3< T > min ( const point3< T > & p , const point3< T > & p2 ) // { // return point3< T >( std::min( p2[0] , p[0] ), // std::min( p2[1] , p[1] ), // std::min( p2[2] , p[2] ) ); // } // inline static point3< T > max ( point3< T > const & p , point3< T > const & p2 ) // { // return point3< T >( std::max( p2[0] , p[0] ), // std::max( p2[1] , p[1] ), // std::max( p2[2] , p[2] ) ); // } template< class point_t1 , class point_t2 > inline static point3< T > min ( const point_t1 & p , const point_t2 & p2 ) { return point3< T >( std::min( (T)(p2[0]) , (T)(p[0]) ), std::min( (T)(p2[1]) , (T)(p[1]) ), std::min( (T)(p2[2]) , (T)(p[2]) ) ); } template< class point_t1 , class point_t2 > inline static point3< T > max ( const point_t1 & p , const point_t2 & p2 ) { return point3< T >( std::max( (T)(p2[0]) , (T)(p[0]) ), std::max( (T)(p2[1]) , (T)(p[1]) ), std::max( (T)(p2[2]) , (T)(p[2]) ) ); } inline static point3< T > Rand ( point3< T > const & p , point3< T > const & p2 ) { T rx = p[0] + (p2[0] - p[0]) * (float)(rand()) / (float)( RAND_MAX ); T ry = p[1] + (p2[1] - p[1]) * (float)(rand()) / (float)( RAND_MAX ); T rz = p[2] + (p2[2] - p[2]) * (float)(rand()) / (float)( RAND_MAX ); return point3<T>( rx , ry , rz ); } inline static point3< T > Rand ( double randMagnitude ) { T rx = randMagnitude * (2.0*(float)(rand()) / (float)( RAND_MAX ) - 1.0); T ry = randMagnitude * (2.0*(float)(rand()) / (float)( RAND_MAX ) - 1.0); T rz = randMagnitude * (2.0*(float)(rand()) / (float)( RAND_MAX ) - 1.0); return point3<T>( rx , ry , rz ); } // inline static point3< T > RandOrientation ( ) // { // T rx = -1.f + 2.f * (float)(rand()) / (float)( RAND_MAX ); // T ry = -1.f + 2.f * (float)(rand()) / (float)( RAND_MAX ); // T rz = -1.f + 2.f * (float)(rand()) / (float)( RAND_MAX ); // point3<T> orientation( rx , ry , rz ); // orientation.normalize(); // return orientation; // } // Choose z uniformly distributed in [-1,1]. // Choose t uniformly distributed on [0, 2*pi). // Let r = sqrt(1-z^2). // Let x = r * cos(t). // Let y = r * sin(t). inline static point3< T > RandOrientation ( ) { T zz = -1.f + 2.f * (float)(rand()) / (float)( RAND_MAX ); T tt = 2.f * M_PI * (float)(rand()) / (float)( RAND_MAX ); T rr = sqrt( 1.0 - zz*zz ); T xx = rr * cos(tt); T yy = rr * sin(tt); return point3<T>( xx , yy , zz ); } inline static point3< T > RandInBox ( double boxHalfSide = 1.0 ) { T xx = boxHalfSide*(-1.0 + 2.0 * (double)(rand()) / (double)( RAND_MAX )); T yy = boxHalfSide*(-1.0 + 2.0 * (double)(rand()) / (double)( RAND_MAX )); T zz = boxHalfSide*(-1.0 + 2.0 * (double)(rand()) / (double)( RAND_MAX )); return point3<T>( xx , yy , zz ); } point3<T> direction() const { T n = norm(); return *this/n; } static T getAngleAroundAxis( point3<T> const & srcVector , point3<T> const & rotatedVector , point3<T> const & axis ) { // double angle = atan2( std::max<double>(-1.0 , std::min<double>( 1.0 , point3<T>::cross(srcVector , rotatedVector).norm() ) ) , // std::max<double>(-1.0 , std::min<double>( 1.0 , point3<T>::dot(srcVector , rotatedVector) ) )); // aie aie aie aie aie aie aie aie... double angle = atan2( point3<T>::cross(srcVector , rotatedVector).norm() , point3<T>::dot(srcVector , rotatedVector) ); if( point3<T>::dot(point3<T>::cross(srcVector , rotatedVector) , axis) < 0.0 ) angle = -angle; return angle; } bool isnan() const { return std::isnan(v[0]) || std::isnan(v[1]) || std::isnan(v[2]); } inline static void glVertex( point3< T > const & p ) { glVertex3f( p[0],p[1],p[2] ); } inline static void glNormal( point3< T > const & p ) { glNormal3f( p[0],p[1],p[2] ); } void glVertex() const { glVertex3f( v[0],v[1],v[2] ); } void glNormal() const { glNormal3f( v[0],v[1],v[2] ); } private: T v[3]; }; template< typename T > inline point3< T > operator + (const point3< T > & p1 , const point3< T > & p2 ) { return point3< T >( p1.x() + p2.x() , p1.y() + p2.y() , p1.z() + p2.z() ); } template< typename T > inline point3< T > operator - (const point3< T > & p1 , const point3< T > & p2 ) { return point3< T >( p1.x() - p2.x() , p1.y() - p2.y() , p1.z() - p2.z() ); } template< typename T > inline point3< T > operator - (const point3< T > & p2 ) { return point3< T >( - p2.x() , - p2.y() , - p2.z() ); } template< typename T > inline point3< T > operator * (const point3< T > & p , int s) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator * (const point3< T > & p , float s) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator * (const point3< T > & p , double s) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator * ( int s , const point3< T > & p ) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator * ( float s , const point3< T > & p ) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator * ( double s , const point3< T > & p ) { return point3< T >( s*p.x() , s*p.y() , s*p.z() ); } template< typename T > inline point3< T > operator / (const point3< T > & p , int s) { return point3< T >( p.x()/s , p.y()/s , p.z()/s ); } template< typename T > inline point3< T > operator / (const point3< T > & p , float s) { return point3< T >( p.x()/s , p.y()/s , p.z()/s ); } template< typename T > inline point3< T > operator / (const point3< T > & p , double s) { return point3< T >( p.x()/s , p.y()/s , p.z()/s ); } template< typename T > inline T operator * (const point3< T > & p1 , const point3< T > & p2) { return p1.x() * p2.x() + p1.y() * p2.y() + p1.z() * p2.z(); } template< typename T > inline point3<T> operator % (const point3<T> & p1 , const point3<T> & p2) { return point3<T>::cross(p1,p2); } template< typename T > inline std::ostream & operator << (std::ostream & s , point3< T > const & p) { s << p[0] << " \t" << p[1] << " \t" << p[2]; return s; } typedef point3< float > point3f; typedef point3< double > point3d; inline double myAbs( const point3d & f ) { return f.norm(); } inline float myAbs( const point3f & f ) { return f.norm(); } namespace StochasticBoundingStruct{ // the 3 canonical axes + 2000 random orientations on the z-positive hemisphere. static double dirs[2003][3] = { { 1 , 0 , 0 } , { 0 , 1 , 0 } , { 0 , 0 , 1 } , { -0.385422 , 0.516128 , 0.764893 } , { 0.697097 , 0.110109 , 0.708471 } , { 0.311979 , 0.691569 , 0.651461 } , { -0.832093 , 0.481536 , 0.275217 } , { -0.572238 , 0.234887 , 0.78573 } , { -0.109098 , -0.971394 , 0.210928 } , { -0.902306 , 0.408123 , 0.138848 } , { -0.570128 , 0.632602 , 0.524185 } , { -0.66706 , -0.32457 , 0.670586 } , { 0.221621 , 0.376512 , 0.899513 } , { 0.0314351 , -0.920669 , 0.389077 } , { -0.674986 , 0.509768 , 0.533415 } , { 0.453828 , 0.177408 , 0.87325 } , { 0.752111 , 0.29876 , 0.587429 } , { -0.920397 , -0.328854 , 0.21148 } , { 0.109396 , -0.64581 , 0.75562 } , { -0.971678 , 0.144991 , 0.186598 } , { 0.801684 , 0.447118 , 0.396721 } , { 0.879867 , -0.353183 , 0.317956 } , { -0.0950819 , -0.0321161 , 0.994951 } , { 0.754686 , -0.608428 , 0.245486 } , { 0.777216 , -0.270578 , 0.568086 } , { -0.7292 , -0.217505 , 0.648814 } , { -0.925599 , 0.0634084 , 0.373158 } , { -0.0803568 , 0.968324 , 0.236416 } , { -0.641205 , 0.333491 , 0.691115 } , { 0.879154 , -0.475082 , 0.0372188 } , { 0.812369 , 0.459884 , 0.358556 } , { -0.751874 , -0.658148 , 0.0390828 } , { 0.676722 , -0.679121 , 0.284326 } , { -0.0675079 , 0.746549 , 0.661897 } , { 0.637238 , 0.328494 , 0.697151 } , { -0.83858 , 0.254731 , 0.481556 } , { 0.587564 , -0.428267 , 0.686553 } , { -0.55295 , -0.804897 , 0.215376 } , { 0.0526419 , -0.425982 , 0.903199 } , { -0.0897022 , -0.991671 , 0.0924214 } , { -0.619757 , 0.654863 , 0.432499 } , { -0.884142 , -0.166764 , 0.436444 } , { -0.77648 , 0.56425 , 0.280537 } , { 0.906532 , 0.0809475 , 0.414304 } , { 0.287072 , -0.706101 , 0.647311 } , { -0.610819 , -0.781133 , 0.129353 } , { -0.843402 , 0.493208 , 0.213117 } , { -0.854138 , -0.194333 , 0.482373 } , { -0.731727 , 0.356389 , 0.581001 } , { 0.747388 , -0.285504 , 0.599915 } , { 0.11617 , 0.0304004 , 0.992764 } , { -0.522105 , -0.826618 , 0.210022 } , { 0.109879 , -0.460211 , 0.880984 } , { -0.723265 , 0.5825 , 0.37092 } , { 0.636892 , -0.762517 , 0.11374 } , { -0.13995 , 0.956635 , 0.255468 } , { -0.710729 , 0.454106 , 0.537263 } , { 0.772457 , 0.497738 , 0.39442 } , { -0.647809 , -0.444059 , 0.618996 } , { 0.411236 , 0.455686 , 0.789452 } , { 0.950792 , 0.24793 , 0.185808 } , { 0.259714 , -0.790225 , 0.555061 } , { -0.970326 , -0.225514 , 0.0872409 } , { 0.0145111 , 0.740151 , 0.672285 } , { 0.654429 , 0.752727 , 0.0715813 } , { 0.76677 , -0.157146 , 0.622389 } , { 0.65972 , 0.383442 , 0.646329 } , { 0.715623 , 0.649749 , 0.256337 } , { -0.90427 , 0.34034 , 0.257809 } , { -0.173731 , 0.0844812 , 0.981163 } , { -0.517476 , -0.603214 , 0.60692 } , { -0.782505 , -0.174024 , 0.59783 } , { -0.99534 , -0.0242384 , 0.0933291 } , { -0.598719 , 0.760331 , 0.251856 } , { 0.0705489 , 0.594529 , 0.800974 } , { -0.205445 , -0.00853607 , 0.978631 } , { -0.0940051 , 0.884794 , 0.456401 } , { 0.126101 , 0.913963 , 0.385707 } , { 0.494095 , 0.623035 , 0.606381 } , { -0.0340296 , 0.310029 , 0.950118 } , { 0.42724 , 0.710798 , 0.558777 } , { 0.849255 , -0.239664 , 0.470454 } , { -0.567892 , 0.657388 , 0.495317 } , { -0.383365 , -0.354398 , 0.852897 } , { -0.799306 , -0.459051 , 0.387791 } , { -0.32595 , -0.268149 , 0.906561 } , { 0.012387 , 0.897792 , 0.440245 } , { 0.0740104 , -0.699068 , 0.711215 } , { 0.110024 , -0.857044 , 0.503358 } , { 0.575597 , -0.779886 , 0.245899 } , { -0.761359 , -0.648324 , 0.00304508 } , { -0.139983 , 0.948432 , 0.284397 } , { 0.494213 , 0.835043 , 0.241777 } , { 0.412646 , 0.910886 , 0.00300169 } , { -0.778852 , 0.115545 , 0.616473 } , { 0.847906 , 0.520515 , 0.100597 } , { 0.381559 , 0.880646 , 0.280848 } , { -0.75984 , 0.644168 , 0.0876987 } , { -0.736586 , -0.669403 , 0.0966486 } , { 0.61001 , -0.792276 , 0.0136739 } , { -0.864806 , -0.302517 , 0.400742 } , { -0.32708 , 0.178495 , 0.927986 } , { 0.619961 , 0.50237 , 0.602721 } , { -0.876188 , -0.303311 , 0.374562 } , { -0.241242 , 0.606737 , 0.757412 } , { 0.716436 , -0.670845 , 0.191536 } , { 0.0403957 , -0.533251 , 0.844992 } , { 0.229727 , -0.683459 , 0.692899 } , { 0.555794 , 0.818392 , 0.146037 } , { -0.0926963 , -0.995174 , 0.0321806 } , { -0.618159 , 0.273929 , 0.736778 } , { 0.105384 , -0.756296 , 0.645687 } , { 0.432666 , -0.480367 , 0.76292 } , { 0.365927 , 0.635624 , 0.679764 } , { -0.124722 , -0.216931 , 0.968187 } , { -0.399871 , -0.915581 , 0.0425861 } , { 0.825642 , -0.076549 , 0.558977 } , { -0.607219 , -0.0839766 , 0.790084 } , { 0.257646 , -0.947904 , 0.187343 } , { -0.973859 , 0.170738 , 0.149824 } , { -0.601329 , 0.0792537 , 0.795061 } , { 0.700292 , 0.110759 , 0.705212 } , { 0.87532 , 0.033876 , 0.482355 } , { -0.461323 , -0.816624 , 0.346854 } , { 0.351135 , -0.879064 , 0.322415 } , { -0.260794 , 0.945855 , 0.193246 } , { 0.129913 , 0.863015 , 0.488188 } , { 0.644597 , -0.753439 , 0.129708 } , { -0.153882 , -0.970458 , 0.185826 } , { -0.883671 , -0.464376 , 0.0589968 } , { -0.927063 , -0.306326 , 0.216147 } , { 0.668522 , 0.570521 , 0.477059 } , { -0.666277 , 0.742205 , 0.072155 } , { 0.660494 , 0.701136 , 0.26862 } , { -0.185185 , -0.706877 , 0.682665 } , { -0.0684437 , 0.976522 , 0.204253 } , { 0.750589 , -0.219435 , 0.623269 } , { -0.816743 , 0.387197 , 0.427795 } , { 0.757362 , 0.648293 , 0.078222 } , { -0.427486 , -0.412167 , 0.804596 } , { 0.988097 , 0.00670096 , 0.153683 } , { 0.277227 , 0.484279 , 0.829831 } , { -0.88351 , 0.112915 , 0.454599 } , { 0.14541 , -0.307944 , 0.940227 } , { 0.751495 , 0.294184 , 0.590518 } , { -0.498719 , -0.346624 , 0.794438 } , { 0.529421 , 0.819243 , 0.220353 } , { -0.493423 , -0.646572 , 0.581789 } , { 0.553122 , -0.831585 , 0.0502359 } , { 0.361316 , 0.817773 , 0.447994 } , { -0.321953 , 0.309534 , 0.894726 } , { 0.0257802 , 0.455535 , 0.889844 } , { -0.112102 , -0.935785 , 0.334276 } , { -0.204189 , 0.72398 , 0.658909 } , { -0.0830892 , 0.721511 , 0.6874 } , { -0.0587021 , 0.55212 , 0.831696 } , { 0.409426 , -0.736357 , 0.538654 } , { 0.991057 , -0.0210081 , 0.131779 } , { 0.901846 , -0.20756 , 0.378935 } , { -0.770037 , -0.0741259 , 0.633679 } , { 0.0676739 , 0.294555 , 0.953235 } , { 0.421282 , 0.469216 , 0.776117 } , { -0.287748 , 0.601198 , 0.745495 } , { -0.663875 , 0.496073 , 0.559626 } , { -0.696262 , -0.254709 , 0.671075 } , { -0.112409 , -0.536003 , 0.836699 } , { 0.489847 , 0.0825545 , 0.867891 } , { 0.105038 , -0.990931 , 0.0837964 } , { 0.604117 , 0.632461 , 0.484805 } , { -0.383633 , -0.283532 , 0.878883 } , { 0.60152 , -0.0898302 , 0.793791 } , { 0.484633 , 0.834026 , 0.263689 } , { 0.254487 , -0.746876 , 0.614339 } , { -0.545553 , -0.497684 , 0.674301 } , { -0.876818 , 0.112511 , 0.467473 } , { -0.237656 , 0.934232 , 0.265952 } , { -0.0294367 , -0.921402 , 0.387493 } , { -0.486728 , -0.216072 , 0.846409 } , { 0.144429 , 0.474964 , 0.868072 } , { 0.0454862 , 0.367985 , 0.928718 } , { 0.820079 , 0.243908 , 0.517667 } , { 0.349893 , 0.930892 , 0.104949 } , { -0.430319 , 0.289971 , 0.854835 } , { -0.190132 , 0.344923 , 0.919172 } , { 0.989667 , 0.125939 , 0.0685496 } , { 0.899366 , -0.415161 , 0.137045 } , { 0.0359748 , -0.111595 , 0.993102 } , { -0.196376 , 0.559523 , 0.805215 } , { -0.0629583 , 0.976987 , 0.203798 } , { 0.363838 , -0.396525 , 0.842846 } , { 0.804676 , 0.286272 , 0.520139 } , { -0.666725 , 0.295121 , 0.684383 } , { -0.799799 , -0.446346 , 0.401368 } , { -0.66263 , 0.748947 , 0.00034225 } , { -0.802633 , 0.181898 , 0.568061 } , { -0.946128 , -0.261158 , 0.191413 } , { 0.96312 , 0.268246 , 0.0210805 } , { 0.735642 , 0.423428 , 0.528715 } , { 0.148642 , 0.414738 , 0.897718 } , { -0.559624 , 0.0595275 , 0.826606 } , { 0.461185 , -0.680632 , 0.569253 } , { 0.132656 , 0.543885 , 0.828608 } , { -0.701118 , -0.0516204 , 0.711174 } , { 0.00575105 , 0.248135 , 0.968709 } , { -0.82125 , 0.342783 , 0.456122 } , { -0.970733 , -0.0725293 , 0.228949 } , { -0.139528 , 0.990071 , 0.0170648 } , { -0.251948 , 0.961593 , 0.108907 } , { 0.666862 , -0.236694 , 0.706591 } , { 0.471992 , 0.551411 , 0.687873 } , { -0.0109387 , 0.983696 , 0.179504 } , { -0.675435 , 0.366979 , 0.63962 } , { -0.697104 , 0.407359 , 0.590003 } , { -0.0385627 , -0.999226 , 0.00782239 } , { -0.846063 , 0.484601 , 0.222123 } , { -0.387058 , 0.743006 , 0.54601 } , { 0.537536 , 0.660675 , 0.523989 } , { -0.319601 , 0.213093 , 0.92328 } , { -0.678914 , -0.239643 , 0.694008 } , { -0.848249 , 0.432644 , 0.305439 } , { -0.0202819 , 0.187009 , 0.982149 } , { -0.483706 , 0.0532724 , 0.873608 } , { 0.287804 , -0.262376 , 0.921047 } , { -0.696575 , 0.55611 , 0.453349 } , { 0.848109 , -0.403074 , 0.343864 } , { -0.0732127 , -0.995498 , 0.0601963 } , { 0.190215 , 0.746444 , 0.637683 } , { 0.937405 , -0.141473 , 0.318209 } , { -0.345088 , -0.567249 , 0.747759 } , { -0.0722422 , -0.895066 , 0.440042 } , { 0.93285 , -0.322559 , 0.16046 } , { -0.543124 , 0.829956 , 0.127234 } , { 0.454942 , 0.339249 , 0.82337 } , { -0.0471716 , -0.863152 , 0.502736 } , { 0.773356 , -0.551904 , 0.311965 } , { -0.568357 , -0.752609 , 0.332491 } , { 0.597168 , 0.451598 , 0.662909 } , { -0.175125 , -0.648494 , 0.740802 } , { -0.196635 , 0.137415 , 0.9708 } , { 0.233797 , -0.554866 , 0.798413 } , { -0.508417 , -0.547525 , 0.664627 } , { -0.441595 , -0.0374702 , 0.896432 } , { 0.230679 , 0.919724 , 0.31764 } , { -0.198322 , 0.0413295 , 0.979265 } , { -0.166508 , -0.642696 , 0.747808 } , { 0.773382 , -0.229258 , 0.591034 } , { 0.107766 , -0.943507 , 0.313339 } , { -0.025376 , -0.805011 , 0.592717 } , { -0.927324 , -0.269352 , 0.259846 } , { 0.229413 , 0.0379033 , 0.972591 } , { -0.259051 , -0.368793 , 0.892684 } , { 0.704154 , 0.61991 , 0.346234 } , { -0.283702 , 0.824966 , 0.48882 } , { -0.0529137 , -0.933678 , 0.354182 } , { 0.717219 , -0.372836 , 0.588718 } , { 0.965919 , 0.234816 , 0.108916 } , { 0.356842 , 0.281283 , 0.890811 } , { 0.350351 , -0.26904 , 0.897146 } , { -0.899917 , -0.237456 , 0.365739 } , { 0.248937 , 0.640887 , 0.72615 } , { 0.788417 , 0.35633 , 0.501426 } , { -0.799418 , 0.525962 , 0.290338 } , { -0.69171 , 0.266217 , 0.671316 } , { -0.197335 , -0.691134 , 0.695265 } , { -0.64364 , -0.764853 , 0.0269642 } , { 0.769969 , -0.345561 , 0.53641 } , { 0.672079 , -0.457287 , 0.582408 } , { 0.952714 , 0.288473 , 0.0954944 } , { 0.625464 , -0.660573 , 0.415257 } , { -0.774309 , 0.469365 , 0.424432 } , { -0.499203 , 0.762656 , 0.411282 } , { -0.250921 , 0.350182 , 0.902447 } , { -0.99454 , -0.0165641 , 0.103032 } , { 0.0854172 , -0.867835 , 0.489456 } , { 0.318629 , 0.256267 , 0.91258 } , { 0.112212 , -0.391527 , 0.913299 } , { -0.75129 , -0.559069 , 0.350722 } , { 0.800773 , 0.0555304 , 0.596388 } , { 0.247943 , -0.323097 , 0.913308 } , { -0.885332 , -0.1681 , 0.433509 } , { -0.948103 , 0.317639 , 0.0143269 } , { -0.0804184 , 0.370244 , 0.925447 } , { -0.70576 , -0.0464985 , 0.706923 } , { 0.872552 , 0.3524 , 0.338332 } , { 0.713814 , 0.658746 , 0.237746 } , { 0.450675 , 0.891214 , 0.0512814 } , { 0.889924 , -0.449341 , 0.07828 } , { -0.260058 , 0.166545 , 0.951122 } , { -0.118895 , 0.982478 , 0.143533 } , { -0.922262 , 0.164286 , 0.349917 } , { 0.656328 , 0.713224 , 0.24606 } , { -0.836753 , -0.285493 , 0.467267 } , { 0.829162 , -0.16806 , 0.533147 } , { -0.166073 , 0.97794 , 0.1267 } , { -0.143735 , 0.750808 , 0.644692 } , { -0.314528 , 0.724548 , 0.613272 } , { -0.101917 , 0.833726 , 0.542692 } , { 0.852526 , 0.483548 , 0.198446 } , { -0.812519 , 0.381986 , 0.44034 } , { -0.508506 , -0.812028 , 0.286412 } , { 0.735844 , 0.670117 , 0.0973507 } , { -0.943289 , -0.0565823 , 0.327114 } , { -0.63929 , 0.764108 , 0.0862963 } , { 0.537237 , -0.0976577 , 0.837759 } , { 0.559135 , 0.374049 , 0.739902 } , { 0.992589 , 0.0438028 , 0.11335 } , { 0.209411 , 0.80909 , 0.549108 } , { -0.959962 , 0.25374 , 0.1187 } , { -0.548551 , -0.532922 , 0.644272 } , { 0.881978 , 0.00116461 , 0.471289 } , { 0.946514 , 0.257534 , 0.194391 } , { 0.629944 , 0.683265 , 0.369214 } , { -0.796188 , 0.473462 , 0.37672 } , { -0.758918 , -0.491514 , 0.427149 } , { -0.450385 , 0.567411 , 0.689346 } , { 0.680931 , -0.539595 , 0.495146 } , { 0.846995 , 0.529119 , 0.0513089 } , { -0.975036 , -0.107606 , 0.194233 } , { -0.190396 , 0.393247 , 0.899503 } , { 0.18395 , 0.100827 , 0.977751 } , { -0.506283 , 0.229744 , 0.831201 } , { 0.622738 , 0.76292 , 0.173639 } , { -0.423672 , -0.55456 , 0.716216 } , { -0.415831 , 0.887214 , 0.199838 } , { 0.454089 , -0.761655 , 0.462261 } , { 0.440816 , 0.822212 , 0.360068 } , { -0.432005 , -0.492247 , 0.755688 } , { -0.341161 , -0.853571 , 0.393734 } , { 0.989515 , 0.104259 , 0.0999494 } , { -0.652492 , 0.508443 , 0.561907 } , { -0.946259 , -0.201426 , 0.253024 } , { 0.471441 , -0.667815 , 0.575992 } , { 0.351964 , 0.903516 , 0.2445 } , { -0.614064 , -0.298446 , 0.730654 } , { 0.608745 , -0.792963 , 0.0252848 } , { -0.857587 , 0.415174 , 0.303604 } , { -0.0645872 , -0.90185 , 0.427195 } , { -0.891527 , 0.431248 , 0.138579 } , { -0.473025 , -0.850385 , 0.230419 } , { -0.494065 , -0.713991 , 0.496101 } , { 0.910021 , 0.414453 , 0.00954401 } , { 0.693493 , -0.630108 , 0.349331 } , { -0.631744 , -0.659888 , 0.406752 } , { -0.0208304 , 0.989329 , 0.144199 } , { -0.577209 , 0.763234 , 0.290349 } , { 0.94863 , 0.111749 , 0.295996 } , { 0.896166 , -0.381178 , 0.227134 } , { 0.679225 , 0.0370938 , 0.732992 } , { -0.110232 , -0.960969 , 0.253747 } , { 0.63138 , 0.758498 , 0.161369 } , { 0.108181 , 0.97913 , 0.17205 } , { 0.689171 , -0.711814 , 0.135518 } , { -0.650513 , -0.757294 , 0.0577842 } , { -0.566207 , 0.721501 , 0.398555 } , { -0.878926 , -0.278109 , 0.387485 } , { 0.374062 , -0.927207 , 0.0191176 } , { -0.326607 , 0.553109 , 0.76642 } , { -0.337242 , 0.714741 , 0.61271 } , { -0.0984992 , 0.992435 , 0.073279 } , { -0.405226 , -0.328998 , 0.852967 } , { 0.1152 , 0.636763 , 0.762405 } , { 0.666029 , 0.0218966 , 0.745604 } , { -0.727988 , 0.0288606 , 0.684983 } , { 0.214271 , -0.976378 , 0.0278273 } , { 0.739439 , 0.499799 , 0.451033 } , { -0.199992 , 0.491167 , 0.847796 } , { 0.937008 , -0.0491626 , 0.34583 } , { -0.231079 , 0.739663 , 0.63206 } , { -0.961836 , 0.092796 , 0.257412 } , { 0.872997 , -0.37802 , 0.308183 } , { 0.515165 , 0.854473 , 0.0669315 } , { -0.510595 , -0.705155 , 0.491985 } , { 0.0708553 , -0.0282404 , 0.997087 } , { 0.969787 , -0.236671 , 0.0591562 } , { -0.877217 , -0.248522 , 0.410764 } , { 0.44491 , -0.884426 , 0.140878 } , { 0.285348 , 0.83578 , 0.469094 } , { 0.832011 , -0.437441 , 0.34118 } , { 0.511226 , -0.769557 , 0.382661 } , { 0.70264 , -0.404607 , 0.585312 } , { 0.327603 , 0.354364 , 0.875844 } , { -0.0837555 , 0.885629 , 0.456778 } , { 0.826032 , -0.507201 , 0.245799 } , { 0.00490831 , -0.486619 , 0.873601 } , { 0.1997 , 0.95798 , 0.205897 } , { -0.706051 , 0.329445 , 0.626863 } , { 0.590432 , -0.266318 , 0.761882 } , { 0.717202 , -0.677882 , 0.161546 } , { 0.633489 , 0.211104 , 0.744397 } , { 0.837894 , 0.444187 , 0.317223 } , { 0.83489 , -0.516486 , 0.190267 } , { -0.627778 , 0.753187 , 0.196479 } , { -0.115169 , -0.96892 , 0.218929 } , { 0.28284 , -0.855918 , 0.432904 } , { -0.98722 , 0.0565568 , 0.148989 } , { -0.897555 , -0.0701648 , 0.435285 } , { -0.914489 , 0.322557 , 0.244269 } , { 0.025956 , 0.831548 , 0.554847 } , { -0.517053 , 0.807739 , 0.283219 } , { -0.0341836 , 0.999393 , 0.00672197 } , { -0.404717 , -0.907077 , 0.115828 } , { -0.8606 , 0.347916 , 0.371917 } , { -0.102083 , 0.967455 , 0.231537 } , { 0.929003 , -0.0703717 , 0.36332 } , { 0.500379 , 0.785505 , 0.364147 } , { -0.422947 , 0.25714 , 0.868904 } , { -0.968901 , 0.201867 , 0.143112 } , { 0.35149 , 0.759556 , 0.547292 } , { -0.746753 , -0.280536 , 0.603042 } , { -0.14375 , 0.988946 , 0.0363689 } , { 0.310807 , 0.945595 , 0.0961729 } , { -0.434021 , -0.792083 , 0.429221 } , { 0.883181 , 0.367863 , 0.290979 } , { -0.985239 , -0.0240218 , 0.169491 } , { 0.502497 , -0.31057 , 0.806872 } , { -0.829904 , 0.205594 , 0.518643 } , { -0.924289 , 0.330929 , 0.190202 } , { 0.145904 , 0.581424 , 0.800411 } , { 0.177825 , 0.888022 , 0.424023 } , { 0.901342 , 0.171577 , 0.397673 } , { 0.0590222 , -0.65127 , 0.756548 } , { -0.440845 , 0.143761 , 0.885996 } , { 0.175558 , 0.825363 , 0.536615 } , { -0.873736 , 0.409999 , 0.2617 } , { 0.635658 , 0.544049 , 0.547677 } , { 0.351396 , -0.723898 , 0.59371 } , { 0.924316 , -0.0667023 , 0.375753 } , { -0.964625 , 0.263156 , 0.0157086 } , { 0.831046 , -0.546641 , 0.102695 } , { -0.369409 , 0.107867 , 0.922985 } , { -0.140331 , -0.756646 , 0.638588 } , { -0.476096 , 0.284012 , 0.832268 } , { -0.301348 , 0.6806 , 0.667812 } , { 0.697784 , -0.671069 , 0.250528 } , { 0.164754 , -0.327916 , 0.93023 } , { 0.49401 , -0.299924 , 0.816088 } , { -0.336862 , 0.457324 , 0.82303 } , { 0.410453 , -0.869736 , 0.274023 } , { 0.990052 , -0.0383465 , 0.135372 } , { -0.470803 , 0.726392 , 0.500698 } , { -0.590812 , 0.177725 , 0.786991 } , { -0.824206 , 0.462408 , 0.326899 } , { -0.555217 , -0.823585 , 0.115943 } , { -0.968044 , 0.0403105 , 0.247518 } , { 0.254495 , -0.413933 , 0.874009 } , { -0.734757 , 0.67036 , 0.103679 } , { 0.308956 , -0.35359 , 0.882905 } , { -0.144948 , -0.90202 , 0.406632 } , { -0.678742 , 0.362395 , 0.638732 } , { -0.130536 , -0.593061 , 0.794505 } , { -0.859435 , -0.0583625 , 0.507903 } , { 0.339207 , -0.577424 , 0.742644 } , { -0.689204 , 0.0361204 , 0.723667 } , { -0.859196 , 0.407481 , 0.309422 } , { 0.826946 , -0.561533 , 0.0289896 } , { -0.703765 , -0.45919 , 0.542088 } , { 0.879049 , -0.383726 , 0.282891 } , { -0.0641181 , 0.194902 , 0.978725 } , { -0.745461 , 0.641735 , 0.180177 } , { -0.462702 , -0.663519 , 0.58792 } , { 0.0442161 , 0.892324 , 0.449224 } , { 0.206327 , -0.975922 , 0.0707459 } , { 0.481743 , -0.850075 , 0.212829 } , { -0.0405921 , 0.171217 , 0.984397 } , { 0.661784 , 0.551332 , 0.50801 } , { -0.101208 , -3.41008e-05 , 0.994865 } , { -0.443302 , -0.479532 , 0.757319 } , { -0.938423 , 0.0995841 , 0.330826 } , { 0.967124 , -0.0651274 , 0.245824 } , { -0.764881 , -0.620054 , 0.174614 } , { -0.395289 , -0.893927 , 0.211282 } , { 0.0167702 , -0.915989 , 0.400853 } , { -0.235339 , -0.94271 , 0.23646 } , { 0.257422 , 0.960357 , 0.106994 } , { 0.341693 , -0.486462 , 0.804114 } , { 0.304235 , -0.620479 , 0.722805 } , { -0.784049 , 0.594281 , 0.179153 } , { 0.325347 , 0.921654 , 0.21143 } , { 0.635366 , 0.549711 , 0.542335 } , { 0.256747 , -0.0277946 , 0.966079 } , { 0.890315 , -0.080736 , 0.448131 } , { 0.146326 , -0.214136 , 0.965782 } , { 0.264313 , -0.585602 , 0.766296 } , { -0.0484446 , -0.752193 , 0.657159 } , { -0.0505503 , -0.920925 , 0.386447 } , { -0.216903 , -0.68413 , 0.696362 } , { 0.942936 , 0.297282 , 0.149981 } , { -0.959244 , -0.267218 , 0.0919018 } , { -0.875923 , -0.0415609 , 0.480657 } , { 0.543083 , -0.676881 , 0.496883 } , { -0.725927 , -0.623645 , 0.289995 } , { -0.722524 , 0.262284 , 0.639661 } , { 0.223519 , -0.974505 , 0.019473 } , { 0.0498862 , 0.693363 , 0.718859 } , { -0.698671 , -0.68657 , 0.201198 } , { 0.640082 , 0.627864 , 0.442812 } , { 0.176685 , 0.598277 , 0.781567 } , { 0.0520292 , 0.343406 , 0.937745 } , { -0.0857454 , 0.279019 , 0.95645 } , { -0.172126 , 0.319958 , 0.931665 } , { -0.151051 , 0.355083 , 0.922551 } , { 0.330673 , -0.0766805 , 0.940625 } , { 0.956497 , -0.0980828 , 0.274759 } , { -0.718965 , -0.694907 , 0.0139478 } , { -0.0535765 , 0.998412 , 0.0174351 } , { 0.159613 , -0.230832 , 0.959813 } , { 0.358364 , 0.565284 , 0.742987 } , { -0.597215 , 0.552201 , 0.581728 } , { 0.410876 , -0.188839 , 0.89192 } , { 0.366262 , -0.53632 , 0.760403 } , { -0.247317 , 0.383265 , 0.889912 } , { -0.512036 , -0.856698 , 0.062346 } , { -0.920523 , 0.379943 , 0.0910034 } , { 0.889771 , 0.400246 , 0.219341 } , { 0.524738 , -0.666386 , 0.529697 } , { -0.091312 , 0.604103 , 0.791657 } , { -0.670759 , 0.339034 , 0.65965 } , { -0.861253 , -0.180026 , 0.47522 } , { -0.0334579 , -0.982823 , 0.181495 } , { -0.587137 , 0.423571 , 0.689825 } , { -0.0737231 , -0.0836161 , 0.993767 } , { 0.613437 , -0.616453 , 0.49364 } , { 0.886698 , 0.213963 , 0.409861 } , { -0.0491599 , -0.871278 , 0.488321 } , { 0.708581 , -0.702922 , 0.0617624 } , { -0.973631 , -0.148964 , 0.17278 } , { -0.775082 , -0.280242 , 0.566314 } , { 0.0717724 , -0.92349 , 0.376848 } , { -0.879966 , -0.474826 , 0.0141669 } , { 0.129146 , 0.931239 , 0.340757 } , { -0.152334 , -0.979719 , 0.13017 } , { 0.0695774 , 0.0540327 , 0.996112 } , { 0.0469622 , 0.71449 , 0.698068 } , { 0.640787 , 0.254725 , 0.724229 } , { -0.0666535 , 0.240829 , 0.968276 } , { -0.99372 , 0.07975 , 0.0784926 } , { -0.260678 , -0.954616 , 0.144065 } , { -0.116351 , -0.680206 , 0.723728 } , { 0.643787 , 0.587309 , 0.490516 } , { 0.0826253 , 0.362963 , 0.928133 } , { 0.950081 , 0.311718 , 0.0133163 } , { -0.217576 , -0.851502 , 0.47708 } , { -0.876288 , 0.432957 , 0.211348 } , { -0.812961 , -0.57972 , 0.0549417 } , { 0.321818 , -0.946733 , 0.0114336 } , { 0.70502 , -0.275905 , 0.653317 } , { -0.155319 , 0.288498 , 0.944799 } , { 0.432093 , 0.897181 , 0.0914433 } , { -0.401382 , -0.90571 , 0.136313 } , { -0.831591 , -0.283518 , 0.477571 } , { 0.0942993 , 0.287389 , 0.953161 } , { -0.822893 , 0.562663 , 0.079098 } , { 0.800031 , -0.570472 , 0.185774 } , { -0.384117 , -0.545602 , 0.744831 } , { 0.83811 , 0.54416 , 0.0382339 } , { -0.960882 , -0.0753728 , 0.266505 } , { 0.756507 , 0.588998 , 0.284216 } , { 0.0124783 , 0.895301 , 0.445287 } , { 0.337014 , 0.939288 , 0.0645022 } , { -0.924676 , -0.224872 , 0.307255 } , { 0.04805 , 0.0914872 , 0.994646 } , { 0.285888 , 0.0451397 , 0.957199 } , { 0.0798163 , 0.012293 , 0.996734 } , { 0.729009 , 0.341868 , 0.593019 } , { -0.758849 , 0.287968 , 0.584143 } , { -0.261892 , -0.600109 , 0.755832 } , { 0.367793 , 0.592909 , 0.71637 } , { -0.937877 , -0.297763 , 0.178113 } , { 0.10114 , 0.475453 , 0.873908 } , { -0.796084 , -0.451848 , 0.402597 } , { 0.716422 , 0.32644 , 0.616585 } , { -0.934631 , 0.301083 , 0.189244 } , { 0.310528 , -0.690455 , 0.653333 } , { -0.2529 , -0.882574 , 0.396365 } , { 0.960773 , 0.276218 , 0.024876 } , { -0.871701 , -0.0535292 , 0.487105 } , { 0.143654 , 0.812608 , 0.564829 } , { 0.191739 , 0.978991 , 0.0693697 } , { 0.0639794 , 0.859537 , 0.507053 } , { -0.782763 , 0.230607 , 0.578016 } , { 0.790834 , -0.4943 , 0.360902 } , { 0.421349 , -0.863296 , 0.277821 } , { 0.136527 , 0.9799 , 0.14545 } , { 0.635472 , 0.72788 , 0.257614 } , { 0.410846 , 0.201244 , 0.889217 } , { -0.0150485 , 0.825548 , 0.564132 } , { -0.266225 , 0.642084 , 0.718925 } , { 0.31442 , -0.740959 , 0.593397 } , { -0.547492 , 0.390031 , 0.740357 } , { 0.173042 , 0.215324 , 0.961089 } , { 0.0368923 , -0.450376 , 0.892076 } , { -0.370864 , -0.614899 , 0.695959 } , { 0.387121 , 0.921551 , 0.0296797 } , { 0.111938 , 0.965695 , 0.234315 } , { -0.466181 , -0.871839 , 0.150239 } , { -0.61396 , -0.478287 , 0.627929 } , { -0.250251 , 0.491555 , 0.834115 } , { -0.289533 , -0.4299 , 0.855194 } , { 0.135113 , -0.426848 , 0.894173 } , { -0.90874 , 0.0141507 , 0.417123 } , { 0.96462 , 0.0568716 , 0.257437 } , { -0.863151 , -0.0642172 , 0.500845 } , { -0.89521 , 0.267884 , 0.356143 } , { -0.72415 , 0.226519 , 0.65138 } , { 0.396117 , -0.581723 , 0.710415 } , { -0.184708 , 0.553687 , 0.811981 } , { 0.0243526 , 0.976022 , 0.216307 } , { 0.306722 , 0.203732 , 0.929739 } , { -0.288601 , 0.409477 , 0.86547 } , { -0.47563 , 0.592801 , 0.649895 } , { 0.996856 , 0.0688997 , 0.0391247 } , { 0.797468 , 0.598793 , 0.0741063 } , { -0.572313 , 0.470174 , 0.671858 } , { -0.670323 , 0.562801 , 0.483656 } , { -0.880931 , -0.28385 , 0.378668 } , { 0.589255 , 0.235943 , 0.772729 } , { 0.307613 , 0.356918 , 0.882034 } , { -0.725146 , 0.673184 , 0.144869 } , { -0.788785 , 0.587409 , 0.181022 } , { -0.703554 , 0.249713 , 0.665323 } , { -0.768632 , 0.381528 , 0.51346 } , { -0.513182 , 0.693207 , 0.506071 } , { -0.179554 , -0.734344 , 0.654599 } , { 0.36032 , 0.281075 , 0.889475 } , { 0.122492 , -0.985298 , 0.119092 } , { -0.876589 , -0.475532 , 0.0738979 } , { 0.739728 , -0.371086 , 0.561336 } , { -0.692662 , -0.623126 , 0.363226 } , { -0.864465 , 0.343617 , 0.366917 } , { 0.99926 , 0.0369065 , 0.0108788 } , { 0.777513 , -0.62851 , 0.0212089 } , { 0.475434 , 0.14914 , 0.867018 } , { 0.214186 , 0.255377 , 0.942818 } , { -0.375702 , -0.348838 , 0.85858 } , { -0.0283414 , 0.376705 , 0.9259 } , { 0.0932436 , -0.483508 , 0.870359 } , { -0.350559 , 0.857202 , 0.377244 } , { -0.435486 , 0.517593 , 0.736511 } , { 0.88575 , 0.461752 , 0.0472374 } , { 0.31069 , 0.178938 , 0.933517 } , { -0.652534 , 0.308015 , 0.692334 } , { 0.515375 , 0.527399 , 0.675454 } , { -0.532645 , 0.79569 , 0.288386 } , { 0.402348 , 0.758161 , 0.513136 } , { -0.0058395 , -0.823462 , 0.567342 } , { -0.134937 , 0.924519 , 0.356449 } , { 0.023085 , 0.694989 , 0.71865 } , { 0.372095 , 0.669505 , 0.64289 } , { -0.00449124 , 0.972534 , 0.232718 } , { -0.717585 , 0.390447 , 0.576735 } , { 0.603677 , -0.796825 , 0.025373 } , { 0.275775 , 0.873112 , 0.402023 } , { -0.368822 , 0.644203 , 0.670055 } , { 0.182373 , 0.448971 , 0.874737 } , { 0.564772 , 0.105493 , 0.818476 } , { 0.0285027 , -0.838917 , 0.543512 } , { -0.912261 , 0.401398 , 0.0816022 } , { -0.38601 , 0.891923 , 0.235519 } , { -0.585327 , -0.590293 , 0.555829 } , { 0.925767 , 0.377247 , 0.0252901 } , { -0.489721 , -0.834995 , 0.250912 } , { -0.739595 , -0.0709388 , 0.669304 } , { -0.317976 , -0.474894 , 0.820589 } , { -0.253331 , 0.894251 , 0.36897 } , { 0.968228 , -0.166774 , 0.186337 } , { 0.790145 , -0.437507 , 0.429254 } , { 0.808875 , -0.473997 , 0.347919 } , { 0.650813 , -0.0367879 , 0.758346 } , { -0.350867 , -0.789728 , 0.503211 } , { -0.420957 , -0.642014 , 0.640791 } , { -0.780709 , 0.24631 , 0.574304 } , { -0.265123 , -0.4973 , 0.826076 } , { -0.178817 , 0.611494 , 0.770779 } , { 0.518012 , 0.854981 , 0.0258942 } , { 0.532669 , -0.0863995 , 0.841902 } , { 0.235454 , -0.801135 , 0.550222 } , { -0.64595 , -0.253597 , 0.720026 } , { 0.744696 , 0.243425 , 0.621427 } , { -0.90181 , 0.0272154 , 0.431275 } , { -0.682509 , -0.661142 , 0.311565 } , { 0.327961 , 0.127102 , 0.936102 } , { 0.109708 , -0.385826 , 0.916025 } , { -0.520135 , -0.852558 , 0.0510342 } , { -0.139319 , -0.8096 , 0.570209 } , { -0.928265 , 0.209275 , 0.307455 } , { -0.604482 , -0.235475 , 0.761021 } , { 0.149857 , -0.533936 , 0.832139 } , { -0.267889 , 0.799469 , 0.537666 } , { 0.112862 , 0.557683 , 0.822346 } , { -0.995632 , -0.0612462 , 0.070475 } , { -0.341586 , -0.857261 , 0.385256 } , { -0.456918 , 0.79972 , 0.389454 } , { 0.646747 , 0.577347 , 0.498385 } , { -0.627449 , 0.140955 , 0.765794 } , { 0.139713 , 0.9649 , 0.222369 } , { -0.865115 , -0.470204 , 0.174599 } , { 0.621598 , 0.656019 , 0.428083 } , { 0.0436108 , -0.663782 , 0.746654 } , { -0.441615 , -0.680943 , 0.584202 } , { -0.644906 , -0.763534 , 0.0333617 } , { -0.635579 , 0.7317 , 0.24628 } , { -0.890948 , -0.224046 , 0.394988 } , { -0.656366 , 0.315634 , 0.685243 } , { -0.022597 , -0.947599 , 0.318663 } , { 0.326225 , -0.898488 , 0.293762 } , { 0.465407 , -0.73839 , 0.488033 } , { 0.926797 , 0.375434 , 0.00983512 } , { -0.0271515 , -0.754488 , 0.655752 } , { 0.87974 , 0.316855 , 0.354485 } , { -0.217193 , 0.882002 , 0.41821 } , { 0.258732 , -0.862089 , 0.43573 } , { -0.616627 , -0.28119 , 0.735326 } , { -0.0296808 , -0.523704 , 0.851383 } , { 0.188799 , 0.920192 , 0.34293 } , { -0.371185 , 0.906508 , 0.201159 } , { 0.694803 , 0.0991563 , 0.712332 } , { 0.718251 , 0.251776 , 0.648633 } , { -0.494704 , 0.860236 , 0.123541 } , { -0.817417 , 0.57496 , 0.035358 } , { 0.67949 , 0.716352 , 0.158535 } , { 0.464199 , -0.7821 , 0.415739 } , { -0.290753 , -0.954749 , 0.062578 } , { 0.619657 , 0.757088 , 0.206986 } , { -0.889549 , -0.444481 , 0.105546 } , { 0.510778 , 0.76529 , 0.391711 } , { -0.952082 , 0.13251 , 0.275646 } , { -0.125766 , -0.987546 , 0.0945262 } , { -0.719099 , 0.688768 , 0.0921677 } , { 0.23742 , -0.238559 , 0.941659 } , { 0.404413 , -0.429302 , 0.807558 } , { 0.886641 , -0.273456 , 0.372946 } , { -0.632746 , 0.744094 , 0.214378 } , { 0.959487 , -0.281494 , 0.012094 } , { -0.790622 , 0.0578863 , 0.609563 } , { 0.107287 , -0.691835 , 0.714041 } , { 0.591391 , 0.255433 , 0.76486 } , { -0.835731 , -0.503374 , 0.219474 } , { 0.843769 , 0.0331206 , 0.535684 } , { -0.182435 , -0.817835 , 0.545768 } , { -0.480253 , 0.252462 , 0.840012 } , { 0.903267 , -0.343452 , 0.257197 } , { 0.26834 , -0.533771 , 0.801924 } , { -0.887466 , 0.30668 , 0.344022 } , { 0.501243 , 0.628402 , 0.594867 } , { 0.281916 , -0.890679 , 0.356671 } , { -0.227028 , -0.0116182 , 0.973819 } , { 0.720141 , -0.483467 , 0.497651 } , { 0.0304788 , -0.671267 , 0.740589 } , { -0.880069 , -0.384213 , 0.279034 } , { 0.176621 , 0.852964 , 0.491179 } , { 0.478491 , -0.555562 , 0.679998 } , { -0.784423 , 0.256313 , 0.564787 } , { 0.945726 , 0.308833 , 0.101119 } , { 0.443525 , 0.891927 , 0.0880395 } , { -0.826056 , -0.189961 , 0.530609 } , { 0.640161 , 0.742004 , 0.199056 } , { -0.292418 , -0.000900415 , 0.95629 } , { -0.227712 , -0.314066 , 0.921688 } , { 0.230814 , 0.381538 , 0.895072 } , { 0.10955 , -0.903657 , 0.414007 } , { 0.344167 , -0.93586 , 0.0756037 } , { 0.204243 , 0.871764 , 0.445324 } , { 0.543181 , 0.724706 , 0.423977 } , { -0.896551 , -0.439018 , 0.0588118 } , { -0.172723 , -0.80064 , 0.573709 } , { -0.857375 , -0.297432 , 0.42005 } , { -0.485622 , -0.237407 , 0.841314 } , { -0.983674 , -0.179867 , 0.00576198 } , { 0.937264 , -0.24781 , 0.245209 } , { 0.615678 , -0.523109 , 0.589319 } , { -0.337943 , 0.94111 , 0.0103292 } , { -0.984429 , 0.168749 , 0.0492296 } , { 0.917277 , -0.0840402 , 0.389283 } , { 0.0119516 , -0.657079 , 0.753727 } , { -0.825143 , 0.480094 , 0.297739 } , { 0.765471 , 0.641951 , 0.0441902 } , { 0.273785 , -0.852945 , 0.444439 } , { -0.696798 , 0.305656 , 0.648881 } , { -0.125027 , 0.429996 , 0.894132 } , { 0.534656 , 0.844964 , 0.0133595 } , { 0.288889 , -0.9571 , 0.0224361 } , { 0.690251 , 0.441469 , 0.573287 } , { -0.142068 , -0.659623 , 0.738047 } , { 0.647491 , -0.0340915 , 0.76131 } , { -0.423592 , 0.835423 , 0.350197 } , { 0.31386 , 0.57035 , 0.759074 } , { 0.553468 , -0.380465 , 0.740892 } , { -0.879258 , 0.38106 , 0.285829 } , { 0.0631023 , -0.623564 , 0.779221 } , { -0.899819 , -0.221898 , 0.375615 } , { -0.192444 , -0.747621 , 0.635632 } , { 0.787205 , -0.539306 , 0.299096 } , { 0.189777 , -0.0312954 , 0.981328 } , { -0.911185 , 0.256043 , 0.322776 } , { 0.475066 , -0.696289 , 0.538046 } , { 0.121238 , -0.630365 , 0.766773 } , { -0.461772 , 0.84034 , 0.283893 } , { -0.669244 , -0.0462034 , 0.741605 } , { -0.419062 , 0.0259755 , 0.907586 } , { 0.0182572 , 0.100165 , 0.994803 } , { -0.685607 , 0.626734 , 0.370334 } , { -0.585048 , 0.213178 , 0.78248 } , { 0.883313 , 0.192522 , 0.427426 } , { 0.292522 , 0.5822 , 0.7586 } , { 0.836406 , 0.375172 , 0.399589 } , { -0.897896 , 0.0997581 , 0.428755 } , { -0.546317 , 0.628172 , 0.55402 } , { -0.22051 , 0.948743 , 0.226413 } , { -0.113446 , -0.728276 , 0.675828 } , { -0.684211 , -0.544196 , 0.485496 } , { 0.627953 , -0.765299 , 0.141395 } , { 0.147156 , 0.6154 , 0.774357 } , { -0.0392734 , 0.782557 , 0.621338 } , { 0.0811623 , 0.89073 , 0.447229 } , { -0.129275 , -0.858497 , 0.496256 } , { 0.375029 , 0.156616 , 0.913687 } , { 0.564267 , -0.796646 , 0.216696 } , { 0.788661 , -0.614653 , 0.0146966 } , { 0.735627 , -0.635123 , 0.235524 } , { 0.210895 , 0.46664 , 0.858936 } , { 0.0913936 , -0.409962 , 0.907512 } , { 0.0894591 , 0.736648 , 0.670333 } , { 0.674728 , 0.226884 , 0.702329 } , { 0.995953 , -0.0831084 , 0.0342247 } , { 0.0554167 , -0.893348 , 0.445935 } , { 0.565981 , -0.802843 , 0.187374 } , { 0.643419 , -0.077731 , 0.761558 } , { 0.171322 , -0.444482 , 0.879252 } , { -0.180729 , 0.833385 , 0.522308 } , { 0.99277 , -0.081435 , 0.0881799 } , { -0.999775 , -0.00586502 , 0.0204021 } , { -0.32026 , -0.295296 , 0.90013 } , { 0.892234 , 0.33576 , 0.301966 } , { 0.0268055 , 0.226541 , 0.973633 } , { 0.39791 , 0.23101 , 0.887864 } , { -0.78838 , 0.590479 , 0.172603 } , { -0.595026 , -0.320008 , 0.737251 } , { 0.960625 , 0.105818 , 0.256908 } , { -0.410565 , -0.533205 , 0.739682 } , { 0.10811 , -0.0713151 , 0.991578 } , { 0.801966 , 0.566634 , 0.189147 } , { 0.861203 , 0.134448 , 0.490157 } , { 0.214876 , -0.494032 , 0.842473 } , { -0.30729 , 0.679326 , 0.6664 } , { 0.428951 , -0.416782 , 0.801432 } , { 0.711123 , 0.584425 , 0.390833 } , { -0.39931 , 0.518015 , 0.756447 } , { 0.12683 , 0.880861 , 0.456067 } , { -0.0312822 , -0.566302 , 0.823604 } , { 0.245943 , -0.314068 , 0.916991 } , { -0.527879 , 0.546825 , 0.649866 } , { -0.299337 , -0.808398 , 0.506843 } , { -0.319023 , 0.292586 , 0.901453 } , { 0.791997 , 0.441161 , 0.42204 } , { -0.216398 , -0.974761 , 0.0548838 } , { -0.912094 , 0.409286 , 0.0238452 } , { 0.040788 , 0.926636 , 0.373741 } , { 0.775227 , -0.625943 , 0.0849673 } , { 0.118577 , -0.453348 , 0.883411 } , { 0.498131 , 0.759144 , 0.419005 } , { 0.938171 , 0.0832501 , 0.336012 } , { -0.809991 , -0.242125 , 0.534126 } , { 0.964395 , -0.0297215 , 0.262791 } , { -0.158969 , 0.82194 , 0.54694 } , { 0.0960675 , 0.844186 , 0.527372 } , { -0.635711 , -0.257476 , 0.72772 } , { -0.469659 , 0.390722 , 0.791679 } , { 0.809745 , 0.290877 , 0.509612 } , { 0.868977 , -0.189509 , 0.457127 } , { -0.207109 , 0.653039 , 0.728455 } , { 0.548485 , 0.540617 , 0.637885 } , { -0.885509 , 0.0323574 , 0.463494 } , { -0.358976 , -0.89455 , 0.266302 } , { -0.566431 , 0.287968 , 0.77216 } , { 0.824356 , 0.564653 , 0.0400408 } , { 0.589737 , 0.790468 , 0.165443 } , { -0.572403 , 0.790092 , 0.219337 } , { 0.912905 , -0.125406 , 0.38843 } , { -0.709163 , 0.145999 , 0.689762 } , { -0.764295 , -0.427679 , 0.482642 } , { 0.631152 , -0.490723 , 0.600697 } , { 0.231863 , -0.659431 , 0.715116 } , { -0.720647 , 0.542863 , 0.43124 } , { 0.900848 , 0.329557 , 0.282603 } , { 0.961192 , -0.0334031 , 0.273851 } , { 0.920292 , 0.261933 , 0.29061 } , { -0.553017 , -0.333854 , 0.763357 } , { 0.382263 , -0.0357214 , 0.923363 } , { -0.794788 , 0.408755 , 0.448589 } , { 0.020409 , -0.571098 , 0.820628 } , { -0.998245 , 0.04371 , 0.0399619 } , { 0.404887 , 0.429262 , 0.807342 } , { -0.594547 , -0.420013 , 0.68564 } , { 0.236755 , 0.573626 , 0.784156 } , { 0.331111 , -0.36804 , 0.868857 } , { -0.0805159 , 0.839224 , 0.537793 } , { 0.723547 , -0.450686 , 0.522841 } , { 0.949695 , 0.281099 , 0.138069 } , { 0.707099 , -0.345121 , 0.617173 } , { 0.46272 , 0.862894 , 0.203234 } , { -0.950839 , 0.267763 , 0.155591 } , { -0.872986 , -0.227222 , 0.431585 } , { -0.0104505 , 0.404471 , 0.914491 } , { 0.131964 , -0.287628 , 0.948607 } , { 0.859609 , -0.365525 , 0.35702 } , { -0.166648 , -0.496809 , 0.851709 } , { -0.98028 , 0.137528 , 0.141908 } , { 0.128612 , -0.930223 , 0.34372 } , { -0.909775 , 0.386505 , 0.151405 } , { -0.248672 , -0.305539 , 0.919134 } , { -0.107382 , -0.7887 , 0.605327 } , { -0.535705 , -0.228169 , 0.812994 } , { -0.948791 , 0.147028 , 0.279604 } , { -0.924705 , 0.31084 , 0.219769 } , { -0.235016 , -0.952542 , 0.193471 } , { 0.443258 , -0.86364 , 0.240099 } , { 0.383857 , -0.641298 , 0.664373 } , { -0.236259 , -0.933998 , 0.26801 } , { 0.444762 , -0.360047 , 0.820093 } , { 0.115552 , -0.991603 , 0.0580566 } , { 0.748312 , 0.566817 , 0.344596 } , { 0.015153 , -0.357193 , 0.933908 } , { -0.275867 , 0.947449 , 0.16198 } , { -0.184476 , -0.277756 , 0.942773 } , { 0.884273 , -0.0657883 , 0.462313 } , { -0.784972 , -0.169362 , 0.595932 } , { -0.254361 , -0.864616 , 0.433289 } , { 0.368547 , -0.466315 , 0.804192 } , { 0.201407 , 0.741499 , 0.640011 } , { -0.686645 , -0.396007 , 0.60967 } , { -0.485221 , 0.247677 , 0.83858 } , { -0.83959 , -0.511631 , 0.182544 } , { 0.132017 , -0.843006 , 0.521453 } , { -0.540667 , 0.737518 , 0.404656 } , { -0.345251 , 0.660064 , 0.667171 } , { -0.970531 , 0.0358942 , 0.238286 } , { 0.84874 , 0.509872 , 0.140252 } , { -0.865002 , -0.0591363 , 0.498272 } , { -0.119174 , 0.636059 , 0.762382 } , { 0.568444 , 0.484557 , 0.664888 } , { -0.864781 , 0.190324 , 0.464682 } , { -0.703115 , 0.0695712 , 0.707664 } , { 0.0350197 , 0.939784 , 0.339971 } , { -0.557077 , 0.766957 , 0.318501 } , { 0.261154 , 0.339243 , 0.903721 } , { -0.683623 , 0.717517 , 0.133522 } , { 0.540768 , -0.829281 , 0.140938 } , { -0.195335 , 0.349077 , 0.916509 } , { -0.0362013 , 0.971711 , 0.23338 } , { -0.159317 , 0.754854 , 0.63625 } , { -0.173502 , 0.522586 , 0.834746 } , { 0.892493 , 0.0702457 , 0.445557 } , { 0.959052 , 0.17102 , 0.22577 } , { -0.114643 , 0.992307 , 0.0467293 } , { -0.285994 , -0.734729 , 0.615127 } , { 0.577309 , 0.295169 , 0.761308 } , { 0.936335 , 0.159308 , 0.312886 } , { 0.218608 , -0.419689 , 0.880949 } , { 0.71999 , -0.521206 , 0.458212 } , { -0.129866 , -0.751191 , 0.647184 } , { -0.768672 , -0.633033 , 0.0917187 } , { -0.434375 , -0.389444 , 0.812189 } , { -0.942332 , -0.320385 , 0.0967726 } , { -0.904291 , -0.413814 , 0.104953 } , { 0.634652 , 0.670741 , 0.383827 } , { -0.550148 , 0.450983 , 0.702817 } , { -0.684074 , -0.716013 , 0.139166 } , { 0.243451 , -0.538892 , 0.806429 } , { -0.850345 , 0.422698 , 0.313431 } , { 0.546199 , -0.124691 , 0.828323 } , { -0.629809 , 0.13459 , 0.765 } , { 0.149402 , -0.985615 , 0.0790023 } , { -0.13244 , -0.0949911 , 0.986629 } , { 0.0535806 , -0.598595 , 0.799258 } , { -0.00884962 , 0.0520983 , 0.998603 } , { 0.959685 , 0.279865 , 0.0260745 } , { -0.554417 , -0.308743 , 0.772852 } , { -0.497229 , 0.805263 , 0.322978 } , { 0.74654 , 0.60983 , 0.266056 } , { -0.91583 , 0.355203 , 0.187313 } , { -0.0427974 , 0.877957 , 0.476823 } , { -0.459749 , -0.82189 , 0.336344 } , { -0.0913867 , -0.969542 , 0.227236 } , { 0.223523 , 0.0620523 , 0.972721 } , { 0.850603 , 0.414715 , 0.323243 } , { 0.181937 , -0.983199 , 0.0147532 } , { -0.369108 , -0.111975 , 0.922616 } , { 0.974313 , 0.19862 , 0.106129 } , { -0.54537 , -0.78576 , 0.291808 } , { 0.558758 , 0.722271 , 0.407571 } , { 0.105457 , -0.498539 , 0.860429 } , { -0.319243 , 0.717351 , 0.619267 } , { -0.574676 , 0.771889 , 0.271909 } , { -0.723076 , 0.0132976 , 0.69064 } , { -0.359659 , -0.145081 , 0.921736 } , { -0.150904 , -0.457376 , 0.876376 } , { -0.0966361 , 0.764323 , 0.637551 } , { 0.188163 , 0.650063 , 0.736215 } , { 0.610233 , -0.792158 , 0.0101179 } , { -0.431935 , -0.748285 , 0.503489 } , { 0.0184455 , -0.521036 , 0.853335 } , { 0.442132 , -0.09778 , 0.891605 } , { -0.796191 , 0.00566982 , 0.605019 } , { -0.0971762 , 0.0326487 , 0.994732 } , { 0.194327 , -0.691854 , 0.695396 } , { -0.506032 , -0.288706 , 0.812761 } , { 0.112829 , -0.52032 , 0.846485 } , { -0.561061 , 0.218873 , 0.798314 } , { -0.646408 , -0.227399 , 0.728318 } , { -0.814636 , -0.566508 , 0.124248 } , { -0.692783 , 0.683579 , 0.22972 } , { -0.736898 , 0.326412 , 0.591976 } , { -0.491501 , -0.820408 , 0.292161 } , { 0.559106 , 0.781246 , 0.277587 } , { 0.758038 , -0.651153 , 0.037128 } , { 0.876661 , -0.314177 , 0.364359 } , { -0.0819339 , 0.954911 , 0.285361 } , { 0.926114 , -0.332171 , 0.178818 } , { -0.712707 , 0.465238 , 0.524978 } , { 0.530396 , -0.314615 , 0.787208 } , { 0.91222 , -0.0733874 , 0.403074 } , { 0.0183266 , -0.101998 , 0.994616 } , { -0.707567 , 0.538488 , 0.457581 } , { 0.690153 , -0.456141 , 0.561805 } , { -0.239829 , -0.362485 , 0.900604 } , { -0.917324 , -0.39807 , 0.00751901 } , { 0.109925 , -0.34015 , 0.933924 } , { -0.0298575 , -0.0625489 , 0.997595 } , { -0.242316 , -0.284043 , 0.927687 } , { -0.74623 , 0.0828246 , 0.660516 } , { 0.596785 , 0.800887 , 0.0492789 } , { 0.257241 , 0.449808 , 0.855278 } , { 0.51813 , -0.836872 , 0.176598 } , { 0.44676 , 0.865893 , 0.22502 } , { -0.869742 , -0.0334299 , 0.492373 } , { 0.538992 , -0.183692 , 0.822037 } , { -0.856514 , -0.515951 , 0.013324 } , { -0.0763536 , 0.83301 , 0.547963 } , { -0.245044 , 0.0880203 , 0.965508 } , { -0.688333 , 0.307905 , 0.656804 } , { 0.273693 , 0.540148 , 0.795822 } , { -0.660709 , -0.750633 , 0.00356448 } , { -0.311555 , 0.00584329 , 0.95021 } , { 0.721288 , -0.291106 , 0.628491 } , { 0.420054 , 0.538056 , 0.730788 } , { 0.533103 , 0.831301 , 0.157289 } , { -0.47249 , 0.659043 , 0.585163 } , { 0.21454 , 0.726218 , 0.653131 } , { -0.860136 , 0.346343 , 0.374449 } , { 0.886343 , -0.394107 , 0.243055 } , { -0.445732 , 0.0924414 , 0.890381 } , { -0.599578 , 0.243827 , 0.76227 } , { 0.777262 , 0.619928 , 0.107486 } , { 0.783514 , 0.182892 , 0.593849 } , { -0.701789 , 0.704673 , 0.104537 } , { 0.564367 , 0.823275 , 0.0608941 } , { -0.427109 , 0.0876926 , 0.899938 } , { 0.805202 , 0.128238 , 0.578969 } , { 0.793046 , 0.605076 , 0.0704278 } , { -0.301915 , -0.217598 , 0.928169 } , { 0.649656 , -0.569562 , 0.503533 } , { -0.847132 , -0.222137 , 0.482724 } , { 0.75969 , 0.450592 , 0.46887 } , { 0.758158 , -0.406567 , 0.509805 } , { -0.712589 , -0.6999 , 0.0485588 } , { -0.691146 , 0.134232 , 0.710141 } , { 0.0498011 , 0.573127 , 0.817952 } , { -0.354963 , -0.456237 , 0.815996 } , { 0.556967 , 0.467127 , 0.686717 } , { 0.61065 , -0.469827 , 0.637471 } , { 0.583386 , 0.811695 , 0.0285054 } , { 0.424861 , 0.097152 , 0.90003 } , { 0.517801 , -0.821967 , 0.237176 } , { 0.859447 , 0.496496 , 0.121829 } , { 0.981295 , 0.155418 , 0.113601 } , { -0.334844 , -0.868484 , 0.365533 } , { 0.532831 , -0.205543 , 0.820879 } , { -0.543327 , -0.699313 , 0.464496 } , { -0.318614 , 0.0456605 , 0.946784 } , { 0.473164 , 0.156662 , 0.866933 } , { 0.862984 , -0.463166 , 0.201832 } , { 0.100763 , 0.26385 , 0.959286 } , { 0.854356 , -0.412869 , 0.315618 } , { 0.945142 , 0.00693212 , 0.326585 } , { 0.386745 , 0.0438578 , 0.921143 } , { -0.600858 , -0.0958466 , 0.793589 } , { -0.707635 , 0.245865 , 0.662422 } , { -0.111343 , 0.465358 , 0.878092 } , { -0.591055 , -0.568244 , 0.572497 } , { 0.0864004 , 0.665364 , 0.741503 } , { 0.6683 , 0.233595 , 0.706264 } , { 0.505228 , 0.190213 , 0.841762 } , { 0.571738 , 0.820374 , 0.0101559 } , { -0.906242 , -0.123347 , 0.404365 } , { 0.11326 , -0.958685 , 0.260949 } , { -0.0604709 , -0.514816 , 0.855165 } , { 0.772015 , 0.509025 , 0.38064 } , { -0.307696 , 0.434151 , 0.846662 } , { 0.0181294 , -0.287057 , 0.957742 } , { 0.664347 , 0.265729 , 0.698592 } , { -0.0204153 , -0.830918 , 0.55602 } , { 0.930659 , -0.323222 , 0.171466 } , { -0.557713 , -0.734957 , 0.385739 } , { -0.875948 , 0.115593 , 0.468353 } , { 0.700654 , 0.542972 , 0.462888 } , { -0.783512 , 0.460553 , 0.417132 } , { 0.501783 , 0.530637 , 0.683109 } , { 0.569689 , 0.820049 , 0.0545357 } , { -0.409251 , -0.802135 , 0.434848 } , { -0.64917 , 0.394729 , 0.650205 } , { 0.00778237 , 0.461202 , 0.887261 } , { 0.468419 , 0.524305 , 0.711117 } , { -0.862866 , -0.391378 , 0.319822 } , { -0.170686 , 0.203139 , 0.964158 } , { -0.459377 , 0.818765 , 0.344379 } , { -0.777294 , -0.609375 , 0.156449 } , { 0.986826 , 0.046591 , 0.154931 } , { 0.0568999 , -0.442906 , 0.894761 } , { 0.217973 , -0.925949 , 0.308392 } , { 0.766562 , -0.404321 , 0.498906 } , { 0.942505 , -0.254539 , 0.216553 } , { 0.899558 , 0.29334 , 0.323647 } , { -0.210998 , 0.524159 , 0.825068 } , { 0.55139 , -0.586861 , 0.592927 } , { -0.170757 , 0.163543 , 0.971646 } , { -0.813929 , 0.386426 , 0.433815 } , { -0.869255 , 0.425612 , 0.251497 } , { 0.969163 , -0.211287 , 0.126807 } , { 0.959401 , 0.281889 , 0.00938708 } , { -0.416048 , 0.84099 , 0.34589 } , { 0.00712107 , 0.969172 , 0.246284 } , { 0.492841 , -0.145458 , 0.857875 } , { 0.852823 , -0.0992688 , 0.512679 } , { 0.706273 , -0.44489 , 0.550682 } , { 0.832631 , -0.136643 , 0.536706 } , { -0.504781 , -0.796256 , 0.333426 } , { 0.469291 , 0.872548 , 0.135738 } , { -0.900427 , -0.111435 , 0.420491 } , { -0.856288 , 0.515293 , 0.0352561 } , { -0.614207 , 0.124402 , 0.779278 } , { -0.42444 , -0.804458 , 0.415569 } , { -0.851647 , 0.482486 , 0.204704 } , { 0.950498 , -0.237363 , 0.200532 } , { 0.528799 , 0.362158 , 0.767602 } , { 0.243454 , 0.969824 , 0.0130686 } , { 0.406356 , -0.365612 , 0.837379 } , { 0.226455 , -0.321667 , 0.919374 } , { -0.15622 , -0.720685 , 0.675432 } , { 0.695627 , 0.287496 , 0.658368 } , { 0.543948 , 0.382485 , 0.746877 } , { 0.363125 , -0.0936031 , 0.927027 } , { -0.840445 , 0.167902 , 0.515229 } , { 0.661756 , -0.135483 , 0.737376 } , { -0.163077 , -0.141392 , 0.976429 } , { -0.699217 , 0.674582 , 0.236716 } , { 0.252451 , 0.486792 , 0.836243 } , { 0.434678 , -0.056226 , 0.898829 } , { -0.573527 , -0.798337 , 0.183643 } , { 0.981289 , -0.151489 , 0.118843 } , { 0.822516 , -0.283848 , 0.492847 } , { -0.471747 , -0.798973 , 0.372958 } , { -0.455556 , -0.596267 , 0.66101 } , { -0.49136 , -0.870584 , 0.0254794 } , { 0.524847 , -0.80534 , 0.275616 } , { -0.885086 , 0.0626489 , 0.461191 } , { 0.0510943 , -0.474219 , 0.878923 } , { -0.144161 , -0.417424 , 0.897204 } , { -0.744092 , -0.408544 , 0.528601 } , { -0.121111 , -0.732297 , 0.670129 } , { -0.882796 , -0.265992 , 0.387195 } , { -0.0963813 , 0.596956 , 0.796464 } , { -0.47735 , -0.677872 , 0.55913 } , { -0.332361 , 0.80588 , 0.489993 } , { -0.266612 , -0.749123 , 0.606409 } , { 0.861879 , 0.277817 , 0.424243 } , { 0.945999 , -0.15375 , 0.285389 } , { 0.809668 , -0.137645 , 0.570518 } , { -0.136864 , -0.960815 , 0.241046 } , { -0.692803 , 0.0755387 , 0.717159 } , { -0.352608 , 0.366084 , 0.861191 } , { -0.996822 , -0.055587 , 0.0570632 } , { -0.841918 , 0.462365 , 0.278196 } , { 0.643523 , -0.64516 , 0.411883 } , { -0.688555 , 0.725185 , 3.18289e-05 } , { -0.207068 , -0.55946 , 0.802576 } , { -0.301945 , -0.938922 , 0.165091 } , { -0.224272 , -0.263893 , 0.938117 } , { -0.155068 , -0.943039 , 0.294333 } , { -0.553902 , -0.82659 , 0.0997092 } , { -0.0408728 , -0.542151 , 0.839287 } , { -0.842457 , -0.347952 , 0.411333 } , { 0.794438 , -0.434102 , 0.424763 } , { 0.184269 , -0.321159 , 0.928925 } , { 0.423175 , 0.856411 , 0.295776 } , { 0.189682 , 0.909965 , 0.368761 } , { -0.0996739 , 0.41996 , 0.902052 } , { -0.338336 , -0.82519 , 0.452317 } , { 0.737888 , -0.335404 , 0.585684 } , { -0.26393 , -0.956311 , 0.125739 } , { 0.484736 , 0.780871 , 0.394045 } , { -0.110472 , -0.587773 , 0.801448 } , { 0.471423 , -0.503393 , 0.724124 } , { -0.209815 , -0.935781 , 0.283358 } , { -0.209464 , 0.54431 , 0.812312 } , { -0.962643 , -0.0817722 , 0.258132 } , { 0.882556 , 0.460922 , 0.0929811 } , { -0.0550703 , 0.986899 , 0.15165 } , { -0.0835697 , -0.0703485 , 0.994016 } , { -0.603002 , -0.776336 , 0.183552 } , { 0.682559 , -0.448998 , 0.576641 } , { -0.501199 , 0.820263 , 0.275624 } , { 0.782924 , 0.485524 , 0.388967 } , { 0.813987 , -0.578664 , 0.050732 } , { 0.849505 , 0.525994 , 0.0408934 } , { 0.434482 , -0.874008 , 0.217567 } , { -0.864691 , -0.0517164 , 0.499635 } , { -0.759991 , -0.643988 , 0.0877117 } , { -0.792815 , 0.559607 , 0.24142 } , { -0.746124 , 0.127161 , 0.653551 } , { 0.292639 , 0.858417 , 0.421287 } , { 0.0447946 , -0.998638 , 0.0267586 } , { -0.824524 , -0.341199 , 0.45138 } , { -0.133476 , 0.990535 , 0.0320121 } , { 0.730719 , 0.587548 , 0.347616 } , { -0.53852 , 0.130618 , 0.832428 } , { 0.0434046 , -0.240637 , 0.969644 } , { 0.22969 , 0.886745 , 0.401155 } , { -0.43643 , 0.859363 , 0.266503 } , { 0.740113 , -0.63457 , 0.222606 } , { 0.105307 , 0.553674 , 0.826048 } , { -0.472218 , -0.774318 , 0.421239 } , { -0.0249753 , 0.887988 , 0.459188 } , { -0.691847 , -0.564221 , 0.450557 } , { -0.584066 , -0.4328 , 0.686696 } , { 0.66296 , -0.730463 , 0.164035 } , { -0.831966 , -0.382833 , 0.401587 } , { 0.59096 , 0.294203 , 0.75114 } , { 0.428824 , 0.521261 , 0.737832 } , { 0.244826 , -0.681481 , 0.689669 } , { 0.0602117 , -0.865982 , 0.496437 } , { -0.074388 , 0.881674 , 0.465959 } , { 0.35589 , 0.157854 , 0.9211 } , { 0.830083 , -0.55503 , 0.0538844 } , { -0.842118 , -0.493472 , 0.217537 } , { 0.304456 , -0.858232 , 0.413212 } , { -0.920053 , -0.0232065 , 0.391106 } , { 0.348633 , 0.0757269 , 0.934195 } , { -0.0449895 , -0.874451 , 0.483023 } , { 0.602829 , -0.355792 , 0.714149 } , { 0.148893 , 0.937887 , 0.313369 } , { 0.562852 , 0.702754 , 0.435126 } , { -0.674787 , 0.447105 , 0.587162 } , { -0.732583 , 0.375215 , 0.567923 } , { -0.393894 , -0.158459 , 0.905394 } , { 0.250643 , -0.852287 , 0.459114 } , { 0.764981 , -0.0164537 , 0.643843 } , { 0.639553 , -0.759662 , 0.117836 } , { 0.972071 , 0.197968 , 0.126041 } , { -0.849059 , 0.251008 , 0.464859 } , { 0.594783 , 0.239671 , 0.767327 } , { 0.769387 , -0.418055 , 0.482985 } , { 0.151384 , 0.979895 , 0.129956 } , { -0.443564 , 0.891677 , 0.0903503 } , { 0.815509 , 0.575066 , 0.0651521 } , { -0.317493 , 0.791135 , 0.522785 } , { 0.926851 , 0.123273 , 0.354614 } , { -0.741533 , -0.664372 , 0.0934764 } , { -0.251187 , -0.452187 , 0.855822 } , { -0.3915 , 0.0614674 , 0.918123 } , { 0.114004 , -0.880388 , 0.460347 } , { -0.796083 , -0.270298 , 0.541471 } , { -0.405657 , 0.741708 , 0.534145 } , { 0.474989 , -0.862806 , 0.173067 } , { 0.403477 , 0.872136 , 0.276742 } , { 0.893571 , -0.124509 , 0.43131 } , { 0.825728 , 0.227861 , 0.515997 } , { 0.211412 , -0.565068 , 0.797498 } , { -0.511077 , 0.67121 , 0.536915 } , { 0.0855244 , 0.961572 , 0.260893 } , { 0.292745 , -0.315479 , 0.902648 } , { 0.0633871 , -0.416861 , 0.906758 } , { 0.975544 , -0.000717178 , 0.219803 } , { 0.404331 , -0.887903 , 0.219419 } , { 0.68091 , -0.314012 , 0.661633 } , { -0.734426 , 0.538139 , 0.413552 } , { -0.738635 , -0.313919 , 0.596551 } , { -0.976209 , 0.193878 , 0.0970962 } , { -0.645793 , 0.733266 , 0.212774 } , { -0.0301506 , 0.915047 , 0.402219 } , { -0.862666 , -0.497353 , 0.0919106 } , { -0.199795 , 0.821809 , 0.533585 } , { -0.448485 , -0.489511 , 0.747824 } , { 0.77406 , -0.60397 , 0.189873 } , { -0.153995 , -0.987648 , 0.0289389 } , { 0.621224 , -0.260276 , 0.739146 } , { -0.258797 , -0.524497 , 0.811127 } , { -0.902438 , 0.0879666 , 0.421743 } , { 0.752637 , 0.555264 , 0.353863 } , { 0.452108 , -0.655336 , 0.605089 } , { 0.822625 , 0.564881 , 0.0647826 } , { -0.0868027 , -0.866856 , 0.490943 } , { -0.239846 , -0.69234 , 0.680544 } , { -0.863098 , -0.30061 , 0.405827 } , { -0.481706 , -0.00545994 , 0.876316 } , { 0.719895 , 0.578956 , 0.382833 } , { -0.951653 , -0.255792 , 0.170079 } , { 0.236509 , 0.948997 , 0.208492 } , { 0.936078 , -0.0548174 , 0.347495 } , { 0.52746 , 0.822872 , 0.211346 } , { 0.0717982 , 0.819992 , 0.567854 } , { -0.364176 , 0.911268 , 0.192266 } , { -0.197447 , 0.527493 , 0.826296 } , { -0.681442 , -0.432934 , 0.590089 } , { 0.803915 , 0.565674 , 0.183667 } , { -0.923448 , 0.361882 , 0.127611 } , { 0.383898 , 0.838495 , 0.386715 } , { 0.565343 , -0.747224 , 0.349347 } , { 0.697002 , -0.674704 , 0.242821 } , { 0.914327 , -0.359142 , 0.187146 } , { 0.211641 , 0.947112 , 0.241218 } , { -0.417842 , 0.094971 , 0.903542 } , { 0.820175 , -0.301215 , 0.486398 } , { 0.848589 , -0.395747 , 0.351115 } , { 0.193297 , -0.972402 , 0.130653 } , { 0.333962 , 0.464222 , 0.820346 } , { 0.102207 , 0.240151 , 0.96534 } , { 0.349727 , -0.163287 , 0.922512 } , { 0.00661616 , -0.167036 , 0.985929 } , { -0.812484 , 0.581532 , 0.0411156 } , { -0.921259 , 0.256687 , 0.29222 } , { -0.90706 , -0.277474 , 0.316624 } , { -0.68703 , -0.0708787 , 0.723164 } , { -0.595693 , -0.0639003 , 0.800666 } , { 0.341178 , -0.915756 , 0.212103 } , { 0.0589931 , -0.399396 , 0.914878 } , { -0.291679 , -0.0103922 , 0.95646 } , { -0.157075 , 0.865558 , 0.475539 } , { 0.850995 , -0.515429 , 0.100698 } , { -0.607823 , 0.54047 , 0.581759 } , { -0.278863 , 0.877967 , 0.389114 } , { -0.236604 , -0.969071 , 0.070142 } , { -0.243777 , 0.00562681 , 0.969815 } , { 0.949357 , -0.132852 , 0.284731 } , { -0.4521 , -0.742182 , 0.494745 } , { 0.760964 , 0.601973 , 0.241996 } , { 0.118874 , 0.638186 , 0.76065 } , { -0.0483665 , 0.950308 , 0.30753 } , { -0.830093 , -0.29355 , 0.474104 } , { 0.567781 , 0.612293 , 0.550202 } , { -0.0757834 , -0.688028 , 0.721716 } , { 0.435407 , -0.395548 , 0.80868 } , { -0.551408 , -0.684818 , 0.476416 } , { -0.279902 , -0.680083 , 0.677601 } , { 0.313959 , -0.332989 , 0.889128 } , { 2.24853e-05 , 0.517584 , 0.855632 } , { -0.735254 , -0.587193 , 0.338535 } , { 0.564715 , 0.821757 , 0.0762397 } , { -0.483314 , -0.37124 , 0.792836 } , { -0.596923 , 0.757587 , 0.264093 } , { -0.882831 , -0.0613865 , 0.465663 } , { -0.287069 , 0.247234 , 0.925455 } , { -0.659155 , -0.592201 , 0.463478 } , { -0.938723 , 0.186471 , 0.289874 } , { 0.659334 , -0.362266 , 0.658819 } , { 0.960813 , 0.192366 , 0.199583 } , { 0.718919 , 0.0186663 , 0.694844 } , { 0.433633 , -0.355138 , 0.828155 } , { -0.629111 , -0.321928 , 0.707518 } , { -0.160962 , -0.513745 , 0.842708 } , { -0.580095 , -0.807249 , 0.108806 } , { 0.321983 , 0.283379 , 0.90334 } , { -0.733212 , 0.442685 , 0.516169 } , { 0.544053 , -0.6438 , 0.538078 } , { -0.812493 , 0.581884 , 0.0355911 } , { -0.179919 , 0.805763 , 0.564247 } , { -0.415771 , -0.89233 , 0.175731 } , { -0.4666 , -0.592827 , 0.656384 } , { 0.32751 , -0.734624 , 0.594193 } , { 0.954271 , -0.196452 , 0.22533 } , { -0.198705 , -0.826671 , 0.526433 } , { -0.0451304 , 0.0376411 , 0.998272 } , { 0.770595 , -0.467485 , 0.433176 } , { -0.584706 , 0.681747 , 0.439704 } , { -0.134732 , 0.1654 , 0.97698 } , { 0.449769 , -0.197704 , 0.870989 } , { 0.994655 , 0.10144 , 0.0192468 } , { -0.1105 , 0.989042 , 0.0979023 } , { 0.410207 , -0.901097 , 0.140549 } , { -0.635069 , 0.217338 , 0.74125 } , { -0.515723 , 0.736242 , 0.438152 } , { 0.601121 , 0.649966 , 0.464971 } , { 0.823297 , -0.56487 , 0.0557101 } , { 0.405221 , -0.795894 , 0.449831 } , { 0.682978 , -0.581471 , 0.442078 } , { -0.878181 , 0.238333 , 0.414724 } , { 0.155825 , -0.57998 , 0.799588 } , { -0.387968 , 0.869522 , 0.305633 } , { 0.562482 , 0.579209 , 0.590026 } , { 0.324512 , 0.875006 , 0.359245 } , { -0.00862921 , -0.233782 , 0.972251 } , { -0.966562 , 0.0258241 , 0.255128 } , { 0.380356 , 0.764394 , 0.520607 } , { 0.312731 , 0.790292 , 0.526914 } , { -0.781685 , 0.623577 , 0.010989 } , { -0.156254 , -0.670899 , 0.724899 } , { -0.584927 , 0.622601 , 0.519834 } , { -0.106913 , 0.94457 , 0.310416 } , { -0.609895 , -0.571841 , 0.548659 } , { 0.580308 , -0.0168921 , 0.814222 } , { -0.752211 , 0.658746 , 0.015252 } , { 0.775703 , 0.624115 , 0.0936187 } , { 0.291027 , -0.888572 , 0.354603 } , { -0.730294 , 0.666293 , 0.150749 } , { -0.784708 , -0.602766 , 0.144588 } , { 0.453553 , -0.272745 , 0.848469 } , { -0.207342 , -0.686692 , 0.696752 } , { -0.444957 , -0.361925 , 0.81916 } , { -0.302347 , -0.575724 , 0.759689 } , { -0.56473 , 0.56936 , 0.597418 } , { 0.912843 , -0.386474 , 0.131737 } , { 0.33899 , -0.924206 , 0.175864 } , { 0.72083 , -0.324246 , 0.612591 } , { -0.864807 , -0.479865 , 0.147779 } , { -0.496619 , -0.86157 , 0.105201 } , { -0.492481 , -0.195799 , 0.848013 } , { 0.437821 , 0.0811959 , 0.895388 } , { -0.120346 , -0.9341 , 0.336117 } , { -0.785149 , -0.517049 , 0.340883 } , { 0.0444725 , -0.973622 , 0.223792 } , { 0.303627 , 0.735126 , 0.606135 } , { -0.722871 , -0.211534 , 0.657808 } , { -0.853222 , -0.473794 , 0.218018 } , { -0.124196 , 0.943253 , 0.307976 } , { -0.823915 , 0.252352 , 0.507427 } , { -0.405158 , 0.866909 , 0.290372 } , { -0.103231 , -0.969547 , 0.222086 } , { -0.223474 , -0.623826 , 0.748933 } , { 0.232434 , 0.706631 , 0.668316 } , { -0.164286 , -0.817665 , 0.551755 } , { -0.575475 , 0.7728 , 0.267597 } , { -0.723802 , 0.406797 , 0.557339 } , { 0.917389 , -0.319073 , 0.237889 } , { 0.174018 , 0.688786 , 0.70377 } , { 0.0626636 , -0.994917 , 0.0788244 } , { 0.0855177 , 0.994263 , 0.0642416 } , { 0.638844 , 0.762185 , 0.104655 } , { 0.436851 , -0.701318 , 0.563306 } , { -0.825885 , 0.353449 , 0.439303 } , { 0.615803 , -0.10403 , 0.781002 } , { 0.018539 , -0.629627 , 0.776677 } , { -0.138301 , 0.7985 , 0.585893 } , { 0.191359 , -0.107593 , 0.975605 } , { -0.568249 , -0.821023 , 0.0549051 } , { 0.00961648 , 0.971752 , 0.235806 } , { 0.664657 , -0.0666023 , 0.744174 } , { 0.350822 , 0.487721 , 0.799407 } , { 0.974123 , -0.114662 , 0.194775 } , { 0.563353 , 0.185896 , 0.805032 } , { 0.513834 , 0.597022 , 0.616067 } , { 0.496715 , 0.781022 , 0.378523 } , { -0.0510972 , 0.96598 , 0.253518 } , { -0.515082 , -0.756834 , 0.402358 } , { 0.974372 , 0.113602 , 0.194148 } , { -0.265032 , -0.947086 , 0.18107 } , { 0.991071 , -0.132336 , 0.0163258 } , { 0.216165 , -0.973277 , 0.0774841 } , { -0.815172 , 0.270196 , 0.512337 } , { -0.107314 , -0.797668 , 0.593472 } , { 0.423182 , -0.882453 , 0.20541 } , { 0.98645 , -0.157561 , 0.0457181 } , { -0.700073 , -0.370316 , 0.610544 } , { -0.173318 , -0.639612 , 0.748904 } , { -0.0793354 , -0.463722 , 0.882421 } , { -0.00406452 , 0.85584 , 0.517224 } , { 0.629261 , 0.292979 , 0.719857 } , { 0.0602318 , 0.567448 , 0.821203 } , { 0.190457 , 0.730763 , 0.655523 } , { 0.867935 , -0.443363 , 0.223873 } , { -0.831375 , 0.112474 , 0.54421 } , { 0.12773 , 0.663512 , 0.737182 } , { 0.832204 , 0.547906 , 0.0850565 } , { -0.0303688 , -0.13061 , 0.990969 } , { -0.104853 , -0.385942 , 0.916545 } , { 0.611616 , 0.78271 , 0.115288 } , { -0.293326 , 0.162466 , 0.942107 } , { -0.327169 , 0.559464 , 0.761552 } , { -0.0328401 , -0.999442 , 0.00613129 } , { 0.377281 , 0.137771 , 0.915794 } , { -0.312639 , 0.947687 , 0.0643909 } , { -0.370741 , 0.697734 , 0.612959 } , { -0.138099 , -0.658128 , 0.740132 } , { -0.31957 , -0.939701 , 0.121805 } , { 0.495298 , -0.164497 , 0.853007 } , { -0.370833 , -0.541251 , 0.754672 } , { -0.0132647 , 0.518246 , 0.855129 } , { -0.497727 , 0.438604 , 0.748261 } , { 0.52099 , -0.49765 , 0.693479 } , { 0.749306 , -0.632133 , 0.197353 } , { -0.543409 , -0.143288 , 0.827149 } , { 0.74694 , 0.661628 , 0.065799 } , { -0.224673 , -0.318076 , 0.921059 } , { -0.42204 , 0.11556 , 0.899182 } , { 0.607361 , -0.031725 , 0.793792 } , { 0.15056 , -0.171425 , 0.973625 } , { 0.343841 , -0.734684 , 0.584819 } , { -0.482372 , -0.786889 , 0.384868 } , { -0.0209057 , 0.997076 , 0.0734965 } , { 0.934695 , -0.219737 , 0.279393 } , { 0.798837 , -0.0858186 , 0.595395 } , { 0.665918 , 0.707946 , 0.2353 } , { -0.879308 , 0.0454528 , 0.47408 } , { -0.864235 , -0.502205 , 0.0298067 } , { -0.730156 , -0.63223 , 0.259147 } , { 0.96199 , -0.267385 , 0.055506 } , { -0.722692 , -0.0233776 , 0.690775 } , { 0.74166 , 0.655038 , 0.144449 } , { -0.940341 , -0.129706 , 0.314541 } , { -0.932651 , -0.330267 , 0.145212 } , { -0.85788 , -0.513139 , 0.027019 } , { -0.187942 , 0.512718 , 0.837734 } , { 0.751474 , 0.632089 , 0.189079 } , { 0.327079 , -0.124277 , 0.93679 } , { -0.324712 , 0.602263 , 0.729275 } , { -0.89638 , -0.400939 , 0.189079 } , { 0.773728 , 0.113148 , 0.623332 } , { 0.758225 , 0.239564 , 0.606386 } , { -0.238161 , -0.970769 , 0.0297819 } , { -0.509495 , 0.447379 , 0.735028 } , { -0.600854 , -0.464456 , 0.65058 } , { -0.941317 , 0.119501 , 0.315661 } , { 0.837802 , -0.499794 , 0.219759 } , { 0.0630814 , -0.583151 , 0.809911 } , { 0.490595 , 0.861997 , 0.127582 } , { 0.728256 , -0.23805 , 0.642632 } , { 0.0536279 , 0.868311 , 0.493112 } , { 0.472535 , 0.733389 , 0.488725 } , { -0.155106 , -0.942186 , 0.297033 } , { 0.2069 , 0.957234 , 0.202227 } , { 0.993575 , 0.0410637 , 0.105461 } , { 0.593256 , -0.678083 , 0.433879 } , { 0.33672 , -0.0428219 , 0.940631 } , { -0.541417 , -0.155732 , 0.826205 } , { -0.755016 , -0.222382 , 0.616844 } , { -0.984565 , -0.104744 , 0.140214 } , { 0.131784 , -0.944588 , 0.300642 } , { -0.00726727 , 0.113233 , 0.993542 } , { 0.777702 , 0.50608 , 0.372911 } , { 0.716332 , 0.695612 , 0.0547003 } , { -0.496634 , 0.695747 , 0.518932 } , { -0.516538 , -0.0419909 , 0.855234 } , { 0.267919 , -0.502034 , 0.822302 } , { -0.873879 , 0.343882 , 0.343629 } , { -0.142782 , 0.984264 , 0.104106 } , { 0.751267 , 0.581108 , 0.312907 } , { -0.83347 , 0.332941 , 0.440996 } , { 0.362676 , -0.929875 , 0.0616398 } , { 0.729046 , -0.665203 , 0.161236 } , { -0.541786 , -0.453737 , 0.707524 } , { 0.207692 , -0.967499 , 0.144258 } , { 0.852421 , 0.45609 , 0.255657 } , { 0.3252 , 0.323567 , 0.888566 } , { 0.0465218 , 0.945181 , 0.323215 } , { 0.599306 , -0.673417 , 0.43283 } , { -0.675957 , 0.10323 , 0.729675 } , { -0.757789 , 0.315448 , 0.571182 } , { 0.328336 , -0.944295 , 0.0224192 } , { -0.470258 , -0.747269 , 0.469518 } , { 0.358344 , -0.796395 , 0.487181 } , { 0.801997 , -0.582347 , 0.132935 } , { -0.123399 , -0.521705 , 0.844154 } , { 0.734514 , -0.597932 , 0.320884 } , { -0.0165508 , 0.294336 , 0.955559 } , { 0.595549 , -0.588239 , 0.54708 } , { -0.290221 , -0.920906 , 0.2602 } , { -0.732465 , 0.0104548 , 0.680725 } , { -0.193855 , -0.876425 , 0.440794 } , { -0.715119 , -0.654789 , 0.244656 } , { -0.213418 , 0.34224 , 0.915055 } , { -0.438943 , 0.897926 , 0.0325235 } , { -0.248759 , -0.736321 , 0.629246 } , { -0.28148 , 0.806989 , 0.51917 } , { -0.0740029 , -0.0116379 , 0.99719 } , { 0.031358 , 0.996914 , 0.0719631 } , { 0.583317 , -0.437675 , 0.684239 } , { -0.0627384 , 0.701481 , 0.709921 } , { -0.970672 , 0.0942335 , 0.22117 } , { 0.486683 , 0.536928 , 0.689092 } , { -0.774407 , 0.370406 , 0.512925 } , { -0.75645 , -0.653815 , 0.0175772 } , { 0.33028 , 0.586952 , 0.739191 } , { -0.82322 , 0.522376 , 0.222332 } , { 0.0663577 , 0.637531 , 0.767562 } , { -0.179087 , 0.277134 , 0.943994 } , { -0.986817 , -0.0729325 , 0.144473 } , { -0.716036 , 0.616553 , 0.327345 } , { 0.721595 , -0.377678 , 0.580223 } , { 0.222693 , 0.897548 , 0.380546 } , { -0.562701 , -0.820114 , 0.103833 } , { -0.102195 , 0.395927 , 0.912578 } , { -0.356546 , -0.263619 , 0.896315 } , { 0.237185 , 0.386657 , 0.891201 } , { 0.24587 , 0.953947 , 0.171851 } , { -0.436801 , 0.800929 , 0.409533 } , { -0.230261 , 0.652115 , 0.722306 } , { 0.119877 , -0.986199 , 0.114199 } , { -0.941419 , -0.332706 , 0.055103 } , { -0.577843 , 0.733186 , 0.358518 } , { 0.240175 , 0.872807 , 0.42488 } , { -0.506784 , 0.614195 , 0.604925 } , { -0.53207 , 0.633297 , 0.561993 } , { 0.777503 , -0.372499 , 0.506688 } , { -0.832392 , 0.348292 , 0.431065 } , { -0.105028 , -0.954129 , 0.28037 } , { 0.473252 , 0.32807 , 0.817559 } , { -0.185644 , -0.233409 , 0.954493 } , { 0.812604 , 0.427985 , 0.395604 } , { -0.166509 , 0.773935 , 0.610982 } , { -0.729512 , -0.535114 , 0.425988 } , { 0.566121 , -0.284641 , 0.773619 } , { -0.551042 , -0.202664 , 0.809494 } , { -0.659971 , 0.642009 , 0.390209 } , { -0.68697 , 0.692484 , 0.220314 } , { 0.707914 , -0.530009 , 0.46685 } , { -0.496873 , 0.230152 , 0.836748 } , { -0.268104 , 0.814167 , 0.515027 } , { 0.811227 , 0.0212555 , 0.584344 } , { 0.787385 , 0.411466 , 0.459043 } , { -0.321708 , 0.343851 , 0.882196 } , { 0.769731 , 0.15849 , 0.618382 } , { 0.178024 , -0.314657 , 0.932362 } , { 0.391347 , 0.652181 , 0.649236 } , { 0.570794 , -0.068929 , 0.818195 } , { 0.147905 , 0.419935 , 0.895421 } , { -0.507906 , -0.204427 , 0.836804 } , { 0.96623 , -0.0831043 , 0.243913 } , { -0.397646 , 0.887203 , 0.233983 } , { -0.137656 , -0.952138 , 0.272919 } , { 0.757596 , 0.528653 , 0.38285 } , { -0.0954204 , 0.65421 , 0.750269 } , { -0.243561 , 0.221963 , 0.944145 } , { -0.222766 , 0.472634 , 0.852638 } , { 0.208103 , -0.599179 , 0.773096 } , { 0.285275 , -0.537596 , 0.793479 } , { 0.206763 , 0.727527 , 0.654182 } , { 0.445453 , 0.532234 , 0.71993 } , { 0.972636 , 0.219638 , 0.0757494 } , { -0.751614 , 0.260124 , 0.606145 } , { -0.00124297 , 0.25264 , 0.96756 } , { 0.782836 , 0.552527 , 0.286151 } , { -0.0737421 , 0.778444 , 0.623367 } , { 0.500432 , -0.240594 , 0.831674 } , { -0.933654 , 0.318329 , 0.164186 } , { -0.139899 , 0.939843 , 0.311647 } , { 0.190866 , -0.977542 , 0.0893371 } , { 0.378343 , 0.185631 , 0.906862 } , { 0.688094 , 0.6482 , 0.326136 } , { 0.929623 , 0.299573 , 0.214609 } , { -0.13041 , 0.515505 , 0.846905 } , { -0.797084 , -0.551723 , 0.245476 } , { 0.0108906 , 0.135406 , 0.99073 } , { 0.830121 , 0.175938 , 0.529098 } , { -0.864605 , -0.213465 , 0.454852 } , { -0.0672245 , 0.270309 , 0.960424 } , { -0.58289 , -0.570478 , 0.578614 } , { 0.784361 , 0.577365 , 0.226776 } , { -0.619356 , 0.115026 , 0.776639 } , { 0.33348 , -0.0627198 , 0.940669 } , { -0.215802 , -0.502925 , 0.836957 } , { -0.849624 , 0.200328 , 0.487861 } , { -0.251153 , 0.965581 , 0.0676435 } , { -0.255449 , -0.269456 , 0.928514 } , { -0.513534 , 0.247834 , 0.821499 } , { 0.47132 , -0.806159 , 0.357723 } , { 0.844685 , 0.310858 , 0.435747 } , { -0.116386 , -0.49489 , 0.861126 } , { -0.458526 , -0.786726 , 0.4133 } , { 0.789031 , 0.346897 , 0.507043 } , { -0.11773 , -0.798091 , 0.590924 } , { 0.704243 , -0.0272486 , 0.709436 } , { 0.0388859 , 0.713127 , 0.699955 } , { -0.0721327 , -0.979194 , 0.189671 } , { -0.642333 , -0.638321 , 0.42421 } , { 0.554205 , 0.594521 , 0.582582 } , { -0.884327 , 0.271205 , 0.380019 } , { -0.0954127 , 0.575044 , 0.812539 } , { 0.600266 , 0.634992 , 0.486279 } , { -0.332349 , -0.481767 , 0.81083 } , { -0.857238 , -0.501724 , 0.115823 } , { 0.161256 , -0.986625 , 0.0238186 } , { -0.837109 , 0.469468 , 0.2808 } , { 0.190593 , -0.08426 , 0.978046 } , { 0.0896565 , 0.981472 , 0.169336 } , { -0.243856 , 0.969811 , 0.000651658 } , { 0.608139 , -0.790221 , 0.0756161 } , { -0.313878 , 0.762239 , 0.566103 } , { -0.706502 , 0.681325 , 0.191445 } , { 0.155597 , -0.409229 , 0.899067 } , { 0.00562531 , -0.0974633 , 0.995223 } , { -0.183663 , 0.444356 , 0.876821 } , { -0.800582 , -0.16391 , 0.576369 } , { -0.545575 , 0.158672 , 0.822904 } , { -0.735663 , 0.0279183 , 0.676772 } , { -0.185746 , -0.958181 , 0.217687 } , { 0.810085 , 0.565046 , 0.156479 } , { 0.026751 , 0.134 , 0.99062 } , { 0.994675 , -0.0982306 , 0.0311762 } , { -0.580838 , -0.423434 , 0.69522 } , { 0.478114 , 0.676341 , 0.56033 } , { -0.259766 , -0.570787 , 0.778925 } , { 0.0749413 , 0.141569 , 0.987088 } , { -0.121672 , -0.0909701 , 0.988393 } , { -0.420426 , -0.12118 , 0.899198 } , { 0.541151 , 0.186377 , 0.820012 } , { -0.533231 , 0.749499 , 0.392322 } , { 0.9583 , 0.0945623 , 0.269663 } , { -0.621383 , 0.185976 , 0.761115 } , { -0.963431 , -0.261429 , 0.058782 } , { -0.873138 , -0.476109 , 0.104641 } , { 0.840816 , 0.138154 , 0.523394 } , { -0.0335506 , 0.761559 , 0.647226 } , { 0.306516 , 0.803148 , 0.510883 } , { -0.698534 , 0.52827 , 0.482681 } , { 0.787397 , -0.195984 , 0.584462 } , { 0.179678 , 0.392628 , 0.901975 } , { 0.900507 , 0.327201 , 0.286404 } , { 0.621691 , 0.726965 , 0.291585 } , { -0.78358 , 0.535344 , 0.315294 } , { -0.848468 , -0.384079 , 0.364123 } , { -0.992456 , 0.088155 , 0.0852048 } , { -0.434063 , 0.885106 , 0.167861 } , { -0.288791 , 0.957387 , 0.0031085 } , { -0.880672 , 0.155623 , 0.447436 } , { 0.154178 , 0.933962 , 0.322403 } , { -0.357179 , -0.261208 , 0.896768 } , { 0.119334 , 0.857903 , 0.499761 } , { 0.698693 , -0.0244223 , 0.715005 } , { -0.441325 , -0.315764 , 0.839956 } , { 0.229606 , 0.948733 , 0.217225 } , { -0.923969 , 0.363142 , 0.120036 } , { -0.283117 , -0.935317 , 0.212195 } , { 0.0118727 , 0.999895 , 0.00826287 } , { 0.41711 , 0.601612 , 0.681236 } , { 0.71214 , 0.102171 , 0.694563 } , { -0.690616 , -0.572178 , 0.442337 } , { 0.650604 , 0.759223 , 0.0171586 } , { -0.988887 , -0.0630486 , 0.134636 } , { 0.252747 , 0.958448 , 0.132271 } , { 0.037429 , -0.261071 , 0.964594 } , { -0.96855 , -0.20956 , 0.134148 } , { 0.272732 , 0.607148 , 0.746317 } , { 0.106588 , 0.87287 , 0.476169 } , { -0.316947 , -0.694883 , 0.645509 } , { 0.854004 , 0.39294 , 0.340993 } , { 0.473003 , -0.393703 , 0.788204 } , { 0.0447569 , -0.183854 , 0.981934 } , { 0.579864 , 0.0178638 , 0.814517 } , { -0.340918 , 0.15172 , 0.927769 } , { 0.355611 , 0.879293 , 0.316834 } , { 0.724368 , -0.683784 , 0.0879228 } , { 0.781844 , -0.176735 , 0.5979 } , { 0.115086 , 0.992786 , 0.0336468 } , { 0.298818 , -0.0956656 , 0.949503 } , { 0.455644 , -0.126041 , 0.881193 } , { -0.626736 , 0.638481 , 0.446702 } , { -0.155539 , -0.107875 , 0.981922 } , { -0.0179569 , 0.993472 , 0.112658 } , { 0.0966711 , 0.933367 , 0.345659 } , { 0.548622 , 0.825829 , 0.130461 } , { 0.436741 , -0.807942 , 0.395585 } , { -0.373755 , 0.922915 , 0.0923917 } , { -0.624754 , -0.745011 , 0.233754 } , { -0.443516 , -0.635225 , 0.632284 } , { -0.976876 , 0.157497 , 0.144593 } , { 0.718273 , 0.129246 , 0.683652 } , { -0.447313 , -0.546111 , 0.70829 } , { -0.115265 , 0.121258 , 0.985906 } , { 0.653578 , -0.134474 , 0.744817 } , { -0.360251 , 0.861971 , 0.356687 } , { 0.506625 , 0.147214 , 0.849505 } , { -0.672345 , 0.393565 , 0.626944 } , { -0.0430316 , -0.958144 , 0.283035 } , { -0.734334 , 0.146366 , 0.66282 } , { 0.795545 , 0.604059 , 0.0471372 } , { 0.173257 , -0.952428 , 0.250725 } , { 0.237852 , 0.442866 , 0.864463 } , { 0.545003 , 0.173713 , 0.820241 } , { 0.651095 , -0.436402 , 0.620991 } , { 0.595012 , -0.539429 , 0.595799 } , { -0.934308 , -0.264621 , 0.238839 } , { -0.0943004 , -0.979548 , 0.177746 } , { -0.765547 , 0.526761 , 0.369406 } , { -0.915146 , -0.343254 , 0.211387 } , { -0.867598 , 0.426047 , 0.256432 } , { 0.278356 , -0.924683 , 0.259767 } , { -0.307344 , -0.114252 , 0.944715 } , { 0.617251 , 0.536472 , 0.575499 } , { 0.671095 , -0.623564 , 0.400997 } , { 0.159994 , -0.973209 , 0.165125 } , { 0.0651679 , 0.240737 , 0.9684 } , { 0.860117 , -0.498284 , 0.109144 } , { 0.597477 , 0.764803 , 0.241034 } , { -0.367376 , -0.927516 , 0.0689201 } , { -0.492165 , -0.864629 , 0.100945 } , { 0.897961 , -0.415313 , 0.14554 } , { 0.901433 , -0.0915184 , 0.423134 } , { 0.591306 , -0.451155 , 0.668443 } , { -0.131085 , 0.965722 , 0.224047 } , { 0.025843 , -0.42085 , 0.906762 } , { -0.408819 , 0.821429 , 0.397644 } , { 0.219085 , 0.405605 , 0.887404 } , { -0.0755332 , 0.645184 , 0.760285 } , { -0.386255 , -0.816088 , 0.429892 } , { 0.642788 , -0.705376 , 0.298777 } , { -0.275235 , -0.306668 , 0.911153 } , { 0.527452 , 0.0336785 , 0.848917 } , { -0.955519 , 0.277444 , 0.100041 } , { -0.719592 , -0.0705782 , 0.690801 } , { -0.266584 , -0.919146 , 0.290006 } , { 0.187122 , 0.911447 , 0.366401 } , { -0.759446 , 0.590865 , 0.272251 } , { -0.257097 , 0.760196 , 0.59666 } , { -0.687519 , -0.434174 , 0.582074 } , { -0.0346846 , -0.988565 , 0.146752 } , { 0.132568 , -0.944306 , 0.301185 } , { 0.417439 , -0.280995 , 0.864168 } , { 0.437841 , -0.148193 , 0.886755 } , { 0.126634 , 0.928712 , 0.348507 } , { 0.29796 , -0.597324 , 0.744596 } , { -0.510463 , -0.294482 , 0.807904 } , { 0.191401 , 0.356546 , 0.914462 } , { -0.981368 , -0.0447431 , 0.186854 } , { -0.0119937 , -0.967332 , 0.253229 } , { -0.135266 , 0.989758 , 0.0456232 } , { -0.271675 , -0.957807 , 0.0938017 } , { -0.846737 , -0.531588 , 0.0212198 } , { -0.354496 , -0.913075 , 0.20156 } , { -0.484497 , 0.391581 , 0.782258 } , { 0.876431 , -0.19877 , 0.438587 } , { 0.469293 , 0.500465 , 0.72753 } , { 0.250256 , 0.844546 , 0.473406 } , { 0.158083 , 0.336385 , 0.928361 } , { 0.178352 , 0.695957 , 0.695582 } , { -0.107728 , 0.566451 , 0.817024 } , { -0.360842 , -0.0103419 , 0.93257 } , { -0.960282 , 0.0546871 , 0.273621 } , { -0.733765 , 0.205119 , 0.6477 } , { -0.325486 , 0.94554 , 0.00360537 } , { 0.904468 , 0.120091 , 0.409287 } , { -0.287448 , -0.439055 , 0.851237 } , { 0.771452 , 0.326791 , 0.545958 } , { -0.405028 , 0.761479 , 0.506065 } , { -0.563529 , -0.664834 , 0.490337 } , { 0.80742 , 0.183347 , 0.560764 } , { -0.604001 , 0.770114 , 0.205202 } , { 0.395659 , -0.629524 , 0.668696 } , { 0.298042 , 0.946979 , 0.120008 } , { 0.0648546 , 0.268012 , 0.96123 } , { 0.510623 , -0.248574 , 0.823089 } , { 0.166434 , -0.0596135 , 0.984249 } , { -0.308412 , 0.395986 , 0.864914 } , { 0.379318 , 0.308248 , 0.872411 } , { 0.848971 , -0.371171 , 0.376138 } , { 0.565334 , 0.0590879 , 0.822743 } , { -0.992028 , 0.0890424 , 0.0891767 } , { 0.312534 , 0.691408 , 0.651366 } , { -0.875838 , 0.472331 , 0.0990485 } , { 0.334856 , -0.942047 , 0.0204675 } , { -0.125364 , -0.984977 , 0.118761 } , { -0.497613 , -0.806129 , 0.320213 } , { 0.559516 , 0.0195039 , 0.82859 } , { -0.609379 , -0.792875 , 0.00257254 } , { -0.902595 , -0.117893 , 0.414034 } , { 0.704823 , 0.649985 , 0.284155 } , { 0.584904 , -0.804553 , 0.102864 } , { -0.727364 , 0.674276 , 0.127642 } , { -0.911761 , -0.000150243 , 0.410722 } , { -0.99389 , -0.108412 , 0.0207353 } , { -0.40234 , 0.288458 , 0.868858 } , { 0.278518 , -0.23088 , 0.932267 } , { -0.252979 , -0.940588 , 0.226487 } , { -0.476927 , 0.201844 , 0.855453 } , { -0.838985 , -0.478599 , 0.258936 } , { 0.328574 , 0.81266 , 0.481273 } , { -0.810767 , -0.449245 , 0.375282 } , { 0.765292 , -0.57037 , 0.298339 } , { 0.589559 , -0.789167 , 0.172151 } , { 0.10944 , -0.394271 , 0.912454 } , { 0.788405 , -0.560077 , 0.254424 } , { 0.246038 , -0.511497 , 0.823308 } , { -0.853767 , 0.132614 , 0.503484 } , { 0.774539 , -0.213967 , 0.595237 } , { -0.110172 , -0.28889 , 0.951002 } , { -0.842985 , 0.535495 , 0.0512097 } , { 0.580131 , 0.0301411 , 0.813965 } , { 0.908925 , -0.116136 , 0.400459 } , { -0.625472 , 0.649147 , 0.43289 } , { 0.558774 , -0.812148 , 0.167891 } , { 0.230474 , 0.347007 , 0.909103 } , { -0.105795 , 0.991955 , 0.0695239 } , { -0.640253 , 0.560236 , 0.525558 } , { 0.419539 , -0.845648 , 0.329948 } , { -0.225489 , -0.850371 , 0.475419 } , { -0.492912 , -0.410376 , 0.767222 } , { -0.617174 , -0.109886 , 0.779116 } , { 0.326556 , -0.383888 , 0.863708 } , { 0.664892 , 0.746907 , 0.00703597 } , { 0.924311 , -0.12256 , 0.361425 } , { 0.205385 , -0.729426 , 0.652498 } , { -0.852246 , 0.473653 , 0.222102 } , { 0.344869 , 0.850976 , 0.396112 } , { -0.972872 , -0.112911 , 0.201919 } , { -0.190017 , 0.438384 , 0.878472 } , { -0.958015 , -0.0924744 , 0.271396 } , { 0.266771 , -0.196227 , 0.943572 } , { -0.229298 , -0.870471 , 0.435549 } , { 0.777292 , -0.267766 , 0.569314 } , { 0.350124 , 0.0495305 , 0.935393 } , { 0.56476 , 0.764048 , 0.311893 } , { 0.0990969 , -0.958941 , 0.265729 } , { 0.700681 , 0.301741 , 0.646528 } , { -0.410066 , -0.875055 , 0.257146 } , { 0.868634 , -0.295203 , 0.397907 } , { 0.722704 , 0.115409 , 0.681454 } , { -0.83569 , -0.261247 , 0.483086 } , { -0.956946 , -0.26818 , 0.111061 } , { -0.471397 , 0.707804 , 0.526117 } , { 0.142281 , -0.460376 , 0.876248 } , { -0.848155 , 0.424277 , 0.31721 } , { 0.633217 , 0.677636 , 0.373958 } , { 0.774101 , 0.527833 , 0.349515 } , { 0.566104 , 0.46772 , 0.678796 } , { 0.689802 , -0.719004 , 0.0848926 } , { 0.307254 , 0.914121 , 0.264532 } , { 0.0268339 , -0.281412 , 0.959212 } , { 0.120226 , 0.348506 , 0.929564 } , { -0.62591 , -0.415976 , 0.659698 } , { -0.64528 , -0.118069 , 0.754768 } , { 0.97028 , 0.227512 , 0.082431 } , { 0.0923899 , -0.442515 , 0.891989 } , { -0.985441 , 0.00944439 , 0.169757 } , { -0.40892 , 0.843814 , 0.347509 } , { 0.723835 , -0.613341 , 0.316031 } , { -0.648807 , -0.00240352 , 0.760949 } , { -0.708918 , 0.31984 , 0.6286 } , { 0.6173 , 0.741834 , 0.261961 } , { 0.32308 , -0.0608347 , 0.944414 } , { 0.782464 , 0.369637 , 0.501117 } , { -0.698584 , 0.642048 , 0.31584 } , { -0.547649 , 0.641426 , 0.537265 } , { 0.0736367 , 0.704049 , 0.706324 } , { 0.982237 , -0.144916 , 0.119208 } , { 0.865498 , -0.361769 , 0.346462 } , { 0.675221 , -0.737534 , 0.0109788 } , { 0.929646 , 0.364663 , 0.0527114 } , { -0.667761 , -0.257242 , 0.698514 } , { 0.462495 , -0.0673398 , 0.884061 } , { -0.525039 , 0.381695 , 0.760686 } , { 0.683212 , -0.000564444 , 0.73022 } , { 0.420557 , 0.885192 , 0.198913 } , { -0.971449 , -0.194974 , 0.13517 } , { -0.746171 , 0.190546 , 0.637904 } , { 0.909071 , 0.416623 , 0.00380576 } , { -0.191327 , 0.285436 , 0.939106 } , { 0.132169 , -0.414928 , 0.900203 } , { -0.663947 , -0.463146 , 0.587086 } , { 0.100529 , -0.992809 , 0.0649869 } , { -0.331074 , 0.403996 , 0.852747 } , { 0.707163 , 0.383667 , 0.593903 } , { -0.395927 , -0.79792 , 0.454495 } , { -0.497763 , 0.479399 , 0.722778 } , { 0.290656 , 0.833195 , 0.470431 } , { 0.715641 , 0.635401 , 0.290042 } , { 0.183316 , 0.963909 , 0.193069 } , { 0.972824 , -0.0178622 , 0.230854 } , { 0.574369 , 0.178051 , 0.798998 } , { 0.0656519 , 0.326844 , 0.942795 } , { -0.98156 , -0.190474 , 0.0160997 } , { -0.795229 , -0.196193 , 0.57369 } , { 0.0793034 , 0.964727 , 0.251024 } , { 0.826061 , 0.460539 , 0.324848 } , { 0.50979 , -0.542397 , 0.667772 } , { -0.79576 , 0.522625 , 0.305988 } , { -0.845024 , -0.274884 , 0.458664 } , { 0.962671 , -0.26935 , 0.0267422 } , { 0.591278 , 0.593062 , 0.546505 } , { -0.916858 , 0.223392 , 0.33086 } , { -0.28375 , -0.710783 , 0.64364 } , { -0.860743 , 0.484853 , 0.155043 } , { 0.201168 , 0.536951 , 0.819277 } , { -0.357849 , 0.918334 , 0.169135 } , { 0.802802 , -0.294537 , 0.518418 } , { -0.00727225 , -0.99845 , 0.0551767 } , { -0.124085 , 0.289568 , 0.94908 } , { 0.527489 , -0.735428 , 0.425325 } , { 0.312386 , 0.312047 , 0.897241 } , { 0.383408 , -0.336884 , 0.859946 } , { 0.168695 , -0.985617 , 0.0100337 } , { 0.130254 , 0.800098 , 0.585557 } , { -0.138974 , 0.743561 , 0.654067 } , { 0.879539 , 0.309063 , 0.36179 } , { 0.584633 , 0.0569884 , 0.809294 } , { 0.0366785 , 0.246249 , 0.968512 } , { -0.759899 , -0.50441 , 0.410029 } }; // just define how many of them you want to keep: static unsigned int nDirs = 33; class NDirectionalBS{ unsigned int ndirs; std::vector< std::pair< double , double > > bounds; double minInterval , maxInterval; bool intervalsUpToDate; void updateIntervals() { minInterval = FLT_MAX; maxInterval = 0.0; for( unsigned int i = 0 ; i < ndirs ; ++i ) { double interval = maxValue(i) - minValue(i); minInterval = std::min( minInterval , interval ); maxInterval = std::max( maxInterval , interval ); } intervalsUpToDate = true; } public: NDirectionalBS() { ndirs = nDirs; bounds.resize(ndirs); for( unsigned int i = 0 ; i < ndirs ; ++i ) bounds[i] = std::pair< double , double >( FLT_MAX , -FLT_MAX ); intervalsUpToDate = true; minInterval = 0.0; maxInterval = 0.0; } NDirectionalBS( unsigned int n ) { assert( n < nDirs ); ndirs = n; bounds.resize(ndirs); for( unsigned int i = 0 ; i < ndirs ; ++i ) bounds[i] = std::pair< double , double >( FLT_MAX , -FLT_MAX ); intervalsUpToDate = true; minInterval = 0.0; maxInterval = 0.0; } void operator = ( const NDirectionalBS & rightSide ) { ndirs = rightSide.ndirs; bounds = rightSide.bounds; minInterval = rightSide.minInterval; maxInterval = rightSide.maxInterval; intervalsUpToDate = rightSide.intervalsUpToDate; } void set( const point3d & p ) { for( unsigned int i = 0 ; i < ndirs ; ++i ) { double dirPos = dirs[i][0]*p[0] + dirs[i][1]*p[1] + dirs[i][2]*p[2]; bounds[i].first = dirPos; bounds[i].second = dirPos; } intervalsUpToDate = true; minInterval = 0.0; maxInterval = 0.0; } void add( const point3d & p ) { for( unsigned int i = 0 ; i < ndirs ; ++i ) { double dirPos = dirs[i][0]*p[0] + dirs[i][1]*p[1] + dirs[i][2]*p[2]; bounds[i].first = std::min< double >( dirPos , bounds[i].first ); bounds[i].second = std::max< double >( dirPos , bounds[i].second ); } intervalsUpToDate = false; } void add( const NDirectionalBS & bs ) { for( unsigned int i = 0 ; i < ndirs ; ++i ) { bounds[i].first = std::min< double >( bounds[i].first , bs.minValue(i) ); bounds[i].second = std::max< double >( bounds[i].second , bs.maxValue(i) ); } intervalsUpToDate = false; } double minValue( unsigned int i ) const { return bounds[i].first; } double maxValue( unsigned int i ) const { return bounds[i].second; } double getMinInterval() { if( !intervalsUpToDate ) updateIntervals(); return minInterval; } double getMaxInterval() { if( !intervalsUpToDate ) updateIntervals(); return maxInterval; } inline double radius() { return getMinInterval() * 0.75; // return getMinInterval() * 0.55; // return getMinInterval() * 0.66; // return getMinInterval() * 0.55; // return getMinInterval() * 1.0; } }; } template< typename T > class BBOX { public: point3<T> bb,BB; BBOX() { clear(); } void clear() { bb[0] = FLT_MAX; BB[0] = -FLT_MAX; } bool isCleared() const { return bb[0] <= BB[0]; } template< class point_t > void set( const point_t & p ) { bb = point3<T>(p[0],p[1],p[2]); BB = point3<T>(p[0],p[1],p[2]); } template< class point_t > void set( const point_t & pbb, const point_t & pBB ) { bb = point3<T>(pbb[0],pbb[1],pbb[2]); BB = point3<T>(pBB[0],pBB[1],pBB[2]); } template< class point_t > void add( const point_t & p ) { bb = point3<T>::min( bb,p ); BB = point3<T>::max( BB,p ); } void add( const BBOX<T> & b ) { bb = point3<T>::min( bb,b.bb ); BB = point3<T>::max( BB,b.BB ); } T squareDiagonal() const { return (BB - bb).sqrnorm(); } inline T diagonal() const { return sqrt( (BB - bb).sqrnorm() ); } inline T radius() const { return diagonal() / 2.0; } inline T squareRadius() const { return squareDiagonal() / 4.0; } inline char getLargestExtent() const { if( BB[0] - bb[0] > BB[1] - bb[1] ) { if( BB[0] - bb[0] > BB[2] - bb[2] ) return 0; return 2; } else { if( BB[1] - bb[1] > BB[2] - bb[2] ) return 1; return 2; } } inline T getExtentValue(char i) const { return BB[i] - bb[i]; } inline T getLargestExtentValue() const { return getExtentValue( getLargestExtent() ); } template< class point_t > inline T getPseudoExtentInDirection( point_t const & dir ) const { return getExtentValue(0) * fabs(dir[0]) +getExtentValue(1) * fabs(dir[1]) +getExtentValue(2) * fabs(dir[2]); } inline void splitAlongAxis( char axis , T value , BBOX<T> & bbox1 , BBOX<T> & bbox2 ) { // for safety: value = std::max<T>( std::min<T>( value , BB[axis] ) , bb[axis] ); point3<T> BB1 = BB; BB1[axis] = value; point3<T> bb2 = bb; bb2[axis] = value; bbox1.set( bb , BB1 ); bbox2.set( bb2 , BB ); } }; typedef BBOX< float > BBOXf; typedef BBOX< double > BBOXd; template< typename T > class mat33 { public: typedef T type_t; //////////// CONSTRUCTORS ////////////// mat33<T>() { vals[0] = 0; vals[1] = 0; vals[2] = 0; vals[3] = 0; vals[4] = 0; vals[5] = 0; vals[6] = 0; vals[7] = 0; vals[8] = 0; } mat33<T>( T v1 , T v2 , T v3 , T v4 , T v5 , T v6 , T v7 , T v8 , T v9) { vals[0] = v1; vals[1] = v2; vals[2] = v3; vals[3] = v4; vals[4] = v5; vals[5] = v6; vals[6] = v7; vals[7] = v8; vals[8] = v9; } template< typename T2 > mat33<T>( const std::vector< T2 > & cc ) { for(int i = 0 ; i < 9 ; ++i ) vals[i]=cc[i]; } template< typename T2 > mat33<T>( const mat33< T2 > & m ) { for(int i = 0 ; i < 9 ; ++i ) vals[i] = (T)(m(i)); } bool isnan() const { return std::isnan(vals[0]) || std::isnan(vals[1]) || std::isnan(vals[2]) || std::isnan(vals[3]) || std::isnan(vals[4]) || std::isnan(vals[5]) || std::isnan(vals[6]) || std::isnan(vals[7]) || std::isnan(vals[8]); } ///////////// SET /////////////// inline void setIdentity() { vals[0] = 1; vals[1] = 0; vals[2] = 0; vals[3] = 0; vals[4] = 1; vals[5] = 0; vals[6] = 0; vals[7] = 0; vals[8] = 1; } inline void setZero() { vals[0] = 0; vals[1] = 0; vals[2] = 0; vals[3] = 0; vals[4] = 0; vals[5] = 0; vals[6] = 0; vals[7] = 0; vals[8] = 0; } template< typename T2 > void operator = (const mat33<T2> & m) { for( unsigned int c = 0 ; c < 9 ; ++c ) vals[c] = (T)(m(c)); } template< typename T2 > inline void set( const mat33<T2> & other ) { for(unsigned int i = 0 ; i < 9; ++i) vals[ i ] = (T)(other(i)); } void operator += (const mat33<T> & m) { for( unsigned int c = 0 ; c < 9 ; ++c ) vals[c] += m(c); } void operator -= (const mat33<T> & m) { for( unsigned int c = 0 ; c < 9 ; ++c ) vals[c] -= m(c); } void operator /= (double s) { for( unsigned int c = 0 ; c < 9 ; ++c ) vals[c] /= s; } //////// ACCESS TO COORDINATES ///////// T operator () (unsigned int i , unsigned int j) const { return vals[3*i + j]; } T & operator () (unsigned int i , unsigned int j) { return vals[3*i + j]; } T operator () (unsigned int v) const { return vals[v]; } T & operator () (unsigned int v) { return vals[v]; } T & getCoord(unsigned int i , unsigned int j) { return vals[3*i+j]; } T getCoord(unsigned int i , unsigned int j) const { return vals[3*i+j]; } T & getCoord(unsigned int i) { return vals[i]; } T getCoord(unsigned int i) const { return vals[i]; } //////// ACCESS TO ROWS / COLUMNS ///////// point3<T> getRow( unsigned int i ) const { return point3<T>( vals[3*i] , vals[3*i+1] , vals[3*i+2] ); } void setRow( unsigned int i , const point3<T> & p) { vals[3*i] = p[0]; vals[3*i+1] = p[1]; vals[3*i+2] = p[2]; } void setRows( const point3<T> & r1 , const point3<T> & r2 , const point3<T> & r3 ) { vals[3*0] = r1[0]; vals[3*0+1] = r1[1]; vals[3*0+2] = r1[2]; vals[3*1] = r2[0]; vals[3*1+1] = r2[1]; vals[3*1+2] = r2[2]; vals[3*2] = r3[0]; vals[3*2+1] = r3[1]; vals[3*2+2] = r3[2]; } point3<T> getCol(unsigned int j) const { return point3<T>( vals[j] , vals[3+j] , vals[6+j] ); } void setCol(unsigned int j , const point3<T> & p) { vals[j] = p[0]; vals[3+j] = p[1]; vals[6+j] = p[2]; } void setCols(const point3<T> & c1 , const point3<T> & c2 , const point3<T> & c3) { vals[0] = c1[0]; vals[3+0] = c1[1]; vals[6+0] = c1[2]; vals[1] = c2[0]; vals[3+1] = c2[1]; vals[6+1] = c2[2]; vals[2] = c3[0]; vals[3+2] = c3[1]; vals[6+2] = c3[2]; } //////// BASICS ///////// inline T sqrnorm() { return vals[0]*vals[0] + vals[1]*vals[1] + vals[2]*vals[2] + vals[3]*vals[3] + vals[4]*vals[4] + vals[5]*vals[5] + vals[6]*vals[6] + vals[7]*vals[7] + vals[8]*vals[8]; } inline T norm() { return sqrt( sqrnorm() ); } inline T determinant() const { return vals[0] * ( vals[4] * vals[8] - vals[7] * vals[5] ) - vals[1] * ( vals[3] * vals[8] - vals[6] * vals[5] ) + vals[2] * ( vals[3] * vals[7] - vals[6] * vals[4] ); } template< class point_t > inline T determinant_with_col0( point_t const & c ) const { return c[0] * ( vals[4] * vals[8] - vals[7] * vals[5] ) - vals[1] * ( c[1] * vals[8] - c[2] * vals[5] ) + vals[2] * ( c[1] * vals[7] - c[2] * vals[4] ); } template< class point_t > inline T determinant_with_col1( point_t const & c ) const { return vals[0] * ( c[1] * vals[8] - c[2] * vals[5] ) - c[0] * ( vals[3] * vals[8] - vals[6] * vals[5] ) + vals[2] * ( vals[3] * c[2] - vals[6] * c[1] ); } template< class point_t > inline T determinant_with_col2( point_t const & c ) const { return vals[0] * ( vals[4] * c[2] - vals[7] * c[1] ) - vals[1] * ( vals[3] * c[2] - vals[6] * c[1] ) + c[0] * ( vals[3] * vals[7] - vals[6] * vals[4] ); } void RSD( mat33<T> & R , mat33<T> & S ) const { mat33<T> U , Vt; T x,y,z; SVD(U,x,y,z,Vt); R = U * Vt; S = Vt.getTranspose() * mat33<T>::Diag(x,y,z)*Vt; } static mat33<T> pseudoInverse( mat33<T> const & m , bool & isRealInverse , double defaultValueForInverseSingularValue = 0.0 ) { T det = m.determinant(); if( fabs(det) != 0.0 ) { isRealInverse = true; return mat33<T>( m(1,1)*m(2,2) - m(2,1)*m(1,2) , m(0,2)*m(2,1) - m(0,1)*m(2,2) , m(0,1)*m(1,2) - m(0,2)*m(1,1) , m(1,2)*m(2,0) - m(1,0)*m(2,2) , m(0,0)*m(2,2) - m(0,2)*m(2,0) , m(0,2)*m(1,0) - m(0,0)*m(1,2) , m(1,0)*m(2,1) - m(1,1)*m(2,0) , m(0,1)*m(2,0) - m(0,0)*m(2,1) , m(0,0)*m(1,1) - m(0,1)*m(1,0) ) / det ; } // otherwise: isRealInverse = false; mat33<T> U ; T sx ; T sy ; T sz ; mat33<T> Vt; m.SVD(U,sx,sy,sz,Vt); T sxInv = sx == 0.0 ? 1.0 / sx : defaultValueForInverseSingularValue; T syInv = sy == 0.0 ? 1.0 / sy : defaultValueForInverseSingularValue; T szInv = sz == 0.0 ? 1.0 / sz : defaultValueForInverseSingularValue; return Vt.getTranspose() * mat33<T>::diag(sxInv , syInv , szInv) * U.getTranspose(); } // template< class point_t > // point_t solveLinearSystem(point_t const & rhs , bool & isPseudoInverse) const { // double det = determinant(); // double epsilonPrecision = 0.000001; // if( fabs(det) < epsilonPrecision ) { // isPseudoInverse = true; // mat33<T> U , Vt; double x,y,z; // SVD(U,x,y,z,Vt); // double xInv = fabs(x) < epsilonPrecision ? 0.0 : 1.0/x; // double yInv = fabs(y) < epsilonPrecision ? 0.0 : 1.0/y; // double zInv = fabs(z) < epsilonPrecision ? 0.0 : 1.0/z; // return Vt.getTranspose() * mat33<T>::diag(xInv,yInv,zInv) * U.getTranspose() * rhs; // } // isPseudoInverse = false; // return point_t( // determinant_with_col0(rhs) / det, // determinant_with_col1(rhs) / det, // determinant_with_col2(rhs) / det // ); // } inline T trace() const { return vals[0] + vals[4] + vals[8]; } //////// TRANSPOSE ///////// inline void transpose() { T xy = vals[1] , xz = vals[2] , yz = vals[5]; vals[1] = vals[3]; vals[3] = xy; vals[2] = vals[6]; vals[6] = xz; vals[5] = vals[7]; vals[7] = yz; } mat33<T> getTranspose() const { return mat33<T>(vals[0],vals[3],vals[6],vals[1],vals[4],vals[7],vals[2],vals[5],vals[8]); } //////// HARMONICITY (not needed usually) ///////// void coutHessianHarmonicity() { std::cout << "xx + yy + zz = " << (getCoord(0,0) + getCoord(1,1) + getCoord(2,2)) << std::endl << "xy - yx : " << getCoord(0,1) - getCoord(1,0) << std::endl << "yz - zy : " << getCoord(1,2) - getCoord(2,1) << std::endl << "xz - zx : " << getCoord(0,2) - getCoord(2,0) << std::endl; } void enforceHessianHarmonicity() { vals[8] = -vals[0] - vals[4]; vals[3] = vals[1]; vals[5] = vals[7]; vals[2] = vals[6]; } inline T harmonicityError() { return std::abs( vals[8] + vals[0] + vals[4] ) + std::abs( vals[3] - vals[1] ) + std::abs( vals[5] - vals[7] ) + std::abs( vals[2] - vals[6] ); } //////// VECTOR PRODUCTS ///////// void setVectorProduct( const point3<T> & v1 , const point3<T> & v2 ) { for( int i = 0 ; i < 3 ; ++i ) for( int j = 0 ; j < 3 ; ++j ) vals[ 3*i+j ] = v1[i]*v2[j]; } void addVectorProduct( const point3<T> & v1 , const point3<T> & v2 ) { for( int i = 0 ; i < 3 ; ++i ) for( int j = 0 ; j < 3 ; ++j ) vals[ 3*i+j ] += v1[i]*v2[j]; } //////////// ROTATION <-> AXIS/ANGLE ///////////// void getAxisAndAngleFromRotationMatrix( point3<T> & axis , T & angle ) const { angle = acos( (trace() - 1) / 2 ); axis[0] = vals[7] - vals[5]; axis[1] = vals[2] - vals[6]; axis[2] = vals[3] - vals[1]; axis.normalize(); } inline static mat33<T> getRotationMatrixFromAxisAndAngle( const point3<T> & axis , T angle ) { mat33<T> w = vectorial(axis); return Identity() + std::sin(angle) * w + ((T)(1.0) - std::cos(angle)) * w * w; } inline static mat33<T> getRotationMatrixMappingUnitsVec1ToVec2( const point3<T> & vec1 , const point3<T> & vec2 ) { point3<T> axis = point3<T>::cross( vec1,vec2 ); T nn = axis.norm(); if( nn <= 0.0000001 ) return mat33<T>::Identity(); T angle = std::asin( nn ); axis /= nn; return getRotationMatrixFromAxisAndAngle(axis,angle); } //////////////////// STATIC STANDARD MATRICES //////////////////////////// inline static mat33<T> Identity() { return mat33<T>(1,0,0 , 0,1,0 , 0,0,1); } inline static mat33<T> Zero() { return mat33<T>(0,0,0 , 0,0,0 , 0,0,0); } template< typename T2 > inline static mat33<T> diag( T2 x , T2 y ,T2 z ) { return mat33<T>(x,0,0 , 0,y,0 , 0,0,z); } inline static mat33<T> Rand() { return mat33<T>( -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ), -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX )); } template< class point_t > inline static mat33<T> getFromCols(const point_t & c1 , const point_t & c2 , const point_t & c3) { // 0 1 2 // 3 4 5 // 6 7 8 return mat33<T>( c1[0] , c2[0] , c3[0] , c1[1] , c2[1] , c3[1] , c1[2] , c2[2] , c3[2] ); } template< class point_t > inline static mat33<T> getFromRows(const point_t & r1 , const point_t & r2 , const point_t & r3) { // 0 1 2 // 3 4 5 // 6 7 8 return mat33<T>( r1[0] , r1[1] , r1[2] , r2[0] , r2[1] , r2[2] , r3[0] , r3[1] , r3[2] ); } inline static mat33<T> Rand( double min_value , double max_value ) { return mat33<T>( min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) ), min_value + (max_value - min_value) * ( (float)(rand()) / (float)( RAND_MAX ) )); } inline static mat33<T> Rand( double randMagnitude ) { T mabs = fabs(randMagnitude); return mat33<T>::Rand(-mabs,mabs); } inline static mat33<T> RandRotation() { point3<T> axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) , -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) , -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ); axis.normalize(); T angle = 2.0 * M_PI * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 ); return mat33<T>::getRotationMatrixFromAxisAndAngle( axis , angle ); } inline static mat33<T> RandRotation( T maxAngle ) { point3<T> axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) , -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) , -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ); axis.normalize(); T angle = maxAngle * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 ); return mat33<T>::getRotationMatrixFromAxisAndAngle( axis , angle ); } inline static mat33<T> createRandomRotation( point3<T> twistAxis , double maxTwist , double maxRotation ) { twistAxis.normalize(); point3<T> u = twistAxis.getOrthogonal(); u.normalize(); const point3<T> & v = point3<T>::cross(u,twistAxis); double uv_axis_angle = 2.0*M_PI * (double)(rand()) / (double)(RAND_MAX); const point3<T> & uv = cos(uv_axis_angle)*u + sin(uv_axis_angle)*v; double rotation_angle = maxRotation * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 ); double twist_angle = maxTwist * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 ); return mat33<T>::getRotationMatrixFromAxisAndAngle(uv , rotation_angle) * mat33<T>::getRotationMatrixFromAxisAndAngle(twistAxis , twist_angle); } // method defined as a standard Linear System Jacobian initialization (either Identity() or RandRotation()) inline static mat33<T> LSJacobianInit() { return mat33<T>::Identity(); } void SVD( mat33<T> & U , T & sx , T & sy , T & sz , mat33<T> & Vt ) const { #ifdef __USE_GSL_FOR_MAT33 gsl_matrix * u = gsl_matrix_alloc(3,3); for(unsigned int i = 0 ; i < 3; ++i) for(unsigned int j = 0 ; j < 3; ++j) gsl_matrix_set( u , i , j , this->getCoord(i,j) ); gsl_matrix * v = gsl_matrix_alloc(3,3); gsl_vector * s = gsl_vector_alloc(3); gsl_vector * work = gsl_vector_alloc(3); gsl_linalg_SV_decomp (u, v, s, work); sx = s->data[0]; sy = s->data[1]; sz = s->data[2]; for(unsigned int i = 0 ; i < 3; ++i) { for(unsigned int j = 0 ; j < 3; ++j) { U(i,j) = gsl_matrix_get( u , i , j ); Vt(i,j) = gsl_matrix_get( v , j , i ); } } gsl_matrix_free(u); gsl_matrix_free(v); gsl_vector_free(s); gsl_vector_free(work); #else assert( 0 && "You need to use a Linear Algebra Library in order to use mat33<T>::SVD !" ); #endif // a transformation T is given as R.B.S.Bt, R = rotation , B = local basis (rotation matrix), S = scales in the basis B // it can be obtained from the svd decomposition of T = U Sigma Vt : // B = V // S = Sigma // R = U.Vt } /////////////////// Projections onto Rotations : //////////////////// mat33<T> getRotationalPart() const { mat33<T> U,Vt; T sx,sy,sz; SVD(U,sx,sy,sz,Vt); const mat33<T> & res = U*Vt; if( res.determinant() < 0 ) { U(2) = -U(2); U(5) = -U(5); U(8) = -U(8); return U*Vt; } // else return res; } void setRotation() { mat33<T> U,Vt; T sx,sy,sz; SVD(U,sx,sy,sz,Vt); const mat33<T> & res = U*Vt; if( res.determinant() < 0 ) { U(2) = -U(2); U(5) = -U(5); U(8) = -U(8); set(U*Vt); return; } // else set(res); } void setRotation( double weight ) { mat33<T> U,Vt; T sx,sy,sz; SVD(U,sx,sy,sz,Vt); mat33<T> S( weight + (1-weight)*sx ,0,0,0,weight + (1-weight)*sy ,0,0,0, weight + (1-weight)*sz ); const mat33<T> & res = U*S*Vt; if( res.determinant() < 0 ) { S(8) = -S(8); set(U*S*Vt); return; } // else set(res); } void setSimilarity() { mat33<T> U,Vt; T sx,sy,sz; SVD(U,sx,sy,sz,Vt); mat33<T> S((sx+sy+sz)/3,0,0,0,(sx+sy+sz)/3,0,0,0,(sx+sy+sz)/3); const mat33<T> & res = U*S*Vt; if( res.determinant() < 0 ) { S(8) = -S(8); set(U* S * Vt); return; } // else set(res); } // TO CHECK WHAT'S BEST // what is the L2 projection on the set of matrices of the form R . B2 . diag[1 1 x] . B2^T ? // is U . V^T . B2 . diag[1 1 x] . B2^T enough ? void setRotationOnTangentPlane( const mat33<T> & B2 ) { // B2 is assumed to be an orthogonal matrix with B2(2) = normal of the tangent plane // SVD : mat33<T> U,Vt; T sx,sy,sz; SVD(U,sx,sy,sz,Vt); if( (U*Vt).determinant() < 0 ){ U(2) = -U(2); U(5) = -U(5); U(8) = -U(8); } const point3<T> & VtB2_col2 = ( Vt * B2 ).getCol(2); T lambda = sx * VtB2_col2[0] * VtB2_col2[0] + sy * VtB2_col2[1] * VtB2_col2[1] + sz * VtB2_col2[2] * VtB2_col2[2]; // if( (U*Vt).determinant() < 0 ){ lambda = -lambda; } mat33<T> NewScales = mat33<T>::Identity(); NewScales(2,2) = lambda; set( U * Vt * B2 * transposeProduct01( NewScales , B2 ) ); } void setRotationOnTangentPlane( const point3<T> & p_normal ) { // p_normal is assumed to be normalized // construction of B2 : 3x3 matrix that represents an orthogonal basis where B2(2) = p_normal point3<T> b1 = p_normal.getOrthogonal(); b1.normalize(); const point3<T> & b2 = point3<T>::cross( p_normal , b1 ); mat33<T> B2; B2.setCol( 0 , b1 ); B2.setCol( 1 , b2 ); B2.setCol( 2 , p_normal ); setRotationOnTangentPlane(B2); } ////////// Stupid products ///////////// // get the result of m1^T * m2: static mat33<T> transposeProduct10( const mat33<T> & m1 , const mat33<T> & m2 ) { return mat33<T>( m1(0)*m2(0) + m1(3)*m2(3) + m1(6)*m2(6) , m1(0)*m2(1) + m1(3)*m2(4) + m1(6)*m2(7) , m1(0)*m2(2) + m1(3)*m2(5) + m1(6)*m2(8) , m1(1)*m2(0) + m1(4)*m2(3) + m1(7)*m2(6) , m1(1)*m2(1) + m1(4)*m2(4) + m1(7)*m2(7) , m1(1)*m2(2) + m1(4)*m2(5) + m1(7)*m2(8) , m1(2)*m2(0) + m1(5)*m2(3) + m1(8)*m2(6) , m1(2)*m2(1) + m1(5)*m2(4) + m1(8)*m2(7) , m1(2)*m2(2) + m1(5)*m2(5) + m1(8)*m2(8) ); } // get the result of m1 * m2^T: static mat33<T> transposeProduct01( const mat33<T> & m1 , const mat33<T> & m2 ) { return mat33<T>( m1(0)*m2(0) + m1(1)*m2(1) + m1(2)*m2(2) , m1(0)*m2(3) + m1(1)*m2(4) + m1(2)*m2(5) , m1(0)*m2(6) + m1(1)*m2(7) + m1(2)*m2(8) , m1(3)*m2(0) + m1(4)*m2(1) + m1(5)*m2(2) , m1(3)*m2(3) + m1(4)*m2(4) + m1(5)*m2(5) , m1(3)*m2(6) + m1(4)*m2(7) + m1(5)*m2(8) , m1(6)*m2(0) + m1(7)*m2(1) + m1(8)*m2(2) , m1(6)*m2(3) + m1(7)*m2(4) + m1(8)*m2(5) , m1(6)*m2(6) + m1(7)*m2(7) + m1(8)*m2(8) ); } // get the result of m^T * m: mat33<T> selfTransposeProduct10( ) const { return mat33<T>( vals[0]*vals[0] + vals[3]*vals[3] + vals[6]*vals[6] , vals[0]*vals[1] + vals[3]*vals[4] + vals[6]*vals[7] , vals[0]*vals[2] + vals[3]*vals[5] + vals[6]*vals[8] , vals[1]*vals[0] + vals[4]*vals[3] + vals[7]*vals[6] , vals[1]*vals[1] + vals[4]*vals[4] + vals[7]*vals[7] , vals[1]*vals[2] + vals[4]*vals[5] + vals[7]*vals[8] , vals[2]*vals[0] + vals[5]*vals[3] + vals[8]*vals[6] , vals[2]*vals[1] + vals[5]*vals[4] + vals[8]*vals[7] , vals[2]*vals[2] + vals[5]*vals[5] + vals[8]*vals[8] ); } // get the result of m * m^T: mat33<T> selfTransposeProduct01( ) const { return mat33<T>( vals[0]*vals[0] + vals[1]*vals[1] + vals[2]*vals[2] , vals[0]*vals[3] + vals[1]*vals[4] + vals[2]*vals[5] , vals[0]*vals[6] + vals[1]*vals[7] + vals[2]*vals[8] , vals[3]*vals[0] + vals[4]*vals[1] + vals[5]*vals[2] , vals[3]*vals[3] + vals[4]*vals[4] + vals[5]*vals[5] , vals[3]*vals[6] + vals[4]*vals[7] + vals[5]*vals[8] , vals[6]*vals[0] + vals[7]*vals[1] + vals[8]*vals[2] , vals[6]*vals[3] + vals[7]*vals[4] + vals[8]*vals[5] , vals[6]*vals[6] + vals[7]*vals[7] + vals[8]*vals[8] ); } template< class point_t > inline static mat33<T> tensor( const point_t & p1 , const point_t & p2 ) { return mat33<T>( p1.x()*p2.x() , p1.x()*p2.y() , p1.x()*p2.z(), p1.y()*p2.x() , p1.y()*p2.y() , p1.y()*p2.z(), p1.z()*p2.x() , p1.z()*p2.y() , p1.z()*p2.z()); } template< class point_t > inline static mat33<T> vectorial( const point_t & p ) { return mat33<T>( 0 , -p.z() , p.y() , p.z() , 0 , - p.x() , - p.y() , p.x() , 0 ); } mat33<T> logOfRotation() const { point3<T> axis; double angle; this->getAxisAndAngleFromRotationMatrix(axis,angle); return angle * vectorial( axis ); } mat33<T> logToRotation() const { point3<T> axis( - (this->operator()(1,2)) , (this->operator()(0,2)) , - (this->operator()(0,1)) ); double angle = axis.norm(); axis.normalize(); return getRotationMatrixFromAxisAndAngle(axis , angle); } mat33<T> operator - () const { return mat33<T>( - vals[0],- vals[1],- vals[2],- vals[3],- vals[4],- vals[5],- vals[6],- vals[7],- vals[8] ); } private: T vals[9]; // will be noted as : // 0 1 2 // 3 4 5 // 6 7 8 }; typedef mat33< float > mat33f; typedef mat33< double > mat33d; template< typename T > mat33<T> operator + (const mat33<T> & m1 , const mat33<T> & m2) { return mat33<T>( m1(0)+m2(0) , m1(1)+m2(1) , m1(2)+m2(2) , m1(3)+m2(3) , m1(4)+m2(4) , m1(5)+m2(5) , m1(6)+m2(6) , m1(7)+m2(7) , m1(8)+m2(8) ); } template< typename T > mat33<T> operator - (const mat33<T> & m1 , const mat33<T> & m2) { return mat33<T>( m1(0)-m2(0) , m1(1)-m2(1) , m1(2)-m2(2) , m1(3)-m2(3) , m1(4)-m2(4) , m1(5)-m2(5) , m1(6)-m2(6) , m1(7)-m2(7) , m1(8)-m2(8) ); } template< typename T > mat33<T> operator * (int s , const mat33<T> & m) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator * (float s , const mat33<T> & m) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator * (double s , const mat33<T> & m) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator * (const mat33<T> & m , int s) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator * (const mat33<T> & m , float s) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator * (const mat33<T> & m , double s) { return mat33<T>( m(0)*s , m(1)*s , m(2)*s , m(3)*s , m(4)*s , m(5)*s , m(6)*s , m(7)*s , m(8)*s ); } template< typename T > mat33<T> operator / (const mat33<T> & m , int s) { return mat33<T>( m(0)/s , m(1)/s , m(2)/s , m(3)/s , m(4)/s , m(5)/s , m(6)/s , m(7)/s , m(8)/s ); } template< typename T > mat33<T> operator / (const mat33<T> & m , float s) { return mat33<T>( m(0)/s , m(1)/s , m(2)/s , m(3)/s , m(4)/s , m(5)/s , m(6)/s , m(7)/s , m(8)/s ); } template< typename T > mat33<T> operator / (const mat33<T> & m , double s) { return mat33<T>( m(0)/s , m(1)/s , m(2)/s , m(3)/s , m(4)/s , m(5)/s , m(6)/s , m(7)/s , m(8)/s ); } template< typename T > point3<T> operator * (const mat33<T> & m , const point3<T> & p) // computes m.p { return point3<T>( m(0)*p[0] + m(1)*p[1] + m(2)*p[2], m(3)*p[0] + m(4)*p[1] + m(5)*p[2], m(6)*p[0] + m(7)*p[1] + m(8)*p[2]); } template< typename T > point3<T> operator * (const point3<T> & p , const mat33<T> & m) // computes p^t . m = (m^t . p)^t { return point3<T>( m(0)*p[0] + m(3)*p[1] + m(6)*p[2], m(1)*p[0] + m(4)*p[1] + m(7)*p[2], m(2)*p[0] + m(5)*p[1] + m(8)*p[2]); } template< typename T > mat33<T> operator * (const mat33<T> & m1 , const mat33<T> & m2) { return mat33<T>( m1(0)*m2(0) + m1(1)*m2(3) + m1(2)*m2(6) , m1(0)*m2(1) + m1(1)*m2(4) + m1(2)*m2(7) , m1(0)*m2(2) + m1(1)*m2(5) + m1(2)*m2(8) , m1(3)*m2(0) + m1(4)*m2(3) + m1(5)*m2(6) , m1(3)*m2(1) + m1(4)*m2(4) + m1(5)*m2(7) , m1(3)*m2(2) + m1(4)*m2(5) + m1(5)*m2(8) , m1(6)*m2(0) + m1(7)*m2(3) + m1(8)*m2(6) , m1(6)*m2(1) + m1(7)*m2(4) + m1(8)*m2(7) , m1(6)*m2(2) + m1(7)*m2(5) + m1(8)*m2(8) ); } template< typename T > inline std::ostream & operator << (std::ostream & s , mat33< T > const & m) { s << m(0) << " \t" << m(1) << " \t" << m(2) << std::endl << m(3) << " \t" << m(4) << " \t" << m(5) << std::endl << m(6) << " \t" << m(7) << " \t" << m(8) << std::endl; return s; } #ifdef __USE_GSL_FOR_MAT33 template< typename T > class mat33staticsvd : public mat33< T > { private: gsl_matrix * u; gsl_matrix * v; gsl_vector * s; gsl_vector * work; bool svd_allocated; void allocate_svd() { if(svd_allocated) return; u = gsl_matrix_alloc(3,3); v = gsl_matrix_alloc(3,3); s = gsl_vector_alloc(3); work = gsl_vector_alloc(3); svd_allocated = true; } void free_svd() { if(!svd_allocated) return; gsl_matrix_free(u); gsl_matrix_free(v); gsl_vector_free(s); gsl_vector_free(work); svd_allocated = false; } public: mat33staticsvd<T>() : mat33< T >() , svd_allocated(false) { } mat33staticsvd<T>( T v1 , T v2 , T v3 , T v4 , T v5 , T v6 , T v7 , T v8 , T v9) : mat33< T >( v1 , v2 , v3 , v4 , v5 , v6 , v7 , v8 , v9) , svd_allocated(false) { } template< typename T2 > mat33staticsvd<T>( const std::vector< T2 > & cc ) : mat33< T >(cc) , svd_allocated(false) { } template< typename T2 > mat33staticsvd<T>( const mat33< T2 > & m ) : mat33< T >(m) , svd_allocated(false) { } ~mat33staticsvd<T>() { free_svd(); } void SVD( mat33<T> & U , T & sx , T & sy , T & sz , mat33<T> & Vt ) const { allocate_svd(); for(unsigned int i = 0 ; i < 3; ++i) for(unsigned int j = 0 ; j < 3; ++j) gsl_matrix_set( u , i , j , this->getCoord(i,j) ); gsl_linalg_SV_decomp (u, v, s, work); sx = s->data[0]; sy = s->data[1]; sz = s->data[2]; for(unsigned int i = 0 ; i < 3; ++i) { for(unsigned int j = 0 ; j < 3; ++j) { U(i,j) = gsl_matrix_get( u , i , j ); Vt(i,j) = gsl_matrix_get( v , j , i ); } } } }; #endif #endif
{ "alphanum_fraction": 0.491868702, "avg_line_length": 68.0057411273, "ext": "h", "hexsha": "2346c50d00018d2da6ca3d2d2bbb3fd09769e8c0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-11-07T10:50:09.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-07T10:50:09.000Z", "max_forks_repo_head_hexsha": "4bdee443cb54c71d6866ae96be9d22dd4a842b75", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jeudine/skinning-subdivision-surfaces", "max_forks_repo_path": "src/point3.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "4bdee443cb54c71d6866ae96be9d22dd4a842b75", "max_issues_repo_issues_event_max_datetime": "2020-06-22T11:56:31.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-08T13:23:01.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "jeudine/skinning-subdivision-surfaces", "max_issues_repo_path": "src/point3.h", "max_line_length": 420, "max_stars_count": 2, "max_stars_repo_head_hexsha": "4bdee443cb54c71d6866ae96be9d22dd4a842b75", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jeudine/skinning-subdivision-surfaces", "max_stars_repo_path": "src/point3.h", "max_stars_repo_stars_event_max_datetime": "2020-07-22T19:31:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-09T06:29:52.000Z", "num_tokens": 59124, "size": 130299 }
#ifndef EX_UTIL #define EX_UTIL #include <gsl/gsl_vector.h> typedef double (*db_fxy)(double x, double y); typedef double (*db_fx) (double); /* print_table_fxy * prints f(x,y) tables given range for x and y */ void print_table_fxy(db_fxy fun, double x_start, double x_end, double x_step, char xch, double y_start, double y_end, double y_step, char ych); /* * vec_linspace * returns a pointer to a gsl_vector from xlow (inclusive) to xhigh (exclusive) * with steps xstep */ gsl_vector *vec_linspace(double xlow, double xhigh, double xstep); /* * vec_fx * given a function db_fx and vector of xpoints xdata, returns a vector f(x) */ gsl_vector *vec_fx(db_fx f, gsl_vector *xdata); /* * vec_from_arr * generates a vector from double array */ gsl_vector *vec_from_arr(double *arr, int arr_len); /* * sign */ int sign(double x); #endif
{ "alphanum_fraction": 0.7093425606, "avg_line_length": 21.675, "ext": "h", "hexsha": "25b7ca90a945f96dbc13233d68678231dbafa38a", "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": "17319213c85f65850c7b017bb4f3030d978ba936", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "aa-m-sa/ex_gnuplot_util", "max_forks_repo_path": "ex_util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "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": "aa-m-sa/ex_gnuplot_util", "max_issues_repo_path": "ex_util.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "17319213c85f65850c7b017bb4f3030d978ba936", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "aa-m-sa/ex_gnuplot_util", "max_stars_repo_path": "ex_util.h", "max_stars_repo_stars_event_max_datetime": "2017-10-15T03:41:21.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-15T03:41:21.000Z", "num_tokens": 240, "size": 867 }
////////////////////////////////////////////////////////////////////////////////// // Stefano Allesina Dec 2009 // sallesina@uchicago.edu // Given a matrix generated by the niche model and a vector containing // the positions of the species used to generate the matrix, finds the likelihood. ////////////////////////////////////////////////////////////////////////////////// // Compile // gcc NewNicheLikelihood.c -o LNICHE -lgsl -lgslcblas -Wall -DHAVE_INLINE -O3 ////////////////////////////////////////////////////////////////////////////////// // Run // ./LNICHE 4 Matrix4.txt Vec4.txt // Where: // * 4 is the number of species // * Matrix4.txt is a text file containing a space separated adjacency matrix // where the rows are the resources and the cols are the consumers // * Vec4.txt is a space separated text file containing the positions (in [0,1.0]) // of the species ////////////////////////////////////////////////////////////////////////////////// // Output // NONE ////////////////////////////////////////////////////////////////////////////////// #include<stdio.h> #include<math.h> #include <stdlib.h> #include<gsl/gsl_math.h> #include<gsl/gsl_integration.h> #include<gsl/gsl_vector.h> #include<gsl/gsl_matrix.h> #include<gsl/gsl_rng.h> #include<gsl/gsl_randist.h> #include<gsl/gsl_cdf.h> #include<gsl/gsl_blas.h> #include<gsl/gsl_linalg.h> #include<gsl/gsl_permutation.h> #include<gsl/gsl_sort_vector_double.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_monte_miser.h> #include <gsl/gsl_monte_vegas.h> // GLOBAL FILE FOR OUTPUT FILE * FOUT; // Structure needed for numerical integration struct myP { double nlm1; double nl; double nr; double nrp1; double n; double beta;}; // UTILITIES int PrintAdjMat(gsl_matrix * X, int a){ int i,j; for (i=0;i<a;i++){ for (j=0;j<a;j++){ fprintf(FOUT,"%1.0f ",gsl_matrix_get(X,i,j)); } fprintf(FOUT,"\n"); } return 0; } int PrintVector(gsl_vector * X, int a){ int i; for (i=0;i<a;i++){ fprintf(FOUT,"%1.3f ",gsl_vector_get(X,i)); } fprintf(FOUT,"\n"); return 0; } // END UTILITIES // INTEGRATION FOR CONSUMERS double Inte(double x, void *p){ struct myP * params = (struct myP *)p; double nlm1=(params->nlm1); double nl=(params->nl); double nr=(params->nr); double nrp1=(params->nrp1); double n=(params->n); double beta=(params->beta); double res=0; res=gsl_ran_beta_pdf(x,1.0,beta); //fprintf(stderr,"Pdf %f\n",res); // Difference double c0,c1; double r2=(double )x*n/2.; if (x*n<=GSL_MIN_DBL(nr-nlm1,nrp1-nl)){ // case ' c0=GSL_MIN_DBL(n,nr-r2); c1=GSL_MIN_DBL(n,nl+r2); } else{ if (x*n<=GSL_MAX_DBL(nr-nlm1,nrp1-nl)){ // case '' if ((nr-nlm1)<=(nrp1-nl)){ // a<=b c0=GSL_MIN_DBL(n,nlm1+r2); c1=GSL_MIN_DBL(n,nl+r2); } else{ // b<a c0=GSL_MIN_DBL(n,nr-r2); c1=GSL_MIN_DBL(n,nrp1-r2); } } else{ // case ''' c0=GSL_MIN_DBL(n,nlm1+r2); c1=GSL_MIN_DBL(n,nrp1-r2); } } res*=(c1-c0); //fprintf(stderr,"Center %f (%f)\n",res,(c1-c0)); // Normalization if ((n+r2)<1.0){ res/=(n-r2); } else{ res/=(1.0-2.0*r2); } //fprintf(stderr,"Rescale %f\n",res); return (res); } double Integrate (double nlm1, double nl, double n, double nr, double nrp1, double Beta){ double error; double result; double low,upp; gsl_function F; struct myP params = { 0., 0., 0., 0., 0., 0.}; // setup the environment gsl_integration_workspace * w= gsl_integration_workspace_alloc (10000); params.beta=Beta; params.nlm1=nlm1; params.nl=nl; params.n=n; params.nr=nr; params.nrp1=nrp1; F.function = &Inte; F.params = &params; low=GSL_MIN_DBL((nr-nl)/n,1.0); upp=GSL_MIN_DBL((nrp1-nlm1)/n,1.0); gsl_integration_qags(&F,low,upp,0,1e-4,10000,w,&result, &error); //fprintf(stderr,"Prob %f\n",result); if (result==0.0) { fprintf(FOUT,"The diet is incompatible with the niche model!!\n"); return -10000.0; // The diet is impossible! } return log(result); } // INTEGRATION FOR BASAL SPECIES double InteBasal(double x, void *p){ struct myP * params = (struct myP *)p; double nlm1=(params->nlm1); double nrp1=(params->nrp1); double n=(params->n); double beta=(params->beta); double res=0; res=gsl_ran_beta_pdf(x,1.0,beta); double r2=(double )x*n/2.; double c1=nrp1-r2; double c0=nlm1+r2; res*=(c1-c0); //fprintf(stderr,"Center %f (%f)\n",res,(c1-c0)); // Normalization if ((n+r2)<1.0){ res/=(n-r2); } else{ res/=(1.0-2.0*r2); } return (res); } double IntegrateBasal(double GapLeft, double GapRight, double n, double Beta){ double error; double result; double low,upp; gsl_function F; struct myP params = { 0., 0., 0., 0., 0., 0.}; // setup the environment gsl_integration_workspace * w= gsl_integration_workspace_alloc (10000); params.beta=Beta; params.nlm1=GapLeft; params.nl=0.0; params.n=n; params.nr=0.0; params.nrp1=GapRight; F.function = &InteBasal; F.params = &params; low=GSL_MIN_DBL(0.0,1.0); upp=GSL_MIN_DBL((GapRight-GapLeft)/n,1.0); gsl_integration_qags(&F,low,upp,0,1e-4,10000,w,&result, &error); //fprintf(stderr,"Prob %f\n",result); if (result==0.0) { fprintf(FOUT,"The diet is incompatible with the niche model!!\n"); return -10000000.0; // The diet is impossible! } return (result); } // COMPUTE THE LIKELIHOOD OF A MATRIX PERFECTLY COMPATIBLE WITH THE NICHE MODEL double ComputeLikelihood(gsl_matrix *A, gsl_vector *Pos, int N, double Beta){ double Prob=0.0; int i,j; double nlm1, nl, n, nr, nrp1; double TmpProb; for (i=0;i<N;i++){ if (gsl_matrix_get(A,i,0)==1){ fprintf(FOUT,"The first species is not basal!!\n"); Prob-=100000000.0; } } if (Prob>-1.0) fprintf(FOUT,"First Sp 0, LogLikelihood Diet 0.0 (1.0)\n"); for (i=1;i<N;i++){ n=gsl_vector_get(Pos,i); nlm1=nl=0.0; nr=nrp1=1.0; // Find first prey for (j=0;j<N;j++){ if (gsl_matrix_get(A,j,i)==1){ nl=gsl_vector_get(Pos,j); if (j>0){ nlm1=gsl_vector_get(Pos,j-1); } break; } } if (nl>0.0){ // i is a predator // Find the last prey for (j=N-1;j>=0;j--){ if (gsl_matrix_get(A,j,i)==1){ nr=gsl_vector_get(Pos,j); if (j<(N-1)){ nrp1=gsl_vector_get(Pos,j+1); } break; } } // Now compute the probability TmpProb=0.0; //fprintf(stderr,"Computing probability of %d (%f %f %f %f %f) Beta: %f\n", i, nlm1, nl, n, nr, nrp1, Beta); TmpProb=Integrate(nlm1, nl, n, nr, nrp1, Beta); fprintf(FOUT,"Consumer Sp %d, LogLikelihood Diet %f (%f)\n",i,TmpProb,exp(TmpProb)); Prob+=TmpProb; } else{ TmpProb=0.0; // for each species compute the probability that the species is not eating any one in between double GapLeft, GapRight; for (j=0;j<=i;j++){ if (j==0){ GapLeft=0.0; } else{ GapLeft=gsl_vector_get(Pos,j-1); } GapRight=gsl_vector_get(Pos,j); //fprintf(stderr,"Left: %f Right:%f Cumulative: %f\n",GapLeft,GapRight,TmpProb); TmpProb+=IntegrateBasal(GapLeft,GapRight, n,Beta); } fprintf(FOUT,"Basal Sp %d, LogLikelihood Diet %f (%f)\n",i,log(TmpProb),TmpProb); // now that you have summed across all possibilities take the log and sum it Prob+=log(TmpProb); } } return Prob; } // READ THE MATRIX AND RUN THE PROBABILITY // Main int main(int argc, char *argv[]){ // First argument: number of species int Sp=atoi(argv[1]); char * FileMat=(argv[2]); char * FilePos=(argv[3]); // Read the matrix FILE * F; // matrix gsl_matrix * A =gsl_matrix_calloc(Sp,Sp); F=fopen(FileMat,"rb"); gsl_matrix_fscanf(F,A); fclose(F); int i,j; double C,Beta; C=Beta=0.0; // compute the C and Beta for (i=0;i<Sp;i++){ for (j=0;j<Sp;j++){ if(gsl_matrix_get(A,i,j)==1) C+=1.0; } } C=(double)C/(double)Sp/(double)Sp; Beta=((double) Sp -1.0)/(2.0*C*(double) Sp) -1.0; char OutFile[200]; sprintf(OutFile,"Output-%s",FileMat); if ((FOUT = fopen(OutFile, "w")) == NULL){ puts("Unable to open the file"); return 0; } // read the vector gsl_vector * Eta=gsl_vector_calloc(Sp); F=fopen(FilePos,"rb"); gsl_vector_fscanf(F,Eta); fclose(F); fprintf(FOUT,"Compatible Adjacency Matrix\n"); PrintAdjMat(A,Sp); fprintf(FOUT,"Species Positions\n"); PrintVector(Eta,Sp); fprintf(FOUT,"Beta: %f\n",Beta); fprintf(FOUT,"LogLikelihood: %f\n",ComputeLikelihood(A,Eta,Sp,Beta)); gsl_matrix_free(A); gsl_vector_free(Eta); fclose(FOUT); return 0; }
{ "alphanum_fraction": 0.6006263775, "avg_line_length": 27.1100628931, "ext": "c", "hexsha": "27ce56a3e93d3c22a25c64a38cf473df976acbba", "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": "52e1108f11a71340864aaca80e92b130f8442a58", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "StefanoAllesina/StefanoAllesina.github.io", "max_forks_repo_path": "assets/img/NewNicheLikelihood.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "52e1108f11a71340864aaca80e92b130f8442a58", "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": "StefanoAllesina/StefanoAllesina.github.io", "max_issues_repo_path": "assets/img/NewNicheLikelihood.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "52e1108f11a71340864aaca80e92b130f8442a58", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "StefanoAllesina/StefanoAllesina.github.io", "max_stars_repo_path": "assets/img/NewNicheLikelihood.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2855, "size": 8621 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_integration.h> #include "ccl.h" typedef struct{ double l; ccl_cosmology *cosmo; ccl_cl_tracer_collection_t *trc1; ccl_cl_tracer_collection_t *trc2; ccl_f2d_t *psp; int *status; } integ_cl_par; typedef struct{ int chipow; double l1; double l2; ccl_cosmology *cosmo; ccl_cl_tracer_collection_t *trc1; ccl_cl_tracer_collection_t *trc2; ccl_cl_tracer_collection_t *trc3; ccl_cl_tracer_collection_t *trc4; ccl_f3d_t *tsp; ccl_f1d_t *ker_extra; ccl_a_finder *finda; int *status; } integ_cov_par; static void update_chi_limits(ccl_cl_tracer_collection_t *trc, double *chimin, double *chimax, int is_union) { int itr; double chimin_h=1E15; double chimax_h=-1E15; for(itr=0; itr < trc->n_tracers; itr++) { if (trc->ts[itr]->chi_min < chimin_h) chimin_h = trc->ts[itr]->chi_min; if (trc->ts[itr]->chi_max > chimax_h) chimax_h = trc->ts[itr]->chi_max; } if(is_union) { if(chimin_h < *chimin) *chimin = chimin_h; if(chimax_h > *chimax) *chimax = chimax_h; } else { if(chimin_h > *chimin) *chimin = chimin_h; if(chimax_h < *chimax) *chimax = chimax_h; } } static void get_k_interval(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, double l, double *lkmin, double *lkmax) { int itr; // Loop through all tracers and find distance bounds double chi_min1 = 1E15; double chi_max1 = -1E15; for (itr=0; itr < trc1->n_tracers; itr++) { if (trc1->ts[itr]->chi_min < chi_min1) chi_min1 = trc1->ts[itr]->chi_min; if (trc1->ts[itr]->chi_max > chi_max1) chi_max1 = trc1->ts[itr]->chi_max; } double chi_min2 = 1E15; double chi_max2 = -1E15; for (itr=0; itr < trc2->n_tracers; itr++) { if (trc2->ts[itr]->chi_min < chi_min2) chi_min2 = trc2->ts[itr]->chi_min; if (trc2->ts[itr]->chi_max > chi_max2) chi_max2 = trc2->ts[itr]->chi_max; } // Find maximum of minima and minimum of maxima // (i.e. edges where the product of both kernels will have support). double chi_min = fmax(chi_min1, chi_min2); double chi_max = fmin(chi_max1, chi_max2); if (chi_min <= 0) chi_min = 0.5*(l+0.5)/cosmo->spline_params.K_MAX; // Don't go beyond kmax *lkmax = log(fmin(cosmo->spline_params.K_MAX, 2*(l+0.5)/chi_min)); *lkmin = log(fmax(cosmo->spline_params.K_MIN, (l+0.5)/chi_max)); } static double transfer_limber_single(ccl_cl_tracer_t *tr, double l, double lk, double k, double chi_l, double a_l, ccl_cosmology *cosmo, ccl_f2d_t *psp, int ignore_jbes_deriv, int *status) { double dd = 0; // Kernel and transfer evaluated at chi_l double w = ccl_cl_tracer_t_get_kernel(tr, chi_l, status); double t = ccl_cl_tracer_t_get_transfer(tr, lk,a_l, status); double fl = ccl_cl_tracer_t_get_f_ell(tr, l, status); if (tr->der_bessel < 1) { //We don't need l+1 dd = w*t; if (tr->der_bessel == -1) { //If we divide by (chi*k)^2 double lp1h = l+0.5; dd /= (lp1h*lp1h); } } else { // We will need l+1 if(ignore_jbes_deriv) dd = 0; else { // Compute chi_{l+1} and a_{l+1} double lp1h = l+0.5; double lp3h = l+1.5; double chi_lp = lp3h/k; double a_lp = ccl_scale_factor_of_chi(cosmo, chi_lp, status); // Compute power spectrum ratio there double pk_ratio = fabs(ccl_f2d_t_eval(psp, lk, a_lp, cosmo, status) / ccl_f2d_t_eval(psp, lk, a_l, cosmo, status)); // Compute kernel and trasfer at chi_{l+1} double w_p = ccl_cl_tracer_t_get_kernel(tr, chi_lp, status); double t_p = ccl_cl_tracer_t_get_transfer(tr, lk,a_lp, status); // sqrt(2l+1/2l+3) double sqell = sqrt(lp1h*pk_ratio/lp3h); if (tr->der_bessel == 1) dd = l*w*t/lp1h-sqell*w_p*t_p; else //we assume der_bessel=2 here to avoid extra if clause dd = sqell*2*w_p*t_p/lp3h - (0.25+2*l)*w*t/(lp1h*lp1h); } } return dd*fl; } static double transfer_limber_wrap(double l,double lk, double k, double chi, double a, ccl_cl_tracer_collection_t *trc, ccl_cosmology *cosmo,ccl_f2d_t *psp, int ignore_jbes_deriv, int *status) { int itr; double transfer = 0; for (itr=0; itr < trc->n_tracers; itr++) { transfer += transfer_limber_single( trc->ts[itr], l, lk, k, chi, a, cosmo, psp, ignore_jbes_deriv, status); if (*status != 0) return -1; } return transfer; } static double cl_integrand(double lk, void *params) { double d1, d2; integ_cl_par *p = (integ_cl_par *)params; double k = exp(lk); double chi = (p->l+0.5)/k; double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status); d1 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc1, p->cosmo, p->psp, 0, p->status); if (d1 == 0) return 0; d2 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc2, p->cosmo, p->psp, 0, p->status); if (d2 == 0) return 0; double pk = ccl_f2d_t_eval(p->psp, lk, a, p->cosmo, p->status); return k*pk*d1*d2; } static void integ_cls_limber_spline(ccl_cosmology *cosmo, integ_cl_par *ipar, double lkmin, double lkmax, double *result, int *status) { int ik; int nk = (int)(fmax((lkmax - lkmin) / cosmo->spline_params.DLOGK_INTEGRATION + 0.5, 1))+1; double *fk_arr = NULL; double *lk_arr = NULL; lk_arr = ccl_linear_spacing(lkmin, lkmax, nk); if(lk_arr == NULL) *status = CCL_ERROR_LOGSPACE; if(*status == 0) { fk_arr = malloc(nk * sizeof(double)); if(fk_arr == NULL) *status = CCL_ERROR_MEMORY; } if(*status == 0) { for(ik=0; ik<nk; ik++) { fk_arr[ik] = cl_integrand(lk_arr[ik], ipar); if(*(ipar->status)) { *status = *(ipar->status); break; } } } if(*status == 0) { ccl_integ_spline(1, nk, lk_arr, &fk_arr, 1, -1, result, gsl_interp_akima, status); } free(fk_arr); free(lk_arr); } static void integ_cls_limber_qag_quad(ccl_cosmology *cosmo, gsl_function *F, double lkmin, double lkmax, gsl_integration_workspace *w, double *result, double *eresult, int *status) { int gslstatus; size_t nevals; gsl_integration_cquad_workspace *w_cquad = NULL; // Integrate gslstatus = gsl_integration_qag(F, lkmin, lkmax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS, w, result, eresult); // Test if a round-off error occured in the evaluation of the integral // If so, try another integration function, more robust but potentially slower if (gslstatus == GSL_EROUND) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: integ_cls_limber_qag_quad(): " "Default GSL integration failure, attempting backup method."); w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w_cquad == NULL) *status = CCL_ERROR_MEMORY; if (*status == 0) { nevals = 0; gslstatus = gsl_integration_cquad(F, lkmin, lkmax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, w_cquad, result, eresult, &nevals); } } gsl_integration_cquad_workspace_free(w_cquad); if(*status == 0) *status = gslstatus; } void ccl_angular_cls_limber(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_f2d_t *psp, int nl_out, double *l_out, double *cl_out, ccl_integration_t integration_method, int *status) { // make sure to init core things for safety if (!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_limber(): distance splines have not been precomputed!"); return; } #pragma omp parallel shared(cosmo, trc1, trc2, l_out, cl_out, \ nl_out, status, psp, integration_method) \ default(none) { int clastatus, lind; integ_cl_par ipar; gsl_integration_workspace *w = NULL; int local_status = *status; gsl_function F; double lkmin, lkmax, l, result, eresult; if (local_status == 0) { // Set up integrating function parameters ipar.cosmo = cosmo; ipar.trc1 = trc1; ipar.trc2 = trc2; ipar.psp = psp; ipar.status = &clastatus; } if(integration_method == ccl_integration_qag_quad) { if (local_status == 0) { w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { local_status = CCL_ERROR_MEMORY; } } if (local_status == 0) { // Set up integrating function F.function = &cl_integrand; F.params = &ipar; } } #pragma omp for schedule(dynamic) for (lind=0; lind < nl_out; ++lind) { if (local_status == 0) { l = l_out[lind]; clastatus = 0; ipar.l = l; // Get integration limits get_k_interval(cosmo, trc1, trc2, l, &lkmin, &lkmax); // Integrate if(integration_method == ccl_integration_qag_quad) { integ_cls_limber_qag_quad(cosmo, &F, lkmin, lkmax, w, &result, &eresult, &local_status); } else if(integration_method == ccl_integration_spline) { integ_cls_limber_spline(cosmo, &ipar, lkmin, lkmax, &result, &local_status); } else local_status = CCL_ERROR_NOT_IMPLEMENTED; if ((*ipar.status == 0) && (local_status == 0)) { cl_out[lind] = result / (l+0.5); } else { ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cls_limber():"); cl_out[lind] = NAN; local_status = CCL_ERROR_INTEG; } } } gsl_integration_workspace_free(w); if (local_status) { #pragma omp atomic write *status = local_status; } } if (*status) { ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_limber(); integration error\n"); } } void ccl_angular_cls_nonlimber(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_f2d_t *psp, int nl_out, int *l_out, double *cl_out, int *status) { *status = CCL_ERROR_INCONSISTENT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cls_nonlimber(); non-Limber integrator not implemented yet\n"); } static double cov_integrand(double chi, void *params) { double d1, d2, d3, d4, tkk, ker=1; integ_cov_par *p = (integ_cov_par *)params; double k1=(p->l1+0.5)/chi; double k2=(p->l2+0.5)/chi; double lk1=log(k1); double lk2=log(k2); double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status); d1 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc1, p->cosmo, NULL, 1, p->status); if (d1 == 0) return 0; d2 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc2, p->cosmo, NULL, 1, p->status); if (d2 == 0) return 0; d3 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc3, p->cosmo, NULL, 1, p->status); if (d3 == 0) return 0; d4 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc4, p->cosmo, NULL, 1, p->status); if (d4 == 0) return 0; tkk = ccl_f3d_t_eval(p->tsp, lk1, lk2, a, p->finda, p->cosmo, p->status); if(p->ker_extra!=NULL) ker = ccl_f1d_t_eval(p->ker_extra, chi); return d1*d2*d3*d4*tkk*ker/pow(chi, p->chipow); } static void integ_cov_limber_spline(ccl_cosmology *cosmo, integ_cov_par *ipar, double chimin, double chimax, double *result, int *status) { int ichi; int nchi = (int)(fmax((chimax - chimin) / cosmo->spline_params.DCHI_INTEGRATION + 0.5, 1))+1; double *fchi_arr = NULL; double *chi_arr = NULL; chi_arr = ccl_linear_spacing(chimin, chimax, nchi); if(chi_arr == NULL) *status = CCL_ERROR_LOGSPACE; if(*status == 0) { fchi_arr = malloc(nchi * sizeof(double)); if(fchi_arr == NULL) *status = CCL_ERROR_MEMORY; } if(*status == 0) { for(ichi=0; ichi<nchi; ichi++) { fchi_arr[ichi] = cov_integrand(chi_arr[ichi], ipar); if(*(ipar->status)) { *status = *(ipar->status); break; } } } if(*status == 0) { ccl_integ_spline(1, nchi, chi_arr, &fchi_arr, 1, -1, result, gsl_interp_akima, status); } free(fchi_arr); free(chi_arr); } static void integ_cov_limber_qag_quad(ccl_cosmology *cosmo, gsl_function *F, double chimin, double chimax, gsl_integration_workspace *w, double *result, double *eresult, int *status) { int gslstatus; size_t nevals; gsl_integration_cquad_workspace *w_cquad = NULL; // Integrate gslstatus = gsl_integration_qag(F, chimin, chimax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, cosmo->gsl_params.N_ITERATION, cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS, w, result, eresult); // Test if a round-off error occured in the evaluation of the integral // If so, try another integration function, more robust but potentially slower if (gslstatus == GSL_EROUND) { ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cov_limber(): " "Default GSL integration failure, attempting backup method."); w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w_cquad == NULL) *status = CCL_ERROR_MEMORY; if (*status == 0) { nevals = 0; gslstatus = gsl_integration_cquad(F, chimin, chimax, 0, cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL, w_cquad, result, eresult, &nevals); } } gsl_integration_cquad_workspace_free(w_cquad); if(*status == 0) *status = gslstatus; } void ccl_angular_cl_covariance(ccl_cosmology *cosmo, ccl_cl_tracer_collection_t *trc1, ccl_cl_tracer_collection_t *trc2, ccl_cl_tracer_collection_t *trc3, ccl_cl_tracer_collection_t *trc4, ccl_f3d_t *tsp, int nl1_out, double *l1_out, int nl2_out, double *l2_out, double *cov_out, ccl_integration_t integration_method, int chi_exponent, ccl_f1d_t *kernel_extra, double prefactor_extra, int *status) { if(!cosmo->computed_distances) { *status = CCL_ERROR_DISTANCES_INIT; ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cl_limber(): distance splines have not been precomputed!"); return; } #pragma omp parallel shared(cosmo, trc1, trc2, trc3, trc4, tsp, \ nl1_out, l1_out, nl2_out, l2_out, cov_out, \ integration_method, chi_exponent, \ kernel_extra, prefactor_extra, status) \ default(none) { int clastatus, lind1,lind2; integ_cov_par ipar; gsl_integration_workspace *w = NULL; int local_status = *status; gsl_function F; double chimin, chimax; double l1, l2, result, eresult; ccl_a_finder *finda = ccl_a_finder_new_from_f3d(tsp); // Find integration limits chimin = 1E15; chimax = -1E15; update_chi_limits(trc1, &chimin, &chimax, 1); update_chi_limits(trc2, &chimin, &chimax, 0); update_chi_limits(trc3, &chimin, &chimax, 0); update_chi_limits(trc4, &chimin, &chimax, 0); if (local_status == 0) { // Set up integrating function parameters ipar.cosmo = cosmo; ipar.trc1 = trc1; ipar.trc2 = trc2; ipar.trc3 = trc3; ipar.trc4 = trc4; ipar.tsp = tsp; ipar.ker_extra = kernel_extra; ipar.finda = finda; ipar.status = &clastatus; ipar.chipow = chi_exponent; } if(integration_method == ccl_integration_qag_quad) { if (local_status == 0) { w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION); if (w == NULL) { local_status = CCL_ERROR_MEMORY; } } if (local_status == 0) { // Set up integrating function F.function = &cov_integrand; F.params = &ipar; } } #pragma omp for schedule(dynamic) for (lind1=0; lind1 < nl1_out; ++lind1) { l1 = l1_out[lind1]; ipar.l1 = l1; for (lind2=0; lind2 < nl2_out; ++lind2) { if (local_status == 0) { l2 = l2_out[lind2]; clastatus = 0; ipar.l2 = l2; // Integrate if(integration_method == ccl_integration_qag_quad) { integ_cov_limber_qag_quad(cosmo, &F, chimin, chimax, w, &result, &eresult, &local_status); } else if(integration_method == ccl_integration_spline) { integ_cov_limber_spline(cosmo, &ipar, chimin, chimax, &result, &local_status); } else local_status = CCL_ERROR_NOT_IMPLEMENTED; if ((*ipar.status == 0) && (local_status == 0)) { cov_out[lind1+nl1_out*lind2] = result * prefactor_extra; } else { ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cov_limber():"); cov_out[lind1+nl1_out*lind2] = NAN; local_status = CCL_ERROR_INTEG; } } } } gsl_integration_workspace_free(w); if (local_status) { #pragma omp atomic write *status = local_status; } ccl_a_finder_free(finda); } if (*status) { ccl_cosmology_set_status_message( cosmo, "ccl_cls.c: ccl_angular_cov_limber(); integration error\n"); } }
{ "alphanum_fraction": 0.5998277903, "avg_line_length": 30.3132137031, "ext": "c", "hexsha": "a92fe2a457d9a824f37f19ceb29831cd31f8a7c5", "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": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carlosggarcia/CCL", "max_forks_repo_path": "src/ccl_cls.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "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": "carlosggarcia/CCL", "max_issues_repo_path": "src/ccl_cls.c", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "f3fe6383e2cbb804a03ad07e4627de6f226780d7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carlosggarcia/CCL", "max_stars_repo_path": "src/ccl_cls.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5714, "size": 18582 }
#ifndef SQ_INCLUDE_GUARD_core_SharedRange_h_ #define SQ_INCLUDE_GUARD_core_SharedRange_h_ #include <gsl/gsl> #include <memory> #include <range/v3/range/concepts.hpp> #include <vector> namespace sq { template <typename R> requires ranges::cpp20::range<R> struct SharedRange { public: explicit SharedRange(const std::shared_ptr<R> &base) : base_{base} {} explicit SharedRange(std::shared_ptr<R> &&base) : base_{std::move(base)} {} constexpr SharedRange() noexcept = default; SharedRange(const SharedRange &) noexcept = default; SharedRange(SharedRange &&) noexcept = default; SharedRange &operator=(const SharedRange &) noexcept = default; SharedRange &operator=(SharedRange &&) noexcept = default; ~SharedRange() noexcept = default; auto begin() { Expects(base_ != nullptr); return ranges::begin(*base_); } auto end() { Expects(base_ != nullptr); return ranges::end(*base_); } private: // views must be semiregular, which means that SharedRange must have a // default constructor, which, unfortunately, means that we can't use // gsl::not_null here. std::shared_ptr<R> base_ = nullptr; }; } // namespace sq namespace ranges { template <typename R> inline constexpr bool enable_view<sq::SharedRange<R>> = true; } // namespace ranges namespace sq { static_assert(ranges::cpp20::range<SharedRange<std::vector<int>>>); static_assert(ranges::cpp20::view<SharedRange<std::vector<int>>>); static_assert(ranges::viewable_range<SharedRange<std::vector<int>>>); } // namespace sq #endif // SQ_INCLUDE_GUARD_core_SharedRange_h_
{ "alphanum_fraction": 0.7283090564, "avg_line_length": 27.224137931, "ext": "h", "hexsha": "f01b92d08f1f38027e5fa18d3a0b9389b83c4783", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/core/include/core/SharedRange.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/core/include/core/SharedRange.h", "max_line_length": 77, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/core/include/core/SharedRange.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": 392, "size": 1579 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * 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 * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Mon Mar 8 17:45:11 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddleinv 32 */ /* * This function contains 372 FP additions, 84 FP multiplications, * (or, 340 additions, 52 multiplications, 32 fused multiply/add), * 92 stack variables, and 128 memory accesses */ static const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618); static const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731); static const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812); static const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191); static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562); static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626); static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938); /* * Generator Id's : * $Id: exprdag.ml,v 1.36 1999/02/19 17:22:11 athena Exp $ * $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $ * $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $ */ void fftwi_no_twiddle_32(const fftw_complex *input, fftw_complex *output, int istride, int ostride) { fftw_real tmp7; fftw_real tmp339; fftw_real tmp70; fftw_real tmp313; fftw_real tmp97; fftw_real tmp215; fftw_real tmp179; fftw_real tmp241; fftw_real tmp14; fftw_real tmp314; fftw_real tmp77; fftw_real tmp340; fftw_real tmp182; fftw_real tmp216; fftw_real tmp104; fftw_real tmp242; fftw_real tmp153; fftw_real tmp236; fftw_real tmp53; fftw_real tmp60; fftw_real tmp287; fftw_real tmp336; fftw_real tmp360; fftw_real tmp290; fftw_real tmp293; fftw_real tmp294; fftw_real tmp170; fftw_real tmp233; fftw_real tmp333; fftw_real tmp359; fftw_real tmp164; fftw_real tmp234; fftw_real tmp173; fftw_real tmp237; fftw_real tmp22; fftw_real tmp318; fftw_real tmp343; fftw_real tmp85; fftw_real tmp112; fftw_real tmp185; fftw_real tmp220; fftw_real tmp245; fftw_real tmp29; fftw_real tmp321; fftw_real tmp342; fftw_real tmp92; fftw_real tmp119; fftw_real tmp184; fftw_real tmp223; fftw_real tmp244; fftw_real tmp126; fftw_real tmp229; fftw_real tmp38; fftw_real tmp45; fftw_real tmp278; fftw_real tmp329; fftw_real tmp357; fftw_real tmp281; fftw_real tmp284; fftw_real tmp285; fftw_real tmp143; fftw_real tmp226; fftw_real tmp326; fftw_real tmp356; fftw_real tmp137; fftw_real tmp227; fftw_real tmp146; fftw_real tmp230; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp3; fftw_real tmp177; fftw_real tmp66; fftw_real tmp96; fftw_real tmp6; fftw_real tmp95; fftw_real tmp69; fftw_real tmp178; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp1; fftw_real tmp2; fftw_real tmp64; fftw_real tmp65; ASSERT_ALIGNED_DOUBLE(); tmp1 = c_re(input[0]); tmp2 = c_re(input[16 * istride]); tmp3 = tmp1 + tmp2; tmp177 = tmp1 - tmp2; tmp64 = c_im(input[0]); tmp65 = c_im(input[16 * istride]); tmp66 = tmp64 + tmp65; tmp96 = tmp64 - tmp65; } { fftw_real tmp4; fftw_real tmp5; fftw_real tmp67; fftw_real tmp68; ASSERT_ALIGNED_DOUBLE(); tmp4 = c_re(input[8 * istride]); tmp5 = c_re(input[24 * istride]); tmp6 = tmp4 + tmp5; tmp95 = tmp4 - tmp5; tmp67 = c_im(input[8 * istride]); tmp68 = c_im(input[24 * istride]); tmp69 = tmp67 + tmp68; tmp178 = tmp67 - tmp68; } tmp7 = tmp3 + tmp6; tmp339 = tmp3 - tmp6; tmp70 = tmp66 + tmp69; tmp313 = tmp66 - tmp69; tmp97 = tmp95 + tmp96; tmp215 = tmp96 - tmp95; tmp179 = tmp177 - tmp178; tmp241 = tmp177 + tmp178; } { fftw_real tmp10; fftw_real tmp98; fftw_real tmp73; fftw_real tmp99; fftw_real tmp13; fftw_real tmp102; fftw_real tmp76; fftw_real tmp101; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp8; fftw_real tmp9; fftw_real tmp71; fftw_real tmp72; ASSERT_ALIGNED_DOUBLE(); tmp8 = c_re(input[4 * istride]); tmp9 = c_re(input[20 * istride]); tmp10 = tmp8 + tmp9; tmp98 = tmp8 - tmp9; tmp71 = c_im(input[4 * istride]); tmp72 = c_im(input[20 * istride]); tmp73 = tmp71 + tmp72; tmp99 = tmp71 - tmp72; } { fftw_real tmp11; fftw_real tmp12; fftw_real tmp74; fftw_real tmp75; ASSERT_ALIGNED_DOUBLE(); tmp11 = c_re(input[28 * istride]); tmp12 = c_re(input[12 * istride]); tmp13 = tmp11 + tmp12; tmp102 = tmp11 - tmp12; tmp74 = c_im(input[28 * istride]); tmp75 = c_im(input[12 * istride]); tmp76 = tmp74 + tmp75; tmp101 = tmp74 - tmp75; } tmp14 = tmp10 + tmp13; tmp314 = tmp10 - tmp13; tmp77 = tmp73 + tmp76; tmp340 = tmp76 - tmp73; { fftw_real tmp180; fftw_real tmp181; fftw_real tmp100; fftw_real tmp103; ASSERT_ALIGNED_DOUBLE(); tmp180 = tmp98 - tmp99; tmp181 = tmp102 + tmp101; tmp182 = K707106781 * (tmp180 + tmp181); tmp216 = K707106781 * (tmp180 - tmp181); tmp100 = tmp98 + tmp99; tmp103 = tmp101 - tmp102; tmp104 = K707106781 * (tmp100 + tmp103); tmp242 = K707106781 * (tmp103 - tmp100); } } { fftw_real tmp49; fftw_real tmp149; fftw_real tmp169; fftw_real tmp288; fftw_real tmp52; fftw_real tmp166; fftw_real tmp152; fftw_real tmp289; fftw_real tmp56; fftw_real tmp154; fftw_real tmp157; fftw_real tmp291; fftw_real tmp59; fftw_real tmp159; fftw_real tmp162; fftw_real tmp292; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp47; fftw_real tmp48; fftw_real tmp167; fftw_real tmp168; ASSERT_ALIGNED_DOUBLE(); tmp47 = c_re(input[31 * istride]); tmp48 = c_re(input[15 * istride]); tmp49 = tmp47 + tmp48; tmp149 = tmp47 - tmp48; tmp167 = c_im(input[31 * istride]); tmp168 = c_im(input[15 * istride]); tmp169 = tmp167 - tmp168; tmp288 = tmp167 + tmp168; } { fftw_real tmp50; fftw_real tmp51; fftw_real tmp150; fftw_real tmp151; ASSERT_ALIGNED_DOUBLE(); tmp50 = c_re(input[7 * istride]); tmp51 = c_re(input[23 * istride]); tmp52 = tmp50 + tmp51; tmp166 = tmp50 - tmp51; tmp150 = c_im(input[7 * istride]); tmp151 = c_im(input[23 * istride]); tmp152 = tmp150 - tmp151; tmp289 = tmp150 + tmp151; } { fftw_real tmp54; fftw_real tmp55; fftw_real tmp155; fftw_real tmp156; ASSERT_ALIGNED_DOUBLE(); tmp54 = c_re(input[3 * istride]); tmp55 = c_re(input[19 * istride]); tmp56 = tmp54 + tmp55; tmp154 = tmp54 - tmp55; tmp155 = c_im(input[3 * istride]); tmp156 = c_im(input[19 * istride]); tmp157 = tmp155 - tmp156; tmp291 = tmp155 + tmp156; } { fftw_real tmp57; fftw_real tmp58; fftw_real tmp160; fftw_real tmp161; ASSERT_ALIGNED_DOUBLE(); tmp57 = c_re(input[27 * istride]); tmp58 = c_re(input[11 * istride]); tmp59 = tmp57 + tmp58; tmp159 = tmp57 - tmp58; tmp160 = c_im(input[27 * istride]); tmp161 = c_im(input[11 * istride]); tmp162 = tmp160 - tmp161; tmp292 = tmp160 + tmp161; } { fftw_real tmp334; fftw_real tmp335; fftw_real tmp331; fftw_real tmp332; ASSERT_ALIGNED_DOUBLE(); tmp153 = tmp149 - tmp152; tmp236 = tmp149 + tmp152; tmp53 = tmp49 + tmp52; tmp60 = tmp56 + tmp59; tmp287 = tmp53 - tmp60; tmp334 = tmp49 - tmp52; tmp335 = tmp292 - tmp291; tmp336 = tmp334 - tmp335; tmp360 = tmp334 + tmp335; tmp290 = tmp288 + tmp289; tmp293 = tmp291 + tmp292; tmp294 = tmp290 - tmp293; tmp170 = tmp166 + tmp169; tmp233 = tmp169 - tmp166; tmp331 = tmp288 - tmp289; tmp332 = tmp56 - tmp59; tmp333 = tmp331 - tmp332; tmp359 = tmp332 + tmp331; { fftw_real tmp158; fftw_real tmp163; fftw_real tmp171; fftw_real tmp172; ASSERT_ALIGNED_DOUBLE(); tmp158 = tmp154 - tmp157; tmp163 = tmp159 + tmp162; tmp164 = K707106781 * (tmp158 + tmp163); tmp234 = K707106781 * (tmp158 - tmp163); tmp171 = tmp154 + tmp157; tmp172 = tmp162 - tmp159; tmp173 = K707106781 * (tmp171 + tmp172); tmp237 = K707106781 * (tmp172 - tmp171); } } } { fftw_real tmp18; fftw_real tmp106; fftw_real tmp81; fftw_real tmp110; fftw_real tmp21; fftw_real tmp109; fftw_real tmp84; fftw_real tmp107; fftw_real tmp316; fftw_real tmp317; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp16; fftw_real tmp17; fftw_real tmp79; fftw_real tmp80; ASSERT_ALIGNED_DOUBLE(); tmp16 = c_re(input[2 * istride]); tmp17 = c_re(input[18 * istride]); tmp18 = tmp16 + tmp17; tmp106 = tmp16 - tmp17; tmp79 = c_im(input[2 * istride]); tmp80 = c_im(input[18 * istride]); tmp81 = tmp79 + tmp80; tmp110 = tmp79 - tmp80; } { fftw_real tmp19; fftw_real tmp20; fftw_real tmp82; fftw_real tmp83; ASSERT_ALIGNED_DOUBLE(); tmp19 = c_re(input[10 * istride]); tmp20 = c_re(input[26 * istride]); tmp21 = tmp19 + tmp20; tmp109 = tmp19 - tmp20; tmp82 = c_im(input[10 * istride]); tmp83 = c_im(input[26 * istride]); tmp84 = tmp82 + tmp83; tmp107 = tmp82 - tmp83; } tmp22 = tmp18 + tmp21; tmp316 = tmp18 - tmp21; tmp317 = tmp81 - tmp84; tmp318 = tmp316 - tmp317; tmp343 = tmp316 + tmp317; tmp85 = tmp81 + tmp84; { fftw_real tmp108; fftw_real tmp111; fftw_real tmp218; fftw_real tmp219; ASSERT_ALIGNED_DOUBLE(); tmp108 = tmp106 - tmp107; tmp111 = tmp109 + tmp110; tmp112 = (K923879532 * tmp108) - (K382683432 * tmp111); tmp185 = (K923879532 * tmp111) + (K382683432 * tmp108); tmp218 = tmp106 + tmp107; tmp219 = tmp110 - tmp109; tmp220 = (K382683432 * tmp218) - (K923879532 * tmp219); tmp245 = (K382683432 * tmp219) + (K923879532 * tmp218); } } { fftw_real tmp25; fftw_real tmp116; fftw_real tmp88; fftw_real tmp114; fftw_real tmp28; fftw_real tmp113; fftw_real tmp91; fftw_real tmp117; fftw_real tmp319; fftw_real tmp320; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp23; fftw_real tmp24; fftw_real tmp86; fftw_real tmp87; ASSERT_ALIGNED_DOUBLE(); tmp23 = c_re(input[30 * istride]); tmp24 = c_re(input[14 * istride]); tmp25 = tmp23 + tmp24; tmp116 = tmp23 - tmp24; tmp86 = c_im(input[30 * istride]); tmp87 = c_im(input[14 * istride]); tmp88 = tmp86 + tmp87; tmp114 = tmp86 - tmp87; } { fftw_real tmp26; fftw_real tmp27; fftw_real tmp89; fftw_real tmp90; ASSERT_ALIGNED_DOUBLE(); tmp26 = c_re(input[6 * istride]); tmp27 = c_re(input[22 * istride]); tmp28 = tmp26 + tmp27; tmp113 = tmp26 - tmp27; tmp89 = c_im(input[6 * istride]); tmp90 = c_im(input[22 * istride]); tmp91 = tmp89 + tmp90; tmp117 = tmp89 - tmp90; } tmp29 = tmp25 + tmp28; tmp319 = tmp25 - tmp28; tmp320 = tmp88 - tmp91; tmp321 = tmp319 + tmp320; tmp342 = tmp320 - tmp319; tmp92 = tmp88 + tmp91; { fftw_real tmp115; fftw_real tmp118; fftw_real tmp221; fftw_real tmp222; ASSERT_ALIGNED_DOUBLE(); tmp115 = tmp113 + tmp114; tmp118 = tmp116 - tmp117; tmp119 = (K382683432 * tmp115) + (K923879532 * tmp118); tmp184 = (K923879532 * tmp115) - (K382683432 * tmp118); tmp221 = tmp114 - tmp113; tmp222 = tmp116 + tmp117; tmp223 = (K923879532 * tmp221) + (K382683432 * tmp222); tmp244 = (K382683432 * tmp221) - (K923879532 * tmp222); } } { fftw_real tmp34; fftw_real tmp122; fftw_real tmp142; fftw_real tmp279; fftw_real tmp37; fftw_real tmp139; fftw_real tmp125; fftw_real tmp280; fftw_real tmp41; fftw_real tmp127; fftw_real tmp130; fftw_real tmp282; fftw_real tmp44; fftw_real tmp132; fftw_real tmp135; fftw_real tmp283; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp32; fftw_real tmp33; fftw_real tmp140; fftw_real tmp141; ASSERT_ALIGNED_DOUBLE(); tmp32 = c_re(input[istride]); tmp33 = c_re(input[17 * istride]); tmp34 = tmp32 + tmp33; tmp122 = tmp32 - tmp33; tmp140 = c_im(input[istride]); tmp141 = c_im(input[17 * istride]); tmp142 = tmp140 - tmp141; tmp279 = tmp140 + tmp141; } { fftw_real tmp35; fftw_real tmp36; fftw_real tmp123; fftw_real tmp124; ASSERT_ALIGNED_DOUBLE(); tmp35 = c_re(input[9 * istride]); tmp36 = c_re(input[25 * istride]); tmp37 = tmp35 + tmp36; tmp139 = tmp35 - tmp36; tmp123 = c_im(input[9 * istride]); tmp124 = c_im(input[25 * istride]); tmp125 = tmp123 - tmp124; tmp280 = tmp123 + tmp124; } { fftw_real tmp39; fftw_real tmp40; fftw_real tmp128; fftw_real tmp129; ASSERT_ALIGNED_DOUBLE(); tmp39 = c_re(input[5 * istride]); tmp40 = c_re(input[21 * istride]); tmp41 = tmp39 + tmp40; tmp127 = tmp39 - tmp40; tmp128 = c_im(input[5 * istride]); tmp129 = c_im(input[21 * istride]); tmp130 = tmp128 - tmp129; tmp282 = tmp128 + tmp129; } { fftw_real tmp42; fftw_real tmp43; fftw_real tmp133; fftw_real tmp134; ASSERT_ALIGNED_DOUBLE(); tmp42 = c_re(input[29 * istride]); tmp43 = c_re(input[13 * istride]); tmp44 = tmp42 + tmp43; tmp132 = tmp42 - tmp43; tmp133 = c_im(input[29 * istride]); tmp134 = c_im(input[13 * istride]); tmp135 = tmp133 - tmp134; tmp283 = tmp133 + tmp134; } { fftw_real tmp327; fftw_real tmp328; fftw_real tmp324; fftw_real tmp325; ASSERT_ALIGNED_DOUBLE(); tmp126 = tmp122 - tmp125; tmp229 = tmp122 + tmp125; tmp38 = tmp34 + tmp37; tmp45 = tmp41 + tmp44; tmp278 = tmp38 - tmp45; tmp327 = tmp34 - tmp37; tmp328 = tmp283 - tmp282; tmp329 = tmp327 - tmp328; tmp357 = tmp327 + tmp328; tmp281 = tmp279 + tmp280; tmp284 = tmp282 + tmp283; tmp285 = tmp281 - tmp284; tmp143 = tmp139 + tmp142; tmp226 = tmp142 - tmp139; tmp324 = tmp279 - tmp280; tmp325 = tmp41 - tmp44; tmp326 = tmp324 - tmp325; tmp356 = tmp325 + tmp324; { fftw_real tmp131; fftw_real tmp136; fftw_real tmp144; fftw_real tmp145; ASSERT_ALIGNED_DOUBLE(); tmp131 = tmp127 - tmp130; tmp136 = tmp132 + tmp135; tmp137 = K707106781 * (tmp131 + tmp136); tmp227 = K707106781 * (tmp131 - tmp136); tmp144 = tmp127 + tmp130; tmp145 = tmp135 - tmp132; tmp146 = K707106781 * (tmp144 + tmp145); tmp230 = K707106781 * (tmp145 - tmp144); } } } { fftw_real tmp277; fftw_real tmp301; fftw_real tmp304; fftw_real tmp306; fftw_real tmp296; fftw_real tmp300; fftw_real tmp299; fftw_real tmp305; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp275; fftw_real tmp276; fftw_real tmp302; fftw_real tmp303; ASSERT_ALIGNED_DOUBLE(); tmp275 = tmp70 - tmp77; tmp276 = tmp22 - tmp29; tmp277 = tmp275 - tmp276; tmp301 = tmp276 + tmp275; tmp302 = tmp278 + tmp285; tmp303 = tmp294 - tmp287; tmp304 = K707106781 * (tmp302 + tmp303); tmp306 = K707106781 * (tmp303 - tmp302); } { fftw_real tmp286; fftw_real tmp295; fftw_real tmp297; fftw_real tmp298; ASSERT_ALIGNED_DOUBLE(); tmp286 = tmp278 - tmp285; tmp295 = tmp287 + tmp294; tmp296 = K707106781 * (tmp286 - tmp295); tmp300 = K707106781 * (tmp286 + tmp295); tmp297 = tmp7 - tmp14; tmp298 = tmp92 - tmp85; tmp299 = tmp297 + tmp298; tmp305 = tmp297 - tmp298; } c_im(output[28 * ostride]) = tmp277 - tmp296; c_im(output[12 * ostride]) = tmp277 + tmp296; c_re(output[20 * ostride]) = tmp299 - tmp300; c_re(output[4 * ostride]) = tmp299 + tmp300; c_im(output[20 * ostride]) = tmp301 - tmp304; c_im(output[4 * ostride]) = tmp301 + tmp304; c_re(output[28 * ostride]) = tmp305 - tmp306; c_re(output[12 * ostride]) = tmp305 + tmp306; } { fftw_real tmp31; fftw_real tmp311; fftw_real tmp310; fftw_real tmp312; fftw_real tmp62; fftw_real tmp63; fftw_real tmp94; fftw_real tmp307; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp15; fftw_real tmp30; fftw_real tmp308; fftw_real tmp309; ASSERT_ALIGNED_DOUBLE(); tmp15 = tmp7 + tmp14; tmp30 = tmp22 + tmp29; tmp31 = tmp15 + tmp30; tmp311 = tmp15 - tmp30; tmp308 = tmp281 + tmp284; tmp309 = tmp290 + tmp293; tmp310 = tmp308 + tmp309; tmp312 = tmp309 - tmp308; } { fftw_real tmp46; fftw_real tmp61; fftw_real tmp78; fftw_real tmp93; ASSERT_ALIGNED_DOUBLE(); tmp46 = tmp38 + tmp45; tmp61 = tmp53 + tmp60; tmp62 = tmp46 + tmp61; tmp63 = tmp46 - tmp61; tmp78 = tmp70 + tmp77; tmp93 = tmp85 + tmp92; tmp94 = tmp78 - tmp93; tmp307 = tmp78 + tmp93; } c_re(output[16 * ostride]) = tmp31 - tmp62; c_re(output[0]) = tmp31 + tmp62; c_im(output[8 * ostride]) = tmp63 + tmp94; c_im(output[24 * ostride]) = tmp94 - tmp63; c_im(output[16 * ostride]) = tmp307 - tmp310; c_im(output[0]) = tmp307 + tmp310; c_re(output[24 * ostride]) = tmp311 - tmp312; c_re(output[8 * ostride]) = tmp311 + tmp312; } { fftw_real tmp121; fftw_real tmp189; fftw_real tmp187; fftw_real tmp193; fftw_real tmp148; fftw_real tmp190; fftw_real tmp175; fftw_real tmp191; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp105; fftw_real tmp120; fftw_real tmp183; fftw_real tmp186; ASSERT_ALIGNED_DOUBLE(); tmp105 = tmp97 - tmp104; tmp120 = tmp112 - tmp119; tmp121 = tmp105 - tmp120; tmp189 = tmp105 + tmp120; tmp183 = tmp179 - tmp182; tmp186 = tmp184 - tmp185; tmp187 = tmp183 + tmp186; tmp193 = tmp183 - tmp186; } { fftw_real tmp138; fftw_real tmp147; fftw_real tmp165; fftw_real tmp174; ASSERT_ALIGNED_DOUBLE(); tmp138 = tmp126 - tmp137; tmp147 = tmp143 - tmp146; tmp148 = (K555570233 * tmp138) - (K831469612 * tmp147); tmp190 = (K831469612 * tmp138) + (K555570233 * tmp147); tmp165 = tmp153 - tmp164; tmp174 = tmp170 - tmp173; tmp175 = (K555570233 * tmp165) + (K831469612 * tmp174); tmp191 = (K555570233 * tmp174) - (K831469612 * tmp165); } { fftw_real tmp176; fftw_real tmp188; fftw_real tmp192; fftw_real tmp194; ASSERT_ALIGNED_DOUBLE(); tmp176 = tmp148 - tmp175; c_im(output[29 * ostride]) = tmp121 - tmp176; c_im(output[13 * ostride]) = tmp121 + tmp176; tmp188 = tmp148 + tmp175; c_re(output[21 * ostride]) = tmp187 - tmp188; c_re(output[5 * ostride]) = tmp187 + tmp188; tmp192 = tmp190 + tmp191; c_im(output[21 * ostride]) = tmp189 - tmp192; c_im(output[5 * ostride]) = tmp189 + tmp192; tmp194 = tmp191 - tmp190; c_re(output[29 * ostride]) = tmp193 - tmp194; c_re(output[13 * ostride]) = tmp193 + tmp194; } } { fftw_real tmp197; fftw_real tmp209; fftw_real tmp207; fftw_real tmp213; fftw_real tmp200; fftw_real tmp210; fftw_real tmp203; fftw_real tmp211; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp195; fftw_real tmp196; fftw_real tmp205; fftw_real tmp206; ASSERT_ALIGNED_DOUBLE(); tmp195 = tmp97 + tmp104; tmp196 = tmp185 + tmp184; tmp197 = tmp195 - tmp196; tmp209 = tmp195 + tmp196; tmp205 = tmp179 + tmp182; tmp206 = tmp112 + tmp119; tmp207 = tmp205 + tmp206; tmp213 = tmp205 - tmp206; } { fftw_real tmp198; fftw_real tmp199; fftw_real tmp201; fftw_real tmp202; ASSERT_ALIGNED_DOUBLE(); tmp198 = tmp126 + tmp137; tmp199 = tmp143 + tmp146; tmp200 = (K980785280 * tmp198) - (K195090322 * tmp199); tmp210 = (K195090322 * tmp198) + (K980785280 * tmp199); tmp201 = tmp153 + tmp164; tmp202 = tmp170 + tmp173; tmp203 = (K980785280 * tmp201) + (K195090322 * tmp202); tmp211 = (K980785280 * tmp202) - (K195090322 * tmp201); } { fftw_real tmp204; fftw_real tmp208; fftw_real tmp212; fftw_real tmp214; ASSERT_ALIGNED_DOUBLE(); tmp204 = tmp200 - tmp203; c_im(output[25 * ostride]) = tmp197 - tmp204; c_im(output[9 * ostride]) = tmp197 + tmp204; tmp208 = tmp200 + tmp203; c_re(output[17 * ostride]) = tmp207 - tmp208; c_re(output[ostride]) = tmp207 + tmp208; tmp212 = tmp210 + tmp211; c_im(output[17 * ostride]) = tmp209 - tmp212; c_im(output[ostride]) = tmp209 + tmp212; tmp214 = tmp211 - tmp210; c_re(output[25 * ostride]) = tmp213 - tmp214; c_re(output[9 * ostride]) = tmp213 + tmp214; } } { fftw_real tmp323; fftw_real tmp347; fftw_real tmp350; fftw_real tmp352; fftw_real tmp338; fftw_real tmp346; fftw_real tmp345; fftw_real tmp351; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp315; fftw_real tmp322; fftw_real tmp348; fftw_real tmp349; ASSERT_ALIGNED_DOUBLE(); tmp315 = tmp313 - tmp314; tmp322 = K707106781 * (tmp318 - tmp321); tmp323 = tmp315 + tmp322; tmp347 = tmp315 - tmp322; tmp348 = (K382683432 * tmp329) - (K923879532 * tmp326); tmp349 = (K923879532 * tmp333) + (K382683432 * tmp336); tmp350 = tmp348 - tmp349; tmp352 = tmp348 + tmp349; } { fftw_real tmp330; fftw_real tmp337; fftw_real tmp341; fftw_real tmp344; ASSERT_ALIGNED_DOUBLE(); tmp330 = (K382683432 * tmp326) + (K923879532 * tmp329); tmp337 = (K382683432 * tmp333) - (K923879532 * tmp336); tmp338 = tmp330 + tmp337; tmp346 = tmp337 - tmp330; tmp341 = tmp339 - tmp340; tmp344 = K707106781 * (tmp342 - tmp343); tmp345 = tmp341 - tmp344; tmp351 = tmp341 + tmp344; } c_im(output[22 * ostride]) = tmp323 - tmp338; c_im(output[6 * ostride]) = tmp323 + tmp338; c_re(output[30 * ostride]) = tmp345 - tmp346; c_re(output[14 * ostride]) = tmp345 + tmp346; c_im(output[30 * ostride]) = tmp347 - tmp350; c_im(output[14 * ostride]) = tmp347 + tmp350; c_re(output[22 * ostride]) = tmp351 - tmp352; c_re(output[6 * ostride]) = tmp351 + tmp352; } { fftw_real tmp355; fftw_real tmp367; fftw_real tmp370; fftw_real tmp372; fftw_real tmp362; fftw_real tmp366; fftw_real tmp365; fftw_real tmp371; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp353; fftw_real tmp354; fftw_real tmp368; fftw_real tmp369; ASSERT_ALIGNED_DOUBLE(); tmp353 = tmp314 + tmp313; tmp354 = K707106781 * (tmp343 + tmp342); tmp355 = tmp353 + tmp354; tmp367 = tmp353 - tmp354; tmp368 = (K923879532 * tmp357) - (K382683432 * tmp356); tmp369 = (K382683432 * tmp359) + (K923879532 * tmp360); tmp370 = tmp368 - tmp369; tmp372 = tmp368 + tmp369; } { fftw_real tmp358; fftw_real tmp361; fftw_real tmp363; fftw_real tmp364; ASSERT_ALIGNED_DOUBLE(); tmp358 = (K923879532 * tmp356) + (K382683432 * tmp357); tmp361 = (K923879532 * tmp359) - (K382683432 * tmp360); tmp362 = tmp358 + tmp361; tmp366 = tmp361 - tmp358; tmp363 = tmp339 + tmp340; tmp364 = K707106781 * (tmp318 + tmp321); tmp365 = tmp363 - tmp364; tmp371 = tmp363 + tmp364; } c_im(output[18 * ostride]) = tmp355 - tmp362; c_im(output[2 * ostride]) = tmp355 + tmp362; c_re(output[26 * ostride]) = tmp365 - tmp366; c_re(output[10 * ostride]) = tmp365 + tmp366; c_im(output[26 * ostride]) = tmp367 - tmp370; c_im(output[10 * ostride]) = tmp367 + tmp370; c_re(output[18 * ostride]) = tmp371 - tmp372; c_re(output[2 * ostride]) = tmp371 + tmp372; } { fftw_real tmp225; fftw_real tmp249; fftw_real tmp247; fftw_real tmp253; fftw_real tmp232; fftw_real tmp250; fftw_real tmp239; fftw_real tmp251; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp217; fftw_real tmp224; fftw_real tmp243; fftw_real tmp246; ASSERT_ALIGNED_DOUBLE(); tmp217 = tmp215 - tmp216; tmp224 = tmp220 - tmp223; tmp225 = tmp217 + tmp224; tmp249 = tmp217 - tmp224; tmp243 = tmp241 - tmp242; tmp246 = tmp244 - tmp245; tmp247 = tmp243 - tmp246; tmp253 = tmp243 + tmp246; } { fftw_real tmp228; fftw_real tmp231; fftw_real tmp235; fftw_real tmp238; ASSERT_ALIGNED_DOUBLE(); tmp228 = tmp226 - tmp227; tmp231 = tmp229 - tmp230; tmp232 = (K195090322 * tmp228) + (K980785280 * tmp231); tmp250 = (K195090322 * tmp231) - (K980785280 * tmp228); tmp235 = tmp233 - tmp234; tmp238 = tmp236 - tmp237; tmp239 = (K195090322 * tmp235) - (K980785280 * tmp238); tmp251 = (K980785280 * tmp235) + (K195090322 * tmp238); } { fftw_real tmp240; fftw_real tmp248; fftw_real tmp252; fftw_real tmp254; ASSERT_ALIGNED_DOUBLE(); tmp240 = tmp232 + tmp239; c_im(output[23 * ostride]) = tmp225 - tmp240; c_im(output[7 * ostride]) = tmp225 + tmp240; tmp248 = tmp239 - tmp232; c_re(output[31 * ostride]) = tmp247 - tmp248; c_re(output[15 * ostride]) = tmp247 + tmp248; tmp252 = tmp250 - tmp251; c_im(output[31 * ostride]) = tmp249 - tmp252; c_im(output[15 * ostride]) = tmp249 + tmp252; tmp254 = tmp250 + tmp251; c_re(output[23 * ostride]) = tmp253 - tmp254; c_re(output[7 * ostride]) = tmp253 + tmp254; } } { fftw_real tmp257; fftw_real tmp269; fftw_real tmp267; fftw_real tmp273; fftw_real tmp260; fftw_real tmp270; fftw_real tmp263; fftw_real tmp271; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp255; fftw_real tmp256; fftw_real tmp265; fftw_real tmp266; ASSERT_ALIGNED_DOUBLE(); tmp255 = tmp215 + tmp216; tmp256 = tmp245 + tmp244; tmp257 = tmp255 + tmp256; tmp269 = tmp255 - tmp256; tmp265 = tmp241 + tmp242; tmp266 = tmp220 + tmp223; tmp267 = tmp265 - tmp266; tmp273 = tmp265 + tmp266; } { fftw_real tmp258; fftw_real tmp259; fftw_real tmp261; fftw_real tmp262; ASSERT_ALIGNED_DOUBLE(); tmp258 = tmp226 + tmp227; tmp259 = tmp229 + tmp230; tmp260 = (K831469612 * tmp258) + (K555570233 * tmp259); tmp270 = (K831469612 * tmp259) - (K555570233 * tmp258); tmp261 = tmp233 + tmp234; tmp262 = tmp236 + tmp237; tmp263 = (K831469612 * tmp261) - (K555570233 * tmp262); tmp271 = (K555570233 * tmp261) + (K831469612 * tmp262); } { fftw_real tmp264; fftw_real tmp268; fftw_real tmp272; fftw_real tmp274; ASSERT_ALIGNED_DOUBLE(); tmp264 = tmp260 + tmp263; c_im(output[19 * ostride]) = tmp257 - tmp264; c_im(output[3 * ostride]) = tmp257 + tmp264; tmp268 = tmp263 - tmp260; c_re(output[27 * ostride]) = tmp267 - tmp268; c_re(output[11 * ostride]) = tmp267 + tmp268; tmp272 = tmp270 - tmp271; c_im(output[27 * ostride]) = tmp269 - tmp272; c_im(output[11 * ostride]) = tmp269 + tmp272; tmp274 = tmp270 + tmp271; c_re(output[19 * ostride]) = tmp273 - tmp274; c_re(output[3 * ostride]) = tmp273 + tmp274; } } } fftw_codelet_desc fftwi_no_twiddle_32_desc = { "fftwi_no_twiddle_32", (void (*)()) fftwi_no_twiddle_32, 32, FFTW_BACKWARD, FFTW_NOTW, 521, 0, (const int *) 0, };
{ "alphanum_fraction": 0.5841750842, "avg_line_length": 29.6145733461, "ext": "c", "hexsha": "bda4c376d5f1ed86a746a734c6540855246de05b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "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": "jlprieur/jlplib", "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9442, "size": 30888 }
#pragma once #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_cdf.h> #include <QVector> #include <algorithm> #include <tuple> class Gaussian1DFit { struct data { double* x; double* y; size_t n; }; enum { numOfPara = 4 }; /* model function: a * exp( -1/2 * [ (t - b) / c ]^2 ) + d */ private: gsl_vector* p0; /* initial fitting parameters:amplitude,center,width,offset*/ gsl_vector* p; /* fitting parameters */ gsl_vector* f; /* residual yi-y(xi) */ gsl_matrix* covar; /*covariance matrix, not yet multiplied by sigma, so is not variance-covariance matrix*/ gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params; gsl_multifit_nlinear_workspace* work; data fit_data; size_t max_iter; double ptol; /* tolerance on fitting parameter p */ double gtol; /* tolerance on gradient */ double ftol; int info;/*fiting stop reason, for debug*/ double rss; /*mean of sum of residual square, dof corrected*/ gsl_vector* confid95; public: Gaussian1DFit() {}; Gaussian1DFit(size_t n, double* datax, double* datay, double a0, double b0, double c0, double d0, size_t max_iter = 200, double ptol = 1.0e-8, double gtol = 1.0e-8, double ftol = 1.0e-8); ~Gaussian1DFit(); void solve_system(); void set_data(double* datay); void set_data(size_t n, double* datax, double* datay, bool free = true); void set_initialP(double a0, double b0, double c0, double d0); static double gaussian(const double a, const double b, const double c, const double d, const double t); QVector<double> calcFittedGaussian(); const QVector<double> fittedPara() const; const QVector<double> confidence95Interval() const; private: static int func_f (const gsl_vector* p, void* datafit, gsl_vector* f); static int func_df(const gsl_vector* p, void* datafit, gsl_matrix* J); static int func_fvv(const gsl_vector* p, const gsl_vector* v, void* datafit, gsl_vector* fvv); };
{ "alphanum_fraction": 0.5633346823, "avg_line_length": 33.8493150685, "ext": "h", "hexsha": "a737af759bd66c936bee3ba74a7d410ecfeb5ecd", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/UI/Gaussian1DFit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "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/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/UI/Gaussian1DFit.h", "max_line_length": 133, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/VimbaCamJILA", "max_stars_repo_path": "VimbaCam/UI/Gaussian1DFit.h", "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": 606, "size": 2471 }
/** * nn.c * * Created by mizu-bai * * This is a implementation of Tensors Warm-up: numpy in LEARNING PYTORCH WITH EXAMPLES * (https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#) using C with GSL. */ #include <stdio.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_math.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> int main(int argc, const char *argv[]) { // create random input and output data int size = 2000; gsl_vector *x = gsl_vector_alloc(size); gsl_vector *y = gsl_vector_alloc(size); for (int i = 0; i < size; i++) { double x_tmp = 2 * M_PI / (double)(size - 1) * (double)i - M_PI; gsl_vector_set(x, i, x_tmp); gsl_vector_set(y, i, sin(x_tmp)); } // randomly init weights int w_size = 4; gsl_vector *w = gsl_vector_alloc(w_size); gsl_rng *r = gsl_rng_alloc(gsl_rng_default); for (int i = 0; i < w_size; i++) { gsl_vector_set(w, i, gsl_ran_gaussian(r, 1.0)); } gsl_rng_free(r); double learning_rate = 1e-6; for(int t = 0; t < 2000; t++) { // forward pass, compute predicted y & compute loss gsl_vector *y_pred = gsl_vector_alloc(size); double loss = 0; for (int i = 0; i < size; i++) { double w_tmp = gsl_poly_eval(w->data, w_size, gsl_vector_get(x, i)); gsl_vector_set(y_pred, i, w_tmp); loss += gsl_pow_2(gsl_vector_get(y_pred, i) - gsl_vector_get(y, i)); } if (t % 100 == 99) { printf("t: %d, loss: %.4f\n", t, loss); } // compute gradients of w with respect to loss gsl_vector *grad_y_pred = gsl_vector_alloc(size); gsl_vector_memcpy(grad_y_pred, y_pred); gsl_vector_sub(grad_y_pred, y); gsl_vector_scale(grad_y_pred, 2); gsl_vector *grad_w = gsl_vector_alloc(w_size); gsl_vector_set_all(grad_w, 0.0); for(int i = 0; i < size; i++) { gsl_vector *grad_y_pred_tmp = gsl_vector_alloc(size); gsl_vector *x_tmp = gsl_vector_alloc(size); gsl_vector_set(grad_w, 0, gsl_vector_get(grad_w, 0) + gsl_vector_get(grad_y_pred, i)); gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred); gsl_vector_mul(grad_y_pred_tmp, x); gsl_vector_set(grad_w, 1, gsl_vector_get(grad_w, 1) + gsl_vector_get(grad_y_pred_tmp, i)); gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred); gsl_vector_memcpy(x_tmp, x); gsl_vector_mul(x_tmp, x); gsl_vector_mul(grad_y_pred_tmp, x_tmp); gsl_vector_set(grad_w, 2, gsl_vector_get(grad_w, 2) + gsl_vector_get(grad_y_pred_tmp, i)); gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred); gsl_vector_memcpy(x_tmp, x); gsl_vector_mul(x_tmp, x); gsl_vector_mul(x_tmp, x); gsl_vector_mul(grad_y_pred_tmp, x_tmp); gsl_vector_set(grad_w, 3, gsl_vector_get(grad_w, 3) + gsl_vector_get(grad_y_pred_tmp, i)); gsl_vector_free(grad_y_pred_tmp); gsl_vector_free(x_tmp); } gsl_vector_scale(grad_w, learning_rate); gsl_vector_sub(w, grad_w); // free gsl_vector_free(y_pred); gsl_vector_free(grad_y_pred); gsl_vector_free(grad_w); } printf("Result: y = %.4f + %.4f * x + %.4f * x^2 + %.4f * x^3\n", gsl_vector_get(w, 0), gsl_vector_get(w, 1), gsl_vector_get(w, 2), gsl_vector_get(w, 3)); // free gsl_vector_free(x); gsl_vector_free(y); gsl_vector_free(w); return 0; }
{ "alphanum_fraction": 0.6094479539, "avg_line_length": 35.3495145631, "ext": "c", "hexsha": "cc4e53675a37d4f243ada229d3257fc3a06e22d2", "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": "be9dd44c7a2d3433faa049e1217969d08dbac432", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "mizu-bai/Data-Science-Demos", "max_forks_repo_path": "nn-gsl/nn.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "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": "mizu-bai/Data-Science-Demos", "max_issues_repo_path": "nn-gsl/nn.c", "max_line_length": 158, "max_stars_count": 1, "max_stars_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mizu-bai/Data-Science-Demos", "max_stars_repo_path": "nn-gsl/nn.c", "max_stars_repo_stars_event_max_datetime": "2021-06-27T12:01:57.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-27T12:01:57.000Z", "num_tokens": 1009, "size": 3641 }
#ifndef LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_ #define LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_ // License: BSD 3 clause #include <numeric> #include <algorithm> #include <atomic> #include <type_traits> #include "promote.h" #include "tick/base/defs.h" namespace tick { namespace detail { template <typename T> struct DLL_PUBLIC vector_operations_unoptimized { template <typename K> tick::promote_t<K> sum(const ulong n, const T *x) const; template <typename K> typename std::enable_if<std::is_same<T, std::atomic<K>>::value, T>::type dot( const ulong n, const T *x, const K *y) const; template <typename K> typename std::enable_if<std::is_same<T, std::atomic<K>>::value, K>::type dot( const ulong n, const K *x, const T *y) const; template <typename K> typename std::enable_if<!std::is_same<T, std::atomic<K>>::value, T>::type dot( const ulong n, const T *x, const K *y) const; template <typename K> typename std::enable_if<std::is_same<T, std::atomic<K>>::value>::type scale( const ulong n, const K alpha, T *x) const; template <typename K> typename std::enable_if<!std::is_same<T, std::atomic<K>>::value>::type scale( const ulong n, const K alpha, T *x) const; template <typename K> typename std::enable_if<std::is_same<T, std::atomic<K>>::value>::type set( const ulong n, const K alpha, T *x) const; template <typename K> typename std::enable_if<!std::is_same<T, std::atomic<K>>::value>::type set( const ulong n, const K alpha, T *x) const; template <typename K, typename Y> typename std::enable_if<std::is_same<T, std::atomic<K>>::value && !std::is_same<Y, std::atomic<K>>::value>::type mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const; template <typename K, typename Y> typename std::enable_if<std::is_same<Y, std::atomic<K>>::value && !std::is_same<T, std::atomic<K>>::value>::type mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const; template <typename K, typename Y> typename std::enable_if<std::is_same<T, std::atomic<K>>::value && std::is_same<Y, std::atomic<K>>::value>::type mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const; template <typename K, typename Y> typename std::enable_if<std::is_same<T, K>::value && std::is_same<Y, K>::value>::type mult_incr(const uint64_t n, const K alpha, const Y *x, T *y) const; }; } // namespace detail } // namespace tick #if !defined(TICK_CBLAS_AVAILABLE) namespace tick { template <typename T> using vector_operations = detail::vector_operations_unoptimized<T>; } // namespace tick #else // if defined(TICK_CBLAS_AVAILABLE) // Find available blas distribution #if defined(TICK_USE_MKL) #include <mkl.h> #elif defined(__APPLE__) #include <Accelerate/Accelerate.h> // TODO(svp) Disabling this feature until we find a good way to determine if // ATLAS is actually available #define XDATA_CATLAS_AVAILABLE #else extern "C" { #include <cblas.h> } #endif // defined(__APPLE__) #include "tick/array/vector/cblas.hpp" #endif // if !defined(TICK_CBLAS_AVAILABLE) #include "tick/array/vector/un_optimized.hpp" #endif // LIB_INCLUDE_TICK_ARRAY_VECTOR_OPERATIONS_H_
{ "alphanum_fraction": 0.6799758016, "avg_line_length": 29.2566371681, "ext": "h", "hexsha": "30756866eee78dcc69d424ba4f03a3b330be1b6d", "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": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "andro2157/tick", "max_forks_repo_path": "lib/include/tick/array/vector_operations.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "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": "andro2157/tick", "max_issues_repo_path": "lib/include/tick/array/vector_operations.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "d22d0e70c8bb2d5b232ffa7b97426010c2328edc", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "andro2157/tick", "max_stars_repo_path": "lib/include/tick/array/vector_operations.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 890, "size": 3306 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <cblas.h> #include <string.h> #include <mpi.h> #include "../inc/knnring.h" knnresult kNN(double *X, double *Y, int n, int m, int d, int k){ knnresult k_nearest; //initalize the result's variable k_nearest.nidx = (int *)malloc(m*k*sizeof(int)); k_nearest.ndist = (double *)malloc(m*k*sizeof(double)); k_nearest.m = m; k_nearest.k = k; //compute the distance Matrix D double *D = compute_D(X,Y,n,m,d,k); //select k-nearest neighbors for every point in QUERY k_select(D,k_nearest.ndist, k_nearest.nidx,n,m,k); return k_nearest; } double *compute_D(double *X, double *Y, int n, int m, int d, int k){ //compute distances using //D = (X*X)ee_t - 2XY_t + ee_t(Y*Y)_t double *tempD = (double *)malloc(n*m*sizeof(double)); double *e_1 = (double *)malloc(d*m*sizeof(double)); double *XX = (double *)malloc(n*d*sizeof(double)); for(int i=0;i<d*m;i++) e_1[i]=1; for(int i=0;i<n*d;i++) XX[i] = X[i]*X[i]; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n,m,d,1,XX,d,e_1,m,0,tempD,m); free(e_1); free(XX); double *e_2 = (double *)malloc(n*d*sizeof(double)); double *YY = (double *)malloc(m*d*sizeof(double)); for(int i=0;i<n*d;i++) e_2[i]=1; for(int i=0;i<m*d;i++) YY[i] = Y[i]*Y[i]; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n,m,d,-2,X,d,Y,d,1,tempD,m); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n,m,d,1,e_2,d,YY,d,1,tempD,m); for(int i=0;i<n*m;i++) tempD[i] = sqrt(fabs(tempD[i])); free(e_2); free(YY); return tempD; } void k_select(double *D, double *ndist, int *nidx,int n, int m, int k){ for(int j=0;j<m;j++){ for(int i=0;i<k;i++){ ndist[j*k+i] = D[j+i*m]; nidx[j*k+i] = i; } //sort the initial k neighbors quick_sort(ndist,nidx,j*k,k*(j+1)-1); } //search the rest points to find it there are closer neighbors for(int j=0;j<m;j++){ for(int i=k;i<n;i++){ if(D[j+i*m] < ndist[k*(j+1)-1]){ ndist[k*(j+1)-1] = D[j+i*m]; nidx[k*(j+1)-1] = i; quick_sort(ndist,nidx,j*k,(j+1)*k-1); } } } } void quick_sort(double *k_dist, int *k_neigh, int low, int high){ if(low<high){ //actuall sorting an element int pi = partition(k_dist,k_neigh,low,high); //recursivelly call quick_sort quick_sort(k_dist,k_neigh,low,pi-1); quick_sort(k_dist,k_neigh,pi+1,high); } } int partition(double *k_dist, int *k_neigh,int low, int high){ double temp_dist; int temp_point; int checker = 0; double pivot = k_dist[high]; //printf("the pivot is %lf \n",pivot); int i = (low-1); for(int j=low;j<=high-1;j++){ if(k_dist[j]<=pivot){ /*swap the two elements*/ i=i+1; temp_dist = k_dist[i]; temp_point = k_neigh[i]; k_dist[i] = k_dist[j]; k_neigh[i] = k_neigh[j]; k_dist[j] = temp_dist; k_neigh[j] = temp_point; checker = 1; } } /* swap the pivot */ i=i+1; temp_dist = k_dist[i]; temp_point = k_neigh[i]; k_dist[i] = k_dist[high]; k_neigh[i] = k_neigh[high]; k_dist[high] = temp_dist; k_neigh[high] = temp_point; return i; } void create_points(double *X,int size){ double *temp; temp = X; srand(time(NULL)); for(int i=0;i<size;i++) temp[i] = (double) 1000*rand()/RAND_MAX; } void write_to_file(char *str1, int *nidx, double *ndist, int amount, int k){ FILE *fp; //file for indexes fp = fopen(str1,"a+"); int counter = 1; for(int i=0;i<amount;i++){ fprintf(fp,"%d)%d -- %lf\n",counter,nidx[i],ndist[i]); counter ++; if((i+1)%k == 0){ fprintf(fp,"k nearest neighbors for next point \n"); counter = 1; } } fclose(fp); } //######################### V1 FUNCTIONS ############################ knnresult distrAllkNN(double *X, int n, int d, int k){ //results variables knnresult knn_process; knnresult knn_temp; int p_rank; //PROCESS RANK int p_size; //TOTAL NUMBER OF PROCESSES int next,prev; //NEXT AND PREVIOUS PROCESSES double *receive_buff; //BUFFERS FOR COMMUNICATION double *Y; //QUERY POINTS //variables for MPI COMMUNICATION. MPI_Status status; MPI_Request send_request,receive_request; int tag; //time variables struct timespec ts_start; struct timespec ts_end; double time; //find the number of processes MPI_Comm_size(MPI_COMM_WORLD, &p_size); //find the id of the process MPI_Comm_rank(MPI_COMM_WORLD, &p_rank); //define the communication tag tag = 1; //define the next and the previous process. //and create the circular communication next = p_rank+1; if(next == p_size) next = 0; prev = p_rank-1; if(prev== -1) prev = p_size-1; //initialize Y block Y = (double *)malloc(n*d*sizeof(double)); //in the first iteration every process computes distances between its own points memcpy(Y,X,n*d*sizeof(double)); //initialize receive buffer receive_buff = (double *)malloc(n*d*sizeof(double)); //MASK COMMUNICATION TIME //Send and receive point for the next iteration //clock_gettime(CLOCK_MONOTONIC,&ts_start); MPI_Isend(Y,n*d,MPI_DOUBLE,next,tag,MPI_COMM_WORLD, &send_request); MPI_Irecv(receive_buff,n*d, MPI_DOUBLE, prev, tag, MPI_COMM_WORLD, &receive_request); //find k-nearest neighbors in this set of points. knn_process = kNN(X,Y,n,n,d,k); for(int i=0;i<n*k;i++) knn_process.nidx[i] = knn_process.nidx[i]+n*p_rank; MPI_Wait(&send_request,&status); //make sure receive_buffer is ready MPI_Wait(&receive_request,&status); //clock_gettime(CLOCK_MONOTONIC,&ts_end); //time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000; //printf("communication time and computation time%lf\n",time); for(int i=0;i<p_size-1;i++){ memcpy(Y,receive_buff,n*d*sizeof(double)); //MASK COMMUNICATION TIME //send the block to the next node clock_gettime(CLOCK_MONOTONIC,&ts_start); MPI_Isend(Y,n*d,MPI_DOUBLE,next,tag,MPI_COMM_WORLD, &send_request); MPI_Irecv(receive_buff,n*d,MPI_DOUBLE,prev,tag,MPI_COMM_WORLD,&receive_request); knn_temp = kNN(Y,X,n,n,d,k); //compare k-nearest points knn_combine(knn_process, knn_temp,n,k,(p_rank-i-1+p_size)%p_size); //make sure Y buffer has been send in order to change it MPI_Wait(&send_request,&status); //make sure receive_buffer is ready MPI_Wait(&receive_request,&status); //clock_gettime(CLOCK_MONOTONIC,&ts_end); //time = 1000000*(double)(ts_end.tv_sec-ts_start.tv_sec)+(double)(ts_end.tv_nsec-ts_start.tv_nsec)/1000; //printf("communication time and knn compute time%lf\n",time); } free(Y); free(knn_temp.nidx); free(knn_temp.ndist); for(int i=0;i<knn_process.m;i++) quick_sort(knn_process.ndist,knn_process.nidx,i*k,k*(i+1)-1); return knn_process; } void knn_combine(knnresult knn_total,knnresult knn_temp, int n, int k, int no_block){ for(int m=0;m<knn_total.m;m++){ for(int j=0;j<k;j++){ if(knn_temp.ndist[m*k+j]>knn_total.ndist[k*(m+1)-1]) break; else{ knn_total.ndist[k*(m+1)-1] = knn_temp.ndist[m*k+j]; knn_total.nidx[k*(m+1)-1] = knn_temp.nidx[m*k+j] + no_block*n; //sort the new element quick_sort(knn_total.ndist,knn_total.nidx,m*k,(m+1)*k-1); } } } }
{ "alphanum_fraction": 0.647446458, "avg_line_length": 24.4429530201, "ext": "c", "hexsha": "4df208051776c8046a9c9f4dfacea68bd0072c1f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kv13/Parallel-And-Distributed-Systems", "max_forks_repo_path": "assignment2/src/knnring_mpi.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kv13/Parallel-And-Distributed-Systems", "max_issues_repo_path": "assignment2/src/knnring_mpi.c", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kv13/Parallel-And-Distributed-Systems", "max_stars_repo_path": "assignment2/src/knnring_mpi.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2319, "size": 7284 }
/** * Created : 2020.09.02; * Last Update : 2021.06.11; * Author : Gabriel Marino de Oliveira <ra115114@uem.br>; * Supervisor/Advisor : Breno Ferraz de Oliveira <>; * Notes : * Compilation : gcc -O3 src/main.c -static -lgls -lglscblas -lm -o simulationRPS.out * Execution : time ./simulationRPS.out */ #include <stdlib.h> #include <stdio.h> #include <math.h> // add mathematical operations; #include <time.h> // add functions to work with time and date, in this case used only to get the seconds counter from 01/01/1970; #include <complex.h> // add complex number operations; #include <gsl/gsl_rng.h> // add pseudo-random number generators; #define Ni 500 // Size of the grid in "i", or abscissa axis; #define Nj 500 // Size of the grid in "j", or ordinate axis; #define dt 0.1 // Time interval; #define tf 10000 // Total Time, or number of generations; #define Pp 0.3 // Predation probability; #define Pm 0.4 // Mobility probability for sthocastic method; /** Is not necessary to sthocastic method define the Reproduction probability, here we assume which "Pp + Pm + Pr = 1" or "Pr = 1 - (Pp + Pm)", * and this is why Reproduction probability is only needed to define for RK method**/ #define Cm 1.0 // Mobility coeficient for RK method; #define Pr 0.4 // Reproduction probability; #define np 100 // Number of points which will be printed when used a logarithmic scale; // const double r = pow((tf/dt), (1.0/np)); // r stands for ratio, will used to generate a arithmetic progression, useful to print equally spaced point
{ "alphanum_fraction": 0.6044077135, "avg_line_length": 58.5483870968, "ext": "h", "hexsha": "159b34b5213a6f211ced617871398cb806aad6b6", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-03-19T01:45:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-19T01:45:50.000Z", "max_forks_repo_head_hexsha": "f90b66c16262dd3c04f5b10f663c8e90124cd842", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Gabriel-Marino/marino-ic21-rps", "max_forks_repo_path": "head.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f90b66c16262dd3c04f5b10f663c8e90124cd842", "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": "Gabriel-Marino/marino-ic21-rps", "max_issues_repo_path": "head.h", "max_line_length": 164, "max_stars_count": null, "max_stars_repo_head_hexsha": "f90b66c16262dd3c04f5b10f663c8e90124cd842", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Gabriel-Marino/marino-ic21-rps", "max_stars_repo_path": "head.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 466, "size": 1815 }
#ifndef __INC_EMULATORSTRUCT__ #define __INC_EMULATORSTRUCT__ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> /** * \@file emulator_struct.h * \brief defines the emulator_struct which contains the details of a working emulator at runtime */ struct modelstruct; /********************************************************************* This data structure holds pointers to the information used to execute the emulator at a new point. This is especially helpful since I want to stream in queries and get results streamed back out. *********************************************************************/ typedef struct emulator_struct { int nparams; int nmodel_points; int nregression_fns; int nthetas; struct modelstruct * model; gsl_matrix * cinverse; gsl_vector * beta_vector; gsl_matrix * h_matrix; } emulator_struct; #include "modelstruct.h" emulator_struct * alloc_emulator_struct(modelstruct * model); void free_emulator_struct(emulator_struct * e); void makeHMatrix_es(gsl_matrix *h_matrix, emulator_struct *e); void makeCovMatrix_es(gsl_matrix *cov_matrix, emulator_struct *e); void makeKVector_es(gsl_vector *kvector, gsl_vector *point, emulator_struct *e); void estimateBeta_es(gsl_vector *beta_vector, emulator_struct *e); void emulate_point(emulator_struct* e, gsl_vector * point, double * mean, double * variance); #endif
{ "alphanum_fraction": 0.7122884474, "avg_line_length": 32.3571428571, "ext": "h", "hexsha": "811b297a23a26945601fcf4637a0b83be1b0046c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_path": "src/emulator_struct.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "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": "MADAI/MADAIEmulator", "max_issues_repo_path": "src/emulator_struct.h", "max_line_length": 97, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/emulator_struct.h", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "num_tokens": 291, "size": 1359 }
/* cdf/test.c * * Copyright (C) 2002 Jason H Stover. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #define TEST(func, args, value, tol) { double res = func args ; gsl_test_rel (res, value, tol, #func #args); } ; #define TEST_TOL0 (2.0*GSL_DBL_EPSILON) #define TEST_TOL1 (16.0*GSL_DBL_EPSILON) #define TEST_TOL2 (256.0*GSL_DBL_EPSILON) #define TEST_TOL3 (2048.0*GSL_DBL_EPSILON) #define TEST_TOL4 (16384.0*GSL_DBL_EPSILON) #define TEST_TOL5 (131072.0*GSL_DBL_EPSILON) #define TEST_TOL6 (1048576.0*GSL_DBL_EPSILON) void test_ugaussian (void); void test_ugaussianinv (void); void test_exponential (void); void test_exponentialinv (void); void test_exppow (void); void test_tdist (void); void test_fdist (void); void test_gamma (void); void test_chisq (void); void test_beta (void); void test_gammainv (void); void test_chisqinv (void); void test_tdistinv (void); void test_betainv (void); void test_finv (void); #include "test_auto.c" struct range { unsigned int min; unsigned int max; } ; double test_binomial_pdf (unsigned int n); double test_binomial_cdf_P (unsigned int n); double test_binomial_cdf_Q (unsigned int n); struct range test_binomial_range (void) { struct range r = {0, 5}; return r; } double test_binomial_pdf (unsigned int k) { return gsl_ran_binomial_pdf (k, 0.3, 5); } double test_binomial_cdf_P (unsigned int k) { return gsl_cdf_binomial_P (k, 0.3, 5); } double test_binomial_cdf_Q (unsigned int k) { return gsl_cdf_binomial_Q (k, 0.3, 5); } struct range test_poisson_range (void) { struct range r = {0, 25}; return r; } double test_poisson_pdf (unsigned int k) { return gsl_ran_poisson_pdf (k, 2.3); } double test_poisson_cdf_P (unsigned int k) { return gsl_cdf_poisson_P (k, 2.3); } double test_poisson_cdf_Q (unsigned int k) { return gsl_cdf_poisson_Q (k, 2.3); } struct range test_geometric_range (void) { struct range r = {0, 25}; return r; } double test_geometric_pdf (unsigned int k) { return gsl_ran_geometric_pdf (k, 0.3); } double test_geometric_cdf_P (unsigned int k) { return gsl_cdf_geometric_P (k, 0.3); } double test_geometric_cdf_Q (unsigned int k) { return gsl_cdf_geometric_Q (k, 0.3); } struct range test_negative_binomial_range (void) { struct range r = {0, 15}; return r; } double test_negative_binomial_pdf (unsigned int k) { return gsl_ran_negative_binomial_pdf (k, 0.3, 5.3); } double test_negative_binomial_cdf_P (unsigned int k) { return gsl_cdf_negative_binomial_P (k, 0.3, 5.3); } double test_negative_binomial_cdf_Q (unsigned int k) { return gsl_cdf_negative_binomial_Q (k, 0.3, 5.3); } struct range test_pascal_range (void) { struct range r = {0, 15}; return r; } double test_pascal_pdf (unsigned int k) { return gsl_ran_pascal_pdf (k, 0.3, 5); } double test_pascal_cdf_P (unsigned int k) { return gsl_cdf_pascal_P (k, 0.3, 5); } double test_pascal_cdf_Q (unsigned int k) { return gsl_cdf_pascal_Q (k, 0.3, 5); } struct range test_hypergeometric_range (void) { struct range r = {0, 26}; return r; } double test_hypergeometric_pdf (unsigned int k) { return gsl_ran_hypergeometric_pdf (k, 7, 19, 13); } double test_hypergeometric_cdf_P (unsigned int k) { return gsl_cdf_hypergeometric_P (k, 7, 19, 13); } double test_hypergeometric_cdf_Q (unsigned int k) { return gsl_cdf_hypergeometric_Q (k, 7, 19, 13); } struct range test_hypergeometric2_range (void) { struct range r = {0, 13250474}; return r; } struct range test_hypergeometric2a_range (void) { struct range r = {3500, 3600}; return r; } struct range test_hypergeometric2b_range (void) { struct range r = {13247474, 13250474}; return r; } double test_hypergeometric2_pdf (unsigned int k) { return gsl_ran_hypergeometric_pdf (k, 76200, 13174274, 678090); } double test_hypergeometric2_cdf_P (unsigned int k) { return gsl_cdf_hypergeometric_P (k, 76200, 13174274, 678090); } double test_hypergeometric2_cdf_Q (unsigned int k) { return gsl_cdf_hypergeometric_Q (k, 76200, 13174274, 678090); } #ifdef LOGARITHMIC struct range test_logarithmic_range (void) { struct range r = {1, 200}; return r; } double test_logarithmic_pdf (unsigned int k) { return gsl_ran_logarithmic_pdf (k, 0.9); } double test_logarithmic_cdf_P (unsigned int k) { return gsl_cdf_logarithmic_P (k, 0.9); } double test_logarithmic_cdf_Q (unsigned int k) { return gsl_cdf_logarithmic_Q (k, 0.9); } #endif void test_discrete_cdf_P (double (*pdf)(unsigned int), double (*cdf_P)(unsigned int), struct range (*range)(void), const char * desc) { double sum; double tol = TEST_TOL2; int i, min, max; struct range r = range(); min = r.min; max = r.max; sum = 0.0; for (i = min; i <= max; i++) { double pi = pdf(i); double Pi = cdf_P(i); sum += pi; gsl_test_rel (Pi, sum, tol, desc, i); } } void test_discrete_cdf_Q (double (*pdf)(unsigned int), double (*cdf_Q)(unsigned int), struct range (*range)(void), const char * desc) { double sum; double tol = TEST_TOL2; int i, min, max; struct range r = range(); min = r.min; max = r.max; sum = cdf_Q(max); for (i = max; i >= min; i--) { double pi = pdf(i); double Qi = cdf_Q(i); gsl_test_rel (Qi, sum, tol, desc, i); sum += pi; } } void test_discrete_cdf_PQ (double (*cdf_P)(unsigned int), double (*cdf_Q)(unsigned int), struct range (*range)(void), const char * desc) { double sum; double tol = GSL_DBL_EPSILON; int i, min, max; struct range r = range(); min = r.min; max = r.max; for (i = min; i <= max; i++) { double Pi = cdf_P(i); double Qi = cdf_Q(i); sum = Pi + Qi; gsl_test_rel (sum, 1.0, tol, desc, i); { int s1 = (Pi<0 || Pi>1); int s2 = (Qi<0 || Qi>1); gsl_test(s1, "Pi in range [0,1] (%.18e)", Pi); gsl_test(s2, "Qi in range [0,1] (%.18e)", Qi); } } } #define TEST_DISCRETE(name) do { \ test_discrete_cdf_P(&test_ ## name ## _pdf, &test_ ## name ## _cdf_P, &test_ ## name ## _range, "test gsl_cdf_" #name "_P (k=%d)") ; \ test_discrete_cdf_Q(&test_ ## name ## _pdf, &test_ ## name ## _cdf_Q, &test_ ## name ## _range, "test gsl_cdf_" #name "_Q (k=%d)") ; \ test_discrete_cdf_PQ(&test_ ## name ## _cdf_P, &test_ ## name ## _cdf_Q, &test_ ## name ## _range, "test gsl_cdf_" #name "_P+Q (k=%d)") ; \ } while (0); int main (void) { gsl_ieee_env_setup (); TEST_DISCRETE(binomial); TEST_DISCRETE(poisson); TEST_DISCRETE(geometric); TEST_DISCRETE(negative_binomial); TEST_DISCRETE(pascal); TEST_DISCRETE(hypergeometric); #ifdef HYPERGEOMETRIC2 TEST_DISCRETE(hypergeometric2); #endif #ifdef LOGARITHMIC TEST_DISCRETE(logarithmic); #endif test_discrete_cdf_PQ(&test_hypergeometric2_cdf_P, &test_hypergeometric2_cdf_Q, &test_hypergeometric2a_range, "test gsl_cdf_hypergeometric_P+Q (k=%d)") ; test_discrete_cdf_PQ(&test_hypergeometric2_cdf_P, &test_hypergeometric2_cdf_Q, &test_hypergeometric2b_range, "test gsl_cdf_hypergeometric_P+Q (k=%d)") ; /* exit (gsl_test_summary ()); */ /* Tests for gaussian cumulative distribution function Function values computed with PARI, 28 digits precision */ test_ugaussian (); test_exponential (); test_exppow (); test_tdist (); test_fdist (); test_gamma (); test_chisq (); test_beta (); test_ugaussianinv (); test_exponentialinv (); test_gammainv (); test_chisqinv (); test_tdistinv (); test_betainv (); test_finv (); test_auto_beta (); test_auto_fdist (); test_auto_cauchy (); test_auto_gaussian (); test_auto_laplace (); test_auto_rayleigh (); test_auto_flat (); test_auto_lognormal (); test_auto_gamma (); test_auto_chisq (); test_auto_tdist (); test_auto_gumbel1 (); test_auto_gumbel2 (); test_auto_weibull (); test_auto_pareto (); test_auto_logistic (); test_auto_gammalarge (); exit (gsl_test_summary ()); } void test_ugaussian (void) { TEST (gsl_cdf_ugaussian_P, (0.0), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (1e-32), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (1e-16), 0.5000000000000000398942280401, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (1e-8), 0.5000000039894228040143267129, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (0.5), 0.6914624612740131036377046105, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (0.7), 0.7580363477769269852506495717, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (5.0), 0.9999997133484281208060883262, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (10.0), 0.9999999999999999999999923801, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (30.0), 1.000000000000000000000000000, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (40.0), 1.000000000000000000000000000, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (1e10), 1.000000000000000000000000000, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-1e-32), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-1e-16), 0.4999999999999999601057719598, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-1e-8), 0.4999999960105771959856732870, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-0.5), 0.3085375387259868963622953894, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-0.7), 0.2419636522230730147493504282, TEST_TOL0); TEST (gsl_cdf_ugaussian_P, (-5.0), 0.0000002866515718791939116737523329, TEST_TOL1); TEST (gsl_cdf_ugaussian_P, (-10.0), 7.619853024160526065973343257e-24, TEST_TOL3); TEST (gsl_cdf_ugaussian_P, (-30.0), 4.906713927148187059533809288e-198, TEST_TOL3); TEST (gsl_cdf_ugaussian_P, (-1e10), 0.0, 0.0); TEST (gsl_cdf_ugaussian_Q, (0.0), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (1e-32), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (1e-16), 0.4999999999999999601057719598, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (1e-8), 0.4999999960105771959856732870, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (0.5), 0.3085375387259868963622953894, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (0.7), 0.2419636522230730147493504282, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (5.0), 0.0000002866515718791939116737523329, TEST_TOL3); TEST (gsl_cdf_ugaussian_Q, (10.0), 7.619853024160526065973343257e-24, TEST_TOL3); TEST (gsl_cdf_ugaussian_Q, (30.0), 4.906713927148187059533809288e-198, TEST_TOL3); TEST (gsl_cdf_ugaussian_Q, (1e10), 0.0, 0.0); TEST (gsl_cdf_ugaussian_Q, (-1e-32), 0.5, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-1e-16), 0.5000000000000000398942280401, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-1e-8), 0.5000000039894228040143267129, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-0.5), 0.6914624612740131036377046105, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-0.7), 0.7580363477769269852506495717, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-5.0), 0.9999997133484281208060883262, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-10.0), 0.9999999999999999999999923801, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-30.0), 1.000000000000000000000000000, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-40.0), 1.000000000000000000000000000, TEST_TOL0); TEST (gsl_cdf_ugaussian_Q, (-1e10), 1.000000000000000000000000000, TEST_TOL0); } /* Test values from Abramowitz & Stegun, Handbook of Mathematical Functions, Table 26.1. Error term is given by dx = dP / Z(x) */ void test_ugaussianinv (void) { TEST (gsl_cdf_ugaussian_Pinv, (0.9999997133), 5.0, 1e-4); TEST (gsl_cdf_ugaussian_Pinv, (0.9999683288), 4.0, 1e-6); TEST (gsl_cdf_ugaussian_Pinv, (0.9986501020), 3.0, 1e-8); TEST (gsl_cdf_ugaussian_Pinv, (0.977249868051821), 2.0, 1e-14); TEST (gsl_cdf_ugaussian_Pinv, (0.841344746068543), 1.0, TEST_TOL3); TEST (gsl_cdf_ugaussian_Pinv, (0.691462461274013), 0.5, TEST_TOL2); TEST (gsl_cdf_ugaussian_Pinv, (0.655421741610324), 0.4, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (0.617911422188953), 0.3, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (0.579259709439103), 0.2, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (0.539827837277029), 0.1, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (0.5), 0.0, TEST_TOL0); TEST (gsl_cdf_ugaussian_Pinv, (4.60172162722971e-1), -0.1, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (4.20740290560897e-1), -0.2, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (3.82088577811047e-1), -0.3, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (3.44578258389676e-1), -0.4, TEST_TOL1); TEST (gsl_cdf_ugaussian_Pinv, (3.08537538725987e-1), -0.5, TEST_TOL2); TEST (gsl_cdf_ugaussian_Pinv, (1.58655253931457e-1), -1.0, TEST_TOL3); TEST (gsl_cdf_ugaussian_Pinv, (2.2750131948179e-2), -2.0, 1e-14); TEST (gsl_cdf_ugaussian_Pinv, (1.349898e-3), -3.0, 1e-8); TEST (gsl_cdf_ugaussian_Pinv, (3.16712e-5), -4.0, 1e-6); TEST (gsl_cdf_ugaussian_Pinv, (2.86648e-7), -5.0, 1e-4); TEST (gsl_cdf_ugaussian_Pinv, (7.61985302416052e-24), -10.0, 1e-4); TEST (gsl_cdf_ugaussian_Qinv, (7.61985302416052e-24), 10.0, 1e-4); TEST (gsl_cdf_ugaussian_Qinv, (2.86648e-7), 5.0, 1e-4); TEST (gsl_cdf_ugaussian_Qinv, (3.16712e-5), 4.0, 1e-6); TEST (gsl_cdf_ugaussian_Qinv, (1.349898e-3), 3.0, 1e-8); TEST (gsl_cdf_ugaussian_Qinv, (2.2750131948179e-2), 2.0, 1e-14); TEST (gsl_cdf_ugaussian_Qinv, (1.58655253931457e-1), 1.0, TEST_TOL3); TEST (gsl_cdf_ugaussian_Qinv, (3.08537538725987e-1), 0.5, TEST_TOL2); TEST (gsl_cdf_ugaussian_Qinv, (3.44578258389676e-1), 0.4, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (3.82088577811047e-1), 0.3, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (4.20740290560897e-1), 0.2, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (4.60172162722971e-1), 0.1, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (0.5), 0.0, TEST_TOL0); TEST (gsl_cdf_ugaussian_Qinv, (0.539827837277029), -0.1, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (0.579259709439103), -0.2, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (0.617911422188953), -0.3, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (0.655421741610324), -0.4, TEST_TOL1); TEST (gsl_cdf_ugaussian_Qinv, (0.691462461274013), -0.5, TEST_TOL2); TEST (gsl_cdf_ugaussian_Qinv, (0.841344746068543), -1.0, TEST_TOL3); TEST (gsl_cdf_ugaussian_Qinv, (0.977249868051821), -2.0, 1e-14); TEST (gsl_cdf_ugaussian_Qinv, (0.9986501020), -3.0, 1e-8); TEST (gsl_cdf_ugaussian_Qinv, (0.9999683288), -4.0, 1e-6); TEST (gsl_cdf_ugaussian_Qinv, (0.9999997133), -5.0, 1e-4); } /* Tests for exponential cumulative distribution function Function values computed with PARI, 28 digits precision */ void test_exponential (void) { TEST (gsl_cdf_exponential_P, (0.1, 0.7), 1.33122100249818372e-1, TEST_TOL0); TEST (gsl_cdf_exponential_P, (1e-32, 0.7), 1.42857142857142857e-32, TEST_TOL0); TEST (gsl_cdf_exponential_P, (1000.0, 0.7), 1.0, TEST_TOL6); TEST (gsl_cdf_exponential_Q, (0.1, 0.7), 8.66877899750181628e-1, TEST_TOL0); TEST (gsl_cdf_exponential_Q, (1e-32, 0.7), 1.0, TEST_TOL0); TEST (gsl_cdf_exponential_Q, (1000.0, 0.7), 0.0, TEST_TOL6); } void test_exponentialinv (void) { TEST (gsl_cdf_exponential_Pinv, (0.13, 0.7), 9.74834471334553546e-2, TEST_TOL0); TEST (gsl_cdf_exponential_Pinv, (1.42e-32, 0.7), 9.94000000000000000e-33, TEST_TOL0); TEST (gsl_cdf_exponential_Qinv, (0.86, 0.7), 1.05576022814208545e-1, TEST_TOL0); TEST (gsl_cdf_exponential_Qinv, (0.99999, 0.7), 7.00003500023333508e-6, TEST_TOL6); } void test_exppow (void) { TEST (gsl_cdf_exppow_P, (-1000.0, 0.7, 1.8), 0.0, TEST_TOL6); TEST (gsl_cdf_exppow_P, (-0.1, 0.7, 1.8), 0.4205349082867515493458053850, TEST_TOL0); TEST (gsl_cdf_exppow_P, (-1e-32, 0.7, 1.8), 0.4999999999999999999999999999, TEST_TOL0); TEST (gsl_cdf_exppow_P, (0.1, 0.7, 1.8), 0.5794650917132484506541946149, TEST_TOL0); TEST (gsl_cdf_exppow_P, (1e-32, 0.7, 1.8), 0.5, TEST_TOL0); TEST (gsl_cdf_exppow_P, (1000.0, 0.7, 1.8), 0.9999999999999999999999956212, TEST_TOL6); TEST (gsl_cdf_exppow_Q, (-1000.0, 0.7, 1.8), 0.9999999999999999999999956212, TEST_TOL6); TEST (gsl_cdf_exppow_Q, (-0.1, 0.7, 1.8), 0.5794650917132484506541946149, TEST_TOL0); TEST (gsl_cdf_exppow_Q, (-1e-32, 0.7, 1.8), 0.5, TEST_TOL0); TEST (gsl_cdf_exppow_Q, (0.1, 0.7, 1.8), 0.4205349082867515493458053850, TEST_TOL0); TEST (gsl_cdf_exppow_Q, (1e-32, 0.7, 1.8), 0.4999999999999999999999999999, TEST_TOL0); TEST (gsl_cdf_exppow_Q, (1000.0, 0.7, 1.8), 0.0, TEST_TOL6); } /* Tests for student's T distribution */ /* p(x,nu) = (1/2)*(1+sign(x)*betaI(x^2/(nu+x^2),1/2,nu/2)) q(x,nu) = (1/2)*(1-sign(x)*betaI(x^2/(nu+x^2),1/2,nu/2)) */ void test_tdist (void) { TEST (gsl_cdf_tdist_P, (0.0, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1e-100, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.001, 1.0), 5.00318309780080559e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.01, 1.0), 5.03182992764908255e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.1, 1.0), 5.31725517430553569e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.325, 1.0), 6.00023120032852123e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.0, 1.0), 0.75000000000000000e0, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.5, 1.0), 8.12832958189001183e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (2.0, 1.0), 8.52416382349566726e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10.0, 1.0), 9.68274482569446430e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (20.0, 1.0), 9.84097748743823625e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (100.0, 1.0), 9.96817007235091745e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1000.0, 1.0), 9.99681690219919441e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10000.0, 1.0), 9.99968169011487724e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.0, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1e-100, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.001, 1.0), 4.99681690219919441e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.01, 1.0), 4.96817007235091745e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.1, 1.0), 4.68274482569446430e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.325, 1.0), 3.99976879967147876e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.0, 1.0), 2.5e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.5, 1.0), 1.87167041810998816e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (2.0, 1.0), 1.47583617650433274e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (10.0, 1.0), 3.17255174305535695e-2, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (20.0, 1.0), 1.59022512561763752e-2, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (100.0, 1.0), 3.18299276490825515e-3, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1000.0, 1.0), 3.18309780080558939e-4, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (10000.0, 1.0), 3.18309885122757724e-5, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1e-100, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.001, 1.0), 4.99681690219919441e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.01, 1.0), 4.96817007235091744e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.1, 1.0), 4.68274482569446430e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.325, 1.0), 3.99976879967147876e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.0, 1.0), 0.25, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.5, 1.0), 1.87167041810998816e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-2.0, 1.0), 1.47583617650433274e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-10.0, 1.0), 3.17255174305535695e-2, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-20.0, 1.0), 1.59022512561763751e-2, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-100.0, 1.0), 3.18299276490825514e-3, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1000.0, 1.0), 3.18309780080558938e-4, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-10000.0, 1.0), 3.18309885122757724e-5, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1e-100, 1.0), 0.5, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.001, 1.0), 5.00318309780080559e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.01, 1.0), 5.03182992764908255e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.1, 1.0), 5.31725517430553570e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.325, 1.0), 6.00023120032852124e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.0, 1.0), 7.5e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.5, 1.0), 8.12832958189001184e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-2.0, 1.0), 8.52416382349566726e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10.0, 1.0), 9.68274482569446430e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-20.0, 1.0), 9.84097748743823625e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-100.0, 1.0), 9.96817007235091745e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1000.0, 1.0), 9.99681690219919441e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10000.0, 1.0), 9.99968169011487724e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.0, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1e-100, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.001, 2.0), 5.00353553302204959e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.01, 2.0), 5.03535445520899514e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.1, 2.0), 5.35267280792929913e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.325, 2.0), 6.11985772746873767e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.0, 2.0), 7.88675134594812882e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.5, 2.0), 8.63803437554499460e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (2.0, 2.0), 9.08248290463863016e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10.0, 2.0), 9.95073771488337154e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (20.0, 2.0), 9.98754668053816452e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (100.0, 2.0), 9.99950007498750219e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1000.0, 2.0), 9.99999500000749945e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10000.0, 2.0), 9.999999950000000739e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.0, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1e-100, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.001, 2.0), 4.99646446697795041e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.01, 2.0), 4.96464554479100486e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.1, 2.0), 4.64732719207070087e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.325, 2.0), 3.88014227253126233e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.0, 2.0), 2.11324865405187118e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.5, 2.0), 1.36196562445500540e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (2.0, 2.0), 9.17517095361369836e-2, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (10.0, 2.0), 4.92622851166284542e-3, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (20.0, 2.0), 1.24533194618354849e-3, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (100.0, 2.0), 4.99925012497812894e-5, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1000.0, 2.0), 4.99999250001249998e-7, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (10000.0, 2.0), 4.99999992500000125e-9, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1e-100, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.001, 2.0), 4.99646446697795041e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.01, 2.0), 4.96464554479100486e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.1, 2.0), 4.64732719207070087e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.325, 2.0), 3.88014227253126233e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.0, 2.0), 2.11324865405187118e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.5, 2.0), 1.36196562445500540e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-2.0, 2.0), 9.17517095361369836e-02, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-10.0, 2.0), 4.92622851166284542e-03, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-20.0, 2.0), 1.24533194618354849e-03, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-100.0, 2.0), 4.99925012497812894e-05, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1000.0, 2.0), 4.99999250001249998e-07, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-10000.0, 2.0), 4.99999992500000125e-09, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1e-100, 2.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.001, 2.0), 5.00353553302204959e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.01, 2.0), 5.03535445520899514e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.1, 2.0), 5.35267280792929913e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.325, 2.0), 6.11985772746873767e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.0, 2.0), 7.88675134594812882e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.5, 2.0), 8.63803437554499460e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-2.0, 2.0), 9.08248290463863016e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10.0, 2.0), 9.95073771488337155e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-20.0, 2.0), 9.98754668053816452e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-100.0, 2.0), 9.99950007498750219e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1000.0, 2.0), 9.99999500000749999e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10000.0, 2.0), 9.99999995000000075e-1, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.0, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1e-100, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.001, 300.0), 5.00398609900942949e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.01, 300.0), 5.03986033020559088e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.1, 300.0), 5.39794441177768194e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (0.325, 300.0), 6.27296201542523812e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.0, 300.0), 8.40941797784686861e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1.5, 300.0), 9.32666983425369137e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (2.0, 300.0), 9.76799239508425455e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10.0, 300.0), 1.00000000000000000e+00, TEST_TOL6); TEST (gsl_cdf_tdist_P, (20.0, 300.0), 1.00000000000000000e+00, TEST_TOL6); TEST (gsl_cdf_tdist_P, (100.0, 300.0), 1.00000000000000000e+00, TEST_TOL6); TEST (gsl_cdf_tdist_P, (1000.0, 300.0), 1.00000000000000000e+00, TEST_TOL6); TEST (gsl_cdf_tdist_P, (10000.0, 300.0), 1.00000000000000000e+00, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.0, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1e-100, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.001, 300.0), 4.99601390099057051e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.01, 300.0), 4.96013966979440912e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.1, 300.0), 4.60205558822231806e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (0.325, 300.0), 3.72703798457476188e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.0, 300.0), 1.59058202215313138e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1.5, 300.0), 6.73330165746308628e-2, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (2.0, 300.0), 2.32007604915745452e-2, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (10.0, 300.0), 8.279313677e-21, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (20.0, 300.0), 1.93159812815803978e-57, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (100.0, 300.0), 1.02557519997736154e-232, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (1000.0, 300.0), 0.00000000000000000e+00, 0.0); TEST (gsl_cdf_tdist_Q, (10000.0, 300.0), 0.00000000000000000e+00, 0.0); TEST (gsl_cdf_tdist_P, (-1e-100, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.001, 300.0), 4.99601390099057051e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.01, 300.0), 4.96013966979440912e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.1, 300.0), 4.60205558822231806e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-0.325, 300.0), 3.72703798457476188e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.0, 300.0), 1.59058202215313138e-01, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1.5, 300.0), 6.73330165746308628e-02, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-2.0, 300.0), 2.32007604915745452e-02, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-10.0, 300.0), 8.279313675556272534e-21, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-20.0, 300.0), 1.93159812815803978e-57, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-100.0, 300.0), 1.02557519997736154e-232, TEST_TOL6); TEST (gsl_cdf_tdist_P, (-1000.0, 300.0), 0.0, 0.0); TEST (gsl_cdf_tdist_P, (-10000.0, 300.0), 0.0, 0.0); TEST (gsl_cdf_tdist_Q, (-1e-100, 300.0), 5.00000000000000000e-01, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.001, 300.0), 5.00398609900942949e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.01, 300.0), 5.03986033020559088e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.1, 300.0), 5.39794441177768194e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-0.325, 300.0), 6.27296201542523812e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.0, 300.0), 8.40941797784686862e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1.5, 300.0), 9.32666983425369137e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-2.0, 300.0), 9.76799239508425455e-1, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10.0, 300.0), 1.000000000000000000e0, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-20.0, 300.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-100.0, 300.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-1000.0, 300.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Q, (-10000.0, 300.0), 1.0, TEST_TOL6); } /* Tests for F distribution */ /* p(x, nu1, nu2) := betaI(1 / (1 + (nu2 / nu1) / x), nu1 / 2, nu2 / 2) */ void test_fdist (void) { TEST (gsl_cdf_fdist_P, (0.0, 1.2, 1.3), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (1e-100, 1.2, 1.3), 6.98194275525039002e-61, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.001, 1.2, 1.3), 1.10608485860238564e-2, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.01, 1.2, 1.3), 4.38636757068313850e-2, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.1, 1.2, 1.3), 1.68242392712840734e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.325, 1.2, 1.3), 3.14130045246195449e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.0, 1.2, 1.3), 5.09630779074755253e-01, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.5, 1.2, 1.3), 5.83998640641553852e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (2.0, 1.2, 1.3), 6.34733581351938787e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10.0, 1.2, 1.3), 8.48446237879200975e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (20.0, 1.2, 1.3), 9.00987726336875039e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (100.0, 1.2, 1.3), 9.64489127047688435e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1000.0, 1.2, 1.3), 9.92012051694116388e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10000.0, 1.2, 1.3), 9.98210862808842585e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.0, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1e-100, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.001, 1.2, 1.3), 9.88939151413976144e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.01, 1.2, 1.3), 9.56136324293168615e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.1, 1.2, 1.3), 8.31757607287159265e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.325, 1.2, 1.3), 6.85869954753804551e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.0, 1.2, 1.3), 4.90369220925244747e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.5, 1.2, 1.3), 4.16001359358446148e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (2.0, 1.2, 1.3), 3.65266418648061213e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10.0, 1.2, 1.3), 1.51553762120799025e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (20.0, 1.2, 1.3), 9.90122736631249612e-2, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (100.0, 1.2, 1.3), 3.55108729523115643e-2, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1000.0, 1.2, 1.3), 7.98794830588361109e-3, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10000.0, 1.2, 1.3), 1.7891371911574145e-3, TEST_TOL6); /* computed with gp-pari */ TEST (gsl_cdf_fdist_P, (3.479082213465832574, 1, 4040712), 0.93785072763723411967, TEST_TOL6); TEST (gsl_cdf_fdist_P, (3.002774644786533109, 1, 4040712), 0.91687787379476055771, TEST_TOL6); TEST (gsl_cdf_fdist_P, (3.000854441173130827, 1, 4040712), 0.91677930719813578619, TEST_TOL6); TEST (gsl_cdf_fdist_P, (3.000064021622133037, 1, 4040712), 0.9167386972447996480399, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.0, 500.0, 1.3), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (1e-100, 500.0, 1.3), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (0.001, 500.0, 1.3), 9.83434460393304765e-141, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.01, 500.0, 1.3), 1.45915624888550014e-26, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.1, 500.0, 1.3), 5.89976509619688165e-4, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.325, 500.0, 1.3), 6.86110486051542533e-2, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.0, 500.0, 1.3), 3.38475053806404615e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.5, 500.0, 1.3), 4.52016245247457422e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (2.0, 500.0, 1.3), 5.27339068937388798e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10.0, 500.0, 1.3), 8.16839628578413905e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (20.0, 500.0, 1.3), 8.81784623056911406e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (100.0, 500.0, 1.3), 9.58045057204221295e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1000.0, 500.0, 1.3), 9.90585749380655275e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10000.0, 500.0, 1.3), 9.97891924831461387e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.0, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1e-100, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.001, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.01, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.1, 500.0, 1.3), 9.99410023490380312e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.325, 500.0, 1.3), 9.31388951394845747e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.0, 500.0, 1.3), 6.61524946193595385e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.5, 500.0, 1.3), 5.47983754752542572e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (2.0, 500.0, 1.3), 4.72660931062611202e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10.0, 500.0, 1.3), 1.83160371421586096e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (20.0, 500.0, 1.3), 1.18215376943088595e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (100.0, 500.0, 1.3), 4.19549427957787016e-2, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1000.0, 500.0, 1.3), 9.41425061934473424e-3, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10000.0, 500.0, 1.3), 2.10807516853862603e-3, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.0, 1.2, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (1e-100, 1.2, 500.0), 8.23342055585482999e-61, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.001, 1.2, 500.0), 1.30461496441289529e-2, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.01, 1.2, 500.0), 5.18324224608033294e-2, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.1, 1.2, 500.0), 2.02235101716076289e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.325, 1.2, 500.0), 3.90502983219393749e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.0, 1.2, 500.0), 6.67656191574653619e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.5, 1.2, 500.0), 7.75539230271467054e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (2.0, 1.2, 500.0), 8.45209114904613705e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10.0, 1.2, 500.0), 9.99168017659120988e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (20.0, 1.2, 500.0), 9.99998005738371669e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (100.0, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1000.0, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10000.0, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.0, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1e-100, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.001, 1.2, 500.0), 9.86953850355871047e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.01, 1.2, 500.0), 9.48167577539196671e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.1, 1.2, 500.0), 7.97764898283923711e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.325, 1.2, 500.0), 6.09497016780606251e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.0, 1.2, 500.0), 3.32343808425346381e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.5, 1.2, 500.0), 2.24460769728532946e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (2.0, 1.2, 500.0), 1.54790885095386295e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10.0, 1.2, 500.0), 8.3198234087901168e-4, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (20.0, 1.2, 500.0), 1.99426162833131e-6, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (100.0, 1.2, 500.0), 6.23302662288217117e-25, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1000.0, 1.2, 500.0), 1.14328577259666930e-134, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10000.0, 1.2, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (0.0, 200.0, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (1e-100, 200.0, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_P, (0.001, 200.0, 500.0), 4.09325080403669893e-251, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.01, 200.0, 500.0), 1.17894325419628688e-151, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.1, 200.0, 500.0), 5.92430940796861258e-57, TEST_TOL6); TEST (gsl_cdf_fdist_P, (0.325, 200.0, 500.0), 3.18220452357263554e-18, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.0, 200.0, 500.0), 5.06746326121168266e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1.5, 200.0, 500.0), 9.99794175718712438e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (2.0, 200.0, 500.0), 9.99999999528236152e-1, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (20.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (100.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (1000.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_P, (10000.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.0, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1e-100, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.001, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.01, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.1, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (0.325, 200.0, 500.0), 9.99999999999999997e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.0, 200.0, 500.0), 4.93253673878831734e-1, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1.5, 200.0, 500.0), 2.05824281287561795e-4, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (2.0, 200.0, 500.0), 4.71763848371410786e-10, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (10.0, 200.0, 500.0), 5.98048337181948436e-96, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (20.0, 200.0, 500.0), 2.92099265879979502e-155, TEST_TOL6); TEST (gsl_cdf_fdist_Q, (1000.0, 200.0, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_Q, (10000.0, 200.0, 500.0), 0.0, 0.0); } void test_finv (void) { TEST (gsl_cdf_fdist_Pinv, (0.0, 1.2, 1.3), 0.0, 0.0); TEST (gsl_cdf_fdist_Pinv, ( 6.98194275525039002e-61, 1.2, 1.3), 1e-100, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.10608485860238564e-2, 1.2, 1.3), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 4.38636757068313850e-2, 1.2, 1.3), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.68242392712840734e-1, 1.2, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 3.14130045246195449e-1, 1.2, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.09630779074755253e-01, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.83998640641553852e-1, 1.2, 1.3), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 6.34733581351938787e-1, 1.2, 1.3), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 8.48446237879200975e-1, 1.2, 1.3), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.00987726336875039e-1, 1.2, 1.3), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.64489127047688435e-1, 1.2, 1.3), 100.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.92012051694116388e-1, 1.2, 1.3), 1000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.98210862808842585e-1, 1.2, 1.3), 10000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.0, 1.2, 1.3), 0.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.88939151413976144e-1, 1.2, 1.3), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.56136324293168615e-1, 1.2, 1.3), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 8.31757607287159265e-1, 1.2, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 6.85869954753804551e-1, 1.2, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.90369220925244747e-1, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.16001359358446148e-1, 1.2, 1.3), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 3.65266418648061213e-1, 1.2, 1.3), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.51553762120799025e-1, 1.2, 1.3), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.90122736631249612e-2, 1.2, 1.3), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 3.55108729523115643e-2, 1.2, 1.3), 100.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 7.98794830588361109e-3, 1.2, 1.3), 1000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.7891371911574145e-3, 1.2, 1.3), 10000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 0.0, 500.0, 1.3), 0.0, 0.0); TEST (gsl_cdf_fdist_Pinv, ( 9.83434460393304765e-141, 500.0, 1.3), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.45915624888550014e-26, 500.0, 1.3), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.89976509619688165e-4, 500.0, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 6.86110486051542533e-2, 500.0, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 3.38475053806404615e-1, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 4.52016245247457422e-1, 500.0, 1.3), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.27339068937388798e-1, 500.0, 1.3), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 8.16839628578413905e-1, 500.0, 1.3), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 8.81784623056911406e-1, 500.0, 1.3), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.58045057204221295e-1, 500.0, 1.3), 100.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.90585749380655275e-1, 500.0, 1.3), 1000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.97891924831461387e-1, 500.0, 1.3), 10000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.0, 500.0, 1.3), 0.0, TEST_TOL6); /* * The algorithm currently implemented in gsl_cdf_fdist_Qinv and Pinv * are not accurate for very large degrees of freedom, so the tests * here are commented out. Another algorithm more suitable for * these extreme values might pass these tests. */ TEST (gsl_cdf_fdist_Qinv, ( 9.99410023490380312e-1, 500.0, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.31388951394845747e-1, 500.0, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 6.61524946193595385e-1, 500.0, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 5.47983754752542572e-1, 500.0, 1.3), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.72660931062611202e-1, 500.0, 1.3), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.83160371421586096e-1, 500.0, 1.3), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.18215376943088595e-1, 500.0, 1.3), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.19549427957787016e-2, 500.0, 1.3), 100.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.41425061934473424e-3, 500.0, 1.3), 1000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 2.10807516853862603e-3, 500.0, 1.3), 10000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 0.0, 1.2, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_Pinv, ( 8.23342055585482999e-61, 1.2, 500.0), 1e-100, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.30461496441289529e-2, 1.2, 500.0), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.18324224608033294e-2, 1.2, 500.0), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 2.02235101716076289e-1, 1.2, 500.0), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 3.90502983219393749e-1, 1.2, 500.0), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 6.67656191574653619e-1, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 7.75539230271467054e-1, 1.2, 500.0), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 8.45209114904613705e-1, 1.2, 500.0), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.99168017659120988e-1, 1.2, 500.0), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.99998005738371669e-1, 1.2, 500.0), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.0, 1.2, 500.0), GSL_POSINF, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.0, 1.2, 500.0), GSL_POSINF, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.0, 1.2, 500.0), GSL_POSINF, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.0, 1.2, 500.0), 0.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.86953850355871047e-1, 1.2, 500.0), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 9.48167577539196671e-1, 1.2, 500.0), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 7.97764898283923711e-1, 1.2, 500.0), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 6.09497016780606251e-1, 1.2, 500.0), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 3.32343808425346381e-1, 1.2, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 2.24460769728532946e-1, 1.2, 500.0), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.54790885095386295e-1, 1.2, 500.0), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 8.3198234087901168e-4, 1.2, 500.0), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.99426162833131e-6, 1.2, 500.0), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 6.23302662288217117e-25, 1.2, 500.0), 100.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.14328577259666930e-134, 1.2, 500.0), 1000.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 0.0, 1.2, 500.0), GSL_POSINF, 0.0); TEST (gsl_cdf_fdist_Pinv, ( 0.0, 200.0, 500.0), 0.0, 0.0); TEST (gsl_cdf_fdist_Pinv, ( 4.09325080403669893e-251, 200.0, 500.0), 0.001, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.17894325419628688e-151, 200.0, 500.0), 0.01, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.92430940796861258e-57, 200.0, 500.0), 0.1, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 3.18220452357263554e-18, 200.0, 500.0), 0.325, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 5.06746326121168266e-1, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 9.99794175718712438e-1, 200.0, 500.0), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Pinv, ( 1.0, 200.0, 500.0), GSL_POSINF, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 1.0, 200.0, 500.0), 0.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.93253673878831734e-1, 200.0, 500.0), 1.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 2.05824281287561795e-4, 200.0, 500.0), 1.5, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 4.71763848371410786e-10, 200.0, 500.0), 2.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 5.98048337181948436e-96, 200.0, 500.0), 10.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 2.92099265879979502e-155, 200.0, 500.0), 20.0, TEST_TOL6); TEST (gsl_cdf_fdist_Qinv, ( 0.0, 200.0, 500.0), GSL_POSINF, 0.0); TEST (gsl_cdf_fdist_Pinv, (0.95,1.0,261.0), 3.8773340322508720313e+00, TEST_TOL3); } /* Tests for gamma distribution */ /* p(x, a, b) := gammaP(b, x / a) */ void test_gamma (void) { TEST (gsl_cdf_gamma_P, (0.0, 1.0, 1.0), 0.0, 0.0); TEST (gsl_cdf_gamma_P, (1e-100, 1.0, 1.0), 1e-100, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.001, 1.0, 1.0), 9.99500166625008332e-4, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.01, 1.0, 1.0), 9.95016625083194643e-3, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.1, 1.0, 1.0), 9.51625819640404268e-2, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.325, 1.0, 1.0), 2.77472646357927811e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.0, 1.0, 1.0), 6.32120558828557678e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.5, 1.0, 1.0), 7.76869839851570171e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (2.0, 1.0, 1.0), 8.64664716763387308e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10.0, 1.0, 1.0), 9.99954600070237515e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (20.0, 1.0, 1.0), 9.99999997938846378e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (100.0, 1.0, 1.0), 1e0, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1000.0, 1.0, 1.0), 1e0, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10000.0, 1.0, 1.0), 1e0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.0, 1.0, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1e-100, 1.0, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.001, 1.0, 1.0), 9.99000499833374992e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.01, 1.0, 1.0), 9.90049833749168054e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.1, 1.0, 1.0), 9.04837418035959573e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.325, 1.0, 1.0), 7.22527353642072189e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.0, 1.0, 1.0), 3.67879441171442322e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.5, 1.0, 1.0), 2.23130160148429829e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (2.0, 1.0, 1.0), 1.35335283236612692e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (10.0, 1.0, 1.0), 4.53999297624848515e-5, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (20.0, 1.0, 1.0), 2.06115362243855783e-9, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (100.0, 1.0, 1.0), 3.72007597602083596e-44, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1000.0, 1.0, 1.0), 0.0, 0.0); TEST (gsl_cdf_gamma_Q, (10000.0, 1.0, 1.0), 0.0, 0.0); TEST (gsl_cdf_gamma_P, (0.0, 1.0, 10.0), 0.0, 0.0); TEST (gsl_cdf_gamma_P, (1e-100, 1.0, 10.0), 1e-101, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.001, 1.0, 10.0), 9.99950001666625001e-5, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.01, 1.0, 10.0), 9.99500166625008332e-4, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.1, 1.0, 10.0), 9.95016625083194643e-3, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.325, 1.0, 10.0), 3.19775501686939529e-2, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.0, 1.0, 10.0), 9.51625819640404268e-2, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.5, 1.0, 10.0), 1.39292023574942193e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (2.0, 1.0, 10.0), 1.81269246922018141e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10.0, 1.0, 10.0), 6.32120558828557678e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (20.0, 1.0, 10.0), 8.64664716763387308e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (100.0, 1.0, 10.0), 9.99954600070237515e-1, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1000.0, 1.0, 10.0), 1e0, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10000.0, 1.0, 10.0), 1e0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.0, 1.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1e-100, 1.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.001, 1.0, 10.0), 9.99900004999833337e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.01, 1.0, 10.0), 9.99000499833374992e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.1, 1.0, 10.0), 9.90049833749168054e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.325, 1.0, 10.0), 9.68022449831306047e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.0, 1.0, 10.0), 9.04837418035959573e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.5, 1.0, 10.0), 8.60707976425057807e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (2.0, 1.0, 10.0), 8.18730753077981859e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (10.0, 1.0, 10.0), 3.67879441171442322e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (20.0, 1.0, 10.0), 1.35335283236612692e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (100.0, 1.0, 10.0), 4.53999297624848515e-5, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1000.0, 1.0, 10.0), 3.72007597602083596e-44, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (10000.0, 1.0, 10.0), 0.0, 0.0); TEST (gsl_cdf_gamma_P, (0.0, 17.0, 10.0), 0e0, 0.0); TEST (gsl_cdf_gamma_P, (1e-100, 17.0, 10.0), 0e0, 0.0); TEST (gsl_cdf_gamma_P, (0.001, 17.0, 10.0), 2.81119174040422844e-83, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.01, 17.0, 10.0), 2.80880324651985887e-66, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.1, 17.0, 10.0), 2.78502998087492130e-49, TEST_TOL6); TEST (gsl_cdf_gamma_P, (0.325, 17.0, 10.0), 1.37283653245125844e-40, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.0, 17.0, 10.0), 2.55811932292544243e-32, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1.5, 17.0, 10.0), 2.40420441175422372e-29, TEST_TOL6); TEST (gsl_cdf_gamma_P, (2.0, 17.0, 10.0), 3.05092926217898577e-27, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10.0, 17.0, 10.0), 1.094920130378183e-15, TEST_TOL6); TEST (gsl_cdf_gamma_P, (20.0, 17.0, 10.0), 5.60605096173161688e-11, TEST_TOL6); TEST (gsl_cdf_gamma_P, (100.0, 17.0, 10.0), 2.70416097848011280e-2, TEST_TOL6); TEST (gsl_cdf_gamma_P, (1000.0, 17.0, 10.0), 1.000000000000000000e0, TEST_TOL6); TEST (gsl_cdf_gamma_P, (10000.0, 17.0, 10.0), 1.000000000000000000e0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.0, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1e-100, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.001, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.01, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.1, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (0.325, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.0, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1.5, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (2.0, 17.0, 10.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (10.0, 17.0, 10.0), 9.99999999999998905e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (20.0, 17.0, 10.0), 9.99999999943939490e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (100.0, 17.0, 10.0), 9.72958390215198872e-1, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (1000.0, 17.0, 10.0), 2.11200951633948570e-25, TEST_TOL6); TEST (gsl_cdf_gamma_Q, (10000.0, 17.0, 10.0), 0.0, 0.0); } void test_chisq (void) { TEST (gsl_cdf_chisq_P, (0.0, 13.0), 0.0, 0.0); TEST (gsl_cdf_chisq_P, (1e-100, 13.0), 0.0, 0.0); TEST (gsl_cdf_chisq_P, (0.001, 13.0), 1.86631102655845996e-25, TEST_TOL6); TEST (gsl_cdf_chisq_P, (0.01, 13.0), 5.87882248504529790e-19, TEST_TOL6); TEST (gsl_cdf_chisq_P, (0.1, 13.0), 1.78796983358555410e-12, TEST_TOL6); TEST (gsl_cdf_chisq_P, (0.325, 13.0), 3.44611313779905183e-9, TEST_TOL6); TEST (gsl_cdf_chisq_P, (1.0, 13.0), 3.83473473513595154e-6, TEST_TOL6); TEST (gsl_cdf_chisq_P, (1.5, 13.0), 4.31718389201041932e-5, TEST_TOL6); TEST (gsl_cdf_chisq_P, (2.0, 13.0), 2.26250084656047180e-4, TEST_TOL6); TEST (gsl_cdf_chisq_P, (10.0, 13.0), 3.06065632019251110e-1, TEST_TOL6); TEST (gsl_cdf_chisq_P, (20.0, 13.0), 9.04789743921908487e-1, TEST_TOL6); TEST (gsl_cdf_chisq_P, (100.0, 13.0), 9.99999999999998341e-1, TEST_TOL6); TEST (gsl_cdf_chisq_P, (1000.0, 13.0), 1e0, TEST_TOL6); TEST (gsl_cdf_chisq_P, (10000.0, 13.0), 1e0, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (0.0, 13.0), 1e0, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (1e-100, 13.0), 1e0, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (0.001, 13.0), 1e0, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (0.01, 13.0), 9.99999999999999999e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (0.1, 13.0), 9.99999999998212030e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (0.325, 13.0), 9.99999996553886862e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (1.0, 13.0), 9.99996165265264864e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (1.5, 13.0), 9.99956828161079896e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (2.0, 13.0), 9.99773749915343953e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (10.0, 13.0), 6.93934367980748890e-1, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (20.0, 13.0), 9.52102560780915127e-2, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (100.0, 13.0), 1.65902608070858809e-15, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (1000.0, 13.0), 1.74851191544860225e-205, TEST_TOL6); TEST (gsl_cdf_chisq_Q, (10000.0, 13.0), 0.0, 0.0); } /* Beta distribution */ void test_beta (void) { TEST (gsl_cdf_beta_P, (0.0, 1.2, 1.3), 0.0, 0.0); TEST (gsl_cdf_beta_P, (1e-100, 1.2, 1.3), 1.34434944656489596e-120, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.001, 1.2, 1.3), 3.37630042504535813e-4, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.01, 1.2, 1.3), 5.34317264038929473e-3, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.1, 1.2, 1.3), 8.33997828306748346e-2, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.325, 1.2, 1.3), 3.28698654180583916e-1, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.5, 1.2, 1.3), 5.29781429451299081e-1, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.9, 1.2, 1.3), 9.38529397224430659e-1, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.99, 1.2, 1.3), 9.96886438341254380e-1, TEST_TOL6); TEST (gsl_cdf_beta_P, (0.999, 1.2, 1.3), 9.99843792833067634e-1, TEST_TOL6); TEST (gsl_cdf_beta_P, (1.0, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.0, 1.2, 1.3), 1.0, 0.0); TEST (gsl_cdf_beta_Q, (1e-100, 1.2, 1.3), 1e0, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.001, 1.2, 1.3), 9.99662369957495464e-1, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.01, 1.2, 1.3), 9.94656827359610705e-1, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.1, 1.2, 1.3), 9.16600217169325165e-1, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.325, 1.2, 1.3), 6.71301345819416084e-1, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.5, 1.2, 1.3), 4.70218570548700919e-1, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.9, 1.2, 1.3), 6.14706027755693408e-2, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.99, 1.2, 1.3), 3.11356165874561958e-3, TEST_TOL6); TEST (gsl_cdf_beta_Q, (0.999, 1.2, 1.3), 1.56207166932365759e-4, TEST_TOL6); TEST (gsl_cdf_beta_Q, (1.0, 1.2, 1.3), 0.0, TEST_TOL6); } void test_betainv (void) { TEST (gsl_cdf_beta_Pinv, (0.0, 1.2, 1.3), 0.0, 0.0); TEST (gsl_cdf_beta_Pinv, ( 1.34434944656489596e-120, 1.2, 1.3), 1e-100, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 3.37630042504535813e-4, 1.2, 1.3), 0.001, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 5.34317264038929473e-3, 1.2, 1.3), 0.01, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 8.33997828306748346e-2, 1.2, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 3.28698654180583916e-1, 1.2, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 5.29781429451299081e-1, 1.2, 1.3), 0.5, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 9.38529397224430659e-1, 1.2, 1.3), 0.9, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 9.96886438341254380e-1, 1.2, 1.3), 0.99, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 9.99843792833067634e-1, 1.2, 1.3), 0.999, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 1.0, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 1.0, 1.2, 1.3), 0.0, 0.0); TEST (gsl_cdf_beta_Qinv, ( 1e0, 1.2, 1.3), 0.0, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 9.99662369957495464e-1, 1.2, 1.3), 0.001, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 9.94656827359610705e-1, 1.2, 1.3), 0.01, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 9.16600217169325165e-1, 1.2, 1.3), 0.1, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 6.71301345819416084e-1, 1.2, 1.3), 0.325, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 4.70218570548700919e-1, 1.2, 1.3), 0.5, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 6.14706027755693408e-2, 1.2, 1.3), 0.9, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 3.11356165874561958e-3, 1.2, 1.3), 0.99, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 1.56207166932365759e-4, 1.2, 1.3), 0.999, TEST_TOL6); TEST (gsl_cdf_beta_Qinv, ( 0.0, 1.2, 1.3), 1.0, TEST_TOL6); TEST (gsl_cdf_beta_Pinv, ( 0.025, 2133.0, 7868.0), 0.20530562929915865457928654, TEST_TOL6); } void test_gammainv (void) { TEST (gsl_cdf_gamma_Pinv, (0.0, 1.0, 1.0), 0.0, 0.0); TEST (gsl_cdf_gamma_Pinv, (1e-100, 1.0, 1.0), 1e-100, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (9.99500166625008332e-4, 1.0, 1.0), 0.001, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (9.95016625083194643e-3, 1.0, 1.0), 0.01, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (9.51625819640404268e-2, 1.0, 1.0), 0.1, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (2.77472646357927811e-1, 1.0, 1.0), 0.325, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (6.32120558828557678e-1, 1.0, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (7.76869839851570171e-1, 1.0, 1.0), 1.5, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (8.64664716763387308e-1, 1.0, 1.0), 2.0, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (9.99954600070237515e-1, 1.0, 1.0), 10.0, TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (9.99999997938846378e-1, 1.0, 1.0), 20.0, 100 * TEST_TOL6); TEST (gsl_cdf_gamma_Pinv, (1.0, 1.0, 1.0), GSL_POSINF, 0.0); /* Test case from Benjamin Redelings <benjamin_redelings@ncsu.edu> */ /* fails on x86_64, FIXME test value is from octave -- get high precision value */ TEST (gsl_cdf_gamma_Pinv, (0.1, 11.887411491530846,1.0), 7.73788447848618e+00, TEST_TOL1); TEST (gsl_cdf_gamma_Qinv, (0.0, 1.0, 1.0), GSL_POSINF, 0.0); TEST (gsl_cdf_gamma_Qinv, (2.06115362243855783e-9, 1.0, 1.0), 20.0, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (4.53999297624848515e-5, 1.0, 1.0), 10.0, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (1.35335283236612692e-1, 1.0, 1.0), 2.0, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (2.23130160148429829e-1, 1.0, 1.0), 1.5, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (3.67879441171442322e-1, 1.0, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (7.22527353642072189e-1, 1.0, 1.0), 0.325, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (9.04837418035959573e-1, 1.0, 1.0), 0.1, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (9.90049833749168054e-1, 1.0, 1.0), 0.01, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (9.99000499833374992e-1, 1.0, 1.0), 0.001, TEST_TOL6); TEST (gsl_cdf_gamma_Qinv, (1.0, 1.0, 1.0), 0.0, 0.0); } void test_chisqinv (void) { TEST (gsl_cdf_chisq_Pinv, (0.0, 13.0), 0.0, 0.0); TEST (gsl_cdf_chisq_Pinv, (1.86631102655845996e-25, 13.0), 0.001, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (5.87882248504529790e-19, 13.0), 0.01, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (1.78796983358555410e-12, 13.0), 0.1, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (3.44611313779905183e-9, 13.0), 0.325, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (3.83473473513595154e-6, 13.0), 1.0, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (4.31718389201041932e-5, 13.0), 1.5, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (2.26250084656047180e-4, 13.0), 2.0, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (3.06065632019251110e-1, 13.0), 10.0, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (9.04789743921908487e-1, 13.0), 20.0, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (9.99999999999998341e-1, 13.0), 100.0, 0.01); TEST (gsl_cdf_chisq_Pinv, (1e0, 13.0), GSL_POSINF, 0.0); TEST (gsl_cdf_chisq_Pinv, (1.93238145206123590e-01, 1.5), 0.211980092931799521729407, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (4.83e-8, 19.19), 1.632280186860266704532868343, TEST_TOL6); /* Test cases for bug 24704 */ TEST (gsl_cdf_chisq_Pinv, (0.05, 1263131.0), 1260517.771133388726131469059, TEST_TOL6); TEST (gsl_cdf_chisq_Pinv, (0.05, 2526262.0), 2522565.864973351096735720202, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (0.0, 13.0), GSL_POSINF, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (1.65902608070858809e-15, 13.0), 100.0, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (9.52102560780915127e-2, 13.0), 20.0, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (6.93934367980748892e-1, 13.0), 10.0, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (9.99773749915343954e-1, 13.0), 2.0, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (9.99956828161079894e-1, 13.0), 1.5, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (9.99996165265264863e-1, 13.0), 1.0, TEST_TOL6); TEST (gsl_cdf_chisq_Qinv, (9.99999996553886862e-1, 13.0), 0.325, 1e-6); TEST (gsl_cdf_chisq_Qinv, (9.99999999998212031e-1, 13.0), 0.1, 1e-5); TEST (gsl_cdf_chisq_Qinv, (1.0, 13.0), 0.0, 0.0); } void test_tdistinv (void) { TEST (gsl_cdf_tdist_Pinv, (0.5, 1.0), 0.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.00318309780080559e-1, 1.0), 0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.03182992764908255e-1, 1.0), 0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.31725517430553569e-1, 1.0), 0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (6.00023120032852123e-1, 1.0), 0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (0.75000000000000000e0, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (8.12832958189001183e-1, 1.0), 1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (8.52416382349566726e-1, 1.0), 2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.68274482569446430e-1, 1.0), 10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.84097748743823625e-1, 1.0), 20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.96817007235091745e-1, 1.0), 100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.99681690219919441e-1, 1.0), 1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.99968169011487724e-1, 1.0), 10000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (0.5, 1.0), 0.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.99681690219919441e-1, 1.0), 0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.96817007235091745e-1, 1.0), 0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.68274482569446430e-1, 1.0), 0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.99976879967147876e-1, 1.0), 0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (2.5e-1, 1.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.87167041810998816e-1, 1.0), 1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.47583617650433274e-1, 1.0), 2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.17255174305535695e-2, 1.0), 10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.59022512561763752e-2, 1.0), 20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.18299276490825515e-3, 1.0), 100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.18309780080558939e-4, 1.0), 1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.18309885122757724e-5, 1.0), 10000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.99681690219919441e-1, 1.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.96817007235091744e-1, 1.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.68274482569446430e-1, 1.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.99976879967147876e-1, 1.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (0.25, 1.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.87167041810998816e-1, 1.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.47583617650433274e-1, 1.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.17255174305535695e-2, 1.0), -10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.59022512561763751e-2, 1.0), -20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.18299276490825514e-3, 1.0), -100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.18309780080558938e-4, 1.0), -1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.18309885122757724e-5, 1.0), -10000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.00318309780080559e-1, 1.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.03182992764908255e-1, 1.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.31725517430553570e-1, 1.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (6.00023120032852124e-1, 1.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (7.5e-1, 1.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (8.12832958189001184e-1, 1.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (8.52416382349566726e-1, 1.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.68274482569446430e-1, 1.0), -10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.84097748743823625e-1, 1.0), -20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.96817007235091745e-1, 1.0), -100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.99681690219919441e-1, 1.0), -1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.99968169011487724e-1, 1.0), -10000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.99646446697795041e-01, 2.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.96464554479100486e-01, 2.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.64732719207070087e-01, 2.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.88014227253126233e-01, 2.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (2.11324865405187118e-01, 2.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.36196562445500540e-01, 2.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.17517095361369836e-02, 2.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.92622851166284542e-03, 2.0), -10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.24533194618354849e-03, 2.0), -20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.99925012497812894e-05, 2.0), -100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.99999250001249998e-07, 2.0), -1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.99999992500000125e-09, 2.0), -10000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.00353553302204959e-1, 2.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.03535445520899514e-1, 2.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.35267280792929913e-1, 2.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (6.11985772746873767e-1, 2.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (7.88675134594812882e-1, 2.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (8.63803437554499460e-1, 2.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.08248290463863016e-1, 2.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.95073771488337155e-1, 2.0), -10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.98754668053816452e-1, 2.0), -20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.99950007498750219e-1, 2.0), -100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.99999500000749999e-1, 2.0), -1000.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.99999995000000075e-1, 2.0), -10000.0, 1e-6); TEST (gsl_cdf_tdist_Pinv, (5.00000000000000000e-01, 300.0), 0.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.00398609900942949e-01, 300.0), 0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.03986033020559088e-01, 300.0), 0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (5.39794441177768194e-01, 300.0), 0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (6.27296201542523812e-01, 300.0), 0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (8.40941797784686861e-01, 300.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.32666983425369137e-01, 300.0), 1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (9.76799239508425455e-01, 300.0), 2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.00000000000000000e+00, 300.0), GSL_POSINF, 0.0); TEST (gsl_cdf_tdist_Qinv, (5.00000000000000000e-01, 300.0), 0.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.99601390099057051e-1, 300.0), 0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.96013966979440912e-1, 300.0), 0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (4.60205558822231806e-1, 300.0), 0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (3.72703798457476188e-1, 300.0), 0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.59058202215313138e-1, 300.0), 1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (6.73330165746308628e-2, 300.0), 1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (2.32007604915745452e-2, 300.0), 2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (8.279313677e-21, 300.0), 10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.93159812815803978e-57, 300.0), 20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.02557519997736154e-232, 300.0), 100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (0.00000000000000000e+00, 300.0), GSL_POSINF, 0.0); TEST (gsl_cdf_tdist_Pinv, (4.99601390099057051e-01, 300.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.96013966979440912e-01, 300.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (4.60205558822231806e-01, 300.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (3.72703798457476188e-01, 300.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.59058202215313138e-01, 300.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (6.73330165746308628e-02, 300.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (2.32007604915745452e-02, 300.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (8.279313675556272534e-21, 300.0), -10.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.93159812815803978e-57, 300.0), -20.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (1.02557519997736154e-232, 300.0), -100.0, TEST_TOL6); TEST (gsl_cdf_tdist_Pinv, (0.0, 300.0), GSL_NEGINF, 0.0); TEST (gsl_cdf_tdist_Qinv, (5.00398609900942949e-1, 300.0), -0.001, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.03986033020559088e-1, 300.0), -0.01, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (5.39794441177768194e-1, 300.0), -0.1, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (6.27296201542523812e-1, 300.0), -0.325, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (8.40941797784686862e-1, 300.0), -1.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.32666983425369137e-1, 300.0), -1.5, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (9.76799239508425455e-1, 300.0), -2.0, TEST_TOL6); TEST (gsl_cdf_tdist_Qinv, (1.000000000000000000e0, 300.0), GSL_NEGINF, TEST_TOL6); }
{ "alphanum_fraction": 0.6992699298, "avg_line_length": 51.2665229885, "ext": "c", "hexsha": "109b5ea0ba0aeba2c20907a7fa7a7565fde0838a", "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": "b723fcad149662a9af981c4e507678d9c7f106d2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "WikiGaze/Wikipedia-readers-gaze", "max_forks_repo_path": "Integration/gsl-1.15/cdf/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2", "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": "WikiGaze/Wikipedia-readers-gaze", "max_issues_repo_path": "Integration/gsl-1.15/cdf/test.c", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "WikiGaze/Wikipedia-readers-gaze", "max_stars_repo_path": "Integration/gsl-1.15/cdf/test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 35389, "size": 71363 }
#include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <omp.h> #include <cblas.h> //Threshold for testing validity of matrix matrix multiplication #define ERROR_THRESHOLD 0.0001 //For measuring wall time using omp_get_wtime() static double start; static double end; //Serial version. Do not change this! void serial_mxm(const double *A, const double *B, double *C, int m, int n, int k) { clock_t start, end; start = clock(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i * n + j] = 0; for (int l = 0; l < k; l++) { C[i * n + j] += A[i * k + l] * B[l * n + j]; } } } end = clock(); printf("\nUsage: %f", (((double)end - (double)start) / (double)CLOCKS_PER_SEC)); } void omp_mxm(double *A, double *B, double *C, int m, int n, int k) { clock_t start, end; start = clock(); #pragma omp parallell for for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[i * n + j] = 0; for (int l = 0; l < k; l++) { C[i * n + j] += A[i * k + l] * B[l * n + j]; } } } end = clock(); printf("\nUsage: %f", (((double)end - (double)start) / (double)CLOCKS_PER_SEC)); } void blas_mxm(double *A, double *B, double *C, int m, int n, int k) { clock_t start, end; start = clock(); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 1.0, C, n); end = clock(); printf("\nUsage: %f", (((double)end - (double)start) / (double)CLOCKS_PER_SEC)); } int main(const unsigned int argc, char **argv) { if (argc <= optind) { printf("Please provide version:\n"); printf("\ts(serial),\n"); printf("\to(penmp) or\n"); printf("\tb(las)\n"); return 0; } char input = argv[optind][0]; optind++; //Simple assumptions that any additional arguments means we want to test the results bool test = !(argc <= optind); int m = 2000; int n = 1000; int k = 200; double *A = (double *)malloc(m * k * sizeof(double)); double *B = (double *)malloc(k * n * sizeof(double)); double *C = (double *)malloc(m * n * sizeof(double)); //Intializing matrix data for (int i = 0; i < (m * k); i++) { A[i] = (double)(i + 1); } for (int i = 0; i < (k * n); i++) { B[i] = (double)(-i - 1); } for (int i = 0; i < (m * n); i++) { C[i] = 0.0; } switch (input) { case 's': serial_mxm(A, B, C, m, n, k); break; case 'o': omp_mxm(A, B, C, m, n, k); break; case 'b': blas_mxm(A, B, C, m, n, k); break; default: printf("Please provide version:\n"); printf("\ts(serial),\n"); printf("\to(penmp) or\n"); printf("\tb(las)\n"); return 0; } printf("\nTop left of A:\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%8.2f\t", A[i * k + j]); } printf("\n"); } printf("\nTop left of B:\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%8.2f\t", B[i * n + j]); } printf("\n"); } printf("\nTop left of C:\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%8.2f\t", C[i * n + j]); } printf("\n"); } if (test) { double *C2 = (double *)malloc(m * n * sizeof(double)); serial_mxm(A, B, C2, m, n, k); bool correct = true; for (int i = 0; i < (m * n); i++) { if (abs(C[i] - C2[i]) > ERROR_THRESHOLD) { correct = false; } } if (correct) { printf("\nMatrix multiplication succeeded\n"); } else { printf("\nMatrix multiplication failed\n"); printf("Top left of correct C:\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { printf("%8.2f\t", C2[i * n + j]); } printf("\n"); } } } printf("\nVersion: %c, time: %.4f\n", input, end - start); return 0; }
{ "alphanum_fraction": 0.4953668921, "avg_line_length": 21.2393617021, "ext": "c", "hexsha": "e7110747fe6664feb2f7bd24507a09326560e607", "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": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andham97/TDT4200", "max_forks_repo_path": "Assignment5/openmp/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "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": "andham97/TDT4200", "max_issues_repo_path": "Assignment5/openmp/main.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andham97/TDT4200", "max_stars_repo_path": "Assignment5/openmp/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1407, "size": 3993 }
/* * Copyright 2017 Daniel Eachern Huang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AUGUR_HDR_H #define AUGUR_HDR_H #ifdef AUGURCPU #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> typedef gsl_rng augur_rng; #ifndef EXTERNC #define EXTERNC #endif #ifndef __HOSTORDEV__ #define __HOSTORDEV__ #endif #ifndef __HOSTDEV__ #define __HOSTDEV__ #endif #else #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> #include <curand.h> #include <curand_kernel.h> #include <thrust/transform_reduce.h> #include <thrust/inner_product.h> #include <thrust/device_ptr.h> #include <thrust/functional.h> #include <thrust/execution_policy.h> typedef curandState_t augur_rng; #ifndef EXTERNC #define EXTERNC extern "C" #endif #ifndef __HOSTORDEV__ #define __HOSTORDEV__ EXTERNC __device__ #endif #ifndef __HOSTDEV__ #define __HOSTDEV__ EXTERNC __host__ __device__ #endif #define THRDS 256 #define BLKS(x) ((int) ceil(((double) x) / THRDS)) #endif #endif
{ "alphanum_fraction": 0.7467277487, "avg_line_length": 17.1685393258, "ext": "h", "hexsha": "b061ffaa9d6aea5069351ab4f060061c4bd36897", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-02-18T20:17:36.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-10T21:55:18.000Z", "max_forks_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rjnw/augurv2", "max_forks_repo_path": "cbits/augur_hdr.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_issues_repo_issues_event_max_datetime": "2017-09-20T19:38:00.000Z", "max_issues_repo_issues_event_min_datetime": "2017-09-20T19:18:13.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rjnw/augurv2", "max_issues_repo_path": "cbits/augur_hdr.h", "max_line_length": 75, "max_stars_count": 14, "max_stars_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rjnw/augurv2", "max_stars_repo_path": "cbits/augur_hdr.h", "max_stars_repo_stars_event_max_datetime": "2020-12-18T15:07:41.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-06T19:51:00.000Z", "num_tokens": 390, "size": 1528 }
/* Some preprocessor magic for having fast inline functions. */ #include <gsl/gsl_matrix.h> #ifndef INLINE #define INLINE static inline #endif #ifndef INLINE_DECL #define INLINE_DECL static inline #endif /* Some preprocessor magic for the "restrict" keyword: http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html */ #if __STDC_VERSION__ >= 199901 #elif defined (__GNUC__) && __GNUC__ >= 2 && __GNUC_MINOR__ >= 91 #define restrict __restrict__ #else #define restrict #endif /* Some preprocessor magic for calling this library from C++ */ #ifdef __cplusplus #define restrict /* nothing */ #endif
{ "alphanum_fraction": 0.7637795276, "avg_line_length": 24.4230769231, "ext": "h", "hexsha": "5582dd51e70559ee8189568688c67ef732e25015", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/csm/restrict.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/csm/restrict.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/csm/restrict.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 151, "size": 635 }
// Copyright 2019-2020 CERN and copyright holders of ALICE O2. // See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. // All rights not expressly granted are reserved. // // This software is distributed under the terms of the GNU General Public // License v3 (GPL Version 3), copied verbatim in the file "COPYING". // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #ifndef O2_FRAMEWORK_ASOA_H_ #define O2_FRAMEWORK_ASOA_H_ #include "Framework/Pack.h" #include "Framework/CheckTypes.h" #include "Framework/FunctionalHelpers.h" #include "Framework/CompilerBuiltins.h" #include "Framework/Traits.h" #include "Framework/Expressions.h" #include "Framework/ArrowTypes.h" #include "Framework/RuntimeError.h" #include "Framework/Kernels.h" #include <arrow/table.h> #include <arrow/array.h> #include <arrow/util/variant.h> #include <gandiva/selection_vector.h> #include <cassert> #include <fmt/format.h> #include <typeinfo> #include <gsl/span> namespace o2::soa { template <typename... C> auto createSchemaFromColumns(framework::pack<C...>) { return std::make_shared<arrow::Schema>(std::vector<std::shared_ptr<arrow::Field>>{C::asArrowField()...}); } using SelectionVector = std::vector<int64_t>; template <typename, typename = void> inline constexpr bool is_index_column_v = false; template <typename T> inline constexpr bool is_index_column_v<T, std::void_t<decltype(sizeof(typename T::binding_t))>> = true; template <typename, typename = void> inline constexpr bool is_type_with_originals_v = false; template <typename T> inline constexpr bool is_type_with_originals_v<T, std::void_t<decltype(sizeof(typename T::originals))>> = true; template <typename T, typename = void> inline constexpr bool is_type_with_parent_v = false; template <typename T> inline constexpr bool is_type_with_parent_v<T, std::void_t<decltype(sizeof(typename T::parent_t))>> = true; template <typename, typename = void> inline constexpr bool is_type_with_metadata_v = false; template <typename T> inline constexpr bool is_type_with_metadata_v<T, std::void_t<decltype(sizeof(typename T::metadata))>> = true; template <typename, typename = void> inline constexpr bool is_type_with_binding_v = false; template <typename T> inline constexpr bool is_type_with_binding_v<T, std::void_t<decltype(sizeof(typename T::binding_t))>> = true; template <typename, typename = void> inline constexpr bool is_type_spawnable_v = false; template <typename T> inline constexpr bool is_type_spawnable_v<T, std::void_t<decltype(sizeof(typename T::spawnable_t))>> = true; template <typename, typename = void> inline constexpr bool is_soa_extension_table_v = false; template <typename T> inline constexpr bool is_soa_extension_table_v<T, std::void_t<decltype(sizeof(typename T::expression_pack_t))>> = true; template <typename T, typename = void> inline constexpr bool is_index_table_v = false; template <typename T> inline constexpr bool is_index_table_v<T, std::void_t<decltype(sizeof(typename T::indexing_t))>> = true; template <typename, typename = void> inline constexpr bool is_self_index_column_v = false; template <typename T> inline constexpr bool is_self_index_column_v<T, std::void_t<decltype(sizeof(typename T::self_index_t))>> = true; template <typename T, typename TLambda> void call_if_has_originals(TLambda&& lambda) { if constexpr (is_type_with_originals_v<T>) { lambda(static_cast<T*>(nullptr)); } } template <typename T, typename TLambda> void call_if_has_not_originals(TLambda&& lambda) { if constexpr (!is_type_with_originals_v<T>) { lambda(static_cast<T*>(nullptr)); } } template <typename H, typename... T> constexpr auto make_originals_from_type() { using decayed = std::decay_t<H>; if constexpr (sizeof...(T) == 0) { if constexpr (is_type_with_originals_v<decayed>) { return typename decayed::originals{}; } else if constexpr (is_type_with_originals_v<typename decayed::table_t>) { return typename decayed::table_t::originals{}; } else if constexpr (is_type_with_parent_v<decayed>) { return make_originals_from_type<typename decayed::parent_t>(); } else { return framework::pack<decayed>{}; } } else if constexpr (is_type_with_originals_v<decayed>) { return framework::concatenate_pack(typename decayed::originals{}, make_originals_from_type<T...>()); } else if constexpr (is_type_with_originals_v<typename decayed::table_t>) { return framework::concatenate_pack(typename decayed::table_t::originals{}, make_originals_from_type<T...>()); } else { return framework::concatenate_pack(framework::pack<decayed>{}, make_originals_from_type<T...>()); } } template <typename... T> constexpr auto make_originals_from_type(framework::pack<T...>) { return make_originals_from_type<T...>(); } /// Policy class for columns which are chunked. This /// will make the compiler take the most generic (and /// slow approach). struct Chunked { constexpr static bool chunked = true; }; /// Policy class for columns which are known to be fully /// inside a chunk. This will generate optimal code. struct Flat { constexpr static bool chunked = false; }; /// unwrapper template <typename T> struct unwrap { using type = T; }; template <typename T> struct unwrap<std::vector<T>> { using type = T; }; template <> struct unwrap<bool> { using type = char; }; template <typename T> using unwrap_t = typename unwrap<T>::type; /// Iterator on a single column. /// FIXME: the ChunkingPolicy for now is fixed to Flat and is a mere boolean /// which is used to switch off slow "chunking aware" parts. This is ok for /// now, but most likely we should move the whole chunk navigation logic there. template <typename T, typename ChunkingPolicy = Chunked> class ColumnIterator : ChunkingPolicy { static constexpr char SCALE_FACTOR = std::is_same_v<std::decay_t<T>, bool> ? 3 : 0; public: /// Constructor of the column iterator. Notice how it takes a pointer /// to the ChunkedArray (for the data store) and to the index inside /// it. This means that a ColumnIterator is actually only available /// as part of a RowView. ColumnIterator(arrow::ChunkedArray const* column) : mColumn{column}, mCurrent{nullptr}, mCurrentPos{nullptr}, mLast{nullptr}, mFirstIndex{0}, mCurrentChunk{0}, mOffset{0} { auto array = getCurrentArray(); mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR); mLast = mCurrent + array->length(); } ColumnIterator() = default; ColumnIterator(ColumnIterator<T, ChunkingPolicy> const&) = default; ColumnIterator<T, ChunkingPolicy>& operator=(ColumnIterator<T, ChunkingPolicy> const&) = default; ColumnIterator(ColumnIterator<T, ChunkingPolicy>&&) = default; ColumnIterator<T, ChunkingPolicy>& operator=(ColumnIterator<T, ChunkingPolicy>&&) = default; /// Move the iterator to the next chunk. void nextChunk() const { auto previousArray = getCurrentArray(); mFirstIndex += previousArray->length(); mCurrentChunk++; auto array = getCurrentArray(); mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR); mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR); } void prevChunk() const { auto previousArray = getCurrentArray(); mFirstIndex -= previousArray->length(); mCurrentChunk--; auto array = getCurrentArray(); mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR); mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR); } void moveToChunk(int chunk) { if (mCurrentChunk < chunk) { while (mCurrentChunk != chunk) { nextChunk(); } } else { while (mCurrentChunk != chunk) { prevChunk(); } } } /// Move the iterator to the end of the column. void moveToEnd() { mCurrentChunk = mColumn->num_chunks() - 1; auto array = getCurrentArray(); mFirstIndex = mColumn->length() - array->length(); mCurrent = reinterpret_cast<unwrap_t<T> const*>(array->values()->data()) + (mOffset >> SCALE_FACTOR) - (mFirstIndex >> SCALE_FACTOR); mLast = mCurrent + array->length() + (mFirstIndex >> SCALE_FACTOR); } decltype(auto) operator*() const { if constexpr (ChunkingPolicy::chunked) { if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) { auto list = std::static_pointer_cast<arrow::ListArray>(mColumn->chunk(mCurrentChunk)); if (O2_BUILTIN_UNLIKELY(*mCurrentPos - mFirstIndex >= list->length())) { nextChunk(); } } else { if (O2_BUILTIN_UNLIKELY(((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) >= mLast))) { nextChunk(); } } } if constexpr (std::is_same_v<bool, std::decay_t<T>>) { // FIXME: check if shifting the masked bit to the first position is better than != 0 return (*(mCurrent + (*mCurrentPos >> SCALE_FACTOR)) & (1 << ((*mCurrentPos + mOffset) & 0x7))) != 0; } else if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) { auto list = std::static_pointer_cast<arrow::ListArray>(mColumn->chunk(mCurrentChunk)); auto offset = list->value_offset(*mCurrentPos - mFirstIndex); auto length = list->value_length(*mCurrentPos - mFirstIndex); return gsl::span{mCurrent + mFirstIndex + offset, mCurrent + mFirstIndex + (offset + length)}; } else { return *(mCurrent + (*mCurrentPos >> SCALE_FACTOR)); } } // Move to the chunk which containts element pos ColumnIterator<T>& moveToPos() { // If we get outside range of the current chunk, go to the next. if constexpr (ChunkingPolicy::chunked) { while (O2_BUILTIN_UNLIKELY((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) >= mLast)) { nextChunk(); } } return *this; } // Move to the chunk which containts element pos ColumnIterator<T>& checkNextChunk() { if constexpr (ChunkingPolicy::chunked) { if (O2_BUILTIN_LIKELY((mCurrent + (*mCurrentPos >> SCALE_FACTOR)) <= mLast)) { return *this; } nextChunk(); } return *this; } mutable unwrap_t<T> const* mCurrent; int64_t const* mCurrentPos; mutable unwrap_t<T> const* mLast; arrow::ChunkedArray const* mColumn; mutable int mFirstIndex; mutable int mCurrentChunk; mutable int mOffset; private: /// get pointer to mCurrentChunk chunk auto getCurrentArray() const { std::shared_ptr<arrow::Array> chunkToUse = mColumn->chunk(mCurrentChunk); mOffset = chunkToUse->offset(); if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::FixedSizeListArray>) { chunkToUse = std::dynamic_pointer_cast<arrow::FixedSizeListArray>(chunkToUse)->values(); return std::static_pointer_cast<arrow_array_for_t<value_for_t<T>>>(chunkToUse); } else if constexpr (std::is_same_v<arrow_array_for_t<T>, arrow::ListArray>) { chunkToUse = std::dynamic_pointer_cast<arrow::ListArray>(chunkToUse)->values(); mOffset = chunkToUse->offset(); return std::static_pointer_cast<arrow_array_for_t<value_for_t<T>>>(chunkToUse); } else { return std::static_pointer_cast<arrow_array_for_t<T>>(chunkToUse); } } }; template <typename T, typename INHERIT> struct Column { using inherited_t = INHERIT; Column(ColumnIterator<T> const& it) : mColumnIterator{it} { } Column() = default; Column(Column const&) = default; Column& operator=(Column const&) = default; Column(Column&&) = default; Column& operator=(Column&&) = default; using persistent = std::true_type; using type = T; static constexpr const char* const& columnLabel() { return INHERIT::mLabel; } ColumnIterator<T> const& getIterator() const { return mColumnIterator; } static auto asArrowField() { return std::make_shared<arrow::Field>(inherited_t::mLabel, framework::expressions::concreteArrowType(framework::expressions::selectArrowType<type>())); } /// FIXME: rather than keeping this public we should have a protected /// non-const getter and mark this private. ColumnIterator<T> mColumnIterator; }; /// The purpose of this class is to store the lambda which is associated to the /// method call. template <typename F, typename INHERIT> struct DynamicColumn { using inherited_t = INHERIT; using persistent = std::false_type; static constexpr const char* const& columnLabel() { return INHERIT::mLabel; } }; template <typename INHERIT> struct IndexColumn { using inherited_t = INHERIT; using persistent = std::false_type; static constexpr const char* const& columnLabel() { return INHERIT::mLabel; } }; template <int64_t START = 0, int64_t END = -1> struct Index : o2::soa::IndexColumn<Index<START, END>> { using base = o2::soa::IndexColumn<Index<START, END>>; constexpr inline static int64_t start = START; constexpr inline static int64_t end = END; Index() = default; Index(Index const&) = default; Index(Index&&) = default; Index& operator=(Index const&) = default; Index& operator=(Index&&) = default; Index(arrow::ChunkedArray const*) { } constexpr inline int64_t rangeStart() { return START; } constexpr inline int64_t rangeEnd() { return END; } int64_t index() const { return index<0>(); } int64_t filteredIndex() const { return index<1>(); } int64_t globalIndex() const { return index<0>() + offsets<0>(); } template <int N = 0> int64_t index() const { return *std::get<N>(rowIndices); } template <int N = 0> int64_t offsets() const { return *std::get<N>(rowOffsets); } void setIndices(std::tuple<int64_t const*, int64_t const*> indices) { rowIndices = indices; } void setOffsets(std::tuple<uint64_t const*> offsets) { rowOffsets = offsets; } static constexpr const char* mLabel = "Index"; using type = int64_t; using bindings_t = typename o2::framework::pack<>; std::tuple<> boundIterators; std::tuple<int64_t const*, int64_t const*> rowIndices; /// The offsets within larger tables. Currently only /// one level of nesting is supported. std::tuple<uint64_t const*> rowOffsets; }; template <typename T> using is_dynamic_t = framework::is_specialization<typename T::base, DynamicColumn>; template <typename T> using is_persistent_t = typename std::decay_t<T>::persistent::type; template <typename T> using is_external_index_t = typename std::conditional<is_index_column_v<T>, std::true_type, std::false_type>::type; template <typename T> using is_self_index_t = typename std::conditional<is_self_index_column_v<T>, std::true_type, std::false_type>::type; template <typename T, template <auto...> class Ref> struct is_index : std::false_type { }; template <template <auto...> class Ref, auto... Args> struct is_index<Ref<Args...>, Ref> : std::true_type { }; template <typename T> using is_index_t = is_index<T, Index>; struct IndexPolicyBase { /// Position inside the current table int64_t mRowIndex = 0; /// Offset within a larger table uint64_t mOffset = 0; }; struct RowViewSentinel { uint64_t const index; }; struct DefaultIndexPolicy : IndexPolicyBase { /// Needed to be able to copy the policy DefaultIndexPolicy() = default; DefaultIndexPolicy(DefaultIndexPolicy&&) = default; DefaultIndexPolicy(DefaultIndexPolicy const&) = default; DefaultIndexPolicy& operator=(DefaultIndexPolicy const&) = default; DefaultIndexPolicy& operator=(DefaultIndexPolicy&&) = default; /// mMaxRow is one behind the last row, so effectively equal to the number of /// rows @a nRows. Offset indicates that the index is actually part of /// a larger DefaultIndexPolicy(int64_t nRows, uint64_t offset) : IndexPolicyBase{0, offset}, mMaxRow(nRows) { } void limitRange(int64_t start, int64_t end) { this->setCursor(start); if (end >= 0) { mMaxRow = std::min(end, mMaxRow); } } std::tuple<int64_t const*, int64_t const*> getIndices() const { return std::make_tuple(&mRowIndex, &mRowIndex); } std::tuple<uint64_t const*> getOffsets() const { return std::make_tuple(&mOffset); } void setCursor(int64_t i) { this->mRowIndex = i; } void moveByIndex(int64_t i) { this->mRowIndex += i; } void moveToEnd() { this->setCursor(mMaxRow); } bool operator!=(DefaultIndexPolicy const& other) const { return O2_BUILTIN_LIKELY(this->mRowIndex != other.mRowIndex); } bool operator==(DefaultIndexPolicy const& other) const { return O2_BUILTIN_UNLIKELY(this->mRowIndex == other.mRowIndex); } bool operator!=(RowViewSentinel const& sentinel) const { return O2_BUILTIN_LIKELY(this->mRowIndex != sentinel.index); } bool operator==(RowViewSentinel const& sentinel) const { return O2_BUILTIN_UNLIKELY(this->mRowIndex == sentinel.index); } auto size() const { return mMaxRow; } int64_t mMaxRow = 0; }; struct FilteredIndexPolicy : IndexPolicyBase { // We use -1 in the IndexPolicyBase to indicate that the index is // invalid. What will validate the index is the this->setCursor() // which happens below which will properly setup the first index // by remapping the filtered index 0 to whatever unfiltered index // it belongs to. FilteredIndexPolicy(gsl::span<int64_t const> selection, uint64_t offset = 0) : IndexPolicyBase{-1, offset}, mSelectedRows(selection), mMaxSelection(selection.size()) { this->setCursor(0); } FilteredIndexPolicy() = default; FilteredIndexPolicy(FilteredIndexPolicy&&) = default; FilteredIndexPolicy(FilteredIndexPolicy const&) = default; FilteredIndexPolicy& operator=(FilteredIndexPolicy const&) = default; FilteredIndexPolicy& operator=(FilteredIndexPolicy&&) = default; std::tuple<int64_t const*, int64_t const*> getIndices() const { return std::make_tuple(&mRowIndex, &mSelectionRow); } std::tuple<uint64_t const*> getOffsets() const { return std::make_tuple(&mOffset); } void limitRange(int64_t start, int64_t end) { this->setCursor(start); if (end >= 0) { mMaxSelection = std::min(end, mMaxSelection); } } void setCursor(int64_t i) { mSelectionRow = i; updateRow(); } void moveByIndex(int64_t i) { mSelectionRow += i; updateRow(); } bool operator!=(FilteredIndexPolicy const& other) const { return O2_BUILTIN_LIKELY(mSelectionRow != other.mSelectionRow); } bool operator==(FilteredIndexPolicy const& other) const { return O2_BUILTIN_UNLIKELY(mSelectionRow == other.mSelectionRow); } bool operator!=(RowViewSentinel const& sentinel) const { return O2_BUILTIN_LIKELY(mSelectionRow != sentinel.index); } bool operator==(RowViewSentinel const& sentinel) const { return O2_BUILTIN_UNLIKELY(mSelectionRow == sentinel.index); } /// Move iterator to one after the end. Since this is a view /// we move the mSelectionRow to one past the view size and /// the mRowIndex to one past the last entry in the selection void moveToEnd() { this->mSelectionRow = this->mMaxSelection; this->mRowIndex = -1; } auto getSelectionRow() const { return mSelectionRow; } auto size() const { return mMaxSelection; } private: inline void updateRow() { this->mRowIndex = O2_BUILTIN_LIKELY(mSelectionRow < mMaxSelection) ? mSelectedRows[mSelectionRow] : -1; } gsl::span<int64_t const> mSelectedRows; int64_t mSelectionRow = 0; int64_t mMaxSelection = 0; }; template <typename... C> class Table; /// Similar to a pair but not a pair, to avoid /// exposing the second type everywhere. template <typename C> struct ColumnDataHolder { C* first; arrow::ChunkedArray* second; }; template <typename IP, typename... C> struct RowViewCore : public IP, C... { public: using policy_t = IP; using table_t = o2::soa::Table<C...>; using all_columns = framework::pack<C...>; using persistent_columns_t = framework::selected_pack<is_persistent_t, C...>; using dynamic_columns_t = framework::selected_pack<is_dynamic_t, C...>; using index_columns_t = framework::selected_pack<is_index_t, C...>; constexpr inline static bool has_index_v = framework::pack_size(index_columns_t{}) > 0; using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>; using internal_index_columns_t = framework::selected_pack<is_self_index_t, C...>; RowViewCore(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy) : IP{policy}, C(columnData[framework::has_type_at_v<C>(all_columns{})])... { bindIterators(persistent_columns_t{}); bindAllDynamicColumns(dynamic_columns_t{}); // In case we have an index column might need to constrain the actual // number of rows in the view to the range provided by the index. // FIXME: we should really understand what happens to an index when we // have a RowViewFiltered. if constexpr (has_index_v) { this->limitRange(this->rangeStart(), this->rangeEnd()); } } RowViewCore() = default; RowViewCore(RowViewCore<IP, C...> const& other) : IP{static_cast<IP const&>(other)}, C(static_cast<C const&>(other))... { bindIterators(persistent_columns_t{}); bindAllDynamicColumns(dynamic_columns_t{}); } RowViewCore(RowViewCore&& other) noexcept { IP::operator=(static_cast<IP&&>(other)); (void(static_cast<C&>(*this) = static_cast<C&&>(other)), ...); bindIterators(persistent_columns_t{}); bindAllDynamicColumns(dynamic_columns_t{}); } RowViewCore& operator=(RowViewCore const& other) { IP::operator=(static_cast<IP const&>(other)); (void(static_cast<C&>(*this) = static_cast<C const&>(other)), ...); bindIterators(persistent_columns_t{}); bindAllDynamicColumns(dynamic_columns_t{}); return *this; } RowViewCore& operator=(RowViewCore&& other) noexcept { IP::operator=(static_cast<IP&&>(other)); (void(static_cast<C&>(*this) = static_cast<C&&>(other)), ...); return *this; } RowViewCore& operator++() { this->moveByIndex(1); return *this; } RowViewCore operator++(int) { RowViewCore<IP, C...> copy = *this; this->operator++(); return copy; } RowViewCore& operator--() { this->moveByIndex(-1); return *this; } RowViewCore operator--(int) { RowViewCore<IP, C...> copy = *this; this->operator--(); return copy; } /// Allow incrementing by more than one the iterator RowViewCore operator+(int64_t inc) const { RowViewCore copy = *this; copy.moveByIndex(inc); return copy; } RowViewCore operator-(int64_t dec) const { return operator+(-dec); } RowViewCore const& operator*() const { return *this; } /// Inequality operator. Actual implementation /// depend on the policy we use for the index. using IP::operator!=; /// Equality operator. Actual implementation /// depend on the policy we use for the index. using IP::operator==; template <typename... CL, typename TA> void doSetCurrentIndex(framework::pack<CL...>, TA* current) { (CL::setCurrent(current), ...); } template <typename CL> auto getCurrent() const { return CL::getCurrentRaw(); } template <typename... Cs> auto getIndexBindingsImpl(framework::pack<Cs...>) const { return std::vector<void const*>{static_cast<Cs const&>(*this).getCurrentRaw()...}; } auto getIndexBindings() const { return getIndexBindingsImpl(external_index_columns_t{}); } template <typename... TA> void bindExternalIndices(TA*... current) { (doSetCurrentIndex(external_index_columns_t{}, current), ...); } template <typename... Cs> void doSetCurrentIndexRaw(framework::pack<Cs...> p, std::vector<void const*>&& ptrs) { (Cs::setCurrentRaw(ptrs[framework::has_type_at_v<Cs>(p)]), ...); } template <typename... Cs, typename E> void doSetCurrentInternal(framework::pack<Cs...>, E* ptr) { (Cs::setCurrentRaw(ptr), ...); } void bindExternalIndicesRaw(std::vector<void const*>&& ptrs) { doSetCurrentIndexRaw(external_index_columns_t{}, std::forward<std::vector<void const*>>(ptrs)); } template <typename E> void bindInternalIndices(E* table) { doSetCurrentInternal(internal_index_columns_t{}, table); } private: /// Helper to move to the correct chunk, if needed. /// FIXME: not needed? template <typename... PC> void checkNextChunk(framework::pack<PC...>) { (PC::mColumnIterator.checkNextChunk(), ...); } /// Helper to move at the end of columns which actually have an iterator. template <typename... PC> void doMoveToEnd(framework::pack<PC...>) { (PC::mColumnIterator.moveToEnd(), ...); } /// Helper which binds all the ColumnIterators to the /// index of a the associated RowView template <typename... PC> auto bindIterators(framework::pack<PC...>) { using namespace o2::soa; (void(PC::mColumnIterator.mCurrentPos = &this->mRowIndex), ...); } template <typename... DC> auto bindAllDynamicColumns(framework::pack<DC...>) { using namespace o2::soa; (bindDynamicColumn<DC>(typename DC::bindings_t{}), ...); if constexpr (has_index_v) { this->setIndices(this->getIndices()); this->setOffsets(this->getOffsets()); } } template <typename DC, typename... B> auto bindDynamicColumn(framework::pack<B...>) { DC::boundIterators = std::make_tuple(&(B::mColumnIterator)...); } }; template <typename, typename = void> constexpr bool is_type_with_policy_v = false; template <typename T> constexpr bool is_type_with_policy_v<T, std::void_t<decltype(sizeof(typename T::policy_t))>> = true; struct ArrowHelpers { static std::shared_ptr<arrow::Table> joinTables(std::vector<std::shared_ptr<arrow::Table>>&& tables); static std::shared_ptr<arrow::Table> concatTables(std::vector<std::shared_ptr<arrow::Table>>&& tables); }; template <typename... T> using originals_pack_t = decltype(make_originals_from_type<T...>()); template <typename T> using is_soa_iterator_t = typename framework::is_base_of_template<RowViewCore, T>; template <typename T> constexpr bool is_soa_iterator_v() { return is_soa_iterator_t<T>::value || framework::is_specialization_v<T, RowViewCore>; } template <typename T> using is_soa_table_t = typename framework::is_specialization<T, soa::Table>; template <typename T> using is_soa_table_like_t = typename framework::is_base_of_template<soa::Table, T>; /// Helper function to extract bound indices template <typename... Is> static constexpr auto extractBindings(framework::pack<Is...>) { return framework::pack<typename Is::binding_t...>{}; } template <typename T> class Filtered; SelectionVector selectionToVector(gandiva::Selection const& sel); template <typename T> auto select(T const& t, framework::expressions::Filter const& f) { return Filtered<T>({t.asArrowTable()}, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f))); } template <typename T> auto sliceBy(T const& t, framework::expressions::BindingNode const& node, int value) { uint64_t offset = 0; std::shared_ptr<arrow::Table> result = nullptr; auto status = o2::framework::getSliceFor(value, node.name.c_str(), t.asArrowTable(), result, offset); if (status.ok()) { return T({result}, offset); } o2::framework::throw_error(o2::framework::runtime_error("Failed to slice table")); O2_BUILTIN_UNREACHABLE(); } arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, const char* label); /// A Table class which observes an arrow::Table and provides /// It is templated on a set of Column / DynamicColumn types. template <typename... C> class Table { public: using table_t = Table<C...>; using columns = framework::pack<C...>; using column_types = framework::pack<typename C::type...>; using persistent_columns_t = framework::selected_pack<is_persistent_t, C...>; using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>; static constexpr auto hashes() { return std::set{typeid(C).hash_code()...}; } template <typename IP, typename Parent, typename... T> struct RowViewBase : public RowViewCore<IP, C...> { using external_index_columns_t = framework::selected_pack<is_external_index_t, C...>; using bindings_pack_t = decltype(extractBindings(external_index_columns_t{})); using parent_t = Parent; using originals = originals_pack_t<T...>; RowViewBase(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy) : RowViewCore<IP, C...>(columnData, std::forward<decltype(policy)>(policy)) { } template <typename Tbl = table_t> RowViewBase(RowViewBase<IP, Tbl, Tbl> const& other) : RowViewCore<IP, C...>(other) { } template <typename Tbl = table_t> RowViewBase(RowViewBase<IP, Tbl, Tbl>&& other) noexcept : RowViewCore<IP, C...>(other) { } RowViewBase() = default; RowViewBase(RowViewBase const&) = default; RowViewBase(RowViewBase&&) = default; RowViewBase& operator=(RowViewBase const&) = default; RowViewBase& operator=(RowViewBase&&) = default; RowViewBase& operator=(RowViewSentinel const& other) { this->mRowIndex = other.index; return *this; } void matchTo(RowViewBase const& other) { this->mRowIndex = other.mRowIndex; } template <typename TI> auto getId() const { using decayed = std::decay_t<TI>; if constexpr (framework::has_type_v<decayed, bindings_pack_t>) { constexpr auto idx = framework::has_type_at_v<decayed>(bindings_pack_t{}); return framework::pack_element_t<idx, external_index_columns_t>::getId(); } else if constexpr (std::is_same_v<decayed, Parent>) { return this->globalIndex(); } else { return static_cast<int32_t>(-1); } } using IP::size; using RowViewCore<IP, C...>::operator++; /// Allow incrementing by more than one the iterator RowViewBase operator+(int64_t inc) const { RowViewBase copy = *this; copy.moveByIndex(inc); return copy; } RowViewBase operator-(int64_t dec) const { return operator+(-dec); } RowViewBase const& operator*() const { return *this; } }; template <typename P, typename... Ts> using RowView = RowViewBase<DefaultIndexPolicy, P, Ts...>; template <typename P, typename... Ts> using RowViewFiltered = RowViewBase<FilteredIndexPolicy, P, Ts...>; using iterator = RowView<table_t, table_t>; using const_iterator = RowView<table_t, table_t>; using unfiltered_iterator = RowView<table_t, table_t>; using unfiltered_const_iterator = RowView<table_t, table_t>; using filtered_iterator = RowViewFiltered<table_t, table_t>; using filtered_const_iterator = RowViewFiltered<table_t, table_t>; Table(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : mTable(table), mEnd{static_cast<uint64_t>(table->num_rows())}, mOffset(offset) { if (mTable->num_rows() == 0) { for (size_t ci = 0; ci < sizeof...(C); ++ci) { mColumnChunks[ci] = nullptr; } mBegin = mEnd; } else { arrow::ChunkedArray* lookups[] = {lookupColumn<C>()...}; for (size_t ci = 0; ci < sizeof...(C); ++ci) { mColumnChunks[ci] = lookups[ci]; } mBegin = unfiltered_iterator{mColumnChunks, {table->num_rows(), offset}}; bindInternalIndices(); } } /// FIXME: this is to be able to construct a Filtered without explicit Join /// so that Filtered<Table1,Table2, ...> always means a Join which /// may or may not be a problem later Table(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset = 0) : Table(ArrowHelpers::joinTables(std::move(tables)), offset) { } unfiltered_iterator begin() { return unfiltered_iterator(mBegin); } RowViewSentinel end() { return RowViewSentinel{mEnd}; } filtered_iterator filtered_begin(gsl::span<int64_t const> selection) { // Note that the FilteredIndexPolicy will never outlive the selection which // is held by the table, so we are safe passing the bare pointer. If it does it // means that the iterator on a table is outliving the table itself, which is // a bad idea. return filtered_iterator(mColumnChunks, {selection, mOffset}); } iterator iteratorAt(uint64_t i) const { return rawIteratorAt(i); } unfiltered_iterator rawIteratorAt(uint64_t i) const { auto it = mBegin + i; it.bindInternalIndices((void*)this); return it; } unfiltered_const_iterator begin() const { return unfiltered_const_iterator(mBegin); } RowViewSentinel end() const { return RowViewSentinel{mEnd}; } /// Return a type erased arrow table backing store for / the type safe table. std::shared_ptr<arrow::Table> asArrowTable() const { return mTable; } /// Return offset auto offset() const { return mOffset; } /// Size of the table, in rows. int64_t size() const { return mTable->num_rows(); } int64_t tableSize() const { return size(); } /// Bind the columns which refer to other tables /// to the associated tables. template <typename... TA> void bindExternalIndices(TA*... current) { mBegin.bindExternalIndices(current...); } void bindInternalIndices() { mBegin.bindInternalIndices(this); } template <typename T> void bindInternalIndicesTo(T* ptr) { mBegin.bindInternalIndices(ptr); } void bindExternalIndicesRaw(std::vector<void const*>&& ptrs) { mBegin.bindExternalIndicesRaw(std::forward<std::vector<void const*>>(ptrs)); } template <typename T, typename... Cs> void doCopyIndexBindings(framework::pack<Cs...>, T& dest) const { dest.bindExternalIndicesRaw(mBegin.getIndexBindings()); } template <typename T> void copyIndexBindings(T& dest) const { doCopyIndexBindings(external_index_columns_t{}, dest); } auto select(framework::expressions::Filter const& f) const { auto t = o2::soa::select(*this, f); copyIndexBindings(t); return t; } auto sliceByCached(framework::expressions::BindingNode const& node, int value) { uint64_t offset = 0; std::shared_ptr<arrow::Table> result = nullptr; auto status = this->getSliceFor(value, node.name.c_str(), result, offset); if (status.ok()) { auto t = table_t({result}, offset); copyIndexBindings(t); return t; } o2::framework::throw_error(o2::framework::runtime_error("Failed to slice table")); O2_BUILTIN_UNREACHABLE(); } auto sliceBy(framework::expressions::BindingNode const& node, int value) const { auto t = o2::soa::sliceBy(*this, node, value); copyIndexBindings(t); return t; } auto slice(uint64_t start, uint64_t end) const { return rawSlice(start, end); } auto rawSlice(uint64_t start, uint64_t end) const { return table_t{mTable->Slice(start, end - start + 1), start}; } auto emptySlice() const { return table_t{mTable->Slice(0, 0), 0}; } protected: /// Offset of the table within a larger table. uint64_t mOffset; private: template <typename T> arrow::ChunkedArray* lookupColumn() { if constexpr (T::persistent::value) { auto label = T::columnLabel(); return getIndexFromLabel(mTable.get(), label); } else { return nullptr; } } std::shared_ptr<arrow::Table> mTable; // Cached pointers to the ChunkedArray associated to a column arrow::ChunkedArray* mColumnChunks[sizeof...(C)]; /// Cached begin iterator for this table. unfiltered_iterator mBegin; /// Cached end iterator for this table. RowViewSentinel mEnd; std::string mCurrentKey; std::shared_ptr<arrow::NumericArray<arrow::Int32Type>> mValues = nullptr; std::shared_ptr<arrow::NumericArray<arrow::Int64Type>> mCounts = nullptr; arrow::Status initializeSliceCaches(char const* key) { mCurrentKey = key; return o2::framework::getSlices(key, mTable, mValues, mCounts); } public: arrow::Status getSliceFor(int value, const char* key, std::shared_ptr<arrow::Table>& output, uint64_t& offset) { arrow::Status status; if (mCurrentKey != key) { status = initializeSliceCaches(key); } if (!status.ok()) { return status; } for (auto slice = 0; slice < mValues->length(); ++slice) { if (mValues->Value(slice) == value) { output = mTable->Slice(offset, mCounts->Value(slice)); return arrow::Status::OK(); } offset += mCounts->Value(slice); } output = mTable->Slice(offset, 0); return arrow::Status::OK(); } }; template <typename T> struct PackToTable { static_assert(framework::always_static_assert_v<T>, "Not a pack"); }; template <typename... C> struct PackToTable<framework::pack<C...>> { using table = o2::soa::Table<C...>; }; template <typename... T> struct TableWrap { using all_columns = framework::concatenated_pack_unique_t<typename T::columns...>; using table_t = typename PackToTable<all_columns>::table; }; /// Template trait which allows to map a given /// Table type to its O2 DataModel origin and description template <typename INHERIT> class TableMetadata { public: static constexpr char const* tableLabel() { return INHERIT::mLabel; } static constexpr char const (&origin())[4] { return INHERIT::mOrigin; } static constexpr char const (&description())[16] { return INHERIT::mDescription; } static std::string sourceSpec() { return fmt::format("{}/{}/{}", INHERIT::mLabel, INHERIT::mOrigin, INHERIT::mDescription); }; }; /// Helper template to define universal join template <typename Key, typename H, typename... Ts> struct IndexTable; template <typename... C1, typename... C2> constexpr auto joinTables(o2::soa::Table<C1...> const& t1, o2::soa::Table<C2...> const& t2) { return o2::soa::Table<C1..., C2...>(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()})); } // special case for appending an index template <typename... C1, typename Key, typename H, typename... C2> constexpr auto joinTables(o2::soa::Table<C1...> const& t1, o2::soa::IndexTable<Key, H, C2...> const& t2) { return joinTables(t1, o2::soa::Table<H, C2...>{t2.asArrowTable()}); } template <typename T, typename... C, typename... O> constexpr auto joinLeft(T const& t1, o2::soa::Table<C...> const& t2, framework::pack<O...>) { return typename o2::soa::TableWrap<O..., o2::soa::Table<C...>>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()})); } template <typename T, typename... C, typename... O> constexpr auto joinRight(o2::soa::Table<C...> const& t1, T const& t2, framework::pack<O...>) { return typename o2::soa::TableWrap<o2::soa::Table<C...>, O...>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()})); } template <typename T1, typename T2, typename... O1, typename... O2> constexpr auto joinBoth(T1 const& t1, T2 const& t2, framework::pack<O1...>, framework::pack<O2...>) { return typename o2::soa::TableWrap<O1..., O2...>::table_t(ArrowHelpers::joinTables({t1.asArrowTable(), t2.asArrowTable()})); } template <typename T1, typename T2> constexpr auto join(T1 const& t1, T2 const& t2) { if constexpr (soa::is_type_with_originals_v<T1>) { if constexpr (soa::is_type_with_originals_v<T2>) { return joinBoth(t1, t2, typename T1::originals{}, typename T2::originals{}); } else { return joinLeft(t1, t2, typename T1::originals{}); } } else { if constexpr (soa::is_type_with_originals_v<T2>) { return joinRight(t1, t2, typename T2::originals{}); } else { return joinTables(t1, t2); } } } template <typename T1, typename T2, typename... Ts> constexpr auto join(T1 const& t1, T2 const& t2, Ts const&... ts) { return join(t1, join(t2, ts...)); } template <typename T1, typename T2> constexpr auto concat(T1&& t1, T2&& t2) { using table_t = typename PackToTable<framework::intersected_pack_t<typename T1::columns, typename T2::columns>>::table; return table_t(ArrowHelpers::concatTables({t1.asArrowTable(), t2.asArrowTable()})); } template <typename... Ts> using JoinBase = decltype(join(std::declval<Ts>()...)); template <typename T1, typename T2> using ConcatBase = decltype(concat(std::declval<T1>(), std::declval<T2>())); template <typename B, typename E> struct EquivalentIndex { constexpr static bool value = false; }; template <typename B, typename E> constexpr bool is_index_equivalent_v = EquivalentIndex<B, E>::value || EquivalentIndex<E, B>::value; template <typename T, typename... Os> constexpr bool are_bindings_compatible_v(framework::pack<Os...>&&) { if constexpr (is_type_with_originals_v<T>) { return (are_bindings_compatible_v<Os>(originals_pack_t<T>{}) || ...); } else { return ((std::is_same_v<T, Os> || is_index_equivalent_v<T, Os>) || ...); } } template <typename T, typename B> constexpr bool is_binding_compatible_v() { return are_bindings_compatible_v<T>(originals_pack_t<B>{}); } void notBoundTable(const char* tableName); } // namespace o2::soa #define DECLARE_SOA_STORE() \ template <typename T> \ struct MetadataTrait { \ using metadata = std::void_t<T>; \ } #define DECLARE_EQUIVALENT_FOR_INDEX(_Base_, _Equiv_) \ template <> \ struct EquivalentIndex<_Base_, _Equiv_> { \ constexpr static bool value = true; \ } #define DECLARE_SOA_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_) \ struct _Name_ : o2::soa::Column<_Type_, _Name_> { \ static constexpr const char* mLabel = _Label_; \ static_assert(!((*(mLabel + 1) == 'I' && *(mLabel + 2) == 'n' && *(mLabel + 3) == 'd' && *(mLabel + 4) == 'e' && *(mLabel + 5) == 'x')), "Index is not a valid column name"); \ using base = o2::soa::Column<_Type_, _Name_>; \ using type = _Type_; \ using column_t = _Name_; \ _Name_(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_() = default; \ _Name_(_Name_ const& other) = default; \ _Name_& operator=(_Name_ const& other) = default; \ \ decltype(auto) _Getter_() const \ { \ return *mColumnIterator; \ } \ }; \ static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_COLUMN(_Name_, _Getter_, _Type_) \ DECLARE_SOA_COLUMN_FULL(_Name_, _Getter_, _Type_, "f" #_Name_) /// An 'expression' column. i.e. a column that can be calculated from other /// columns with gandiva based on supplied C++ expression. #define DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_, _Expression_) \ struct _Name_ : o2::soa::Column<_Type_, _Name_> { \ static constexpr const char* mLabel = _Label_; \ using base = o2::soa::Column<_Type_, _Name_>; \ using type = _Type_; \ using column_t = _Name_; \ using spawnable_t = std::true_type; \ _Name_(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_, _Name_>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_() = default; \ _Name_(_Name_ const& other) = default; \ _Name_& operator=(_Name_ const& other) = default; \ \ decltype(auto) _Getter_() const \ { \ return *mColumnIterator; \ } \ static o2::framework::expressions::Projector Projector() \ { \ return _Expression_; \ } \ }; \ static const o2::framework::expressions::BindingNode _Getter_ { _Label_, typeid(_Name_).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_EXPRESSION_COLUMN(_Name_, _Getter_, _Type_, _Expression_) \ DECLARE_SOA_EXPRESSION_COLUMN_FULL(_Name_, _Getter_, _Type_, "f" #_Name_, _Expression_); /// An index column is a column of indices to elements / of another table named /// _Name_##s. The column name will be _Name_##Id and will always be stored in /// "fIndex"#_Table_#[_Suffix_]. If _Suffix_ is not empty it has to begin /// with _ (underscore) to make the columns identifiable for the table merging /// It will also have two special methods, setCurrent(...) /// and getCurrent(...) which allow you to set / retrieve associated table. /// It also exposes a getter _Getter_ which allows you to retrieve the pointed /// object. /// Notice how in order to define an index column, the table it points /// to **must** be already declared. This is therefore only /// useful to express child -> parent relationships. In case one /// needs to go from parent to child, the only way is to either have /// a separate "association" with the two indices, or to use the standard /// grouping mechanism of AnalysisTask. /// /// Normal index: returns iterator to a bound table /// Slice index: return an instance of the bound table type with a slice defined by the values in 0 and 1st elements /// Array index: return an array of iterators, defined by values in its elements /// SLICE #define DECLARE_SOA_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_) \ struct _Name_##IdSlice : o2::soa::Column<_Type_[2], _Name_##IdSlice> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static_assert((*_Suffix_ == '\0') || (*_Suffix_ == '_'), "Suffix has to begin with _"); \ static constexpr const char* mLabel = "fIndexSlice" #_Table_ _Suffix_; \ using base = o2::soa::Column<_Type_[2], _Name_##IdSlice>; \ using type = _Type_[2]; \ using column_t = _Name_##IdSlice; \ using binding_t = _Table_; \ _Name_##IdSlice(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_[2], _Name_##IdSlice>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##IdSlice() = default; \ _Name_##IdSlice(_Name_##IdSlice const& other) = default; \ _Name_##IdSlice& operator=(_Name_##IdSlice const& other) = default; \ std::array<_Type_, 2> inline getIds() const \ { \ return _Getter_##Ids(); \ } \ \ bool has_##_Getter_() const \ { \ auto a = *mColumnIterator; \ return a[0] >= 0 && a[1] >= 0; \ } \ \ std::array<_Type_, 2> _Getter_##Ids() const \ { \ auto a = *mColumnIterator; \ return std::array{a[0], a[1]}; \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) { \ o2::soa::notBoundTable(#_Table_); \ } \ if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) { \ return static_cast<T const*>(mBinding)->emptySlice(); \ } \ auto a = *mColumnIterator; \ auto t = static_cast<T const*>(mBinding)->rawSlice(a[0], a[1]); \ static_cast<T const*>(mBinding)->copyIndexBindings(t); \ return t; \ } \ \ auto _Getter_() const \ { \ return _Getter_##_as<binding_t>(); \ } \ \ template <typename T> \ bool setCurrent(T* current) \ { \ if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) { \ assert(current != nullptr); \ this->mBinding = current; \ return true; \ } \ return false; \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; #define DECLARE_SOA_SLICE_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, "") /// ARRAY #define DECLARE_SOA_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_) \ struct _Name_##Ids : o2::soa::Column<std::vector<_Type_>, _Name_##Ids> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static_assert((*_Suffix_ == '\0') || (*_Suffix_ == '_'), "Suffix has to begin with _"); \ static constexpr const char* mLabel = "fIndexArray" #_Table_ _Suffix_; \ using base = o2::soa::Column<std::vector<_Type_>, _Name_##Ids>; \ using type = std::vector<_Type_>; \ using column_t = _Name_##Ids; \ using binding_t = _Table_; \ _Name_##Ids(arrow::ChunkedArray const* column) \ : o2::soa::Column<std::vector<_Type_>, _Name_##Ids>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##Ids() = default; \ _Name_##Ids(_Name_##Ids const& other) = default; \ _Name_##Ids& operator=(_Name_##Ids const& other) = default; \ \ gsl::span<const _Type_> inline getIds() const \ { \ return _Getter_##Ids(); \ } \ \ gsl::span<const _Type_> _Getter_##Ids() const \ { \ return *mColumnIterator; \ } \ \ bool has_##_Getter_() const \ { \ return !(*mColumnIterator).empty(); \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) { \ o2::soa::notBoundTable(#_Table_); \ } \ return getIterators<T>(); \ } \ \ template <typename T> \ auto getIterators() const \ { \ auto result = std::vector<typename T::unfiltered_iterator>(); \ for (auto& i : *mColumnIterator) { \ result.push_back(static_cast<T const*>(mBinding)->rawIteratorAt(i)); \ } \ return result; \ } \ \ auto _Getter_() const \ { \ return _Getter_##_as<binding_t>(); \ } \ \ template <typename T> \ auto _Getter_##_first_as() const \ { \ if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) { \ o2::soa::notBoundTable(#_Table_); \ } \ return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator)[0]); \ } \ \ template <typename T> \ auto _Getter_##_last_as() const \ { \ if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) { \ o2::soa::notBoundTable(#_Table_); \ } \ return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator).back()); \ } \ \ auto _Getter_first() const \ { \ return _Getter_##_first_as<binding_t>(); \ } \ \ auto _Getter_last() const \ { \ return _Getter_##_last_as<binding_t>(); \ } \ \ template <typename T> \ bool setCurrent(T* current) \ { \ if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) { \ assert(current != nullptr); \ this->mBinding = current; \ return true; \ } \ return false; \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; #define DECLARE_SOA_ARRAY_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, "") /// NORMAL #define DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Table_, _Suffix_) \ struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static_assert((*_Suffix_ == '\0') || (*_Suffix_ == '_'), "Suffix has to begin with _"); \ static constexpr const char* mLabel = "fIndex" #_Table_ _Suffix_; \ using base = o2::soa::Column<_Type_, _Name_##Id>; \ using type = _Type_; \ using column_t = _Name_##Id; \ using binding_t = _Table_; \ _Name_##Id(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##Id() = default; \ _Name_##Id(_Name_##Id const& other) = default; \ _Name_##Id& operator=(_Name_##Id const& other) = default; \ type inline getId() const \ { \ return _Getter_##Id(); \ } \ \ type _Getter_##Id() const \ { \ return *mColumnIterator; \ } \ \ bool has_##_Getter_() const \ { \ return *mColumnIterator >= 0; \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ if (O2_BUILTIN_UNLIKELY(mBinding == nullptr)) { \ o2::soa::notBoundTable(#_Table_); \ } \ if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) { \ throw o2::framework::runtime_error_f("Accessing invalid index for %s", #_Getter_); \ } \ return static_cast<T const*>(mBinding)->rawIteratorAt(*mColumnIterator); \ } \ \ auto _Getter_() const \ { \ return _Getter_##_as<binding_t>(); \ } \ \ template <typename T> \ bool setCurrent(T* current) \ { \ if constexpr (o2::soa::is_binding_compatible_v<T, binding_t>()) { \ assert(current != nullptr); \ this->mBinding = current; \ return true; \ } \ return false; \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ binding_t const* getCurrent() const { return static_cast<binding_t const*>(mBinding); } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; \ static const o2::framework::expressions::BindingNode _Getter_##Id { "fIndex" #_Table_ _Suffix_, typeid(_Name_##Id).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, _Name_##s, "") /// SELF #define DECLARE_SOA_SELF_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_) \ struct _Name_##Id : o2::soa::Column<_Type_, _Name_##Id> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static constexpr const char* mLabel = "fIndex" _Label_; \ using base = o2::soa::Column<_Type_, _Name_##Id>; \ using type = _Type_; \ using column_t = _Name_##Id; \ using self_index_t = std::true_type; \ _Name_##Id(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_, _Name_##Id>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##Id() = default; \ _Name_##Id(_Name_##Id const& other) = default; \ _Name_##Id& operator=(_Name_##Id const& other) = default; \ type inline getId() const \ { \ return _Getter_##Id(); \ } \ \ type _Getter_##Id() const \ { \ return *mColumnIterator; \ } \ \ bool has_##_Getter_() const \ { \ return *mColumnIterator >= 0; \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) { \ throw o2::framework::runtime_error_f("Accessing invalid index for %s", #_Getter_); \ } \ return static_cast<T const*>(mBinding)->rawIteratorAt(*mColumnIterator); \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; \ static const o2::framework::expressions::BindingNode _Getter_##Id { "fIndex" _Label_, typeid(_Name_##Id).hash_code(), \ o2::framework::expressions::selectArrowType<_Type_>() } #define DECLARE_SOA_SELF_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, #_Name_) /// SELF SLICE #define DECLARE_SOA_SELF_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_) \ struct _Name_##IdSlice : o2::soa::Column<_Type_[2], _Name_##IdSlice> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static constexpr const char* mLabel = "fIndexSlice" _Label_; \ using base = o2::soa::Column<_Type_[2], _Name_##IdSlice>; \ using type = _Type_[2]; \ using column_t = _Name_##IdSlice; \ using self_index_t = std::true_type; \ _Name_##IdSlice(arrow::ChunkedArray const* column) \ : o2::soa::Column<_Type_[2], _Name_##IdSlice>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##IdSlice() = default; \ _Name_##IdSlice(_Name_##IdSlice const& other) = default; \ _Name_##IdSlice& operator=(_Name_##IdSlice const& other) = default; \ std::array<_Type_, 2> inline getIds() const \ { \ return _Getter_##Ids(); \ } \ \ bool has_##_Getter_() const \ { \ auto a = *mColumnIterator; \ return a[0] >= 0 && a[1] >= 0; \ } \ \ std::array<_Type_, 2> _Getter_##Ids() const \ { \ auto a = *mColumnIterator; \ return std::array{a[0], a[1]}; \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ if (O2_BUILTIN_UNLIKELY(!has_##_Getter_())) { \ return static_cast<T const*>(mBinding)->emptySlice(); \ } \ auto a = *mColumnIterator; \ auto t = static_cast<T const*>(mBinding)->rawSlice(a[0], a[1]); \ static_cast<T const*>(mBinding)->copyIndexBindings(t); \ return t; \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; #define DECLARE_SOA_SELF_SLICE_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_SLICE_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, "_" #_Name_) /// SELF ARRAY #define DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, _Type_, _Label_) \ struct _Name_##Ids : o2::soa::Column<std::vector<_Type_>, _Name_##Ids> { \ static_assert(std::is_integral_v<_Type_>, "Index type must be integral"); \ static constexpr const char* mLabel = "fIndexArray" _Label_; \ using base = o2::soa::Column<std::vector<_Type_>, _Name_##Ids>; \ using type = std::vector<_Type_>; \ using column_t = _Name_##Ids; \ using self_index_t = std::true_type; \ _Name_##Ids(arrow::ChunkedArray const* column) \ : o2::soa::Column<std::vector<_Type_>, _Name_##Ids>(o2::soa::ColumnIterator<type>(column)) \ { \ } \ \ _Name_##Ids() = default; \ _Name_##Ids(_Name_##Ids const& other) = default; \ _Name_##Ids& operator=(_Name_##Ids const& other) = default; \ gsl::span<const _Type_> inline getIds() const \ { \ return _Getter_##Ids(); \ } \ \ gsl::span<const _Type_> _Getter_##Ids() const \ { \ return *mColumnIterator; \ } \ \ bool has_##_Getter_() const \ { \ return !(*mColumnIterator).empty(); \ } \ \ template <typename T> \ auto _Getter_##_as() const \ { \ return getIterators<T>(); \ } \ \ template <typename T> \ auto getIterators() const \ { \ auto result = std::vector<typename T::unfiltered_iterator>(); \ for (auto& i : *mColumnIterator) { \ result.push_back(static_cast<T const*>(mBinding)->rawIteratorAt(i)); \ } \ return result; \ } \ \ template <typename T> \ auto _Getter_##_first_as() const \ { \ return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator)[0]); \ } \ \ template <typename T> \ auto _Getter_##_last_as() const \ { \ return static_cast<T const*>(mBinding)->rawIteratorAt((*mColumnIterator).back()); \ } \ \ bool setCurrentRaw(void const* current) \ { \ this->mBinding = current; \ return true; \ } \ void const* getCurrentRaw() const { return mBinding; } \ void const* mBinding = nullptr; \ }; #define DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN(_Name_, _Getter_) DECLARE_SOA_SELF_ARRAY_INDEX_COLUMN_FULL(_Name_, _Getter_, int32_t, "_" #_Name_) /// A dynamic column is a column whose values are derived /// from those of other real columns. These can be used for /// example to provide different coordinate systems (e.g. polar, /// cylindrical) from a persister representation (e.g. cartesian). /// _Name_ is a unique typename which will be associated with the /// column. _Getter_ is a mnemonic to retrieve the value of /// the column in a given row. The variadic template argument /// (...) is used to capture a lambda or callable object which /// will be used to perform the transformation. /// Notice that the macro will define a template type _Name_ /// which will have as template argument the types of the columns /// to be bound for the operation. /// /// For example, let's assume you have: /// /// \code{.cpp} /// /// namespace point { /// DECLARE_SOA_COLUMN(X, x, float, "fX"); /// DECLARE_SOA_COLUMN(Y, y, float, "fY"); /// } /// /// DECLARE_SOA_DYNAMIC_COLUMN(R2, r2, [](x, y) { return x*x + y+y; }); /// /// DECLARE_SOA_TABLE(Point, "MISC", "POINT", /// X, Y, (R2<X,Y>)); /// \endcode /// #define DECLARE_SOA_DYNAMIC_COLUMN(_Name_, _Getter_, ...) \ struct _Name_##Callback { \ static inline constexpr auto getLambda() { return __VA_ARGS__; } \ }; \ \ struct _Name_##Helper { \ using callable_t = decltype(o2::framework::FunctionMetadata(std::declval<decltype(_Name_##Callback::getLambda())>())); \ using return_type = typename callable_t::return_type; \ }; \ template <typename... Bindings> \ struct _Name_ : o2::soa::DynamicColumn<typename _Name_##Helper::callable_t::type, _Name_<Bindings...>> { \ using base = o2::soa::DynamicColumn<typename _Name_##Helper::callable_t::type, _Name_<Bindings...>>; \ using helper = _Name_##Helper; \ using callback_holder_t = _Name_##Callback; \ using callable_t = helper::callable_t; \ using callback_t = callable_t::type; \ \ _Name_(arrow::ChunkedArray const*) \ { \ } \ _Name_() = default; \ _Name_(_Name_ const& other) = default; \ _Name_& operator=(_Name_ const& other) = default; \ static constexpr const char* mLabel = #_Name_; \ using type = typename callable_t::return_type; \ \ template <typename... FreeArgs> \ type _Getter_(FreeArgs... freeArgs) const \ { \ return boundGetter(std::make_index_sequence<std::tuple_size_v<decltype(boundIterators)>>{}, freeArgs...); \ } \ \ template <size_t... Is, typename... FreeArgs> \ type boundGetter(std::integer_sequence<size_t, Is...>&&, FreeArgs... freeArgs) const \ { \ return __VA_ARGS__((**std::get<Is>(boundIterators))..., freeArgs...); \ } \ \ using bindings_t = typename o2::framework::pack<Bindings...>; \ std::tuple<o2::soa::ColumnIterator<typename Bindings::type> const*...> boundIterators; \ } #define DECLARE_SOA_TABLE_FULL(_Name_, _Label_, _Origin_, _Description_, ...) \ using _Name_ = o2::soa::Table<__VA_ARGS__>; \ \ struct _Name_##Metadata : o2::soa::TableMetadata<_Name_##Metadata> { \ using table_t = _Name_; \ static constexpr char const* mLabel = _Label_; \ static constexpr char const mOrigin[4] = _Origin_; \ static constexpr char const mDescription[16] = _Description_; \ }; \ \ template <> \ struct MetadataTrait<_Name_> { \ using metadata = _Name_##Metadata; \ }; \ \ template <> \ struct MetadataTrait<_Name_::unfiltered_iterator> { \ using metadata = _Name_##Metadata; \ }; #define DECLARE_SOA_TABLE(_Name_, _Origin_, _Description_, ...) \ DECLARE_SOA_TABLE_FULL(_Name_, #_Name_, _Origin_, _Description_, __VA_ARGS__); #define DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, _Origin_, _Description_, ...) \ struct _Name_##Extension : o2::soa::Table<__VA_ARGS__> { \ using base_t = o2::soa::Table<__VA_ARGS__>; \ _Name_##Extension(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : o2::soa::Table<__VA_ARGS__>(table, offset){}; \ _Name_##Extension(_Name_##Extension const&) = default; \ _Name_##Extension(_Name_##Extension&&) = default; \ using expression_pack_t = framework::pack<__VA_ARGS__>; \ using iterator = typename base_t::template RowView<_Name_##Extension, _Name_##Extension>; \ using const_iterator = iterator; \ }; \ using _Name_ = o2::soa::Join<_Name_##Extension, _Table_>; \ \ struct _Name_##ExtensionMetadata : o2::soa::TableMetadata<_Name_##ExtensionMetadata> { \ using table_t = _Name_##Extension; \ using base_table_t = typename _Table_::table_t; \ using expression_pack_t = typename _Name_##Extension::expression_pack_t; \ using originals = soa::originals_pack_t<_Table_>; \ using sources = originals; \ static constexpr char const* mLabel = #_Name_ "Extension"; \ static constexpr char const mOrigin[4] = _Origin_; \ static constexpr char const mDescription[16] = _Description_; \ }; \ \ template <> \ struct MetadataTrait<_Name_##Extension> { \ using metadata = _Name_##ExtensionMetadata; \ }; #define DECLARE_SOA_EXTENDED_TABLE(_Name_, _Table_, _Description_, ...) \ DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, "DYN", _Description_, __VA_ARGS__) #define DECLARE_SOA_EXTENDED_TABLE_USER(_Name_, _Table_, _Description_, ...) \ DECLARE_SOA_EXTENDED_TABLE_FULL(_Name_, _Table_, "AOD", _Description_, __VA_ARGS__) #define DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, _Origin_, _Description_, _Exclusive_, ...) \ struct _Name_ : o2::soa::IndexTable<_Key_, __VA_ARGS__> { \ _Name_(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : o2::soa::IndexTable<_Key_, __VA_ARGS__>(table, offset){}; \ _Name_(_Name_ const&) = default; \ _Name_(_Name_&&) = default; \ using iterator = typename base_t::template RowView<_Name_, _Name_>; \ using const_iterator = iterator; \ }; \ \ struct _Name_##Metadata : o2::soa::TableMetadata<_Name_##Metadata> { \ using Key = _Key_; \ using index_pack_t = framework::pack<__VA_ARGS__>; \ using originals = decltype(soa::extractBindings(index_pack_t{})); \ using sources = typename _Name_::sources_t; \ static constexpr char const* mLabel = #_Name_; \ static constexpr char const mOrigin[4] = _Origin_; \ static constexpr char const mDescription[16] = _Description_; \ static constexpr bool exclusive = _Exclusive_; \ }; \ \ template <> \ struct MetadataTrait<_Name_> { \ using metadata = _Name_##Metadata; \ }; \ \ template <> \ struct MetadataTrait<_Name_::iterator> { \ using metadata = _Name_##Metadata; \ }; #define DECLARE_SOA_INDEX_TABLE(_Name_, _Key_, _Description_, ...) \ DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, "IDX", _Description_, false, __VA_ARGS__) #define DECLARE_SOA_INDEX_TABLE_EXCLUSIVE(_Name_, _Key_, _Description_, ...) \ DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, "IDX", _Description_, true, __VA_ARGS__) #define DECLARE_SOA_INDEX_TABLE_USER(_Name_, _Key_, _Description_, ...) \ DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, "AOD", _Description_, false, __VA_ARGS__) #define DECLARE_SOA_INDEX_TABLE_EXCLUSIVE_USER(_Name_, _Key_, _Description_, ...) \ DECLARE_SOA_INDEX_TABLE_FULL(_Name_, _Key_, "AOD", _Description_, true, __VA_ARGS__) namespace o2::soa { template <typename... Ts> struct Join : JoinBase<Ts...> { Join(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset = 0); template <typename... ATs> Join(uint64_t offset, std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, ATs... ts); using base = JoinBase<Ts...>; using originals = originals_pack_t<Ts...>; template <typename... TA> void bindExternalIndices(TA*... externals); using table_t = base; using persistent_columns_t = typename table_t::persistent_columns_t; using iterator = typename table_t::template RowView<Join<Ts...>, Ts...>; using const_iterator = iterator; using filtered_iterator = typename table_t::template RowViewFiltered<Join<Ts...>, Ts...>; using filtered_const_iterator = filtered_iterator; }; template <typename... Ts> Join<Ts...>::Join(std::vector<std::shared_ptr<arrow::Table>>&& tables, uint64_t offset) : JoinBase<Ts...>{ArrowHelpers::joinTables(std::move(tables)), offset} { } template <typename... Ts> template <typename... ATs> Join<Ts...>::Join(uint64_t offset, std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, ATs... ts) : Join<Ts...>(std::vector<std::shared_ptr<arrow::Table>>{t1, t2, ts...}, offset) { } template <typename... Ts> template <typename... TA> void Join<Ts...>::bindExternalIndices(TA*... externals) { base::bindExternalIndices(externals...); } template <typename T1, typename T2> struct Concat : ConcatBase<T1, T2> { Concat(std::shared_ptr<arrow::Table> t1, std::shared_ptr<arrow::Table> t2, uint64_t offset = 0) : ConcatBase<T1, T2>{ArrowHelpers::concatTables({t1, t2}), offset} {} Concat(std::vector<std::shared_ptr<arrow::Table>> tables, uint64_t offset = 0) : ConcatBase<T1, T2>{ArrowHelpers::concatTables(std::move(tables)), offset} {} using base = ConcatBase<T1, T2>; using originals = framework::concatenated_pack_t<originals_pack_t<T1>, originals_pack_t<T2>>; template <typename... TA> void bindExternalIndices(TA*... externals) { base::bindExternalIndices(externals...); } // FIXME: can be remove when we do the same treatment we did for Join to Concatenate using left_t = T1; using right_t = T2; using table_t = ConcatBase<T1, T2>; using persistent_columns_t = typename table_t::persistent_columns_t; using iterator = typename table_t::template RowView<Concat<T1, T2>, T1, T2>; using filtered_iterator = typename table_t::template RowViewFiltered<Concat<T1, T2>, T1, T2>; }; template <typename T> using is_soa_join_t = framework::is_specialization<T, soa::Join>; template <typename T> using is_soa_concat_t = framework::is_specialization<T, soa::Concat>; template <typename T> inline constexpr bool is_soa_join_v = is_soa_join_t<T>::value; template <typename T> inline constexpr bool is_soa_concat_v = is_soa_concat_t<T>::value; template <typename T> class FilteredBase : public T { public: using self_t = FilteredBase<T>; using originals = originals_pack_t<T>; using table_t = typename T::table_t; using persistent_columns_t = typename T::persistent_columns_t; using external_index_columns_t = typename T::external_index_columns_t; template <typename P, typename... Os> constexpr static auto make_it(framework::pack<Os...> const&) { return typename table_t::template RowViewFiltered<P, Os...>{}; } using iterator = decltype(make_it<FilteredBase<T>>(originals{})); using const_iterator = iterator; FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0) : T{std::move(tables), offset}, mSelectedRows{getSpan(selection)} { resetRanges(); } FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0) : T{std::move(tables), offset}, mSelectedRowsCache{std::move(selection)}, mCached{true} { resetRanges(); } FilteredBase(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0) : T{std::move(tables), offset}, mSelectedRows{selection} { resetRanges(); } iterator begin() { return iterator(mFilteredBegin); } RowViewSentinel end() { return RowViewSentinel{*mFilteredEnd}; } const_iterator begin() const { return const_iterator(mFilteredBegin); } RowViewSentinel end() const { return RowViewSentinel{*mFilteredEnd}; } iterator iteratorAt(uint64_t i) { return mFilteredBegin + i; } int64_t size() const { return mSelectedRows.size(); } int64_t tableSize() const { return table_t::asArrowTable()->num_rows(); } auto const& getSelectedRows() const { return mSelectedRows; } static inline auto getSpan(gandiva::Selection const& sel) { if (sel == nullptr) { return gsl::span<int64_t const>{}; } auto array = std::static_pointer_cast<arrow::Int64Array>(sel->ToArray()); auto start = array->raw_values(); auto stop = start + array->length(); return gsl::span{start, stop}; } /// Bind the columns which refer to other tables /// to the associated tables. template <typename... TA> void bindExternalIndices(TA*... current) { table_t::bindExternalIndices(current...); mFilteredBegin.bindExternalIndices(current...); } void bindExternalIndicesRaw(std::vector<void const*>&& ptrs) { mFilteredBegin.bindExternalIndicesRaw(std::forward<std::vector<void const*>>(ptrs)); } template <typename T1, typename... Cs> void doCopyIndexBindings(framework::pack<Cs...>, T1& dest) const { dest.bindExternalIndicesRaw(mFilteredBegin.getIndexBindings()); } template <typename T1> void copyIndexBindings(T1& dest) const { doCopyIndexBindings(external_index_columns_t{}, dest); } auto rawSliceBy(framework::expressions::BindingNode const& node, int value) const { return (table_t)this->sliceBy(node, value); } auto sliceByCached(framework::expressions::BindingNode const& node, int value) { uint64_t offset = 0; std::shared_ptr<arrow::Table> result = nullptr; auto status = ((table_t*)this)->getSliceFor(value, node.name.c_str(), result, offset); if (status.ok()) { auto start = offset; auto end = start + result->num_rows(); auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start); auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end); SelectionVector slicedSelection{start_iterator, stop_iterator}; std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(), [&](int64_t idx) { return idx - static_cast<int64_t>(start); }); self_t fresult{{result}, std::move(slicedSelection), start}; copyIndexBindings(fresult); return fresult; } o2::framework::throw_error(o2::framework::runtime_error("Failed to slice table")); O2_BUILTIN_UNREACHABLE(); } auto sliceBy(framework::expressions::BindingNode const& node, int value) const { auto t = o2::soa::sliceBy((table_t)(*this), node, value); auto start = t.offset(); auto end = start + t.size(); auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start); auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end); SelectionVector slicedSelection{start_iterator, stop_iterator}; std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(), [&](int64_t idx) { return idx - static_cast<int64_t>(start); }); self_t result{{t.asArrowTable()}, std::move(slicedSelection), start}; copyIndexBindings(result); return result; } auto select(framework::expressions::Filter const& f) const { auto t = o2::soa::select(*this, f); copyIndexBindings(t); return t; } protected: auto slice(uint64_t start, uint64_t end) { auto start_iterator = std::lower_bound(mSelectedRows.begin(), mSelectedRows.end(), start); auto stop_iterator = std::lower_bound(start_iterator, mSelectedRows.end(), end); SelectionVector slicedSelection{start_iterator, stop_iterator}; std::transform(slicedSelection.begin(), slicedSelection.end(), slicedSelection.begin(), [&](int64_t idx) { return idx - static_cast<int64_t>(start); }); return self_t{{this->asArrowTable()->Slice(start, end - start + 1)}, std::move(slicedSelection), start}; } void sumWithSelection(SelectionVector const& selection) { mCached = true; SelectionVector rowsUnion; std::set_union(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(rowsUnion)); mSelectedRowsCache.clear(); mSelectedRowsCache = rowsUnion; resetRanges(); } void intersectWithSelection(SelectionVector const& selection) { mCached = true; SelectionVector intersection; std::set_intersection(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(intersection)); mSelectedRowsCache.clear(); mSelectedRowsCache = intersection; resetRanges(); } void sumWithSelection(gsl::span<int64_t const> const& selection) { mCached = true; SelectionVector rowsUnion; std::set_union(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(rowsUnion)); mSelectedRowsCache.clear(); mSelectedRowsCache = rowsUnion; resetRanges(); } void intersectWithSelection(gsl::span<int64_t const> const& selection) { mCached = true; SelectionVector intersection; std::set_intersection(mSelectedRows.begin(), mSelectedRows.end(), selection.begin(), selection.end(), std::back_inserter(intersection)); mSelectedRowsCache.clear(); mSelectedRowsCache = intersection; resetRanges(); } private: void resetRanges() { if (mCached) { mSelectedRows = gsl::span{mSelectedRowsCache}; } mFilteredEnd.reset(new RowViewSentinel{mSelectedRows.size()}); if (tableSize() == 0) { mFilteredBegin = *mFilteredEnd; } else { mFilteredBegin = table_t::filtered_begin(mSelectedRows); } } gsl::span<int64_t const> mSelectedRows; SelectionVector mSelectedRowsCache; bool mCached = false; iterator mFilteredBegin; std::shared_ptr<RowViewSentinel> mFilteredEnd; }; template <typename T> class Filtered : public FilteredBase<T> { public: using self_t = Filtered<T>; Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0) : FilteredBase<T>(std::move(tables), selection, offset) {} Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0) : FilteredBase<T>(std::move(tables), std::forward<SelectionVector>(selection), offset) {} Filtered(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0) : FilteredBase<T>(std::move(tables), selection, offset) {} Filtered<T> operator+(SelectionVector const& selection) { Filtered<T> copy(*this); copy.sumWithSelection(selection); return copy; } Filtered<T> operator+(gsl::span<int64_t const> const& selection) { Filtered<T> copy(*this); copy.sumWithSelection(selection); return copy; } Filtered<T> operator+(Filtered<T> const& other) { return operator+(other.getSelectedRows()); } Filtered<T> operator+=(SelectionVector const& selection) { this->sumWithSelection(selection); return *this; } Filtered<T> operator+=(gsl::span<int64_t const> const& selection) { this->sumWithSelection(selection); return *this; } Filtered<T> operator+=(Filtered<T> const& other) { return operator+=(other.getSelectedRows()); } Filtered<T> operator*(SelectionVector const& selection) { Filtered<T> copy(*this); copy.intersectWithSelection(selection); return copy; } Filtered<T> operator*(gsl::span<int64_t const> const& selection) { Filtered<T> copy(*this); copy.intersectWithSelection(selection); return copy; } Filtered<T> operator*(Filtered<T> const& other) { return operator*(other.getSelectedRows()); } Filtered<T> operator*=(SelectionVector const& selection) { this->intersectWithSelection(selection); return *this; } Filtered<T> operator*=(gsl::span<int64_t const> const& selection) { this->intersectWithSelection(selection); return *this; } Filtered<T> operator*=(Filtered<T> const& other) { return operator*=(other.getSelectedRows()); } using FilteredBase<T>::sliceByCached; }; template <typename T> class Filtered<Filtered<T>> : public FilteredBase<typename T::table_t> { public: using self_t = Filtered<Filtered<T>>; using table_t = typename FilteredBase<typename T::table_t>::table_t; Filtered(std::vector<Filtered<T>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0) : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), selection, offset) { for (auto& table : tables) { *this *= table; } } Filtered(std::vector<Filtered<T>>&& tables, SelectionVector&& selection, uint64_t offset = 0) : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), std::forward<SelectionVector>(selection), offset) { for (auto& table : tables) { *this *= table; } } Filtered(std::vector<Filtered<T>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0) : FilteredBase<typename T::table_t>(std::move(extractTablesFromFiltered(std::move(tables))), selection, offset) { for (auto& table : tables) { *this *= table; } } Filtered<Filtered<T>> operator+(SelectionVector const& selection) { Filtered<Filtered<T>> copy(*this); copy.sumWithSelection(selection); return copy; } Filtered<Filtered<T>> operator+(gsl::span<int64_t const> const& selection) { Filtered<Filtered<T>> copy(*this); copy.sumWithSelection(selection); return copy; } Filtered<Filtered<T>> operator+(Filtered<T> const& other) { return operator+(other.getSelectedRows()); } Filtered<Filtered<T>> operator+=(SelectionVector const& selection) { this->sumWithSelection(selection); return *this; } Filtered<Filtered<T>> operator+=(gsl::span<int64_t const> const& selection) { this->sumWithSelection(selection); return *this; } Filtered<Filtered<T>> operator+=(Filtered<T> const& other) { return operator+=(other.getSelectedRows()); } Filtered<Filtered<T>> operator*(SelectionVector const& selection) { Filtered<Filtered<T>> copy(*this); copy.intersectionWithSelection(selection); return copy; } Filtered<Filtered<T>> operator*(gsl::span<int64_t const> const& selection) { Filtered<Filtered<T>> copy(*this); copy.intersectionWithSelection(selection); return copy; } Filtered<Filtered<T>> operator*(Filtered<T> const& other) { return operator*(other.getSelectedRows()); } Filtered<Filtered<T>> operator*=(SelectionVector const& selection) { this->intersectWithSelection(selection); return *this; } Filtered<Filtered<T>> operator*=(gsl::span<int64_t const> const& selection) { this->intersectWithSelection(selection); return *this; } Filtered<Filtered<T>> operator*=(Filtered<T> const& other) { return operator*=(other.getSelectedRows()); } using FilteredBase<typename T::table_t>::sliceByCached; private: std::vector<std::shared_ptr<arrow::Table>> extractTablesFromFiltered(std::vector<Filtered<T>>&& tables) { std::vector<std::shared_ptr<arrow::Table>> outTables; for (auto& table : tables) { outTables.push_back(table.asArrowTable()); } return outTables; } }; template <typename T> using is_soa_filtered_t = typename framework::is_base_of_template<soa::FilteredBase, T>; /// Template for building an index table to access matching rows from non- /// joinable, but compatible tables, e.g. Collisions and ZDCs. /// First argument is the key table (BCs for the Collisions+ZDCs case), the rest /// are index columns defined for the required tables. /// First index will be used by process() as the grouping template <typename Key, typename H, typename... Ts> struct IndexTable : Table<soa::Index<>, H, Ts...> { using base_t = Table<soa::Index<>, H, Ts...>; using table_t = base_t; using safe_base_t = Table<H, Ts...>; using indexing_t = Key; using first_t = typename H::binding_t; using rest_t = framework::pack<typename Ts::binding_t...>; using sources_t = originals_pack_t<Key, first_t, typename Ts::binding_t...>; IndexTable(std::shared_ptr<arrow::Table> table, uint64_t offset = 0) : base_t{table, offset} { } IndexTable(IndexTable const&) = default; IndexTable(IndexTable&&) = default; IndexTable& operator=(IndexTable const&) = default; IndexTable& operator=(IndexTable&&) = default; using iterator = typename base_t::template RowView<IndexTable<Key, H, Ts...>, IndexTable<Key, H, Ts...>>; using const_iterator = iterator; }; template <typename T> using is_soa_index_table_t = typename framework::is_base_of_template<soa::IndexTable, T>; template <typename T> struct SmallGroups : Filtered<T> { SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, gandiva::Selection const& selection, uint64_t offset = 0) : Filtered<T>(std::move(tables), selection, offset) {} SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, SelectionVector&& selection, uint64_t offset = 0) : Filtered<T>(std::move(tables), std::forward<SelectionVector>(selection), offset) {} SmallGroups(std::vector<std::shared_ptr<arrow::Table>>&& tables, gsl::span<int64_t const> const& selection, uint64_t offset = 0) : Filtered<T>(std::move(tables), selection, offset) {} }; } // namespace o2::soa #endif // O2_FRAMEWORK_ASOA_H_
{ "alphanum_fraction": 0.4467785598, "avg_line_length": 48.0274888559, "ext": "h", "hexsha": "ea9fcb770618259d2c5fd002d04f1f33beffbd8f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-23T15:15:53.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-23T15:15:53.000Z", "max_forks_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "adriansev/AO2Dproto", "max_forks_repo_path": "o2data_model/ASoA.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "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": "adriansev/AO2Dproto", "max_issues_repo_path": "o2data_model/ASoA.h", "max_line_length": 179, "max_stars_count": null, "max_stars_repo_head_hexsha": "bf4f9009c2e16560ecfda9e4907321163281b7de", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "adriansev/AO2Dproto", "max_stars_repo_path": "o2data_model/ASoA.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 23736, "size": 129290 }
// MIT License Copyright (c) 2020 Jarrett Wendt #pragma once #include "Macros.h" #include "Memory.h" #include "Util.h" #include <algorithm> // std::min/max #include <compare> // std::strong_ordering #include <functional> #include <initializer_list> // std::initializer/list #include <iterator> // std::random_access_iterator #include <gsl/gsl> // gsl::owner // Some macros to save on typing. // These get #undef-ed at the end of the .inl file. // Also pretty convenient in case I ever decide I want to change/rename the template args. // The only downside is that intellisense thinks my methods are unimplemented. #define TEMPLATE template<typename T, Concept::ReserveStrategy ReserveStrategy> #define ARRAY Array<T, ReserveStrategy> namespace Library { // TODO: Array<bool> can be specialized as a bit-array to save memory. /** * A contiguous-memory dynamically resizing array. * Internally uses std::vector and provides more convenience methods to it. * Name chosen to disambiguate between vector the data container and vector the mathematical concept. * * @param <T> The type for this container to store. * @param <ReserveStrategy> A callable type for determining a new capacity given the current memory usage. */ template<typename T, Concept::ReserveStrategy ReserveStrategy = Util::DefaultReserveStrategy> class Array final { public: using value_type = T; using reference = T&; using const_reference = const T&; using pointer = T*; using const_pointer = const T*; using size_type = size_t; using difference_type = ptrdiff_t; using reserve_strategy = ReserveStrategy; private: using internal_size_type = uint32_t; T* array{ nullptr }; internal_size_type size{ 0 }; internal_size_type capacity{ 0 }; public: #pragma region Special Members /** * default ctor * creates an empty container owning no memory */ Array() = default; /** * explicit ctor * * @param capacity how many elements worth of space to reserve */ explicit Array(size_type capacity); /** * explicit ctor * * @param count how many elements of space to reserve and construct * @param prototype prototypical value to be copy-constructed into each element */ Array(size_type count, const T& prototype); /** * explicit ctor * Fills the container with values read through the iterators. * * @param <It> the iterator type * @param first the beginning iterator, inclusive * @param last the last iterator, exclusive */ template<std::forward_iterator It> Array(It first, It last); /** * explicit ctor * Fills the container with values read through the iterators. * * @param <It> the iterator type * @param first the beginning iterator, inclusive * @param last the last iterator, exclusive */ template<std::random_access_iterator It> Array(It first, It last); /** * typecast ctor which accepts any range * will at most resize once * * @param range the range to construct from */ template<Concept::RangeOf<T> Range> Array(const Range& range); /** * typecast ctor which accepts any range * will at most resize once * * @param range the range to construct from */ template<Concept::RangeOf<T> Range> Array& operator=(const Range& range); /** * initializer_list ctor * * @param list the initializer_list to construct this container from */ Array(std::initializer_list<T> list); /** * initializer_list operator= * * @param list the initializer_list to assign this container to * @return this container after assignment */ Array& operator=(std::initializer_list<T> list); /** * copy ctor * * @param other the container to copy */ Array(const Array& other); /** * move ctor * * @param other the container to move, will be made empty after this operation */ Array(Array&& other) noexcept; /** * copy operator= * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ Array& operator=(const Array& other); /** * move operator= * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ Array& operator=(Array&& other) noexcept; /** * templated copy ctor accepting containers with other ReserveStrategies * this container will keep its original reserve strategy * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ template<Concept::ReserveStrategy OtherReserveStrategy> Array(const Array<T, OtherReserveStrategy>& other); /** * templated move ctor accepting containers with other ReserveStrategies * this container will keep its original reserve strategy * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ template<Concept::ReserveStrategy OtherReserveStrategy> Array(Array<T, OtherReserveStrategy>&& other) noexcept; /** * templated copy operator= accepting containers with other ReserveStrategies * this container will keep its original reserve strategy * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ template<Concept::ReserveStrategy OtherReserveStrategy> Array& operator=(const Array<T, OtherReserveStrategy>& other); /** * templated move operator= accepting containers with other ReserveStrategies * this container will keep its original reserve strategy * * @param other the container to move, will be made empty after this operation * @returns this container after assignment */ template<Concept::ReserveStrategy OtherReserveStrategy> Array& operator=(Array<T, OtherReserveStrategy>&& other) noexcept; /** * dtor * frees all associated memory */ ~Array(); #pragma endregion #pragma region iterator class iterator final { friend class Array; friend class const_iterator; private: T* data{ nullptr }; #ifdef _DEBUG Array* owner{ nullptr }; #endif public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; private: iterator(T* data, [[maybe_unused]] Array* owner) noexcept : data(data) #ifdef _DEBUG ,owner(owner) #endif {} public: /** * explicit constructor * * @param index index for this iterator to start at * @param owner the container this iterator references */ iterator(const size_type index, Array& owner) noexcept : iterator(owner.array + index, &owner) {} SPECIAL_MEMBERS(iterator, default) /** * Difference of two iterators. * * @param left lhs of the operator * @param right rhs of the operator * @returns The difference between the indices of the two iterators. * * @asserts The iterators are initialized and they belong to the same container. */ [[nodiscard]] friend difference_type operator-(const iterator left, const iterator right) noexcept { // No need to AssertInitialize anything because it will be called by operator += // AssertInitialize is therefore implicitly called on right since we're comparing it to left's owner assertm(left.owner == right.owner, "iterators must belong to the same container"); return left.data - right.data; } /** * Will not go beyond end(). * * @param i How much to increment the iterator by. * @returns A new iterator at that index. * * @asserts this iterator is initialized */ [[nodiscard]] iterator operator+(difference_type i) const noexcept; /** * @returns The value of the index the iterator is at. * * @asserts this iterator is initialized and not at end(). */ [[nodiscard]] reference operator*() const; RANDOM_ITER_OPS(iterator) private: /** * @asserts this iterator is initialized. */ constexpr void AssertInitialized() const noexcept; }; class const_iterator final { friend class Array; CONST_RANDOM_ACCESS_ITERATOR(const_iterator, iterator) /** * explicit constructor * * @param index index for this iterator to start at * @param owner the container this iterator references */ const_iterator(const size_t index, const Array& owner) noexcept : it{ index, const_cast<Array&>(owner) } {}; }; BEGIN_END(iterator, const_iterator, Array) MAKE_REVERSE_BEGIN_END #pragma endregion #pragma region Properties /** * @returns true if the container is empty, false otherwise */ [[nodiscard]] constexpr bool IsEmpty() const noexcept; /** * @returns true if the container is full, false otherwise */ [[nodiscard]] constexpr bool IsFull() const noexcept; /** * @returns How many elements are in the container. */ [[nodiscard]] constexpr size_type Size() const noexcept; /** * @returns The number of elements this container can hold without resizing. */ [[nodiscard]] constexpr size_type Capacity() const noexcept; /** * @param it an iterator * @returns the index represented by the iterator */ [[nodiscard]] constexpr size_type IndexOf(const_iterator it) const noexcept; #pragma endregion #pragma region Element Access /** * Returns a reference to the given index with bounds checking. * * @param index position of the element to return * @returns reference to the requested element * * @throws std::out_of_range if index >= Size() */ [[nodiscard]] T& At(size_type index); /** * Returns a reference to the given index with bounds checking. * * @param index position of the element to return * @returns reference to the requested element * * @throws std::out_of_range if index >= Size() */ [[nodiscard]] const T& At(size_type index) const; /** * Returns a reference to the given index with bounds checking. * * @param index position of the element to return * @returns reference to the requested element * * @throws std::out_of_range if index >= Size() */ [[nodiscard]] T& operator[](size_type index); /** * Returns a reference to the given index with bounds checking. * * @param index position of the element to return * @returns reference to the requested element * * @throws std::out_of_range if index >= Size() */ [[nodiscard]] const T& operator[](size_type index) const; /** * @returns reference to the first element. * * @throws std::out_of_range if the container is empty */ [[nodiscard]] T& Front(); /** * @returns reference to the first element. * * @throws std::out_of_range if the container is empty */ [[nodiscard]] const T& Front() const; /** * @returns reference to the last element. * * @throws std::out_of_range if the container is empty */ [[nodiscard]] T& Back(); /** * @returns reference to the last element. * * @throws std::out_of_range if the container is empty */ [[nodiscard]] const T& Back() const; #pragma endregion #pragma region Insert /** * @param index where the new element will be constructed * @param t value to insert */ void Insert(size_t index, const T& t); /** * @param index where the new element will be constructed * @param t value to insert */ void Insert(size_t index, T&& t); /** * @param index where the new element will be constructed * @param count how many copies of the value to insert * @param t value to insert * @returns iterator at the position of the last element inserted */ iterator Insert(size_t index, size_t count, const T& t); /** * @param index where the new element will be constructed * @param list initializer_list of values to insert * @returns iterator at the position of the last element inserted */ iterator Insert(size_t index, std::initializer_list<T> list); /** * Insert elements through the values read from the iterators in the range [first, last). * * @param index where the first new element will be constructed * @param first beginning iterator, inclusive * @param last ending iterator, exclusive * @returns iterator at the position of the last element inserted * * @throws std::invalid_argument if the iterators belong to this container */ template<std::forward_iterator It> iterator Insert(size_t index, It first, It last); /** * @param it position of where to insert * @param t prototypical value to insert * * @throws std::invalid_argument if the iterator does not belong to this container */ void Insert(const_iterator it, const T& t); /** * @param it position of where to insert * @param t prototypical value to insert * * @throws std::invalid_argument if the iterator does not belong to this container */ void Insert(const_iterator it, T&& t); /** * @param it initial position of where to insert * @param count how many copies of the prototype to insert * @param t prototypical value to insert * @returns iterator at the last element inserted * * @throws std::invalid_argument if the iterator does not belong to this container */ iterator Insert(const_iterator it, size_t count, const T& t); /** * @param it initial position of where to insert * @param list initializer_list of values to insert * @returns iterator at the last element inserted * * @throws std::invalid_argument if the iterator does not belong to this container */ iterator Insert(const_iterator it, std::initializer_list<T> list); /** * Insert elements through the values read from the iterators in the range [first, last). * * @param it initial position of where to insert * @param first beginning iterator, inclusive * @param last ending iterator, exclusive * @returns iterator at the position of the last element inserted * * @throws std::invalid_argument if the iterators do not belong to this container */ template<std::forward_iterator It> iterator Insert(const_iterator it, It first, It last); /** * Inserts a new element into the container directly at index. * * @param index Position in the container to put this element. * @param args Arguments to forward to the constructor of the element. * * @throws std::out_of_range if index > Size(). */ template<typename... Args> reference Emplace(size_t index, Args&&... args); /** * Inserts a new element into the container directly at index. * The passed iterator is guaranteed to be valid and pointing at the position of the newly emplaced element after the operation. * * @param it Position in the container to put this element. * @param args Arguments to forward to the constructor of the element. * * @throws std::out_of_range if index > Size(). */ template<typename... Args> reference Emplace(const_iterator it, Args&&... args); /** * Appends a new element to the end of the container. * O(1) most cases. * O(n) if the operation requires a Resize(). * * @param args Arguments to forward to the constructor of the element. */ template<typename... Args> reference EmplaceBack(Args&&... args); /** * Appends a new element to the front of the container. * O(1) most cases. * O(n) if the operation requires a Resize(). * * @param args Arguments to forward to the constructor of the element. */ template<typename... Args> reference EmplaceFront(Args&&... args); /** * Appends the element to the end of the container. * O(1) most cases. * O(n) if the operation requires a Resize(). * * @param t The value of the element to append. */ void PushBack(const T& t); /** * Appends the element to the end of the container. * O(n) where n is Size(). * * @param t The value of the element to append. */ void PushBack(T&& t); /** * Appends the element to the front of the container. * O(n) where n is Size(). * * @param t The value of the element to prepend. */ void PushFront(const T& t); /** * Appends the element to the front of the container. * O(n) where n is Size(). * * @param t The value of the element to prepend. */ void PushFront(T&& t); /** * Insert elements through the values read from the iterators in the range [first, last). * Only resizes once (this is most efficient if It is a random access iterator). * * @param it initial position of where to insert * @param first beginning iterator, inclusive * @param last ending iterator, exclusive * @returns iterator at the position of the last element inserted */ template<std::forward_iterator It> void PushBack(It first, It last); /** * Insert elements through the values read from the iterators in the range [first, last). * Only resizes once (this is most efficient if It is a random access iterator). * * @param it initial position of where to insert * @param first beginning iterator, inclusive * @param last ending iterator, exclusive * @returns iterator at the position of the last element inserted */ template<std::forward_iterator It> void PushFront(It first, It last); /** * Copies the passed prototypical value into the remaining empty slots. * O(n) where n is Capacity() - Size(). * * @param prototype The prottype to fill the container with. */ void Fill(const T& prototype); #pragma endregion #pragma region Remove /** * Removes the first instance of the passed value from the container. * Will only return false if the value did not exist in the container. * A return value of true does not imply that no duplicate values do not still exist in the container. * All elements after the removed one get shifted to the left in memory. * O(n) * * @param t The value to remove. * @returns Whether or not a removal operation was performed. */ bool Remove(const T& t); /** * Removes the first element matching the passed predicate. * Will only return false if the value did not exist in the container. * A return value of true does not imply that no duplicate values do not still exist in the container. * All elements after the removed one get shifted to the left in memory. * O(n) * * @param predicate The predicate to query with. * @returns Whether or not a removal was performed. */ template<std::predicate<T> Predicate> bool Remove(Predicate predicate); /** * Removes the index specified and shift values to the left over. * O(n) where n is Size() - index; * * @param index The index to remove. */ void RemoveAt(size_t index); /** * Removes all elements matching the specified value. * O(n) * * @param t The value to remove all instances of. * @returns How many removals were performed. */ size_t RemoveAll(const T& t); /** * Removes all elements matching the passed predicate. * O(n) * * @param predicate The predicate to query with. * @returns How many elements were removed. */ template<std::predicate<T> Predicate> size_t RemoveAll(Predicate predicate); template<std::predicate<T> Predicate> friend size_t erase_if(Array& arr, const Predicate predicate) { return arr.RemoveAll(predicate); } /** * Removes the range [first, last) elements between the two passed indices. * If last is beyond Size() then all elements from first to the end will be removed safely. * Does nothing if the indices are both beyond Size(). * * @param first index of the first value to remove, inclusive. * @param last index of the last value to remove, exclusive. * @returns The number of elements removed, equal to first - last unless last > Size(). * * @throws std::invalid_argument if first > last. */ size_t Remove(size_t first, size_t last); /** * Removes the range [first, last) elements between the two passed iterators. * O(n) where n = Size() - first * * @param first iterator at the first element to remove, inclusive * @param last iterator at the last element to remove, exclusive * @returns The number of elements removed. */ size_t Remove(const_iterator first, const_iterator last); /** * O(1) * Removes the last element of the container. * Does nothing if the container is empty. */ void PopBack(); /** * O(n) where n = Size() - 1 before the operation. * Removes the first element of the container. * Does nothing if the container is empty. */ void PopFront(); /** * Erases all elements from the container by calling the destructors on each of them. * Afterwards Size() == 0. */ void Clear() noexcept; /** * Erases all memory held by this container. */ void Empty() noexcept; #pragma endregion #pragma region Query /** * Does an O(n) search for the first occurrence of the passed element. * * @param t the element to query for. * @returns the index of the first element found, or Size() if it was not found. */ size_type IndexOf(const T& t) const; /** * Does an O(n) search for the first element matching the passed predicate. * * @param predicate the predicate to query with. * @returns the index of the first element found, or Size() if it was not found. */ template<std::predicate<T> Predicate> size_type IndexOf(Predicate predicate) const; #pragma endregion #pragma region Memory /** * Warning! Use at your own risk! Manipulating this memory can invalidate the state of the Array. * * @returns pointer to the underlying data. nullptr if the container is empty. */ [[nodiscard]] T* Data() noexcept; /** * Warning! Use at your own risk! Manipulating this memory can invalidate the state of the Array. * * @returns pointer to the underlying data. nullptr if the container is empty. */ [[nodiscard]] const T* Data() const noexcept; /** * Gets the underlying data and empties this container without deallocating any memory. * Guaranteed to cause a memory leak if the caller discards this return value. * Caller assumes all responsibility for managing this data. * * @returns pointer, size, capacity */ [[nodiscard]] std::tuple<gsl::owner<T*>, size_t, size_t> TakeData() noexcept; /** * Force this container to take on the given memory. * Will free all currently associated memory and destruct all objects. * The container will manage the given data as if it had allocated it itself, * possibly reallocating it in the event of an operation that would do such a thing. * * @param data pointer, size, capacity */ void SetData(std::tuple<T*, size_t, size_t> data) noexcept; /** * Force this container to take on the given memory. * Will free all currently associated memory and destruct all objects. * The container will manage the given data as if it had allocated it itself, * possibly reallocating it in the event of an operation that would do such a thing. * * @param array pointer to array of T * @param size how many elements array contains * @param capacity how many elements array can store */ void SetData(T* array, size_t size, size_t capacity) noexcept; /** * O(n) where n is the current size of the container. * Does nothing if newCapacity <= Capacity(). * * @param newCapacity The new capacity for the container. * * @throws std::length_error if newCapacity > MaxSize() * @throws std::bad_alloc if memory allocation fails. */ void Reserve(size_t newCapacity); /** * O(n) where n = newSize - Size(), or n = newSize if the operation requires a Reserve(). * If the current Size() is greater than newSize, the container is reduced to its first newSize elements. * * @param newSize The new size for the container. * @param prototype The value to initialize each new element with. */ void Resize(size_t newSize, const T& prototype = T()); /** * Reduces memory usage such that Size() == Capacity(). * O(n) where n = Size(). * Does nothing if IsFull() */ void ShrinkToFit(); /** * Reduces memory usage such that Capacity() == std::max(count, Size()). * O(n) where n = Size(). * Does nothing if Capacity() already == std::max(count, Size()). */ void ShrinkToFit(size_t count); /** * TODO: It might be that the STL expects swap to be lowercase and a non-member function (so a friend function will do). * O(1) * * @param <OtherReserveStrategy> template parameter allowing swapping Arrays with different ReserveStrategies. * @param other container to exchange contents with. */ template<Concept::ReserveStrategy OtherReserveStrategy> void Swap(Array<T, OtherReserveStrategy>& other) noexcept; /** * Reverses the order of the elements in the container. * O(n) */ void Reverse() noexcept; #pragma endregion #pragma region Operators /** * templated operator== to allow for comparing containers with different reserve strategies * * @param <OtherReserveStrategy> reserve strategy for the other container * @param left lhs container * @param right rhs container * @returns whether or not the two containers are equal. */ template<Concept::ReserveStrategy OtherReserveStrategy> [[nodiscard]] friend bool operator==(const Array& left, const Array<T, OtherReserveStrategy>& right) { return &left == reinterpret_cast<const Array*>(&right) || left.Size() == right.Size() && std::equal(left.begin(), left.end(), right.begin(), right.end()); } /** * templated operator== to allow for comparing containers with different reserve strategies * * @param <OtherReserveStrategy> reserve strategy for the other container * @param left lhs container * @param right rhs container * @returns whether or not the two containers are equal. */ template<Concept::ReserveStrategy OtherReserveStrategy> [[nodiscard]] friend bool operator!=(const Array& left, const Array<T, OtherReserveStrategy>& right) { return !operator==(left, right); } friend std::ostream& operator<<(std::ostream& stream, const ARRAY& array) noexcept { Util::StreamTo(stream, array.begin(), array.end()); return stream; } #pragma endregion #pragma region Helpers private: /** * assumes Capacity() is sufficient * * @param first the beginning iterator to read from (inclusive) * @param last the ending iterator to read from (exclusive) */ template<std::forward_iterator It> void PushBackNoResize(It first, It last); /** * Helper for methods that accept iterators. * * @param it The iterator who's owner to compare against this. * * @asserts owner == this */ void AssertOwner(iterator it) const; /** * @param it The iterator who's owner to compare against this. * * @asserts owner == this */ void AssertOwner(const_iterator it) const; /** * Calls the ReserveStrategy template argument and sanity checks its return value. * @returns A safe new Capacity() for this container. */ [[nodiscard]] size_type InvokeReserveStrategy() const noexcept; /** * Calls destructor on all elements. */ void DestructAll() noexcept; /** * Calls the destructor on all elements in range [first, last). * * @param first Index of first element to be deconstructed, inclusive. * @param last Index of last element to be decondstructed, exclusive. */ void DestructAll(const size_type first, const size_type last) noexcept; /** * Shifts the internal array to the right starting at the passed index. * Moves memory as if calling the destructor on elements before they're overwritten and after they're moved. * * @param startIndex The index to start the shifts at. * @param shiftAmount How much to shift by. */ void ShiftRight(size_type startIndex = 0, size_type shiftAmount = 1) noexcept; /** * Shifts the internal array to the left starting at the passed index. * Moves memory as if calling the destructor on elements before they're overwritten and after they're moved. * * @param startIndex The index to start the shifts at. * @param shiftAmount How much to shift by. */ void ShiftLeft(size_type startIndex = 0, size_type shiftAmount = 1) noexcept; /** * Helper called from constructors. * Assumes size is 0 and capacity is sufficient. * * @param list list to copy elements from. */ void Copy(std::initializer_list<T> list); /** * Helper called from constructors. * Assumes size is 0 and capacity is sufficient. * * @param list list to copy elements from. */ template<typename OtherReserveStrategy> void Copy(const Array<T, OtherReserveStrategy>& other); /** * Helper called from copy assignment operators. * * @param other The array being copied. * @returns this after the copy. */ template<typename OtherReserveStrategy> [[nodiscard]] Array& CopyAssign(const Array<T, OtherReserveStrategy>& other); /** * Helper called from move assignment operators. * * @param other The array being moved. * @returns this after the move. */ template<typename OtherReserveStrategy> [[nodiscard]] Array& MoveAssign(Array<T, OtherReserveStrategy>&& other); /** * Helper called from constructors. * Sets this Array's state after std::move. */ void SetPostMoveState(); #pragma endregion }; } #include "Array.inl"
{ "alphanum_fraction": 0.6806198967, "avg_line_length": 30.6486210419, "ext": "h", "hexsha": "5522575a94c00d99d14483f7b7578740f6251769", "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": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JarrettWendt/FIEAEngine", "max_forks_repo_path": "source/Library/containers/Array.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "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": "JarrettWendt/FIEAEngine", "max_issues_repo_path": "source/Library/containers/Array.h", "max_line_length": 157, "max_stars_count": 2, "max_stars_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JarrettWendt/FIEAEngine", "max_stars_repo_path": "source/Library/containers/Array.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:11:58.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-27T14:01:39.000Z", "num_tokens": 7422, "size": 30005 }
/* multifit/fsolver.c * * 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. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit_nlin.h> gsl_multifit_fsolver * gsl_multifit_fsolver_alloc (const gsl_multifit_fsolver_type * T, size_t n, size_t p) { int status; gsl_multifit_fsolver * s; if (n < p) { GSL_ERROR_VAL ("insufficient data points, n < p", GSL_EINVAL, 0); } s = (gsl_multifit_fsolver *) malloc (sizeof (gsl_multifit_fsolver)); if (s == 0) { GSL_ERROR_VAL ("failed to allocate space for multifit solver struct", GSL_ENOMEM, 0); } s->x = gsl_vector_calloc (p); if (s->x == 0) { free (s); GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0); } s->f = gsl_vector_calloc (n); if (s->f == 0) { gsl_vector_free (s->x); free (s); GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0); } s->dx = gsl_vector_calloc (p); if (s->dx == 0) { gsl_vector_free (s->x); gsl_vector_free (s->f); free (s); GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0); } s->state = malloc (T->size); if (s->state == 0) { gsl_vector_free (s->dx); gsl_vector_free (s->x); gsl_vector_free (s->f); free (s); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for multifit solver state", GSL_ENOMEM, 0); } s->type = T ; status = (s->type->alloc)(s->state, n, p); if (status != GSL_SUCCESS) { (s->type->free)(s->state); free (s->state); gsl_vector_free (s->dx); gsl_vector_free (s->x); gsl_vector_free (s->f); free (s); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to set solver", status, 0); } s->function = NULL; return s; } int gsl_multifit_fsolver_set (gsl_multifit_fsolver * s, gsl_multifit_function * f, const gsl_vector * x) { if (s->f->size != f->n) { GSL_ERROR ("function size does not match solver", GSL_EBADLEN); } if (s->x->size != x->size) { GSL_ERROR ("vector length does not match solver", GSL_EBADLEN); } s->function = f; gsl_vector_memcpy(s->x,x); return (s->type->set) (s->state, s->function, s->x, s->f, s->dx); } int gsl_multifit_fsolver_iterate (gsl_multifit_fsolver * s) { return (s->type->iterate) (s->state, s->function, s->x, s->f, s->dx); } void gsl_multifit_fsolver_free (gsl_multifit_fsolver * s) { RETURN_IF_NULL (s); (s->type->free) (s->state); free (s->state); gsl_vector_free (s->dx); gsl_vector_free (s->x); gsl_vector_free (s->f); free (s); } const char * gsl_multifit_fsolver_name (const gsl_multifit_fsolver * s) { return s->type->name; } gsl_vector * gsl_multifit_fsolver_position (const gsl_multifit_fsolver * s) { return s->x; }
{ "alphanum_fraction": 0.6145018258, "avg_line_length": 24.2658227848, "ext": "c", "hexsha": "aab59c2f22466fe46ebe53bf1fa27379499ba2cf", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/fsolver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/fsolver.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/multifit/fsolver.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 1142, "size": 3834 }
/* movstat/sumacc.c * * Moving window sum accumulator * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_movstat.h> typedef double ringbuf_type_t; #include "ringbuf.c" typedef struct { double sum; /* current window sum */ ringbuf *rbuf; /* ring buffer storing current window */ } sumacc_state_t; static size_t sumacc_size(const size_t n) { size_t size = 0; size += sizeof(sumacc_state_t); size += ringbuf_size(n); return size; } static int sumacc_init(const size_t n, void * vstate) { sumacc_state_t * state = (sumacc_state_t *) vstate; state->sum = 0.0; state->rbuf = (ringbuf *) ((unsigned char *) vstate + sizeof(sumacc_state_t)); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int sumacc_insert(const double x, void * vstate) { sumacc_state_t * state = (sumacc_state_t *) vstate; if (ringbuf_is_full(state->rbuf)) { /* subtract oldest element from sum */ state->sum -= ringbuf_peek_back(state->rbuf); } /* add new element to sum and ring buffer */ state->sum += x; ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int sumacc_delete(void * vstate) { sumacc_state_t * state = (sumacc_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) { state->sum -= ringbuf_peek_back(state->rbuf); ringbuf_pop_back(state->rbuf); } return GSL_SUCCESS; } static int sumacc_get(void * params, double * result, const void * vstate) { const sumacc_state_t * state = (const sumacc_state_t *) vstate; (void) params; *result = state->sum; return GSL_SUCCESS; } static const gsl_movstat_accum sum_accum_type = { sumacc_size, sumacc_init, sumacc_insert, sumacc_delete, sumacc_get }; const gsl_movstat_accum *gsl_movstat_accum_sum = &sum_accum_type;
{ "alphanum_fraction": 0.7071865443, "avg_line_length": 23.1504424779, "ext": "c", "hexsha": "dbd9c71c21f26bab1c9966c7fec516e8a91edecf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/sumacc.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/movstat/sumacc.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/movstat/sumacc.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": 711, "size": 2616 }
static const char help[] = "Solves time-dependent nonlinear ice sheet problem in 2D:\n" "(*) H_t + div q = m\n" "where q = (q^x,q^y) is the nonsliding shallow ice approximation (SIA) flux,\n" " q = - Gamma H^{n+2} |grad s|^{n-1} grad s\n" "always subject to the constraint\n" " H(t,x,y) >= 0.\n" "In these equations H(t,x,y) is ice thickness, b(x,y) is bed elevation,\n" "s(t,x,y) = H(t,x,y) + b(x,y) is surface elevation, and m(x,y) is the\n" "climatic mass balance. Constants are n > 1 and Gamma = 2 A (rho g)^n / (n+2).\n" "The domain is square, Omega = [0,L] x [0,L], with periodic boundary conditions.\n" "Equation (*) is semi-discretized in space by a Q1 structured-grid FVE method\n" "(Bueler, 2016). The resulting method-of-lines ODE in time is in the form\n" " F(t,H,H_t) = G(t,H)\n" "For this ODE we define three callbacks:\n" " FormIFunction() evaluates F(H,H_t) = H_t + div q\n" " FormRHSFunction() evaluates G(t,H) = m\n" " FormIJacobian() evaluates (shift) dF/dH_t + dF/dH.\n" "Options -snes_fd_color works well but is slower than the default Jacobian\n" "by a factor of two or so. Requires SNESVI types (i.e.\n" "-snes_type vinewton{rsls|ssls}) because of constraint. With current PETSc\n" "design, explicit TS types do not work.\n\n"; /* try: ./ice -da_refine 3 # only meaningful at this res and higher ./ice -snes_atol 1.0e-14 # CRITICAL; some lower bound on SNES norm is # critical to allowing convergence near steady state ./ice # DEFAULT uses analytical jacobian ./ice -snes_fd_color ./ice -snes_type vinewtonrsls # DEFAULT ./ice -snes_type vinewtonssls # slightly more robust? (other -snes_types like newtonls not allowed because don't support bounds) ./ice -ts_type arkimex # DEFAULT ./ice -ts_type beuler # robust ./ice -ts_type cn # mis-behaves on long time steps ./ice -ts_type cn -ts_theta_adapt # good ./ice -ts_type theta -ts_theta_adapt # good ./ice -ts_type bdf -ts_bdf_adapt -ts_bdf_order 2|3|4|5|6 # good # time-stepping control options -ts_adapt_type basic # DEFAULT -ts_adapt_basic_clip 0.5,1.2 # DEFAULT and recommended; doesn't lengthen too much, but allows significantly shorter, in response to estimate of local truncation error (vs default: 0.1,10.0) -ts_max_snes_failures -1 # recommended: do retry solve -ts_adapt_scale_solve_failed 0.9 # recommended: try a slightly-easier problem -ts_max_reject 50 # recommended?: keep trying if lte is too big ./ice -ice_dtlimits # info on comparison to explicit ./ice -ts_adapt_monitor # info on adapt # PC possibilities -ksp_type gmres # DEFAULT -pc_type ilu # DEFAULT -pc_type gamg -pc_gamg_threshold 0.0 -pc_gamg_agg_nsmooths 1 # these are GAMG defaults -pc_type gamg -pc_gamg_threshold 0.2 -pc_gamg_agg_nsmooths 1 # a little faster? -pc_type lu -pc_type asm -sub_pc_type lu -pc_type asm -sub_pc_type ilu -pc_type mg -pc_type mg -pc_mg_levels 4 -mg_levels_ksp_monitor # shows nontriviality converging ice caps on mountains: mpiexec -n 2 ./ice -da_refine 5 -ts_monitor_solution draw -snes_converged_reason -ice_tf 10000.0 -ice_dtinit 100.0 -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9 # start with short time step and it will find good time scale ./ice -snes_converged_reason -da_refine 4 -ice_dtinit 0.1 # recovery from convergence failures works! (failure here triggered by n=4): ./ice -da_refine 3 -ice_n 4 -ts_max_snes_failures -1 -snes_converged_reason verif with dome=1, halfar=2: for TEST in 1 2; do for N in 2 3 4 5 6; do mpiexec -n 2 ./ice -ice_monitor 0 -ice_verif $TEST -ice_eps 0.0 -ice_dtinit 50.0 -ice_tf 2000.0 -da_refine $N -ts_type beuler done done actual test B from Bueler et al 2005: ./ice -ice_verif 2 -ice_eps 0 -ice_dtinit 100 -ice_tf 25000 -ice_L 2200e3 -da_refine $N recommended "new PISM": mpiexec -n N ./ice -da_refine M \ -snes_type vinewtonrsls \ -ts_type arkimex \ #(OR -ts_type bdf -ts_bdf_adapt -ts_bdf_order 4) -ts_adapt_type basic -ts_adapt_basic_clip 0.5,1.2 \ -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9 \ -pc_type gamg run to generate final-time result in file ice_192_50000.dat: mpiexec -n 4 ./ice -da_refine 6 -pc_type mg -pc_mg_levels 4 -ice_dtlimits -ice_tf 50000 -ice_dtinit 1.0 -ts_max_snes_failures -1 -ts_adapt_scale_solve_failed 0.9 -ice_dump */ #include <petsc.h> #include "icecmb.h" // context is entirely grid-independent info typedef struct { double secpera,// number of seconds in a year L, // spatial domain is [0,L] x [0,L] tf, // final time; time domain is [0,tf] dtinit, // user-requested initial time step dtmax, // set TS maximum time step g, // acceleration of gravity rho_ice,// ice density n_ice, // Glen exponent for SIA flux term A_ice, // ice softness Gamma, // coefficient for SIA flux term D0, // representative value of diffusivity (used in regularizing D) eps, // regularization parameter for D delta, // dimensionless regularization for slope in SIA formulas lambda, // amount of upwinding; lambda=0 is none and lambda=1 is "full" locmaxD,// maximum of diffusivity from last residual evaluation dtexplicitsum;// running sum of explicit dt limit int verif; // 0 = not verification, 1 = dome, 2 = Halfar (1983) PetscBool monitor,// use -ice_monitor monitor_dt_limits,// also monitor time step limits for explicit schemes dump; // dump state (H,b) at final time CMBModel *cmb;// defined in cmbmodel.h } AppCtx; #include "iceverif.h" extern PetscErrorCode SetFromOptionsAppCtx(AppCtx*); extern PetscErrorCode IceMonitor(TS, int, double, Vec, void*); extern PetscErrorCode ExplicitLimitsMonitor(TS, int, double, Vec, void*); extern PetscErrorCode FormBedLocal(DMDALocalInfo*, int, double**, AppCtx*); extern PetscErrorCode FormBounds(SNES,Vec,Vec); extern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, double, double**, double**, double**, AppCtx*); extern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, double, double**, double**, double, Mat, Mat, AppCtx *user); extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double, double**, double**, AppCtx*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da; TS ts; SNES snes; // no need to destroy (owned by TS) TSAdapt adapt; Vec H; AppCtx user; CMBModel cmb; DMDALocalInfo info; double dx,dy,**aH; PetscInitialize(&argc,&argv,(char*)0,help); ierr = SetFromOptionsAppCtx(&user); CHKERRQ(ierr); ierr = SetFromOptions_CMBModel(&cmb,user.secpera); user.cmb = &cmb; // this DMDA is the cell-centered grid ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_PERIODIC,DM_BOUNDARY_PERIODIC, DMDA_STENCIL_BOX, 3,3,PETSC_DECIDE,PETSC_DECIDE, 1, 1, // dof=1, stencilwidth=1 NULL,NULL,&da); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates ierr = DMSetApplicationContext(da, &user);CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, 0.0,1.0); CHKERRQ(ierr); // initialize the TS and configure its time-axis, including its TSAdapt ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr); ierr = TSSetTime(ts,0.0); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,user.tf); CHKERRQ(ierr); ierr = TSSetTimeStep(ts,user.dtinit); CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSGetAdapt(ts,&adapt); CHKERRQ(ierr); ierr = TSAdaptSetType(adapt,TSADAPTBASIC); CHKERRQ(ierr); ierr = TSAdaptSetClip(adapt,0.5,1.2); CHKERRQ(ierr); ierr = TSAdaptSetStepLimits(adapt,0.0,user.dtmax); CHKERRQ(ierr); if (user.monitor) { ierr = TSMonitorSet(ts,IceMonitor,&user,NULL); CHKERRQ(ierr); } if (user.monitor_dt_limits) { ierr = TSMonitorSet(ts,ExplicitLimitsMonitor,&user,NULL); CHKERRQ(ierr); } // set methods to compute parts of ODE system, for the DMDA grid, for TS callback ierr = TSSetDM(ts,da); CHKERRQ(ierr); ierr = DMDATSSetIFunctionLocal(da,INSERT_VALUES, (DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr); ierr = DMDATSSetIJacobianLocal(da, (DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr); ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES, (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr); // configure the SNES and DM to solve a NCP/VI at each step ierr = TSGetSNES(ts,&snes); CHKERRQ(ierr); ierr = SNESSetType(snes,SNESVINEWTONRSLS); CHKERRQ(ierr); ierr = SNESVISetComputeVariableBounds(snes,&FormBounds); CHKERRQ(ierr); // should be done setting up TS ierr = TSSetFromOptions(ts);CHKERRQ(ierr); // report on space-time grid ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); dx = user.L / (double)(info.mx); dy = user.L / (double)(info.my); ierr = PetscPrintf(PETSC_COMM_WORLD, "solving on domain [0,L] x [0,L] (L=%.3f km) and time interval [0,tf] (tf=%.3f a)\n" "grid: %d x %d points, spacing dx=%.3f km x dy=%.3f km, dtinit=%.3f a\n", user.L/1000.0,user.tf/user.secpera, info.mx,info.my,dx/1000.0,dy/1000.0,user.dtinit/user.secpera); // set up initial condition on fine grid ierr = DMCreateGlobalVector(da,&H);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)H,"H"); CHKERRQ(ierr); ierr = DMDAVecGetArray(da,H,&aH); CHKERRQ(ierr); if (user.verif == 1) { ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr); } else if (user.verif == 2) { double t0; ierr = TSGetTime(ts,&t0); CHKERRQ(ierr); ierr = HalfarThicknessLocal(&info,t0,aH,&user); CHKERRQ(ierr); } else { // fill H according to chop-scale-CMB ierr = FormBedLocal(&info,0,aH,&user); CHKERRQ(ierr); // H(x,y) <- b(x,y) ierr = ChopScaleInitialHLocal_CMBModel(&cmb,&info,aH,aH); CHKERRQ(ierr); } ierr = DMDAVecRestoreArray(da,H,&aH); CHKERRQ(ierr); // solve ierr = TSSolve(ts,H); CHKERRQ(ierr); // time-stepping summary if -ice_dtlimits if (user.monitor_dt_limits) { int count; ierr = TSGetStepNumber(ts,&count); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "average dt %.5f a, average dtexplicit %.5f a\n", (user.tf/user.secpera)/(double)count, (user.dtexplicitsum/user.secpera)/(double)count); CHKERRQ(ierr); } // dump state if requested if (user.dump) { char filename[1024]; PetscViewer viewer; Vec b; double **ab; ierr = VecDuplicate(H,&b);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)b,"b"); CHKERRQ(ierr); ierr = DMDAVecGetArray(da,b,&ab); CHKERRQ(ierr); ierr = FormBedLocal(&info,0,ab,&user); CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da,b,&ab); CHKERRQ(ierr); ierr = sprintf(filename,"ice_%d_%d.dat",info.mx,(int)(user.tf/user.secpera)); ierr = PetscPrintf(PETSC_COMM_WORLD,"writing PETSC binary file %s ...\n",filename); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr); ierr = VecView(b,viewer); CHKERRQ(ierr); ierr = VecView(H,viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); VecDestroy(&b); } // compute error in verification case if (user.verif > 0) { Vec Hexact; double infnorm, onenorm; ierr = VecDuplicate(H,&Hexact); CHKERRQ(ierr); ierr = DMDAVecGetArray(da,Hexact,&aH); CHKERRQ(ierr); if (user.verif == 1) { ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr); } else if (user.verif == 2) { double tf; ierr = TSGetTime(ts,&tf); CHKERRQ(ierr); ierr = HalfarThicknessLocal(&info,tf,aH,&user); CHKERRQ(ierr); } else { SETERRQ(PETSC_COMM_WORLD,3,"invalid user.verif ... how did I get here?\n"); } ierr = DMDAVecRestoreArray(da,Hexact,&aH); CHKERRQ(ierr); ierr = VecAXPY(H,-1.0,Hexact); CHKERRQ(ierr); // H <- H + (-1.0) Hexact VecDestroy(&Hexact); ierr = VecNorm(H,NORM_INFINITY,&infnorm); CHKERRQ(ierr); ierr = VecNorm(H,NORM_1,&onenorm); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "errors on verif %d: |H-Hexact|_inf = %.3f, |H-Hexact|_average = %.3f\n", user.verif,infnorm,onenorm/(double)(info.mx*info.my)); CHKERRQ(ierr); } // clean up VecDestroy(&H); TSDestroy(&ts); DMDestroy(&da); return PetscFinalize(); } PetscErrorCode SetFromOptionsAppCtx(AppCtx *user) { PetscErrorCode ierr; PetscBool set; user->secpera= 31556926.0; // number of seconds in a year user->L = 1800.0e3; // m; note domeL=750.0e3 is radius of verification ice sheet user->tf = 100.0 * user->secpera; // default to 100 years user->dtinit = 10.0 * user->secpera; // default to 10 year as initial step user->dtmax = 1.0e6 * user->secpera; // default to million years; huge user->g = 9.81; // m/s^2 user->rho_ice= 910.0; // kg/m^3 user->n_ice = 3.0; user->A_ice = 3.1689e-24; // 1/(Pa^3 s); EISMINT I value user->D0 = 1.0; // m^2 / s user->eps = 0.001; user->delta = 1.0e-4; user->lambda = 0.25; user->dtexplicitsum = 0.0; user->verif = 0; user->monitor = PETSC_TRUE; user->monitor_dt_limits = PETSC_FALSE; user->dump = PETSC_FALSE; user->cmb = NULL; PetscFunctionBeginUser; ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"ice_","options to ice","");CHKERRQ(ierr); ierr = PetscOptionsReal( "-A", "set value of ice softness A in units Pa-3 s-1", "ice.c",user->A_ice,&user->A_ice,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-D0", "representative value of diffusivity (used in regularizing D) in units m2 s-1", "ice.c",user->D0,&user->D0,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-delta", "dimensionless regularization for slope in SIA formulas", "ice.c",user->delta,&user->delta,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-dt_init", "initial time step; input units are years", "ice.c",user->dtinit,&user->dtinit,&set);CHKERRQ(ierr); if (set) user->dtinit *= user->secpera; ierr = PetscOptionsReal( "-dt_max", "maximum time step; input units are years", "ice.c",user->dtmax,&user->dtmax,&set);CHKERRQ(ierr); if (set) user->dtmax *= user->secpera; ierr = PetscOptionsBool( "-dump", "save final state (H, b)", "ice.c",user->dump,&user->dump,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-eps", "dimensionless regularization for diffusivity D", "ice.c",user->eps,&user->eps,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-L", "side length of domain in meters", "ice.c",user->L,&user->L,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-lambda", "amount of upwinding; lambda=0 is none and lambda=1 is full", "ice.c",user->lambda,&user->lambda,NULL);CHKERRQ(ierr); ierr = PetscOptionsBool( "-monitor", "use the ice monitor which shows ice sheet volume and area", "ice.c",user->monitor,&user->monitor,&set);CHKERRQ(ierr); if (!set) user->monitor = PETSC_TRUE; ierr = PetscOptionsBool( "-monitor_dt_limits", "monitor the time-step limits which would apply to an explicit scheme", "ice.c",user->monitor_dt_limits,&user->monitor_dt_limits,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-n", "value of Glen exponent n", "ice.c",user->n_ice,&user->n_ice,NULL);CHKERRQ(ierr); if (user->n_ice <= 1.0) { SETERRQ1(PETSC_COMM_WORLD,1, "ERROR: n = %f not allowed ... n > 1 is required\n",user->n_ice); } ierr = PetscOptionsReal( "-rho", "ice density in units kg m3", "ice.c",user->rho_ice,&user->rho_ice,NULL);CHKERRQ(ierr); ierr = PetscOptionsReal( "-tf", "final time in seconds; input units are years", "ice.c",user->tf,&user->tf,&set);CHKERRQ(ierr); if (set) user->tf *= user->secpera; ierr = PetscOptionsInt( "-verif","1 = dome exact solution; 2 = halfar exact solution", "ice.c",user->verif,&(user->verif),&set);CHKERRQ(ierr); if ((set) && ((user->verif < 0) || (user->verif > 2))) { SETERRQ1(PETSC_COMM_WORLD,2, "ERROR: verif = %d not allowed ... 0 <= verif <= 2 is required\n", user->verif); } ierr = PetscOptionsEnd();CHKERRQ(ierr); // derived constant computed after other ice properties are set user->Gamma = 2.0 * PetscPowReal(user->rho_ice*user->g,user->n_ice) * user->A_ice / (user->n_ice+2.0); PetscFunctionReturn(0); } // this basic monitor gives current time, volume, area PetscErrorCode IceMonitor(TS ts, int step, double time, Vec H, void *ctx) { PetscErrorCode ierr; AppCtx *user = (AppCtx*)ctx; double lvol = 0.0, vol, larea = 0.0, area, darea, **aH; int j, k; MPI_Comm com; DM da; DMDALocalInfo info; PetscFunctionBeginUser; ierr = TSGetDM(ts,&da);CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); darea = user->L * user->L / (double)(info.mx * info.my); ierr = DMDAVecGetArrayRead(da,H,&aH); CHKERRQ(ierr); for (k = info.ys; k < info.ys + info.ym; k++) { for (j = info.xs; j < info.xs + info.xm; j++) { if (aH[k][j] > 1.0) { // for volume/area its helpful to not count tinys larea += darea; lvol += aH[k][j]; } } } ierr = DMDAVecRestoreArrayRead(da,H,&aH); CHKERRQ(ierr); lvol *= darea; ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr); ierr = MPI_Allreduce(&lvol,&vol,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr); ierr = MPI_Allreduce(&larea,&area,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "%3d: time %.3f a, volume %.1f 10^3 km^3, area %.1f 10^3 km^2\n", step,time/user->secpera,vol/1.0e12,area/1.0e9); CHKERRQ(ierr); PetscFunctionReturn(0); } // this monitor reports on max diffusivity, velocity, explicit time-step limits (for comparison) PetscErrorCode ExplicitLimitsMonitor(TS ts, int step, double time, Vec H, void *ctx) { PetscErrorCode ierr; AppCtx *user = (AppCtx*)ctx; double maxD, dd, dtD=PETSC_INFINITY; MPI_Comm com; DM da; DMDALocalInfo info; PetscFunctionBeginUser; if (time <= 0.0) { PetscFunctionReturn(0); } // globalize maxD ierr = TSGetDM(ts,&da);CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr); ierr = MPI_Allreduce(&(user->locmaxD),&maxD,1,MPI_DOUBLE,MPI_MAX,com); CHKERRQ(ierr); // compute explicit limits if (maxD <= 0.0) { ierr = PetscPrintf(PETSC_COMM_WORLD," [NO -ice_monitor_dt_limits output because maxD is zero]\n"); CHKERRQ(ierr); } else { ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); dd = PetscMin(user->L / (double)(info.mx), user->L / (double)(info.my)); dtD = dd * dd / (4.0*maxD); ierr = PetscPrintf(PETSC_COMM_WORLD," max D_SIA %.3f m2s-1, dtD %.3e a\n", maxD,dtD/user->secpera); CHKERRQ(ierr); user->dtexplicitsum += dtD; } PetscFunctionReturn(0); } PetscErrorCode FormBedLocal(DMDALocalInfo *info, int stencilwidth, double **ab, AppCtx *user) { int j,k,r,s; const double dx = user->L / (double)(info->mx), dy = user->L / (double)(info->my), Z = PETSC_PI / user->L; double x, y, b; // vaguely-random frequencies and coeffs generated by fiddling; see randbed.py const int nc = 4, jc[4] = {1, 3, 6, 8}, kc[4] = {1, 3, 4, 7}; const double scalec = 750.0, C[4][4] = { { 2.00000000, 0.33000000, -0.55020034, 0.54495520}, { 0.50000000, 0.45014486, 0.60551833, -0.52250644}, { 0.93812068, 0.32638429, -0.24654812, 0.33887052}, { 0.17592361, -0.35496741, 0.22694547, -0.05280704} }; PetscFunctionBeginUser; // go through owned portion of grid and compute b(x,y) for (k = info->ys-stencilwidth; k < info->ys + info->ym+stencilwidth; k++) { y = k * dy; for (j = info->xs-stencilwidth; j < info->xs + info->xm+stencilwidth; j++) { x = j * dx; // b(x,y) is sum of a few sines b = 0.0; for (r = 0; r < nc; r++) { for (s = 0; s < nc; s++) { b += C[r][s] * sin(jc[r] * Z * x) * sin(kc[s] * Z * y); } } ab[k][j] = scalec * b; } } PetscFunctionReturn(0); } // for call-back: tell SNESVI (variational inequality) that we want // 0.0 <= H < +infinity PetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) { PetscErrorCode ierr; PetscFunctionBeginUser; ierr = VecSet(Xl,0.0); CHKERRQ(ierr); ierr = VecSet(Xu,PETSC_INFINITY); CHKERRQ(ierr); PetscFunctionReturn(0); } // value of gradient at a point typedef struct { double x,y; } Grad; /* We factor the SIA flux as q = - H^{n+2} sigma(|grad s|) grad s where sigma is the slope-dependent part sigma(z) = Gamma z^{n-1}. Also D = H^{n+2} sigma(|grad s|) so that q = - D grad s. */ static double sigma(Grad gH, Grad gb, const AppCtx *user) { const double n = user->n_ice; if (n > 1.0) { const double sx = gH.x + gb.x, sy = gH.y + gb.y, slopesqr = sx * sx + sy * sy + user->delta * user->delta; return user->Gamma * PetscPowReal(slopesqr,(n-1.0)/2); } else { return user->Gamma; } } /* Regularized derivative of sigma with respect to nodal value H_l: d sigma / dl = (d sigma / d gH.x) * (d gH.x / dl) + (d sigma / d gH.y) * (d gH.y / dl), but d sigma / d gH.x = Gamma * (n-1) * |gH + gb|^{n-3.0} * (gH.x + gb.x) d sigma / d gH.y = Gamma * (n-1) * |gH + gb|^{n-3.0} * (gH.y + gb.y) However, power n-3.0 can be negative, which generates NaN in areas where the surface gradient gH+gb is zero or tiny, so we add delta^2 to |grad s|^2. */ static double DsigmaDl(Grad gH, Grad gb, Grad dgHdl, const AppCtx *user) { const double n = user->n_ice; if (n > 1.0) { const double sx = gH.x + gb.x, sy = gH.y + gb.y, slopesqr = sx * sx + sy * sy + user->delta * user->delta, tmp = user->Gamma * (n-1) * PetscPowReal(slopesqr,(n-3.0)/2); return tmp * sx * dgHdl.x + tmp * sy * dgHdl.y; } else { return 0.0; } } /* Pseudo-velocity from bed slope: W = - sigma * grad b. */ static Grad W(double sigma, Grad gb) { Grad W; W.x = - sigma * gb.x; W.y = - sigma * gb.y; return W; } /* Derivative of pseudo-velocity W with respect to nodal value H_l. */ static Grad DWDl(double dsigmadl, Grad gb) { Grad dWdl; dWdl.x = - dsigmadl * gb.x; dWdl.y = - dsigmadl * gb.y; return dWdl; } /* DCS = diffusivity from the continuation scheme: D(eps) = (1-eps) sigma H^{n+2} + eps D_0 so D(1)=D_0 and D(0)=sigma H^{n+2}. */ static double DCS(double sigma, double H, const AppCtx *user) { return (1.0 - user->eps) * sigma * PetscPowReal(PetscAbsReal(H),user->n_ice+2.0) + user->eps * user->D0; } /* Derivative of diffusivity D = DCS with respect to nodal value H_l. Since D = (1-eps) sigma H^{n+2} + eps D0 it follows that d D / dl = (1-eps) [ (d sigma / dl) H^{n+2} + sigma (n+2) H^{n+1} (d H / dl) ] = (1-eps) H^{n+1} [ (d sigma / dl) H + sigma (n+2) (d H / dl) ] */ static double DDCSDl(double sigma, double dsigmadl, double H, double dHdl, const AppCtx *user) { const double Hpow = PetscPowReal(PetscAbsReal(H),user->n_ice+1.0); return (1.0 - user->eps) * Hpow * ( dsigmadl * H + sigma * (user->n_ice+2.0) * dHdl ); } /* Flux component from the non-sliding SIA on a general bed. */ PetscErrorCode SIAflux(Grad gH, Grad gb, double H, double Hup, PetscBool xdir, double *D, double *q, const AppCtx *user) { const double mysig = sigma(gH,gb,user), myD = DCS(mysig,H,user); const Grad myW = W(mysig,gb); PetscFunctionBeginUser; if (D) { *D = myD; } if (xdir && q) { *q = - myD * gH.x + myW.x * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0); } else { *q = - myD * gH.y + myW.y * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0); } PetscFunctionReturn(0); } static double DSIAfluxDl(Grad gH, Grad gb, Grad dgHdl, double H, double dHdl, double Hup, double dHupdl, PetscBool xdir, const AppCtx *user) { const double Huppow = PetscPowReal(PetscAbsReal(Hup),user->n_ice+1.0), dHuppow = (user->n_ice+2.0) * Huppow * dHupdl, mysig = sigma(gH,gb,user), myD = DCS(mysig,H,user), dsigmadl = DsigmaDl(gH,gb,dgHdl,user), dDdl = DDCSDl(mysig,dsigmadl,H,dHdl,user); const Grad myW = W(mysig,gb), dWdl = DWDl(dsigmadl,gb); if (xdir) return - dDdl * gH.x - myD * dgHdl.x + dWdl.x * Huppow * Hup + myW.x * dHuppow; else return - dDdl * gH.y - myD * dgHdl.y + dWdl.y * Huppow * Hup + myW.y * dHuppow; } // gradients of weights for Q^1 interpolant static const double gx[4] = {-1.0, 1.0, 1.0, -1.0}, gy[4] = {-1.0, -1.0, 1.0, 1.0}; static double fieldatpt(double xi, double eta, double f[4]) { // weights for Q^1 interpolant double x[4] = { 1.0-xi, xi, xi, 1.0-xi}, y[4] = {1.0-eta, 1.0-eta, eta, eta}; return x[0] * y[0] * f[0] + x[1] * y[1] * f[1] + x[2] * y[2] * f[2] + x[3] * y[3] * f[3]; } static double fieldatptArray(int u, int v, double xi, double eta, double **f) { double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]}; return fieldatpt(xi,eta,ff); } static double dfieldatpt(int l, double xi, double eta) { const double x[4] = { 1.0-xi, xi, xi, 1.0-xi}, y[4] = {1.0-eta, 1.0-eta, eta, eta}; return x[l] * y[l]; } static Grad gradfatpt(double xi, double eta, double dx, double dy, double f[4]) { Grad gradf; double x[4] = { 1.0-xi, xi, xi, 1.0-xi}, y[4] = {1.0-eta, 1.0-eta, eta, eta}; gradf.x = gx[0] * y[0] * f[0] + gx[1] * y[1] * f[1] + gx[2] * y[2] * f[2] + gx[3] * y[3] * f[3]; gradf.y = x[0] *gy[0] * f[0] + x[1] *gy[1] * f[1] + x[2] *gy[2] * f[2] + x[3] *gy[3] * f[3]; gradf.x /= dx; gradf.y /= dy; return gradf; } static Grad gradfatptArray(int u, int v, double xi, double eta, double dx, double dy, double **f) { double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]}; return gradfatpt(xi,eta,dx,dy,ff); } static Grad dgradfatpt(int l, double xi, double eta, double dx, double dy) { Grad dgradfdl; const double x[4] = { 1.0-xi, xi, xi, 1.0-xi}, y[4] = {1.0-eta, 1.0-eta, eta, eta}, gx[4] = {-1.0, 1.0, 1.0, -1.0}, gy[4] = {-1.0, -1.0, 1.0, 1.0}; dgradfdl.x = gx[l] * y[l] / dx; dgradfdl.y = x[l] * gy[l] / dy; return dgradfdl; } // indexing of the 8 quadrature points along the boundary of the control volume in M* // point s=0,...,7 is in element (j,k) = (j+je[s],k+ke[s]) static const int je[8] = {0, 0, -1, -1, -1, -1, 0, 0}, ke[8] = {0, 0, 0, 0, -1, -1, -1, -1}, ce[8] = {0, 3, 1, 0, 2, 1, 3, 2}; // direction of flux at 4 points in each element static const PetscBool xdire[4] = {PETSC_TRUE, PETSC_FALSE, PETSC_TRUE, PETSC_FALSE}; // local (element-wise) coords of quadrature points for M* static const double locx[4] = { 0.5, 0.75, 0.5, 0.25}, locy[4] = { 0.25, 0.5, 0.75, 0.5}; /* FormIFunctionLocal = IFunction call-back by TS using DMDA info. Evaluates residual FF on local process patch: FF_{j,k} = \int_{\partial V_{j,k}} \mathbf{q} \cdot \mathbf{n} - m_{j,k} \Delta x \Delta y where V_{j,k} is the control volume centered at (x_j,y_k). Regarding indexing locations along the boundary of the control volume where flux is evaluated, this figure shows four elements and one control volume centered at (x_j,y_k). The boundary of the control volume has 8 points, numbered s=0,...,7: ------------------- | | | | ..2..|..1.. | | 3: | :0 | k |--------- ---------| | 4: | :7 | | ..5..|..6.. | | | | ------------------- j Regarding flux-component indexing on the element indexed by (j,k) node, the value (aqquad[c])[k][j] for c=0,1,2,3 is an x-component at "*" and a y-component at "%"; note (x_j,y_k) is lower-left corner: ------------------- | : | | *2 | | 3 : 1 | |....%.... ....%....| | : | | *0 | | : | @------------------- (j,k) */ PetscErrorCode FormIFunctionLocal(DMDALocalInfo *info, double t, double **aH, double **aHdot, double **FF, AppCtx *user) { PetscErrorCode ierr; const double dx = user->L / (double)(info->mx), dy = user->L / (double)(info->my); // coefficients of quadrature evaluations along the boundary of the control volume in M* const double coeff[8] = {dy/2, dx/2, dx/2, -dy/2, -dy/2, -dx/2, -dx/2, dy/2}; const PetscBool upwind = (user->lambda > 0.0); const double upmin = (1.0 - user->lambda) * 0.5, upmax = (1.0 + user->lambda) * 0.5; int c, j, k, s; double H, Hup, lxup, lyup, **aqquad[4], **ab, DSIA_ckj, qSIA_ckj; Grad gH, gb; Vec qquad[4], b; PetscFunctionBeginUser; #if 0 // optionally check admissibility for (k = info->ys; k < info->ys + info->ym; k++) { for (j = info->xs; j < info->xs + info->xm; j++) { if (aH[k][j] < 0.0) { SETERRQ3(PETSC_COMM_WORLD,1,"ERROR: non-admissible H[k][j] = %.3e < 0.0 detected at j,k = %d,%d ... stopping\n",aH[k][j],j,k); } } } #endif user->locmaxD = 0.0; ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr); if (user->verif > 0) { ierr = VecSet(b,0.0); CHKERRQ(ierr); ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr); } else { ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr); ierr = FormBedLocal(info,1,ab,user); CHKERRQ(ierr); // get stencil width } for (c = 0; c < 4; c++) { ierr = DMGetLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr); ierr = DMDAVecGetArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr); } // loop over locally-owned elements, including ghosts, to get fluxes q at // c = 0,1,2,3 points in element; note start at (xs-1,ys-1) for (k = info->ys-1; k < info->ys + info->ym; k++) { for (j = info->xs-1; j < info->xs + info->xm; j++) { for (c=0; c<4; c++) { H = fieldatptArray(j,k,locx[c],locy[c],aH); gH = gradfatptArray(j,k,locx[c],locy[c],dx,dy,aH); gb = gradfatptArray(j,k,locx[c],locy[c],dx,dy,ab); if (upwind) { if (xdire[c] == PETSC_TRUE) { lxup = (gb.x <= 0.0) ? upmin : upmax; lyup = locy[c]; } else { lxup = locx[c]; lyup = (gb.y <= 0.0) ? upmin : upmax; } Hup = fieldatptArray(j,k,lxup,lyup,aH); } else Hup = H; ierr = SIAflux(gH,gb,H,Hup,xdire[c], &DSIA_ckj,&qSIA_ckj,user); CHKERRQ(ierr); aqquad[c][k][j] = qSIA_ckj; if (user->monitor_dt_limits) { user->locmaxD = PetscMax(user->locmaxD,DSIA_ckj); } } } } // loop over nodes, not including ghosts, to get function F(t,H,H') from quadature over // s = 0,1,...,7 points on boundary of control volume (rectangle) around node for (k=info->ys; k<info->ys+info->ym; k++) { for (j=info->xs; j<info->xs+info->xm; j++) { FF[k][j] = aHdot[k][j]; // now add integral over control volume boundary using two // quadrature points on each side for (s=0; s<8; s++) FF[k][j] += coeff[s] * aqquad[ce[s]][k+ke[s]][j+je[s]] / (dx * dy); } } for (c = 0; c < 4; c++) { ierr = DMDAVecRestoreArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr); ierr = DMRestoreLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr); } ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr); ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr); PetscFunctionReturn(0); } // use j,k for x,y directions in loops and MatSetValuesStencil typedef struct { PetscInt foo,k,j,bar; } MyStencil; PetscErrorCode FormIJacobianLocal(DMDALocalInfo *info, double t, double **aH, double **aHdot, double shift, Mat J, Mat P, AppCtx *user) { PetscErrorCode ierr; const double dx = user->L / (double)(info->mx), dy = user->L / (double)(info->my); const double coeff[8] = {dy/2, dx/2, dx/2, -dy/2, -dy/2, -dx/2, -dx/2, dy/2}; const PetscBool upwind = (user->lambda > 0.0); const double upmin = (1.0 - user->lambda) * 0.5, upmax = (1.0 + user->lambda) * 0.5; int j, k, c, l, s, u, v; double H, Hup, **aDqDlquad[16], **ab, val[33], DqSIADl_clkj; Grad gH, gb; Vec DqDlquad[16], b; MyStencil col[33],row; PetscFunctionBeginUser; ierr = MatZeroEntries(P); CHKERRQ(ierr); // because using ADD_VALUES below ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr); if (user->verif > 0) { ierr = VecSet(b,0.0); CHKERRQ(ierr); ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr); } else { ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr); ierr = FormBedLocal(info,1,ab,user); CHKERRQ(ierr); // get stencil width } for (c = 0; c < 16; c++) { ierr = DMGetLocalVector(info->da, &(DqDlquad[c])); CHKERRQ(ierr); ierr = DMDAVecGetArray(info->da,DqDlquad[c],&(aDqDlquad[c])); CHKERRQ(ierr); } // loop over locally-owned elements, including ghosts, to get DfluxDl for // l=0,1,2,3 at c=0,1,2,3 points in element; note start at (xs-1,ys-1) for (k = info->ys-1; k < info->ys + info->ym; k++) { for (j = info->xs-1; j < info->xs + info->xm; j++) { for (c=0; c<4; c++) { double lxup = locx[c], lyup = locy[c]; H = fieldatptArray(j,k,locx[c],locy[c],aH); gH = gradfatptArray(j,k,locx[c],locy[c],dx,dy,aH); gb = gradfatptArray(j,k,locx[c],locy[c],dx,dy,ab); if (upwind) { if (xdire[c] == PETSC_TRUE) { lxup = (gb.x <= 0.0) ? upmin : upmax; lyup = locy[c]; } else { lxup = locx[c]; lyup = (gb.y <= 0.0) ? upmin : upmax; } Hup = fieldatptArray(j,k,lxup,lyup,aH); } else { Hup = H; } for (l=0; l<4; l++) { Grad dgHdl; double dHdl, dHupdl; dgHdl = dgradfatpt(l,locx[c],locy[c],dx,dy); dHdl = dfieldatpt(l,locx[c],locy[c]); dHupdl = (upwind) ? dfieldatpt(l,lxup,lyup) : dHdl; DqSIADl_clkj = DSIAfluxDl(gH,gb,dgHdl,H,dHdl,Hup,dHupdl,xdire[c],user); aDqDlquad[4*c+l][k][j] = DqSIADl_clkj; } } } } // loop over nodes, not including ghosts, to get derivative of residual // with respect to nodal value for (k=info->ys; k<info->ys+info->ym; k++) { row.k = k; for (j=info->xs; j<info->xs+info->xm; j++) { row.j = j; for (s=0; s<8; s++) { u = j + je[s]; v = k + ke[s]; for (l=0; l<4; l++) { const int djfroml[4] = { 0, 1, 1, 0}, dkfroml[4] = { 0, 0, 1, 1}; col[4*s+l].j = u + djfroml[l]; col[4*s+l].k = v + dkfroml[l]; val[4*s+l] = coeff[s] * aDqDlquad[4*ce[s]+l][v][u] / (dx * dy); } } col[32].j = j; col[32].k = k; val[32] = shift; ierr = MatSetValuesStencil(P,1,(MatStencil*)&row, 33,(MatStencil*)col,val,ADD_VALUES);CHKERRQ(ierr); } } for (c = 0; c < 16; c++) { ierr = DMDAVecRestoreArray(info->da,DqDlquad[c],&(aDqDlquad[c])); CHKERRQ(ierr); ierr = DMRestoreLocalVector(info->da, &(DqDlquad[c])); CHKERRQ(ierr); } ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr); ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr); ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); if (J != P) { ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); } //ierr = MatView(J,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info, double t, double **aH, double **GG, AppCtx *user) { PetscErrorCode ierr; const double dx = user->L / (double)(info->mx), dy = user->L / (double)(info->my); int j, k; Vec b; double **ab, y, x, m; PetscFunctionBeginUser; ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr); ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr); ierr = FormBedLocal(info,0,ab,user); CHKERRQ(ierr); // stencil width NOT needed for (k=info->ys; k<info->ys+info->ym; k++) { y = k * dy; for (j=info->xs; j<info->xs+info->xm; j++) { x = j * dx; if (user->verif == 1) { m = DomeCMB(x,y,user); } else if (user->verif == 2) { m = 0.0; } else { m = M_CMBModel(user->cmb,ab[k][j] + aH[k][j]); // s = b + H is surface elevation } GG[k][j] = m; } } ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr); ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.5736611637, "avg_line_length": 40.7131147541, "ext": "c", "hexsha": "1805ca468e5b71837d6f13431b9e4d2620130ca1", "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": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch12/icet/icet.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "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": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch12/icet/icet.c", "max_line_length": 172, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch12/icet/icet.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 12897, "size": 39736 }
/* GENETIC - A simple genetic algorithm. Copyright 2014, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file evolution.c * \brief Source file to define evolution functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> //#include "config.h" #include "bits.h" #include "sort.h" #include "entity.h" #include "population.h" #include "mutation.h" #include "reproduction.h" #include "adaptation.h" #include "selection.h" #include "evolution.h" #define DEBUG_EVOLUTION 0 ///< Macro to debug the evolution functions. /** * Function to sort the survivals of the evaluated population */ void evolution_sort (Population * population) ///< Population. { unsigned int i, j, index[population->nentities]; double objective[population->nsurvival]; Entity entity[population->nsurvival]; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_sort: start\n"); #endif index_new (population->objective, index, population->nentities); for (i = 0; i < population->nsurvival; ++i) { j = index[i]; objective[i] = population->objective[j]; entity_new (entity + i, population->genome_nbytes, i); memcpy (entity[i].genome, population->entity[j].genome, population->genome_nbytes); } for (i = 0; i < population->nsurvival; ++i) { population->objective[i] = objective[i]; memcpy (population->entity[i].genome, entity[i].genome, population->genome_nbytes); entity_free (entity + i); } #if DEBUG_EVOLUTION fprintf (stderr, "evolution_sort: end\n"); #endif } /** * Funtion to apply the mutation evolution. */ void evolution_mutation (Population * population, ///< Population. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; Entity *mother, *son; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_mutation: start\n"); #endif for (i = population->mutation_max; i > population->mutation_min;) { #if DEBUG_EVOLUTION fprintf (stderr, "evolution_mutation: selection\n"); #endif selection_mutation (population, &mother, rng); son = population->entity + --i; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_mutation: mutation in %u\n", i); #endif mutation (population, mother, son, rng); } #if DEBUG_EVOLUTION fprintf (stderr, "evolution_mutation: end\n"); #endif } /** * Funtion to apply the reproduction evolution. */ void evolution_reproduction (Population * population, ///< Population. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; Entity *mother, *father, *son; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_reproduction: start\n"); #endif for (i = population->reproduction_max; i > population->reproduction_min;) { #if DEBUG_EVOLUTION fprintf (stderr, "evolution_reproduction: selection\n"); #endif selection_reproduction (population, &mother, &father, rng); son = population->entity + --i; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_reproduction: reproduction in %u\n", i); #endif reproduction (mother, father, son, population->genome_nbits, rng); } #if DEBUG_EVOLUTION fprintf (stderr, "evolution_reproduction: end\n"); #endif } /** * Funtion to apply the adaptation evolution. */ void evolution_adaptation (Population * population, ///< Population. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; Entity *mother, *son; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_adaptation: start\n"); #endif for (i = population->adaptation_max; i > population->adaptation_min;) { #if DEBUG_EVOLUTION fprintf (stderr, "evolution_adaptation: selection\n"); #endif selection_adaptation (population, &mother, rng); son = population->entity + --i; #if DEBUG_EVOLUTION fprintf (stderr, "evolution_adaptation: adaptation in %u\n", i); #endif adaptation (population, mother, son, rng); } #if DEBUG_EVOLUTION fprintf (stderr, "evolution_adaptation: end\n"); #endif }
{ "alphanum_fraction": 0.7081489676, "avg_line_length": 31.7192982456, "ext": "c", "hexsha": "27a1f954bcd76468a9f8e2ef9614479931fe1d37", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_path": "3.0.0/evolution.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/genetic", "max_issues_repo_path": "3.0.0/evolution.c", "max_line_length": 79, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_path": "3.0.0/evolution.c", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "num_tokens": 1284, "size": 5424 }
// The MIT License (MIT) // // Copyright (c) 2018 Mateusz Pusz, Conor Williams, Oliver Schonrock // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <units/bits/external/hacks.h> #include <array> #include <cassert> #include <cmath> #include <cstdint> #include <numeric> #include <tuple> #include <type_traits> #include <gsl/gsl-lite.hpp> namespace units::detail { template<typename T> [[nodiscard]] constexpr T abs(T v) noexcept { return v < 0 ? -v : v; } // the following functions enable gcd and related computations on ratios // with exponents. They avoid overflow. Further information here: // https://github.com/mpusz/units/issues/62#issuecomment-588152833 // Computes (a * b) mod m relies on unsigned integer arithmetic, should not // overflow [[nodiscard]] constexpr std::uint64_t mulmod(std::uint64_t a, std::uint64_t b, std::uint64_t m) { std::uint64_t res = 0; if (b >= m) { if (m > UINT64_MAX / 2u) { b -= m; } else { b %= m; } } while (a != 0) { if (a & 1) { if (b >= m - res) { res -= m; } res += b; } a >>= 1; std::uint64_t temp_b = b; if (b >= m - b) { temp_b -= m; } b += temp_b; } return res; } // Calculates (a ^ e) mod m , should not overflow. [[nodiscard]] constexpr std::uint64_t modpow(std::uint64_t a, std::uint64_t e, std::uint64_t m) { a %= m; std::uint64_t result = 1; while (e > 0) { if (e & 1) { result = mulmod(result, a, m); } a = mulmod(a, a, m); e >>= 1; } return result; } // gcd(a * 10 ^ e, b), should not overflow [[nodiscard]] constexpr std::intmax_t gcdpow(std::intmax_t a, std::intmax_t e, std::intmax_t b) noexcept { assert(a > 0); assert(e >= 0); assert(b > 0); // gcd(i, j) = gcd(j, i mod j) for j != 0 Euclid; // // gcd(a 10^e, b) = gcd(b, a 10^e mod b) // // (a 10^e) mod b -> [ (a mod b) (10^e mod b) ] mod b return std::gcd( b, static_cast<std::intmax_t>(mulmod(static_cast<std::uint64_t>(a % b), modpow(10, static_cast<std::uint64_t>(e), static_cast<std::uint64_t>(b)), static_cast<std::uint64_t>(b)))); } constexpr void cwap(std::intmax_t& lhs, std::intmax_t& rhs) { std::intmax_t tmp = lhs; lhs = rhs; rhs = tmp; } // Computes the rational gcd of n1/d1 x 10^e1 and n2/d2 x 10^e2 [[nodiscard]] constexpr auto gcd_frac(std::intmax_t n1, std::intmax_t d1, std::intmax_t e1, std::intmax_t n2, std::intmax_t d2, std::intmax_t e2) noexcept { // Short cut for equal ratios if (n1 == n2 && d1 == d2 && e1 == e2) { return std::array{n1, d1, e1}; } if (e2 > e1) { detail::cwap(n1, n2); detail::cwap(d1, d2); detail::cwap(e1, e2); } std::intmax_t exp = e2; // minimum // gcd(a/b,c/d) = gcd(a⋅d, c⋅b) / b⋅d assert(std::numeric_limits<std::intmax_t>::max() / n1 > d2); assert(std::numeric_limits<std::intmax_t>::max() / n2 > d1); std::intmax_t num = detail::gcdpow(n1 * d2, e1 - e2, n2 * d1); assert(std::numeric_limits<std::intmax_t>::max() / d1 > d2); std::intmax_t den = d1 * d2; std::intmax_t gcd = std::gcd(num, den); return std::array{num / gcd, den / gcd, exp}; } constexpr void normalize(std::intmax_t& num, std::intmax_t& den, std::intmax_t& exp) { if(num == 0) { den = 1; exp = 0; return; } std::intmax_t gcd = std::gcd(num, den); num = num * (den < 0 ? -1 : 1) / gcd; den = detail::abs(den) / gcd; while (num % 10 == 0) { num /= 10; ++exp; } while (den % 10 == 0) { den /= 10; --exp; } } [[nodiscard]] constexpr std::intmax_t safe_multiply(std::intmax_t lhs, std::intmax_t rhs) { constexpr std::intmax_t c = std::uintmax_t(1) << (sizeof(std::intmax_t) * 4); const std::intmax_t a0 = detail::abs(lhs) % c; const std::intmax_t a1 = detail::abs(lhs) / c; const std::intmax_t b0 = detail::abs(rhs) % c; const std::intmax_t b1 = detail::abs(rhs) / c; gsl_Expects(a1 == 0 || b1 == 0); // overflow in multiplication gsl_Expects(a0 * b1 + b0 * a1 < (c >> 1)); // overflow in multiplication gsl_Expects(b0 * a0 <= INTMAX_MAX); // overflow in multiplication gsl_Expects((a0 * b1 + b0 * a1) * c <= INTMAX_MAX - b0 * a0); // overflow in multiplication return lhs * rhs; } } // namespace units::detail
{ "alphanum_fraction": 0.6064139942, "avg_line_length": 28.1435897436, "ext": "h", "hexsha": "9ea155b6fcbc8795c1f154c7e47ece9629d8098b", "lang": "C", "max_forks_count": 70, "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z", "max_forks_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bebuch/units", "max_forks_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_issues_count": 283, "max_issues_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "bebuch/units", "max_issues_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_line_length": 127, "max_stars_count": 571, "max_stars_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bebuch/units", "max_stars_repo_path": "src/core/include/units/bits/ratio_maths.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z", "num_tokens": 1713, "size": 5488 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "parmt_utils.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "iscl/array/array.h" #include "iscl/memory/memory.h" /*! * @brief Computes the [mrows x 6] forward modeling matrix for synthesizing * a waveform. * * @param[in] sacGxx data structure describing the Green's functions to be * scaled by the mxx Green's functions * @param[in] sacGyy data structure describing the Green's functions to be * scaled by the myy Green's functions * @param[in] sacGzz data structure describing the Green's functions to be * scaled by the mzz Green's functions * @param[in] sacGxy data structure describing the Green's functions to be * scaled by the mxy Green's functions * @param[in] sacGxz data structure describing the Green's functions to be * scaled by the mxz Green's functions * @param[in] sacGyz data structure describing the Green's functions to be * scaled by the myz Green's functions * * @param[out] mrows number of rows in forward modeling matrix * @param[out] ierr 0 indicates success * * @result the [npts x 6] column major forward modeling matirx packed * \f$ \{G_{xx}, G_{yy}, G_{zz}, G_{xy}, G_{xz}, G_{yz} \f$. * this must be freed with ISCL's memory_free64f. * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * */ double *parmt_utils_sacGrns2GrnsMat(const struct sacData_struct sacGxx, const struct sacData_struct sacGyy, const struct sacData_struct sacGzz, const struct sacData_struct sacGxy, const struct sacData_struct sacGxz, const struct sacData_struct sacGyz, int *mrows, int *ierr) { const char *fcnm = "parmt_utils_sacGrns2GrnsMat\0"; double *G; int npts, nptsGxx, nptsGyy, nptsGzz, nptsGxy, nptsGxz, nptsGyz; G = NULL; *mrows = 0; // Verify the inputs *ierr = sacio_getIntegerHeader(SAC_INT_NPTS, sacGxx.header, &nptsGxx); *ierr += sacio_getIntegerHeader(SAC_INT_NPTS, sacGyy.header, &nptsGyy); *ierr += sacio_getIntegerHeader(SAC_INT_NPTS, sacGzz.header, &nptsGzz); *ierr += sacio_getIntegerHeader(SAC_INT_NPTS, sacGxy.header, &nptsGxy); *ierr += sacio_getIntegerHeader(SAC_INT_NPTS, sacGxz.header, &nptsGxz); *ierr += sacio_getIntegerHeader(SAC_INT_NPTS, sacGyz.header, &nptsGyz); if (*ierr != 0 || nptsGxx != nptsGyy || nptsGxx != nptsGzz || nptsGxx != nptsGxy || nptsGxx != nptsGxz || nptsGxx != nptsGyz) { if (*ierr != 0){printf("%s: Error reading headers\n", fcnm);} printf("%s: Inconsistent Green's functions trace lenths\n", fcnm); return G; } if (nptsGxx < 1) { printf("%s: No points in Green's functions\n", fcnm); return G; } if (nptsGxx != sacGxx.npts || nptsGxx != sacGyy.npts || nptsGxx != sacGzz.npts || nptsGxx != sacGxy.npts || nptsGxx != sacGxz.npts || nptsGxx != sacGyz.npts) { printf("%s: header npts differs from data npts\n", fcnm); return G; } if (sacGxx.data == NULL || sacGyy.data == NULL || sacGzz.data == NULL || sacGxy.data == NULL || sacGxz.data == NULL || sacGyz.data == NULL) { printf("%s: null grns fns detected\n", fcnm); return G; } // Finally set the column major modeling matrix npts = nptsGxx; *mrows = npts; G = memory_calloc64f(npts*6); cblas_dcopy(npts, sacGxx.data, 1, &G[0*npts], 1); cblas_dcopy(npts, sacGyy.data, 1, &G[1*npts], 1); cblas_dcopy(npts, sacGzz.data, 1, &G[2*npts], 1); cblas_dcopy(npts, sacGxy.data, 1, &G[3*npts], 1); cblas_dcopy(npts, sacGxz.data, 1, &G[4*npts], 1); cblas_dcopy(npts, sacGyz.data, 1, &G[5*npts], 1); return G; } //============================================================================// /*! * @brief Computes a synthetic seismogram from Green's functions * */ int parmt_utils_sacGrnsToEst(const struct sacData_struct data, const struct sacData_struct sacGxx, const struct sacData_struct sacGyy, const struct sacData_struct sacGzz, const struct sacData_struct sacGxy, const struct sacData_struct sacGxz, const struct sacData_struct sacGyz, const double *__restrict__ mt, const bool lrescale, struct sacData_struct *est) { const char *fcnm = "parmt_utils_sacGrnsToEst\0"; double *G; int ierr, npts, nptsGxx, nptsGyy, nptsGzz, nptsGxy, nptsGxz, nptsGyz; const int ldg = 6; double xnum, xden, xscal; // Release memory on the target sacio_free(est); // Build the modeling matrix G = parmt_utils_sacGrns2GrnsMat(sacGxx, sacGyy, sacGzz, sacGxy, sacGxz, sacGyz, &npts, &ierr); if (ierr != 0) { printf("%s: Failed to make forward modeling matrix\n", fcnm); memory_free64f(&G); } // Copy the sacGxx to the estimate sacio_copy(data, est); est->header.isynth = 501; // set a number // Set the modeling matrix G = memory_calloc64f(npts*ldg); cblas_dcopy(npts, sacGxx.data, 1, &G[0*npts], 1); cblas_dcopy(npts, sacGyy.data, 1, &G[1*npts], 1); cblas_dcopy(npts, sacGzz.data, 1, &G[2*npts], 1); cblas_dcopy(npts, sacGxy.data, 1, &G[3*npts], 1); cblas_dcopy(npts, sacGxz.data, 1, &G[4*npts], 1); cblas_dcopy(npts, sacGyz.data, 1, &G[5*npts], 1); // Compute Gm = u to compute the estimate cblas_dgemv(CblasColMajor, CblasNoTrans, npts, 6, 1.0, G, npts, mt, 1, 0.0, est->data, 1); memory_free64f(&G); // Potentially rescale the synthetic if (lrescale) { xnum = array_maxAbs64f(npts, data.data, &ierr); xden = array_maxAbs64f(npts, est->data, &ierr); xscal = xnum/xden; cblas_dscal(npts, xscal, est->data, 1); } return 0; }
{ "alphanum_fraction": 0.5838267373, "avg_line_length": 40.6202531646, "ext": "c", "hexsha": "41ecaa06e5e5f66b88268ea9e82d060dd78e7453", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "utils/sacGrnsToEst.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_path": "utils/sacGrnsToEst.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "utils/sacGrnsToEst.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1921, "size": 6418 }
#include <math.h> #include <stdio.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_vector.h> #include <argtable2.h> #include "qdm.h" void qdm_mspline_vector( gsl_vector *result, const double tau, const size_t spline_df, const gsl_vector *knots ) { size_t bin = qdm_vector_search(knots, tau); gsl_vector_set(result, 0, 0); for (size_t m = 0; m < result->size - 1; m++) { double v; if (bin < m) { v = 0; } else if (bin - spline_df + 1 > m) { v = 0; } else if (bin == m) { double n = 3 * gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 2); double d1 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m); double d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m); double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m); v = n / (d1 * d2 * d3); } else if (bin == m + 1) { double i1 = 1 / (gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1)); double i2n = gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 2); double i2d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m); double i2d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m); double i2d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1); double i2 = i2n / (i2d1 * i2d2 * i2d3); double i3n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 2); double i3d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m); double i3d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1); double i3d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1); double i3 = i3n / (i3d1 * i3d2 * i3d3); v = 3 * (i1 - i2 - i3); } else { double n = 3 * gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 2); double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m); double d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1); double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 2); double d = d1 * d2 * d3; v = n / d; } gsl_vector_set(result, m + 1, v); } } void qdm_mspline_matrix(gsl_matrix *result, const size_t spline_df, const gsl_vector *x, const gsl_vector *knots) { for (size_t i = 0; i < result->size1; i++) { gsl_vector_view row = gsl_matrix_row(result, i); qdm_mspline_vector(&row.vector, gsl_vector_get(x, i), spline_df, knots); } }
{ "alphanum_fraction": 0.6142742582, "avg_line_length": 32.3896103896, "ext": "c", "hexsha": "eaf027bf8ed160f4d2116ab962cf56be5aec7883", "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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "src/mspline.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "src/mspline.c", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "src/mspline.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 922, "size": 2494 }
#pragma once #include "halley/maths/vector3.h" #include <gsl/span> namespace Halley { class AudioListenerData; class AudioChannelData; class AudioPosition { public: struct SpatialSource { SpatialSource(); SpatialSource(Vector2f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f); SpatialSource(Vector3f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f); Vector3f pos; float referenceDistance; float maxDistance; }; AudioPosition(); static AudioPosition makeUI(float pan = 0.0f); // -1.0f = left, 1.0f = right static AudioPosition makePositional(Vector2f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f); static AudioPosition makePositional(Vector3f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f); static AudioPosition makePositional(std::vector<SpatialSource> sources); static AudioPosition makeFixed(); void setMix(size_t srcChannels, gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const; void setPosition(Vector3f position); private: std::vector<SpatialSource> sources; float pan = 0; bool isUI = false; bool isPannable = false; void setMixFixed(size_t srcChannels, gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const; void setMixUI(gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const; void setMixPositional(gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const; }; }
{ "alphanum_fraction": 0.760728983, "avg_line_length": 37.8, "ext": "h", "hexsha": "9a675e803a47bd6b6a10cfba9d2eab5f35a92542", "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": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sunhay/halley", "max_forks_repo_path": "src/engine/audio/include/halley/audio/audio_position.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "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": "sunhay/halley", "max_issues_repo_path": "src/engine/audio/include/halley/audio/audio_position.h", "max_line_length": 165, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sunhay/halley", "max_stars_repo_path": "src/engine/audio/include/halley/audio/audio_position.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": 463, "size": 1701 }
/* trav.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_bst.h> #include <gsl/gsl_errno.h> int gsl_bst_trav_init(gsl_bst_trav * trav, const gsl_bst_workspace * w) { int status = (w->type->trav_init)((void *) &trav->trav_data, (const void *) &w->table); trav->type = w->type; return status; } /* gsl_bst_trav_first() Initialize traverser to least-valued item in tree and return a pointer to it. Return NULL if tree has no nodes. */ void * gsl_bst_trav_first(gsl_bst_trav * trav, const gsl_bst_workspace * w) { trav->type = w->type; return (w->type->trav_first)((void *) &trav->trav_data, (const void *) &w->table); } /* gsl_bst_trav_last() Initializes |trav| for |tree| and selects and returns a pointer to its greatest-valued item. Returns NULL if |tree| contains no nodes. */ void * gsl_bst_trav_last (gsl_bst_trav * trav, const gsl_bst_workspace * w) { trav->type = w->type; return (w->type->trav_last)((void * ) &trav->trav_data, (const void *) &w->table); } /* gsl_bst_trav_find() Searches for |item| in tree. If found, initializes |trav| to the item found and returns the item as well. If there is no matching item, initializes |trav| to the null item and returns |NULL|. */ void * gsl_bst_trav_find (const void * item, gsl_bst_trav * trav, const gsl_bst_workspace * w) { trav->type = w->type; return (w->type->trav_find)(item, (void * ) &trav->trav_data, (const void *) &w->table); } /* gsl_bst_trav_insert() Attempts to insert |item| into tree. If |item| is inserted successfully, it is returned and |trav| is initialized to its location. If a duplicate is found, it is returned and |trav| is initialized to its location. No replacement of the item occurs. If a memory allocation failure occurs, |NULL| is returned and |trav| is initialized to the null item. */ void * gsl_bst_trav_insert (void * item, gsl_bst_trav * trav, gsl_bst_workspace * w) { trav->type = w->type; return (w->type->trav_insert)(item, (void * ) &trav->trav_data, (void *) &w->table); } /* gsl_bst_trav_copy() Copy traverser 'src' into 'dest' */ void * gsl_bst_trav_copy(gsl_bst_trav * dest, const gsl_bst_trav * src) { dest->type = src->type; return (src->type->trav_copy)((void * ) &dest->trav_data, (const void *) &src->trav_data); } /* gsl_bst_trav_next() Update traverser to point to next sequential node, and return a pointer to its data */ void * gsl_bst_trav_next(gsl_bst_trav * trav) { return (trav->type->trav_next)((void *) &trav->trav_data); } /* gsl_bst_trav_prev() Update traverser to point to previous sequential node, and return a pointer to its data */ void * gsl_bst_trav_prev(gsl_bst_trav * trav) { return (trav->type->trav_prev)((void *) &trav->trav_data); } /* gsl_bst_trav_cur() Return a pointer to data of current traverser node */ void * gsl_bst_trav_cur(const gsl_bst_trav * trav) { return (trav->type->trav_cur)((const void *) &trav->trav_data); } /* gsl_bst_trav_replace() Replace current item in trav with new_item and returns the item replaced. The new item must not change the ordering of the tree. */ void * gsl_bst_trav_replace (gsl_bst_trav * trav, void * new_item) { return (trav->type->trav_replace)((void * ) &trav->trav_data, new_item); }
{ "alphanum_fraction": 0.7125585986, "avg_line_length": 26.8410596026, "ext": "c", "hexsha": "6442c264a635a18b3f1bd8ebd3dd01ba0f1e2123", "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/bst/trav.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/bst/trav.c", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/bst/trav.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": 1217, "size": 4053 }
/**************************************************************/ /*! \brief This file contains all .h files */ /**************************************************************/ #ifndef __SLIM_H__ #define __SLIM_H__ #define _GNU_SOURCE 1 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <bcls.h> #include <GKlib.h> #include <def.h> #include <struct.h> #include <proto.h> #include <mpi.h> #include <omp.h> #endif
{ "alphanum_fraction": 0.5939086294, "avg_line_length": 20.7368421053, "ext": "h", "hexsha": "2d987578229007a6af26112a9128c35b4f161ef4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_path": "include/slim.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "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": "echristakopoulou/glslim", "max_issues_repo_path": "include/slim.h", "max_line_length": 64, "max_stars_count": 3, "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_path": "include/slim.h", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "num_tokens": 208, "size": 788 }
#ifndef __gslInterp_ #define __gslInterp__ #include "include/stdinc.h" #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_integration.h> #include <vector> class gslInterp { protected: gsl_interp_accel *acc; gsl_interp *interp; vector<double> x, y; public: gslInterp(vector<double> &x0, vector<double> &y0) { acc = gsl_interp_accel_alloc(); for (size_t i = 0; i < x0.size(); i++) { x.push_back(x0[i]); y.push_back(y0[i]); } interp = gsl_interp_alloc(gsl_interp_linear, x.size()); gsl_interp_init(interp, &x[0], &y[0], x.size()); } ~gslInterp() { gsl_interp_accel_free(acc); gsl_interp_free(interp); } void init(vector<double> &x0, vector<double> &y0) { gsl_interp_accel_free(acc); gsl_interp_free(interp); acc = gsl_interp_accel_alloc(); x.clear(); y.clear(); for (size_t i = 0; i < x0.size(); i++) { x.push_back(x0[i]); y.push_back(y0[i]); } interp = gsl_interp_alloc(gsl_interp_linear, x.size()); gsl_interp_init(interp, &x[0], &y[0], x.size()); } inline double eval(double xc) { return gsl_interp_eval(interp, &x[0], &y[0], xc, acc); } inline double deriv(double xc) { return gsl_interp_eval_deriv(interp, &x[0], &y[0], xc, acc); } inline double deriv2(double xc) { return gsl_interp_eval_deriv2(interp, &x[0], &y[0], xc, acc); } inline double integ(double x_lo, double x_up) { return gsl_interp_eval_integ(interp, &x[0], &y[0], x_lo, x_up, acc); } }; #endif // __gslInterp__
{ "alphanum_fraction": 0.6307884856, "avg_line_length": 26.6333333333, "ext": "h", "hexsha": "cc216048ca376075e17c15a973839124c02c526f", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rieder/amuse", "max_forks_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_issues_count": 690, "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rknop/amuse", "max_issues_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_line_length": 72, "max_stars_count": 131, "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rknop/amuse", "max_stars_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "num_tokens": 490, "size": 1598 }
/* specfunc/test_gamma.c * * Copyright (C) 2007 Brian Gough * 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 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_test.h> #include <gsl/gsl_sf.h> #include "test_sf.h" int test_gamma(void) { gsl_sf_result r; gsl_sf_result r1, r2; double sgn; int s = 0; TEST_SF(s, gsl_sf_lngamma_e, (-0.1, &r), 2.368961332728788655 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (-1.0/256.0, &r), 5.547444766967471595 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (1.0e-08, &r), 18.420680738180208905 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (0.1, &r), 2.252712651734205 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (1.0 + 1.0/256.0, &r), -0.0022422226599611501448 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (2.0 + 1.0/256.0, &r), 0.0016564177556961728692 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (100.0, &r), 359.1342053695753 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (-1.0-1.0/65536.0, &r), 11.090348438090047844 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (-1.0-1.0/268435456.0, &r), 19.408121054103474300 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (-100.5, &r), -364.9009683094273518 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lngamma_e, (-100-1.0/65536.0, &r), -352.6490910117097874 , TEST_TOL0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (0.7, &r, &sgn), 0.26086724653166651439, TEST_TOL1, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (0.1, &r, &sgn), 2.2527126517342059599, TEST_TOL0, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-0.1, &r, &sgn), 2.368961332728788655, TEST_TOL0, -1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-1.0-1.0/65536.0, &r, &sgn), 11.090348438090047844, TEST_TOL0, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-2.0-1.0/256.0, &r, &sgn), 4.848447725860607213, TEST_TOL0, -1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-2.0-1.0/65536.0, &r, &sgn), 10.397193628164674967, TEST_TOL0, -1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-3.0-1.0/8.0, &r, &sgn), 0.15431112768404182427, TEST_TOL2, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-100.5, &r, &sgn), -364.9009683094273518, TEST_TOL0, -1.0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (1.0 + 1.0/4096.0, &r), 0.9998591371459403421 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (1.0 + 1.0/32.0, &r), 0.9829010992836269148 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (2.0 + 1.0/256.0, &r), 1.0016577903733583299 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (9.0, &r), 40320.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (10.0, &r), 362880.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (100.0, &r), 9.332621544394415268e+155 , TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (170.0, &r), 4.269068009004705275e+304 , TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (171.0, &r), 7.257415615307998967e+306 , TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (-10.5, &r), -2.640121820547716316e-07 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_e, (-11.25, &r), 6.027393816261931672e-08 , TEST_TOL0, GSL_SUCCESS); /* exp()... not my fault */ TEST_SF(s, gsl_sf_gamma_e, (-1.0+1.0/65536.0, &r), -65536.42280587818970 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (1.0e-08, &r), 3989.423555759890865 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (1.0e-05, &r), 126.17168469882690233 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (0.001, &r), 12.708492464364073506 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (1.5, &r), 1.0563442442685598666 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (3.0, &r), 1.0280645179187893045 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (9.0, &r), 1.0092984264218189715 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (11.0, &r), 1.0076024283104962850 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (100.0, &r), 1.0008336778720121418 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (1.0e+05, &r), 1.0000008333336805529 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammastar_e, (1.0e+20, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (2.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (3.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (4.0, &r), 1.0/6.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (10.0, &r), 1.0/362880.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (100.0, &r), 1.0715102881254669232e-156, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-1.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-2.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-3.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-4.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-10.5, &r), -1.0/2.640121820547716316e-07, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-11.25, &r), 1.0/6.027393816261931672e-08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gammainv_e, (-1.0+1.0/65536.0, &r), -1.0/65536.42280587818970 , TEST_TOL1, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_lngamma_complex_e, (5.0, 2.0, &r1, &r2), 2.7487017561338026749, TEST_TOL0, 3.0738434100497007915, TEST_TOL0, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_lngamma_complex_e, (100.0, 100.0, &r1, &r2), 315.07804459949331323, TEST_TOL1, 2.0821801804113110099, TEST_TOL3, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_lngamma_complex_e, (100.0, -1000.0, &r1, &r2), -882.3920483010362817000, TEST_TOL1, -2.1169293725678813270, TEST_TOL3, GSL_SUCCESS); TEST_SF_2(s, gsl_sf_lngamma_complex_e, (-100.0, -1.0, &r1, &r2), -365.0362469529239516000, TEST_TOL1, -3.0393820262864361140, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (10, 1.0/1048576.0, &r), 1.7148961854776073928e-67 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (10, 1.0/1024.0, &r), 2.1738891788497900281e-37 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (10, 1.0, &r), 2.7557319223985890653e-07 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (10, 5.0, &r), 2.6911444554673721340 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (10, 500.0, &r), 2.6911444554673721340e+20 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (100, 100.0, &r), 1.0715102881254669232e+42 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (1000, 200.0, &r), 2.6628790558154746898e-267 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_taylorcoeff_e, (1000, 500.0, &r), 2.3193170139740855074e+131 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_fact_e, (0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_fact_e, (1, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_fact_e, (7, &r), 5040.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_fact_e, (33, &r), 8.683317618811886496e+36 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_doublefact_e, (0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_doublefact_e, (1, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_doublefact_e, (7, &r), 105.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_doublefact_e, (33, &r), 6.332659870762850625e+18 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnfact_e, (0, &r), 0.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnfact_e, (1, &r), 0.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnfact_e, (7, &r), 8.525161361065414300 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnfact_e, (33, &r), 85.05446701758151741 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (0, &r), 0.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (7, &r), 4.653960350157523371 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (33, &r), 43.292252022541719660 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (34, &r), 45.288575519655959140 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (1034, &r), 3075.6383796271197707 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lndoublefact_e, (1035, &r), 3078.8839081731809169 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnchoose_e, (7,3, &r), 3.555348061489413680 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnchoose_e, (5,2, &r), 2.302585092994045684 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (7,3, &r), 35.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (7,4, &r), 35.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (5,2, &r), 10.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (5,3, &r), 10.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (500,495, &r), 255244687600.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (500,5, &r), 255244687600.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (500,200, &r), 5.054949849935532221e+144 , TEST_TOL5, GSL_SUCCESS); TEST_SF(s, gsl_sf_choose_e, (500,300, &r), 5.054949849935532221e+144 , TEST_TOL5, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnpoch_e, (5, 0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnpoch_e, (5, 1.0/65536.0, &r), 0.000022981557571259389129, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnpoch_e, (5, 1.0/256.0, &r), 0.005884960217985189004, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnpoch_e, (7,3, &r), 6.222576268071368616, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnpoch_e, (5,2, &r), 3.401197381662155375, TEST_TOL0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lnpoch_sgn_e, (5.0, 0.0, &r, &sgn), 0.0, TEST_TOL1, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lnpoch_sgn_e, (-4.5, 0.25, &r, &sgn), 0.7430116475119920117, TEST_TOL1, 1.0, GSL_SUCCESS); TEST_SF_SGN(s, gsl_sf_lnpoch_sgn_e, (-4.5, 1.25, &r, &sgn), 2.1899306304483174731, TEST_TOL1, -1.0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (5, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (7,3, &r), 504.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (5,2, &r), 30.0 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (5,1.0/256.0, &r), 1.0059023106151364982 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (5,0, &r), 1.506117668431800472, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (7,3, &r), 503.0/3.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (5,2, &r), 29.0/2.0, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (5,0.01, &r), 1.5186393661368275330, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (-5.5,0.01, &r), 1.8584945633829063516, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (-5.5,-1.0/8.0, &r), 1.0883319303552135488, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (-5.5,-1.0/256.0, &r), 1.7678268037726177453, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_pochrel_e, (-5.5,-11.0, &r), 0.09090909090939652475, TEST_TOL0, GSL_SUCCESS); /* Add tests for special cases with negative arguments */ TEST_SF(s, gsl_sf_poch_e, (-9.0, -4.0, &r), 1.0/17160.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, -3.0, &r), -1.0/1320.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, -3.5, &r), 0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, 4.0, &r), 3024.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, 3.0, &r), -504.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, 3.5, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-9.0, 0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-8.0, -4.0, &r), 1.0/11880.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-8.0, -3.0, &r), -1.0/990.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-8.0, +4.0, &r), 1680.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-8.0, +3.0, &r), -336.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-3.0, +4.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); /* FIXME: we should be able to get an exact answer for poch(-a,a) if gsl_sf_lngamma functions were fixed to handle integer arguments exactly as a special case */ TEST_SF(s, gsl_sf_poch_e, (-3.0, +3.0, &r), -6.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-4.0, +4.0, &r), 24.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_poch_e, (-3.0, +100.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1e-100, 0.001, &r), 1.0, TEST_TOL0, GSL_SUCCESS) ; TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 0.001, &r), 0.9936876467088602902, TEST_TOL0, GSL_SUCCESS) ; TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 1.0, &r), 0.9997803916424144436, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 10.0, &r), 0.9999999958306921828, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 0.001, &r), 0.0009995001666250083319, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 1.01, &r), 0.6357810204284766802, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 10.0, &r), 0.9999546000702375151, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (10.0, 10.01, &r), 0.5433207586693410570, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (10.0, 20.0, &r), 0.9950045876916924128, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1000.0, 1000.1, &r), 0.5054666401440661753, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1000.0, 2000.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS); /* Test for failure of the Gautschi recurrence (now fixed) for x = a - 2 */ TEST_SF(s, gsl_sf_gamma_inc_P_e, (34.0, 32.0, &r), 0.3849626436463866776322932129, TEST_TOL2, GSL_SUCCESS); /* and the next test is gamma_inc_P(37,35-20*eps) */ TEST_SF(s, gsl_sf_gamma_inc_P_e, (37.0, 3.499999999999999289e+01, &r), 0.3898035054195570860969333039, TEST_TOL2, GSL_SUCCESS); /* Regression test Martin Jansche <jansche@ling.ohio-state.edu> BUG#12 */ TEST_SF(s, gsl_sf_gamma_inc_P_e, (10, 1e-16, &r), 2.755731922398588814734648067e-167, TEST_TOL2, GSL_SUCCESS); /* Regression test for gsl_cdf_chisq_Pinv, (0.05, 1263131.0) */ TEST_SF(s, gsl_sf_gamma_inc_P_e, (1263131.0, 1261282.3637, &r), 0.04994777516935182963821362168, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (1263131.0, 1263131.0, &r), 0.500118321758657770672882362502514254, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.0, 0.001, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 0.001, &r), 0.006312353291139709793, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 1.0, &r), 0.00021960835758555639171, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 2.0, &r), 0.00004897691783098147880, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 5.0, &r), 1.1509813397308608541e-06, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 0.001, &r), 0.9990004998333749917, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 1.01, &r), 0.3642189795715233198, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 10.0, &r), 0.00004539992976248485154, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (10.0, 10.01, &r), 0.4566792413306589430, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (10.0, 100.0, &r), 1.1253473960842733885e-31, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1000.0, 1000.1, &r), 0.4945333598559338247, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1000.0, 2000.0, &r), 6.847349459614753180e-136, TEST_TOL2, GSL_SUCCESS); /* designed to trap the a-x=1 problem */ TEST_SF(s, gsl_sf_gamma_inc_Q_e, (100, 99.0, &r), 0.5266956696005394, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (200, 199.0, &r), 0.5188414119121281, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (100, 99.0, &r), 0.4733043303994607, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_P_e, (200, 199.0, &r), 0.4811585880878718, TEST_TOL2, GSL_SUCCESS); /* Test for x86 cancellation problems */ TEST_SF(s, gsl_sf_gamma_inc_P_e, (5670, 4574, &r), 3.063972328743934e-55, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (5670, 4574, &r), 1.0000000000000000, TEST_TOL2, GSL_SUCCESS); /* test suggested by Michel Lespinasse [gsl-discuss Sat, 13 Nov 2004] */ TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0e+06-1.0, 1.0e+06-2.0, &r), 0.50026596175224547004, TEST_TOL3, GSL_SUCCESS); /* tests in asymptotic regime related to Lespinasse test */ TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0e+06+2.0, 1.0e+06+1.0, &r), 0.50026596135330304336, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0e+06, 1.0e+06-2.0, &r), 0.50066490399940144811, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0e+07, 1.0e+07-2.0, &r), 0.50021026104978614908, TEST_TOL2, GSL_SUCCESS); /* non-normalized "Q" function */ TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0/1048576.0, 1.0/1048576.0, &r), 13.285819596290624271, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.001, 1.0/1048576.0, &r), 13.381275128625328858, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0, 1.0/1048576.0, &r), 1.0485617142715768655e+06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.00001,0.001, &r), 6.3317681434563592142, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.0001,0.001, &r), 6.3338276439767189385, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.001, 0.001, &r), 6.3544709102510843793, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.5, 0.001, &r), 59.763880515942196981, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0, 0.001, &r), 992.66896046923884234, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-3.5, 0.001, &r), 9.0224404490639003706e+09, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-10.5, 0.001, &r), 3.0083661558184815656e+30, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.001, 0.1, &r), 1.8249109609418620068, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.5, 0.1, &r), 3.4017693366916154163, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-10.0, 0.1, &r), 8.9490757483586989181e+08, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-10.5, 0.1, &r), 2.6967403834226421766e+09, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.001, 1.0, &r), 0.21928612679072766340, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.5, 1.0, &r), 0.17814771178156069019, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0, 1.0, &r), 0.14849550677592204792, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-2.5, 1.0, &r), 0.096556648631275160264, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0, 10.0, &r), 3.8302404656316087616e-07, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.001, 10.0, &r), 4.1470562324807320961e-06, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-0.5, 10.0, &r), 1.2609042613241570681e-06, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-1.0, 10.0, &r), 3.8302404656316087616e-07, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-10.5, 10.0, &r), 6.8404927328441566785e-17, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-100.0, 10.0, &r), 4.1238327669858313997e-107, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (-200.0, 10.0, &r), 2.1614091830529343423e-207, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.0, 0.001, &r), 6.3315393641361493320, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.001, 0.001, &r), 6.3087159394864007261, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 1.0, 0.001, &r), 0.99900049983337499167, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 10.0, 0.001, &r), 362880.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.0, 1.0, &r), 0.21938393439552027368, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.001, 1.0, &r), 0.21948181320730279613, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 1.0, 1.0, &r), 0.36787944117144232160, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 10.0, 1.0, &r), 362879.95956592242045, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (100.0, 1.0, &r), 9.3326215443944152682e+155, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.0, 100.0, &r), 3.6835977616820321802e-46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 0.001, 100.0, &r), 3.7006367674063550631e-46, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 1.0, 100.0, &r), 3.7200759760208359630e-44, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, ( 10.0, 100.0, &r), 4.0836606309106112723e-26, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_gamma_inc_e, (100.0, 100.0, &r), 4.5421981208626694294e+155, TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1.0e-8, &r), 19.113827924512310617 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 0.01, &r), 18.420681743788563403 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1.0, &r), 18.420680743952365472 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 10.0, &r), 18.420680715662683009 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1000.0, &r), 18.420680669107656949 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 0.1, &r), 2.9813614810376273949 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 1.0, &r), 2.3025850929940456840 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 100.0, &r), 1.7926462324527931217 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 1000, &r), 1.5619821298353164928 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1.00025, &r), -0.0002499687552073570, TEST_TOL4, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1.01, &r), -0.009950330853168082848 , TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1000.0, &r), -6.907755278982137052 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 100.0, &r), -139.66525908670663927 , TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 1000.0, &r), -336.4348576477366051 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 1.0e+8, &r), -1482.9339185256447309 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (1.0, 1.0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (1.0, 1.001, &r), 0.9990009990009990010 , TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (1.0, 5.0, &r), 0.2 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (1.0, 100.0, &r), 0.01 , TEST_TOL1, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (10.0, 100.0, &r), 2.3455339739604649879e-15 , TEST_TOL2, GSL_SUCCESS); /* Test negative arguments */ TEST_SF(s, gsl_sf_beta_e, (2.5, -0.1, &r), -11.43621278354402041480, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (2.5, -1.1, &r), 14.555179906328753255202, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-0.25, -0.1, &r), -13.238937960945229110, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-1.25, -0.1, &r), -14.298052997820847439, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-100.1, -99.1, &r), -1.005181917797644630375787297e60, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-100.1, 99.3, &r), 0.0004474258199579694011200969001, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (100.1, -99.3, &r), 1.328660939628876472028853747, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-100.1, 1.2, &r), 0.00365530364287960795444856281, TEST_TOL3, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (100.1, -1.2, &r), 1203.895236907821059270698160, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-100.1, -1.2, &r), -3236.073671884748847700283841, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-100.001, 0.0099, &r), -853.946649365611147996495177, TEST_TOL4, GSL_SUCCESS); /* Other test cases */ TEST_SF(s, gsl_sf_beta_e, (1e-32, 1.5, &r), 1e32, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (1e-6, 0.5, &r), 1000001.386293677092419390336, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_e, (-1.5, 0.5, &r), 0.0, TEST_TOL0, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (1.0, 1.0, 0.0, &r), 0.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (1.0, 1.0, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (0.1, 0.1, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 1.0, 0.5, &r), 0.5, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 0.1, 1.0, 0.5, &r), 0.9330329915368074160, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (10.0, 1.0, 0.5, &r), 0.0009765625000000000000, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (50.0, 1.0, 0.5, &r), 8.881784197001252323e-16, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 0.1, 0.5, &r), 0.06696700846319258402, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 10.0, 0.5, &r), 0.99902343750000000000, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 50.0, 0.5, &r), 0.99999999999999911180, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 1.0, 0.1, &r), 0.10, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 2.0, 0.1, &r), 0.19, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 1.0, 2.0, 0.9, &r), 0.99, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (50.0, 60.0, 0.5, &r), 0.8309072939016694143, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (90.0, 90.0, 0.5, &r), 0.5, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, ( 500.0, 500.0, 0.6, &r), 0.9999999999157549630, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (5000.0, 5000.0, 0.4, &r), 4.518543727260666383e-91, TEST_TOL5, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (5000.0, 5000.0, 0.6, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (5000.0, 2000.0, 0.6, &r), 8.445388773903332659e-89, TEST_TOL5, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.1, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.2, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.2, -0.1, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.2, 0.5, &r), 0.675252001958389971991335, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.2, -0.1, 0.5, &r), 0.324747998041610028008665, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.1, 0.0, &r), 0.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.2, 0.0, &r), 0.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.2, -0.1, 0.0, &r), 0.0, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.1, -0.2, 0.3, &r), 0.7469186777964287252, TEST_TOL2, GSL_SUCCESS); TEST_SF(s, gsl_sf_beta_inc_e, (-0.2, -0.1, 0.3, &r), 0.3995299653262016818, TEST_TOL2, GSL_SUCCESS); /* Bug report from Thomas Tanner <tanner@gmx.de> */ TEST_SF(s, gsl_sf_beta_inc_e, (0.5, 101.5, 0.999457, &r), 1.0, TEST_TOL2, GSL_SUCCESS); return s; }
{ "alphanum_fraction": 0.7003456342, "avg_line_length": 72.6979695431, "ext": "c", "hexsha": "9799355329ad29c10637a1aa763dc779776b9718", "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/specfunc/test_gamma.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/specfunc/test_gamma.c", "max_line_length": 129, "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/specfunc/test_gamma.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": 12461, "size": 28643 }
/** * * @file timing.c * * PLASMA auxiliary 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 Mathieu Faverge * @author Dulceneia Becker * @date 2010-11-15 * **/ #define _FMULS FMULS_GEQRF( M, N ) #define _FADDS FADDS_GEQRF( M, N ) #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef PLASMA_EZTRACE #include <eztrace.h> #endif #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #ifdef USE_MKL #include <mkl_cblas.h> #include <mkl_lapacke.h> #else #include <cblas.h> #include <lapacke.h> #endif #include "plasma.h" #include "core_blas.h" #include "flops.h" #include "timing.h" #include "auxiliary.h" #include "main.h" #include "workspace.h" #include "Utils.h" #define EPSILON 1.0E-9 static double RunTest(double *t_, struct user_parameters*); static double RunTest_dpotrf(real_Double_t *t_, struct user_parameters* params) { double t; int64_t N = params->matrix_size; int64_t NB = params->blocksize; int check = params->check; int uplo = PlasmaUpper; double check_res = 0; /* Allocate Data */ PLASMA_desc *descA = NULL; double* ptr = malloc(N * N * sizeof(double)); PLASMA_Desc_Create(&descA, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, N, 0, 0, N, N); #pragma omp parallel #pragma omp master plasma_pdplgsy_quark( (double)N, *descA, 51 ); /* Save A for check */ double *A = NULL; if(check) { A = (double*)malloc(N * N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descA, (void*)A, N); } double t_start, t_end; //START_TIMING(); t_start = rtclock(); #pragma omp parallel #pragma omp master plasma_pdpotrf_quark(uplo, *descA); //STOP_TIMING(); t_end = rtclock(); *t_ = t_end - t_start; /* Check the solution */ if ( check ) { PLASMA_desc *descB = NULL; double* ptr = (double*)malloc(N * sizeof(double)); PLASMA_Desc_Create(&descB, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, 1, 0, 0, N, 1); plasma_pdpltmg_seq(* descB, 7672 ); double* B = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)B, N); PLASMA_dpotrs_Tile( uplo, descA, descB ); double* X = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)X, N); check_res = d_check_solution(N, N, 1, A, N, B, X, N); PASTE_CODE_FREE_MATRIX( descB ); free( A ); free( B ); free( X ); } PASTE_CODE_FREE_MATRIX( descA ); return check_res; } static double RunTest_dgetrf(real_Double_t *t_, struct user_parameters* params) { double t; int64_t N = params->matrix_size; int64_t NB = params->blocksize; int check = params->check; double check_res = 0; /* Allocate Data */ PLASMA_desc *descA = NULL; double* ptr = malloc(N * N * sizeof(double)); PLASMA_Desc_Create(&descA, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, N, 0, 0, N, N); int* piv = (int*)malloc(N * sizeof(double)); #pragma omp parallel #pragma omp master plasma_pdpltmg_quark(*descA, 3456); /* Save AT in lapack layout for check */ double *A = NULL; if(check) { A = (double*)malloc(N * N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descA, (void*)A, N); } double t_start, t_end; //START_TIMING(); t_start = rtclock(); #pragma omp parallel #pragma omp master plasma_pdgetrf_rectil_quark(*descA, piv); //STOP_TIMING(); t_end = rtclock(); *t_ = t_end - t_start; /* Check the solution */ if ( check ) { PLASMA_desc *descB = NULL; double* ptr = (double*)malloc(N * sizeof(double)); PLASMA_Desc_Create(&descB, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, 1, 0, 0, N, 1); plasma_pdpltmg_seq(*descB, 7732 ); double* b = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)b, N); PLASMA_dgetrs_Tile( PlasmaNoTrans, descA, piv, descB ); double* x = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)x, N); check_res = d_check_solution(N, N, 1, A, N, b, x, N); PASTE_CODE_FREE_MATRIX( descB ); free(A); free(b); free(x); } PASTE_CODE_FREE_MATRIX( descA ); free( piv ); return check_res; } static double RunTest_dgeqrf(real_Double_t *t_, struct user_parameters* params) { double t; PLASMA_desc *descT; int64_t N = params->matrix_size; int64_t IB = params->iblocksize; int64_t NB = params->blocksize; int check = params->check; double check_res = 0; /* Allocate Data */ PLASMA_desc *descA = NULL; double *ptr = (double*)malloc(N * N * sizeof(double)); PLASMA_Desc_Create(&descA, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, N, 0, 0, N, N); #pragma omp parallel #pragma omp master plasma_pdpltmg_quark(*descA, 5373 ); /* Save A for check */ double *A = NULL; if ( check ) { A = (double*)malloc(N * N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descA, (void*)A, N); } /* Allocate Workspace */ plasma_alloc_ibnb_tile(N, N, PlasmaRealDouble, &descT, IB, NB); double t_start, t_end; //START_TIMING(); t_start = rtclock(); #pragma omp parallel #pragma omp master plasma_pdgeqrf_quark( *descA, *descT , IB); //STOP_TIMING(); t_end = rtclock(); *t_ = t_end - t_start; /* Check the solution */ if ( check ) { /* Allocate B for check */ PLASMA_desc *descB = NULL; double* ptr = (double*)malloc(N * sizeof(double)); PLASMA_Desc_Create(&descB, ptr, PlasmaRealDouble, NB, NB, NB*NB, N, 1, 0, 0, N, 1); /* Initialize and save B */ plasma_pdpltmg_seq(*descB, 2264 ); double *B = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)B, N); /* Compute the solution */ PLASMA_dgeqrs_Tile( descA, descT, descB , IB); /* Copy solution to X */ double *X = (double*)malloc(N * sizeof(double)); plasma_pdtile_to_lapack_quark(*descB, (void*)X, N); check_res = d_check_solution(N, N, 1, A, N, B, X, N); /* Free checking structures */ PASTE_CODE_FREE_MATRIX( descB ); free( A ); free( B ); free( X ); } /* Free data */ PLASMA_Dealloc_Handle_Tile(&descT); PASTE_CODE_FREE_MATRIX( descA ); return check_res; } int ISEED[4] = {0,0,0,1}; /* initial seed for zlarnv() */ double run(struct user_parameters* params) { double t; double fmuls, fadds; double flops; params->succeed = 1; int type = params->type; if (params->matrix_size <= 0) { params->matrix_size = 2048; } if (params->blocksize <= 0) { params->blocksize = 128; } //ifdef if (params->iblocksize <= 0) { params->iblocksize = params->blocksize; } if (params->type <= 0) { params->type = 1; type = params->type; } int64_t N = params->matrix_size; int64_t M = params->matrix_size; fadds = (double)(_FADDS); fmuls = (double)(_FMULS); flops = 1e-9 * (fmuls + fadds); //mod aqui if (type == 1) { if (RunTest_dgeqrf(&t, params) > EPSILON && params->check) params->succeed = 0; } else if (type == 2) { if (RunTest_dgetrf(&t, params) > EPSILON && params->check) params->succeed = 0; } else if (type == 3) { if (RunTest_dpotrf(&t, params) > EPSILON && params->check) params->succeed = 0; } // return gflops return flops / t; }
{ "alphanum_fraction": 0.6024157661, "avg_line_length": 24.8107255521, "ext": "c", "hexsha": "24897414ad1d47b5bcda2ffa3f07fbc25b0ace3b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-01-29T17:09:46.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-11T17:08:06.000Z", "max_forks_repo_head_hexsha": "9cd1e49ec8a21c7ed63bbca7e769ceb56a5b62d3", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "fabiodrg/Unibench", "max_forks_repo_path": "benchmarks/kastors/plasma/src/timing.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9cd1e49ec8a21c7ed63bbca7e769ceb56a5b62d3", "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": "fabiodrg/Unibench", "max_issues_repo_path": "benchmarks/kastors/plasma/src/timing.c", "max_line_length": 91, "max_stars_count": 3, "max_stars_repo_head_hexsha": "9cd1e49ec8a21c7ed63bbca7e769ceb56a5b62d3", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "fabiodrg/Unibench", "max_stars_repo_path": "benchmarks/kastors/plasma/src/timing.c", "max_stars_repo_stars_event_max_datetime": "2020-09-20T01:53:40.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-27T01:43:38.000Z", "num_tokens": 2421, "size": 7865 }
#pragma once #include <algorithm> #include <gsl/gsl_assert> #include "family_type.h" #include "family_mask.h" #include "entity_id.h" #include "halley/data_structures/nullable_reference.h" #include "halley/support/exception.h" #include "halley/support/debug.h" #include "halley/utils/utils.h" namespace Halley { class Entity; class FamilyBindingBase; class Family { friend class World; public: explicit Family(FamilyMaskType inclusionMask, FamilyMaskType optionalMask); virtual ~Family() {} size_t count() const { return elemCount; } void* getElement(size_t n) const { return static_cast<char*>(elems) + (n * elemSize); } void addOnEntitiesAdded(FamilyBindingBase* bind); void removeOnEntityAdded(FamilyBindingBase* bind); void addOnEntitiesRemoved(FamilyBindingBase* bind); void removeOnEntityRemoved(FamilyBindingBase* bind); void addOnEntitiesReloaded(FamilyBindingBase* bind); void removeOnEntitiesReloaded(FamilyBindingBase* bind); void notifyAdd(void* entities, size_t count); void notifyRemove(void* entities, size_t count); void notifyReload(void* entities, size_t count); protected: virtual void addEntity(Entity& entity) = 0; virtual void refreshEntity(Entity& entity) = 0; void removeEntity(Entity& entity); void reloadEntity(Entity& entity); virtual void updateEntities() = 0; virtual void clearEntities() = 0; void* elems = nullptr; size_t elemCount = 0; size_t elemSize = 0; Vector<EntityId> toRemove; Vector<EntityId> toReload; Vector<FamilyBindingBase*> addEntityCallbacks; Vector<FamilyBindingBase*> removeEntityCallbacks; Vector<FamilyBindingBase*> modifiedEntityCallbacks; private: FamilyMaskType inclusionMask; FamilyMaskType optionalMask; }; class FamilyBase { protected: NullableReferenceAnchor anchor; public: EntityId entityId; }; template <typename T> class FamilyBaseOf : public FamilyBase { public: NullableReferenceOf<T> getReference() { return anchor.getReferenceOf<T>(); } NullableReferenceOf<const T> getReference() const { return anchor.getReferenceOf<const T>(); } }; // Apple's Clang 3.5 does not seem to have constexpr std::max... constexpr size_t maxSize(size_t a, size_t b) { return a > b ? a : b; } template <typename T> class FamilyImpl : public Family { constexpr static size_t storageSize = sizeof(T) - alignUp(sizeof(FamilyBase), alignof(void*)); static_assert(std::is_base_of<FamilyBase, T>::value, "Family type does not derive from FamilyBase"); // I don't know why this needs to be aligned up to 8 on Win32. :| static_assert(alignUp(T::Type::getNumComponents() * sizeof(void*), size_t(8)) == storageSize, "Family type has unexpected storage size"); struct StorageType : public FamilyBase { alignas(alignof(void*)) std::array<char, storageSize> data; }; public: explicit FamilyImpl(MaskStorage& storage) : Family(T::Type::inclusionMask(storage), T::Type::optionalMask(storage)) { } protected: void addEntity(Entity& entity) override { auto& e = entities.emplace_back(); e.entityId = entity.getEntityId(); T::Type::loadComponents(entity, &e.data[0]); dirty = true; } void refreshEntity(Entity& entity) override { for (auto& e: entities) { if (e.entityId == entity.getEntityId()) { T::Type::loadComponents(entity, &e.data[0]); break; } } } void updateEntities() override { if (dirty) { // Notify additions HALLEY_DEBUG_TRACE(); size_t prevSize = elemCount; size_t curSize = entities.size(); updateElems(); Expects(curSize >= prevSize); if (curSize > prevSize) { notifyAdd(entities.data() + prevSize, curSize - prevSize); } dirty = false; } if (!toReload.empty()) { // Notify reloads HALLEY_DEBUG_TRACE(); std::vector<StorageType*> reloadedEntities; for (auto& entity : entities) { if (std::find(toReload.begin(), toReload.end(), entity.entityId) != toReload.end()) { reloadedEntities.push_back(&entity); } } notifyReload(reloadedEntities.data(), reloadedEntities.size()); toReload.clear(); } // Remove removeDeadEntities(); } void clearEntities() override { notifyRemove(entities.data(), entities.size()); entities.clear(); updateElems(); } private: Vector<StorageType> entities; bool dirty = false; void updateElems() { elems = entities.empty() ? nullptr : entities.data(); elemCount = entities.size(); elemSize = sizeof(StorageType); } void removeDeadEntities() { // Performance-critical code // Benchmarks suggest that using a Vector is faster than std::set and std::unordered_set if (!toRemove.empty()) { HALLEY_DEBUG_TRACE(); size_t removeCount = toRemove.size(); Expects(removeCount > 0); Expects(removeCount <= entities.size()); std::sort(toRemove.begin(), toRemove.end()); for (size_t i = 1; i < toRemove.size(); ++i) { Expects(toRemove[i - 1] != toRemove[i]); } // Move all entities to be removed to the back of the vector { int n = int(entities.size()); // Note: it's important to scan it forward. Scanning backwards would improve performance for short-lived entities, // but it causes an issue where an entity is removed and added to the same family in one frame. for (int i = 0; i < n; i++) { EntityId id = entities[i].entityId; auto iter = std::lower_bound(toRemove.begin(), toRemove.end(), id); if (iter != toRemove.end() && id == *iter) { toRemove.erase(iter); if (i != n - 1) { std::swap(entities[i], entities[n - 1]); i--; } n--; if (toRemove.empty()) { break; } } } Ensures(size_t(n) + removeCount == entities.size()); } Expects(toRemove.empty()); // Notify removal size_t newSize = entities.size() - removeCount; Ensures(newSize < entities.size()); notifyRemove(entities.data() + newSize, removeCount); // Remove them entities.resize(newSize); updateElems(); } Ensures(toRemove.empty()); } }; }
{ "alphanum_fraction": 0.6720779221, "avg_line_length": 25.6666666667, "ext": "h", "hexsha": "e70910c382fd97a753e9950ddec92d246bdac823", "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/entity/include/halley/entity/family.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/entity/include/halley/entity/family.h", "max_line_length": 139, "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/entity/include/halley/entity/family.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": 1632, "size": 6160 }
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <text_shaper/font.h> #include <fmt/format.h> #include <gsl/span> #include <gsl/span_ext> #include <optional> #include <variant> #include <vector> namespace text { /// Holds the system path to a font file. struct font_path { std::string value; }; /// Holds a view into the contents of a font file. struct font_memory_ref { std::string identifier; //!< a unique identifier for this font gsl::span<uint8_t> data; //!< font file contents (non-owned) }; /// Represents a font source (such as file path or memory). using font_source = std::variant<font_path, font_memory_ref>; /// Holds a list of fonts. using font_source_list = std::vector<font_source>; /** * Font location API. * * Used for locating fonts and fallback fonts to be used * for text shaping and glyph rendering. */ class font_locator { public: virtual ~font_locator() = default; /** * Enumerates all available fonts. */ virtual font_source_list all() = 0; /** * Locates the font matching the given description the best * and an ordered list of fallback fonts. */ virtual font_source_list locate(font_description const& description) = 0; /** * Resolves the given codepoint sequence into an ordered list of * possible fonts that can be used for text shaping the given * codepoint sequence. */ virtual font_source_list resolve(gsl::span<const char32_t> codepoints) = 0; }; } // namespace text namespace fmt // {{{ { template <> struct formatter<text::font_path> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(text::font_path path, FormatContext& ctx) { return fmt::format_to(ctx.out(), "path {}", path.value); } }; template <> struct formatter<text::font_memory_ref> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(text::font_memory_ref ref, FormatContext& ctx) { return fmt::format_to(ctx.out(), "in-memory: {}", ref.identifier); } }; template <> struct formatter<text::font_source> { template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(text::font_source source, FormatContext& ctx) { if (std::holds_alternative<text::font_path>(source)) return fmt::format_to(ctx.out(), "{}", std::get<text::font_path>(source)); if (std::holds_alternative<text::font_memory_ref>(source)) return fmt::format_to(ctx.out(), "{}", std::get<text::font_memory_ref>(source)); return fmt::format_to(ctx.out(), "UNKNOWN SOURCE"); } }; } // namespace fmt
{ "alphanum_fraction": 0.6782433984, "avg_line_length": 26.1954887218, "ext": "h", "hexsha": "e445137bb02f014d80c62ec1e0fb6245af484a9f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_path": "src/text_shaper/font_locator.h", "max_issues_count": 69, "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_path": "src/text_shaper/font_locator.h", "max_line_length": 92, "max_stars_count": 4, "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_path": "src/text_shaper/font_locator.h", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "num_tokens": 800, "size": 3484 }
/*************************************************************************** * * * * Copyright (C) 2011 by Stefan Oslowski * * Licensed under the Academic Free License version 2.1 * * ****************************************************************************/ #ifndef __Pulsar__TimeDomainCovariance_h #define __Pulsar__TimeDomainCovariance_h #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include "Pulsar/ProfileCovariance.h" namespace Pulsar { class TimeDomainCovariance : public ProfileCovariance { public: //! Default constructor TimeDomainCovariance (); //! Destructor ~TimeDomainCovariance (); //! Choose which bins are to be used in the calculation of covariance matrix void choose_bins ( unsigned, unsigned ); //! Get the name of class used std::string get_name () const; //! Adds the given Profile to the covariance matrix estimate void add_Profile (const Profile* ); void add_Profile (const Profile*, float wt ); //! Get the whole covariance matrix void get_covariance_matrix ( double * ); //! Get the whole covariance matrix - gsl void get_covariance_matrix_gsl ( gsl_matrix * ); //! Set the whole covariance matrix void set_covariance_matrix ( double * ); //! Get the i, j covariance matrix element, where i is the row and j is the column double get_covariance_matrix_value ( unsigned, unsigned ); //! This normalizes the covariance matrix after all profiles were added void finalize (); //! Return a text interface that can be used to configure this instance //virtual TextInterface::Parser* get_interface (); //! Get the count of profiles used to estimate the covariance matrix unsigned get_count (); //! Set the count of profiles used to estimate the covariance matrix void set_count ( unsigned ); //! Get the rank of covariance matrix unsigned get_rank (); //! Set the rank of covariance matrix void set_rank ( unsigned ); //! Reset the covariance matrix calculations void reset (); protected: //! first bin to be used unsigned first_bin; //! last bin to be used unsigned last_bin; //! Auxiliary variable for covariance matrix_calculation gsl_matrix *covariance_gsl; //! Auxiliary variable for storing the profile gsl_vector_view p_gsl; }; } #endif
{ "alphanum_fraction": 0.6507870754, "avg_line_length": 27.7471264368, "ext": "h", "hexsha": "107569bba25e7edec1e885fdd0ad1c5eabe6b084", "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": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_forks_repo_licenses": [ "AFL-2.1" ], "max_forks_repo_name": "xuanyuanstar/psrchive_CDFT", "max_forks_repo_path": "More/General/Pulsar/TimeDomainCovariance.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AFL-2.1" ], "max_issues_repo_name": "xuanyuanstar/psrchive_CDFT", "max_issues_repo_path": "More/General/Pulsar/TimeDomainCovariance.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_stars_repo_licenses": [ "AFL-2.1" ], "max_stars_repo_name": "xuanyuanstar/psrchive_CDFT", "max_stars_repo_path": "More/General/Pulsar/TimeDomainCovariance.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 522, "size": 2414 }
/* specfunc/debye.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* augmented to n=5 and 6 2005-11-08 by R. J. Mathar, http://www.strw.leidenuniv.nl/~mathar */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_debye.h> #include "error.h" #include "check.h" #include "chebyshev.h" #include "cheb_eval.c" static double adeb1_data[17] = { 2.4006597190381410194, 0.1937213042189360089, -0.62329124554895770e-02, 0.3511174770206480e-03, -0.228222466701231e-04, 0.15805467875030e-05, -0.1135378197072e-06, 0.83583361188e-08, -0.6264424787e-09, 0.476033489e-10, -0.36574154e-11, 0.2835431e-12, -0.221473e-13, 0.17409e-14, -0.1376e-15, 0.109e-16, -0.9e-18 }; static cheb_series adeb1_cs = { adeb1_data, 16, -1.0, 1.0, 9 }; static double adeb2_data[18] = { 2.5943810232570770282, 0.2863357204530719834, -0.102062656158046713e-01, 0.6049109775346844e-03, -0.405257658950210e-04, 0.28633826328811e-05, -0.2086394303065e-06, 0.155237875826e-07, -0.11731280087e-08, 0.897358589e-10, -0.69317614e-11, 0.5398057e-12, -0.423241e-13, 0.33378e-14, -0.2645e-15, 0.211e-16, -0.17e-17, 0.1e-18 }; static cheb_series adeb2_cs = { adeb2_data, 17, -1.0, 1.0, 10 }; static double adeb3_data[17] = { 2.707737068327440945, 0.340068135211091751, -0.12945150184440869e-01, 0.7963755380173816e-03, -0.546360009590824e-04, 0.39243019598805e-05, -0.2894032823539e-06, 0.217317613962e-07, -0.16542099950e-08, 0.1272796189e-09, -0.987963460e-11, 0.7725074e-12, -0.607797e-13, 0.48076e-14, -0.3820e-15, 0.305e-16, -0.24e-17 }; static cheb_series adeb3_cs = { adeb3_data, 16, -1.0, 1.0, 10 }; static double adeb4_data[17] = { 2.781869415020523460, 0.374976783526892863, -0.14940907399031583e-01, 0.945679811437042e-03, -0.66132916138933e-04, 0.4815632982144e-05, -0.3588083958759e-06, 0.271601187416e-07, -0.20807099122e-08, 0.1609383869e-09, -0.125470979e-10, 0.9847265e-12, -0.777237e-13, 0.61648e-14, -0.4911e-15, 0.393e-16, -0.32e-17 }; static cheb_series adeb4_cs = { adeb4_data, 16, -1.0, 1.0, 10 }; static double adeb5_data[17] = { 2.8340269546834530149, 0.3994098857106266445, -0.164566764773099646e-1, 0.10652138340664541e-2, -0.756730374875418e-4, 0.55745985240273e-5, -0.4190692330918e-6, 0.319456143678e-7, -0.24613318171e-8, 0.1912801633e-9, -0.149720049e-10, 0.11790312e-11, -0.933329e-13, 0.74218e-14, -0.5925e-15, 0.475e-16, -0.39e-17 }; static cheb_series adeb5_cs = { adeb5_data, 16, -1.0, 1.0, 10 }; static double adeb6_data[17] = { 2.8726727134130122113, 0.4174375352339027746, -0.176453849354067873e-1, 0.11629852733494556e-2, -0.837118027357117e-4, 0.62283611596189e-5, -0.4718644465636e-6, 0.361950397806e-7, -0.28030368010e-8, 0.2187681983e-9, -0.171857387e-10, 0.13575809e-11, -0.1077580e-12, 0.85893e-14, -0.6872e-15, 0.552e-16, -0.44e-17 }; static cheb_series adeb6_cs = { adeb6_data, 16, -1.0, 1.0, 10 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_debye_1_e(const double x, gsl_sf_result * result) { const double val_infinity = 1.64493406684822644; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - 0.25*x + x*x/36.0; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb1_cs, t, &c); result->val = c.val - 0.25 * x; result->err = c.err + 0.25 * x * GSL_DBL_EPSILON; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double sum = 0.0; double xk = nexp * x; double rk = nexp; int i; for(i=nexp; i>=1; i--) { sum *= ex; sum += (1.0 + 1.0/xk)/rk; rk -= 1.0; xk -= x; } result->val = val_infinity/x - sum*ex; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < xcut) { result->val = (val_infinity - exp(-x)*(x+1.0)) / x; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { result->val = val_infinity/x; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_debye_2_e(const double x, gsl_sf_result * result) { const double val_infinity = 4.80822761263837714; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - x/3.0 + x*x/24.0; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb2_cs, t, &c); result->val = c.val - x/3.0; result->err = c.err + GSL_DBL_EPSILON * x/3.0; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double xk = nexp * x; double rk = nexp; double sum = 0.0; int i; for(i=nexp; i>=1; i--) { sum *= ex; sum += (1.0 + 2.0/xk + 2.0/(xk*xk)) / rk; rk -= 1.0; xk -= x; } result->val = val_infinity/(x*x) - 2.0 * sum * ex; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < xcut) { const double x2 = x*x; const double sum = 2.0 + 2.0*x + x2; result->val = (val_infinity - 2.0 * sum * exp(-x)) / x2; result->err = GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { result->val = (val_infinity/x)/x; result->err = GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } int gsl_sf_debye_3_e(const double x, gsl_sf_result * result) { const double val_infinity = 19.4818182068004875; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - 3.0*x/8.0 + x*x/20.0; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb3_cs, t, &c); result->val = c.val - 0.375*x; result->err = c.err + GSL_DBL_EPSILON * 0.375*x; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double xk = nexp * x; double rk = nexp; double sum = 0.0; int i; for(i=nexp; i>=1; i--) { double xk_inv = 1.0/xk; sum *= ex; sum += (((6.0*xk_inv + 6.0)*xk_inv + 3.0)*xk_inv + 1.0) / rk; rk -= 1.0; xk -= x; } result->val = val_infinity/(x*x*x) - 3.0 * sum * ex; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x < xcut) { const double x3 = x*x*x; const double sum = 6.0 + 6.0*x + 3.0*x*x + x3; result->val = (val_infinity - 3.0 * sum * exp(-x)) / x3; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { result->val = ((val_infinity/x)/x)/x; result->err = GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } int gsl_sf_debye_4_e(const double x, gsl_sf_result * result) { const double val_infinity = 99.5450644937635129; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - 2.0*x/5.0 + x*x/18.0; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb4_cs, t, &c); result->val = c.val - 2.0*x/5.0; result->err = c.err + GSL_DBL_EPSILON * 2.0*x/5.0; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double xk = nexp * x; double rk = nexp; double sum = 0.0; int i; for(i=nexp; i>=1; i--) { double xk_inv = 1.0/xk; sum *= ex; sum += ((((24.0*xk_inv + 24.0)*xk_inv + 12.0)*xk_inv + 4.0)*xk_inv + 1.0) / rk; rk -= 1.0; xk -= x; } result->val = val_infinity/(x*x*x*x) - 4.0 * sum * ex; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x < xcut) { const double x2 = x*x; const double x4 = x2*x2; const double sum = 24.0 + 24.0*x + 12.0*x2 + 4.0*x2*x + x4; result->val = (val_infinity - 4.0 * sum * exp(-x)) / x4; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { result->val = (((val_infinity/x)/x)/x)/x; result->err = GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } int gsl_sf_debye_5_e(const double x, gsl_sf_result * result) { const double val_infinity = 610.405837190669483828710757875 ; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - 5.0*x/12.0 + 5.0*x*x/84.0; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb5_cs, t, &c); result->val = c.val - 5.0*x/12.0; result->err = c.err + GSL_DBL_EPSILON * 5.0*x/12.0; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double xk = nexp * x; double rk = nexp; double sum = 0.0; int i; for(i=nexp; i>=1; i--) { double xk_inv = 1.0/xk; sum *= ex; sum += (((((120.0*xk_inv + 120.0)*xk_inv + 60.0)*xk_inv + 20.0)*xk_inv + 5.0)*xk_inv+ 1.0) / rk; rk -= 1.0; xk -= x; } result->val = val_infinity/(x*x*x*x*x) - 5.0 * sum * ex; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x < xcut) { const double x2 = x*x; const double x4 = x2*x2; const double x5 = x4*x; const double sum = 120.0 + 120.0*x + 60.0*x2 + 20.0*x2*x + 5.0*x4 + x5; result->val = (val_infinity - 5.0 * sum * exp(-x)) / x5; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { result->val = ((((val_infinity/x)/x)/x)/x)/x; result->err = GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } int gsl_sf_debye_6_e(const double x, gsl_sf_result * result) { const double val_infinity = 4356.06887828990661194792541535 ; const double xcut = -GSL_LOG_DBL_MIN; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) { result->val = 1.0 - 3.0*x/7.0 + x*x/16.0; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x <= 4.0) { const double t = x*x/8.0 - 1.0; gsl_sf_result c; cheb_eval_e(&adeb6_cs, t, &c); result->val = c.val - 3.0*x/7.0; result->err = c.err + GSL_DBL_EPSILON * 3.0*x/7.0; return GSL_SUCCESS; } else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) { const int nexp = floor(xcut/x); const double ex = exp(-x); double xk = nexp * x; double rk = nexp; double sum = 0.0; int i; for(i=nexp; i>=1; i--) { double xk_inv = 1.0/xk; sum *= ex; sum += ((((((720.0*xk_inv + 720.0)*xk_inv + 360.0)*xk_inv + 120.0)*xk_inv + 30.0)*xk_inv+ 6.0)*xk_inv+ 1.0) / rk; rk -= 1.0; xk -= x; } result->val = val_infinity/(x*x*x*x*x*x) - 6.0 * sum * ex; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else if(x < xcut) { const double x2 = x*x; const double x4 = x2*x2; const double x6 = x4*x2; const double sum = 720.0 + 720.0*x + 360.0*x2 + 120.0*x2*x + 30.0*x4 + 6.0*x4*x +x6 ; result->val = (val_infinity - 6.0 * sum * exp(-x)) / x6; result->err = GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { result->val = (((((val_infinity/x)/x)/x)/x)/x)/x ; result->err = GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_debye_1(const double x) { EVAL_RESULT(gsl_sf_debye_1_e(x, &result)); } double gsl_sf_debye_2(const double x) { EVAL_RESULT(gsl_sf_debye_2_e(x, &result)); } double gsl_sf_debye_3(const double x) { EVAL_RESULT(gsl_sf_debye_3_e(x, &result)); } double gsl_sf_debye_4(const double x) { EVAL_RESULT(gsl_sf_debye_4_e(x, &result)); } double gsl_sf_debye_5(const double x) { EVAL_RESULT(gsl_sf_debye_5_e(x, &result)); } double gsl_sf_debye_6(const double x) { EVAL_RESULT(gsl_sf_debye_6_e(x, &result)); }
{ "alphanum_fraction": 0.6095170455, "avg_line_length": 24.8324514991, "ext": "c", "hexsha": "07c2f570bdad60c643165d49933b72f2f4eb2d3c", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/debye.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/debye.c", "max_line_length": 119, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/debye.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": 5569, "size": 14080 }
#pragma once #include "BoundingVolume.h" #include "Library.h" #include "TileContentLoadResult.h" #include "TileContentLoader.h" #include "TileID.h" #include "TileRefine.h" #include <CesiumAsync/AsyncSystem.h> #include <CesiumAsync/Future.h> #include <CesiumAsync/HttpHeaders.h> #include <CesiumAsync/IAssetAccessor.h> #include <CesiumGltfReader/GltfReader.h> #include <glm/mat4x4.hpp> #include <gsl/span> #include <spdlog/fwd.h> #include <cstddef> #include <optional> namespace CesiumGeospatial { class GlobeRectangle; } namespace Cesium3DTilesSelection { class Tileset; /** * @brief Creates {@link TileContentLoadResult} from glTF data. */ class CESIUM3DTILESSELECTION_API GltfContent final : public TileContentLoader { public: /** * @copydoc TileContentLoader::load * * The result will only contain the `model`. Other fields will be * empty or have default values. */ CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>> load(const TileContentLoadInput& input) override; /** * @brief Create a {@link TileContentLoadResult} from the given data. * * (Only public to be called from `Batched3DModelContent`) * * @param asyncSystem The async system to use for requesting any external * content. * @param pLogger Only used for logging * @param url The URL, only used for logging * @param headers The http headers to use for resolving any external content. * @param pAssetAccessor The asset accessor to use to resolve external * content. * @param data The actual glTF data * @param contentOptions The content options for loading this glTF. * @return The {@link TileContentLoadResult} */ static CesiumAsync::Future<std::unique_ptr<TileContentLoadResult>> load( const CesiumAsync::AsyncSystem& asyncSystem, const std::shared_ptr<spdlog::logger>& pLogger, const std::string& url, const CesiumAsync::HttpHeaders& headers, const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor, const gsl::span<const std::byte>& data, const TilesetContentOptions& contentOptions); /** * @brief Creates texture coordinates for mapping {@link RasterOverlay} tiles * to {@link Tileset} tiles. * * Generates new texture coordinates for the `gltf` using the given * `projections`. The first new texture coordinate (`u` or `s`) will be 0.0 at * the `minimumX` of the given `rectangle` and 1.0 at the `maximumX`. The * second texture coordinate (`v` or `t`) will be 0.0 at the `minimumY` of * the given `rectangle` and 1.0 at the `maximumY`. * * Coordinate values for vertices in between these extremes are determined by * projecting the vertex position with the `projection` and then computing the * fractional distance of that projected position between the minimum and * maximum. * * Projected positions that fall outside the `globeRectangle` will be clamped * to the edges, so the coordinate values will never be less then 0.0 or * greater than 1.0. * * These texture coordinates are stored in the provided glTF, and a new * primitive attribute named `_CESIUMOVERLAY_n` is added to each primitive, * where `n` starts with the `firstTextureCoordinateID` passed to this * function and increases with each projection. * * @param gltf The glTF model. * @param modelToEcefTransform The transformation of this glTF to ECEF * coordinates. * @param firstTextureCoordinateID The texture coordinate ID of the first * projection. * @param globeRectangle The rectangle that all projected vertex positions are * expected to lie within. If this parameter is std::nullopt, it is computed * from the vertices. * @param projections The projections for which to generate texture * coordinates. There is a linear relationship between the coordinates of this * projection and the generated texture coordinates. * @return The detailed of the generated texture coordinates. */ static std::optional<TileContentDetailsForOverlays> createRasterOverlayTextureCoordinates( CesiumGltf::Model& gltf, const glm::dmat4& modelToEcefTransform, int32_t firstTextureCoordinateID, const std::optional<CesiumGeospatial::GlobeRectangle>& globeRectangle, std::vector<CesiumGeospatial::Projection>&& projections); /** * @brief Computes a bounding region from the vertex positions in a glTF * model. * * If the glTF model spans the anti-meridian, the west and east longitude * values will be in the usual -PI to PI range, but east will have a smaller * value than west. * * @param gltf The model. * @param transform The transform from model coordinates to ECEF coordinates. * @return The computed bounding region. */ static CesiumGeospatial::BoundingRegion computeBoundingRegion( const CesiumGltf::Model& gltf, const glm::dmat4& transform); /** * @brief Applies the glTF's RTC_CENTER, if any, to the given rootTransform. * * @param gltf * @param rootTransform * @return glm::dmat4x4 */ /** * @brief Applies the glTF's RTC_CENTER, if any, to the given transform. * * If the glTF has a `CESIUM_RTC` extension, this function will multiply the * given matrix with the (translation) matrix that is created from the * `RTC_CENTER` in the. If the given model does not have this extension, then * this function will return the `rootTransform` unchanged. * * @param model The glTF model * @param rootTransform The matrix that will be multiplied with the transform * @return The result of multiplying the `RTC_CENTER` with the * `rootTransform`. */ static glm::dmat4x4 applyRtcCenter( const CesiumGltf::Model& gltf, const glm::dmat4x4& rootTransform); /** * @brief Applies the glTF's `gltfUpAxis`, if any, to the given transform. * * By default, the up-axis of a glTF model will the the Y-axis. * * If the tileset that contained the model had the `asset.gltfUpAxis` string * property, then the information about the up-axis has been stored in as a * number property called `gltfUpAxis` in the `extras` of the given model. * * Depending on whether this value is `CesiumGeometry::Axis::X`, `Y`, or `Z`, * the given matrix will be multiplied with a matrix that converts the * respective axis to be the Z-axis, as required by the 3D Tiles standard. * * @param model The glTF model * @param rootTransform The matrix that will be multiplied with the transform * @return The result of multiplying the `rootTransform` with the * `gltfUpAxis`. */ static glm::dmat4x4 applyGltfUpAxisTransform( const CesiumGltf::Model& model, const glm::dmat4x4& rootTransform); private: static CesiumGltfReader::GltfReader _gltfReader; }; } // namespace Cesium3DTilesSelection
{ "alphanum_fraction": 0.7217683105, "avg_line_length": 37.4535519126, "ext": "h", "hexsha": "4d00aa989da2245d8d1d14a50aa38fb83d7b6d91", "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": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "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": "yieryi/cesium-native", "max_issues_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "Cesium3DTilesSelection/include/Cesium3DTilesSelection/GltfContent.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1761, "size": 6854 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_roots.h> #include "cosmocalc.h" static double gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p); static double onederiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p); static double twoderiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p); static double nonlinear_gaussnorm_scale_funct(double gaussR, void *p); static double gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p) { double gaussRad = (*(double*)p); double k = exp(lnk); return linear_powspec(k,1.0)*k*k*k/2.0/M_PI/M_PI*exp(-1.0*k*k*gaussRad*gaussRad); } static double onederiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p) { double gaussRad = (*(double*)p); double k = exp(lnk); return linear_powspec(k,1.0)*k*k*k/2.0/M_PI/M_PI*exp(-1.0*k*k*gaussRad*gaussRad)*(-1.0*k*k*2.0*gaussRad); } static double twoderiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct(double lnk, void *p) { double gaussRad = (*(double*)p); double k = exp(lnk); return linear_powspec(k,1.0)*k*k*k/2.0/M_PI/M_PI*exp(-1.0*k*k*gaussRad*gaussRad)*(-2.0*k*k + 4.0*k*k*k*k*gaussRad*gaussRad); } //uses Takahashi et al. (2012) arXiv:1208.2701 unless macro below is set to use true Smith+03 //#define SMITH03 double nonlinear_powspec(double k, double a) { static int initFlag = 1; static int currCosmoNum; static gsl_spline *spline[4]; static gsl_interp_accel *accel[4]; int i; double xtab[COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH],ytab[COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH]; double Rsigma,C,neff,ksigma,sigma2; double an,bn,cn,alphan,gamman,betan,mun,nun; double f1,f2,f3; double DeltakNL,dsigma2dR,d2sigma2d2R,PkNL,PkL; double y,DeltakL,fy,DeltakQ,DeltakHprime,DeltakH; //double t; double I0,I1; double abserr; gsl_integration_workspace *workspace; gsl_function F; double gaussRad; #define WORKSPACE_NUM 10000000 #define ABSERR 1e-6 #define RELERR 0.0 if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum) { currCosmoNum = cosmoData.cosmoNum; if(initFlag) { for(i=0;i<4;++i) spline[i] = gsl_spline_alloc(gsl_interp_akima,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); for(i=0;i<4;++i) accel[i] = gsl_interp_accel_alloc(); initFlag = 0; } else { for(i=0;i<4;++i) gsl_spline_free(spline[i]); for(i=0;i<4;++i) spline[i] = gsl_spline_alloc(gsl_interp_akima,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); for(i=0;i<4;++i) gsl_interp_accel_reset(accel[i]); } //t = -wtime(); for(i=0;i<COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH;++i) { xtab[i] = i*(1.0-AEXPN_MIN_NONLINPK)/(COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH-1.0) + AEXPN_MIN_NONLINPK; ytab[i] = get_nonlinear_gaussnorm_scale(xtab[i]); } gsl_spline_init(spline[0],xtab,ytab,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); gsl_sort(ytab,(size_t) 1,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); for(i=0;i<COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH;++i) { xtab[i] = ytab[i]; ytab[i] = gaussiannorm_linear_powspec(xtab[i]); } gsl_spline_init(spline[1],xtab,ytab,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); F.params = &gaussRad; F.function = &onederiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct; for(i=0;i<COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH;++i) { gaussRad = xtab[i]; gsl_integration_qags(&F,log(1e-4),log(2.0*M_PI/gaussRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr); gsl_integration_qags(&F,log(2.0*M_PI/gaussRad),log(1e3),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr); ytab[i] = I0+I1; } gsl_spline_init(spline[2],xtab,ytab,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); F.function = &twoderiv_gaussiannorm_linear_powspec_exact_lnk_integ_funct; for(i=0;i<COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH;++i) { gaussRad = xtab[i]; gsl_integration_qags(&F,log(1e-4),log(2.0*M_PI/gaussRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr); gsl_integration_qags(&F,log(2.0*M_PI/gaussRad),log(1e3),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr); ytab[i] = I0+I1; } gsl_spline_init(spline[3],xtab,ytab,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); gsl_integration_workspace_free(workspace); #undef ABSERR #undef RELERR #undef WORKSPACE_NUM //t += wtime(); //fprintf(stderr,"comp of non-linear Pk took %f seconds.\n",t); } Rsigma = gsl_spline_eval(spline[0],a,accel[0]); sigma2 = gsl_spline_eval(spline[1],Rsigma,accel[1]); dsigma2dR = gsl_spline_eval(spline[2],Rsigma,accel[2]); d2sigma2d2R = gsl_spline_eval(spline[3],Rsigma,accel[3]); ksigma = 1.0/Rsigma; neff = -1.0*Rsigma/sigma2*dsigma2dR - 3.0; C = -1.0*(d2sigma2d2R*Rsigma*Rsigma/sigma2 + dsigma2dR*Rsigma/sigma2 - dsigma2dR*dsigma2dR*Rsigma*Rsigma/sigma2/sigma2); double ha,weffa,omegaMz,omegaDEwz; ha = hubble_noscale(a); weffa = weff(a); omegaMz = cosmoData.OmegaM/a/a/a/ha/ha; omegaDEwz = (1.0-cosmoData.OmegaM)/ha/ha/pow(a,3.0*(1.0 + weffa)); #ifdef SMITH03 an = pow(10.0,1.4861 + 1.8369*neff + 1.6762*neff*neff + 0.7940*neff*neff*neff + 0.1670*neff*neff*neff*neff - 0.6206*C); bn = pow(10.0,0.9463 + 0.9466*neff + 0.3084*neff*neff - 0.9400*C); cn = pow(10.0,-0.2807 + 0.6669*neff + 0.3214*neff*neff - 0.0793*C); gamman = 0.8649 + 0.2989*neff + 0.1631*C; alphan = 1.3884 + 0.3700*neff - 0.1452*neff*neff; betan = 0.8291 + 0.9854*neff + 0.3401*neff*neff; mun = pow(10.0,-3.5442 + 0.1908*neff); nun = pow(10.0,0.9589 + 1.2857*neff); f1 = pow(OmegaMz,-0.0307); f2 = pow(OmegaMz,-0.0585); f3 = pow(OmegaMz,0.0743); #else an = pow(10.0,1.5222 + 2.8553*neff + 2.3706*neff*neff + 0.9903*neff*neff*neff + 0.2250*neff*neff*neff*neff - 0.6038*C + 0.1749*omegaDEwz*(1.0 + weffa)); bn = pow(10.0,-0.5642 + 0.5864*neff + 0.5716*neff*neff - 1.5474*C + 0.2279*omegaDEwz*(1.0 + weffa)); cn = pow(10.0,0.3698 + 2.0404*neff + 0.8161*neff*neff + 0.5869*C); gamman = 0.1971 - 0.0843*neff + 0.8460*C; alphan = fabs(6.0835 + 1.3373*neff - 0.1959*neff*neff - 5.5274*C); betan = 2.0379 - 0.7354*neff + 0.3157*neff*neff + 1.2490*neff*neff*neff + 0.3980*neff*neff*neff*neff - 0.1682*C; mun = 0.0; nun = pow(10.0,5.2105 + 3.6902*neff); f1 = pow(omegaMz,-0.0307); f2 = pow(omegaMz,-0.0585); f3 = pow(omegaMz,0.0743); #endif PkL = linear_powspec(k,a); y = k/ksigma; fy = y/4.0 + y*y/8.0; DeltakL = PkL*k*k*k/2.0/M_PI/M_PI; DeltakQ = DeltakL*pow(1.0 + DeltakL,betan)/(1.0 + alphan*DeltakL)*exp(-1.0*fy); DeltakHprime = an*pow(y,3.0*f1)/(1.0 + bn*pow(y,f2) + pow(cn*f3*y,3.0 - gamman)); DeltakH = DeltakHprime/(1.0 + mun/y + nun/y/y); DeltakNL = DeltakQ + DeltakH; PkNL = DeltakNL/(k*k*k/2.0/M_PI/M_PI); return PkNL; } double gaussiannorm_linear_powspec(double gaussRad) { #define PNL_RGAUSS_MIN 0.0001 #define PNL_RGAUSS_MAX 100.0 #define WORKSPACE_NUM 10000000 #define ABSERR 1e-6 #define RELERR 0.0 static int initFlag = 1; static int currCosmoNum; static gsl_spline *spline = NULL; static gsl_interp_accel *accel = NULL; double I0,I1; double abserr; gsl_integration_workspace *workspace; gsl_function F; int i; double xtab[COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH]; double ytab[COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH]; double dlnr; double lnrmin; double lnr; if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum) { initFlag = 0; currCosmoNum = cosmoData.cosmoNum; workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM); F.function = &gaussiannorm_linear_powspec_exact_lnk_integ_funct; dlnr = log(PNL_RGAUSS_MAX/PNL_RGAUSS_MIN)/(COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH-1.0); lnrmin = log(PNL_RGAUSS_MIN); for(i=0;i<COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH;++i) { lnr = dlnr*i + lnrmin; xtab[i] = exp(lnr); F.params = &(xtab[i]); gsl_integration_qags(&F,log(1e-4),log(2.0*M_PI/gaussRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr); gsl_integration_qags(&F,log(2.0*M_PI/gaussRad),log(1e3),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr); //gsl_integration_qagil(&F,log(2.0*M_PI/gaussRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I0,&abserr); //gsl_integration_qagiu(&F,log(2.0*M_PI/gaussRad),ABSERR,RELERR,(size_t) WORKSPACE_NUM,workspace,&I1,&abserr); xtab[i] = lnr; ytab[i] = log(I0+I1); } gsl_integration_workspace_free(workspace); if(spline != NULL) gsl_spline_free(spline); spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); gsl_spline_init(spline,xtab,ytab,(size_t) (COSMOCALC_NONLINEAR_POWSPEC_TABLE_LENGTH)); if(accel != NULL) gsl_interp_accel_reset(accel); else accel = gsl_interp_accel_alloc(); #undef ABSERR #undef RELERR #undef WORKSPACE_NUM #undef PNL_RGAUSS_MIN #undef PNL_RGAUSS_MAX } return exp(gsl_spline_eval(spline,log(gaussRad),accel)); } static double nonlinear_gaussnorm_scale_funct(double gaussR, void *p) { double gf = ((double*)p)[0]; return gaussiannorm_linear_powspec(gaussR)*gf*gf-1.0; } double get_nonlinear_gaussnorm_scale(double a) { double gf = growth_function(a); double Rsigma,Rlow=0.001,Rhigh=10.0; int itr,maxItr=1000,status; #define ABSERR 1e-6 #define RELERR 1e-6 const gsl_root_fsolver_type *T; gsl_root_fsolver *s; gsl_function F; F.function = &nonlinear_gaussnorm_scale_funct; F.params = &gf; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s,&F,Rlow,Rhigh); itr = 0; do { itr++; status = gsl_root_fsolver_iterate(s); Rsigma = gsl_root_fsolver_root(s); Rlow = gsl_root_fsolver_x_lower(s); Rhigh = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(Rlow,Rhigh,ABSERR,RELERR); } while(status == GSL_CONTINUE && itr < maxItr); #undef ABSERR #undef RELERR gsl_root_fsolver_free(s); return Rsigma; }
{ "alphanum_fraction": 0.6998382647, "avg_line_length": 32.9498432602, "ext": "c", "hexsha": "e37f78558862cf6777e4d3e9137de7bc0597be4e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_path": "src/nonlinear_powspec.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_path": "src/nonlinear_powspec.c", "max_line_length": 154, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_path": "src/nonlinear_powspec.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4028, "size": 10511 }
#include <cblas.h>
{ "alphanum_fraction": 0.7222222222, "avg_line_length": 18, "ext": "h", "hexsha": "f6e0a41cc7aaf9e4a8f3bc6165bfe31080a32a79", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:25:21.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-03T05:29:38.000Z", "max_forks_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Max0u/NDArray", "max_forks_repo_path": "Sources/C/CBlas/cblas.h", "max_issues_count": 14, "max_issues_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_issues_repo_issues_event_max_datetime": "2020-04-22T03:44:41.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-02T06:07:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Max0u/NDArray", "max_issues_repo_path": "Sources/C/CBlas/cblas.h", "max_line_length": 18, "max_stars_count": 66, "max_stars_repo_head_hexsha": "49c5f1ec9958a73afde90842c57995d8de9f57b7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Max0u/NDArray", "max_stars_repo_path": "Sources/C/CBlas/cblas.h", "max_stars_repo_stars_event_max_datetime": "2021-12-22T04:55:11.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-02T01:36:02.000Z", "num_tokens": 6, "size": 18 }
#pragma once #include <fstream> #include <memory> #include <optional> #include <sstream> #include <utility> #include <gsl/pointers> #include <fmt/core.h> #include <fmt/ranges.h> #include <nop/serializer.h> #include <nop/status.h> #include <nop/structure.h> #include <nop/utility/die.h> #include <nop/utility/stream_reader.h> #include <nop/utility/stream_writer.h> #include <core/Util.h> #include <core/storage/Page.h> #include <core/storage/PageCache.h> #include <core/storage/btree/Config.h> #include <core/storage/btree/Node.h> namespace internal::storage::btree { namespace util { template<BtreeConfig Config = DefaultConfig> class BtreePrinter; } template<BtreeConfig Config = DefaultConfig> class Btree final { using Self = Btree<Config>; using Key = typename Config::Key; using Val = typename Config::Val; using Ref = typename Config::Ref; using Nod = Node<Config>; friend util::BtreePrinter<Config>; public: //! Number of entries in branch and leaf nodes may differ //! Directly unwrap with `.value()` since we _want to fail at compile time_ in case their is no value which //! satisfies the predicates int NUM_LINKS_BRANCH = ::internal::binsearch_primitive(2l, Page::size(), [](long current, long, long) { return nop::Encoding<Nod>::Size({typename Nod::Metadata(typename Nod::Branch(std::vector<Ref>(current), std::vector<Position>(current))), {}, true}) - Page::size(); }).value(); int NUM_RECORDS_BRANCH = NUM_LINKS_BRANCH - 1; //! Equivalent to `m` in Knuth's definition //! Make sure that when a leaf is split, its contents could be distributed among the two branch nodes. //! Directly unwrap with `.value()` since we _want to fail at compile time_ in case their is no value which //! satisfies the predicates int _NUM_RECORDS_LEAF = ::internal::binsearch_primitive(2l, Page::size(), [](long current, long, long) { return nop::Encoding<Nod>::Size({typename Nod::Metadata(typename Nod::Leaf(std::vector<Key>(current), std::vector<Val>(current))), {}, true}) - Page::size(); }).value(); int NUM_RECORDS_LEAF = _NUM_RECORDS_LEAF - 1 >= NUM_RECORDS_BRANCH * 2 ? NUM_RECORDS_BRANCH * 2 - 1 : _NUM_RECORDS_LEAF; private: static inline constexpr bool APPLY_COMPRESSION = Config::APPLY_COMPRESSION; static inline constexpr int PAGE_CACHE_SIZE = Config::PAGE_CACHE_SIZE; static inline constexpr uint32_t MAGIC = 0xB75EEA41; public: struct Header { Position m_rootpos; std::size_t m_size{}; std::size_t m_depth{}; uint32_t m_magic{MAGIC}; uint32_t m_pgcache_size{PAGE_CACHE_SIZE}; uint8_t m_apply_compression{APPLY_COMPRESSION}; /* * The storage locations of the tree header and the tree contents differ. * This one stores the name of the file which contains the header of the tree, * whereas the other name passed to the Btree constructor is the one where * the actual nodes of the tree are stored. */ std::string m_content_file; /* * We don't want to serialize this. It is used only to check whether the header * we are currently possessing is valid. */ bool m_dirty{false}; Header() = default; explicit Header(Position rootpos, std::size_t size, std::size_t depth, std::string_view content_file) : m_rootpos{rootpos}, m_size{size}, m_depth{depth}, m_content_file{std::string{content_file}} {} [[nodiscard]] auto &rootpos() noexcept { return m_rootpos; } [[nodiscard]] auto &size() noexcept { return m_size; } [[nodiscard]] auto &depth() noexcept { return m_depth; } [[nodiscard]] auto &dirty() noexcept { return m_dirty; } auto operator<=>(const Header &) const noexcept = default; friend std::ostream &operator<<(std::ostream &os, const Header &h) { os << "Header { .rootpos = " << h.m_rootpos << ", .size =" << h.m_size << ", .depth =" << h.m_depth << " }"; return os; } NOP_STRUCTURE(Header, m_rootpos, m_size, m_depth, m_magic, m_pgcache_size, m_apply_compression, m_content_file); }; private: [[nodiscard]] bool is_node_full(const Self::Nod &node) { if (node.is_branch()) return node.is_full(NUM_RECORDS_BRANCH); return node.is_full(NUM_RECORDS_LEAF); } [[nodiscard]] auto node_split(Self::Nod &node) { if (node.is_branch()) return node.split(NUM_RECORDS_BRANCH); return node.split(NUM_RECORDS_LEAF); } [[nodiscard]] std::optional<Val> search_subtree(const Self::Nod &node, const Self::Key &target_key) const noexcept { if (node.is_branch()) { const auto &refs = node.branch().m_refs; const std::size_t index = std::lower_bound(refs.cbegin(), refs.cend(), target_key) - refs.cbegin(); const Position pos = node.branch().m_links[index]; const auto other = Nod::from_page(m_pgcache.get_page(pos)); return search_subtree(other, target_key); } assert(node.is_leaf()); const auto &keys = node.leaf().m_keys; const auto &vals = node.leaf().m_vals; const auto it = std::lower_bound(keys.cbegin(), keys.cend(), target_key); if (it == keys.cend() || *it != target_key) return {}; return vals[it - keys.cbegin()]; } Nod make_new_root() { auto old_root = root(); auto old_pos = m_rootpos; auto new_pos = m_pgcache.get_new_pos(); old_root.set_parent(new_pos); old_root.set_root(false); auto [midkey, sibling] = node_split(old_root); auto sibling_pos = m_pgcache.get_new_pos(); Nod new_root{typename Nod::Metadata(typename Nod::Branch({midkey}, {old_pos, sibling_pos})), new_pos, true}; m_pgcache.put_page(new_pos, new_root.make_page()); m_pgcache.put_page(old_pos, old_root.make_page()); m_pgcache.put_page(sibling_pos, sibling.make_page()); m_rootpos = new_pos; ++m_depth; m_header.m_dirty = true; return new_root; } public: [[nodiscard]] auto root() noexcept { return std::as_const(*this).root(); } [[nodiscard]] auto root() const noexcept { return Nod::from_page(m_pgcache.get_page(rootpos())); } [[nodiscard]] auto &header() noexcept { return m_header; } [[nodiscard]] const auto &rootpos() const noexcept { return m_rootpos; } [[nodiscard]] std::size_t size() noexcept { return m_size; } [[nodiscard]] std::size_t size() const noexcept { return m_size; } [[nodiscard]] bool empty() const noexcept { return size() == 0; } [[nodiscard]] bool empty() noexcept { return size() == 0; } [[nodiscard]] std::size_t depth() { return m_depth; } [[nodiscard]] auto num_records_leaf() const noexcept { return NUM_RECORDS_LEAF; } [[nodiscard]] auto num_records_branch() const noexcept { return NUM_RECORDS_BRANCH; } public: /* * Operations API */ void put(const Self::Key &key, const Self::Val &val) { Position currpos{rootpos()}; Nod curr{root()}; if (is_node_full(curr)) curr = make_new_root(); while (true) { if (curr.is_leaf()) { /* fmt::print(" -- Putting kv pair in leaf ... \n"); */ auto &keys = curr.leaf().m_keys; auto &vals = curr.leaf().m_vals; const std::size_t index = std::lower_bound(keys.cbegin(), keys.cend(), key) - keys.cbegin(); if (!keys.empty() && index < keys.size() && keys[index] == key) return; keys.insert(keys.begin() + index, key); vals.insert(vals.begin() + index, val); m_pgcache.put_page(currpos, curr.make_page()); ++m_size; break; } auto &refs = curr.branch().m_refs; auto &links = curr.branch().m_links; const std::size_t index = std::lower_bound(refs.cbegin(), refs.cend(), key) - refs.cbegin(); const Position child_pos = links[index]; assert(child_pos.is_set()); auto child = Nod::from_page(m_pgcache.get_page(child_pos)); if (!is_node_full(child)) { currpos = child_pos; curr = std::move(child); continue; } auto [midkey, sibling] = node_split(child); auto sibling_pos = m_pgcache.get_new_pos(); assert(std::find(refs.cbegin(), refs.cend(), midkey) == refs.cend()); assert(std::find(links.cbegin(), links.cend(), sibling_pos) == links.cend()); refs.insert(refs.begin() + index, midkey); links.insert(links.begin() + index + 1, sibling_pos); m_pgcache.put_page(sibling_pos, std::move(sibling.make_page())); m_pgcache.put_page(child_pos, std::move(child.make_page())); m_pgcache.put_page(currpos, std::move(curr.make_page())); if (key < midkey) { currpos = child_pos; curr = std::move(child); } else if (key > midkey) { currpos = sibling_pos; curr = std::move(sibling); } } } [[nodiscard]] std::optional<Val> get(const Self::Key &key) const noexcept { return search_subtree(root(), key); } [[nodiscard]] bool contains(const Self::Key &key) const noexcept { return search_subtree(root(), key).has_value(); } private: void save_header() const noexcept { if (m_header.dirty()) { m_header.rootpos() = m_rootpos; m_header.size() = m_size; m_header.dirty() = false; } nop::Serializer<nop::StreamWriter<std::ofstream>> serializer{m_header_name.data(), std::ios::trunc}; serializer.Write(m_header) || nop::Die(std::cerr); } bool load_header() { nop::Deserializer<nop::StreamReader<std::ifstream>> deserializer{m_header_name.data()}; deserializer.Read(&m_header) || nop::Die(std::cerr); std::cout << m_header << "\n"; return true; } void bare_init() noexcept { m_rootpos = m_pgcache.get_new_pos(); Nod root_initial{typename Nod::Metadata(typename Nod::Leaf({}, {})), m_rootpos, true}; m_pgcache.put_page(m_rootpos, std::move(root_initial.make_page())); // Fill in initial header m_header.rootpos() = m_rootpos; m_header.size() = m_size; m_header.depth() = m_depth; } public: /* * Persistence API */ void load() { auto ok = load_header(); assert(ok); m_rootpos = m_header.m_rootpos; m_size = m_header.m_size; m_depth = m_header.m_depth; } void save() const { save_header(); m_pgcache.flush_all(); } public: explicit Btree(std::string_view pgcache_name, std::string_view btree_header_name = "/tmp/eu-btree-header", bool should_load = false) : m_pgcache{pgcache_name, PAGE_CACHE_SIZE}, m_header_name{btree_header_name} { assert(NUM_RECORDS_BRANCH > 1); assert(NUM_RECORDS_LEAF > 1); if (should_load) load(); else bare_init(); } private: mutable PageCache m_pgcache; mutable Header m_header; const std::string_view m_header_name; Position m_rootpos; std::size_t m_size{0}; std::size_t m_depth{0}; }; }// namespace internal::storage::btree
{ "alphanum_fraction": 0.6853564547, "avg_line_length": 29.8275862069, "ext": "h", "hexsha": "37f04e39d3e5514a17d35cce3a3cbeb84aca5ae3", "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": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "boki1/eugene", "max_forks_repo_path": "src/core/storage/btree/Btree.h", "max_issues_count": 12, "max_issues_repo_head_hexsha": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_issues_repo_issues_event_max_datetime": "2022-03-05T14:46:33.000Z", "max_issues_repo_issues_event_min_datetime": "2021-09-01T08:41:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "boki1/eugene", "max_issues_repo_path": "src/core/storage/btree/Btree.h", "max_line_length": 181, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fceedc2d535715ce40d9c80e62fb61e2b26e78ef", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "boki1/eugene", "max_stars_repo_path": "src/core/storage/btree/Btree.h", "max_stars_repo_stars_event_max_datetime": "2021-09-01T05:17:05.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-01T05:17:05.000Z", "num_tokens": 2799, "size": 10380 }
#ifndef DBJ_FLOAT_VARIOUS_MATMULS_INC #define DBJ_FLOAT_VARIOUS_MATMULS_INC #include "dbj_matrix.h" #include <stdlib.h> #include <intrin.h> // #define __SSE__ 1 #ifdef HAVE_CBLAS #include <cblas.h> #endif #undef DBJ_API #define DBJ_API ////////////////////////////////////////////////////////////////////// // all of the bellow uses: typedef DBJ_MATRIX_STRUCT(float) float_matrix_struct; ////////////////////////////////////////////////////////////////////// typedef void* (*mat_mul_function) ( const unsigned, const unsigned, const unsigned, float a[][*], float b[][*], float m[][*] ); typedef struct { const char* description; mat_mul_function function; } description_function_pair; #define DF_PAIR(D_,F_) (description_function_pair){ .description = D_ , .function = F_ } ////////////////////////////////////////////////////////////////////// DBJ_API float_matrix_struct* new_float_matrix(const unsigned /*n_rows*/, const unsigned /*n_cols*/); DBJ_API float_matrix_struct* make_random_float_matrix( const unsigned /*n_rows*/, const unsigned /*n_cols*/, float (*)(void) ); DBJ_API void* mat_transpose( const unsigned /*n_rows*/, const unsigned /*n_cols*/, float /*a*/[/*static n_rows*/][*/*n_cols*/], float /*m*/[/*static n_cols*/][*/*n_rows*/] ); DBJ_API void* mat_mul_null( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { // used for when algorithms are not implemented yet (void)a; (void)b; (void)m; return NULL; } DBJ_API void* mat_mul_0(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); DBJ_API void* mat_mul_1(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); DBJ_API void* mat_mul_3(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); DBJ_API void* mat_mul_4(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); #if __SSE__ DBJ_API void* mat_mul_2(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); DBJ_API void* mat_mul_7(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); #endif // __SSE__ #ifdef HAVE_CBLAS DBJ_API void* mat_mul_5(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); DBJ_API void* mat_mul_6(const unsigned /*n_a_rows*/, const unsigned /*n_a_cols*/, const unsigned /*n_b_cols*/, float a[ /*n_a_rows*/][* /*n_a_cols*/], float b[ /*n_a_rows*/][* /*n_b_cols*/], float m[ /*n_a_rows*/][* /*n_b_cols*/] ); #endif // HAVE_CBLAS const description_function_pair dbj_float_matmuls_algo_table[] = { DF_PAIR("0: naive - no optimization" , mat_mul_0) , DF_PAIR("1: transposing the second matrix" , mat_mul_1) , DF_PAIR("2: explicitly vectorized sdot() with SSE" , mat_mul_2) , /* requires __SSE__ */ DF_PAIR("3: implicitly vectorized sdot()" , mat_mul_3) , DF_PAIR("4: no vectorization hints", mat_mul_4) , #ifdef HAVE_CBLAS DF_PAIR("5: with sdot() from an external CBLAS library" , mat_mul_5) , DF_PAIR("6: with sgemm() from an external CBLAS library", mat_mul_6) , #else DF_PAIR("5: with sdot() from CBLAS library not implemented " , mat_mul_null) , DF_PAIR("6: with sgemm() from CBLAS library not implemented ", mat_mul_null) , #endif // ! HAVE_CBLAS DF_PAIR("7: explicitly SSE sdot() plus loop tiling", mat_mul_7) /* requires __SSE__ */ }; static const unsigned dbj_float_matmuls_algo_table_size = (sizeof(dbj_float_matmuls_algo_table) / sizeof(dbj_float_matmuls_algo_table[0])); ////////////////////////////////////////////////////////////////////// #ifdef DBJ_FLOAT_VARIOUS_MATMULS_IMPLEMENTATION ////////////////////////////////////////////////////////////////////// DBJ_API float_matrix_struct* new_float_matrix(const unsigned n_rows, const unsigned n_cols) { // float_matrix_struct* retval = NULL; // must be init to NULL float_matrix_struct* retval = DBJ_MATRIX_ALLOC(n_rows, n_cols, DBJ_MATRIX_STRUCT_SIZE(float, n_rows, n_cols)); if (retval) { retval->rows = n_rows; retval->cols = n_cols; } else { fprintf(stderr, "\n%s(%d) DBJ_MATRIX_NEW failed?\n", __FILE__, __LINE__); perror(" "); exit(1); } return retval; } /* allocate new matrix and populate it with random float's */ DBJ_API float_matrix_struct* make_random_float_matrix( const unsigned n_rows, const unsigned n_cols, float (*float_rand)(void) ) { float_matrix_struct* fmt_pointer = new_float_matrix(n_rows, n_cols); DBJ_MATRIX_ALIAS(matrix, float, n_cols); DBJ_MATRIX_CAST(mx, matrix, fmt_pointer); for (unsigned i = 0; i < n_rows; ++i) for (unsigned j = 0; j < n_cols; ++j) mx[i][j] = float_rand(); // return fmt_pointer; } DBJ_API void* mat_transpose( const unsigned n_rows, const unsigned n_cols, float a[static n_rows][n_cols], float m[static n_cols][n_rows] ) { for (unsigned i = 0; i < n_rows; ++i) for (unsigned j = 0; j < n_cols; ++j) m[j][i] = a[i][j]; return m; } DBJ_API float sdot_1(int n, const float x[static n], const float y[static n]) { float s = 0.0f; for (int i = 0; i < n; ++i) s += x[i] * y[i]; return s; } DBJ_API float sdot_8(int n, const float x[static n], const float y[static n]) { int i, n8 = n >> 3 << 3; float s = 0.0f, t[8] = { 0.0f }; // t[0] = t[1] = t[2] = t[3] = t[4] = t[5] = t[6] = t[7] = 0.0f; for (i = 0; i < n8; i += 8) { t[0] += x[i + 0] * y[i + 0]; t[1] += x[i + 1] * y[i + 1]; t[2] += x[i + 2] * y[i + 2]; t[3] += x[i + 3] * y[i + 3]; t[4] += x[i + 4] * y[i + 4]; t[5] += x[i + 5] * y[i + 5]; t[6] += x[i + 6] * y[i + 6]; t[7] += x[i + 7] * y[i + 7]; } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; s += t[0] + t[1] + t[2] + t[3] + t[4] + t[5] + t[6] + t[7]; return s; } #ifdef __SSE__ DBJ_API float sdot_sse(int n, const float x[static n], const float y[static n]) { int i, n8 = n >> 3 << 3; __m128 vs1, vs2; float s, t[4]; vs1 = _mm_setzero_ps(); vs2 = _mm_setzero_ps(); for (i = 0; i < n8; i += 8) { __m128 vx1, vx2, vy1, vy2; vx1 = _mm_loadu_ps(&x[i]); vx2 = _mm_loadu_ps(&x[i + 4]); vy1 = _mm_loadu_ps(&y[i]); vy2 = _mm_loadu_ps(&y[i + 4]); vs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1)); vs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2)); } for (s = 0.0f; i < n; ++i) s += x[i] * y[i]; _mm_storeu_ps(t, vs1); s += t[0] + t[1] + t[2] + t[3]; _mm_storeu_ps(t, vs2); s += t[0] + t[1] + t[2] + t[3]; return s; } #endif // __SSE__ /************************************************** Various Matrix multiplication algorithms NOTE: check and choose for your RT Env there are differences but are *very* dependant on compiler, OS and hardware */ DBJ_API void* mat_mul_0( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { for (unsigned i = 0; i < n_a_rows; ++i) { for (unsigned j = 0; j < n_b_cols; ++j) { float t = 0.0; for (unsigned k = 0; k < n_a_cols; ++k) t += a[i][k] * b[k][j]; m[i][j] = t; } } return m; } DBJ_API void* mat_mul_1( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { const unsigned n_b_rows = n_a_cols; // Temp rows and cols are inverted float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) { const float* ai = a[i]; float* mi = m[i]; for (unsigned j = 0; j < n_b_cols; ++j) { float t = 0.0f, * bTj = bT[j]; for (unsigned k = 0; k < n_a_cols; ++k) t += ai[k] * bTj[k]; mi[j] = t; } } free(Temp); return m; } DBJ_API void* mat_mul_2( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { #ifndef __SSE__ #error __SEE__ is required here #endif const unsigned n_b_rows = n_a_cols; float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = sdot_sse(n_a_cols, a[i], bT[j]); free(Temp); return m; } DBJ_API void* mat_mul_7( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { #ifndef __SSE__ #error __SEE__ is required here #endif const unsigned x = 16, n_b_rows = n_a_cols; float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; i += x) { for (unsigned j = 0; j < n_b_cols; j += x) { unsigned je = n_b_cols < j + x ? n_b_cols : j + x; unsigned ie = n_a_rows < i + x ? n_a_rows : i + x; for (unsigned ii = i; ii < ie; ++ii) for (unsigned jj = j; jj < je; ++jj) m[ii][jj] += sdot_sse(n_a_cols, a[ii], bT[jj]); } } free(Temp); return m; } ///////////////////////////////////////////////////////////////////////////////////// DBJ_API void* mat_mul_3( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { int n_b_rows = n_a_cols; float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = sdot_8(n_a_cols, a[i], bT[j]); free(Temp); return m; } DBJ_API void* mat_mul_4( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { int n_b_rows = n_a_cols; float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = sdot_1(n_a_cols, a[i], bT[j]); free(Temp); return m; } #ifdef HAVE_CBLAS DBJ_API void* mat_mul_5( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { const unsigned n_b_rows = n_a_cols; float_matrix_struct* Temp = new_float_matrix(n_b_cols, n_b_rows); DBJ_MATRIX_ALIAS(matrix, float, n_b_rows); DBJ_MATRIX_CAST(bT, matrix, Temp); (void)mat_transpose(n_b_rows, n_b_cols, b, bT); for (unsigned i = 0; i < n_a_rows; ++i) for (unsigned j = 0; j < n_b_cols; ++j) m[i][j] = cblas_sdot(n_a_cols, a[i], 1, bT[j], 1); // clas_sdot() ??? free(Temp); return m; } DBJ_API void* mat_mul_6( const unsigned n_a_rows, const unsigned n_a_cols, const unsigned n_b_cols, float a[static n_a_rows][n_a_cols], float b[static n_a_rows][n_b_cols], float m[static n_a_rows][n_b_cols] ) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_a_rows, n_b_cols, n_a_cols, 1.0f, a[0], n_a_rows, b[0], n_b_rows, 0.0f, m[0], n_a_rows); return m; } #endif // HAVE_CBLAS ////////////////////////////////////////////////////////////////////// #endif // DBJ_FLOAT_VARIOUS_MATMULS_IMPLEMENTATION ////////////////////////////////////////////////////////////////////// #undef DF_PAIR #endif // DBJ_FLOAT_VARIOUS_MATMULS_INC
{ "alphanum_fraction": 0.6375427151, "avg_line_length": 32.0298507463, "ext": "h", "hexsha": "b10c4632a354f35e90a75decf408e981c73589bd", "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": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "DBJDBJ/dbj_matmul", "max_forks_repo_path": "r_and_d/dbj_float_various_matmuls.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "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": "DBJDBJ/dbj_matmul", "max_issues_repo_path": "r_and_d/dbj_float_various_matmuls.h", "max_line_length": 146, "max_stars_count": null, "max_stars_repo_head_hexsha": "e1f1c6ce0724afa3afb8d38bcc63e4772b9f2866", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "DBJDBJ/dbj_matmul", "max_stars_repo_path": "r_and_d/dbj_float_various_matmuls.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4211, "size": 12876 }
/*! \file ExtremaRootFinding.h * \brief header file for finding roots and extrema of a function \todo not implemented yet */ #ifndef MINMAXROOT_H #define MINMAXROOT_H #include <cmath> #include <iostream> #include <gsl/gsl_math.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <Precision.h> #include <Function.h> #include <Matrix.h> #include <GMatrix.h> #include <Interpolate.h> using namespace std; namespace Math { //// Brent bracket search for extrema //Double_t Brent(); } #endif
{ "alphanum_fraction": 0.7229965157, "avg_line_length": 19.1333333333, "ext": "h", "hexsha": "1f52f1fee5f230d8d46ea3c7eb73bf60187618da", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z", "max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_path": "src/Math/ExtremaRootFinding.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ICRAR/NBodylib", "max_issues_repo_path": "src/Math/ExtremaRootFinding.h", "max_line_length": 66, "max_stars_count": null, "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_path": "src/Math/ExtremaRootFinding.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 154, "size": 574 }
/* ** ECM - eigenvector centrality mapping, I/O interface ** ** G.Lohmann, MPI-KYB, updated Oct 2018 */ #include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ #define SQR(x) ((x) * (x)) #define ReLU(x) ((x) > 0 ? (x) : 0) VImage WriteOutput(VAttrList list,VImage map,float *eigvec,size_t n) { size_t i; int b,r,c; int nrows=0,ncols=0,ntimesteps=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&ntimesteps,&nrows,&ncols); VImage dest = VCreateImage(nslices,nrows,ncols,VFloatRepn); VFillImage(dest,VAllBands,0); VCopyImageAttrs (src[0], dest); VSetAttr(VImageAttrList(dest),"modality",NULL,VStringRepn,"ECM"); for (i=0; i<n; i++) { b = VPixel(map,0,0,i,VInteger); r = VPixel(map,0,1,i,VInteger); c = VPixel(map,0,2,i,VInteger); if (b < 0 || r < 0 || c < 0) VError(" WriteOutput: illegal address %d %d %d",b,r,c); VPixel(dest,b,r,c,VFloat) = eigvec[i]; } return dest; } void NormalizeData(gsl_matrix_float *X,int nt) { int i,j; double s1,s2,mean,sd,u,nx,tiny=1.0e-6; float *arr=NULL; nx = (double)nt; for (i=0; i<X->size1; i++) { s1=s2=0; arr = gsl_matrix_float_ptr(X,i,0); for (j=0; j<nt; j++) { u = (double)arr[j]; s1 += u; s2 += u*u; } mean = s1/nx; sd = sqrt((s2 - nx * mean * mean) / (nx - 1.0)); arr = gsl_matrix_float_ptr(X,i,0); for (j=0; j<nt; j++) { u = (double)arr[j]; if (sd > tiny) arr[j] = (float)((u-mean)/sd); else arr[j] = 0; } } for (i=0; i<X->size1; i++) { for (j=0; j<X->size2; j++) { double u = (double)gsl_matrix_float_get(X,i,j); if (gsl_isnan(u) || gsl_isinf(u)) gsl_matrix_float_set(X,i,j,0); } } } VImage VoxelMap(VAttrList list,VImage mask,size_t nvox) { int b,r,c; /* read image dims */ int nrows=0,ncols=0,ntimesteps=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&ntimesteps,&nrows,&ncols); /* voxel addresses */ VImage map = VCreateImage(1,5,nvox,VIntegerRepn); if (map == NULL) VError(" error allocating addr map"); VFillImage(map,VAllBands,0); VPixel(map,0,3,0,VInteger) = nslices; VPixel(map,0,3,1,VInteger) = nrows; VPixel(map,0,3,2,VInteger) = ncols; int i = 0; for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { if (VGetPixel(mask,b,r,c) < 0.1) continue; VPixel(map,0,0,i,VInteger) = b; VPixel(map,0,1,i,VInteger) = r; VPixel(map,0,2,i,VInteger) = c; i++; } } } return map; } /* count number of voxels */ size_t NumVoxels(VImage mask) { int b,r,c; size_t nvox = 0; for (b=0; b<VImageNBands(mask); b++) { for (r=0; r<VImageNRows(mask); r++) { for (c=0; c<VImageNColumns(mask); c++) { if (VGetPixel(mask,b,r,c) < 0.1) continue; nvox++; } } } fprintf(stderr," nvoxels: %ld\n",(long)nvox); return nvox; } gsl_matrix_float *ReadDataECM(VAttrList list,VImage mask,VImage map,VShort first,VShort length,int type,size_t nvox) { size_t i,j; int b,r,c; /* read image dims */ int nrows=0,ncols=0,ntimesteps=0,nt=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&ntimesteps,&nrows,&ncols); if (VImageNRows(mask) != nrows) VError(" inconsistent image dims, mask has %d rows, image has %d rows",VImageNRows(mask),nrows); if (VImageNColumns(mask) != ncols) VError(" inconsistent image dims, mask has %d columns, image has %d columns",VImageNColumns(mask),ncols); if (VImageNBands(mask) != nslices) VError(" inconsistent image dims, mask has %d slices, image has %d slices",VImageNBands(mask),nslices); /* get time steps to include */ if (length < 1) length = ntimesteps-1; int last = first + length; if (last >= ntimesteps) last = ntimesteps-1; if (first < 0) first = 0; nt = last - first + 1; if (nt < 2) VError(" not enough timesteps, nt= %d",nt); fprintf(stderr," ntimesteps: %d, first= %d, last= %d, nt= %d\n", (int)ntimesteps,(int)first,(int)last,(int)nt); /* alloc and fill matrix X */ size_t dim = nt; if (type == 0 || type == 7) dim = 2*nt; gsl_matrix_float *X = gsl_matrix_float_calloc(nvox,dim); for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VInteger); r = VPixel(map,0,1,i,VInteger); c = VPixel(map,0,2,i,VInteger); float *ptr = gsl_matrix_float_ptr(X,i,0); int k; j = 0; for (k=first; k<=last; k++) { if (j >= X->size2) VError(" j= %d %d",j,X->size2); if (k >= VImageNBands(src[b])) VError(" k= %d %d",k, VImageNBands(src[b])); *ptr++ = (float) VGetPixel(src[b],k,r,c); j++; } } /* normalize */ NormalizeData(X,nt); return X; }
{ "alphanum_fraction": 0.6118819621, "avg_line_length": 25.4577114428, "ext": "c", "hexsha": "99506ce18460666ff8327f7ec7b88ae7d5e73c86", "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/nets/vecm/ECM_IO.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/nets/vecm/ECM_IO.c", "max_line_length": 116, "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/nets/vecm/ECM_IO.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": 1838, "size": 5117 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_sscal (const int N, const float alpha, float *X, const int incX) { #define BASE float #include "source_scal_r.h" #undef BASE }
{ "alphanum_fraction": 0.7298578199, "avg_line_length": 17.5833333333, "ext": "c", "hexsha": "e4a83348515792301cc1d7e63b186fa1c7afb9b1", "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/sscal.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/sscal.c", "max_line_length": 70, "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/sscal.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": 65, "size": 211 }
// Sammlung verwendeter Funktionen #include "global.h" #include "steppmethods.h" #include "targets.h" #include <gsl/gsl_cblas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_gamma.h> #include <math.h> #include <stdio.h> #include "utility.h" #include <string.h> #include <time.h> #include <omp.h> double Norm_Diff(double *vec1,double *vec2, int dim, int p) //berechnet norm von || vec1-vec2 ||_p { double result = 0.0d; double temp; if (p == 1) { for (int i = 0; i < DIM; i++) { result += fabs(vec1[i] - vec2[i]); } return(result); } if (p == 2) { for (int i = 0; i < DIM; i++) { result += pow(vec1[i] - vec2[i],2.0); } return(sqrt(result)); } if (p == 0) { for (int i = 0; i < DIM; i++) { temp = fabs(vec1[i] - vec2[i]); if (result < temp) { result = temp; } } return(result); } return (0.0f); } void Lattice_Setup(double **positions,int numbertoinf,int dim, double latticespacing) // puts coordinates into lattice matrix of dimension numbertoinf**dim, dim { printf("setze Gitter auf \n"); int m = -numbertoinf + 1; int l = -numbertoinf + 1; int count = 0; while(count<ipow(numbertoinf,dim)) { if (m> (numbertoinf - 1) ) // if over line, restart { m = -numbertoinf +1; l = l + 2; } positions[count][0] = m * latticespacing/2; positions[count][1] = l * latticespacing/2; m = m + 2; count = count +1; } printf("Gitter aufgesetzt \n"); } int ipow(int base, int exp) // I^p for integer i { int result = 1; if( (base < 0)\ || (exp < 0)) { printf("wrong base or exponent, smaller zero!\n"); exit; } while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } int Kahan_Sum(int N, double input[], double *ans){ // Add elements via Kahan summation, code is pretty much Wikipedia copy paste int i; double y,t,sum = 0.0d; double c = 0.0d; // A running compensation for lost low-order bits. for (i=0; i<N; i++){ y = input[i] - c; // So far, so good: c is zero. t = sum + y; // Alas, sum is big, y small, so low-order digits of y are lost. c = (t - sum) - y; // (t - sum) cancels the high-order part of y; subtracting y recovers negative (low part of y) sum = t; // Algebraically, c should always be zero. Beware overly-aggressive optimizing compilers! } // Next time around, the lost low part will be added to y in a fresh attempt. *ans = (sum); return 0; } int Sign_Sum(int N, double *input, double *ans){ // Add seperated by sign int i; double sum = 0.0, negsum = 0.0; for (i=0; i<N; i++){ if(input[i]<0.0) negsum += input[i]; if(input[i]>=0.0) sum += input[i]; } *ans = sum + negsum; return 0; } int Neumaier_Sum(int N, double input[N], double *ans){ // Add elements of input by Neumaier summation int i; double t,sum = input[0]; double c = 0.0; // A running compensation for lost low-order bits. for (i=1; i<N; i++){ t = sum + input[i]; if (fabs(sum)>=fabs(input[i])) { c += (sum - t) + input[i]; // If sum is bigger, low-order digits of input[i] are lost. } else { c += (input[i] - t) + sum; // Else low-order digits of sum are lost } sum = t; } // Next time around, the lost low part will be added to y in a fresh attempt. *ans = (sum + c); // Correction only applied once in the very end return 0; } void deleteSpaces(char src[], char dst[]){ // deletes spaces from string // src is supposed to be zero ended // dst is supposed to be large enough to hold src int s, d=0; for (s=0; src[s] != 0; s++) if (src[s] != ' ') { dst[d] = src[s]; if (dst[d] == ':') { dst[d] = '_'; } d++; } dst[d] = 0; } void vec_zero(double *v,int N){ // zero target vector of double int i; for (i= 0 ; i < N; i++) { v[i] = 0.0; } } void vec_zero_i(int *v,int N){ // zero target vector of ints int i; for (i= 0 ; i < N; i++) { v[i] = 0; } } void zero_Impuls(double *v) { // zero target vector of momenta double P[OSSZI + 1]; double sum; double OS = OSSZI * 1.0; for (int j = 0; j < DIM; j++) { for (int i = 0; i < OSSZI; i++) { P[i] = v[DIM + i * DIM + j]; } P[OSSZI] = v[j] * mass; Sum_Method(OSSZI+1,P,&sum); for (int i = 0; i < OSSZI; i++) { v[DIM + i * DIM + j] -= sum/( OS + 1.0); } v[j] -= sum/( OS + 1.0) /mass; } } int Update_Lattice_Position(int * pos, const double *vec, const double lattice_spacing){ // updatet Int-Vector pos when leaving square lattice cell int ret_val = 0; // return zero if no update neccessary, -1 if out of bounds for (int j = 0; j< DIM; j++) { int trigger = 1; while(trigger) { if (vec[j]< pos[j]*lattice_spacing - lattice_spacing/2.0) { pos[j]-=1; trigger = 1; ret_val = 1; }else { trigger = 0; } if (vec[j]> pos[j]*lattice_spacing + lattice_spacing/2.0) { pos[j]+=1; trigger = 1; ret_val = 1; }else { trigger = 0; } } } if ((abs(pos[0])> NUMBER_TO_INF) || (abs(pos[1])> NUMBER_TO_INF)) { printf(" \n particle out of bounds"); FLAG_DUMP_VALUE = 1; // error occured return(-1); } return(ret_val); } void VVerlet(int N, double *y, double **ans, double *t, // Velocity Verlet for Start y, return ans[LengthT][ORDER] to times T void (*derivmethod) (double *y, double *ans, double t, int N)){ int i,j; for(i=0; i< N; i++){ ans[0][i] = y[i]; // give initial vec to answer } double x[N/2], v[N/2], a[N/2], z[N]; vec_zero(x,N/2); vec_zero(v,N/2); vec_zero(a,N/2); vec_zero(z,N); int current_index = 0; double current_t = t[current_index]; derivmethod(y, z, current_t, N); // get first derivative for (j = 0; j < DIM; j++ ) // bring y-p Form to x-v-a { x[j] = y[j]; v[j] = y[DIM + j]/mass; a[j] = z[DIM + j]/mass; #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { x[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM]; v[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i]; a[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i]; } } while(current_index < LENGTH_T-1) { while(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE) { //integrate till space till next time smaller than stepsize Stepper_Method(N, x, v, a, &current_t, derivmethod); } // get to y-Form current_index = current_index +1; for (j = 0; j < DIM; j++ ) { ans[current_index][DIM + j] = mass * v[j]; ans[current_index][j] = x[j]; #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { ans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM]; ans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i]; // übergib SChritt an antwort } } } } void VVerlet_parallel(const int N, const double *y, double **ans, double *t, // Velocity Verlet for Start y, return ans[LengthT][ORDER] to times T void (*derivmethod) (double *y, double *ans, double t, int N)){ int i,j; for(i=0; i< N; i++){ ans[0][i] = y[i]; // give initial vec to answer } TARGET_FLAG = 1; double x[N/2], v[N/2], a[N/2], z[N]; vec_zero(x,N/2); vec_zero(v,N/2); vec_zero(a,N/2); vec_zero(z,N); int current_index = 0; double current_t = t[current_index]; derivmethod(y, z, current_t, N); // giv f' int steps_in_intervall = 0; // counts steps done in intervall t, t+ dt int max_steps_in_intervall = 100000; // after X steps, assume error occured for (j = 0; j < DIM; j++ ) // y-p --> x-v-a form { x[j] = y[j]; VIRTUAL_X[j] = x[j]; v[j] = y[DIM + j]/mass; VIRTUAL_V[j] = v[j]; a[j] = z[DIM + j]/mass; } #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { for (j = 0; j < DIM; j++ ) { x[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM]; v[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i]; a[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i]; } } LASTSTEPSIZE = MAXSTEPSIZE; while(current_index < LENGTH_T-1) { while(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE) //integrate till space till next time smaller than stepsize { Stepper_Method(N, x, v, a, &current_t, derivmethod); steps_in_intervall++; if(steps_in_intervall > max_steps_in_intervall) { FLAG_DUMP_VALUE = 1; // too many steps, error occured printf("too many steps taken to advance one time point \n"); } if (FLAG_DUMP_VALUE) // if error occured somewhere leave calculation { return; } } steps_in_intervall = 0; // reset stepcount current_index = current_index +1; // get back to y-form for (j = 0; j < DIM; j++ ) { if(VIRTUAL_FLAG) { ans[current_index][DIM + j] = mass * VIRTUAL_V[j]; ans[current_index][j] = VIRTUAL_X[j]; }else { ans[current_index][DIM + j] = mass * v[j]; ans[current_index][j] = x[j]; } } #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { for (j = 0; j < DIM; j++ ) { ans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM]; ans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i] ; // give step to answer } } } if (TARGET_FLAG) // if no contact, give simulation length as contact time { time_first_contact += TIME_END; TARGET_FLAG = 0; } } void VVerlet_parallel_burn(const int N, const double *y, double **ans, double *t, // Velocity Verlet für Start y, Ausgabe ans[LengthT][ORDER] zu Zeiten T void (*derivmethod) (double *y, double *ans, double t, int N)) // always involes free particle for burning samples { int i,j; for(i=0; i< N; i++){ ans[0][i] = y[i]; // übergib startvektor an antwort } TARGET_FLAG = 1; double x[N/2], v[N/2], a[N/2], z[N]; vec_zero(x,N/2); vec_zero(v,N/2); vec_zero(a,N/2); vec_zero(z,N); int current_index = 0; double current_t = t[current_index]; derivmethod(y, z, current_t, N); // übergib erste Ableitung // bringe aus y-p y Form auf x-v-a for (j = 0; j < DIM; j++ ) { x[j] = y[j]; v[j] = y[DIM + j]/mass; a[j] = z[DIM + j]/mass; } #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { for (j = 0; j < DIM; j++ ) { x[DIM + j + i*DIM] = y[2*DIM + j + i * 2*DIM]; v[DIM + j + i*DIM] = y[3*DIM + j + i * 2*DIM]/massq[i]; a[DIM + j + i*DIM] = z[3*DIM + j + i * 2*DIM]/massq[i]; } } while(current_index < LENGTH_T-1) { while(fabs(current_t - t[current_index + 1])> MAXSTEPSIZE) { //integriere bis abstand zu nächstem t kleiner schrittweite VVerlet_Step_deriv(N, x, v, a, &current_t, derivmethod); //printf ("%fx %ft \n", x[1], current_t); } // rechne wieder auf y-Form current_index = current_index +1; for (j = 0; j < DIM; j++ ) { ans[current_index][DIM + j] = mass * v[j]; ans[current_index][j] = x[j]; } #pragma omp parallel for for (i= 0 ; i < OSSZI; i++) { for (j = 0; j < DIM; j++ ) { ans[current_index][2*DIM + j + i * 2*DIM] = x[DIM +j+ i*DIM]; ans[current_index][3*DIM + j + i * 2*DIM] = v[DIM +j+ i*DIM] * massq[i]; // übergib SChritt an antwort } } } if (TARGET_FLAG) // FAlls kein erstkontakt addiere gesamtzeit { time_first_contact += TIME_END; TARGET_FLAG = 0; } } void Bath_Setup(double *y, char *inputlabel, gsl_rng * r){ int a,b,i; double u,P[OSSZI], sum=0.0; if (strcmp(inputlabel,"ZWANZIG")==0) { for (b = 0; b < DIM; b++) { y[b] = 0.0; //massives particle seperatly y[DIM+b] = 0.0; for (a = 0; a < OSSZI; a++) { u = gsl_ran_gaussian(r, 1.0); y[2*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP / massq[a]) / ommega[a] * u; //q = (k*T/m)^0.5/ommega * N(0,1) u = gsl_ran_gaussian(r, 1.0); y[3*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP * massq[a]) * u; //p_q = (k*T*m)^0.5 * N(0,1) } } return; } if (strcmp(inputlabel,"ZWANZIG_THERMALIZED")==0) { for (b = 0; b < DIM; b++) { y[b] = 0.0; //massives particle seperatly u = gsl_ran_gaussian(r, 1.0); y[DIM+b] = sqrt(KBOLTZ * TEMP * mass) * u; //p_q = (k*T*m)^0.5 * N(0,1) for (a = 0; a < OSSZI; a++) { u = gsl_ran_gaussian(r, 1.0); y[2*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP / massq[a]) / ommega[a] * u; //q = (k*T/m)^0.5/ommega * N(0,1) u = gsl_ran_gaussian(r, 1.0); y[3*DIM + a * 2*DIM + b] = sqrt(KBOLTZ * TEMP * massq[a]) * u; //p_q = (k*T*m)^0.5 * N(0,1) } } return; } printf("FALSCHES BADLABEL"); exit(1); } void Ommega_Setup(gsl_rng * r) { // draw uniformly nonrandom double nr_osszillators = 1.0 * OSSZI; // cast Osszi to double double higher_cutoff = 1.0/(0.5 * TIME_STEPS); //cleanly resolve smallest steps double lower_cutoff = 1.0/(1.6 * TIME_END); //cleanly resolve till end time higher_cutoff = 5.0* pow( (GAMMA/mass), 1.0/(2.0-ALPHA)); lower_cutoff = 5E-5; double ommega_step = (higher_cutoff - lower_cutoff)/(nr_osszillators); for (int i = 0; i < OSSZI; i++) { ommega[i] = lower_cutoff + i * ommega_step; } printf("\nnonrandom bath "); printf ("Ommega_Max = %1.3e ", ommega[OSSZI-1] ); printf ("Ommega_Min = %1.3e\n", ommega[0] ); } void Gamma_Setup(double *gamma){ //Set coupling for Exponent Alpha so that MSD s^2 prop to //t^ALPHA, ALPHA = 1 (classical diff) seperately // put constants in gamma int i; double TOL = 1e-3; double nr_osz = (double) OSSZI; double delta_ommega = ommega[1]-ommega[0]; if (! (KUPF_BINARY)) { if (fabs(ALPHA-1.0)<TOL){ // Alpha = 1 for(i = 0; i < OSSZI; i++) { gamma[i] = sqrt(GAMMA) * ommega[i] * sqrt(delta_ommega); } if (OUTPUT_FLAG) { printf("ALPHA rounded to 1 \n"); } } if (fabs(ALPHA-1.0)>TOL){ for(i = 0; i < OSSZI; i++) { gamma[i] = sqrt(GAMMA) * pow(ommega[i], 0.5 + ALPHA * 0.5)\ * sqrt( 2/sqrt(M_PI * 2) * sin(M_PI * ALPHA/2.0) * gsl_sf_gamma(1 - ALPHA)) * sqrt(delta_ommega); } } if (OUTPUT_FLAG) { printf("Konstanten aufgesetzt für Alpha = %f \n " , ALPHA); } }else { if (fabs(ALPHA-1.0)<TOL) // Alpha = 1 { for(i = 0; i < OSSZI; i++) { gamma[i] = 1.0 / sqrt(2.0 * M_PI) * GAMMA * (delta_ommega); } printf("Konstanten aufgesetzt für KUPF_A rounded to 1 \n " ); }else { for(i = 0; i < OSSZI; i++) { gamma[i] = 1.0 / sqrt(2.0 * M_PI) * GAMMA * gsl_sf_gamma(1 - ALPHA)\ * sin(M_PI * ALPHA/2.0) * pow(ommega[i], ALPHA - 1.0) * (delta_ommega); } printf("Konstanten aufgesetzt für KUPF_A = %2.2f \n ", ALPHA ); } } } void deriv(double *yin, double *ans, double t, int N){ // Hamiltonian derivative int i,j; double P[OSSZI], Q[OSSZI], temp_vec[OSSZI]; double sum; for(j = 0; j < DIM; j++) { #pragma omp parallel for for(i = 0; i < OSSZI; i++) { Q[i] = yin[(2 + i * 2) * DIM + j ]; //get P und Q for easier indexing P[i] = yin[(3 + i * 2) * DIM + j ]; } sum = 0.0; #pragma omp parallel for for (i = 0 ; i < OSSZI; i++) { // Sum if(KUPF_BINARY) { temp_vec[i] = -coupling[i] * (Q[i] - yin[j]); }else { temp_vec[i] = coupling[i] * Q[i] - pow(coupling[i],2.0)/pow(ommega[i],2.0) * yin[j]; } } Sum_Method(OSSZI, temp_vec, &sum); ans[j] = yin[DIM+ j]/mass; // dx/dx = p/m ans[DIM+j] = sum ; //p-deriv #pragma omp parallel for for (i = 0 ; i < OSSZI; i++) { ans[(2 + i * 2) * DIM + j ] = P[i]/massq[i]; // dq/dt = p_q/m_q if(KUPF_BINARY) { ans[(3 + i * 2) * DIM + j ] = coupling[i] * (Q[i] - yin[j]); // dp_q/dt = -w^2 * q+ gamma * x }else { ans[(3 + i * 2) * DIM + j ] = - ommega[i] * ommega[i] * Q[i] + coupling[i] * yin[j]; // dp_q/dt = -w^2 * q+ gamma * x } } } } void deriv_parallel(const double *yin, double *ans, double t, int N) // deriv with i-j loops reversed for parralelization { // Ableitungsfunktion int i,j; double temp_vec[OSSZI]; double sum; #pragma omp parallel for // Values for Bath particles parralized for (i = 0 ; i < OSSZI; i++) { for(j = 0; j < DIM; j++) { ans[(2 + i * 2) * DIM + j ] = yin[(3 + i * 2) * DIM + j ]/massq[i]; // dq/dt = p_q/m_q if(KUPF_BINARY) { ans[(3 + i * 2) * DIM + j ] = -coupling[i] * (yin[(2 + i * 2) * DIM + j] - yin[j]); // dp_q/dt = -w^2 * q+ gamma * x }else { ans[(3 + i * 2) * DIM + j ] = - ommega[i] * ommega[i] * yin[(2 + i * 2) * DIM + j]\ + coupling[i] * yin[j]; // dp_q/dt = -w^2 * q+ gamma * x } } } for(j = 0; j < DIM; j++) // Values for heavy particle { sum = 0.0; #pragma omp parallel for for (i = 0 ; i < OSSZI; i++) { // berechne die Summe if(KUPF_BINARY) { temp_vec[i] = coupling[i] * (yin[(2 + i * 2) * DIM + j] - yin[j]); // dp_q/dt = -w^2 * q+ gamma * x }else { temp_vec[i] = coupling[i] * yin[(2 + i * 2) * DIM + j]\ - pow(coupling[i],2.0)/pow(ommega[i],2.0) * yin[j]; // for Kahan summation : vec gamma^2/ommega^2 } } Sum_Method(OSSZI, temp_vec, &sum); ans[j] = yin[DIM+ j]/mass; // dx/dx = p/m ans[DIM+j] = sum ; //p-deriv } }
{ "alphanum_fraction": 0.545407339, "avg_line_length": 26.3805175038, "ext": "c", "hexsha": "91224b516afde1c428bcb266cfee0daf6715d6e0", "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": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_forks_repo_path": "utility.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "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": "nowottnm/KAC_ZWANZIG_SIM", "max_issues_repo_path": "utility.c", "max_line_length": 161, "max_stars_count": null, "max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_stars_repo_path": "utility.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6725, "size": 17332 }
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <math.h> #include <assert.h> #include <gsl/gsl_math.h> #include "com3.h" // #define debugmode 1 int unit_tests(void); const int64_t comr = 2; // Radius of com filter in pixels // The filter will be (2*comr+1)^3 pixels int pointInDomain(int64_t * restrict Point, size_t * Domain, int nDim) // Check if a point is in the domain of a 3D image { for(int kk = 0; kk<nDim; kk++) if(Point[kk]<0 || Point[kk]>= (int64_t) Domain[kk]) return 0; return 1; } int checkBounds(int64_t * restrict D, const size_t M, const size_t N, const size_t P) { if(D[0]>=comr && D[0]+comr<(int64_t) M && D[1]>=comr && D[1]+comr<(int64_t) N && D[2]>=comr && D[2]+comr<(int64_t) P) return 1; // ok return 0; } void com3_localw(double * restrict V, double * restrict W, const size_t M, const size_t N, const size_t P, int64_t * restrict D, double * restrict C) { #ifdef debugmode printf("D: [%u %u %u]\n", D[0], D[1], D[2]); printf("M: %lu N: %lu P: %lu\n", M, N, P); #endif double sum = 0; double dx = 0; double dy = 0; double dz = 0; #ifdef debugmode printf("sum: %f\n", sum); #endif if(checkBounds(D, M, N, P)) { double val = V[D[0] + D[1]*M + D[2]*M*N]; for(int kk = -comr; kk<=comr; kk++) { for(int ll = -comr; ll<=comr; ll++) { for(int mm = -comr; mm<=comr; mm++) { size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N; // printf("pos: %lu V[pos]: %f\n", pos, V[pos]); dx += kk*V[pos]*val/W[pos]; dy += ll*V[pos]*val/W[pos]; dz += mm*V[pos]*val/W[pos]; sum += V[pos]; } } } //printf("sum: %f\n", sum); } if(sum>0) { #ifdef debugmode printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz); #endif C[0] = D[0] + dx/sum; C[1] = D[1] + dy/sum; C[2] = D[2] + dz/sum; } else { #ifdef debugmode printf("No com calculation\n"); #endif C[0] = D[0]; C[1] = D[1]; C[2] = D[2]; } } void com3_local(double * restrict V, const size_t M, const size_t N, const size_t P, int64_t * restrict D, double * restrict C) { #ifdef debugmode printf("D: [%u %u %u]\n", D[0], D[1], D[2]); printf("M: %lu N: %lu P: %lu\n", M, N, P); #endif double sum = 0; double dx = 0; double dy = 0; double dz = 0; #ifdef debugmode printf("sum: %f\n", sum); #endif if(checkBounds(D, M, N, P)) { for(int kk = -comr; kk<=comr; kk++) { for(int ll = -comr; ll<=comr; ll++) { for(int mm = -comr; mm<=comr; mm++) { size_t pos = (D[0]+kk) + (D[1]+ll)*M + (D[2]+mm)*M*N; // printf("pos: %lu V[pos]: %f\n", pos, V[pos]); dx += kk*V[pos]; dy += ll*V[pos]; dz += mm*V[pos]; sum += V[pos]; } } } //printf("sum: %f\n", sum); } if(sum>0) { #ifdef debugmode printf("sum: %f (%f, %f, %f)\n", sum, dx, dy, dz); #endif C[0] = D[0] + dx/sum; C[1] = D[1] + dy/sum; C[2] = D[2] + dz/sum; } else { #ifdef debugmode printf("No com calculation\n"); #endif C[0] = D[0]; C[1] = D[1]; C[2] = D[2]; } } void setLmax(double *V, double * W, size_t * Domain, int64_t * Dot) // Adds V(dot) to all W within comr of dot // uses global value comr { uint32_t m = Dot[0]; uint32_t n = Dot[1]; uint32_t p = Dot[2]; size_t M = Domain[0]; size_t N = Domain[1]; size_t P = Domain[2]; double val = V[m + n*M + p*M*N]; for(uint32_t pp = GSL_MAX(p-comr,0) ; pp<= GSL_MIN(p+comr, P-1) ; pp++) { for(uint32_t nn = GSL_MAX(n-comr,0) ; nn<= GSL_MIN(n+comr, N-1) ; nn++) { for(uint32_t mm = GSL_MAX(m-comr,0) ; mm<= GSL_MIN(m+comr, M-1) ; mm++) { W[mm + nn*M + pp*M*N] += val; } } } } void setWeights(double * V, double * W, size_t M, size_t N, size_t P, double * D, size_t nD) { size_t Domain[] = {M, N, P}; int64_t Dot[] = {0,0,0}; for(size_t kk = 0; kk<nD; kk++) { Dot[0] = D[kk*3 + 0]; Dot[1] = D[kk*3 + 1]; Dot[2] = D[kk*3 + 2]; setLmax(V, W, Domain, Dot); } } void com3(double * V, size_t M, size_t N, size_t P, double * D, double * C, size_t L, int weighted) { /* Centre of mass * * V: MxNxP image * P 3xL list of dots * C 3xL list of fitted dots */ int64_t Dround[] = {0,0,0}; size_t Domain[] = {M, N, P}; double * W; if(weighted == 1) // Set up the weighting matrix { W = (double *) calloc(M*N*P, sizeof(double)); for(size_t kk = 0; kk<L; kk++) { Dround[0] = nearbyint(D[kk*3]-1); Dround[1] = nearbyint(D[kk*3+1]-1); Dround[2] = nearbyint(D[kk*3+2]-1); if(pointInDomain(Dround, Domain, 3)) setLmax(V, W, Domain, Dround); } } if(weighted == 1) for(size_t kk = 0; kk<L; kk++) { Dround[0] = nearbyint(D[kk*3]-1); Dround[1] = nearbyint(D[kk*3+1]-1); Dround[2] = nearbyint(D[kk*3+2]-1); // printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]); com3_localw(V, W, M, N, P, Dround, C+kk*3); } if(weighted ==0) for(size_t kk = 0; kk<L; kk++) { Dround[0] = nearbyint(D[kk*3]-1); Dround[1] = nearbyint(D[kk*3+1]-1); Dround[2] = nearbyint(D[kk*3+2]-1); // printf("%d %d %d\n", Dround[0], Dround[1], Dround[2]); com3_local(V, M, N, P, Dround, C+kk*3); } if(weighted == 1){ // This was used for debugging //for(size_t xx = 0; xx<M*N*P; xx++) // V[xx] = W[xx]; free(W); } } #ifdef standalone int unit_tests() { // Size of image uint32_t M = 100; uint32_t N = 100; uint32_t P = 100; uint32_t L = 2; // number of dots double * V = malloc(M*N*P*sizeof(double)); double * D = malloc(L*3*sizeof(double)); double * C = malloc(L*3*sizeof(double)); memset(V, 0, M*N*P*sizeof(double)); memset(C, 0, 3*L*sizeof(double)); for(size_t kk = 0; kk<M*N*P; kk++) V[kk] = 0; D[0] = 11; D[1] = 12; D[2] = 13; D[3] = 0; D[4] = 15; D[5] = 16; size_t pos = D[0] + M*D[1] + M*N*D[2]; V[pos] = 3; // V[pos+1] = 1; // V[pos + M] = 1; V[pos + M*N] = 1; // Ordinary com3(V, M, N, P, D, C, L, 0); // Weighted com3(V, M, N, P, D, C, L, 1); for(uint32_t kk=0; kk<L; kk++) { printf("%d [%f %f %f] -> ", kk, D[3*kk], D[3*kk+1], D[3*kk+2]); printf(" [%f %f %f]\n", C[3*kk], C[3*kk+1], C[3*kk+2]); } free(C); free(D); free(V); return 0; } int main(int argc, char ** argv) { printf("%s\n", argv[0]); if(argc == 1) return unit_tests(); } #endif
{ "alphanum_fraction": 0.4841602777, "avg_line_length": 22.3, "ext": "c", "hexsha": "4eca838340c62baec965be7af61b832a353161e3", "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/com3.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/com3.c", "max_line_length": 108, "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/com3.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": 2612, "size": 6913 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_parser_Parser_inl_h_ #define SQ_INCLUDE_GUARD_parser_Parser_inl_h_ #include <charconv> #include "core/ASSERT.h" #include "core/errors.h" #include <gsl/gsl> namespace sq::parser { template <std::integral Int> std::optional<Int> Parser::parse_integer() { const auto opt_token = accept_token(TokenKind::Integer); if (!opt_token) { return std::nullopt; } const auto &token = opt_token.value(); const auto str_view = token.view(); ASSERT(!str_view.empty()); const auto *begin = str_view.data(); // We can't really avoid using pointer arithmetic when using // std::from_chars - it requires a const char* to indicate the end of the // string, but we can only reasonably make one using pointer arithmetic. // In particular, std::string, std::string_view, std::span etc. only // provide iterator versions of end(), but we need a pointer. // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) const auto *end = begin + str_view.size(); Int value = 0; const auto [ptr, ec] = std::from_chars(begin, end, value, 10); if (ec == std::errc::result_out_of_range) { auto ss = std::ostringstream{}; ss << "integer " << str_view << " does not fit in required type; " << "must be in the closed interval [" << std::numeric_limits<Int>::min() << ", " << std::numeric_limits<Int>::max() << "]"; throw OutOfRangeError{token, ss.str()}; } ASSERT(ec == std::errc{}); ASSERT(ptr == end); return value; } } // namespace sq::parser #endif // SQ_INCLUDE_GUARD_parser_Parser_inl_h_
{ "alphanum_fraction": 0.6267409471, "avg_line_length": 35.1960784314, "ext": "h", "hexsha": "4d6fed98e4d1171e46dcabf6e4bbec25c769d909", "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/parser/include/parser/Parser.inl.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/parser/include/parser/Parser.inl.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/parser/include/parser/Parser.inl.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": 435, "size": 1795 }
/* * emu_noh.c * * * Created by Earl Lawrence on 9/17/09. * Update 11/30/2012 * * This program was prepared by Los Alamos National Security, LLC at Los Alamos National Laboratory (LANL) * under contract No. DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the program * are reserved by the DOE and Los Alamos National Security, LLC. Permission is granted to the public to * copy and use this software without charge, provided that this Notice and any statement of authorship are * reproduced on all copies. Neither the U.S. Government nor LANS makes any warranty, express or implied, * or assumes any liability or responsibility for the use of this software. * * */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "pcbasis_noh.h" #include "design_noh.h" #include "pcweights_noh.h" #include "corrlengths_noh.h" #include "precisions_noh.h" #include "meansd.h" #include "kemu.h" #include "ksim.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif // Sizes of stuff and number of redshifts static int m=37, neta=5500, p=5, peta=6, rs=11, nsim=582; // Kriging basis computed by emuInit, sizes should be peta and m static double KrigBasis[6][37]; // Initialization function that computes the Kriging basis void emuInit_noh() { int i,j,k,l; double cov; gsl_matrix *SigmaSim = gsl_matrix_alloc(m,m); gsl_vector *b = gsl_vector_alloc(m); // Do these one principal component at a time for(i=0; i<peta; i++) { // Fill in the covariance matrix for the principals components // Also make a gsl_vector with the weights. for(j=0; j<m; j++) { // Diagonal gsl_matrix_set(SigmaSim, j, j, (1.0/lamz[i]) + (1.0/lamws[i])); // Off-diagonals for(k=0; k<j; k++) { // Compute the covariance cov = 0.0; for(l=0; l<p; l++) { cov -= beta[i][l]*pow(x[j][l]-x[k][l], 2.0); } cov = exp(cov)/lamz[i]; gsl_matrix_set(SigmaSim, j, k, cov); gsl_matrix_set(SigmaSim, k, j, cov); } // for(k=0; k<j; k++) gsl_vector_set(b, j, w[i][j]); } // for(j=0; j<m; j++) // Cholesky and solve gsl_linalg_cholesky_decomp(SigmaSim); gsl_linalg_cholesky_svx(SigmaSim, b); // Copy into the Kriging Basis for(j=0; j<m; j++) { KrigBasis[i][j] = gsl_vector_get(b, j); } } // for(i=0; i<peta; i++) gsl_matrix_free(SigmaSim); gsl_vector_free(b); } // The actual emulation // Cosmological parameters, placeholder for the output, type of output void emu_noh(double *xstar, double *ystar, int *outtype) { static int inited=0; int i, j, k; double wstar[peta], Sigmastar[peta][m], ystaremu[neta], ystar_allz[rs*nsim], logc; double xstarstd[p]; double zemu[rs], ybyz[rs]; FILE *fp; // Interpolation stuff for k and then z gsl_spline *lininterp_k = gsl_spline_alloc(gsl_interp_linear, neta/rs); gsl_spline *lininterp_z = gsl_spline_alloc(gsl_interp_linear, rs); gsl_interp_accel *accel = gsl_interp_accel_alloc(); // Iinitialize if necessary if(inited==0) { emuInit_noh(); inited=1; } // Check the inputs to make sure we're interpolating. for(i=0; i<p; i++) { if((xstar[i] < xmin[i]) || (xstar[i] > xmin[i]+xrange[i])) { //printf("The inputs are outside the domain of the emulator.\n"); switch(i) { case 0: printf("omega_b must be between %f and %f.\n", xmin[i], xmin[i]+xrange[i]); break; case 1: printf("omega_m must be between %f and %f.\n", xmin[i], xmin[i]+xrange[i]); break; case 2: printf("n_s must be between %f and %f.\n", xmin[i], xmin[i]+xrange[i]); break; case 3: printf("w must be between %f and %f.\n", xmin[i], xmin[i]+xrange[i]); break; case 4: printf("sigma_8 must be between %f and %f.\n", xmin[i], xmin[i]+xrange[i]); break; } exit(1); } } // for(i=0; i<p; i++) // Check redshift to make sure we're interpolating if((xstar[p] < 0) || (xstar[p] > 4)) { //printf("The inputs are outside the domain of the emulator.\n"); printf("z must between 0 and 4\n"); exit(1); } // Standardize the inputs for(i=0; i<p; i++) { xstarstd[i] = (xstar[i] - xmin[i]) / xrange[i]; } // Compute the covariances between the new input and sims for all PCs for(i=0; i<peta; i++) { for(j=0; j<m; j++) { logc = 0.0; for(k=0; k<p; k++) { logc -= beta[i][k]*pow(x[j][k]-xstarstd[k], 2.0); } Sigmastar[i][j] = exp(logc)/lamz[i]; } } // Compute wstar, the predicted PC weights for the new input for(i=0; i<peta; i++) { wstar[i]=0.0; for(j=0; j<m; j++) { wstar[i] += Sigmastar[i][j] * KrigBasis[i][j]; } } // Compute ystar, the new output for(i=0; i<neta; i++) { ystaremu[i] = 0.0; for(j=0; j<peta; j++) { ystaremu[i] += K[i][j]*wstar[j]; } ystaremu[i] = ystaremu[i]*sd + mean[i]; } //printf("Emulated\n"); // Interpolate the emulated output onto the original domain. for(i=0; i<rs; i++) { gsl_spline_init(lininterp_k, kemu, &ystaremu[i*neta/rs], neta/rs); for(j=0; j<nsim; j++) { ystar_allz[i*nsim+j] = gsl_spline_eval(lininterp_k, ksim[j], accel); } gsl_interp_accel_reset(accel); } //printf("k interped\n"); // Fill in the k values for the final output for(i=0; i<nsim; i++) { ystar[i] = ksim[i]; } // Interpolate on to the desired redshift // The order needs to be reversed here. for(i=0; i<rs; i++) { zemu[i] = (1/aemu[rs-i-1]) - 1.0; } for(i=0; i<nsim; i++) { // Build an array with the values of y for a given value of z // Reverse the order for(j=0; j<rs; j++) { ybyz[rs-j-1] = ystar_allz[j*nsim+i]; } gsl_spline_init(lininterp_z, zemu, ybyz, rs); ystar[nsim+i] = gsl_spline_eval(lininterp_z, xstar[p], accel); gsl_interp_accel_reset(accel); } //printf("z interped\n"); switch(outtype[0]) { default: for(j=0; j<nsim; j++) { ystar[nsim+j] = pow(10.0,ystar[nsim+j]); } break; case 1: // Transform to Delta^2 for(j=0; j<nsim; j++) { ystar[nsim+j] = ystar[nsim+j] + 1.5*log10(ksim[j]); ystar[nsim+j] = pow(10.0,ystar[nsim+j]); } break; case 2: // Transform to P(k) for(j=0; j<nsim; j++) { ystar[nsim+j] = ystar[nsim+j] - 1.5*log10(ksim[j]); ystar[nsim+j] = pow(10.0,ystar[nsim+j])*2.0*M_PI*M_PI; } break; } // Free some stuff. I always forget this. // Thanks to Tim Eifler for discovering it (apparently the hard way). gsl_spline_free(lininterp_z); gsl_spline_free(lininterp_k); gsl_interp_accel_free(accel); } // Linker function for use with Fortran void emu_noh_(double *x, double *y, int *outtype) { void emu(); emu(x,y,outtype); }
{ "alphanum_fraction": 0.5395325073, "avg_line_length": 31.825203252, "ext": "c", "hexsha": "3e586be9c1e0dc4963f79f4683a3aa6e3e46cac1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_line_length": 109, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 2365, "size": 7829 }
/** * * @file core_strdalg1.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Azzam Haidar * @date 2013-07-04 * @generated s Tue Jan 7 11:44:50 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_float * * CORE_strdalg1 is a part of the tridiagonal reduction algorithm (bulgechasing) * It correspond to a local driver of the kernels that should be executed on a * single core. * ******************************************************************************* * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in] nb * The size of the Bandwidth of the matrix A, * which correspond to the tile size. nb >= 0. * * @param[in,out] A * float array, dimension (lda,n) * On entry, the (nb+1)-by-n band lower hermetian matrix to * be reduced to tridiagonal. * On exit, the diagonal and first subdiagonal of A are over- * written by the corresponding elements of the tridiagonal. * * @param[in] lda * (input) INTEGER * The leading dimension of the array A. LDA >= max(1,nb+1). * * @param[out] V * float array, dimension (n) if wantz=0 * or ldv*Vblksiz*blkcnt if wantz>0. * The scalar elementary reflectors are written in this * array. * * @param[out] TAU * float array, dimension (n) if wantz=0 * or Vblksiz*Vblksiz*blkcnt if wantz>0. * The scalar factors of the elementary reflectors are written * in this array. * * @param[in] Vblksiz * Local parameter to Plasma. It correspond to the local bloccking * of the applyQ2 used to apply the orthogonal matrix Q2. * * @param[in] wantz * integer tobe 0 or 1. if wantz=0 the V and TAU are not stored on * only they are kept for next step then overwritten. * * @param[in] i * Integer that refer to the current sweep. (outer loop). * * @param[in] sweepid * Integer that refer to the sweep to chase.(inner loop). * * @param[in] m * Integer that refer to a sweep step, to ensure order dependencies. * * @param[in] grsiz * Integer that refer to the size of a group. * group mean the number of kernel that should be executed sequentially * on the same core. * group size is a trade-off between locality (cache reuse) and parallelism. * a small group size increase parallelism while a large group size increase * cache reuse. * * @param[in] work * Workspace of size nb. Used by the core_ssbtype[123]cb. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_strdalg1 = PCORE_strdalg1 #define CORE_strdalg1 PCORE_strdalg1 #endif void CORE_strdalg1( int n, int nb, float *A, int lda, float *V, float *TAU, int Vblksiz, int wantz, int i, int sweepid, int m, int grsiz, float *work) { int k, shift=3; int myid, colpt, stind, edind, blklastind, stepercol; k = shift / grsiz; stepercol = (k*grsiz == shift) ? k : k+1; for (k = 0; k < grsiz; k++){ myid = (i-sweepid)*(stepercol*grsiz) +(m-1)*grsiz + k+1; if(myid%2 ==0) { colpt = (myid/2) * nb + 1 + sweepid - 1; stind = colpt - nb + 1; edind = min(colpt, n); blklastind = colpt; } else { colpt = ((myid+1)/2)*nb + 1 +sweepid -1 ; stind = colpt-nb+1; edind = min(colpt,n); if( (stind>=edind-1) && (edind==n) ) blklastind = n; else blklastind = 0; } if( myid == 1 ) CORE_ssbtype1cb(n, nb, A, lda, V, TAU, stind-1, edind-1, sweepid-1, Vblksiz, wantz, work); else if(myid%2 == 0) CORE_ssbtype2cb(n, nb, A, lda, V, TAU, stind-1, edind-1, sweepid-1, Vblksiz, wantz, work); else /*if(myid%2 == 1)*/ CORE_ssbtype3cb(n, nb, A, lda, V, TAU, stind-1, edind-1, sweepid-1, Vblksiz, wantz, work); if(blklastind >= (n-1)) break; } }
{ "alphanum_fraction": 0.5345325339, "avg_line_length": 34.3740458015, "ext": "c", "hexsha": "c491869db75b52b6f2ced4e83d67dd55c021e8f4", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_strdalg1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_strdalg1.c", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_strdalg1.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1294, "size": 4503 }
static char help[] = "Structured-grid minimal surface equation (MSE) in 2D. Option prefix mse_.\n" "Equation is\n" " - div ( (1 + |grad u|^2)^q grad u ) = 0\n" "on the unit square [0,1]x[0,1] subject to Dirichlet boundary\n" "conditions u = g(x,y). Power q defaults to -1/2 (i.e. MSE) but is adjustable.\n" "Catenoid and tent boundary conditions are implemented; catenoid is an exact\n" "solution. We re-use the Jacobian from the Poisson equation, but it is suitable\n" "only for low-amplitude g, or as preconditioning material in -snes_mf_operator.\n" "Options -snes_fd_color and -snes_grid_sequence K are recommended.\n" "This code is multigrid (GMG) capable.\n\n"; #include <petsc.h> #include "../ch6/poissonfunctions.h" #include "../quadrature.h" typedef struct { double q, // the exponent in the diffusivity; // =-1/2 for minimal surface eqn; =0 for Laplace eqn tent_H, // height of tent door along y=0 boundary catenoid_c; // parameter in catenoid formula int quaddegree; // quadrature degree used in -mse_monitor } MinimalCtx; // Dirichlet boundary conditions static double g_bdry_tent(double x, double y, double z, void *ctx) { PoissonCtx *user = (PoissonCtx*)ctx; MinimalCtx *mctx = (MinimalCtx*)(user->addctx); if (x < 1.0e-8) { return 2.0 * mctx->tent_H * (y < 0.5 ? y : 1.0 - y); } else return 0; } static double g_bdry_catenoid(double x, double y, double z, void *ctx) { PoissonCtx *user = (PoissonCtx*)ctx; MinimalCtx *mctx = (MinimalCtx*)(user->addctx); const double c = mctx->catenoid_c; return c * cosh(x/c) * sin(acos( (y/c) / cosh(x/c) )); } // the coefficient (diffusivity) of minimal surface equation, as a function // of w = |grad u|^2 static double DD(double w, double q) { return pow(1.0 + w,q); } typedef enum {TENT, CATENOID} ProblemType; static const char* ProblemTypes[] = {"tent","catenoid", "ProblemType", "", NULL}; extern PetscErrorCode FormExactFromG(DMDALocalInfo*, Vec, PoissonCtx*); extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, double**, double **FF, PoissonCtx*); extern PetscErrorCode MSEMonitor(SNES, int, double, void*); int main(int argc,char **argv) { PetscErrorCode ierr; DM da; SNES snes; Vec u_initial, u; PoissonCtx user; MinimalCtx mctx; PetscBool monitor = PETSC_FALSE, exact_init = PETSC_FALSE; DMDALocalInfo info; ProblemType problem = CATENOID; // defaults: mctx.q = -0.5; mctx.tent_H = 1.0; mctx.catenoid_c = 1.1; // case shown in Figure in book mctx.quaddegree = 3; user.cx = 1.0; user.cy = 1.0; user.cz = 1.0; PetscInitialize(&argc,&argv,NULL,help); ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"mse_", "minimal surface equation solver options",""); CHKERRQ(ierr); ierr = PetscOptionsReal("-catenoid_c", "parameter for problem catenoid; c >= 1 required", "minimal.c",mctx.catenoid_c,&(mctx.catenoid_c),NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-exact_init", "initial Newton iterate = continuum exact solution; only for catenoid", "minimal.c",exact_init,&(exact_init),NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-monitor", "print surface area and diffusivity bounds at each SNES iteration", "minimal.c",monitor,&(monitor),NULL);CHKERRQ(ierr); ierr = PetscOptionsReal("-q", "power of (1+|grad u|^2) in diffusivity", "minimal.c",mctx.q,&(mctx.q),NULL); CHKERRQ(ierr); ierr = PetscOptionsInt("-quaddegree", "quadrature degree (=1,2,3) used in -mse_monitor", "minimal.c",mctx.quaddegree,&(mctx.quaddegree),NULL); CHKERRQ(ierr); ierr = PetscOptionsEnum("-problem", "problem type determines boundary conditions", "minimal.c",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem, NULL); CHKERRQ(ierr); ierr = PetscOptionsReal("-tent_H", "'door' height for problem tent", "minimal.c",mctx.tent_H,&(mctx.tent_H),NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); user.addctx = &mctx; // attach MSE-specific parameters switch (problem) { case TENT: if (exact_init) { SETERRQ(PETSC_COMM_WORLD,2, "initialization with exact solution only possible for -mse_problem catenoid\n"); } user.g_bdry = &g_bdry_tent; break; case CATENOID: if (mctx.catenoid_c < 1.0) { SETERRQ(PETSC_COMM_WORLD,3, "catenoid exact solution only valid if c >= 1\n"); } if ((exact_init) && (mctx.q != -0.5)) { SETERRQ(PETSC_COMM_WORLD,4, "initialization with catenoid exact solution only possible if q=-0.5\n"); } user.g_bdry = &g_bdry_catenoid; break; default: SETERRQ(PETSC_COMM_WORLD,5,"unknown problem type\n"); } ierr = DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_BOX, // contrast with fish2 3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,0.0,1.0); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetDM(snes,da); CHKERRQ(ierr); ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES, (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr); // this is the Jacobian of the Poisson equation, thus ONLY APPROXIMATE; // generally use -snes_fd_color or -snes_mf_operator ierr = DMDASNESSetJacobianLocal(da, (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr); if (monitor) { ierr = SNESMonitorSet(snes,MSEMonitor,&user,NULL); CHKERRQ(ierr); } ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr); if ((problem == CATENOID) && (mctx.q == -0.5) && (exact_init)) { ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); ierr = FormExactFromG(&info,u_initial,&user); CHKERRQ(ierr); } else { // initial iterate has u=g on boundary and u=0 in interior ierr = InitialState(da, ZEROS, PETSC_TRUE, u_initial, &user); CHKERRQ(ierr); } //STARTSNESSOLVE ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr); ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr); ierr = DMDestroy(&da); CHKERRQ(ierr); ierr = SNESGetDM(snes,&da); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"done on %d x %d grid and problem %s", info.mx,info.my,ProblemTypes[problem]); CHKERRQ(ierr); ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); //ENDSNESSOLVE // evaluate numerical error in exact solution case if ((problem == CATENOID) && (mctx.q == -0.5)) { Vec u_exact; double errnorm; ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr); ierr = FormExactFromG(&info,u_exact,&user); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact ierr = VecDestroy(&u_exact); CHKERRQ(ierr); ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, ": error |u-uexact|_inf = %.5e\n",errnorm); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD," ...\n"); CHKERRQ(ierr); } ierr = SNESDestroy(&snes); CHKERRQ(ierr); return PetscFinalize(); } PetscErrorCode FormExactFromG(DMDALocalInfo *info, Vec uexact, PoissonCtx *user) { PetscErrorCode ierr; int i, j; double xymin[2], xymax[2], hx, hy, x, y, **auexact; ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); ierr = DMDAVecGetArray(info->da,uexact,&auexact); CHKERRQ(ierr); for (j = info->ys; j < info->ys + info->ym; j++) { y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { x = i * hx; auexact[j][i] = user->g_bdry(x,y,0.0,user); } } ierr = DMDAVecRestoreArray(info->da,uexact,&auexact); CHKERRQ(ierr); return 0; } PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, double **au, double **FF, PoissonCtx *user) { PetscErrorCode ierr; MinimalCtx *mctx = (MinimalCtx*)(user->addctx); int i, j; double xymin[2], xymax[2], hx, hy, hxhy, hyhx, x, y, ue, uw, un, us, une, use, unw, usw, dux, duy, De, Dw, Dn, Ds; ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info->mx - 1); hy = (xymax[1] - xymin[1]) / (info->my - 1); hxhy = hx / hy; hyhx = hy / hx; for (j = info->ys; j < info->ys + info->ym; j++) { y = j * hy; for (i = info->xs; i < info->xs + info->xm; i++) { x = i * hx; if (j==0 || i==0 || i==info->mx-1 || j==info->my-1) { FF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,user); } else { // assign neighbor values with either boundary condition or // current u at that point (==> symmetric matrix) ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,0.0,user) : au[j][i+1]; uw = (i-1 == 0) ? user->g_bdry(x-hx,y,0.0,user) : au[j][i-1]; un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,0.0,user) : au[j+1][i]; us = (j-1 == 0) ? user->g_bdry(x,y-hy,0.0,user) : au[j-1][i]; if (i+1 == info->mx-1 || j+1 == info->my-1) { une = user->g_bdry(x+hx,y+hy,0.0,user); } else { une = au[j+1][i+1]; } if (i-1 == 0 || j+1 == info->my-1) { unw = user->g_bdry(x-hx,y+hy,0.0,user); } else { unw = au[j+1][i-1]; } if (i+1 == info->mx-1 || j-1 == 0) { use = user->g_bdry(x+hx,y-hy,0.0,user); } else { use = au[j-1][i+1]; } if (i-1 == 0 || j-1 == 0) { usw = user->g_bdry(x-hx,y-hy,0.0,user); } else { usw = au[j-1][i-1]; } // gradient (dux,duy) at east point (i+1/2,j): dux = (ue - au[j][i]) / hx; duy = (un + une - us - use) / (4.0 * hy); De = DD(dux * dux + duy * duy, mctx->q); // ... at west point (i-1/2,j): dux = (au[j][i] - uw) / hx; duy = (unw + un - usw - us) / (4.0 * hy); Dw = DD(dux * dux + duy * duy, mctx->q); // ... at north point (i,j+1/2): dux = (ue + une - uw - unw) / (4.0 * hx); duy = (un - au[j][i]) / hy; Dn = DD(dux * dux + duy * duy, mctx->q); // ... at south point (i,j-1/2): dux = (ue + use - uw - usw) / (4.0 * hx); duy = (au[j][i] - us) / hy; Ds = DD(dux * dux + duy * duy, mctx->q); // evaluate residual FF[j][i] = - hyhx * (De * (ue - au[j][i]) - Dw * (au[j][i] - uw)) - hxhy * (Dn * (un - au[j][i]) - Ds * (au[j][i] - us)); } } } return 0; } // compute surface area and bounds on diffusivity using Q^1 elements and // tensor product gaussian quadrature PetscErrorCode MSEMonitor(SNES snes, int its, double norm, void *user) { PetscErrorCode ierr; PoissonCtx *pctx = (PoissonCtx*)(user); MinimalCtx *mctx = (MinimalCtx*)(pctx->addctx); DM da; Vec u, uloc; DMDALocalInfo info; const Quad1D q = gausslegendre[mctx->quaddegree-1]; // from ../quadrature.h double xymin[2], xymax[2], hx, hy, **au, x_i, y_j, x, y, ux, uy, W, D, Dminloc = PETSC_INFINITY, Dmaxloc = 0.0, Dmin, Dmax, arealoc = 0.0, area; int i, j, r, s; MPI_Comm comm; ierr = SNESGetDM(snes, &da); CHKERRQ(ierr); ierr = SNESGetSolution(snes, &u); CHKERRQ(ierr); ierr = DMGetLocalVector(da, &uloc); CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, u, INSERT_VALUES, uloc); CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, u, INSERT_VALUES, uloc); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); ierr = DMDAGetBoundingBox(info.da,xymin,xymax); CHKERRQ(ierr); hx = (xymax[0] - xymin[0]) / (info.mx - 1); hy = (xymax[1] - xymin[1]) / (info.my - 1); ierr = DMDAVecGetArrayRead(da,uloc,&au); CHKERRQ(ierr); //STARTMONITORLOOP // loop over rectangular cells in grid for (j = info.ys; j < info.ys + info.ym; j++) { if (j == 0) continue; y_j = j * hy; // NE corner of cell is (x_i,y_j) for (i = info.xs; i < info.xs + info.xm; i++) { if (i == 0) continue; x_i = i * hx; // loop over quadrature points in cell for (r = 0; r < q.n; r++) { x = x_i - hx + hx * 0.5 * (q.xi[r] + 1); for (s = 0; s < q.n; s++) { y = y_j - hy + hy * 0.5 * (q.xi[s] + 1); // gradient of u(x,y) at a quadrature point ux = (au[j][i] - au[j][i-1]) * (y - (y_j - hy)) + (au[j-1][i] - au[j-1][i-1]) * (y_j - y); ux /= hx * hy; uy = (au[j][i] - au[j-1][i]) * (x - (x_i - hx)) + (au[j][i-1] - au[j-1][i-1]) * (x_i - x); uy /= hx * hy; W = ux * ux + uy * uy; // min and max of diffusivity at quadrature points D = DD(W,mctx->q); Dminloc = PetscMin(Dminloc,D); Dmaxloc = PetscMax(Dmaxloc,D); // apply quadrature in surface area formula arealoc += q.w[r] * q.w[s] * PetscSqrtReal(1.0 + W); } } } } //ENDMONITORLOOP ierr = DMDAVecRestoreArrayRead(da,uloc,&au); CHKERRQ(ierr); ierr = DMRestoreLocalVector(da, &uloc); CHKERRQ(ierr); // do global reductions and report ierr = PetscObjectGetComm((PetscObject)da,&comm); CHKERRQ(ierr); arealoc *= hx * hy / 4.0; // from change of variables formula ierr = MPI_Allreduce(&arealoc,&area,1,MPI_DOUBLE,MPI_SUM,comm); CHKERRQ(ierr); ierr = MPI_Allreduce(&Dminloc,&Dmin,1,MPI_DOUBLE,MPI_MIN,comm); CHKERRQ(ierr); ierr = MPI_Allreduce(&Dmaxloc,&Dmax,1,MPI_DOUBLE,MPI_MAX,comm); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"area = %.8f; %.4f <= D <= %.4f\n", area,Dmin,Dmax); CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.5193178295, "avg_line_length": 45.0418994413, "ext": "c", "hexsha": "9016ae45cd2d452c6bc62e0bef192cc874be3837", "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": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch7/minimal.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "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": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch7/minimal.c", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch7/minimal.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4742, "size": 16125 }
/* randist/bigauss.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The Bivariate Gaussian probability distribution is p(x,y) dxdy = (1/(2 pi sigma_x sigma_y sqrt(c))) exp(-((x/sigma_x)^2 + (y/sigma_y)^2 - 2 r (x/sigma_x)(y/sigma_y))/2c) dxdy where c = 1-r^2 */ void gsl_ran_bivariate_gaussian (const gsl_rng * r, double sigma_x, double sigma_y, double rho, double *x, double *y) { double u, v, r2, scale; do { /* choose x,y in uniform square (-1,-1) to (+1,+1) */ u = -1 + 2 * gsl_rng_uniform (r); v = -1 + 2 * gsl_rng_uniform (r); /* see if it is in the unit circle */ r2 = u * u + v * v; } while (r2 > 1.0 || r2 == 0); scale = sqrt (-2.0 * log (r2) / r2); *x = sigma_x * u * scale; *y = sigma_y * (rho * u + sqrt(1 - rho*rho) * v) * scale; } double gsl_ran_bivariate_gaussian_pdf (const double x, const double y, const double sigma_x, const double sigma_y, const double rho) { double u = x / sigma_x ; double v = y / sigma_y ; double c = 1 - rho*rho ; double p = (1 / (2 * M_PI * sigma_x * sigma_y * sqrt(c))) * exp (-(u * u - 2 * rho * u * v + v * v) / (2 * c)); return p; }
{ "alphanum_fraction": 0.6045977011, "avg_line_length": 30.6338028169, "ext": "c", "hexsha": "c23f401bf0189d8aab30774f168ea7ed70cd9bd4", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/bigauss.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/bigauss.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/bigauss.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": 660, "size": 2175 }
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root // for more information. #ifndef NOVELRT_UTILITIES_MISC_H #define NOVELRT_UTILITIES_MISC_H #include <filesystem> #include <gsl/span> #include <type_traits> #if defined(NDEBUG) #define unused(x) (void)(x) #else #define unused(x) (void)(0) #endif namespace NovelRT::Utilities { class Misc { public: static inline const char* CONSOLE_LOG_GENERIC = "NovelRT"; static inline const char* CONSOLE_LOG_APP = "Application"; static inline const char* CONSOLE_LOG_DOTNET = ".NET"; static inline const char* CONSOLE_LOG_GFX = "GFX"; static inline const char* CONSOLE_LOG_STATS = "Statistics"; static inline const char* CONSOLE_LOG_AUDIO = "Audio"; static inline const char* CONSOLE_LOG_INPUT = "Input"; static inline const char* CONSOLE_LOG_WINDOWING = "WindowManager"; /** * @brief Gets the path to the executable. * * @return The path to the executable. */ static std::filesystem::path getExecutablePath(); /** * @brief Gets the path to the directory that contains the executable. <br/> * For example, `/home/stuff/game/best-game-executable` will return `/home/stuff/game` * * @return The path to the directory that contains the executable. */ static std::filesystem::path getExecutableDirPath() { return getExecutablePath().parent_path(); } [[nodiscard]] static std::vector<const char*> GetStringSpanAsCharPtrVector( const gsl::span<const std::string>& target) noexcept { size_t extensionLength = target.size(); std::vector<const char*> targetPtrs{}; targetPtrs.reserve(extensionLength); for (auto&& extension : target) { targetPtrs.emplace_back(extension.c_str()); } return targetPtrs; } }; } template<class T, class U = std::underlying_type_t<T>> constexpr T operator~(T a) { return static_cast<T>(~static_cast<U>(a)); } template<class T, class U = std::underlying_type_t<T>> constexpr T operator|(T a, T b) { return static_cast<T>((static_cast<U>(a) | static_cast<U>(b))); } template<class T, class U = std::underlying_type_t<T>> constexpr T operator&(T a, T b) { return static_cast<T>((static_cast<U>(a) & static_cast<U>(b))); } template<class T, class U = std::underlying_type_t<T>> constexpr T operator^(T a, T b) { return static_cast<T>((static_cast<U>(a) ^ static_cast<U>(b))); } template<class T, class U = std::underlying_type_t<T>> constexpr T& operator|=(T& a, T b) { return a = static_cast<T>((static_cast<U>(a) | static_cast<U>(b))); } template<class T, class U = std::underlying_type_t<T>> constexpr T& operator&=(T& a, T b) { return a = static_cast<T>((static_cast<U>(a) & static_cast<U>(b))); } template<class T, class U = std::underlying_type_t<T>> constexpr T& operator^=(T& a, T b) { return a = static_cast<T>((static_cast<U>(a) ^ static_cast<U>(b))); } #endif //! NOVELRT_UTILITIES_MISC_H
{ "alphanum_fraction": 0.6407074155, "avg_line_length": 31.5980392157, "ext": "h", "hexsha": "500ec267e8fd49b79ccfa70c2a5395a9321cde50", "lang": "C", "max_forks_count": 56, "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:52:18.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-22T15:57:00.000Z", "max_forks_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BanalityOfSeeking/NovelRT", "max_forks_repo_path": "include/NovelRT/Utilities/Misc.h", "max_issues_count": 270, "max_issues_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:28:20.000Z", "max_issues_repo_issues_event_min_datetime": "2019-02-14T20:33:05.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "BanalityOfSeeking/NovelRT", "max_issues_repo_path": "include/NovelRT/Utilities/Misc.h", "max_line_length": 119, "max_stars_count": 167, "max_stars_repo_head_hexsha": "82000a25fd53157b26a6e6d6c71cbee0ebaa241b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Exadon/NovelRT", "max_stars_repo_path": "include/NovelRT/Utilities/Misc.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:14:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-12T14:12:04.000Z", "num_tokens": 785, "size": 3223 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <lapacke.h> #include "kjg_gsl.h" void kjg_gsl_matrix_fprintf (FILE * stream, gsl_matrix * m, const char *template) { size_t i, j; for (i = 0; i < m->size1; i++) { fprintf (stream, template, gsl_matrix_get (m, i, 0)); for (j = 1; j < m->size2; j++) { fprintf (stream, "\t"); fprintf (stream, template, gsl_matrix_get (m, i, j)); } fprintf (stream, "\n"); } } void kjg_gsl_matrix_fscanf (FILE * stream, gsl_matrix * m) { size_t i, j; double x; for (i = 0; i < m->size1; i++) { for (j = 0; j < m->size2; j++) { fscanf (stream, "%lg", &x); gsl_matrix_set (m, i, j, x); } } } void kjg_gsl_evec_fprintf (FILE * stream, gsl_vector * eval, gsl_matrix * evec, const char *template) { size_t i, j; fprintf (stream, "#"); fprintf (stream, template, gsl_vector_get (eval, 0)); for (i = 1; i < eval->size; i++) { fprintf (stream, "\t"); fprintf (stream, template, gsl_vector_get (eval, i)); } fprintf (stream, "\n"); kjg_gsl_matrix_fprintf (stream, evec, template); } int kjg_gsl_evec_fscanf (FILE * stream, gsl_vector * eval, gsl_matrix * evec) { size_t i, j; int r; double x; r = fscanf (stream, "#%lg", &x); if (r != 1) return (r); gsl_vector_set (eval, 0, x); for (i = 1; i < eval->size; i++) { r = fscanf (stream, "%lg", &x); if (r != 1) return (r); gsl_vector_set (eval, i, x); } for (i = 0; i < evec->size1; i++) { for (j = 0; j < evec->size2; j++) { r = fscanf (stream, "%lg", &x); if (r != 1) return (r); gsl_matrix_set (evec, i, j, x); } } return (0); } gsl_rng * kjg_gsl_rng_init () { const gsl_rng_type *T; gsl_rng *r; extern long seed; gsl_rng_env_setup (); gsl_rng_default_seed = seed; T = gsl_rng_default; r = gsl_rng_alloc (T); // fprintf (stderr, "generator type: %s\n", gsl_rng_name (r)); // fprintf (stderr, "seed = %lu\n", gsl_rng_default_seed); return (r); } int kjg_gsl_matrix_frobenius_normalize (gsl_matrix * m) { double s = kjg_gsl_dlange ('F', m); double d = m->size1 * m->size2; return (gsl_matrix_scale (m, d / s)); } double kjg_gsl_dlange (const char norm, const gsl_matrix * m) { return (LAPACKE_dlange (LAPACK_ROW_MAJOR, norm, m->size1, m->size2, m->data, m->tda)); } int kjg_gsl_dgeqrf (gsl_matrix * m, gsl_vector * tau) { return (LAPACKE_dgeqrf (LAPACK_ROW_MAJOR, m->size1, m->size2, m->data, m->tda, tau->data)); } int kjg_gsl_dorgqr (gsl_matrix * m, gsl_vector * tau) { return (LAPACKE_dorgqr (LAPACK_ROW_MAJOR, m->size2, m->size2, m->size2, m->data, m->tda, tau->data)); } void kjg_gsl_ran_ugaussian_pair (const gsl_rng * r, double x[2]) { double r2; do { /* choose x,y in uniform square (-1,-1) to (+1,+1) */ x[0] = -1 + 2 * gsl_rng_uniform_pos (r); x[1] = -1 + 2 * gsl_rng_uniform_pos (r); /* see if it is in the unit circle */ r2 = x[0] * x[0] + x[1] * x[1]; } while (r2 > 1.0 || r2 == 0); r2 = sqrt (-2.0 * log (r2) / r2); x[0] *= r2; x[1] *= r2; } void kjg_gsl_ran_ugaussian_matrix (const gsl_rng * r, gsl_matrix * m) { size_t i, j; double *data; double x, y, r2; for (i = 0; i < m->size1; i++) { data = gsl_matrix_ptr (m, i, 0); for (j = 0; j < m->size2 - 1; j += 2) { kjg_gsl_ran_ugaussian_pair (r, data); data += 2; } if (m->size2 % 2) *data = gsl_rng_uniform_pos (r); } } void kjg_gsl_matrix_QR (gsl_matrix * m) { gsl_vector *tau = gsl_vector_alloc (m->size2); kjg_gsl_dgeqrf (m, tau); kjg_gsl_dorgqr (m, tau); gsl_vector_free (tau); } int kjg_gsl_SVD (gsl_matrix * M, gsl_matrix * V, gsl_vector * S) { size_t big_enough = M->size1 + V->size2; double *superb = malloc (big_enough * sizeof (double)); double *U; int info = LAPACKE_dgesvd (LAPACK_ROW_MAJOR, // row major 'O', 'S', M->size1, M->size2, M->data, M->tda, S->data, U, big_enough, V->data, V->tda, superb); free (superb); return (info); }
{ "alphanum_fraction": 0.5810810811, "avg_line_length": 20.0857142857, "ext": "c", "hexsha": "980815b03bf0aa5ce0ea6127bd05d4c19e3c0057", "lang": "C", "max_forks_count": 63, "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:57:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-20T08:57:41.000Z", "max_forks_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "nevrome/EIG", "max_forks_repo_path": "src/ksrc/kjg_gsl.c", "max_issues_count": 73, "max_issues_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:30:51.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-27T14:57:04.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "nevrome/EIG", "max_issues_repo_path": "src/ksrc/kjg_gsl.c", "max_line_length": 78, "max_stars_count": 142, "max_stars_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "nevrome/EIG", "max_stars_repo_path": "src/ksrc/kjg_gsl.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:29:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-12T07:58:32.000Z", "num_tokens": 1569, "size": 4218 }
/** @file Copyright John Reid 2006 */ #ifndef BIOPSY_LOG_PROBS_H_ #define BIOPSY_LOG_PROBS_H_ #ifdef _MSC_VER # pragma once #endif //_MSC_VER #include <gsl/gsl_sf_log.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_machine.h> #include <boost/test/floating_point_comparison.hpp> namespace biopsy { inline double safe_log( double x ) { return x <= 0.0 ? std::numeric_limits< double >::quiet_NaN() : gsl_sf_log( x ); } template< typename ParameterRange > void normalise_discrete_probabilities( ParameterRange & parameters ) { using namespace boost; const double sum = std::accumulate( begin( parameters ), end( parameters ), 0.0 ); BOOST_FOREACH( typename range_value< ParameterRange >::type & p, parameters ) { p /= sum; } } template< typename log_vector, typename out_vector > void probabilities_from_logs_of_choose( const log_vector & logs, out_vector & out ) { out.resize( logs.size() ); // find the largest - as we can get underflow problems const double largest = *( std::max_element( logs.begin(), logs.end() ) ); for( unsigned i = 0; logs.size() != i; ++i ) { //scale by the largest const double v = logs[i] - largest; out[i] = (v <= GSL_LOG_DBL_MIN) ? 0.0 : gsl_sf_exp( v ); BOOST_ASSERT( ! _isnan( out[i] ) ); } normalise_discrete_probabilities( out ); } template< typename ValueRange, typename ParameterRange > double dirichlet_log_pdf( const ValueRange & values, const ParameterRange & parameters ) { using namespace boost; const double param_sum = std::accumulate( begin( parameters ), end( parameters ), 0.0 ); double result = gsl_sf_lngamma( param_sum ); typedef boost::tuple< double, double > param_value_tuple; BOOST_FOREACH( const param_value_tuple & t, make_iterator_range( make_zip_iterator( make_tuple( begin( parameters ), begin( values ) ) ), make_zip_iterator( make_tuple( end( parameters ), end( values ) ) ) ) ) { const double p = t.get<0>(); const double v = t.get<1>(); result -= gsl_sf_lngamma( p ); result += ( p - 1.0 ) * gsl_sf_log( v ); } return result; } template< typename ParameterRange, typename OutputRange > void draw_from_dirichlet( const ParameterRange & alpha, OutputRange & output ) { using namespace boost; BOOST_ASSERT( size( alpha ) == size( output ) ); gsl_ran_dirichlet( get_gsl_rng(), size( alpha ), &*begin( alpha ), &*begin( output ) ); } template< typename ParameterRange > unsigned draw_from_multi( const ParameterRange & alpha ) { using namespace boost; using namespace boost::test_tools; BOOST_ASSERT( close_at_tolerance< double >( percent_tolerance_t< double >( 1.0 ) )( 1.0, std::accumulate( begin( alpha ), end( alpha ), 0.0 ) ) ); double p = gsl_rng_uniform( get_gsl_rng() ); unsigned result = 0; BOOST_FOREACH( const double a, alpha ) { if( p < a ) { break; } p -= a; ++result; } BOOST_ASSERT( result < size( alpha ) ); return result; } } //namespace biopsy #endif //BIOPSY_LOG_PROBS_H_
{ "alphanum_fraction": 0.6867588933, "avg_line_length": 18.6257668712, "ext": "h", "hexsha": "c4c7a7052ea8cc9af25d767773dd2d8dafc109ed", "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": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_path": "C++/include/biopsy/log_probs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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": "JohnReid/biopsy", "max_issues_repo_path": "C++/include/biopsy/log_probs.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_path": "C++/include/biopsy/log_probs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 837, "size": 3036 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_amax (void) { { int N = 1; float X[] = { -0.388f }; int incX = -1; int expected = 0; int k; k = cblas_isamax(N, X, incX); gsl_test_int(k, expected, "samax(case 52)"); }; { int N = 1; double X[] = { 0.247 }; int incX = -1; int expected = 0; int k; k = cblas_idamax(N, X, incX); gsl_test_int(k, expected, "damax(case 53)"); }; { int N = 1; float X[] = { 0.704f, 0.665f }; int incX = -1; int expected = 0; int k; k = cblas_icamax(N, X, incX); gsl_test_int(k, expected, "camax(case 54)"); }; { int N = 1; double X[] = { -0.599, -0.758 }; int incX = -1; int expected = 0; int k; k = cblas_izamax(N, X, incX); gsl_test_int(k, expected, "zamax(case 55)"); }; { int N = 2; float X[] = { 0.909f, 0.037f }; int incX = 1; int expected = 0; int k; k = cblas_isamax(N, X, incX); gsl_test_int(k, expected, "samax(case 56)"); }; { int N = 2; double X[] = { 0.271, -0.426 }; int incX = 1; int expected = 1; int k; k = cblas_idamax(N, X, incX); gsl_test_int(k, expected, "damax(case 57)"); }; { int N = 2; float X[] = { -0.648f, 0.317f, 0.62f, 0.392f }; int incX = 1; int expected = 1; int k; k = cblas_icamax(N, X, incX); gsl_test_int(k, expected, "camax(case 58)"); }; { int N = 2; double X[] = { -0.789, 0.352, 0.562, 0.697 }; int incX = 1; int expected = 1; int k; k = cblas_izamax(N, X, incX); gsl_test_int(k, expected, "zamax(case 59)"); }; { int N = 2; float X[] = { 0.487f, 0.918f }; int incX = -1; int expected = 0; int k; k = cblas_isamax(N, X, incX); gsl_test_int(k, expected, "samax(case 60)"); }; { int N = 2; double X[] = { 0.537, 0.826 }; int incX = -1; int expected = 0; int k; k = cblas_idamax(N, X, incX); gsl_test_int(k, expected, "damax(case 61)"); }; { int N = 2; float X[] = { 0.993f, 0.172f, -0.825f, 0.873f }; int incX = -1; int expected = 0; int k; k = cblas_icamax(N, X, incX); gsl_test_int(k, expected, "camax(case 62)"); }; { int N = 2; double X[] = { 0.913, -0.436, -0.134, 0.129 }; int incX = -1; int expected = 0; int k; k = cblas_izamax(N, X, incX); gsl_test_int(k, expected, "zamax(case 63)"); }; }
{ "alphanum_fraction": 0.5175615664, "avg_line_length": 17.3216783217, "ext": "c", "hexsha": "1eb228cd22cb78690f4d686ec45df629e647217b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_amax.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_amax.c", "max_line_length": 51, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_amax.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": 1000, "size": 2477 }
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, liyanrong@ihep.ac.cn * Thu, Aug 4, 2016 */ /*! * \file reconstruct_sa.c * \brief reconstruct sa and RM data. */ #ifdef SA #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <float.h> #include <gsl/gsl_interp.h> #include "brains.h" void *best_model_sa; /*!< best model */ void *best_model_std_sa; /*!< standard deviation of the best model */ /*! * postprocessing. */ void postprocess_sa() { char posterior_sample_file[BRAINS_MAX_STR_LENGTH]; int num_ps, i, j, k; double *pm, *pmstd; void *posterior_sample, *post_model; int size_of_modeltype = num_params * sizeof(double); best_model_sa = malloc(size_of_modeltype); best_model_std_sa = malloc(size_of_modeltype); if(thistask == roottask) { // initialize smoothing workspace char fname[200]; FILE *fp, *fline, *fsa; sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes); // get number of lines in posterior sample file get_posterior_sample_file(dnest_options_file, posterior_sample_file); //file for posterior sample fp = fopen(posterior_sample_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", posterior_sample_file); exit(0); } //file for line reconstruction sprintf(fname, "%s/%s", parset.file_dir, "data/sa_line_rec.txt"); fline = fopen(fname, "w"); if(fline == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } //file for phase sprintf(fname, "%s/%s", parset.file_dir, "data/sa_phase_rec.txt"); fsa = fopen(fname, "w"); if(fsa == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } // read number of lines if(fscanf(fp, "# %d", &num_ps) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } printf("# Number of points in posterior sample: %d\n", num_ps); post_model = malloc(size_of_modeltype); posterior_sample = malloc(num_ps * size_of_modeltype); force_update = 1; which_parameter_update = -1; // force to update the transfer function which_particle_update = 0; for(i=0; i<num_ps; i++) { // read lines for(j=0; j<num_params; j++) { if(fscanf(fp, "%lf", (double *)post_model + j) < 1) { fprintf(stderr, "# Error: Cannot read file %s.\n", posterior_sample_file); exit(0); } } fscanf(fp, "\n"); //store model memcpy(posterior_sample+i*size_of_modeltype, post_model, size_of_modeltype); calculate_sa_from_blrmodel(post_model, 0); //if( i % (num_ps/10+1) == 0) { // output sa line for(j=0; j<n_vel_sa_data; j++) { fprintf(fline, "%e %e\n", wave_sa_data[j], Fline_sa[j]); } fprintf(fline, "\n"); // output sa phase for(k=0; k<n_base_sa_data; k++) { for(j=0; j<n_vel_sa_data; j++) { fprintf(fsa, "%e %e\n", wave_sa_data[j], phase_sa[k*n_vel_sa_data + j]/(PhaseFactor * wave_sa_data[j]) ); } } fprintf(fsa, "\n"); } } fclose(fp); fclose(fline); fclose(fsa); sa_smooth_end(); pm = (double *)best_model_sa; pmstd = (double *)best_model_std_sa; for(j=0; j<num_params; j++) { pm[j] = pmstd[j] = 0.0; } for(i=0; i<num_ps; i++) { for(j =0; j<num_params; j++) pm[j] += *((double *)posterior_sample + i*num_params + j ); } for(j=0; j<num_params; j++) pm[j] /= num_ps; for(i=0; i<num_ps; i++) { for(j=0; j<num_params; j++) pmstd[j] += pow( *((double *)posterior_sample + i*num_params + j ) - pm[j], 2.0 ); } for(j=0; j<num_params; j++) { if(num_ps > 1) pmstd[j] = sqrt(pmstd[j]/(num_ps-1.0)); else pmstd[j] = 0.0; } for(j = 0; j<num_params_sa; j++) printf("Best params %d %f +- %f\n", j, *((double *)best_model_sa + j), *((double *)best_model_std_sa+j) ); free(post_model); free(posterior_sample); } return; } /*! * this function run dnest sampleing, reconstruct light curves using the best estimates for parameters. */ void reconstruct_sa() { int i, argc=0; char **argv; //configure restart of dnest argv = malloc(9*sizeof(char *)); for(i=0; i<9; i++) { argv[i] = malloc(BRAINS_MAX_STR_LENGTH*sizeof(char)); } //setup argc and argv strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc++], "/data/restartsa_dnest.txt"); if(parset.flag_restart == 1) { strcpy(argv[argc++], "-r"); strcpy(argv[argc], parset.file_dir); strcat(argv[argc], "/"); strcat(argv[argc++], "data/restartsa_dnest.txt"); } if(parset.flag_postprc == 1) { strcpy(argv[argc++], "-p"); } if(parset.flag_temp == 1) { sprintf(argv[argc++], "-t%f", parset.temperature); } if(parset.flag_sample_info == 1) { strcpy(argv[argc++], "-c"); } //level-dependent sampling { strcpy(argv[argc++], "-l"); } reconstruct_sa_init(); sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes); dnest_sa(argc, argv); sa_smooth_end(); if(parset.flag_exam_prior != 1 && parset.flag_para_name != 1) { postprocess_sa(); if(thistask == roottask) { FILE *fp; char fname[200]; int j, k; force_update = 1; which_parameter_update = -1; // force to update the transfer function which_particle_update = 0; sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes); calculate_sa_from_blrmodel(best_model_sa, 1); sa_smooth_end(); sprintf(fname, "%s/%s", parset.file_dir, "data/psa_line.txt"); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } // output sa line for(j=0; j<n_vel_sa_data; j++) { fprintf(fp, "%e %e\n", wave_sa_data[j], Fline_sa[j]); } fclose(fp); //file for phase sprintf(fname, "%s/%s", parset.file_dir, "data/psa_phase.txt"); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } for(k=0; k<n_base_sa_data; k++) { for(j=0; j<n_vel_sa_data; j++) { fprintf(fp, "%e %e\n", wave_sa_data[j], phase_sa[k*n_vel_sa_data + j]/(PhaseFactor * wave_sa_data[j]) ); } fprintf(fp, "\n"); } fclose(fp); } } reconstruct_sa_end(); //clear up argv for(i=0; i<9; i++) { free(argv[i]); } free(argv); return; } void reconstruct_sa_init() { sprintf(dnest_options_file, "%s/%s", parset.file_dir, "src/OPTIONSSA"); if(thistask == roottask) { get_num_particles(dnest_options_file); } MPI_Bcast(&parset.num_particles, 1, MPI_INT, roottask, MPI_COMM_WORLD); phase_sa = malloc(n_base_sa_data * n_vel_sa_data * sizeof(double)); Fline_sa = malloc(n_vel_sa_data * sizeof(double)); /* cloud sample related */ clouds_weight = malloc(parset.n_cloud_per_task * sizeof(double)); clouds_alpha = malloc(parset.n_cloud_per_task * sizeof(double)); clouds_beta = malloc(parset.n_cloud_per_task * sizeof(double)); clouds_vel = malloc(parset.n_cloud_per_task * parset.n_vel_per_cloud * sizeof(double)); workspace_phase = malloc( (3*n_vel_sa_data)* sizeof(double)); if(parset.flag_save_clouds && thistask == roottask) { if(parset.n_cloud_per_task <= 1000) icr_cloud_save = 1; else icr_cloud_save = parset.n_cloud_per_task/1000; char fname[200]; sprintf(fname, "%s/%s", parset.file_dir, parset.cloud_out_file); fcloud_out = fopen(fname, "w"); if(fcloud_out == NULL) { fprintf(stderr, "# Error: Cannot open file %s\n", fname); exit(-1); } } return; } void reconstruct_sa_end() { int i; free(phase_sa); free(Fline_sa); for(i=0; i<num_params; i++) { free(par_range_model[i]); free(par_prior_gaussian[i]); } free(par_range_model); free(par_prior_gaussian); free(par_prior_model); free(par_fix); free(par_fix_val); free(best_model_sa); free(best_model_std_sa); /* clouds sample related */ free(clouds_weight); free(clouds_alpha); free(clouds_beta); free(clouds_vel); free(workspace_phase); if(parset.flag_save_clouds && thistask==roottask) { fclose(fcloud_out); } if(thistask == roottask) { printf("Ends reconstruct_sa.\n"); } return; } /*! * this function calculate probability. * * At each MCMC step, only one parameter is updated, which only changes some values; thus, * optimization that reuses the unchanged values can improve computation efficiency. */ double prob_sa(const void *model) { double prob_sa = 0.0, var2, dy; int i, j; calculate_sa_from_blrmodel(model, 0); for(j=0; j<n_epoch_sa_data; j++) { for(i=0; i<n_vel_sa_data; i++) { dy = Fline_sa[i] - Fline_sa_data[i + j*n_vel_sa_data]; var2 = Flerrs_sa_data[i+j*n_vel_sa_data]*Flerrs_sa_data[i+j*n_vel_sa_data]; prob_sa += -0.5 * (dy*dy)/var2 - 0.5*log(var2 * 2.0*PI); } } for(j=0; j<n_base_sa_data; j++) { for(i=0; i<n_vel_sa_data; i++) { dy = phase_sa[j*n_vel_sa_data + i] - phase_sa_data[j*n_vel_sa_data + i]; var2 = pherrs_sa_data[j*n_vel_sa_data + i] * pherrs_sa_data[j*n_vel_sa_data + i]; prob_sa += -0.5 * (dy*dy)/var2 - 0.5*log(var2 * 2.0*PI); } } return prob_sa; } #endif
{ "alphanum_fraction": 0.5958869415, "avg_line_length": 24.2530712531, "ext": "c", "hexsha": "d83c3e0e4539d0d3921573fb47abc90ee24b59cb", "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": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_path": "src/reconstruct_sa.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "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": "yzxamos/BRAINS", "max_issues_repo_path": "src/reconstruct_sa.c", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_path": "src/reconstruct_sa.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2902, "size": 9871 }
#pragma once #include <memory> #include <gsl\gsl> #include "RTTI.h" namespace Library { class Game; class AbstractContentTypeReader : public RTTI { RTTI_DECLARATIONS(AbstractContentTypeReader, RTTI) public: AbstractContentTypeReader(const AbstractContentTypeReader&) = default; AbstractContentTypeReader& operator=(const AbstractContentTypeReader&) = default; AbstractContentTypeReader(AbstractContentTypeReader&&) = default; AbstractContentTypeReader& operator=(AbstractContentTypeReader&&) = default; virtual ~AbstractContentTypeReader() = default; std::uint64_t TargetTypeId() const; virtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) = 0; protected: AbstractContentTypeReader(Game& game, const std::uint64_t targetTypeId); gsl::not_null<Game*> mGame; const std::uint64_t mTargetTypeId; }; template <typename T> class ContentTypeReader : public AbstractContentTypeReader { public: ContentTypeReader(const ContentTypeReader&) = default; ContentTypeReader& operator=(const ContentTypeReader&) = default; ContentTypeReader(ContentTypeReader&&) = default; ContentTypeReader& operator=(ContentTypeReader&&) = default; virtual ~ContentTypeReader() = default; virtual std::shared_ptr<RTTI> Read(const std::wstring& assetName) override; protected: ContentTypeReader(Game& game, const std::uint64_t targetTypeId); virtual std::shared_ptr<T> _Read(const std::wstring& assetName) = 0; }; } #include "ContentTypeReader.inl"
{ "alphanum_fraction": 0.7725752508, "avg_line_length": 29.3137254902, "ext": "h", "hexsha": "83628ddb6bdac6217a24c4911a2e4c66ae12cefe", "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/ContentTypeReader.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/ContentTypeReader.h", "max_line_length": 83, "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/ContentTypeReader.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 352, "size": 1495 }
#include <cblas.h> #include "tasks.h" #include "utils.h" void gemm_task_par_reconfigure(int nth) { // empty } void gemm_task_par_finalize(void) { // empty } void gemm_task_par(void *ptr, int nth, int me) { struct gemm_task_arg *arg = (struct gemm_task_arg*) ptr; int m = arg->m; int n = arg->n; int k = arg->k; double *A21 = arg->A21; double *A21T = arg->A21T; double *A22 = arg->A22; int ldA = arg->ldA; // Cut A21T into panels of size m-by-blksz. Compute nominal block size. int blksz = iceil(n, nth); // Determine my share of A21T. int my_first_col = blksz * me; int my_num_cols = min(blksz, n - my_first_col); // Compute A22 := A22 - A21 * A21T', using my share of A22 and A21T. cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, m, my_num_cols, k, -1.0, A21, ldA, A21T + my_first_col, ldA, 1.0, A22 + my_first_col * ldA, ldA); }
{ "alphanum_fraction": 0.5556621881, "avg_line_length": 22.652173913, "ext": "c", "hexsha": "0f12833785a285ecacb98457fcdaed0d9a06e850", "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": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_path": "src/examples/dpotrf/task-gemm-par.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "NLAFET/pcp-runtime", "max_issues_repo_path": "src/examples/dpotrf/task-gemm-par.c", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_path": "src/examples/dpotrf/task-gemm-par.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 330, "size": 1042 }
/* 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 <stdlib.h> #include <phonoc_array.h> #include <phonoc_utils.h> #include <phonon4_h/frequency_shift.h> #include <phonon4_h/real_to_reciprocal.h> static void get_fc4_normal_for_frequency_shift_at_gp (double *fc4_normal_real, const double *frequencies, const lapack_complex_double *eigenvectors, const int grid_point0, const int grid_point1, const int *grid_address, const int *mesh, const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const Iarray *band_indices, const double cutoff_frequency); static lapack_complex_double fc4_sum(const int bi0, const int bi1, const lapack_complex_double *eigvecs0, const lapack_complex_double *eigvecs1, const lapack_complex_double *fc4_reciprocal, const double *masses, const int num_atom); static int collect_undone_grid_points(int *undone, char *phonon_done, const int num_grid_points, const int *grid_points); void get_fc4_frequency_shifts(double *frequency_shifts, const double *fc4_normal_real, const double *frequencies, const Iarray *grid_points1, const Darray *temperatures, const int *band_indicies, const int num_band0, const int num_band, const double unit_conversion_factor) { int i, j, k, l; double shift, num_phonon; for (i = 0; i < temperatures->dims[0]; i++) { for (j = 0; j < num_band0; j++) { shift = 0; #pragma omp parallel for reduction(+:shift) private(k, l, num_phonon) for (k = 0; k < grid_points1->dims[0]; k++) { for (l = 0; l < num_band; l++) { if (temperatures->data[i] > 0) { num_phonon = 2 * bose_einstein(frequencies[grid_points1->data[k] * num_band + l], temperatures->data[i]) + 1; } else { num_phonon = 1; } shift += unit_conversion_factor * fc4_normal_real [k * num_band0 * num_band + j * num_band + l] * num_phonon; } } frequency_shifts[i * num_band0 + j] = shift; } } } void get_fc4_normal_for_frequency_shift(double *fc4_normal_real, const double *frequencies, const lapack_complex_double *eigenvectors, const int grid_point0, const Iarray *grid_points1, const int *grid_address, const int *mesh, const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const Iarray *band_indicies, const double cutoff_frequency) { int i, num_atom, num_band, num_band0; num_atom = multiplicity->dims[1]; num_band = num_atom * 3; num_band0 = band_indicies->dims[0]; #pragma omp parallel for private(i) for (i = 0; i < grid_points1->dims[0]; i++) { get_fc4_normal_for_frequency_shift_at_gp(fc4_normal_real + i * num_band0 * num_band, frequencies, eigenvectors, grid_point0, grid_points1->data[i], grid_address, mesh, fc4, shortest_vectors, multiplicity, masses, p2s_map, s2p_map, band_indicies, cutoff_frequency); } } void set_phonons_for_frequency_shift(Darray *frequencies, Carray *eigenvectors, char *phonon_done, const Iarray *grid_points, const int *grid_address, const int *mesh, const Darray *fc2, const Darray *svecs_fc2, const Iarray *multi_fc2, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, const double *born, const double *dielectric, const double *reciprocal_lattice, const double *q_direction, const double nac_factor, const char uplo) { int num_undone; int *undone; undone = (int*)malloc(sizeof(int) * frequencies->dims[0]); num_undone = collect_undone_grid_points(undone, phonon_done, grid_points->dims[0], grid_points->data); get_undone_phonons(frequencies, eigenvectors, undone, num_undone, grid_address, mesh, fc2, svecs_fc2, multi_fc2, masses_fc2, p2s_fc2, s2p_fc2, unit_conversion_factor, born, dielectric, reciprocal_lattice, q_direction, nac_factor, uplo); free(undone); } void reciprocal_to_normal4(lapack_complex_double *fc4_normal, const lapack_complex_double *fc4_reciprocal, const double *freqs0, const double *freqs1, const lapack_complex_double *eigvecs0, const lapack_complex_double *eigvecs1, const double *masses, const int *band_indices, const int num_band0, const int num_band, const double cutoff_frequency) { int i, j, bi, num_atom; lapack_complex_double fc4_sum_elem; num_atom = num_band / 3; for (i = 0; i < num_band0; i++) { bi = band_indices[i]; if (freqs0[bi] > cutoff_frequency) { for (j = 0; j < num_band; j++) { if (freqs1[j] > cutoff_frequency) { fc4_sum_elem = fc4_sum(bi, j, eigvecs0, eigvecs1, fc4_reciprocal, masses, num_atom); fc4_normal[i * num_band + j] = lapack_make_complex_double (lapack_complex_double_real(fc4_sum_elem) / freqs0[bi] / freqs1[j], lapack_complex_double_imag(fc4_sum_elem) / freqs0[bi] / freqs1[j]); } else { fc4_normal[i * num_band + j] = lapack_make_complex_double(0, 0); } } } else { for (j = 0; j < num_band; j++) { fc4_normal[i * num_band + j] = lapack_make_complex_double(0, 0); } } } } static void get_fc4_normal_for_frequency_shift_at_gp (double *fc4_normal_real, const double *frequencies, const lapack_complex_double *eigenvectors, const int grid_point0, const int grid_point1, const int *grid_address, const int *mesh, const double *fc4, const Darray *shortest_vectors, const Iarray *multiplicity, const double *masses, const int *p2s_map, const int *s2p_map, const Iarray *band_indices, const double cutoff_frequency) { int i, num_atom, num_band, num_band0; lapack_complex_double *fc4_reciprocal, *fc4_normal; double q[12]; num_atom = multiplicity->dims[1]; num_band = num_atom * 3; num_band0 = band_indices->dims[0]; fc4_reciprocal = (lapack_complex_double*) malloc(sizeof(lapack_complex_double) * num_atom * num_atom * num_atom * num_atom * 81); fc4_normal = (lapack_complex_double*) malloc(sizeof(lapack_complex_double) * num_band0 * num_band); for (i = 0; i < 3; i++) { q[i + 3] = (double)grid_address[grid_point0 * 3 + i] / mesh[i]; q[i] = -q[i + 3]; q[i + 6] = (double)grid_address[grid_point1 * 3 + i] / mesh[i]; q[i + 9] = -q[i + 6]; } real_to_reciprocal4(fc4_reciprocal, q, fc4, shortest_vectors, multiplicity, p2s_map, s2p_map); reciprocal_to_normal4(fc4_normal, fc4_reciprocal, frequencies + grid_point0 * num_band, frequencies + grid_point1 * num_band, eigenvectors + grid_point0 * num_band * num_band, eigenvectors + grid_point1 * num_band * num_band, masses, band_indices->data, num_band0, num_band, cutoff_frequency); for (i = 0; i < num_band0 * num_band; i++) { fc4_normal_real[i] = lapack_complex_double_real(fc4_normal[i]); } free(fc4_reciprocal); free(fc4_normal); } static lapack_complex_double fc4_sum(const int bi0, const int bi1, const lapack_complex_double *eigvecs0, const lapack_complex_double *eigvecs1, const lapack_complex_double *fc4_reciprocal, const double *masses, const int num_atom) { int i, j, k, l, m, n, p, q; double sum_real, sum_imag, sum_real_cart, sum_imag_cart, mmm; lapack_complex_double eig_prod, eigvec0conj, eigvec1conj; sum_real = 0; sum_imag = 0; for (i = 0; i < num_atom; i++) { for (j = 0; j < num_atom; j++) { for (k = 0; k < num_atom; k++) { for (l = 0; l < num_atom; l++) { sum_real_cart = 0; sum_imag_cart = 0; mmm = sqrt(masses[i] * masses[j] * masses[k] * masses[l]); for (m = 0; m < 3; m++) { eigvec0conj = lapack_make_complex_double (lapack_complex_double_real (eigvecs0[(i * 3 + m) * num_atom * 3 + bi0]), -lapack_complex_double_imag (eigvecs0[(i * 3 + m) * num_atom * 3 + bi0])); for (n = 0; n < 3; n++) { for (p = 0; p < 3; p++) { for (q = 0; q < 3; q++) { eigvec1conj = lapack_make_complex_double (lapack_complex_double_real (eigvecs1[(l * 3 + q) * num_atom * 3 + bi1]), -lapack_complex_double_imag (eigvecs1[(l * 3 + q) * num_atom * 3 + bi1])); eig_prod = phonoc_complex_prod(eigvec0conj, phonoc_complex_prod(eigvecs0[(j * 3 + n) * num_atom * 3 + bi0], phonoc_complex_prod(eigvecs1[(k * 3 + p) * num_atom * 3 + bi1], phonoc_complex_prod(eigvec1conj, fc4_reciprocal[i * num_atom * num_atom * num_atom * 81 + j * num_atom * num_atom * 81 + k * num_atom * 81 + l * 81 + m * 27 + n * 9 + p * 3 + q])))); sum_real_cart += lapack_complex_double_real(eig_prod); sum_imag_cart += lapack_complex_double_imag(eig_prod); } } } } sum_real += sum_real_cart / mmm; sum_imag += sum_imag_cart / mmm; } } } } return lapack_make_complex_double(sum_real, sum_imag); } static int collect_undone_grid_points(int *undone, char *phonon_done, const int num_grid_points, const int *grid_points) { int i, gp, num_undone; num_undone = 0; for (i = 0; i < num_grid_points; i++) { gp = grid_points[i]; if (phonon_done[gp] == 0) { undone[num_undone] = gp; num_undone++; phonon_done[gp] = 1; } } return num_undone; }
{ "alphanum_fraction": 0.6434960388, "avg_line_length": 29.7189873418, "ext": "c", "hexsha": "08fcfa148fdd07b18edddd863e15d9510ada6f4b", "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/frequency_shift.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/frequency_shift.c", "max_line_length": 79, "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/frequency_shift.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": 3300, "size": 11739 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <gsl/gsl_rng.h> #ifdef SUBFIND #include "fof.h" #include "allvars.h" #include "proto.h" #include "domain.h" #include "subfind.h" static struct id_list { MyIDType ID; int GrNr; int SubNr; float BindingEgy; #ifdef SUBFIND_SAVE_PARTICLELISTS float Pos[3]; float Vel[3]; int Type; #ifdef STELLARAGE float Mass; float StellarAge; #endif #endif } *ID_list; static int Nids; void subfind(int num) { double t0, t1, tstart, tend; int i, gr, nlocid, offset, limit, ncount; #ifdef DENSITY_SPLIT_BY_TYPE struct unbind_data *d; int j, n, count[6], countall[6]; double a3inv, dmax1, dmax2; #endif if(ThisTask == 0) printf("\nWe now execute a parallel version of SUBFIND.\n"); tstart = second(); #ifndef ONLY_PRODUCE_HSML_FILES if(!All.ComovingIntegrationOn) { if(ThisTask == 0) printf("works only for comoving integration.\n"); endrun(0); } #endif #ifdef DENSITY_SPLIT_BY_TYPE a3inv = 1 / (All.Time * All.Time * All.Time); for(j = 0; j < 6; j++) count[j] = 0; /* let's count number of particles of selected species */ for(i = 0; i < NumPart; i++) count[P[i].Type]++; MPI_Allreduce(count, countall, 6, MPI_INT, MPI_SUM, MPI_COMM_WORLD); /* do first loop: basically just defining the hsml for different species */ for(j = 0; j < 6; j++) { if((1 << j) & (DENSITY_SPLIT_BY_TYPE)) { #ifdef BLACK_HOLES if(j == 5) countall[j] = 0; /* this will prevent that the black holes are treated separately */ #endif force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart); if(countall[j] > All.DesNumNgb) { /* build index list of particles of selectes species */ d = (struct unbind_data *) mymalloc(count[j] * sizeof(struct unbind_data)); for(i = 0, n = 0; i < NumPart; i++) if(P[i].Type == j) d[n++].index = i; t0 = second(); if(ThisTask == 0) printf("Tree construction for species %d (%d).\n", j, countall[j]); CPU_Step[CPU_FOF] += measure_time(); force_treebuild(count[j], d); myfree(d); t1 = second(); if(ThisTask == 0) printf("tree build for species %d took %g sec\n", j, timediff(t0, t1)); } else { t0 = second(); if(ThisTask == 0) printf("Tree construction.\n"); CPU_Step[CPU_FOF] += measure_time(); force_treebuild(NumPart, NULL); t1 = second(); if(ThisTask == 0) printf("tree build took %g sec\n", timediff(t0, t1)); } /* let's determine the local densities */ t0 = second(); subfind_setup_smoothinglengths(j); subfind_density(j); t1 = second(); if(ThisTask == 0) printf("density and smoothing length for species %d took %g sec\n", j, timediff(t0, t1)); force_treefree(); /* let's save density contribution of own species */ for(i = 0; i < NumPart; i++) if(P[i].Type == j) P[i].w.density_sum = P[i].u.DM_Density; } } /* do second loop: now calculate all density contributions */ for(j = 0; j < 6; j++) { if((1 << j) & (DENSITY_SPLIT_BY_TYPE)) { force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart); /* build index list of particles of selectes species */ d = (struct unbind_data *) mymalloc(count[j] * sizeof(struct unbind_data)); for(i = 0, n = 0; i < NumPart; i++) if(P[i].Type == j) d[n++].index = i; t0 = second(); if(ThisTask == 0) printf("Tree construction for species %d (%d).\n", j, countall[j]); CPU_Step[CPU_FOF] += measure_time(); force_treebuild(count[j], d); myfree(d); t1 = second(); if(ThisTask == 0) printf("tree build for species %d took %g sec\n", j, timediff(t0, t1)); /* let's determine the local densities */ t0 = second(); for(i = 0; i < 6; i++) if((1 << i) & (DENSITY_SPLIT_BY_TYPE)) if(j != i) { if(countall[i] > All.DesNumNgb) { if(ThisTask == 0) printf("calculating density contribution of species %d to species %d\n", j, i); subfind_density(-(i + 1)); } } t1 = second(); if(ThisTask == 0) printf("density() of species %d took %g sec\n", j, timediff(t0, t1)); force_treefree(); /* let's sum up density contribution */ for(i = 0; i < NumPart; i++) if((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE)) if(j != P[i].Type) if(countall[P[i].Type] > All.DesNumNgb) P[i].w.density_sum += P[i].u.DM_Density; } } for(i = 0; i < NumPart; i++) { P[i].u.DM_Density = P[i].w.density_sum; if(P[i].Type == 0) P[i].w.int_energy = DMAX(All.MinEgySpec, SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1)); else P[i].w.int_energy = 0; } #else force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart); t0 = second(); if(ThisTask == 0) printf("Tree construction.\n"); CPU_Step[CPU_FOF] += measure_time(); force_treebuild(NumPart, NULL); t1 = second(); if(ThisTask == 0) printf("tree build took %g sec\n", timediff(t0, t1)); /* let's determine the local dark matter densities */ t0 = second(); subfind_setup_smoothinglengths(); subfind_density(); t1 = second(); if(ThisTask == 0) printf("dark matter density() took %g sec\n", timediff(t0, t1)); force_treefree(); #endif /* DENSITY_SPLIT_BY_TYPE */ if(DumpFlag) { /* let's save the densities to a file (for making images) */ t0 = second(); subfind_save_densities(num); t1 = second(); if(ThisTask == 0) printf("saving densities took %g sec\n", timediff(t0, t1)); } #ifdef ONLY_PRODUCE_HSML_FILES return; #endif /* count how many groups we have that should be done collectively */ limit = 0.6 * All.TotNumPart / NTask; for(i = 0, ncount = 0; i < Ngroups; i++) if(Group[i].Len >= limit) ncount++; MPI_Allreduce(&ncount, &Ncollective, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if(ThisTask == 0) { printf("\nNumber of FOF halos treated with collective SubFind code = %d\n", Ncollective); printf("(the adopted size-limit for the collective algorithm was %d particles.)\n", limit); printf("the other %d FOF halos are treated in parallel with serial code\n\n", TotNgroups - Ncollective); } /* to decide on which task a group should be: * if GrNr <= Ncollective: collective groupfinding. * the task where the group info is put is TaskNr = (GrNr - 1) % NTask */ /* now we distribute the particles such that small groups are assigned in * total to certain CPUs, and big groups are left where they are */ t0 = second(); for(i = 0; i < NumPart; i++) { if(P[i].GrNr > Ncollective && P[i].GrNr <= TotNgroups) /* particle is in small group */ P[i].targettask = (P[i].GrNr - 1) % NTask; else P[i].targettask = ThisTask; } subfind_exchange(); /* distributes gas particles as well if needed */ t1 = second(); if(ThisTask == 0) printf("subfind_exchange()() took %g sec\n", timediff(t0, t1)); subfind_distribute_groups(); qsort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_GrNr); for(i = 0; i < NumPart; i++) if(P[i].GrNr > Ncollective && P[i].GrNr <= TotNgroups) if(((P[i].GrNr - 1) % NTask) != ThisTask) { printf("i=%d %d task=%d\n", i, P[i].GrNr, ThisTask); endrun(87); } /* lets estimate the maximum number of substructures we need to store on the local CPU */ for(i = 0, nlocid = 0; i < Ngroups; i++) nlocid += Group[i].Len; MaxNsubgroups = nlocid / All.DesLinkNgb; /* this is a quite conservative upper limit */ Nsubgroups = 0; SubGroup = (struct subgroup_properties *) mymalloc(MaxNsubgroups * sizeof(struct subgroup_properties)); for(i = 0; i < NumPart; i++) P[i].SubNr = (1 << 30); /* default */ /* we begin by applying the collective version of subfind to distributed groups */ t0 = second(); for(GrNr = 1; GrNr <= Ncollective; GrNr++) subfind_process_group_collectively(num); t1 = second(); if(ThisTask == 0) printf("processing of collective halos took %g sec\n", timediff(t0, t1)); #ifdef SUBFIND_COLLECTIVE_STAGE1 if(ThisTask == 0) printf("stage 1 ended\n"); endrun(0); #endif for(i = 0; i < NumPart; i++) { P[i].origindex = i; P[i].origintask = ThisTask; } t0 = second(); qsort(P, NumPart, sizeof(struct particle_data), subfind_compare_P_GrNr_DM_Density); t1 = second(); if(ThisTask == 0) printf("sort of local particles()() took %g sec\n", timediff(t0, t1)); /* now we have the particles of groups consecutively, but SPH particles are not aligned. They can however be accessed via SphP[P[i].originindex] */ /* let's count how many local particles we have in small groups */ for(i = 0, nlocid = 0; i < NumPart; i++) if(P[i].GrNr > Ncollective && P[i].GrNr <= Ngroups) /* particle is in small group */ nlocid++; if(ThisTask == 0) printf("contructing tree for serial subfind of local groups\n"); subfind_loctree_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart); if(ThisTask == 0) printf("Start to do local groups with serial subfind algorithm\n"); t0 = second(); /* we now apply a serial version of subfind to the local groups */ for(gr = 0, offset = 0; gr < Ngroups; gr++) { if(Group[gr].GrNr > Ncollective) { if(((Group[gr].GrNr - 1) % NTask) == ThisTask) offset = subfind_process_group_serial(gr, offset); } } t1 = second(); if(ThisTask == 0) printf("processing of local groups took took %g sec\n", timediff(t0, t1)); subfind_loctree_treefree(); /* bringing back particles in original positions, such that gas particles are aligned */ t0 = second(); qsort(P, NumPart, sizeof(struct particle_data), subfind_compare_P_origindex); t1 = second(); if(ThisTask == 0) printf("unsorting of local particles()() took %g sec\n", timediff(t0, t1)); GrNr = -1; /* to ensure that domain decomposition acts normally again */ /* now determine the remaining spherical overdensity values for the non-local groups */ domain_free_trick(); CPU_Step[CPU_FOF] += measure_time(); #ifdef DENSITY_SPLIT_BY_TYPE printf("Task %d: testing particles ...\n", ThisTask); for(i = 0; i < NumPart; i++) { if(P[i].origintask != ThisTask) printf("Task %d: Holding particle of task %d !\n", ThisTask, P[i].origintask); if(P[i].origindex != i) printf("Task %d: Particles is in wrong position (is=%d, was=%d) !\n", ThisTask, i, P[i].origindex); } #endif All.DoDynamicUpdate = 0; domain_Decomposition(); force_treebuild(NumPart, NULL); /* compute spherical overdensities for FOF groups */ t0 = second(); subfind_overdensity(); t1 = second(); if(ThisTask == 0) printf("determining spherical overdensity masses took %g sec\n", timediff(t0, t1)); /* determine which halos are contaminated by boundary particles */ t0 = second(); subfind_contamination(); t1 = second(); if(ThisTask == 0) printf("determining contamination of halos took %g sec\n", timediff(t0, t1)); force_treefree(); domain_free(); domain_allocate_trick(); /* now assemble final output */ subfind_save_final(num); tend = second(); if(ThisTask == 0) printf("\nFinished with SUBFIND. (total time=%g sec)\n\n", timediff(tstart, tend)); myfree(SubGroup); CPU_Step[CPU_FOF] += measure_time(); } void subfind_save_final(int num) { int i, j, totsubs, masterTask, groupTask, nprocgroup; char buf[1000]; double t0, t1; /* prepare list of ids with assigned group numbers */ parallel_sort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_GrNr); parallel_sort(SubGroup, Nsubgroups, sizeof(struct subgroup_properties), subfind_compare_SubGroup_GrNr_SubNr); ID_list = mymalloc(sizeof(struct id_list) * NumPart); for(i = 0, Nids = 0; i < NumPart; i++) { if(P[i].GrNr <= TotNgroups) { ID_list[Nids].GrNr = P[i].GrNr; ID_list[Nids].SubNr = P[i].SubNr; ID_list[Nids].BindingEgy = P[i].v.DM_BindingEnergy; ID_list[Nids].ID = P[i].ID; #ifdef SUBFIND_SAVE_PARTICLELISTS for(j = 0; j < 3; j++) { ID_list[Nids].Pos[j] = P[i].Pos[j]; ID_list[Nids].Vel[j] = P[i].Vel[j]; } ID_list[Nids].Type = P[i].Type; #ifdef STELLARAGE ID_list[Nids].Mass = P[i].Mass; if(P[i].Type == 4) ID_list[Nids].StellarAge = P[i].StellarAge; else ID_list[Nids].StellarAge = 0; #endif #endif Nids++; } } parallel_sort(ID_list, Nids, sizeof(struct id_list), subfind_compare_ID_list); MPI_Allreduce(&Nsubgroups, &TotNsubgroups, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); /* fill in the FirstSub-values */ for(i = 0, totsubs = 0; i < Ngroups; i++) { if(i > 0) Group[i].FirstSub = Group[i - 1].FirstSub + Group[i - 1].Nsubs; else Group[i].FirstSub = 0; totsubs += Group[i].Nsubs; } MPI_Allgather(&totsubs, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD); for(j = 1, Send_offset[0] = 0; j < NTask; j++) Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; for(i = 0; i < Ngroups; i++) Group[i].FirstSub += Send_offset[ThisTask]; MPI_Allgather(&Nids, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD); for(j = 1, Send_offset[0] = 0; j < NTask; j++) Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; if(ThisTask == 0) { sprintf(buf, "%s/groups_%03d", All.OutputDir, num); mkdir(buf, 02755); } MPI_Barrier(MPI_COMM_WORLD); if(NTask < All.NumFilesWrittenInParallel) { printf ("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n"); endrun(241931); } t0 = second(); nprocgroup = NTask / All.NumFilesWrittenInParallel; if((NTask % All.NumFilesWrittenInParallel)) nprocgroup++; masterTask = (ThisTask / nprocgroup) * nprocgroup; for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */ subfind_save_local_catalogue(num); MPI_Barrier(MPI_COMM_WORLD); /* wait inside the group */ } t1 = second(); if(ThisTask == 0) { printf("Subgroup catalogues saved. took = %g sec\n", timediff(t0, t1)); fflush(stdout); } myfree(ID_list); } void subfind_save_local_catalogue(int num) { FILE *fd; char buf[500], fname[500]; float *mass, *pos, *vel, *spin; #ifdef SAVE_MASS_TAB float *masstab; #endif int i, j, *len; MyIDType *ids; sprintf(fname, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "subhalo_tab", num, ThisTask); strcpy(buf, fname); if(!(fd = fopen(buf, "w"))) { printf("can't open file `%s`\n", buf); endrun(1183); } my_fwrite(&Ngroups, sizeof(int), 1, fd); my_fwrite(&TotNgroups, sizeof(int), 1, fd); my_fwrite(&Nids, sizeof(int), 1, fd); my_fwrite(&TotNids, sizeof(long long), 1, fd); my_fwrite(&NTask, sizeof(int), 1, fd); my_fwrite(&Nsubgroups, sizeof(int), 1, fd); my_fwrite(&TotNsubgroups, sizeof(int), 1, fd); /* group len */ len = mymalloc(Ngroups * sizeof(int)); for(i = 0; i < Ngroups; i++) len[i] = Group[i].Len; my_fwrite(len, Ngroups, sizeof(int), fd); myfree(len); /* offset into id-list */ len = mymalloc(Ngroups * sizeof(int)); for(i = 0; i < Ngroups; i++) len[i] = Group[i].Offset; my_fwrite(len, Ngroups, sizeof(int), fd); myfree(len); /* mass */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].Mass; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* location (potential minimum) */ pos = mymalloc(Ngroups * 3 * sizeof(float)); for(i = 0; i < Ngroups; i++) for(j = 0; j < 3; j++) pos[i * 3 + j] = Group[i].Pos[j]; my_fwrite(pos, Ngroups, 3 * sizeof(float), fd); myfree(pos); /* M_Mean200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].M_Mean200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* R_Mean200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].R_Mean200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* M_Crit200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].M_Crit200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* R_Crit200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].R_Crit200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* M_TopHat200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].M_TopHat200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* R_TopHat200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].R_TopHat200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); #ifdef SO_VEL_DISPERSIONS /* VelDisp_Mean200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].VelDisp_Mean200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* VelDisp_Crit200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].VelDisp_Crit200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* VelDisp_TopHat200 */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].VelDisp_TopHat200; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); #endif /* contamination particle count */ len = mymalloc(Ngroups * sizeof(int)); for(i = 0; i < Ngroups; i++) len[i] = Group[i].ContaminationLen; my_fwrite(len, Ngroups, sizeof(int), fd); myfree(len); /* contamination mass */ mass = mymalloc(Ngroups * sizeof(float)); for(i = 0; i < Ngroups; i++) mass[i] = Group[i].ContaminationMass; my_fwrite(mass, Ngroups, sizeof(float), fd); myfree(mass); /* number of substructures in FOF group */ len = mymalloc(Ngroups * sizeof(int)); for(i = 0; i < Ngroups; i++) len[i] = Group[i].Nsubs; my_fwrite(len, Ngroups, sizeof(int), fd); myfree(len); /* first substructure in FOF group */ len = mymalloc(Ngroups * sizeof(int)); for(i = 0; i < Ngroups; i++) len[i] = Group[i].FirstSub; my_fwrite(len, Ngroups, sizeof(int), fd); myfree(len); /* ------------------------------ */ /* Len of substructure */ len = mymalloc(Nsubgroups * sizeof(int)); for(i = 0; i < Nsubgroups; i++) len[i] = SubGroup[i].Len; my_fwrite(len, Nsubgroups, sizeof(int), fd); myfree(len); /* offset of substructure */ len = mymalloc(Nsubgroups * sizeof(int)); for(i = 0; i < Nsubgroups; i++) len[i] = SubGroup[i].Offset; my_fwrite(len, Nsubgroups, sizeof(int), fd); myfree(len); /* parent of substructure */ len = mymalloc(Nsubgroups * sizeof(int)); for(i = 0; i < Nsubgroups; i++) len[i] = SubGroup[i].SubParent; my_fwrite(len, Nsubgroups, sizeof(int), fd); myfree(len); /* Mass of substructure */ mass = mymalloc(Nsubgroups * sizeof(float)); for(i = 0; i < Nsubgroups; i++) mass[i] = SubGroup[i].Mass; my_fwrite(mass, Nsubgroups, sizeof(float), fd); myfree(mass); /* Pos of substructure */ pos = mymalloc(Nsubgroups * 3 * sizeof(float)); for(i = 0; i < Nsubgroups; i++) for(j = 0; j < 3; j++) pos[i * 3 + j] = SubGroup[i].Pos[j]; my_fwrite(pos, Nsubgroups, 3 * sizeof(float), fd); myfree(pos); /* Vel of substructure */ vel = mymalloc(Nsubgroups * 3 * sizeof(float)); for(i = 0; i < Nsubgroups; i++) for(j = 0; j < 3; j++) vel[i * 3 + j] = SubGroup[i].Vel[j]; my_fwrite(vel, Nsubgroups, 3 * sizeof(float), fd); myfree(vel); /* Center of mass of substructure */ pos = mymalloc(Nsubgroups * 3 * sizeof(float)); for(i = 0; i < Nsubgroups; i++) for(j = 0; j < 3; j++) pos[i * 3 + j] = SubGroup[i].CM[j]; my_fwrite(pos, Nsubgroups, 3 * sizeof(float), fd); myfree(pos); /* Spin of substructure */ spin = mymalloc(Nsubgroups * 3 * sizeof(float)); for(i = 0; i < Nsubgroups; i++) for(j = 0; j < 3; j++) spin[i * 3 + j] = SubGroup[i].Spin[j]; my_fwrite(spin, Nsubgroups, 3 * sizeof(float), fd); myfree(spin); /* velocity dispesion */ mass = mymalloc(Nsubgroups * sizeof(float)); for(i = 0; i < Nsubgroups; i++) mass[i] = SubGroup[i].SubVelDisp; my_fwrite(mass, Nsubgroups, sizeof(float), fd); myfree(mass); /* maximum circular velocity */ mass = mymalloc(Nsubgroups * sizeof(float)); for(i = 0; i < Nsubgroups; i++) mass[i] = SubGroup[i].SubVmax; my_fwrite(mass, Nsubgroups, sizeof(float), fd); myfree(mass); /* radius of maximum circular velocity */ mass = mymalloc(Nsubgroups * sizeof(float)); for(i = 0; i < Nsubgroups; i++) mass[i] = SubGroup[i].SubVmaxRad; my_fwrite(mass, Nsubgroups, sizeof(float), fd); myfree(mass); /* radius of half the mass */ mass = mymalloc(Nsubgroups * sizeof(float)); for(i = 0; i < Nsubgroups; i++) mass[i] = SubGroup[i].SubHalfMass; my_fwrite(mass, Nsubgroups, sizeof(float), fd); myfree(mass); /* ID of most bound particle */ ids = mymalloc(Nsubgroups * sizeof(MyIDType)); for(i = 0; i < Nsubgroups; i++) ids[i] = SubGroup[i].SubMostBoundID; my_fwrite(ids, Nsubgroups, sizeof(MyIDType), fd); myfree(ids); /* GrNr of substructure */ len = mymalloc(Nsubgroups * sizeof(int)); for(i = 0; i < Nsubgroups; i++) len[i] = SubGroup[i].GrNr; my_fwrite(len, Nsubgroups, sizeof(int), fd); myfree(len); /* Masstab of substructure */ #ifdef SAVE_MASS_TAB masstab = mymalloc(Nsubgroups * 6 * sizeof(float)); for(i = 0; i < Nsubgroups; i++) for(j = 0; j < 6; j++) masstab[i * 6 + j] = SubGroup[i].MassTab[j]; my_fwrite(masstab, Nsubgroups, 6 * sizeof(float), fd); myfree(masstab); #endif fclose(fd); #ifdef SUBFIND_SAVE_PARTICLELISTS sprintf(buf, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "subhalo_posvel", num, ThisTask); if(!(fd = fopen(buf, "w"))) { printf("can't open file `%s`\n", buf); endrun(1184); } my_fwrite(&Ngroups, sizeof(int), 1, fd); my_fwrite(&TotNgroups, sizeof(int), 1, fd); my_fwrite(&Nids, sizeof(int), 1, fd); my_fwrite(&TotNids, sizeof(long long), 1, fd); my_fwrite(&NTask, sizeof(int), 1, fd); my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd); my_fwrite(&All.Time, sizeof(double), 1, fd); float *posdata; double a3inv; char *types; if(All.ComovingIntegrationOn) a3inv = 1.0 / (All.Time * All.Time * All.Time); else a3inv = 1.0; posdata = (float *) mymalloc(3 * Nids * sizeof(float)); for(i = 0; i < Nids; i++) for(j = 0; j < 3; j++) posdata[i * 3 + j] = ID_list[i].Pos[j]; my_fwrite(posdata, 3 * sizeof(float), Nids, fd); for(i = 0; i < Nids; i++) for(j = 0; j < 3; j++) posdata[i * 3 + j] = ID_list[i].Vel[j] * sqrt(a3inv); my_fwrite(posdata, 3 * sizeof(float), Nids, fd); types = (char *) posdata; for(i = 0; i < Nids; i++) types[i] = ID_list[i].Type; my_fwrite(types, sizeof(char), Nids, fd); #ifdef STELLARAGE for(i = 0; i < Nids; i++) posdata[i] = ID_list[i].Mass; my_fwrite(posdata, sizeof(float), Nids, fd); for(i = 0; i < Nids; i++) posdata[i] = ID_list[i].StellarAge; my_fwrite(posdata, sizeof(float), Nids, fd); #endif myfree(posdata); fclose(fd); #endif ids = (MyIDType *) ID_list; for(i = 0; i < Nids; i++) ids[i] = ID_list[i].ID; sprintf(buf, "%s/groups_%03d/%s_%03d.%d", All.OutputDir, num, "subhalo_ids", num, ThisTask); if(!(fd = fopen(buf, "w"))) { printf("can't open file `%s`\n", buf); endrun(1184); } my_fwrite(&Ngroups, sizeof(int), 1, fd); my_fwrite(&TotNgroups, sizeof(int), 1, fd); my_fwrite(&Nids, sizeof(int), 1, fd); my_fwrite(&TotNids, sizeof(long long), 1, fd); my_fwrite(&NTask, sizeof(int), 1, fd); my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd); my_fwrite(ids, sizeof(MyIDType), Nids, fd); fclose(fd); } int subfind_compare_ID_list(const void *a, const void *b) { if(((struct id_list *) a)->GrNr < ((struct id_list *) b)->GrNr) return -1; if(((struct id_list *) a)->GrNr > ((struct id_list *) b)->GrNr) return +1; if(((struct id_list *) a)->SubNr < ((struct id_list *) b)->SubNr) return -1; if(((struct id_list *) a)->SubNr > ((struct id_list *) b)->SubNr) return +1; if(((struct id_list *) a)->BindingEgy < ((struct id_list *) b)->BindingEgy) return -1; if(((struct id_list *) a)->BindingEgy > ((struct id_list *) b)->BindingEgy) return +1; return 0; } int subfind_compare_SubGroup_GrNr_SubNr(const void *a, const void *b) { if(((struct subgroup_properties *) a)->GrNr < ((struct subgroup_properties *) b)->GrNr) return -1; if(((struct subgroup_properties *) a)->GrNr > ((struct subgroup_properties *) b)->GrNr) return +1; if(((struct subgroup_properties *) a)->SubNr < ((struct subgroup_properties *) b)->SubNr) return -1; if(((struct subgroup_properties *) a)->SubNr > ((struct subgroup_properties *) b)->SubNr) return +1; return 0; } int subfind_compare_P_GrNr_DM_Density(const void *a, const void *b) { if(((struct particle_data *) a)->GrNr < (((struct particle_data *) b)->GrNr)) return -1; if(((struct particle_data *) a)->GrNr > (((struct particle_data *) b)->GrNr)) return +1; if(((struct particle_data *) a)->u.DM_Density > (((struct particle_data *) b)->u.DM_Density)) return -1; if(((struct particle_data *) a)->u.DM_Density < (((struct particle_data *) b)->u.DM_Density)) return +1; return 0; } int subfind_compare_P_origindex(const void *a, const void *b) { if(((struct particle_data *) a)->origindex < (((struct particle_data *) b)->origindex)) return -1; if(((struct particle_data *) a)->origindex > (((struct particle_data *) b)->origindex)) return +1; return 0; } #endif
{ "alphanum_fraction": 0.6187736563, "avg_line_length": 26.42, "ext": "c", "hexsha": "938b93e7d74b8d378222ef6fac0d25b1f5273ecd", "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/subfind.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/subfind.c", "max_line_length": 110, "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/subfind.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8399, "size": 26420 }
#ifndef PVIZUTIL_H #define PVIZUTIL_H #include <math.h> #include <string> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <H5Cpp.h> using namespace std; using namespace H5; class PvizUtil { public: static void split(const int n, const int nsplit, int* counts, int* offsets) { if (nsplit == 0) throw "Cannot split by zero"; // i = 0 offsets[0] = 0; counts[0] = ceil(n/(double)nsplit); // i > 0 for (int i = 1; i < nsplit; i++) { offsets[i] = offsets[i-1] + counts[i-1]; counts[i] = ceil((n - offsets[i])/(double)(nsplit - i)); } }; static bool H5CheckDataset(const std::string &filename, const std::string &datasetname) { bool rtn = true; try { H5::H5File file(filename, H5F_ACC_RDONLY ); H5::DataSet dataset = file.openDataSet(datasetname); } catch (H5::FileIException e) { rtn = false; } return rtn; }; static void H5GetDatasetDim(const std::string &filename, const std::string &datasetname, const int &rank, hsize_t *dim) { H5::H5File file( filename, H5F_ACC_RDONLY ); H5::DataSet dataset = file.openDataSet(datasetname); /* * Get dataspace of the dataset. */ H5::DataSpace dataspace = dataset.getSpace(); /* * Get the number of dimensions in the dataspace. */ if (rank != dataspace.getSimpleExtentNdims()) { throw std::invalid_argument("Rank mismatch!!"); } dataspace.getSimpleExtentDims(dim, NULL); }; static void H5ReadByOffset(const std::string &filename, const std::string &datasetname, const H5::DataType &mem_type, const size_t &rowOffset, const size_t &size, void *m) { H5::H5File file(filename, H5F_ACC_RDONLY); H5::DataSet dataset = file.openDataSet(datasetname); H5::DataSpace dataspace = dataset.getSpace(); checkDataset(dataset, mem_type, rowOffset, size, m); hsize_t offset[1]; // hyperslab offset in the file hsize_t count[1]; // size of the hyperslab in the file offset[0] = rowOffset; count[0] = size; dataspace.selectHyperslab(H5S_SELECT_SET, count, offset); H5::DataSpace memspace(1, count); dataset.read(m, mem_type, memspace, dataspace); }; static void H5ReadByRow(const std::string &filename, const std::string &datasetname, const H5::DataType &mem_type, const size_t &rowOffset, const size_t &size1, const size_t &size2, void *m) { H5::H5File file(filename, H5F_ACC_RDONLY); H5::DataSet dataset = file.openDataSet(datasetname); H5::DataSpace dataspace = dataset.getSpace(); checkDataset(dataset, mem_type, rowOffset, size1, size2, m); hsize_t offset[2]; // hyperslab offset in the file hsize_t count[2]; // size of the hyperslab in the file offset[0] = rowOffset; offset[1] = 0; count[0] = size1; count[1] = size2; dataspace.selectHyperslab(H5S_SELECT_SET, count, offset); H5::DataSpace memspace(2, count); dataset.read(m, mem_type, memspace, dataspace); }; static void H5WriteByRow(const std::string &filename, const std::string &datasetname, const H5::DataType &mem_type, const size_t &rowOffset, const size_t &size1, const size_t &size2, const gsl_matrix *m) { H5::H5File file(filename, H5F_ACC_RDWR); H5::DataSet dataset = file.openDataSet(datasetname); H5::DataSpace dataspace = dataset.getSpace(); checkDataset(dataset, mem_type, rowOffset, size1, size2, m); hsize_t offset[2]; // hyperslab offset in the file hsize_t count[2]; // size of the hyperslab in the file offset[0] = rowOffset; offset[1] = 0; count[0] = size1; count[1] = size2; dataspace.selectHyperslab(H5S_SELECT_SET, count, offset); H5::DataSpace memspace(2, count); dataset.write(m, mem_type, memspace, dataspace); }; protected: static void checkDataset(const H5::DataSet& dataset, const H5::DataType &mem_type, const size_t rowOffset, const size_t &size1, const size_t &size2, const void *m) { // Check datatype /* H5T_class_t class_t = dataset.getTypeClass(); if ((class_t != H5T_FLOAT) && (class_t != H5T_INTEGER)) { throw std::runtime_error("Type mismatch!!"); } */ H5::DataType dtype = dataset.getDataType(); if (!(dtype == mem_type)) { throw std::runtime_error("Data type mismatch!!"); } H5::DataSpace dataspace = dataset.getSpace(); // Check rank if (dataspace.getSimpleExtentNdims() != 2) { throw std::runtime_error("Rank mismatch!!"); } // Check dimension hsize_t dims_out[2]; dataspace.getSimpleExtentDims(dims_out, NULL); if (dims_out[0] < size1) { throw std::runtime_error("Dimension mismatch!!"); } if (dims_out[1] != size2) { throw std::runtime_error("Dimension mismatch!!"); } // Check parameter if (dims_out[0] <= rowOffset) { throw std::runtime_error("Offset is out of range!!"); } if (dims_out[0] < rowOffset + size1) { throw std::runtime_error("Count is out of range!!"); } }; static void checkDataset(const H5::DataSet& dataset, const H5::DataType &mem_type, const size_t rowOffset, const size_t &size, const void *m) { // Check datatype /* H5T_class_t class_t = dataset.getTypeClass(); if ((class_t != H5T_FLOAT) && (class_t != H5T_INTEGER)) { throw std::runtime_error("Type mismatch!!"); } */ H5::DataType dtype = dataset.getDataType(); if (!(dtype == mem_type)) { throw std::runtime_error("Data type mismatch!!"); } H5::DataSpace dataspace = dataset.getSpace(); // Check rank if (dataspace.getSimpleExtentNdims() != 1) { throw std::runtime_error("Rank mismatch!!"); } // Check dimension hsize_t dims_out[1]; dataspace.getSimpleExtentDims(dims_out, NULL); if (dims_out[0] < size) { throw std::runtime_error("Dimension mismatch!!"); } // Check parameter if (dims_out[0] <= rowOffset) { throw std::runtime_error("Offset is out of range!!"); } if (dims_out[0] < rowOffset + size) { throw std::runtime_error("Count is out of range!!"); } }; }; #endif //PVIZUTIL_H
{ "alphanum_fraction": 0.6346000954, "avg_line_length": 23.7320754717, "ext": "h", "hexsha": "8776988e2406eb27474256e2f9b9f594d22597f7", "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": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_forks_repo_licenses": [ "xpp" ], "max_forks_repo_name": "jychoi-hpc/pviz3", "max_forks_repo_path": "pvizmodel/src/pvizutil.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "xpp" ], "max_issues_repo_name": "jychoi-hpc/pviz3", "max_issues_repo_path": "pvizmodel/src/pvizutil.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1", "max_stars_repo_licenses": [ "xpp" ], "max_stars_repo_name": "jychoi-hpc/pviz3", "max_stars_repo_path": "pvizmodel/src/pvizutil.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1922, "size": 6289 }
/** * @file Sampler.h * * @brief This private head contains the definition of the Sampler type * * @author Stefan Reinhold * @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved. * You may use, distribute and modify this code under the terms of * the AFL 3.0 license; see LICENSE for full license details. */ #pragma once #include "MeasurementModel.h" #include "VoxelVolume.h" #include <Eigen/Core> #include <gsl/gsl> namespace CortidQCT { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" class VolumeSampler { public: VoxelVolume::ValueType outside; inline explicit VolumeSampler( VoxelVolume const &vol, VoxelVolume::ValueType outside_ = VoxelVolume::ValueType{0}) noexcept : outside{outside_}, volume_{vol} {} template <class Derived, class DerivedOut> inline void operator()(Eigen::MatrixBase<Derived> const &positions, Eigen::MatrixBase<DerivedOut> &values, VoxelVolume::ValueType slope, VoxelVolume::ValueType intercept) const { using Eigen::Vector3f; Expects(values.rows() == positions.rows()); Expects(positions.cols() == 3); Vector3f const scale{1.f / volume_.voxelSize().width, 1.f / volume_.voxelSize().height, 1.f / volume_.voxelSize().depth}; volume_.withUnsafeDataPointer([this, &positions, &values, scale, slope, intercept](auto const *ptr) { #pragma omp parallel for for (Eigen::Index i = 0; i < positions.rows(); ++i) { values(i) = this->interpolate( (positions.row(i).array() * scale.array().transpose()) .matrix() .transpose(), gsl::make_not_null(ptr)) * slope + intercept; } }); } template <class Derived> inline Eigen::Matrix<VoxelVolume::ValueType, Eigen::Dynamic, 1> operator()(Eigen::MatrixBase<Derived> const &positions, VoxelVolume::ValueType slope, VoxelVolume::ValueType intercept) const { Eigen::Matrix<VoxelVolume::ValueType, Eigen::Dynamic, 1> values( positions.rows()); operator()(positions, values, slope, intercept); return values; } private: template <class Derived> inline VoxelVolume::ValueType at(Eigen::MatrixBase<Derived> const &pos, gsl::not_null<VoxelVolume::ValueType const *> ptr) const { auto const &size = volume_.size(); auto const isInside = (pos.array() >= 0).all() && pos(0) < gsl::narrow_cast<int>(size.width) && pos(1) < gsl::narrow_cast<int>(size.height) && pos(2) < gsl::narrow_cast<int>(size.depth); auto const index = gsl::narrow_cast<std::size_t>(pos(2)) * size.width * size.height + gsl::narrow_cast<std::size_t>(pos(1)) * size.width + gsl::narrow_cast<std::size_t>(pos(0)); return isInside ? ptr.get()[index] : outside; } template <class Derived> inline auto interpolate(Eigen::MatrixBase<Derived> const &pos, gsl::not_null<VoxelVolume::ValueType const *> ptr) const { using Value = VoxelVolume::ValueType; using Eigen::Vector3f; using Eigen::Vector3i; using gsl::make_not_null; Vector3i const x0 = pos.array().floor().matrix().template cast<int>(); Vector3i const x1 = pos.array().ceil().matrix().template cast<int>(); Vector3f const xd = pos - x0.cast<float>(); Vector3f const xn = Vector3f::Ones() - xd; // get values of lattice points Value const c000 = at(x0, ptr); Value const c001 = at(Vector3i{x0(0), x0(1), x1(2)}, ptr); Value const c010 = at(Vector3i{x0(0), x1(1), x0(2)}, ptr); Value const c011 = at(Vector3i{x0(0), x1(1), x1(2)}, ptr); Value const c100 = at(Vector3i{x1(0), x0(1), x0(2)}, ptr); Value const c101 = at(Vector3i{x1(0), x0(1), x1(2)}, ptr); Value const c110 = at(Vector3i{x1(0), x1(1), x0(2)}, ptr); Value const c111 = at(x1, ptr); auto const c00 = c000 * xn(0) + c100 * xd(0); auto const c01 = c001 * xn(0) + c101 * xd(0); auto const c10 = c010 * xn(0) + c110 * xd(0); auto const c11 = c011 * xn(0) + c111 * xd(0); auto const c0 = c00 * xn(1) + c10 * xd(1); auto const c1 = c01 * xn(1) + c11 * xd(1); auto const c = c0 * xn(2) + c1 * xd(2); return c; } VoxelVolume const &volume_; }; class ModelSampler { public: inline explicit ModelSampler(MeasurementModel const &model) noexcept : model_(model) {} template <class DerivedIn, class VectorOut> inline void operator()(Eigen::MatrixBase<DerivedIn> const &positions, float offset, VectorOut &&values) const { using Eigen::Dynamic; using Eigen::Matrix; using Eigen::Vector3f; Expects(values.rows() == positions.rows()); Expects(positions.cols() == 4); Expects(values.cols() == 1); Vector3f const min{model_.samplingRange.min, model_.densityRange.min, model_.angleRange.min}; Vector3f const scale{1.f / model_.samplingRange.stride, 1.f / model_.densityRange.stride, 1.f / model_.angleRange.stride}; for (auto &&label : model_.labels()) { model_.withUnsafeDataPointer(label, [this, &positions, &values, min, scale, offset, label](float const *ptr) { for (Eigen::Index i = 0; i < positions.rows(); ++i) { if (static_cast<MeasurementModel::Label>(positions(i, 3)) != label) { continue; } Vector3f const position{positions(i, 0) + offset, positions(i, 1), positions(i, 2)}; values(i) = this->interpolate( ((position - min).array() * scale.array()).matrix(), ptr); } }); } } template <class Derived> inline Eigen::Matrix<float, Eigen::Dynamic, 1> operator()(Eigen::MatrixBase<Derived> const &positions, float offset) const { Eigen::Matrix<float, Eigen::Dynamic, 1> values(positions.rows()); operator()(positions, offset, values); return values; } private: inline float at(int x, int y, int z, Eigen::Vector3i const &sizeI, float const *ptr) const { auto const index = x * sizeI.y() * sizeI.z() + z * sizeI.y() + y; return ptr[index]; } template <class Derived> inline float interpolate(Eigen::MatrixBase<Derived> const &pos, float const *ptr) const { using Eigen::Vector3f; using Eigen::Vector3i; using std::clamp; using std::log; Vector3i const sizeI{static_cast<int>(model_.samplingRange.numElements()), static_cast<int>(model_.densityRange.numElements()), static_cast<int>(model_.angleRange.numElements())}; auto const x00 = clamp(static_cast<int>(pos(0)), 0, sizeI.x() - 1); auto const x01 = clamp(static_cast<int>(pos(2) + 0.5f), 0, sizeI.z() - 1); auto const x0 = static_cast<int>(pos(1)); auto const x1 = x0 + 1; auto const xd = pos(1) - static_cast<float>(x0); auto const xn = 1.f - xd; auto const c0 = at(x00, clamp(x0, 0, sizeI.y() - 1), x01, sizeI, ptr); auto const c1 = at(x00, clamp(x1, 0, sizeI.y() - 1), x01, sizeI, ptr); auto const c = c0 * xn + c1 * xd; return log(c); } MeasurementModel const &model_; }; #pragma clang diagnostic pop } // namespace CortidQCT
{ "alphanum_fraction": 0.586314557, "avg_line_length": 33.4217391304, "ext": "h", "hexsha": "9bca2768f2c54e6dadc29ffe56877c964923855b", "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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": [ "AFL-3.0" ], "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_path": "lib/Sampler.h", "max_issues_count": 28, "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_licenses": [ "AFL-3.0" ], "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_path": "lib/Sampler.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": [ "AFL-3.0" ], "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_path": "lib/Sampler.h", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "num_tokens": 2020, "size": 7687 }
#ifndef __GSL_PERMUTE_H__ #define __GSL_PERMUTE_H__ #include <gsl/gsl_permute_complex_long_double.h> #include <gsl/gsl_permute_complex_double.h> #include <gsl/gsl_permute_complex_float.h> #include <gsl/gsl_permute_long_double.h> #include <gsl/gsl_permute_double.h> #include <gsl/gsl_permute_float.h> #include <gsl/gsl_permute_ulong.h> #include <gsl/gsl_permute_long.h> #include <gsl/gsl_permute_uint.h> #include <gsl/gsl_permute_int.h> #include <gsl/gsl_permute_ushort.h> #include <gsl/gsl_permute_short.h> #include <gsl/gsl_permute_uchar.h> #include <gsl/gsl_permute_char.h> #endif /* __GSL_PERMUTE_H__ */
{ "alphanum_fraction": 0.8045602606, "avg_line_length": 24.56, "ext": "h", "hexsha": "c15f062731acb7d31aed83822010206fd4a7c649", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_line_length": 48, "max_stars_count": null, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/gsl/gsl_permute.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 190, "size": 614 }
#ifdef FUTILITY_HAVE_PETSC #include <petsc.h> #include <petscsys.h> #include <petscfix.h> #include <petscksp.h> #if ((PETSC_VERSION_MAJOR<=3) && (PETSC_VERSION_MINOR<=5)) #include <petsc-private/fortranimpl.h> #include <petsc-private/pcimpl.h> #else #include <petsc/private/fortranimpl.h> #include <petsc/private/pcmgimpl.h> #endif #ifdef PETSC_USE_POINTER_CONVERSION extern void *PetscToPointer(void*); extern int PetscFromPointer(void *); extern void PetscRmPointer(void*); #else #define PetscToPointer(a) (*(PetscFortranAddr *)(a)) #define PetscFromPointer(a) (PetscFortranAddr)(a) #define PetscRmPointer(a) #endif #if ((PETSC_VERSION_MAJOR<=3) && (PETSC_VERSION_MINOR<=5)) //This is taken from petsc-3.5/src/ksp/pc/impls/mg/mgimpl.h //There is no version of petsc/private/pcmgimpl.h that is includable in older // versions of PETSc, so we just have to manually redefine the typdefs defined // in mgimpl.h here. typedef struct { PetscInt cycles; /* Type of cycle to run: 1 V 2 W */ PetscInt level; /* level = 0 coarsest level */ PetscInt levels; /* number of active levels used */ Vec b; /* Right hand side */ Vec x; /* Solution */ Vec r; /* Residual */ PetscErrorCode (*residual)(Mat,Vec,Vec,Vec); Mat A; /* matrix used in forming residual*/ KSP smoothd; /* pre smoother */ KSP smoothu; /* post smoother */ Mat interpolate; Mat restrct; /* restrict is a reserved word in C99 and on Cray */ Vec rscale; /* scaling of restriction matrix */ PetscLogEvent eventsmoothsetup; /* if logging times for each level */ PetscLogEvent eventsmoothsolve; PetscLogEvent eventresidual; PetscLogEvent eventinterprestrict; } PC_MG_Levels; typedef struct { PCMGType am; /* Multiplicative, additive or full */ PetscInt cyclesperpcapply; /* Number of cycles to use in each PCApply(), multiplicative only*/ PetscInt maxlevels; /* total number of levels allocated */ PetscInt galerkin; /* use Galerkin process to compute coarser matrices, 0=no, 1=yes, 2=yes but computed externally */ PetscBool usedmfornumberoflevels; /* sets the number of levels by getting this information out of the DM */ PetscInt nlevels; PC_MG_Levels **levels; PetscInt default_smoothu; /* number of smooths per level if not over-ridden */ PetscInt default_smoothd; /* with calls to KSPSetTolerances() */ PetscReal rtol,abstol,dtol,ttol; /* tolerances for when running with PCApplyRichardson_MG */ void *innerctx; /* optional data for preconditioner, like PCEXOTIC that inherits off of PCMG */ PetscLogStage stageApply; } PC_MG; #endif #ifdef PETSC_HAVE_FORTRAN_CAPS #define pcmgsoftreset_ PCMGSOFTRESET #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE) && !defined(FORTRANDOUBLEUNDERSCORE) #define pcmgsoftreset_ pcmgsoftreset #endif #undef __FUNCT__ #define __FUNCT__ "PCMGSoftReset" PetscErrorCode PCMGSoftReset(PC pc) { PC_MG *mg = (PC_MG*)pc->data; PC_MG_Levels **mglevels = mg->levels; PetscErrorCode ierr; PetscInt i,n; PetscFunctionBegin; if (mglevels) { n = mglevels[0]->levels; for (i=0; i<n; i++) { ierr = MatDestroy(&mglevels[i]->A);CHKERRQ(ierr); if (mglevels[i]->smoothd != mglevels[i]->smoothu) { ierr = KSPReset(mglevels[i]->smoothd);CHKERRQ(ierr); } ierr = KSPReset(mglevels[i]->smoothu);CHKERRQ(ierr); } } //This may not work if DM's are used to define the MG structure. pc->setupcalled = PETSC_FALSE; PetscFunctionReturn(0); } PETSC_EXTERN void PETSC_STDCALL pcmgsoftreset_(PC pc, int *__ierr ){ *__ierr = PCMGSoftReset( (PC)PetscToPointer((pc) )); } #endif
{ "alphanum_fraction": 0.6229586936, "avg_line_length": 39.6571428571, "ext": "c", "hexsha": "cc34f4cd4cf3c3712fde81126549092c0a72dce6", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2022-01-16T08:05:59.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-29T17:13:08.000Z", "max_forks_repo_head_hexsha": "cd7831395c7c56adcbbc5be38773d2e850c6b5b6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "wgurecky/Futility", "max_forks_repo_path": "src/pcmg_supplement.c", "max_issues_count": 183, "max_issues_repo_head_hexsha": "158950c2c3aceffedf547ed4ea777e023035ca6e", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:34:06.000Z", "max_issues_repo_issues_event_min_datetime": "2017-03-30T20:14:44.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "picmc/Futility", "max_issues_repo_path": "src/pcmg_supplement.c", "max_line_length": 144, "max_stars_count": 36, "max_stars_repo_head_hexsha": "158950c2c3aceffedf547ed4ea777e023035ca6e", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "picmc/Futility", "max_stars_repo_path": "src/pcmg_supplement.c", "max_stars_repo_stars_event_max_datetime": "2021-12-02T07:15:07.000Z", "max_stars_repo_stars_event_min_datetime": "2017-02-26T01:17:46.000Z", "num_tokens": 1061, "size": 4164 }
/* cdf/poisson.c * * Copyright (C) 2004 Jason H. Stover. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. */ /* * Computes the cumulative distribution function for a Poisson * random variable. For a Poisson random variable X with parameter * mu, * * Pr( X <= k ) = Pr( Y >= p ) * * where Y is a gamma random variable with parameters k+1 and 1. * * Reference: * * W. Feller, "An Introduction to Probability and Its * Applications," volume 1. Wiley, 1968. Exercise 46, page 173, * chapter 6. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cdf.h> #include "error.h" /* * Pr (X <= k) for a Poisson random variable X. */ double gsl_cdf_poisson_P (const unsigned int k, const double mu) { double P; double a; if (mu <= 0.0) { CDF_ERROR ("mu <= 0", GSL_EDOM); } a = (double) k + 1.0; P = gsl_cdf_gamma_Q (mu, a, 1.0); return P; } /* * Pr ( X > k ) for a Possion random variable X. */ double gsl_cdf_poisson_Q (const unsigned int k, const double mu) { double Q; double a; if (mu <= 0.0) { CDF_ERROR ("mu <= 0", GSL_EDOM); } a = (double) k + 1.0; Q = gsl_cdf_gamma_P (mu, a, 1.0); return Q; }
{ "alphanum_fraction": 0.657262278, "avg_line_length": 22.5176470588, "ext": "c", "hexsha": "cab04505ee2f0802ad40cd362807c81855577454", "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/cdf/poisson.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/cdf/poisson.c", "max_line_length": 77, "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/cdf/poisson.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": 563, "size": 1914 }
#include "scripts.h" #include "utility/fileutils.h" #include "lua.h" #include "lauxlib.h" #include "subsystems.h" #include "rendering/rendering.h" #include <gsl/gsl_math.h> /** * Retrieve the integer value in the table at the top of the stack * associated with the specified key. */ sd_result get_int_field(lua_State *L, const char *key, int *out) { lua_getfield(L, -1, key); if (!lua_isnumber(L, -1)) { return SD_SCRIPT_TYPE_ERROR; } *out = (int)lua_tonumber(L, -1); lua_pop(L, 1); return SD_OK; } /** * Retrieve the double value in the table at the top of the stack * associated with the specified key. */ sd_result get_double_field(lua_State *L, const char *key, double *out) { lua_getfield(L, -1, key); if (!lua_isnumber(L, -1)) { return SD_SCRIPT_TYPE_ERROR; } *out = lua_tonumber(L, -1); lua_pop(L, 1); return SD_OK; } /** * Retrieve the string value in the table at the top of the stack * associated with the specified key. */ sd_result get_string_field(lua_State *L, const char *key, char *out, size_t out_size) { lua_getfield(L, -1, key); if (!lua_isstring(L, -1)) { return SD_SCRIPT_TYPE_ERROR; } size_t max = GSL_MIN(lua_rawlen(L, -1), out_size); strncpy(out, lua_tostring(L, -1), max); lua_pop(L, 1); return SD_OK; } /** * Retrieve the boolean value in the table at the top of the stack * associated with the specified key. */ sd_result get_bool_field(lua_State *L, const char *key, char *out) { lua_getfield(L, -1, key); if (!lua_isboolean(L, -1)) { return SD_SCRIPT_TYPE_ERROR; } *out = lua_toboolean(L, -1); lua_pop(L, 1); return SD_OK; } sd_result read_init_info(const char *resource_path, initialization_params *out) { lua_State *L = luaL_newstate(); bzero(out, sizeof(initialization_params)); window_creation_info *winfo = calloc(1, sizeof(window_creation_info)); out->window_info = winfo; char *file_path = NULL; fileutils.get_full_path(resource_path, &file_path); if (luaL_loadfile(L, file_path) || lua_pcall(L, 0, 0, 0)) { printf("Problem loading file %s\n", file_path); return SD_GEN_ERROR; } lua_getglobal(L, "timer"); if (!lua_isstring(L, -1)) { printf("Timer type is not a string\n"); return SD_SCRIPT_TYPE_ERROR; } const char *timer_type = lua_tostring(L,-1); if (strncasecmp("glfw", timer_type, lua_rawlen(L, -1))) { printf("glfw timer specified\n"); }; out->timer_function = glfwGetTime; lua_pop(L, 1); lua_getglobal(L, "window"); if (!lua_istable(L, -1)) { printf("Window description is not a table\n"); return SD_SCRIPT_TYPE_ERROR; } get_int_field(L, "w", &winfo->width); get_int_field(L, "h", &winfo->height); get_bool_field(L, "full_screen", &winfo->full_screen); get_string_field(L, "title", winfo->window_title, sizeof(winfo->window_title)); // Sub table lua_getfield(L, -1, "clear_color"); double dbuffer; get_double_field(L, "R", &dbuffer); winfo->clear_color[0] = (GLfloat)dbuffer; get_double_field(L, "G", &dbuffer); winfo->clear_color[1] = (GLfloat)dbuffer; get_double_field(L, "B", &dbuffer); winfo->clear_color[2] = (GLfloat)dbuffer; get_double_field(L, "A", &dbuffer); winfo->clear_color[3] = (GLfloat)dbuffer; lua_pop(L, 1); return SD_OK; } scripts_struct const scripts = { .read_init_info=read_init_info };
{ "alphanum_fraction": 0.6786670634, "avg_line_length": 27.7768595041, "ext": "c", "hexsha": "49851c8a168b64c2f731b6c8efe1a28df45b64d9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "influenza/c8", "max_forks_repo_path": "src/scripts/scripts.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "influenza/c8", "max_issues_repo_path": "src/scripts/scripts.c", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "influenza/c8", "max_stars_repo_path": "src/scripts/scripts.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1006, "size": 3361 }
#ifndef CWANNIER_PARSESCF_H #define CWANNIER_PARSESCF_H #include <stdbool.h> #include <stdio.h> #include <gsl/gsl_matrix.h> #include "bstrlib/bstrlib.h" #define CWANNIER_PARSESCF_OK 0 #define CWANNIER_PARSESCF_ERR 1 int ParseSCF(char *filePath, double *num_electrons, double *alat, gsl_matrix *R); void get_b_row(gsl_matrix *R, int row, bstring line); #endif // CWANNIER_PARSESCF_H
{ "alphanum_fraction": 0.7855297158, "avg_line_length": 22.7647058824, "ext": "h", "hexsha": "0b984561c9a19dec38aecc7396b5b3f199ccbd8a", "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": "ParseSCF.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": "ParseSCF.h", "max_line_length": 81, "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": "ParseSCF.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 121, "size": 387 }
#pragma once #include <memory> #include "halley/resources/resource.h" #include "halley/utils/utils.h" #include <gsl/gsl> #include "halley/core/resources/resource_collection.h" namespace Halley { class ResourceLoader; class BinaryFile : public Resource { public: BinaryFile(); explicit BinaryFile(const Bytes& data); explicit BinaryFile(Bytes&& data); explicit BinaryFile(gsl::span<const gsl::byte> data); explicit BinaryFile(std::unique_ptr<ResourceDataStream> stream); static std::unique_ptr<BinaryFile> loadResource(ResourceLoader& loader); constexpr static AssetType getAssetType() { return AssetType::BinaryFile; } void reload(Resource&& resource) override; const Bytes& getBytes() const; Bytes& getBytes(); gsl::span<const gsl::byte> getSpan() const; gsl::span<gsl::byte> getSpan(); std::shared_ptr<ResourceDataStream> getStream() const; private: Bytes data; std::shared_ptr<ResourceDataStream> stream; bool streaming = false; }; }
{ "alphanum_fraction": 0.7406281662, "avg_line_length": 25.9736842105, "ext": "h", "hexsha": "536f826289d907b69808b7caaf2e35230bc737d4", "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": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sunhay/halley", "max_forks_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "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": "sunhay/halley", "max_issues_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.h", "max_line_length": 77, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sunhay/halley", "max_stars_repo_path": "src/engine/utils/include/halley/file_formats/binary_file.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": 237, "size": 987 }
/* * lowly.h * low-ell likelihood in the pixel domain * * JF Cardoso and Simon Prunet. January 2008. * */ #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_int.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_gamma.h> #ifdef HAS_PMC #include "invgamma.h" #endif #include "lowly_common.h" #include "chealpix.h" #ifndef __LOWLY__ #define __LOWLY__ // llll = low ell log-likelihood typedef struct { long npix_seen ; long npix,nside ; double * X_seen ; double * F_seen ; double * NoiseVar ; double * CosMat ; long lmax ; double * Wl ; double * q_buf; double * X_seen_buf; double * F_seen_buf; double * covmat_buf; double * buffer; int isLog; int partial_nindex; int* partial_index; double *partial_cl; double v2; STRUCT_TIMER_DEFS; } llll_struct ; typedef llll_struct llll_partial_struct; // create and initialize the structure holding the material to compute the likelihood llll_struct* init_lowly( double *X, // map size npix unsigned char *Mask, // mask size npix double* Foreground, // if !=NULL a foreground map long npix, char* ordering, // ring or nested double noisevar, // microK/pixel double v2, // sigma^2 for foreground marginalization double *Wl, // wl Cl unit lmax+1 values double lmax, error **err ); void free_lowly(llll_struct** self); // return the low-ell log-likelihood for spectrum C_l double lowly_lkl( void * llll_str , double * C_l , error **err ) ; // return the low-ell log-likelihood for log(Cl) double lowly_lkl_logcl( void * llll_str, double * logCl, error **err ); llll_struct * init_lowly_log(llll_struct* self,error **err); // These are wrappers on top of lowly_lkl and lowly_lkl_logcl // in case only a subset of Cls are varied as parameters double lowly_partial_lkl(void *llll_str, double *cl, error **err); double lowly_partial_lkl_logcl(void *llll_str, double *logcl, error **err); void free_lowly_partial(llll_partial_struct **elf); llll_partial_struct* init_lowly_partial( llll_struct *orig,int n,int* index, double* cl,error **err) ; llll_partial_struct* init_lowly_partial_logcl( llll_struct *orig,int n,int* index, double* cl,error **err) ; double lowly_lkl_with_noise(void *llll_str, double *cl, error **err); // ------ internals. Used for computation --------------------- // assign and compute the npix_seen * npix_seen matrix of the cosines between seen pixels double * build_cosine_matrix ( const long nside, const long * pixel_indices , const long npix_seen , const int ordering, error **err ) ; // assign and compute \sum_l W_l C_l P_l(cos) (2l+1)/4pi double * build_cov_matrix ( double *orig, const double * CosMat , const double * NoiseVar, const long npix_seen , const long lmax , const double * q, error **err ) ; // assign and compute inverse covariance matrix, same inputs as above double * build_invcov_matrix ( double *orig, const double * cosmat, const double * noisevar, const long npix_seen, const long lmax, const double *q, error **err ) ; // assign and compute W_l P_l(cos) (2l+1)/4pi double * build_dcov_matrix ( double *orig, const double *cosmat, const long npix_seen, const long lmax, const double wl, error **err ); // compute signal covariance for one value of z=cos(theta_ij) double scalCov ( const double z, const long lmax, const double *q ) ; // compute signal covariance derivative (with respect to C_l) for one value of z=cos(theta_ij) double scaldCov ( const double z, const double wl, // = Wl[ell] const long ell ) ; // tentative computation of signal covariance matrix using matrix (blas) algebra double * matCov( const double * cosmat, const long npix_seen, const long lmax, const double * q); // Computes gradient of likelihood with respect to C_l double * grad_lowly_lkl ( double * orig, llll_struct * self, const double * covmat, const double * invcovmat, error **err ) ; // Computes diagonal of fisher matrix, with respect to C_l double * diag_fisher_lowly_lkl ( double *orig, llll_struct * self, //const double * invcovmat, const double *q, error **err) ; // Computes peak of posterior by pseudo-Newton iteration double * pseudo_newton( llll_struct * self, double * cl, long niter, error **err ) ; #ifdef HAS_PMC typedef struct { invgamma * _ivg; double *data,*wl,*N; size_t ndim; } invgamma_prop; invgamma_prop* invgamma_prop_init(size_t ndim,int* ell,double* clhat, double* fsky, double* wl,double noisevar,long nside,error **err); void free_invgamma_prop(invgamma_prop **pelf); double invgamma_prop_log_pdf(invgamma_prop *self, double *x, error **err); long simulate_invgamma_prop(pmc_simu *psim,invgamma_prop *proposal, gsl_rng * r,parabox *pb,error **err); size_t get_importance_weight_invgamma_prop(pmc_simu *psim, const invgamma_prop *m, posterior_log_pdf_func *posterior_log_pdf, void *extra, error **err); void update_invgamma_prop(invgamma_prop *g,pmc_simu *psim,error **err); invgamma_prop* invgamma_prop_init_new(size_t ndim,int* ell,double* clhat, double* fsky, double* wl,double* N,error **err); #endif void computeAlphaBeta(double *alpha, double *beta,int ell, double clhat, double fsky, double wl, double Nl); double cl2xl(double cl, double wl, double Nl); #define lowly_base -10 + clowly_base #define lowly_outofrange -2 + lowly_base #define lowly_negcl -4 + lowly_base #define lowly_fish_negative -5 + lowly_base #define lowly_spec_negative -6 + lowly_base #endif
{ "alphanum_fraction": 0.6597753541, "avg_line_length": 28.5720930233, "ext": "h", "hexsha": "36c77feb5e915d507b8ad2fa017fc4f95b11c56a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/lowly.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/lowly.h", "max_line_length": 135, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/lowly.h", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 1658, "size": 6143 }
/* See compilation notes in simple_cplx.c*/ #include <complex.h> //nice names for C's complex types #include <gsl/gsl_vector.h> //gsl_vector_complex gsl_vector_complex *cvec_dot_gslcplx(gsl_vector_complex *v, gsl_complex x); gsl_vector_complex *vec_dot_gslcplx(gsl_vector *v, gsl_complex x); gsl_vector_complex *cvec_dot_c(gsl_vector_complex *v, complex double x); gsl_vector_complex *vec_dot_c(gsl_vector *v, complex double x); void gsl_vector_complex_print(gsl_vector_complex *v); #define gsl_cplx_from_c99(x) (gsl_complex){.dat= {creal(x), cimag(x)}} complex double ddot (complex double x, complex double y); #define dot(x,y) _Generic((x), \ gsl_vector*: dot_given_vec(y), \ gsl_vector_complex*: dot_given_cplx_vec(y), \ default: ddot)((x),(y)) #define dot_given_vec(y) _Generic((y), \ gsl_complex: vec_dot_gslcplx, \ default: vec_dot_c) #define dot_given_cplx_vec(y) _Generic((y), \ gsl_complex: cvec_dot_gslcplx, \ default: cvec_dot_c)
{ "alphanum_fraction": 0.6024691358, "avg_line_length": 41.8965517241, "ext": "h", "hexsha": "49dc2d52a27d1b26bb8b0963b1c2b1d1d24cf06a", "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": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "catalingheorghe/learning-activities", "max_forks_repo_path": "progr/c/21st-century-c/21st-Century-Examples/cplx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "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": "catalingheorghe/learning-activities", "max_issues_repo_path": "progr/c/21st-century-c/21st-Century-Examples/cplx.h", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8ca2eefc7e8ea3170506a5698c3e5a3bff333de2", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "catalingheorghe/learning-activities", "max_stars_repo_path": "progr/c/21st-century-c/21st-Century-Examples/cplx.h", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-10T11:24:07.000Z", "num_tokens": 290, "size": 1215 }
#ifndef SCANMATCHERPROCESSOR_H #define SCANMATCHERPROCESSOR_H #include <gmapping/log/sensorlog.h> #include <gmapping/sensor/sensor_range/rangesensor.h> #include <gmapping/sensor/sensor_range/rangereading.h> //#include <gsl/gsl_eigen.h> #include <gmapping/scanmatcher/scanmatcher.h> namespace GMapping { class ScanMatcherProcessor { public: ScanMatcherProcessor(const ScanMatcherMap& m); ScanMatcherProcessor (double xmin, double ymin, double xmax, double ymax, double delta, double patchdelta); virtual ~ScanMatcherProcessor (); virtual void processScan(const RangeReading & reading); void setSensorMap(const SensorMap& smap, std::string sensorName="FLASER"); void init(); void setMatchingParameters (double urange, double range, double sigma, int kernsize, double lopt, double aopt, int iterations, bool computeCovariance=false); void setRegistrationParameters(double regScore, double critScore); OrientedPoint getPose() const; inline const ScanMatcherMap& getMap() const {return m_map;} inline ScanMatcher& matcher() {return m_matcher;} inline void setmaxMove(double mmove){m_maxMove=mmove;} bool useICP; protected: ScanMatcher m_matcher; bool m_computeCovariance; bool m_first; SensorMap m_sensorMap; double m_regScore, m_critScore; unsigned int m_beams; double m_maxMove; //state ScanMatcherMap m_map; OrientedPoint m_pose; OrientedPoint m_odoPose; int m_count; //gsl_eigen_symmv_workspace * m_eigenspace; }; }; #endif
{ "alphanum_fraction": 0.7802419355, "avg_line_length": 29.76, "ext": "h", "hexsha": "5815bbd532c0b8967ebdda43f6c9580815d2cf7f", "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": "946db1678a99043fc179a5a82499c4bd98cd19d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "HouCongCN/Gmapping-Code", "max_forks_repo_path": "fastSLAMproject/src/gmapping/openslam_gmapping/scanmatcher/scanmatcherprocessor.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "946db1678a99043fc179a5a82499c4bd98cd19d6", "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": "HouCongCN/Gmapping-Code", "max_issues_repo_path": "fastSLAMproject/src/gmapping/openslam_gmapping/scanmatcher/scanmatcherprocessor.h", "max_line_length": 133, "max_stars_count": null, "max_stars_repo_head_hexsha": "946db1678a99043fc179a5a82499c4bd98cd19d6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "HouCongCN/Gmapping-Code", "max_stars_repo_path": "fastSLAMproject/src/gmapping/openslam_gmapping/scanmatcher/scanmatcherprocessor.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 395, "size": 1488 }
#include <math.h> #include <stdio.h> #include <complex.h> #include <lapacke.h> #include <libhades.h> #include "unittest.h" int test_trace() { matrix_t *A, *B; matrix_complex_t *C, *D; double trace; complex_t trace_cplx; unittest_t test; unittest_init(&test, "matrix_mult", "Test trace"); A = matrix_alloc(3,3); B = matrix_alloc(3,3); matrix_set(A, 0,0, 1); matrix_set(A, 0,1, 2); matrix_set(A, 0,2, 3); matrix_set(A, 1,0, 4); matrix_set(A, 1,1, 5); matrix_set(A, 1,2, 6); matrix_set(A, 2,0, 7); matrix_set(A, 2,1, 8); matrix_set(A, 2,2, 9); matrix_set(B, 0,0, 9); matrix_set(B, 0,1, 8); matrix_set(B, 0,2, 7); matrix_set(B, 1,0, 6); matrix_set(B, 1,1, 5); matrix_set(B, 1,2, 4); matrix_set(B, 2,0, 3); matrix_set(B, 2,1, 2); matrix_set(B, 2,2, 1); trace = matrix_trace_AB(A, B); AssertEqual(&test, trace, 189); AssertEqual(&test, matrix_trace(A), 15); AssertEqual(&test, matrix_trace(B), 15); matrix_free(A); matrix_free(B); C = matrix_complex_alloc(3,3); D = matrix_complex_alloc(3,3); matrix_set(C, 0,0, CPLX(0,1)); matrix_set(C, 0,1, CPLX(-2,0)); matrix_set(C, 0,2, CPLX(3,1)); matrix_set(C, 1,0, CPLX(-2,0)); matrix_set(C, 1,1, CPLX(1,0)); matrix_set(C, 1,2, CPLX(0,1)); matrix_set(C, 2,0, CPLX(0,-2)); matrix_set(C, 2,1, CPLX(1,3)); matrix_set(C, 2,2, CPLX(5,0)); matrix_set(D, 0,0, CPLX(0,-2)); matrix_set(D, 0,1, CPLX(0,1)); matrix_set(D, 0,2, CPLX(2,-2)); matrix_set(D, 1,0, CPLX(1,0)); matrix_set(D, 1,1, CPLX(5,0)); matrix_set(D, 1,2, CPLX(0,1)); matrix_set(D, 2,0, CPLX(-1,0)); matrix_set(D, 2,1, CPLX(-4,-4)); matrix_set(D, 2,2, CPLX(0,1)); trace_cplx = matrix_complex_trace(C); AssertEqual(&test, CREAL(trace_cplx), 6); AssertEqual(&test, CIMAG(trace_cplx), 1); trace_cplx = matrix_complex_trace(D); AssertEqual(&test, CREAL(trace_cplx), 5); AssertEqual(&test, CIMAG(trace_cplx), -1); trace = matrix_trace_complex_AB_real(C, D); AssertEqual(&test, trace, -1); trace_cplx = matrix_trace_complex_AB(C, D); AssertEqual(&test, CREAL(trace_cplx), -1); AssertEqual(&test, CIMAG(trace_cplx), -5); matrix_complex_free(C); matrix_complex_free(D); return test_results(&test, stderr); } int test_matrix_mult() { matrix_t *A, *B, *C; unittest_t test; unittest_init(&test, "matrix_mult", "Test matrix multiplication"); A = matrix_alloc(2,3); B = matrix_alloc(3,2); matrix_set(A, 0,0, 3); matrix_set(A, 0,1, 2); matrix_set(A, 0,2, 1); matrix_set(A, 1,0, 1); matrix_set(A, 1,1, 0); matrix_set(A, 1,2, 2); matrix_set(B, 0,0, 1); matrix_set(B, 0,1, 2); matrix_set(B, 1,0, 0); matrix_set(B, 1,1, 1); matrix_set(B, 2,0, 4); matrix_set(B, 2,1, 0); C = matrix_mult(A,B,1,NULL); matrix_free(A); matrix_free(B); AssertEqual(&test, matrix_get(C,0,0), 7); AssertEqual(&test, matrix_get(C,0,1), 8); AssertEqual(&test, matrix_get(C,1,0), 9); AssertEqual(&test, matrix_get(C,1,1), 2); matrix_free(C); return test_results(&test, stderr); } int test_matrix_zeros() { int m,n; matrix_t *A; matrix_complex_t *C; unittest_t test; unittest_init(&test, "matrix_zeros", "Test function matrix_zeros"); for(m = 6; m < 20; m++) for(n = 1; n < 8; n++) { int im, in; A = matrix_zeros(m,n, NULL); C = matrix_complex_zeros(m,n, NULL); for(im = 0; im < m; im++) for(in = 0; in < n; in++) { complex_t c = matrix_get(C,im,in); AssertEqual(&test, matrix_get(A,im,in),0); AssertEqual(&test, CREAL(c), 0); AssertEqual(&test, CIMAG(c), 0); } matrix_free(A); matrix_complex_free(C); } return test_results(&test, stderr); } int test_zeros() { matrix_t *A; matrix_complex_t *B; unittest_t test; unittest_init(&test, "matrix_zeros", "Test zeros"); size_t rows = 100, columns = 150; A = matrix_zeros (rows, columns, NULL); B = matrix_complex_zeros(rows, columns, NULL); for(size_t i = 0; i < rows; i++) for(size_t j = 0; j < columns; j++) { AssertEqual(&test, matrix_get(A, i,j), 0); AssertEqual(&test, matrix_get(B, i,j), 0); } matrix_free(A); matrix_complex_free(B); return test_results(&test, stderr); } int test_matrix_kron() { matrix_t *A, *B, *AB; matrix_complex_t *C, *D, *CD; matrix_t *E, *EE; unittest_t test; unittest_init(&test, "matrix_kron", "Test function matrix_kron"); A = matrix_alloc(3,2); B = matrix_alloc(2,2); matrix_set(A, 0,0, 1); matrix_set(A, 0,1, 2); matrix_set(A, 1,0, 3); matrix_set(A, 1,1, 4); matrix_set(A, 2,0, 5); matrix_set(A, 2,1, 6); matrix_set(B, 0,0, 7); matrix_set(B, 0,1, 8); matrix_set(B, 1,0, 9); matrix_set(B, 1,1, 0); AB = matrix_kron(A, B, NULL); matrix_free(A); matrix_free(B); AssertEqual(&test, matrix_get(AB, 0,0), 7); AssertEqual(&test, matrix_get(AB, 0,1), 8); AssertEqual(&test, matrix_get(AB, 0,2), 14); AssertEqual(&test, matrix_get(AB, 0,3), 16); AssertEqual(&test, matrix_get(AB, 1,0), 9); AssertEqual(&test, matrix_get(AB, 1,1), 0); AssertEqual(&test, matrix_get(AB, 1,2), 18); AssertEqual(&test, matrix_get(AB, 1,3), 0); AssertEqual(&test, matrix_get(AB, 2,0), 21); AssertEqual(&test, matrix_get(AB, 2,1), 24); AssertEqual(&test, matrix_get(AB, 2,2), 28); AssertEqual(&test, matrix_get(AB, 2,3), 32); AssertEqual(&test, matrix_get(AB, 3,0), 27); AssertEqual(&test, matrix_get(AB, 3,1), 0); AssertEqual(&test, matrix_get(AB, 3,2), 36); AssertEqual(&test, matrix_get(AB, 3,3), 0); AssertEqual(&test, matrix_get(AB, 4,0), 35); AssertEqual(&test, matrix_get(AB, 4,1), 40); AssertEqual(&test, matrix_get(AB, 4,2), 42); AssertEqual(&test, matrix_get(AB, 4,3), 48); AssertEqual(&test, matrix_get(AB, 5,0), 45); AssertEqual(&test, matrix_get(AB, 5,1), 0); AssertEqual(&test, matrix_get(AB, 5,2), 54); AssertEqual(&test, matrix_get(AB, 5,3), 0); matrix_free(AB); C = matrix_complex_alloc(2,2); D = matrix_complex_alloc(2,2); matrix_set(C, 0,0, CPLX(1,1)); matrix_set(C, 0,1, CPLX(2,-2)); matrix_set(C, 1,0, CPLX(5,0)); matrix_set(C, 1,1, CPLX(0,-1)); matrix_set(D, 0,0, CPLX(0,-1)); matrix_set(D, 0,1, CPLX(2,0)); matrix_set(D, 1,0, CPLX(5,0)); matrix_set(D, 1,1, CPLX(0,7)); CD = matrix_complex_alloc(4,4); matrix_complex_kron(C, D, CD); matrix_complex_free(C); matrix_complex_free(D); AssertEqual(&test, CREAL(matrix_get(CD, 0,0)), 1); AssertEqual(&test, CIMAG(matrix_get(CD, 0,0)), -1); AssertEqual(&test, CREAL(matrix_get(CD, 0,1)), 2); AssertEqual(&test, CIMAG(matrix_get(CD, 0,1)), 2); AssertEqual(&test, CREAL(matrix_get(CD, 0,2)), -2); AssertEqual(&test, CIMAG(matrix_get(CD, 0,2)), -2); AssertEqual(&test, CREAL(matrix_get(CD, 0,3)), 4); AssertEqual(&test, CIMAG(matrix_get(CD, 0,3)), -4); AssertEqual(&test, CREAL(matrix_get(CD, 1,0)), 5); AssertEqual(&test, CIMAG(matrix_get(CD, 1,0)), 5); AssertEqual(&test, CREAL(matrix_get(CD, 1,1)), -7); AssertEqual(&test, CIMAG(matrix_get(CD, 1,1)), 7); AssertEqual(&test, CREAL(matrix_get(CD, 1,2)), 10); AssertEqual(&test, CIMAG(matrix_get(CD, 1,2)), -10); AssertEqual(&test, CREAL(matrix_get(CD, 1,3)), 14); AssertEqual(&test, CIMAG(matrix_get(CD, 1,3)), 14); AssertEqual(&test, CREAL(matrix_get(CD, 2,0)), 0); AssertEqual(&test, CIMAG(matrix_get(CD, 2,0)), -5); AssertEqual(&test, CREAL(matrix_get(CD, 2,1)), 10); AssertEqual(&test, CIMAG(matrix_get(CD, 2,1)), 0); AssertEqual(&test, CREAL(matrix_get(CD, 2,2)), -1); AssertEqual(&test, CIMAG(matrix_get(CD, 2,2)), 0); AssertEqual(&test, CREAL(matrix_get(CD, 2,3)), 0); AssertEqual(&test, CIMAG(matrix_get(CD, 2,3)), -2); AssertEqual(&test, CREAL(matrix_get(CD, 3,0)), 25); AssertEqual(&test, CIMAG(matrix_get(CD, 3,0)), 0); AssertEqual(&test, CREAL(matrix_get(CD, 3,1)), 0); AssertEqual(&test, CIMAG(matrix_get(CD, 3,1)), 35); AssertEqual(&test, CREAL(matrix_get(CD, 3,2)), 0); AssertEqual(&test, CIMAG(matrix_get(CD, 3,2)), -5); AssertEqual(&test, CREAL(matrix_get(CD, 3,3)), 7); AssertEqual(&test, CIMAG(matrix_get(CD, 3,3)), 0); matrix_complex_free(CD); E = matrix_zeros(2,2, NULL); matrix_set(E, 0,0, 1); matrix_set(E, 1,1, 2); EE = matrix_kron(E, E, NULL); matrix_free(E); AssertEqual(&test, matrix_get(EE, 0,0), 1); AssertEqual(&test, matrix_get(EE, 1,1), 2); AssertEqual(&test, matrix_get(EE, 2,2), 2); AssertEqual(&test, matrix_get(EE, 3,3), 4); for(size_t i = 0; i < 4; i++) for(size_t j = 0; j < 4; j++) if(i != j) AssertEqual(&test, matrix_get(EE, i,j), 0); matrix_free(EE); return test_results(&test, stderr); } int main(int argc, char *argv[]) { test_matrix_zeros(); test_matrix_kron(); test_matrix_mult(); test_zeros(); test_trace(); return 0; }
{ "alphanum_fraction": 0.5859110169, "avg_line_length": 27.7647058824, "ext": "c", "hexsha": "8dc4d6c0c86eb3a7cba8bea2f534cc06fe216c45", "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": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "michael-hartmann/libhades", "max_forks_repo_path": "tests/tests.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "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": "michael-hartmann/libhades", "max_issues_repo_path": "tests/tests.c", "max_line_length": 71, "max_stars_count": 4, "max_stars_repo_head_hexsha": "81a2ab18dbf59975f8fbae0693a757b054b4501c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "michael-hartmann/libhades", "max_stars_repo_path": "tests/tests.c", "max_stars_repo_stars_event_max_datetime": "2019-08-28T20:09:32.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-03T15:07:53.000Z", "num_tokens": 3395, "size": 9440 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> double f1(double x, void* params) { return x*x; } double f2(double x, void* params) { return 1 / sqrt(x); } void calculateIntegralVoid(double (*f)(double x), double a, double b, int maxInterval, double expected) { FILE* output = fopen("integral.txt", "w"); int n = 1; while (n < maxInterval) { double dx = (b - a) / (double)n; double sum = 0; for (int i = 1; i < n; ++i) { sum += f(a + i * dx); } sum *= dx; fprintf (output,"%d %f\n", n, expected - sum); n++; } } int calculateIntegral(double (*f)(double x), double a, double b, int n, double expected, double error) { double dx = (b - a) / (double)n; double sum = 0; for (int i = 1; i < n; ++i) { sum += f(a + i * dx); } sum *= dx; if (fabs(sum - expected) < error) { printf("Sum with error %.1e error for %d samples: %.18f\n", error, n, sum); return 1; } printf("DIFFERENCE with error %.1e error for %d samples: %.18f\n", error, n, fabs(sum - expected)); return 1; } void tryFindIntergral(double (*f)(double x), double a, double b, double expected, double error, int step) { int interval = step; while (!calculateIntegral(f, a, b, interval, expected, error)) { interval += step; } } void gslIntegral(double (*f)(double x, void* params), double expected) { gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double result, error; double alpha = 1.0; gsl_function F; F.function = f; F.params = &alpha; gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000, w, &result, &error); printf ("result = % .18f\n", result); printf ("exact result = % .18f\n", expected); printf ("estimated error = % .18f\n", error); printf ("actual error = % .18f\n", result - expected); printf ("intervals = %zu\n", w->size); gsl_integration_workspace_free (w); } int main (int argc, char* argv[]) { // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-3, 1000); // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-4, 215000000); // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-5, 100000); // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-6, 1000000); // calculateIntegralVoid(f2, 0.0, 1.0, 100000, 2.0); gslIntegral(f2, 2.0); return 0; }
{ "alphanum_fraction": 0.565395654, "avg_line_length": 25.1443298969, "ext": "c", "hexsha": "35a87ece26506ed2e4809cbaef0837c1bf71b064", "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": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "komilll/mownit_linux", "max_forks_repo_path": "zad4/calkowanie.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "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": "komilll/mownit_linux", "max_issues_repo_path": "zad4/calkowanie.c", "max_line_length": 105, "max_stars_count": null, "max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "komilll/mownit_linux", "max_stars_repo_path": "zad4/calkowanie.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 794, "size": 2439 }
/****************************************************************************** * * * PROBLEM.C * * * * INITIAL CONDITIONS FOR BONDI INFLOW * * * ******************************************************************************/ #include "decs.h" // Local functions void coord_transform(double *Pr, int i, int j); double lfish_calc(double rmax) ; void set_problem_params() { } // Rootfinding for analytic Bondi solution #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> struct params { double r, mdot, n, C1, C2; }; double rfunc(double T, void *params) { struct params *p = (struct params *) params; //double r = p->r; double r = MY_MAX(2.5, p->r); // Solution breaks inside event horizon double mdot = p->mdot; double n = p->n; double C1 = p->C1; double C2 = p->C2; double resid = (pow(1. + (1. + n)*T,2)*(1. - 2.*mdot/r + pow(C1,2)/ (pow(r,4)*pow(T,2*n))) - C2); //printf("r = %e T = %e resid = %e\n", r, T, resid); return resid; //return (pow(1. + (1. + n)*T,2)*(1. - 2.*mdot/r + pow(C1,2)/ // (pow(r,4)*pow(T,2*n))) - C2); } double C1, C2, T_bondi[N1+2*NG][N2+2*NG], n; // Adapted from M. Chandra double get_Tfunc(double T, double r) { return pow(1.+(1.+n)*T,2.)*(1.-2./r+pow(C1/r/r/pow(T,n),2.))-C2; } double get_T(double r) { double rtol = 1.e-12; double ftol = 1.e-14; double Tmin = 0.6*(sqrt(C2) - 1.)/(n + 1); double Tmax = pow(C1*sqrt(2./r/r/r),1./n); double f0, f1, fh; double T0, T1, Th; T0 = 0.6*Tmin; f0 = get_Tfunc(T0, r); T1 = Tmax; f1 = get_Tfunc(T1, r); if (f0*f1 > 0.) { printf("Failed solving for T at r = %e C1 = %e C2 = %e\n", r, C1, C2); exit(-1); } Th = (f1*T0 - f0*T1)/(f1 - f0); fh = get_Tfunc(Th, r); double epsT = rtol*(Tmin + Tmax); while (fabs(Th - T0) > epsT && fabs(Th - T1) > epsT && fabs(fh) > ftol) { if (fh*f0 < 0.) { T0 = Th; f0 = fh; } else { T1 = Th; f1 = fh; } Th = (f1*T0 - f0*T1)/(f1 - f0); fh = get_Tfunc(Th, r); } return Th; } void bl_to_ks(double X[NDIM], double ucon_bl[NDIM], double ucon_ks[NDIM]) { double r, th; bl_coord(X, &r, &th); double trans[NDIM][NDIM]; DLOOP2 trans[mu][nu] = 0.; DLOOP1 trans[mu][mu] = 1.; trans[0][1] = 2.*r/(r*r - 2.*r + a*a); trans[3][1] = a/(r*r - 2.*r + a*a); DLOOP1 ucon_ks[mu] = 0.; DLOOP2 ucon_ks[mu] += trans[mu][nu]*ucon_bl[nu]; } void fourvel_to_prim(double ucon[NDIM], double prim[NVAR], struct of_geom *geom) { double alpha, beta[NDIM], gamma; alpha = 1.0/sqrt(-geom->gcon[0][0]); beta[1] = alpha*alpha*geom->gcon[0][1]; beta[2] = alpha*alpha*geom->gcon[0][2]; beta[3] = alpha*alpha*geom->gcon[0][3]; gamma = ucon[0]*alpha; prim[U1] = ucon[1] + beta[1]*gamma/alpha; prim[U2] = ucon[2] + beta[2]*gamma/alpha; prim[U3] = ucon[3] + beta[3]*gamma/alpha; } void set_ut(double ucon[NDIM], struct of_geom *geom) { double AA, BB, CC; AA = geom->gcov[0][0]; BB = 2.*(geom->gcov[0][1]*ucon[1] + geom->gcov[0][2]*ucon[2] + geom->gcov[0][3]*ucon[3]); CC = 1. + geom->gcov[1][1]*ucon[1]*ucon[1] + geom->gcov[2][2]*ucon[2]*ucon[2] + geom->gcov[3][3]*ucon[3]*ucon[3] + 2. *(geom->gcov[1][2]*ucon[1]*ucon[2] + geom->gcov[1][3]*ucon[1]*ucon[3] + geom->gcov[2][3]*ucon[2]*ucon[3]); double discr = BB*BB - 4.*AA*CC; ucon[0] = (-BB - sqrt(discr))/(2.*AA); } void get_prim_bondi(int i, int j, int k, double P[NVAR]) { double r, th, X[NDIM]; coord(i, j, k, CENT, X); bl_coord(X, &r, &th); while (r < Reh) { i++; coord(i, j, k, CENT, X); bl_coord(X, &r, &th); } double T = T_bondi[i][j]; double ur = -C1/(pow(T,n)*pow(r,2)); double rho = pow(T,n); double u = rho*T/(gam - 1.); double ucon_bl[NDIM], ucon_ks[NDIM], ucon_mks[NDIM]; struct of_geom geom_bl, *geom_mks; blgset(i, j, &geom_bl); DLOOP1 { ucon_bl[mu] = 0.; ucon_ks[mu] = 0.; ucon_mks[mu] = 0.; } ucon_bl[1] = ur; set_ut(ucon_bl, &geom_bl); bl_to_ks(X, ucon_bl, ucon_ks); double dxdX[NDIM][NDIM], dXdx[NDIM][NDIM]; set_dxdX(X, dxdX); invert(&dxdX[0][0], &dXdx[0][0]); DLOOP2 { ucon_mks[mu] += dXdx[mu][nu]*ucon_ks[nu]; } geom_mks = get_geometry(i, j, k, CENT); fourvel_to_prim(ucon_mks, P, geom_mks); //printf("[%i %i %i] r = %e ucons = %e %e %e vr = %e\n", // i, j, k, r, ucon_bl[1], ucon_ks[1], ucon_mks[1], P[U1]); P[RHO] = rho; P[UU] = u; P[B1] = 0.; P[B2] = 0.; P[B3] = 0.; /*if (j == N2/2){ printf("\nu[1]: %e %e %e\n", ucon_bl[1], ucon_ks[1], ucon_mks[1]); printf("T rho ur u = %e %e %e %e\n", T, rho, ur, u); printf("P[] = %e %e %e %e\n", P[0], P[1], P[2], P[3]); }*/ /*double gcov[NDIM][NDIM]; bl_gcov_func(r, th, gcov); double ut = -sqrt((-1. - gcov[1][1]*ur*ur)/gcov[0][0]); double ucon[NDIM] = {ut, ur, 0, 0}; // if ( j == NG) // printf("ucon[] = %e %e %e %e\n", ucon[0], ucon[1], ucon[2], ucon[3]); double trans[NDIM][NDIM]; // transform to Kerr-Schild // Make transform matrix memset(trans, 0, 16*sizeof(double)); for (int mu = 0; mu < NDIM; mu++) { trans[mu][mu] = 1.; } trans[0][1] = 2. * r / (r * r - 2. * r + a * a); trans[3][1] = a / (r * r - 2. * r + a * a); // Transform from BL to KS coordinates double tmp[NDIM]; for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.; for (int mu = 0; mu < NDIM; mu++) { for (int nu = 0; nu < NDIM; nu++) { tmp[mu] += trans[mu][nu]*ucon[nu]; } } for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu]; // Transform from KS to MKS coordinates set_dxdX(X, trans); for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.; for (int mu = 0; mu < NDIM; mu++) { for (int nu = 0; nu < NDIM; nu++) { tmp[mu] += trans[mu][nu]*ucon[nu]; } } for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu]; struct of_geom *geom = get_geometry(i, j, k, CENT); double alpha = 1.0 / sqrt( -geom->gcon[0][0] ) ; double gamma = ucon[0] * alpha; double beta[NDIM]; beta[1] = alpha * alpha * geom->gcon[0][1]; beta[2] = alpha * alpha * geom->gcon[0][2]; beta[3] = alpha * alpha * geom->gcon[0][3]; P[RHO] = rho; P[UU] = u; P[U1] = ucon[1] + beta[1] * gamma / alpha; P[U2] = 0.; P[U3] = 0.; P[B1] = 0.; P[B2] = 0.; P[B3] = 0.; if (r < 5.) P[U1] = 0.; //P[U1] *= 0.;*/ } /*void get_bondi_prim(double r, double P[NDIM]) { double T, rho, ur, ut; if (r > 2. + 1.e-8) { T = get_T(r); rho = pow(T, n); ur = -C1/r/r/pow(T,n); ut = (2.*ur/r+sqrt(ur*ur+1.-2./r))/(1.-2./r); } else { T = 1.; rho = RHOMIN; ur = 0.; ut = 1.; } P[RHO] = rho; P[UU] = n*rho*T; P[U1] = (ur + 2.*ut/(r + 2.))/r; P[U2] = 0.; P[U3] = 0.; P[B1] = 0.; P[B2] = 0.; P[B3] = 0.; }*/ void init_prob() { double r, th, X[NDIM]; double mdot = 1.; double rs = 8.; n = 1./(gam - 1.); // Solution constants double uc = sqrt(mdot/(2.*rs)); double Vc = -sqrt(pow(uc,2)/(1. - 3.*pow(uc,2))); double Tc = -n*pow(Vc,2)/((n + 1.)*(n*pow(Vc,2) - 1.)); C1 = uc*pow(rs,2)*pow(Tc,n); C2 = pow(1. + (1. + n)*Tc,2)*(1. - 2.*mdot/rs + pow(C1,2)/ (pow(rs,4)*pow(Tc,2*n))); printf("a = %e Reh = %e\n", a, Reh); printf("mdot = %e\n", mdot); printf("rs = %e\n", rs); printf("n = %e\n", n); printf("uc = %e\n", uc); printf("Vc = %e\n", Vc); printf("Tc = %e\n", Tc); printf("C1 = %e\n", C1); printf("C2 = %e\n", C2); ZSLOOP(-NG,N1+NG-1,-NG,N2+NG-1,-NG,N3+NG-1) { coord(i, j, k, CENT, X); bl_coord(X, &r, &th); T_bondi[i][j] = get_T(r); } ZLOOP { get_prim_bondi(i, j, k, P[i][j][k]); } // ZSLOOP } // Convert Boyer-Lindquist four-velocity to MKS 3-velocity void coord_transform(double *Pr, int ii, int jj) { double X[NDIM], r, th, ucon[NDIM], trans[NDIM][NDIM], tmp[NDIM]; double AA, BB, CC, discr; double alpha, gamma, beta[NDIM]; struct of_geom *geom, blgeom; coord(ii, jj, 0, CENT, X); bl_coord(X, &r, &th); blgset(ii, jj, &blgeom); ucon[1] = Pr[U1]; ucon[2] = Pr[U2]; ucon[3] = Pr[U3]; AA = blgeom.gcov[0][0]; BB = 2. * (blgeom.gcov[0][1] * ucon[1] + blgeom.gcov[0][2] * ucon[2] + blgeom.gcov[0][3] * ucon[3]); CC = 1. + blgeom.gcov[1][1] * ucon[1] * ucon[1] + blgeom.gcov[2][2] * ucon[2] * ucon[2] + blgeom.gcov[3][3] * ucon[3] * ucon[3] + 2. * (blgeom.gcov[1][2] * ucon[1] * ucon[2] + blgeom.gcov[1][3] * ucon[1] * ucon[3] + blgeom.gcov[2][3] * ucon[2] * ucon[3]); discr = BB * BB - 4. * AA * CC; ucon[0] = (-BB - sqrt(discr)) / (2. * AA); // This is ucon in BL coords // transform to Kerr-Schild // Make transform matrix memset(trans, 0, 16*sizeof(double)); for (int mu = 0; mu < NDIM; mu++) { trans[mu][mu] = 1.; } trans[0][1] = 2. * r / (r * r - 2. * r + a * a); trans[3][1] = a / (r * r - 2. * r + a * a); // Transform from BL to KS coordinates for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.; for (int mu = 0; mu < NDIM; mu++) { for (int nu = 0; nu < NDIM; nu++) { tmp[mu] += trans[mu][nu]*ucon[nu]; } } for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu]; // Transform from KS to MKS coordinates set_dxdX(X, trans); for (int mu = 0; mu < NDIM; mu++) tmp[mu] = 0.; for (int mu = 0; mu < NDIM; mu++) { for (int nu = 0; nu < NDIM; nu++) { tmp[mu] += trans[mu][nu]*ucon[nu]; } } for (int mu = 0; mu < NDIM; mu++) ucon[mu] = tmp[mu]; //ucon[1] *= (1. / (r - R0)); //ucon[1] /= dr_dx(X[1]); //ucon[2] *= // (1. / (M_PI + (1. - hslope) * M_PI * cos(2. * M_PI * X[2]))); //ucon[2] /= dth_dx(X[2]); // Solve for v. Use same u^t, unchanged under KS -> KS' geom = get_geometry(ii, jj, 0, CENT) ; alpha = 1.0 / sqrt( -geom->gcon[0][0] ) ; gamma = ucon[0] * alpha; beta[1] = alpha * alpha * geom->gcon[0][1]; beta[2] = alpha * alpha * geom->gcon[0][2]; beta[3] = alpha * alpha * geom->gcon[0][3]; Pr[U1] = ucon[1] + beta[1] * gamma / alpha; Pr[U2] = ucon[2] + beta[2] * gamma / alpha; Pr[U3] = ucon[3] + beta[3] * gamma / alpha; } double lfish_calc(double r) { return (((pow(a, 2) - 2. * a * sqrt(r) + pow(r, 2)) * ((-2. * a * r * (pow(a, 2) - 2. * a * sqrt(r) + pow(r, 2))) / sqrt(2. * a * sqrt(r) + (-3. + r) * r) + ((a + (-2. + r) * sqrt(r)) * (pow(r, 3) + pow(a, 2) * (2. + r))) / sqrt(1 + (2. * a) / pow (r, 1.5) - 3. / r))) / (pow(r, 3) * sqrt(2. * a * sqrt(r) + (-3. + r) * r) * (pow(a, 2) + (-2. + r) * r)) ); } void bound_gas_prob_x1r(int i, int j, int k, grid_prim_type P) { get_prim_bondi(i, j, k, P[i][j][k]); }
{ "alphanum_fraction": 0.4815827863, "avg_line_length": 26.1766109785, "ext": "c", "hexsha": "3f103e4bd09f047810a83a718a80e59def08bb48", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_path": "prob/bondi/problem.c", "max_issues_count": 13, "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_path": "prob/bondi/problem.c", "max_line_length": 80, "max_stars_count": 16, "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_path": "prob/bondi/problem.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z", "num_tokens": 4629, "size": 10968 }
/* Copyright (c) 2013, Taiga Nomi and the respective contributors All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "tiny_dnn/core/params/fully_params.h" #ifdef CNN_USE_CBLAS extern "C" { #include <cblas.h> } #endif namespace tiny_dnn { namespace kernels { inline void fully_connected_op_cblas(const tensor_t &in_data, const vec_t &W, const vec_t &bias, tensor_t &out_data, const core::fully_params &params, const bool layer_parallelize) { #ifdef CNN_USE_CBLAS size_t out_size = params.out_size_; size_t in_size = params.in_size_; float_t alpha = 1; float_t beta = 1; const float_t *input = in_data[0].data(); const float_t *weight = W.data(); float_t *output = out_data[0].data(); if (bias.empty()) memset(output, 0, sizeof(float_t) * out_size); else memcpy(output, bias.data(), sizeof(float_t) * out_size); #ifdef CNN_USE_DOUBLE cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, out_size, in_size, alpha, input, in_size, weight, out_size, beta, output, out_size); #else cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, out_size, in_size, alpha, input, in_size, weight, out_size, beta, output, out_size); #endif #endif // CNN_USE_CBLAS } } // namespace kernels } // namespace tiny_dnn
{ "alphanum_fraction": 0.6169681847, "avg_line_length": 30.8269230769, "ext": "h", "hexsha": "b9403e7ddc8a155ad515dd02bb48c1f6b6fe03fd", "lang": "C", "max_forks_count": 12, "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_head_hexsha": "ba452be4de67fa1d85d86f2425a3fa6e254205a4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "stillwater-sc/tiny-dnn", "max_forks_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "ba452be4de67fa1d85d86f2425a3fa6e254205a4", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "stillwater-sc/tiny-dnn", "max_issues_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_line_length": 80, "max_stars_count": 63, "max_stars_repo_head_hexsha": "4e6e151c464f47733e8f68c2b86dc32609d0c669", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tom01h/tiny-dnn", "max_stars_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "num_tokens": 404, "size": 1603 }
/* permutation/test.c * * Copyright (C) 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_test.h> unsigned int p5[120][5] = { {0, 1, 2, 3, 4}, {0, 1, 2, 4, 3}, {0, 1, 3, 2, 4}, {0, 1, 3, 4, 2}, {0, 1, 4, 2, 3}, {0, 1, 4, 3, 2}, {0, 2, 1, 3, 4}, {0, 2, 1, 4, 3}, {0, 2, 3, 1, 4}, {0, 2, 3, 4, 1}, {0, 2, 4, 1, 3}, {0, 2, 4, 3, 1}, {0, 3, 1, 2, 4}, {0, 3, 1, 4, 2}, {0, 3, 2, 1, 4}, {0, 3, 2, 4, 1}, {0, 3, 4, 1, 2}, {0, 3, 4, 2, 1}, {0, 4, 1, 2, 3}, {0, 4, 1, 3, 2}, {0, 4, 2, 1, 3}, {0, 4, 2, 3, 1}, {0, 4, 3, 1, 2}, {0, 4, 3, 2, 1}, {1, 0, 2, 3, 4}, {1, 0, 2, 4, 3}, {1, 0, 3, 2, 4}, {1, 0, 3, 4, 2}, {1, 0, 4, 2, 3}, {1, 0, 4, 3, 2}, {1, 2, 0, 3, 4}, {1, 2, 0, 4, 3}, {1, 2, 3, 0, 4}, {1, 2, 3, 4, 0}, {1, 2, 4, 0, 3}, {1, 2, 4, 3, 0}, {1, 3, 0, 2, 4}, {1, 3, 0, 4, 2}, {1, 3, 2, 0, 4}, {1, 3, 2, 4, 0}, {1, 3, 4, 0, 2}, {1, 3, 4, 2, 0}, {1, 4, 0, 2, 3}, {1, 4, 0, 3, 2}, {1, 4, 2, 0, 3}, {1, 4, 2, 3, 0}, {1, 4, 3, 0, 2}, {1, 4, 3, 2, 0}, {2, 0, 1, 3, 4}, {2, 0, 1, 4, 3}, {2, 0, 3, 1, 4}, {2, 0, 3, 4, 1}, {2, 0, 4, 1, 3}, {2, 0, 4, 3, 1}, {2, 1, 0, 3, 4}, {2, 1, 0, 4, 3}, {2, 1, 3, 0, 4}, {2, 1, 3, 4, 0}, {2, 1, 4, 0, 3}, {2, 1, 4, 3, 0}, {2, 3, 0, 1, 4}, {2, 3, 0, 4, 1}, {2, 3, 1, 0, 4}, {2, 3, 1, 4, 0}, {2, 3, 4, 0, 1}, {2, 3, 4, 1, 0}, {2, 4, 0, 1, 3}, {2, 4, 0, 3, 1}, {2, 4, 1, 0, 3}, {2, 4, 1, 3, 0}, {2, 4, 3, 0, 1}, {2, 4, 3, 1, 0}, {3, 0, 1, 2, 4}, {3, 0, 1, 4, 2}, {3, 0, 2, 1, 4}, {3, 0, 2, 4, 1}, {3, 0, 4, 1, 2}, {3, 0, 4, 2, 1}, {3, 1, 0, 2, 4}, {3, 1, 0, 4, 2}, {3, 1, 2, 0, 4}, {3, 1, 2, 4, 0}, {3, 1, 4, 0, 2}, {3, 1, 4, 2, 0}, {3, 2, 0, 1, 4}, {3, 2, 0, 4, 1}, {3, 2, 1, 0, 4}, {3, 2, 1, 4, 0}, {3, 2, 4, 0, 1}, {3, 2, 4, 1, 0}, {3, 4, 0, 1, 2}, {3, 4, 0, 2, 1}, {3, 4, 1, 0, 2}, {3, 4, 1, 2, 0}, {3, 4, 2, 0, 1}, {3, 4, 2, 1, 0}, {4, 0, 1, 2, 3}, {4, 0, 1, 3, 2}, {4, 0, 2, 1, 3}, {4, 0, 2, 3, 1}, {4, 0, 3, 1, 2}, {4, 0, 3, 2, 1}, {4, 1, 0, 2, 3}, {4, 1, 0, 3, 2}, {4, 1, 2, 0, 3}, {4, 1, 2, 3, 0}, {4, 1, 3, 0, 2}, {4, 1, 3, 2, 0}, {4, 2, 0, 1, 3}, {4, 2, 0, 3, 1}, {4, 2, 1, 0, 3}, {4, 2, 1, 3, 0}, {4, 2, 3, 0, 1}, {4, 2, 3, 1, 0}, {4, 3, 0, 1, 2}, {4, 3, 0, 2, 1}, {4, 3, 1, 0, 2}, {4, 3, 1, 2, 0}, {4, 3, 2, 0, 1}, {4, 3, 2, 1, 0} } ; int main (void) { int i = 0, j, status = 0; gsl_permutation * p ; p = gsl_permutation_alloc (5); gsl_permutation_init (p); do { for (j = 0; j < 5; j++) { status |= (p->data[j] != p5[i][j]); } i++; } while (gsl_permutation_next(p) == GSL_SUCCESS); gsl_test(status, "gsl_permutation_next, 5-th order permutation, 120 steps"); do { i--; for (j = 0; j < 5; j++) { status |= (p->data[j] != p5[i][j]); } } while (gsl_permutation_prev(p) == GSL_SUCCESS); gsl_test(status, "gsl_permutation_prev, 5-th order permutation, 120 steps"); gsl_permutation_free (p); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.4408945687, "avg_line_length": 36.8235294118, "ext": "c", "hexsha": "270bdc9776e64ec0cd9cbb33026951b1a716ff69", "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/permutation/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/permutation/test.c", "max_line_length": 78, "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/permutation/test.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2289, "size": 3756 }
#ifndef __INCLUDE_EMUPLUSPLUS__ #define __INCLUDE_EMUPLUSPLUS__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <string> #include <vector> extern "C"{ #include "multi_modelstruct.h" #include "multivar_support.h" } using namespace std; /** * @file emuplusplus.h * \brief a simple c++ interface to a trained emulator * * Instance of the emulator class are built from a trained emulator, * the emulator can then be sampled at a point in the parameter space by the function QueryEmulator * * They must be initialized from an interactive_emulator statefile, this includes all the data for * a trained emulator * */ class emulator{ public: emulator(string StateFilePath); // default constructor will return Y values emulator(string StateFilePath, bool PcaOnly); ~emulator(); /** query the emulator with a vector xpoint in the parameter space * could add a method to output the means, errors and a covaraince matrix */ void QueryEmulator(const vector<double> &xpoint, vector<double> &Means, vector<double> &Errors); /** * get the emulator pca decomp */ void getEmulatorPCA(vector<double> *pca_evals, vector< vector<double> > *pca_evecs, vector<double> *pca_mean); int getRegressionOrder(void){return(the_model->regression_order);}; int getCovFnIndex(void){return(the_model->cov_fn_index);}; int number_params; int number_outputs; private: // if true the values are output in the pca space, otherwise they're in the real space bool outputPCAValues; string StateFilePath; multi_modelstruct *the_model; // the c structure which defines the model multi_emulator *the_emulator; // the c structure which defines the emulator gsl_vector *the_emulate_point; gsl_vector *the_emulate_mean; gsl_vector *the_emulate_var; }; #endif
{ "alphanum_fraction": 0.7543079489, "avg_line_length": 26.0724637681, "ext": "h", "hexsha": "56bb9b55ebd88b739181934b2f68df5b724213c4", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_path": "src/EmuPlusPlus.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "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": "MADAI/MADAIEmulator", "max_issues_repo_path": "src/EmuPlusPlus.h", "max_line_length": 111, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/EmuPlusPlus.h", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "num_tokens": 443, "size": 1799 }
/* * Copyright 2020 Makani Technologies LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIM_MODELS_SENSORS_LOADCELL_H_ #define SIM_MODELS_SENSORS_LOADCELL_H_ #include <gsl/gsl_vector.h> #include <stdint.h> #include <functional> #include <vector> #include "common/c_math/vec2.h" #include "common/c_math/vec3.h" #include "common/macros.h" #include "control/system_types.h" #include "sim/faults/faults.h" #include "sim/models/sensors/sensor.h" #include "sim/models/signals/measurement.h" #include "sim/sim_messages.h" namespace sim { void TetherForceToLoadcells(const WingParams &wing_params, const LoadcellParams loadcell_params[], const Vec3 &tether_force_b, double loadcell_forces[]); } // namespace sim class Loadcell : public Sensor { friend class LoadcellTest; public: Loadcell(const LoadcellParams *loadcell_params, const LoadcellSimParams &loadcell_sim_params, const WingParams &wing_params, FaultSchedule *faults); ~Loadcell() {} void UpdateSensorOutputs(SimSensorMessage *sensor_message, TetherUpMessage * /*tether_up*/) const override; void Publish() const override; void set_Fb_tether(const Vec3 &val) { Fb_tether_.set_val(val); } void set_tether_released(bool val) { tether_released_.set_val(val); } private: void DiscreteStepHelper(double t) override; double tensions(int32_t i) const { return tensions_[i].recorded(); } const Vec3 &Fb_tether() const { return Fb_tether_.val(); } // Loadcell parameters. const LoadcellParams *loadcell_params_; const LoadcellSimParams &loadcell_sim_params_; const WingParams &wing_params_; // Input states. State<Vec3> Fb_tether_; State<bool> tether_released_; // Discrete state. std::vector<DiscreteState<double>> actual_tensions_; // Sub-models. std::vector<Measurement<double>> tensions_; DISALLOW_COPY_AND_ASSIGN(Loadcell); }; #endif // SIM_MODELS_SENSORS_LOADCELL_H_
{ "alphanum_fraction": 0.7227683838, "avg_line_length": 30.2738095238, "ext": "h", "hexsha": "f22e813f8fe05771531f4e1994232713cd1d2d65", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "sim/models/sensors/loadcell.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "sim/models/sensors/loadcell.h", "max_line_length": 75, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "sim/models/sensors/loadcell.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": 606, "size": 2543 }
#include <stdio.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_const_cgsm.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include "global.h" #include "eos_pres.h" #include "eos_rho.h" #include "param.h" // the system of ODEs to be integrated int func (double r, const double y[], double f[], void *params) { struct param *myparams = (struct param *) params; double (*pres) (double, void *); // EOS pressure pointer double (*rho) (double, void *); // EOS density pointer pres = &eos_pres; rho = &eos_rho; // set a minimum pressure cutoff. if we don't, the ODE solver will wobble all // over the surface and crash, or if you make the error tolerance really strict // it'll integrate forever if (y[1] < 1.0e-9 * myparams->pinit) { if (myparams->single_star == 0) { printf ("surface reached!\n"); printf ("%12s %12s %12s\n", "R (km)", "M (M_sun)", "rho(0) (g/cm^3)"); } printf ("%12le %12le %12le\n", r / 1.0e+5, y[0] / GSL_CONST_CGSM_SOLAR_MASS, myparams->rho_init); return GSL_EBADFUNC; // this flag tells GSL integrator to quit } // for a single star we can print M, P and rho as functions of r if (myparams->single_star == 0) { printf ("%12le %12le %12le %12le\n", r / 1.0e+5, y[0] / GSL_CONST_CGSM_SOLAR_MASS, y[1], rho (y[1], myparams)); } // mass conservation equation f[0] = 4.0 * M_PI * pow (r, 2.0) * rho (y[1], myparams); // TOV equation f[1] = -(GSL_CONST_CGSM_GRAVITATIONAL_CONSTANT / pow (r, 2.0)) * (rho (y[1], myparams) + (y[1] / pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0))) * (y[0] + 4 * M_PI * pow (r, 3.0) * y[1] / pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0)) / (1.0 - (2.0 * GSL_CONST_CGSM_GRAVITATIONAL_CONSTANT * y[0] / (pow (GSL_CONST_CGSM_SPEED_OF_LIGHT, 2.0) * r))); // ODEs tend to return NaNs at the same radius where P < 0 if ((gsl_isnan (f[0]) || gsl_isnan (f[1]))) { /* print values at the radius where ODEs diverge. this is almost always at the surface */ printf ("%12f %12f %12f\n", r / 1.0e+5, y[0] / GSL_CONST_CGSM_SOLAR_MASS, myparams->rho_init); return GSL_EBADFUNC; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6198459447, "avg_line_length": 32.4558823529, "ext": "c", "hexsha": "8f3338df32a5165b85010c3c42a6fd779a4bb22d", "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": "5288ad6972b47143e1ce57e282f516143f07b158", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "bcfriesen/TOV_solver", "max_forks_repo_path": "src/func.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "bcfriesen/TOV_solver", "max_issues_repo_path": "src/func.c", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "bcfriesen/TOV_solver", "max_stars_repo_path": "src/func.c", "max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z", "num_tokens": 774, "size": 2207 }
/* (rho v, u) = ( v , div(C : grad(u)) ) + (v,F) where (v,F) = (v, Mp delta_1) + (v, -div(-Ms delta_2 )) (rho v, u) = -(grad(v) , C : grad(u)) + (v, sigma.n)_ds + (v, Mp delta_1) + (grad(v), Ms delta_2 ) - (v, (Ms delta_2 ).n)_ds = -(grad(v) , C : grad(u)) +(v, Mp delta_1 ) + (grad(v), Ms delta_2 ) + (v, sigma.n)_ds - (v, (-Ms delta_2 ).n)_ds ==> which will be dropped as we assume the source does not intersect with the boundary */ #include <petsc.h> #include <petsctime.h> #include <petscksp.h> #include <petscdm.h> #include <petscdmda.h> #include "rupture.h" typedef enum { TENS2D_XX=0, TENS2D_YY=1, TENS2D_XY=2 } VoigtTensor2d; typedef struct _p_SpecFECtx *SpecFECtx; typedef struct { PetscInt region; PetscReal lambda,mu; PetscReal rho; } QPntIsotropicElastic; struct _p_SpecFECtx { PetscMPIInt rank,size; PetscInt basisorder; PetscInt mx,my,mz; PetscInt mx_g,my_g,mz_g,nx_g,ny_g,nz_g; //PetscReal dx,dy,dz; PetscInt dim; PetscInt dofs; DM dm; PetscInt npe,npe_1d,ne,ne_g; PetscInt *element; PetscReal *xi1d,*w1d,*w; PetscReal *elbuf_coor,*elbuf_field,*elbuf_field2; PetscInt *elbuf_dofs; PetscInt nqp; QPntIsotropicElastic *cell_data; PetscReal **dN_dxi,**dN_deta; PetscReal **dN_dx,**dN_dy; //PetscInt source_implementation; /* DR */ /* DR */ PetscReal delta; /* fault thickness */ PetscReal *elbuf_field3; /* additional element buffer (will hold velocity) */ DRVar *dr_qp_data; /* stores data like slip, slip-rate */ PetscReal mu_s,mu_d,D_c; /* linear slip weakening parameters */ }; typedef struct { PetscReal xi[2]; PetscInt nbasis; PetscInt *element_indices; PetscReal *element_values; PetscReal *buffer; } PointwiseContext; /** * Function to calculate weighting for the traction */ PetscErrorCode PetscTanHWeighting(PetscReal *Result, PetscReal ValueTrial, PetscReal CritValue, PetscReal phi, PetscReal Amplitude, PetscReal Offset) { PetscReal weight; weight = 0.5 * PetscTanhReal((PetscAbsReal(phi)-Offset) * Amplitude) + 0.5; Result[0] = CritValue * (1.0 - weight) + ValueTrial * weight ; PetscFunctionReturn(0); } /** * Function to calculate the new KV timestep following Galvez (2014) eq 27. * dT_KV = (sqrt(1+(eta*eta)/(dT*dT))-eta/dT) */ void GetStableTimeStep(double dT, double eta, double * dT_KV) { dT_KV[0] = (sqrt(1 + (eta/dT) * (eta/dT)) - eta / dT)*dT; } /* warp for dr mesh get ymax plot (exp(4*x)-1)/exp(4),x s = y / ymax s' = (exp(4*s)-1)/exp(4) */ PetscErrorCode warp_y_exp(SpecFECtx c,PetscReal factor) { PetscInt i,N; PetscReal ymax = -1.0e32,s[2],sp[2]; Vec coor; PetscScalar *_coor; PetscErrorCode ierr; DMGetCoordinates(c->dm,&coor); VecGetSize(coor,&N); N = N / 2; VecGetArray(coor,&_coor); for (i=0; i<N; i++) { ymax = PetscMax(ymax,_coor[2*i+1]); } for (i=0; i<N; i++) { s[0] = _coor[2*i+0]; s[1] = _coor[2*i+1]; // normalize to 1 s[1] = s[1] / ymax; sp[0] = s[0]; sp[1] = s[1]; if (s[1] >= 0.0) { sp[1] = (PetscExpReal(factor * s[1]) - 1.0)/PetscExpReal(factor); } else { PetscReal _s = PetscAbsReal(s[1]); sp[1] = -(PetscExpReal(factor * _s) - 1.0)/PetscExpReal(factor); } sp[1] *= ymax; _coor[2*i+0] = sp[0]; _coor[2*i+1] = sp[1]; } VecRestoreArray(coor,&_coor); PetscFunctionReturn(0); } /* N = polynomial order */ PetscErrorCode CreateGLLCoordsWeights(PetscInt N,PetscInt *_npoints,PetscReal **_xi,PetscReal **_w) { PetscInt N1; PetscReal *xold,*x,*w,*P; PetscReal eps,res; PetscInt i,j,k; PetscErrorCode ierr; // Truncation + 1 N1 = N + 1; ierr = PetscMalloc(sizeof(PetscReal)*N1,&xold);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*N1,&x);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*N1,&w);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*N1*N1,&P);CHKERRQ(ierr); // Use the Chebyshev-Gauss-Lobatto nodes as the first guess for (i=0; i<N1; i++) { x[i]=PetscCosReal(PETSC_PI*i/(PetscReal)N); } // The Legendre Vandermonde Matrix for (i=0; i<N1; i++) { for (j=0; j<N1; j++) { P[i+j*N1] = 0.0; } } // Compute P_(N) using the recursion relation // Compute its first and second derivatives and // update x using the Newton-Raphson method. for (i=0; i<N1; i++) { xold[i]=2.0; } res = 1.0; eps = 1.0e-12; while (res > eps) { //xold=x; for (i=0; i<N1; i++) { xold[i] = x[i]; } //P(:,1)=1; P(:,2)=x; for (i=0; i<N1; i++) { for (j=0; j<N1; j++) { P[i+0*N1] = 1.0; P[i+1*N1] = x[i]; } } //for k=2:N // P(:,k+1)=( (2*k-1)*x.*P(:,k)-(k-1)*P(:,k-1) )/k; //end for (i=0; i<N1; i++) { for (k=1; k<N; k++) { P[i+(k+1)*N1] = ( (2.0*(k+1)-1.0)*x[i] * P[i+k*N1] - (k+1.0-1.0) * P[i+(k-1)*N1] ) / (PetscReal)(k+1.0); } } //x=xold-( x.*P(:,N1)-P(:,N) )./( N1*P(:,N1) ); for (i=0; i<N1; i++) { x[i] = xold[i] - (x[i] * P[i+(N1-1)*N1] - P[i+(N-1)*N1]) / ( N1 * P[i+(N1-1)*N1] ); } res = 0.0; for (i=0; i<N1; i++) { res += (x[i] - xold[i])*(x[i] - xold[i]); } res = PetscSqrtReal(res); } // w=2./(N*N1*P(:,N1).^2); for (i=0; i<N1; i++) { PetscReal pp = P[i+(N1-1)*N1]; w[i] = 2.0 / (N*N1*pp*pp); } if (_xi) { /* flip order so they are ordered from -1 to 1 */ for (i=0; i<N1/2; i++) { PetscReal tmp; tmp = x[i]; x[i] = x[N1-1-i]; x[N1-1-i] = tmp; } *_xi = x; } else { ierr = PetscFree(x);CHKERRQ(ierr); } if (_npoints) { *_npoints = N1; } if (_w) { *_w = w; } else { ierr = PetscFree(w);CHKERRQ(ierr); } ierr = PetscFree(xold);CHKERRQ(ierr); ierr = PetscFree(P);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode MatComputeConditionNumber(Mat A,PetscReal *cond) { PetscReal *realpt,*complexpt,*nrmeigs; PetscInt rank,i; KSP kspV; PC pc; Vec x,y; PetscErrorCode ierr; ierr = MatCreateVecs(A,&y,&x);CHKERRQ(ierr); ierr = VecSet(y,1.0);CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_SELF,&kspV);CHKERRQ(ierr); ierr = KSPSetOperators(kspV,A,A);CHKERRQ(ierr); ierr = KSPSetType(kspV,KSPPREONLY);CHKERRQ(ierr); ierr = KSPGetPC(kspV,&pc);CHKERRQ(ierr); ierr = PCSetType(pc,PCNONE);CHKERRQ(ierr); ierr = KSPSolve(kspV,y,x);CHKERRQ(ierr); ierr = MatGetSize(A,&rank,0);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*rank,&realpt);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*rank,&complexpt);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*rank,&nrmeigs);CHKERRQ(ierr); ierr = KSPComputeEigenvaluesExplicitly(kspV,rank,realpt,complexpt);CHKERRQ(ierr); for (i=0; i<rank; i++) { nrmeigs[i] = PetscSqrtReal( realpt[i]*realpt[i] + complexpt[i]*complexpt[i]); } ierr = PetscSortReal(rank,nrmeigs);CHKERRQ(ierr); *cond = nrmeigs[rank-1]/nrmeigs[0]; ierr = PetscFree(nrmeigs);CHKERRQ(ierr); ierr = PetscFree(realpt);CHKERRQ(ierr); ierr = PetscFree(complexpt);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = KSPDestroy(&kspV);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode TabulateBasis1d_CLEGENDRE(PetscInt npoints,PetscReal xi[],PetscInt order,PetscInt *_nbasis,PetscReal ***_Ni) { PetscErrorCode ierr; PetscReal **Ni,*xilocal,**basis_coeff, *monomials; PetscInt i,j,k,p; PetscInt nbasis,cnt; Mat A; Vec x,y; KSP ksp; PC pc; ierr = CreateGLLCoordsWeights(order,&nbasis,&xilocal,NULL);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&monomials);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*npoints,&Ni);CHKERRQ(ierr); for (i=0; i<npoints; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&Ni[i]);CHKERRQ(ierr); } ierr = PetscMalloc(sizeof(PetscReal*)*nbasis,&basis_coeff);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&basis_coeff[i]);CHKERRQ(ierr); } /* generate all the basis coefficients */ ierr = MatCreateSeqDense(PETSC_COMM_SELF,nbasis,nbasis,NULL,&A);CHKERRQ(ierr); for (k=0; k<nbasis; k++) { PetscReal xil,Aij; xil = xilocal[k]; cnt = 0; for (i=0; i<nbasis; i++) { Aij = PetscPowReal(xil,(PetscReal)i); ierr = MatSetValue(A,k,cnt,Aij,INSERT_VALUES);CHKERRQ(ierr); cnt++; } } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); { PetscReal cond; PetscBool compute_vandermonde_condition = PETSC_FALSE; ierr = PetscOptionsGetBool(NULL,NULL,"-compute_vandermonde_condition",&compute_vandermonde_condition,NULL);CHKERRQ(ierr); if (compute_vandermonde_condition) { PetscPrintf(PETSC_COMM_WORLD,"Computing condition number of Vandermonde matrix\n"); ierr = MatComputeConditionNumber(A,&cond);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"cond(V) = %1.6e \n",cond); } } ierr = MatCreateVecs(A,&x,&y);CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_SELF,&ksp);CHKERRQ(ierr); ierr = KSPSetOptionsPrefix(ksp,"basis_");CHKERRQ(ierr); ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr); ierr = KSPSetType(ksp,KSPPREONLY);CHKERRQ(ierr); ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); ierr = PCSetType(pc,PCLU);CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr); for (k=0; k<nbasis; k++) { const PetscScalar *LA_x; ierr = VecZeroEntries(y);CHKERRQ(ierr); ierr = VecSetValue(y,k,1.0,INSERT_VALUES);CHKERRQ(ierr); ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); ierr = KSPSolve(ksp,y,x);CHKERRQ(ierr); ierr = VecGetArrayRead(x,&LA_x);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { basis_coeff[k][i] = LA_x[i]; } ierr = VecRestoreArrayRead(x,&LA_x);CHKERRQ(ierr); } /* evaluate basis at each xi[] */ for (p=0; p<npoints; p++) { /* generate all monomials for point, p */ cnt = 0; for (i=0; i<nbasis; i++) { monomials[cnt] = PetscPowReal((PetscReal)xi[p],(PetscReal)i); cnt++; } for (i=0; i<nbasis; i++) { Ni[p][i] = 0.0; for (j=0; j<nbasis; j++) { Ni[p][i] += basis_coeff[i][j] * monomials[j]; } if (PetscAbsReal(Ni[p][i]) < 1.0e-12) { Ni[p][i] = 0.0; } } /* printf("p = %d (xi = %+1.4e) N = [",p,xi[p]); for (i=0; i<nbasis; i++) { printf(" %+1.4e ",Ni[p][i]); } printf("]\n"); */ } //for (p=0; p<npoints; p++) { // ierr = PetscFree(Ni[p]);CHKERRQ(ierr); //} //ierr = PetscFree(Ni);CHKERRQ(ierr); *_Ni = Ni; *_nbasis = nbasis; ierr = PetscFree(monomials);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { ierr = PetscFree(basis_coeff[i]);CHKERRQ(ierr); } ierr = PetscFree(basis_coeff);CHKERRQ(ierr); ierr = PetscFree(xilocal);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = KSPDestroy(&ksp);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode TabulateBasisDerivatives1d_CLEGENDRE(PetscInt npoints,PetscReal xi[],PetscInt order,PetscInt *_nbasis,PetscReal ***_GNix) { PetscErrorCode ierr; PetscReal **GNix,*xilocal,**basis_coeff, *monomials; PetscInt i,j,k,p; PetscInt nbasis,cnt; Mat A; Vec x,y; KSP ksp; PC pc; ierr = CreateGLLCoordsWeights(order,&nbasis,&xilocal,NULL);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&monomials);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*npoints,&GNix);CHKERRQ(ierr); for (i=0; i<npoints; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&GNix[i]);CHKERRQ(ierr); } ierr = PetscMalloc(sizeof(PetscReal*)*nbasis,&basis_coeff);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&basis_coeff[i]);CHKERRQ(ierr); } /* generate all the basis coefficients */ ierr = MatCreateSeqDense(PETSC_COMM_SELF,nbasis,nbasis,NULL,&A);CHKERRQ(ierr); for (k=0; k<nbasis; k++) { PetscReal xil,Aij; xil = xilocal[k]; cnt = 0; for (i=0; i<nbasis; i++) { Aij = PetscPowReal(xil,(PetscReal)i); ierr = MatSetValue(A,k,cnt,Aij,INSERT_VALUES);CHKERRQ(ierr); cnt++; } } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); { PetscReal cond; PetscBool compute_vandermonde_condition = PETSC_FALSE; ierr = PetscOptionsGetBool(NULL,NULL,"-compute_vandermonde_condition",&compute_vandermonde_condition,NULL);CHKERRQ(ierr); if (compute_vandermonde_condition) { PetscPrintf(PETSC_COMM_WORLD,"Computing condition number of Vandermonde matrix\n"); ierr = MatComputeConditionNumber(A,&cond);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"cond(V) = %1.6e \n",cond); } } ierr = MatCreateVecs(A,&x,&y);CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_SELF,&ksp);CHKERRQ(ierr); ierr = KSPSetOptionsPrefix(ksp,"basis_");CHKERRQ(ierr); ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr); ierr = KSPSetType(ksp,KSPPREONLY);CHKERRQ(ierr); ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); ierr = PCSetType(pc,PCLU);CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr); for (k=0; k<nbasis; k++) { const PetscScalar *LA_x; ierr = VecZeroEntries(y);CHKERRQ(ierr); ierr = VecSetValue(y,k,1.0,INSERT_VALUES);CHKERRQ(ierr); ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); ierr = KSPSolve(ksp,y,x);CHKERRQ(ierr); ierr = VecGetArrayRead(x,&LA_x);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { basis_coeff[k][i] = LA_x[i]; } ierr = VecRestoreArrayRead(x,&LA_x);CHKERRQ(ierr); } /* evaluate basis at each xi[] */ for (p=0; p<npoints; p++) { /* generate all monomials for point, p */ cnt = 0; for (i=0; i<nbasis; i++) { PetscReal dm_dx; if (i == 0) { dm_dx = 0.0; } else { dm_dx = ((PetscReal)i)*PetscPowReal((PetscReal)xi[p],(PetscReal)(i-1)); } monomials[cnt] = dm_dx; cnt++; } for (i=0; i<nbasis; i++) { GNix[p][i] = 0.0; for (j=0; j<nbasis; j++) { GNix[p][i] += basis_coeff[i][j] * monomials[j]; } if (PetscAbsReal(GNix[p][i]) < 1.0e-12) { GNix[p][i] = 0.0; } } /* printf("p = %d (xi = %+1.4e) dN_dx = [",p,xi[p]); for (i=0; i<nbasis; i++) { printf(" %+1.4e ",GNix[p][i]); } printf("]\n"); */ } ierr = PetscFree(monomials);CHKERRQ(ierr); for (i=0; i<nbasis; i++) { ierr = PetscFree(basis_coeff[i]);CHKERRQ(ierr); } ierr = PetscFree(basis_coeff);CHKERRQ(ierr); ierr = PetscFree(xilocal);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = KSPDestroy(&ksp);CHKERRQ(ierr); *_nbasis = nbasis; *_GNix = GNix; PetscFunctionReturn(0); } PetscErrorCode TabulateBasisDerivativesTensorProduct2d(PetscInt order,PetscReal ***_dN_dxi,PetscReal ***_dN_deta) { PetscErrorCode ierr; PetscReal *xiq,**dphi_xi,**dN_dxi,**dN_deta; PetscInt qpoint,k,i,j,qi,qj,nqp,nbasis; ierr = CreateGLLCoordsWeights(order,&nqp,&xiq,NULL);CHKERRQ(ierr); ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,xiq,order,&nbasis,&dphi_xi);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*nqp*nqp,&dN_dxi);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*nqp*nqp,&dN_deta);CHKERRQ(ierr); for (i=0; i<nqp*nqp; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_dxi[i]);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_deta[i]);CHKERRQ(ierr); } qpoint = 0; for (qj=0; qj<nqp; qj++) { for (qi=0; qi<nqp; qi++) { k = 0; for (j=0; j<nbasis; j++) { for (i=0; i<nbasis; i++) { PetscReal phi_xi,phi_eta; phi_xi = 0.0; if (qi == i) phi_xi = 1.0; phi_eta = 0.0; if (qj == j) phi_eta = 1.0; dN_dxi[qpoint][k] = dphi_xi[qi][i] * phi_eta; dN_deta[qpoint][k] = phi_xi * dphi_xi[qj][j]; k++; }} qpoint++; }} /* viewer */ /* for (k=0; k<nqp*nqp; k++) { printf("qp[%d]: dNdxi = [ ",k); for (j=0; j<nbasis*nbasis; j++) { printf(" %+1.4e ",dN_dxi[k][j]); } printf("]\n"); printf("qp[%d]: dNdeta = [ ",k); for (j=0; j<nbasis*nbasis; j++) { printf(" %+1.4e ",dN_deta[k][j]); } printf("]\n"); } */ /* free up mempry */ ierr = PetscFree(xiq);CHKERRQ(ierr); for (k=0; k<nqp; k++) { ierr = PetscFree(dphi_xi[k]);CHKERRQ(ierr); } ierr = PetscFree(dphi_xi);CHKERRQ(ierr); if (_dN_dxi) { *_dN_dxi = dN_dxi; } else { for (k=0; k<nqp*nqp; k++) { ierr = PetscFree(dN_dxi[k]);CHKERRQ(ierr); } ierr = PetscFree(dN_dxi);CHKERRQ(ierr); } if (_dN_deta) { *_dN_deta = dN_deta; } else { for (k=0; k<nqp*nqp; k++) { ierr = PetscFree(dN_deta[k]);CHKERRQ(ierr); } ierr = PetscFree(dN_deta);CHKERRQ(ierr); } PetscFunctionReturn(0); } PetscErrorCode TabulateBasisDerivativesAtPointTensorProduct2d(PetscReal xiq[],PetscInt order,PetscReal ***_dN_dxi,PetscReal ***_dN_deta) { PetscErrorCode ierr; PetscReal **dphi_xi,**Ni_xi,**dphi_eta,**Ni_eta,**dN_dxi,**dN_deta; PetscInt qpoint,k,i,j,q,nqp,nbasis; nqp = 1; ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,&xiq[0],order,&nbasis,&dphi_xi);CHKERRQ(ierr); ierr = TabulateBasis1d_CLEGENDRE(nqp,&xiq[0],order,&nbasis,&Ni_xi);CHKERRQ(ierr); ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,&xiq[1],order,&nbasis,&dphi_eta);CHKERRQ(ierr); ierr = TabulateBasis1d_CLEGENDRE(nqp,&xiq[1],order,&nbasis,&Ni_eta);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*nqp,&dN_dxi);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal*)*nqp,&dN_deta);CHKERRQ(ierr); for (i=0; i<nqp; i++) { ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_dxi[i]);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_deta[i]);CHKERRQ(ierr); } qpoint = 0; for (q=0; q<nqp; q++) { k = 0; for (j=0; j<nbasis; j++) { for (i=0; i<nbasis; i++) { PetscReal phi_xi,phi_eta; phi_xi = Ni_xi[q][i]; phi_eta = Ni_eta[q][j]; dN_dxi[qpoint][k] = dphi_xi[q][i] * phi_eta; dN_deta[qpoint][k] = phi_xi * dphi_eta[q][j]; k++; }} qpoint++; } /* viewer */ /* for (k=0; k<nqp; k++) { printf("qp[%d]: dNdxi = [ ",k); for (j=0; j<nbasis*nbasis; j++) { printf(" %+1.4e ",dN_dxi[k][j]); } printf("]\n"); printf("qp[%d]: dNdeta = [ ",k); for (j=0; j<nbasis*nbasis; j++) { printf(" %+1.4e ",dN_deta[k][j]); } printf("]\n"); } */ /* free up mempry */ for (k=0; k<nqp; k++) { ierr = PetscFree(dphi_xi[k]);CHKERRQ(ierr); ierr = PetscFree(dphi_eta[k]);CHKERRQ(ierr); } ierr = PetscFree(dphi_xi);CHKERRQ(ierr); ierr = PetscFree(dphi_eta);CHKERRQ(ierr); for (k=0; k<nqp; k++) { ierr = PetscFree(Ni_xi[k]);CHKERRQ(ierr); ierr = PetscFree(Ni_eta[k]);CHKERRQ(ierr); } ierr = PetscFree(Ni_xi);CHKERRQ(ierr); ierr = PetscFree(Ni_eta);CHKERRQ(ierr); if (_dN_dxi) { *_dN_dxi = dN_dxi; } else { for (k=0; k<nqp*nqp; k++) { ierr = PetscFree(dN_dxi[k]);CHKERRQ(ierr); } ierr = PetscFree(dN_dxi);CHKERRQ(ierr); } if (_dN_deta) { *_dN_deta = dN_deta; } else { for (k=0; k<nqp*nqp; k++) { ierr = PetscFree(dN_deta[k]);CHKERRQ(ierr); } ierr = PetscFree(dN_deta);CHKERRQ(ierr); } PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreate(SpecFECtx *c) { SpecFECtx ctx; PetscErrorCode ierr; ierr = PetscMalloc(sizeof(struct _p_SpecFECtx),&ctx);CHKERRQ(ierr); ierr = PetscMemzero(ctx,sizeof(struct _p_SpecFECtx));CHKERRQ(ierr); ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&ctx->rank);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&ctx->size);CHKERRQ(ierr); *c = ctx; PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateENMap2d_SEQ(SpecFECtx c) { PetscErrorCode ierr; PetscInt ni0,nj0,i,j,ei,ej,ecnt,*emap,nid; ierr = PetscMalloc(sizeof(PetscInt)*c->ne*c->npe,&c->element);CHKERRQ(ierr); ierr = PetscMemzero(c->element,sizeof(PetscInt)*c->ne*c->npe);CHKERRQ(ierr); ecnt = 0; for (ej=0; ej<c->my; ej++) { nj0 = ej*(c->npe_1d-1); for (ei=0; ei<c->mx; ei++) { ni0 = ei*(c->npe_1d-1); emap = &c->element[c->npe*ecnt]; for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { nid = (ni0 + i) + (nj0 + j) * c->nx_g; emap[i+j*c->npe_1d] = nid; } } ecnt++; } } PetscFunctionReturn(0); } /* Creates domain over [0,1]^d - scale later */ PetscErrorCode SpecFECtxCreateMeshCoords2d_SEQ(SpecFECtx c) { PetscErrorCode ierr; Vec coor; DM cdm; DMDACoor2d **LA_coor2d; PetscInt ei,ej,i,j,ni0,nj0; PetscReal dx,dy,x0,y0; ierr = DMDASetUniformCoordinates(c->dm,0.0,1.0,0.0,1.0,0,0);CHKERRQ(ierr); ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr); dx = 1.0/((PetscReal)c->mx_g); dy = 1.0/((PetscReal)c->my_g); ierr = DMDAVecGetArray(cdm,coor,&LA_coor2d);CHKERRQ(ierr); for (ej=0; ej<c->my; ej++) { for (ei=0; ei<c->mx; ei++) { x0 = 0.0 + ei*dx; y0 = 0.0 + ej*dy; ni0 = ei*(c->npe_1d-1); nj0 = ej*(c->npe_1d-1); for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { LA_coor2d[nj0+j][ni0+i].x = 0.5*(c->xi1d[i]+1.0)*dx + x0; LA_coor2d[nj0+j][ni0+i].y = 0.5*(c->xi1d[j]+1.0)*dy + y0; //if ((ej==0) && (j==0)) { // printf("[e %d,i %d] xc %+1.4e\n",ei,i,LA_coor2d[nj0+j][ni0+i].x*4.0e3-2.0e3); //} } } } } ierr = DMDAVecRestoreArray(cdm,coor,&LA_coor2d);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxScaleMeshCoords(SpecFECtx c,PetscReal scale[],PetscReal shift[]) { PetscErrorCode ierr; Vec coor,lcoor; DM cdm; ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); if (scale) { if (c->dim >= 1) ierr = VecStrideScale(coor,0,scale[0]);CHKERRQ(ierr); if (c->dim >= 2) ierr = VecStrideScale(coor,1,scale[1]);CHKERRQ(ierr); if (c->dim == 3) ierr = VecStrideScale(coor,2,scale[2]);CHKERRQ(ierr); } if (shift) { Vec ss; ierr = VecDuplicate(coor,&ss);CHKERRQ(ierr); if (c->dim >= 1) { ierr = VecZeroEntries(ss);CHKERRQ(ierr); ierr = VecStrideSet(ss,0,shift[0]);CHKERRQ(ierr); ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr); } if (c->dim >= 2) { ierr = VecZeroEntries(ss);CHKERRQ(ierr); ierr = VecStrideSet(ss,1,shift[1]);CHKERRQ(ierr); ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr); } if (c->dim >= 3) { ierr = VecZeroEntries(ss);CHKERRQ(ierr); ierr = VecStrideSet(ss,2,shift[2]);CHKERRQ(ierr); ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr); } ierr = VecDestroy(&ss);CHKERRQ(ierr); } ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(c->dm,&lcoor);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,coor,INSERT_VALUES,lcoor);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,coor,INSERT_VALUES,lcoor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateMesh_SEQ(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs) { PetscErrorCode ierr; PetscInt stencil_width,i,j; c->dim = dim; c->mx = mx; c->my = my; c->mz = mz; c->mx_g = mx; c->my_g = my; c->mz_g = mz; c->basisorder = basisorder; c->dofs = ndofs; c->nx_g = basisorder*mx + 1; c->ny_g = basisorder*my + 1; c->nz_g = basisorder*mz + 1; ierr = CreateGLLCoordsWeights(basisorder,&c->npe_1d,&c->xi1d,&c->w1d);CHKERRQ(ierr); stencil_width = 1; switch (dim) { case 2: c->npe = c->npe_1d * c->npe_1d; c->ne = mx * my; c->ne_g = mx * my; ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX, c->nx_g,c->ny_g,PETSC_DECIDE,PETSC_DECIDE,ndofs,stencil_width,NULL,NULL,&c->dm);CHKERRQ(ierr); ierr = DMSetUp(c->dm);CHKERRQ(ierr); ierr = SpecFECtxCreateENMap2d_SEQ(c);CHKERRQ(ierr); ierr = SpecFECtxCreateMeshCoords2d_SEQ(c);CHKERRQ(ierr); /* tensor product for weights */ ierr = PetscMalloc(sizeof(PetscReal)*c->npe,&c->w);CHKERRQ(ierr); for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { c->w[i+j*c->npe_1d] = c->w1d[i] * c->w1d[j]; } } ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dxi,&c->dN_deta);CHKERRQ(ierr); ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dx,&c->dN_dy);CHKERRQ(ierr); break; } c->nqp = c->npe; ierr = PetscMalloc(sizeof(QPntIsotropicElastic)*c->ne,&c->cell_data);CHKERRQ(ierr); ierr = PetscMemzero(c->cell_data,sizeof(QPntIsotropicElastic)*c->ne);CHKERRQ(ierr); ierr = PetscMalloc1(c->ne * c->nqp,&c->dr_qp_data);CHKERRQ(ierr); ierr = PetscMemzero(c->dr_qp_data,sizeof(DRVar)*c->ne*c->nqp);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dim,&c->elbuf_coor);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field2);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field3);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscInt)*c->npe*c->dofs,&c->elbuf_dofs);CHKERRQ(ierr); PetscFunctionReturn(0); } /* Degree 4 has 5 basis in each direction | | 0--1--2--3--4 */ PetscErrorCode SpecFECtxGetCornerBasis_MPI(SpecFECtx c,PetscInt *si,PetscInt *si_g,PetscInt *sj,PetscInt *sj_g) { PetscInt gi,gj,m,n,k; PetscErrorCode ierr; ierr = DMDAGetGhostCorners(c->dm,&gi,&gj,NULL,&m,&n,NULL);CHKERRQ(ierr); /*printf("rank %d: gi,gj %d %d npe %d\n",c->rank,gi,gj,c->npe_1d);*/ for (k=0; k<m; k++) { if (((gi+k) % (c->npe_1d-1)) == 0) { *si = k; *si_g = gi+k; break; } } for (k=0; k<n; k++) { if (((gj+k) % (c->npe_1d-1)) == 0) { *sj = k; *sj_g = gj+k; break; } } PetscFunctionReturn(0); } PetscErrorCode SpecFECtxGetLocalBoundingBox(SpecFECtx c,PetscReal gmin[],PetscReal gmax[]) { PetscErrorCode ierr; PetscInt si[]={0,0},si_g[]={0,0},m,n,ii,jj; const PetscReal *LA_coor; Vec coor; ierr = SpecFECtxGetCornerBasis_MPI(c,&si[0],&si_g[0],&si[1],&si_g[1]);CHKERRQ(ierr); ierr = DMDAGetGhostCorners(c->dm,NULL,NULL,NULL,&m,&n,NULL);CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); ii = si[0]; jj = si[1]; gmin[0] = LA_coor[2*(ii + jj*m)+0]; gmin[1] = LA_coor[2*(ii + jj*m)+1]; ii = si[0] + c->mx * c->basisorder; jj = si[1] + c->my * c->basisorder; gmax[0] = LA_coor[2*(ii + jj*m)+0]; gmax[1] = LA_coor[2*(ii + jj*m)+1]; ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateENMap2d_MPI(SpecFECtx c) { PetscErrorCode ierr; PetscInt ni0,nj0,i,j,ei,ej,ecnt,*emap,nid; PetscInt si,si_g,sj,sj_g,nx_local; ierr = PetscMalloc(sizeof(PetscInt)*c->ne*c->npe,&c->element);CHKERRQ(ierr); ierr = PetscMemzero(c->element,sizeof(PetscInt)*c->ne*c->npe);CHKERRQ(ierr); ierr = SpecFECtxGetCornerBasis_MPI(c,&si,&si_g,&sj,&sj_g);CHKERRQ(ierr); ierr = DMDAGetGhostCorners(c->dm,NULL,NULL,NULL,&nx_local,NULL,NULL);CHKERRQ(ierr); /*printf("rank %d : %d %d x %d %d\n",c->rank,si,si_g,sj,sj_g);*/ ecnt = 0; for (ej=0; ej<c->my; ej++) { nj0 = sj + ej*(c->npe_1d-1); for (ei=0; ei<c->mx; ei++) { ni0 = si + ei*(c->npe_1d-1); emap = &c->element[c->npe*ecnt]; for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { nid = (ni0 + i) + (nj0 + j) * nx_local; emap[i+j*c->npe_1d] = nid; //if (c->rank == 0) { // printf("e %d : %d [max %d]\n",ecnt,nid,c->ne*c->npe); //} } } ecnt++; } } PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateMeshCoords2d_MPI(SpecFECtx c) { PetscErrorCode ierr; Vec coor,gcoor; DM cdm; PetscInt ei,ej,i,j,ni0,nj0,si,si_g,sj,sj_g,gi,gj,m,n; PetscReal dx,dy,x0,y0; PetscReal *LA_coor; ierr = DMDASetUniformCoordinates(c->dm,0.0,1.0,0.0,1.0,0,0);CHKERRQ(ierr); ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = DMGetCoordinates(c->dm,&gcoor);CHKERRQ(ierr); ierr = VecZeroEntries(gcoor);CHKERRQ(ierr); ierr = SpecFECtxGetCornerBasis_MPI(c,&si,&si_g,&sj,&sj_g);CHKERRQ(ierr); ierr = DMDAGetGhostCorners(c->dm,&gi,&gj,NULL,&m,&n,NULL);CHKERRQ(ierr); dx = 1.0/((PetscReal)c->mx_g); dy = 1.0/((PetscReal)c->my_g); ierr = VecGetArray(coor,&LA_coor);CHKERRQ(ierr); for (ej=0; ej<c->my; ej++) { for (ei=0; ei<c->mx; ei++) { if ( si >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Out of range-si"); if ( sj >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Out of range-sj"); x0 = LA_coor[2*(si + sj*m)+0] + ei*dx; y0 = LA_coor[2*(si + sj*m)+1] + ej*dy; ni0 = si + ei*(c->npe_1d-1); nj0 = sj + ej*(c->npe_1d-1); //printf("rank %d : (%d,%d) -> %d %d %+1.4e %+1.4e\n",c->rank,ei,ej,ni0,nj0,x0,y0); for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { if ( (ni0+i)+(nj0+j)*m >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Local index out of range"); LA_coor[2*((ni0+i) + (nj0+j)*m)+0] = x0 + 0.5*(c->xi1d[i]+1.0)*dx; LA_coor[2*((ni0+i) + (nj0+j)*m)+1] = y0 + 0.5*(c->xi1d[j]+1.0)*dy; ierr = VecSetValueLocal(gcoor,2*((ni0+i) + (nj0+j)*m)+0,x0 + 0.5*(c->xi1d[i]+1.0)*dx,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValueLocal(gcoor,2*((ni0+i) + (nj0+j)*m)+1,y0 + 0.5*(c->xi1d[j]+1.0)*dy,INSERT_VALUES);CHKERRQ(ierr); } } } } ierr = VecRestoreArray(coor,&LA_coor);CHKERRQ(ierr); ierr = VecAssemblyBegin(gcoor);CHKERRQ(ierr); ierr = VecAssemblyEnd(gcoor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateMesh_MPI(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs) { PetscErrorCode ierr; PetscInt stencil_width,i,j; DM dm_ref; PetscInt ranks[3]; PetscInt r,*lx,*ly; const PetscInt *lx_ref,*ly_ref; DMDALocalInfo info; c->dim = dim; c->mx_g = mx; c->my_g = my; c->mz_g = mz; c->basisorder = basisorder; c->dofs = ndofs; c->nx_g = basisorder*mx + 1; c->ny_g = basisorder*my + 1; c->nz_g = basisorder*mz + 1; ierr = CreateGLLCoordsWeights(basisorder,&c->npe_1d,&c->xi1d,&c->w1d);CHKERRQ(ierr); stencil_width = 1; switch (dim) { case 2: c->npe = c->npe_1d * c->npe_1d; c->ne_g = mx * my; ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX, c->mx_g,c->my_g,PETSC_DECIDE,PETSC_DECIDE,1,0,NULL,NULL,&dm_ref);CHKERRQ(ierr); ierr = DMSetUp(dm_ref);CHKERRQ(ierr); /*ierr = DMView(dm_ref,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); */ ierr = DMDAGetInfo(dm_ref,NULL,NULL,NULL,NULL,&ranks[0],&ranks[1],NULL,NULL,NULL,NULL,NULL,NULL,NULL);CHKERRQ(ierr); ierr = DMDAGetOwnershipRanges(dm_ref,&lx_ref,&ly_ref,NULL);CHKERRQ(ierr); ierr = DMDAGetLocalInfo(dm_ref,&info);CHKERRQ(ierr); c->mx = info.xm; c->my = info.ym; c->ne = c->mx * c->my; ierr = PetscMalloc1(ranks[0],&lx);CHKERRQ(ierr); ierr = PetscMalloc1(ranks[1],&ly);CHKERRQ(ierr); for (r=0; r<ranks[0]; r++) { lx[r] = lx_ref[r] * (c->npe_1d - 1); } lx[ranks[0]-1]++; /*for (r=0; r<ranks[0]; r++) PetscPrintf(PETSC_COMM_WORLD,"npoints-i[%D] %D \n",r,lx[r]);*/ for (r=0; r<ranks[1]; r++) { ly[r] = ly_ref[r] * (c->npe_1d - 1); } ly[ranks[1]-1]++; /*for (r=0; r<ranks[1]; r++) PetscPrintf(PETSC_COMM_WORLD,"npoints-j[%D] %D \n",r,ly[r]);*/ ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX, c->nx_g,c->ny_g,ranks[0],ranks[1],ndofs,stencil_width,lx,ly,&c->dm);CHKERRQ(ierr); ierr = DMSetUp(c->dm);CHKERRQ(ierr); /*ierr = DMView(c->dm,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); */ ierr = SpecFECtxCreateENMap2d_MPI(c);CHKERRQ(ierr); ierr = SpecFECtxCreateMeshCoords2d_MPI(c);CHKERRQ(ierr); /* tensor product for weights */ ierr = PetscMalloc(sizeof(PetscReal)*c->npe,&c->w);CHKERRQ(ierr); for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { c->w[i+j*c->npe_1d] = c->w1d[i] * c->w1d[j]; } } ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dxi,&c->dN_deta);CHKERRQ(ierr); ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dx,&c->dN_dy);CHKERRQ(ierr); ierr = PetscFree(lx);CHKERRQ(ierr); ierr = PetscFree(ly);CHKERRQ(ierr); ierr = DMDestroy(&dm_ref);CHKERRQ(ierr); break; } c->nqp = c->npe; ierr = PetscMalloc(sizeof(QPntIsotropicElastic)*c->ne,&c->cell_data);CHKERRQ(ierr); ierr = PetscMemzero(c->cell_data,sizeof(QPntIsotropicElastic)*c->ne);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dim,&c->elbuf_coor);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field2);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field3);CHKERRQ(ierr); ierr = PetscMalloc(sizeof(PetscInt)*c->npe*c->dofs,&c->elbuf_dofs);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxCreateMesh(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs) { PetscMPIInt size; PetscErrorCode ierr; ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); if (size == 1) { ierr = SpecFECtxCreateMesh_SEQ(c,dim,mx,my,mz,basisorder,ndofs);CHKERRQ(ierr); } else { ierr = SpecFECtxCreateMesh_MPI(c,dim,mx,my,mz,basisorder,ndofs);CHKERRQ(ierr); } ierr = DMDASetFieldName(c->dm,0,"_x");CHKERRQ(ierr); ierr = DMDASetFieldName(c->dm,1,"_y");CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxSetConstantMaterialProperties(SpecFECtx c,PetscReal lambda,PetscReal mu,PetscReal rho) { PetscInt q; for (q=0; q<c->ne; q++) { c->cell_data[q].lambda = lambda; c->cell_data[q].mu = mu; c->cell_data[q].rho = rho; } PetscFunctionReturn(0); } PetscErrorCode SpecFECtxSetConstantMaterialProperties_Velocity(SpecFECtx c,PetscReal Vp,PetscReal Vs,PetscReal rho) { PetscErrorCode ierr; PetscReal mu,lambda; mu = Vs * Vs * rho; lambda = Vp * Vp * rho - 2.0 * mu; ierr = SpecFECtxSetConstantMaterialProperties(c,lambda,mu,rho);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD," [material] Vp = %1.8e\n",Vp); PetscPrintf(PETSC_COMM_WORLD," [material] Vs = %1.8e\n",Vs); PetscPrintf(PETSC_COMM_WORLD," [material] lambda = %1.8e\n",lambda); PetscPrintf(PETSC_COMM_WORLD," [material] mu = %1.8e\n",mu); PetscPrintf(PETSC_COMM_WORLD," [material] rho = %1.8e\n",rho); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxSetPerturbedMaterialProperties_Velocity(SpecFECtx c,PetscReal Vp0,PetscReal delta_Vp,PetscReal Vs0,PetscReal delta_Vs,PetscReal rho0,PetscReal delta_rho) { PetscErrorCode ierr; Vec Vp,Vs,rho; PetscRandom r; const PetscReal *LA_Vp,*LA_Vs,*LA_rho; PetscInt e; ierr = VecCreate(PETSC_COMM_WORLD,&Vp);CHKERRQ(ierr); ierr = VecSetSizes(Vp,c->ne,c->ne_g);CHKERRQ(ierr); ierr = VecSetFromOptions(Vp);CHKERRQ(ierr); ierr = VecDuplicate(Vp,&Vs);CHKERRQ(ierr); ierr = VecDuplicate(Vp,&rho);CHKERRQ(ierr); ierr = PetscRandomCreate(PETSC_COMM_WORLD,&r);CHKERRQ(ierr); ierr = PetscRandomSetType(r,PETSCRAND48);CHKERRQ(ierr); ierr = PetscRandomSetInterval(r,Vp0-delta_Vp,Vp0+delta_Vp);CHKERRQ(ierr); ierr = PetscRandomSetSeed(r,1);CHKERRQ(ierr); ierr = PetscRandomSeed(r);CHKERRQ(ierr); ierr = VecSetRandom(Vp,r);CHKERRQ(ierr); ierr = PetscRandomSetInterval(r,Vs0-delta_Vs,Vs0+delta_Vs);CHKERRQ(ierr); ierr = PetscRandomSetSeed(r,2);CHKERRQ(ierr); ierr = PetscRandomSeed(r);CHKERRQ(ierr); ierr = VecSetRandom(Vs,r);CHKERRQ(ierr); ierr = PetscRandomSetInterval(r,rho0-delta_rho,rho0+delta_rho);CHKERRQ(ierr); ierr = PetscRandomSetSeed(r,3);CHKERRQ(ierr); ierr = PetscRandomSeed(r);CHKERRQ(ierr); ierr = VecSetRandom(rho,r);CHKERRQ(ierr); ierr = PetscRandomDestroy(&r);CHKERRQ(ierr); ierr = VecGetArrayRead(Vp,&LA_Vp);CHKERRQ(ierr); ierr = VecGetArrayRead(Vs,&LA_Vs);CHKERRQ(ierr); ierr = VecGetArrayRead(rho,&LA_rho);CHKERRQ(ierr); for (e=0; e<c->ne; e++) { PetscReal mu,lambda; mu = LA_Vs[e] * LA_Vs[e] * LA_rho[e]; lambda = LA_Vp[e] * LA_Vp[e] * LA_rho[e] - 2.0 * mu; c->cell_data[e].lambda = lambda; c->cell_data[e].mu = mu; c->cell_data[e].rho = LA_rho[e]; } ierr = VecRestoreArrayRead(rho,&LA_rho);CHKERRQ(ierr); ierr = VecRestoreArrayRead(Vs,&LA_Vs);CHKERRQ(ierr); ierr = VecRestoreArrayRead(Vp,&LA_Vp);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD," [material] Vp0 = %1.8e : delta = %+1.8e\n",Vp0,delta_Vp); PetscPrintf(PETSC_COMM_WORLD," [material] Vs0 = %1.8e : delta = %+1.8e\n",Vs0,delta_Vs); PetscPrintf(PETSC_COMM_WORLD," [material] rho0 = %1.8e : delta = %+1.8e\n",rho0,delta_rho); ierr = VecDestroy(&rho);CHKERRQ(ierr); ierr = VecDestroy(&Vs);CHKERRQ(ierr); ierr = VecDestroy(&Vp);CHKERRQ(ierr); PetscFunctionReturn(0); } void ElementEvaluateGeometry_CellWiseConstant2d(PetscInt npe,PetscReal el_coords[], PetscInt nbasis,PetscReal *detJ) { PetscReal J00,J11; PetscReal dx,dy; dx = el_coords[2*(nbasis-1)+0] - el_coords[2*0+0]; dy = el_coords[2*(npe-1)+1] - el_coords[2*0+1]; J00 = 0.5 * dx; J11 = 0.5 * dy; *detJ = J00*J11; } void ElementEvaluateDerivatives_CellWiseConstant2d(PetscInt nqp,PetscInt npe,PetscReal el_coords[], PetscInt nbasis,PetscReal **dN_dxi,PetscReal **dN_deta, PetscReal **dN_dx,PetscReal **dN_dy) { PetscInt k,q; PetscReal J00,J11,iJ00,iJ11; PetscReal dx,dy; dx = el_coords[2*(nbasis-1)+0] - el_coords[2*0+0]; dy = el_coords[2*(npe-1)+1] - el_coords[2*0+1]; J00 = 0.5 * dx; J11 = 0.5 * dy; for (q=0; q<nqp; q++) { iJ00 = 1.0/J00; iJ11 = 1.0/J11; /* shape function derivatives */ for (k=0; k<npe; k++) { dN_dx[q][k] = iJ00 * dN_dxi[q][k]; dN_dy[q][k] = iJ11 * dN_deta[q][k]; } } } /* Assemble rhs L(u) = - \int B^T D B u dV */ PetscErrorCode AssembleLinearForm_ElastoDynamics2d(SpecFECtx c,Vec u,Vec F) { PetscErrorCode ierr; PetscInt e,nqp,q,i,nbasis,ndof; PetscReal e_vec[3],sigma_vec[3]; PetscInt *element,*elnidx,*eldofs; PetscReal *fe,*ux,*uy,*elcoords,detJ,*field; Vec coor,ul,fl; const PetscReal *LA_coor,*LA_u; QPntIsotropicElastic *celldata; ierr = VecZeroEntries(F);CHKERRQ(ierr); eldofs = c->elbuf_dofs; elcoords = c->elbuf_coor; nbasis = c->npe; nqp = c->nqp; ndof = c->dofs; fe = c->elbuf_field; element = c->element; field = c->elbuf_field2; ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&fl);CHKERRQ(ierr); ierr = VecZeroEntries(fl);CHKERRQ(ierr); ux = &field[0]; uy = &field[nbasis]; for (e=0; e<c->ne; e++) { /* get element -> node map */ elnidx = &element[nbasis*e]; /* generate dofs */ for (i=0; i<nbasis; i++) { eldofs[2*i ] = 2*elnidx[i]; eldofs[2*i+1] = 2*elnidx[i]+1; } /* get element coordinates */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; elcoords[2*i ] = LA_coor[2*nidx ]; elcoords[2*i+1] = LA_coor[2*nidx+1]; } /* get element displacements */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; ux[i] = LA_u[2*nidx ]; uy[i] = LA_u[2*nidx+1]; } /* compute derivatives */ ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ); ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords, c->npe_1d,c->dN_dxi,c->dN_deta, c->dN_dx,c->dN_dy); ierr = PetscMemzero(fe,sizeof(PetscReal)*nbasis*ndof);CHKERRQ(ierr); /* get access to element->quadrature points */ celldata = &c->cell_data[e]; for (q=0; q<c->nqp; q++) { PetscReal fac; PetscReal c11,c12,c21,c22,c33,lambda_qp,mu_qp; PetscReal *dNidx,*dNidy; dNidx = c->dN_dx[q]; dNidy = c->dN_dy[q]; /* compute strain @ quadrature point */ /* e = Bu = [ d/dx 0 ][ u v ]^T [ 0 d/dy ] [ d/dy d/dx ] */ e_vec[0] = e_vec[1] = e_vec[2] = 0.0; for (i=0; i<nbasis; i++) { e_vec[0] += dNidx[i] * ux[i]; e_vec[1] += dNidy[i] * uy[i]; e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]); } /* evaluate constitutive model */ lambda_qp = celldata->lambda; mu_qp = celldata->mu; /* coeff = E_qp * (1.0 + nu_qp)/(1.0 - 2.0*nu_qp); c11 = coeff*(1.0 - nu_qp); c12 = coeff*(nu_qp); c21 = coeff*(nu_qp); c22 = coeff*(1.0 - nu_qp); c33 = coeff*(0.5 * (1.0 - 2.0 * nu_qp)); */ c11 = 2.0*mu_qp + lambda_qp; c12 = lambda_qp; c21 = lambda_qp; c22 = 2.0*mu_qp + lambda_qp; c33 = mu_qp; /* compute stress @ quadrature point */ sigma_vec[TENS2D_XX] = c11 * e_vec[0] + c12 * e_vec[1]; sigma_vec[TENS2D_YY] = c21 * e_vec[0] + c22 * e_vec[1]; sigma_vec[TENS2D_XY] = c33 * e_vec[2]; //printf("s = %1.4e %1.4e %1.4e \n",sigma_vec[0],sigma_vec[1],sigma_vec[2]); /* a(u,v) = B^T s = [ d/dx 0 d/dy ][ sxx syy sxy ]^T [ 0 d/dy d/dx ] */ fac = detJ * c->w[q]; for (i=0; i<nbasis; i++) { fe[2*i ] += -fac * (dNidx[i] * sigma_vec[TENS2D_XX] + dNidy[i] * sigma_vec[TENS2D_XY]); fe[2*i+1] += -fac * (dNidy[i] * sigma_vec[TENS2D_YY] + dNidx[i] * sigma_vec[TENS2D_XY]); } } //ierr = VecSetValuesLocal(F,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr); ierr = VecSetValues(fl,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(fl);CHKERRQ(ierr); ierr = VecAssemblyEnd(fl);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr); ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&fl);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SpecFECtxGetDRCellData(SpecFECtx c,PetscInt e_index,DRVar **data) { *data = &c->dr_qp_data[c->nqp * e_index]; PetscFunctionReturn(0); } PetscErrorCode EvaluateVelocityAtPoint(SpecFECtx c,const PetscReal LA_v[],PetscReal xr[],PetscReal vr[]) { PetscReal gmin[3],gmax[3],dx,dy; PetscInt k,ei,ej,eid,*element,*elbasis; PetscReal N[400]; PetscErrorCode ierr; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Needs updating to support MPI"); /* get containing element */ ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */ dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[1] - gmin[1])/dy; eid = ei + ej * c->mx; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; { PetscInt nbasis,i,j; PetscReal **N_s1,**N_s2,xi,eta,x0,y0; x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */ y0 = gmin[1] + ej*dy; // (xi - (-1))/2 = (x - x0)/dx xi = 2.0*(xr[0] - x0)/dx - 1.0; eta = 2.0*(xr[1] - y0)/dy - 1.0; /* compute basis */ ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr); ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr); k = 0; for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { N[k] = N_s1[0][i] * N_s2[0][j]; k++; } } ierr = PetscFree(N_s1[0]);CHKERRQ(ierr); ierr = PetscFree(N_s1);CHKERRQ(ierr); ierr = PetscFree(N_s2[0]);CHKERRQ(ierr); ierr = PetscFree(N_s2);CHKERRQ(ierr); } vr[0] = vr[1] = 0.0; for (k=0; k<c->npe; k++) { PetscInt nid = elbasis[k]; vr[0] += N[k] * LA_v[2*nid+0]; vr[1] += N[k] * LA_v[2*nid+1]; } PetscFunctionReturn(0); } PetscErrorCode PointLocation_v2(SpecFECtx c,const PetscReal xr[],PetscInt *_eid,PetscReal **N1,PetscReal **N2) { static PetscBool beenhere = PETSC_FALSE; static PetscReal gmin[3],gmax[3]; PetscReal dx,dy; PetscInt ei,ej,eid; PetscInt nbasis; PetscReal **N_s1,**N_s2,xi,eta,x0,y0; PetscErrorCode ierr; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Needs updating to support MPI"); /* get containing element */ if (!beenhere) { ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); beenhere = PETSC_TRUE; } dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */ dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[1] - gmin[1])/dy; eid = ei + ej * c->mx; x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */ y0 = gmin[1] + ej*dy; // (xi - (-1))/2 = (x - x0)/dx xi = 2.0*(xr[0] - x0)/dx - 1.0; eta = 2.0*(xr[1] - y0)/dy - 1.0; /* compute basis */ ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr); ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr); *_eid = eid; *N1 = N_s1[0]; *N2 = N_s2[0]; //ierr = PetscFree(N_s1[0]);CHKERRQ(ierr); ierr = PetscFree(N_s1);CHKERRQ(ierr); //ierr = PetscFree(N_s2[0]);CHKERRQ(ierr); ierr = PetscFree(N_s2);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode FaultSDFInit_v2(SpecFECtx c) { PetscErrorCode ierr; PetscInt e,i,q,nbasis,nqp,ndof; Vec coor; const PetscReal *LA_coor; PetscInt *element,*elnidx,*eldofs; PetscReal *elcoords; DRVar *dr_celldata; PetscReal factor; PetscInt factor_i; eldofs = c->elbuf_dofs; elcoords = c->elbuf_coor; nbasis = c->npe; nqp = c->nqp; ndof = c->dofs; element = c->element; factor = ((PetscReal)(c->ne)) * 0.1; factor_i = (PetscInt)factor; if (factor_i == 0) { factor_i = 1; } ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); for (e=0; e<c->ne; e++) { /* get element -> node map */ elnidx = &element[nbasis*e]; /* generate dofs */ for (i=0; i<nbasis; i++) { eldofs[2*i ] = 2*elnidx[i]; eldofs[2*i+1] = 2*elnidx[i]+1; } /* get element coordinates */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; elcoords[2*i ] = LA_coor[2*nidx ]; elcoords[2*i+1] = LA_coor[2*nidx+1]; } ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr); for (q=0; q<c->nqp; q++) { PetscReal coor_qp[2]; PetscBool modify_stress_state; coor_qp[0] = elcoords[2*q ]; coor_qp[1] = elcoords[2*q+1]; modify_stress_state = PETSC_FALSE; dr_celldata[q].eid[0] = -1; dr_celldata[q].eid[1] = -1; ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&modify_stress_state);CHKERRQ(ierr); if (modify_stress_state) { PetscReal x_plus[2],x_minus[2]; //printf("[e %d , q %d] x_qp %+1.4e , %+1.4e\n",e,q,coor_qp[0],coor_qp[1]); ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr); ierr = PointLocation_v2(c,(const PetscReal*)x_plus, &dr_celldata[q].eid[0],&dr_celldata[q].N1_plus,&dr_celldata[q].N2_plus);CHKERRQ(ierr); ierr = PointLocation_v2(c,(const PetscReal*)x_minus,&dr_celldata[q].eid[1],&dr_celldata[q].N1_minus,&dr_celldata[q].N2_minus);CHKERRQ(ierr); //printf(" [e %d,q %d] x_qp -> x+ %+1.4e , %+1.4e [eid %d]\n",e,q,x_plus[0],x_plus[1],dr_celldata[q].eid[0]); //printf(" [e %d,q %d] x_qp -> x- %+1.4e , %+1.4e [eid %d]\n",e,q,x_minus[0],x_minus[1],dr_celldata[q].eid[1]); } } if (e%factor_i == 0) { printf("[Fault point location] Done element %d of %d\n",e,c->ne); } } printf("[Fault point location-v2] Finished\n"); ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } /* Use tabulated basis at delta(+,-) to interpolate velocity */ PetscErrorCode FaultSDFTabulateInterpolation_v2(SpecFECtx c,const PetscReal LA_v[],DRVar *dr_celldata_q, PetscReal v_plus[],PetscReal v_minus[]) { PetscInt eid_delta,*element_delta; PetscReal vx_d_e,vy_d_e,Ni; PetscInt i,ii,jj,nbasis,*element,nidx; nbasis = c->npe; element = c->element; if (!dr_celldata_q->N1_plus || !dr_celldata_q->N2_plus) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"[+] N1,N2 not allocated"); eid_delta = dr_celldata_q->eid[0]; element_delta = &element[nbasis*eid_delta]; v_plus[0] = v_plus[1] = 0.0; i = 0; for (jj=0; jj<c->npe_1d; jj++) { for (ii=0; ii<c->npe_1d; ii++) { nidx = element_delta[i]; Ni = dr_celldata_q->N1_plus[ii] * dr_celldata_q->N2_plus[jj]; vx_d_e = LA_v[2*nidx ]; vy_d_e = LA_v[2*nidx+1]; v_plus[0] += Ni * vx_d_e; v_plus[1] += Ni * vy_d_e; i++; } } if (!dr_celldata_q->N1_minus || !dr_celldata_q->N2_minus) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"[-] N1,N2 not allocated"); eid_delta = dr_celldata_q->eid[1]; element_delta = &element[nbasis*eid_delta]; v_minus[0] = v_minus[1] = 0.0; i = 0; for (jj=0; jj<c->npe_1d; jj++) { for (ii=0; ii<c->npe_1d; ii++) { nidx = element_delta[i]; Ni = dr_celldata_q->N1_minus[ii] * dr_celldata_q->N2_minus[jj]; vx_d_e = LA_v[2*nidx ]; vy_d_e = LA_v[2*nidx+1]; v_minus[0] += Ni * vx_d_e; v_minus[1] += Ni * vy_d_e; i++; } } PetscFunctionReturn(0); } PetscErrorCode VoigtTensorContract_ai_Tij_bj(PetscReal a[],PetscReal t[2][2],PetscReal b[],PetscReal *r) { PetscReal s=0; PetscInt i,j; for (i=0; i<2; i++) { for (j=0; j<2; j++) { s += a[i] * t[i][j] * b[j]; } } *r = s; PetscFunctionReturn(0); } PetscErrorCode VoigtTensorConvert(PetscReal T[],PetscReal t[2][2]) { t[0][0] = T[TENS2D_XX]; t[0][1] = T[TENS2D_XY]; t[1][0] = T[TENS2D_XY]; t[1][1] = T[TENS2D_YY]; PetscFunctionReturn(0); } PetscErrorCode TensorConvertToVoigt(PetscReal t[2][2],PetscReal T[]) { T[TENS2D_XX] = t[0][0]; T[TENS2D_XY] = t[0][1]; T[TENS2D_YY] = t[1][1]; if (fabs(t[1][0] - t[0][1]) > 1.0e-12) { SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert non-symmetric tensor into Voigt format"); } PetscFunctionReturn(0); } PetscErrorCode TensorZeroEntries(PetscReal t[2][2]) { t[0][0] = 0; t[0][1] = 0; t[1][0] = 0; t[1][1] = 0; PetscFunctionReturn(0); } PetscErrorCode TensorScale(PetscReal y[2][2],PetscReal a) { y[0][0] = a*y[0][0]; y[0][1] = a*y[0][1]; y[1][0] = a*y[1][0]; y[1][1] = a*y[1][1]; PetscFunctionReturn(0); } PetscErrorCode TensorAXPY(PetscReal y[2][2],PetscReal a,PetscReal x[2][2]) { y[0][0] += a*x[0][0]; y[0][1] += a*x[0][1]; y[1][0] += a*x[1][0]; y[1][1] += a*x[1][1]; PetscFunctionReturn(0); } PetscErrorCode VectorContract_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2]) { PetscInt i,j; for (i=0; i<2; i++) { for (j=0; j<2; j++) { t[i][j] = a[i] * b[j]; } } PetscFunctionReturn(0); } PetscErrorCode VectorContractAdd_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2]) { PetscInt i,j; for (i=0; i<2; i++) { for (j=0; j<2; j++) { t[i][j] += a[i] * b[j]; } } PetscFunctionReturn(0); } PetscErrorCode VectorContractAbsAdd_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2]) { PetscInt i,j; for (i=0; i<2; i++) { for (j=0; j<2; j++) { t[i][j] += fabs(a[i] * b[j]); } } PetscFunctionReturn(0); } PetscErrorCode TensorRtAR(PetscReal R[2][2],PetscReal T[2][2],PetscReal Tr[2][2]) { PetscInt i,j,k,l; // Tr[i][j] = Rt[i][k]T[k][l]R[l][j] = Rt[k][i]T[k][l]R[l][j] for (i=0; i<2; i++) { for (j=0; j<2; j++) { Tr[i][j] = 0.0; for (k=0; k<2; k++) { for (l=0; l<2; l++) { Tr[i][j] += R[k][i] * T[k][l] * R[l][j]; } } } } PetscFunctionReturn(0); } PetscErrorCode TensorTransform(PetscReal e1[],PetscReal e2[],PetscReal T[2][2],PetscReal Tr[2][2]) { PetscReal R[2][2]; R[0][0] = e1[0]; R[0][1] = e2[0]; R[1][0] = e1[1]; R[1][1] = e2[1]; TensorRtAR(R,T,Tr); PetscFunctionReturn(0); } PetscErrorCode TensorInverseTransform(PetscReal e1[],PetscReal e2[],PetscReal T[2][2],PetscReal Tr[2][2]) { PetscReal R[2][2],iR[2][2],det; R[0][0] = e1[0]; R[0][1] = e2[0]; R[1][0] = e1[1]; R[1][1] = e2[1]; det = R[0][0] * R[1][1] - R[0][1] * R[1][0]; iR[0][0] = R[1][1]/det; iR[0][1] = -R[0][1]/det; iR[1][0] = -R[1][0]/det; iR[1][1] = R[0][0]/det; TensorRtAR(iR,T,Tr); PetscFunctionReturn(0); } PetscErrorCode AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv(SpecFECtx c,Vec u,Vec v,PetscReal dt,PetscReal time,PetscReal gamma,Vec F) { PetscErrorCode ierr; PetscInt e,nqp,q,i,nbasis,ndof; PetscReal e_vec[3],edot_vec[3],sigma_vec[3],sigma_trial[3],gradu[4],gradv[4],gradv_q[9*9][4]; PetscInt *element,*elnidx,*eldofs; PetscReal *fe,*ux,*uy,*vx,*vy,*elcoords,detJ,*fieldU,*fieldV; Vec coor,ul,vl,fl; const PetscReal *LA_coor,*LA_u,*LA_v; QPntIsotropicElastic *celldata; DRVar *dr_celldata; // 0.55 is a good fit to matching sem2pack's displacement field...near the point (0,500) PetscReal sigma_n_0 = 120.0 * 1.0e6 * 1.0; PetscReal sigma_t_0 = 70.0 * 1.0e6 * 1.0; PetscReal sigma_n_1 = 120.0 * 1.0e6 * 1.0; PetscReal sigma_t_1 = 81.6 * 1.0e6 * 1.0; static PetscBool beenhere = PETSC_FALSE; static PetscReal gmin[3],gmax[3]; PetscReal dx,dy; if (!beenhere) { ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); beenhere = PETSC_TRUE; } dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ierr = VecZeroEntries(F);CHKERRQ(ierr); eldofs = c->elbuf_dofs; elcoords = c->elbuf_coor; nbasis = c->npe; nqp = c->nqp; ndof = c->dofs; fe = c->elbuf_field; element = c->element; fieldU = c->elbuf_field2; fieldV = c->elbuf_field3; ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&vl);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr); ierr = VecGetArrayRead(vl,&LA_v);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&fl);CHKERRQ(ierr); ierr = VecZeroEntries(fl);CHKERRQ(ierr); ux = &fieldU[0]; uy = &fieldU[nbasis]; vx = &fieldV[0]; vy = &fieldV[nbasis]; for (e=0; e<c->ne; e++) { ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr); } for (e=0; e<c->ne; e++) { PetscReal x_cell[] = {0,0}; /* get element -> node map */ elnidx = &element[nbasis*e]; /* generate dofs */ for (i=0; i<nbasis; i++) { eldofs[2*i ] = 2*elnidx[i]; eldofs[2*i+1] = 2*elnidx[i]+1; } /* get element coordinates */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; elcoords[2*i ] = LA_coor[2*nidx ]; elcoords[2*i+1] = LA_coor[2*nidx+1]; x_cell[0] += elcoords[2*i ]; x_cell[1] += elcoords[2*i+1]; } x_cell[0] = x_cell[0] / ((PetscReal)nbasis); x_cell[1] = x_cell[1] / ((PetscReal)nbasis); /* get element displacements & velocities */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; ux[i] = LA_u[2*nidx ]; uy[i] = LA_u[2*nidx+1]; vx[i] = LA_v[2*nidx ]; vy[i] = LA_v[2*nidx+1]; } /* compute derivatives */ ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ); ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords, c->npe_1d,c->dN_dxi,c->dN_deta, c->dN_dx,c->dN_dy); ierr = PetscMemzero(fe,sizeof(PetscReal)*nbasis*ndof);CHKERRQ(ierr); /* get access to element->quadrature points */ celldata = &c->cell_data[e]; ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr); for (q=0; q<c->nqp; q++) { PetscReal *dNidx,*dNidy; dNidx = c->dN_dx[q]; dNidy = c->dN_dy[q]; gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0; for (i=0; i<nbasis; i++) { gradv[0] += dNidx[i] * vx[i]; gradv[1] += dNidy[i] * vx[i]; gradv[2] += dNidx[i] * vy[i]; gradv[3] += dNidy[i] * vy[i]; } gradv_q[q][0] = gradv[0]; gradv_q[q][1] = gradv[1]; gradv_q[q][2] = gradv[2]; gradv_q[q][3] = gradv[3]; } for (q=0; q<c->nqp; q++) { PetscReal fac; PetscReal c11,c12,c21,c22,c33,lambda_qp,mu_qp; PetscReal *dNidx,*dNidy; PetscReal coor_qp[2]; PetscBool inside_fault_region; PetscBool sliding_active; dNidx = c->dN_dx[q]; dNidy = c->dN_dy[q]; /* compute strain @ quadrature point */ /* e = Bu = [ d/dx 0 ][ u v ]^T [ 0 d/dy ] [ d/dy d/dx ] */ e_vec[0] = e_vec[1] = e_vec[2] = 0.0; for (i=0; i<nbasis; i++) { e_vec[0] += dNidx[i] * ux[i]; e_vec[1] += dNidy[i] * uy[i]; e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]); } edot_vec[0] = edot_vec[1] = edot_vec[2] = 0.0; for (i=0; i<nbasis; i++) { edot_vec[0] += dNidx[i] * vx[i]; edot_vec[1] += dNidy[i] * vy[i]; edot_vec[2] += (dNidx[i] * vy[i] + dNidy[i] * vx[i]); } gradu[0] = gradu[1] = gradu[2] = gradu[3] = 0.0; gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0; for (i=0; i<nbasis; i++) { gradu[0] += dNidx[i] * ux[i]; gradu[1] += dNidy[i] * ux[i]; gradu[2] += dNidx[i] * uy[i]; gradu[3] += dNidy[i] * uy[i]; gradv[0] += dNidx[i] * vx[i]; gradv[1] += dNidy[i] * vx[i]; gradv[2] += dNidx[i] * vy[i]; gradv[3] += dNidy[i] * vy[i]; } coor_qp[0] = elcoords[2*q ]; coor_qp[1] = elcoords[2*q+1]; /* evaluate constitutive model */ lambda_qp = celldata->lambda; mu_qp = celldata->mu; /* coeff = E_qp * (1.0 + nu_qp)/(1.0 - 2.0*nu_qp); c11 = coeff*(1.0 - nu_qp); c12 = coeff*(nu_qp); c21 = coeff*(nu_qp); c22 = coeff*(1.0 - nu_qp); c33 = coeff*(0.5 * (1.0 - 2.0 * nu_qp)); */ c11 = 2.0 * mu_qp + lambda_qp; c12 = lambda_qp; c21 = lambda_qp; c22 = 2.0 * mu_qp + lambda_qp; c33 = mu_qp; /* compute stress @ quadrature point */ sigma_vec[TENS2D_XX] = c11 * e_vec[0] + c12 * e_vec[1]; sigma_vec[TENS2D_YY] = c21 * e_vec[0] + c22 * e_vec[1]; sigma_vec[TENS2D_XY] = c33 * e_vec[2]; /* From Day and Ely "Effect of a Shallow Weak Zone on Fault Rupture: Numerical Simulation of Scale-Model Experiments", BSSA, 2002 alpha = cp beta = cs volumetric terms; rho (cp^2 - 2 cs^2) gamma [div(v)] shear terms; rho cs^2 gamma [v_{i,j} + v_{j,i}] */ /* //printf("lambda_qp * gamma %+1.4e : mu_qp * gamma %+1.4e\n",lambda_qp * gamma,mu_qp * gamma); sigma_vec[TENS2D_XX] += lambda_qp * gamma * edot_vec[0]; sigma_vec[TENS2D_YY] += lambda_qp * gamma * edot_vec[1]; sigma_vec[TENS2D_XY] += mu_qp * gamma * edot_vec[2]; */ { PetscReal factor = 1.0; //ierr = FaultSDFMollifer(coor_qp,2.0 * c->delta,NULL,&factor);CHKERRQ(ierr); //printf("%+1.4e %+1.4e %+1.4e\n",coor_qp[0],coor_qp[1],factor); c11 = factor * (2.0 * mu_qp + lambda_qp) * gamma; c12 = factor * (lambda_qp) * gamma; c21 = factor * (lambda_qp) * gamma; c22 = factor * (2.0 * mu_qp + lambda_qp) * gamma; c33 = factor * (mu_qp) * gamma; } /* compute stress @ quadrature point */ sigma_vec[TENS2D_XX] += c11 * edot_vec[0] + c12 * edot_vec[1]; sigma_vec[TENS2D_YY] += c21 * edot_vec[0] + c22 * edot_vec[1]; sigma_vec[TENS2D_XY] += c33 * edot_vec[2]; sigma_trial[TENS2D_XX] = sigma_vec[TENS2D_XX]; sigma_trial[TENS2D_YY] = sigma_vec[TENS2D_YY]; sigma_trial[TENS2D_XY] = sigma_vec[TENS2D_XY]; inside_fault_region = PETSC_FALSE; ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&inside_fault_region);CHKERRQ(ierr); if (fabs(x_cell[1]) > c->delta) { inside_fault_region = PETSC_FALSE; } inside_fault_region = PETSC_FALSE; if (fabs(x_cell[1]) < c->delta && fabs(x_cell[0]) < 15.0e3) { inside_fault_region = PETSC_TRUE; } /* NOTE - Not sure how to generalize the notion of an off-fault normal stress for non-planar geometries */ /* NOTE - I'm not sure it is even well defined... */ if (inside_fault_region) { /* add the initial stress state on fault */ if (fabs(coor_qp[0]) < 1.5*1.0e3+1.0) { sigma_trial[TENS2D_XY] += sigma_t_1; sigma_trial[TENS2D_YY] += (-sigma_n_1); /* negative in compression */ } else { sigma_trial[TENS2D_XY] += sigma_t_0; sigma_trial[TENS2D_YY] += (-sigma_n_0); /* negative in compression */ } } else { sigma_trial[TENS2D_XY] += sigma_t_0; sigma_trial[TENS2D_YY] += (-sigma_n_0); /* negative in compression */ } /* Make stress glut corrections here */ if (inside_fault_region) { PetscReal x_plus[2],x_minus[2],v_plus[2],v_minus[2]; PetscReal normal[2],tangent[2],Vplus,Vminus,slip,slip_k,slip_rate; PetscReal sigma_n,sigma_t,phi_p; PetscReal e_inelastic_xy = 0.0; PetscReal tau,mu_s,mu_d,D_c,mu_friction,T, ttau; evaluate_sdf(NULL,coor_qp,&phi_p); //if (phi_p < 0) printf("[e %d , q %d] x_qp %+1.4e , %+1.4e : phi %+1.4e \n",e,q,coor_qp[0],coor_qp[1],phi_p); //printf(" x_qp -> phi %+1.4e\n",phi_p); ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr); //printf(" x_qp -> x+ %+1.4e , %+1.4e\n",x_plus[0],x_plus[1]); //printf(" x_qp -> x- %+1.4e , %+1.4e\n",x_minus[0],x_minus[1]); #if 1 /* ================================================================ */ ierr = FaultSDFTabulateInterpolation_v2(c,LA_u,&dr_celldata[q],v_plus,v_minus);CHKERRQ(ierr); ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr); ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr); /* Resolve velocities at delta(+,-) onto fault */ /* [option 2] Removal of normal component method */ /* I like this approach as it does not require a tangenet vector */ { PetscReal mag_vdotn; mag_vdotn = (v_plus[0] * normal[0] + v_plus[1] * normal[1]); v_plus[0] = v_plus[0] - mag_vdotn * normal[0]; v_plus[1] = v_plus[1] - mag_vdotn * normal[1]; /* Error checking is not generalized to non-planar faults */ if (fabs(v_plus[1]) > 1.0e-10) { /* error checking to ensure that the y component is completely removed */ printf(" phi %+1.8e : v+_y > 0 (%+1.8e)\n",phi_p,v_plus[1]); printf(" |v+| %+1.8e\n",mag_vdotn); printf(" x_qp -> v+ %+1.8e , %+1.8e\n",v_plus[0],v_plus[1]); exit(1); } mag_vdotn = (v_minus[0] * normal[0] + v_minus[1] * normal[1]); v_minus[0] = v_minus[0] - mag_vdotn * normal[0]; v_minus[1] = v_minus[1] - mag_vdotn * normal[1]; /* Error checking is not generalized to non-planar faults */ if (fabs(v_minus[1]) > 1.0e-10) { printf(" phi %+1.8e : v-_y > 0 (%+1.8e)\n",phi_p,v_minus[1]); printf(" |v-| %+1.8e\n",mag_vdotn); printf(" x_qp -> v+ %+1.8e , %+1.8e\n",v_minus[0],v_minus[1]); exit(1); } } /* I believe that extract the first component of the vector is perfectly valid for non-planar faults */ Vplus = v_plus[0]; Vminus = v_minus[0]; slip = Vplus - Vminus; slip = dr_celldata[q].slip; slip_rate = dr_celldata[q].slip_rate; //slip = (0.5*Vplus*c->delta - 0.5*Vminus*c->delta)/(2.0 * c->delta); /* ================================================================ */ #endif //slip = dr_celldata[q].slip; // n_i s_ij n_j // = ni si0 n0 + ni si1 n1 // = n0 s00 n0 + n1 s10 n0 + n0 s01 n1 + n1 s11 n1 sigma_n = 0.0; /* [option 1] */ sigma_n += normal[0] * sigma_trial[TENS2D_XX] * normal[0]; sigma_n += normal[1] * sigma_trial[TENS2D_XY] * normal[0]; sigma_n += normal[0] * sigma_trial[TENS2D_XY] * normal[1]; sigma_n += normal[1] * sigma_trial[TENS2D_YY] * normal[1]; /* [option 2] - only valid for a horizontal fault! */ /* option 1 and 2 are identical for horizontal fault */ sigma_n = sigma_trial[TENS2D_YY]; sigma_t = 0.0; /* [option 1] - uses the tangent vectors - yuck */ sigma_t += tangent[0] * sigma_trial[TENS2D_XX] * normal[0]; sigma_t += tangent[1] * sigma_trial[TENS2D_XY] * normal[0]; sigma_t += tangent[0] * sigma_trial[TENS2D_XY] * normal[1]; sigma_t += tangent[1] * sigma_trial[TENS2D_YY] * normal[1]; /* [option 2] - only valid for a horizontal fault! */ sigma_t = sigma_trial[TENS2D_XY]; sigma_t = sigma_t - mu_qp * gradu[2]; // new tweak [March 16] dr_celldata[q].mu = 0; e_inelastic_xy = 0.0; sliding_active = PETSC_FALSE; if (sigma_n < 0) { /* only consider inelastic corrections if in compression */ T = sqrt(sigma_t * sigma_t); /* Hard code linear slip weakening */ mu_s = c->mu_s; mu_d = c->mu_d; D_c = c->D_c; FricSW(&mu_friction, mu_s, mu_d, D_c, fabs(slip)); /* note the inclusion of making slip always positive */ dr_celldata[q].mu = mu_friction; tau = -mu_friction * sigma_n; if (tau < 0) { printf("-mu sigma_n < 0 error\n"); exit(1); } if (T > tau) { PetscReal factor; ierr = FaultSDFMollifer(coor_qp,dy,NULL,&factor);CHKERRQ(ierr); e_inelastic_xy = c->delta * (sigma_t - tau) / (mu_qp); // = du / dy /**Antiparallel condition between slip rate and critical shear */ ttau = tau; if ( sigma_t < 0.0) //slip_rate=v(+)-v(-) defined following Dalguer { ttau = -tau; //printf(" [phi: %f, T: %f, tau: %f, Coor_x: %f,Coor_y: %f, slipe_rate: %f, sigma_t (PreBlend): %f, slip: %f, e_vec[2]: %f]\n", phi_p, T, tau, coor_qp[0], coor_qp[1], slip_rate, sigma_t, slip, e_vec[2]); } sigma_trial[TENS2D_XY] = ttau; /**TP3 - Smoothing for p > 1 */ if(c->basisorder > 1) { //ierr = PetscTanHWeighting( &sigma_t, sigma_t, tau, phi_p , 4.*(c->basisorder)/c->delta, 0.65*c->delta); CHKERRQ(ierr); ierr = PetscTanHWeighting( &sigma_t, sigma_t, ttau, phi_p , 6.5*(c->basisorder)/c->delta, 0.85*c->delta); CHKERRQ(ierr); sigma_trial[TENS2D_XY] = sigma_t; } //printf(" sigma_xy %+1.8e\n",sigma_vec[TENS2D_XY]); sliding_active = PETSC_TRUE; dr_celldata[q].sliding = PETSC_TRUE; } else { e_inelastic_xy = 0.0; slip_rate = 0; sliding_active = PETSC_FALSE; } // Error checking / verification that consistency conditions are approximately satisfied /* if (T > fabs(tau)) { if (fabs(sigma_trial[TENS2D_XY]) - fabs(tau) > 1e-7) { printf(" [1] |T_t| - mu |T_n| %+1.12e < = ?\n",fabs(sigma_trial[TENS2D_XY]) - fabs(tau)); } { double a = slip_rate * fabs(sigma_trial[TENS2D_XY]) - fabs(slip_rate) * sigma_trial[TENS2D_XY]; if (fabs(a) > 1.0e-10) { printf(" [3] dot s |T_t| - |dot s| T_t %+1.12e = 0 ?\n",slip_rate * fabs(sigma_trial[TENS2D_XY]) - fabs(slip_rate) * sigma_trial[TENS2D_XY]); } } } */ } } /* Remove weird non-generalizable background stress state */ if (inside_fault_region) { /* remove the initial stress state on fault */ if (fabs(coor_qp[0]) < 1.5*1.0e3+1.0) { sigma_trial[TENS2D_XY] -= sigma_t_1; sigma_trial[TENS2D_YY] -= (-sigma_n_1); /* negative in compression */ } else { sigma_trial[TENS2D_XY] -= sigma_t_0; sigma_trial[TENS2D_YY] -= (-sigma_n_0); /* negative in compression */ } } else { sigma_trial[TENS2D_XY] -= sigma_t_0; sigma_trial[TENS2D_YY] -= (-sigma_n_0); /* negative in compression */ } /* These components weren't modified in the horizontal fault case - but they might be in general */ sigma_vec[TENS2D_XX] = sigma_trial[TENS2D_XX]; sigma_vec[TENS2D_YY] = sigma_trial[TENS2D_YY]; /* This component was modified in the horizontal fault case - it's likely it might also be modified in the general case */ sigma_vec[TENS2D_XY] = sigma_trial[TENS2D_XY]; fac = detJ * c->w[q]; for (i=0; i<nbasis; i++) { fe[2*i ] += -fac * (dNidx[i] * sigma_vec[TENS2D_XX] + dNidy[i] * sigma_vec[TENS2D_XY]); fe[2*i+1] += -fac * (dNidy[i] * sigma_vec[TENS2D_YY] + dNidx[i] * sigma_vec[TENS2D_XY]); } } ierr = VecSetValues(fl,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(fl);CHKERRQ(ierr); ierr = VecAssemblyEnd(fl);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr); ierr = VecRestoreArrayRead(vl,&LA_v);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&vl);CHKERRQ(ierr); ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&fl);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode Update_StressGlut2d(SpecFECtx c,Vec u,Vec v,PetscReal dt) { PetscErrorCode ierr; PetscInt e,nqp,q,i,nbasis,ndof; PetscReal e_vec[3],gradu[4],gradv[4],gradv_q[9*9][4]; PetscInt *element,*elnidx,*eldofs; PetscReal *ux,*uy,*vx,*vy,*elcoords,detJ,*fieldU,*fieldV; Vec coor,ul,vl; const PetscReal *LA_coor,*LA_u,*LA_v; QPntIsotropicElastic *celldata; DRVar *dr_celldata; static PetscBool beenhere = PETSC_FALSE; static PetscReal gmin[3],gmax[3]; PetscReal dx,dy; if (!beenhere) { ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); beenhere = PETSC_TRUE; } dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); eldofs = c->elbuf_dofs; elcoords = c->elbuf_coor; nbasis = c->npe; nqp = c->nqp; ndof = c->dofs; element = c->element; fieldU = c->elbuf_field2; fieldV = c->elbuf_field3; ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr); ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&vl);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr); ierr = VecGetArrayRead(vl,&LA_v);CHKERRQ(ierr); ux = &fieldU[0]; uy = &fieldU[nbasis]; vx = &fieldV[0]; vy = &fieldV[nbasis]; for (e=0; e<c->ne; e++) { PetscReal x_cell[] = {0,0}; /* get element -> node map */ elnidx = &element[nbasis*e]; /* generate dofs */ for (i=0; i<nbasis; i++) { eldofs[2*i ] = 2*elnidx[i]; eldofs[2*i+1] = 2*elnidx[i]+1; } /* get element coordinates */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; elcoords[2*i ] = LA_coor[2*nidx ]; elcoords[2*i+1] = LA_coor[2*nidx+1]; x_cell[0] += elcoords[2*i ]; x_cell[1] += elcoords[2*i+1]; } x_cell[0] = x_cell[0] / ((PetscReal)nbasis); x_cell[1] = x_cell[1] / ((PetscReal)nbasis); /* get element displacements & velocities */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; ux[i] = LA_u[2*nidx ]; uy[i] = LA_u[2*nidx+1]; vx[i] = LA_v[2*nidx ]; vy[i] = LA_v[2*nidx+1]; } /* compute derivatives */ ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ); ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords, c->npe_1d,c->dN_dxi,c->dN_deta, c->dN_dx,c->dN_dy); /* get access to element->quadrature points */ celldata = &c->cell_data[e]; ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr); for (q=0; q<c->nqp; q++) { PetscReal *dNidx,*dNidy; dNidx = c->dN_dx[q]; dNidy = c->dN_dy[q]; gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0; for (i=0; i<nbasis; i++) { gradv[0] += dNidx[i] * vx[i]; gradv[1] += dNidy[i] * vx[i]; gradv[2] += dNidx[i] * vy[i]; gradv[3] += dNidy[i] * vy[i]; } gradv_q[q][0] = gradv[0]; gradv_q[q][1] = gradv[1]; gradv_q[q][2] = gradv[2]; gradv_q[q][3] = gradv[3]; } for (q=0; q<c->nqp; q++) { PetscReal *dNidx,*dNidy; PetscReal coor_qp[2]; PetscBool inside_fault_region; dNidx = c->dN_dx[q]; dNidy = c->dN_dy[q]; /* compute strain @ quadrature point */ /* e = Bu = [ d/dx 0 ][ u v ]^T [ 0 d/dy ] [ d/dy d/dx ] */ e_vec[0] = e_vec[1] = e_vec[2] = 0.0; for (i=0; i<nbasis; i++) { e_vec[0] += dNidx[i] * ux[i]; e_vec[1] += dNidy[i] * uy[i]; e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]); } gradu[0] = gradu[1] = gradu[2] = gradu[3] = 0.0; gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0; for (i=0; i<nbasis; i++) { gradu[0] += dNidx[i] * ux[i]; gradu[1] += dNidy[i] * ux[i]; gradu[2] += dNidx[i] * uy[i]; gradu[3] += dNidy[i] * uy[i]; gradv[0] += dNidx[i] * vx[i]; gradv[1] += dNidy[i] * vx[i]; gradv[2] += dNidx[i] * vy[i]; gradv[3] += dNidy[i] * vy[i]; } coor_qp[0] = elcoords[2*q ]; coor_qp[1] = elcoords[2*q+1]; inside_fault_region = PETSC_FALSE; ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&inside_fault_region);CHKERRQ(ierr); if (fabs(x_cell[1]) > c->delta) { inside_fault_region = PETSC_FALSE; } inside_fault_region = PETSC_FALSE; if (fabs(x_cell[1]) < c->delta && fabs(x_cell[0]) < 15.0e3) { inside_fault_region = PETSC_TRUE; } //if (e == 720849) { // printf("e %d : xcell %+1.8e %+1.8e inside? %d\n",e,x_cell[0],x_cell[1],(int)inside_fault_region); //} /* Make stress glut corrections here */ if (inside_fault_region) { PetscReal x_plus[2],x_minus[2],plus[2],minus[2]; PetscReal normal[2],tangent[2],Uplus,Uminus,Vplus,Vminus,slip,slip_rate,phi_p; evaluate_sdf(NULL,coor_qp,&phi_p); ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr); /* ================================================================ */ ierr = FaultSDFTabulateInterpolation_v2(c,LA_v,&dr_celldata[q],plus,minus);CHKERRQ(ierr); ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr); ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr); /* Resolve velocities at delta(+,-) onto fault */ { PetscReal mag_vdotn; mag_vdotn = plus[0] * normal[0] + plus[1] * normal[1]; plus[0] = plus[0] - mag_vdotn * normal[0]; plus[1] = plus[1] - mag_vdotn * normal[1]; mag_vdotn = minus[0] * normal[0] + minus[1] * normal[1]; minus[0] = minus[0] - mag_vdotn * normal[0]; minus[1] = minus[1] - mag_vdotn * normal[1]; } Vplus = plus[0]; Vminus = minus[0]; slip_rate = Vplus - Vminus; /* mid-point quadrature rule */ //slip_rate = (0.5*Vplus*c->delta - 0.5*Vminus*c->delta)/(2.0*c->delta); /* ================================================================ */ ierr = FaultSDFTabulateInterpolation_v2(c,LA_u,&dr_celldata[q],plus,minus);CHKERRQ(ierr); ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr); ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr); /* Resolve displacement at delta(+,-) onto fault */ { PetscReal mag_vdotn; mag_vdotn = plus[0] * normal[0] + plus[1] * normal[1]; plus[0] = plus[0] - mag_vdotn * normal[0]; plus[1] = plus[1] - mag_vdotn * normal[1]; mag_vdotn = minus[0] * normal[0] + minus[1] * normal[1]; minus[0] = minus[0] - mag_vdotn * normal[0]; minus[1] = minus[1] - mag_vdotn * normal[1]; } Uplus = plus[0]; Uminus = minus[0]; slip = Uplus - Uminus; /* mid-point quadrature rule */ //slip = (0.5*Uplus*c->delta - 0.5*Uminus*c->delta)/(2.0*c->delta); /* ================================================================ */ if (dr_celldata[q].sliding) { /* dr_celldata[q].slip_rate = slip_rate; dr_celldata[q].slip += slip_rate * dt; dr_celldata[q].slip_rate = (slip - dr_celldata[q].slip)/dt; dr_celldata[q].slip = slip; */ dr_celldata[q].slip_rate = slip_rate; dr_celldata[q].slip = slip; } } } } ierr = VecRestoreArrayRead(vl,&LA_v);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&vl);CHKERRQ(ierr); ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode AssembleBilinearForm_Mass2d(SpecFECtx c,Vec A) { PetscErrorCode ierr; PetscInt e,index,q,i,nbasis,ndof; PetscInt *element,*elnidx,*eldofs; PetscReal *elcoords,*Me,detJ; Vec coor; const PetscReal *LA_coor; QPntIsotropicElastic *celldata; ierr = VecZeroEntries(A);CHKERRQ(ierr); eldofs = c->elbuf_dofs; elcoords = c->elbuf_coor; nbasis = c->npe; ndof = c->dofs; Me = c->elbuf_field; element = c->element; ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr); for (e=0; e<c->ne; e++) { /* get element -> node map */ elnidx = &element[nbasis*e]; /* generate dofs */ for (i=0; i<nbasis; i++) { eldofs[2*i ] = 2*elnidx[i]; eldofs[2*i+1] = 2*elnidx[i]+1; } /* get element coordinates */ for (i=0; i<nbasis; i++) { PetscInt nidx = elnidx[i]; elcoords[2*i ] = LA_coor[2*nidx ]; elcoords[2*i+1] = LA_coor[2*nidx+1]; } ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ); /* get access to element->quadrature points */ celldata = &c->cell_data[e]; for (q=0; q<nbasis; q++) { PetscReal fac,Me_ii; fac = detJ * c->w[q]; Me_ii = fac * (celldata->rho); /* \int u0v0 dV */ index = 2*q; Me[index] = Me_ii; /* \int u1v1 dV */ index = 2*q + 1; Me[index] = Me_ii; } ierr = VecSetValuesLocal(A,nbasis*ndof,eldofs,Me,ADD_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(A);CHKERRQ(ierr); ierr = VecAssemblyEnd(A);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode ElastoDynamicsConvertLame2Velocity(PetscReal rho,PetscReal mu,PetscReal lambda,PetscReal *Vs,PetscReal *Vp) { if (Vs) { *Vs = PetscSqrtReal(mu/rho); } if (Vp) { *Vp = PetscSqrtReal( (lambda + 2.0*mu)/rho); } PetscFunctionReturn(0); } PetscErrorCode ElastoDynamicsComputeTimeStep_2d(SpecFECtx ctx,PetscReal *_dt) { PetscInt e,q,order; PetscReal dt_min,dt_min_g,polynomial_fac; //QPntIsotropicElastic *qpdata; PetscReal gmin[3],gmax[3],min_el_r,dx,dy; PetscErrorCode ierr; QPntIsotropicElastic *celldata; *_dt = PETSC_MAX_REAL; dt_min = PETSC_MAX_REAL; order = ctx->basisorder; polynomial_fac = 1.0 / (2.0 * (PetscReal)order + 1.0); ierr = DMGetBoundingBox(ctx->dm,gmin,gmax);CHKERRQ(ierr); dx = (gmax[0] - gmin[0])/((PetscReal)ctx->mx_g); dy = (gmax[1] - gmin[1])/((PetscReal)ctx->my_g); min_el_r = dx; min_el_r = PetscMin(min_el_r,dy); /* find smallest dx across the element in local coordinates */ { PetscInt n; PetscReal sep2min,sep2; sep2min = 1.0e32; for (n=0; n<ctx->npe_1d-1; n++) { sep2 = PetscAbsReal(ctx->xi1d[n+1] - ctx->xi1d[n]); /*printf(" xi %+1.4e [n] : xi %+1.4e [n+1] : delta_xi %+1.6e\n",ctx->xi1d[n],ctx->xi1d[n+1],sep2); */ if (sep2 < sep2min) { sep2min = sep2; } } polynomial_fac = 1.0; min_el_r = min_el_r * ( sep2min / 2.0 ); /* the factor 2.0 here is associated with the size of the element in the local coordinate system xi \in [-1,+1] */ } for (e=0; e<ctx->ne; e++) { PetscReal max_el_Vp,value; /* get max Vp for element */ max_el_Vp = PETSC_MIN_REAL; /* get access to element->quadrature points */ celldata = &ctx->cell_data[e]; for (q=0; q<ctx->nqp; q++) { PetscReal qp_rho,qp_mu,qp_lambda,qp_Vp; qp_rho = celldata->rho; qp_mu = celldata->mu; qp_lambda = celldata->lambda; ierr = ElastoDynamicsConvertLame2Velocity(qp_rho,qp_mu,qp_lambda,0,&qp_Vp);CHKERRQ(ierr); max_el_Vp = PetscMax(max_el_Vp,qp_Vp); } value = polynomial_fac * 1.0 * min_el_r / max_el_Vp; dt_min = PetscMin(dt_min,value); } ierr = MPI_Allreduce(&dt_min,&dt_min_g,1,MPIU_REAL,MPIU_MIN,PETSC_COMM_WORLD);CHKERRQ(ierr); *_dt = dt_min_g; PetscFunctionReturn(0); } PetscErrorCode RecordUV(SpecFECtx c,PetscReal time,PetscReal xr[],Vec u,Vec v) { FILE *fp = NULL; PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2; const PetscReal *LA_u,*LA_v,*LA_c; Vec coor; static PetscBool beenhere = PETSC_FALSE; PetscErrorCode ierr; PetscInt ei,ej,n,nid,eid,*element,*elbasis; static char filename[PETSC_MAX_PATH_LEN]; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Needs updating to support MPI"); if (!beenhere) { ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,"receiverCP-%Dx%D-p%D.dat",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr); } ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */ dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[1] - gmin[1])/dy; /* todo - needs to be sub-domain gmin */ eid = ei + ej * c->mx; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); // find closest // sep2min = 1.0e32; nid = -1; for (n=0; n<c->npe; n++) { sep2 = (xr[0]-LA_c[2*elbasis[n]])*(xr[0]-LA_c[2*elbasis[n]]); sep2 += (xr[1]-LA_c[2*elbasis[n]+1])*(xr[1]-LA_c[2*elbasis[n]+1]); if (sep2 < sep2min) { nid = elbasis[n]; sep2min = sep2; } } if (!beenhere) { fp = fopen(filename,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"# SpecFECtx meta data\n"); fprintf(fp,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp,"# Receiver meta data\n"); fprintf(fp,"# + receiver location: x,y %+1.8e %+1.8e\n",xr[0],xr[1]); fprintf(fp,"# + takes displ/velo from basis nearest to requested receiver location\n"); fprintf(fp,"# + receiver location: x,y %+1.8e %+1.8e --mapped to nearest node --> %+1.8e %+1.8e\n",xr[0],xr[1],LA_c[2*nid],LA_c[2*nid+1]); fprintf(fp,"# Time series header\n"); fprintf(fp,"# time ux uy vx vy\n"); beenhere = PETSC_TRUE; } else { fp = fopen(filename,"a"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); } ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr); ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr); fprintf(fp,"%1.4e %+1.8e %+1.8e %+1.8e %+1.8e\n",time,LA_u[2*nid],LA_u[2*nid+1],LA_v[2*nid],LA_v[2*nid+1]); ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); fclose(fp); PetscFunctionReturn(0); } PetscErrorCode RecordUV_interp(SpecFECtx c,PetscReal time,PetscReal xr[],Vec u,Vec v) { FILE *fp = NULL; PetscReal gmin[3],gmax[3],dx,dy,ur[2],vr[2]; const PetscReal *LA_u,*LA_v; static PetscBool beenhere = PETSC_FALSE; PetscErrorCode ierr; PetscInt k,ei,ej,eid,*element,*elbasis; static PetscReal N[400]; static char filename[PETSC_MAX_PATH_LEN]; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Needs updating to support MPI"); if (!beenhere) { ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,"receiver-%Dx%D-p%D.dat",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr); } if (!beenhere) { fp = fopen(filename,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"# SpecFECtx meta data\n"); fprintf(fp,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp,"# Receiver meta data\n"); fprintf(fp,"# + receiver location: x,y %+1.8e %+1.8e\n",xr[0],xr[1]); fprintf(fp,"# + records displ/velo at requested receiver location through interpolating the FE solution\n"); fprintf(fp,"# Time series header\n"); fprintf(fp,"# time ux uy vx vy\n"); } else { fp = fopen(filename,"a"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); } /* get containing element */ ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */ dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[1] - gmin[1])/dy; eid = ei + ej * c->mx; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; if (!beenhere) { PetscInt nbasis,i,j; PetscReal **N_s1,**N_s2,xri[2],xi,eta,x0,y0; const PetscReal *LA_c; Vec coor; /* compute xi,eta */ ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */ y0 = gmin[1] + ej*dy; // (xi - (-1))/2 = (x - x0)/dx xi = 2.0*(xr[0] - x0)/dx - 1.0; eta = 2.0*(xr[1] - y0)/dy - 1.0; /* compute basis */ ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr); ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr); k = 0; for (j=0; j<c->npe_1d; j++) { for (i=0; i<c->npe_1d; i++) { N[k] = N_s1[0][i] * N_s2[0][j]; k++; } } ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); xri[0] = xri[1] = 0.0; for (k=0; k<c->npe; k++) { PetscInt nid = elbasis[k]; xri[0] += N[k] * LA_c[2*nid+0]; xri[1] += N[k] * LA_c[2*nid+1]; } PetscPrintf(PETSC_COMM_SELF,"# receiver location: x,y %+1.8e %+1.8e -- interpolated coordinate --> %+1.8e %+1.8e\n",xr[0],xr[1],xri[0],xri[1]); ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); ierr = PetscFree(N_s1[0]);CHKERRQ(ierr); ierr = PetscFree(N_s1);CHKERRQ(ierr); ierr = PetscFree(N_s2[0]);CHKERRQ(ierr); ierr = PetscFree(N_s2);CHKERRQ(ierr); } ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr); ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr); ur[0] = ur[1] = vr[0] = vr[1] = 0.0; for (k=0; k<c->npe; k++) { PetscInt nid = elbasis[k]; ur[0] += N[k] * LA_u[2*nid+0]; ur[1] += N[k] * LA_u[2*nid+1]; vr[0] += N[k] * LA_v[2*nid+0]; vr[1] += N[k] * LA_v[2*nid+1]; } fprintf(fp,"%1.4e %+1.8e %+1.8e %+1.8e %+1.8e\n",time,ur[0],ur[1],vr[0],vr[1]); ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr); beenhere = PETSC_TRUE; fclose(fp); PetscFunctionReturn(0); } PetscErrorCode RecordUVA_MultipleStations_NearestGLL_SEQ(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a) { FILE *fp = NULL; const PetscReal *LA_u,*LA_v,*LA_a; static PetscBool beenhere = PETSC_FALSE; static char filename[PETSC_MAX_PATH_LEN]; static PetscInt *nid_list = NULL; PetscInt r; PetscErrorCode ierr; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Supports sequential only"); if (!beenhere) { const PetscReal *LA_c; Vec coor; PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2; PetscInt ei,ej,n,nid,eid,*element,*elbasis; ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,"closestqpsource-receiverCP-uva-%Dx%D-p%D.dat",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr); ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); for (r=0; r<nr; r++) { if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)",r,xr[2*r+0],gmin[0]); if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)",r,xr[2*r+1],gmin[1]); if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)",r,xr[2*r+0],gmax[0]); if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)",r,xr[2*r+1],gmax[1]); dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[2*r+0] - gmin[0])/dx; if (ei == c->mx_g) ei--; dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[2*r+1] - gmin[1])/dy; if (ej == c->my_g) ej--; eid = ei + ej * c->mx_g; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; // find closest // sep2min = 1.0e32; nid = -1; for (n=0; n<c->npe; n++) { sep2 = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]); sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]); if (sep2 < sep2min) { nid = elbasis[n]; sep2min = sep2; } } nid_list[r] = nid; } fp = fopen(filename,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"# SpecFECtx meta data\n"); fprintf(fp,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp,"# Receiver meta data\n"); fprintf(fp,"# + number receiver locations: %d\n",nr); fprintf(fp,"# + takes displ/velo/accel from basis nearest to requested receiver location\n"); for (r=0; r<nr; r++) { fprintf(fp,"# + receiver location [%d]: x,y %+1.8e %+1.8e\n",r,xr[2*r+0],xr[2*r+1]); fprintf(fp,"# + mapped to nearest node --> %+1.8e %+1.8e\n",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]); } fprintf(fp,"# Time series header <field>(<column index>)\n"); fprintf(fp,"# time(1)\n"); for (r=0; r<nr; r++) { PetscInt offset = 1 + r*6; /* 1 is for time */ fprintf(fp,"# ux(%d) uy(%d) vx(%d) vy(%d) ax(%d) ay(%d) -> station [%d]\n",offset+1,offset+2,offset+3,offset+4,offset+5,offset+6,r); } ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); beenhere = PETSC_TRUE; } else { fp = fopen(filename,"a"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); } ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr); ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr); ierr = VecGetArrayRead(a,&LA_a);CHKERRQ(ierr); fprintf(fp,"%1.4e",time); for (r=0; r<nr; r++) { fprintf(fp," %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e",LA_u[2*nid_list[r]],LA_u[2*nid_list[r]+1],LA_v[2*nid_list[r]],LA_v[2*nid_list[r]+1],LA_a[2*nid_list[r]],LA_a[2*nid_list[r]+1]); } fprintf(fp,"\n"); ierr = VecRestoreArrayRead(a,&LA_a);CHKERRQ(ierr); ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr); fclose(fp); PetscFunctionReturn(0); } PetscErrorCode RecordUVA_MultipleStations_NearestGLL_MPI(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a) { FILE *fp = NULL; const PetscReal *LA_u,*LA_v,*LA_a,*LA_c; static PetscBool beenhere = PETSC_FALSE; static char filename[PETSC_MAX_PATH_LEN]; static PetscInt *nid_list = NULL; static PetscInt *eid_list = NULL; static PetscInt *gll_list = NULL; static PetscInt nr_local = 0; PetscInt r,k; Vec lu,lv,la,coor; PetscErrorCode ierr; if (!beenhere) { PetscReal gmin[3],gmax[3],gmin_domain[3],gmax_domain[3],dx,dy,sep2min,sep2; PetscInt ei,ej,n,nid,gllid,eid,*element,*elbasis; ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,"closestqpsource-receiverCP-uva-%Dx%D-p%D-rank%d.dat",c->mx_g,c->my_g,c->basisorder,(int)c->rank);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&eid_list);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&gll_list);CHKERRQ(ierr); for (r=0; r<nr; r++) { nid_list[r] = -1; eid_list[r] = -1; gll_list[r] = -1; } ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); ierr = SpecFECtxGetLocalBoundingBox(c,gmin_domain,gmax_domain);CHKERRQ(ierr); ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); for (r=0; r<nr; r++) { int count,recv_count; PetscBool receiver_found = PETSC_TRUE; int rank,rank_min_g; if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)",r,xr[2*r+0],gmin[0]); if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)",r,xr[2*r+1],gmin[1]); if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)",r,xr[2*r+0],gmax[0]); if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)",r,xr[2*r+1],gmax[1]); if (xr[2*r+0] < gmin_domain[0]) receiver_found = PETSC_FALSE; if (xr[2*r+1] < gmin_domain[1]) receiver_found = PETSC_FALSE; if (xr[2*r+0] > gmax_domain[0]) receiver_found = PETSC_FALSE; if (xr[2*r+1] > gmax_domain[1]) receiver_found = PETSC_FALSE; dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[2*r+0] - gmin_domain[0])/dx; if (ei == c->mx) ei--; dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[2*r+1] - gmin_domain[1])/dy; if (ej == c->my) ej--; if (ei < 0) receiver_found = PETSC_FALSE; if (ej < 0) receiver_found = PETSC_FALSE; if (ei > c->mx) receiver_found = PETSC_FALSE; if (ej > c->my) receiver_found = PETSC_FALSE; nid = -1; gllid = -1; if (receiver_found) { eid = ei + ej * c->mx; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; // find closest // sep2min = 1.0e32; for (n=0; n<c->npe; n++) { sep2 = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]); sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]); if (sep2 < sep2min) { nid = elbasis[n]; gllid = n; sep2min = sep2; } } } /* check for duplicates */ count = 0; if (receiver_found) { count = 1; } ierr = MPI_Allreduce(&count,&recv_count,1,MPI_INT,MPI_SUM,PETSC_COMM_WORLD);CHKERRQ(ierr); if (recv_count == 0) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"A receiver was defined but no rank claimed it"); if (recv_count > 1) { /* resolve duplicates */ rank = (int)c->rank; if (!receiver_found) { rank = (int)c->size; } ierr = MPI_Allreduce(&rank,&rank_min_g,1,MPI_INT,MPI_MIN,PETSC_COMM_WORLD);CHKERRQ(ierr); if (rank == rank_min_g) { PetscPrintf(PETSC_COMM_SELF,"[RecordUVA] + Multiple ranks located receiver (%+1.4e,%+1.4e) - rank %d claiming ownership\n",xr[2*r+0],xr[2*r+1],rank_min_g); } /* mark non-owning ranks as not claiming source */ if (rank != rank_min_g) { receiver_found = PETSC_FALSE; } } if (receiver_found) { nid_list[r] = nid; eid_list[r] = eid; gll_list[r] = gllid; nr_local++; } } fp = fopen(filename,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"# SpecFECtx meta data\n"); fprintf(fp,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp,"# Receiver meta data\n"); fprintf(fp,"# + number receiver locations: %d\n",nr); fprintf(fp,"# + number receiver locations <local>: %d\n",nr_local); fprintf(fp,"# + takes displ/velo/accel from basis nearest to requested receiver location\n"); for (r=0; r<nr; r++) { if (nid_list[r] == -1) { continue; } fprintf(fp,"# + receiver location [%d]: x,y %+1.8e %+1.8e\n",r,xr[2*r+0],xr[2*r+1]); fprintf(fp,"# + mapped to nearest node --> %+1.8e %+1.8e\n",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]); } if (nr_local != 0) { PetscInt count = 0; fprintf(fp,"# Time series header <field>(<column index>)\n"); fprintf(fp,"# time(1)\n"); for (r=0; r<nr; r++) { PetscInt offset; if (nid_list[r] == -1) { continue; } offset = 1 + count*7; /* 1 is for time */ fprintf(fp,"# ux(%d) uy(%d) vx(%d) vy(%d) ax(%d) ay(%d) curl(v) (%d)-> station [%d]\n",offset+1,offset+2,offset+3,offset+4,offset+5,offset+6,offset+7,r); count++; } } else { fprintf(fp,"# <note> No receivers found on this sub-domain\n"); fprintf(fp,"# <note> This file will remain empty\n"); } ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); fclose(fp); fp = NULL; } if (!beenhere) { char metafname[PETSC_MAX_PATH_LEN]; FILE *fp_meta = NULL; int *owned,*owned_g; ierr = PetscSNPrintf(metafname,PETSC_MAX_PATH_LEN-1,"closestqpsource-receiverCP-uva-%Dx%D-p%D.mpimeta",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&owned);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&owned_g);CHKERRQ(ierr); for (r=0; r<nr; r++) { owned[r] = -1; if (nid_list[r] != -1) { owned[r] = (int)c->rank; } } ierr = MPI_Allreduce(owned,owned_g,nr,MPI_INT,MPI_MAX,PETSC_COMM_WORLD);CHKERRQ(ierr); if (c->rank == 0) { fp_meta = fopen(metafname,"w"); if (!fp_meta) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",metafname); fprintf(fp_meta,"# SpecFECtx parallel/MPI meta data\n"); fprintf(fp_meta,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp_meta,"# Receiver meta data\n"); fprintf(fp_meta,"# + number receiver locations: %d\n",nr); for (r=0; r<nr; r++) { fprintf(fp_meta,"# + receiver [%d]: mapped to MPI rank %d\n",r,owned_g[r]); } fclose(fp_meta); } ierr = PetscFree(owned_g);CHKERRQ(ierr); ierr = PetscFree(owned);CHKERRQ(ierr); } beenhere = PETSC_TRUE; ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&lu);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&lv);CHKERRQ(ierr); ierr = DMGetLocalVector(c->dm,&la);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,lu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,lu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,lv);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,lv);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(c->dm,a,INSERT_VALUES,la);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(c->dm,a,INSERT_VALUES,la);CHKERRQ(ierr); ierr = VecGetArrayRead(lu,&LA_u);CHKERRQ(ierr); ierr = VecGetArrayRead(lv,&LA_v);CHKERRQ(ierr); ierr = VecGetArrayRead(la,&LA_a);CHKERRQ(ierr); if (nr_local != 0) { fp = fopen(filename,"a"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"%1.4e",time); for (r=0; r<nr; r++) { PetscInt eidx,gllidx; PetscReal *elcoor,*elvelocity; PetscReal dvxdy,dvydx,curl; PetscReal *grad_N_xi[2]; PetscReal *grad_N_x[2]; if (eid_list[r] == -1) { continue; } /* write the components of u,v,a */ fprintf(fp," %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e",LA_u[2*nid_list[r]],LA_u[2*nid_list[r]+1],LA_v[2*nid_list[r]],LA_v[2*nid_list[r]+1],LA_a[2*nid_list[r]],LA_a[2*nid_list[r]+1]); /* compute and write the k^th component of the curl(v) */ eidx = eid_list[r]; gllidx = gll_list[r]; grad_N_xi[0] = c->dN_dxi[gllidx]; grad_N_xi[1] = c->dN_deta[gllidx]; grad_N_x[0] = c->dN_dx[gllidx]; grad_N_x[1] = c->dN_dy[gllidx]; elcoor = c->elbuf_field; elvelocity = c->elbuf_field2; for (k=0; k<c->npe; k++) { PetscInt basisid = c->element[c->npe*eidx + k]; elcoor[2*k+0] = LA_c[2*basisid + 0]; elcoor[2*k+1] = LA_c[2*basisid + 1]; elvelocity[2*k+0] = LA_v[2*basisid + 0]; elvelocity[2*k+1] = LA_v[2*basisid + 1]; } ElementEvaluateDerivatives_CellWiseConstant2d(1,c->npe,elcoor,c->npe_1d,&grad_N_xi[0],&grad_N_xi[1],&grad_N_x[0],&grad_N_x[1]); dvxdy = 0.0; dvydx = 0.0; for (k=0; k<c->npe; k++) { PetscReal vx,vy; vx = elvelocity[2*k+0]; vy = elvelocity[2*k+1]; dvxdy += grad_N_x[1][k] * vx; dvydx += grad_N_x[0][k] * vy; } curl = dvydx - dvxdy; fprintf(fp," %+1.8e",curl); } fprintf(fp,"\n"); if (fp) { fclose(fp); fp = NULL; } } ierr = VecRestoreArrayRead(a,&LA_a);CHKERRQ(ierr); ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr); ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr); ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&la);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&lv);CHKERRQ(ierr); ierr = DMRestoreLocalVector(c->dm,&lu);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode RecordUVA_MultipleStations_NearestGLL(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a) { PetscErrorCode ierr; //if (c->size == 1) { //ierr = RecordUVA_MultipleStations_NearestGLL_SEQ(c,time,nr,xr,u,v,a);CHKERRQ(ierr); //} else { ierr = RecordUVA_MultipleStations_NearestGLL_MPI(c,time,nr,xr,u,v,a);CHKERRQ(ierr); //} PetscFunctionReturn(0); } PetscErrorCode RecordDRVar_MultipleStations_NearestGLL_SEQ(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[]) { FILE *fp = NULL; static PetscBool beenhere = PETSC_FALSE; static char filename[PETSC_MAX_PATH_LEN]; static PetscInt *qid_list = NULL; static PetscInt *nid_list = NULL; static PetscInt *eid_list = NULL; PetscInt r; PetscErrorCode ierr; if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Supports sequential only"); if (!beenhere) { const PetscReal *LA_c; Vec coor; PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2; PetscInt ei,ej,n,qid,nid,eid,*element,*elbasis; ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,"receiverCP-dr-%Dx%D-p%D.dat",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&qid_list);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr); ierr = PetscMalloc1(nr,&eid_list);CHKERRQ(ierr); ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr); ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr); ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr); for (r=0; r<nr; r++) { if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)",r,xr[2*r+0],gmin[0]); if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)",r,xr[2*r+1],gmin[1]); if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)",r,xr[2*r+0],gmax[0]); if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)",r,xr[2*r+1],gmax[1]); dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g); ei = (xr[2*r+0] - gmin[0])/dx; if (ei == c->mx_g) ei--; dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g); ej = (xr[2*r+1] - gmin[1])/dy; if (ej == c->my_g) ej--; eid = ei + ej * c->mx_g; eid_list[r] = eid; { PetscBool inside; PetscInt e,i; sep2min = 1.0e32; element = c->element; for (e=0; e<c->ne; e++) { PetscReal xcell[] = {0,0}; elbasis = &element[c->npe*e]; for (i=0; i<c->npe; i++) { xcell[0] += LA_c[2*elbasis[i]+0]; xcell[1] += LA_c[2*elbasis[i]+1]; } xcell[0] = xcell[0] / ((PetscReal)c->npe); xcell[1] = xcell[1] / ((PetscReal)c->npe); ierr = FaultSDFQuery(xcell,c->delta,NULL,&inside);CHKERRQ(ierr); if (inside) { sep2 = (xr[2*r+0]-xcell[0])*(xr[2*r+0]-xcell[0]); sep2 += (xr[2*r+1]-xcell[1])*(xr[2*r+1]-xcell[1]); if (sep2 < sep2min) { eid = e; sep2min = sep2; } } } } eid_list[r] = eid; /* get element -> node map */ element = c->element; elbasis = &element[c->npe*eid]; // find closest // sep2min = 1.0e32; nid = -1; qid = -1; for (n=0; n<c->npe; n++) { sep2 = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]); sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]); if (sep2 < sep2min) { nid = elbasis[n]; qid = n; sep2min = sep2; } } nid_list[r] = nid; qid_list[r] = qid; } fp = fopen(filename,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); fprintf(fp,"# SpecFECtx meta data\n"); fprintf(fp,"# mx %d : my %d : basis order %d\n",c->mx_g,c->my_g,c->basisorder); fprintf(fp,"# Receiver meta data\n"); fprintf(fp,"# + number receiver locations: %d\n",nr); fprintf(fp,"# + takes DR variables from quadrature point nearest to requested receiver location\n"); for (r=0; r<nr; r++) { PetscReal xcell[] = {0,0}; PetscInt i; fprintf(fp,"# + receiver location [%d]: x,y %+1.8e %+1.8e\n",r,xr[2*r+0],xr[2*r+1]); fprintf(fp,"# + mapped to nearest node --> %+1.8e %+1.8e\n",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]); fprintf(fp,"# + mapped to nearest element/quad-point --> %d %d\n",eid_list[r],qid_list[r]); elbasis = &element[c->npe*eid_list[r]]; for (i=0; i<c->npe; i++) { xcell[0] += LA_c[2*elbasis[i]+0]; xcell[1] += LA_c[2*elbasis[i]+1]; } xcell[0] = xcell[0] / ((PetscReal)c->npe); xcell[1] = xcell[1] / ((PetscReal)c->npe); fprintf(fp,"# + mapped to nearest element --> %d with centroid %+1.8e %+1.8e\n",eid_list[r],xcell[0],xcell[1]); } fprintf(fp,"# Time series header <field>(<column index>)\n"); fprintf(fp,"# time(1)\n"); for (r=0; r<nr; r++) { PetscInt offset = 1 + r*4; /* 1 is for time */ fprintf(fp,"# slip(%d) sliprate(%d) mu(%d) sliding(%d) -> station [%d]\n",offset+1,offset+2,offset+3,offset+4,r); } ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr); beenhere = PETSC_TRUE; } else { fp = fopen(filename,"a"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",filename); } fprintf(fp,"%1.4e",time); for (r=0; r<nr; r++) { DRVar *cell_data; PetscInt e_index,q_index; e_index = eid_list[r]; q_index = qid_list[r]; ierr = SpecFECtxGetDRCellData(c,e_index,&cell_data);CHKERRQ(ierr); fprintf(fp," %+1.8e %+1.8e %+1.8e %+1.2e",cell_data[q_index].slip,cell_data[q_index].slip_rate,cell_data[q_index].mu,(double)cell_data[q_index].sliding); } fprintf(fp,"\n"); fclose(fp); PetscFunctionReturn(0); } PetscErrorCode SE2WaveViewer_JSON(SpecFECtx ctx,PetscInt step,PetscReal time, const char data_description[],PetscInt len,const char *fieldname[],const Vec field[], const char pbin[],const char jfilename[]) { PetscErrorCode ierr; char str[PETSC_MAX_PATH_LEN]; FILE *fp = NULL; PetscMPIInt commrank; PetscInt k; ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&commrank);CHKERRQ(ierr); if (commrank != 0) PetscFunctionReturn(0); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"%s",jfilename);CHKERRQ(ierr); fp = fopen(str,"w"); if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Failed to open file \"%s\"",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"{\"se2wave\":{");CHKERRQ(ierr); fprintf(fp,"%s\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"time\": %1.12e",time);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"step\": %D",step);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"spatial_dimension\": %D",ctx->dim);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"mx\": %D",ctx->mx_g);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"my\": %D",ctx->my_g);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"nx\": %D",ctx->nx_g);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"ny\": %D",ctx->ny_g);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"basis_degree\": %D",ctx->basisorder);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"fields\": [ ");CHKERRQ(ierr); fprintf(fp,"%s",str); for (k=0; k<len; k++) { ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"\"null\"");CHKERRQ(ierr); if (field[k]) { ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"\"%s\"",fieldname[k]);CHKERRQ(ierr); } if (k != (len-1)) { fprintf(fp,"%s, ",str); } else { fprintf(fp,"%s",str); } } ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," ]");CHKERRQ(ierr); fprintf(fp,"%s,\n",str); //ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"datafile\": \"%s\"",pbin);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"data\":{");CHKERRQ(ierr); fprintf(fp,"%s\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"description\": \"%s\"",data_description);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"fields\": [ ");CHKERRQ(ierr); fprintf(fp,"%s",str); for (k=0; k<len; k++) { ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"\"null\"");CHKERRQ(ierr); if (field[k]) { ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"\"%s\"",fieldname[k]);CHKERRQ(ierr); } if (k != (len-1)) { fprintf(fp,"%s, ",str); } else { fprintf(fp,"%s",str); } } ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," ]");CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"writer\": \"petsc_binary\"");CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"type\": \"Vec\"");CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"filename\": \"%s\"",pbin);CHKERRQ(ierr); fprintf(fp,"%s,\n",str); /* petsc always writes binary in big endian ordering (even on a small endian machine) */ ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"endian\": \"big\"");CHKERRQ(ierr); fprintf(fp,"%s\n",str); /* #ifdef WORDSIZE_BIGENDIAN ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"endian\": \"big\"");CHKERRQ(ierr); fprintf(fp,"%s\n",str); #else ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"endian\": \"little\"");CHKERRQ(ierr); fprintf(fp,"%s\n",str); #endif */ ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," }");CHKERRQ(ierr); fprintf(fp,"%s,\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1," \"version\": [1,0,0]");CHKERRQ(ierr); fprintf(fp,"%s\n",str); ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,"}}");CHKERRQ(ierr); fprintf(fp,"%s\n",str); fclose(fp); PetscFunctionReturn(0); } PetscErrorCode SE2WaveCoordinateViewerViewer(SpecFECtx ctx,PetscInt step,PetscReal time,const char prefix[]) { PetscErrorCode ierr; PetscViewer vu; Vec coor = NULL; char fname[PETSC_MAX_PATH_LEN]; ierr = DMGetCoordinates(ctx->dm,&coor);CHKERRQ(ierr); if (!coor) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Must have a valid coordinate vector"); ierr = PetscSNPrintf(fname,PETSC_MAX_PATH_LEN-1,"%s_coor.pbin",prefix);CHKERRQ(ierr); { char jname[PETSC_MAX_PATH_LEN]; Vec input[] = {NULL}; const char *fieldname[] = { "coor" }; input[0] = coor; ierr = PetscSNPrintf(jname,PETSC_MAX_PATH_LEN-1,"%s_coor.json",prefix);CHKERRQ(ierr); ierr = SE2WaveViewer_JSON(ctx,step,time,"coordinates",1,fieldname,input,fname,jname);CHKERRQ(ierr); } ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,fname,FILE_MODE_WRITE,&vu);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->mx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->my_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->nx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->ny_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = VecView(coor,vu);CHKERRQ(ierr); ierr = PetscViewerDestroy(&vu);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode SE2WaveWaveFieldViewer(SpecFECtx ctx,PetscInt step,PetscReal time,Vec u,Vec v,const char prefix[]) { PetscErrorCode ierr; PetscViewer vu; char fname[PETSC_MAX_PATH_LEN]; if (!u && !v) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"At least one of the displacement or velocity vectors must be non-NULL"); ierr = PetscSNPrintf(fname,PETSC_MAX_PATH_LEN-1,"%s_wavefield.pbin",prefix);CHKERRQ(ierr); { char jname[PETSC_MAX_PATH_LEN]; Vec input[] = {NULL,NULL}; const char *fieldname[] = { "u", "v" }; input[0] = u; input[1] = v; ierr = PetscSNPrintf(jname,PETSC_MAX_PATH_LEN-1,"%s_wavefield.json",prefix);CHKERRQ(ierr); ierr = SE2WaveViewer_JSON(ctx,step,time,"wavefield",2,fieldname,input,fname,jname);CHKERRQ(ierr); } ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,fname,FILE_MODE_WRITE,&vu);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->mx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->my_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->nx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->ny_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&step,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(vu,(void*)&time,1,PETSC_REAL,PETSC_FALSE);CHKERRQ(ierr); if (u) { ierr = VecView(u,vu);CHKERRQ(ierr); } if (v) { ierr = VecView(v,vu);CHKERRQ(ierr); } ierr = PetscViewerDestroy(&vu);CHKERRQ(ierr); PetscFunctionReturn(0); } PetscErrorCode se2dr_demo(PetscInt mx,PetscInt my) { PetscErrorCode ierr; SpecFECtx ctx; PetscInt p,k,nt,of; PetscViewer viewer; Vec u,v,a,f,g,Md; PetscReal time,dt,time_max; PetscInt nrecv; PetscReal *xr_list; PetscBool dump_ic_src_vts = PETSC_FALSE; PetscBool ignore_receiver_output = PETSC_FALSE; PetscReal nrm,max,min,dx,dy; char vts_fname[PETSC_MAX_PATH_LEN]; ierr = PetscOptionsGetBool(NULL,NULL,"-dump_ic_src",&dump_ic_src_vts,NULL);CHKERRQ(ierr); ierr = PetscOptionsGetBool(NULL,NULL,"-ignore_receiver_output",&ignore_receiver_output,NULL);CHKERRQ(ierr); /* Create the structured mesh for the spectral element method. The default mesh is defined over the domain [0,1]^2. */ ierr = SpecFECtxCreate(&ctx);CHKERRQ(ierr); p = 2; ierr = PetscOptionsGetInt(NULL,NULL,"-bdegree",&p,NULL);CHKERRQ(ierr); ierr = SpecFECtxCreateMesh(ctx,2,mx,my,PETSC_DECIDE,p,2);CHKERRQ(ierr); /* Define your domain by shifting and scaling the default [0,1]^2 domain */ { PetscReal alpha = 20.0e3; PetscReal scale[] = { 3.0*alpha, 3.0*alpha }; PetscReal shift[] = { -1.5*alpha,-1.5*alpha }; ierr = SpecFECtxScaleMeshCoords(ctx,scale,shift);CHKERRQ(ierr); } /* Specify fault dimensions */ { PetscReal gmin[3],gmax[3]; ierr = DMGetBoundingBox(ctx->dm,gmin,gmax);CHKERRQ(ierr); dx = (gmax[0] - gmin[0])/((PetscReal)ctx->mx_g); dy = (gmax[1] - gmin[1])/((PetscReal)ctx->my_g); } PetscPrintf(PETSC_COMM_WORLD,"[se2dr] cell sizes: dx = %1.4e, dy = %1.4e\n",dx,dy); ctx->delta = 25.0; ierr = PetscOptionsGetReal(NULL,NULL,"-delta",&ctx->delta,NULL);CHKERRQ(ierr); { PetscBool found; PetscReal delta_factor = 0.0; found = PETSC_FALSE; ierr = PetscOptionsGetReal(NULL,NULL,"-delta_cell_factor",&delta_factor,&found);CHKERRQ(ierr); if (found) { ctx->delta = dy * delta_factor; } } PetscPrintf(PETSC_COMM_WORLD,"[se2dr] using fault delta = %1.4e\n",ctx->delta); PetscPrintf(PETSC_COMM_WORLD,"[se2dr] elements across fault = %1.4e\n",2.0 * ctx->delta/dy); //ierr = FaultSDFInit_v1(ctx);CHKERRQ(ierr); ierr = FaultSDFInit_v2(ctx);CHKERRQ(ierr); /* Specify the material properties for the domain. This function sets constant material properties in every cell. More general methods can be easily added. */ ierr = SpecFECtxSetConstantMaterialProperties_Velocity(ctx,6000.0 ,3464.0, 2670.0);CHKERRQ(ierr); // vp,vs,rho /* Linear slip weakening parameters */ ctx->mu_s = 0.677; ctx->mu_d = 0.525; ctx->D_c = 0.40; ierr = DMCreateGlobalVector(ctx->dm,&u);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)u,"disp");CHKERRQ(ierr); ierr = DMCreateGlobalVector(ctx->dm,&v);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)v,"velo");CHKERRQ(ierr); ierr = DMCreateGlobalVector(ctx->dm,&a);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)a,"accl");CHKERRQ(ierr); ierr = DMCreateGlobalVector(ctx->dm,&f);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)f,"f");CHKERRQ(ierr); ierr = DMCreateGlobalVector(ctx->dm,&g);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)g,"g");CHKERRQ(ierr); ierr = DMCreateGlobalVector(ctx->dm,&Md);CHKERRQ(ierr); ierr = VecZeroEntries(u);CHKERRQ(ierr); /* Write out the mesh and intial values for the displacement, velocity and acceleration (u,v,a) */ if (dump_ic_src_vts) { ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,"uva.vts",FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(u,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } ierr = AssembleBilinearForm_Mass2d(ctx,Md);CHKERRQ(ierr); /* Define the location of the receivers */ nrecv = 8; ierr = PetscMalloc1(nrecv*2,&xr_list);CHKERRQ(ierr); xr_list[0] = 4.0e3; xr_list[1] = ctx->delta; xr_list[2] = 4.0e3; xr_list[3] = -ctx->delta; xr_list[4] = 6.0e3; xr_list[5] = ctx->delta; xr_list[6] = 6.0e3; xr_list[7] = -ctx->delta; xr_list[8] = 8.0e3; xr_list[9] = ctx->delta; xr_list[10] = 8.0e3; xr_list[11] = -ctx->delta; xr_list[12] = 10.0e3; xr_list[13] = ctx->delta; xr_list[14] = 10.0e3; xr_list[15] = -ctx->delta; /* Initialize time loop */ k = 0; time = 0.0; time_max = 0.4; ierr = PetscOptionsGetReal(NULL,NULL,"-tmax",&time_max,NULL);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"[se2dr] Requested time period: %1.4e\n",time_max); ierr = ElastoDynamicsComputeTimeStep_2d(ctx,&dt);CHKERRQ(ierr); dt = dt * 0.5; ierr = PetscOptionsGetReal(NULL,NULL,"-dt",&dt,NULL);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"[se2dr] Using time step size: %1.4e\n",dt); nt = 1000000; nt = (PetscInt)(time_max / dt ) + 4; ierr = PetscOptionsGetInt(NULL,NULL,"-nt",&nt,NULL);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD,"[se2dr] Estimated number of time steps: %D\n",nt); of = 5000; ierr = PetscOptionsGetInt(NULL,NULL,"-of",&of,NULL);CHKERRQ(ierr); ierr = SE2WaveCoordinateViewerViewer(ctx,0,0.0,"default_mesh");CHKERRQ(ierr); { char prefix[PETSC_MAX_PATH_LEN]; ierr = PetscSNPrintf(prefix,PETSC_MAX_PATH_LEN-1,"step-%.4D",0);CHKERRQ(ierr); ierr = SE2WaveWaveFieldViewer(ctx,k,time,u,v,prefix);CHKERRQ(ierr); } if (k%of == 0) { ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,"step-%.4D.vts",0);CHKERRQ(ierr); ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(u,viewer);CHKERRQ(ierr); ierr = VecView(v,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } /* Perform time stepping */ for (k=1; k<=nt; k++) { time = time + dt; ierr = VecAXPY(u,dt,v);CHKERRQ(ierr); /* u_{n+1} = u_{n} + dt.v_{n} */ ierr = VecAXPY(u,0.5*dt*dt,a);CHKERRQ(ierr); /* u_{n+1} = u_{n+1} + 0.5.dt^2.a_{n} */ ierr = VecAXPY(v,0.5*dt,a);CHKERRQ(ierr); /* v' = v_{n} + 0.5.dt.a_{n} */ /* Compute f = -F^{int}( u_{n+1} ) */ //printf("[time:%f] ",time); ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv(ctx,u,v,dt,time,0.5*dt,f);CHKERRQ(ierr); //ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv_cellwise(ctx,u,v,dt,time,1.1*dt,f);CHKERRQ(ierr); //ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv_cellwise_v2(ctx,u,v,dt,time,1.1*dt,f);CHKERRQ(ierr); /* Update force; F^{ext}_{n+1} = f + S(t_{n+1}) g(x) */ ierr = VecAXPY(f,1.0,g);CHKERRQ(ierr); /* "Solve"; a_{n+1} = M^{-1} f */ ierr = VecPointwiseDivide(a,f,Md);CHKERRQ(ierr); /* Update velocity */ ierr = VecAXPY(v,0.5*dt,a);CHKERRQ(ierr); /* v_{n+1} = v' + 0.5.dt.a_{n+1} */ /* Update slip-rate & slip */ ierr = Update_StressGlut2d(ctx,u,v,dt);CHKERRQ(ierr); if (k%10 == 0) { PetscPrintf(PETSC_COMM_WORLD,"[step %9D] time = %1.4e : dt = %1.4e \n",k,time,dt); VecNorm(u,NORM_2,&nrm); VecMin(u,0,&min); VecMax(u,0,&max); PetscPrintf(PETSC_COMM_WORLD," [displacement] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \n",max,min,nrm); VecNorm(v,NORM_2,&nrm); VecMin(v,0,&min); VecMax(v,0,&max); PetscPrintf(PETSC_COMM_WORLD," [velocity] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \n",max,min,nrm); } /* Write out the u,v,a values at each receiver */ if (!ignore_receiver_output) { ierr = RecordUVA_MultipleStations_NearestGLL(ctx,time,nrecv,xr_list,u,v,a);CHKERRQ(ierr); ierr = RecordDRVar_MultipleStations_NearestGLL_SEQ(ctx,time,nrecv,xr_list);CHKERRQ(ierr); } if (k%of == 0) { ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,"step-%.4D.vts",k);CHKERRQ(ierr); ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(u,viewer);CHKERRQ(ierr); ierr = VecView(v,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } if (k%of == 0) { char prefix[PETSC_MAX_PATH_LEN]; ierr = PetscSNPrintf(prefix,PETSC_MAX_PATH_LEN-1,"step-%.4D",k);CHKERRQ(ierr); ierr = SE2WaveWaveFieldViewer(ctx,k,time,u,v,prefix);CHKERRQ(ierr); } if (time >= time_max) { break; } } PetscPrintf(PETSC_COMM_WORLD,"[step %9D] time = %1.4e : dt = %1.4e \n",k,time,dt); VecNorm(u,NORM_2,&nrm); VecMin(u,0,&min); VecMax(u,0,&max); PetscPrintf(PETSC_COMM_WORLD," [displacement] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \n",max,min,nrm); VecNorm(v,NORM_2,&nrm); VecMin(v,0,&min); VecMax(v,0,&max); PetscPrintf(PETSC_COMM_WORLD," [velocity] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \n",max,min,nrm); /* plot last snapshot */ ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,"step-%.4D.vts",k);CHKERRQ(ierr); ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = VecView(u,viewer);CHKERRQ(ierr); ierr = VecView(v,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = PetscFree(xr_list);CHKERRQ(ierr); ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&v);CHKERRQ(ierr); ierr = VecDestroy(&a);CHKERRQ(ierr); ierr = VecDestroy(&f);CHKERRQ(ierr); ierr = VecDestroy(&Md);CHKERRQ(ierr); ierr = VecDestroy(&g);CHKERRQ(ierr); PetscFunctionReturn(0); } int main(int argc,char **args) { PetscErrorCode ierr; PetscInt mx,my; PetscMPIInt size; ierr = PetscInitialize(&argc,&args,(char*)0,NULL);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); mx = my = 8; ierr = PetscOptionsGetInt(NULL,NULL,"-mx",&mx,NULL);CHKERRQ(ierr); my = mx; ierr = PetscOptionsGetInt(NULL,NULL,"-my",&my,NULL);CHKERRQ(ierr); ierr = se2dr_demo(mx,my);CHKERRQ(ierr); ierr = PetscFinalize(); return(ierr); }
{ "alphanum_fraction": 0.5910516317, "avg_line_length": 32.9469582705, "ext": "c", "hexsha": "285c51aa09126a7f1ee053b372dcddc8b875f407", "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": "2608df5c2e635ad16f422877ff440af69f98f960", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Nicolucas/C-Scripts", "max_forks_repo_path": "se2dr/Versions/se2drTpv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2608df5c2e635ad16f422877ff440af69f98f960", "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": "Nicolucas/C-Scripts", "max_issues_repo_path": "se2dr/Versions/se2drTpv.c", "max_line_length": 217, "max_stars_count": null, "max_stars_repo_head_hexsha": "2608df5c2e635ad16f422877ff440af69f98f960", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Nicolucas/C-Scripts", "max_stars_repo_path": "se2dr/Versions/se2drTpv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 45728, "size": 131063 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> double fn1 (double x, void * params) { return cos(x) + 1.0; } int main (void) { int status; int iter = 0, max_iter = 100; const gsl_min_fminimizer_type *T; gsl_min_fminimizer *s; double m = 2.0, m_expected = M_PI; double a = 0.0, b = 6.0; gsl_function F; F.function = &fn1; F.params = 0; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc (T); gsl_min_fminimizer_set (s, &F, m, a, b); printf ("using %s method\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); do { iter++; status = gsl_min_fminimizer_iterate (s); m = gsl_min_fminimizer_x_minimum (s); a = gsl_min_fminimizer_x_lower (s); b = gsl_min_fminimizer_x_upper (s); status = gsl_min_test_interval (a, b, 0.001, 0.0); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5d [%.7f, %.7f] " "%.7f %+.7f %.7f\n", iter, a, b, m, m - m_expected, b - a); } while (status == GSL_CONTINUE && iter < max_iter); gsl_min_fminimizer_free (s); return status; }
{ "alphanum_fraction": 0.5524625268, "avg_line_length": 21.2272727273, "ext": "c", "hexsha": "45d79a94fe3fb2085be5d0295471cb18a75bc1dc", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/min.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/min.c", "max_line_length": 52, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/min.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 480, "size": 1401 }
#include <math.h> #include <stdlib.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_poly.h> #include "userFunc.h" #define G 6.67384e-8 /* 2010 CODATA value in CGS units */ #define ALPHAMIN 1.0e-3 /* Minimum alpha allowed for numerical reasons */ /**************************************************************************/ /* This defines userFunc routines for the Krumholz & Burkert (2010) GI */ /* disk problem. */ /**************************************************************************/ void userEOS(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, void *params, double *gamma, double *delta) { fprintf(stderr, "Warning: userEOS function called but not implemented!\n"); return; } void userAlpha(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, const double *gamma, const double *delta, void *params, double *alpha) { gsl_poly_complex_workspace *wksp; double coef[6], sol[10]; double omega, kappa, T1, sigma, kcrit, J, Q, d, tfast, tgrowth; int i, j; const int m=2; gsl_complex nu2, nu; double alphacoef = ((double *) params)[4]; /* Allocate workspace */ wksp = gsl_poly_complex_workspace_alloc(6); /* Store the coefficiencts of the dispersion relation polynomial that don't change */ coef[2] = -8.0; coef[3] = coef[4] = 0.0; /* Loop over cells */ for (i=0; i<grd->nr; i++) { /* Handle negative column densities, which may arise if the time step overshoots. We just need to make sure the code doesn't barf here, as the negative column densities will be fixed by the iterative solver. */ if (col[i] <= 0.0) { alpha[i] = ALPHAMIN; continue; } /* The various quantities needed for the stability analysis */ sigma = sqrt(pres[i]/col[i]); omega = grd->vphi_g[i+1]/grd->r_g[i+1]; kappa = sqrt(2.0*(1.0+grd->beta_g[i+1]))*omega; T1 = -(2.0*m*omega/(kappa*grd->r_g[i+1])) * (2.0*m*omega/(kappa*grd->r_g[i+1])) * (grd->beta_g[i+1]-1); kcrit = kappa*kappa / (2.0*M_PI*G*col[i]); Q = kappa*sigma / (M_PI*G*col[i]); if (Q < 0) printf("Q < 0! kappa = %f, sigma = %f, col = %f\n", kappa, sigma, col[i]); J = sqrt(T1)/kcrit; /* Coefficients of the disperison relation polynomial */ coef[0] = -Q*Q*Q*Q; coef[1] = 6.0*Q*Q; coef[5] = 16.0*J*J; /* Find roots, giving minima and maxima of D */ gsl_poly_complex_solve(coef, 6, wksp, sol); /* For each root, compute the growth time of the instability */ tfast = 1.0e30; for (j=0; j<5; j++) { /* Skip roots with negative real part, or imaginary part that is greater than roundoff */ if ((sol[2*j] < 0) || (fabs(sol[2*j+1]) > 1.0e-6)) continue; /* Compute D */ d = (Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]) * (Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j] - 4.0*J*J*sol[2*j]*sol[2*j]); /* Ignore stable roots */ if (d > 0) continue; /* Get frequency and growth time */ GSL_SET_COMPLEX(&nu2, 1.0 + 0.5*(Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]), 0.5 * sqrt(-d)); nu = gsl_complex_sqrt(nu2); tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega); /* Store minimum growth time */ if (tgrowth < tfast) tfast = tgrowth; } /* Now check for gravitational instability */ if (Q < 1) { GSL_SET_COMPLEX(&nu, 0.0, sqrt(1.0/(Q*Q)-1.0)); tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega); if (tgrowth < tfast) tfast = tgrowth; } /* Compute alpha based on the fastest growing mode timescale */ alpha[i] = alphacoef * exp(-tfast+1.0); if (alpha[i] > 1.0) alpha[i] = 1.0; if (alpha[i] < ALPHAMIN) alpha[i] = ALPHAMIN; } /* Free workspace */ gsl_poly_complex_workspace_free(wksp); } void userMassSrc(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, const double *gamma, const double *delta, void *params, double *massSrc) { /* Estimate Mdot by dSigma/dt = - eta_ML Sigma_SFR = - eta_ML eps_ff Sigma_g/t_ff, */ int i; double shapefac = ((double *) params)[2]; double zetad = ((double *) params)[3]; double etaML = ((double *) params)[5]; double epsffmax = ((double *) params)[6]; double rhostar, a, b, c, h; double rhog, tff, alphavir, epsff; for (i=0; i<grd->nr; i++) { /* Stellar density */ rhostar = shapefac * SQR(grd->vphi_g[i+1]) * (1.0+2.0*grd->beta_g[i+1]) / (4.0*M_PI*G*SQR(grd->r_g[i+1])); /* Get scale height from OML model */ if (rhostar > 0.0) { a = 2.0*M_PI*zetad*G*rhostar*col[i]; b = M_PI/2.0*G*SQR(col[i]); c = -pres[i]; h = (-b + sqrt(b*b-4.0*a*c))/(2.0*a); } else { h = pres[i] / (M_PI/2.0*G*SQR(col[i])); } /* Gas density and free-fall time */ rhog = col[i]/(2*h); tff = sqrt(3*M_PI/(32*G*rhog)); /* Virial ratio */ alphavir = pres[i]/(M_PI/2.0*G*col[i]*col[i]*h); /* epsff */ if (alphavir <= 1.0) epsff = epsffmax; else epsff = epsffmax*exp(-alphavir); /* Mdot */ massSrc[i] = -(1.0+etaML) * epsff * col[i] / tff; } } void userIntEnSrc(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, const double *gamma, const double *delta, void *params, double *intEnSrc) { /* Cooling rate = eta Sigma sigma^2 Omega = eta P vphi/r */ int i; double eta = ((double *) params)[0]; double sigmath = ((double *) params)[1]; double shapefac = ((double *) params)[2]; double zetad = ((double *) params)[3]; double sigma2, sigmaNT, rhostar, a, b, c, h; for (i=0; i<grd->nr; i++) { /* Gas velocity dispersion */ sigma2 = pres[i]/col[i]; if (sigma2 > SQR(sigmath)) { sigmaNT = sqrt(sigma2 - SQR(sigmath)); /* Stellar density */ rhostar = shapefac * SQR(grd->vphi_g[i+1]) * (1.0+2.0*grd->beta_g[i+1]) / (4.0*M_PI*G*SQR(grd->r_g[i+1])); /* Get scale height from OML model */ if (rhostar > 0.0) { a = 2.0*M_PI*zetad*G*rhostar*col[i]; b = M_PI/2.0*G*SQR(col[i]); c = -pres[i]; h = (-b + sqrt(b*b-4.0*a*c))/(2.0*a); } else { h = pres[i] / (M_PI/2.0*G*SQR(col[i])); } /* Cooling rate = eta Sigma sigmaNT^2 / (h/sigmaNT) */ intEnSrc[i] = -eta * col[i] * SQR(sigmaNT) / (h/sigmaNT); } else { intEnSrc[i] = 0.0; } } } void userIBC(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, const double *gamma, const double *delta, const pres_bc_type ibc_pres, const enth_bc_type ibc_enth, void *params, double *ibc_pres_val, double *ibc_enth_val) { fprintf(stderr, "Warning: userIBC function called but not implemented!\n"); return; } void userOBC(const double t, const double dt, const grid *grd, const double *col, const double *pres, const double *eInt, const double *gamma, const double *delta, const pres_bc_type obc_pres, const enth_bc_type obc_enth, void *params, double *obc_pres_val, double *obc_enth_val) { fprintf(stderr, "Warning: userOBC function called but not implemented!\n"); return; } void userPreTimestep(const double t, const double dt, const grid *grd, double *col, double *pres, double *eInt, double *mBnd, double *eBnd, double *mSrc, double *eSrc, void *params, const unsigned long nUserOut, double *userOut) { fprintf(stderr, "Warning: userPreTimestep function called but not implemented!\n"); return; } void userPostTimestep(const double t, const double dt, const grid *grd, double *col, double *pres, double *eInt, double *mBnd, double *eBnd, double *mSrc, double *eSrc, void *params, const unsigned long nUserOut, double *userOut) { fprintf(stderr, "Warning: userPostTimestep function called but not implemented!\n"); return; } void userCheckRead( FILE *fp, grid *grd, const unsigned long nOut, double *tOut, double *colOut, double *presOut, double *eIntOut, double *mBndOut, double *eBndOut, double *mSrcOut, double *eSrcOut, const unsigned long nUserOut, double *userOut, void *params ) { fprintf(stderr, "Warning: userCheckRead function called but not implemented!\n"); return; } void userCheckWrite( FILE *fp, const grid *grd, const unsigned long nOut, const double *tOut, const double *colOut, const double *presOut, const double *eIntOut, const double *mBndOut, const double *eBndOut, const double *mSrcOut, const double *eSrcOut, const unsigned long nUserOut, const double *userOut, const void *params ) { fprintf(stderr, "Warning: userCheckWrite function called but not implemented!\n"); return; }
{ "alphanum_fraction": 0.5963648454, "avg_line_length": 31.1137931034, "ext": "c", "hexsha": "f36eb2b2f7f4de3f5acb7098679634597c5d63c1", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2943, "size": 9023 }
// Copyright Jean Pierre Cimalando 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include "keystate.h" #include <gsl/gsl> #include <string> #include <cstdint> struct Midi_Output { std::string id; std::string name; }; enum Midi_Message_Flag { Midi_Message_Is_First = 1, }; /// class Midi_Instrument { public: Midi_Instrument(); virtual ~Midi_Instrument() {} void send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags); void initialize(); void all_sound_off(); const Keyboard_State &keyboard_state() const noexcept { return kbs_; } virtual void flush_events() {} virtual void open_midi_output(gsl::cstring_span id) = 0; virtual void close_midi_output() = 0; virtual bool is_synth() const { return false; } protected: virtual void handle_send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags) = 0; private: Keyboard_State kbs_; };
{ "alphanum_fraction": 0.6956521739, "avg_line_length": 24.0222222222, "ext": "h", "hexsha": "1bac9210de3c8de8ac24182adbe01a3aca48c5c2", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_path": "sources/player/instrument.h", "max_issues_count": 19, "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_path": "sources/player/instrument.h", "max_line_length": 102, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_path": "sources/player/instrument.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "num_tokens": 267, "size": 1081 }
#include <stdio.h> #include <gsl/gsl_poly.h> int main() { double a = 1.0, b = -3.0, c = 2.0; double x0 = 0.0, x1 = 0.0; gsl_poly_solve_quadratic(a, b, c, &x0, &x1); printf("%4.1fx^2 + %4.1fx + %4.1f = 0 -> x = %4.1f, %4.1f\n", a, b, c, x0, x1); return 0; }
{ "alphanum_fraction": 0.5109489051, "avg_line_length": 22.8333333333, "ext": "c", "hexsha": "5d4d2554e4bed843b1023fa19238675f8031db74", "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": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_forks_repo_licenses": [ "FSFAP" ], "max_forks_repo_name": "julnamoo/practice-linux", "max_forks_repo_path": "src_book0/ex10/list1032/list1032A.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "FSFAP" ], "max_issues_repo_name": "julnamoo/practice-linux", "max_issues_repo_path": "src_book0/ex10/list1032/list1032A.c", "max_line_length": 63, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_stars_repo_licenses": [ "FSFAP" ], "max_stars_repo_name": "julnamoo/practice-linux", "max_stars_repo_path": "src_book0/ex10/list1032/list1032A.c", "max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z", "num_tokens": 138, "size": 274 }
#ifndef OPENMC_TALLIES_FILTER_TIME_H #define OPENMC_TALLIES_FILTER_TIME_H #include <gsl/gsl-lite.hpp> #include "openmc/tallies/filter.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Bins the incident particle time. //============================================================================== class TimeFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~TimeFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override { return "time"; } void from_xml(pugi::xml_node node) override; void get_all_bins(const Particle& p, TallyEstimator estimator, FilterMatch& match) const override; void to_statepoint(hid_t filter_group) const override; std::string text_label(int bin) const override; //---------------------------------------------------------------------------- // Accessors const vector<double>& bins() const { return bins_; } void set_bins(gsl::span<const double> bins); protected: //---------------------------------------------------------------------------- // Data members vector<double> bins_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_ENERGY_H
{ "alphanum_fraction": 0.4780100937, "avg_line_length": 27.1960784314, "ext": "h", "hexsha": "c66481c5780945b7d28c1f33343f0d8082fd2b8a", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2018-07-26T14:34:13.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T18:18:46.000Z", "max_forks_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RyotaroOKabe/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_time.h", "max_issues_count": 673, "max_issues_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_issues_repo_issues_event_max_datetime": "2018-08-02T15:28:47.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-02T20:37:12.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "RyotaroOKabe/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_time.h", "max_line_length": 80, "max_stars_count": 123, "max_stars_repo_head_hexsha": "9926294324cb80dd7ff0e4f1a9b361addfcfa8fc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RyotaroOKabe/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_time.h", "max_stars_repo_stars_event_max_datetime": "2018-07-21T03:05:48.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-09T18:21:00.000Z", "num_tokens": 248, "size": 1387 }
/* Simbicon 1.5 Controller Editor Framework, Copyright 2009 Stelian Coros, Philippe Beaudoin and Michiel van de Panne. All rights reserved. Web: www.cs.ubc.ca/~van/simbicon_cef This file is part of the Simbicon 1.5 Controller Editor Framework. Simbicon 1.5 Controller Editor Framework 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. Simbicon 1.5 Controller Editor Framework 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 Simbicon 1.5 Controller Editor Framework. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <stdlib.h> #include <stdio.h> #include <string.h> #include <MathLib/MathLib.h> #include <MathLib/ThreeTuple.h> #include <gsl/matrix/gsl_matrix.h> #define MATRIX_AT(m, i, j) (*((m->data + ((i) * m->tda + (j))))) class Vector3d; /*====================================================================================================================================================================* | This class will be used to represent matrices of arbitrary sizes (m rows by n columns) that have elements of type double. The underlying data strucutre used by | | this class is gsl's (Gnu Scientific Library) matrix class. This class also makes use of the ATLAS implementation of BLAS for some operations such as matrix-matrix | | multiplication. This class is meant to improve performance, not necessarily ease of use. | *====================================================================================================================================================================*/ class Matrix { friend class Vector; protected: //this data structure holds all the matrix data gsl_matrix *matrix; public: /** constructor - creates an m rows by n columns matrix that is not initialized to any particular values */ Matrix(int m, int n); /** default constructor */ Matrix(); /** copy constructor - performs a deep copy of the matrix passed in as a parameter. */ Matrix(const Matrix& other); /** destructor. */ virtual ~Matrix(); /** loads the matrix with all zero values. */ void loadZero(); /** loads the matrix with 1's on the diagonal, 0's everywhere else - note: the matrix doesn't have to be square. */ void loadIdentity(); /** this method sets the current matrix to a 3x3 matrix that is equal to the outer product of the vectors a and b */ void setToOuterproduct(const Vector3d& a, const Vector3d& b); /** this method resizes the current matrix to have m rows and n cols. If not enough space is allocated for it, then a new matrix of correct dimensions is allocated. There is no guarantee with regards to the data that is contained in the matrix after a resize operation. */ void resizeTo(int m, int n); /** copy operator - performs a deep copy of the matrix passed in as a parameter. */ Matrix& operator=(const Matrix &other); /** this method performs a shallow copy of the matrix that is passed in as a parameter. */ void shallowCopy(const Matrix& other, int startRow = 0, int startCol = 0, int endRow = -1, int endCol = -1); /** this method performs a deep copy of the matrix that is passed in as a paramerer. */ void deepCopy(const Matrix& other); /** Returns the number of columns */ int getColumnCount() const; /** Returns the number of rows */ int getRowCount()const; /** Multiplies each element in the current matrix by a constant */ void multiplyBy(const double val); /** This method sets the current matrix to be equal to one of the products: a * b, a'*b, a*b' or a'*b'. The values of transA and transB indicate which of the matrices are tranposed and which ones are not. */ void setToProductOf(const Matrix& a, const Matrix& b, bool transA = false, bool transB = false); /** This method computes the inverse of the matrix a and writes it over the current matrix. The implementation for the inverse of a matrix was obtained from Graphite. The parameter t is used as a threshold value for determinants, etc so that we still get a result for the inverse of our matrix even if it is very poorly conditioned. */ void setToInverseOf(const Matrix &a, double t = 0); /** This method prints the contents of the matrix - testing purpose only. */ void printMatrix() const; /** This method prints the contents of the matrix - testing purpose only. */ std::string toString() const; /** This method sets the current matrix to be a sub-matrix (starting at (i,j) and ending at (i+rows, j+cols) of the one that is passed in as a parameter - shallow copy only. */ void setToSubmatrix(const Matrix &a, int i, int j, int rows, int cols); /** This method returns a copy of the value of the matrix at (i,j) */ double get(int i, int j) const; /** This method sets the value of the matrix at (i,j) to newVal. */ void set(int i, int j, double newVal); /** This method is used to set the values in the matrix to the ones that are passed in the array of doubles. It is assumed that the array contains the right number of elements and that there is no space between consecutive rows (tda == nrCols). */ void setValues(double* vals); /** this method returns a pointer to its internal matrix data structure */ gsl_matrix* getMatrixPointer() const; /** Implement this operator to have a quick way of multiplying 3x3 matrices by vectors - used for dynamics for instance */ Vector3d operator * (const Vector3d &other); /** Implement a potentially faster function for 3x3 matrix - vector3d multiplication. Result and v need to be different!! */ void postMultiplyVector(const Vector3d& v, Vector3d& result); /** Still need to do (if need be): get row/col vector. Initialize a matrix from a vector so that we can create a 1xn matrix easily. make sure dgemv works properly, implement vector class, etc, swap, add, scale matrices, etc */ /** this method adds the matrix that is passed in as a parameter to the current matrix. In addition, it scales, both matrices by the two numbers that are passed in as parameters: *this = a * *this + b * other. */ void add(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0); /** this method subtracts the matrix that is passed in as a parameter from the current matrix. In addition, it scales, both matrices by the two numbers that are passed in as parameters: *this = a * *this - b * other. */ void sub(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0); }; void testMatrixClass();
{ "alphanum_fraction": 0.6715617057, "avg_line_length": 33.0934579439, "ext": "h", "hexsha": "be531829907510db638400e83b68b4f02179a559", "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": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_forks_repo_path": "SPlisHSPlasH/MathLib/Matrix.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "max_issues_repo_issues_event_max_datetime": "2019-11-29T12:54:26.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-28T03:31:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_issues_repo_path": "SPlisHSPlasH/MathLib/Matrix.h", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_stars_repo_path": "SPlisHSPlasH/MathLib/Matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1662, "size": 7082 }
/*System includes*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <sys/stat.h> #include <float.h> /*GSL includes*/ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_statistics_double.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include <pthread.h> #include <gsl/gsl_sf_exp.h> /*User includes*/ #include "c_vbgmm_fit.h" void readInputData(const char *szFile, t_Data *ptData); void c_vbgmm_fit (double* adX, int nN, int nD, int nK, int* anAssign, int debug, int bAssign); void readAssigns(const char *szFile, int *anAssign, int nN); int main() { t_Data tData; int *anAssign = NULL; int i = 0, j = 0, nN = -1, nD = -1, nK = 0; double* adX = NULL; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); readInputData("PCA_transformed_data_gt2000.csv", &tData); nN = tData.nN; nD = tData.nD; adX = (double *) malloc(nN*nD*sizeof(double)); anAssign = (int *) malloc(nN*sizeof(int)); readAssigns("clustering_gt2000.csv", anAssign, nN); for(i = 0; i < nN; i++){ if(anAssign[i] > nK){ nK = anAssign[i]; } for(j = 0; j < nD; j++){ adX[i*nD + j] = tData.aadX[i][j]; } } nK = nK + 1; fprintf(stderr,"Run c_vbgmm_fit with %d clusters\n",nK); fflush(stderr); c_vbgmm_fit (adX, nN, nD, nK, anAssign, FALSE, TRUE); for(i = 0; i < nN; i++){ printf("%d,%d\n",i,anAssign[i]); } free(adX); free(anAssign); return 0; } void readInputData(const char *szFile, t_Data *ptData) { double **aadX = NULL; int i = 0, j = 0, nD = 0, nN = 0; char *szLine = (char *) malloc(sizeof(char)*MAX_LINE_LENGTH); FILE* ifp = NULL; if(!szLine) goto memoryError; ifp = fopen(szFile, "r"); if(ifp){ char* szTok = NULL; char* pcError = NULL; if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); /*count dimensions*/ while(strtok(NULL, DELIM) != NULL){ nD++; } /*count data points*/ while(fgets(szLine, MAX_LINE_LENGTH, ifp) != NULL){ nN++; } fclose(ifp); /*reopen input file*/ ifp = fopen(szFile, "r"); if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; /*allocate memory for dimension names*/ //ptData->aszDimNames = (char **) malloc(nD*sizeof(char*)); //if(!ptData->aszDimNames) //goto memoryError; szTok = strtok(szLine, DELIM); /*read in dim names*/ for(i = 0; i < nD; i++){ szTok = strtok(NULL, DELIM); // ptData->aszDimNames[i] = strdup(szTok); } /*allocate memory for data matrix*/ aadX = (double **) malloc(nN*sizeof(double*)); if(!aadX) goto memoryError; for(i = 0; i < nN; i++){ aadX[i] = (double *) malloc(nD*sizeof(double)); if(!aadX[i]) goto memoryError; } /*read in input data*/ //ptData->aszSampleNames = (char **) malloc(nN*sizeof(char*)); //if(!ptData->aszSampleNames) //goto memoryError; for(i = 0; i < nN; i++){ if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); // ptData->aszSampleNames[i] = strdup(szTok); for(j = 0; j < nD; j++){ szTok = strtok(NULL, DELIM); aadX[i][j] = strtod(szTok,&pcError); if(*pcError != '\0'){ goto formatError; } } } } else{ fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile); fflush(stderr); exit(EXIT_FAILURE); } free(szLine); ptData->nD = nD; ptData->nN = nN; ptData->aadX = aadX; return; memoryError: fprintf(stderr, "Failed allocating memory in readInputData\n"); fflush(stderr); exit(EXIT_FAILURE); formatError: fprintf(stderr, "Incorrectly formatted abundance data file\n"); fflush(stderr); exit(EXIT_FAILURE); } void readAssigns(const char *szFile, int *anAssign, int nN) { int i = 0; char *szLine = (char *) malloc(sizeof(char)*MAX_LINE_LENGTH); FILE* ifp = NULL; if(!szLine) goto memoryError; ifp = fopen(szFile, "r"); if(ifp){ char* szTok = NULL; char* pcError = NULL; if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; for(i = 0; i < nN; i++){ if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); szTok = strtok(NULL, DELIM); anAssign[i] = strtod(szTok,&pcError); if(*pcError != '\0'){ goto formatError; } } } else{ fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile); fflush(stderr); exit(EXIT_FAILURE); } free(szLine); return; memoryError: fprintf(stderr, "Failed allocating memory in readInputData\n"); fflush(stderr); exit(EXIT_FAILURE); formatError: fprintf(stderr, "Incorrectly formatted abundance data file\n"); fflush(stderr); exit(EXIT_FAILURE); }
{ "alphanum_fraction": 0.6021877849, "avg_line_length": 22.4795081967, "ext": "c", "hexsha": "3cc3769032954e5564f1ce8a4e6da7647f746e0f", "lang": "C", "max_forks_count": 47, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:31:46.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-03T18:30:50.000Z", "max_forks_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "merenlab/CONCOCT", "max_forks_repo_path": "c-concoct/test_vbgmm_fit.c", "max_issues_count": 156, "max_issues_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:26:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:51:10.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "merenlab/CONCOCT", "max_issues_repo_path": "c-concoct/test_vbgmm_fit.c", "max_line_length": 94, "max_stars_count": 79, "max_stars_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "merenlab/CONCOCT", "max_stars_repo_path": "c-concoct/test_vbgmm_fit.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:12:15.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-16T15:08:51.000Z", "num_tokens": 1697, "size": 5485 }
#include <stdlib.h> #include <stdio.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> struct data { double *t; double *y; size_t n; }; /* model function: a * exp( -1/2 * [ (t - b) / c ]^2 ) */ double gaussian(const double a, const double b, const double c, const double t) { const double z = (t - b) / c; return (a * exp(-0.5 * z * z)); } int func_f (const gsl_vector * x, void *params, gsl_vector * f) { struct data *d = (struct data *) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); size_t i; for (i = 0; i < d->n; ++i) { double ti = d->t[i]; double yi = d->y[i]; double y = gaussian(a, b, c, ti); gsl_vector_set(f, i, yi - y); } return GSL_SUCCESS; } int func_df (const gsl_vector * x, void *params, gsl_matrix * J) { struct data *d = (struct data *) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); size_t i; for (i = 0; i < d->n; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); gsl_matrix_set(J, i, 0, -ei); gsl_matrix_set(J, i, 1, -(a / c) * ei * zi); gsl_matrix_set(J, i, 2, -(a / c) * ei * zi * zi); } return GSL_SUCCESS; } int func_fvv (const gsl_vector * x, const gsl_vector * v, void *params, gsl_vector * fvv) { struct data *d = (struct data *) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); double va = gsl_vector_get(v, 0); double vb = gsl_vector_get(v, 1); double vc = gsl_vector_get(v, 2); size_t i; for (i = 0; i < d->n; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); double Dab = -zi * ei / c; double Dac = -zi * zi * ei / c; double Dbb = a * ei / (c * c) * (1.0 - zi*zi); double Dbc = a * zi * ei / (c * c) * (2.0 - zi*zi); double Dcc = a * zi * zi * ei / (c * c) * (3.0 - zi*zi); double sum; sum = 2.0 * va * vb * Dab + 2.0 * va * vc * Dac + vb * vb * Dbb + 2.0 * vb * vc * Dbc + vc * vc * Dcc; gsl_vector_set(fvv, i, sum); } return GSL_SUCCESS; } void callback(const size_t iter, void *params, const gsl_multifit_nlinear_workspace *w) { gsl_vector *f = gsl_multifit_nlinear_residual(w); gsl_vector *x = gsl_multifit_nlinear_position(w); double avratio = gsl_multifit_nlinear_avratio(w); double rcond; (void) params; /* not used */ /* compute reciprocal condition number of J(x) */ gsl_multifit_nlinear_rcond(&rcond, w); fprintf(stderr, "iter %2zu: a = %.4f, b = %.4f, c = %.4f, |a|/|v| = %.4f cond(J) = %8.4f, |f(x)| = %.4f\n", iter, gsl_vector_get(x, 0), gsl_vector_get(x, 1), gsl_vector_get(x, 2), avratio, 1.0 / rcond, gsl_blas_dnrm2(f)); } void solve_system(gsl_vector *x, gsl_multifit_nlinear_fdf *fdf, gsl_multifit_nlinear_parameters *params) { const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; const size_t max_iter = 200; const double xtol = 1.0e-8; const double gtol = 1.0e-8; const double ftol = 1.0e-8; const size_t n = fdf->n; const size_t p = fdf->p; gsl_multifit_nlinear_workspace *work = gsl_multifit_nlinear_alloc(T, params, n, p); gsl_vector * f = gsl_multifit_nlinear_residual(work); gsl_vector * y = gsl_multifit_nlinear_position(work); int info; double chisq0, chisq, rcond; /* initialize solver */ gsl_multifit_nlinear_init(x, fdf, work); /* store initial cost */ gsl_blas_ddot(f, f, &chisq0); /* iterate until convergence */ gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol, callback, NULL, &info, work); /* store final cost */ gsl_blas_ddot(f, f, &chisq); /* store cond(J(x)) */ gsl_multifit_nlinear_rcond(&rcond, work); gsl_vector_memcpy(x, y); /* print summary */ fprintf(stderr, "NITER = %zu\n", gsl_multifit_nlinear_niter(work)); fprintf(stderr, "NFEV = %zu\n", fdf->nevalf); fprintf(stderr, "NJEV = %zu\n", fdf->nevaldf); fprintf(stderr, "NAEV = %zu\n", fdf->nevalfvv); fprintf(stderr, "initial cost = %.12e\n", chisq0); fprintf(stderr, "final cost = %.12e\n", chisq); fprintf(stderr, "final x = (%.12e, %.12e, %12e)\n", gsl_vector_get(x, 0), gsl_vector_get(x, 1), gsl_vector_get(x, 2)); fprintf(stderr, "final cond(J) = %.12e\n", 1.0 / rcond); gsl_multifit_nlinear_free(work); } int main (void) { const size_t n = 300; /* number of data points to fit */ const size_t p = 3; /* number of model parameters */ const double a = 5.0; /* amplitude */ const double b = 0.4; /* center */ const double c = 0.15; /* width */ const gsl_rng_type * T = gsl_rng_default; gsl_vector *f = gsl_vector_alloc(n); gsl_vector *x = gsl_vector_alloc(p); gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params = gsl_multifit_nlinear_default_parameters(); struct data fit_data; gsl_rng * r; size_t i; gsl_rng_env_setup (); r = gsl_rng_alloc (T); fit_data.t = malloc(n * sizeof(double)); fit_data.y = malloc(n * sizeof(double)); fit_data.n = n; /* generate synthetic data with noise */ for (i = 0; i < n; ++i) { double t = (double)i / (double) n; double y0 = gaussian(a, b, c, t); double dy = gsl_ran_gaussian (r, 0.1 * y0); fit_data.t[i] = t; fit_data.y[i] = y0 + dy; } /* define function to be minimized */ fdf.f = func_f; fdf.df = func_df; fdf.fvv = func_fvv; fdf.n = n; fdf.p = p; fdf.params = &fit_data; /* starting point */ gsl_vector_set(x, 0, 1.0); gsl_vector_set(x, 1, 0.0); gsl_vector_set(x, 2, 1.0); fdf_params.trs = gsl_multifit_nlinear_trs_lmaccel; solve_system(x, &fdf, &fdf_params); /* print data and model */ { double A = gsl_vector_get(x, 0); double B = gsl_vector_get(x, 1); double C = gsl_vector_get(x, 2); for (i = 0; i < n; ++i) { double ti = fit_data.t[i]; double yi = fit_data.y[i]; double fi = gaussian(A, B, C, ti); printf("%f %f %f\n", ti, yi, fi); } } gsl_vector_free(f); gsl_vector_free(x); gsl_rng_free(r); return 0; }
{ "alphanum_fraction": 0.5865428528, "avg_line_length": 25.7607843137, "ext": "c", "hexsha": "34145cfa4aa524ec79a0829043dd65c3006bac50", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/nlfit2b.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/nlfit2b.c", "max_line_length": 109, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/nlfit2b.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": 2208, "size": 6569 }
/* rng/fishman20.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 generator is taken from * * Donald E. Knuth * The Art of Computer Programming * Volume 2 * Third Edition * Addison-Wesley * Page 108 * * It is called "Fishman" * * This implementation copyright (C) 2001 Carlo Perassi * and (C) 2003 Heiko Bauke. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_rng.h> static inline unsigned long int ran_get (void *vstate); static double ran_get_double (void *vstate); static void ran_set (void *state, unsigned long int s); static const long int m = 2147483647, a = 48271, q = 44488, r = 3399; typedef struct { unsigned long int x; } ran_state_t; static inline unsigned long int ran_get (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; const unsigned long int x = state->x; const long int h = x / q; const long int t = a * (x - h * q) - h * r; if (t < 0) { state->x = t + m; } else { state->x = t; } return state->x; } static double ran_get_double (void *vstate) { ran_state_t *state = (ran_state_t *) vstate; return ran_get (state) / 2147483647.0; } static void ran_set (void *vstate, unsigned long int s) { ran_state_t *state = (ran_state_t *) vstate; if ((s%m) == 0) s = 1; /* default seed is 1 */ state->x = s & m; return; } static const gsl_rng_type ran_type = { "fishman20", /* name */ 2147483646, /* RAND_MAX */ 1, /* RAND_MIN */ sizeof (ran_state_t), &ran_set, &ran_get, &ran_get_double }; const gsl_rng_type *gsl_rng_fishman20 = &ran_type;
{ "alphanum_fraction": 0.650382328, "avg_line_length": 22.6346153846, "ext": "c", "hexsha": "025bec324961515e144277b54c44861dbe529686", "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/fishman20.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/rng/fishman20.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/rng/fishman20.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 666, "size": 2354 }
#include <cblas.h> #include <stdio.h> #include <stdlib.h> #define N 1000000 #define REP 500 /* compilar: gcc fonte.c -o exec -lblas */ int main( void ) { float *x, *y, *y2; int i, j; double ti = 0, tf = 0; /* ti = tempo inicial // tf = tempo final */ struct timeval tempo_inicio, tempo_fim; /* aloca vetores dianmicamente */ x = ( float* ) malloc( N * sizeof( float ) ); y = ( float* ) malloc( N * sizeof( float ) ); y2 = ( float* ) malloc( N * sizeof( float ) ); /* atribue valores aleatorios */ for( i = 0; i < N; i++ ) { x[ i ] = random( ); y2[ i ] = y[ i ] = random( ); } /* marca tempo inicial */ gettimeofday( &tempo_inicio, NULL ); /* Calcula y=alfa*x+y */ for( j = 0; j < REP; j++ ) { cblas_saxpy( N, 0.5, x, 1, y, 1 ); } /* calcula o tempo gasto */ gettimeofday( &tempo_fim, NULL ); tf = ( double ) tempo_fim.tv_usec / 1000000.0 + tempo_fim.tv_sec; ti = ( double ) tempo_inicio.tv_usec / 1000000.0 + tempo_inicio.tv_sec; printf( "Tempo gasto em saxpy (BLAS) %.15f segundos \n", tf - ti ); /* marca tempo inicial */ gettimeofday( &tempo_inicio, NULL ); /* Calcula y=alfa*x+y */ for( j = 0; j < REP; j++ ) { for( i = 0; i < N; i++ ) { y2[ i ] = 0.5 * x[ i ] + y2[ i ]; } } /* calcula o tempo gasto */ gettimeofday( &tempo_fim, NULL ); tf = ( double ) tempo_fim.tv_usec / 1000000.0 + tempo_fim.tv_sec; ti = ( double ) tempo_inicio.tv_usec / 1000000.0 + tempo_inicio.tv_sec; printf( "Tempo gasto direto %.15f segundos \n", tf - ti ); return( 0 ); }
{ "alphanum_fraction": 0.5718891038, "avg_line_length": 28.7222222222, "ext": "c", "hexsha": "4d4b38fd45b6cc8806d2f9f1d3e8ee8493f7a635", "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": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lellisls/PAD", "max_forks_repo_path": "at02-cache/exemplos/compara-blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "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": "lellisls/PAD", "max_issues_repo_path": "at02-cache/exemplos/compara-blas.c", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lellisls/PAD", "max_stars_repo_path": "at02-cache/exemplos/compara-blas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 553, "size": 1551 }
// -------------------------------------------------------------- // File: ex10.c // Description: Example with the sections directive // Software stack: Exercises suite for V. Keller lecture // Version: 1.0 // License: BSD // Author: Vincent Keller (Vincent.Keller@epfl.ch), CADMOS, 2012 // // COMPILATION AND LINKING // // WITHOUT MKL : gcc -O3 -ftree-vectorize dgemm.c -lgsl -lgslcblas -lm -o dgemm // WITH MKL : export MKLROOT=/software/intel/mkl; icc -DMKLINUSE -DMKL_ILP64 -openmp -I${MKLROOT}/include -O3 -xHost dgemm.c -L${MKLROOT}/lib/intel64 -lmkl_intel_ilp64 -lmkl_core -lmkl_intel_thread -lpthread -lm -o dgemm // -------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <omp.h> #if defined(MKLINUSE) #include "mkl.h" #else #include <gsl/gsl_blas.h> #endif double verification(double ** array, int N){ double ret; int i,j; for (i=0;i<N;i++){ for (j=0;j<N;j++){ ret+=array[i][j]; } } return ret; } double second() { struct timeval tp; int i; i = gettimeofday(&tp,NULL); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } int main( ) { int N, myrank,i,j,k,chunk, mysize; double ** A; double ** B; double ** C; double t1, t2; double *A_dgemm, *B_dgemm, *C_dgemm; double alpha, beta; mysize = 1; N=2000; #if defined(MKLINUSE) A_dgemm = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); B_dgemm = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); C_dgemm = (double *)mkl_malloc( N*N*sizeof( double ), 64 ); #else A_dgemm = (double *)malloc( N*N*sizeof( double )); B_dgemm = (double *)malloc( N*N*sizeof( double )); C_dgemm = (double *)malloc( N*N*sizeof( double )); #endif for (i = 0; i < (N*N); i++) { A_dgemm[i] = 1.0; } for (i = 0; i < (N*N); i++) { B_dgemm[i] = 2.0; } for (i = 0; i < (N*N); i++) { C_dgemm[i] = 0.0; } alpha= 1.0; beta = 0.0; A = (double**)malloc(N*sizeof(double*)); B = (double**)malloc(N*sizeof(double*)); C = (double**)malloc(N*sizeof(double*)); for (i=0;i<N;i++){ A[i]=(double*)malloc(N*sizeof(double)); B[i]=(double*)malloc(N*sizeof(double)); C[i]=(double*)malloc(N*sizeof(double)); } for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } // ============================================================================================================ t1 = second(); for (i=0;i<N;i++){ for (j=0;j<N;j++){ for (k=0;k<N;k++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[IJK] Compute time [s] : %6.3f \n", (t2-t1)); printf("[IJK] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[IJK] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } t1 = second(); for (i=0;i<N;i++){ for (k=0;k<N;k++){ for (j=0;j<N;j++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[IKJ] Compute time [s] : %6.3f \n", (t2-t1)); printf("[IKJ] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[IKJ] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } t1 = second(); for (j=0;j<N;j++){ for (i=0;i<N;i++){ for (k=0;k<N;k++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[JIK] Compute time [s] : %6.3f \n", (t2-t1)); printf("[JIK] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[JIK] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } t1 = second(); for (j=0;j<N;j++){ for (k=0;k<N;k++){ for (i=0;i<N;i++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[JKI] Compute time [s] : %6.3f \n", (t2-t1)); printf("[JKI] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[JKI] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } t1 = second(); for (k=0;k<N;k++){ for (i=0;i<N;i++){ for (j=0;j<N;j++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[KIJ] Compute time [s] : %6.3f \n", (t2-t1)); printf("[KIJ] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[KIJ] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ for (i=0;i<N;i++){ for (j=0;j<N;j++){ A[i][j] = 1.0; B[i][j] = 2.0; C[i][j] = 0.0; } } t1 = second(); for (k=0;k<N;k++){ for (j=0;j<N;j++){ for (i=0;i<N;i++){ C[i][j]=C[i][j] + A[i][k]*B[k][j]; } } } t2 = second(); printf("[KJI] Compute time [s] : %6.3f \n", (t2-t1)); printf("[KJI] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[KJI] Verification : %6.3f \n\n", verification(C,N)); // ============================================================================================================ t1 = second(); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N,N,N, alpha, A_dgemm, N, B_dgemm, N, beta, C_dgemm, N); t2 = second(); printf("[DGEMM OPT] Compute time [s] : %6.3f \n", (t2-t1)); printf("[DGEMM OPT] Performance [GF/s]: %6.3f \n", (((double)N*(double)N*(double)N*2.0)/((t2-t1)*1.e9))); printf("[DGEMM OPT] Verification : %6.3f \n\n", verification(C,N)); for (i=0;i<N;i++){ free(A[i]); free(B[i]); free(C[i]); } free(A); free(B); free(C); return 0; }
{ "alphanum_fraction": 0.334683665, "avg_line_length": 32.78515625, "ext": "c", "hexsha": "1711f31c499a9fda531c910db9bec0b0e813f528", "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": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_path": "examples-course-examples/optimization/dgemm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "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": "vkeller/math-454", "max_issues_repo_path": "examples-course-examples/optimization/dgemm.c", "max_line_length": 221, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_path": "examples-course-examples/optimization/dgemm.c", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "num_tokens": 2366, "size": 8393 }
/****************************************************************************** CosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics https://github.com/CosmoLike/CosmoCov by CosmoLike developers ******************************************************************************/ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> // #include "../class/include/class.h" #include <gsl/gsl_odeiv.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> //void omega_a(double aa,double *om_m,double *om_v); double omv_vareos(double a); static inline double hoverh0(double a); double growfac(double a); //int func_for_growfac(double a,const double y[],double f[],void *params); double Tsqr_EH_wiggle(double khoverMPC); //double int_for_sigma_r_sqr(double k, void * args); double sigma_r_sqr(); //double Delta_L_wiggle(double k); //double Delta_lin_wiggle(double k,double a); double p_lin(double k,double a); //double int_sig_R_knl(double logk, void *args); //double int_neff(double lnk, void *args); //double int_cur(double lnk, void *args); //void nonlin_scale(double amp, double *R_NL, double *neff, double *Curv); //double Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin); //void Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da); //double Delta_NL_Halofit(double k_NL, double a); //k in h/Mpc double Pdelta(double k_NL,double a); //k in coverH0 units //double int_for_chi(double a,void * args); double f_K(double chi); double chi(double a); double a_chi(double chi1); // extern void emu(double *xstar, double *ystar, double *kstar); //c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //variable Omega_v //c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double omv_vareos(double a) { return(cosmology.Omega_v*exp(-3.*((cosmology.w0+cosmology.wa+1.)*log(a)+cosmology.wa*(1.-a)))); } //c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //c evolution of omega matter and omega lamda with expansion factor void omega_a(double aa,double *om_m,double *om_v) { double a2,omega_curv; a2=aa*aa; omega_curv=1.0-cosmology.Omega_m- cosmology.Omega_v; *om_m=cosmology.Omega_m /(cosmology.Omega_m +aa*(omv_vareos(aa) *a2 +omega_curv)); *om_v=omv_vareos(aa)*a2*aa/(cosmology.Omega_m+aa*(a2*omv_vareos(aa) +omega_curv)); } //c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //growth factor including Dark energy parameters w0, wa //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //function for growfac (DGL) int func_for_growfac(double a,const double y[],double f[],void *params) { //double *p=(double *)params; if (a == 0) { printf("a=0 in function 'func_for_growfac'!\n"); exit(1); } double aa=a*a; double omegam=cosmology.Omega_m/(aa*a); double omegav=omv_vareos(a); double hub = hoverh0(a); double one_plus_mg_mu = 1.; hub = hub*hub; f[0]=y[1]; if(cosmology.MGmu != 0){ one_plus_mg_mu += cosmology.MGmu*omegav/hub/cosmology.Omega_v; } f[1]=y[0]*3.*cosmology.Omega_m/(2.*hub*aa*aa*a)*one_plus_mg_mu-y[1]/a*(2.-(omegam+(3.*(cosmology.w0+cosmology.wa*(1.-a))+1)*omegav)/(2.*hub)); return GSL_SUCCESS; } static inline double hoverh0(double a){ return sqrt(cosmology.Omega_m /(a*a*a) + (1.-cosmology.Omega_m -cosmology.Omega_v )/(a*a) + omv_vareos(a) ); } double growfac(double a) { const double MINA=1.e-8; static cosmopara C; static double *ai; static double *table; double res; gsl_interp *intf=gsl_interp_alloc(gsl_interp_linear,Ntable.N_a); gsl_interp_accel *acc=gsl_interp_accel_alloc(); if (recompute_expansion(C)) { if(table!=0) free_double_vector(table,0, Ntable.N_a-1); if(ai!=0) free_double_vector(ai,0, Ntable.N_a-1); ai=create_double_vector(0, Ntable.N_a-1); table=create_double_vector(0, Ntable.N_a-1); int i; const gsl_odeiv_step_type *T=gsl_odeiv_step_rkf45; gsl_odeiv_step *s=gsl_odeiv_step_alloc(T,2); gsl_odeiv_control *c=gsl_odeiv_control_y_new(1.e-6,0.0); gsl_odeiv_evolve *e=gsl_odeiv_evolve_alloc(2); double t=MINA; //start a double t1=1.1; //final a double h=1.e-6; //initial step size double y[2]={MINA,MINA}; //initial conditions double norm; double par[0]={}; gsl_odeiv_system sys={func_for_growfac,NULL,2,&par}; for (i=1;i<=Ntable.N_a;i++) { ai[i-1]=i*t1/(1.*Ntable.N_a); while(t<ai[i-1]) gsl_odeiv_evolve_apply(e,c,s,&sys,&t,ai[i-1],&h,y); if (i==1) norm=y[0]/ai[i-1]; table[i-1]=y[0]/norm; } gsl_odeiv_evolve_free(e); gsl_odeiv_control_free(c); gsl_odeiv_step_free(s); update_cosmopara(&C); } gsl_interp_init(intf,ai,table,Ntable.N_a); res=gsl_interp_eval(intf,ai,table,a,acc); gsl_interp_accel_free(acc); gsl_interp_free(intf); return(res); } // ---------------------------- Transfer Function from EH98 ---------------------- //Input: k -- Wavenumber at which to calculate transfer function, in Mpc^-1. Output: Returns the value of the full transfer function fitting formula. This is the form given in Section 3 of Eisenstein & Hu (1997). Notes: Units are Mpc, not h^-1 Mpc. double Tsqr_EH_wiggle(double khoverMPC) { static double omhh=-123.; static double obhh=-123.; static double OMEGA_V = -123.; static double f_baryon; static double k_equality; static double sound_horizon; static double beta_c; static double alpha_c; static double beta_node; static double alpha_b; static double beta_b; static double k_silk; //if (omhh != cosmology.Omega_m*cosmology.h0*cosmology.h0 || obhh != cosmology.omb*cosmology.h0*cosmology.h0|| OMEGA_V != cosmology.Omega_v){ double theta_cmb,z_equality,z_drag,R_drag,R_equality; double z_drag_b1, z_drag_b2; double alpha_c_a1, alpha_c_a2, beta_c_b1, beta_c_b2, alpha_b_G, y; omhh = cosmology.Omega_m*cosmology.h0*cosmology.h0; obhh = cosmology.omb*cosmology.h0*cosmology.h0; OMEGA_V = cosmology.Omega_v; f_baryon = obhh/omhh; //printf("%le\n",f_baryon); theta_cmb=2.728/2.7;// Tcmb in units of 2.7 K z_equality= 2.50e4*omhh/POW4(theta_cmb);//Redshift of matter-radiation equality, really 1+z k_equality=0.0746*omhh/SQR(theta_cmb);//Scale of equality, in Mpc^-1 z_drag_b1 = 0.313*pow(omhh,-0.419)*(1+0.607*pow(omhh,0.674)); z_drag_b2 = 0.238*pow(omhh,0.223); z_drag=1291*pow(omhh,0.251)/(1+0.659*pow(omhh,0.828))*(1+z_drag_b1*pow(obhh,z_drag_b2));//Redshift of drag epoch R_drag=31.5*obhh/POW4(theta_cmb)*(1000/(1+z_drag));//Photon-baryon ratio at drag epoch R_equality= 31.5*obhh/POW4(theta_cmb)*(1000/z_equality);//Photon-baryon ratio at equality epoch sound_horizon=2./3./k_equality*sqrt(6./R_equality)*log((sqrt(1+R_drag)+sqrt(R_drag+R_equality))/(1+sqrt(R_equality)));//Sound horizon at drag epoch, in Mpc k_silk= 1.6*pow(obhh,0.52)*pow(omhh,0.73)*(1+pow(10.4*omhh,-0.95));//Silk damping scale, in Mpc^-1 alpha_c_a1 = pow(46.9*omhh,0.670)*(1+pow(32.1*omhh,-0.532)); alpha_c_a2 = pow(12.0*omhh,0.424)*(1+pow(45.0*omhh,-0.582)); alpha_c=pow(alpha_c_a1,-f_baryon)*pow(alpha_c_a2,-CUBE(f_baryon)); //CDM suppression beta_c_b1 = 0.944/(1+pow(458*omhh,-0.708)); beta_c_b2 = pow(0.395*omhh, -0.0266); beta_c=1.0/(1+beta_c_b1*(pow(1-f_baryon, beta_c_b2)-1));//CDM log shift y = z_equality/(1+z_drag); alpha_b_G = y*(-6.*sqrt(1+y)+(2.+3.*y)*log((sqrt(1+y)+1)/(sqrt(1+y)-1))); alpha_b=2.07*k_equality*sound_horizon*pow(1+R_drag,-0.75)*alpha_b_G;//Baryon suppression beta_node = 8.41*pow(omhh, 0.435);//Sound horizon shift beta_b= 0.5+f_baryon+(3.-2.*f_baryon)*sqrt(pow(17.2*omhh,2.0)+1);//Baryon envelope shift //} // Start of TFfit_onek from the original tf_fit.c at http://background.uchicago.edu/~whu/transfer/transferpage.html double T_c_ln_beta,T_c_ln_nobeta , T_c_C_alpha, T_c_C_noalpha; double q,qsqr, xx, xx_tilde; double T_c_f, T_c, s_tilde, T_b_T0, T_b; double k=khoverMPC*cosmology.h0; //internally this routine uses Mpc^-1 not h/Mpc q = k/13.41/k_equality; qsqr =SQR(q); xx = k*sound_horizon; T_c_ln_beta = log(2.718282+1.8*beta_c*q); T_c_ln_nobeta = log(2.718282+1.8*q); T_c_ln_beta = log(2.718282+1.8*beta_c*q); T_c_C_alpha = 14.2/alpha_c + 386.0/(1+69.9*pow(q,1.08)); T_c_C_noalpha = 14.2 + 386.0/(1+69.9*pow(q,1.08)); T_c_f = 1.0/(1.0+POW4(xx/5.4)); T_c = T_c_f*T_c_ln_beta/(T_c_ln_beta+T_c_C_noalpha*qsqr) +(1-T_c_f)*T_c_ln_beta/(T_c_ln_beta+T_c_C_alpha*qsqr); s_tilde = sound_horizon*pow(1+CUBE(beta_node/xx),-1./3.); xx_tilde = k*s_tilde; T_b_T0 = T_c_ln_nobeta/(T_c_ln_nobeta+T_c_C_noalpha*qsqr); T_b = sin(xx_tilde)/(xx_tilde)*(T_b_T0/(1+SQR(xx/5.2))+alpha_b/(1+CUBE(beta_b/xx))*exp(-pow(k/k_silk,1.4))); return SQR(f_baryon*T_b + (1-f_baryon)*T_c); } //Calculate Normalization see Cosmology Notes 8.105 double int_for_sigma_r_sqr(double k, void * args) { double kR, res, x; kR = k*8.; // r=8 Mpc/h x = (sin(kR) - kR*cos(kR))/(kR*kR*kR); res = pow(k,2.+cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05))*Tsqr_EH_wiggle(k)*x*x; return res; } double sigma_r_sqr() { static double res = -123.; static cosmopara C; double integral,array[1]; if (recompute_Delta(C)) //strictly speaking, this is recomputed unnecessarily if only sigma_8 changes { integral = int_gsl_integrate_medium_precision(int_for_sigma_r_sqr,(void*)array,1e-4,1e6,NULL,512); res = 9.0*integral; //see Peackock97, eq. 29 update_cosmopara(&C); } if (!(res>0.0)){ fprintf(stderr,"failed with sigma_r_sqr = %le\n", res); } assert(res>0.0); return res; } double Delta_L_wiggle(double k) { static cosmopara C; static double *table_P; static double dk = .0, logkmin = .0, logkmax = .0; double klog,f1,norm; int i; if (k < limits.k_min_mpc || k > limits.k_max_mpc){ norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr(); return norm*pow(k,cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05)+3.0)*Tsqr_EH_wiggle(k); //printf("outside Delta_L_tab\n"); } else{ if (recompute_Delta(C)) { if (cosmology.M_nu > 0){ printf("Implementation of EH transfer function does not support massive neutrinos\n EXIT\n"); } update_cosmopara(&C); norm=cosmology.sigma_8*cosmology.sigma_8/sigma_r_sqr(); if(table_P!=0) free_double_vector(table_P,0, Ntable.N_k_lin-1); table_P=create_double_vector(0, Ntable.N_k_lin-1); logkmin = log(limits.k_min_mpc); logkmax = log(limits.k_max_mpc); dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.); klog = logkmin; for (i=0; i<Ntable.N_k_lin; i++, klog += dk) { table_P[i]=log(norm*pow(exp(klog),cosmology.n_spec+ 0.5*cosmology.alpha_s*log(k/0.05)+3.0)*Tsqr_EH_wiggle(exp(klog))); } //printf("finished Delta_L_wiggle\n"); } } klog=log(k); f1=interpol(table_P, Ntable.N_k_lin, logkmin, logkmax, dk,klog, 1.0,1.0 ); return exp(f1); } // linear power spectrum routine with k in units H_0/c; used in covariances.c for beat coupling and in halo.c double p_lin(double k,double a) { static cosmopara C; static double **table_P_Lz = 0; static double logkmin = 0., logkmax = 0., dk = 0., da = 0.; int status; // if (strcmp(pdeltaparams.runmode,"CLASS")==0 || strcmp(pdeltaparams.runmode,"class")==0) return p_class(k,a,0, &status); double amp,ampsqr,grow0,aa,klog,val; int i,j; if (a >= 0.99999){a =0.99999;} if (recompute_cosmo3D(C)){ update_cosmopara(&C); if (table_P_Lz!=0) free_double_matrix(table_P_Lz,0, Ntable.N_a-1, 0, Ntable.N_k_lin-1); table_P_Lz = create_double_matrix(0, Ntable.N_a-1, 0, Ntable.N_k_lin-1); grow0=growfac(1.); da = (1. - limits.a_min)/(Ntable.N_a-1.); aa = limits.a_min; for (i=0; i<Ntable.N_a; i++, aa +=da) { if(aa>1.0) aa=1.0; amp=growfac(aa)/grow0; ampsqr=amp*amp; logkmin = log(limits.k_min_mpc); logkmax = log(limits.k_max_mpc); dk = (logkmax - logkmin)/(Ntable.N_k_lin-1.); klog = logkmin; for (j=0; j<Ntable.N_k_lin; j++, klog += dk) { table_P_Lz[i][j] = log(ampsqr*Delta_L_wiggle(exp(klog))); //printf("%le %le",exp(klog),Delta_L_wiggle(exp(klog)); } } } if (k/cosmology.coverH0 > exp(logkmax)) return 0.0; klog = log(k/cosmology.coverH0); val = interpol2d(table_P_Lz, Ntable.N_a, limits.a_min, 1., da, a, Ntable.N_k_lin, logkmin, logkmax, dk, klog, 3.0+cosmology.n_spec, 0.0); if(isnan(val) || (k==0)) return 0.0; return 2.0*constants.pi_sqr*exp(val)/k/k/k; } double int_sig_R_knl(double lnk, void *args) // tak12 A4 { double krsqr; double *params= (double *) args; double Rscale=params[0]; //printf("Rscale %le k %le\n",Rscale,exp(lnk)); krsqr= SQR(exp(lnk)*Rscale); return Delta_L_wiggle(exp(lnk))*exp(-krsqr); } double int_neff(double lnk, void *args) //tak12 A5 { double krsqr; double *params= (double *) args; double Rscale=params[0]; krsqr= SQR(exp(lnk)*Rscale); return Delta_L_wiggle(exp(lnk))*2.0*krsqr*exp(-krsqr); //see S03 eq. 59 } double int_cur(double lnk, void *args) //tak12 A5 { double krsqr; double *params= (double *) args; double Rscale=params[0]; krsqr= SQR(exp(lnk)*Rscale); return Delta_L_wiggle(exp(lnk))*4.0*krsqr*(1.0-krsqr)*exp(-krsqr); // S03 eq.60 } //iterative calculation of the nonlinear scale as defined in tak12 A4 void nonlin_scale(double amp, double *R_NL, double *neff, double *Curv) { double sig_R,kmax,logkmax,sig_R_noamp,neffplus3; int iterstep; const int itermax = 40; int converged=0; double array[1]; double logRmin = -3.0; double logRmax = 4.0; iterstep=0; while(converged==0) { array[0]=pow(10.,(logRmin+logRmax)/2.0); //flexible upper limit of integration depending on drop-off of filter function kmax = sqrt(5.*log(10.))/array[0]; if (kmax<8000.0) logkmax = log(8000.0); sig_R_noamp=sqrt(int_gsl_integrate_medium_precision(int_sig_R_knl,(void*)array,-4.5,logkmax,NULL,512)); //integral goes over ln k exponent correspond to k_min~0.011 sig_R=amp*sig_R_noamp; if (sig_R>1.0) logRmin=log10(array[0]); if (sig_R<1.0) logRmax=log10(array[0]); iterstep=iterstep+1; if(fabs(sig_R-1.0) < 0.0001 || iterstep>itermax) converged=1; } *R_NL=array[0]; //R where sig_R==1 neffplus3=int_gsl_integrate_medium_precision(int_neff,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp; *neff= neffplus3 - 3.0; *Curv= int_gsl_integrate_medium_precision(int_cur,(void*)array,-4.5,logkmax,NULL,512)/sig_R_noamp/sig_R_noamp + SQR(neffplus3); //printf("%d %le\n",iterstep,amp); } double Halofit(double k, double amp, double omm, double omv,double w_z, double R_NL, double neff,double Curv, double P_delta_Lin) { double y_scale,n2eff,n3eff,n4eff; double a_n,b_n,c_n,gamma_n,alpha_n,beta_n,nu_n,f1,f2,f3; double Delta_H,Delta_H_Prime,Delta_Q; //determine nonlinear scale, neff and curvature, see tak12 A4, A5 y_scale=k*R_NL; n2eff=neff*neff; n3eff=n2eff*neff; n4eff=n2eff*n2eff; //calculate coefficients a_n = pow(10.,1.5222+2.8553*neff + 2.3706*n2eff+0.9903*n3eff+0.2250*n4eff-0.6038*Curv+0.1749*omv*(1.0+w_z)); b_n = pow(10., -0.5642+0.5864*neff + 0.5716*n2eff-1.5474*Curv +0.2279*omv*(1.0+w_z)); c_n = pow(10., 0.3698+ 2.0404*neff + 0.8161*n2eff+0.5869*Curv); gamma_n = 0.1971-0.0843*neff + 0.8460*Curv; alpha_n = fabs(6.0835 + 1.3373*neff - 0.1959*n2eff - 5.5274*Curv); beta_n = 2.0379 - 0.7354*neff + 0.3157*n2eff + 1.2490*n3eff + 0.3980*n4eff - 0.1682*Curv; nu_n = pow(10,5.2105+3.6902*neff); f1 = pow(omm,(-0.0307)); f2 = pow(omm,(-0.0585)); f3 = pow(omm,(0.0743)); //TwoHaloTerm Delta_Q=P_delta_Lin*(pow((1.0+P_delta_Lin),beta_n)/(1.0+alpha_n*P_delta_Lin))*exp(-(y_scale/4.0+y_scale*y_scale/8.0)); //OneHaloterm Delta_H_Prime=(a_n*pow(y_scale,3.0*f1))/(1.0+b_n*pow(y_scale,f2)+pow(c_n*f3*y_scale,3.0-gamma_n)); Delta_H=Delta_H_Prime/(1.0+nu_n*pow(y_scale,-2.0)); // using mu=0.0 Tak A12 //printf("Delta_Q %le Delta_H %le\n",Delta_Q,Delta_H); return Delta_H+Delta_Q; } void Delta_halofit(double **table_P_NL,double logkmin, double logkmax, double dk, double da) { double rk,omm,omv,w_z,amp,grow0,aa,klog; double R_NL,Curv,neff,P_delta,P_delta_Lin; int i,j; grow0=growfac(1.); aa = limits.a_min; //binning in k and a must be the same as in emu for (i=0; i<Ntable.N_a; i++, aa +=da) { if(aa>1.0) aa=1.0; omega_a(aa,&omm,&omv); w_z=cosmology.w0+cosmology.wa*(1.-aa); amp=growfac(aa)/grow0; nonlin_scale(amp, &R_NL, &neff, &Curv); //printf("%le %le %le %le\n",aa,R_NL,neff,Curv); klog = logkmin; for (j=0; j<Ntable.N_k_nlin; j++, klog += dk) { rk=exp(klog); P_delta_Lin=amp*amp*Delta_L_wiggle(rk); P_delta=Halofit(rk, amp, omm, omv, w_z, R_NL, neff, Curv, P_delta_Lin); table_P_NL[i][j]=log(P_delta); } } } double Delta_NL_Halofit(double k_NL, double a) { static cosmopara C; static double logkmin = 0., logkmax = 0., dk = 0., da = 0.; static double **table_P_NL=0; double klog,val; if (recompute_cosmo3D(C)){ update_cosmopara(&C); if (table_P_NL!=0) free_double_matrix(table_P_NL,0, Ntable.N_a-1, 0, Ntable.N_k_nlin-1); table_P_NL = create_double_matrix(0, Ntable.N_a-1, 0, Ntable.N_k_nlin-1); da = (1. - limits.a_min)/(Ntable.N_a-1.); logkmin = log(limits.k_min_mpc); logkmax = log(limits.k_max_mpc); dk = (logkmax - logkmin)/(Ntable.N_k_nlin-1.); Delta_halofit(table_P_NL,logkmin, logkmax, dk, da); } klog = log(k_NL); val = interpol2d(table_P_NL, Ntable.N_a, limits.a_min, 1., da, a, Ntable.N_k_nlin, logkmin, logkmax, dk, klog, cosmology.n_spec, 0.0); return exp(val); // returns the dimensionless power spectrum as a function of scale factor a and k } double nonlinear_scale_computation(double a) { static cosmopara C; static double da = 0.; static double *table=0; double omm,omv,amp,grow0,aa,res; double R_NL,Curv,neff; int i; if (recompute_cosmo3D(C)){ update_cosmopara(&C); grow0=growfac(1.); da = (1.-limits.a_min)/(Ntable.N_a-1.); aa = limits.a_min; if (table!=0) free_double_vector(table, 0, Ntable.N_a-1); table = create_double_vector(0, Ntable.N_a-1); for (i=0; i<Ntable.N_a; i++, aa+=da) { if(aa>1.0) aa=1.0; omega_a(aa,&omm,&omv); amp=growfac(aa)/grow0; nonlin_scale(amp, &R_NL, &neff, &Curv); table[i] = 1./R_NL; } } res = interpol(table, Ntable.N_a, limits.a_min, 1., da, a, 0.0, 0.0); return res; } /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ //Pdelta is called with k in units H0/c since the comoving distance chi is in units c/H0. Upstream Pdelta all routines are in h/mpc double Pdelta(double k_NL,double a) { static int P_type = -1; if (P_type == -1){ if (strcmp(pdeltaparams.runmode,"Halofit")==0) P_type = 0; if (strcmp(pdeltaparams.runmode,"halofit")==0) P_type = 0; // if (strcmp(pdeltaparams.runmode,"emu")==0) P_type = 1; // if (strcmp(pdeltaparams.runmode,"emu_only")==0) P_type = 2; if (strcmp(pdeltaparams.runmode,"linear")==0) P_type = 3; // if (strcmp(pdeltaparams.runmode,"CLASS")==0) P_type = 4; // if (strcmp(pdeltaparams.runmode,"class")==0) P_type = 4; if (strcmp(pdeltaparams.runmode,"cosmo_sim_test") ==0) P_type = 5; } //printf("%s set\n",pdeltaparams.runmode); double pdelta = 0.,kintern=k_NL/cosmology.coverH0,error,k_nonlin,res; int status; switch (P_type){ case 0: pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL; break; // case 1: pdelta=2.0*constants.pi_sqr*Delta_NL_emu(kintern,a)/k_NL/k_NL/k_NL; break; // case 2: pdelta=2.0*constants.pi_sqr*Delta_NL_emu_only(kintern,a)/k_NL/k_NL/k_NL; break; case 3: pdelta=p_lin(k_NL,a); break; // case 4: pdelta=p_class(k_NL,a,1, &status); break; case 5: k_nonlin=nonlinear_scale_computation(a); if (kintern<0.01) pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL; else{ error=0.01*pow((pdeltaparams.DIFF_A*kintern/k_nonlin),pdeltaparams.DIFF_n); pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)*(1.0+error)/k_NL/k_NL/k_NL; } break; default: printf("cosmo3D:Pdelta: %s Pdelta runmode not defined\n",pdeltaparams.runmode); printf("using Halofit (standard)\n"); pdelta=2.0*constants.pi_sqr*Delta_NL_Halofit(kintern,a)/k_NL/k_NL/k_NL; break; } // double z = 1./a -1 ; // if (z > 4.) { // printf(" z:%lf a:%lf k_Mpc:%lf PkRatio:%lf \n",z,a,kintern,PkRatio_baryons(kintern, a)); // } // if (bary.isPkbary==1) pdelta = pdelta*PkRatio_baryons(kintern, a); return pdelta; } /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ /*============================================================ *see BS 2.41 bzw Logbook for detailed calculation of chi from a.*/ double int_for_chi(double a, void * args){ //double res,asqr; //asqr=a*a; //res= 1./sqrt(a*cosmology.Omega_m + asqr*(1.-cosmology.Omega_m -cosmology.Omega_v ) + asqr*asqr*omv_vareos(a)); //return res; return 1./(a*a*hoverh0(a)); //changed to call of hoverh0 to be ready for other parametrizations } /*for the calculation of chi we have to integrate from a(z2)=a up to a(z1)=1, which means todays expansion factor*/ double chi(double a) { static cosmopara C; static double *table; static double da = 0.; double aa,res; int i; double array[1]; if (recompute_expansion(C)){ update_cosmopara(&C); da = (1.-limits.a_min)/(Ntable.N_a-1.); aa = limits.a_min; if (table!=0) free_double_vector(table, 0, Ntable.N_a-1); table = create_double_vector(0, Ntable.N_a-1); for (i=0; i<Ntable.N_a-1; i++, aa+=da) { table[i] = int_gsl_integrate_medium_precision(int_for_chi,(void*)array, aa, 1.,NULL,1000); } table[Ntable.N_a-1] =.0; } res = interpol(table, Ntable.N_a, limits.a_min, 1., da, a, 0.0, 0.0); // comoving distance in c/H_0 if (res < 0){printf ("interpolation error in chi(%e)\n",a); res=0.01;} return res; } //auxilary function to look up a(chi) double a_chi(double chi1){ static gsl_spline * a_spline = NULL; static gsl_interp_accel * a_accel = NULL; static cosmopara C; static double chi_max =-1.; if (!a_spline){ a_spline = gsl_spline_alloc(gsl_interp_cspline, Ntable.N_a); a_accel = gsl_interp_accel_alloc(); } if (recompute_cosmo3D(C)){ update_cosmopara(&C); double *table_a,*table_chi; table_a = create_double_vector(0, Ntable.N_a-1); table_chi = create_double_vector(0, Ntable.N_a-1); for (int i = 0; i < Ntable.N_a; i++){ table_a[i] = 1.0 - (1.0 - 0.99*limits.a_min)/(Ntable.N_a-1.)*(double)i; table_chi[i] = int_gsl_integrate_medium_precision(int_for_chi,NULL, table_a[i], 1.,NULL,1000); // printf("%d %e %e\n",i,table_a[i],table_chi[i]); } chi_max = int_gsl_integrate_medium_precision(int_for_chi,NULL, limits.a_min, 1.,NULL,1000); gsl_spline_init(a_spline, table_chi, table_a, Ntable.N_a); free_double_vector(table_a,0, Ntable.N_a-1); free_double_vector(table_chi,0, Ntable.N_a-1); } if (chi1 <=0.0){return 1.0;} if (chi1 > chi_max){printf("called a_chi(chi) with chi > chi(limits.a_min\nEXIT\n");exit(1);} return gsl_spline_eval(a_spline,chi1,a_accel); } /*===============================calculating the angular diameter distance f_K BS01 2.4, 2.30: f_K is a radial function that, depending on the curvature of the Universe, is a trigonometric, linear, or hyperbolic function of chi */ double f_K(double chi) { double K, K_h, f; K = (cosmology.Omega_m + cosmology.Omega_v - 1.); if (K > precision.medium) { /* open */ K_h = sqrt(K); // K in units H0/c see BS eq. 2.30 f = 1./K_h*sin(K_h*chi); //printf("open\n"); } else if (K < -precision.medium) { /* closed */ K_h = sqrt(-K); f = 1./K_h*sinh(K_h*chi); //printf("closed K=%le %le %le\n",K,cosmology.Omega_m,cosmology.Omega_v); } else { /* flat */ f = chi; //printf("flatK=%le %le %le\n",K,cosmology.Omega_m,cosmology.Omega_v); } return f; }
{ "alphanum_fraction": 0.6468262057, "avg_line_length": 35.6526162791, "ext": "c", "hexsha": "8022360d78f07e7d14e8dd1a7d1b1768c1158a90", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z", "max_forks_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joezuntz/CosmoCov", "max_forks_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "joezuntz/CosmoCov", "max_issues_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_line_length": 249, "max_stars_count": 9, "max_stars_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joezuntz/CosmoCov", "max_stars_repo_path": "cosmolike_core/theory/cosmo3D.c", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z", "num_tokens": 8813, "size": 24529 }
/* ndlinear.c * * Copyright (C) 2006, 2007 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include "gsl_multifit_ndlinear.h" static int ndlinear_construct_row(const gsl_vector *d, gsl_vector *x, gsl_multifit_ndlinear_workspace *w); /* gsl_multifit_ndlinear_alloc() Allocate a ndlinear workspace Inputs: n_dim - dimension of fit function N - number of terms in each sum; N[i] = N_i, 0 <= i < n_dim u - basis functions to call u[j] = u^{(j)}, 0 <= j < n_dim params - parameters to pass to basis functions Return: pointer to new workspace Notes: the supplied basis functions 'u[j]' must accept three arguments: int uj(double x, double y[], void *params) and fill the y[] vector so that y[i] = u_{i}^{(j)}(x) (the ith basis function for the jth parameter evaluated at x) */ gsl_multifit_ndlinear_workspace * gsl_multifit_ndlinear_alloc(size_t n_dim, size_t N[], int (**u)(double x, double y[], void *p), void *params) { gsl_multifit_ndlinear_workspace *w; size_t n_coeffs; /* total number of fit coefficients */ size_t i, idx; size_t sum_N; if (n_dim == 0) { GSL_ERROR_NULL("n_dim must be at least 1", GSL_EINVAL); } w = calloc(1, sizeof(gsl_multifit_ndlinear_workspace)); if (!w) { GSL_ERROR_NULL("failed to allocate space for workspace", GSL_ENOMEM); } w->N = calloc(n_dim, sizeof(size_t)); if (!w->N) { gsl_multifit_ndlinear_free(w); GSL_ERROR_NULL("failed to allocate space for N vector", GSL_ENOMEM); } n_coeffs = 1; sum_N = 0; for (i = 0; i < n_dim; ++i) { if (N[i] == 0) { gsl_multifit_ndlinear_free(w); GSL_ERROR_NULL("one of the sums is empty", GSL_EINVAL); } /* The total number of coefficients is: N_1 * N_2 * ... * N_n */ n_coeffs *= N[i]; w->N[i] = N[i]; sum_N += N[i]; } w->n_dim = n_dim; w->n_coeffs = n_coeffs; w->work = gsl_vector_alloc(n_coeffs); w->work2 = gsl_vector_alloc(sum_N); if (!w->work || !w->work2) { gsl_multifit_ndlinear_free(w); GSL_ERROR_NULL("failed to allocate space for basis vector", GSL_ENOMEM); } w->v = calloc(n_dim, sizeof(gsl_vector_view)); if (!w->v) { gsl_multifit_ndlinear_free(w); GSL_ERROR_NULL("failed to allocate space for basis vector", GSL_ENOMEM); } w->u = calloc(n_dim, sizeof(int *)); if (!w->u) { gsl_multifit_ndlinear_free(w); GSL_ERROR_NULL("failed to allocate space for basis functions", GSL_ENOMEM); } idx = 0; for (i = 0; i < n_dim; ++i) { w->v[i] = gsl_vector_subvector(w->work2, idx, N[i]); idx += N[i]; w->u[i] = u[i]; } w->params = params; return (w); } /* gsl_multifit_ndlinear_alloc() */ /* gsl_multifit_ndlinear_free() Free workspace w */ void gsl_multifit_ndlinear_free(gsl_multifit_ndlinear_workspace *w) { if (w->N) free(w->N); if (w->work) gsl_vector_free(w->work); if (w->work2) gsl_vector_free(w->work2); if (w->v) free(w->v); if (w->u) free(w->u); free(w); } /* gsl_multifit_ndlinear_free() */ /* gsl_multifit_ndlinear_design() This function constructs the coefficient design matrix 'X' Inputs: vars - independent variable vectors for matrix X vars is a ndata-by-n_dim matrix where the ith row specifies the n_dim independent variables for the ith observation, so that vars_{ij} = (x_i)_j, the jth element of the ith input variable vector X - (output) design matrix (must be ndata-by-w->n_coeffs) w - workspace Return: success or error */ int gsl_multifit_ndlinear_design(const gsl_matrix *vars, gsl_matrix *X, gsl_multifit_ndlinear_workspace *w) { const size_t ndata = vars->size1; if ((X->size1 != ndata) || (X->size2 != w->n_coeffs)) { GSL_ERROR("X matrix has wrong dimensions", GSL_EBADLEN); } else { size_t i; /* looping */ int s; for (i = 0; i < ndata; ++i) { gsl_vector_const_view d = gsl_matrix_const_row(vars, i); gsl_vector_view xv = gsl_matrix_row(X, i); s = ndlinear_construct_row(&d.vector, &xv.vector, w); if (s != GSL_SUCCESS) return s; } return GSL_SUCCESS; } } /* gsl_multifit_ndlinear_design() */ /* gsl_multifit_ndlinear_est() Compute the model function at a given data point with errors Inputs: x - data point (w->n_dim elements) c - coefficient vector cov - covariance matrix y - where to store fit function result y_err - standard deviation of fit w - workspace Return: success or error */ int gsl_multifit_ndlinear_est(const gsl_vector *x, const gsl_vector *c, const gsl_matrix *cov, double *y, double *y_err, gsl_multifit_ndlinear_workspace *w) { if (c->size != w->n_coeffs) { GSL_ERROR("c vector has wrong size", GSL_EBADLEN); } else { int s; s = ndlinear_construct_row(x, w->work, w); if (s != GSL_SUCCESS) return s; /* * Now w->work contains the appropriate basis functions * evaluated at the given point - compute the function value */ s = gsl_multifit_linear_est(w->work, c, cov, y, y_err); return s; } } /* gsl_multifit_ndlinear_est() */ /* gsl_multifit_ndlinear_calc() Compute the model function at a given data point Inputs: x - data point (w->n_dim elements) c - coefficient vector w - workspace Return: model value */ double gsl_multifit_ndlinear_calc(const gsl_vector *x, const gsl_vector *c, gsl_multifit_ndlinear_workspace *w) { if (c->size != w->n_coeffs) { GSL_ERROR_VAL("c vector has wrong size", GSL_EBADLEN, 0.0); } else { double y; int s; s = ndlinear_construct_row(x, w->work, w); if (s != GSL_SUCCESS) { GSL_ERROR_VAL("constructing matrix row failed", s, 0.0); } gsl_blas_ddot(w->work, c, &y); return y; } } /* gsl_multifit_ndlinear_calc() */ /* gsl_multifit_ndlinear_ncoeffs() Return the total number of fit coefficients */ size_t gsl_multifit_ndlinear_ncoeffs(gsl_multifit_ndlinear_workspace *w) { return w->n_coeffs; } /* gsl_multifit_ndlinear_ncoeffs() */ /****************************************** * INTERNAL ROUTINES * ******************************************/ /* ndlinear_construct_row() Compute a row of the design matrix X: X(:,j) = u_{r_0}^{(0)}(d_0) * u_{r_1)^{(1)}(d_1) * ... * u_{r_{n-1}}^{(n-1)}(d_{n-1}) where 'd' is the corresponding data vector for that row Inputs: d - data vector of length w->n_dim x - (output) where to store row of design matrix X w - workspace Return: success or error */ static int ndlinear_construct_row(const gsl_vector *d, gsl_vector *x, gsl_multifit_ndlinear_workspace *w) { size_t j; int k, s; size_t denom, rk; double melement; /* compute basis functions for this data point */ for (j = 0; j < w->n_dim; ++j) { s = w->u[j](gsl_vector_get(d, j), w->v[j].vector.data, w->params); if (s != GSL_SUCCESS) return s; } for (j = 0; j < w->n_coeffs; ++j) { /* * The (:,j) element of the matrix X will be: * * X_{:,j} = u_{r_0}^{(0)}(d_0) * * u_{r_1)^{(1)}(d_1) * * ... * * u_{r_{n-1}}^{(n-1)}(d_{n-1}) * * with the basis function indices r_k given by * * r_k = floor(j / Prod_{i=(k+1)..(n-1)} [ N_i ]) (mod N_k) * * In the case where N_i = N for all i, * * r_k = floor(j / N^{n - k - 1}) (mod N) * * n: dimension of fit function (w->n_dim) * N_i: number of terms in sum i of fit function */ /* calculate the r_k and the matrix element X_{:,j} */ denom = 1; melement = 1.0; for (k = (int)(w->n_dim - 1); k >= 0; --k) { rk = (j / denom) % w->N[k]; denom *= w->N[k]; melement *= gsl_vector_get(&(w->v[k]).vector, rk); } /* set the matrix element */ gsl_vector_set(x, j, melement); } return GSL_SUCCESS; } /* ndlinear_construct_row() */
{ "alphanum_fraction": 0.5836407716, "avg_line_length": 25.0978835979, "ext": "c", "hexsha": "82dcaf06878132a0964372d63d1720c47c9dca87", "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": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rennhak/Keyposes", "max_forks_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "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": "rennhak/Keyposes", "max_issues_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_line_length": 81, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rennhak/Keyposes", "max_stars_repo_path": "src/BodyComponents/archive/ndlinear-1.0/src/ndlinear.c", "max_stars_repo_stars_event_max_datetime": "2018-05-05T12:45:52.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-26T07:28:56.000Z", "num_tokens": 2673, "size": 9487 }
#ifndef structs_h #define structs_h #include <ceed.h> #include <petsc.h> #include "../problems/cl-problems.h" // ----------------------------------------------------------------------------- // Command Line Options // ----------------------------------------------------------------------------- // Forcing function options typedef enum { FORCE_NONE = 0, FORCE_CONST = 1, FORCE_MMS = 2 } forcingType; static const char *const forcing_types[] = {"none", "constant", "mms", "forcingType","FORCE_",0 }; static const char *const forcing_types_for_disp[] = {"None", "Constant", "Manufactured solution" }; // Multigrid options typedef enum { MULTIGRID_LOGARITHMIC = 0, MULTIGRID_UNIFORM = 1, MULTIGRID_NONE = 2 } multigridType; static const char *const multigrid_types [] = {"logarithmic", "uniform", "none", "multigridType","MULTIGRID",0 }; static const char *const multigrid_types_for_disp[] = {"P-multigrid, logarithmic coarsening", "P-multigrind, uniform coarsening", "No multigrid" }; // ----------------------------------------------------------------------------- // Application data structs // ----------------------------------------------------------------------------- // Units typedef struct Units_ *Units; struct Units_ { // Fundamental units PetscScalar meter; PetscScalar kilogram; PetscScalar second; // Derived unit PetscScalar Pascal; }; // Application context from user command line options typedef struct AppCtx_ *AppCtx; struct AppCtx_ { const char *name, *name_for_disp; // problem name char ceed_resource[PETSC_MAX_PATH_LEN]; // libCEED backend char mesh_file[PETSC_MAX_PATH_LEN]; // exodusII mesh file char output_dir[PETSC_MAX_PATH_LEN]; PetscBool test_mode; PetscBool view_soln; PetscBool view_final_soln; PetscViewer energy_viewer; problemType problem_choice; forcingType forcing_choice; multigridType multigrid_choice; PetscInt degree; PetscInt q_extra; PetscInt num_levels; PetscInt *level_degrees; PetscInt num_increments; // Number of steps PetscInt bc_clamp_count; PetscInt bc_clamp_faces[16]; // [translation; 3] [rotation axis; 3] [rotation magnitude c_0, c_1] // The rotations are (c_0 + c_1 s) \pi, where s = x · axis PetscScalar bc_clamp_max[16][8]; PetscInt bc_traction_count; PetscInt bc_traction_faces[16]; PetscScalar bc_traction_vector[16][3]; PetscScalar forcing_vector[3]; PetscReal test_tol; PetscReal expect_final_strain; }; // Forcing function data typedef struct { CeedQFunctionUser setup_forcing; const char *setup_forcing_loc; } forcingData; extern forcingData forcing_options[3]; // Data for PETSc Matshell typedef struct UserMult_ *UserMult; struct UserMult_ { MPI_Comm comm; DM dm; Vec X_loc, Y_loc, neumann_bcs; CeedVector x_ceed, y_ceed; CeedOperator op; CeedQFunction qf; Ceed ceed; PetscScalar load_increment; CeedQFunctionContext ctx_phys, ctx_phys_smoother; }; // Data for Jacobian setup routine typedef struct FormJacobCtx_ *FormJacobCtx; struct FormJacobCtx_ { UserMult *jacob_ctx; PetscInt num_levels; SNES snes_coarse; Mat *jacob_mat, jacob_mat_coarse; Vec u_coarse; }; // Data for PETSc Prolongation/Restriction Matshell typedef struct UserMultProlongRestr_ *UserMultProlongRestr; struct UserMultProlongRestr_ { MPI_Comm comm; DM dm_c, dm_f; Vec loc_vec_c, loc_vec_f; CeedVector ceed_vec_c, ceed_vec_f; CeedOperator op_prolong, op_restrict; Ceed ceed; }; #define SOLIDS_MAX_NUMBER_FIELDS 16 // libCEED data struct for level typedef struct CeedData_ *CeedData; struct CeedData_ { Ceed ceed; CeedBasis basis_x, basis_u, basis_c_to_f, basis_energy, basis_diagnostic; CeedElemRestriction elem_restr_x, elem_restr_u, elem_restr_geo_data_i, elem_restr_energy, elem_restr_diagnostic, elem_restr_geo_data_diagnostic_i, elem_restr_stored_fields_i[SOLIDS_MAX_NUMBER_FIELDS]; CeedQFunction qf_residual, qf_jacobian, qf_energy, qf_diagnostic; CeedOperator op_residual, op_jacobian, op_restrict, op_prolong, op_energy, op_diagnostic; CeedVector geo_data, geo_data_diagnostic, x_ceed, y_ceed, true_soln, stored_fields[SOLIDS_MAX_NUMBER_FIELDS]; }; typedef struct { CeedQFunctionUser setup_geo, residual, jacobian, energy, diagnostic, true_soln; const char *setup_geo_loc, *residual_loc, *jacobian_loc, *energy_loc, *diagnostic_loc, *true_soln_loc; CeedQuadMode quadrature_mode; CeedInt geo_data_size, number_fields_stored; CeedInt *field_sizes; const char *const *field_names; } ProblemData; #endif // structs_h
{ "alphanum_fraction": 0.5690017513, "avg_line_length": 35.6875, "ext": "h", "hexsha": "b9ec34b62a34329f676152352385c119f2078b38", "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": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "LeilaGhaffari/libCEED", "max_forks_repo_path": "examples/solids/include/structs.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "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": "LeilaGhaffari/libCEED", "max_issues_repo_path": "examples/solids/include/structs.h", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "4a63c7da274c5bcaedf5323dad2ae658837a33b1", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "LeilaGhaffari/libCEED", "max_stars_repo_path": "examples/solids/include/structs.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1287, "size": 5710 }
#pragma once #include <memory> #include <string> #include <vector> #include <gsl/span> struct VfsSearchResult { std::string filename; bool dir; size_t sizeInBytes; uint32_t lastModified; }; enum class SeekDir { Start = 0, Current = 1, End = 2 }; /* Abstractions for accessing files in the virtual file system. The virtual file system is backed by TIO in a normal game, which means that the files are scattered across the .dat files and data directories. */ class Vfs { public: virtual ~Vfs() { }; static Vfs* CreateStdIoVfs(); /* Reads a file fully into a string. */ std::string ReadAsString(std::string_view filename); /* Reads a binary file fully into a vector of uint8_t. */ std::vector<uint8_t> ReadAsBinary(std::string_view filename); /** * Does the file exist? */ virtual bool FileExists(std::string_view path) = 0; /** * Does the directory exist? */ virtual bool DirExists(std::string_view path) = 0; /** * Creates a directory. */ virtual bool MkDir(std::string_view path) = 0; /** * Will return all files and directories that match the given glob pattern, which * is not recursive. * Example: mes\*.mes will return the names of all files in mes (not full paths) that end with .mes. */ virtual std::vector<VfsSearchResult> Search(std::string_view globPattern) = 0; /** * Removes an empty directory. */ virtual bool RemoveDir(std::string_view path) = 0; /** * Removes a file (no directories). */ virtual bool RemoveFile(std::string_view path) = 0; /** * Deletes all files and dirctories within the given directory. */ bool CleanDir(std::string_view path); /** * Returns true if the given directory does not contain anything. */ bool IsDirEmpty(std::string_view path); /** * Writes binary data to a file. */ void WriteBinaryFile(std::string_view path, gsl::span<uint8_t> data); using FileHandle = void*; virtual FileHandle Open(std::string_view name, std::string_view mode) = 0; virtual size_t Read(void* buffer, size_t size, FileHandle handle) = 0; virtual size_t Write(const void* buffer, size_t size, FileHandle handle) = 0; virtual size_t Length(FileHandle handle) = 0; virtual size_t Tell(FileHandle handle) = 0; virtual void Seek(FileHandle handle, int position, SeekDir dir = SeekDir::Start) = 0; virtual void Close(FileHandle handle) = 0; }; class VfsPath { public: VfsPath() = delete; static bool IsFileSystem(std::string_view path); static std::string Concat(std::string_view a, std::string_view b); }; extern std::unique_ptr<Vfs> vfs;
{ "alphanum_fraction": 0.7023670935, "avg_line_length": 22.8053097345, "ext": "h", "hexsha": "f31d57c71ff736fee435bcd9300c4ffadc1073a8", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_issues_count": 457, "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_line_length": 86, "max_stars_count": 69, "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_path": "Infrastructure/include/infrastructure/vfs.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "num_tokens": 669, "size": 2577 }
/* * Copyright 2016 Maikel Nadolski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <gsl_assert.h> #ifndef HMM_ALGORITHM_BACKWARD_H_ #define HMM_ALGORITHM_BACKWARD_H_ namespace maikel { namespace hmm { template <class I, class J, class T> class backward_range_fn { public: using model = hidden_markov_model<T>; using row_vector = typename model::row_vector; using matrix = typename model::matrix; using symbol_type = typename std::iterator_traits<I>::value_type; backward_range_fn() = delete; backward_range_fn(I seq_it, I seq_end, J scaling_it, model const& hmm) : hmm_{&hmm}, seq_it_{seq_it}, seq_end_{seq_end}, scaling_it_{scaling_it}, beta_(hmm.states()), next_beta_(hmm.states()) { if (seq_it != seq_end) initial_coefficients(*scaling_it); } class iterator : public boost::iterator_facade< iterator, row_vector, std::input_iterator_tag, row_vector const& > { public: iterator() = default; private: friend class backward_range_fn; friend class boost::iterator_core_access; iterator(backward_range_fn& parent) : parent_{parent ? &parent : nullptr} {} backward_range_fn* parent_ = nullptr; row_vector const& dereference() const { Expects(parent_ && *parent_); return parent_->beta_; } void increment() { Expects(parent_ && *parent_); if (!parent_->next()) parent_ = nullptr; } bool equal(iterator other) const noexcept { return parent_ == other.parent_; } }; operator bool() const noexcept { return seq_it_ != seq_end_; } iterator begin() noexcept { return {*this}; } iterator end() noexcept { return {}; } private: model const* hmm_; // not owning I seq_it_, seq_end_; J scaling_it_; row_vector beta_; row_vector next_beta_; void initial_coefficients(T scaling) noexcept { Expects(beta_.size() == hmm_->states()); beta_.fill(scaling); } void recursion_advance(symbol_type s, T scaling) noexcept { using size_type = typename model::size_type; matrix const& A = hmm_->transition_matrix(); matrix const& B = hmm_->symbol_probabilities(); next_beta_.swap(beta_); // check pre conditions size_type states = A.rows(); Expects(A.cols() == states); Expects(B.rows() == states); Expects(next_beta_.size() == states); Expects(beta_.size() == states); size_type ob = gsl::narrow<size_type>(s); Expects(0 <= ob && ob < B.cols()); // recursion formula for (size_type i = 0; i < states; ++i) { beta_(i) = 0.0; for (size_type j = 0; j < states; ++j) beta_(i) += A(i,j)*B(j,ob)*next_beta_(j); beta_(i) *= scaling; } } bool next() { Expects(*this); symbol_type s = *seq_it_++; ++scaling_it_; if (seq_it_ == seq_end_) return false; recursion_advance(s, *scaling_it_); return true; } }; template <class I, class J, class T> backward_range_fn<I, J, T> backward(I begin, I end, J scaling, hidden_markov_model<T> const& hmm) { return {begin, end, scaling, hmm}; } } // namespace hmm } // namespace maikel #endif /* HMM_ALGORITHM_BACKWARD_H_ */
{ "alphanum_fraction": 0.5622864951, "avg_line_length": 28.6993464052, "ext": "h", "hexsha": "475c5f03167f54a3bc88a6d70c3efd7e0acaa24d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_path": "include/maikel/hmm/algorithm/backward.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_path": "include/maikel/hmm/algorithm/backward.h", "max_line_length": 83, "max_stars_count": 1, "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_path": "include/maikel/hmm/algorithm/backward.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "num_tokens": 975, "size": 4391 }
/* multilarge_nlinear/fdf.c * * Copyright (C) 2015, 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multilarge_nlinear.h> gsl_multilarge_nlinear_workspace * gsl_multilarge_nlinear_alloc (const gsl_multilarge_nlinear_type * T, const gsl_multilarge_nlinear_parameters * params, const size_t n, const size_t p) { gsl_multilarge_nlinear_workspace * w; if (n < p) { GSL_ERROR_VAL ("insufficient data points, n < p", GSL_EINVAL, 0); } w = calloc (1, sizeof (gsl_multilarge_nlinear_workspace)); if (w == 0) { GSL_ERROR_VAL ("failed to allocate space for workspace", GSL_ENOMEM, 0); } w->n = n; w->p = p; w->type = T; w->fdf = NULL; w->niter = 0; w->params = *params; /* the cgst method uses its own built-in linear solver */ if (w->params.trs == gsl_multilarge_nlinear_trs_cgst) { w->params.solver = gsl_multilarge_nlinear_solver_none; } w->x = gsl_vector_calloc (p); if (w->x == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0); } w->f = gsl_vector_calloc (n); if (w->f == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0); } w->dx = gsl_vector_calloc (p); if (w->dx == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0); } w->g = gsl_vector_alloc (p); if (w->g == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for g", GSL_ENOMEM, 0); } if (w->params.solver == gsl_multilarge_nlinear_solver_cholesky || w->params.solver == gsl_multilarge_nlinear_solver_mcholesky) { w->JTJ = gsl_matrix_alloc (p, p); if (w->JTJ == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for JTJ", GSL_ENOMEM, 0); } } w->sqrt_wts_work = gsl_vector_calloc (n); if (w->sqrt_wts_work == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for weights", GSL_ENOMEM, 0); } w->state = (T->alloc)(&(w->params), n, p); if (w->state == 0) { gsl_multilarge_nlinear_free (w); GSL_ERROR_VAL ("failed to allocate space for state", GSL_ENOMEM, 0); } return w; } void gsl_multilarge_nlinear_free (gsl_multilarge_nlinear_workspace * w) { RETURN_IF_NULL (w); if (w->state) (w->type->free) (w->state); if (w->dx) gsl_vector_free (w->dx); if (w->x) gsl_vector_free (w->x); if (w->f) gsl_vector_free (w->f); if (w->sqrt_wts_work) gsl_vector_free (w->sqrt_wts_work); if (w->g) gsl_vector_free (w->g); if (w->JTJ) gsl_matrix_free (w->JTJ); free (w); } gsl_multilarge_nlinear_parameters gsl_multilarge_nlinear_default_parameters(void) { gsl_multilarge_nlinear_parameters params; params.trs = gsl_multilarge_nlinear_trs_lm; params.scale = gsl_multilarge_nlinear_scale_more; params.solver = gsl_multilarge_nlinear_solver_cholesky; params.fdtype = GSL_MULTILARGE_NLINEAR_FWDIFF; params.factor_up = 3.0; params.factor_down = 2.0; params.avmax = 0.75; params.h_df = GSL_SQRT_DBL_EPSILON; params.h_fvv = 0.01; params.max_iter = 0; params.tol = 1.0e-6; return params; } int gsl_multilarge_nlinear_init (const gsl_vector * x, gsl_multilarge_nlinear_fdf * fdf, gsl_multilarge_nlinear_workspace * w) { return gsl_multilarge_nlinear_winit(x, NULL, fdf, w); } int gsl_multilarge_nlinear_winit (const gsl_vector * x, const gsl_vector * wts, gsl_multilarge_nlinear_fdf * fdf, gsl_multilarge_nlinear_workspace * w) { const size_t n = w->f->size; if (n != fdf->n) { GSL_ERROR ("function size does not match workspace", GSL_EBADLEN); } else if (w->x->size != x->size) { GSL_ERROR ("vector length does not match workspace", GSL_EBADLEN); } else if (wts != NULL && n != wts->size) { GSL_ERROR ("weight vector length does not match workspace", GSL_EBADLEN); } else { size_t i; /* initialize counters for function and Jacobian evaluations */ fdf->nevalf = 0; fdf->nevaldfu = 0; fdf->nevaldf2 = 0; fdf->nevalfvv = 0; w->fdf = fdf; gsl_vector_memcpy(w->x, x); w->niter = 0; if (wts) { w->sqrt_wts = w->sqrt_wts_work; for (i = 0; i < n; ++i) { double wi = gsl_vector_get(wts, i); gsl_vector_set(w->sqrt_wts, i, sqrt(wi)); } } else { w->sqrt_wts = NULL; } return (w->type->init) (w->state, w->sqrt_wts, w->fdf, w->x, w->f, w->g, w->JTJ); } } int gsl_multilarge_nlinear_iterate (gsl_multilarge_nlinear_workspace * w) { int status = (w->type->iterate) (w->state, w->sqrt_wts, w->fdf, w->x, w->f, w->g, w->JTJ, w->dx); w->niter++; return status; } double gsl_multilarge_nlinear_avratio (const gsl_multilarge_nlinear_workspace * w) { return (w->type->avratio) (w->state); } int gsl_multilarge_nlinear_rcond (double * rcond, const gsl_multilarge_nlinear_workspace * w) { int status = (w->type->rcond) (rcond, w->JTJ, w->state); return status; } int gsl_multilarge_nlinear_covar (gsl_matrix * covar, gsl_multilarge_nlinear_workspace * w) { if (covar->size1 != covar->size2) { GSL_ERROR ("covariance matrix must be square", GSL_ENOTSQR); } else if (covar->size1 != w->p) { GSL_ERROR ("covariance matrix does not match workspace", GSL_EBADLEN); } else { int status = (w->type->covar) (w->JTJ, covar, w->state); return status; } } /* gsl_multilarge_nlinear_driver() Iterate the nonlinear least squares solver until completion Inputs: maxiter - maximum iterations to allow xtol - tolerance in step x gtol - tolerance in gradient ftol - tolerance in ||f|| callback - callback function to call each iteration callback_params - parameters to pass to callback function info - (output) info flag on why iteration terminated 1 = stopped due to small step size ||dx| 2 = stopped due to small gradient 3 = stopped due to small change in f GSL_ETOLX = ||dx|| has converged to within machine precision (and xtol is too small) GSL_ETOLG = ||g||_inf is smaller than machine precision (gtol is too small) GSL_ETOLF = change in ||f|| is smaller than machine precision (ftol is too small) w - workspace Return: GSL_SUCCESS if converged GSL_MAXITER if maxiter exceeded without converging GSL_ENOPROG if no accepted step found on first iteration */ int gsl_multilarge_nlinear_driver (const size_t maxiter, const double xtol, const double gtol, const double ftol, void (*callback)(const size_t iter, void *params, const gsl_multilarge_nlinear_workspace *w), void *callback_params, int *info, gsl_multilarge_nlinear_workspace * w) { int status; size_t iter = 0; /* call user callback function prior to any iterations * with initial system state */ if (callback) callback(iter, callback_params, w); do { status = gsl_multilarge_nlinear_iterate (w); /* * If the solver reports no progress on the first iteration, * then it didn't find a single step to reduce the * cost function and more iterations won't help so return. * * If we get a no progress flag on subsequent iterations, * it means we did find a good step in a previous iteration, * so continue iterating since the solver has now reset * mu to its initial value. */ if (status == GSL_ENOPROG && iter == 0) { *info = status; return GSL_EMAXITER; } ++iter; if (callback) callback(iter, callback_params, w); /* test for convergence */ status = gsl_multilarge_nlinear_test(xtol, gtol, ftol, info, w); } while (status == GSL_CONTINUE && iter < maxiter); /* * the following error codes mean that the solution has converged * to within machine precision, so record the error code in info * and return success */ if (status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG) { *info = status; status = GSL_SUCCESS; } /* check if max iterations reached */ if (iter >= maxiter && status != GSL_SUCCESS) status = GSL_EMAXITER; return status; } /* gsl_multilarge_nlinear_driver() */ const char * gsl_multilarge_nlinear_name (const gsl_multilarge_nlinear_workspace * w) { return w->type->name; } gsl_vector * gsl_multilarge_nlinear_position (const gsl_multilarge_nlinear_workspace * w) { return w->x; } gsl_vector * gsl_multilarge_nlinear_residual (const gsl_multilarge_nlinear_workspace * w) { return w->f; } gsl_vector * gsl_multilarge_nlinear_step (const gsl_multilarge_nlinear_workspace * w) { return w->dx; } size_t gsl_multilarge_nlinear_niter (const gsl_multilarge_nlinear_workspace * w) { return w->niter; } const char * gsl_multilarge_nlinear_trs_name (const gsl_multilarge_nlinear_workspace * w) { return w->params.trs->name; } /* gsl_multilarge_nlinear_eval_f() Compute residual vector y with user callback function, and apply weighting transform if given: y~ = sqrt(W) y Inputs: fdf - callback function x - model parameters swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn)) set to NULL for unweighted fit y - (output) (weighted) residual vector y_i = sqrt(w_i) f_i where f_i is unweighted residual */ int gsl_multilarge_nlinear_eval_f(gsl_multilarge_nlinear_fdf *fdf, const gsl_vector *x, const gsl_vector *swts, gsl_vector *y) { int s = ((*((fdf)->f)) (x, fdf->params, y)); ++(fdf->nevalf); /* y <- sqrt(W) y */ if (swts) gsl_vector_mul(y, swts); return s; } /* gsl_multilarge_nlinear_eval_df() Compute Jacobian matrix-vector product: v = J * u or v = J^T u Inputs: TransJ - use J or J^T x - model parameters f - residual vector f(x) u - input vector u swts - weight matrix W = diag(w1,w2,...,wn) set to NULL for unweighted fit h - finite difference step size fdtype - finite difference method fdf - callback function v - (output) vector v JTJ - (output) matrix J^T J work - workspace for finite difference, size n */ int gsl_multilarge_nlinear_eval_df(const CBLAS_TRANSPOSE_t TransJ, const gsl_vector *x, const gsl_vector *f, const gsl_vector *u, const gsl_vector *swts, const double h, const gsl_multilarge_nlinear_fdtype fdtype, gsl_multilarge_nlinear_fdf *fdf, gsl_vector *v, gsl_matrix *JTJ, gsl_vector *work) { const size_t n = fdf->n; const size_t p = fdf->p; if (u != NULL && ((TransJ == CblasNoTrans && u->size != p) || (TransJ == CblasTrans && u->size != n))) { GSL_ERROR("u vector has wrong size", GSL_EBADLEN); } else if (v != NULL && ((TransJ == CblasNoTrans && v->size != n) || (TransJ == CblasTrans && v->size != p))) { GSL_ERROR("v vector has wrong size", GSL_EBADLEN); } else if (JTJ != NULL && ((JTJ->size1 != p) || (JTJ->size2 != p))) { GSL_ERROR("JTJ matrix has wrong size", GSL_EBADLEN); } else { int status = GSL_SUCCESS; if (fdf->df) { /* call user-supplied function */ status = ((*((fdf)->df)) (TransJ, x, u, fdf->params, v, JTJ)); if (v) ++(fdf->nevaldfu); if (JTJ) ++(fdf->nevaldf2); } else { #if 0 /* use finite difference Jacobian approximation */ status = gsl_multilarge_nlinear_df(h, fdtype, x, swts, fdf, f, df, work); #endif } return status; } } /* gsl_multilarge_nlinear_eval_fvv() Compute second direction derivative vector yvv with user callback function, and apply weighting transform if given: yvv~ = sqrt(W) yvv Inputs: h - step size for finite difference, if needed x - model parameters, size p v - unscaled geodesic velocity vector, size p f - residual vector f(x), size n swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn)) set to NULL for unweighted fit fdf - callback function yvv - (output) (weighted) second directional derivative vector yvv_i = sqrt(w_i) fvv_i where f_i is unweighted work - workspace, size p */ int gsl_multilarge_nlinear_eval_fvv(const double h, const gsl_vector *x, const gsl_vector *v, const gsl_vector *f, const gsl_vector *swts, gsl_multilarge_nlinear_fdf *fdf, gsl_vector *yvv, gsl_vector *work) { int status = GSL_SUCCESS; if (fdf->fvv != NULL) { /* call user-supplied function */ status = ((*((fdf)->fvv)) (x, v, fdf->params, yvv)); ++(fdf->nevalfvv); } else { #if 0 /* use finite difference approximation */ status = gsl_multilarge_nlinear_fdfvv(h, x, v, f, J, swts, fdf, yvv, work); #endif } /* yvv <- sqrt(W) yvv */ if (swts) gsl_vector_mul(yvv, swts); return status; }
{ "alphanum_fraction": 0.5842609871, "avg_line_length": 27.4575971731, "ext": "c", "hexsha": "bdea91c8c798b0d2e1fd0006ab9941f386442d71", "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/multilarge_nlinear/fdf.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/multilarge_nlinear/fdf.c", "max_line_length": 91, "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/multilarge_nlinear/fdf.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 4175, "size": 15541 }
#include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <cblas.h> #include <string.h> // memcpy #include <math.h> #include <clblast_c.h> #include "cgraph.h" #include "cg_operation.h" #include "cg_types.h" #include "cg_variables.h" #include "cg_errors.h" #include "cg_constants.h" #include "cg_enums.h" #include "cg_factory.h" #include "cg_math.h" //#pragma OPENCL EXTENSION cl_khr_fp64 : enable #if cg_float == float #define cblas_dcopy cblas_scopy #define cblas_dscal cblas_sscal #define cblas_dgemm cblas_sgemm #define cblas_ddot cblas_sdot #define cblas_dgemv cblas_sgemv #define cl_double cl_float #endif void checkErr(CCLErr* err){ if (err != NULL) { fprintf(stderr, "\n%s\n", err->message); exit(-1); } } #define CHECK_ERROR(err) \ checkErr(err); //if (err != NULL) { fprintf(stderr, "\n%s\n", err->message); exit(-1); } CCLContext * ctx = NULL; CCLProgram* prg = NULL; CCLQueue* queue = NULL; CCLDevice* dev = NULL; #if cg_float == float #define CLBlastDcopy CLBlastScopy #define CLBlastDscal CLBlastSscal #define CLBlastDgemm CLBlastSgemm #define CLBlastDdot CLBlastSdot #define CLBlastDomatcopy CLBlastSomatcopy #define CLBlastDsum CLBlastSsum #endif void copyDataToHost(CGResultNode* res){ CCLEvent* evt = NULL; CCLErr * err = NULL; switch(res->type){ case CGVT_DOUBLE: break; case CGVT_VECTOR:{ CGVector* V = (CGVector*)res->value; V->data = malloc(V->len* sizeof(cgcl_float)); if (V->loc == CG_DATALOC_DEVICE_MEM) { evt = ccl_buffer_enqueue_read(V->buf, queue, CL_TRUE, 0, V->len * sizeof(cgcl_float), V->data, NULL, NULL); if (!evt) exit(-1); ccl_buffer_destroy(V->buf); } else printf("FUCK\n"); V->loc = CG_DATALOC_HOST_MEM; break; } case CGVT_MATRIX:{ CGMatrix* M = (CGMatrix*)res->value; M->data = malloc(M->rows*M->cols* sizeof(cgcl_float)); if (M->loc == CG_DATALOC_DEVICE_MEM) { evt = ccl_buffer_enqueue_read(M->buf, queue, CL_TRUE, 0, M->rows * M->cols * sizeof(cgcl_float), M->data, NULL, NULL); if (!evt) exit(-1); ccl_buffer_destroy(M->buf); } else printf("FUCK2\n"); M->loc = CG_DATALOC_HOST_MEM; break; } } cl_bool status = ccl_queue_finish(queue, NULL); //if (!status) exit(-1); ////ccl_queue_destroy(queue); } CGDouble* makeDeviceDouble(){ CCLErr * err = NULL; CGDouble* Y = calloc(1, sizeof(CGDouble)); cg_float* ptr = &Y->value; Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE, sizeof(cgcl_float), NULL, &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; Y->value = 0.0; return Y; } CGVector* makeDeviceVector(uint64_t len){ CCLErr * err = NULL; CGVector* Y = calloc(1, sizeof(CGVector)); Y->len = len; Y->data = NULL; //calloc(len, sizeof(cg_float)); Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE , len * sizeof(cgcl_float), Y->data, &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; return Y; } CGVector* makeDeviceVectorZeros(uint64_t len){ CCLErr * err = NULL; CGVector* Y = calloc(1, sizeof(CGVector)); Y->len = len; Y->data = calloc(len, sizeof(cg_float)); Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, len * sizeof(cgcl_float), Y->data, &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; return Y; } CGMatrix* makeDeviceMatrix(uint64_t rows, uint64_t cols){ CCLErr * err = NULL; CGMatrix* Y = calloc(1, sizeof(CGMatrix)); Y->rows = rows; Y->cols = cols; Y->data = NULL; //calloc(rows*cols, sizeof(cg_float)); Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE , rows*cols * sizeof(cgcl_float), Y->data, &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; return Y; } CGMatrix* makeDeviceMatrixZeros(uint64_t rows, uint64_t cols){ CCLErr * err = NULL; CGMatrix* Y = calloc(1, sizeof(CGMatrix)); Y->rows = rows; Y->cols = cols; Y->data = calloc(rows*cols, sizeof(cg_float)); Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, rows*cols * sizeof(cgcl_float), Y->data, &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; return Y; } int selectContext() { /* Code. */ ctx = ccl_context_new_from_menu(NULL); if (ctx == NULL) exit(-1); CCLErr * err = NULL; prg = ccl_program_new_from_source_file(ctx, "/Users/praisethemoon/projects/cgraph/source/libcgraph/kernels/vec.cl", NULL); cl_bool status = ccl_program_build(prg, NULL, &err); printf("%s\n", ccl_program_get_build_log(prg, NULL)); CHECK_ERROR(err) dev = ccl_context_get_device(ctx, 0, &err); queue = ccl_queue_new(ctx, dev, 0, &err); return 0; } /* * ********************* * Multiplication * ********************* */ /* * d.d */ CGResultNode* mulDD(CGDouble* M, CGDouble* V, CGraph* graph, CGNode* parentNode){ CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = M->value * V->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * d.V == V.d */ CGResultNode* mulDV(CGDouble* A, CGVector* V, CGraph* graph, CGNode* parentNode){ CGVector* Y = makeDeviceVector(V->len); CCLErr * err = NULL; //if(A->value != 0){ uint64_t len = V->len; CCLBuffer * a = V->buf, * c = NULL; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; cl_mem V_mem = ccl_buffer_unwrap(V->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); cl_command_queue q = ccl_queue_unwrap(queue); //cblas_dcopy(V->len, V->data, 1, y, 1); //cblas_dscal(V->len, a->value, y, 1); CLBlastDcopy(V->len, V_mem, 0.0, 1, Y_mem, 0.0, 1, &q, NULL); CLBlastDscal(V->len, A->value, Y_mem, 0.0, 1, &q, NULL); //ccl_queue_destroy(queue); //} CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * d.M == M.d */ CGResultNode* mulDM(CGDouble* A, CGMatrix* M, CGraph* graph, CGNode* parentNode){ uint64_t size = M->cols*M->rows; cg_float value = A->value; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); //if(A->value != 0){ CCLErr * err = NULL; CCLBuffer * a = M->buf; CHECK_ERROR(err) CHECK_ERROR(err) cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); cl_command_queue q = ccl_queue_unwrap(queue); //cblas_dcopy(V->len, V->data, 1, y, 1); //cblas_dscal(V->len, a->value, y, 1); CLBlastDcopy(size, M_mem, 0.0, 1, Y_mem, 0.0, 1, &q, NULL); CLBlastDscal(size, A->value, Y_mem, 0.0, 1, &q, NULL); //ccl_queue_destroy(queue); //} CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M*v * broadcasting */ CGResultNode* mulMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ if(M->cols != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Add M(%"PRIu64", %"PRIu64") by V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t i = 0; //res[i] = M->data[i] * V->data[(i)%V->len]; uint64_t len = M->rows*M->cols; uint64_t vlen = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "mul_mv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, V->buf, Y->buf, ccl_arg_priv(vlen, cl_ulong), NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M*N * broadcasting */ CGResultNode* mulMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if((M1->rows != M2->rows) && (M1->cols != M2->cols)){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot multiply M(%"PRIu64", %"PRIu64") by N(%"PRIu64", %"PRIu64")", M1->rows, M1->cols, M2->rows, M2->cols); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t size = M1->cols*M1->rows; CGMatrix* Y = makeDeviceMatrix(M1->rows, M1->cols); uint64_t len = M1->rows*M1->cols; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "mul_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M1->buf, M2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M.v */ CGResultNode* dotMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if(M->cols != 1){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot calculate M(%"PRIu64", %"PRIu64") DOT V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t len = M->rows*V->len; CGMatrix* Y = makeDeviceMatrix(M->rows, V->len); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; cl_command_queue q = ccl_queue_unwrap(queue); cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem V_mem = ccl_buffer_unwrap(V->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); CLBlastDgemm(CLBlastLayoutRowMajor, CLBlastTransposeNo, CLBlastTransposeNo, M->rows, V->len, M->cols, 1.0, M_mem, 0, M->cols, V_mem, 0, V->len, 0.0, Y_mem, 0, Y->cols, &q, NULL ); //evt = ccl_buffer_enqueue_read(Y->buf, queue, CL_TRUE, 0, // len * sizeof(cl_double), Y->data, NULL, NULL); //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * v.M */ CGResultNode* dotVM(CGVector* V, CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if(M->rows != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot calculate V(%"PRIu64") DOT M(%"PRIu64", %"PRIu64")", V->len, M->rows, M->cols); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CGVector* Y = makeDeviceVector(M->cols); uint64_t m = 1; uint64_t n = M->cols; uint64_t k = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; cl_command_queue q = ccl_queue_unwrap(queue); cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem V_mem = ccl_buffer_unwrap(V->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); //cblas_dgemm(CblasRowMajor, // CblasNoTrans, CblasNoTrans, m, n, k, 1, V->data, k, M->data, n, 0, Y->data, n); CLBlastDgemm(CLBlastLayoutRowMajor, CLBlastTransposeNo, CLBlastTransposeNo, m, n, k, 1.0, V_mem, 0, k, M_mem, 0, n, 0.0, Y_mem, 0, n, &q, NULL ); //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M.N */ CGResultNode* dotMM(CGMatrix* M, CGMatrix* N, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if(M->cols != N->rows){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot DOT M(%"PRIu64", %"PRIu64") by N(%"PRIu64", %"PRIu64")", M->rows, M->cols, N->rows, N->cols); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CGMatrix* Z = makeDeviceMatrix(M->rows, N->cols); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; cl_command_queue q = ccl_queue_unwrap(queue); cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem N_mem = ccl_buffer_unwrap(N->buf); cl_mem Z_mem = ccl_buffer_unwrap(Z->buf); /* cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M->rows, N->cols, M->cols, 1.0, M->data, M->cols, N->data, N->cols, 0, z, Z->cols); */ CLBlastDgemm(CLBlastLayoutRowMajor, CLBlastTransposeNo, CLBlastTransposeNo, M->rows, N->cols, M->cols, 1.0, M_mem, 0, M->cols, N_mem, 0, N->cols, 0.0, Z_mem, 0, Z->cols, &q, NULL ); //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Z; return result; } /* * V.V */ CGResultNode* crossVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if(V1->len != V2->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot compute Cross Product of V(%"PRIu64") by V(%"PRIu64")", V1->len, V2->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t size = V1->len; CGVector* Y = makeDeviceVector(V1->len); uint64_t len = V1->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "mul_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V1->buf, V2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * ********************* * Dot Product * ********************* */ /* * V.V */ CGResultNode* dotVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; if(V1->len != V2->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot compute Dot Product of V(%"PRIu64") by V(%"PRIu64")", V1->len, V2->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t size = V1->len; cg_float res = 0; CGDouble* Y = makeDeviceDouble(); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; cl_command_queue q = ccl_queue_unwrap(queue); cl_mem M_mem = ccl_buffer_unwrap(V1->buf); cl_mem N_mem = ccl_buffer_unwrap(V2->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); //Y->value = cblas_ddot(V1->len, V1->data, 1, V2->data, 1); CLBlastDdot(size, Y_mem, 0, M_mem, 0.0, 1, N_mem, 0.0, 1, &q, NULL); evt = ccl_buffer_enqueue_read(Y->buf, queue, CL_TRUE, 0, sizeof(cl_double), &Y->value, NULL, NULL); //ccl_queue_destroy(queue); ccl_buffer_destroy(Y->buf); Y->loc = CG_DATALOC_HOST_MEM; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * ********************* * Division * ********************* */ /* * d/d */ CGResultNode* divDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){ if(D2->value == 0.0){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Diving by zero D/(D=0)"); return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg); } cg_float res = D1->value / D2->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = res; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * V/d */ CGResultNode* divVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){ if(D->value == 0.0){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Diving by zero V/(D=0)"); return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg); } CGVector* Y = makeDeviceVector(V->len); CCLErr * err = NULL; //if(A->value != 0){ uint64_t len = V->len; CCLBuffer * a = V->buf, * c = NULL; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; cl_mem V_mem = ccl_buffer_unwrap(V->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); cl_command_queue q = ccl_queue_unwrap(queue); //cblas_dcopy(V->len, V->data, 1, y, 1); //cblas_dscal(V->len, a->value, y, 1); CLBlastDcopy(V->len, V_mem, 0.0, 1, Y_mem, 0.0, 1, &q, NULL); CLBlastDscal(V->len, 1.0/D->value, Y_mem, 0.0, 1, &q, NULL); //ccl_queue_destroy(queue); //} CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * V/V */ CGResultNode* divVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){ if(V1->len != V2->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot calculate V(%"PRIu64") DIV V(%"PRIu64")", V1->len, V2->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; uint64_t size = V1->len; CGVector* Y = makeDeviceVector(V1->len); uint64_t len = V1->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "div_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V1->buf, V2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * d/V element-wise */ CGResultNode* divDV(CGDouble* D, CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = V->len; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; // TODO: check if D.value == 0.0 CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "div_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(D->value, cgcl_float), V->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M/d */ CGResultNode* divMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){ if(D->value == 0.0){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Diving by zero M/(D=0)"); return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg); } uint64_t size = M->cols*M->rows; cg_float value = D->value; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); //if(A->value != 0){ CCLErr * err = NULL; CCLBuffer * a = M->buf; CHECK_ERROR(err) CHECK_ERROR(err) cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); cl_command_queue q = ccl_queue_unwrap(queue); CLBlastDcopy(size, M_mem, 0.0, 1, Y_mem, 0.0, 1, &q, NULL); CLBlastDscal(size, 1.0/D->value, Y_mem, 0.0, 1, &q, NULL); //ccl_queue_destroy(queue); //} CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M/v */ CGResultNode* divMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ if(M->rows != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot calculate M(%"PRIu64", %"PRIu64") DIV V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; uint64_t vlen = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "div_mv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, V->buf, Y->buf, ccl_arg_priv(vlen, cl_ulong), NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * d/M element-wise */ CGResultNode* divDM(CGDouble* D, CGMatrix* M, CGraph* graph, CGNode* parentNode){ uint64_t len = M->rows*M->cols; CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); // TODO: check if D.value == 0.0 CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "div_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(D->value, cgcl_float), M->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Addition * ********************* */ /* * d+d */ CGResultNode* addDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){ cg_float res = D1->value + D2->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = res; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * V+d */ CGResultNode* addVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = V->len; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "add_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(D->value, cgcl_float), V->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M+d */ CGResultNode* addMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = M->rows*M->cols; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "add_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), ccl_arg_priv(D->value, cgcl_float), M->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result;; } /* * V+V */ CGResultNode* addVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){ if(V1->len != V2->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Add V(%"PRIu64") by V(%"PRIu64")", V1->len, V2->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t size = V1->len; CCLErr * err = NULL; CGVector* Y = makeDeviceVector(size); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "add_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), V1->buf, V2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M+V */ CGResultNode* addMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ if(M->cols != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Add M(%"PRIu64", %"PRIu64") by V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; uint64_t vlen = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "add_mv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, V->buf, Y->buf, ccl_arg_priv(vlen, cl_ulong), NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M+M */ CGResultNode* addMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){ if((M1->rows != M2->rows) && (M1->cols != M2->cols)){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot add M(%"PRIu64", %"PRIu64") by N(%"PRIu64", %"PRIu64")", M1->rows, M1->cols, M2->rows, M2->cols); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; uint64_t size = M1->cols*M1->rows; CGMatrix* Y = makeDeviceMatrix(M1->rows, M1->cols); uint64_t len = M1->rows*M1->cols; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "add_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M1->buf, M2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Substraction * ********************* */ /* * d-d */ CGResultNode* subDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){ cg_float res = D1->value - D2->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = res; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * V-d */ CGResultNode* subVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = V->len; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sub_vd", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(D->value, cgcl_float), V->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * d-V */ CGResultNode* subDV(CGDouble* D, CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = V->len; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sub_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(D->value, cgcl_float), V->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M-d */ CGResultNode* subMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = M->rows*M->cols; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "sub_vd", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), ccl_arg_priv(D->value, cgcl_float), M->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * D-M */ CGResultNode* subDM(CGDouble* D, CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; uint64_t size = M->rows*M->cols; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "sub_dv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), ccl_arg_priv(D->value, cgcl_float), M->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * V-V */ CGResultNode* subVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){ if(V1->len != V2->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Substract V(%"PRIu64") by V(%"PRIu64")", V1->len, V2->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } uint64_t size = V1->len; CCLErr * err = NULL; CGVector* Y = makeDeviceVector(size); CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "sub_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), V1->buf, V2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M-M */ CGResultNode* subMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){ if((M1->rows != M2->rows) && (M1->cols != M2->cols)){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Substract M(%"PRIu64", %"PRIu64") by N(%"PRIu64", %"PRIu64")", M1->rows, M1->cols, M2->rows, M2->cols); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; uint64_t size = M1->cols*M1->rows; CGMatrix* Y = makeDeviceMatrix(M1->rows, M1->cols); uint64_t len = M1->rows*M1->cols; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sub_vv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M1->buf, M2->buf, Y->buf, NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M-V */ CGResultNode* subMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ if(M->rows != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Substract M(%"PRIu64", %"PRIu64") by V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; uint64_t vlen = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sub_mv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, V->buf, Y->buf, ccl_arg_priv(vlen, cl_ulong), NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * V-M */ CGResultNode* subVM(CGVector* V, CGMatrix* M, CGraph* graph, CGNode* parentNode){ if(M->rows != V->len){ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot Substract M(%"PRIu64", %"PRIu64") by V(%"PRIu64")", M->rows, M->cols, V->len); return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg); } CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; uint64_t vlen = V->len; CHECK_ERROR(err) CHECK_ERROR(err) CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sub_mv", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, V->buf, Y->buf, ccl_arg_priv(vlen, cl_ulong), NULL); CHECK_ERROR(err) //ccl_queue_destroy(queue); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Power * ********************* */ /* * d^d */ CGResultNode* powDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){ cg_float res = pow(D1->value, D2->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = res; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * V^d */ CGResultNode* powVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float value = D->value; CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "pow_vd", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(value, cgcl_float), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * M^d */ CGResultNode* powMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float value = D->value; CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "pow_vd", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), ccl_arg_priv(value, cgcl_float), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Transpose Multiplication * ********************* */ /* * M^T.v * TODO */ CGResultNode* mulMtV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){ cg_float* y = calloc(V->len, sizeof(cg_float)); CGVector* Y = calloc(1, sizeof(CGVector)); Y->len = V->len; Y->data = y; cblas_dgemv(CblasRowMajor, CblasTrans, M->rows, M->cols, 1.0, M->data, V->len, V->data, 1, 0.0, Y->data, 1); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * exp(d) */ CGResultNode* expD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = exp(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * exp(v) */ CGResultNode* expV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "exp_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * exp(M) */ CGResultNode* expM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "exp_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * log(d) */ CGResultNode* logD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = log(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * log(V) */ CGResultNode* logV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "log_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * exp(M) */ CGResultNode* logM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "log_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Sin * ********************* */ /* * sin(d) */ CGResultNode* sinD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = sin(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * sin(V) */ CGResultNode* sinV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sin_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * sin(M) */ CGResultNode* sinM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "sin_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * cos * ********************* */ /* * cos(d) */ CGResultNode* cosD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = cos(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * cos(V) */ CGResultNode* cosV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "cos_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * sin(M) */ CGResultNode* cosM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "cos_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * tan * ********************* */ /* * tan(d) */ CGResultNode* tanD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = tan(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * tan(V) */ CGResultNode* tanV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "tan_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * tan(M) */ CGResultNode* tanM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "tan_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * tanh * ********************* */ /* * tanh(d) */ CGResultNode* tanhD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float y = tanh(D->value); CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = y; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * tanh(V) */ CGResultNode* tanhV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "tanh_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * tanh(M) */ CGResultNode* tanhM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "tanh_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * Invert * ********************* */ // TODO /* * ********************* * Transpose * ********************* */ /* * D^t */ CGResultNode* transposeD(CGDouble* D, CGraph* graph, CGNode* parentNode){ CGDouble* R = calloc(1, sizeof(CGDouble)); R->value = D->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = R; return result; } /* * V^t */ CGResultNode* transposeV(CGVector* V, CGraph* graph, CGNode* parentNode){ uint64_t size = V->len; CCLErr * err = NULL; CCLEvent* evt = NULL; CGMatrix* Y = calloc(1, sizeof(CGMatrix)); Y->rows = V->len; Y->cols = 1; Y->data = NULL; Y->buf = ccl_buffer_new(ctx, CL_MEM_READ_WRITE , V->len * sizeof(cgcl_float), NULL, &err); CHECK_ERROR(err) CCLEventWaitList ewl = NULL; evt = ccl_buffer_enqueue_copy(V->buf, Y->buf, queue, 0, 0, V->len * sizeof(cgcl_float), NULL, &err); CHECK_ERROR(err) ccl_event_wait(ccl_ewl(&ewl, evt, NULL), &err); CHECK_ERROR(err) Y->loc = CG_DATALOC_DEVICE_MEM; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * M^t */ CGResultNode* transposeM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ uint64_t size = M->cols*M->rows; CGMatrix* Y = makeDeviceMatrix(M->cols, M->rows); //if(A->value != 0){ CCLErr * err = NULL; CCLBuffer * a = M->buf; CHECK_ERROR(err) CHECK_ERROR(err) cl_mem M_mem = ccl_buffer_unwrap(M->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); cl_command_queue q = ccl_queue_unwrap(queue); CLBlastDomatcopy(CLBlastLayoutRowMajor, CLBlastTransposeYes, M->rows, M->cols, 1.0f, M_mem, 0, M->cols, Y_mem, 0, Y->cols, &q, NULL); CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * ********************* * SUM * ********************* */ /* * sum(D) */ CGResultNode* sumD(CGDouble* D, CGraph* graph, CGNode* parentNode){ return makeDoubleResultNode(D->value); } /* * sum(V) */ CGResultNode* sumV(CGVector* V, CGraph* graph, CGNode* parentNode){ CGDouble* Y = makeDeviceDouble(); CCLEvent* evt = NULL; cl_command_queue q = ccl_queue_unwrap(queue); cl_mem V_mem = ccl_buffer_unwrap(V->buf); cl_mem Y_mem = ccl_buffer_unwrap(Y->buf); uint64_t size = V->len; CLBlastDsum(size, Y_mem, 0, V_mem, 0, 1, &q, NULL); evt = ccl_buffer_enqueue_read(Y->buf, queue, CL_TRUE, 0, sizeof(cl_double), &Y->value, NULL, NULL); //ccl_queue_destroy(queue); ccl_buffer_destroy(Y->buf); Y->loc = CG_DATALOC_HOST_MEM; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } /* * TODO: * sum(M, axis=axis) */ CGResultNode* sumM(CGMatrix* M, CGraph* graph, CGNode* parentNode, uint8_t axis){ CCLErr * err = NULL; CGVector* Y = NULL; CCLEvent* evt = NULL; uint64_t size = M->rows*M->cols; if(axis == 0){ uint64_t len = M->cols; Y = makeDeviceVectorZeros(len); size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "sum_matrix_rows", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) } else { uint64_t len = M->rows; Y = makeDeviceVectorZeros(len); size_t gws = size; evt = ccl_program_enqueue_kernel(prg, "sum_matrix_cols", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(size, cl_uint), ccl_arg_priv(M->cols, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } CGResultNode* max(CGNode* X, CGraph* graph){ CGResultNode* res = computeCGNode(graph, X->axop->uhs); switch(res->type){ case CGVT_DOUBLE: { cg_float y = 0; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = ((CGDouble*)res->value)->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_VECTOR: { CGVector* v = (CGVector*)res->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); uint64_t i = 1; cg_float m = v->data[0]; for (;i < v->len; i++){ if(v->data[i] > m) m = v->data[i]; } Y->value = m; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_MATRIX: { CGMatrix* M = (CGMatrix*)res->value; CGVector* V = calloc(1, sizeof(CGVector)); if(X->axop->axis == 0){ uint64_t len = M->cols; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->cols;i++){ y[i] = M->data[i]; } for(i=0;i<M->rows*M->cols;i++){ if(y[i%len] < M->data[i]) y[i%len] = M->data[i]; } } else { uint64_t len = M->rows; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows;i++){ y[i] = M->data[i*M->cols]; } for(i=0;i<M->rows*M->cols;i++){ if(y[i/M->cols] < M->data[i]) y[i/M->cols] = M->data[i]; } } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = V; return result; } } } CGResultNode* min(CGNode* X, CGraph* graph){ CGResultNode* res = computeCGNode(graph, X->axop->uhs); switch(res->type){ case CGVT_DOUBLE: { cg_float y = 0; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = ((CGDouble*)res->value)->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_VECTOR: { CGVector* v = (CGVector*)res->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); uint64_t i = 1; cg_float m = v->data[0]; for (;i < v->len; i++){ if(v->data[i] > m) m = v->data[i]; } Y->value = m; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_MATRIX: { CGMatrix* M = (CGMatrix*)res->value; CGVector* V = calloc(1, sizeof(CGVector)); if(X->axop->axis == 0){ uint64_t len = M->cols; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->cols;i++){ y[i] = M->data[i]; } for(i=0;i<M->rows*M->cols;i++){ if(y[i%len] > M->data[i]) y[i%len] = M->data[i]; } } else { uint64_t len = M->rows; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows;i++){ y[i] = M->data[i*M->cols]; } for(i=0;i<M->rows*M->cols;i++){ if(y[i/M->cols] > M->data[i]) y[i/M->cols] = M->data[i]; } } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = V; return result; } } } CGResultNode* argmax(CGNode* X, CGraph* graph){ CGResultNode* res = computeCGNode(graph, X->axop->uhs); switch(res->type){ case CGVT_DOUBLE: { cg_float y = 0; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = ((CGDouble*)res->value)->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_VECTOR: { CGVector* v = (CGVector*)res->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); uint64_t i = 1; uint64_t maxIdx = 0; for (;i < v->len; i++){ if(v->data[i] > v->data[maxIdx]) maxIdx = i; } Y->value = maxIdx; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_MATRIX: { CGMatrix* M = (CGMatrix*)res->value; CGVector* V = calloc(1, sizeof(CGVector)); if(X->axop->axis == 0){ uint64_t len = M->cols; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->cols;i++){ y[i] = i; } for(i=0;i<M->rows*M->cols;i++){ if(M->data[(uint64_t)y[i%len]] < M->data[i]) y[i%len] = i; } // transform vector representation into matrix for(i=0;i<M->cols;i++){ y[i] = ((int)y[i])/M->cols; } } else { uint64_t len = M->rows; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows;i++){ y[i] = i*M->cols; } for(i=0;i<M->rows*M->cols;i++){ if(M->data[(uint64_t)y[i/M->cols]] < M->data[i]) y[i/M->cols] = i; } // transform vector representation into matrix for(i=0;i<M->rows;i++){ y[i] = ((int)y[i])%M->cols; } } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = V; return result; } } } CGResultNode* argmin(CGNode* X, CGraph* graph){ CGResultNode* res = computeCGNode(graph, X->axop->uhs); switch(res->type){ case CGVT_DOUBLE: { cg_float y = 0; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = 0; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_VECTOR: { CGVector* v = (CGVector*)res->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); uint64_t i = 1; uint64_t minIdx = 0; for (;i < v->len; i++){ if(v->data[i] > v->data[minIdx]) minIdx = (cg_float)i; } Y->value = minIdx; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_MATRIX: { CGMatrix* M = (CGMatrix*)res->value; CGVector* V = calloc(1, sizeof(CGVector)); if(X->axop->axis == 0){ uint64_t len = M->cols; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->cols;i++){ y[i] = i; } for(i=0;i<M->rows*M->cols;i++){ if(M->data[(uint64_t)y[i%len]] > M->data[i]) y[i%len] = (cg_float)i; } // transform vector representation into matrix for(i=0;i<M->cols;i++){ y[i] = ((int)y[i])/M->cols; } } else { uint64_t len = M->rows; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows;i++){ y[i] = i*M->cols; } for(i=0;i<M->rows*M->cols;i++){ if(M->data[(uint64_t)y[i/M->cols]] > M->data[i]) y[i/M->cols] = (cg_float)i; } // transform vector representation into matrix for(i=0;i<M->rows;i++){ y[i] = ((int)y[i])%M->cols; } } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = V; return result; } } } CGResultNode* mean(CGNode* X, CGraph* graph){ CGResultNode* res = computeCGNode(graph, X->axop->uhs); switch(res->type){ case CGVT_DOUBLE: { cg_float y = 0; CGDouble* Y = calloc(1, sizeof(CGDouble)); Y->value = ((CGDouble*)res->value)->value; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_VECTOR: { CGVector* v = (CGVector*)res->value; CGDouble* Y = calloc(1, sizeof(CGDouble)); uint64_t i = 0; cg_float m = v->data[0]; for (;i < v->len; i++){ m += v->data[i]; } m /= v->len; Y->value = m; CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_DOUBLE; result->value = Y; return result; } case CGVT_MATRIX: { CGMatrix* M = (CGMatrix*)res->value; CGVector* V = calloc(1, sizeof(CGVector)); if(X->axop->axis == 0){ uint64_t len = M->cols; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows*M->cols;i++){ y[i%len] += M->data[i]; } for(i=0;i<M->cols;i++){ y[i] /= M->rows; } } else { uint64_t len = M->rows; cg_float* y = calloc(len, sizeof(cg_float)); V->data = y; V->len = len; uint64_t i = 0; for(;i<M->rows*M->cols;i++){ y[i/M->cols] += M->data[i]; } for(i=0;i<M->rows;i++){ y[i] /= M->cols; } } CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = V; return result; } } } /* * relu(d) */ CGResultNode* reluD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float val = D->value; return makeDoubleResultNode(__cg_relu(val)); } /* * relu(V) */ CGResultNode* reluV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "relu_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * relu(M) */ CGResultNode* reluM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "relu_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } /* * softplus(d) */ CGResultNode* softplusD(CGDouble* D, CGraph* graph, CGNode* parentNode){ cg_float val = D->value; return makeDoubleResultNode(__cg_softplus(val)); } /* * softplus(V) */ CGResultNode* softplusV(CGVector* V, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGVector* Y = makeDeviceVector(V->len); uint64_t len = V->len; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "softplus_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), V->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_VECTOR; result->value = Y; return result; } /* * softplus(M) */ CGResultNode* softplusM(CGMatrix* M, CGraph* graph, CGNode* parentNode){ CCLErr * err = NULL; CGMatrix* Y = makeDeviceMatrix(M->rows, M->cols); uint64_t len = M->rows*M->cols; CCLEvent* evt = NULL; size_t gws = len; evt = ccl_program_enqueue_kernel(prg, "softplus_v", queue, 1, NULL, &gws, NULL, NULL, &err, ccl_arg_priv(len, cl_uint), M->buf, Y->buf, NULL); CHECK_ERROR(err) CGResultNode* result = calloc(1, sizeof(CGResultNode)); result->type = CGVT_MATRIX; result->value = Y; return result; } #if cg_float == float #undef cblas_dcopy #undef cblas_dscal #undef cblas_dgemm #undef cblas_ddot #undef cblas_dgemv #undef cl_double #endif #if cg_float == float #undef CLBlastDcopy #undef CLBlastDscal #undef CLBlastDgemm #undef CLBlastDdot #undef CLBlastDsum #endif
{ "alphanum_fraction": 0.5552497467, "avg_line_length": 24.2312202272, "ext": "c", "hexsha": "97ae2eaa86bd08cdc8b68a564c0a438050b05c6a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z", "max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "praisethemoon/ccgraph", "max_forks_repo_path": "source/libcgraph/source/cg_clops.c", "max_issues_count": 27, "max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Enehcruon/cgraph", "max_issues_repo_path": "source/libcgraph/source/cg_clops.c", "max_line_length": 150, "max_stars_count": 8, "max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Enehcruon/cgraph", "max_stars_repo_path": "source/libcgraph/source/cg_clops.c", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z", "num_tokens": 19208, "size": 66127 }
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_complex_math.h> #include <gsl/gsl_sf_erf.h> #include <math.h> #include <stdlib.h> /* ------------------------------------------------------ */ gsl_complex gsl_complex_step_real (gsl_complex a) { gsl_complex z; if (GSL_REAL(a) < 0) { GSL_SET_COMPLEX (&z, 0, 0); } else { GSL_SET_COMPLEX (&z, 1, 0); } return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_min_real (gsl_complex a, gsl_complex b) { gsl_complex z; double min; /* just consider real parts */ min = GSL_REAL(a) < GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b); GSL_SET_COMPLEX (&z, min, 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_max_real (gsl_complex a, gsl_complex b) { gsl_complex z; double max; /* just consider real parts */ max = GSL_REAL(a) > GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b); GSL_SET_COMPLEX (&z, max, 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_carg (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_arg(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_cabs (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_abs(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_cabs2 (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_abs2(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_clogabs (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_complex_logabs(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_erf (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, gsl_sf_erf(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_arctan2 (gsl_complex a, gsl_complex b) { gsl_complex z, p; if(GSL_REAL(b) != 0.0) { z = gsl_complex_arctan(gsl_complex_div(a, b)); if(GSL_REAL(b) < 0.0){ GSL_SET_COMPLEX (&p, M_PI, 0); if(GSL_REAL(a) >= 0.0) z = gsl_complex_add(z, p); else z = gsl_complex_sub(z, p); } } else { if(GSL_REAL(a) >= 0.0) { GSL_SET_COMPLEX (&z, M_PI/2.0, 0.0); } else { GSL_SET_COMPLEX (&z, -M_PI/2.0, 0.0); } } return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_realpart (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, GSL_REAL(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_imagpart (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, GSL_IMAG(a), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_round (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, trunc(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_ceiling (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, ceil(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ gsl_complex gsl_complex_floor (gsl_complex a) { gsl_complex z; GSL_SET_COMPLEX (&z, floor(GSL_REAL(a)), 0); return z; } /* ------------------------------------------------------ */ void gsl_complex_rand_seed(long a) { srandom(a); } /* ------------------------------------------------------ */ gsl_complex gsl_complex_rand (gsl_complex a) { double r = random()/((double) RAND_MAX); return gsl_complex_rect(r, 0.0); }
{ "alphanum_fraction": 0.5280578694, "avg_line_length": 21.0230414747, "ext": "c", "hexsha": "1842fb8a2941a54e1e7ea9e7edcc47e7759c5aa3", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_path": "liboct_parser/gsl_userdef.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_path": "liboct_parser/gsl_userdef.c", "max_line_length": 69, "max_stars_count": 4, "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_path": "liboct_parser/gsl_userdef.c", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "num_tokens": 1148, "size": 4562 }