Search is not available for this dataset
text
string
meta
dict
#include <fftw.h> #include <stdio.h> #include <stdlib.h> #define N 16 main() { int i; fftw_complex in[N], out[N]; float fact; fftw_plan p,p2; printf(" stuff in data\n"); for (i=0;i<N;i++) { in[i].re=(i*i); in[i].im=1; } printf(" create plans\n"); p = fftw_create_plan(N, FFTW_FORWARD, FFTW_ESTIMATE); p2= fftw_create_plan(N, FFTW_BACKWARD, FFTW_ESTIMATE); printf(" do it\n"); fftw_one(p, in, out); for (i=0;i<N;i++) { printf("%12.4f %12.4f\n",out[i].re,out[i].im); } printf(" \n"); printf(" undo it\n"); fftw_one(p2, out,in); fact=1.0/(float)N; for (i=0;i<N;i++) { printf("%10.2f %10.2f\n",in[i].re*fact,in[i].im*fact); } printf(" clean up\n"); fftw_destroy_plan(p); fftw_destroy_plan(p2); }
{ "alphanum_fraction": 0.5520702635, "avg_line_length": 22.1388888889, "ext": "c", "hexsha": "e7449135f54e272a173fd37c062aa1b94697c671", "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": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "timkphd/examples", "max_forks_repo_path": "oneday/libs/fft/test2.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_issues_repo_issues_event_max_datetime": "2022-02-09T01:59:47.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-09T01:59:47.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "timkphd/examples", "max_issues_repo_path": "oneday/libs/fft/test2.c", "max_line_length": 59, "max_stars_count": 5, "max_stars_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "timkphd/examples", "max_stars_repo_path": "oneday/libs/fft/test2.c", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:09:47.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-01T00:29:22.000Z", "num_tokens": 278, "size": 797 }
// lasp_math_raw.c // // last-edit-by: J.A. de Jong // // Description: // Operations working on raw arrays of floating point numbers ////////////////////////////////////////////////////////////////////// #define TRACERPLUS (-5) #include "lasp_math_raw.h" #if LASP_USE_BLAS #include <cblas.h> #endif void d_elem_prod_d(d res[], const d arr1[], const d arr2[], const us size) { #if LASP_USE_BLAS == 1 #if LASP_DEBUG if(arr1 == arr2) { DBGWARN("d_elem_prod_d: Array 1 and array 2 point to the same" " memory. This results in pointer aliasing, for which" " testing is still to be done. Results might be" " unrealiable."); } #endif #if LASP_DOUBLE_PRECISION #define elem_prod_fun cblas_dsbmv #else #define elem_prod_fun cblas_ssbmv #endif /* These parameters do not matter for this specific case */ const CBLAS_ORDER mat_order= CblasColMajor; const CBLAS_UPLO uplo = CblasLower; /* Extra multiplication factor */ const d alpha = 1.0; /* void cblas_dsbmv(OPENBLAS_CONST enum CBLAS_ORDER order, */ /* OPENBLAS_CONST enum CBLAS_UPLO Uplo, */ /* OPENBLAS_CONST blasint N, */ /* OPENBLAS_CONST blasint K, */ /* OPENBLAS_CONST double alpha, */ /* OPENBLAS_CONST double *A, */ /* OPENBLAS_CONST blasint lda, */ /* OPENBLAS_CONST double *X, */ /* OPENBLAS_CONST blasint incX, */ /* OPENBLAS_CONST double beta, */ /* double *Y, */ /* OPENBLAS_CONST blasint incY); */ elem_prod_fun(mat_order, uplo, (blasint) size, 0, // Just the diagonal; 0 super-diagonal bands alpha, /* Multiplication factor alpha */ arr1, 1, /* LDA */ arr2, /* x */ 1, /* incX = 1 */ 0.0, /* Beta */ res, /* The Y matrix to write to */ 1); /* incY */ #undef elem_prod_fun #else /* No blas routines, routine is very simple, but here we * go! */ DBGWARN("Performing slow non-blas vector-vector multiplication"); for(us i=0;i<size;i++) { res[i] = arr1[i]*arr2[i]; } #endif } void c_hadamard(c res[], const c arr1[], const c arr2[], const us size) { fsTRACE(15); uVARTRACE(15,size); dbgassert(arr1 && arr2 && res,NULLPTRDEREF); #if LASP_USE_BLAS == 1 #if LASP_DEBUG if(arr1 == arr2) { DBGWARN("c_elem_prod_c: Array 1 and array 2 point to the same" " memory. This results in pointer aliasing, for which" " testing is still to be done. Results might be" " unrealiable."); } #endif /* LASP_DEBUG */ #if LASP_DOUBLE_PRECISION #define elem_prod_fun cblas_zgbmv #else #define elem_prod_fun cblas_cgbmv #endif c alpha = 1.0; c beta = 0.0; TRACE(15,"Calling " annestr(elem_prod_fun)); uVARTRACE(15,size); elem_prod_fun(CblasColMajor, CblasNoTrans, (blasint) size, /* M: Number of rows */ (blasint) size, /* B: Number of columns */ 0, /* KL: Number of sub-diagonals */ 0, /* KU: Number of super-diagonals */ (d*) &alpha, /* Multiplication factor */ (d*) arr2, /* A */ 1, /* LDA */ (d*) arr1, /* x */ 1, /* incX = 1 */ (d*) &beta, (d*) res, /* The Y matrix to write to */ 1); /* incY (increment in res) */ #undef elem_prod_fun #else /* No blas routines, routine is very simple, but here we * go! */ DBGWARN("Performing slower non-blas vector-vector multiplication"); for(us i=0;i<size;i++) { res[i] = arr1[i]*arr2[i]; } #endif feTRACE(15); } //////////////////////////////////////////////////////////////////////
{ "alphanum_fraction": 0.4711321606, "avg_line_length": 30.1632653061, "ext": "c", "hexsha": "196895a5be32c4d5be4870ab0aa95e084a3927a7", "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": "7cc77b073a91eb7470b449604544d9f57faf32e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "asceenl/lasp", "max_forks_repo_path": "lasp/c/lasp_math_raw.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7cc77b073a91eb7470b449604544d9f57faf32e9", "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": "asceenl/lasp", "max_issues_repo_path": "lasp/c/lasp_math_raw.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "7cc77b073a91eb7470b449604544d9f57faf32e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "asceenl/lasp", "max_stars_repo_path": "lasp/c/lasp_math_raw.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1093, "size": 4434 }
/** * @file modalbeamformer.h * @brief Beamforming in the spherical harmonics domain. * @author Kenichi Kumatani */ #ifndef MODALBEAMFORMER_H #define MODALBEAMFORMER_H #include <stdio.h> #include <assert.h> #include <float.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_fft_complex.h> #include <common/refcount.h> #include "common/jexception.h" #include "stream/stream.h" //#include "stream/pyStream.h" #include "beamformer/spectralinfoarray.h" #include "modulated/modulated.h" #include "beamformer/beamformer.h" // ----- definition for class `ModeAmplitudeCalculator' ----- // gsl_complex modeAmplitude(int order, double ka); class ModeAmplitudeCalculator { public: ModeAmplitudeCalculator(int order, float minKa=0.01, float maxKa=20, float wid=0.01); ~ModeAmplitudeCalculator(); gsl_vector_complex *get() const { return mode_amplitude_; } private: gsl_vector_complex *mode_amplitude_; float minKa_; float maxKa_; float wid_; }; typedef refcount_ptr<ModeAmplitudeCalculator> ModeAmplitudeCalculatorPtr; // ----- definition for class `EigenBeamformer' ----- // /** @class EigenBeamformer @brief This beamformer is implemented based on Meyer and Elko's ICASSP paper. In Boaz Rafaely's paper, this method is referred to as the phase-mode beamformer @usage 1) construct this object, bf = EigenBeamformer(...) 2) set the radious of the spherical array with bf.set_eigenmike_geometry() or bf.set_array_geometry(..). 3) set the look direction with bf.set_look_direction(..) 4) process each block with bf.next() until it hits the end */ class EigenBeamformer : public SubbandDS { public: EigenBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "EigenBeamformer"); ~EigenBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); virtual unsigned dim() const { return dim_;} void set_sigma2(float sigma2){ sigma2_ = sigma2; } void set_weight_gain(float wgain){ wgain_ = wgain; } void set_eigenmike_geometry(); void set_array_geometry(double a, gsl_vector *theta_s, gsl_vector *phi_s); virtual void set_look_direction(double theta, double phi); const gsl_matrix_complex *mode_amplitudes(); const gsl_vector *array_geometry(int type); // type==0 -> theta, type==1 -> phi virtual gsl_matrix *beampattern(unsigned fbinX, double theta = 0, double phi = 0, double minTheta=-M_PI, double maxTheta=M_PI, double minPhi=-M_PI, double maxPhi=M_PI, double widthTheta=0.1, double widthPhi=0.1 ); /** @brief obtain the spherical transformation coefficients at each frame @return spherical harmonics transformation coefficients at the current frame */ virtual SnapShotArrayPtr snapshot_array() const { return(st_snapshot_array_); } virtual SnapShotArrayPtr snapshot_array2() const { return(snapshot_array_); } const gsl_matrix_complex *blocking_matrix(unsigned fbinX, unsigned unitX=0 ) const { return (bfweight_vec_[unitX]->B())[fbinX]; } #ifdef ENABLE_LEGACY_BTK_API void setSigma2(float sigma2){ set_sigma2(sigma2); } void setWeightGain(float wgain){ set_weight_gain(wgain); } void setEigenMikeGeometry(){ set_eigenmike_geometry(); } void setArrayGeometry(double a, gsl_vector *theta_s, gsl_vector *phi_s){ set_array_geometry(a, theta_s, phi_s); } virtual void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); } const gsl_matrix_complex *getModeAmplitudes(){ return mode_amplitudes(); } const gsl_vector *getArrayGeometry(int type){ return array_geometry(type);} virtual gsl_matrix *getBeamPattern( unsigned fbinX, double theta = 0, double phi = 0, double minTheta=-M_PI, double maxTheta=M_PI, double minPhi=-M_PI, double maxPhi=M_PI, double widthTheta=0.1, double widthPhi=0.1 ){ return beampattern(fbinX, theta, phi, minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi); } virtual SnapShotArrayPtr getSnapShotArray(){ return snapshot_array(); } virtual SnapShotArrayPtr getSnapShotArray2(){ return snapshot_array2(); } const gsl_matrix_complex *getBlockingMatrix(unsigned fbinX, unsigned unitX=0){ return blocking_matrix(fbinX, unitX); } #endif protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool calc_spherical_harmonics_at_each_position_( gsl_vector *theta_s, gsl_vector *phi_s ); // need to be tested!! virtual bool calc_steering_unit_( int unitX=0, bool isGSC=false ); virtual bool alloc_steering_unit_( int unitN=1 ); void alloc_image_( bool flag=true ); bool calc_mode_amplitudes_(); unsigned samplerate_; unsigned NC_; unsigned maxOrder_; unsigned dim_; // the number of the spherical harmonics transformation coefficients bool weights_normalized_; gsl_matrix_complex *mode_mplitudes_; // [maxOrder_] the mode amplitudes. gsl_vector_complex *F_; // Spherical Transform coefficients [dim_] gsl_vector_complex **sh_s_; // Conjugate of spherical harmonics at each sensor position [dim_][nChan]: Y_n^{m*} SnapShotArrayPtr st_snapshot_array_; // for compatibility with a post-filtering object double theta_; // look direction double phi_; // look direction double a_; // the radius of the rigid sphere. gsl_vector *theta_s_; // sensor positions gsl_vector *phi_s_; // sensor positions gsl_matrix *beampattern_; gsl_vector *WNG_; // white noise gain float wgain_; // float sigma2_; // dialog loading }; typedef Inherit<EigenBeamformer, SubbandDSPtr> EigenBeamformerPtr; // ----- definition for class DOAEstimatorSRPEB' ----- // /** @class DOAEstimatorSRPEB @brief estimate the direction of arrival based on the maximum steered response power @usage 1) construct this object, doaEstimator = DOAEstimatorSRPEB(...) 2) set the radious of the spherical array, doaEstimator.set_eigenmike_geometry() or doaEstimator.set_array_geometry(..). 3) process each block, doaEstimator.next() 4) get the N-best hypotheses at the current instantaneous frame through doaEstimator.nbest_doas() 5) do doaEstimator.getFinalNBestHypotheses() after a static segment is processed. You can then obtain the averaged N-best hypotheses of the static segment with doaEstimator.nbest_doas(). */ class DOAEstimatorSRPEB : public DOAEstimatorSRPBase, public EigenBeamformer { public: DOAEstimatorSRPEB( unsigned nBest, unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "DirectionEstimatorSRPBase"); ~DOAEstimatorSRPEB(); const gsl_vector_complex* next(int frame_no = -5); void reset(); protected: virtual void calc_steering_unit_table_(); virtual float calc_response_power_( unsigned uttX ); }; typedef Inherit<DOAEstimatorSRPEB, EigenBeamformerPtr> DOAEstimatorSRPEBPtr; // ----- definition for class `SphericalDSBeamformer' ----- // /** @class SphericalDSBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note this implementation is based on Boaz Rafaely's letter, "Phase-Mode versus Delay-and-Sum Spherical Microphone Array", IEEE Signal Processing Letters, vol. 12, Oct. 2005. */ class SphericalDSBeamformer : public EigenBeamformer { public: SphericalDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "SphericalDSBeamformer"); ~SphericalDSBeamformer(); virtual gsl_vector *calc_wng(); #ifdef ENABLE_LEGACY_BTK_API virtual gsl_vector *calcWNG(){ return calc_wng(); } #endif protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool calc_spherical_harmonics_at_each_position_( gsl_vector *theta_s, gsl_vector *phi_s ); }; typedef Inherit<SphericalDSBeamformer, EigenBeamformerPtr> SphericalDSBeamformerPtr; // ----- definition for class `DualSphericalDSBeamformer' ----- // /** @class DualSphericalDSBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note In addition to SphericalDSBeamformer, this class has an object of the *normal* D&S beamformer */ class DualSphericalDSBeamformer : public SphericalDSBeamformer { public: DualSphericalDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "SphericalDSBeamformer"); ~DualSphericalDSBeamformer(); virtual SnapShotArrayPtr snapshot_array() const { return snapshot_array_; } virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const { return bfweight_vec2_[srcX]; } #ifdef ENABLE_LEGACY_BTK_API virtual SnapShotArrayPtr getSnapShotArray(){ return snapshot_array(); } #endif protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool alloc_steering_unit_( int unitN=1 ); vector<BeamformerWeights *> bfweight_vec2_; // weights of a normal D&S beamformer. }; typedef Inherit<DualSphericalDSBeamformer, SphericalDSBeamformerPtr> DualSphericalDSBeamformerPtr; // ----- definition for class DOAEstimatorSRPPSphDSB' ----- // class DOAEstimatorSRPSphDSB : public DOAEstimatorSRPBase, public SphericalDSBeamformer { public: DOAEstimatorSRPSphDSB( unsigned nBest, unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "DOAEstimatorSRPPSphDSB" ); ~DOAEstimatorSRPSphDSB(); const gsl_vector_complex* next(int frame_no = -5); void reset(); protected: virtual void calc_steering_unit_table_(); virtual float calc_response_power_( unsigned uttX ); }; typedef Inherit<DOAEstimatorSRPSphDSB, SphericalDSBeamformerPtr> DOAEstimatorSRPSphDSBPtr; // ----- definition for class `SphericalHWNCBeamformer' ----- // /** @class SphericalHWNCBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() */ class SphericalHWNCBeamformer : public EigenBeamformer { public: SphericalHWNCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = "SphericalHWNCBeamformer"); ~SphericalHWNCBeamformer(); virtual gsl_vector *calc_wng(); virtual void set_wng( double ratio){ ratio_=ratio; calc_wng();} #ifdef ENABLE_LEGACY_BTK_API gsl_vector *calcWNG(){ return calc_wng(); } void setWNG( double ratio){ set_wng(ratio);} #endif protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); protected: float ratio_; }; typedef Inherit<SphericalHWNCBeamformer, EigenBeamformerPtr> SphericalHWNCBeamformerPtr; // ----- definition for class `SphericalGSCBeamformer' ----- // /** @class SphericalGSCBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note this implementation is based on Boaz Rafaely's letter, "Phase-Mode versus Delay-and-Sum Spherical Microphone Array", IEEE Signal Processing Letters, vol. 12, Oct. 2005. */ class SphericalGSCBeamformer : public SphericalDSBeamformer { public: SphericalGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "SphericalGSCBeamformer"); ~SphericalGSCBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); void set_look_direction(double theta, double phi); void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight); #ifdef ENABLE_LEGACY_BTK_API void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); } void setActiveWeights_f( unsigned fbinX, const gsl_vector* packedWeight ){ set_active_weights_f(fbinX, packedWeight); } #endif }; typedef Inherit<SphericalGSCBeamformer, SphericalDSBeamformerPtr> SphericalGSCBeamformerPtr; // ----- definition for class `SphericalHWNCGSCBeamformer' ----- // /** @class SphericalHWNCGSCBeamformer @usage 1) construct this object, mb = SphericalHWNCGSCBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() */ class SphericalHWNCGSCBeamformer : public SphericalHWNCBeamformer { public: SphericalHWNCGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = "SphericalHWNCGSCBeamformer"); ~SphericalHWNCGSCBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); void set_look_direction(double theta, double phi); void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight); #ifdef ENABLE_LEGACY_BTK_API void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); } void setActiveWeights_f( unsigned fbinX, const gsl_vector* packedWeight ){ set_active_weights_f(fbinX, packedWeight); } #endif }; typedef Inherit<SphericalHWNCGSCBeamformer, SphericalHWNCBeamformerPtr> SphericalHWNCGSCBeamformerPtr; // ----- definition for class `DualSphericalGSCBeamformer' ----- // /** @class DualSphericalGSCBeamformer @usage 1) construct this object, mb = DualSphericalGSCBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note In addition to DualSphericalGSCBeamformer, this class has an object of the *normal* D&S beamformer */ class DualSphericalGSCBeamformer : public SphericalGSCBeamformer { public: DualSphericalGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "DualSphericalGSCBeamformer"); ~DualSphericalGSCBeamformer(); virtual SnapShotArrayPtr snapshot_array() const {return(snapshot_array_);} virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const { return bfweight_vec2_[srcX]; } #ifdef ENABLE_LEGACY_BTK_API virtual SnapShotArrayPtr getSnapShotArray(){return(snapshot_array_);} #endif protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool alloc_steering_unit_( int unitN=1 ); vector<BeamformerWeights *> bfweight_vec2_; // weights of a normal D&S beamformer. }; typedef Inherit<DualSphericalGSCBeamformer, SphericalGSCBeamformerPtr> DualSphericalGSCBeamformerPtr; // ----- definition for class `SphericalMOENBeamformer' ----- // /** @class SphericalGSCBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note this implementation is based on Z. Li and R. Duraiswami's letter, "Flexible and Optimal Design of Spherical Microphone Arrays for Beamforming", IEEE Trans. SAP. */ class SphericalMOENBeamformer : public SphericalDSBeamformer { public: SphericalMOENBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "SphericalMOENBeamformer"); ~SphericalMOENBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); void fix_terms(bool flag){ is_term_fixed_ = flag; } void set_diagonal_looading(unsigned fbinX, float diagonalWeight); virtual SnapShotArrayPtr snapshot_array() const { return snapshot_array_; } virtual gsl_matrix *beampattern(unsigned fbinX, double theta = 0, double phi = 0, double minTheta=-M_PI, double maxTheta=M_PI, double minPhi=-M_PI, double maxPhi=M_PI, double widthTheta=0.1, double widthPhi=0.1 ); #ifdef ENABLE_LEGACY_BTK_API void fixTerms( bool flag ){ fix_terms(flag); } void setLevelOfDiagonalLoading( unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); } virtual gsl_matrix *getBeamPattern( unsigned fbinX, double theta = 0, double phi = 0, double minTheta=-M_PI, double maxTheta=M_PI, double minPhi=-M_PI, double maxPhi=M_PI, double widthTheta=0.1, double widthPhi=0.1 ){ return beampattern(fbinX, theta, phi, minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi); } #endif protected: virtual bool alloc_steering_unit_( int unitN=1 ); virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); bool calc_moen_weights_( unsigned fbinX, gsl_vector_complex *weights, double dThreshold = 1.0E-8, bool calcInverseMatrix = true, unsigned unitX=0 ); private: // maxOrder_ == Neff in the Li's paper. unsigned bf_order_; // N in the Li's paper. float CN_; gsl_matrix_complex** A_; /* A_[fftLen2+1][dim_][nChan]; Coeffcients of the spherical harmonics expansion; See Eq. (31) & (32) */ gsl_matrix_complex** fixedW_; /* _fixedW[fftLen2+1][nChan][dim_]; [ A^H A + l^2 I ]^{-1} A^H */ gsl_vector_complex** BN_; // _BN[fftLen2+1][dim_] float* diagonal_weights_; bool is_term_fixed_; float dthreshold_; }; typedef Inherit<SphericalMOENBeamformer, SphericalDSBeamformerPtr> SphericalMOENBeamformerPtr; // ----- definition for class `SphericalSpatialDSBeamformer' ----- // /** @class SphericalSpatialDSBeamformer @usage 1) construct this object, mb = SphericalSpatialDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() @note this implementation is based on Boaz Rafaely's letter, "Phase-Mode versus Delay-and-Sum Spherical Microphone Array", IEEE Signal Processing Letters, vol. 12, Oct. 2005. */ class SphericalSpatialDSBeamformer : public SphericalDSBeamformer { public: SphericalSpatialDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = "SphericalSpatialDSBeamformer"); ~SphericalSpatialDSBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool alloc_steering_unit_( int unitN = 1 ); virtual bool calc_steering_unit_( int unitX = 0, bool isGSC = false ); }; typedef Inherit<SphericalSpatialDSBeamformer, SphericalDSBeamformerPtr> SphericalSpatialDSBeamformerPtr; // ----- definition for class `SphericalSpatialHWNCBeamformer' ----- // /** @class SphericalSpatialHWNCBeamformer @usage 1) construct this object, mb = SphericalDSBeamformer(...) 2) set the radious of the spherical array mb.set_array_geometry(..) or 3) set the look direction mb.set_look_direction() 4) process each block mb.next() */ class SphericalSpatialHWNCBeamformer : public SphericalHWNCBeamformer { public: SphericalSpatialHWNCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = "SphericalHWNCBeamformer"); ~SphericalSpatialHWNCBeamformer(); virtual const gsl_vector_complex* next(int frame_no = -5); protected: virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights ); virtual bool alloc_steering_unit_( int unitN = 1 ); virtual bool calc_steering_unit_( int unitX = 0, bool isGSC = false ); private: gsl_matrix_complex *calc_diffuse_noise_model_( unsigned fbinX ); gsl_matrix_complex **SigmaSI_; // SigmaSI_[fftLen/2+1][chanN] double dthreshold_; }; typedef Inherit<SphericalSpatialHWNCBeamformer, SphericalHWNCBeamformerPtr> SphericalSpatialHWNCBeamformerPtr; #endif
{ "alphanum_fraction": 0.7449180328, "avg_line_length": 42.0275590551, "ext": "h", "hexsha": "45e5149a732c0d925f3d287dfc18b5730f41c166", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_line_length": 233, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 5481, "size": 21350 }
/** * Created: Wed Aug 31 20:27:45 CST 2016 * @author: Lie Yan * @email: robin.lie.yan@outlook.com * */ #pragma once #include <gsl.h> namespace formulae { namespace interm { enum class ItemTag : uint8_t { INoad, IPen, ISpace, IStyle }; struct Item { virtual ItemTag tag() const = 0; virtual gsl::owner<Item *> clone() const = 0; }; class ItemRef { public: ItemRef(gsl::owner<Item *> itemPtr) : _itemPtr(itemPtr) {} ItemRef(const ItemRef &rhs) { _itemPtr.reset(rhs._itemPtr->clone()); } ItemRef &operator=(const ItemRef &rhs) { _itemPtr.reset(rhs._itemPtr->clone()); return *this; } ItemRef(ItemRef &&rhs) = default; ItemRef &operator=(ItemRef &&rhs) = default; virtual ~ItemRef() = default; /* -------------------------------------------------------- */ ItemTag tag() const { return _itemPtr->tag(); } template<typename T> T& as() const { return *dynamic_cast<T*>(_itemPtr.get()); } private: std::unique_ptr<Item> _itemPtr; }; using ilist_t = list_t<ItemRef>; } }
{ "alphanum_fraction": 0.6161417323, "avg_line_length": 21.1666666667, "ext": "h", "hexsha": "3f9441e687ee82181c2b499de3c199b1b0694493", "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": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "robin33n/formulae-cxx", "max_forks_repo_path": "include/interm/types/IL0_Item.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "robin33n/formulae-cxx", "max_issues_repo_path": "include/interm/types/IL0_Item.h", "max_line_length": 72, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "robin33n/formulae-cxx", "max_stars_repo_path": "include/interm/types/IL0_Item.h", "max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z", "num_tokens": 293, "size": 1016 }
// Copyright @ 2012 Zhi Qiu and Chun Shen // Ver 2.1 // Note the version used in iSS is slightly slower than the one // used in iS, do not mix them unless necessary. #ifndef SRC_EMISSIONFUNCTION_H_ #define SRC_EMISSIONFUNCTION_H_ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <string> #include <vector> #include <array> #include <memory> #include "Table.h" #include "TableFunction.h" #include "ParameterReader.h" #include "particle_decay.h" #include "data_struct.h" #include "data_struct.h" #include "Random.h" #include "pretty_ostream.h" class EmissionFunctionArray { private: int hydro_mode; // switch for (2+1)-d or (3+1)-d hypersurface int flag_PCE_; int flag_restrict_deltaf; double deltaf_max_ratio; pretty_ostream messager; const std::string path_; const std::string table_path_; const AfterburnerType afterburner_type_; std::shared_ptr<RandomUtil::Random> ran_gen_ptr; int MC_sampling; int number_of_repeated_sampling; int local_charge_conservation; Table *pT_tab, *phi_tab, *y_minus_eta_tab; int pT_tab_length, phi_tab_length; // the y_minus_eta_min_index holds the index // to the smallest positive y-eta_s value int y_minus_eta_tab_length, y_minus_eta_min_index; // true if y_minus_eta_tab has only positive part bool positive_y_minus_eta_table_only; ParameterReader *paraRdr; // used to pass-in parameters int USE_OSCAR_FORMAT; int USE_GZIP_FORMAT; int INCLUDE_DELTAF, INCLUDE_BULK_DELTAF, INCLUDE_DIFFUSION_DELTAF; int bulk_deltaf_kind; int turn_on_rhob; Table *dN_pTdpTdphidy; // dN / (pt dpt dphi dy) // store the largest element when summing over xt and eta // to get dN / (pt dpt dphi dy); used during sampling. Table *dN_pTdpTdphidy_max; double **dN_dxtdetady; // dN / (d^2x_t deta dy) (correction: and dtau) // dN / (d^2x_t deta dy) is the (weighted) sum of all elements of // the [pT_tab_length][phi_tab_length]-sized dN/dall matrix; // this array records the maximum value of this dN/dall matrix, // for each eta and FO-cell. double **dN_dxtdetady_pT_max; double **dN_dxtdy_4all; // dN / (dxt dy) for all particles // dN/(dxt dy) for one particle species std::vector<double> dN_dxtdy_for_one_particle_species; int number_of_chosen_particles; // used in spectra and flow calculations; // it has length Nparticle, 0 means miss, 1 means include std::vector<int> chosen_particles_01_table; // 0/1: Particles with similar mass and chemical potentials // will be sampled using the same dN/(dxt deta dy) matrix int grouping_particles; // Usable only when grouping_particles is 1. // If two particles have mass and chemical potentials // close within this relative tolerance, they are considered to be // identical and will be sampled successively without regenerating // the dN / (dxt deta dy) matrix for efficiency. double mc_grouping_tolerance; // store particle index; // the sampling process follows the order specified by this table std::vector<int> chosen_particles_sampling_table; // store chosen particle monte carlo number that are not found in pdg.dat std::vector<int> unidentifiedPid_table; // list for information for all particles int Nparticles; std::vector<particle_info> particles; // list for information for all fluid cells long FO_length; const std::vector<FO_surf> &FOsurf_ptr; // store the last particle index being used by calculate_dNArrays function int last_particle_idx; double **trig_phi_table, **hypertrig_y_minus_eta_table; inline long determine_number_to_sample( double dN, int model=1, double para1=0); const gsl_rng_type *gsl_type_random_number; gsl_rng *gsl_random_r; bool particles_are_the_same(int, int); //long *sorted_FZ; //array for bulk delta f coefficients Table *bulkdf_coeff; // table parameter for diffusion deltaf coefficient int deltaf_qmu_coeff_table_length_T; int deltaf_qmu_coeff_table_length_mu; double delta_qmu_coeff_table_T0, delta_qmu_coeff_table_mu0; double delta_qmu_coeff_table_dT, delta_qmu_coeff_table_dmu; double **deltaf_qmu_coeff_tb; // kappa_B [1/fm^3] // arrays to speed up computing particle yield double sf_dx, sf_x_min, sf_x_max; int sf_tb_length; int sf_expint_truncate_order; double** sf_bessel_Kn; double** sf_expint_En; double lambert_x_min, lambert_x_max, lambert_dx; std::vector<double> lambert_W; int flag_output_samples_into_files; int flag_store_samples_in_memory; //! particle decay int flag_perform_decays; particle_decay *decayer_ptr; public: EmissionFunctionArray(std::shared_ptr<RandomUtil::Random> ran_gen, Table* chosen_particle, Table* pt_tab_in, Table* phi_tab_in, Table* eta_tab_in, std::vector<particle_info> particles_in, const std::vector<FO_surf> &FOsurf_ptr_in, int flag_PCE_in, ParameterReader* paraRdr_in, std::string path_in, std::string table_path, AfterburnerType afterburner_type); ~EmissionFunctionArray(); std::vector< std::vector<iSS_Hadron>* >* Hadron_list; void initialize_special_function_arrays(); double get_special_function_K1(double arg); double get_special_function_K2(double arg); void get_special_function_En(double arg, std::vector<double> &results); double get_special_function_lambertW(double arg); void calculate_dNArrays(int); void calculate_dN_dxtdetady(int); void calculate_dN_pTdpTdphidy(int); void write_dN_pTdpTdphidy_toFile(); std::string dN_pTdpTdphidy_filename; // where to save void write_dN_dxtdetady_toFile(); std::string dN_dxtdetady_filename; void calculate_flows(int to_order, std::string flow_diff_filename, std::string flow_inte_filename); std::string flow_differential_filename_old, flow_integrated_filename_old; std::string flow_differential_filename, flow_integrated_filename; void calculate_dN_pTdpTdphidy_and_flows_4all_old_output( int perform_sampling = 0); void calculate_dN_pTdpTdphidy_and_flows_4all(int perform_sampling = 0); void calculate_dN_dxtdetady_and_sample_4all(); void shell(); // it all starts here... void combine_samples_to_OSCAR(); std::string OSCAR_header_filename, OSCAR_output_filename; void combine_samples_to_gzip_file(); // Sample files // where samples, its control informations, and its "format file" // are stored; // the first two can contain a "%d" string to generate multiple files std::string samples_format_filename; // First sampling method void sample_using_dN_dxtdetady_smooth_pT_phi(); void calculate_dN_dtau_using_dN_dxtdetady( double tau0 = 0, double dtau = 0.5, double tau_max = 17); void calculate_dN_dphi_using_dN_pTdpTdphidy(); void calculate_dN_deta_using_dN_dxtdetady(); void calculate_dN_dxt_using_dN_dxtdetady(); void calculate_dN_dx_using_dN_dxtdetady( double x_min, double x_max, double dx); // Second sampling method void calculate_dN_analytic(const particle_info* particle, double mu, double Temperature, std::array<double, 5> &results); // the following variables need to be set first in order to // call this function void calculate_dN_dxtdy_4all_particles(); void calculate_dN_dxtdy_for_one_particle_species(const int particle_idx); double calculate_total_FZ_energy_flux(); // to be used after calculate_dN_dxtdy_4all_particles void sample_using_dN_dxtdy_4all_particles_conventional(); // Third sampling method void sample_using_dN_pTdpTdphidy(); Table pT_tab4Sampling, phi_tab4Sampling; int pT_tab4Sampling_length, phi_tab4Sampling_length; double** trig_phi_tab4Sampling; void getbulkvisCoefficients(double Tdec, std::array<double, 3> &bulkvisCoefficients); void load_deltaf_qmu_coeff_table(std::string filename); double get_deltaf_qmu_coeff(double T, double muB); void check_samples_in_memory(); int get_number_of_sampled_events() {return(Hadron_list->size());}; int get_number_of_particles(int iev) { return((*Hadron_list)[iev]->size()); }; iSS_Hadron get_hadron(int iev, int ipart) { return((*(*Hadron_list)[iev])[ipart]); }; std::vector<iSS_Hadron>* get_hadron_list_iev(const int iev) { return(Hadron_list->at(iev)); } void perform_resonance_feed_down( std::vector< std::vector<iSS_Hadron>* >* input_particle_list); int compute_number_of_sampling_needed(int number_of_particles_needed); double estimate_ideal_maximum( int sign, double mass, double Tdec, double mu, double f0_mass, TableFunction &z_exp_m_z); double estimate_shear_viscous_maximum( int sign, double mass, double Tdec, double mu, double f0_mass, TableFunction &z_exp_m_z, double pi_size); double estimate_diffusion_maximum( int sign, int baryon, double mass, double Tdec, double mu, double f0_mass, TableFunction &z_exp_m_z, double prefactor_qmu, double guess_ideal, double q_size); double get_deltaf_bulk( double mass, double pdotu, double bulkPi, double Tdec, int sign, double f0, const std::array<double, 3> bulkvisCoefficients); int sample_momemtum_from_a_fluid_cell( const double mass, const double degen, const int sign, const int baryon, const int strange, const int charge, const double pT_to, const double y_minus_eta_s_range, const double maximum_guess, const FO_surf *surf, const std::array<double, 3> bulkvisCoefficients, const double deltaf_qmu_coeff, double &pT, double &phi, double &y_minus_eta_s); double estimate_maximum( const FO_surf *surf, const int real_particle_idx, const double mass, const double sign, const double degen, const int baryon, const int strange, const int charge, TableFunction &z_exp_m_z, const std::array<double, 3> bulkvisCoefficients, const double deltaf_qmu_coeff); std::string add_one_sampled_particle( const int repeated_sampling_idx, const unsigned long FO_idx, const FO_surf *surf, const int particle_monval, const double mass, const double pT, const double phi, const double y_minus_eta_s, const double eta_s); }; #endif // SRC_EMISSIONFUNCTION_H_ /*---------------------------------------------------------------------- Change log: See changelog.txt. ----------------------------------------------------------------------*/
{ "alphanum_fraction": 0.6986883763, "avg_line_length": 37.8595890411, "ext": "h", "hexsha": "9e16a606f80d86a8e594df63058e2898d563d846", "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": "9391b8830e385c0f5f1600a1cfd1ad355ea582c5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "doliinychenko/iSS", "max_forks_repo_path": "src/emissionfunction.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9391b8830e385c0f5f1600a1cfd1ad355ea582c5", "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": "doliinychenko/iSS", "max_issues_repo_path": "src/emissionfunction.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "9391b8830e385c0f5f1600a1cfd1ad355ea582c5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "doliinychenko/iSS", "max_stars_repo_path": "src/emissionfunction.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2761, "size": 11055 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------ // Intrinsics.h //------------------------------------------------------------------------------ #pragma once #include <arcana/analysis/introspector.h> #include <gsl/gsl> #include <array> namespace mage { class Intrinsics { public: Intrinsics() = default; Intrinsics(gsl::span<const float, 4> intrinsicsCxCyFxFy, uint32_t imageWidth, uint32_t imageHeight); Intrinsics(float cx, float cy, float fx, float fy, uint32_t imageWidth, uint32_t imageHeight); // cx, cy, fx, fy gsl::span<const float, 4> GetCoefficients() const { return m_coefficients; } std::array<float, 4> GetNormalizedCoefficients() const; float GetCx() const { return m_coefficients[0]; } //principle point pixels float GetCy() const { return m_coefficients[1]; } //principle point pixels float GetFx() const { return m_coefficients[2]; } //focal length pixels float GetFy() const { return m_coefficients[3]; } //focal length pixels void SetCx(float cx) { m_coefficients[0] = cx; } //principle point pixels void SetCy(float cy) { m_coefficients[1] = cy; } //principle point pixels void SetFx(float fx) { m_coefficients[2] = fx; } //focal length pixels void SetFy(float fy) { m_coefficients[3] = fy; } //focal length pixels uint32_t GetCalibrationWidth() const { return m_widthPixels; } uint32_t GetCalibrationHeight() const { return m_heightPixels; } private: std::array<float, 4> m_coefficients{}; // cx, cy, fx, fy in pixels uint32_t m_widthPixels{}; //widht/height calibration was performed for uint32_t m_heightPixels{}; }; template<typename ArchiveT> void introspect_object(mira::introspector<ArchiveT>& intro, const Intrinsics& intrin) { intro( cereal::make_nvp("Coefficients", intrin.GetCoefficients()) ); } }
{ "alphanum_fraction": 0.6080038573, "avg_line_length": 37.0357142857, "ext": "h", "hexsha": "40b9cfb2bda57a3c8f1b939eac85eb8ab4620f55", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_line_length": 108, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Data/Intrinsics.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 511, "size": 2074 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpMisc.h> #include <gbpRNG.h> #include <gsl/gsl_linalg.h> void add_gaussian_noise(double *data, int n_data, int *seed, double sigma, double *covariance) { int i_data; int j_data; double * data_temp; RNG_info *RNG; // Initialize RNG RNG = (RNG_info *)SID_malloc(sizeof(RNG_info)); init_RNG(seed, RNG, RNG_DEFAULT); // Generate a random displacement vector gsl_vector *b; b = gsl_vector_calloc(n_data); for(i_data = 0; i_data < n_data; i_data++) gsl_vector_set(b, i_data, sigma * random_gaussian(RNG)); // Use the rotated covariance matrix (if available) if(covariance != NULL) { // Perform Cholesky Decomposition gsl_matrix *m; m = gsl_matrix_calloc(n_data, n_data); for(i_data = 0; i_data < n_data; i_data++) for(j_data = 0; j_data < n_data; j_data++) gsl_matrix_set(m, i_data, j_data, covariance[i_data * n_data + j_data]); gsl_linalg_cholesky_decomp(m); for(i_data = 0; i_data < n_data; i_data++) for(j_data = i_data + 1; j_data < n_data; j_data++) gsl_matrix_set(m, i_data, j_data, 0.); for(i_data = 0; i_data < n_data; i_data++) { for(j_data = 0; j_data < n_data; j_data++) data[i_data] += gsl_matrix_get(m, i_data, j_data) * gsl_vector_get(b, j_data); } gsl_matrix_free(m); } else { for(j_data = 0; j_data < n_data; j_data++) data[j_data] += gsl_vector_get(b, j_data); } // Clean-up free_RNG(RNG); SID_free(SID_FARG RNG); gsl_vector_free(b); }
{ "alphanum_fraction": 0.604610951, "avg_line_length": 32.7358490566, "ext": "c", "hexsha": "83798b8d7de7259404bcc40fd88af6ecdbb19ecb", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpRNG/add_gaussian_noise.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpRNG/add_gaussian_noise.c", "max_line_length": 96, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpRNG/add_gaussian_noise.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 495, "size": 1735 }
// // Engine.hpp // PretendToWork // // Created by tqtifnypmb on 14/12/2017. // Copyright © 2017 tqtifnypmb. All rights reserved. // #pragma once #include "../rope/Rope.h" #include "../types.h" #include "Revision.h" #include <gsl/gsl> #include <vector> #include <map> namespace brick { class Engine { public: using DeltaList = std::vector<Revision>; Engine(size_t authorId, gsl::not_null<Rope*> rope); template <class Converter> void insert(gsl::span<const char> bytes, size_t pos); void insert(const detail::CodePointList& cplist, size_t pos); void erase(const Range& range); std::pair<DeltaList, DeltaList> sync(Engine& other); void fastForward(const std::vector<Revision>& revs); const std::vector<Revision>& revisions() const { return revisions_; } std::vector<Revision>& revisions() { return revisions_; } size_t authorId() const { return authorId_; } size_t nextRevId() { return revId_++; } private: Revision delta(const Revision& history, Revision& rev); std::vector<Revision> delta(Revision& rev); void appendRevision(Revision rev); bool appendRevision(Revision rev, bool pendingRev, std::vector<Revision>* deltas); std::pair<DeltaList, DeltaList> sync(Engine& other, bool symetric); gsl::not_null<Rope*> rope_; std::vector<Revision> revisions_; std::vector<Revision> pendingRevs_; std::map<size_t, std::pair<size_t, size_t>> sync_state_; size_t authorId_; size_t revId_; }; template <class Converter> void Engine::insert(gsl::span<const char> bytes, size_t pos) { return insert(Converter::encode(bytes), pos); } } // namespace brick
{ "alphanum_fraction": 0.6461971831, "avg_line_length": 23.0519480519, "ext": "h", "hexsha": "1dae3cb7a6fc570a07749a7d3a14ced553c64897", "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": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_path": "src/crdt/Engine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "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": "tqtifnypmb/brick", "max_issues_repo_path": "src/crdt/Engine.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_path": "src/crdt/Engine.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 462, "size": 1775 }
/* linalg/qr_ud.c * * Copyright (C) 2020 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> /* * this module contains routines for the QR factorization of a matrix * using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with * additional modifications courtesy of Julien Langou. */ static int aux_QR_TRD_decomp (gsl_matrix * U, gsl_matrix * A, const gsl_vector * D, gsl_matrix * T); static double qrtd_householder_transform (double *v0, double *v1); static double qrtrd_householder_transform (double *v0, gsl_vector * v, double *d); /* gsl_linalg_QR_UD_decomp() Compute the QR decomposition of the "triangle on top of diagonal" matrix [ U ] = Q [ R ] [ D ] [ 0 ] where U is N-by-N upper triangular, D is N-by-N diagonal Inputs: U - on input, upper triangular N-by-N matrix on output, R factor in upper triangle D - diagonal N-by-N matrix Y - (output) upper triangular N-by-N matrix (lower part of V) T - (output) block reflector matrix, N-by-N Notes: 1) Based on the Elmroth/Gustavson algorithm, taking into account the sparse structure of the U,S matrices 2) The Householder matrix V has the special form: N V = [ I ] N [ Y ] N with Y upper triangular 3) The orthogonal matrix is Q = I - V T V^T */ int gsl_linalg_QR_UD_decomp (gsl_matrix * U, const gsl_vector * D, gsl_matrix * Y, gsl_matrix * T) { const size_t N = U->size1; if (N != U->size2) { GSL_ERROR ("U matrix must be square", GSL_ENOTSQR); } else if (D->size != N) { GSL_ERROR ("D matrix does not match dimensions of U", GSL_EBADLEN); } else if (Y->size1 != Y->size2) { GSL_ERROR ("Y matrix must be square", GSL_ENOTSQR); } else if (Y->size1 != N) { GSL_ERROR ("Y matrix does not match dimensions of U", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix has wrong dimensions", GSL_EBADLEN); } else if (N == 1) { /* base case, compute Householder transform for single column matrix */ double * T00 = gsl_matrix_ptr(T, 0, 0); double * U00 = gsl_matrix_ptr(U, 0, 0); double * Y00 = gsl_matrix_ptr(Y, 0, 0); *Y00 = gsl_vector_get(D, 0); *T00 = qrtd_householder_transform(U00, Y00); return GSL_SUCCESS; } else { /* * partition matrices: * * N1 N2 N1 N2 * N1 [ U11 U12 ] and N1 [ T11 T12 ] * N2 [ 0 U22 ] N2 [ 0 T22 ] * N1 [ D11 D12 ] * N2 [ 0 D22 ] */ int status; const size_t N1 = N / 2; const size_t N2 = N - N1; gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1); gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2); gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2); gsl_vector_const_view D1 = gsl_vector_const_subvector(D, 0, N1); gsl_vector_const_view D2 = gsl_vector_const_subvector(D, N1, N2); gsl_matrix_view Y11 = gsl_matrix_submatrix(Y, 0, 0, N1, N1); gsl_matrix_view Y12 = gsl_matrix_submatrix(Y, 0, N1, N1, N2); gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1); gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2); gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2); gsl_matrix_view m; /* * Eq. 2: recursively factor * * N1 N1 * N1 [ U11 ] = Q1 [ R11 ] N1 * N2 [ 0 ] [ 0 ] N2 * N1 [ D11 ] [ 0 ] N1 * N2 [ 0 ] [ 0 ] N2 */ status = gsl_linalg_QR_UD_decomp(&U11.matrix, &D1.vector, &Y11.matrix, &T11.matrix); if (status) return status; /* * Eq. 3: * * N2 N2 N2 * N1 [ R12 ] = Q1^T [ U12 ] = [ U12 - W ] N1 * N2 [ U22~ ] [ U22 ] [ U22 ] N2 * N1 [ D12~ ] [ 0 ] [ - V31 W ] N1 * N2 [ D22~ ] [ D22 ] [ D22 ] N2 * * where W = T11^T U12, using T12 as temporary storage, and * * N1 * V1 = [ I ] N1 * [ 0 ] N2 * [ V31 ] N1 * [ 0 ] N2 */ gsl_matrix_memcpy(&T12.matrix, &U12.matrix); /* W := U12 */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */ gsl_matrix_sub(&U12.matrix, &T12.matrix); /* R12 := U12 - W */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Y11.matrix, &T12.matrix); /* W := -V31 W */ gsl_matrix_memcpy(&Y12.matrix, &T12.matrix); /* Y12 := -V31 W */ /* * Eq. 4: factor the "triangle on top of rectangle on top of diagonal" matrix * * N2 [ U22 ] = Q2~ [ R22 ] N2 * N1 [ Y12 ] [ 0 ] N1 * N2 [ D22 ] [ 0 ] N2 */ m = gsl_matrix_submatrix(Y, 0, N1, N, N2); status = aux_QR_TRD_decomp(&U22.matrix, &m.matrix, &D2.vector, &T22.matrix); if (status) return status; /* * Eq. 13: update T12 := -T11 * V1^T * V2 * T22 * * where: * * N1 N2 * V1 = [ I ] N1 V2 = [ 0 ] N1 * [ 0 ] N2 [ I ] N2 * [ V31~ ] N1 [ V32~ ] N1 * [ 0 ] N2 [ V42~ ] N2 * * Note: V1^T V2 = V31~^T V32~ */ gsl_matrix_memcpy(&T12.matrix, &Y12.matrix); /* T12 := V32~ */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &Y11.matrix, &T12.matrix); /* T12 := V31~^T V32~ */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */ gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */ return GSL_SUCCESS; } } /* Find the least squares solution to the overdetermined system * * [ U ] x = b * [ D ] * * using the QR factorization [ U; D ] = Q R. * * Inputs: R - upper triangular R matrix, N-by-N * Y - upper triangular Y matrix, N-by-N * T - upper triangular block reflector, N-by-N * b - right hand side, size 2*N * x - (output) solution, size 2*N * x(1:N) = least squares solution vector * x(N+1:2*N) = vector whose norm equals ||b - Ax|| * work - workspace, size N */ int gsl_linalg_QR_UD_lssolve (const gsl_matrix * R, const gsl_matrix * Y, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x, gsl_vector * work) { const size_t N = R->size1; const size_t M = 2 * N; if (R->size2 != N) { GSL_ERROR ("R matrix must be square", GSL_ENOTSQR); } else if (Y->size1 != Y->size2) { GSL_ERROR ("Y matrix must be square", GSL_ENOTSQR); } else if (Y->size1 != N) { GSL_ERROR ("Y and R must have same dimensions", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN); } else if (M != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (M != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else if (N != work->size) { GSL_ERROR ("workspace must be length N", GSL_EBADLEN); } else { return gsl_linalg_QR_UU_lssolve(R, Y, T, b, x, work); } } /* aux_QR_TRD_decomp() Compute the QR decomposition of the "triangle on top of rectangle on top of diagonal" matrix [ U ] = Q [ R ] [ A ] [ 0 ] [ D ] [ 0 ] where U is N-by-N upper triangular, A is M-by-N dense, D is N-by-N diagonal Inputs: U - on input, upper triangular N-by-N matrix on output, R factor in upper triangle A - on input, A is stored in A(1:M,1:N) on output, Y is stored in A(1:M+N,1:N) size (M+N)-by-N D - diagonal N-by-N matrix T - (output) block reflector matrix, N-by-N Notes: 1) Based on the Elmroth/Gustavson algorithm, taking into account the sparse structure of the U,S matrices 2) The Householder matrix V has the special form: N V = [ I ] N [ Y ] M+N with Y upper trapezoidal 3) The orthogonal matrix is Q = I - V T V^T */ static int aux_QR_TRD_decomp (gsl_matrix * U, gsl_matrix * A, const gsl_vector * D, gsl_matrix * T) { const size_t N = U->size1; if (N != U->size2) { GSL_ERROR ("U matrix must be square", GSL_ENOTSQR); } else if (A->size1 <= N) { GSL_ERROR ("A matrix must have > N rows", GSL_EBADLEN); } else if (D->size != N) { GSL_ERROR ("D matrix does not match dimensions of U", GSL_EBADLEN); } else if (T->size1 != N || T->size2 != N) { GSL_ERROR ("T matrix has wrong dimensions", GSL_EBADLEN); } else if (N == 1) { /* base case, compute Householder transform for single column matrix */ const size_t M = A->size1 - N; double * T00 = gsl_matrix_ptr(T, 0, 0); double * U00 = gsl_matrix_ptr(U, 0, 0); gsl_vector_view v = gsl_matrix_subcolumn(A, 0, 0, M); double * D00 = gsl_matrix_ptr(A, M, 0); *D00 = gsl_vector_get(D, 0); *T00 = qrtrd_householder_transform(U00, &v.vector, D00); return GSL_SUCCESS; } else { /* * partition matrices: * * N1 N2 N1 N2 * N1 [ U11 U12 ] and N1 [ T11 T12 ] * N2 [ 0 U22 ] N2 [ 0 T22 ] * N1 [ D11 D12 ] * N2 [ 0 D22 ] */ int status; const size_t M = A->size1 - N; const size_t N1 = N / 2; const size_t N2 = N - N1; gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1); gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2); gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2); gsl_matrix_view A1 = gsl_matrix_submatrix(A, 0, 0, M, N1); gsl_matrix_view A2 = gsl_matrix_submatrix(A, 0, N1, M, N2); gsl_vector_const_view D1 = gsl_vector_const_subvector(D, 0, N1); gsl_vector_const_view D2 = gsl_vector_const_subvector(D, N1, N2); gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1); gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2); gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2); gsl_matrix_view Y41 = gsl_matrix_submatrix(A, M, 0, N1, N1); gsl_matrix_view Y42 = gsl_matrix_submatrix(A, M, N1, N1, N2); gsl_matrix_view m; /* * Eq. 2: recursively factor * * N1 N1 * N1 [ U11 ] = Q1 [ R11 ] N1 * N2 [ 0 ] [ 0 ] N2 * M [ A1 ] [ 0 ] M * N1 [ D11 ] [ 0 ] N1 * N2 [ 0 ] [ 0 ] N2 */ m = gsl_matrix_submatrix(A, 0, 0, M + N1, N1); status = aux_QR_TRD_decomp(&U11.matrix, &m.matrix, &D1.vector, &T11.matrix); if (status) return status; /* * Eq. 3: * * N2 N2 N2 * N1 [ R12 ] = Q1^T [ U12 ] = [ U12 - W ] N1 * N2 [ U22~ ] [ U22 ] [ U22 ] N2 * M [ A2~ ] [ A2 ] [ A2 - V31 W ] M * N1 [ D12~ ] [ 0 ] [ - V41 W ] N1 * N2 [ D22~ ] [ D22 ] [ D22 ] N2 * * where W = T11^T ( U12 + V31^T A2 ), using T12 as temporary storage, and * * N1 * V1 = [ I ] N1 * [ 0 ] N2 * [ V31 ] M * [ V41 ] N1 * [ 0 ] N2 */ gsl_matrix_memcpy(&T12.matrix, &U12.matrix); /* W := U12 */ gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* W := U12 + V31^T A2 */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */ gsl_matrix_sub(&U12.matrix, &T12.matrix); /* R12 := U12 - W */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A1.matrix, &T12.matrix, 1.0, &A2.matrix); /* A2 := A2 - V31 W */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Y41.matrix, &T12.matrix); /* W := -V41 W */ gsl_matrix_memcpy(&Y42.matrix, &T12.matrix); /* V42 := -431 W */ /* * Eq. 4: factor the "triangle on top of rectangle on top of diagonal" matrix * * N2 [ U22 ] = Q2~ [ R22 ] N2 * N1 [ Y12 ] [ 0 ] N1 * N2 [ D22 ] [ 0 ] N2 */ m = gsl_matrix_submatrix(A, 0, N1, M + N, N2); status = aux_QR_TRD_decomp(&U22.matrix, &m.matrix, &D2.vector, &T22.matrix); if (status) return status; /* * Eq. 13: update T12 := -T11 * V1^T * V2 * T22 * * where: * * N1 N2 * V1 = [ I ] N1 V2 = [ 0 ] N1 * [ 0 ] N2 [ I ] N2 * [ V31~ ] M [ V32~ ] M * [ V41~ ] N1 [ V42~ ] N1 * [ 0 ] N2 [ V52~ ] N2 * * Note: V1^T V2 = V31~^T V32~ + V41~^T V42~ */ gsl_matrix_memcpy(&T12.matrix, &Y42.matrix); /* T12 := V42~ */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &Y41.matrix, &T12.matrix); /* T12 := V41~^T V42~ */ gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* T12 := V31~^T V32~^T + V41~^T V42~ */ gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */ gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */ return GSL_SUCCESS; } } /* qrtd_householder_transform() This routine is an optimized version of gsl_linalg_householder_transform(), designed for the QR decomposition of M-by-N matrices of the form: B = [ U ] [ S ] where U,S are N-by-N upper triangular. This routine computes a householder transformation (tau,v) of a x so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will be a subcolumn of the matrix B, and so its structure will be: x = [ x0 ] <- 1 nonzero value for the diagonal element of U [ y0 ] <- 1 nonzero value for the diagonal element of S Inputs: v0 - pointer to diagonal element of U on input, v0 = x0; v1 - on input, pointer to diagonal element of S on output, householder vector v */ static double qrtd_householder_transform (double *v0, double *v1) { /* replace v[0:M-1] with a householder vector (v[0:M-1]) and coefficient tau that annihilate v[1:M-1] */ double alpha, beta, tau ; /* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */ double xnorm = fabs(*v1); if (xnorm == 0) { return 0.0; /* tau = 0 */ } alpha = *v0; beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ; tau = (beta - alpha) / beta ; { double s = (alpha - beta); if (fabs(s) > GSL_DBL_MIN) { *v1 /= s; *v0 = beta; } else { *v1 *= GSL_DBL_EPSILON / s; *v1 /= GSL_DBL_EPSILON; *v0 = beta; } } return tau; } /* qrtrd_householder_transform() This routine is an optimized version of gsl_linalg_householder_transform(), designed for the QR decomposition of M-by-N matrices of the form: B = [ U ] [ A ] [ D ] where U is N-by-N upper triangular A is M-by-N dense and D is N-by-N diagonal. This routine computes a householder transformation (tau,v) of a x so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will be a subcolumn of the matrix B, and so its structure will be: x = [ x0 ] <- 1 nonzero value for the diagonal element of S [ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1] [ x ] <- M nonzero values for the dense part A Inputs: v0 - pointer to diagonal element of S on input, v0 = x0; v - on input, x vector on output, householder vector v d - on input, diagonal element of D on output, householder element */ static double qrtrd_householder_transform (double *v0, gsl_vector * v, double *d) { /* replace v[0:M-1] with a householder vector (v[0:M-1]) and coefficient tau that annihilate v[1:M-1] */ double alpha, beta, tau ; /* compute xnorm = || [ 0 ; v ; 0 ; d] ||, ignoring zero part of vector */ double xnorm; xnorm = gsl_blas_dnrm2(v); xnorm = gsl_hypot(xnorm, *d); if (xnorm == 0) { return 0.0; /* tau = 0 */ } alpha = *v0; beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ; tau = (beta - alpha) / beta ; { double s = (alpha - beta); if (fabs(s) > GSL_DBL_MIN) { gsl_blas_dscal (1.0 / s, v); *d /= s; *v0 = beta; } else { gsl_blas_dscal (GSL_DBL_EPSILON / s, v); gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v); *d *= GSL_DBL_EPSILON / s; *d /= GSL_DBL_EPSILON; *v0 = beta; } } return tau; }
{ "alphanum_fraction": 0.5394871795, "avg_line_length": 31.8298969072, "ext": "c", "hexsha": "8a4280badb381fa1257155d8093bbb04b95b316b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.c", "max_line_length": 142, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.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": 6073, "size": 18525 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef zip_efeefa3a_157a_4c4c_83b0_99ec8e0364a1_h #define zip_efeefa3a_157a_4c4c_83b0_99ec8e0364a1_h #include <gslib/config.h> #include <gslib/tree.h> #include <gslib/vdir.h> __gslib_begin__ typedef void* zip_handle; struct zip_argument { int level; /* 0-9, default -1 */ const gchar* name; const gchar* comment; zip_argument() { level = -1, comment = name = 0; } zip_argument(const gchar* n) { level = -1, name = n, comment = 0; } zip_argument(int l, const gchar* n, const gchar* c) { level = l, name = n, comment = c; } }; struct zip_node { enum { zt_folder, zt_file, zt_buffer, }; uint tag; string name; }; typedef _treenode_wrapper<zip_node> zip_wrapper; typedef tree<zip_node, zip_wrapper> zip_directory; struct zip_folder: public zip_node { zip_folder() { tag = zt_folder; } }; struct zip_file: public zip_node { string password; string comment; string path; zip_file() { tag = zt_file; } }; struct zip_buffer: public zip_node { string password; string comment; vessel buffer; zip_buffer() { tag = zt_buffer; } }; extern void get_zip_path(string& path, const zip_wrapper* w); extern void create_zip_directory(zip_directory& dir, const gchar* path); extern void convert_zip_directory(zip_directory& dir, vdir& vd); extern bool do_zip(const zip_argument& arg, const zip_directory& dir); extern bool do_zip(const zip_argument& arg, const gchar* path); struct zip_info_node { string name; int length; int size; float ratio; uint crc; }; typedef list<zip_info_node> zip_info; extern bool view_zip_info(zip_info& info, const gchar* path); extern void do_unzip(const gchar* src, const gchar* dest); extern void do_unzip(const gchar* src, vdir& vd); class zip { public: zip() { _zh = 0; } ~zip() { close(0); } void create(const zip_argument& arg); void close(const gchar* comment); bool start(const gchar* name, const gchar* password, const gchar* comment); bool write(const void* buf, int size); void finish(); protected: zip_handle _zh; zip_argument _arg; }; class unzip { public: unzip() { _zh = 0; } ~unzip() { close(); } bool open(const gchar* filename); void close(); bool view(zip_info& info); bool extract(const gchar* path); bool extract_item(const gchar* path, const gchar* name, const gchar* password); bool extract(vdir& vd); bool extract_item(vdir& vd, const gchar* name, const gchar* password); protected: zip_handle _zh; }; __gslib_end__ #endif
{ "alphanum_fraction": 0.650229635, "avg_line_length": 28.3356164384, "ext": "h", "hexsha": "c089e9c017acb995a57160cb07cf0135d5ce0e07", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/zip.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/zip.h", "max_line_length": 94, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/zip.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 1009, "size": 4137 }
/* 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. $Id$ */ #include <config.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <fortran_types.h> #include <gsl/gsl_sf_legendre.h> /* normalization constants for the spherical harmonics */ static double sph_cnsts[9] = { 0.282094791773878, /* l = 0 */ 0.488602511902920, 0.488602511902920, 0.488602511902920, /* l = 1 */ 0.182091405098680, 0.364182810197360, 0.630783130505040, 0.364182810197360, 0.182091405098680 }; /* Computes real spherical harmonics ylm in the direction of vector r: ylm = c * plm( cos(theta) ) * sin(m*phi) for m < 0 ylm = c * plm( cos(theta) ) * cos(m*phi) for m >= 0 with (theta,phi) the polar angles of r, c a positive normalization constant and plm associated legendre polynomials. */ void FC_FUNC_(oct_ylm, OCT_YLM) (const fint * np, const double *x, const double *y, const double *z, const fint *l, const fint *m, double * restrict ylm) { double r, r2, rr, rx, ry, rz, cosphi, sinphi, cosm, sinm, phase; int i, ip; if(l[0] == 0) { for (ip = 0; ip < np[0]; ip++) ylm[ip] = sph_cnsts[0]; return; } for (ip = 0; ip < np[0]; ip++){ r2 = x[ip]*x[ip] + y[ip]*y[ip] + z[ip]*z[ip]; /* if r=0, direction is undefined => make ylm=0 except for l=0 */ if(r2 < 1.0e-15){ ylm[ip] = 0.0; continue; } switch(l[0]){ case 1: rr = 1.0/sqrt(r2); switch(m[0]){ case -1: ylm[ip] = -sph_cnsts[1]*rr*y[ip]; continue; case 0: ylm[ip] = sph_cnsts[2]*rr*z[ip]; continue; case 1: ylm[ip] = -sph_cnsts[3]*rr*x[ip]; continue; } case 2: switch(m[0]){ case -2: ylm[ip] = sph_cnsts[4]*6.0*x[ip]*y[ip]/r2; continue; case -1: ylm[ip] = -sph_cnsts[5]*3.0*y[ip]*z[ip]/r2; continue; case 0: ylm[ip] = sph_cnsts[6]*0.5*(3.0*z[ip]*z[ip]/r2 - 1.0); continue; case 1: ylm[ip] = -sph_cnsts[7]*3.0*x[ip]*z[ip]/r2; continue; case 2: ylm[ip] = sph_cnsts[8]*3.0*(x[ip]*x[ip] - y[ip]*y[ip])/r2; continue; } } /* get phase */ rr = 1.0/sqrt(r2); rx = x[ip]*rr; ry = y[ip]*rr; rz = z[ip]*rr; r = hypot(rx, ry); if(r < 1e-20) r = 1e-20; /* one never knows... */ cosphi = rx/r; sinphi = ry/r; /* compute sin(mphi) and cos(mphi) by adding cos/sin */ cosm = 1.; sinm=0.; for(i = 0; i < abs(m[0]); i++){ double a = cosm, b = sinm; cosm = a*cosphi - b*sinphi; sinm = a*sinphi + b*cosphi; } phase = m[0] < 0 ? sinm : cosm; phase = m[0] == 0 ? phase : sqrt(2.0)*phase; /* adding small number (~= 10^-308) to avoid floating invalids */ rz = rz + DBL_MIN; r = gsl_sf_legendre_sphPlm(l[0], abs(m[0]), rz); /* I am not sure whether we are including the Condon-Shortley factor (-1)^m */ ylm[ip] = r*phase; } }
{ "alphanum_fraction": 0.6030491248, "avg_line_length": 29.5166666667, "ext": "c", "hexsha": "45f616548e4e59d5466d7bb2b098f652c5fc3f0f", "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": "25cb84cf590276af9ce4617039ba3849e328594c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "neelravi/octopus", "max_forks_repo_path": "src/math/ylm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "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": "neelravi/octopus", "max_issues_repo_path": "src/math/ylm.c", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "neelravi/octopus", "max_stars_repo_path": "src/math/ylm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1240, "size": 3542 }
#pragma once #include <string> #include <vector> #include <set> #include <map> #include <gsl/gsl> #include <gamesystems/map/sector.h> #include "streams.h" #include "animgoals/anim.h" struct QuestSave { GameTime acceptedTime; uint32_t acceptedArea; uint32_t state; }; struct ObjRefSave { ObjectId id; uint32_t mapId; locXY location; }; struct AnimGoalSave { AnimGoalType type; ObjRefSave selfObj; ObjRefSave targetObj; ObjRefSave blockObj; ObjRefSave scratchObj; ObjRefSave parentObj; locXY targetLoc; locXY range; int animId; int animIdPrev; int animData; int animData2; int spellData; int skillData; int flagsData; int scratchVal1; int scratchVal2; int scratchVal3; int scratchVal4; int scratchVal5; int scratchVal6; int soundHandle; }; struct AnimSlotSave { AnimSlotId id; uint32_t flags; int currentState; uint32_t field14; uint64_t field18; ObjRefSave animObj; std::vector<AnimGoalSave> goals; std::array<uint8_t, 0xF8> unk; uint64_t pathInfo; GameTime someTime; uint32_t field2c90; }; struct SpellObjSave { ObjectId id; uint32_t casterPartSysName; }; struct SpellSave { uint32_t spellId; uint32_t spellIdx; uint32_t active; uint32_t spellEnum; uint32_t spellEnumOrg; uint32_t flagsSth; ObjectId caster; uint32_t casterPartSysName; // 0 if none uint32_t spellClass; uint32_t spellLevel; uint32_t baseCasterLevel; uint32_t spellDc; uint32_t spellObjCount; // Guess objHndl unknownObj; std::array<SpellObjSave, 128> spellObjs; // Not really sure if this is spell objs size_t targetListNumItemsCopy; size_t targetListNumItems; std::array<SpellObjSave, 32> targets; uint32_t numProjectiles; std::array<ObjectId, 5> projectiles; LocFull aoeCenter; uint32_t duration; uint32_t durationRemaining; uint32_t spellRange; uint32_t savingThrowResult; uint32_t metaMagic; uint32_t spellId2; }; struct TimeEventArgSave { int32_t intVal = 0; float floatVal = 0; ObjRefSave objectRefVal; locXY locVal = {0, 0}; std::string pythonObj; }; struct TimeEventSave { GameTime expiresAt; TimeEventType type; std::vector<TimeEventArgSave> args; }; class SaveGameArchive { public: static void Create(const std::string &folder, const std::string &filename); static void Unpack(const std::string &filename, const std::string &folder); private: static void AddFolder(const std::string &folder, OutputStream &indexStream, OutputStream &dataStream); static void UnpackFolder(const std::string &folder, InputStream &indexStream, InputStream &dataStream); static void UnpackFile(const std::string &folder, InputStream &indexStream, InputStream &dataStream); }; class SaveGame { public: void Load(const std::string &path); private: void LoadDataSav(InputStream &in); std::vector<std::string> mCustomDescriptions; bool mIronman = false; uint32_t mIronmanSaveNumber = 0; std::string mIronmanSaveName; std::vector<SectorTime> mSectorTimes; std::vector<uint8_t> mGlobalVars; std::vector<uint8_t> mGlobalFlags; uint32_t mStoryState = 0; std::vector<int32_t> mEncounterQueue; std::string mMapDataPath; std::string mMapSavePath; std::set<uint32_t> mVisitedMaps; uint32_t mNextSpellId = 0; std::vector<SpellSave> mSpells; uint32_t mLightSchemeId = 0; uint32_t mLightSchemeHourOfDay = 0; std::set<uint32_t> mKnownAreas; std::vector<uint32_t> mSoundSchemeIds; // At most 2 bool mSoundGameOverSound = false; std::vector<uint32_t> mSoundGameOverStash; // 2 scheme ids bool mSoundGameInCombat = false; std::vector<uint32_t> mSoundGameCombatStash; // 2 scheme ids std::vector<QuestSave> mQuests; bool mInCombat = false; GameTime mRealTime; GameTime mGameTime; GameTime mAnimTime; std::vector<TimeEventSave> mTimeEvents; uint32_t mNextAnimId = 0; uint32_t mActiveGoalCount = 0; bool mAnimCatchup = false; uint32_t mAnimActionId = 0; std::vector<uint32_t> mUnkAnimVals; std::map<size_t, AnimSlotSave> mAnimSlots; static AnimSlotSave ReadAnimSlot(InputStream &in); static ObjRefSave ReadObjRef(InputStream &in); static void ReadSystemFooter(InputStream &in, const char *system); };
{ "alphanum_fraction": 0.7658382066, "avg_line_length": 21.1546391753, "ext": "h", "hexsha": "c2ba229d4a88fed1dbf60009c50992c28bef6de9", "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": "TemplePlus/util/savegame.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": "TemplePlus/util/savegame.h", "max_line_length": 82, "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": "TemplePlus/util/savegame.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": 1153, "size": 4104 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> double f (double px, void * par) { double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2; struct my_f_params { double x; double y; double z; double v;}; struct my_f_params * params = (struct my_f_params *)par; double T2 = (params->x); double es = (params->y); double eF = (params->z); double py = (params->v); double xi,argument; double sx=2.*sin(px/2.),sy=2.*sin(py/2.); double data[] = { ed , 0. , tpd*sx , -tpd*sy, 0., es , tsp*sx , tsp*sy, tpd*sx, tsp*sx, ep , -tpp*sx*sy, -tpd*sy, tsp*sy, -tpp*sx*sy, ep }; gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4); gsl_vector *eval = gsl_vector_alloc (4); gsl_matrix *evec = gsl_matrix_alloc (4, 4); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4); gsl_eigen_symmv (&m.matrix, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC); double e = gsl_vector_get (eval, 2); gsl_vector_view evec_i = gsl_matrix_column (evec, 2); xi = gsl_vector_get(&evec_i.vector,0)*gsl_vector_get(&evec_i.vector,1); gsl_vector_free (eval); gsl_matrix_free (evec); double eeF=e-eF; if ( eeF == 0 ) argument=1./T2; else argument=(tanh(eeF/T2))/eeF; argument*=xi*xi; return argument; } double g(double py, void * p) { struct my_f_params { double a; double b; double c; }; struct my_f_params * params = (struct my_f_params *)p; double T2 = (params->a); double es = (params->b); double eF = (params->c); //printf("%g %g %g\n",a,b,c); struct your_f_params { double x; double y; double z; double v; }; struct your_f_params parametri = { T2, es , eF , py }; double result, error; gsl_integration_workspace * w = gsl_integration_workspace_alloc (5000000); gsl_function F; F.function = &f; F.params = &parametri; gsl_integration_qags (&F, 0, 2*M_PI, 0, 1e-7, 5000000, w, &result, &error); gsl_integration_workspace_free (w); return result; } double dvoenintegral(double T2, double es, double eF) { double dvoenintegral, error; struct my_f_params { double a; double b; double c; }; gsl_integration_workspace * v = gsl_integration_workspace_alloc (5000000); gsl_function F; struct my_f_params params = {T2, es , eF}; F.function = &g; F.params = &params; gsl_integration_qags (&F, 0, 2*M_PI, 0, 1e-7, 5000000, v, &dvoenintegral, &error); gsl_integration_workspace_free (v); return (dvoenintegral)/(2*M_PI*M_PI); } double optim(double L, void * pp) { struct my_f_params { double a; double b; double c; }; struct my_f_params * params = (struct my_f_params *)pp; double Jsd = (params->a); double es = (params->b); double eF = (params->c); double TT=2.*exp(-L); double tmp=dvoenintegral(TT,es,eF); return Jsd*tmp-1; } double nameri_nula( double Jsd, double es, double eF) { int status; double Kelvin=1/11604.; struct my_f_params { double a; double b; double c; }; struct my_f_params params = { Jsd, es , eF}; int iter = 0, max_iter = 100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double r = 0; double x_lo = 1E-6, x_hi = 7; gsl_function F; F.function = &optim; F.params = &params; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, x_lo, x_hi); //printf ("using %s method\n", gsl_root_fsolver_name (s)); //printf ("%5s [%9s, %9s] %9s %10s\n", "iter", "lower", "upper", "root", "err"); do { iter++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); x_lo = gsl_root_fsolver_x_lower (s); x_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001); //if (status == GSL_SUCCESS) //printf ("Converged:\n"); //printf ("%5d [%.7f, %.7f] %.7f %+.7f\n", iter, x_lo, x_hi, r, x_hi - x_lo); } while (status == GSL_CONTINUE && iter < max_iter); //printf("T_c=%g\n",exp(-r)/Kelvin); gsl_root_fsolver_free (s); return (2*exp(-r)/Kelvin); } double granichni_tochki(double a, double b,double es) { double sx=2.*sin(a/2.); double sy=2.*sin(b/2.); double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2; double data[] = { ed , 0. , tpd*sx , -tpd*sy, 0., es , tsp*sx , tsp*sy, tpd*sx, tsp*sx, ep , -tpp*sx*sy, -tpd*sy, tsp*sy, -tpp*sx*sy, ep }; gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4); gsl_vector *eval = gsl_vector_alloc (4); gsl_matrix *evec = gsl_matrix_alloc (4, 4); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4); gsl_eigen_symmv (&m.matrix, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_vector_free (eval); gsl_matrix_free (evec); return ( gsl_vector_get (eval, 2) ); } double pd(double e, double es) { double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2; double A,B,C,xd,eep,eed,ees,ppd; eep=e-ep; eed=e-ed; ees=e-es; A=16.*(4.*tpd*tpd*tsp*tsp + 2.*tsp*tsp*tpp*eed-2.*tpd*tpd*tpp*ees-tpp*tpp*eed*ees); B=-4.*eep*(tsp*tsp*eed+tpd*tpd*ees); C=ees*eep*eep*eed; xd=(-B+sqrt(B*B-A*C))/A; //printf("xd=%g\n",xd); ppd=2*asin(sqrt(xd)); //printf("xd=%g ppd=%g e=%g es=%g\n",xd,ppd,e,es); return ppd; } double fermi(double px, void * p) { struct my_f_params { double a; double b; }; struct my_f_params * params = (struct my_f_params *)p; double eF = (params->a); double es = (params->b); double A,B,C,eep,eed,ees,e,F; double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2; e=eF; eep=e-ep; eed=e-ed; ees=e-es; A=16.*(4.*tpd*tpd*tsp*tsp + 2.*tsp*tsp*tpp*eed-2.*tpd*tpd*tpp*ees-tpp*tpp*eed*ees); B=-4.*eep*(tsp*tsp*eed+tpd*tpd*ees); C=ees*eep*eep*eed; double x=sin(px/2.)*sin(px/2.); F=(px-2*asin(sqrt(- (C+B*x)/(A*x+B) ))); return F; } double ffactor( double eF , double es ) { double res, error; struct my_f_params { double a; double b; }; gsl_integration_workspace * v = gsl_integration_workspace_alloc (1000); gsl_function F; struct my_f_params params = {eF , es}; F.function = &fermi; F.params = &params; gsl_integration_qag (&F, pd(eF,es) , M_PI , 0, 1e-7, 1000, 6 , v, &res, &error); gsl_integration_workspace_free (v); return (8*res)/(4*M_PI*M_PI) ; } double ffactornula( double eF , void * p ) { double res, error; double es = *(double *) p; struct my_f_params { double a; double b; }; gsl_integration_workspace * v = gsl_integration_workspace_alloc (100000); gsl_function F; struct my_f_params params = {eF , es}; F.function = &fermi; F.params = &params; gsl_integration_qags (&F, pd(eF,es) , M_PI , 0, 1e-7, 100000, v, &res, &error); gsl_integration_workspace_free (v); return (8*res)/(4*M_PI*M_PI) - 0.66; } double ferminula( double evhs, double etop, double es) { int status; int iter = 0, max_iter = 100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double r = 0; double x_lo = evhs+1E-7, x_hi = etop-1E-7; gsl_function F; F.function = &ffactornula; F.params = &es; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, x_lo, x_hi); //printf ("using %s method\n", gsl_root_fsolver_name (s)); //printf ("%5s [%9s, %9s] %9s %10s\n", "iter", "lower", "upper", "root", "err"); do { iter++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); x_lo = gsl_root_fsolver_x_lower (s); x_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001); //if (status == GSL_SUCCESS) //printf ("Converged:\n"); //printf ("%5d [%.7f, %.7f] %.7f %+.7f\n", iter, x_lo, x_hi, r, x_hi - x_lo); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return r; } int main(void) { double Kelvin=1/11604.; double es=6.0, eF=1.301531002,tsp=1.63,ep=-.9,tpd=1.13; double Jsd,Tc,evhs,etop,s,ss; //double tmp; /* Jsd=1/dvoenintegral(90*Kelvin,es,eF); printf ("Jsd= %g\n",Jsd); Tc=nameri_nula(Jsd,es,eF); printf ("Tc= %g\n",Tc); evhs=granichni_tochki(0,M_PI,es); printf("evhs=%g\n",evhs); etop=granichni_tochki(M_PI,M_PI,es); printf("etop=%g\n",etop); ff=ffactor(evhs, es); printf("filling factor(evhs)=%g\n",ff); printf("%g\n",ferminula(evhs,etop,es)); */ Jsd=1/dvoenintegral(90*Kelvin,es,eF); for(es=5;es<8.5;es+=0.1) { evhs=granichni_tochki(0,M_PI,es); etop=granichni_tochki(M_PI,M_PI,es); eF=ferminula(evhs,etop,es); Tc=nameri_nula(Jsd,es,eF); //s=((es-eF)*(eF-ep))/(4*tsp*tsp); ss=((es-eF)*(eF-ep))/(4*tsp*tpd); //printf("Tc=%g es=%g eF=%g\n",Tc,es,eF); printf("%g %g\n",ss,log(Tc)); //printf("%g %g\n",1/(2*(1+s)),Tc ); } return 0; }
{ "alphanum_fraction": 0.5263305584, "avg_line_length": 28.5093333333, "ext": "c", "hexsha": "7f2abe896ad24908a93952b40123ce2237a656c4", "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": "968c055802abcfa179fae72b0b73d3b1c82c829b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zlatan/Superconductivity", "max_forks_repo_path": "Tc_r.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "968c055802abcfa179fae72b0b73d3b1c82c829b", "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": "zlatan/Superconductivity", "max_issues_repo_path": "Tc_r.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "968c055802abcfa179fae72b0b73d3b1c82c829b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zlatan/Superconductivity", "max_stars_repo_path": "Tc_r.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3308, "size": 10691 }
#ifndef UTILS_H #define UTILS_H #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <dirent.h> #include <memory.h> #include <time.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sf_psi.h> #include <gsl/gsl_sf_gamma.h> #include <vector> using namespace std; double log_sum(double log_a, double log_b); double log_normalize(double * array, int nlen); double log_normalize(vector<double> & vec, int nlen); double log_subtract(double log_a, double log_b); double log_factorial(int n, double a); double similarity(const int* v1, const int* v2, int n); bool file_exists(const char * filename); bool dir_exists(const char * directory); template <typename T> void free_vec_ptr(vector <T* > & v) { int size = v.size(); T* p = NULL; for (int i = 0; i < size; i ++) { p = v[i]; delete [] p; } v.clear(); } // find the max and argmax in an array template <typename T> T max(const T * x, int n, int* argmax) { *argmax = 0; T max_val = x[0]; for (int i = 1; i < n; i++) if (x[i] > max_val) { max_val = x[i]; *argmax = i; } return max_val; } // find the max and argmax in an vector template <typename T> T max_vec(vector<T> & v, int n, int* argmax) { *argmax = 0; T max_val = v[0]; for (int i = 1; i < n; i++) if (v[i] > max_val) { max_val = v[i]; *argmax = i; } return max_val; } // set a value to the entire array template <typename T> void set_array(T * array, int size, T value) { for (int i = 0; i < size; i++) array[i] = value; } // swap two elements in an array template < typename T > void swap_array_element(T * array, int i, int j) { if (i == j) return; T a = array[i]; array[i] = array[j]; array[j] = a; } // set a value to a entrie vector template <typename T> void set_vector(vector<T> & v, T value) { int size = v.size(); for (int i = 0; i < size; i++) v[i] = value; } // swap two elements in vector template < typename T > void swap_vec_element(vector<T> & v, int i, int j) { if (i == j) return; // no need to swap T a = v[i]; v[i] = v[j]; v[j] = a; } /// gsl_wrappers //double lgamma(double x); // linux has this unsigned int rmultinomial(const double* p, int n, double tot_p=-1); double rgamma(double a, double b); double rbeta(double a, double b); unsigned int rbernoulli(double p); double runiform(); void rshuffle (void* base, size_t n, size_t size); unsigned long int runiform_int(unsigned long int n); #endif
{ "alphanum_fraction": 0.5858009276, "avg_line_length": 23.9572649573, "ext": "h", "hexsha": "9bccd57b40c41a7c64cb4d0fc9bbf98ae3954eb6", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2018-10-17T07:16:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-14T10:00:32.000Z", "max_forks_repo_head_hexsha": "8024dd3b916ac2dfc336221dd32faba4c0a98442", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "osmanbaskaya/mapping-impact", "max_forks_repo_path": "run/hdp-wsi/topicmodelling/hdp/utils.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8024dd3b916ac2dfc336221dd32faba4c0a98442", "max_issues_repo_issues_event_max_datetime": "2017-09-03T12:06:35.000Z", "max_issues_repo_issues_event_min_datetime": "2017-09-03T11:57:43.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "osmanbaskaya/mapping-impact", "max_issues_repo_path": "run/hdp-wsi/topicmodelling/hdp/utils.h", "max_line_length": 75, "max_stars_count": 5, "max_stars_repo_head_hexsha": "d013f5b90024620ee79a72e85aa5e5761c3cd8dc", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "marziehf/Topic-Sensitive-Embeddings", "max_stars_repo_path": "topicmodelling/hdp/utils.h", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:33:51.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-12T18:50:16.000Z", "num_tokens": 805, "size": 2803 }
#pragma once #include <gsl/gsl_assert> #include <src/util/Logging.h> #ifndef NDEBUG //#define RNR_EXPECTS(x) Expects(x) //#define RNR_ENSURES(x) Ensures(x) /** * specifies a precondition that is expected to be true * terminates the program if the condition is not met and the program is compiled in debug mode */ #define RNR_EXPECTS(x) \ do { \ if (!(x)) { \ LOG(ERROR) << "assertion failed: " << #x; \ std::terminate(); \ } \ } while (0) /** * specifies a postcondition that is expected to be made true by the code block above * terminates the program if the condition is not met and the program is compiled in debug mode */ #define RNR_ENSURES(x) \ do { \ if (!(x)) { \ LOG(ERROR) << "assertion failed: " << #x; \ std::terminate(); \ } \ } while (0) #else #define RNR_EXPECTS(x) #define RNR_ENSURES(x) #endif
{ "alphanum_fraction": 0.6228956229, "avg_line_length": 23.4473684211, "ext": "h", "hexsha": "6d74cf7601712c0cf27ec24f5c65c2c51a2ba4a6", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-03-21T20:53:11.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-30T21:33:07.000Z", "max_forks_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DavHau/Riner", "max_forks_repo_path": "src/common/Assert.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:57:08.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-30T22:10:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "DavHau/Riner", "max_issues_repo_path": "src/common/Assert.h", "max_line_length": 95, "max_stars_count": 4, "max_stars_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DavHau/Riner", "max_stars_repo_path": "src/common/Assert.h", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:41:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-24T03:24:08.000Z", "num_tokens": 245, "size": 891 }
// @file utils.h // // \date Created on: Sep 23, 2017 // \author Gopalakrishna Hegde // // Description: // // // #ifndef INC_UTILS_H_ #define INC_UTILS_H_ #include "common_types.h" #include <cblas.h> void PrintMat(char *name, const float *ptr, int H, int W, CBLAS_LAYOUT layout); void RandInitF32(float *p_data, int N); void SeqInitF32(float *p_data, int N); void PrintTensor(const float *data, TensorDim dim); int TensorSize(TensorDim dim); bool TensorCompare(const float *t1, const float *t2, TensorDim dim); #endif // INC_UTILS_H_
{ "alphanum_fraction": 0.7208872458, "avg_line_length": 23.5217391304, "ext": "h", "hexsha": "7a2c7002d195dad371ffb732f11f089f377db257", "lang": "C", "max_forks_count": 23, "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_path": "inc/utils.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_path": "inc/utils.h", "max_line_length": 79, "max_stars_count": 54, "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_path": "inc/utils.h", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "num_tokens": 160, "size": 541 }
#ifndef __FFT_DECON_OPERATOR_H__ #define __FFT_DECON_OPERATOR_H__ #include <string> #include <gsl/gsl_errno.h> #include <gsl/gsl_fft_complex.h> #include "mspass/seismic/TimeWindow.h" #include "mspass/utility/Metadata.h" #include "mspass/seismic/CoreTimeSeries.h" #include "mspass/algorithms/deconvolution/ComplexArray.h" namespace mspass::algorithms::deconvolution{ /*! \brief Object to hold components needed in all fft based decon algorithms. The fft based algorithms implemented here us the GNU Scientific Library prime factorization fft algorithm. Those methods require initialization given length of the fft to load and store the factorization data. This object holds these for all such methods and recomputes them only when needed for efficiency. */ class FFTDeconOperator { public: FFTDeconOperator(); FFTDeconOperator(const mspass::utility::Metadata& md); FFTDeconOperator(const FFTDeconOperator& parent); ~FFTDeconOperator(); FFTDeconOperator& operator=(const FFTDeconOperator& parent); void changeparameter(const mspass::utility::Metadata& md); void change_size(const int nfft_new); void change_shift(const int shift) { sample_shift=shift; }; int get_size(){return nfft;}; int get_shift(){return sample_shift;}; int operator_size() { return static_cast<int>(nfft); }; int operator_shift() { return sample_shift; }; double df(const double dt){ double period; period=static_cast<double>(nfft)*dt; return 1.0/period; }; /*! \brief Return inverse wavelet for Fourier methods. This is a helper to be used by the inverse_wavelet method for all Fourier based deconvolution methods. It avoids repetitious code that would be required otherwise. inverse_wavelet methods are only wrappers for this generic method. See documentation for inverse_wavelet for description of tshift and t0parent. */ mspass::seismic::CoreTimeSeries FourierInverse(const ComplexArray& winv, const ComplexArray& sw, const double dt, const double t0parent); protected: int nfft; int sample_shift; gsl_fft_complex_wavetable *wavetable; gsl_fft_complex_workspace *workspace; ComplexArray winv; }; /* This helper is best referenced here */ /*! \brief Circular buffer procedure. In the Fourier world circular vectors are an important thing to deal with because the fft is intimately connected with circlular things. This routine can be used, for example, to time shift the time domain version of a signal after it was processed with an fft. \param d - is the input vector to be shifted \param i0 - is the wrap point. On exit sample i0 of d will be sample 0. (Warning - this is C convention sample number) */ std::vector<double> circular_shift(const std::vector<double>& d,const int i0); /*! Derive fft length from a time window. All deconvlution methods using an fft need to define nfft based on the length of the working time series. This procedure returns the size from an input window and sample interval. */ int ComputeFFTLength(const mspass::seismic::TimeWindow w, const double dt); /*! Derive fft length using parameters in a metadata object. This procedure is basically a higher level version of the function of the same name with a time window and sample interval argument. This procedure extracts these using three parameter keys to extract the real numbers form md: deconvolution_data_window_start, decon_window_end, and target dt. */ int ComputeFFTLength(const mspass::utility::Metadata& md); /*! Returns next power of 2 larger than n. * * Some FFT implementations require the size of the input data vector be a power * of 2. This routine can be used to define a buffer size satisfying that constraint.*/ extern "C" { unsigned int nextPowerOf2(unsigned int n); } } #endif
{ "alphanum_fraction": 0.7523291925, "avg_line_length": 38.64, "ext": "h", "hexsha": "63fca050efe49bae7365bc547eff8a10060a308e", "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": "11bd292a778a2a0d8470734239a7347fe4a1c0a7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "seisman/mspass", "max_forks_repo_path": "cxx/include/mspass/algorithms/deconvolution/FFTDeconOperator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "11bd292a778a2a0d8470734239a7347fe4a1c0a7", "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": "seisman/mspass", "max_issues_repo_path": "cxx/include/mspass/algorithms/deconvolution/FFTDeconOperator.h", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "11bd292a778a2a0d8470734239a7347fe4a1c0a7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "seisman/mspass", "max_stars_repo_path": "cxx/include/mspass/algorithms/deconvolution/FFTDeconOperator.h", "max_stars_repo_stars_event_max_datetime": "2021-10-18T10:02:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-18T10:02:13.000Z", "num_tokens": 894, "size": 3864 }
/** * @file coroutine/net.h * @brief Async I/O operation support with system socket functions * @author github.com/luncliff (luncliff@gmail.com) * @copyright CC BY 4.0 */ #pragma once #ifndef COROUTINE_NET_IO_H #define COROUTINE_NET_IO_H #include <gsl/gsl> #include <coroutine/return.h> /** * @defgroup Network * Helper types to apply `co_await` for socket operations + Name resolution utilities */ #if __has_include(<WinSock2.h>) // use winsock #include <WS2tcpip.h> #include <WinSock2.h> #include <ws2def.h> /** @brief indicates current import: using Windows Socket API? */ /** @brief indicates current import: using <netinet/*.h>? */ static constexpr bool is_winsock = true; static constexpr bool is_netinet = false; using io_control_block = OVERLAPPED; #elif __has_include(<netinet/in.h>) // use netinet #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <unistd.h> static constexpr bool is_winsock = false; static constexpr bool is_netinet = true; /** * @brief Follow the definition of Windows `OVERLAPPED` * @see https://docs.microsoft.com/en-us/windows/win32/sync/synchronization-and-overlapped-input-and-output * @see https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped * @ingroup Network */ struct io_control_block { uint64_t internal; // uint32_t errc, int32_t flag uint64_t internal_high; // int64_t len, socklen_t addrlen union { struct { int32_t offset; int32_t offset_high; }; void* ptr; // sockaddr* addr; }; int64_t handle; // int64_t sd; }; #endif // winsock || netinet namespace coro { /** * @brief This is simply a view to storage. Be aware that it doesn't have ownership * @ingroup Network */ using io_buffer_t = gsl::span<std::byte>; static_assert(sizeof(io_buffer_t) <= sizeof(void*) * 2); /** * @brief A struct to describe "1 I/O request" to system API. * @ingroup Network * When I/O request is submitted, an I/O task becomes 1 coroutine handle */ class io_work_t : public io_control_block { public: coroutine_handle<void> task{}; io_buffer_t buffer{}; protected: /** * @see await_ready * @return true The given socket can be use for non-blocking operations * @return false For Windows, the return is always `false` */ bool ready() const noexcept; public: /** * @brief Multiple retrieving won't be a matter * @return uint32_t error code from the system */ uint32_t error() const noexcept; }; static_assert(sizeof(io_work_t) <= 56); /** * @brief Awaitable type to perform `sendto` I/O request * @see sendto * @see WSASendTo * @ingroup Network */ class io_send_to final : public io_work_t { private: /** * @brief makes an I/O request with given context(`coroutine_handle<void>`) * @throw std::system_error */ void suspend(coroutine_handle<void> t) noexcept(false); /** * @brief Fetch I/O result/error * @return int64_t return of `sendto` * * This function must be used through `co_await`. * Multiple invoke of this will lead to malfunction. */ int64_t resume() noexcept; public: bool await_ready() const noexcept { return this->ready(); } /** * @throw std::system_error */ void await_suspend(coroutine_handle<void> t) noexcept(false) { return this->suspend(t); } int64_t await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_send_to) == sizeof(io_work_t)); /** * @brief Awaitable type to perform `recvfrom` I/O request * @see recvfrom * @see WSARecvFrom * @ingroup Network */ class io_recv_from final : public io_work_t { private: /** * @brief makes an I/O request with given context(`coroutine_handle<void>`) * @throw std::system_error */ void suspend(coroutine_handle<void> t) noexcept(false); /** * @brief Fetch I/O result/error * @return int64_t return of `recvfrom` * * This function must be used through `co_await`. * Multiple invoke of this will lead to malfunction. */ int64_t resume() noexcept; public: bool await_ready() const noexcept { return this->ready(); } /** * @throw std::system_error */ void await_suspend(coroutine_handle<void> t) noexcept(false) { return this->suspend(t); } int64_t await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_recv_from) == sizeof(io_work_t)); /** * @brief Awaitable type to perform `send` I/O request * @see send * @see WSASend * @ingroup Network */ class io_send final : public io_work_t { private: /** * @brief makes an I/O request with given context(`coroutine_handle<void>`) * @throw std::system_error */ void suspend(coroutine_handle<void> t) noexcept(false); /** * @brief Fetch I/O result/error * @return int64_t return of `send` * * This function must be used through `co_await`. * Multiple invoke of this will lead to malfunction. */ int64_t resume() noexcept; public: bool await_ready() const noexcept { return this->ready(); } void await_suspend(coroutine_handle<void> t) noexcept(false) { return this->suspend(t); } int64_t await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_send) == sizeof(io_work_t)); /** * @brief Awaitable type to perform `recv` I/O request * @see recv * @see WSARecv * @ingroup Network */ class io_recv final : public io_work_t { private: /** * @brief makes an I/O request with given context(`coroutine_handle<void>`) * @throw std::system_error */ void suspend(coroutine_handle<void> t) noexcept(false); /** * @brief Fetch I/O result/error * @return int64_t return of `recv` * * This function must be used through `co_await`. * Multiple invoke of this will lead to malfunction. */ int64_t resume() noexcept; public: bool await_ready() const noexcept { return this->ready(); } void await_suspend(coroutine_handle<void> t) noexcept(false) { return this->suspend(t); } int64_t await_resume() noexcept { return this->resume(); } }; static_assert(sizeof(io_recv) == sizeof(io_work_t)); /** * @brief Constructs `io_send_to` awaitable with the given parameters * @param sd * @param remote * @param buf * @param work * @return io_send_to& * * @ingroup Network */ auto send_to(uint64_t sd, const sockaddr_in& remote, io_buffer_t buf, io_work_t& work) noexcept(false) -> io_send_to&; /** * @brief Constructs `io_send_to` awaitable with the given parameters * @param sd * @param remote * @param buf * @param work * @return io_send_to& * * @ingroup Network */ auto send_to(uint64_t sd, const sockaddr_in6& remote, io_buffer_t buf, io_work_t& work) noexcept(false) -> io_send_to&; /** * @brief Constructs `io_recv_from` awaitable with the given parameters * @param sd * @param remote * @param buf * @param work * @return io_recv_from& * * @ingroup Network */ auto recv_from(uint64_t sd, sockaddr_in& remote, io_buffer_t buf, io_work_t& work) noexcept(false) -> io_recv_from&; /** * @brief Constructs `io_recv_from` awaitable with the given parameters * @param sd * @param remote * @param buf * @param work * @return io_recv_from& * * @ingroup Network */ auto recv_from(uint64_t sd, sockaddr_in6& remote, io_buffer_t buf, io_work_t& work) noexcept(false) -> io_recv_from&; /** * @brief Constructs `io_send` awaitable with the given parameters * @param sd * @param buf * @param flag * @param work * @return io_send& * * @ingroup Network */ auto send_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, io_work_t& work) noexcept(false) -> io_send&; /** * @brief Constructs `io_recv` awaitable with the given parameters * @param sd * @param buf * @param flag * @param work * @return io_recv& * * @ingroup Network */ auto recv_stream(uint64_t sd, io_buffer_t buf, uint32_t flag, io_work_t& work) noexcept(false) -> io_recv&; /** * @brief Poll internal I/O works and invoke user callback * @param nano timeout in nanoseconds * @throw std::system_error * * @ingroup Network */ void poll_net_tasks(uint64_t nano) noexcept(false); /** * @brief Thin wrapper of `getaddrinfo` for IPv4 * * @param hint * @param host * @param serv * @param output * @return uint32_t Error code from the `getaddrinfo` that can be the argument of `gai_strerror` * @see getaddrinfo * @see gai_strerror * * @ingroup Network */ uint32_t get_address(const addrinfo& hint, // gsl::czstring host, gsl::czstring serv, gsl::span<sockaddr_in> output) noexcept; /** * @brief Thin wrapper of `getaddrinfo` for IPv6 * * @param hint * @param host * @param serv * @param output * @return uint32_t Error code from the `getaddrinfo` that can be the argument of `gai_strerror` * @see getaddrinfo * @see gai_strerror * * @ingroup Network */ uint32_t get_address(const addrinfo& hint, // gsl::czstring host, gsl::czstring serv, gsl::span<sockaddr_in6> output) noexcept; /** * @brief Thin wrapper of `getnameinfo` * * @param addr * @param name * @param serv can be `nullptr` * @param flags * @return uint32_t EAI_AGAIN ... * @see getnameinfo * * @ingroup Network */ uint32_t get_name(const sockaddr_in& addr, // gsl::basic_zstring<char, NI_MAXHOST> name, gsl::basic_zstring<char, NI_MAXSERV> serv, int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept; /** * @brief Thin wrapper of `getnameinfo` * @param addr * @param name * @param serv can be `nullptr` * @param flags * @return uint32_t EAI_AGAIN ... * @see getnameinfo * * @ingroup Network */ uint32_t get_name(const sockaddr_in6& addr, // gsl::basic_zstring<char, NI_MAXHOST> name, gsl::basic_zstring<char, NI_MAXSERV> serv, int32_t flags = NI_NUMERICHOST | NI_NUMERICSERV) noexcept; } // namespace coro #endif // COROUTINE_NET_IO_H
{ "alphanum_fraction": 0.630420712, "avg_line_length": 26.970074813, "ext": "h", "hexsha": "3c44827d01ad5fd5091201b0ec77f43543479b09", "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": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "dmitrykobets-msft/coroutine", "max_forks_repo_path": "interface/coroutine/net.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "dmitrykobets-msft/coroutine", "max_issues_repo_path": "interface/coroutine/net.h", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "114a4342b9ceaa149e3014f7b9346025d0722c19", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "dmitrykobets-msft/coroutine", "max_stars_repo_path": "interface/coroutine/net.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2690, "size": 10815 }
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @file testing/rndtiled.c * @version 1.3.0 * @author Aleksandr Mikhalev * @date 2017-11-07 * */ #ifdef MKL #include <mkl.h> #else #include <cblas.h> #include <lapacke.h> #endif #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <starsh.h> #include <starsh-randtlr.h> int main(int argc, char **argv) { if(argc != 6) { printf("%d arguments provided, but 5 are needed\n", argc-1); printf("randtlr N NB decay maxrank tol\n"); return 1; } int N = atoi(argv[1]); int block_size = atoi(argv[2]); double decay = atof(argv[3]); int maxrank = atoi(argv[4]); double tol = atof(argv[5]); int onfly = 0; char symm = 'N', dtype = 'd'; STARSH_int shape[2] = {N, N}; int info; srand(0); // Init STARS-H info = starsh_init(); if(info != 0) return info; // Generate problem by random matrices STARSH_randtlr *data; STARSH_kernel *kernel; info = starsh_application((void **)&data, &kernel, N, dtype, STARSH_RANDTLR, STARSH_RANDTLR_KERNEL1, STARSH_RANDTLR_NB, block_size, STARSH_RANDTLR_DECAY, decay, STARSH_RANDTLR_DIAG, (double)N, 0); if(info != 0) { printf("Problem was NOT generated (wrong parameters)\n"); return info; } // Init problem with given data and kernel and print short info STARSH_problem *P; info = starsh_problem_new(&P, 2, shape, symm, dtype, data, data, kernel, "Randomly generated tiled blr-matrix"); if(info != 0) return info; starsh_problem_info(P); // Init plain clusterization and print info STARSH_cluster *C; info = starsh_cluster_new_plain(&C, data, N, block_size); if(info != 0) return info; starsh_cluster_info(C); // Init tlr division into admissible blocks and print short info STARSH_blrf *F; info = starsh_blrf_new_tlr(&F, P, symm, C, C); if(info != 0) return info; starsh_blrf_info(F); // Approximate each admissible block STARSH_blrm *M; double time1 = omp_get_wtime(); info = starsh_blrm_approximate(&M, F, maxrank, tol, onfly); if(info != 0) return info; time1 = omp_get_wtime()-time1; // Print info about updated format and approximation starsh_blrf_info(F); starsh_blrm_info(M); printf("TIME TO APPROXIMATE: %e secs\n", time1); // Measure approximation error time1 = omp_get_wtime(); double rel_err = starsh_blrm__dfe_omp(M); time1 = omp_get_wtime()-time1; printf("TIME TO MEASURE ERROR: %e secs\nRELATIVE ERROR: %e\n", time1, rel_err); if(rel_err/tol > 10.) { printf("Resulting relative error is too big\n"); return 1; } // Free block low-rank matrix starsh_blrm_free(M); // Free block low-rank format starsh_blrf_free(F); // Free clusterization info starsh_cluster_free(C); // Free STARS_Problem instance starsh_problem_free(P); // Free randomly generated data starsh_randtlr_free(data); return 0; }
{ "alphanum_fraction": 0.6248875562, "avg_line_length": 29.7767857143, "ext": "c", "hexsha": "b4068be615b1d1327244cfd1a48f7b2d57ddc4ed", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-11-09T10:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-09T10:54:18.000Z", "max_forks_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "wawando/stars-h", "max_forks_repo_path": "testing/randtlr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "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": "wawando/stars-h", "max_issues_repo_path": "testing/randtlr.c", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "wawando/stars-h", "max_stars_repo_path": "testing/randtlr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 958, "size": 3335 }
/** * * @file qwrapper_dlantr.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:44:57 2014 * **/ #include <lapacke.h> #include "common.h" void CORE_dlantr_quark(Quark *quark); void CORE_dlantr_f1_quark(Quark *quark); /***************************************************************************//** * **/ void QUARK_CORE_dlantr(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const double *A, int LDA, int szeA, int szeW, double *result) { szeW = max(1, szeW); DAG_CORE_LANGE; QUARK_Insert_Task(quark, CORE_dlantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(double)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_dlantr_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const double *A, int LDA, int szeA, int szeW, double *result, double *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANGE; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_dlantr_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(double)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_dlantr_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &M, VALUE, sizeof(int), &N, VALUE, sizeof(double)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(double)*szeW, NULL, SCRATCH, sizeof(double), result, OUTPUT, sizeof(double)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlantr_quark = PCORE_dlantr_quark #define CORE_dlantr_quark PCORE_dlantr_quark #endif void CORE_dlantr_quark(Quark *quark) { double *normA; PLASMA_enum norm, uplo, diag; int M; int N; double *A; int LDA; double *work; quark_unpack_args_9(quark, norm, uplo, diag, M, N, A, LDA, work, normA); *normA = LAPACKE_dlantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlantr_f1_quark = PCORE_dlantr_f1_quark #define CORE_dlantr_f1_quark PCORE_dlantr_f1_quark #endif void CORE_dlantr_f1_quark(Quark *quark) { double *normA; PLASMA_enum norm, uplo, diag; int M; int N; double *A; int LDA; double *work; double *fake; quark_unpack_args_10(quark, norm, uplo, diag, M, N, A, LDA, work, normA, fake); *normA = LAPACKE_dlantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); }
{ "alphanum_fraction": 0.4758972181, "avg_line_length": 33.8776978417, "ext": "c", "hexsha": "9d1e9d141ef71efd478094ba5f3c06740b64dfe1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlantr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlantr.c", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlantr.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1217, "size": 4709 }
#ifndef S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H #define S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H #include <s3d/utilities/eigen.h> #include <vector> #include <gsl/gsl> namespace s3d { struct ViewerContext; class ViewerDepthConverter { public: using Point = Eigen::Vector2d; using Pointf = Eigen::Vector2f; explicit ViewerDepthConverter(gsl::not_null<ViewerContext*> context); std::vector<float> computePerceivedDepth(const std::vector<float>& disparitiesPercent); // horizontal position and depth in meters std::vector<Pointf> computeDepthPositions(const std::vector<Point>& imagePoints, const std::vector<float>& disparities); float computePerceivedDepth(float disparityPercent); // 0 in the middle of the image float computeHorizontalPosition(float imageX); std::vector<float> computeHorizontalPositions(const std::vector<Point>& imagePoints); void setViewerContext(gsl::not_null<ViewerContext*> viewerContext); private: ViewerContext* viewerContext_; }; } // namespace s3d #endif // S3D_DISPARITY_VIEWER_DEPTH_CONVERTER_H
{ "alphanum_fraction": 0.7536101083, "avg_line_length": 26.380952381, "ext": "h", "hexsha": "2459cef6d834706fe79e469e01f13bff13ff4d58", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_line_length": 89, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/core/s3d/include/s3d/disparity/viewer_depth_converter.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 258, "size": 1108 }
/* rstat/rquantile.c * * Copyright (C) 2015 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_sort.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_rstat.h> /* * Running quantile calculation based on the paper * * [1] R. Jain and I. Chlamtac, "The P^2 algorithm for dynamic * calculation of quantiles and histograms without storing * observations", Communications of the ACM, October 1985 */ static double calc_psq(const double qp1, const double q, const double qm1, const double d, const double np1, const double n, const double nm1); gsl_rstat_quantile_workspace * gsl_rstat_quantile_alloc(const double p) { gsl_rstat_quantile_workspace *w; w = calloc(1, sizeof(gsl_rstat_quantile_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->p = p; gsl_rstat_quantile_reset(w); return w; } /* gsl_rstat_quantile_alloc() */ void gsl_rstat_quantile_free(gsl_rstat_quantile_workspace *w) { free(w); } /* gsl_rstat_quantile_free() */ int gsl_rstat_quantile_reset(gsl_rstat_quantile_workspace *w) { const double p = w->p; size_t i; /* initialize positions n */ for (i = 0; i < 5; ++i) w->npos[i] = i + 1; /* initialize n' */ w->np[0] = 1.0; w->np[1] = 1.0 + 2.0 * p; w->np[2] = 1.0 + 4.0 * p; w->np[3] = 3.0 + 2.0 * p; w->np[4] = 5.0; /* initialize dn' */ w->dnp[0] = 0.0; w->dnp[1] = 0.5 * p; w->dnp[2] = p; w->dnp[3] = 0.5 * (1.0 + p); w->dnp[4] = 1.0; w->n = 0; return GSL_SUCCESS; } int gsl_rstat_quantile_add(const double x, gsl_rstat_quantile_workspace *w) { if (w->n < 5) { w->q[w->n] = x; } else { int i; int k = -1; if (w->n == 5) { /* initialization: sort the first five heights */ gsl_sort(w->q, 1, w->n); } /* step B1: find k such that q_k <= x < q_{k+1} */ if (x < w->q[0]) { w->q[0] = x; k = 0; } else if (x >= w->q[4]) { w->q[4] = x; k = 3; } else { for (i = 0; i <= 3; ++i) { if (w->q[i] <= x && x < w->q[i + 1]) { k = i; break; } } } if (k < 0) { /* we could get here if x is nan */ GSL_ERROR ("invalid input argument x", GSL_EINVAL); } /* step B2(a): update n_i */ for (i = k + 1; i <= 4; ++i) ++(w->npos[i]); /* step B2(b): update n_i' */ for (i = 0; i < 5; ++i) w->np[i] += w->dnp[i]; /* step B3: update heights */ for (i = 1; i <= 3; ++i) { double ni = (double) w->npos[i]; double d = w->np[i] - ni; if ((d >= 1.0 && (w->npos[i + 1] - w->npos[i] > 1)) || (d <= -1.0 && (w->npos[i - 1] - w->npos[i] < -1))) { int dsign = (d > 0.0) ? 1 : -1; double qp1 = w->q[i + 1]; double qi = w->q[i]; double qm1 = w->q[i - 1]; double np1 = (double) w->npos[i + 1]; double nm1 = (double) w->npos[i - 1]; double qp = calc_psq(qp1, qi, qm1, (double) dsign, np1, ni, nm1); if (qm1 < qp && qp < qp1) w->q[i] = qp; else { /* use linear formula */ w->q[i] += dsign * (w->q[i + dsign] - qi) / ((double) w->npos[i + dsign] - ni); } w->npos[i] += dsign; } } } ++(w->n); return GSL_SUCCESS; } /* gsl_rstat_quantile_add() */ double gsl_rstat_quantile_get(gsl_rstat_quantile_workspace *w) { if (w->n >= 5) { return w->q[2]; } else { /* not yet initialized */ gsl_sort(w->q, 1, w->n); return gsl_stats_quantile_from_sorted_data(w->q, 1, w->n, w->p); } } /* gsl_rstat_quantile_get() */ static double calc_psq(const double qp1, const double q, const double qm1, const double d, const double np1, const double n, const double nm1) { double outer = d / (np1 - nm1); double inner_left = (n - nm1 + d) * (qp1 - q) / (np1 - n); double inner_right = (np1 - n - d) * (q - qm1) / (n - nm1); return q + outer * (inner_left + inner_right); } /* calc_psq() */
{ "alphanum_fraction": 0.5150239234, "avg_line_length": 25.1201923077, "ext": "c", "hexsha": "0c4e84ad43c87d400e138d25345a727fa720e8b3", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rstat/rquantile.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/rstat/rquantile.c", "max_line_length": 97, "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/rstat/rquantile.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": 1670, "size": 5225 }
/* Matrix multiplication. Based on the amazing: https://github.com/HandsOnOpenCL/Exercises-Solutions/tree/a908ac3f0fadede29f2735eb1264b0db7f4311a0/Solutions/Exercise08 The most basic / useful application where OpenCL might be faster than CPU. TODO: make a SERIOUS matrix implementation. Also compare with existing SERIOUS CPU and GPU implementations: - http://stackoverflow.com/questions/1907557/optimized-matrix-multiplication-in-c - http://stackoverflow.com/questions/12289235/simple-and-fast-matrix-vector-multiplication-in-c-c - https://www.quora.com/What-is-the-best-way-to-multiply-two-matrices-in-C++ - http://stackoverflow.com/questions/25900312/optimizing-batched-matrix-multiplication-opencl-code Serious CPU implementation means it considers: - caching - SIMD Articles: - http://www.netlib.org/utk/papers/autoblock/node2.html - http://codereview.stackexchange.com/questions/101144/simd-matrix-multiplication */ #include "common.h" #include <cblas.h> #include <clBLAS.h> #define NELEMS(a) sizeof(a)/sizeof(a[0]) #define UNUSED(x) (void)(x) /* TODO how to auto tune this? * GCC 6 was not smart enough to use widest type automatically: * anything larger than the widest type just dropped perf drastically. */ #define VECTOR_NELEMS 4 #define VECTOR_SIZEOF (VECTOR_NELEMS * sizeof(F)) typedef cl_float F; typedef F Vec __attribute__ ((vector_size(VECTOR_SIZEOF))); /* Stuff reused across OpenCL calls. * It would not be fair to consider their alocation time for each call, * as the functions will be called millions of times. * * TODO: also factor out the kernel compile time. * Currently recompiled every time. * Implementations already cache compiled kernels, but we would need * to call each function multiple times. * */ typedef struct { Common common; /* We only factor out the allocation of those buffers. * Data transfer time with clEnqueueWriteBuffer must still be considered. */ cl_mem buf_a, buf_b, buf_c; } Cache; typedef void (*MatMul)(const F *A, const F *B, F *C, size_t n, Cache *cache); void cl_buf_init(Cache *cache, size_t mat_sizeof) { cache->buf_a = clCreateBuffer(cache->common.context, CL_MEM_READ_ONLY, mat_sizeof, NULL, NULL); cache->buf_b = clCreateBuffer(cache->common.context, CL_MEM_READ_ONLY, mat_sizeof, NULL, NULL); cache->buf_c = clCreateBuffer(cache->common.context, CL_MEM_WRITE_ONLY, mat_sizeof, NULL, NULL); } void cl_buf_deinit(Cache *cache) { clReleaseMemObject(cache->buf_a); clReleaseMemObject(cache->buf_b); clReleaseMemObject(cache->buf_c); } /* No, this was not created for debugging, my code is flawless from the first try. */ void mat_print(const F *A, size_t n) { size_t i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { printf("%f ", A[i*n+j]); } puts(""); } } /* Zero a matrix. */ void mat_zero(F *A, size_t n) { size_t i, n2; n2 = n*n; for (i = 0; i < n2; ++i) { A[i] = 0.0; } } /* Initialize a random matrix. */ void mat_rand(F *A, size_t n) { size_t i, n2; n2 = n*n; for (i = 0; i < n2; ++i) { A[i] = ((float)rand()) / ((float)RAND_MAX); } } /* Initialize a random matrix. */ void mat_trans(F *A, size_t n) { size_t i, j, i1, i2; F tmp; for (i = 0; i < n; ++i) { for (j = 0; j < i; ++j) { i1 = i*n+j; i2 = j*n+i; tmp = A[i1]; A[i1] = A[i2]; A[i2] = tmp; } } } /* Check if two matrices are equal with given mean squared err_maxor. */ int mat_eq(const F *A, const F *B, size_t n) { const F err_max = 10e-3; F err, diff, a, b; size_t i, i_max; err = 0.0; i_max = n*n; for (i = 0; i < i_max; ++i) { a = A[i]; b = B[i]; diff = a - b; err += diff * diff; } return (sqrt(err) / i_max) < err_max; } void mat_assert_eq(const F *A, const F *B, size_t n) { if (!mat_eq(A, B, n)) { puts(""); mat_print(A, n); puts(""); mat_print(B, n); assert(0); } } size_t zmin(size_t x, size_t y) { return (x < y) ? x : y; } /* C = A*B, width n, naive. */ void mat_mul_cpu(const F *A, const F *B, F *C, size_t n, Cache *cache) { F tmp; size_t i, j, k; UNUSED(cache); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { tmp = 0.0; for (k = 0; k < n; ++k) { tmp += A[i*n+k] * B[k*n+j]; } C[i*n+j] = tmp; } } } /* Transpose matrix B to increase cache hits. */ void mat_mul_cpu_trans(const F *A, const F *B, F *C, size_t n, Cache *cache) { F tmp; size_t i, j, k; UNUSED(cache); mat_trans((F*)B, n); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { tmp = 0.0; for (k = 0; k < n; ++k) { tmp += A[i*n+k] * B[j*n+k]; } C[i*n+j] = tmp; } } mat_trans((F*)B, n); } /* Zero vector. */ void vec_zero(Vec *vec, size_t vec_n) { size_t i; for (i = 0; i < vec_n; ++i) { (*vec)[i] = 0.0; } } /* Load vector from array. */ void vec_load(Vec *vec, size_t vec_n, const F* A, size_t A_base) { size_t i; for (i = 0; i < vec_n; ++i) { (*vec)[i] = A[A_base + i]; } } /* Sum elements of the vector. */ F vec_sum(Vec vec, size_t vec_n) { size_t i; F sum; sum = 0.0; for (i = 0; i < vec_n; ++i) { sum += vec[i]; } return sum; } /* Transpose matrix B to both: * * - increase cache hits * - simd GCC vector extensions which is made possible. * by the transposition, to increase likelyhood of SIMDs. * * Note that GCC 6 O=3 is smart enough to use SIMD * even for the naive CPU method. However this was still way faster. * */ void mat_mul_cpu_trans_vec(const F *A, const F *B, F *C, size_t n, Cache *cache) { F tmpf; size_t i, j, k, k_max, ai, bi; Vec tmp, a, b; UNUSED(cache); mat_trans((F*)B, n); k_max = (n / VECTOR_NELEMS) * VECTOR_NELEMS; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { vec_zero(&tmp, VECTOR_NELEMS); for (k = 0; k < k_max; k += VECTOR_NELEMS) { ai = i * n + k; bi = j * n + k; vec_load(&a, VECTOR_NELEMS, A, ai); vec_load(&b, VECTOR_NELEMS, B, bi); tmp += a * b; } tmpf = 0.0; for (; k < n; ++k) { tmpf += A[i*n+k] * B[j*n+k]; } C[i*n+j] = vec_sum(tmp, VECTOR_NELEMS) + tmpf; } } mat_trans((F*)B, n); } /* Blocked matrix multiplication. * TODO slower than transpose, sometimes similar timing to naive. * Why do they say that this is better? * */ void mat_mul_cpu_block(const F *A, const F *B, F *C, size_t n, Cache *cache) { size_t ib, jb, kb, i, j, k, i_max, j_max, k_max, nb ; F tmp; UNUSED(cache); nb = lround(sqrt(n)); for (ib = 0; ib < n; ib += nb) { i_max = zmin(ib + nb, n); for (jb = 0; jb < n; jb += nb) { k_max = zmin(jb + nb, n); for (kb = 0; kb < n; kb += nb) { j_max = zmin(kb + nb, n); /* TODO would be cool to recurse here, but would require more offset parameters, * likely similar to tose of CBLAS. */ for (i = ib; i < i_max; ++i) { for (j = kb; j < j_max; ++j) { tmp = 0.0; for (k = jb; k < k_max; ++k) { tmp += A[i*n+k] * B[k*n+j]; } C[i*n+j] += tmp; } } } } } } /* The golden single thread CPU standard. */ void mat_mul_cpu_cblas(const F *A, const F *B, F *C, size_t n, Cache *cache) { UNUSED(cache); cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0, A, n, B, n, 0.0, C, n ); } /* Simplest possible CL implementation. No speedup. */ void mat_mul_cl(const F *A, const F *B, F *C, size_t n, Cache *cache) { cl_uint ncl; size_t global_work_size[2], mat_sizeof; /* Setup variables. */ global_work_size[0] = n; global_work_size[1] = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ common_create_kernel_file(&cache->common, "matmul.cl", NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, sizeof(ncl), &ncl); clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 2, NULL, global_work_size, NULL, 0, NULL, NULL); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } /* Cache rows in private memory. Drastic speedups expected over naive CPU. */ void mat_mul_cl_row_priv(const F *A, const F *B, F *C, size_t n, Cache *cache) { char options[256]; cl_uint ncl; size_t global_work_size, mat_sizeof; /* Setup variables. */ global_work_size = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ snprintf(options, sizeof(options), "-DPRIV_ROW_SIZE=%ju", n); common_create_kernel_file(&cache->common, "matmul_row_priv.cl", options); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, sizeof(ncl), &ncl); clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, NULL, 0, NULL, NULL); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } /* Let's see if this is any different from local memory. * Outcome: much slower than private memory, slower than naive method. */ void mat_mul_cl_row_local(const F *A, const F *B, F *C, size_t n, Cache *cache) { cl_uint ncl; size_t global_work_size, local_work_size, mat_sizeof; /* Setup variables. */ /* Cannot be larger than 1 on this example, otherwise memory conflicts * will happen between work items. */ local_work_size = 1; global_work_size = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ common_create_kernel_file(&cache->common, "matmul_row_local.cl", NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, n * sizeof(F), NULL); clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl); clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } /* Like row private, but to reduce global memory accesses, * we copy only once per work group to local memory. * * Each work group contains a few rows of A. * * We load the first column, multiply all rows by that column, synrhconize, * load another column, and so on. * * This leads to a thread blockage / memory access tradeoff. * * We make work groups as large as possible to reload memory less times. */ void mat_mul_cl_row_priv_col_local(const F *A, const F *B, F *C, size_t n, Cache *cache) { char options[256]; cl_uint ncl; size_t global_work_size, local_work_size, mat_sizeof; /* Setup variables. */ global_work_size = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ snprintf(options, sizeof(options), "-DPRIV_ROW_SIZE=%ju", n); common_create_kernel_file(&cache->common, "matmul_row_priv_col_local.cl", options); local_work_size = 0; clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(local_work_size), &local_work_size, NULL); local_work_size = zmin(local_work_size, n); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, n * sizeof(F), NULL); clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl); clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } /* Copy as many cols from B as possibl to the local memory, only then start multiplying. * This leads to less memory barrier hits. * How many rows we copy is limited by the local memory size, ideally the entire matrix will fit. */ void mat_mul_cl_row_priv_cols_local(const F *A, const F *B, F *C, size_t n, Cache *cache) { char options[256]; cl_uint ncl, n_local_cols; cl_ulong local_mem_size; size_t col_size, global_work_size, local_work_size, mat_sizeof; /* Setup variables. */ col_size = n * sizeof(F); global_work_size = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ snprintf(options, sizeof(options), "-DPRIV_ROW_SIZE=%ju", n); common_create_kernel_file(&cache->common, "matmul_row_priv_cols_local.cl", options); local_work_size = 0; clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(local_work_size), &local_work_size, NULL); local_work_size = zmin(local_work_size, n); local_mem_size = 0; clGetDeviceInfo(cache->common.device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(local_mem_size), &local_mem_size, NULL); /* TODO: can blow up without that - 1. Why? * It only reaches the max without it, not crosses, right? * So bug in the kernel? */ n_local_cols = zmin(local_mem_size / col_size, n) - 1; /*puts("");*/ /*printf("max memory %llu\n", (unsigned long long)local_mem_size);*/ /*printf("n_local_cols %llu\n", (unsigned long long)n_local_cols);*/ /*printf("memory %llu\n", (unsigned long long)n_local_cols * n * sizeof(F));*/ clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, n_local_cols * col_size, NULL); clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl); clSetKernelArg(cache->common.kernel, 5, sizeof(n_local_cols), &n_local_cols); clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } void mat_mul_cl_block(const F *A, const F *B, F *C, size_t n, Cache *cache) { cl_uint ncl, nblkcl; size_t global_work_size[2], local_work_size[2], mat_sizeof, nblk; /* Setup variables. */ global_work_size[0] = n; global_work_size[1] = n; mat_sizeof = n * n * sizeof(F); ncl = n; /* Run kernel. */ common_create_kernel_file(&cache->common, "matmul_block.cl", NULL); clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(nblk), &nblk, NULL); nblk = sqrt(zmin(nblk, n)); nblk = zmin(nblk, 3); nblkcl = nblk; local_work_size[0] = nblk; local_work_size[1] = nblk; clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a); clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b); clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c); clSetKernelArg(cache->common.kernel, 3, nblk * nblk * sizeof(F), NULL); printf("nblk = %llu\n", (unsigned long long)nblk); printf("local memory = %llu\n", (unsigned long long)2 * nblk * nblk * sizeof(F)); clSetKernelArg(cache->common.kernel, 4, nblk * nblk * sizeof(F), NULL); clSetKernelArg(cache->common.kernel, 5, sizeof(ncl), &ncl); clSetKernelArg(cache->common.kernel, 6, sizeof(nblkcl), &nblkcl); clEnqueueNDRangeKernel( cache->common.command_queue, cache->common.kernel, 2, NULL, global_work_size, local_work_size, 0, NULL, NULL ); clFlush(cache->common.command_queue); clFinish(cache->common.command_queue); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } void mat_mul_cl_clblas(const F *A, const F *B, F *C, size_t n, Cache *cache) { cl_event event; size_t mat_sizeof; mat_sizeof = n * n * sizeof(F); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL); clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL); clblasSgemm( clblasRowMajor, clblasNoTrans, clblasNoTrans, n, n, n, 1.0, cache->buf_a, 0, n, cache->buf_b, 0, n, 0.0, cache->buf_c, 0, n, 1, &(cache->common.command_queue), 0, NULL, &event ); clWaitForEvents(1, &event); clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL); } double bench(MatMul f, const F *A, const F *B, F *C, F *C_ref, size_t n, Cache *cache) { double dt, time; mat_zero(C, n); time = common_get_nanos(); f(A, B, C, n, cache); dt = common_get_nanos() - time; if (C_ref != NULL) mat_assert_eq(C, C_ref, n); printf("%.3e ", dt); fflush(stdout); return dt; } int main(int argc, char **argv) { srand(time(NULL)); Cache cache; double max_runtime; /* Overly slow ones commented out by default. */ MatMul mat_mul_funcs[] = { /*mat_mul_cpu,*/ mat_mul_cpu_trans, mat_mul_cpu_trans_vec, mat_mul_cpu_block, mat_mul_cpu_cblas, /*mat_mul_cl,*/ mat_mul_cl_row_priv, mat_mul_cl_row_local, mat_mul_cl_row_priv_col_local, mat_mul_cl_row_priv_cols_local, /* TODO broken for larger matrics, some cells contain trash. * Likey some memory overflow problem. */ /*mat_mul_cl_block,*/ mat_mul_cl_clblas, }; int first, func_done[NELEMS(mat_mul_funcs)] = {0}; size_t f, i; size_t mat_sizeof; /* CLI args. */ if (argc > 1) { max_runtime = strtod(argv[1], NULL); } else { max_runtime = 1.0; } common_init(&(cache.common), NULL); /* Unit test 2x2. */ { const F A[] = { 1.0, 2.0, 3.0, 4.0 }; const F B[] = { 5.0, 6.0, 7.0, 8.0 }; enum N { n = 2 }; F C[n*n]; const F C_ref[] = { 19.0, 22.0, 43.0, 50.0 }; cl_buf_init(&cache, n * n * sizeof(F)); for (f = 0; f < sizeof(mat_mul_funcs)/sizeof(mat_mul_funcs[0]); ++f) { mat_zero(C, n); mat_mul_funcs[f](A, B, C, n, &cache); mat_assert_eq(C, C_ref, n); } cl_buf_deinit(&cache); } /* Unit test 4x4. */ { const F A[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, }; const F B[] = { 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, }; const F C_ref[] = { 250.0, 260.0, 270.0, 280.0, 618.0, 644.0, 670.0, 696.0, 986.0, 1028.0, 1070.0, 1112.0, 1354.0, 1412.0, 1470.0, 1528.0, }; enum N { n = 4 }; F C[n*n]; cl_buf_init(&cache, n * n * sizeof(F)); for (f = 0; f < NELEMS(mat_mul_funcs); ++f) { mat_zero(C, n); mat_mul_funcs[f](A, B, C, n, &cache); mat_assert_eq(C, C_ref, n); } cl_buf_deinit(&cache); } /* Benchmarks. */ { double dt; F *A = NULL, *B = NULL, *C = NULL, *C_ref = NULL, *dst = NULL, *ref = NULL; int done; size_t n = 2; puts("#matmul"); done = 0; while(1) { printf("%zu ", (size_t)log2(n)); mat_sizeof = n * n * sizeof(F); /* CPU setup. */ A = aligned_alloc(VECTOR_SIZEOF, mat_sizeof); B = aligned_alloc(VECTOR_SIZEOF, mat_sizeof); C = aligned_alloc(VECTOR_SIZEOF, mat_sizeof); C_ref = aligned_alloc(VECTOR_SIZEOF, mat_sizeof); if (NULL == A || NULL == B || NULL == C) { printf("error: could not allocate memory for n = %zu", n); break; } mat_rand(A, n); mat_rand(B, n); cl_buf_init(&cache, mat_sizeof); first = 1; for (f = 0; f < NELEMS(mat_mul_funcs); ++f) { if (func_done[f]) { printf("%*s", 10, ""); } else { if (first) { dst = C_ref; ref = NULL; first = 0; } else { dst = C; ref = C_ref; } dt = bench(mat_mul_funcs[f], A, B, dst, ref, n, &cache); if (dt > max_runtime) func_done[f] = 1; } } puts(""); done = 1; for (i = 0; i < NELEMS(mat_mul_funcs); ++i) { if (!func_done[i]) { done = 0; break; } } if (done) break; n *= 2; /* CPU deinit. */ free(A); free(B); free(C); free(C_ref); cl_buf_deinit(&cache); } common_deinit(&cache.common); } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5865091927, "avg_line_length": 34.4120111732, "ext": "c", "hexsha": "2dfd4757560ee25430cd77fb4c395de420429ca1", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "liujiamingustc/phd", "max_forks_repo_path": "awesome/c_cpp/cpp-cheat/opencl/interactive/matmul.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "liujiamingustc/phd", "max_issues_repo_path": "awesome/c_cpp/cpp-cheat/opencl/interactive/matmul.c", "max_line_length": 139, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "liujiamingustc/phd", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/opencl/interactive/matmul.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z", "num_tokens": 7361, "size": 24639 }
#ifndef matops_h #define matops_h #include <ceed.h> #include <petsc.h> #include "../include/structs.h" // This function uses libCEED to compute the local action of an operator PetscErrorCode ApplyLocalCeedOp(Vec X, Vec Y, UserMult user); // This function uses libCEED to compute the non-linear residual PetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx); // This function uses libCEED to apply the Jacobian for assembly via a SNES PetscErrorCode ApplyJacobianCoarse_Ceed(SNES snes, Vec X, Vec Y, void *ctx); // This function uses libCEED to compute the action of the Jacobian PetscErrorCode ApplyJacobian_Ceed(Mat A, Vec X, Vec Y); // This function uses libCEED to compute the action of the prolongation operator PetscErrorCode Prolong_Ceed(Mat A, Vec X, Vec Y); // This function uses libCEED to compute the action of the restriction operator PetscErrorCode Restrict_Ceed(Mat A, Vec X, Vec Y); // This function returns the computed diagonal of the operator PetscErrorCode GetDiag_Ceed(Mat A, Vec D); // This function calculates the strain energy in the final solution PetscErrorCode ComputeStrainEnergy(DM dm_energy, UserMult user, CeedOperator op_energy, Vec X, PetscReal *energy); // this function checks to see if the computed energy is close enough to reference file energy. PetscErrorCode RegressionTests_solids(AppCtx app_ctx, PetscReal energy); #endif // matopts_h
{ "alphanum_fraction": 0.7518694765, "avg_line_length": 38.7105263158, "ext": "h", "hexsha": "83981758bc8e5f81847f73d9bd4e601aa046bc20", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/solids/include/matops.h", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/solids/include/matops.h", "max_line_length": 95, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/solids/include/matops.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 346, "size": 1471 }
// // her2.h // Linear Algebra Template Library // // Created by Rodney James on 12/23/11. // Copyright (c) 2011 University of Colorado Denver. All rights reserved. // #ifndef _her2_h #define _her2_h /// @file her2.h Performs complex outer product of two vectors. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs a vector outer product of two complex vectors. /// /// For a complex Hermitian matrix A, complex vectors x and y, and complex scalar alpha, /// /// A := alpha * x * y' + conj(alpha) * y * x' + A /// /// is computed. The result is Hermitian and is stored as either upper or lower triangular in A. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether A is stored as upper or lower triangular. /// /// if uplo = 'U' or 'u' then A is upper triangular /// if uplo = 'L' or 'l' then A is lower triangular /// /// @param n Specifies the order of the matrix A. n>=0 /// @param alpha Complex scalar. /// @param x Pointer to complex vector x. /// @param incx Increment of the vector x. x!=0 /// @param y Pointer to complex vector y. /// @param incy Increment of the vector y. y!=0 /// @param A Pointer to complex Hermitian n-by-n matrix A.If uplo = 'U' or 'u' then only the upper /// triangular part of A is referenced and the lower part is not referenced. If uplo = 'L' or 'l' then /// only the lower triangular part of A is referenced and the upper part is not referenced. /// @param ldA Column length of matrix A. ldA>=n. /// @ingroup BLAS template <typename real_t> int HER2(char uplo, int_t n, complex<real_t> alpha, complex<real_t> *x, int_t incx, complex<real_t> *y, int_t incy, complex<real_t> *A, int_t ldA) { using std::conj; using std::real; using std::toupper; const complex<real_t> zero(0.0,0.0); complex<real_t> tx,ty; int_t i,j,kx,ky,jx,ix,jy,iy; uplo=toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<n) return -9; else if((n==0)||(alpha==zero)) return 0; if((incx==1)&&(incy==1)) { if(uplo=='U') { for(j=0;j<n;j++) { tx=conj(alpha*x[j]); ty=alpha*conj(y[j]); for(i=0;i<j;i++) A[i]+=x[i]*ty+y[i]*tx; A[j]=real(A[j])+real(x[j]*ty+y[j]*tx); A+=ldA; } } else { for(j=0;j<n;j++) { tx=conj(alpha*x[j]); ty=alpha*conj(y[j]); A[j]=real(A[j])+real(x[j]*ty+y[j]*tx); for(i=j+1;i<n;i++) A[i]+=x[i]*ty+y[i]*tx; A+=ldA; } } } else { kx=(incx>0)?0:(1-n)*incx; ky=(incy>0)?0:(1-n)*incy; if(uplo=='U') { jx=kx; jy=ky; for(j=0;j<n;j++) { tx=conj(alpha*x[jx]); ty=alpha*conj(y[jy]); ix=kx; iy=ky; for(i=0;i<j;i++) { A[i]+=x[ix]*ty+y[iy]*tx; ix+=incx; iy+=incy; } A[j]=real(A[j])+real(x[jx]*ty+y[jy]*tx); A+=ldA; jx+=incx; jy+=incy; } } else { jx=kx; jy=ky; for(j=0;j<n;j++) { tx=conj(alpha*x[jx]); ty=alpha*conj(y[jy]); ix=jx; iy=jy; A[j]=real(A[j])+real(x[jx]*ty+y[jy]*tx); for(i=j+1;i<n;i++) { ix+=incx; iy+=incy; A[i]+=x[ix]*ty+y[iy]*tx; } jx+=incx; jy+=incy; A+=ldA; } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int HER2<float>(char uplo, int_t n, complex<float> alpha, complex<float> *x, int_t incx, complex<float> *y, int_t incy, complex<float> *A, int_t ldA) { uplo=std::toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(ldA<n) return -7; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_cher2(CblasColMajor,Uplo,n,&alpha,x,incx,y,incy,A,ldA); return 0; } template <> int HER2<double>(char uplo, int_t n, complex<double> alpha, complex<double> *x, int_t incx, complex<double> *y, int_t incy, complex<double> *A, int_t ldA) { uplo=std::toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(ldA<n) return -7; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_zher2(CblasColMajor,Uplo,n,&alpha,x,incx,y,incy,A,ldA); return 0; } #endif } #endif
{ "alphanum_fraction": 0.4742019302, "avg_line_length": 27.7731958763, "ext": "h", "hexsha": "3e1487bbf01c9c3abf256d774d1e03a60f92486e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/her2.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/her2.h", "max_line_length": 169, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/her2.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 1578, "size": 5388 }
/* Copyright (c) 2011-2017, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION 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 ``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 OWNER 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. */ #pragma once namespace amgx { template <class Matrix> typename Matrix::value_type estimate_largest_eigen_value(Matrix &A); } #include <norm.h> #include <multiply.h> #include <blas.h> namespace amgx { template <class Matrix> typename Matrix::value_type estimate_largest_eigen_value(Matrix &A) { typedef typename Matrix::TConfig TConfig; typedef typename Matrix::value_type ValueTypeA; typedef typename TConfig::VecPrec ValueTypeB; typedef Vector<TConfig> VVector; VVector x(A.get_num_rows()), y(A.get_num_rows()); fill(x, 1); for (int i = 0; i < 20; i++) { ValueTypeB Lmax = get_norm(A, x, LMAX); scal(x, ValueTypeB(1) / Lmax); multiply(A, x, y); x.swap(y); } ValueTypeB retval = get_norm(A, x, L2) / get_norm(A, y, L2); return retval; } } // namespace amgx
{ "alphanum_fraction": 0.7301784973, "avg_line_length": 37.0615384615, "ext": "h", "hexsha": "14443ca7d4dc6db7ba0b2fe0a30789b47c38ec17", "lang": "C", "max_forks_count": 112, "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:46:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-16T11:00:10.000Z", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_path": "3rd_party/AMGX/base/include/miscmath.h", "max_issues_count": 143, "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:13:16.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-18T10:30:34.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_path": "3rd_party/AMGX/base/include/miscmath.h", "max_line_length": 93, "max_stars_count": 278, "max_stars_repo_head_hexsha": "11af85608ea0f4720e03cbcc920521745f9e40e5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "fizmat/AMGX", "max_stars_repo_path": "base/include/miscmath.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:54:04.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-13T18:28:31.000Z", "num_tokens": 545, "size": 2409 }
#include <stdbool.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include "numstates.h" int main(int argc, char *argv[]) { int num_bands = 2; double t = 1.0; double E0 = 6.0; double deltaE = 14.0; void Efn(double k[3], gsl_vector *energies) { double cx = cos(2.0 * M_PI * k[0]); double cy = cos(2.0 * M_PI * k[1]); double cz = cos(2.0 * M_PI * k[2]); double tk = -2.0 * t * (cx + cy + cz); int i; double E0_band; for (i = 0; i < num_bands; i++) { E0_band = E0 + ((double)i) * deltaE; gsl_vector_set(energies, i, E0_band + tk); } } int na = 8; int nb = 8; int nc = 8; int G_order[3] = {0, 1, 2}; int G_neg[3] = {1, 1, 1}; bool use_cache = true; EnergyCache *Ecache = init_EnergyCache(na, nb, nc, num_bands, G_order, G_neg, Efn, use_cache); double E = 0.0; double count = NumStates(E, Ecache); double eps = 1e-9; double expected_E0 = 0.0; if (fabs(count - expected_E0) > eps) { printf("Incorrect occupation; got %f, expected %f\n", count, expected_E0); return 1; } E = 6.0; count = NumStates(E, Ecache); double expected_E6 = 0.5; if (fabs(count - expected_E6) > eps) { printf("Incorrect occupation; got %f, expected %f\n", count, expected_E6); return 1; } E = 12.0; count = NumStates(E, Ecache); double expected_E12 = 1.0; if (fabs(count - expected_E12) > eps) { printf("Incorrect occupation; got %f, expected %f\n", count, expected_E12); return 1; } E = 26.0; count = NumStates(E, Ecache); double expected_E24 = 2.0; if (fabs(count - expected_E24) > eps) { printf("Incorrect occupation; got %f, expected %f\n", count, expected_E24); return 1; } printf("Numstates test passed.\n"); return 0; }
{ "alphanum_fraction": 0.5550978373, "avg_line_length": 27.7428571429, "ext": "c", "hexsha": "c050bdb9f2ee2842d3a68da0b5b776b0b2ffa84b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_path": "numstates_test.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_path": "numstates_test.c", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_path": "numstates_test.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 643, "size": 1942 }
/* * ----------------------------------------------------------------- * pmsr_lib.c * Pairwise Mixing Stirred Reactor Library * Version: 2.0 * Last Update: Oct 1, 2019 * * This is a computational library with routines to implement * a Pairwise Mixing Stirred Reactor (PMSR) model. * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2019 by Americo Barbosa da Cunha Junior * ----------------------------------------------------------------- */ #include <math.h> #include <time.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_errno.h> #include "../include/pmsr_lib.h" /* * ----------------------------------------------------------------- * pmsr_title * * This function prints the program title on the screen. * * last update: Oct 20, 2009 * ----------------------------------------------------------------- */ void pmsr_title() { time_t curtime = time (NULL); struct tm *loctime = localtime (&curtime); printf("\n"); printf("============================================="); printf("\n Pairwise Mixing Stirred Reactor --- PMSR\n"); printf("\n by"); printf("\n Americo Barbosa da Cunha Junior"); printf("\n americo.cunhajr@gmail.com\n"); printf("\n Date:"); printf("\n %s", asctime(loctime) ); printf("============================================="); printf("\n"); return; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_input * * This function receives PMSR parameters from user * and returns GSL_SUCCESS if there is no error. * * Input: * seed - RNG seed * Np - # of particles * Ndt - # of time steps * t0 - initial time * delta_t - time step * tau_res - residence time * tau_mix - mixture time * tau_pair - pairwise time * * Output: * success or error * * last update: Oct 1, 2019 * ----------------------------------------------------------------- */ int pmsr_input(unsigned long int *seed,unsigned int *Np,unsigned int *Ndt, double *t0,double *delta_t,double *tau_res,double *tau_mix, double *tau_pair,double *Tmax,double *Tmin, double *atol,double *rtol) { printf("\n Input PMSR parameters:\n"); printf("\n RNG seed:"); scanf("%lu", seed); printf("\n %lu\n", *seed); if( *seed <= 0 ) *seed = time(NULL); printf("\n # of particles:"); scanf("%d", Np); printf("\n %d\n", *Np); if( *Np <= 0 || *Np % 2 != 0 ) GSL_ERROR(" Np must be a positive even integer",GSL_EINVAL); printf("\n # of time steps:"); scanf("%d", Ndt); printf("\n %d\n", *Ndt); if( *Ndt <= 0 ) GSL_ERROR(" Ndt must be a positive integer",GSL_EINVAL); printf("\n initial time:"); scanf("%lf", t0); printf("\n %+.1e\n", *t0); if( *t0 < 0.0 ) GSL_ERROR(" t0 must be a grather than zero",GSL_EINVAL); printf("\n time step:"); scanf("%lf", delta_t); printf("\n %+.1e\n", *delta_t); if( *delta_t <= 0.0 ) GSL_ERROR(" delta_t must be a grather than zero",GSL_EINVAL); printf("\n residence time:"); scanf("%lf", tau_res); printf("\n %+.1e\n", *tau_res); if( *tau_res <= 0.0 ) GSL_ERROR(" tau_res must be a grather than zero",GSL_EINVAL); printf("\n mixture time:"); scanf("%lf", tau_mix); printf("\n %+.1e\n", *tau_mix); if( *tau_mix <= 0.0 ) GSL_ERROR(" tau_mix must be a grather than zero",GSL_EINVAL); printf("\n pairwise time:"); scanf("%lf", tau_pair); printf("\n %+.1e\n", *tau_pair); if( *tau_pair <= 0.0 ) GSL_ERROR(" tau_pair must be a grather than zero",GSL_EINVAL); printf("\n temperature upper bound:"); scanf("%lf", Tmax); printf("\n %+.1e\n", *Tmax); if( *Tmax <= 0.0 ) GSL_ERROR(" Tmax must be a grather than zero",GSL_EINVAL); printf("\n temperature lower bound:"); scanf("%lf", Tmin); printf("\n %+.1e\n", *Tmin); if( *Tmin < 0.0 || *Tmin > *Tmax ) GSL_ERROR(" Tmin must be less than Tmax and a grather than zero",GSL_EINVAL); printf("\n absolute tolerance:"); scanf("%lf", atol); printf("\n %+.1e\n", *atol); if( *atol <= 0.0 ) GSL_ERROR(" atol must be a grather than zero",GSL_EINVAL); printf("\n relative tolerance:"); scanf("%lf", rtol); printf("\n %+.1e\n", *rtol); if( *rtol <= 0.0 ) GSL_ERROR(" rtol must be a grather than zero",GSL_EINVAL); return GSL_SUCCESS; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_alloc * * This function allocates an internal memory block for * pmsr workspace struct. If successful, returns a pointer to * pmsr_wrk. If a startup error occurs returns NULL. * * last update: Nov 5, 2009 * ----------------------------------------------------------------- */ pmsr_wrk *pmsr_alloc() { pmsr_wrk *pmsr = NULL; /* memory allocation for pmsr struct */ pmsr = (pmsr_wrk *) malloc(sizeof(pmsr_wrk)); if ( pmsr == NULL ) return NULL; /* setting pmsr_wrk elements */ pmsr->pmsr_idx = NULL; pmsr->pmsr_ps = NULL; return pmsr; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_init * * This function initiates the system of particles * with an initial composition phi. * * Input: * Np - # of particles * Neq - # of equations * pmsr - pointer to a struct pmsr * * Output: * success or error * * last update: Sep 22, 2009 * ----------------------------------------------------------------- */ int pmsr_init(int Np,int Neq,pmsr_wrk *pmsr) { int i; /* checking if pmsr is NULL */ if ( pmsr == NULL ) return GSL_EINVAL; /* memory allocation for the system of particles */ pmsr->pmsr_ps = (gsl_vector **) malloc(Np*sizeof(gsl_vector *)); if ( pmsr->pmsr_ps == NULL ) return GSL_ENOMEM; for ( i = 0; i < Np; i++ ) pmsr->pmsr_ps[i] = gsl_vector_calloc(Neq); /* memory allocation for the vector of indices */ pmsr->pmsr_idx = (int *) malloc(Np*sizeof(int)); if ( pmsr->pmsr_idx == NULL ) { for ( i = 0; i < Np; i++ ) { gsl_vector_free(pmsr->pmsr_ps[i]); pmsr->pmsr_ps[i] = NULL; } free(pmsr->pmsr_ps); pmsr->pmsr_ps = NULL; return GSL_ENOMEM; } /* initial configuration of particles pairwise */ for ( i = 0; i < Np; i++ ) pmsr->pmsr_idx[i] = i; return GSL_SUCCESS; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_free * * This routine frees the memory allocated by pmsr_alloc. * * Input: * pmsr - pointer to a struct pmsr * * Output: * void * * last update: May 10, 2009 * ----------------------------------------------------------------- */ void pmsr_free(int Np,void **pmsr_bl) { int i; pmsr_wrk *pmsr = NULL; /* checking if pmsr_bl is NULL */ if ( *pmsr_bl == NULL ) return; /* checking if Np is positive */ if ( Np <= 0 ) return; pmsr = (pmsr_wrk *) (*pmsr_bl); /* releasing pmsr elements */ if ( pmsr->pmsr_ps != NULL ) { for ( i = 0; i < Np; i++ ) if ( pmsr->pmsr_ps[i] != NULL ) { gsl_vector_free(pmsr->pmsr_ps[i]); pmsr->pmsr_ps[i] = NULL; } /* releasing pmsr struct */ free(pmsr->pmsr_ps); pmsr->pmsr_ps = NULL; } if ( pmsr->pmsr_idx != NULL ) { free(pmsr->pmsr_idx); pmsr->pmsr_idx = NULL; } free(*pmsr_bl); *pmsr_bl = NULL; return; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_set_all * * This function sets the system of particles with a given * composition phi. * * Input: * pmsr - pointer to a struct pmsr * phi - composition * * Output: * success or error * * last update: Mar 2, 2010 * ----------------------------------------------------------------- */ void pmsr_set_all(int Np,gsl_vector *phi,pmsr_wrk *pmsr) { int i; /* setting all particles with an initial phi */ for ( i = 0; i < Np; i++ ) gsl_vector_memcpy(pmsr->pmsr_ps[i],phi); return; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_Nexc * * This function computes the number of particles to be exchanged, * Nexc, corresponding to outflow/inflow particles. * * Nexc = ceil( 1/2 Np delta_t/taus_res ) * * Input: * Np - # of particles * delta_t - time step * tau_res - residence time * * Output: * Nexc - # of particles to be exchanged * * last update: Feb 12, 2009 * ----------------------------------------------------------------- */ int pmsr_Nexc(int Np,double delta_t,double tau_res) { return ceil( (Np/2)*(delta_t/tau_res) ); } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_Npair * * This function computes the number of particles to be pairwised, * Npair, corresponding to pairing particles. * * Npair = ceil( 1/2 Np delta_t/taus_pair ) * * Input: * Np - # of particles * delta_t - time step * tau_pair - pairwise time * * Output: * Npair - # of particles to be pairwised * * last update: Feb 12, 2009 * ----------------------------------------------------------------- */ int pmsr_Npair(int Np,double delta_t,double tau_pair) { return ceil( (Np/2)*(delta_t/tau_pair) ); } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_meanvar * * This function computes the mean and the variance * of a particular property in a system of particles * using the algorithm of Knuth/Welford. * * Ref.: * D. E. Knuth (1998) * The Art of Computer Programming, * volume 2: Seminumerical Algorithms * 3rd ed., Addison-Wesley. * * B. P. Welford (1962). * "Note on a method for calculating corrected sums * of squares and products". Technometrics 4(3):419–420 * * Input: * Np - # of particles * k - property index * ps - system of particle * * Output: * mean - propertie mean value * var - propertie variance * * last update: Mar 4, 2010 * ----------------------------------------------------------------- */ void pmsr_meanvar(int Np,int k,gsl_vector **ps,double *mean,double *var) { int i; double M = 0.0; double S = 0.0; double delta = 0.0; for ( i = 0; i < Np; i++ ) { delta = ps[i]->data[k] - M; M += delta/(double) (i+1); S += delta*(ps[i]->data[k] - M); } /* mean */ *mean = M; /* variance */ *var = S/(double) (i-1); return; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_mixture * * This function computes the mixture step in PMSR model. * * Input: * Np - # of particles * Neq - # of equations * delta_t - time step * tau_mix - mixture time * idx - particles index vector * * Output: * ps - system of particles * * last update: Mar 9, 2009 * ----------------------------------------------------------------- */ void pmsr_mixture(int Np,int Neq,double delta_t,double tau_mix, int *idx,gsl_vector **ps) { int k, i; double sum, dif; /* particle index */ k = 0; /* mixture of the Np particles */ while( k < Np/2 ) { /* mixture of two particles */ for ( i = 0; i < Neq; i++ ) { /* sum = 1/2(phi_p0 + phi_q0) */ sum = 0.5*( ps[idx[2*k]]->data[i] + ps[idx[2*k+1]]->data[i] ); /* dif = 1/2(phi_p0 - phi_q0) */ dif = 0.5*( ps[idx[2*k]]->data[i] - ps[idx[2*k+1]]->data[i] ); /* phi_p = dif.exp(-2/tau delta_t) + sum */ ps[idx[2*k]]->data[i] = dif*exp(-(2.0/tau_mix)*delta_t) + sum; /* phi_q = -dif.exp(-2/tau delta_t) + sum */ ps[idx[2*k+1]]->data[i] = -dif*exp(-(2.0/tau_mix)*delta_t) + sum; } k++; } return; } /*----------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * pmsr_iops * * This function executes the inflow/outflow, * pairwise and shuflle steps. * * Input: * Np - # of particles * Nexc - # of particles to be exchanged * Npair - # of particles to be pairwised * rand - rng workspace * phi - inflow composition * * Output: * p - system of particles * pairs - pairs of particles index * * last update: Mar 1, 2010 * ----------------------------------------------------------------- */ void pmsr_iops(int Np,int Nexc,int Npair,gsl_rng *rand, gsl_vector *phi,pmsr_wrk *pmsr) { int i; int idx1[Nexc+Npair]; int idx2[2*(Nexc+Npair)]; int *aux = NULL; /* memory allocation */ aux = (int *) malloc((Np/2)*sizeof(int)); /* setting aux vector with integers from 0 to Np/2-1 */ for ( i = 0; i < Np/2; i++ ) aux[i] = i; /* selecting Nexc + Npair pairs at random */ gsl_ran_choose(rand,idx1,Nexc+Npair,aux,Np/2,sizeof(int)); for ( i = 0; i < Nexc + Npair; i++ ) { idx2[2*i ] = pmsr->pmsr_idx[2*idx1[i] ]; idx2[2*i+1] = pmsr->pmsr_idx[2*idx1[i]+1]; } /* changing composition of Nexc pairs (inflow / outflow) */ for ( i = 0; i < Nexc; i++ ) { gsl_vector_memcpy(pmsr->pmsr_ps[idx2[2*i] ],phi); gsl_vector_memcpy(pmsr->pmsr_ps[idx2[2*i+1]],phi); } /* shuffling the selected pairs */ gsl_ran_shuffle(rand,idx2,2*(Nexc+Npair),sizeof(int)); /* setting the new partners in the system */ for ( i = 0; i < Nexc + Npair; i++ ) { pmsr->pmsr_idx[2*idx1[i] ] = idx2[2*i ]; pmsr->pmsr_idx[2*idx1[i]+1] = idx2[2*i+1]; } /* releasing allocated memory */ free(aux); aux = NULL; return; } /*----------------------------------------------------------------*/
{ "alphanum_fraction": 0.4623423909, "avg_line_length": 24.2733224223, "ext": "c", "hexsha": "dbc1d75578e5591b2872a36617f0ce49e5236732", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 4157, "size": 14831 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #ifndef _createK2_h #define _createK2_h #include <petsc.h> #include <petscmat.h> #include <petscvec.h> #include <petscksp.h> PetscErrorCode bsscr_buildK2(KSP ksp); PetscErrorCode bsscr_DGMiGtD( Mat *_K2, Mat K, Mat G, Mat M); PetscErrorCode bsscr_GMiGt( Mat *_K2, Mat K, Mat G, Mat M); PetscErrorCode bsscr_GGt( Mat *_K2, Mat K, Mat G); #endif
{ "alphanum_fraction": 0.4103547459, "avg_line_length": 47.4090909091, "ext": "h", "hexsha": "05fd731f905e837a47875efb443a4c0c9d9ee8ea", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/createK2.h", "max_issues_count": 561, "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/createK2.h", "max_line_length": 87, "max_stars_count": 116, "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/createK2.h", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "num_tokens": 357, "size": 1043 }
/* ode-initval/test_odeiv.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_ieee_utils.h> #include "gsl_odeiv.h" int rhs_linear (double t, const double y[], double f[], void *params); int jac_linear (double t, const double y[], double *dfdy, double dfdt[], void *params); int rhs_sin (double t, const double y[], double f[], void *params); int jac_sin (double t, const double y[], double *dfdy, double dfdt[], void *params); int rhs_exp (double t, const double y[], double f[], void *params); int jac_exp (double t, const double y[], double *dfdy, double dfdt[], void *params); int rhs_stiff (double t, const double y[], double f[], void *params); int jac_stiff (double t, const double y[], double *dfdy, double dfdt[], void *params); void test_stepper_linear (const gsl_odeiv_step_type * T, double h, double base_prec); void test_stepper_sin (const gsl_odeiv_step_type * T, double h, double base_prec); void test_stepper_exp (const gsl_odeiv_step_type * T, double h, double base_prec); void test_stepper_stiff (const gsl_odeiv_step_type * T, double h, double base_prec); void test_evolve_system_flat (gsl_odeiv_step * step, const gsl_odeiv_system * sys, double t0, double t1, double hstart, double y[], double yfin[], double err_target, const char *desc); void test_evolve_system (const gsl_odeiv_step_type * T, const gsl_odeiv_system * sys, double t0, double t1, double hstart, double y[], double yfin[], double err_target, const char *desc); void test_evolve_exp (const gsl_odeiv_step_type * T, double h, double err); void test_evolve_sin (const gsl_odeiv_step_type * T, double h, double err); void test_evolve_stiff1 (const gsl_odeiv_step_type * T, double h, double err); void test_evolve_stiff5 (const gsl_odeiv_step_type * T, double h, double err); /* RHS for a + b t */ int rhs_linear (double t, const double y[], double f[], void *params) { f[0] = 0.0; f[1] = y[0]; return GSL_SUCCESS; } int jac_linear (double t, const double y[], double *dfdy, double dfdt[], void *params) { gsl_matrix dfdy_mat; dfdy_mat.size1 = 2; dfdy_mat.size2 = 2; dfdy_mat.tda = 2; dfdy_mat.data = dfdy; dfdy_mat.block = 0; gsl_matrix_set (&dfdy_mat, 0, 0, 0.0); gsl_matrix_set (&dfdy_mat, 0, 1, 0.0); gsl_matrix_set (&dfdy_mat, 1, 0, 1.0); gsl_matrix_set (&dfdy_mat, 1, 1, 0.0); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv_system rhs_func_lin = { rhs_linear, jac_linear, 2, 0 }; /* RHS for sin(t),cos(t) */ int rhs_sin (double t, const double y[], double f[], void *params) { f[0] = -y[1]; f[1] = y[0]; return GSL_SUCCESS; } int jac_sin (double t, const double y[], double *dfdy, double dfdt[], void *params) { gsl_matrix dfdy_mat; dfdy_mat.data = dfdy; dfdy_mat.size1 = 2; dfdy_mat.size2 = 2; dfdy_mat.tda = 2; dfdy_mat.block = 0; gsl_matrix_set (&dfdy_mat, 0, 0, 0.0); gsl_matrix_set (&dfdy_mat, 0, 1, -1.0); gsl_matrix_set (&dfdy_mat, 1, 0, 1.0); gsl_matrix_set (&dfdy_mat, 1, 1, 0.0); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv_system rhs_func_sin = { rhs_sin, jac_sin, 2, 0 }; /* RHS for a exp(t)+ b exp(-t) */ int rhs_exp (double t, const double y[], double f[], void *params) { f[0] = y[1]; f[1] = y[0]; return GSL_SUCCESS; } int jac_exp (double t, const double y[], double *dfdy, double dfdt[], void *params) { gsl_matrix dfdy_mat; dfdy_mat.data = dfdy; dfdy_mat.size1 = 2; dfdy_mat.size2 = 2; dfdy_mat.tda = 2; dfdy_mat.block = 0; gsl_matrix_set (&dfdy_mat, 0, 0, 0.0); gsl_matrix_set (&dfdy_mat, 0, 1, 1.0); gsl_matrix_set (&dfdy_mat, 1, 0, 1.0); gsl_matrix_set (&dfdy_mat, 1, 1, 0.0); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv_system rhs_func_exp = { rhs_exp, jac_exp, 2, 0 }; /* RHS for stiff example */ int rhs_stiff (double t, const double y[], double f[], void *params) { f[0] = 998.0 * y[0] + 1998.0 * y[1]; f[1] = -999.0 * y[0] - 1999.0 * y[1]; return GSL_SUCCESS; } int jac_stiff (double t, const double y[], double *dfdy, double dfdt[], void *params) { gsl_matrix dfdy_mat; dfdy_mat.data = dfdy; dfdy_mat.size1 = 2; dfdy_mat.size2 = 2; dfdy_mat.tda = 2; dfdy_mat.block = 0; gsl_matrix_set (&dfdy_mat, 0, 0, 998.0); gsl_matrix_set (&dfdy_mat, 0, 1, 1998.0); gsl_matrix_set (&dfdy_mat, 1, 0, -999.0); gsl_matrix_set (&dfdy_mat, 1, 1, -1999.0); dfdt[0] = 0.0; dfdt[1] = 0.0; return GSL_SUCCESS; } gsl_odeiv_system rhs_func_stiff = { rhs_stiff, jac_stiff, 2, 0 }; void test_stepper_linear (const gsl_odeiv_step_type * T, double h, double base_prec) { int s = 0; double y[2]; double yerr[2]; double t; double del; double delmax = 0.0; int count = 0; gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2); y[0] = 1.0; y[1] = 0.0; for (t = 0.0; t < 4.0; t += h) { gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_lin); del = fabs ((y[1] - (t + h)) / y[1]); delmax = GSL_MAX_DBL (del, delmax); if (del > (count + 1.0) * base_prec) { printf (" LINEAR(%20.17g) %20.17g %20.17g %8.4g\n", t + h, y[1], t + h, del); s++; } count++; } gsl_test (s, "%s, linear [0,4], max relative error = %g", gsl_odeiv_step_name (stepper), delmax); gsl_odeiv_step_free (stepper); } void test_stepper_sin (const gsl_odeiv_step_type * T, double h, double base_prec) { int s = 0; double y[2]; double yerr[2]; double t; double del; double delmax = 0.0; int count = 0; gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2); y[0] = 1.0; y[1] = 0.0; for (t = 0.0; t < M_PI; t += h) { int stat; double sin_th = sin (t + h); gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_sin); del = fabs ((y[1] - sin_th) / sin_th); delmax = GSL_MAX_DBL (del, delmax); { if (t < 0.5 * M_PI) { stat = (del > (count + 1.0) * base_prec); } else if (t < 0.7 * M_PI) { stat = (del > 1.0e+04 * base_prec); } else if (t < 0.9 * M_PI) { stat = (del > 1.0e+06 * base_prec); } else { stat = (del > 1.0e+09 * base_prec); } if (stat != 0) { printf (" SIN(%22.18g) %22.18g %22.18g %10.6g\n", t + h, y[1], sin_th, del); } s += stat; } count++; } if (delmax > 1.0e+09 * base_prec) { s++; printf (" SIN(0 .. M_PI) delmax = %g\n", delmax); } gsl_test (s, "%s, sine [0,pi], max relative error = %g", gsl_odeiv_step_name (stepper), delmax); delmax = 0.0; for (; t < 100.5 * M_PI; t += h) { gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_sin); del = fabs (y[1] - sin (t)); delmax = GSL_MAX_DBL (del, delmax); count++; } if (del > count * 2.0 * base_prec) { s++; printf (" SIN(%22.18g) %22.18g %22.18g %10.6g\n", t + h, y[1], sin (t), del); } gsl_test (s, "%s, sine [pi,100.5*pi], max absolute error = %g", gsl_odeiv_step_name (stepper), delmax); gsl_odeiv_step_free (stepper); } void test_stepper_exp (const gsl_odeiv_step_type * T, double h, double base_prec) { int s = 0; double y[2]; double yerr[2]; double t; double del, delmax = 0.0; int count = 0; gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2); y[0] = 1.0; y[1] = 1.0; for (t = 0.0; t < 20.0; t += h) { double ex = exp (t + h); gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_exp); del = fabs ((y[1] - ex) / y[1]); delmax = GSL_MAX_DBL (del, delmax); if (del > (count + 1.0) * 2.0 * base_prec) { printf (" EXP(%20.17g) %20.17g %20.17g %8.4g\n", t + h, y[1], ex, del); s++; } count++; } gsl_test (s, "%s, exponential [0,20], max relative error = %g", gsl_odeiv_step_name (stepper), delmax); gsl_odeiv_step_free (stepper); } void test_stepper_stiff (const gsl_odeiv_step_type * T, double h, double base_prec) { int s = 0; double y[2]; double yerr[2]; double t; double del, delmax = 0.0; int count = 0; gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2); y[0] = 1.0; y[1] = 0.0; for (t = 0.0; t < 20.0; t += h) { gsl_odeiv_step_apply (stepper, t, h, y, yerr, NULL, NULL, &rhs_func_stiff); if (t > 0.04) { double arg = t + h; double e1 = exp (-arg); double e2 = exp (-1000.0 * arg); double u = 2.0 * e1 - e2; /* double v = -e1 + e2; */ del = fabs ((y[0] - u) / y[0]); delmax = GSL_MAX_DBL (del, delmax); if (del > (count + 1.0) * 100.0 * base_prec) { printf (" STIFF(%20.17g) %20.17g %20.17g %8.4g\n", arg, y[0], u, del); s++; } } count++; } gsl_test (s, "%s, stiff [0,20], max relative error = %g", gsl_odeiv_step_name (stepper), delmax); gsl_odeiv_step_free (stepper); } void test_evolve_system_flat (gsl_odeiv_step * step, const gsl_odeiv_system * sys, double t0, double t1, double hstart, double y[], double yfin[], double err_target, const char *desc) { int s = 0; double frac; double t = t0; double h = hstart; gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension); while (t < t1) { gsl_odeiv_evolve_apply (e, NULL, step, sys, &t, t1, &h, y); } frac = fabs ((y[1] - yfin[1]) / yfin[1]) + fabs ((y[0] - yfin[0]) / yfin[0]); if (frac > 2.0 * e->count * err_target) { printf ("FLAT t = %.5e y0 = %g y1= %g\n", t, y[0], y[1]); s++; } gsl_test (s, "%s, %s, evolve, no control, max relative error = %g", gsl_odeiv_step_name (step), desc, frac); gsl_odeiv_evolve_free (e); } void test_evolve_system (const gsl_odeiv_step_type * T, const gsl_odeiv_system * sys, double t0, double t1, double hstart, double y[], double yfin[], double err_target, const char *desc) { int s = 0; double frac; double t = t0; double h = hstart; gsl_odeiv_step * step = gsl_odeiv_step_alloc (T, sys->dimension); gsl_odeiv_control *c = gsl_odeiv_control_standard_new (0.0, err_target, 1.0, 1.0); gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension); while (t < t1) { gsl_odeiv_evolve_apply (e, c, step, sys, &t, t1, &h, y); /* printf ("SYS t = %.18e h = %g y0 = %g y1= %g\n", t, h, y[0], y[1]); */ } frac = fabs ((y[1] - yfin[1]) / yfin[1]) + fabs ((y[0] - yfin[0]) / yfin[0]); if (frac > 2.0 * e->count * err_target) { printf ("SYS t = %.5e h = %g y0 = %g y1= %g\n", t, h, y[0], y[1]); s++; } gsl_test (s, "%s, %s, evolve, standard control, relative error = %g", gsl_odeiv_step_name (step), desc, frac); gsl_odeiv_evolve_free (e); gsl_odeiv_control_free (c); gsl_odeiv_step_free (step); } void test_evolve_exp (const gsl_odeiv_step_type * T, double h, double err) { double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 1.0; yfin[0] = exp (10.0); yfin[1] = yfin[0]; test_evolve_system (T, &rhs_func_exp, 0.0, 10.0, h, y, yfin, err, "exp [0,10]"); } void test_evolve_sin (const gsl_odeiv_step_type * T, double h, double err) { double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; yfin[0] = cos (2.0); yfin[1] = sin (2.0); test_evolve_system (T, &rhs_func_sin, 0.0, 2.0, h, y, yfin, err, "sine [0,2]"); } void test_evolve_stiff1 (const gsl_odeiv_step_type * T, double h, double err) { double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; { double arg = 1.0; double e1 = exp (-arg); double e2 = exp (-1000.0 * arg); yfin[0] = 2.0 * e1 - e2; yfin[1] = -e1 + e2; } test_evolve_system (T, &rhs_func_stiff, 0.0, 1.0, h, y, yfin, err, "stiff [0,1]"); } void test_evolve_stiff5 (const gsl_odeiv_step_type * T, double h, double err) { double y[2]; double yfin[2]; y[0] = 1.0; y[1] = 0.0; { double arg = 5.0; double e1 = exp (-arg); double e2 = exp (-1000.0 * arg); yfin[0] = 2.0 * e1 - e2; yfin[1] = -e1 + e2; } test_evolve_system (T, &rhs_func_stiff, 0.0, 5.0, h, y, yfin, err, "stiff [0,5]"); } int main (void) { int i; struct ptype { const gsl_odeiv_step_type *type; double h; } p[20]; p[0].type = gsl_odeiv_step_rk2; p[0].h = 1.0e-03; p[1].type = gsl_odeiv_step_rk2imp; p[1].h = 1.0e-03; p[2].type = gsl_odeiv_step_rk4; p[2].h = 1.0e-03; p[3].type = gsl_odeiv_step_rk4imp; p[3].h = 1.0e-03; p[4].type = gsl_odeiv_step_rkf45; p[4].h = 1.0e-03; p[5].type = gsl_odeiv_step_rk8pd; p[5].h = 1.0e-03; p[6].type = gsl_odeiv_step_rkck; p[6].h = 1.0e-03; p[7].type = gsl_odeiv_step_bsimp; p[7].h = 0.1; p[8].type = gsl_odeiv_step_gear1; p[8].h = 1.0e-03; p[9].type = gsl_odeiv_step_gear2; p[9].h = 1.0e-03; p[10].type = 0; gsl_ieee_env_setup (); for (i = 0; p[i].type != 0; i++) { test_stepper_linear (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON); test_stepper_sin (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON); test_stepper_exp (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON); test_stepper_stiff (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON); } for (i = 0; p[i].type != 0; i++) { test_evolve_exp (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON); test_evolve_sin (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON); test_evolve_stiff1 (p[i].type, p[i].h, 1e-5); test_evolve_stiff5 (p[i].type, p[i].h, 1e-5); } exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.588741363, "avg_line_length": 24.0423452769, "ext": "c", "hexsha": "2f0c08cab7ef7a7e0e6bcc37d4d66bfdb561a7c4", "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/ode-initval/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/ode-initval/test.c", "max_line_length": 84, "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/ode-initval/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": 5602, "size": 14762 }
#include <stdio.h> #include <gsl/gsl_cblas.h> int main () { int lda = 3; float A[] = { 0.11, 0.12, 0.13, 0.21, 0.22, 0.23 }; int ldb = 2; float B[] = { 1011, 1012, 1021, 1022, 1031, 1032 }; int ldc = 2; float C[] = { 0.00, 0.00, 0.00, 0.00 }; /* Compute C = A B */ cblas_sgemm (CblasRowMajor, CblasNoTrans, CblasNoTrans, 2, 2, 3, 1.0, A, lda, B, ldb, 0.0, C, ldc); printf("[ %g, %g\n", C[0], C[1]); printf(" %g, %g ]\n", C[2], C[3]); }
{ "alphanum_fraction": 0.4290909091, "avg_line_length": 17.1875, "ext": "c", "hexsha": "111c4e5c6141834be9e0082606408843644f3a4d", "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/cblas/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/cblas/demo.c", "max_line_length": 66, "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/cblas/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 241, "size": 550 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void init_MCMC(MCMC_info * MCMC, const char *problem_name, void * params, int (*f)(double *, MCMC_info *, double **), int n_P, double *P_init, char ** P_names, double *P_limit_min, double *P_limit_max, int n_arrays, ...) { int i_P; int i_array; int i; FILE * ft, *ft_restart; char test_dir[256], test_restart[256]; va_list vargs; va_start(vargs, n_arrays); SID_log("Initializing MCMC structure...", SID_LOG_OPEN); // Set defaults to bare minimums MCMC->n_avg = 100; MCMC->n_iterations_burn = 4; MCMC->n_iterations = 8; MCMC->n_thin = 1; MCMC->coverage_size = 100; MCMC->flag_autocor_on = GBP_FALSE; MCMC->flag_integrate_on = GBP_FALSE; MCMC->flag_analysis_on = GBP_TRUE; MCMC->first_map_call = GBP_TRUE; MCMC->first_link_call = GBP_TRUE; MCMC->flag_init_chain = GBP_TRUE; MCMC->first_chain_call = GBP_TRUE; MCMC->first_parameter_call = GBP_TRUE; MCMC->first_likelihood_call = GBP_TRUE; MCMC->ln_likelihood_last = 0.; MCMC->ln_likelihood_new = 0.; MCMC->ln_likelihood_chain = 0.; MCMC->P_init = NULL; MCMC->P_new = NULL; MCMC->P_last = NULL; MCMC->P_chain = NULL; MCMC->P_limit_min = NULL; MCMC->P_limit_max = NULL; MCMC->P_min = NULL; MCMC->P_max = NULL; MCMC->P_avg = NULL; MCMC->dP_avg = NULL; MCMC->P_best = NULL; MCMC->P_peak = NULL; MCMC->P_lo_68 = NULL; MCMC->P_hi_68 = NULL; MCMC->P_lo_95 = NULL; MCMC->P_hi_95 = NULL; MCMC->n_M = NULL; MCMC->M_new = NULL; MCMC->M_last = NULL; MCMC->DS = NULL; MCMC->last = NULL; MCMC->V = NULL; MCMC->m = NULL; MCMC->b = NULL; MCMC->RNG = NULL; MCMC->params = NULL; MCMC->temperature = 1.0; MCMC->n_DS = 0; MCMC->n_M_total = 0; MCMC->n_fail = 0; MCMC->n_success = 0; MCMC->n_propositions = 0; MCMC->n_map_calls = 0; // Process the passed arguments MCMC->map_P_to_M = f; MCMC->compute_MCMC_ln_likelihood = compute_MCMC_ln_likelihood_default; MCMC->params = params; MCMC->n_P = n_P; sprintf(MCMC->problem_name, "%s", problem_name); MCMC->P_names = (char **)SID_malloc(sizeof(char *) * MCMC->n_P); MCMC->P_name_length = 0; for(i_P = 0; i_P < n_P; i_P++) { MCMC->P_names[i_P] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE); sprintf(MCMC->P_names[i_P], "%s", P_names[i_P]); MCMC->P_name_length = GBP_MAX((size_t)(MCMC->P_name_length), strlen(MCMC->P_names[i_P])); } sprintf(MCMC->P_name_format, "%%-%ds", MCMC->P_name_length); // Initialize the MCMC mode and set things associated with it set_MCMC_mode(MCMC, MCMC_MODE_DEFAULT); // MCMC->my_chain is set here // Set parameter arrays and limits MCMC->P_init = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_new = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_last = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_chain = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_limit_min = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->P_limit_max = (double *)SID_malloc(sizeof(double) * MCMC->n_P); if(P_limit_min == NULL) { for(i_P = 0; i_P < n_P; i_P++) MCMC->P_limit_min[i_P] = -DBL_MAX * 1e-3; } else { for(i_P = 0; i_P < n_P; i_P++) MCMC->P_limit_min[i_P] = P_limit_min[i_P]; } if(P_limit_max == NULL) { for(i_P = 0; i_P < n_P; i_P++) MCMC->P_limit_max[i_P] = DBL_MAX * 1e-3; } else { for(i_P = 0; i_P < n_P; i_P++) MCMC->P_limit_max[i_P] = P_limit_max[i_P]; } // Set parameter initial values memcpy(MCMC->P_init, P_init, (size_t)MCMC->n_P * sizeof(double)); memcpy(MCMC->P_new, P_init, (size_t)MCMC->n_P * sizeof(double)); memcpy(MCMC->P_last, P_init, (size_t)MCMC->n_P * sizeof(double)); memcpy(MCMC->P_chain, P_init, (size_t)MCMC->n_P * sizeof(double)); // Set arrays MCMC->n_arrays = n_arrays; if(n_arrays > 0) { MCMC->array = (double **)SID_malloc(sizeof(double *) * MCMC->n_arrays); MCMC->array_name = (char **)SID_malloc(sizeof(char *) * MCMC->n_arrays); for(i_array = 0; i_array < n_arrays; i_array++) { MCMC->array[i_array] = (double *)SID_malloc(sizeof(double) * MCMC->n_P); MCMC->array_name[i_array] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE); memcpy(MCMC->array[i_array], (double *)va_arg(vargs, double *), (size_t)(MCMC->n_P) * sizeof(double)); sprintf(MCMC->array_name[i_array], "%s", (char *)va_arg(vargs, char *)); } } else MCMC->array = NULL; // Set autotune defaults (if needed) if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_AUTOTUNE)) set_MCMC_autotune(MCMC, -1., -1., -1., -1, -1, -1, -1); // Negatives mean use defaults (set in gbpMCMC.h) // Initialize Communicator SID_Comm_init(&(MCMC->comm)); SID_Comm_split(SID_COMM_WORLD, MCMC->my_chain, SID.My_rank, MCMC->comm); // Set the base output directory if(MCMC->my_chain == SID.My_rank) { // Generate directory and stop filenames sprintf(test_dir, "./%s_MCMC/", SID.My_binary); sprintf(test_restart, "./%s_MCMC/stop", SID.My_binary); // analyze_MCMC() needs to know what the filename root is. We also need to strip trailing '/'s. strcpy(MCMC->filename_output_root, test_dir); int i_char; int flag_continue; for(i_char = strlen(MCMC->filename_output_root) - 1, flag_continue = GBP_TRUE; i_char >= 0 && flag_continue; i_char--) { if(MCMC->filename_output_root[i_char] != '/') flag_continue = GBP_FALSE; else MCMC->filename_output_root[i_char] = '\0'; } i = 0; // Try to open them ... ft = fopen(test_dir, "r"); ft_restart = fopen(test_restart, "r"); // If the directory exists & there is no stop file in it then... if((ft != NULL) && (ft_restart == NULL)) { // Increment the directory suffix until we don't find a directory, // whilst always ensuring we don't come across a stop file (which indicates // the previous run was stopped prematurely and we want restart the run). do { fclose(ft); i++; sprintf(test_dir, "./%s_MCMC.%d/", SID.My_binary, i); ft = fopen(test_dir, "r"); sprintf(test_restart, "./%s_MCMC.%d/stop", SID.My_binary, i); ft_restart = fopen(test_restart, "r"); } while((ft != NULL) && (ft_restart == NULL)); } // Finally, if we did find a stop file then close it and remove it. if(ft_restart != NULL) { fclose(ft_restart); remove(test_restart); } // Copy the directory name we settled on to the MCMC structure strcpy(MCMC->filename_output_dir, test_dir); SID_log("ouput_dir set to: %s", SID_LOG_COMMENT, MCMC->filename_output_dir); } // Broadcast the output directory to all the other cores. SID_Bcast(MCMC->filename_output_dir, SID_MAX_FILENAME_LENGTH, SID_CHAR, MCMC->my_chain, MCMC->comm); // Initilize the random number generator MCMC->RNG = (RNG_info *)SID_malloc(sizeof(RNG_info)); init_seed_from_clock(&(MCMC->seed)); SID_Bcast(&(MCMC->seed), 1, SID_INT, SID_MASTER_RANK, MCMC->comm); init_RNG(&(MCMC->seed), MCMC->RNG, RNG_DEFAULT); SID_log("Done.", SID_LOG_CLOSE); va_end(vargs); }
{ "alphanum_fraction": 0.5510462175, "avg_line_length": 41.419047619, "ext": "c", "hexsha": "762c8b634dcd1ebfbb205d83e352e17192ca2ef4", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/init_MCMC.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/init_MCMC.c", "max_line_length": 128, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/init_MCMC.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 2542, "size": 8698 }
#ifndef WILCOXONPARALLELTESTS_H #define WILCOXONPARALLELTESTS_H #include <fstream> #include <cmath> #include <iostream> #include <sstream> #include <cstdlib> #include <vector> #include <cstring> #include <gsl/gsl_cdf.h> using namespace std; struct approximatePosition { int x; double y; }; class WilcoxonTest { public: WilcoxonTest(float * _data, int _dataXsize, int _dataYsize, string _testIndexes, string _controlIndexes); WilcoxonTest(float * _data, int _dataXsize, int _dataYsize, vector<int> * _testIndexes, vector<int> * _controlIndexes); vector<double> * test(); private: //Variables int dataYsize; int dataXsize; float * data; vector<double> * pValues; string netCdfFileName; vector<int> * testIndexes; vector<int> * controlIndexes; std::vector<std::vector<approximatePosition> * > * approximatePTable; //Set up void readNetCdfFile(string dataName, string xDimension, string yDimension); std::vector<approximatePosition> * getPositions(string positionsLine); std::vector<string> * splitLine(string inputString, char lineSplit = ';'); void readApproximatePtable(); vector<int> * parseIntString(string input); //Wilcoxon Test main methods float calculateWValue(int yIndex, vector<float> * absoluteValues, vector<float> * signs); double calculatePValue(float w, int numberOfZeroes); float calculateZValue(float w, int Nr); //Wilcoxon Test helper methods double getApproximatePValue(float w, float z); double approximateP(float w, float z, approximatePosition beginningPos, approximatePosition endPos); double * rankThePairs(int yIndex, vector<float> * absoluteValues); int getSign(float value); int getNumberOfZeroes(vector<float> * absoluteValues); void trim(string& str); //sorting void quicksort(int m, int n, vector<float> * absoluteValues, vector<float> * signs); void swap(float * x, float * y); int choose_pivot(int i, int j ); }; #endif
{ "alphanum_fraction": 0.719, "avg_line_length": 31.746031746, "ext": "h", "hexsha": "4533fc72b586c0b9bff88e59029dd69ef0c1a481", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2020-05-21T09:45:52.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-01T07:57:52.000Z", "max_forks_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stenver/wilcoxon-test", "max_forks_repo_path": "WilcoxonTestLibrary/src/WilcoxonTest.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "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": "stenver/wilcoxon-test", "max_issues_repo_path": "WilcoxonTestLibrary/src/WilcoxonTest.h", "max_line_length": 123, "max_stars_count": 5, "max_stars_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stenver/wilcoxon-test", "max_stars_repo_path": "WilcoxonTestLibrary/src/WilcoxonTest.h", "max_stars_repo_stars_event_max_datetime": "2021-01-15T14:35:01.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-05T09:29:06.000Z", "num_tokens": 507, "size": 2000 }
/* integration/qcheb.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> /* This function computes the 12-th order and 24-th order Chebyshev approximations to f(x) on [a,b] */ void gsl_integration_qcheb (gsl_function * f, double a, double b, double *cheb12, double *cheb24) { size_t i; double fval[25], v[12]; /* These are the values of cos(pi*k/24) for k=1..11 needed for the Chebyshev expansion of f(x) */ const double x[11] = { 0.9914448613738104, 0.9659258262890683, 0.9238795325112868, 0.8660254037844386, 0.7933533402912352, 0.7071067811865475, 0.6087614290087206, 0.5000000000000000, 0.3826834323650898, 0.2588190451025208, 0.1305261922200516 }; const double center = 0.5 * (b + a); const double half_length = 0.5 * (b - a); fval[0] = 0.5 * GSL_FN_EVAL (f, b); fval[12] = GSL_FN_EVAL (f, center); fval[24] = 0.5 * GSL_FN_EVAL (f, a); for (i = 1; i < 12; i++) { const size_t j = 24 - i; const double u = half_length * x[i-1]; fval[i] = GSL_FN_EVAL(f, center + u); fval[j] = GSL_FN_EVAL(f, center - u); } for (i = 0; i < 12; i++) { const size_t j = 24 - i; v[i] = fval[i] - fval[j]; fval[i] = fval[i] + fval[j]; } { const double alam1 = v[0] - v[8]; const double alam2 = x[5] * (v[2] - v[6] - v[10]); cheb12[3] = alam1 + alam2; cheb12[9] = alam1 - alam2; } { const double alam1 = v[1] - v[7] - v[9]; const double alam2 = v[3] - v[5] - v[11]; { const double alam = x[2] * alam1 + x[8] * alam2; cheb24[3] = cheb12[3] + alam; cheb24[21] = cheb12[3] - alam; } { const double alam = x[8] * alam1 - x[2] * alam2; cheb24[9] = cheb12[9] + alam; cheb24[15] = cheb12[9] - alam; } } { const double part1 = x[3] * v[4]; const double part2 = x[7] * v[8]; const double part3 = x[5] * v[6]; { const double alam1 = v[0] + part1 + part2; const double alam2 = x[1] * v[2] + part3 + x[9] * v[10]; cheb12[1] = alam1 + alam2; cheb12[11] = alam1 - alam2; } { const double alam1 = v[0] - part1 + part2; const double alam2 = x[9] * v[2] - part3 + x[1] * v[10]; cheb12[5] = alam1 + alam2; cheb12[7] = alam1 - alam2; } } { const double alam = (x[0] * v[1] + x[2] * v[3] + x[4] * v[5] + x[6] * v[7] + x[8] * v[9] + x[10] * v[11]); cheb24[1] = cheb12[1] + alam; cheb24[23] = cheb12[1] - alam; } { const double alam = (x[10] * v[1] - x[8] * v[3] + x[6] * v[5] - x[4] * v[7] + x[2] * v[9] - x[0] * v[11]); cheb24[11] = cheb12[11] + alam; cheb24[13] = cheb12[11] - alam; } { const double alam = (x[4] * v[1] - x[8] * v[3] - x[0] * v[5] - x[10] * v[7] + x[2] * v[9] + x[6] * v[11]); cheb24[5] = cheb12[5] + alam; cheb24[19] = cheb12[5] - alam; } { const double alam = (x[6] * v[1] - x[2] * v[3] - x[10] * v[5] + x[0] * v[7] - x[8] * v[9] - x[4] * v[11]); cheb24[7] = cheb12[7] + alam; cheb24[17] = cheb12[7] - alam; } for (i = 0; i < 6; i++) { const size_t j = 12 - i; v[i] = fval[i] - fval[j]; fval[i] = fval[i] + fval[j]; } { const double alam1 = v[0] + x[7] * v[4]; const double alam2 = x[3] * v[2]; cheb12[2] = alam1 + alam2; cheb12[10] = alam1 - alam2; } cheb12[6] = v[0] - v[4]; { const double alam = x[1] * v[1] + x[5] * v[3] + x[9] * v[5]; cheb24[2] = cheb12[2] + alam; cheb24[22] = cheb12[2] - alam; } { const double alam = x[5] * (v[1] - v[3] - v[5]); cheb24[6] = cheb12[6] + alam; cheb24[18] = cheb12[6] - alam; } { const double alam = x[9] * v[1] - x[5] * v[3] + x[1] * v[5]; cheb24[10] = cheb12[10] + alam; cheb24[14] = cheb12[10] - alam; } for (i = 0; i < 3; i++) { const size_t j = 6 - i; v[i] = fval[i] - fval[j]; fval[i] = fval[i] + fval[j]; } cheb12[4] = v[0] + x[7] * v[2]; cheb12[8] = fval[0] - x[7] * fval[2]; { const double alam = x[3] * v[1]; cheb24[4] = cheb12[4] + alam; cheb24[20] = cheb12[4] - alam; } { const double alam = x[7] * fval[1] - fval[3]; cheb24[8] = cheb12[8] + alam; cheb24[16] = cheb12[8] - alam; } cheb12[0] = fval[0] + fval[2]; { const double alam = fval[1] + fval[3]; cheb24[0] = cheb12[0] + alam; cheb24[24] = cheb12[0] - alam; } cheb12[12] = v[0] - v[2]; cheb24[12] = cheb12[12]; for (i = 1; i < 12; i++) { cheb12[i] *= 1.0 / 6.0; } cheb12[0] *= 1.0 / 12.0; cheb12[12] *= 1.0 / 12.0; for (i = 1; i < 24; i++) { cheb24[i] *= 1.0 / 12.0; } cheb24[0] *= 1.0 / 24.0; cheb24[24] *= 1.0 / 24.0; }
{ "alphanum_fraction": 0.4955031393, "avg_line_length": 25.6217391304, "ext": "c", "hexsha": "a6564f7640f9a8e1ebde49e831c3c4c5f2abdbbc", "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/integration/qcheb.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/integration/qcheb.c", "max_line_length": 92, "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/integration/qcheb.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": 2445, "size": 5893 }
//---------------------------------------------------------------------------- // History: 2018-04-30 Dwayne Robinson - Created //---------------------------------------------------------------------------- #pragma once #include <iterator> #include <memory> // For uninitialized_move/copy and std::unique_ptr. #include <assert.h> #include <algorithm> #if USE_CPP_MODULES //import std.core; import Common.ArrayRef; #else #ifdef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF #include <gsl/span> #define array_ref gsl::span #else #include "Common.ArrayRef.h" // gsl::span may be mostly substituted instead of array_ref, just missing intersects(). #endif #endif MODULE(Common.FastVector); EXPORT_BEGIN #pragma warning(push) #pragma warning(disable:4127) // Conditional expression is constant. VS can't tell that certain compound conditionals of template parameters aren't always constant when the tempalate parameter is true. #if defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL > 0 // For std::uninitialized_copy and std::uninitialized_move. #define FASTVECTOR_MAKE_UNCHECKED stdext::make_unchecked_array_iterator #else #define FASTVECTOR_MAKE_UNCHECKED #endif // fast_vector is a dynamic array that can substitute for std::vector, where it: // (1) avoids heap allocations when the element count fits within the fixed-size capacity. // (2) avoids unnecessarily initializing elements if ShouldInitializeElements == false. // This is useful for large buffers which will just be overwritten soon anyway. // (3) supports most vector methods except insert/erase/emplace. // // Template parameters: // - DefaultArraySize - passing 0 means it is solely heap allocated. Passing > 0 // reserves that much element capacity before allocating heap memory. // // - ShouldInitializeElements - ensures elements are constructed when resizing, and // it must be true for objects with non-trivial constructors, but it can be set // false for large buffers to avoid unnecessarily initializing memory which will // just be overwritten soon later anyway. // // Examples: // fast_vector<int, 20> axes - up to 20 integers before heap allocation. // fast_vector<int, 0, false> axes - always heap allocated but never initialized. // fast_vector<int> axes - basically std::vector. template<typename T, size_t DefaultArraySize = 0, bool ShouldInitializeElements = true> class fast_vector; enum fast_vector_use_memory_buffer_enum { fast_vector_use_memory_buffer // To avoid ambiguous constructor overload resolution. }; // The base class is separated out for the customization of passing specific // memory, and to avoid bloating additional template permutations solely due to // differing array sizes. template<typename T, bool ShouldInitializeElements> class fast_vector<T, 0, ShouldInitializeElements> { static_assert(ShouldInitializeElements || std::is_trivial<T>::value); using self = fast_vector<T, 0, ShouldInitializeElements>; public: // Standard container type definitions. using value_type = T; using pointer = T*; using reference = T&; using iterator = pointer; using const_reference = T const&; using const_iterator = T const*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using size_type = size_t; using difference_type = ptrdiff_t; using mutable_value_type = typename std::remove_const<T>::type; using mutable_iterator = mutable_value_type*; // If true, the data types needs additional alignment like SSE and AVX types. constexpr static bool NeedsTypeAlignmentBeyondMaxAlignT = alignof(T) > alignof(std::max_align_t); constexpr static size_t MinimumMemoryBlockSize = NeedsTypeAlignmentBeyondMaxAlignT ? sizeof(void*) : 0; public: constexpr fast_vector() noexcept { } fast_vector(size_t initialSize) { resize(initialSize); } fast_vector(array_ref<const T> initialValues) { assign(initialValues); } fast_vector(const fast_vector& otherVector) { assign(otherVector); } fast_vector(fast_vector&& otherVector) // Throws std::bad_alloc if low on memory. { transfer_from(otherVector); } // Construct using explicit fixed size memory buffer. // - Used by the derived template specialization which includes a fixed size buffer. // - May also be used by the caller to pass an explicit buffer such as a local array, // where the buffer is guaranteed to live for the lifetime of the fast_vector. constexpr fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray) : data_(initialBackingArray.data()), capacity_(initialBackingArray.size()) { } fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, array_ref<const T> initialValues) : data_(initialBackingArray.data()), capacity_(initialBackingArray.size()) { assign(initialValues); } fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, size_t initialSize) : data_(initialBackingArray.data()), capacity_(initialBackingArray.size()) { resize(initialSize); } fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, pointer p, size_t elementCount) : data_(initialBackingArray.data()), capacity_(initialBackingArray.size()) { assign({p, elementCount}); } template <typename IteratorType> fast_vector(fast_vector_use_memory_buffer_enum, array_ref<T> initialBackingArray, IteratorType begin, IteratorType end) : data_(initialBackingArray.data()), capacity_(initialBackingArray.size()) { assign(begin, end); } ~fast_vector() noexcept(std::is_nothrow_destructible<T>::value) { free(); } // Clear the vector and free all memory. Calling clear() then shrink_to_fit() // is a less efficient way to accomplish it too. void free() { clear(); // Destruct objects and zero the size. if (dataIsAllocatedMemory_) { FreeMemoryBlock(data_); data_ = nullptr; capacity_ = 0; } } // Iterators iterator begin() const noexcept { return data_; } iterator end() const noexcept { return data_ + size_; } const_iterator cbegin() const noexcept { return begin(); } const_iterator cend() const noexcept { return end(); }; reverse_iterator rbegin() const noexcept { return reverse_iterator(begin()); } reverse_iterator rend() const noexcept { return reverse_iterator(end()); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(end()); } // Capacity size_type size() const noexcept { return size_; } size_type size_in_bytes() const noexcept { return size_ * sizeof(T); } size_type capacity() const noexcept { return capacity_; } static constexpr size_type max_size() noexcept { return SIZE_MAX / sizeof(T); } bool empty() const noexcept { return size_ == 0; } // Element access T& operator[](size_t i) const noexcept { return data_[i]; } T& front() const noexcept { return data_[0]; } T& back() const noexcept { return data_[size_ - 1]; } T* data() const noexcept { return data_; } T* data_end() const noexcept { return data_ + size_; } array_ref<T> data_span() noexcept { return {data_, size_}; } array_ref<T const> data_span() const noexcept { return {data_, size_}; } T& at(size_t i) { return checked_read(i); } T& at(size_t i) const { return checked_read(i); } T& checked_read(size_t i) { if (i >= size_) { throw std::out_of_range("fast_vector array index out of range."); } return data_[i]; } const T& checked_read(size_t i) const { return const_cast<self&>(*this).checked_read(i); } fast_vector& operator=(const fast_vector& otherVector) { assign(otherVector); return *this; } fast_vector& operator=(fast_vector&& otherVector) // Throws std::bad_alloc if low on memory. { transfer_from(otherVector); return *this; } // Clear any existing elements and copy the new elements from span. void assign(array_ref<const T> span) { #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF assert(!span.intersects(data_span())); // No self intersection. #endif clear(); size_t newSize = span.size(); reserve(newSize); std::uninitialized_copy(FASTVECTOR_MAKE_UNCHECKED(span.data()), FASTVECTOR_MAKE_UNCHECKED(span.data()) + newSize, /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_)); size_ = newSize; } // Clear any existing elements and copy the new elements from the iterable range. template <typename IteratorType> void assign(IteratorType begin, IteratorType end) { clear(); size_t newSize = std::distance(begin, end); reserve(newSize); std::uninitialized_copy(FASTVECTOR_MAKE_UNCHECKED(begin), FASTVECTOR_MAKE_UNCHECKED(end), /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_)); size_ = newSize; } // Tranfer all elements from the other vector to this one. // This only offers the weak exception guarantee, that no leaks will happen // if type T throws in the middle of a copy. void transfer_from(array_ref<const T> span) { #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF assert(!span.intersects(data_span())); // No self intersection. #endif clear(); size_t newSize = span.size(); reserve(newSize); std::uninitialized_move(FASTVECTOR_MAKE_UNCHECKED(span.data()), FASTVECTOR_MAKE_UNCHECKED(span.data()) + newSize, /*out*/ FASTVECTOR_MAKE_UNCHECKED(data_)); size_ = newSize; } // Tranfer all elements from the other vector to this one. // This only offers the weak exception guarantee, that no leaks will happen // if type T throws in the middle of a copy. void transfer_from(fast_vector<T, 0, ShouldInitializeElements>& other) { if (&other == this) { return; // Nop for self assignment. } if (other.dataIsAllocatedMemory_) { free(); // Take ownership of new data directly. data_ = other.data_; other.data_ = nullptr; size_ = other.size_; other.size_ = 0; capacity_ = other.capacity_; other.capacity_ = 0; dataIsAllocatedMemory_ = other.dataIsAllocatedMemory_; other.dataIsAllocatedMemory_ = false; } else { // Copying from a fixed size buffer; so it's unsafe to simply // steal the pointers as that may leave a dangling pointer // when the other fast vector disappears. transfer_from(make_array_ref(other)); } } void clear() noexcept(std::is_nothrow_destructible<T>::value) { if (ShouldInitializeElements) { std::destroy(data_, data_ + size_); } size_ = 0; // But do not free heap memory. } void resize(size_t newSize) { if (newSize > size_) { if (newSize > capacity_) { reserve_at_least(newSize); } // Grow data to the new size, calling the default constructor on each new item. if (ShouldInitializeElements) { std::uninitialized_value_construct<iterator>(data_ + size_, data_ + newSize); } size_ = newSize; } else if (newSize < size_) { // Shrink the data to the new size, calling the destructor on each item. Capacity remains intact. if (ShouldInitializeElements) { std::destroy(data_ + newSize, data_ + size_); } size_ = newSize; } } void reserve(size_t newCapacity) { if (newCapacity <= capacity_) { return; // Nothing to do. } if (newCapacity > max_size()) { throw std::bad_alloc(); // Too many elements. } size_t newByteSize = newCapacity * sizeof(T); ReallocateMemory(newByteSize); capacity_ = newCapacity; } void reserve_at_least(size_t newCapacity) { // Grow with 1.5x factor to avoid frequent reallocations. newCapacity = std::max((size_ * 3 / 2), newCapacity); reserve(newCapacity); } void shrink_to_fit() { if (!dataIsAllocatedMemory_ || capacity_ == size_) { return; // Nothing to do. } size_t newByteSize = size_ * sizeof(T); ReallocateMemory(newByteSize); capacity_ = size_; } void push_back(const T& newValue) { reserve(size_ + 1);// new(static_cast<void*>(data_ + size_)) T(newValue); ++size_; } void push_back(T&& newValue) { reserve(size_ + 1); new(static_cast<void*>(data_ + size_)) T(std::move(newValue)); ++size_; } void append(array_ref<const T> span) { insert(size_, span); } void insert(size_t insertionOffset, array_ref<const T> span) { insert(insertionOffset, span.begin(), span.end()); } void insert(size_t insertionOffset, const_iterator begin, const_iterator end) { assert(insertionOffset <= size_); // Grow array size. size_t newSize = std::distance(begin, end) + size_; if (newSize < size_) { throw std::bad_alloc(); } reserve_at_least(newSize); // Add empty elements to the end. size_t oldSize = size_; if (ShouldInitializeElements) { std::uninitialized_value_construct<iterator>(data_ + size_, data_ + newSize); } size_ = newSize; // Shift elements to the end to make more room. std::move_backward(data_ + insertionOffset, data_ + oldSize, data_ + newSize); std::copy(begin, end, /*out*/ data_ + insertionOffset); } void insert(const_iterator position, array_ref<const T> span) { insert(position - begin(), span.begin(), span.end()); } void erase(const_iterator begin, const_iterator end) { assert(end >= begin); assert(begin >= data_); assert(end <= data_ + size_); // Shift elements to front. size_t oldSize = size_; std::copy(iterator(end), data_ + size_, iterator(begin)); size_ -= std::distance(begin, end); // Destroy elements at the end. if (ShouldInitializeElements) { std::destroy(data_ + size_, data_ + oldSize); } } void erase(const_iterator position) { erase(position, position + 1); } // Returns underlying malloc()'d memory block. // - May be transferred to another fast_vector via attach_memory. // - Caller must free() the memory if not transferred. // - This is more safely used when T is a POD type, as the caller would also // need to appropriately call any destructors if complex objects. // - If the vector is using fixed size memory (no allocations have happened), // the returned span is empty and points to null. // - If the vector is using allocated memory, the memory block will be not // empty and non-null, and the vector is then empty. // - No object destructors are called. // - If NeedsTypeAlignmentBeyondMaxAlignT is true, the data array might start // after the memory block for alignment. // // fast_vector<int> vector(20); // ... // auto memory = vector.detach_memory(); // std::unique_ptr<char, decltype(&std::free)> p(memory.data(), &std::free); // ... // otherVector.attach_memory(memory); // p.release(); // unique_ptr does not own it anymore. // array_ref<uint8_t> detach_memory() noexcept { array_ref<uint8_t> data; // Only heap allocated memory can be returned, not the fixed size buffer. if (dataIsAllocatedMemory_) { // Return the raw memory block, from the actual beginning of memory to the true end. // The data might start beyond the memory block for alignment purposes. uint8_t* bytes = reinterpret_cast<uint8_t*>(data_); size_t byteCount = size_ * sizeof(T); data = {reinterpret_cast<uint8_t*>(GetMemoryBlock(data_)), bytes + byteCount}; data_ = nullptr; size_ = 0; capacity_ = 0; } return data; } // Take ownership of the memory, which came from malloc or another fast_vector // via detach_memory. // - If ShouldInitializeElements == true, then the memory is presumed to contain // valid objects, which will be destructed when the fast_vector dies. // - Because the memory is raw, it's possible to reuse a different data type. // - The memory must be aligned to alignof(std::max_align_t). // - If NeedsTypeAlignmentBeyondMaxAlignT is true, the memory must be at least // sizeof(void*) bytes. // void attach_memory(array_ref<uint8_t> memory) noexcept(std::is_nothrow_destructible<T>::value) { #ifndef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF assert(!memory.intersects(data_span())); // No self intersection. #endif assert((reinterpret_cast<size_t>(memory.data()) & (alignof(std::max_align_t) - 1)) == 0); // malloc/realloc should return aligned pointers up to max_align_t. assert(memory.data() == nullptr || memory.size() >= MinimumMemoryBlockSize); free(); T* data = AlignMemoryBlock(memory.data()); // Take ownership of new data. data_ = data; uint8_t* dataEnd = memory.data() + memory.size(); size_ = (dataEnd - reinterpret_cast<uint8_t*>(data_)) / sizeof(T); capacity_ = size_; dataIsAllocatedMemory_ = true; } protected: void ReallocateMemory(size_t newByteSize) // Throws std::bad_alloc if low on memory, or if T's move constructor fails. { assert(newByteSize >= size_ * sizeof(T)); // Shouldn't have been called otherwise, because it's wrong for size_ to be less than actual memory. // Handle alignment needs when the type is beyond what malloc/realloc guarantee. // This needed for SSE and AVX types (which need 16 and 32 bytes). Any other standard // type should have sufficient alignment by default. newByteSize = InflateMemorySizeForAlignment(newByteSize); // Try to reallocate the memory block directly rather allocate a new block and manually // copying. The memory manager can sometimes just extend the existing data block in-place // if there is space behind the block. Only trivially moveable types comply though, whereas // std::string would not comply due to the small string optimization. if (std::is_trivially_move_constructible<T>::value && dataIsAllocatedMemory_) { // Try to just reallocate the existing memory block. void* memory = realloc(GetMemoryBlock(data_), newByteSize); if (memory == nullptr && newByteSize > 0) { throw std::bad_alloc(); } data_ = AlignMemoryBlock(/*modified*/ memory); } else { // Allocate a new memory buffer if one isn't allocated yet, // or if the data type is complex enough that it's not trivially // moveable (e.g. std::string, which contains pointers that point // into the class address itself for the small string optimization). void* memory = std::malloc(newByteSize); std::unique_ptr<void, decltype(std::free)*> newDataHolder(memory, &std::free); // Copy an any existing elements from the fixed size buffer. T* newData = AlignMemoryBlock(memory); std::uninitialized_move(FASTVECTOR_MAKE_UNCHECKED(data_), FASTVECTOR_MAKE_UNCHECKED(data_) + size_, /*out*/ FASTVECTOR_MAKE_UNCHECKED(newData)); // Release the existing block, and assign the new one. if (dataIsAllocatedMemory_) { FreeMemoryBlock(data_); } newDataHolder.release(); data_ = newData; dataIsAllocatedMemory_ = true; // Caller updates capacity_ and size_. This simply reallocates the memory block. } } // No object destruction, just a direct free. static void FreeMemoryBlock(T* data) { std::free(GetMemoryBlock(data)); } // Get the actual memory block associated with the data. static void* GetMemoryBlock(T* data) { mutable_value_type* mutableData = const_cast<mutable_value_type*>(data); if (NeedsTypeAlignmentBeyondMaxAlignT && data != nullptr) { // Read the pointer to the actual block which is set immediately before the data. // [ptr to memory block][data ...] return reinterpret_cast<void**>(mutableData)[-1]; } else { return mutableData; } } // Return aligned data for the given type, storing the raw memory block from malloc. // Write the memory block associated with the data, and return the data. // The caller has already ensure enough space exists in the block for alignment. static T* AlignMemoryBlock(void* memory) { if (NeedsTypeAlignmentBeyondMaxAlignT && memory != nullptr) { // Return a pointer to the aligned data, which starts after the pointer to the original // memory. // // [ptr to memory block][data ...] // Return the pointer to the actual block which is set immediately before the data. // [ptr to memory block][data ...] constexpr size_t alignmentMask = alignof(T) - 1; static_assert((alignof(T) & alignmentMask) == 0, "Alignment must be a power of 2."); static_assert(NeedsTypeAlignmentBeyondMaxAlignT == false || alignof(T) >= alignof(void*), "Alignment must be at least the size of a pointer for NeedsTypeAlignmentBeyondMaxAlignT to be true."); // Align memory. Note calling std::align is awkward given it expects sizes, which are // already correct earlier and do not need to be passed to this function. size_t memoryAddress = reinterpret_cast<size_t>(memory); memoryAddress = (memoryAddress + sizeof(void*) + alignmentMask) & ~alignmentMask; mutable_value_type* data = reinterpret_cast<mutable_value_type*>(memoryAddress); // Store the pointer to the original memory block. reinterpret_cast<void**>(data)[-1] = memory; return data; } else { assert((reinterpret_cast<size_t>(memory) & (alignof(std::max_align_t) - 1)) == 0); // malloc/realloc should return aligned pointers up to max_align_t. return reinterpret_cast<T*>(memory); } } static size_t InflateMemorySizeForAlignment(size_t newByteSize) { if (NeedsTypeAlignmentBeyondMaxAlignT && newByteSize != 0) { // Need to increase the allocation size to include enough for full type alignment // and the size of a single pointer preceding the data. size_t alignedByteSize = newByteSize + alignof(T) - alignof(std::max_align_t) + MinimumMemoryBlockSize; if (alignedByteSize < newByteSize) { throw std::bad_alloc(); // Too much memory requested and overflowed. } newByteSize = alignedByteSize; } // else malloc/realloc default alignment will suffice. return newByteSize; } protected: T* data_ = nullptr; // May point to fixed size array or allocated memory, depending on dataIsAllocatedMemory_. size_t size_ = 0; // Count in elements. size_t capacity_ = 0; // Count in elements. bool dataIsAllocatedMemory_ = false; }; // Derived specialization which includes a fixed size buffer. template <typename T, size_t DefaultArraySize, bool ShouldInitializeElements> class fast_vector : public fast_vector<T, 0, ShouldInitializeElements> { public: using BaseClass = fast_vector<T, 0, ShouldInitializeElements>; constexpr fast_vector() noexcept : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData()) { } fast_vector(array_ref<const T> initialValues) : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), initialValues) { } fast_vector(std::initializer_list<const T> initialValues) : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), make_array_ref(initialValues)) { } fast_vector(const fast_vector& otherVector) : BaseClass(otherVector) { } fast_vector(typename BaseClass::pointer p, size_t elementCount) : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), p, elementCount) { } template <typename IteratorType> fast_vector(IteratorType begin, IteratorType end) : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), begin, end) { } fast_vector(size_t initialSize) : BaseClass(fast_vector_use_memory_buffer, GetFixedSizeArrayData(), initialSize) { } // Move constructor. Will not throw unless type T throws, since the // target is guaranteed to have enough space. fast_vector(fast_vector&& otherVector) noexcept(std::is_nothrow_move_assignable<T>::value) : BaseClass(std::move(otherVector)) { } // Explicit overload for base class, to avoid the compiler from undesireably // choosing the constructor overload which takes a span of initialValues or // the copy constructor. fast_vector(BaseClass&& otherVector) // Throws std::bad_alloc if low on memory. : BaseClass(std::move(otherVector)) { } // Move assignment. Will not throw unless type T throws, since the // target vector is guaranteed to have a large enough fixed-size array. fast_vector& operator=(fast_vector&& otherVector) noexcept(std::is_nothrow_move_assignable<T>::value && std::is_nothrow_destructible<T>::value) { BaseClass::transfer_from(otherVector); return *this; } fast_vector& operator=(BaseClass&& otherVector) // Throws std::bad_alloc if low on memory. { BaseClass::transfer_from(otherVector); return *this; } fast_vector& operator=(const fast_vector& otherVector) { BaseClass::assign(otherVector); return *this; } fast_vector& operator=(const BaseClass& otherVector) { BaseClass::assign(otherVector); return *this; } private: constexpr array_ref<T> GetFixedSizeArrayData() noexcept { return array_ref<T>(reinterpret_cast<T*>(std::data(fixedSizedArrayData_)), std::size(fixedSizedArrayData_)); } private: // Uninitialized data to be used by the base class. // It's declared as raw bytes rather than an std::array<T> to avoid any initialization cost // up front, only initializing the fields which actually exist when resized later. // // Note Visual Studio 2017 15.8 requires you to declare _ENABLE_EXTENDED_ALIGNED_STORAGE // if your type T is > max_align_t. // std::aligned_storage_t<sizeof(T), alignof(T)> fixedSizedArrayData_[DefaultArraySize]; }; #ifdef USE_GSL_SPAN_INSTEAD_OF_ARRAY_REF #undef array_ref #endif #undef FASTVECTOR_MAKE_UNCHECKED #pragma warning(pop) EXPORT_END
{ "alphanum_fraction": 0.6247732485, "avg_line_length": 37.1717557252, "ext": "h", "hexsha": "375fb87421f4193cfcb2a8d0b1614ca96d3ba1d3", "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": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "moyogo/TextLayoutSampler", "max_forks_repo_path": "Common.FastVector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "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": "moyogo/TextLayoutSampler", "max_issues_repo_path": "Common.FastVector.h", "max_line_length": 205, "max_stars_count": null, "max_stars_repo_head_hexsha": "b4acfafde44c4f06a9ed74308a3268c4093817ac", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "moyogo/TextLayoutSampler", "max_stars_repo_path": "Common.FastVector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6257, "size": 29217 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <assert.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <stdbool.h> #include "core_allvars.h" #include "core_proto.h" #define IMF_CONSTANT IMF_norm/(IMF_slope + 1.0) // Local Proto-Types // void update_SN_stars_array(int p, double stars, double dt, int tree, int ngal); void update_stellar_tracking(int p, double stars, double dt, int tree, int ngal); // External Functions // void update_from_SN_feedback(int p, int centralgal, double reheated_mass, double ejected_mass, double mass_stars_recycled, double mass_metals_new, double NSN, double dt) { double metallicity, metallicityHot, dust_fraction_cold, dust_fraction_hot; double dust_fraction_coldhot, dust_fraction_hotcold; // These are the dust fractions defined by M_colddust / (Mcold + Mhot) and M_hotdust / (Mcold + Mhot). // These second dust fractions are required because when we annihilate dust from SN we want the TOTAL amount to be NSN * eta * Ms. // Dust constants, taken mainly from Dayal, Ferrara and Saro 2011. double yd = 0.5 / 1.0e10 * Hubble_h; // Amount of dust mass created from each supernova event. Units of Msun. double eta = 0.4; // Coupling between shock energy and annihilation of dust. double Ms = 6.8e3 / 1.0e10 * Hubble_h; // Amount of mass that is accelerated to 100km/s by SN blastwave. Units of Msun. double dust_added = 0.0, dust_removed = 0.0; XASSERT((reheated_mass >= 0.0) && (ejected_mass >= 0.0) && (mass_stars_recycled >= 0.0) && (mass_metals_new >= 0.0), "When trying to update from the supernova feedback we got negative masses.\nReheated Mass = %.4e (1.0e10 Msun/h) \t Ejected Mass = %.4e (1.0e10 Msun/h) \t Mass of Stars Recycled = %.4e (1.0e10 Msun/h) \t Mass of Metals Added = %.4e (1.0e10 Msun/h)\n", reheated_mass, ejected_mass, mass_stars_recycled, mass_metals_new); Gal[p].StellarMass -= mass_stars_recycled; // The supernova remnants are instantly moved back into the cold ISM. Gal[p].Total_Stellar_Stars -= mass_stars_recycled; if (Gal[p].Total_Stellar_Stars < 0.0) Gal[p].Total_Stellar_Stars = 0.0; Gal[p].ColdGas += mass_stars_recycled; Gal[p].DustColdGas += yd * NSN; // Dust is created by supernova (something) on cold gas. Gal[p].ColdGas -= yd * NSN; // Hence the created dust is subtracted from the cold gas reservoir. dust_added += yd * NSN; if(Gal[p].ColdGas > 1.0e-10) Gal[p].MetalsColdGas += mass_metals_new; // ISM is enriched by new metals. else Gal[centralgal].MetalsHotGas += mass_metals_new; // Here we do checks to see if we need to rescale the amount of mass that has been ejected/reheated. // if(reheated_mass > Gal[p].ColdGas) // Just perform this check again to be sure. reheated_mass = Gal[p].ColdGas; // Because SF takes gas out of cold resevoir. if(ejected_mass > Gal[centralgal].HotGas) ejected_mass = Gal[centralgal].HotGas; metallicity = get_metallicity(Gal[p].ColdGas, Gal[p].MetalsColdGas); dust_fraction_cold = get_dust_fraction(Gal[p].ColdGas, Gal[p].DustColdGas); dust_fraction_coldhot = get_dust_fraction(Gal[p].ColdGas + Gal[p].HotGas + Gal[p].EjectedMass, Gal[p].DustColdGas); Gal[p].ColdGas -= reheated_mass; Gal[p].MetalsColdGas -= reheated_mass * metallicity; Gal[p].DustColdGas -= reheated_mass * dust_fraction_cold; // Dust that has been reheated to the hot reservoir. Gal[p].DustColdGas -= NSN * eta * Ms * dust_fraction_coldhot; // Dust that has been annihilated by shocks. dust_removed += NSN * eta * Ms * dust_fraction_coldhot; Gal[centralgal].HotGas += reheated_mass; Gal[centralgal].MetalsHotGas += reheated_mass * metallicity; Gal[centralgal].DustHotGas += reheated_mass * dust_fraction_cold; metallicityHot = get_metallicity(Gal[centralgal].HotGas, Gal[centralgal].MetalsHotGas); dust_fraction_hot = get_dust_fraction(Gal[p].HotGas, Gal[p].DustHotGas); dust_fraction_hotcold = get_dust_fraction(Gal[p].ColdGas + Gal[p].HotGas + Gal[p].EjectedMass, Gal[p].DustHotGas); // When dust_fraction_hotcold is calculated is irrelevant (i.e., before or after mass is added/subtracted from ColdGas). // This is because mass is conserved between ColdGas and HotGas during this step. Gal[centralgal].HotGas -= ejected_mass; Gal[centralgal].MetalsHotGas -= ejected_mass * metallicityHot; Gal[centralgal].DustHotGas -= ejected_mass * dust_fraction_hot; // Dust that has been ejected from the galaxy. Gal[centralgal].DustHotGas -= NSN * eta * Ms * dust_fraction_hotcold; // Dust that has been annihilated by shocks. dust_removed += NSN * eta * Ms * dust_fraction_hotcold; Gal[centralgal].EjectedMass += ejected_mass; Gal[centralgal].MetalsEjectedMass += ejected_mass * metallicityHot; Gal[centralgal].DustEjectedMass += ejected_mass * dust_fraction_hot; Gal[centralgal].EjectedMassSN += ejected_mass; Gal[p].GridOutflowRate[Halo[Gal[centralgal].HaloNr].SnapNum] += ejected_mass / dt; Gal[p].GrandSum -= mass_stars_recycled; if(Gal[p].ColdGas < 0.0) // Some final checks. Gal[p].ColdGas = 0.0; if(Gal[p].MetalsColdGas < 0.0) Gal[p].MetalsColdGas = 0.0; if(Gal[p].StellarMass < 0.0) Gal[p].StellarMass = 0.0; if(Gal[centralgal].HotGas < 0.0) Gal[centralgal].HotGas = 0.0; if(Gal[p].MetalsHotGas < 0.0) Gal[p].MetalsHotGas = 0.0; if(Gal[p].GrandSum < 0.0) Gal[p].GrandSum = 0.0; if (Gal[p].DustColdGas < 0.0) Gal[p].DustColdGas = 0.0; if (Gal[p].DustHotGas < 0.0) Gal[p].DustHotGas = 0.0; } void update_from_star_formation(int p, double stars, double dt, int step, bool ismerger, int tree, int ngal) { double metallicity = get_metallicity(Gal[p].ColdGas, Gal[p].MetalsColdGas); double dust_fraction_cold = get_dust_fraction(Gal[p].ColdGas, Gal[p].DustColdGas); double time_spanned; // If the SF episode was from a merger the stars are placed in different reservoirs. if(!ismerger) { Gal[p].SfrDisk[step] += stars / dt; Gal[p].SfrDiskColdGas[step] = Gal[p].ColdGas; Gal[p].SfrDiskColdGasMetals[step] = Gal[p].MetalsColdGas; } else { Gal[p].SfrBulge[step] += stars / dt; Gal[p].SfrBulgeColdGas[step] += Gal[p].ColdGas; Gal[p].SfrBulgeColdGasMetals[step] += Gal[p].MetalsColdGas; Gal[p].BulgeMass += stars; Gal[p].MetalsBulgeMass += stars; } // If we're doing delayed SN we need to update the tracking if (ismerger == true) { time_spanned = 0.0; } else { time_spanned = dt; } //time_spanned = dt; if (IRA == 0) { update_SN_stars_array(p, stars, time_spanned, tree, ngal); } if (PhotonPrescription == 1) { update_stellar_tracking(p, stars, dt, tree, ngal); } // update gas and metals from star formation Gal[p].ColdGas -= stars; Gal[p].MetalsColdGas -= metallicity * stars; Gal[p].StellarMass += stars; Gal[p].MetalsStellarMass += metallicity * stars; Gal[p].DustColdGas -= dust_fraction_cold * stars; // When stars form they eat up dust. if (Gal[p].ColdGas < 0.0) Gal[p].ColdGas = 0.0; if (Gal[p].MetalsColdGas < 0.0) Gal[p].MetalsColdGas = 0.0; } void starformation_and_feedback(int p, int centralgal, double time, double dt, int halonr, int step, int tree, int ngal) { double reff, tdyn, strdot, stars; double cold_crit; double reheated_mass = 0.0, mass_metals_new = 0.0, mass_stars_recycled = 0.0, ejected_mass = 0.0, NSN = 0.0; // Initialise variables strdot = 0.0; // First we check to see if we need to do delayed supernova feedback. if(IRA == 0) { do_previous_recycling(p, centralgal, step, dt); // The total amount that the reservoirs need to be adjusted by for this evolution step (i.e., ALL steps) has already been determined. // Within each substep (i.e., each `step` iteration) we ask 'how many iterations are left?' and then adjusts the reservoirs by this amount. // After the reservoirs have been updated, we subtract the amount of mass that we added from the running totals. // // These running totals are required because contemporaneous SN could cause extra mass to be added/removed within the next step iteration. update_from_SN_feedback(p, centralgal, Gal[p].reheated_mass / (STEPS-step), Gal[p].ejected_mass / (STEPS-step), Gal[p].mass_stars_recycled / (STEPS-step), Gal[p].mass_metals_new / (STEPS-step), Gal[p].NSN / (STEPS-step), dt); Gal[p].reheated_mass -= Gal[p].reheated_mass / (STEPS-step); Gal[p].ejected_mass -= Gal[p].ejected_mass / (STEPS-step); Gal[p].mass_stars_recycled -= Gal[p].mass_stars_recycled / (STEPS-step); Gal[p].mass_metals_new -= Gal[p].mass_metals_new / (STEPS-step); Gal[p].NSN -= Gal[p].NSN / (STEPS-step); } // star formation recipes if(SFprescription == 0) { // we take the typical star forming region as 3.0*r_s using the Milky Way as a guide reff = 3.0 * Gal[p].DiskScaleRadius; tdyn = reff / Gal[p].Vvir; // from Kauffmann (1996) eq7 x piR^2, (Vvir in km/s, reff in Mpc/h) in units of 10^10Msun/h cold_crit = 0.19 * Gal[p].Vvir * reff; if(Gal[p].ColdGas > cold_crit && tdyn > 0.0) strdot = SfrEfficiency * (Gal[p].ColdGas - cold_crit) / tdyn; else { strdot = 0.0; } } else { printf("No star formation prescription selected!\n"); ABORT(0); } stars = strdot * dt; if(stars < 0.0) stars = 0.0; if(SupernovaRecipeOn == 1) { if(IRA == 0) do_contemporaneous_SN(p, centralgal, dt, &stars, &reheated_mass, &mass_metals_new, &mass_stars_recycled, &ejected_mass, &NSN); else if(IRA == 1) { do_IRA_SN(p, centralgal, &stars, &reheated_mass, &mass_metals_new, &mass_stars_recycled, &ejected_mass, &NSN); } } if(stars > Gal[p].ColdGas) // we do this check in 'do_current_sn()' but if supernovarecipeon == 0 then we don't do the check. { double factor = Gal[p].ColdGas / stars; stars *= factor; } update_from_star_formation(p, stars, dt, step, false, tree, ngal); update_from_SN_feedback(p, centralgal, reheated_mass, ejected_mass, mass_stars_recycled, mass_metals_new, NSN, dt); // check for disk instability if(DiskInstabilityOn) check_disk_instability(p, centralgal, halonr, time, dt, step, tree, ngal); } // This function will calculate the fraction of stars formed in snapshot i that go nova in snapshot j. // Will also calculate the mass fraction of stars formed in snapshot i that go nova in snapshot j. // Based off equation (17) and (24) of Mutch et al. (2016). // // INPUT: The bounds for the integral (m_low and m_high). ## UNITS: Msun. // : Pointers to modify the values for number and mass fraction of stars that go nova (*Delta_Eta and *Delta_m). ## UNITS: Msun^-1 (Delta_Eta) and unitless (Delta_m). // // OUTPUT: None but delta_Eta, the number fraction of stars, and delta_m, the mass fraction of stars, will be modified. void calculate_Delta_Eta(double m_low, double m_high, double *Delta_Eta, double *Delta_m) { if (m_low < 8.0) m_low = 8.0; if (m_high < 8.0) m_high = 8.0; int32_t bin_idx_low = round((m_low - m_IMFbins_low) / (m_IMFbins_delta)); int32_t bin_idx_high = round((m_high - m_IMFbins_low) / (m_IMFbins_delta)); if (bin_idx_high == N_massbins) --bin_idx_high; if (bin_idx_low == N_massbins) --bin_idx_low; *Delta_Eta = IMF_CONSTANT * (IMF_massgrid_eta[bin_idx_high] - IMF_massgrid_eta[bin_idx_low]); *Delta_m = IMF_CONSTANT * (IMF_massgrid_m[bin_idx_high] - IMF_massgrid_m[bin_idx_low]); } // This function determines the amount of mass reheated for a supernova event. // // INPUT: The number fraction of stars that have gone nova (Delta_Eta) ## UNITS: Msun^-1. // : The mass of stars formed (stars). ## UNITS: 1.0e10Msun/h (code units). // : The maximum velocity of the galaxy disc (Vmax). ## UNITS: km/s. // // OUTPUT: The amount of mass reheated by the supernova event. ## UNITS: 1.0e10Msun/h (code units). double calculate_reheated_mass(double Delta_Eta, double stars, double Vmax) { // if(stars < 1e-10) // return 0.0; double epsilon_mass; if(RescaleSN == 0) { epsilon_mass = FeedbackReheatingEpsilon; } else { epsilon_mass = alpha_mass * (0.5 + pow(Vmax/V_mass, -beta_mass)); } if (epsilon_mass > epsilon_mass_max) { epsilon_mass = epsilon_mass_max; // We enforce a maximum value for the mass loading factor. } double reheated_mass = Delta_Eta/Eta_SNII * stars * epsilon_mass; return reheated_mass; } // This function determines the amount of energy injected from a supernova event. // // INPUT: The number fraction of stars that have gone nova (Delta_Eta) ## UNITS: Msun^-1. // : The mass of stars formed (stars). ## UNITS: 1.0e10Msun/h (code units). // : The maximum velocity of the galaxy disc (Vmax). ## UNITS: km/s. // // OUTPUT: The amount of energy from a supernova event. ## UNITS: erg. double calculate_reheated_energy(double Delta_Eta, double stars, double Vmax) { double epsilon_energy; if(RescaleSN == 0) { epsilon_energy = FeedbackEjectionEfficiency; } else { epsilon_energy = alpha_energy * (0.5 + pow(Vmax/V_energy, -beta_energy)); } double reheated_energy = 0.5 * Delta_Eta * stars * epsilon_energy * EnergySN; // Delta_Eta was in Msun so need to convert to stars to Msun. return reheated_energy; } // This function calculates the mass of stars that would have gone supernova in time t. // Function and fit taken from Portinari et al. (1998). // // INPUT: Time (in Myr). // // OUTPUT: Mass of stars (in Msun) that would have gone Nova in time t. double calculate_coreburning(double t) { /* double a = 0.7473; // Fits from Portinari et al. (1998). double b = -2.6979; double c = -4.7659; double d = 0.5934; double m = pow(10, a/log10(t) + b * exp(c/log10(t)) + d); return m; */ int32_t bin_idx = (t - coreburning_tbins_low) / (coreburning_tbins_delta); if (bin_idx < 0) // Time is so short that only stars with mass greater than 120Msun can go nova. return 120.0; if (bin_idx > N_tbins) // Time is so long that all stars within the IMF range can go nova. return 8.0; return coreburning_times[bin_idx]; } // If the cold gas that has been reheated has enough energy, it is possible to unbind some of the gas in the hot halo. // This function determines this threshhold and how much mass is unbound and ejected. // // INPUT: Amount of cold gas reheated by supernova events (reheated_mass). ## UNITS: 1.0e10Msun/h (code units). // : Amount of energy injected from the supernova events (reheated_energy). ## UNITS: erg. // : Virial velocity of the background FoF halo (Vvir). ## UNITS: km/s. // // OUTPUT: Mass of ejected material. ## UNITS: 1.0e10Msun/h (code units). // // Note: Be aware here that a number of unit changes have occurred. // This is necessary because of how Joules are defined. double calculate_ejected_mass(double *reheated_mass, double reheated_energy, double Vvir) { double ejected_mass; double Delta_Ehot; const double Joule_to_erg = 0.5 * SOLAR_MASS / 1.0e3 * 1.0e3 * 1.0e3 * 1.0e7; // Note: This is ergs assuming the mass used is in kg. // As we use 1.0e10 Msun/h our energy isn't quite ergs. // However we have kept this consistent throughout allowing the factor to be cancelled. const double inv_Joule_to_erg = 1.0 / Joule_to_erg; if(Vvir > 0.0) { Delta_Ehot = *reheated_mass * Vvir * Vvir * Joule_to_erg; // Change in the thermal energy of the hot resevoir in erg.. // Note the units here. Want final answer in Ergs (which is 1e-7 Joules) which has SI units of kg m^2 s^-2. // We change the mass from 1.0e10Msun/h to kg. Change virial velocity from km/s to m/s. Finally change Joules to erg. if(reheated_energy > Delta_Ehot) // Have enough energy to have some ejected mass. { ejected_mass = (reheated_energy - Delta_Ehot) * inv_Joule_to_erg / (Vvir * Vvir); // Balance between the excess thermal energy and the thermal energy of the hot gas. // Energy changed from erg to Joules (kg m^2 s^-2) then divided by virial velocity (converted to m/s) giving final units of kg. } else // Not enough energy to eject mass. { ejected_mass = 0.0; *reheated_mass = reheated_energy * inv_Joule_to_erg / (Vvir * Vvir); // Amount of mass that can be reheated to virial temperature of the hot halo. } } else ejected_mass = 0.0; if(ejected_mass < 0.0) ejected_mass = 0.0; return ejected_mass; } // This function answers the question, "How many stars formed in the previous time steps will explode during the current supernova timestep." // Note: Since the time scale on which we calculate SN feedback is variable (defined by the user in 'TimeResolutionSN') we use the terminology 'supernova timestep'. // Double note: This function is different to "do_contemporaneous_SN" because that looks at the stars formed during the CURRENT STAR FORMATION time step, not previous ones. void do_previous_SN(int p, int centralgal, double dt) { double reheated_mass = 0.0; double reheated_energy = 0.0; double mass_stars_recycled = 0.0; double mass_metals_new = 0.0; double ejected_mass = 0.0; double NSN = 0.0; // This is the number of supernova events during this time step. int i; double m_low = -1.0, m_high = -1.0, t_low = -1.0, t_high = -1.0; double Delta_Eta, Delta_m; double time_until_next_SN; if(dt * UnitTime_in_Megayears / Hubble_h < TimeResolutionSN) // If the star formation time scale is smaller than the time scale on which we do SN feedback time_until_next_SN = TimeResolutionSN; // Then the time that we next calculate delayed SN feedback would be given dictated by the time resolution of SN. else // Otherwise the star formation time scale is larger than the SN feedback time scale. { time_until_next_SN = dt * UnitTime_in_Megayears / Hubble_h; // Then the time that we next calculate delayed SN feedback is in the next SF timestep. } if(SupernovaRecipeOn == 1) // Calculating the ejected mass due to previous star formation episodes. { for(i = 1; i < SN_Array_Len; ++i) { if(Gal[p].SN_Stars[i] < 1e-10) continue; // First calculate the smallest star which would have expended its H and He and gone supernova. // This defines the mass boundary below which a star will not go nova in the current SN step. t_low = (i * TimeResolutionSN) / 2.0 + time_until_next_SN; // (i * TimeResolutionSN) is the number of stars that were formed that many megayears ago. time_until_next_SN allows us to ask how many of stars will explode in this SN step. if(t_low < 2) t_low = 2; if (t_low > 45) m_low = 120.0; m_low = calculate_coreburning(t_low); if (m_low < 8.0) // We enforce that SN-II only occur in stars M > 8Msun. m_low = 8.0; if (m_low > 120.0) continue; // Next we calculate the largest stellar mass which would have expended its H and He and gone supernova. // This defines the mass boundary beyond which a star would have gone nova BEFORE the current SN step. t_high = (i * TimeResolutionSN) / 2.0; // (i * TimeResolutionSN) is the number of stars that were formed that many Megayears ago. The / 2.0 factor arises from the fact that we assume stars were formed in a single co-eval burst in the middle of this period. if(t_high < 2) t_high = 2; m_high = calculate_coreburning(t_high); if (m_high < 8) // In this instance every star that has formed in i Myr ago has already gone supernova and accounted for. continue; if (m_high > 120.0) continue; calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars i Myr ago that go supernova in the current SF step. reheated_mass += calculate_reheated_mass(Delta_Eta, Gal[p].SN_Stars[i], Gal[centralgal].Vmax); // Update the amount of mass reheated from previous stars that have gone nova. reheated_energy += calculate_reheated_energy(Delta_Eta, Gal[p].SN_Stars[i], Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. mass_stars_recycled += Delta_m * Gal[p].SN_Stars[i]; // Update the amount of stellar mass recycled from previous stars that have gone nova. // Since stars have gone supernova, need to update the number of stars remaining at that time. if (PhotonPrescription == 1) { Gal[p].Stellar_Stars[i] -= Delta_m * Gal[p].SN_Stars[i]; if (Gal[p].Stellar_Stars[i] < 0.0) Gal[p].Stellar_Stars[i] = 0.0; } Gal[p].SN_Stars[i] -= Delta_m * Gal[p].SN_Stars[i]; if (Gal[p].SN_Stars[i] < 0.0) Gal[p].SN_Stars[i] = 0.0; mass_metals_new += Delta_m / m_SNII * Yield * Gal[p].SN_Stars[i]; // Update the amount of new metals that the supernova has enriched the ISM with. NSN += Delta_Eta * Gal[p].SN_Stars[i] * 1.0e10 / Hubble_h; // The number of supernova events will be simply given by the number fraction of stars that exploded times the mass of stars. XASSERT(reheated_mass >= 0.0, "i = %d \t Reheated mass = %.4e \t t_low = %.4e Myr \t m_low = %.4e \t t_high = %.4e Myr \t m_high = %.4e\n", i, reheated_mass, t_low, m_low, t_high, m_high); // Just make sure we're doing this right. } if(reheated_mass > Gal[p].ColdGas) // Can't reheated more cold gas than we currently have. reheated_mass = Gal[p].ColdGas; XASSERT(reheated_mass >= 0.0, "Reheated mass = %.4e \t t_low = %.4e Myr \t m_low = %.4e \t t_high = %.4e Myr \t m_high = %.4e\n", reheated_mass, t_low, m_low, t_high, m_high); // Just make sure we're doing this right. assert(reheated_energy >= 0.0); assert(mass_stars_recycled >= 0.0); assert(mass_metals_new >= 0.0); ejected_mass = calculate_ejected_mass(&reheated_mass, reheated_energy, Gal[centralgal].Vmax); // Calculate the amount of mass ejected from supernova events. XASSERT(ejected_mass >= 0.0, "For galaxy %d the ejected mass was %.4e \t reheated_mass = %.4e\n", p, ejected_mass, reheated_mass); } Gal[p].reheated_mass = reheated_mass; Gal[p].ejected_mass = ejected_mass; Gal[p].mass_stars_recycled = mass_stars_recycled; Gal[p].mass_metals_new = mass_metals_new; Gal[p].NSN = NSN; } /* void do_current_SN(int p, int centralgal, int halonr, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass) { *reheated_mass = 0.0; double reheated_energy = 0.0; *mass_stars_recycled = 0.0; *mass_metals_new = 0.0; *ejected_mass = 0.0; double Delta_Eta = Eta_SNII; double Delta_m = RecycleFraction; double mass_fraction = 1.0; *mass_stars_recycled = Delta_m * (*stars); *reheated_mass = calculate_reheated_mass(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the amount of mass reheated from stars that have gone nova. if(*reheated_mass > Gal[p].ColdGas) // Can only reheat as much cold gas we have available. *reheated_mass = Gal[p].ColdGas; if((*reheated_mass + *stars > Gal[p].ColdGas) && (*reheated_mass + *stars > 0.0)) { double factor = Gal[p].ColdGas / (*reheated_mass + *stars); *reheated_mass *= factor; *stars *= factor; } *mass_metals_new = mass_fraction * Yield * (*stars); // Update the amount of new metals that the supernova has enriched the ISM with. reheated_energy = calculate_reheated_energy(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. assert(*reheated_mass >= 0.0); // Just make sure we're doing this right. assert(reheated_energy >= 0.0); assert(*mass_stars_recycled >= 0.0); assert(*mass_metals_new >= 0.0); *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vvir); // Calculate the amount of mass ejected from supernova events. } */ void do_previous_recycling(int p, int centralgal, int step, double dt) { if(Gal[p].StellarAge_Numerator > 0.0) { double t_low, t_high; double m_low, m_high; double Delta_Eta, Delta_m; double mass_stars_recycled; double NSN; double mwmsa = Gal[p].StellarAge_Numerator / Gal[p].StellarAge_Denominator; // The numerator is weighted by the age of the stars with the denominator simply being the number of stars. double time_into_snap = dt * step; t_high = (mwmsa - ((Age[Gal[p].SnapNum - 1]) - time_into_snap)) * UnitTime_in_Megayears / Hubble_h; if (t_high < 2.0) t_high = 2.0; if (t_high > 45.0) m_high = 8.0; else m_high = calculate_coreburning(t_high); t_low = (mwmsa - (Age[Gal[p].SnapNum] - time_into_snap)) * UnitTime_in_Megayears / Hubble_h; if (t_low < 2.0) t_low = 2.0; if (t_low > 45.0) m_low = 8.0; else m_low = calculate_coreburning(t_low); calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars from snapshot i that go nova in the snapshot we are evolving FROM. mass_stars_recycled = Delta_m * Gal[p].StellarAge_Denominator; // Update the amount of stellar mass recycled from previous stars that have gone nova. NSN = Delta_Eta * Gal[p].StellarAge_Denominator * 1.0e10 / Hubble_h; update_from_SN_feedback(p, centralgal, 0.0, 0.0, mass_stars_recycled, 0.0, NSN, dt); } } // In this function we answer the question, "How many stars formed in the current star formation time step will explode by the time we next calculate our supernova feedback?" // Note: This function only concerns itself with stars formed in the CURRENT STAR FORMATION time step, unlike "do_previous_SN" which focuses on calculated SN feedback from PREVIOUS STAR FORMATION time steps. void do_contemporaneous_SN(int p, int centralgal, double dt, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass, double *NSN) { *reheated_mass = 0.0; double reheated_energy = 0.0; *mass_stars_recycled = 0.0; *mass_metals_new = 0.0; *ejected_mass = 0.0; double m_low, m_high, t_low; double Delta_Eta, Delta_m; double fac; if(dt * UnitTime_in_Megayears / Hubble_h / 2.0 < TimeResolutionSN) // If the star formation time scale is smaller than the time scale on which we do SN feedback t_low = (TimeResolutionSN - Gal[p].Total_SN_SF_Time); // Then our 'sub-grid' SN feedback time will be the time from this SF episode until we next calculate SN feedback (divided by 2 as we assume the stars are formed in the middle of the interval). else // Otherwise the star formation time scale is larger than the SN feedback time scale. t_low = (dt * UnitTime_in_Megayears / Hubble_h) / 2.0; // Then the feedback time will be the time from this SF event to the next star formation event. This is because SN feedback is only calculated when star formation occurs regardless of the actual value of 'TimeResolutionSN'. if (t_low < 2.0) t_low = 2.0; m_low = calculate_coreburning(t_low); if(m_low < 8.0) m_low = 8.0; if(m_low > 120.0) return; m_high = 120.0; calculate_Delta_Eta(m_low, m_high, &Delta_Eta, &Delta_m); // Calculate the number and mass fraction of stars i Myr ago that go supernova in the current SF step. *reheated_mass = calculate_reheated_mass(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the amount of mass reheated from previous stars that have gone nova. if((*stars + *reheated_mass) > Gal[p].ColdGas && (*stars + *reheated_mass) > 0.0) { fac = Gal[p].ColdGas / (*stars + *reheated_mass); *stars *= fac; *reheated_mass *= fac; } reheated_energy += calculate_reheated_energy(Delta_Eta, *stars, Gal[centralgal].Vmax); // Update the energy injected from previous stars that have gone nova. *mass_stars_recycled += Delta_m * (*stars); // Update the amount of stellar mass recycled from previous stars that have gone nova. *mass_metals_new += Delta_m / m_SNII * Yield * (*stars); // Update the amount of new metals that the supernova has enriched the ISM with. if(*reheated_mass > Gal[p].ColdGas) // Can't reheated more cold gas than we currently have. *reheated_mass = Gal[p].ColdGas; *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vmax); // Calculate the amount of mass ejected from supernova events. *NSN = Delta_Eta * (*stars * 1.0e10 / Hubble_h); assert(*reheated_mass >= 0.0); // Just make sure we're doing this right. assert(reheated_energy >= 0.0); assert(*mass_stars_recycled >= 0.0); assert(*mass_metals_new >= 0.0); assert(*ejected_mass >= 0.0); } void do_IRA_SN(int p, int centralgal, double *stars, double *reheated_mass, double *mass_metals_new, double *mass_stars_recycled, double *ejected_mass, double *NSN) { double fac; *reheated_mass = 0.0; *mass_metals_new = 0.0; *mass_stars_recycled = 0.0; *ejected_mass = 0.0; *reheated_mass = calculate_reheated_mass(Eta_SNII, *stars, Gal[centralgal].Vmax); *NSN = Eta_SNII * (*stars); if((*stars + *reheated_mass) > Gal[p].ColdGas && (*stars + *reheated_mass) > 0.0) { fac = Gal[p].ColdGas / (*stars + *reheated_mass); *stars *= fac; *reheated_mass *= fac; } double reheated_energy = calculate_reheated_energy(Eta_SNII, *stars, Gal[centralgal].Vmax); *ejected_mass = calculate_ejected_mass(&(*reheated_mass), reheated_energy, Gal[centralgal].Vmax); if(*ejected_mass < 0.0) *ejected_mass = 0.0; *mass_metals_new = Yield * (*stars); *mass_stars_recycled = RecycleFraction * (*stars); } // Local Functions // // This function updates the array which holds the amount of stars formed in the past 50 Myr. // As we only need this array for doing delayed SN, if we are using the IRA then this function will never be called. // If the SF timestep is less than the resolution on which we do supernova feedback then we will keep track of the total stars formed over these small timesteps and then update them all in one bin. // If the SF timestep is larger than the resolution on which we do supernova feedback we will spread the stars formed evenly over a number of elements (>= 1). // // INPUT: The index of the galaxy (p). // : The number of stars formed in the current SF episode (stars). ## UNITS: 1.0e10 Msun/h (Code Units). // : The timestep over which the SF is occuring (dt). ## UNITS: Code Units, multiply by 'UnitTime_in_Megayears / Hubble_h' for Myr. // : The tree currently being used (tree); currently used for debugging purposes. // // OUTPUT: None. void update_SN_stars_array(int p, double stars, double dt, int tree, int ngal) { double time_spanned = dt * UnitTime_in_Megayears / Hubble_h; // The time spanned by this star formation event. Gal[p].Total_SN_SF_Time += time_spanned; // How long it has been since we've updated the array? Gal[p].Total_SN_Stars += stars; // How many stars we will need to bin once we do update the array? if(Gal[p].Total_SN_SF_Time > TimeResolutionSN * SN_Array_Len) // This handles cases in which the time spanned is greater than 50Myr. In this case we wipe the array clean and push the star formation into a 50Myr bin. Gal[p].Total_SN_SF_Time = TimeResolutionSN * SN_Array_Len; if(Gal[p].Total_SN_SF_Time < TimeResolutionSN) // If it hasn't been long enough yet, don't update the array. return; int num_shuffled = round(Gal[p].Total_SN_SF_Time/TimeResolutionSN); // How many cells will this SF event span. double stars_spread = Gal[p].Total_SN_Stars/num_shuffled; // We spread the stars evenly over time. int i; XASSERT(Gal[p].IsMalloced == 1, "We are attempting to update the stars array but this galaxy has already had its arrays freed.\nGalaxy %d \t Halo %d \t Tree %d \t Time spanned %.4eMyr\n", p, Gal[p].HaloNr, tree, time_spanned); for(i = SN_Array_Len - 1; i > num_shuffled - 1; --i) { Gal[p].SN_Stars[i] = Gal[p].SN_Stars[i-num_shuffled]; // Shuffle the current elements of the array far enough along so we can store the new stars. } XPRINT(p < ngal, "We have the case where the galaxy p is greater than the number of galaxies. p = %d \t ngal = %d\n", p, ngal); for(i = SN_Array_Len - 1; i > (SN_Array_Len - num_shuffled - 1); --i) { Gal[p].StellarAge_Numerator += Gal[p].SN_Stars[i] * (Age[Gal[p].SnapNum - 4]); Gal[p].StellarAge_Denominator += Gal[p].SN_Stars[i]; } for(i = 0; i < num_shuffled; ++i) { Gal[p].StellarAge_Numerator += Gal[p].SN_Stars[i] * (Age[Gal[p].SnapNum - 4]); Gal[p].SN_Stars[i] = stars_spread; // Update the vacated elements with the new stars. Gal[p].GrandSum += stars_spread; } Gal[p].Total_SN_SF_Time = 0.0; // We've updated so reset our variables. Gal[p].Total_SN_Stars = 0.0; } void update_stellar_tracking(int p, double stars, double dt, int tree, int ngal) { double time_spanned = dt * UnitTime_in_Megayears / Hubble_h; // The time spanned by this star formation event. Gal[p].Total_Stellar_SF_Time += time_spanned; // How long it has been since we've updated the array? Gal[p].Total_Stellar_Stars += stars; // How many stars we will need to bin once we do update the array? if(Gal[p].Total_Stellar_SF_Time > TimeResolutionStellar * StellarTracking_Len) Gal[p].Total_Stellar_SF_Time = TimeResolutionStellar * StellarTracking_Len; if(Gal[p].Total_Stellar_SF_Time < TimeResolutionStellar) // If it hasn't been long enough yet, don't update the array. return; int num_shuffled = round(Gal[p].Total_Stellar_SF_Time/TimeResolutionStellar); // How many cells will this SF event span. double stars_spread = Gal[p].Total_Stellar_Stars/num_shuffled; // We spread the stars evenly over time. int i; XASSERT(Gal[p].IsMalloced == 1, "We are attempting to update the Stellar Tracking array but this galaxy has already had its arrays freed.\nGalaxy %d \t Halo %d \t Tree %d \t Time spanned %.4eMyr\n", p, Gal[p].HaloNr, tree, time_spanned); for(i = StellarTracking_Len - 1; i > num_shuffled - 1; --i) { Gal[p].Stellar_Stars[i] = Gal[p].Stellar_Stars[i-num_shuffled]; // Shuffle the current elements of the array far enough along so we can store the new stars. } XPRINT(p < ngal, "We have the case where the galaxy p is greater than the number of galaxies. p = %d \t ngal = %d\n", p, ngal); for(i = 0; i < num_shuffled; ++i) { Gal[p].Stellar_Stars[i] = stars_spread; // Update the vacated elements with the new stars. } Gal[p].Total_Stellar_SF_Time = 0.0; // We've updated so reset our variables. Gal[p].Total_Stellar_Stars = 0.0; }
{ "alphanum_fraction": 0.6958190149, "avg_line_length": 42.3786407767, "ext": "c", "hexsha": "b7db9f59026869032e934f489097c08d01410794", "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": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_path": "src/sage/model_starformation_and_feedback.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_path": "src/sage/model_starformation_and_feedback.c", "max_line_length": 438, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_path": "src/sage/model_starformation_and_feedback.c", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "num_tokens": 10481, "size": 34920 }
#pragma once #include "JsonHandler.h" #include "Library.h" #include <gsl/span> #include <cstddef> #include <optional> #include <string> #include <vector> namespace rapidjson { struct MemoryStream; } namespace CesiumJsonReader { /** * @brief The result of {@link Reader::readJson}. */ template <typename T> struct ReadJsonResult { /** * @brief The value read from the JSON, or `std::nullopt` on error. */ std::optional<T> value; /** * @brief Errors that occurred while reading. */ std::vector<std::string> errors; /** * @brief Warnings that occurred while reading. */ std::vector<std::string> warnings; }; /** * @brief Reads JSON. */ class CESIUMJSONREADER_API JsonReader { public: /** * @brief Reads JSON from a byte buffer. * * @param data The buffer from which to read JSON. * @param handler The handler to receive the top-level JSON object. * @return The result of reading the JSON. */ template <typename T> static ReadJsonResult<typename T::ValueType> readJson(const gsl::span<const std::byte>& data, T& handler) { ReadJsonResult<typename T::ValueType> result; result.value.emplace(); FinalJsonHandler finalHandler(result.warnings); handler.reset(&finalHandler, &result.value.value()); JsonReader::internalRead( data, handler, finalHandler, result.errors, result.warnings); if (!result.errors.empty()) { result.value.reset(); } return result; } private: class FinalJsonHandler : public JsonHandler { public: FinalJsonHandler(std::vector<std::string>& warnings); virtual void reportWarning( const std::string& warning, std::vector<std::string>&& context) override; void setInputStream(rapidjson::MemoryStream* pInputStream) noexcept; private: std::vector<std::string>& _warnings; rapidjson::MemoryStream* _pInputStream; }; static void internalRead( const gsl::span<const std::byte>& data, IJsonHandler& handler, FinalJsonHandler& finalHandler, std::vector<std::string>& errors, std::vector<std::string>& warnings); }; } // namespace CesiumJsonReader
{ "alphanum_fraction": 0.6675811614, "avg_line_length": 22.3163265306, "ext": "h", "hexsha": "3680acaa0166d19ddf6a8c651687bde1f3dd1cca", "lang": "C", "max_forks_count": 66, "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z", "max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yieryi/cesium-native", "max_forks_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_issues_count": 256, "max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "yieryi/cesium-native", "max_issues_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_line_length": 72, "max_stars_count": 154, "max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yieryi/cesium-native", "max_stars_repo_path": "CesiumJsonReader/include/CesiumJsonReader/JsonReader.h", "max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z", "num_tokens": 517, "size": 2187 }
/* multifit_nlinear/trust.c * * Copyright (C) 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include "common.c" #include "nielsen.c" /* * This module contains a high level driver for a general trust * region nonlinear least squares solver. This container handles * the computation of all of the quantities relevant to all trust * region methods, including: * * residual vector: f_k = f(x_k) * Jacobian matrix: J_k = J(x_k) * gradient vector: g_k = J_k^T f_k * scaling matrix: D_k */ typedef struct { size_t n; /* number of observations */ size_t p; /* number of parameters */ double delta; /* trust region radius */ double mu; /* LM parameter */ long nu; /* for updating LM parameter */ gsl_vector *diag; /* D = diag(J^T J) */ gsl_vector *x_trial; /* trial parameter vector */ gsl_vector *f_trial; /* trial function vector */ gsl_vector *workp; /* workspace, length p */ gsl_vector *workn; /* workspace, length n */ void *trs_state; /* workspace for trust region subproblem */ void *solver_state; /* workspace for linear least squares solver */ double avratio; /* current |a| / |v| */ /* tunable parameters */ gsl_multifit_nlinear_parameters params; } trust_state_t; static void * trust_alloc (const gsl_multifit_nlinear_parameters * params, const size_t n, const size_t p); static void trust_free(void *vstate); static int trust_init(void *vstate, const gsl_vector * swts, gsl_multifit_nlinear_fdf *fdf, const gsl_vector *x, gsl_vector *f, gsl_matrix *J, gsl_vector *g); static int trust_iterate(void *vstate, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, gsl_vector *x, gsl_vector *f, gsl_matrix *J, gsl_vector *g, gsl_vector *dx); static int trust_rcond(double *rcond, void *vstate); static double trust_avratio(void *vstate); static void trust_trial_step(const gsl_vector * x, const gsl_vector * dx, gsl_vector * x_trial); static double trust_calc_rho(const gsl_vector * f, const gsl_vector * f_trial, const gsl_vector * g, const gsl_matrix * J, const gsl_vector * dx, trust_state_t * state); static int trust_eval_step(const gsl_vector * f, const gsl_vector * f_trial, const gsl_vector * g, const gsl_matrix * J, const gsl_vector * dx, double * rho, trust_state_t * state); static double trust_scaled_norm(const gsl_vector *D, const gsl_vector *a); static void * trust_alloc (const gsl_multifit_nlinear_parameters * params, const size_t n, const size_t p) { trust_state_t *state; state = calloc(1, sizeof(trust_state_t)); if (state == NULL) { GSL_ERROR_NULL ("failed to allocate lm state", GSL_ENOMEM); } state->diag = gsl_vector_alloc(p); if (state->diag == NULL) { GSL_ERROR_NULL ("failed to allocate space for diag", GSL_ENOMEM); } state->workp = gsl_vector_alloc(p); if (state->workp == NULL) { GSL_ERROR_NULL ("failed to allocate space for workp", GSL_ENOMEM); } state->workn = gsl_vector_alloc(n); if (state->workn == NULL) { GSL_ERROR_NULL ("failed to allocate space for workn", GSL_ENOMEM); } state->x_trial = gsl_vector_alloc(p); if (state->x_trial == NULL) { GSL_ERROR_NULL ("failed to allocate space for x_trial", GSL_ENOMEM); } state->f_trial = gsl_vector_alloc(n); if (state->f_trial == NULL) { GSL_ERROR_NULL ("failed to allocate space for f_trial", GSL_ENOMEM); } state->trs_state = (params->trs->alloc)(params, n, p); if (state->trs_state == NULL) { GSL_ERROR_NULL ("failed to allocate space for trs state", GSL_ENOMEM); } state->solver_state = (params->solver->alloc)(n, p); if (state->solver_state == NULL) { GSL_ERROR_NULL ("failed to allocate space for solver state", GSL_ENOMEM); } state->n = n; state->p = p; state->delta = 0.0; state->params = *params; return state; } static void trust_free(void *vstate) { trust_state_t *state = (trust_state_t *) vstate; const gsl_multifit_nlinear_parameters *params = &(state->params); if (state->diag) gsl_vector_free(state->diag); if (state->workp) gsl_vector_free(state->workp); if (state->workn) gsl_vector_free(state->workn); if (state->x_trial) gsl_vector_free(state->x_trial); if (state->f_trial) gsl_vector_free(state->f_trial); if (state->trs_state) (params->trs->free)(state->trs_state); if (state->solver_state) (params->solver->free)(state->solver_state); free(state); } /* trust_init() Initialize trust region solver Inputs: vstate - workspace swts - sqrt(W) vector fdf - user callback functions x - initial parameter values f - (output) f(x) vector J - (output) J(x) matrix g - (output) J(x)' f(x) vector Return: success/error */ static int trust_init(void *vstate, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, const gsl_vector *x, gsl_vector *f, gsl_matrix *J, gsl_vector *g) { int status; trust_state_t *state = (trust_state_t *) vstate; const gsl_multifit_nlinear_parameters *params = &(state->params); double Dx; /* evaluate function and Jacobian at x and apply weight transform */ status = gsl_multifit_nlinear_eval_f(fdf, x, swts, f); if (status) return status; status = gsl_multifit_nlinear_eval_df(x, f, swts, params->h_df, params->fdtype, fdf, J, state->workn); if (status) return status; /* compute g = J^T f */ gsl_blas_dgemv(CblasTrans, 1.0, J, f, 0.0, g); /* initialize diagonal scaling matrix D */ (params->scale->init)(J, state->diag); /* compute initial trust region radius */ Dx = trust_scaled_norm(state->diag, x); state->delta = 0.3 * GSL_MAX(1.0, Dx); /* initialize LM parameter */ status = nielsen_init(J, state->diag, &(state->mu), &(state->nu)); if (status) return status; /* initialize trust region method solver */ { gsl_multifit_nlinear_trust_state trust_state; trust_state.x = x; trust_state.f = f; trust_state.g = g; trust_state.J = J; trust_state.diag = state->diag; trust_state.sqrt_wts = swts; trust_state.mu = &(state->mu); trust_state.params = params; trust_state.solver_state = state->solver_state; trust_state.fdf = fdf; trust_state.avratio = &(state->avratio); status = (params->trs->init)(&trust_state, state->trs_state); if (status) return status; } /* set default parameters */ state->avratio = 0.0; return GSL_SUCCESS; } /* trust_iterate() This function performs 1 iteration of the trust region algorithm. It calls a user-specified method for computing the next step (LM or dogleg), then tests if the computed step is acceptable. Args: vstate - trust workspace swts - data weights (NULL if unweighted) fdf - function and Jacobian pointers x - on input, current parameter vector on output, new parameter vector x + dx f - on input, f(x) on output, f(x + dx) J - on input, J(x) on output, J(x + dx) g - on input, g(x) = J(x)' f(x) on output, g(x + dx) = J(x + dx)' f(x + dx) dx - (output only) parameter step vector Return: 1) GSL_SUCCESS if we found a step which reduces the cost function 2) GSL_ENOPROG if 15 successive attempts were to made to find a good step without success 3) If a scaling matrix D is used, inputs and outputs are set to the unscaled quantities (ie: J and g) */ static int trust_iterate(void *vstate, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, gsl_vector *x, gsl_vector *f, gsl_matrix *J, gsl_vector *g, gsl_vector *dx) { int status; trust_state_t *state = (trust_state_t *) vstate; const gsl_multifit_nlinear_parameters *params = &(state->params); const gsl_multifit_nlinear_trs *trs = params->trs; gsl_multifit_nlinear_trust_state trust_state; gsl_vector *x_trial = state->x_trial; /* trial x + dx */ gsl_vector *f_trial = state->f_trial; /* trial f(x + dx) */ gsl_vector *diag = state->diag; /* diag(D) */ double rho; /* ratio actual_reduction/predicted_reduction */ int foundstep = 0; /* found step dx */ int bad_steps = 0; /* consecutive rejected steps */ /* store all state parameters needed by low level methods */ trust_state.x = x; trust_state.f = f; trust_state.g = g; trust_state.J = J; trust_state.diag = state->diag; trust_state.sqrt_wts = swts; trust_state.mu = &(state->mu); trust_state.params = params; trust_state.solver_state = state->solver_state; trust_state.fdf = fdf; trust_state.avratio = &(state->avratio); /* initialize trust region subproblem with this Jacobian */ status = (trs->preloop)(&trust_state, state->trs_state); if (status) return status; /* loop until we find an acceptable step dx */ while (!foundstep) { /* calculate new step */ status = (trs->step)(&trust_state, state->delta, dx, state->trs_state); /* occasionally the iterative methods (ie: CG Steihaug) can fail to find a step, * so in this case skip rho calculation and count it as a rejected step */ if (status == GSL_SUCCESS) { /* compute x_trial = x + dx */ trust_trial_step(x, dx, x_trial); /* compute f_trial = f(x + dx) */ status = gsl_multifit_nlinear_eval_f(fdf, x_trial, swts, f_trial); if (status) return status; /* check if step should be accepted or rejected */ status = trust_eval_step(f, f_trial, g, J, dx, &rho, state); if (status == GSL_SUCCESS) foundstep = 1; } else { /* an iterative TRS method failed to find a step vector */ rho = -1.0; } /* * update trust region radius: if rho is large, * then the quadratic model is a good approximation * to the objective function, enlarge trust region. * If rho is small (or negative), the model function * is a poor approximation so decrease trust region. This * can happen even if the step is accepted. */ if (rho > 0.75) state->delta *= params->factor_up; else if (rho < 0.25) state->delta /= params->factor_down; if (foundstep) { /* step was accepted */ /* compute J <- J(x + dx) */ status = gsl_multifit_nlinear_eval_df(x_trial, f_trial, swts, params->h_df, params->fdtype, fdf, J, state->workn); if (status) return status; /* update x <- x + dx */ gsl_vector_memcpy(x, x_trial); /* update f <- f(x + dx) */ gsl_vector_memcpy(f, f_trial); /* compute new g = J^T f */ gsl_blas_dgemv(CblasTrans, 1.0, J, f, 0.0, g); /* update scaling matrix D */ (params->scale->update)(J, diag); /* step accepted, decrease LM parameter */ status = nielsen_accept(rho, &(state->mu), &(state->nu)); if (status) return status; bad_steps = 0; } else { /* step rejected, increase LM parameter */ status = nielsen_reject(&(state->mu), &(state->nu)); if (status) return status; if (++bad_steps > 15) { /* if more than 15 consecutive rejected steps, report no progress */ return GSL_ENOPROG; } } } return GSL_SUCCESS; } /* trust_iterate() */ static int trust_rcond(double *rcond, void *vstate) { int status; trust_state_t *state = (trust_state_t *) vstate; const gsl_multifit_nlinear_parameters *params = &(state->params); status = (params->solver->rcond)(rcond, state->solver_state); return status; } static double trust_avratio(void *vstate) { trust_state_t *state = (trust_state_t *) vstate; return state->avratio; } /* compute x_trial = x + dx */ static void trust_trial_step(const gsl_vector * x, const gsl_vector * dx, gsl_vector * x_trial) { size_t i, N = x->size; for (i = 0; i < N; i++) { double dxi = gsl_vector_get (dx, i); double xi = gsl_vector_get (x, i); gsl_vector_set (x_trial, i, xi + dxi); } } /* trust_calc_rho() Calculate ratio of actual reduction to predicted reduction. rho = actual_reduction / predicted_reduction actual_reduction = 1 - ( ||f+|| / ||f|| )^2 predicted_reduction = -2 g^T dx / ||f||^2 - ( ||J*dx|| / ||f|| )^2 = -2 fhat . beta - ||beta||^2 where: beta = J*dx / ||f|| Inputs: f - f(x) f_trial - f(x + dx) g - gradient J^T f J - Jacobian dx - proposed step, size p state - workspace Return: rho = actual_reduction / predicted_reduction If actual_reduction is < 0, return rho = -1 */ static double trust_calc_rho(const gsl_vector * f, const gsl_vector * f_trial, const gsl_vector * g, const gsl_matrix * J, const gsl_vector * dx, trust_state_t * state) { int status; const gsl_multifit_nlinear_parameters *params = &(state->params); const gsl_multifit_nlinear_trs *trs = params->trs; const double normf = gsl_blas_dnrm2(f); const double normf_trial = gsl_blas_dnrm2(f_trial); gsl_multifit_nlinear_trust_state trust_state; double rho; double actual_reduction; double pred_reduction; double u; /* if ||f(x+dx)|| > ||f(x)|| reject step immediately */ if (normf_trial >= normf) return -1.0; trust_state.x = NULL; trust_state.f = f; trust_state.g = g; trust_state.J = J; trust_state.diag = state->diag; trust_state.sqrt_wts = NULL; trust_state.mu = &(state->mu); trust_state.params = params; trust_state.solver_state = state->solver_state; trust_state.fdf = NULL; trust_state.avratio = &(state->avratio); /* compute numerator of rho (actual reduction) */ u = normf_trial / normf; actual_reduction = 1.0 - u*u; /* * compute denominator of rho (predicted reduction); this is calculated * inside each trust region subproblem, since it depends on the local * model used, which can vary according to each TRS */ status = (trs->preduction)(&trust_state, dx, &pred_reduction, state->trs_state); if (status) return -1.0; if (pred_reduction > 0.0) rho = actual_reduction / pred_reduction; else rho = -1.0; return rho; } /* trust_eval_step() Evaluate proposed step to determine if it should be accepted or rejected */ static int trust_eval_step(const gsl_vector * f, const gsl_vector * f_trial, const gsl_vector * g, const gsl_matrix * J, const gsl_vector * dx, double * rho, trust_state_t * state) { int status = GSL_SUCCESS; const gsl_multifit_nlinear_parameters *params = &(state->params); if (params->trs == gsl_multifit_nlinear_trs_lmaccel) { /* reject step if acceleration is too large compared to velocity */ if (state->avratio > params->avmax) status = GSL_FAILURE; } /* compute rho */ *rho = trust_calc_rho(f, f_trial, g, J, dx, state); if (*rho <= 0.0) status = GSL_FAILURE; return status; } /* compute || diag(D) a || */ static double trust_scaled_norm(const gsl_vector *D, const gsl_vector *a) { const size_t n = a->size; double e2 = 0.0; size_t i; for (i = 0; i < n; ++i) { double Di = gsl_vector_get(D, i); double ai = gsl_vector_get(a, i); double u = Di * ai; e2 += u * u; } return sqrt (e2); } static const gsl_multifit_nlinear_type trust_type = { "trust-region", trust_alloc, trust_init, trust_iterate, trust_rcond, trust_avratio, trust_free }; const gsl_multifit_nlinear_type *gsl_multifit_nlinear_trust = &trust_type;
{ "alphanum_fraction": 0.622255346, "avg_line_length": 29.6146010187, "ext": "c", "hexsha": "2d42ff70121bd02192fcfb6cf44d2c2ac74132bf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/trust.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/trust.c", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/trust.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": 4544, "size": 17443 }
/* * Monte Carlo.cpp * * Copyright 2017 Benjamin Church <ben@U430> * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_integration.h> #include <time.h> #define ADIABATIC_CUTOFF 1 #define INTEGRATION_POINTS 81 #define INTEGRAL_FUDGE_FACTOR 1.0125 #define INTEGRATION_SECTIONS 8 #define CUTOFF_SCALE 1E3 #define min(x,y) (x < y? x : y) #define sign(x) (x >= 0? 1.0 : -1.0) #define dot_macro(A, B) ((A).x * (B).x + (A).y * (B).y + (A).z * (B).z) #define mag_sq(A) dot_macro(A, A) #define mag(A) sqrt(dot_macro(A, A)) #define assign_vec(A, x_val, y_val, z_val) {(A).x = x_val; (A).y = y_val; (A).z = z_val;} #define assign_vec_diff(d, A, B) {(d).x = (A).x - (B).x; (d).y = (A).y - (B).y; (d).z = (A).z - (B).z;} #define make_unit(A) {double len = mag(A); assign_vec(A, (A.x)/len, (A.y)/len, (A.z)/len);} #define rho_profile(x, a, b) (pow(x, 2 - a)*pow((1 + x), a - b)) gsl_rng *RNG; gsl_integration_workspace * w; const int default_log_num_trials = 6; int num_trials, num_points = 100; const double pi = 3.14159265; double crit_density = 1.3211775E-7, f = 0.1, g = 1E-4, p = 1.9, G = 0.0045, k = 2, M_prim = 1E12, T_age = 1E4; double m_max, m_min, expected_num, R_core_prim, R_max_prim, c_prim; double MaxRadius(double M) { return pow(3.0*M/(4.0 * pi * 200.0 * crit_density), 1.0/3.0); } typedef struct { double x, y, z; } vector; typedef struct { double m, s, max_val; }data_cell; void update_cell(data_cell *ptr, double new_data, int k) { double old_m = ptr->m; ptr->m += (new_data - old_m)/(double) k; ptr->s += (new_data - old_m)*(new_data - ptr->m); if(ptr->max_val < new_data) ptr->max_val = new_data; } void reset_cell(data_cell *ptr) { ptr->m = 0; ptr->s = 0; ptr->max_val = 0; } typedef struct { double R, theta, phi; double cos_theta; double M, r_core, r_max, alpha, beta, c, normalization; double integs[INTEGRATION_SECTIONS]; vector v, position; } halo; double Power(double x, int y) { if(y > 0) { double result = 1; while(y > 0) { if(y % 2 == 0) { x = x*x; y = y/2; } else { result = x*result; y--; } } return result; } else if(y < 0) return 1/Power(x, -y); else return 1; } void print_vector(vector *A) { printf("(%.3f, %.3f, %.3f)\n", A->x, A->y, A->z); } double perp_mag_sq(vector *A, vector *u) { double dot_prod = dot_macro(*A, *u); return mag_sq(*A) - dot_prod*dot_prod/mag_sq(*u); } double MFreeNFW(double r) { if(r < R_max_prim) return M_prim*(log(1 + r/R_core_prim)-r/(r + R_core_prim))/(log(1 + c_prim) - c_prim/( 1 + c_prim)); else return M_prim; } double DFreeNFW(double r) { if(r < R_max_prim) return 200.0/3.0 * crit_density / (log(1 + c_prim) - c_prim/(1 + c_prim))*pow(c_prim, 3) * 1.0/(r/R_core_prim*pow(1+r/R_core_prim, 2.0)); else return 0.0; } double PhiFreeNFW(double r) { if(r < R_max_prim) return -M_prim*G*((R_max_prim/r * log(1 + r/R_core_prim) - log(1 + c_prim))/(log(1 + c_prim) - c_prim/(1 + c_prim)) + 1)/R_max_prim; else return -M_prim*G/r; } double TidalRadius(double M, double R) { return R*pow(M/(2*MFreeNFW(R)), 1.0/3.0); } double NFW_func(double x, double r) { return (log(1.0 + x) - x/(1.0 + x))/(log(1.0 + c_prim) - c_prim/(1.0 + c_prim)) - r; } double df (double x) { return x/((1.0 + x)*(1.0 + x)) * 1.0/(log(1.0 + c_prim) - c_prim/(1.0 + c_prim)); } double newton(double r) { int itr, maxmitr = 100; double h, x0 = 0.1, x1, allerr = pow(10, -6); for (itr = 0; itr < maxmitr; itr++) { h = NFW_func(x0, r)/df(x0); x1 = x0 - h; if (fabs(h) < allerr) { return x1; } x0 = x1; } return x1; } double rho_profile_func(double x, void *params) { double *param_ptr = (double *)params; return pow(x, 2 - param_ptr[0])*pow((1 + x), param_ptr[0] - param_ptr[1]); } double integ_profile(double alpha, double beta, double r) { /*if(alpha > 3) return 1; double dist = 0, step = r/INTEGRATION_POINTS, sum = 0; int i; for(i = 0; i < INTEGRATION_POINTS; i++) { if(i == 0 && alpha > 2 && alpha < 3) sum += 8.0/(3.0*step) * 1/(3.0 - alpha) * pow(step, 3 - alpha); else if(i == 0 || i == INTEGRATION_POINTS - 1) sum += rho_profile(dist, alpha, beta); else if(i%3 == 0) sum += 2*rho_profile(dist, alpha, beta); else sum += 3*rho_profile(dist, alpha, beta); dist += step; } return 3.0*step/8.0*sum * INTEGRAL_FUDGE_FACTOR;*/ //printf("int %f\n", 3*step/8*sum); double result, error; double arr[2]; arr[0] = alpha; arr[1] = beta; gsl_function F; F.function = &rho_profile_func; F.params = arr; gsl_integration_qags (&F, 0, r, 0, 1e-7, 1000, w, &result, &error); if(error/result > 1e-7)printf("LARGE INTEG ERROR WARNING %f for result %f", error, result); //printf("alpha: %.3f beta: %.3f r: %.3f err %f\n", alpha, beta, r, (result - quick_result)/result); return result; } double worst_thing_ever(int lr, double a, double b, double r) { switch(lr) { case -2: return pow(2,-2 + b)*pow(3,-4 + a - b)*(-20.25 - ((8*a*a*a + 12*a*a*(-2 + b) + b*(38 + (-15 + b)*b) + 2*a*(8 + 3*(-7 + b)*b))*(-0.0078125 + Power(1 - 2*r,4)/8.))/2. + 81*r - 27*(-6 + 2*a + b)*(0.1875 + (-1 + r)*r) + (3*(4*a*a + 4*a*(-4 + b) + (-9 + b)*(-2 + b))*(-1 + 4*r)*(7 + 4*r*(-5 + 4*r)))/32.); break; case -1: return (pow(2,-4 + a - b)*(-24 + 48*r - ((-2 + a + b)*(a*a + (-7 + b)*b + a*(-1 + 2*b))*(-3 + 2*r)*(-1 + 2*r)*(5 + 4*(-2 + r)*r))/64. - 3*(-4 + a + b)*(3 - 8*r + 4*r*r) + 6*(8 + a*a - 7*b + b*b + a*(-5 + 2*b))*(-0.2916666666666667 + (r*(3 + (-3 + r)*r))/3.)))/3.0; break; case 0: return pow(2,-4 - a)*pow(3,-4 + a - b)*(-(a*a*a*(-1 + Power(-2 + r,4))) - 16*(27 + (3*b)/4. + (b*b*b*(-1 + Power(-2 + r,4)))/2. + 40*b*r - 48*b*r*r - 27*r*r*r + 4*b*r*r*r + (13*b*r*r*r*r)/4. - 3*b*b*(1 + Power(-2 + r,3)*r)) - 3*a*a*(-1 + r)*(-41 + 2*b*(-3 + r)*(5 + (-4 + r)*r) - r*(-23 + r + r*r)) - 2*a*(-1 + r)*(-75 + 6*b*b*(-3 + r)*(5 + (-4 + r)*r) + r*(-187 + r*(77 + r)) - 3*b*(37 + r*(5 + r*(-19 + 5*r))))); break; case 1: return -(pow(2,-5 - 2*a)*pow(5,-3 + a - b)*(-2 + r)*(a*a*a*(-120 + 68*r - 14*r*r + r*r*r) + a*a*(-1880 + 596*r - 38*r*r - 3*r*r*r + 12*b*(-120 + 68*r - 14*r*r + r*r*r)) + 2*a*(-2200 - 1932*r + 426*r*r + r*r*r + b*(-3920 + 344*r + 268*r*r - 42*r*r*r) + 24*b*b*(-120 + 68*r - 14*r*r + r*r*r)) + 8*(-500*(4 + 2*r + r*r) + 8*b*b*b*(-120 + 68*r - 14*r*r + r*r*r) - 4*b*b*(40 + 212*r - 86*r*r + 9*r*r*r) + b*(-200 - 1892*r + 206*r*r + 31*r*r*r))))/3.0; break; case 2: return pow(2,-4 - 3*a)*pow(3,-7 + 2*a - 2*b)*(-8957952 - ((-2 + a)*(-1 + a)*a + 8*(182 + 3*(-11 + a)*a)*b + 192*(-10 + a)*b*b + 512*b*b*b)* (-64 + Power(-8 + r,4)/4.) + 2239488*r - 15552*(-18 + a + 8*b)*(48 - 16*r + r*r) + 72*(162 + a*a - 224*b + 64*b*b + a*(-19 + 16*b))*(-448 + r*(192 + (-24 + r)*r))); break; case 3: return (pow(2,-5 - 4*a)*pow(17,-3 + a - b)*(-965935104 - (a*a*a + a*a*(-3 + 48*b) + 32*b*(307 - 432*b + 128*b*b) + a*(2 - 912*b + 768*b*b))* (-1024 + Power(-16 + r,4)/4.) + 120741888*r - 221952*(-34 + a + 16*b)*(192 - 32*r + r*r) + 272*(578 + a*a - 832*b + 256*b*b + a*(-35 + 32*b))*(-3584 + r*(768 + (-48 + r)*r))))/3.0; break; case 4: return pow(2,-6 - 5*a)*pow(33,-4 + a - b)*11*(-113048027136 - (a*a*a + a*a*(-3 + 96*b) + 64*b*(1123 - 1632*b + 512*b*b) + a*(2 - 3360*b + 3072*b*b))*(-16384 + Power(-32 + r,4)/4.) + 7065501696*r - 3345408*(-66 + a + 32*b)*(768 - 64*r + r*r) + 1056*(2178 + a*a - 3200*b + 1024*b*b + a*(-67 + 64*b))*(-28672 + r*(3072 + (-96 + r)*r))); break; case 5: return (pow(2,-7 - 6*a)*pow(65,-3 + a - b)* (-13822328832000 + 431947776000*r - (((-2 + a)*(-1 + a)*a + 64*(8582 + 3*(-67 + a)*a)*b + 12288*(-66 + a)*b*b + 262144*b*b*b)*(-96 + r)*(-32 + r)* (5120 + (-128 + r)*r))/4. - 51916800*(-130 + a + 64*b)*(3072 - 128*r + r*r) + 4160*(8450 + a*a - 12544*b + 4096*b*b + a*(-131 + 128*b))* (-229376 + r*(12288 + (-192 + r)*r))))/3.0; break; }; return 1; } double sec_integ_profile(halo *ptr, double r) { double a = ptr->alpha, b = ptr->beta; int lr = floor(log2(r)); //MAKE BETTER! if(lr < -2) return pow(r, 3-a)*(1/(3-a) + r*(a-b)/(4-a) + (a*a - a + b - 2*a*b + b*b)/(5-a)*r*r/2.0); if(lr >= INTEGRATION_SECTIONS - 2) return integ_profile(a, b, r); //MAKE BETTER return ptr->integs[lr + 2] + worst_thing_ever(lr, a, b, r); } double get_M() { double r = gsl_rng_uniform(RNG); return M_prim*pow(pow(m_max/M_prim, 1.0-p)*r + pow(m_min/M_prim, 1.0-p)*(1.0-r), 1.0/(1.0-p)); } double c_bar(double M) { return pow(10.0, 1.0 - 0.1 * (log10(M) - 12)); } void set_shape(halo *ptr, double M, double R) { ptr->r_max = pow(3*M/(4 * pi * 200.0 * crit_density), 1.0/3.0); ptr->alpha = gsl_ran_gaussian_ziggurat(RNG, 0.2) + 1.25; //suggested by J. Ostriker ptr->beta = 3; //probalby need to change ptr->c = gsl_ran_lognormal(RNG, log(c_bar(M)), 0.25); //Ludlow el. al. (2013) and Frank van den Bosch ptr->r_core = ptr->r_max/ptr->c; int i; double r = 1.0/4.0, a = ptr->alpha, b = ptr->beta; ptr->integs[0] = pow(r, 3-a)*(1/(3-a) + r*(a-b)/(4-a) + (a*a - a + b - 2*a*b + b*b)/(5-a)*r*r/2.0); r *= 2; for(i = 0; i < INTEGRATION_SECTIONS - 1; i++) { ptr->integs[i + 1] = ptr->integs[i] + worst_thing_ever(i - 2, ptr->alpha, ptr->beta, r); r *= 2; } ptr->normalization = sec_integ_profile(ptr, ptr->c); } void set_velocity(halo *ptr, double R) { double v_sigma = sqrt(1.0/3.0)*sqrt(-PhiFreeNFW(R)); ptr->v.x = gsl_ran_gaussian_ziggurat(RNG, v_sigma); ptr->v.y = gsl_ran_gaussian_ziggurat(RNG, v_sigma); ptr->v.z = gsl_ran_gaussian_ziggurat(RNG, v_sigma); } double enclosed_mass(halo *ptr, double r) { double x = r/(ptr->r_core); if(x > ptr->c) return ptr->M; else { /* double sec = sec_integ_profile(ptr, x), integ = integ_profile(ptr->alpha, ptr->beta, x); double lerr = log(fabs(sec - integ)); if(lerr > -4) { printf("alpha: %f beta: %f r: %f \n", ptr->alpha, ptr->beta, x); printf("lerr: %f sec: %f real: %f r: \n", lerr, sec, integ); }*/ return ptr->M * sec_integ_profile(ptr, x)/ptr->normalization; } } void truncate(halo *ptr, double R) { double l2 = R*R*perp_mag_sq(&(ptr->v), &(ptr->position)); double r0 = l2/(M_prim * G); double E = 0.5*mag_sq(ptr->v) + PhiFreeNFW(R); double ecc = sqrt(1.0 + 2.0*E*l2/(M_prim * G * M_prim * G)); double R_min = min(fabs(r0/(1.0 + ecc)), fabs(r0/(1.0 - ecc))); /*printf("velocity: "); print_vector(ptr->v); printf("position "); print_vector(halo_pos(ptr)); printf("R = %.3f theta = %.3f phi = %.3f\n l2 = %.3f e = %.3f \n", ptr->R, ptr->theta, ptr->phi, l2, ecc);*/ if(E > 0 || R_min < 0.1) { ptr->M = 0; } else { double Rt = TidalRadius(ptr->M, R_min); double R_max = min(ptr->r_max, Rt); double new_M = enclosed_mass(ptr, R_max); ptr->r_max = R_max; ptr->c = R_max/ptr->r_core; ptr->normalization *= (new_M/ptr->M); ptr->M = new_M; } } halo *make_halo(halo *ptr) { ptr->R = newton(gsl_rng_uniform(RNG)) * R_core_prim; ptr->cos_theta = 2*gsl_rng_uniform(RNG) - 1; ptr->theta = acos(ptr->cos_theta); ptr->phi = 2*pi*gsl_rng_uniform(RNG); assign_vec(ptr->position, ptr->R * sin(ptr->theta) * cos(ptr->phi), ptr->R * sin(ptr->theta) * sin(ptr->phi), ptr->R * ptr->cos_theta); ptr->M = get_M(); set_shape(ptr, ptr->M, ptr->R); set_velocity(ptr, ptr->R); truncate(ptr, ptr->R); return ptr; } void print_halo_basic(halo *ptr) { printf("\n R = %3f \n theta = %3f \n M = %3f \n", ptr->R, ptr->theta, ptr->M); } double Fluc(halo *halos, int num_halos, double D) { double sum = 0; int i; vector my_pos = {0, 0, D}, diff; double natural_fluc = 2 * pi* pow(D, 3.0/2.0)/sqrt(MFreeNFW(D) * G) * 1/(PhiFreeNFW(D)); for(i = 0; i < num_halos; i++) { double R = halos[i].R; double r = sqrt(R*R + D*D - 2.0*R*D*halos[i].cos_theta); assign_vec_diff(diff, halos[i].position, my_pos); make_unit(diff) double v_r = dot_macro(halos[i].v, diff); double produced_fluc = ((r > CUTOFF_SCALE) ? (enclosed_mass(halos + i, r) * G /(r*r) * v_r) : 0); //sum += produced_fluc; //KILLEM // kill heating which is adiabtic if(produced_fluc/natural_fluc > 1 || ! ADIABATIC_CUTOFF) sum += produced_fluc; /*printf("%.3f\n", D); printf("velocity: "); print_vector(halos[i]->v); printf("position "); print_vector(halo_pos(halos[i])); printf("R = %.3f theta = %.3f phi = %.3f\n v_r = %.3f \n", halos[i]->R, halos[i]->theta, halos[i]->phi, v_r);*/ } return sum*sum; } double Fluc_mass_range(halo *halos, int num_halos, double D, double min_mass, double max_mass) { double sum = 0; int i; vector my_pos = {0, 0, D}, diff; double natural_fluc = 2 * pi* pow(D, 3.0/2.0)/sqrt(MFreeNFW(D) * G) * 1/(PhiFreeNFW(D)); for(i = 0; i < num_halos; i++) { double R = halos[i].R; double r = sqrt(R*R + D*D - 2.0*R*D*halos[i].cos_theta); if(halos[i].M < max_mass && halos[i].M > min_mass) { assign_vec_diff(diff, halos[i].position, my_pos); make_unit(diff) double v_r = dot_macro(halos[i].v, diff); double produced_fluc = ((r > CUTOFF_SCALE) ? (enclosed_mass(halos + i, r) * G /(r*r) * v_r) : 0); //sum += produced_fluc; //KILLEM // kill heating which is adiabtic if(produced_fluc/natural_fluc > 1 || ! ADIABATIC_CUTOFF) sum += produced_fluc; /*printf("%.3f\n", D); printf("velocity: "); print_vector(halos[i]->v); printf("position "); print_vector(halo_pos(halos[i])); printf("R = %.3f theta = %.3f phi = %.3f\n v_r = %.3f \n", halos[i]->R, halos[i]->theta, halos[i]->phi, v_r);*/ } } return sum*sum; } double H_Density(halo *halos, int num_halos, double D, double dD) { double sum = 0; int i; for(i = 0; i < num_halos; i++) { if(halos[i].R < D && halos[i].R > D - dD) sum += halos[i].M; } return sum/(4.0*pi*D*D*dD); } int print_out = 0; void init(int argc, char **argv) { const gsl_rng_type *T; gsl_rng_env_setup(); T = gsl_rng_default; RNG = gsl_rng_alloc (T); w = gsl_integration_workspace_alloc (1000); if(argc >= 2) num_trials = (int)pow(10, atoi(argv[1])); else num_trials = (int)pow(10, default_log_num_trials); if(argc > 2) print_out = 1; R_max_prim = MaxRadius(M_prim); c_prim = c_bar(M_prim); R_core_prim = R_max_prim/c_prim; m_max = f*M_prim; m_min = g*M_prim; expected_num = (2.0-p)/(1.0-p)*f*(pow(m_max/M_prim, 1.0-p) - pow(m_min/M_prim, 1.0-p)) / (pow(m_max/M_prim, 2.0-p) - pow(m_min/M_prim, 2.0-p)); } double std_err_mean(double sum_of_squares) { return sqrt(sum_of_squares/((double) num_trials*(num_trials - 1))); } void sq_root_data(data_cell *data, int num) { int i; for(i = 0; i < num; i++) { data[i].m = sqrt(data[i].m); data[i].s *= pow(1.0/(2.0*data[i].m), 2); data[i].max_val = sqrt(data[i].max_val); } } void print_to_file(char *name, double *Ds, data_cell *data) { int j; char path[100], filename[50], snum[10], addendum[10]; strcpy(path, "data_files/"); strcpy(filename, name); strcpy(addendum, ".txt"); snprintf(snum, 10, "%d_%d", (int)gsl_rng_default_seed, (int)log10(num_trials)); strcat(path, filename); strcat(path, snum); strcat(path, addendum); FILE *f = NULL; if(!print_out) f = fopen(path, "w"); if(!print_out && f != NULL) { for(j = 0; j < num_points; j++) { double sig = std_err_mean(data[j].s)/data[j].m/log(10); printf("%f, %f, %f, %f\n", data[j].m, data[j].s, sig, log10(data[j].m)); if(data[j].m > 0) fprintf(f, "%f %f %f %f\n", log10(Ds[j]), log10(data[j].m), sig, log10(data[j].max_val)); } fclose(f); } else { for(j = 0; j < num_points; j++) { double sig = std_err_mean(data[j].s)/data[j].m/log(10); printf("%f, %f, %f, %f\n", data[j].m, data[j].s, sig, log10(data[j].m)); if(data[j].m > 0) printf("%f : %f +/- %f\n", log10(Ds[j]), log10(data[j].m), sig); } } } int main(int argc, char **argv) { init(argc, argv); unsigned int max_allowed_halos = (int)(10*expected_num); double Ds[num_points]; data_cell Flucs[num_points], Dens[num_points]; halo *halolist = malloc(max_allowed_halos*sizeof(halo)); double mass = 0, avg_mass = 0; int i,j; for(i = 0; i < num_points; i++) { Ds[i] = pow(10, 5.0*i/(double) num_points); reset_cell(&Flucs[i]); reset_cell(&Dens[i]); } int hist_num = 10; data_cell Hist_Flucs[hist_num]; for(int i = 0; i < hist_num; i++) reset_cell(Hist_Flucs + i); for(i = 0; i < num_trials; i++) { if(i % 100 == 0)printf("%d out of %d \n", i/100, num_trials/100); unsigned int num_halos = gsl_ran_poisson(RNG, expected_num); if(num_halos > max_allowed_halos) { max_allowed_halos *= 2; free(halolist); halolist = malloc(max_allowed_halos*sizeof(halo)); printf("ALLOCATING\n"); } mass = 0; //printf("Expect: %f Have: %lu \n", expected_num, num_halos); for(j = 0; j < num_halos; j++) { make_halo(halolist + j); //print_halo_basic(halolist + j); mass += halolist[j].M; if(mass != mass) { print_halo_basic(halolist + j); printf("%f %f %d %f\n", mass, halolist[j].M, j, halolist[j].alpha); return -1; } } for(j = 0; j < num_points; j++) { update_cell(Flucs + j, Fluc(halolist, num_halos, Ds[j]), i + 1); update_cell(Dens + j, (j == 0 ? H_Density(halolist, num_halos, Ds[j], Ds[j]) : H_Density(halolist, num_halos, Ds[j], Ds[j] - Ds[j-1])), i + 1); } //printf("Mass frac: %f \n", mass/M_prim); avg_mass += mass/num_trials; for(int j = 0; j < hist_num; j++) update_cell(Hist_Flucs + j, Fluc_mass_range(halolist, num_halos, 1e4, M_prim*g*pow(f/g, (double) j/ (double) hist_num), M_prim*g*pow(f/g, (double) (j + 1)/ (double) hist_num)), i + 1); /*for(j = 0; j < num_points; j++) { //printf("%f : %f\n", pow(10, 5.0*j/num_points), log10(Flucs[j])); //printf("%f : %f\n", pow(10, 5.0*j/num_points), log10(Dens[j])); //printf("%f : %f\n", pow(10, 5.0*j/num_points), Hist[j]); }*/ } print_to_file("Density", Ds, Dens); sq_root_data(Flucs, num_points); print_to_file("Flucs", Ds, Flucs); printf("Mass frac: %f \n", avg_mass/M_prim); sq_root_data(Hist_Flucs, hist_num); for(int i = 0; i < hist_num; i++) printf("Mass: %f Fluc: %f SDEV: %f\n", M_prim*g*pow(f/g, (double) i/ (double) hist_num), Hist_Flucs[i].m, std_err_mean(Hist_Flucs[i].s)); gsl_rng_free (RNG); gsl_integration_workspace_free (w); return 0; }
{ "alphanum_fraction": 0.5785313085, "avg_line_length": 28.7414050822, "ext": "c", "hexsha": "8befb792ad5166c15b81728c399c6590217d7a92", "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": "38e3e61ec1913fb2d94fbb8a5db53b90ec32ed66", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "benvchurch/project-eva", "max_forks_repo_path": "Monte_Carlo/Monte_Carlo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "38e3e61ec1913fb2d94fbb8a5db53b90ec32ed66", "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": "benvchurch/project-eva", "max_issues_repo_path": "Monte_Carlo/Monte_Carlo.c", "max_line_length": 187, "max_stars_count": 1, "max_stars_repo_head_hexsha": "38e3e61ec1913fb2d94fbb8a5db53b90ec32ed66", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "benvchurch/project-eva", "max_stars_repo_path": "Monte_Carlo/Monte_Carlo.c", "max_stars_repo_stars_event_max_datetime": "2017-07-27T19:02:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-27T19:02:16.000Z", "num_tokens": 7465, "size": 19228 }
#include <ceed.h> #include <petsc.h> #include "../problems/neo-hookean.h" // Build libCEED context object PetscErrorCode PhysicsContext_NH(MPI_Comm comm, Ceed ceed, Units *units, CeedQFunctionContext *ctx) { PetscErrorCode ierr; Physics_NH phys; PetscFunctionBegin; ierr = PetscMalloc1(1, units); CHKERRQ(ierr); ierr = PetscMalloc1(1, &phys); CHKERRQ(ierr); ierr = ProcessPhysics_NH(comm, phys, *units); CHKERRQ(ierr); CeedQFunctionContextCreate(ceed, ctx); CeedQFunctionContextSetData(*ctx, CEED_MEM_HOST, CEED_COPY_VALUES, sizeof(*phys), phys); ierr = PetscFree(phys); CHKERRQ(ierr); PetscFunctionReturn(0); } // Build libCEED smoother context object PetscErrorCode PhysicsSmootherContext_NH(MPI_Comm comm, Ceed ceed, CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother) { PetscErrorCode ierr; PetscScalar nu_smoother = 0; PetscBool nu_flag = PETSC_FALSE; Physics_NH phys, phys_smoother; PetscFunctionBegin; ierr = PetscOptionsBegin(comm, NULL, "Neo-Hookean physical parameters for smoother", NULL); CHKERRQ(ierr); ierr = PetscOptionsScalar("-nu_smoother", "Poisson's ratio for smoother", NULL, nu_smoother, &nu_smoother, &nu_flag); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics if (nu_flag) { // Copy context CeedQFunctionContextGetData(ctx, CEED_MEM_HOST, &phys); ierr = PetscMalloc1(1, &phys_smoother); CHKERRQ(ierr); ierr = PetscMemcpy(phys_smoother, phys, sizeof(*phys)); CHKERRQ(ierr); CeedQFunctionContextRestoreData(ctx, &phys); // Create smoother context CeedQFunctionContextCreate(ceed, ctx_smoother); phys_smoother->nu = nu_smoother; CeedQFunctionContextSetData(*ctx_smoother, CEED_MEM_HOST, CEED_COPY_VALUES, sizeof(*phys_smoother), phys_smoother); ierr = PetscFree(phys_smoother); CHKERRQ(ierr); } else { *ctx_smoother = NULL; } PetscFunctionReturn(0); } // Process physics options - Neo-Hookean PetscErrorCode ProcessPhysics_NH(MPI_Comm comm, Physics_NH phys, Units units) { PetscErrorCode ierr; PetscBool nu_flag = PETSC_FALSE; PetscBool Young_flag = PETSC_FALSE; phys->nu = 0; phys->E = 0; units->meter = 1; // 1 meter in scaled length units units->second = 1; // 1 second in scaled time units units->kilogram = 1; // 1 kilogram in scaled mass units PetscFunctionBeginUser; ierr = PetscOptionsBegin(comm, NULL, "Neo-Hookean physical parameters", NULL); CHKERRQ(ierr); ierr = PetscOptionsScalar("-nu", "Poisson's ratio", NULL, phys->nu, &phys->nu, &nu_flag); CHKERRQ(ierr); ierr = PetscOptionsScalar("-E", "Young's Modulus", NULL, phys->E, &phys->E, &Young_flag); CHKERRQ(ierr); ierr = PetscOptionsScalar("-units_meter", "1 meter in scaled length units", NULL, units->meter, &units->meter, NULL); CHKERRQ(ierr); units->meter = fabs(units->meter); ierr = PetscOptionsScalar("-units_second", "1 second in scaled time units", NULL, units->second, &units->second, NULL); CHKERRQ(ierr); units->second = fabs(units->second); ierr = PetscOptionsScalar("-units_kilogram", "1 kilogram in scaled mass units", NULL, units->kilogram, &units->kilogram, NULL); CHKERRQ(ierr); units->kilogram = fabs(units->kilogram); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics // Check for all required options to be set if (!nu_flag) { SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "-nu option needed"); } if (!Young_flag) { SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "-E option needed"); } // Define derived units units->Pascal = units->kilogram / (units->meter * PetscSqr(units->second)); // Scale E to Pa phys->E *= units->Pascal; PetscFunctionReturn(0); };
{ "alphanum_fraction": 0.6631840796, "avg_line_length": 34.358974359, "ext": "c", "hexsha": "f0b8af460785299d157503ab9b251e97b182846a", "lang": "C", "max_forks_count": 41, "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_path": "examples/solids/problems/neo-hookean.c", "max_issues_count": 781, "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_path": "examples/solids/problems/neo-hookean.c", "max_line_length": 81, "max_stars_count": 123, "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_path": "examples/solids/problems/neo-hookean.c", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "num_tokens": 1070, "size": 4020 }
#ifdef USING_FFTW #include <fftw.h> #elif defined USING_FFTW3 #include <fftw3.h> #else typedef double fftw_real; typedef struct { fftw_real re, im; } fftw_complex_orig; typedef fftw_real HPCC_Complex[2]; typedef HPCC_Complex fftw_complex; #endif typedef enum { FFTW2_FORWARD = -1, FFTW2_BACKWARD = 1 } fftw_direction; struct hpcc_fftw_plan_struct { fftw_complex *w1, *w2, *ww1, *ww2, *ww3, *ww4, *c, *d; int n, c_size, d_size; int flags; fftw_direction dir; }; typedef struct hpcc_fftw_plan_struct *hpcc_fftw_plan; extern hpcc_fftw_plan HPCC_fftw_create_plan(int n, fftw_direction dir, int flags); extern void HPCC_fftw_destroy_plan(hpcc_fftw_plan plan); extern void HPCC_fftw_one(hpcc_fftw_plan plan, fftw_complex *in, fftw_complex *out); #ifdef USING_FFTW #elif defined USING_FFTW3 #define c_re(c) ((c)[0]) #define c_im(c) ((c)[1]) #else typedef struct hpcc_fftw_plan_struct *fftw_plan; #define c_re(c) ((c)[0]) #define c_im(c) ((c)[1]) #define fftw_malloc malloc #define fftw_free free /* flags for the planner */ #define FFTW_ESTIMATE (0) #define FFTW_MEASURE (1) #define FFTW_OUT_OF_PLACE (0) #define FFTW_IN_PLACE (8) #define FFTW_USE_WISDOM (16) #define fftw_create_plan HPCC_fftw_create_plan #define fftw_destroy_plan HPCC_fftw_destroy_plan #define fftw_one HPCC_fftw_one #endif
{ "alphanum_fraction": 0.7567567568, "avg_line_length": 20.1818181818, "ext": "h", "hexsha": "ead5d698c3db6b47471d849c2268aa0a27fcc1fb", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-14T01:30:03.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-14T01:30:03.000Z", "max_forks_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Ringbo/HPCC_optimization", "max_forks_repo_path": "FFT/wrapfftw.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "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": "Ringbo/HPCC_optimization", "max_issues_repo_path": "FFT/wrapfftw.h", "max_line_length": 84, "max_stars_count": 1, "max_stars_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Ringbo/HPCC_optimization", "max_stars_repo_path": "FFT/wrapfftw.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:29:58.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-14T01:29:58.000Z", "num_tokens": 418, "size": 1332 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iniparser.h> #include "parmt_utils.h" #include "prepmt/prepmt_dataArchive.h" #include "prepmt/prepmt_greens.h" #include "prepmt/prepmt_hudson96.h" #include "prepmt/prepmt_commands.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "ispl/process.h" #include "iscl/array/array.h" #include "iscl/fft/fft.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" #include "iscl/signal/convolve.h" #include "iscl/signal/filter.h" static int getPrimaryArrival(const struct sacHeader_struct hdr, double *time, char phaseName[8]); static int getPrimaryArrivalNoPolarity(const struct sacHeader_struct hdr, double *time, char phaseName[8]); static void shiftGreens(const int npgrns, const int lag, double *__restrict__ G, double *__restrict__ work); //============================================================================// /*! * @brief Converts the fundamental faults Green's functions to Green's * functions that can be used by parmt. * * @param[in] nobs Number of observations. * @param[in] obs Observed waveforms to contextualize. This is an * array of length [nobs]. * @param[in] ndepth Number of depths. * @param[in] ntstar Number of t*s'. * @param[in] ffGrns Fundamental fault Green's functions for every t* and * depth in the grid search for each observation. This * is an array of dimension [nobs x ndepth x ntstar x 10]. * * @param[in,out] grns Holds space for Green's functions. * Contains the Green's functions that can be applied to * a moment tensor to produce a synthetic for every t* * and depth in the grid search for each observation. * This is an array of length [nobs x ndepth x ntstar x 6]. * * @result 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_greens_ffGreensToGreens(const int nobs, const struct sacData_struct *obs, const int ndepth, const int ntstar, const struct sacData_struct *ffGrns, struct sacData_struct *grns) { char knetwk[8], kstnm[8], kcmpnm[8], khole[8], phaseName[8], phaseNameGrns[8]; double az, baz, cmpaz, cmpinc, cmpincSEED, epoch, epochNew, evla, evlo, o, pick, pickTime, pickTimeGrns, stel, stla, stlo; int indices[6], i, icomp, id, ierr, idx, iobs, it, kndx, l, npts; const char *kcmpnms[6] = {"GXX\0", "GYY\0", "GZZ\0", "GXY\0", "GXZ\0", "GYZ\0"}; /* const double xmom = 1.0; // no confusing `relative' magnitudes const double xcps = 1.e-20; // convert dyne-cm mt to output cm const double cm2m = 1.e-2; // cm to meters const double dcm2nm = 1.e+7; // magnitudes intended to be specified in // Dyne-cm but I work in N-m // Given a M0 in Newton-meters get a seismogram in meters const double xscal = xmom*xcps*cm2m*dcm2nm; */ const int nTimeVars = 11; const enum sacHeader_enum pickVars[11] = {SAC_FLOAT_A, SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3, SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7, SAC_FLOAT_T8, SAC_FLOAT_T9}; //memset(grns, 0, sizeof(struct tdSearchGreens_struct)); for (iobs=0; iobs<nobs; iobs++) { ierr = 0; ierr += sacio_getFloatHeader(SAC_FLOAT_AZ, obs[iobs].header, &az); ierr += sacio_getFloatHeader(SAC_FLOAT_BAZ, obs[iobs].header, &baz); ierr += sacio_getFloatHeader(SAC_FLOAT_CMPINC, obs[iobs].header, &cmpinc); ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ, obs[iobs].header, &cmpaz); ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA, obs[iobs].header, &evla); ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO, obs[iobs].header, &evlo); ierr += sacio_getFloatHeader(SAC_FLOAT_STLA, obs[iobs].header, &stla); ierr += sacio_getFloatHeader(SAC_FLOAT_STLO, obs[iobs].header, &stlo); ierr += sacio_getCharacterHeader(SAC_CHAR_KNETWK, obs[iobs].header, knetwk); ierr += sacio_getCharacterHeader(SAC_CHAR_KSTNM, obs[iobs].header, kstnm); ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM, obs[iobs].header, kcmpnm); if (ierr != 0) { fprintf(stderr, "%s: Error reading header variables\n", __func__); break; } // This one isn't critical but it would be nice to have sacio_getFloatHeader(SAC_FLOAT_STEL, obs[iobs].header, &stel); // Station location code is not terribly important sacio_getCharacterHeader(SAC_CHAR_KHOLE, obs[iobs].header, khole); cmpincSEED = cmpinc - 90.0; // SAC to SEED convention // Get the primary arrival ierr = sacio_getEpochalStartTime(obs[iobs].header, &epoch); if (ierr != 0) { fprintf(stderr, "%s: Error getting start time\n", __func__); break; } ierr += getPrimaryArrivalNoPolarity(obs[iobs].header, &pickTime, phaseName); //ierr += getPrimaryArrival(obs[iobs].header, &pickTime, phaseName); if (ierr != 0) { fprintf(stderr, "%s: Error getting primary pick\n", __func__); break; } // Need to figure out the component ierr = parmt_utils_getComponent(kcmpnm, cmpinc, &icomp); if (ierr != 0) { fprintf(stderr, "%s: Error getting component\n", __func__); break; } /* icomp = 1; if (fabs(cmpinc - 0.0) < 1.e-4 || fabs(cmpinc - 180.0) < 1.e-4) { if (kcmpnm[2] == 'Z' || kcmpnm[2] == 'z' || kcmpnm[2] == '1') { icomp = 1; } else { fprintf(stderr, "%s: cmpinc is 0 but channel=%s isn't vertical", __func__, kcmpnm); } } else if (fabs(cmpinc - 90.0) < 1.e-4) { icomp = 2; if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' || kcmpnm[2] == '1' || kcmpnm[2] == '2') { icomp = 2; } else if (kcmpnm[2] == 'N' || kcmpnm[2] == 'n' || kcmpnm[2] == '2' || kcmpnm[2] == '3') { icomp = 3; } else { fprintf(stderr, "%s: cmpinc is 90 but channel=%s is weird", __func__, kcmpnm); return -1; } } */ /* else if (kcmpnm[2] == 'E' || kcmpnm[2] == 'e' || kcmpnm[2] == '3') { icomp = 3; } */ /* else { fprintf(stderr, "%s: Can't classify component %s with cmpinc=%f\n", __func__, kcmpnm, cmpinc); } */ // Process all Green's functions in this block for (id=0; id<ndepth; id++) { for (it=0; it<ntstar; it++) { idx = prepmt_hudson96_observationDepthTstarToIndex( ndepth, ntstar, iobs, id, it); kndx = 10*idx; sacio_getFloatHeader(SAC_FLOAT_O, ffGrns[kndx].header, &o); getPrimaryArrival(ffGrns[kndx].header, &pickTimeGrns, phaseNameGrns); if (strcasecmp(phaseNameGrns, phaseName) != 0) { fprintf(stdout, "%s: Phase name mismatch %s %s\n", __func__, phaseName, phaseNameGrns); } npts = ffGrns[kndx].npts; ierr = prepmt_greens_getHudson96GreensFunctionsIndices( nobs, ntstar, ndepth, iobs, it, id, indices); /* indx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS, nobs, ntstar, ndepth, iobs, it, id); */ for (i=0; i<6; i++) { sacio_copy(ffGrns[kndx], &grns[indices[i]]); if (obs[iobs].pz.lhavePZ) { sacio_copyPolesAndZeros(obs[iobs].pz, &grns[indices[i]].pz); } sacio_setFloatHeader(SAC_FLOAT_AZ, az, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_BAZ, baz, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_CMPAZ, cmpaz, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_CMPINC, cmpinc, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_EVLA, evla, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_EVLO, evlo, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_STLA, stla, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_STLO, stlo, &grns[indices[i]].header); sacio_setFloatHeader(SAC_FLOAT_STEL, stel, &grns[indices[i]].header); sacio_setCharacterHeader(SAC_CHAR_KNETWK, knetwk, &grns[indices[i]].header); sacio_setCharacterHeader(SAC_CHAR_KSTNM, kstnm, &grns[indices[i]].header); sacio_setCharacterHeader(SAC_CHAR_KHOLE, khole, &grns[indices[i]].header); sacio_setCharacterHeader(SAC_CHAR_KCMPNM, kcmpnms[i], &grns[indices[i]].header); sacio_setCharacterHeader(SAC_CHAR_KEVNM, "SYNTHETIC\0", &grns[indices[i]].header); // Set the start time by aligning on the arrival epochNew = epoch + (pickTime - o) - pickTimeGrns; sacio_setEpochalStartTime(epochNew, &grns[indices[i]].header); // Update the pick times for (l=0; l<nTimeVars; l++) { ierr = sacio_getFloatHeader(pickVars[l], grns[indices[i]].header, &pick); if (ierr == 0) { pick = pick + o; sacio_setFloatHeader(pickVars[l], pick, &grns[indices[i]].header); } } } //printf("%d %d\n", kndx, indices[0]); //printf("%e\n", array_max64f(npts, ffGrns[kndx+0].data)); ierr = parmt_utils_ff2mtGreens64f(npts, icomp, az, baz, cmpaz, cmpincSEED, ffGrns[kndx+0].data, ffGrns[kndx+1].data, ffGrns[kndx+2].data, ffGrns[kndx+3].data, ffGrns[kndx+4].data, ffGrns[kndx+5].data, ffGrns[kndx+6].data, ffGrns[kndx+7].data, ffGrns[kndx+8].data, ffGrns[kndx+9].data, grns[indices[0]].data, grns[indices[1]].data, grns[indices[2]].data, grns[indices[3]].data, grns[indices[4]].data, grns[indices[5]].data); if (ierr != 0) { fprintf(stderr, "%s: Failed to rotate Greens functions\n", __func__); } // Fix the characteristic magnitude scaling in CPS // N.B. this is done early now /* for (i=0; i<6; i++) { cblas_dscal(npts, xscal, grns[indices[i]].data, 1); //printf("%d %d %e\n", kndx, indices[i], // array_max64f(npts,grns[indices[i]].data)); } */ } } } return 0; } //============================================================================// /*! * @brief Convenience function which returns the index of the Green's * function on the Green's function structure. * * @param[in] GMT_TERM Name of the desired Green's function: * (G11_TERM, G22_TERM, ..., G23_TERM). * @param[in] nobs Number of observations. * @param[in] ntstar Number of t*'s. * @param[in] ndepth Number of depths. * @param[in] iobs Desired observation number (C numbering). * @param[in] itstar Desired t* (C numbering). * @param[in] idepth Desired depth (C numbering). * * @result Negative indicates failure. Otherwise, this is the index in * grns.grns corresponding to the desired * (iobs, idepth, itstar, G??_GRNS) coordinate. * * @author Ben Baker, ISTI * */ int prepmt_greens_getHudson96GreensFunctionIndex( const enum prepmtGreens_enum GMT_TERM, const int nobs, const int ntstar, const int ndepth, const int iobs, const int itstar, const int idepth) { int igx, indx, ngrns; ngrns = 6*nobs*ntstar*ndepth; indx =-1; igx = (int) GMT_TERM - 1; if (igx < 0 || igx > 5) { fprintf(stderr, "%s: Can't classify Green's functions index\n", __func__); return indx; } indx = iobs*(6*ntstar*ndepth) + idepth*(6*ntstar) + itstar*6 + igx; if (indx < 0 || indx >= ngrns) { fprintf(stderr, "%s: indx out of bounds - segfault is coming\n", __func__); return -1; } return indx; } //============================================================================// /*! * @brief Repicks the Green's functions onset time with an STA/LTA picker. * * @param[in] sta Short term average window length (seconds). * @param[in] lta Long term average window length (seconds). * @param[in] threshPct Percentage of max STA/LTA after which an arrival * is declared. * @param[in] nobs Number of observations. * @param[in] ntstar Number of t*'s. * @param[in] ndepth Number of depths. * @param[in] iobs C numbered observation index. * @param[in] itstar C numbered t* index. * @param[in] idepth C numbered depth index. * * @param[in,out] grns On input contains the Green's functions. * On output the first defined arrival time has been * modified with an STA/LTA picker. The header variable * to be modified is most likely SAC_FLOAT_A. * This is an array of dimension [6]. * * @brief 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_greens_repickGreensWithSTALTA( const double sta, const double lta, const double threshPct, struct sacData_struct *grns) { struct stalta_struct stalta; enum sacHeader_enum pickHeader; double *charFn, *g, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz, *gxxPad, *gyyPad, *gzzPad, *gxyPad, *gxzPad, *gyzPad, apick, charMax, dt, tpick; int ierr, k, npts, nlta, npad, nsta, nwork, prePad; const int nTimeVars = 11; const enum sacHeader_enum pickVars[11] = {SAC_FLOAT_A, SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3, SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7, SAC_FLOAT_T8, SAC_FLOAT_T9}; // Check STA/LTA ierr = 0; memset(&stalta, 0, sizeof(struct stalta_struct)); if (lta < sta || sta < 0.0) { if (lta < sta){fprintf(stderr, "%s: Error lta < sta\n", __func__);} if (sta < 0.0){fprintf(stderr, "%s: Error sta is < 0\n", __func__);} return -1; } ierr = sacio_getIntegerHeader(SAC_INT_NPTS, grns[0].header, &npts); if (ierr != 0 || npts < 1) { if (ierr != 0) { fprintf(stderr, "%s: Error getting number of points from header\n", __func__); } else { fprintf(stderr, "%s: Error no data points\n", __func__); } return -1; } ierr = sacio_getFloatHeader(SAC_FLOAT_DELTA, grns[0].header, &dt); if (ierr != 0 || dt <= 0.0) { if (ierr != 0){fprintf(stderr, "%s: failed to get dt\n", __func__);} if (dt <= 0.0) { fprintf(stderr, "%s: invalid sampling period\n", __func__); } return -1; } // Define the windows nsta = (int) (sta/dt + 0.5); nlta = (int) (lta/dt + 0.5); prePad = MAX(64, fft_nextpow2(nlta, &ierr)); npad = prePad + npts; // Set space gxxPad = memory_calloc64f(npad); gyyPad = memory_calloc64f(npad); gzzPad = memory_calloc64f(npad); gxyPad = memory_calloc64f(npad); gxzPad = memory_calloc64f(npad); gyzPad = memory_calloc64f(npad); charFn = memory_calloc64f(npad); // Reference pointers Gxx = grns[0].data; Gyy = grns[1].data; Gzz = grns[2].data; Gxy = grns[3].data; Gxz = grns[4].data; Gyz = grns[5].data; // Pre-pad signals array_set64f_work(prePad, Gxx[0], gxxPad); array_set64f_work(prePad, Gyy[0], gyyPad); array_set64f_work(prePad, Gzz[0], gzzPad); array_set64f_work(prePad, Gxy[0], gxyPad); array_set64f_work(prePad, Gxz[0], gxzPad); array_set64f_work(prePad, Gyz[0], gyzPad); // Copy rest of array array_copy64f_work(npts, Gxx, &gxxPad[prePad]); array_copy64f_work(npts, Gyy, &gyyPad[prePad]); array_copy64f_work(npts, Gzz, &gzzPad[prePad]); array_copy64f_work(npts, Gxy, &gxyPad[prePad]); array_copy64f_work(npts, Gxz, &gxzPad[prePad]); array_copy64f_work(npts, Gyz, &gyzPad[prePad]); // apply the sta/lta for (k=0; k<6; k++) { g = NULL; if (k == 0) { g = gxxPad; } else if (k == 1) { g = gyyPad; } else if (k == 2) { g = gzzPad; } else if (k == 3) { g = gxyPad; } else if (k == 4) { g = gxzPad; } else if (k == 5) { g = gyzPad; } ierr = stalta_setShortAndLongTermAverage(nsta, nlta, &stalta); if (ierr != 0) { fprintf(stderr, "%s: Error setting STA/LTA\n", __func__); break; } ierr = stalta_setData64f(npad, g, &stalta); if (ierr != 0) { fprintf(stderr, "%s: Error setting data\n", __func__); break; } ierr = stalta_applySTALTA(&stalta); if (ierr != 0) { fprintf(stderr, "%s: Error applying STA/LTA\n", __func__); break; } ierr = stalta_getData64f(stalta, npad, &nwork, g); if (ierr != 0) { fprintf(stderr, "%s: Error getting result\n", __func__); break; } cblas_daxpy(npad, 1.0, g, 1, charFn, 1); stalta_resetInitialConditions(&stalta); stalta_resetFinalConditions(&stalta); g = NULL; } // Compute the pick time charMax = array_max64f(npts, &charFn[prePad], &ierr); tpick =-1.0; for (k=prePad; k<npad; k++) { if (charFn[k] > 0.01*threshPct*charMax) { tpick = (double) (k - prePad)*dt; break; } } if (tpick ==-1.0) { tpick = (double) (array_argmax64f(npad, charFn, &ierr) - prePad)*dt; } // Overwrite the pick pickHeader = SAC_UNKNOWN_HDRVAR; for (k=0; k<nTimeVars; k++) { if (sacio_getFloatHeader(pickVars[k], grns[k].header, &apick) == 0) { pickHeader = pickVars[k]; break; } } if (pickHeader == SAC_UNKNOWN_HDRVAR) { fprintf(stdout, "%s: Could not locate primary arrival - assume A\n", __func__); pickHeader = SAC_FLOAT_A; } //printf("%f %f\n", tpick, apick); //double apick; //sacio_getFloatHeader(SAC_FLOAT_A, grns[0].header, &apick); for (k=0; k<6; k++) { sacio_setFloatHeader(pickHeader, tpick, &grns[k].header); } // Dereference pointers and free space Gxx = NULL; Gyy = NULL; Gzz = NULL; Gxy = NULL; Gxz = NULL; Gyz = NULL; memory_free64f(&gxxPad); memory_free64f(&gyyPad); memory_free64f(&gzzPad); memory_free64f(&gxyPad); memory_free64f(&gxzPad); memory_free64f(&gyzPad); memory_free64f(&charFn); stalta_free(&stalta); return ierr; } //============================================================================// int prepmt_greens_processHudson96Greens( const int nobs, const int ntstar, const int ndepth, const struct prepmtCommands_struct cmds, struct sacData_struct *grns) { struct serialCommands_struct commands; struct parallelCommands_struct parallelCommands; double *G, dt, dt0, epoch, epoch0, time; int *dataPtr, indices[6], i, i0, i1, i2, ierr, iobs, idep, it, kndx, l, npts, npts0, nq, nwork, ny, ns, nsuse; bool lnewDt, lnewStartTime; const int nTimeVars = 12; const enum sacHeader_enum timeVars[12] = {SAC_FLOAT_A, SAC_FLOAT_O, SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3, SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7, SAC_FLOAT_T8, SAC_FLOAT_T9}; const int spaceInquiry =-1; // Loop on the observations ns = ndepth*ntstar*6; dataPtr = memory_calloc32i(ns); for (iobs=0; iobs<nobs; iobs++) { // Set the processing structure memset(&parallelCommands, 0, sizeof(struct parallelCommands_struct)); memset(&commands, 0, sizeof(struct serialCommands_struct)); kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS, nobs, ntstar, ndepth, iobs, 0, 0); // Parse the commands ierr = process_stringsToSerialCommandsOptions( cmds.cmds[iobs].ncmds, (const char **) cmds.cmds[iobs].cmds, &commands); if (ierr != 0) { fprintf(stderr, "%s: Error setting serial command string\n", __func__); goto ERROR; } // Determine some characteristics of the processing sacio_getEpochalStartTime(grns[kndx].header, &epoch0); sacio_getFloatHeader(SAC_FLOAT_DELTA, grns[kndx].header, &dt0); lnewDt = false; lnewStartTime = false; epoch = epoch0; dt = dt0; for (i=0; i<commands.ncmds; i++) { if (commands.commands[i].type == CUT_COMMAND) { i0 = commands.commands[i].cut.i0; epoch = epoch + (double) i0*dt; lnewStartTime = true; } if (commands.commands[i].type == DOWNSAMPLE_COMMAND) { nq = commands.commands[i].downsample.nq; dt = dt*(double) nq; lnewDt = true; } if (commands.commands[i].type == DECIMATE_COMMAND) { nq = commands.commands[i].decimate.nqAll; dt = dt*(double) nq; lnewDt = true; } } // Set the commands on the parallel processing structure ierr = process_setCommandOnAllParallelCommands(ns, commands, &parallelCommands); if (ierr != 0) { fprintf(stderr, "%s: Error setting the parallel commands\n", __func__); goto ERROR; } // Get the data dataPtr[0] = 0; for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { kndx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS, nobs, ntstar, ndepth, iobs, idep, it); ierr = sacio_getIntegerHeader(SAC_INT_NPTS, grns[kndx].header, &npts); if (ierr != 0) { fprintf(stderr, "%s: Error getting npts\n", __func__); goto ERROR; } i1 = idep*6*ntstar + it*6 + 0; i2 = i1 + 6; for (i=i1; i<i2; i++) { dataPtr[i+1] = dataPtr[i] + npts; } } } nwork = dataPtr[6*ndepth*ntstar]; if (nwork < 1) { fprintf(stderr, "%s: Invalid workspace size: %d\n", __func__, nwork); ierr = 1; goto ERROR; } G = memory_calloc64f(nwork); for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { ierr = prepmt_greens_getHudson96GreensFunctionsIndices( nobs, ntstar, ndepth, iobs, it, idep, indices); if (ierr != 0) { fprintf(stderr, "%s: Error getting index\n", __func__); goto ERROR; } for (i=0; i<6; i++) { i1 = idep*6*ntstar + it*6 + i; //if (i == 0){printf("fill: %d %d %d %e\n", i1, indices[i], dataPtr[i1], array_max64f(grns[indices[i]].npts, grns[indices[i]].data));} cblas_dcopy(grns[indices[i]].npts, grns[indices[i]].data, 1, &G[dataPtr[i1]], 1); } } } // Set the data ierr = process_setParallelCommandsData64f(ns, dataPtr, G, &parallelCommands); if (ierr != 0) { fprintf(stderr, "%s: Error setting data\n", __func__); goto ERROR; } // Apply the commands ierr = process_applyParallelCommands(&parallelCommands); if (ierr != 0) { fprintf(stderr, "%s: Error processing data\n", __func__); goto ERROR; } // Get the data ierr = process_getParallelCommandsData64f(parallelCommands, spaceInquiry, spaceInquiry, &ny, &nsuse, dataPtr, G); if (ny < nwork) { memory_free64f(&G); G = memory_calloc64f(ny); } ny = nwork; ierr = process_getParallelCommandsData64f(parallelCommands, nwork, ns, &ny, &nsuse, dataPtr, G); //printf("%d\n", nsuse); if (ierr != 0) { fprintf(stderr, "%s: Error getting data\n", __func__); goto ERROR; } // Unpack the data for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { ierr = prepmt_greens_getHudson96GreensFunctionsIndices( nobs, ntstar, ndepth, iobs, it, idep, indices); if (ierr != 0) { fprintf(stderr, "%s: Error getting index\n", __func__); goto ERROR; } for (i=0; i<6; i++) { i1 = idep*6*ntstar + it*6 + i; sacio_getIntegerHeader(SAC_INT_NPTS, grns[indices[i]].header, &npts0); npts = dataPtr[i1+1] - dataPtr[i1]; // Resize event if (npts != npts0) { sacio_freeData(&grns[indices[i]]); grns[indices[i]].data = sacio_malloc64f(npts); grns[indices[i]].npts = npts; sacio_setIntegerHeader(SAC_INT_NPTS, npts, &grns[indices[i]].header); ierr = array_copy64f_work(npts, &G[dataPtr[i1]], grns[indices[i]].data); } else { ierr = array_copy64f_work(npts, &G[dataPtr[i1]], grns[indices[i]].data); //if (i == 0){printf("%d %d %e\n", iobs, indices[i], array_max64f(grns[indices[i]].npts, grns[indices[i]].data));} } } // Update the times if (lnewStartTime) { for (i=0; i<6; i++) { // Update the picks for (l=0; l<nTimeVars; l++) { ierr = sacio_getFloatHeader(timeVars[l], grns[indices[i]].header, &time); if (ierr == 0) { time = time + epoch0; // Turn to real time time = time - epoch; // Relative to new time sacio_setFloatHeader(timeVars[l], time, &grns[indices[i]].header); } } // Loop on picks sacio_setEpochalStartTime(epoch, &grns[indices[i]].header); } // Loop on signals } // Update the sampling period if (lnewDt) { for (i=0; i<6; i++) { sacio_setFloatHeader(SAC_FLOAT_DELTA, dt, &grns[indices[i]].header); } } } // Loop on t* } // Loop on depths process_freeSerialCommands(&commands); process_freeParallelCommands(&parallelCommands); memory_free64f(&G); } ERROR:; memory_free32i(&dataPtr); return 0; } //============================================================================// /*! * @brief Writes a Green's functions archive that is appropriate for parmt. * * @param[in] archiveName Name of archive file to write. * @param[in] nwaves Number of waveforms. * @param[in] ndepths Number of depths in grid-search. * @param[in] evla Event latitude (degrees). * @param[in] evlo Event longitude (degrees). * @param[in] depths Depths (km) in grid search. This is an array of * dimension [ndepths]. * @param[in] sac SAC observations to write. This is an array of * dimension [nwaves]. * @param[in] sacGrns Corresponding Green's functions to write. This * is an array of dimension [6 x ndepths x nwaves] * where the fastest dimension is 6 and the slowest * dimension is nwaves. Each Green's function * group for the waveform, depth pair is packed: * \f$ \{ G_{xx}, G_{yy}, G_{zz}, * G_{xy}, G_{xz}, G_{yz} \} \f$. * * @result 0 indicates success. * * @author Ben Baker * */ int prepmt_greens_writeArchive(const char *archiveName, //const char *archiveDir, const char *projnm, const int nwaves, const int ndepths, const double evla, const double evlo, const double *__restrict__ depths, const struct sacData_struct *sac, const struct sacData_struct *sacGrns) { int id, ierr, indx, k; hid_t h5fl; // initialize the archive ierr = prepmt_dataArchive_createArchive(archiveName, //archiveDir, projnm, ndepths, evla, evlo, depths); if (ierr != 0) { fprintf(stderr, "%s: Error creating archive\n", __func__); return -1; } // open it for writing h5fl = prepmt_dataArchive_openArchive(archiveName, &ierr); //archiveDir, projnm, &ierr); // write each observation and greens fns for (k=0; k<nwaves; k++) { ierr = prepmt_dataArchive_addObservation(h5fl, sac[k]); for (id=0; id<ndepths; id++) { indx = k*ndepths*6 + id*6; ierr = prepmt_dataArchive_addGreensFunctions(h5fl, sac[k], sacGrns[indx+0], sacGrns[indx+1], sacGrns[indx+2], sacGrns[indx+3], sacGrns[indx+4], sacGrns[indx+5]); //printf("%f %e\n", sacGrns[indx+0].header.evdp, sacGrns[indx+0].data[12]); if (ierr != 0){return -1;} } } prepmt_dataArchive_closeArchive(h5fl); return ierr; } //============================================================================// int prepmt_greens_cutHudson96FromData(const int nobs, const struct sacData_struct *data, const int ndepth, const int ntstar, struct sacData_struct *grns) { char **newCmds; struct prepmtModifyCommands_struct options; double cut0, dt, epoch, epochData; int i, ierr, idep, indx, iobs, it, npts; const int ncmds = 2; //const char *cmds[2] = {"cut\0", "demean\0"}; struct prepmtCommands_struct prepMTcmds; newCmds = (char **) calloc(2, sizeof(char *)); for (i=0; i<2; i++) { newCmds[i] = (char *) calloc(MAX_CMD_LEN, sizeof(char)); } strcpy(newCmds[1], "demean\0"); prepMTcmds.cmds = (struct prepmtCommandsChars_struct *) calloc(1, sizeof(struct prepmtCommandsChars_struct)); prepMTcmds.cmds[0].ncmds = ncmds; memset(&options, 0, sizeof(struct prepmtModifyCommands_struct)); for (iobs=0; iobs<nobs; iobs++) { // Get the primary pick ierr = sacio_getEpochalStartTime(data[iobs].header, &epoch); if (ierr != 0) { fprintf(stderr, "%s: Error getting start time\n", __func__); break; } epochData = epoch; sacio_getFloatHeader(SAC_FLOAT_DELTA, data[iobs].header, &dt); sacio_getIntegerHeader(SAC_INT_NPTS, data[iobs].header, &npts); cut0 = epoch; //cut1 = cut0 + dt*(double) (npts - 1); for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { indx = prepmt_greens_getHudson96GreensFunctionIndex(G11_GRNS, nobs, ntstar, ndepth, iobs, it, idep); //printf("%d %d %d %d\n", iobs, it, idep, indx); sacio_getEpochalStartTime(grns[indx].header, &epoch); if (cut0 - epoch < 0.0) { fprintf(stdout, "%s: Cut may be funky\n", __func__); } options.cut0 = fmax(0.0, cut0 - epoch); options.cut1 = options.cut0 + dt*(double) (npts - 1); /* newCmds = prepmt_commands_modifyCommands(ncmds, cmds, options, grns[indx], &ierr); */ ierr = cut_cutEpochalTimesToString(grns[indx].header.delta, 0.0, options.cut0, options.cut1, newCmds[0]); //strcpy(newCmds[1], "demean"); //printf("%s %f\n", newCmds[0], grns[indx].header.delta); prepMTcmds.cmds[0].cmds = newCmds; ierr = prepmt_greens_processHudson96Greens(1, 1, 1, prepMTcmds, &grns[indx]); // Enforce the epochal time for (i=0; i<6; i++) { sacio_setEpochalStartTime(epochData, &grns[indx+i].header); } //printf("%d %e\n", indx, array_max64f(grns[indx].npts, grns[indx].data)); for (i=0; i<ncmds; i++) { // free(newCmds[i]); } //free(newCmds); } } } for (i=0; i<2; i++) { free(newCmds[i]); } free(newCmds[i]); free(prepMTcmds.cmds); return 0; } //============================================================================// /*! * @brief Convenience function for extracting the: * \$ \{ G_{xx}, G_{yy}, G_{zz}, G_{xy}, G_{xz}, G_{yz} \} \$ * Green's functions indices for the observation, t*, and depth. * * @param[in] nobs Total number of observations. * @param[in] ntstar Total number of t*. * @param[in] ndepth Total number of depths. * @param[in] iobs Observation number. This is C indexed. * @param[in] itstar t* index. This is C indexed. * @param[in] idepth Depth index. This is C indexed. * @param[in] grns Contains the Green's functions. * @param[out] indices Contains the Green's functions indices defining * the indices that return the: * \$ \{ G_{xx}, G_{yy}, G_{zz}, * G_{xy}, G_{xz}, G_{yz} \} \$ * for this observation, t*, and depth. * * @result 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_greens_getHudson96GreensFunctionsIndices( const int nobs, const int ntstar, const int ndepth, const int iobs, const int itstar, const int idepth, int indices[6]) { int i, ierr; const enum prepmtGreens_enum mtTerm[6] = {G11_GRNS, G22_GRNS, G33_GRNS, G12_GRNS, G13_GRNS, G23_GRNS}; ierr = 0; for (i=0; i<6; i++) { indices[i] = prepmt_greens_getHudson96GreensFunctionIndex(mtTerm[i], nobs, ntstar, ndepth, iobs, itstar, idepth); if (indices[i] < 0){ierr = ierr + 1;} } if (ierr != 0) { fprintf(stderr, "%s: Error getting indices (obs,t*,depth)=(%d,%d,%d)\n", __func__, iobs, itstar, idepth); } return ierr; } //============================================================================// /*! * @brief Aligns the Green's functions to the data via cross-correlation. * * @param[in] data Holds the observed data. * @param[in] luseEnvelope If true then cross-correlate the envelopes of * the waveforms. \n * Otherwise, cross-correlate the waveforms * themselves. In this case the absolute values * of the cross-correlation are used. * @param[in] lnorm If true then use a normalized cross-correlation * so that all waveforms can contribute equally. \n * Otherwise, use the non-normalized cross-correlation. * @param[in] maxTimLag Max time lag (seconds) allowed in cross-correlation. * * @param[in,out] grns On input contains the Green's functions to * align to the data. * On output contains the Green's functions which * have been aligned to the data via cross-correlation. * * @result 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_greens_xcAlignGreensToData(const struct sacData_struct data, const bool luseEnvelope, const bool lnorm, const double maxTimeLag, struct sacData_struct *grns) { double *dataPad, *Gxx, *Gyy, *Gzz, *Gxy, *Gxz, *Gyz, *xc, dt, dtGrns, epochData, epochGrns; int ierr, insertData, lxc, maxShift, npadData, npts, npgrns; ierr = 0; sacio_getIntegerHeader(SAC_INT_NPTS, data.header, &npts); sacio_getIntegerHeader(SAC_INT_NPTS, grns[0].header, &npgrns); if (npts < 1 || npgrns < 1) { fprintf(stderr, "%s: Error no data\n", __func__); fprintf(stderr, "%s: Error no grns functions\n", __func__); return -1; } sacio_getFloatHeader(SAC_FLOAT_DELTA, data.header, &dt); sacio_getFloatHeader(SAC_FLOAT_DELTA, data.header, &dtGrns); if (fabs(dt - dtGrns) > 1.e-6 || dt <= 0.0) { if (dt <= 0.0){fprintf(stderr, "%s: dt is invalid\n", __func__);} if (fabs(dt - dtGrns) > 1.e-6) { fprintf(stderr, "%s: dt is inconsistent\n", __func__); } return -1; } // Need a common reference - choose the start time ierr = sacio_getEpochalStartTime(data.header, &epochData); if (ierr != 0) { fprintf(stderr, "%s: Error getting data start time\n", __func__); return -1; } ierr = sacio_getEpochalStartTime(grns[0].header, &epochGrns); if (ierr != 0) { fprintf(stderr, "%s: Error getting grns start time\n", __func__); return -1; } if (epochData < epochGrns) { fprintf(stderr, "%s: epochData < epochGrns not programmed\n", __func__); return -1; } // Insert the data in a epochal time aligned array insertData = (int) ((epochData - epochGrns)/dt + 0.5); npadData = insertData + npts; //printf("%d %d\n", insertData, npts); dataPad = memory_calloc64f(npadData); array_copy64f_work(npts, data.data, &dataPad[insertData]); // Create pointers to Green's functions Gxx = grns[0].data; Gyy = grns[1].data; Gzz = grns[2].data; Gxy = grns[3].data; Gxz = grns[4].data; Gyz = grns[5].data; // Compute hte max lag maxShift =-1; if (maxTimeLag >= 0.0){maxShift = (int) (maxTimeLag/dt + 0.5);} //printf("%d %f %f\n", maxShift, maxTimeLag/dt, maxTimeLag); // Align lxc = npadData + npgrns - 1; //npts + npgrns - 1; xc = memory_calloc64f(lxc); ierr = prepmt_greens_xcAlignGreensToData_work(npadData, dataPad, //data.data, npgrns, luseEnvelope, lnorm, maxShift, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, lxc, xc); memory_free64f(&xc); memory_free64f(&dataPad); // Dereference pointers Gxx = NULL; Gyy = NULL; Gzz = NULL; Gxy = NULL; Gxz = NULL; Gyz = NULL; return ierr; } //============================================================================// int prepmt_greens_xcAlignGreensToData_work( const int npts, double *__restrict__ data, const int npgrns, const bool luseEnvelope, const bool lnorm, const int maxShift, double *__restrict__ Gxx, double *__restrict__ Gyy, double *__restrict__ Gzz, double *__restrict__ Gxy, double *__restrict__ Gxz, double *__restrict__ Gyz, const int lxc, double *__restrict__ xc) { double *dwork, *Gwork, *xcorrWork, egrns, esig, xdiv; int i, ierr, ierr1, kmt, l1, l2, lag, lcref, nlag; //------------------------------------------------------------------------// ierr = 0; lcref = npgrns + npts - 1; if (lcref > lxc){return -1;} xcorrWork = memory_calloc64f(lcref); array_zeros64f_work(lxc, xc); if (luseEnvelope) { Gwork = memory_calloc64f(npgrns); dwork = memory_calloc64f(npts); ierr = signal_filter_envelope64f_work(npts, data, dwork); esig = cblas_dnrm2(npts, dwork, 1); } else { Gwork = NULL; dwork = data; esig = cblas_dnrm2(npts, data, 1); } // Loop on the Green's functions for (kmt=0; kmt<6; kmt++) { if (kmt == 0) { if (!luseEnvelope) { Gwork = Gxx; } else { signal_filter_envelope64f_work (npgrns, Gxx, Gwork); } } else if (kmt == 1) { if (!luseEnvelope) { Gwork = Gyy; } else { signal_filter_envelope64f_work (npgrns, Gyy, Gwork); } } else if (kmt == 2) { if (!luseEnvelope) { Gwork = Gzz; } else { signal_filter_envelope64f_work (npgrns, Gzz, Gwork); } } else if (kmt == 3) { if (!luseEnvelope) { Gwork = Gxy; } else { signal_filter_envelope64f_work (npgrns, Gxy, Gwork); } } else if (kmt == 4) { if (!luseEnvelope) { Gwork = Gxz; } else { signal_filter_envelope64f_work (npgrns, Gxz, Gwork); } } else { if (!luseEnvelope) { Gwork = Gyz; } else { signal_filter_envelope64f_work (npgrns, Gyz, Gwork); } } egrns = cblas_dnrm2(npgrns, Gwork, 1); ierr1 = signal_convolve_correlate64f_work(npts, dwork, npgrns, Gwork, CONVCOR_FULL, lcref, xcorrWork); if (ierr1 != 0) { if (ierr1 != 0) { fprintf(stderr, "%s: Error correlating kmt %d\n", __func__, kmt); } ierr = ierr + 1; } // sum in the result - absolute value handles polarity else { xdiv = 1.0; if (lnorm){xdiv = 1.0/(esig*egrns);} if (luseEnvelope) { #pragma omp simd for (i=0; i<lcref; i++) { xc[i] = xc[i] + xcorrWork[i]*xdiv; } } else { #pragma omp simd for (i=0; i<lcref; i++) { xc[i] = xc[i] + fabs(xcorrWork[i]*xdiv); //if (kmt == 5){printf("%e\n", xc[i]);} } } } } // Loop on green's functions // Compute the lag where the times range from [-npgrns:npts]. Hence, // lag = npgrns is the unlagged cross-correlation. if (maxShift < 0) { lag = array_argmax64f(lcref, xc, &ierr); } else { l1 = MAX(0, npgrns - maxShift); l2 = MIN(lcref - 1, npgrns + maxShift); nlag = l2 - l1 + 1; lag = l1 + array_argmax64f(nlag, &xc[l1], &ierr); } lag =-npgrns + lag; //printf("%d %d %d\n", lag, npgrns, npts); /* for (i=0; i<npts; i++) { printf("%e\n", data[i]); } for (i=0; i<npgrns; i++) { printf("%e %e %e %e %e %e\n", Gxx[i], Gyy[i], Gzz[i], Gxy[i], Gxz[i], Gyz[i]); } for (i=0; i<lcref; i++) { printf("%d %e\n",-npgrns+i, xc[i]); } printf("%d\n", lag); */ //getchar(); // Shift the greens' functions array_zeros64f_work(lcref, xcorrWork); shiftGreens(npgrns, lag, Gxx, xcorrWork); shiftGreens(npgrns, lag, Gyy, xcorrWork); shiftGreens(npgrns, lag, Gzz, xcorrWork); shiftGreens(npgrns, lag, Gxy, xcorrWork); shiftGreens(npgrns, lag, Gxz, xcorrWork); shiftGreens(npgrns, lag, Gyz, xcorrWork); if (luseEnvelope) { memory_free64f(&Gwork); memory_free64f(&dwork); } else { dwork = NULL; Gwork = NULL; } memory_free64f(&xcorrWork); return 0; } //============================================================================// /*! * @brief Utility function for use after the Green's functions have been * manually aligned to issue a measure of the alignment quality. * * @param[in] npts Number of points in data and Green's functions. * @param[in] luseEnvelope If true then cross-correlate the envelopes of * the waveforms. \n * Otherwise, cross-correlate the waveforms * themselves. In this case the absolute values * of the cross-correlation are used. * @param[in] lnorm If true then use a normalized cross-correlation * so that all waveforms can contribute equally. \n * Otherwise, use the non-normalized cross-correlation. * @param[in] data Observed waveforms. This is an array of dimension * [npts]. * @param[in] Gxx Aligned Gxx Green's function. This is an array of * dimension [npts]. * @param[in] Gyy Aligned Gyy Green's function. This is an array of * dimension [npts]. * @param[in] Gzz Aligned Gzz Green's function. This is an array of * dimension [npts]. * @param[in] Gxy Aligned Gxy Green's function. This is an array of * dimension [npts]. * @param[in] Gxz Aligned Gxz Green's function. This is an array of * dimension [npts]. * @param[in] Gyz Aligned Gyz Green's function. This is an array of * dimension [npts]. * * @param[out] ierr 0 indicates success. * * @result The zero-lag cross-correlation score of the Green's function to * data alignment. * * @author Ben Baker, ISTI * */ double prepmt_greens_scoreXCAlignment(const int npts, const bool luseEnvelope, const bool lnorm, const double *__restrict__ data, const double *__restrict__ Gxx, const double *__restrict__ Gyy, const double *__restrict__ Gzz, const double *__restrict__ Gxy, const double *__restrict__ Gxz, const double *__restrict__ Gyz, int *ierr) { double *dwork, *Gwork, egrns, esig, xcStack, xdiv; const double *G; int i; enum isclError_enum isclError; *ierr = 0; xcStack = 0.0; dwork = NULL; G = NULL; Gwork = memory_calloc64f(npts); if (luseEnvelope) { dwork = signal_filter_envelope64f(npts, data, &isclError); if (isclError != ISCL_SUCCESS) { fprintf(stderr, "%s: Error computing data envelope\n", __func__); *ierr = 1; return xcStack; } esig = cblas_dnrm2(npts, dwork, 1); } else { dwork = array_copy64f(npts, data, &isclError); if (isclError != ISCL_SUCCESS) { fprintf(stderr, "%s: Error copying data\n", __func__); *ierr = 1; return xcStack; } esig = cblas_dnrm2(npts, data, 1); } for (i=0; i<6; i++) { if (i == 0) { G = Gxx; } else if (i == 1) { G = Gyy; } else if (i == 2) { G = Gzz; } else if (i == 3) { G = Gxy; } else if (i == 4) { G = Gxz; } else if (i == 5) { G = Gyz; } if (luseEnvelope) { isclError = signal_filter_envelope64f_work(npts, G, Gwork); if (isclError != ISCL_SUCCESS) { fprintf(stderr, "%s: Error computing Grns envelope\n", __func__); *ierr = 1; return xcStack; } } else { isclError = array_copy64f_work(npts, G, Gwork); if (isclError != ISCL_SUCCESS) { fprintf(stderr, "%s: Error copying G to Gwork\n", __func__); *ierr = 1; return xcStack; } } egrns = cblas_dnrm2(npts, Gwork, 1); xdiv = 1.0; if (lnorm){xdiv = 1.0/(esig*egrns);} xdiv = xdiv*1.0/6.0; // Normalization term for sum if (luseEnvelope) { xcStack = xcStack + xdiv*cblas_ddot(npts, dwork, 1, Gwork, 1); } else { xcStack = xcStack + xdiv*fabs(cblas_ddot(npts, dwork, 1, Gwork, 1)); } G = NULL; } memory_free64f(&dwork); memory_free64f(&Gwork); return xcStack; } //============================================================================// static int getPrimaryArrival(const struct sacHeader_struct hdr, double *time, char phaseName[8]) { const enum sacHeader_enum timeVars[11] = {SAC_FLOAT_A, SAC_FLOAT_T0, SAC_FLOAT_T1, SAC_FLOAT_T2, SAC_FLOAT_T3, SAC_FLOAT_T4, SAC_FLOAT_T5, SAC_FLOAT_T6, SAC_FLOAT_T7, SAC_FLOAT_T8, SAC_FLOAT_T9}; const enum sacHeader_enum timeVarNames[11] = {SAC_CHAR_KA, SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3, SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7, SAC_CHAR_KT8, SAC_CHAR_KT9}; int i, ifound1, ifound2; memset(phaseName, 0, 8*sizeof(char)); for (i=0; i<11; i++) { ifound1 = sacio_getFloatHeader(timeVars[i], hdr, time); ifound2 = sacio_getCharacterHeader(timeVarNames[i], hdr, phaseName); if (ifound1 == 0 && ifound2 == 0){return 0;} } fprintf(stderr, "%s: Failed to get primary pick\n", __func__); *time =-12345.0; memset(phaseName, 0, 8*sizeof(char)); strcpy(phaseName, "-12345"); return -1; } //============================================================================// static int getPrimaryArrivalNoPolarity(const struct sacHeader_struct hdr, double *time, char phaseName[8]) { int ierr; size_t lenos; ierr = getPrimaryArrival(hdr, time, phaseName); if (ierr == 0) { lenos = strlen(phaseName); if (lenos > 0) { if (phaseName[lenos-1] == '+' || phaseName[lenos-1] == '-') { phaseName[lenos-1] = '\0'; } } } return ierr; } //============================================================================// static void shiftGreens(const int npgrns, const int lag, double *__restrict__ G, double *__restrict__ work) { int ncopy; if (lag == 0){return;} array_copy64f_work(npgrns, G, work); array_zeros64f_work(npgrns, G); if (lag > 0) { ncopy = npgrns - lag; array_copy64f_work(ncopy, work, &G[lag]); } else { ncopy = npgrns + lag; array_copy64f_work(ncopy, &work[-lag], G); } return; }
{ "alphanum_fraction": 0.466284587, "avg_line_length": 37.8628461043, "ext": "c", "hexsha": "fa76bdcee250062b2a7319dc2628eb548cf8782c", "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": "prepmt/greens.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": "prepmt/greens.c", "max_line_length": 154, "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": "prepmt/greens.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 14695, "size": 58801 }
#include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "cconfigspace_internal.h" #include "distribution_internal.h" struct _ccs_distribution_normal_data_s { _ccs_distribution_common_data_t common_data; ccs_float_t mu; ccs_float_t sigma; ccs_scale_type_t scale_type; ccs_numeric_t quantization; int quantize; }; typedef struct _ccs_distribution_normal_data_s _ccs_distribution_normal_data_t; static ccs_result_t _ccs_distribution_del(ccs_object_t o) { (void)o; return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_normal_get_bounds(_ccs_distribution_data_t *data, ccs_interval_t *interval_ret); static ccs_result_t _ccs_distribution_normal_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t *values); static ccs_result_t _ccs_distribution_normal_strided_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, size_t stride, ccs_numeric_t *values); static ccs_result_t _ccs_distribution_normal_soa_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t **values); static _ccs_distribution_ops_t _ccs_distribution_normal_ops = { { &_ccs_distribution_del }, &_ccs_distribution_normal_samples, &_ccs_distribution_normal_get_bounds, &_ccs_distribution_normal_strided_samples, &_ccs_distribution_normal_soa_samples }; static ccs_result_t _ccs_distribution_normal_get_bounds(_ccs_distribution_data_t *data, ccs_interval_t *interval_ret) { _ccs_distribution_normal_data_t *d = (_ccs_distribution_normal_data_t *)data; const ccs_numeric_type_t data_type = d->common_data.data_types[0]; const ccs_scale_type_t scale_type = d->scale_type; const ccs_numeric_t quantization = d->quantization; const int quantize = d->quantize; ccs_numeric_t l; ccs_bool_t li; ccs_numeric_t u; ccs_bool_t ui; if (scale_type == CCS_LOGARITHMIC) { if (data_type == CCS_NUM_FLOAT) { if (quantize) { l.f = quantization.f; li = CCS_TRUE; } else { l.f = 0.0; li = CCS_FALSE; } u.f = CCS_INFINITY; ui = CCS_FALSE; } else { if (quantize) { l.i = quantization.i; u.i = (CCS_INT_MAX/quantization.i)*quantization.i; } else { l.i = 1; u.i = CCS_INT_MAX; } li = CCS_TRUE; ui = CCS_TRUE; } } else { if (data_type == CCS_NUM_FLOAT) { l.f = -CCS_INFINITY; li = CCS_FALSE; u.f = CCS_INFINITY; ui = CCS_FALSE; } else { if (quantize) { l.i = (CCS_INT_MIN/quantization.i)*quantization.i; u.i = (CCS_INT_MAX/quantization.i)*quantization.i; } else { l.i = CCS_INT_MIN; u.i = CCS_INT_MAX; } li = CCS_TRUE; ui = CCS_TRUE; } } interval_ret->type = data_type; interval_ret->lower = l; interval_ret->upper = u; interval_ret->lower_included = li; interval_ret->upper_included = ui; return CCS_SUCCESS; } static inline ccs_result_t _ccs_distribution_normal_samples_float(gsl_rng *grng, const ccs_scale_type_t scale_type, const ccs_float_t quantization, const ccs_float_t mu, const ccs_float_t sigma, const int quantize, size_t num_values, ccs_float_t *values) { size_t i; if (scale_type == CCS_LOGARITHMIC && quantize) { ccs_float_t lq = log(quantization*0.5); if (mu - lq >= 0.0) //at least 50% chance to get a valid value for (i = 0; i < num_values; i++) do { values[i] = gsl_ran_gaussian(grng, sigma) + mu; } while (values[i] < lq); else //use tail distribution for (i = 0; i < num_values; i++) values[i] = gsl_ran_gaussian_tail(grng, lq - mu, sigma) + mu; } else for (i = 0; i < num_values; i++) values[i] = gsl_ran_gaussian(grng, sigma) + mu; if (scale_type == CCS_LOGARITHMIC) for (i = 0; i < num_values; i++) values[i] = exp(values[i]); if (quantize) { ccs_float_t rquantization = 1.0 / quantization; for (i = 0; i < num_values; i++) values[i] = round(values[i] * rquantization) * quantization; } return CCS_SUCCESS; } static inline ccs_result_t _ccs_distribution_normal_samples_int(gsl_rng *grng, const ccs_scale_type_t scale_type, const ccs_int_t quantization, const ccs_float_t mu, const ccs_float_t sigma, const int quantize, size_t num_values, ccs_numeric_t *values) { size_t i; ccs_float_t q; if (quantize) q = quantization*0.5; else q = 0.5; if (scale_type == CCS_LOGARITHMIC) { ccs_float_t lq = log(q); if (mu - lq >= 0.0) for (i = 0; i < num_values; i++) do { do { values[i].f = gsl_ran_gaussian(grng, sigma) + mu; } while (values[i].f < lq); values[i].f = exp(values[i].f); } while (CCS_UNLIKELY(values[i].f - q > (ccs_float_t)CCS_INT_MAX)); else for (i = 0; i < num_values; i++) do { values[i].f = gsl_ran_gaussian_tail(grng, lq - mu, sigma) + mu; values[i].f = exp(values[i].f); } while (CCS_UNLIKELY(values[i].f - q > (ccs_float_t)CCS_INT_MAX)); } else for (i = 0; i < num_values; i++) do { values[i].f = gsl_ran_gaussian(grng, sigma) + mu; } while (CCS_UNLIKELY(values[i].f - q > (ccs_float_t)CCS_INT_MAX || values[i].f + q < (ccs_float_t)CCS_INT_MIN)); if (quantize) { ccs_float_t rquantization = 1.0 / quantization; for (i = 0; i < num_values; i++) values[i].i = (ccs_int_t)round(values[i].f * rquantization) * quantization; } else for (i = 0; i < num_values; i++) values[i].i = round(values[i].f); return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_normal_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t *values) { _ccs_distribution_normal_data_t *d = (_ccs_distribution_normal_data_t *)data; const ccs_numeric_type_t data_type = d->common_data.data_types[0]; const ccs_scale_type_t scale_type = d->scale_type; const ccs_numeric_t quantization = d->quantization; const ccs_float_t mu = d->mu; const ccs_float_t sigma = d->sigma; const int quantize = d->quantize; gsl_rng *grng; CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng)); if (data_type == CCS_NUM_FLOAT) return _ccs_distribution_normal_samples_float(grng, scale_type, quantization.f, mu, sigma, quantize, num_values, (ccs_float_t*) values); else return _ccs_distribution_normal_samples_int(grng, scale_type, quantization.i, mu, sigma, quantize, num_values, values); } static inline ccs_result_t _ccs_distribution_normal_strided_samples_float(gsl_rng *grng, const ccs_scale_type_t scale_type, const ccs_float_t quantization, const ccs_float_t mu, const ccs_float_t sigma, const int quantize, size_t num_values, size_t stride, ccs_float_t *values) { size_t i; if (scale_type == CCS_LOGARITHMIC && quantize) { ccs_float_t lq = log(quantization*0.5); if (mu - lq >= 0.0) //at least 50% chance to get a valid value for (i = 0; i < num_values; i++) do { values[i*stride] = gsl_ran_gaussian(grng, sigma) + mu; } while (values[i*stride] < lq); else //use tail distribution for (i = 0; i < num_values; i++) values[i*stride] = gsl_ran_gaussian_tail(grng, lq - mu, sigma) + mu; } else for (i = 0; i < num_values; i++) values[i*stride] = gsl_ran_gaussian(grng, sigma) + mu; if (scale_type == CCS_LOGARITHMIC) for (i = 0; i < num_values; i++) values[i*stride] = exp(values[i*stride]); if (quantize) { ccs_float_t rquantization = 1.0 / quantization; for (i = 0; i < num_values; i++) values[i*stride] = round(values[i*stride] * rquantization) * quantization; } return CCS_SUCCESS; } static inline ccs_result_t _ccs_distribution_normal_strided_samples_int(gsl_rng *grng, const ccs_scale_type_t scale_type, const ccs_int_t quantization, const ccs_float_t mu, const ccs_float_t sigma, const int quantize, size_t num_values, size_t stride, ccs_numeric_t *values) { size_t i; ccs_float_t q; if (quantize) q = quantization*0.5; else q = 0.5; if (scale_type == CCS_LOGARITHMIC) { ccs_float_t lq = log(q); if (mu - lq >= 0.0) for (i = 0; i < num_values; i++) do { do { values[i*stride].f = gsl_ran_gaussian(grng, sigma) + mu; } while (values[i*stride].f < lq); values[i*stride].f = exp(values[i*stride].f); } while (CCS_UNLIKELY(values[i*stride].f - q > (ccs_float_t)CCS_INT_MAX)); else for (i = 0; i < num_values; i++) do { values[i*stride].f = gsl_ran_gaussian_tail(grng, lq - mu, sigma) + mu; values[i*stride].f = exp(values[i*stride].f); } while (CCS_UNLIKELY(values[i*stride].f - q > (ccs_float_t)CCS_INT_MAX)); } else for (i = 0; i < num_values; i++) do { values[i*stride].f = gsl_ran_gaussian(grng, sigma) + mu; } while (CCS_UNLIKELY(values[i*stride].f - q > (ccs_float_t)CCS_INT_MAX || values[i*stride].f + q < (ccs_float_t)CCS_INT_MIN)); if (quantize) { ccs_float_t rquantization = 1.0 / quantization; for (i = 0; i < num_values; i++) values[i*stride].i = (ccs_int_t)round(values[i*stride].f * rquantization) * quantization; } else for (i = 0; i < num_values; i++) values[i*stride].i = round(values[i*stride].f); return CCS_SUCCESS; } static ccs_result_t _ccs_distribution_normal_strided_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, size_t stride, ccs_numeric_t *values) { _ccs_distribution_normal_data_t *d = (_ccs_distribution_normal_data_t *)data; const ccs_numeric_type_t data_type = d->common_data.data_types[0]; const ccs_scale_type_t scale_type = d->scale_type; const ccs_numeric_t quantization = d->quantization; const ccs_float_t mu = d->mu; const ccs_float_t sigma = d->sigma; const int quantize = d->quantize; gsl_rng *grng; CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng)); if (data_type == CCS_NUM_FLOAT) return _ccs_distribution_normal_strided_samples_float(grng, scale_type, quantization.f, mu, sigma, quantize, num_values, stride, (ccs_float_t*) values); else return _ccs_distribution_normal_strided_samples_int(grng, scale_type, quantization.i, mu, sigma, quantize, num_values, stride, values); } static ccs_result_t _ccs_distribution_normal_soa_samples(_ccs_distribution_data_t *data, ccs_rng_t rng, size_t num_values, ccs_numeric_t **values) { if (*values) return _ccs_distribution_normal_samples(data, rng, num_values, *values); return CCS_SUCCESS; } extern ccs_result_t ccs_create_normal_distribution(ccs_numeric_type_t data_type, ccs_float_t mu, ccs_float_t sigma, ccs_scale_type_t scale_type, ccs_numeric_t quantization, ccs_distribution_t *distribution_ret) { CCS_CHECK_PTR(distribution_ret); if (data_type != CCS_NUM_FLOAT && data_type != CCS_NUM_INTEGER) return -CCS_INVALID_TYPE; if (scale_type != CCS_LINEAR && scale_type != CCS_LOGARITHMIC) return -CCS_INVALID_SCALE; if (data_type == CCS_NUM_INTEGER && quantization.i < 0 ) return -CCS_INVALID_VALUE; if (data_type == CCS_NUM_FLOAT && quantization.f < 0.0 ) return -CCS_INVALID_VALUE; uintptr_t mem = (uintptr_t)calloc(1, sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_normal_data_t) + sizeof(ccs_numeric_type_t)); if (!mem) return -CCS_OUT_OF_MEMORY; ccs_distribution_t distrib = (ccs_distribution_t)mem; _ccs_object_init(&(distrib->obj), CCS_DISTRIBUTION, (_ccs_object_ops_t *)&_ccs_distribution_normal_ops); _ccs_distribution_normal_data_t * distrib_data = (_ccs_distribution_normal_data_t *)(mem + sizeof(struct _ccs_distribution_s)); distrib_data->common_data.data_types = (ccs_numeric_type_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_normal_data_t)); distrib_data->common_data.type = CCS_NORMAL; distrib_data->common_data.dimension = 1; distrib_data->common_data.data_types[0] = data_type; distrib_data->scale_type = scale_type; distrib_data->quantization = quantization; distrib_data->mu = mu; distrib_data->sigma = sigma; if (data_type == CCS_NUM_FLOAT) { if (quantization.f != 0.0) distrib_data->quantize = 1; } else { if (quantization.i != 0) distrib_data->quantize = 1; } distrib->data = (_ccs_distribution_data_t *)distrib_data; *distribution_ret = distrib; return CCS_SUCCESS; } extern ccs_result_t ccs_normal_distribution_get_parameters(ccs_distribution_t distribution, ccs_float_t *mu_ret, ccs_float_t *sigma_ret, ccs_scale_type_t *scale_type_ret, ccs_numeric_t *quantization_ret) { CCS_CHECK_DISTRIBUTION(distribution, CCS_NORMAL); if (!mu_ret && !sigma_ret && !scale_type_ret && !quantization_ret) return -CCS_INVALID_VALUE; _ccs_distribution_normal_data_t * data = (_ccs_distribution_normal_data_t *)distribution->data; if (mu_ret) *mu_ret = data->mu; if (sigma_ret) *sigma_ret = data->sigma; if (scale_type_ret) *scale_type_ret = data->scale_type; if (quantization_ret) *quantization_ret = data->quantization; return CCS_SUCCESS; }
{ "alphanum_fraction": 0.5435438991, "avg_line_length": 40.8983050847, "ext": "c", "hexsha": "70bf285405a4d99cfef966c451a85a63cc856e33", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_path": "src/distribution_normal.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_path": "src/distribution_normal.c", "max_line_length": 150, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_path": "src/distribution_normal.c", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "num_tokens": 4037, "size": 16891 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #define qh_QHimport #include <libqhull_r/qhull_ra.h> void print_summary(qhT *qh); double findDelaunay(qhT *qh, int dim, coordT *TargetCoord); double findNearestVertices(qhT *qh, int dim, coordT *TargetCoord); double findNearestCentrum(qhT *qh, int dim, coordT *TargetCoord); void obtain_convex_h_qhull(int n_data, double *ef2cvh, int *x, double *y, int NCatDim, int *nCat_min, int *nCat_max, double *E0, char *qhullflags) { int i, j, k, l, nid, Ndim; double tmp; Ndim = NCatDim - 1; // because nV is dependent on other nCats printf("Convex hull is created using qhull.\n"); printf("Input data\n"); printf("---------------------------\n"); printf(" nL nN nM nC nV Ef\n"); for (i=0;i<n_data;i++) { for (j=0;j<NCatDim;j++) printf("%4d ",x[NCatDim*i+j]); printf(" % .4f\n",y[i]); } printf("---------------------------\n"); // Convex Hull by calling qhull int DIM; int SIZEcube, SIZEdiamond, TOTpoints; int dim; /* dimension of points */ int numpoints; /* number of points */ DIM = Ndim + 1; /* because of ef as one additional dimension */ dim = DIM; TOTpoints = n_data; numpoints= n_data; // coordT points[(DIM+1)*TOTpoints]; /* array of coordinates for each point */ coordT points[DIM*TOTpoints]; /* array of coordinates for each point */ coordT *rows[TOTpoints]; boolT ismalloc= False; /* True if qhull should free points in qh_freeqhull() or reallocation */ char flags[250]; /* option flags for qhull, see qh-quick.htm */ FILE *outfile= stdout; /* output from qh_produce_output() use NULL to skip qh_produce_output() */ FILE *errfile= stderr; /* error messages from qhull code */ int exitcode; /* 0 if no error from qhull */ facetT *facet; /* set by FORALLfacets */ int curlong, totlong; /* memory remaining after qh_memfreeshort */ qhT qh_qh; /* Qhull's data structure. First argument of most calls */ qhT *qh= &qh_qh; QHULL_LIB_CHECK qh_zero(qh, errfile); printf( "\ncompute %d-d convexhull, options:%s\n", dim, qhullflags); // sprintf(flags, "qhull o Qx "); // Error generated sprintf(flags, "qhull o %s ",qhullflags); // sprintf(flags, "qhull o QJ "); // sprintf(flags, "qhull o C-0 "); // Error generated // sprintf(flags, "qhull o C-n "); // Error generated // sprintf(flags, "qhull o Cn "); // Error generated // sprintf(flags, "qhull o Qt "); // Error generated // sprintf(flags, "qhull o Qx C-n "); // Error generated for (i=0;i<n_data;i++) { //size of points is n_data by (Ndim+1) for (j=0;j<Ndim;j++) //size of x is n_data by Ndim points[dim*i+j] = x[NCatDim*i+j]; points[dim*i+Ndim] = y[i]; } for (i=0;i<numpoints;i++) //size of rows is n_data x (Ndim+1) rows[i]= points+dim*i; // for (i=numpoints; i--; ) // rows[i]= points+dim*i; qh_printmatrix(qh, outfile, "input", rows, numpoints, dim); exitcode= qh_new_qhull(qh, dim, numpoints, points, ismalloc, flags, outfile, errfile); if (!exitcode) { /* if no error */ print_summary(qh); printf( "\nThe relative Ef w.r.t. the convex hull:\n", dim); exitcode= setjmp(qh->errexit); if (!exitcode) { /* Trap Qhull errors in findDelaunay(). Without the setjmp(), Qhull will exit() after reporting an error */ qh->NOerrexit= False; for (i=0;i<numpoints;i++) { // ef2cvh[i] = findDelaunay(qh, DIM, rows[i]); // ef2cvh[i] = findNearestVertices(qh, DIM, rows[i]); ef2cvh[i] = findNearestCentrum(qh, DIM, rows[i]); printf("ef2cvh[%d] = % .4e\n", i, ef2cvh[i]); } } qh->NOerrexit= True; } qh_freeqhull(qh, !qh_ALL); /* free long memory */ qh_memfreeshort(qh, &curlong, &totlong); /* free short memory and memory allocator */ if (curlong || totlong) fprintf(errfile, "qhull internal warning (user_eg, #2): did not free %d bytes of long memory (%d pieces)\n", totlong, curlong); } void print_summary(qhT *qh) { facetT *facet; vertexT *vertex; int k; printf("\n%d facets with normals:\n", qh->num_facets); FORALLfacets { for (k=0; k < qh->hull_dim; k++) { printf("%6.2g ", facet->normal[k]); // printf("", facet->vertices); } printf("\n"); } printf("\n%d vertices:\n",qh->num_vertices); FORALLvertices { qh_printvertex(qh, qh->fout, vertex); } } double findDelaunay(qhT *qh, int dim, coordT *TargetCoord) { int j, k; coordT tmppoint[ 100]; boolT isoutside; realT bestdist; facetT *facet; vertexT *vertex, **vertexp; for (k= 0; k < dim; k++) tmppoint[k]= TargetCoord[k]; qh_setdelaunay(qh, dim+1, 1, tmppoint); facet= qh_findbestfacet(qh, tmppoint, qh_ALL, &bestdist, &isoutside); if (facet->tricoplanar) { fprintf(stderr, "findDelaunay: not implemented for triangulated, non-simplicial Delaunay regions (tricoplanar facet, f%d).\n", facet->id); qh_errexit(qh, qh_ERRqhull, facet, NULL); } for (k= 0; k < dim-1; k++) printf("% .3f ",tmppoint[k]); printf("% .3f, ",tmppoint[dim-1]); printf("facet id: %d\n",facet->id); /* FOREACHvertex_(facet->vertices) { for (k=0; k < dim; k++) printf("%5.3f ", vertex->point[k]); printf("vertex id: %d, point id: %d\n", vertex->id, qh_pointid(qh, vertex->point)); }*/ FOREACHvertex_(facet->vertices) { printf("vertex id: %d, point id: %d\n", vertex->id, qh_pointid(qh, vertex->point)); } gsl_matrix * A = gsl_matrix_alloc (dim,dim); gsl_matrix * V = gsl_matrix_alloc (dim,dim); gsl_vector * S = gsl_vector_alloc (dim); gsl_vector * work = gsl_vector_alloc (dim); gsl_vector * b = gsl_vector_alloc (dim); gsl_vector * x = gsl_vector_alloc (dim); j= 0; FOREACHvertex_(facet->vertices) { for (k= 0; k < dim; k++) gsl_matrix_set (A,k,j, vertex->point[k]); gsl_vector_set(b,j,tmppoint[j]); j++; } double ef[dim]; // dismiss the last row corresponding to Ef // & apply the constriction on the coefficients sum_x_i = 1 for (k= 0; k < dim; k++) { ef[k] = gsl_matrix_get (A,dim-1,k); gsl_matrix_set (A,dim-1,k,1.0); } gsl_vector_set(b,dim-1,2.0); gsl_linalg_SV_decomp(A, V, S, work); gsl_linalg_SV_solve (A, V, S, b, x); double ef_cvh = 0.0; for (k= 0; k < dim; k++) ef_cvh += gsl_vector_get(x,k)*ef[k]; gsl_matrix_free(A); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(b); gsl_vector_free(x); return(TargetCoord[dim-1]-ef_cvh); } double findNearestVertices(qhT *qh, int dim, coordT *TargetCoord) { int i, j, k; int nid; double ef_cvh; double tmp; double tmppoint[dim]; boolT isoutside; realT bestdist; facetT *facet; vertexT *vertex, **vertexp; nid = qh->num_vertices; for (k= 0; k < dim; k++) tmppoint[k]= TargetCoord[k]; double verticespoint[nid][dim]; j = 0; FORALLvertices { for (k= 0; k < dim; k++) verticespoint[j][k] = vertex->point[k]; j++; } double dij2[nid]; int ids[nid]; for (j= 0; j< nid; j++) { tmp = 0.0; for (k= 0; k < dim-1; k++) { //ef is excluded for configurational coordinate tmp += pow(verticespoint[j][k] - tmppoint[k],2); } dij2[j] = tmp; ids[j] = j; } sort_array_ids(dij2,ids,nid); gsl_matrix * A = gsl_matrix_alloc (dim,dim); gsl_matrix * V = gsl_matrix_alloc (dim,dim); gsl_vector * S = gsl_vector_alloc (dim); gsl_vector * work = gsl_vector_alloc (dim); gsl_vector * b = gsl_vector_alloc (dim); gsl_vector * x = gsl_vector_alloc (dim); if (dij2[0]==0.0) ef_cvh = 0.0; else { for (j= 0; j< dim; j++) { for (k= 0; k < dim; k++) gsl_matrix_set (A,k,j,verticespoint[ids[j]][k]); gsl_vector_set(b,j,tmppoint[j]); } for (k= 0; k < dim; k++) { //dismiss the last row corresponding to ef gsl_matrix_set (A,dim-1,k,1.0); } gsl_vector_set(b,dim-1,2.0); //dismiss the last row corresponding to ef gsl_linalg_SV_decomp(A, V, S, work); gsl_linalg_SV_solve (A, V, S, b, x); tmp = 0.0; for (j= 0; j< dim; j++) tmp += gsl_vector_get(x,j)*verticespoint[ids[j]][dim-1]; ef_cvh = tmppoint[dim-1]-tmp; } gsl_matrix_free(A); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(b); gsl_vector_free(x); return(ef_cvh); } double findNearestCentrum(qhT *qh, int dim, coordT *TargetCoord) { int i, j, k; int nf, nv; double ef_cvh; double tmp; double tmppoint[dim]; boolT isoutside; realT bestdist; facetT *facet; vertexT *vertex, **vertexp; pointT *centrum; nf = qh->num_facets; nv = qh->num_vertices; for (k= 0; k < dim; k++) tmppoint[k]= TargetCoord[k]; double facet_normal[nf][dim]; double facet_center[nf][dim]; int facet_id[nf]; int num_lowerhullfacets; j = 0; FORALLfacets { if (facet->normal[dim-1] < 0.0) {//is the slope in ef direction negative? for (k= 0; k < dim; k++) { facet_normal[j][k] = facet->normal[k]; if (qh->CENTERtype == qh_AScentrum) centrum= facet->center; else centrum= qh_getcentrum(qh, facet); facet_center[j][k] = centrum[k]; facet_id[j] = facet->id; } j++; } } num_lowerhullfacets = j; double dij2[num_lowerhullfacets]; int ids[num_lowerhullfacets]; for (j= 0; j< num_lowerhullfacets; j++) { tmp = 0.0; for (k= 0; k < dim-1; k++) { //ef is excluded for configurational coordinate tmp += pow(facet_center[j][k] - tmppoint[k],2); } dij2[j] = tmp; ids[j] = j; } sort_array_ids(dij2,ids,num_lowerhullfacets); int projectedfacet = facet_id[ids[0]]; double vertices_point[dim][dim]; FORALLfacets { if (facet->id == projectedfacet) { j = 0; FOREACHvertex_(facet->vertices) { for (k=0; k < dim; k++) vertices_point[j][k] = vertex->point[k]; j++; } } } gsl_matrix * A = gsl_matrix_alloc (dim,dim); gsl_matrix * V = gsl_matrix_alloc (dim,dim); gsl_vector * S = gsl_vector_alloc (dim); gsl_vector * work = gsl_vector_alloc (dim); gsl_vector * b = gsl_vector_alloc (dim); gsl_vector * x = gsl_vector_alloc (dim); for (j= 0; j< dim; j++) { for (k= 0; k < dim; k++) gsl_matrix_set (A,k,j,vertices_point[j][k]); gsl_vector_set(b,j,tmppoint[j]); } for (k= 0; k < dim; k++) { //dismiss the last row corresponding to ef gsl_matrix_set (A,dim-1,k,1.0); } gsl_vector_set(b,dim-1,1.0); //dismiss the last row corresponding to ef printf("A:\n"); for (j= 0; j< dim; j++) { for (k= 0; k < dim; k++) printf("%g ", gsl_matrix_get (A,j,k)); printf("\n"); } printf("b:\n"); for (j= 0; j< dim; j++) printf("%g\n", gsl_vector_get(b,j)); gsl_linalg_SV_decomp(A, V, S, work); gsl_linalg_SV_solve (A, V, S, b, x); printf("solution:\n"); for (j= 0; j< dim; j++) printf("%g\n", gsl_vector_get(x,j)); // need to check if the components of x is in [0,2] for (j= 0; j< dim; j++) { tmp = gsl_vector_get(x,j); if (tmp < -0.1 || tmp > 1.0) { printf("\n%d-component of x is %f, out of range\n", j, tmp); exit(-1); } } tmp = 0.0; for (j= 0; j< dim; j++) tmp += gsl_vector_get(x,j)*vertices_point[j][dim-1]; ef_cvh = tmppoint[dim-1]-tmp; gsl_matrix_free(A); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); gsl_vector_free(b); gsl_vector_free(x); return(ef_cvh); }
{ "alphanum_fraction": 0.549937578, "avg_line_length": 32.3636363636, "ext": "c", "hexsha": "2699eb7c3df4abd88f9a995b864e885f75e19e3e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "eunseok-lee/spin_atom_CE3", "max_forks_repo_path": "src_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "eunseok-lee/spin_atom_CE3", "max_issues_repo_path": "src_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_line_length": 148, "max_stars_count": null, "max_stars_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "eunseok-lee/spin_atom_CE3", "max_stars_repo_path": "src_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3950, "size": 12816 }
#ifndef _PROBABILITY_H_ #define _PROBABILITY_H_ #include <gsl/gsl_rng.h> // Non-uniform distributions: //There are a HUGE variety of distributions to choose from, which are // documented at the gsl website. #include <gsl/gsl_randist.h> // Seeding: #include <sys/time.h> //When using ANY gsl code, must add -lgsl -lgslcblas [-lm ???] to compile lines //USE_LINK_FLAG -lgsl -lgslcblas //RandGen is a virtual class. Use it in function definitions, // but when DECLARING a random number generator, use one of its derived // classes, such as gsl_RandGen. #define UNUSED_ARGUMENT(x) (void)x class RandGen { public: //Create a random number generator with Seed generated by system clock: RandGen() {} //Create a random number generator, and specify seed RandGen(const long & seed) {UNUSED_ARGUMENT(seed);} virtual ~RandGen() {} //uniform double on [0, 1): virtual double uniform(void) = 0; //uniform double on (0, 1): virtual double openUniform(void) = 0; //unsigned long int on [0, 1, 2, ..., n - 1]: virtual unsigned long unsignedInt(const unsigned long & n) = 0; // bool, true with probability p, false with probability 1-p: virtual bool bernoulli(const double & p) = 0; //exponentially distributed, p(x) ~ exp(-x/mu) virtual double exponential(const double & mu) = 0; //gaussian double with zero mean and standard deviation sigma: virtual double gaussian(const double & sigma) = 0; //poisson unsigned int with mean Mu: virtual unsigned int poisson(const double & mu) = 0; //binomial unsigned int for n trials with probability P of success virtual unsigned int binomial(const double & p, unsigned intnN) = 0; }; class GslRandGen : public RandGen { public: GslRandGen(); GslRandGen(const long & seed); virtual ~GslRandGen(); //uniform double on [0, 1): virtual double uniform(void); //uniform double on (0, 1): virtual double openUniform(void); //unsigned long int on [0, 1, 2, ..., n - 1]: virtual unsigned long unsignedInt(const unsigned long & n); // bool, true with probability p, false with probability 1-p: bool bernoulli(const double & p); //exponentially distributed, p(x) ~ exp(-x/mu) double exponential(const double & mu); //gaussian double with zero mean and standard deviation sigma: double gaussian(const double & sigma); //poisson unsigned int with mean Mu: unsigned int poisson(const double & mu); //binomial unsigned int for n trials with probability P of success unsigned int binomial(const double & p, unsigned intnN); private: gsl_rng* r; static bool firstInit; }; #endif
{ "alphanum_fraction": 0.7099884304, "avg_line_length": 31.6219512195, "ext": "h", "hexsha": "326c075a3511cb5559a9f3e269f1b49dafd2c44d", "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": "8f5115cd700759dea3b85a3b2214ba4f5dc06a32", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "TedBrookings/Brookings-et-al-2014", "max_forks_repo_path": "fitneuron/include/probability.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8f5115cd700759dea3b85a3b2214ba4f5dc06a32", "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": "TedBrookings/Brookings-et-al-2014", "max_issues_repo_path": "fitneuron/include/probability.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "8f5115cd700759dea3b85a3b2214ba4f5dc06a32", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "TedBrookings/Brookings-et-al-2014", "max_stars_repo_path": "fitneuron/include/probability.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 693, "size": 2593 }
/* * 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 allvars.h * \brief header file of allvars.c. */ #ifndef _ALLVARS_H #define _ALLVARS_H #include <stdio.h> #include <stdlib.h> #include <float.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_interp.h> /*! \def GRAVITY * \brief Gravitational constant. * \def SOLAR_MASS * \brief Solar mass. * \def C * \brief speed of light. * \def SEC_PER_YEAR * \brief seconds per year. * \def CM_PER_LD * \brief light day in centimeter. * \def PI * \brief Pi. * \def BRAINS_MAX_STR_LENGTH * \brief maximum string length. */ #define GRAVITY 6.672e-8 #define SOLAR_MASS 1.989e33 #define C 2.9979e10 #define SEC_PER_YEAR 3.155e7 #define CM_PER_LD (C*8.64e4) #define CM_PER_PC (3.08567758e+18) #define CM_PER_MPC (3.08567758e+24) #define PI M_PI #define BRAINS_MAX_STR_LENGTH (256) #define EPS (DBL_MIN) /* epsilon of the machine as in Matlab */ /* for PARDICT */ #define MAXTAGS 300 #define DOUBLE 1 #define STRING 2 #define INT 3 enum PRIOR_TYPE {GAUSSIAN=1, UNIFORM=2}; /* variables for MPICH */ extern int thistask, totaltask, namelen; extern int roottask; extern char proc_name[MPI_MAX_PROCESSOR_NAME]; /*! \struct PARSET * \brief the configuration parameters. */ typedef struct { char param_file[BRAINS_MAX_STR_LENGTH]; char continuum_file[BRAINS_MAX_STR_LENGTH], line_file[BRAINS_MAX_STR_LENGTH], line2d_file[BRAINS_MAX_STR_LENGTH], pcon_out_file[BRAINS_MAX_STR_LENGTH], pline_out_file[BRAINS_MAX_STR_LENGTH], pline2d_out_file[BRAINS_MAX_STR_LENGTH], pline2d_data_out_file[BRAINS_MAX_STR_LENGTH], cloud_out_file[BRAINS_MAX_STR_LENGTH], tran_out_file[BRAINS_MAX_STR_LENGTH], tran2d_out_file[BRAINS_MAX_STR_LENGTH], tran2d_data_out_file[BRAINS_MAX_STR_LENGTH]; char file_dir[BRAINS_MAX_STR_LENGTH]; int flag_dim; int flag_trend, flag_trend_diff; int n_con_recon, n_line_recon, n_vel_recon; int n_tau; double rcloud_max, time_back; int flag_blrmodel; int n_cloud_per_task, n_vel_per_cloud; int flag_save_clouds; int flag_InstRes; double InstRes, InstRes_err; char file_instres[BRAINS_MAX_STR_LENGTH]; int num_particles; char str_par_fix[BRAINS_MAX_STR_LENGTH], str_par_fix_val[BRAINS_MAX_STR_LENGTH]; int flag_narrowline; double flux_narrowline, width_narrowline, shift_narrowline; double flux_narrowline_err, width_narrowline_err, shift_narrowline_err; int flag_linecenter; double linecenter_err; int flag_postprc; int flag_restart; int flag_sample_info; int flag_temp; int flag_exam_prior; int flag_rng_seed, rng_seed; int flag_fixvar; int flag_nonlinear; int flag_force_update; int flag_force_run; int flag_con_sys_err, flag_line_sys_err; double temperature; int flag_help, flag_end; int flag_para_name; double redshift; double linecenter; #ifdef SA char sa_file[BRAINS_MAX_STR_LENGTH]; int flag_sa_blrmodel, flag_sa_par_mutual; double sa_linecenter; double sa_InstRes; char sa_str_par_fix[BRAINS_MAX_STR_LENGTH], sa_str_par_fix_val[BRAINS_MAX_STR_LENGTH]; int n_sa_vel_recon, n_sa_base_recon; #endif }PARSET; extern PARSET parset; typedef struct { int id; void *addr; char tag[50]; int isset; }PARDICT; extern PARDICT *pardict; extern int num_pardict; extern double VelUnit, C_Unit; extern int n_con_data, n_line_data, n_vel_data, n_vel_data_incr, n_vel_data_ext, n_con_max; extern double *Tcon_data, *Fcon_data, *Fcerrs_data; extern double *Tline_data, *Fline_data, *Flerrs_data; extern double *Vline_data, *Fline2d_data, *Flerrs2d_data, *Wline_data; extern double *Vline_data_ext, *Wline_data_ext; extern double con_scale, line_scale; extern double con_error_mean, line_error_mean, line_error_mean_sq; extern char dnest_options_file[BRAINS_MAX_STR_LENGTH]; extern int which_parameter_update, which_particle_update; // which parameter and particle to be updated extern int which_level_update; extern double *limits; // external from dnest /* continuum reconstruction */ extern int nq; extern double *Tcon, *Fcon, *Fcerrs, *Fcon_rm; extern double Tcon_min, Tcon_max; extern double *PSmat, *USmat, *PSmat_data; extern double *PCmat_data, *IPCmat_data, *PQmat, *PEmat1, *PEmat2; extern double *workspace, *workspace_uv; extern double *var_param, *var_param_std; extern double logz_con; extern double *Larr_data, *Larr_rec; extern double *pow_Tcon_data; extern double Tspan_data, Tspan_data_con, Tcad_data, Tmed_data; /* line reconstruction */ extern double *Fline_at_data; extern double *Tline, *Fline, *Flerrs; extern double Tline_min, Tline_max; extern double logz_line; /* line 2d reconstruction */ extern double *Fline2d_at_data; extern double *Fline2d, *Flerrs2d; extern double logz_line2d; extern int BLRmodel_size; extern int *par_fix, npar_fix; extern double *par_fix_val; extern int num_params_blr_tot; extern int num_params, num_params_blr, num_params_blr_model, num_params_var, num_params_difftrend, num_params_nlr, num_params_res; extern int num_params_drw, num_params_trend, num_params_resp; extern int num_params_linecenter; extern double **blr_range_model, **par_range_model; extern int *par_prior_model; /* prior type for model parameters */ extern double **par_prior_gaussian; /* center and std of Gaussian priors */ extern double var_range_model[15][2]; extern double nlr_range_model[3][2]; extern int nlr_prior_model[3]; extern double mass_range[2]; extern double sys_err_line_range[2]; /* range for systematic error of line */ extern double resp_range[2][2]; extern int idx_resp, idx_difftrend, idx_linecenter; extern double *instres_epoch, *instres_err_epoch; /* transfer function / velocity-delay map */ extern double *TransTau, *TransV, *TransW, *Trans1D, *Trans2D_at_veldata, *Trans2D; extern double rcloud_min_set, rcloud_max_set, time_back_set; extern double **Fcon_rm_particles, **Fcon_rm_particles_perturb; extern double *prob_con_particles, *prob_con_particles_perturb; extern int force_update; extern double **TransTau_particles, **TransTau_particles_perturb; extern double **Trans1D_particles, **Trans1D_particles_perturb; extern double **Trans2D_at_veldata_particles, **Trans2D_at_veldata_particles_perturb; extern double **Fline_at_data_particles, **Fline_at_data_particles_perturb; extern double *clouds_tau, *clouds_weight, *clouds_vel; extern FILE *fcloud_out; extern int icr_cloud_save; /* GSL */ extern const gsl_rng_type * gsl_T; extern gsl_rng * gsl_r; extern gsl_interp_accel *gsl_acc; extern gsl_interp *gsl_linear; #ifdef SA extern double PhaseFactor; extern int num_params_rm; extern int num_params_sa, num_params_sa_blr_model, num_params_sa_extpar, num_params_sa_blr; extern int n_epoch_sa_data, n_vel_sa_data, n_base_sa_data; extern double *vel_sa_data, *base_sa_data, *Fline_sa_data, *Flerrs_sa_data, *phase_sa_data, *pherrs_sa_data; extern double *wave_sa_data; extern double sa_flux_norm; extern double *phase_sa, *Fline_sa, *base_sa, *vel_sa, *wave_sa; extern double *clouds_alpha, *clouds_beta; extern double **sa_extpar_range, **sa_blr_range_model; extern int SABLRmodel_size; extern int *idx_sa_par_mutual, *idx_rm_par_mutual; extern double *prob_sa_particles, *prob_sa_particles_perturb; extern double sa_phase_error_mean, sa_line_error_mean; extern double *workspace_phase; #endif #endif
{ "alphanum_fraction": 0.7765096218, "avg_line_length": 26.9107142857, "ext": "h", "hexsha": "a006924822da3da9ab340daf05bb4e04aecb9ac2", "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/allvars.h", "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/allvars.h", "max_line_length": 130, "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/allvars.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2150, "size": 7535 }
/* eigen/gensymmv.c * * Copyright (C) 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 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 <stdlib.h> #include <config.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> /* * This module computes the eigenvalues and eigenvectors of a real * generalized symmetric-definite eigensystem A x = \lambda B x, where * A and B are symmetric, and B is positive-definite. */ static void gensymmv_normalize_eigenvectors(gsl_matrix *evec); /* gsl_eigen_gensymmv_alloc() Allocate a workspace for solving the generalized symmetric-definite eigenvalue problem. The size of this workspace is O(4n). Inputs: n - size of matrices Return: pointer to workspace */ gsl_eigen_gensymmv_workspace * gsl_eigen_gensymmv_alloc(const size_t n) { gsl_eigen_gensymmv_workspace *w; if (n == 0) { GSL_ERROR_NULL ("matrix dimension must be positive integer", GSL_EINVAL); } w = (gsl_eigen_gensymmv_workspace *) calloc (1, sizeof (gsl_eigen_gensymmv_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->size = n; w->symmv_workspace_p = gsl_eigen_symmv_alloc(n); if (!w->symmv_workspace_p) { gsl_eigen_gensymmv_free(w); GSL_ERROR_NULL("failed to allocate space for symmv workspace", GSL_ENOMEM); } return (w); } /* gsl_eigen_gensymmv_alloc() */ /* gsl_eigen_gensymmv_free() Free workspace w */ void gsl_eigen_gensymmv_free (gsl_eigen_gensymmv_workspace * w) { RETURN_IF_NULL (w); if (w->symmv_workspace_p) gsl_eigen_symmv_free(w->symmv_workspace_p); free(w); } /* gsl_eigen_gensymmv_free() */ /* gsl_eigen_gensymmv() Solve the generalized symmetric-definite eigenvalue problem A x = \lambda B x for the eigenvalues \lambda and eigenvectors x. Inputs: A - real symmetric matrix B - real symmetric and positive definite matrix eval - where to store eigenvalues evec - where to store eigenvectors w - workspace Return: success or error */ int gsl_eigen_gensymmv (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_gensymmv_workspace * w) { const size_t N = A->size1; /* check matrix and vector sizes */ if (N != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if ((N != B->size1) || (N != B->size2)) { GSL_ERROR ("B matrix dimensions must match A", GSL_EBADLEN); } else if (eval->size != N) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (evec->size1 != evec->size2) { GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR); } else if (evec->size1 != N) { GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN); } else if (w->size != N) { GSL_ERROR ("matrix size does not match workspace", GSL_EBADLEN); } else { int s; /* compute Cholesky factorization of B */ s = gsl_linalg_cholesky_decomp(B); if (s != GSL_SUCCESS) return s; /* B is not positive definite */ /* transform to standard symmetric eigenvalue problem */ gsl_eigen_gensymm_standardize(A, B); /* compute eigenvalues and eigenvectors */ s = gsl_eigen_symmv(A, eval, evec, w->symmv_workspace_p); if (s != GSL_SUCCESS) return s; /* backtransform eigenvectors: evec -> L^{-T} evec */ gsl_blas_dtrsm(CblasLeft, CblasLower, CblasTrans, CblasNonUnit, 1.0, B, evec); /* the blas call destroyed the normalization - renormalize */ gensymmv_normalize_eigenvectors(evec); return GSL_SUCCESS; } } /* gsl_eigen_gensymmv() */ /******************************************** * INTERNAL ROUTINES * ********************************************/ /* gensymmv_normalize_eigenvectors() Normalize eigenvectors so that their Euclidean norm is 1 Inputs: evec - eigenvectors */ static void gensymmv_normalize_eigenvectors(gsl_matrix *evec) { const size_t N = evec->size1; size_t i; /* looping */ for (i = 0; i < N; ++i) { gsl_vector_view vi = gsl_matrix_column(evec, i); double scale = 1.0 / gsl_blas_dnrm2(&vi.vector); gsl_blas_dscal(scale, &vi.vector); } } /* gensymmv_normalize_eigenvectors() */
{ "alphanum_fraction": 0.6492057489, "avg_line_length": 26.0492610837, "ext": "c", "hexsha": "b8d575de8630838958eba2de73c21252c8afe4a3", "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/eigen/gensymmv.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/eigen/gensymmv.c", "max_line_length": 89, "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/eigen/gensymmv.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": 1420, "size": 5288 }
#include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> int main (void) { double data[] = { 1.0 , 1/2.0, 1/3.0, 1/4.0, 1/2.0, 1/3.0, 1/4.0, 1/5.0, 1/3.0, 1/4.0, 1/5.0, 1/6.0, 1/4.0, 1/5.0, 1/6.0, 1/7.0 }; gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4); gsl_vector *eval = gsl_vector_alloc (4); gsl_matrix *evec = gsl_matrix_alloc (4, 4); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4); gsl_eigen_symmv (&m.matrix, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); { int i; for (i = 0; i < 4; i++) { double eval_i = gsl_vector_get (eval, i); gsl_vector_view evec_i = gsl_matrix_column (evec, i); printf ("eigenvalue = %g\n", eval_i); printf ("eigenvector = \n"); gsl_vector_fprintf (stdout, &evec_i.vector, "%g"); } } gsl_vector_free (eval); gsl_matrix_free (evec); return 0; }
{ "alphanum_fraction": 0.526032316, "avg_line_length": 21.8431372549, "ext": "c", "hexsha": "a24c912fce7b7dea2b5714fff9fd8c6d583a9f2a", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen.c", "max_line_length": 50, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/eigen.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": 399, "size": 1114 }
/* vector/gsl_vector_uint.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_UINT_H__ #define __GSL_VECTOR_UINT_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_uint.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; unsigned int *data; gsl_block_uint *block; int owner; } gsl_vector_uint; typedef struct { gsl_vector_uint vector; } _gsl_vector_uint_view; typedef _gsl_vector_uint_view gsl_vector_uint_view; typedef struct { gsl_vector_uint vector; } _gsl_vector_uint_const_view; typedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view; /* Allocation */ gsl_vector_uint *gsl_vector_uint_alloc (const size_t n); gsl_vector_uint *gsl_vector_uint_calloc (const size_t n); gsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_uint_free (gsl_vector_uint * v); /* Views */ _gsl_vector_uint_view gsl_vector_uint_view_array (unsigned int *v, size_t n); _gsl_vector_uint_view gsl_vector_uint_view_array_with_stride (unsigned int *base, size_t stride, size_t n); _gsl_vector_uint_const_view gsl_vector_uint_const_view_array (const unsigned int *v, size_t n); _gsl_vector_uint_const_view gsl_vector_uint_const_view_array_with_stride (const unsigned int *base, size_t stride, size_t n); _gsl_vector_uint_view gsl_vector_uint_subvector (gsl_vector_uint *v, size_t i, size_t n); _gsl_vector_uint_view gsl_vector_uint_subvector_with_stride (gsl_vector_uint *v, size_t i, size_t stride, size_t n); _gsl_vector_uint_const_view gsl_vector_uint_const_subvector (const gsl_vector_uint *v, size_t i, size_t n); _gsl_vector_uint_const_view gsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v, size_t i, size_t stride, size_t n); /* Operations */ void gsl_vector_uint_set_zero (gsl_vector_uint * v); void gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x); int gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i); int gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v); int gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v); int gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v); int gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v, const char *format); int gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src); int gsl_vector_uint_reverse (gsl_vector_uint * v); int gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w); int gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j); unsigned int gsl_vector_uint_max (const gsl_vector_uint * v); unsigned int gsl_vector_uint_min (const gsl_vector_uint * v); void gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out); size_t gsl_vector_uint_max_index (const gsl_vector_uint * v); size_t gsl_vector_uint_min_index (const gsl_vector_uint * v); void gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax); int gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b); int gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b); int gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b); int gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b); int gsl_vector_uint_scale (gsl_vector_uint * a, const double x); int gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x); int gsl_vector_uint_equal (const gsl_vector_uint * u, const gsl_vector_uint * v); int gsl_vector_uint_isnull (const gsl_vector_uint * v); int gsl_vector_uint_ispos (const gsl_vector_uint * v); int gsl_vector_uint_isneg (const gsl_vector_uint * v); int gsl_vector_uint_isnonneg (const gsl_vector_uint * v); INLINE_DECL unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i); INLINE_DECL void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x); INLINE_DECL unsigned int * gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i); INLINE_DECL const unsigned int * gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN unsigned int * gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (unsigned int *) (v->data + i * v->stride); } INLINE_FUN const unsigned int * gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const unsigned int *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_UINT_H__ */
{ "alphanum_fraction": 0.6761257661, "avg_line_length": 32.4935064935, "ext": "h", "hexsha": "d2f6cb35e38ea5da48f6d91b3e4614fe26cd949b", "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/gsl/gsl_vector_uint.h", "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/gsl/gsl_vector_uint.h", "max_line_length": 104, "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/gsl/gsl_vector_uint.h", "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": 1771, "size": 7506 }
#ifdef ESL_WITH_GSL /* interface_gsl.h * Easel's interfaces to the GNU Scientific Library * * SRE, Tue Jul 13 15:36:48 2004 * SVN $Id: interface_gsl.h 11 2005-01-06 11:44:17Z eddy $ */ #ifndef ESL_INTERFACE_GSL_INCLUDED #define ESL_INTERFACE_GSL_INCLUDED #include <stdlib.h> #include <easel/easel.h> #include <easel/dmatrix.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_eigen.h> extern int esl_GSL_MatrixInversion(ESL_DMATRIX *A, ESL_DMATRIX **ret_Ai); #endif /*ESL_INTERFACE_GSL_INCLUDED*/ #endif /*ESL_WITH_GSL*/
{ "alphanum_fraction": 0.7555555556, "avg_line_length": 24.375, "ext": "h", "hexsha": "1e65a0c7e950a71e4550f357c134c8388d57fccf", "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": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juan-rodriguez-rivas/cointerfaces", "max_forks_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "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": "juan-rodriguez-rivas/cointerfaces", "max_issues_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "d9cfdb93e241e2246718c0fc5a4ec22424ee6ed4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juan-rodriguez-rivas/cointerfaces", "max_stars_repo_path": "third_party_software/hmmer-3.0-linux-intel-x86_64/easel/interface_gsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 187, "size": 585 }
/* * gsl_binomial_randomdev.h * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ // Generated includes: #include "config.h" #ifndef GSL_BINOMIAL_RANDOMDEV_H #define GSL_BINOMIAL_RANDOMDEV_H // Includes from libnestutil: #include "lockptr.h" // Includes from librandom: #include "gslrandomgen.h" #include "randomdev.h" #include "randomgen.h" // Includes from sli: #include "dictdatum.h" #ifdef HAVE_GSL // External includes: #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> /*BeginDocumentation Name: rdevdict::gsl_binomial - GSL binomial random deviate generator Description: This function returns a random integer from the binomial distribution, the number of successes in n independent trials with probability p. The probability distribution for binomial variates is, p(k) = (n! / k!(n-k)!) p^k (1-p)^(n-k) , 0<=k<=n, n>0 Please note that the RNG used to initialize gsl_binomial has to be from the GSL (prefixed gsl_ in rngdict) Parameters: p - probability of success in a single trial (double) n - number of trials (positive integer) SeeAlso: CreateRDV, RandomArray, rdevdict Author: Jochen Martin Eppler */ namespace librandom { /** Class GSL_BinomialRandomDev Generates an RNG which returns Binomial(k;p;n) distributed random numbers out of an RNG which returns binomially distributed random numbers: p(k) = (n! / k!(n-k)!) p^k (1-p)^(n-k) , 0<=k<=n, n<0 Arguments: - pointer to an RNG - parameter p (optional, default = 0.5) - parameter n (optional, default = 1) @see http://www.gnu.org/software/gsl/manual/html_node/The-Binomial-Distribution.html @ingroup RandomDeviateGenerators */ class GSL_BinomialRandomDev : public RandomDev { public: // accept only lockPTRs for initialization, // otherwise creation of a lock ptr would // occur as side effect---might be unhealthy GSL_BinomialRandomDev( RngPtr, double p_s = 0.5, unsigned int n_s = 1 ); GSL_BinomialRandomDev( double p_s = 0.5, unsigned int n_s = 1 ); /** * set parameters for p and n * @parameters * p - success probability for single trial * n - number of trials */ void set_p_n( double, unsigned int ); void set_p( double ); //!<set p void set_n( unsigned int ); //!<set n /** * Import sets of overloaded virtual functions. * We need to explicitly include sets of overloaded * virtual functions into the current scope. * According to the SUN C++ FAQ, this is the correct * way of doing things, although all other compilers * happily live without. */ using RandomDev::operator(); using RandomDev::ldev; long ldev(); //!< draw integer long ldev( RngPtr ) const; //!< draw integer, threaded bool has_ldev() const { return true; } double operator()( RngPtr ) const; //!< return as double, threaded //! set distribution parameters from SLI dict void set_status( const DictionaryDatum& ); //! get distribution parameters from SLI dict void get_status( DictionaryDatum& ) const; private: double p_; //!<probability p of binomial distribution unsigned int n_; //!<parameter n in binomial distribution gsl_rng* rng_; }; inline double GSL_BinomialRandomDev::operator()( RngPtr rthrd ) const { return static_cast< double >( ldev( rthrd ) ); } } #endif #endif
{ "alphanum_fraction": 0.7073477604, "avg_line_length": 26.1447368421, "ext": "h", "hexsha": "599acb36350cc74a3ad1fb70d234901b02d8e6c6", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_line_length": 80, "max_stars_count": 45, "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "num_tokens": 1048, "size": 3974 }
#include "pyactpol.h" #include <gsl/gsl_linalg.h> /* sync.c * * scan-synchronous mode fitting and removal. */ static int fit_poly(float *x, double *y, int n, int order, int samp, double *fit); static int fit_sine(double *t, double *y, int n, double f, double *fit, double *coeff); /* Find the amplitude and phase of the synchronous signal in a set of * detectors together with the phase of the azimuth scan. * * az should already have the mean removed. ctime should start at 0 * to minimize rounding errors. nwin should be the number of samples * to use for the amplitude fit; i.e. an round number of azimuth scans. */ static int mbSyncFit(double* az, double* ctime, float* data, int ndata, int *dets, int ndets, float *sync_amp, float* sync_phase, float *sync_rms, float *phaseAz, float f, int order, int samp, int nT) { int n, nwin; double sampRate, thetaAz; // Calculate size of data window to do analysis sampRate = (double)ndata / (ctime[ndata-1] - ctime[0]); nwin = floor( (double)nT / f * sampRate ); if (nwin > ndata) { nwin = ndata; } double *fit_az = malloc(nwin * sizeof(double)); double *coeff_az = malloc(2 * sizeof(double)); // Obtain phase of azimuth scan if (fit_sine(ctime, az, nwin, f, fit_az, coeff_az) != 0) return 1; if (coeff_az[0] > 0) thetaAz = atan(coeff_az[1]/coeff_az[0]); else thetaAz = atan(coeff_az[1]/coeff_az[0]) + M_PI; *phaseAz = thetaAz; free(fit_az); free(coeff_az); float *tcopy = malloc(nwin * sizeof(float)); for (int j=0; j<nwin; j++) tcopy[j] = ctime[j] - ctime[0]; // Process all selected detectors #pragma omp parallel private(n) { double *y = malloc(nwin * sizeof(double)); double *fit_1f = malloc(nwin * sizeof(double)); double *fit_syn = malloc(nwin * sizeof(double)); double *coeff_syn = malloc(2 * sizeof(double)); #pragma omp for for (n = 0; n < ndets; n++) { int i; double A, theta, rms; float *det_data = data + ndata * dets[n]; // Obtain copy of data for (i = 0; i < nwin; i++) y[i] = det_data[i]; // Fit and subtract polynomial fit_poly(tcopy, y, nwin, order, samp, fit_1f); for (i = 0; i < nwin; i++) y[i] -= fit_1f[i]; // Fit sinusoidal to obtain amplitude and phase fit_sine(ctime, y, nwin, f, fit_syn, coeff_syn); A = sqrt(coeff_syn[0]*coeff_syn[0] + coeff_syn[1]*coeff_syn[1]); if (A == 0) theta = 0.0; else if (coeff_syn[0] > 0) theta = atan(coeff_syn[1]/coeff_syn[0]); else theta = atan(coeff_syn[1]/coeff_syn[0]) + M_PI; sync_amp[n] = A; sync_phase[n] = theta; // Find fit RMS error rms = 0.0; for (i = 0; i < nwin; i++) rms += (y[i] - fit_syn[i])*(y[i] - fit_syn[i]); sync_rms[n] = sqrt(rms/nwin); } /* pragma omp for */ free(y); free(fit_1f); free(fit_syn); free(coeff_syn); } /* pragma omp parallel */ return 0; } /// Fit sinusoidal of a given frequency to data. /// \param t Independent variable (time). /// \param y Dependent variable (data). /// \param n Number of elements in data. /// \param f Frequency of the sinusoid. /// \param fit Vector of fitted data (sinusoid). /// \param coeff Coefficients of sinusoid (A*cos(th) + B*sin(th)). static int fit_sine(double *t, double *y, int n, double f, double *fit, double *coeff) { int k; double temp_c, temp_s; double cos2, sin2, sincos, ycos, ysin; cos2 = sin2 = sincos = ycos = ysin = 0.0; for (k = 0; k < n; k++) { temp_c = cos(2*M_PI*f*t[k]); temp_s = sin(2*M_PI*f*t[k]); cos2 += temp_c*temp_c; sin2 += temp_s*temp_s; sincos += temp_s*temp_c; ycos += y[k]*temp_c; ysin += y[k]*temp_s; } coeff[0] = (sin2*ycos - sincos*ysin) / (cos2*sin2 - sincos*sincos); coeff[1] = (cos2*ysin - sincos*ycos) / (cos2*sin2 - sincos*sincos); // Evaluate result for (k = 0; k < n; k++) { fit[k] = cos(2*M_PI*f*t[k])*coeff[0] + sin(2*M_PI*f*t[k])*coeff[1]; } return 0; } /// Fit polynomial to data to remove common mode. /// \param x Independent variable. /// \param y Dependent variable (data). /// \param n Number of elements in data. /// \param order Order of polinomial to fit. /// \param samp Number of samples to take from data to do the fit. /// \param fit vector with evaluated polynomial static int fit_poly(float *x, double *y, int n, int order, int samp, double *fit) { int i, j, k; int N; double *coeff; double **A, *pows; double temp; gsl_vector *g_Ab = gsl_vector_calloc(order+1); gsl_matrix *g_AA = gsl_matrix_alloc(order+1,order+1); gsl_vector *g_x = gsl_vector_alloc(order+1); gsl_permutation *g_p = gsl_permutation_alloc(order+1); int signum = 0; int status = 1; // failure. if (order <= 0) { print_error("Invalid 'order=%i' in fit_poly\n", order); return 1; } // Initializa Matrices and Vectors coeff = malloc((order+1) * sizeof(double)); N = n/samp; if (N < order) { print_error("Fitting 'order=%i' with 'N=%i' data points in fit_poly\n", order, N); return 1; } A = (double **)malloc((order+1) * sizeof(double *)); A[0] = (double *)malloc(N * (order+1) * sizeof(double)); for (i = 0; i < order+1; i++){ A[i] = A[0] + N * i; for( j = 0; j < N; j++ ) A[i][j] = 0.0; } pows = (double *)malloc((2*order+1) * sizeof(double)); for (i = 0; i < 2*order+1; i++) pows[i] = 0.0; // Generate A matrix for (i = 0; i < order+1; i++) for (k = 0; k < N; k++) { A[i][k] = 1.0; for (j = 0; j < i; j++) A[i][k] *= x[k*samp + samp/2]; } // Generate AA as transpose(A)*A for (i = 2*order; i > 0; i -= 2) { for (k = 0; k < N; k++) { pows[i] += A[i/2][k]*A[i/2][k]; pows[i-1] += A[i/2][k]*A[i/2-1][k]; } } for (k = 0; k < N; k++) pows[0]++; for (i = 0; i < order+1; i++) for (j = 0; j < order+1; j++) g_AA->data[i*g_AA->tda+j] = pows[i+j]; /* for (i = 0; i < order+1; i++) { for (j = 0; j <= i; j++) { for (k = 0; k < N; k++) AA[i][j] += A[j][k]*A[i][k]; } }*/ // Generate Ab as transpose(A)*y for (i = 0; i < order+1; i++) { for (k = 0; k < N; k++) { temp = 0.0; for (j = 0; j < samp; j++) temp += y[k*samp + j]; g_Ab->data[i] += A[i][k] * temp / (float)samp; } } // Solve system if ((status = gsl_linalg_LU_decomp(g_AA, g_p, &signum))!=0) goto exit_now; if ((status = gsl_linalg_LU_solve(g_AA, g_p, g_Ab, g_x))!=0) goto exit_now; // Copy out... for (i = 0; i < order+1; i++) coeff[i] = g_x->data[i]; // Evaluate result for (k = 0; k < n; k++) { fit[k] = 0.0; for (i = 0; i < order+1; i++) { temp = 1.0; for (j = 0; j < i; j++) temp *= x[k]; fit[k] += temp * coeff[i]; } } /* for (k = 0; k < n; k++) fit[k] = 0.0; for (i = 0; i < order+1; i++) for (k = 0; k < n; k++) fit[k] += A[i][k] * Ab[i]; */ status = 0; exit_now: free(A[0]); free(A); free(pows); free(coeff); gsl_vector_free(g_Ab); gsl_vector_free(g_x); gsl_matrix_free(g_AA); gsl_permutation_free(g_p); return status; } PyDoc_STRVAR(get_sync_amps__doc__, "get_sync_amps(data, dets, az, ctime)\n" "\n" "The arrays must be C-ordered with dimensions like:\n" " data [ *,n_data] (float)\n" " dets [n_det] (int)\n" " az [n_data] (double)\n" " ctime[n_data] (double)\n" "\n" "Returns (az_phase, amps_cos, amps_sin)." ); static PyObject *get_sync_amps(PyObject *self, PyObject *args) { PyArrayObject *data_array; PyArrayObject *dets_array; PyArrayObject *az_array; PyArrayObject *ctime_array; double scan_freq; int order, samp, nT; if (!PyArg_ParseTuple(args, "O!O!O!O!diii", &PyArray_Type, &data_array, &PyArray_Type, &dets_array, &PyArray_Type, &az_array, &PyArray_Type, &ctime_array, &scan_freq, &order, &samp, &nT )) po_raise("invalid arguments."); // Types and ordering ASSERT_CARRAY_TYPE_NDIM(data_array, NPY_FLOAT32, 2); ASSERT_CARRAY_TYPE_NDIM(dets_array, NPY_INT32, 1); ASSERT_CARRAY_TYPE_NDIM(az_array, NPY_FLOAT64, 1); ASSERT_CARRAY_TYPE_NDIM(ctime_array, NPY_FLOAT64, 1); int ndata = PyArray_DIMS(data_array)[1]; int ndet = PyArray_DIMS(dets_array)[0]; po_assert(PyArray_DIMS(az_array)[0] == ndata); po_assert(PyArray_DIMS(ctime_array)[0] == ndata); float *data = PyArray_DATA(data_array); double *az = PyArray_DATA(az_array); double *ctime = PyArray_DATA(ctime_array); int *dets = PyArray_DATA(dets_array); // We've been so thorough, it would be a shame to segfault now. for (int i=0; i<ndet; i++) po_assert(dets[i] >= 0 && dets[i] < PyArray_DIMS(data_array)[0]); // And, places for the results. npy_intp ndet_ = ndet; PyArrayObject *amp_array = (PyArrayObject*) PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32); PyArrayObject *phase_array = (PyArrayObject*) PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32); PyArrayObject *rms_array = (PyArrayObject*) PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32); float phaseAz = -1.; mbSyncFit(az, ctime, data, ndata, dets, ndet, PyArray_DATA(amp_array), PyArray_DATA(phase_array), PyArray_DATA(rms_array), &phaseAz, scan_freq, order, samp, nT); return Py_BuildValue("NNNf", amp_array, phase_array, rms_array, phaseAz); } PyMethodDef pyactpol_sync_methods[] = { {"get_sync_amps", get_sync_amps, METH_VARARGS, get_sync_amps__doc__}, {NULL, NULL, 0, NULL} /* Sentinel */ };
{ "alphanum_fraction": 0.5695847924, "avg_line_length": 27.160326087, "ext": "c", "hexsha": "68703dc560dc6753eb9f380ec7dd5f356a9f4e44", "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": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ACTCollaboration/moby2", "max_forks_repo_path": "src/sync.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_issues_repo_issues_event_max_datetime": "2020-04-08T15:10:46.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-08T15:10:46.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "ACTCollaboration/moby2", "max_issues_repo_path": "src/sync.c", "max_line_length": 89, "max_stars_count": 3, "max_stars_repo_head_hexsha": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ACTCollaboration/moby2", "max_stars_repo_path": "src/sync.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:04:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-23T15:59:37.000Z", "num_tokens": 3330, "size": 9995 }
/*****************************************************************\ __ / / / / __ __ / /______ _______ / / / / ________ __ __ / ______ \ /_____ \ / / / / / _____ | / / / / / / | / _______| / / / / / / /____/ / / / / / / / / / / _____ / / / / / / _______/ / / / / / / / / / /____/ / / / / / / |______ / |______/ / /_/ /_/ |________/ / / / / \_______/ \_______ / /_/ /_/ / / / / High Level Game Framework /_/ --------------------------------------------------------------- Copyright (c) 2007-2011 - Rodrigo Braz Monteiro. This file is subject to the terms of halley_license.txt. \*****************************************************************/ #pragma once #include <iostream> #include <iomanip> #include <sstream> #include <cmath> #include "halley/text/halleystring.h" #include <gsl/gsl_assert> #include <cstdint> namespace Halley { // This whole class is TERRIBLE // There should be a type distinction between linear and gamma space, with conversions, // and the default Colour type should be Colour4c template <typename T> constexpr T colMinValue() { return 0; } template <typename T> constexpr T colMaxValue() { return 255; } template <> constexpr float colMaxValue<float>() { return 1.0f; } template <typename T, typename U> constexpr U convertColour(T x) { return U(float(x) * colMaxValue<U>() / colMaxValue<T>()); } template <> constexpr uint8_t convertColour(int x) { return static_cast<uint8_t>(x); } template <typename T> class Colour4 { public: T r = colMinValue<T>(); T g = colMinValue<T>(); T b = colMinValue<T>(); T a = colMaxValue<T>(); constexpr Colour4() = default; constexpr Colour4(T luma) : r(luma) , g(luma) , b(luma) {} constexpr Colour4(T r, T g, T b, T a=colMaxValue<T>()) : r(r) , g(g) , b(b) , a(a) {} Colour4(const String& str) { *this = fromString(str); } template <typename U> Colour4(const Colour4<U> c) { r = convertColour<U, T>(c.r); g = convertColour<U, T>(c.g); b = convertColour<U, T>(c.b); a = convertColour<U, T>(c.a); } String toString() const { std::stringstream ss; ss << "#" << std::hex; writeByte(ss, r); writeByte(ss, g); writeByte(ss, b); if (byteRep(a) != 255) writeByte(ss, a); ss.flush(); return ss.str(); } static Colour4 fromString(String str) { Colour4 col; size_t len = str.length(); if (len >= 1 && str[0] == '#') { if (len >= 3) { col.r = parseHex(str.substr(1, 2)); } if (len >= 5) { col.g = parseHex(str.substr(3, 2)); } if (len >= 7) { col.b = parseHex(str.substr(5, 2)); } if (len >= 9) { col.a = parseHex(str.substr(7, 2)); } } return col; } static Colour4 fromHSV(float h, float s, float v) { float r = 0; float g = 0; float b = 0; if (s == 0) { r = v * 255; if (r < 0) r = 0; if (r > 255) r = 255; g = b = r; } else { h = float(std::fmod(h, 1.0f)); int hi = int(h * 6.0f); float f = h*6 - hi; float p = v*(1-s); float q = v*(1-f*s); float t = v*(1-(1-f)*s); switch (hi) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; break; //default: throw Exception("Invalid value!"); } } return Colour4<T>(Colour4<float>(r, g, b)); } constexpr Colour4 multiplyLuma(float t) const { return Colour4(r*t, g*t, b*t, a); } constexpr Colour4 inverseMultiplyLuma(float t) const { return Colour4(1.0f - ((1.0f - r) * t), 1.0f - ((1.0f - g) * t), 1.0f - ((1.0f - b) * t), a); } constexpr Colour4 multiplyAlpha(float t) const { return Colour4(r, g, b, a * t); } constexpr Colour4 operator+(const Colour4& c) const { return Colour4(r+c.r, g+c.g, b+c.b, a+c.a); } constexpr Colour4 operator*(const Colour4& c) const { return Colour4(r * c.r, g * c.g, b * c.b, a * c.a); } constexpr Colour4 operator*(float t) const { return Colour4(r*t, g*t, b*t, a*t); } constexpr bool operator==(const Colour4& c) const { return r == c.r && g == c.g && b == c.b && a == c.a; } constexpr bool operator!=(const Colour4& c) const { return r != c.r || g != c.g || b != c.b || a != c.a; } private: uint8_t byteRep(T v) const { return convertColour<T, uint8_t>(v); } static T parseHex(String str) { std::stringstream ss(str); int value; ss << std::hex; ss >> value; return convertColour<uint8_t, T>(static_cast<uint8_t>(value)); } template <typename U> void writeByte(U& os, T component) const { unsigned int value = byteRep(component); if (value < 16) os << '0'; os << value; } }; typedef Colour4<uint8_t> Colour4c; typedef Colour4<float> Colour4f; typedef Colour4f Colour; }
{ "alphanum_fraction": 0.5092036427, "avg_line_length": 21.776371308, "ext": "h", "hexsha": "8d01b47a291dce252bf0eaa48f6a02f91d9d80d1", "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": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "chidddy/halley", "max_forks_repo_path": "src/engine/utils/include/halley/maths/colour.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "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": "chidddy/halley", "max_issues_repo_path": "src/engine/utils/include/halley/maths/colour.h", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "chidddy/halley", "max_stars_repo_path": "src/engine/utils/include/halley/maths/colour.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1710, "size": 5161 }
/* randist/rayleigh.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The Rayleigh distribution has the form p(x) dx = (x / sigma^2) exp(-x^2/(2 sigma^2)) dx for x = 0 ... +infty */ double gsl_ran_rayleigh (const gsl_rng * r, const double sigma) { double u = gsl_rng_uniform_pos (r); return sigma * sqrt(-2.0 * log (u)); } double gsl_ran_rayleigh_pdf (const double x, const double sigma) { if (x < 0) { return 0 ; } else { double u = x / sigma ; double p = (u / sigma) * exp(-u * u / 2.0) ; return p; } } /* The Rayleigh tail distribution has the form p(x) dx = (x / sigma^2) exp((a^2 - x^2)/(2 sigma^2)) dx for x = a ... +infty */ double gsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma) { double u = gsl_rng_uniform_pos (r); return sqrt(a * a - 2.0 * sigma * sigma * log (u)); } double gsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma) { if (x < a) { return 0 ; } else { double u = x / sigma ; double v = a / sigma ; double p = (u / sigma) * exp((v + u) * (v - u) / 2.0) ; return p; } }
{ "alphanum_fraction": 0.6310054482, "avg_line_length": 23.476744186, "ext": "c", "hexsha": "1600d5b3638d51e308f917bed742e6502e1bdb31", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/randist/rayleigh.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/randist/rayleigh.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/randist/rayleigh.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": 608, "size": 2019 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "compearth.h" /* #ifdef COMPEARTH_USE_MKL #include <mkl_cblas.h> #else #include <cblas.h> #endif */ /*! * @brief Converts a moment tensor, M, from input system defined by i1in * to moment tensor, Mout, to output system defind by i2in. * * @param[in] nmt Number of moment tensors. * @param[in] i1in Coordinate system for M: \n * = CE_USE (1) -> up, south, east \n * = CE_NED (2) -> north, east, down \n * = CE_NWU (3) -> north west, up \n * = CE_ENU (4) -> east, north, up \n * = CE_SEU (5) -> south, east, up \n * @param[in] i2in Coordinate system for Mout: \n * = CE_USE (1) -> up, south, east \n * = CE_NED (2) -> north, east, down \n * = CE_NWU (3) -> north west, up \n * = CE_ENU (4) -> east, north, up \n * = CE_SEU (5) -> south, east, up \n * @param[in] M Input moment tensor in system i1in. This is an * an array of dimension [6 x nmt]. * The C indices {0,1,2,3,4,5} correspond to matrix * indices: {11, 22, 33, 12, 13, 23}. * * @param[out] Mout Corresponding moment tensor now in system i2in. * This is an array of dimension [6 x nmt]. * the C indices {0,1,2,3,4,5} correspond to matrix * indices: {11, 22, 33, 12, 13, 23} * * @result 0 indicates success. * * @date 2016 - Ben Baker converted Carl Tape's convert_MT.m to C * * @copyright MIT * */ int compearth_convertMT(const int nmt, const enum compearthCoordSystem_enum i1in, const enum compearthCoordSystem_enum i2in, const double *__restrict__ M, double *__restrict__ Mout) { int i, i1, i2; // Check the inputs to avoid seg faults if (nmt < 1 || M == NULL || Mout == NULL) { if (nmt < 1){fprintf(stderr, "%s: No moment tensors\n", __func__);} if (M == NULL){fprintf(stderr, "%s: Error M is NULL\n", __func__);} if (Mout == NULL) { fprintf(stderr, "%s: Error Mout is NULL\n", __func__); } return -1; } for (i=0; i<6*nmt; i++){Mout[i] = 0.0;} // Quick checks i1 = (int) i1in; i2 = (int) i2in; if (i1 < 1 || i1 > 5) { fprintf(stderr, "%s: Error unknown input coordinate system %d\n", __func__, i1); return -1; } if (i2 < 1 || i2 > 5) { fprintf(stderr, "%s: Error unkonwn output coordinate system %d\n", __func__, i2); return -1; } // Base case if (i1 == i2) { memcpy(Mout, M, (size_t) nmt*6*sizeof(double)); //cblas_dcopy(6*nmt, M, 1, Mout, 1); return 0; } // Convert if (i1 == 1) { // up-south-east (GCMT) to north-east-down (AkiRichards) // (AR, 1980, p. 118) if (i2 == 2) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; // tt -> xx Mout[6*i+1] = M[6*i+2]; // pp -> yy Mout[6*i+2] = M[6*i+0]; // rr -> zz Mout[6*i+3] =-M[6*i+5]; // -tp -> xy Mout[6*i+4] = M[6*i+3]; // rt -> xz Mout[6*i+5] =-M[6*i+4]; // -rp -> yz } } // up-south-east (GCMT) to north-west-up else if (i2 == 3) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+2]; Mout[6*i+2] = M[6*i+0]; Mout[6*i+3] = M[6*i+5]; Mout[6*i+4] =-M[6*i+3]; Mout[6*i+5] =-M[6*i+4]; } } // up-south-east (GCMT) to east-north-up else if (i2 == 4) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+2]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+0]; Mout[6*i+3] =-M[6*i+5]; Mout[6*i+4] = M[6*i+4]; Mout[6*i+5] =-M[6*i+3]; } } // up-south-east (GCMT) to south-east-up else if (i2 == 5) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+2]; Mout[6*i+2] = M[6*i+0]; Mout[6*i+3] = M[6*i+5]; Mout[6*i+4] = M[6*i+3]; Mout[6*i+5] = M[6*i+4]; } } } else if (i1 == 2) { // north-east-down (AkiRichards) to up-south-east (GCMT) // (AR, 1980, p. 118) if (i2 == 1) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+2]; // zz -> rr Mout[6*i+1] = M[6*i+0]; // xx -> tt Mout[6*i+2] = M[6*i+1]; // yy -> pp Mout[6*i+3] = M[6*i+4]; // xz -> rt Mout[6*i+4] =-M[6*i+5]; // -yz -> rp Mout[6*i+5] =-M[6*i+3]; // -xy -> tp } } // north-east-down (AkiRichards) to north-west-up else if (i2 == 3) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] =-M[6*i+4]; Mout[6*i+5] = M[6*i+5]; } } // north-east-down (AkiRichards) to east-north-up else if (i2 == 4) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] = M[6*i+3]; Mout[6*i+4] =-M[6*i+5]; Mout[6*i+5] =-M[6*i+4]; } } // north-east-down (AkiRichards) to south-east-up else if (i2 == 5) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] = M[6*i+4]; Mout[6*i+5] =-M[6*i+5]; } } } else if (i1 == 3) { // north-west-up to up-south-east (GCMT) if (i2 == 1) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+2]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+1]; Mout[6*i+3] =-M[6*i+4]; Mout[6*i+4] =-M[6*i+5]; Mout[6*i+5] = M[6*i+3]; } } // north-west-up to north-east-down (AkiRichards) else if (i2 == 2) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] =-M[6*i+4]; Mout[6*i+5] = M[6*i+5]; } } // north-west-up to east-north-up else if (i2 == 4) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] =-M[6*i+5]; Mout[6*i+5] = M[6*i+4]; } } // north-west-up to south-east-up else if (i2 == 5) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] = M[6*i+3]; Mout[6*i+4] =-M[6*i+4]; Mout[6*i+5] =-M[6*i+5]; } } } else if (i1 == 4) { // east-north-up to up-south-east (GCMT) if (i2 == 1) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+2]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+0]; Mout[6*i+3] =-M[6*i+5]; Mout[6*i+4] = M[6*i+4]; Mout[6*i+5] =-M[6*i+3]; } } // east-north-up to north-east-down (AkiRichards) else if (i2 == 2) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] = M[6*i+3]; Mout[6*i+4] =-M[6*i+5]; Mout[6*i+5] =-M[6*i+4]; } } // east-north-up to north-west-up else if (i2 == 3) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] = M[6*i+5]; Mout[6*i+5] =-M[6*i+4]; } } // east-north-up to south-east-up else if (i2 == 5) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] =-M[6*i+5]; Mout[6*i+5] = M[6*i+4]; } } } else if (i1 == 5) { // south-east-up to up-south-east (GCMT) if (i2 == 1) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+2]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+1]; Mout[6*i+3] = M[6*i+4]; Mout[6*i+4] = M[6*i+5]; Mout[6*i+5] = M[6*i+3]; } } // south-east-up to north-east-down (AkiRichards) else if (i2 == 2) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] = M[6*i+4]; Mout[6*i+5] =-M[6*i+5]; } } // south-east-up to north-west-up else if (i2 == 3) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+0]; Mout[6*i+1] = M[6*i+1]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] = M[6*i+3]; Mout[6*i+4] =-M[6*i+4]; Mout[6*i+5] =-M[6*i+5]; } } // south-east-up to east-north-up else if (i2 == 4) { for (i=0; i<nmt; i++) { Mout[6*i+0] = M[6*i+1]; Mout[6*i+1] = M[6*i+0]; Mout[6*i+2] = M[6*i+2]; Mout[6*i+3] =-M[6*i+3]; Mout[6*i+4] = M[6*i+5]; Mout[6*i+5] =-M[6*i+4]; } } } return 0; }
{ "alphanum_fraction": 0.3423898707, "avg_line_length": 30.9048913043, "ext": "c", "hexsha": "506fc89de15df26755ed819545994301bd3a5f4d", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_path": "c_src/convertMT.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "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": "carltape/mtbeach", "max_issues_repo_path": "c_src/convertMT.c", "max_line_length": 75, "max_stars_count": 9, "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_path": "c_src/convertMT.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "num_tokens": 4059, "size": 11373 }
#ifndef _AVA_COMMON_SUPPORT_STD_SPAN_H_ #define _AVA_COMMON_SUPPORT_STD_SPAN_H_ #pragma once #include <gsl/span> #include <gsl/span_ext> namespace std { using gsl::span; } // namespace std #define EMPTY_CHAR_SPAN std::span<const char>() #define STRING_AS_SPAN(STR_VAR) std::span<const char>((STR_VAR).data(), (STR_VAR).length()) #define VECTOR_AS_SPAN(VEC_VAR) std::span<const decltype(VEC_VAR)::value_type>((VEC_VAR).data(), (VEC_VAR).size()) #define VECTOR_AS_CHAR_SPAN(VEC_VAR) \ std::span<const char>(reinterpret_cast<const char *>((VEC_VAR).data()), \ sizeof(decltype(VEC_VAR)::value_type) * (VEC_VAR).size()) #endif // _AVA_COMMON_SUPPORT_STD_SPAN_H_
{ "alphanum_fraction": 0.6913580247, "avg_line_length": 31.6956521739, "ext": "h", "hexsha": "b8866689a561b1bd664830566ae5eb361449b5be", "lang": "C", "max_forks_count": 15, "max_forks_repo_forks_event_max_datetime": "2021-11-18T03:35:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-31T21:25:14.000Z", "max_forks_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "anjuna-security/ava", "max_forks_repo_path": "common/support/std_span.h", "max_issues_count": 81, "max_issues_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_issues_repo_issues_event_max_datetime": "2021-07-14T12:22:47.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-16T02:47:04.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "anjuna-security/ava", "max_issues_repo_path": "common/support/std_span.h", "max_line_length": 114, "max_stars_count": 24, "max_stars_repo_head_hexsha": "9187a05e99dfadf9711a890a9b0e2760e6e58c66", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "anjuna-security/ava", "max_stars_repo_path": "common/support/std_span.h", "max_stars_repo_stars_event_max_datetime": "2021-08-03T23:48:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-31T21:25:10.000Z", "num_tokens": 180, "size": 729 }
#ifndef OPENMC_TALLIES_FILTER_SURFACE_H #define OPENMC_TALLIES_FILTER_SURFACE_H #include <cstdint> #include <unordered_map> #include <gsl/gsl> #include "openmc/tallies/filter.h" #include "openmc/vector.h" namespace openmc { //============================================================================== //! Specifies which surface particles are crossing //============================================================================== class SurfaceFilter : public Filter { public: //---------------------------------------------------------------------------- // Constructors, destructors ~SurfaceFilter() = default; //---------------------------------------------------------------------------- // Methods std::string type() const override { return "surface"; } 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 void set_surfaces(gsl::span<int32_t> surfaces); private: //---------------------------------------------------------------------------- // Data members //! The indices of the surfaces binned by this filter. vector<int32_t> surfaces_; //! A map from surface indices to filter bin indices. std::unordered_map<int32_t, int> map_; }; } // namespace openmc #endif // OPENMC_TALLIES_FILTER_SURFACE_H
{ "alphanum_fraction": 0.5137908916, "avg_line_length": 27.350877193, "ext": "h", "hexsha": "368fd09d064f65d9e380f207abee41b0b24a018b", "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": "922f688978693761f82c4a3764ab05dd96cc8cff", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "huak95/openmc", "max_forks_repo_path": "include/openmc/tallies/filter_surface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff", "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": "huak95/openmc", "max_issues_repo_path": "include/openmc/tallies/filter_surface.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stu314159/openmc", "max_stars_repo_path": "include/openmc/tallies/filter_surface.h", "max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z", "num_tokens": 283, "size": 1559 }
#ifndef CWANNIER_BAND_ENERGY #define CWANNIER_BAND_ENERGY #include <stdbool.h> #include <stdio.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include "HTightBinding.h" #include "ctetra/sum.h" double BandEnergy(double *E_Fermi, HTightBinding *Hrs, gsl_matrix *R, double num_electrons, int na, int nb, int nc, bool use_cache); #endif // CWANNIER_BAND_ENERGY
{ "alphanum_fraction": 0.7731481481, "avg_line_length": 27, "ext": "h", "hexsha": "463f8a348ec229f99922bf481ad5c8a88164fbb9", "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": "BandEnergy.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": "BandEnergy.h", "max_line_length": 132, "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": "BandEnergy.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 130, "size": 432 }
/* * Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger, * Eduardo Grossi, and Derek Teaney * All rights reserved. * * FastReso is distributed under MIT license; * see the LICENSE file that should be present in the root * of the source distribution, or alternately available at: * https://github.com/amazeliauskas/FastReso/ */ #ifndef FASTFO_qag_params_h #define FASTFO_qag_params_h #include <gsl/gsl_integration.h> namespace qag_params{ const double fEpsRel = 1e-6; const double fEpsAbs = 1e-10; const int fKey = GSL_INTEG_GAUSS51; const int fLimit = 1000; } #endif
{ "alphanum_fraction": 0.7302100162, "avg_line_length": 29.4761904762, "ext": "h", "hexsha": "0196e761dd225145e262627f934eeb879afa61ca", "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": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "amazeliauskas/FastReso", "max_forks_repo_path": "qag_params.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "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": "amazeliauskas/FastReso", "max_issues_repo_path": "qag_params.h", "max_line_length": 70, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "amazeliauskas/FastReso", "max_stars_repo_path": "qag_params.h", "max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z", "num_tokens": 180, "size": 619 }
#pragma once #include <gsl/span> /** * This header is mainly for shorthands when dealing with `gsl::span`s * see the `gsl` or c++ core guidelines for more info on what a `gsl::span` is/does. */ namespace riner { template<class T, std::ptrdiff_t Extent = gsl::dynamic_extent> using span = gsl::span<T, Extent>; template<std::ptrdiff_t Extent = gsl::dynamic_extent> using ByteSpan = span<uint8_t, Extent>; template<std::ptrdiff_t Extent = gsl::dynamic_extent> using cByteSpan = span<const uint8_t, Extent>; }
{ "alphanum_fraction": 0.6894639556, "avg_line_length": 25.7619047619, "ext": "h", "hexsha": "81a1ee0b959d615c447d1260fdb3527a7692033f", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-03-21T20:53:11.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-30T21:33:07.000Z", "max_forks_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DavHau/Riner", "max_forks_repo_path": "src/common/Span.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_issues_repo_issues_event_max_datetime": "2020-06-15T15:57:08.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-30T22:10:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "DavHau/Riner", "max_issues_repo_path": "src/common/Span.h", "max_line_length": 83, "max_stars_count": 4, "max_stars_repo_head_hexsha": "f9e9815b713572f03497f0e4e66c3f82a0241b66", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DavHau/Riner", "max_stars_repo_path": "src/common/Span.h", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:41:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-24T03:24:08.000Z", "num_tokens": 149, "size": 541 }
#ifndef _PC_PATCH_H #define _PC_PATCH_H #include <petsc.h> PETSC_EXTERN PetscErrorCode PCPatchInitializePackage(void); PETSC_EXTERN PetscErrorCode PCCreate_PATCH(PC); PETSC_EXTERN PetscErrorCode PCPatchSetCellNumbering(PC, PetscSection); PETSC_EXTERN PetscErrorCode PCPatchSetDiscretisationInfo(PC, PetscInt, DM *, PetscInt *, PetscInt *, const PetscInt **, const PetscInt *, PetscInt, const PetscInt *, PetscInt, const PetscInt *); PETSC_EXTERN PetscErrorCode PCPatchSetComputeOperator(PC, PetscErrorCode (*)(PC,Mat,PetscInt,const PetscInt *,PetscInt,const PetscInt *,void *), void *); typedef enum {PC_PATCH_STAR, PC_PATCH_VANKA, PC_PATCH_USER, PC_PATCH_PYTHON} PCPatchConstructType; PETSC_EXTERN const char *const PCPatchConstructTypes[]; #endif
{ "alphanum_fraction": 0.7652173913, "avg_line_length": 53.6666666667, "ext": "h", "hexsha": "b9327d07e6c4eee8e810a6f46c270d86fc7565a1", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-01-23T15:21:31.000Z", "max_forks_repo_forks_event_min_datetime": "2018-01-23T15:21:31.000Z", "max_forks_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wence-/ssc", "max_forks_repo_path": "ssc/libssc.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_issues_repo_issues_event_max_datetime": "2018-09-27T10:54:59.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-05T12:22:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "wence-/ssc", "max_issues_repo_path": "ssc/libssc.h", "max_line_length": 194, "max_stars_count": null, "max_stars_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wence-/ssc", "max_stars_repo_path": "ssc/libssc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 184, "size": 805 }
/* sys/pow_int.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_pow_int.h> #ifndef HIDE_INLINE_STATIC double gsl_pow_2(const double x) { return x*x; } double gsl_pow_3(const double x) { return x*x*x; } double gsl_pow_4(const double x) { double x2 = x*x; return x2*x2; } double gsl_pow_5(const double x) { double x2 = x*x; return x2*x2*x; } double gsl_pow_6(const double x) { double x2 = x*x; return x2*x2*x2; } double gsl_pow_7(const double x) { double x3 = x*x*x; return x3*x3*x; } double gsl_pow_8(const double x) { double x2 = x*x; double x4 = x2*x2; return x4*x4; } double gsl_pow_9(const double x) { double x3 = x*x*x; return x3*x3*x3; } #endif double gsl_pow_int(double x, int n) { double value = 1.0; if(n < 0) { x = 1.0/x; n = -n; } /* repeated squaring method * returns 0.0^0 = 1.0, so continuous in x */ do { if(n & 1) value *= x; /* for n odd */ n >>= 1; x *= x; } while (n); return value; }
{ "alphanum_fraction": 0.6685714286, "avg_line_length": 31.8181818182, "ext": "c", "hexsha": "ebcb0c7e2df1186a012321f73eeb4b35e0d97bba", "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/sys/pow_int.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/sys/pow_int.c", "max_line_length": 88, "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/sys/pow_int.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": 542, "size": 1750 }
/* specfunc/gsl_sf_mathieu.h * * Copyright (C) 2002 Lowell Johnson * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: L. Johnson */ #ifndef __GSL_SF_MATHIEU_H__ #define __GSL_SF_MATHIEU_H__ #include <gsl/gsl_sf_result.h> #include <gsl/gsl_eigen.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS #define GSL_SF_MATHIEU_COEFF 100 typedef struct { size_t size; size_t even_order; size_t odd_order; int extra_values; double qa; /* allow for caching of results: not implemented yet */ double qb; /* allow for caching of results: not implemented yet */ double *aa; double *bb; double *dd; double *ee; double *tt; double *e2; double *zz; gsl_vector *eval; gsl_matrix *evec; gsl_eigen_symmv_workspace *wmat; } gsl_sf_mathieu_workspace; /* Compute an array of characteristic (eigen) values from the recurrence matrices for the Mathieu equations. */ int gsl_sf_mathieu_a_array(int order_min, int order_max, double qq, gsl_sf_mathieu_workspace *work, double result_array[]); int gsl_sf_mathieu_b_array(int order_min, int order_max, double qq, gsl_sf_mathieu_workspace *work, double result_array[]); /* Compute the characteristic value for a Mathieu function of order n and type ntype. */ int gsl_sf_mathieu_a(int order, double qq, gsl_sf_result *result); int gsl_sf_mathieu_b(int order, double qq, gsl_sf_result *result); /* Compute the Fourier coefficients for a Mathieu function. */ int gsl_sf_mathieu_a_coeff(int order, double qq, double aa, double coeff[]); int gsl_sf_mathieu_b_coeff(int order, double qq, double aa, double coeff[]); /* Allocate computational storage space for eigenvalue solution. */ gsl_sf_mathieu_workspace *gsl_sf_mathieu_alloc(const size_t nn, const double qq); void gsl_sf_mathieu_free(gsl_sf_mathieu_workspace *workspace); /* Compute an angular Mathieu function. */ int gsl_sf_mathieu_ce(int order, double qq, double zz, gsl_sf_result *result); int gsl_sf_mathieu_se(int order, double qq, double zz, gsl_sf_result *result); int gsl_sf_mathieu_ce_array(int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]); int gsl_sf_mathieu_se_array(int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]); /* Compute a radial Mathieu function. */ int gsl_sf_mathieu_Mc(int kind, int order, double qq, double zz, gsl_sf_result *result); int gsl_sf_mathieu_Ms(int kind, int order, double qq, double zz, gsl_sf_result *result); int gsl_sf_mathieu_Mc_array(int kind, int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]); int gsl_sf_mathieu_Ms_array(int kind, int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]); __END_DECLS #endif /* !__GSL_SF_MATHIEU_H__ */
{ "alphanum_fraction": 0.7051964512, "avg_line_length": 36.5277777778, "ext": "h", "hexsha": "99217b31fda87ff5a75e39f0c435f1199ad42345", "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_sf_mathieu.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_sf_mathieu.h", "max_line_length": 124, "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_sf_mathieu.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 944, "size": 3945 }
#ifndef BSPTN_H #define BSPTN_H #include <vector> #include <gsl/gsl_sf_bessel.h> #include "SpecialFunctions.h" // NUMERICAL KERNELS ///// /// CREATION OF KERNEL ARRAYS //// //Kernel array sizes // 1st ORDER extern double F1b_k1; extern double G1b_k1; extern double F1b_k2; extern double G1b_k2; extern double F1b_k3; extern double G1b_k3; extern double F1b_1; extern double G1b_1; extern double F1b_2; extern double G1b_2; extern double F1b_3; extern double G1b_3; // 2nd order extern double F2b_k12; extern double G2b_k12; extern double F2b_k13; extern double G2b_k13; extern double F2b_k23; extern double G2b_k23; extern double F2b_p2mp; extern double G2b_p2mp; extern double F2b_p3mp; extern double G2b_p3mp; extern double F2b_12a; extern double G2b_12a; extern double F2b_13a; extern double G2b_13a; extern double F2b_23a; extern double G2b_23a; // 3rd order extern double F3b_12mp; extern double G3b_12mp; extern double F3b_13mp; extern double G3b_13mp; extern double F3b_21mp; extern double G3b_21mp; extern double F3b_23mp; extern double G3b_23mp; extern double F3b_31mp; extern double G3b_31mp; extern double F3b_32mp; extern double G3b_32mp; extern double F3b_1pp; extern double G3b_1pp; extern double F3b_2pp; extern double G3b_2pp; extern double F3b_3pp; extern double G3b_3pp; // 4th order extern double F4b_12pp; extern double G4b_12pp; extern double F4b_13pp; extern double G4b_13pp; extern double F4b_23pp; extern double G4b_23pp; const double myh0sqr = pow2(1./2997.92); class BSPTN { public: // tree level equation solvers : dgp, f(R) void initnb0_dgp(double A, double k[], double x[], double kargs[], double omega0, double par1, double par2, double par3); void initnb0_fofr(double A, double k[], double x[], double kargs[], double omega0, double par1, double par2, double par3); // 1-loop level equation solvers : dgp, f(R) void initnb1_dgp(double A, double k[], double x[], double kargs[], double omega0, double par1, double par2, double par3, double epars[]); void initnb1_fr(double A, double k[], double x[], double kargs[], double omega0, double par1, double par2, double par3, double epars[]); }; #endif // BSPTN_H
{ "alphanum_fraction": 0.7589204026, "avg_line_length": 19.8727272727, "ext": "h", "hexsha": "826f7860f42a30fb670c48d3db79658c4490685a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_path": "reactions/src/BSPTN.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_path": "reactions/src/BSPTN.h", "max_line_length": 139, "max_stars_count": 3, "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_path": "reactions/src/BSPTN.h", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "num_tokens": 747, "size": 2186 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2013-2020 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; This program is free software; you can redistribute it and/or */ /*; modify it under the terms of the GNU General Public License as */ /*; published by the Free Software Foundation; either version 2 of */ /*; the License, or (at your option) any later version. */ /*; */ /*; This program is distributed in the hope that it will be useful, */ /*; but WITHOUT ANY WARRANTY; without even the implied warranty of */ /*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /*; GNU General Public License for more details. */ /*; */ /*; You should have received a copy of the GNU General Public */ /*; License along with this program; if not, write to the Free */ /*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #include "ObitRMFit.h" #include "ObitThread.h" #include "ObitSinCos.h" #ifdef HAVE_GSL #include <gsl/gsl_blas.h> #endif /* HAVE_GSL */ #ifndef VELIGHT #define VELIGHT 2.997924562e8 #endif /* VELIGHT */ /*----------------Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitRMFit.c * ObitRMFit class function definitions. * This class is derived from the Obit base class. */ /** name of the class defined in this file */ static gchar *myClassName = "ObitRMFit"; /** Function to obtain parent ClassInfo */ static ObitGetClassFP ObitParentGetClass = ObitGetClass; /** * ClassInfo structure ObitRMFitClassInfo. * This structure is used by class objects to access class functions. */ static ObitRMFitClassInfo myClassInfo = {FALSE}; /*--------------- File Global Variables ----------------*/ /*---------------Private function prototypes----------------*/ /** Private: Initialize newly instantiated object. */ void ObitRMFitInit (gpointer in); /** Private: Deallocate members. */ void ObitRMFitClear (gpointer in); /** Private: Set Class function pointers. */ static void ObitRMFitClassInfoDefFn (gpointer inClass); /** Private: Do actual fitting */ static void Fitter (ObitRMFit* in, ObitErr *err); /** Private: Write output image */ static void WriteOutput (ObitRMFit* in, ObitImage *outImage, ObitErr *err); #ifdef HAVE_GSL /** Private: Solver function evaluation */ static int RMFitFunc (const gsl_vector *x, void *params, gsl_vector *f); /** Private: Solver Jacobian evaluation */ static int RMFitJac (const gsl_vector *x, void *params, gsl_matrix *J); /** Private: Solver function + Jacobian evaluation */ static int RMFitFuncJac (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); #endif /* HAVE_GSL */ /** Private: Threaded fitting */ static gpointer ThreadNLRMFit (gpointer arg); /** Private: Threaded RM synthesis fitting */ static gpointer ThreadRMSynFit (gpointer arg); /*---------------Private structures----------------*/ /* FT threaded function argument */ typedef struct { /** ObitRMFit object */ ObitRMFit *in; /* Obit error stack object */ ObitErr *err; /** First (1-rel) value in y to process this thread */ olong first; /** Highest (1-rel) value in y to process this thread */ olong last; /** thread number, >0 -> no threading */ olong ithread; /** max number of terms to fit */ olong nterm; /** number of frequencies */ olong nlamb2; /** number of valid data points in x, q, u, w */ olong nvalid; /** maximum iteration */ olong maxIter; /** acceptable iteration delta, rel and abs. */ odouble minDelta; /** Array of Lambda^2 (nlamb2) */ ofloat *lamb2; /** Array of Q, U weights (1/RMS) per inFArrays (nlamb2) */ ofloat *Qweight, *Uweight; /** Array of Q, U variance per inFArrays (nlamb2) */ ofloat *Qvar, *Uvar; /** Array of Q, U pixel values being fitted (nlamb2) */ ofloat *Qobs, *Uobs; /** Array of polarized intensity pixel values being fitted (nlamb2) */ ofloat *Pobs; /** min Q/U SNR */ ofloat minQUSNR; /** min fraction of valid samples */ ofloat minFrac; /** Reference lambda^2 */ ofloat refLamb2; /** Vector of guess/fitted coefficients, optional errors */ ofloat *coef; /** Chi squared of fit */ ofloat ChiSq; /** Do error analysis? */ gboolean doError; /** work arrays */ double *x, *q, *u, *w; ofloat *wrk1, *wrk2, *wrk3; #ifdef HAVE_GSL /** Fitting solver */ gsl_multifit_fdfsolver *solver; /** Fitting solver function structure */ gsl_multifit_function_fdf *funcStruc; /** Fitting work vector */ gsl_vector *work; /** Covariance matrix */ gsl_matrix *covar; #endif /* HAVE_GSL */ } NLRMFitArg; /** Private: Actual fitting */ static void NLRMFit (NLRMFitArg *arg); /** Private: coarse search */ static olong RMcoarse (NLRMFitArg *arg); /*----------------------Public functions---------------------------*/ /** * Constructor. * Initializes class if needed on first call. * \param name An optional name for the object. * \return the new object. */ ObitRMFit* newObitRMFit (gchar* name) { ObitRMFit* out; ofloat s, c; /* Class initialization if needed */ if (!myClassInfo.initialized) ObitRMFitClassInit(); /* allocate/init structure */ out = g_malloc0(sizeof(ObitRMFit)); /* initialize values */ if (name!=NULL) out->name = g_strdup(name); else out->name = g_strdup("Noname"); /* set ClassInfo */ out->ClassInfo = (gpointer)&myClassInfo; /* initialize other stuff */ ObitRMFitInit((gpointer)out); ObitSinCosCalc(0.0, &s, &c); /* Sine/cosine functions */ return out; } /* end newObitRMFit */ /** * Returns ClassInfo pointer for the class. * \return pointer to the class structure. */ gconstpointer ObitRMFitGetClass (void) { /* Class initialization if needed */ if (!myClassInfo.initialized) ObitRMFitClassInit(); return (gconstpointer)&myClassInfo; } /* end ObitRMFitGetClass */ /** * Make a deep copy of an ObitRMFit. * \param in The object to copy * \param out An existing object pointer for output or NULL if none exists. * \param err Obit error stack object. * \return pointer to the new object. */ ObitRMFit* ObitRMFitCopy (ObitRMFit *in, ObitRMFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; gboolean oldExist; gchar *outName; olong i, nOut; /* error checks */ if (err->error) return out; g_assert (ObitIsA(in, &myClassInfo)); if (out) g_assert (ObitIsA(out, &myClassInfo)); /* Create if it doesn't exist */ oldExist = out!=NULL; if (!oldExist) { /* derive object name */ outName = g_strconcat ("Copy: ",in->name,NULL); out = newObitRMFit(outName); g_free(outName); } /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ out->nlamb2 = in->nlamb2; out->nterm = in->nterm; /* Arrays */ if (out->QRMS) g_free(out->QRMS); out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->QRMS) for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i]; if (out->URMS) g_free(out->URMS); out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->URMS) for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i]; /* reference this class members */ if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc); if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc); if (out->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]); } if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]); } if (out->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (out->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]); } if (in->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]); } return out; } /* end ObitRMFitCopy */ /** * Make a copy of a object but do not copy the actual data * This is useful to create an RMFit similar to the input one. * \param in The object to copy * \param out An existing object pointer for output, must be defined. * \param err Obit error stack object. */ void ObitRMFitClone (ObitRMFit *in, ObitRMFit *out, ObitErr *err) { const ObitClassInfo *ParentClass; olong i, nOut; /* error checks */ g_assert (ObitErrIsA(err)); if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert (ObitIsA(out, &myClassInfo)); /* deep copy any base class members */ ParentClass = myClassInfo.ParentClass; g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL)); ParentClass->ObitCopy (in, out, err); /* copy this class */ out->nlamb2 = in->nlamb2; out->nterm = in->nterm; /* Arrays */ if (out->QRMS) g_free(out->QRMS); out->QRMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->QRMS) for (i=0; i<out->nlamb2; i++) out->QRMS[i] = in->QRMS[i]; if (out->URMS) g_free(out->URMS); out->URMS = g_malloc0(out->nlamb2*sizeof(ofloat)); if (in->URMS) for (i=0; i<out->nlamb2; i++) out->URMS[i] = in->URMS[i]; /* reference this class members */ if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc); if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc); if (out->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayUnref(out->inQFArrays[i]); } if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) out->inQFArrays[i] = ObitFArrayRef(in->inQFArrays[i]); } if (out->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayUnref(out->inUFArrays[i]); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) out->inUFArrays[i] = ObitFArrayRef(in->inUFArrays[i]); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (out->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]); } if (in->outFArrays) { for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]); } } /* end ObitRMFitClone */ /** * Creates an ObitRMFit * \param name An optional name for the object. * \param nterm Number of coefficients of powers of log(nu) * \return the new object. */ ObitRMFit* ObitRMFitCreate (gchar* name, olong nterm) { ObitRMFit* out; /* Create basic structure */ out = newObitRMFit (name); out->nterm = nterm; return out; } /* end ObitRMFitCreate */ /** * Fit RM to an image cube pixels. * The third axis of the output image will be "SPECRM " to indicate that the * planes are RM fit parameters. The "CRVAL" on this axis will be the reference * Frequency for the fitting. * Item "NTERM" is added to the output image descriptor * \param in Spectral fitting object * Potential parameters on in->info: * \li "refLamb2" OBIT_double scalar Reference frequency for fit [def ref for inQImage] * \li "minQUSNR" OBIT_float scalar min. SNR for Q and U pixels [def 3.0] * \li "minFrac" OBIT_float scalar min. fraction of planes included [def 0.5] * \li "doError" OBIT_boolean scalar If true do error analysis [def False] * \li "doRMSyn" OBIT_boolean scalar If true do max RM synthesis [def False] * \li "maxRMSyn" OBIT_float scalar max RM to search (rad/m^2) [def ambiguity] * \li "minRMSyn" OBIT_float scalar min RM to search (rad/m^2)[def -ambiguity] * \li "delRMSyn" OBIT_float scalar RM increment for search (rad/m^2)[def 1.0] * \li "maxChi2" OBIT_float scalar max Chi^2 for search [def 10.0] * * \param inQImage Q Image cube to be fitted * \param inUImage U Image cube to be fitted * \param outImage Image cube with fitted spectra. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * if doError: * Planes nterm+1->2*nterm are uncertainties in coefficients * Plane 2*nterm+1 = Chi squared of fit * if do RMsyn, planes are 1=RM, 2=EVPA@0 lambda, 3=amp@0 lambda, 4=sum wt. * \param err Obit error stack object. */ void ObitRMFitCube (ObitRMFit* in, ObitImage *inQImage, ObitImage *inUImage, ObitImage *outImage, ObitErr *err) { olong i, iplane, nOut, plane[5]={1,1,1,1,1}, noffset=0; olong naxis[2]; ObitIOSize IOBy; ObitInfoType type; ObitIOCode retCode; union ObitInfoListEquiv InfoReal; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; odouble freq; gchar *today=NULL, *SPECRM = "SPECRM ", *MaxRMSyn = "MaxRMSyn", keyword[9]; ObitHistory *inHist=NULL, *outHist=NULL; gchar hiCard[73], *TF[2]={"False","True"}; gchar *routine = "ObitRMFitCube"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(inQImage)); g_assert(ObitImageIsA(inUImage)); g_assert(ObitImageIsA(outImage)); /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif /* Control parameters */ /* Min Q/U pixel SNR for fit */ InfoReal.flt = 3.0; type = OBIT_float; in->minQUSNR = 3.0; ObitInfoListGetTest(in->info, "minQUSNR", &type, dim, &InfoReal); if (type==OBIT_float) in->minQUSNR = InfoReal.flt; else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl; /* Min fraction of planes in the fit */ InfoReal.flt = 0.5; type = OBIT_float; in->minFrac = 0.5; ObitInfoListGetTest(in->info, "minFrac", &type, dim, &InfoReal); if (type==OBIT_float) in->minFrac = InfoReal.flt; else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl; /* Want Error analysis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal); in->doError = InfoReal.itg; /* Want max RM Synthesis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doRMSyn", &type, dim, &InfoReal); in->doRMSyn = InfoReal.itg; if (in->doRMSyn) Obit_log_error(err, OBIT_InfoErr, "Using Max RM Synthesis"); /* Max RM for RM syn search */ InfoReal.flt = 0.0; type = OBIT_float; in->maxRMSyn = 0.0; ObitInfoListGetTest(in->info, "maxRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->maxRMSyn = InfoReal.flt; else if (type==OBIT_double) in->maxRMSyn = (ofloat)InfoReal.dbl; /* Min RM for RM syn search */ InfoReal.flt = 1.0; type = OBIT_float; in->minRMSyn = 1.0; ObitInfoListGetTest(in->info, "minRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->minRMSyn = InfoReal.flt; else if (type==OBIT_double) in->minRMSyn = (ofloat)InfoReal.dbl; /* Delta RM for RM syn search */ InfoReal.flt = 1.0; type = OBIT_float; in->delRMSyn = 1.0; ObitInfoListGetTest(in->info, "delRMSyn", &type, dim, &InfoReal); if (type==OBIT_float) in->delRMSyn = InfoReal.flt; else if (type==OBIT_double) in->delRMSyn = (ofloat)InfoReal.dbl; /* maxChi2 for RM syn search */ InfoReal.flt = 10.0; type = OBIT_float; in->maxChi2 = 10.0; ObitInfoListGetTest(in->info, "maxChi2", &type, dim, &InfoReal); if (type==OBIT_float) in->maxChi2 = InfoReal.flt; else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl; /* Open input images to get info */ IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (inQImage->info, "IOBy", OBIT_long, dim, &IOBy); inQImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (inQImage, OBIT_IO_ReadOnly, err); if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); ObitInfoListAlwaysPut (inUImage->info, "IOBy", OBIT_long, dim, &IOBy); inUImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (inUImage, OBIT_IO_ReadOnly, err); if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inUImage->name); /* Check compatability */ Obit_return_if_fail(((inQImage->myDesc->inaxes[0]==inUImage->myDesc->inaxes[0]) && (inQImage->myDesc->inaxes[1]==inUImage->myDesc->inaxes[1]) && (inQImage->myDesc->inaxes[2]==inUImage->myDesc->inaxes[2])), err, "%s: Input images incompatable", routine); /* Get Reference frequency/lambda^2 , default from input Q ref. freq. */ InfoReal.dbl = VELIGHT/inQImage->myDesc->crval[inQImage->myDesc->jlocf]; InfoReal.dbl *= InfoReal.dbl; type = OBIT_double; in->refLamb2 = InfoReal.dbl; ObitInfoListGetTest(in->info, "refLamb2", &type, dim, &InfoReal); if (type==OBIT_float) in->refLamb2 = InfoReal.flt; else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl; in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */ /* What plane does spectral data start on */ if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], "SPECLNMF", 8)) { noffset = 2; /* What plane does spectral data start on */ ObitInfoListGetTest (inQImage->myDesc->info, "NTERM", &type, dim, &noffset); } else { /* Normal spectral cube */ noffset = 0; } /* Determine number of frequency planes and initialize in */ in->nlamb2 = inQImage->myDesc->inaxes[inQImage->myDesc->jlocf]-noffset; in->QRMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->URMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->lamb2 = g_malloc0(in->nlamb2*sizeof(odouble)); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* always 4 for doRMSyn */ if (in->doRMSyn) nOut = 4; /* Define term arrays */ in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*)); for (i=0; i<nOut; i++) in->outFArrays[i] = NULL; /* Image size */ in->nx = inQImage->myDesc->inaxes[0]; in->ny = inQImage->myDesc->inaxes[1]; naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); /* Output Image descriptor */ outImage->myDesc = ObitImageDescCopy (inQImage->myDesc, in->outDesc, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* Change third axis to type "SPECRM " and leave the reference frequency as the "CRVAL" */ outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut; outImage->myDesc->crval[outImage->myDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0; outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0; if (in->doRMSyn) strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], MaxRMSyn, IMLEN_KEYWORD); else strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM , IMLEN_KEYWORD); outImage->myDesc->bitpix = -32; /* Float it */ /* Creation date today */ today = ObitToday(); strncpy (outImage->myDesc->date, today, IMLEN_VALUE); if (today) g_free(today); /* Copy of output descriptor to in */ in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err); /* Loop reading planes */ for (iplane=0; iplane<in->nlamb2; iplane++) { /* Lambda^2 Check for MFImage outputs */ if (!strncmp(inQImage->myDesc->ctype[inQImage->myDesc->jlocf], "SPECLNMF", 8)) { sprintf (keyword, "FREQ%4.4d",iplane+1); freq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]); ObitInfoListGetTest (inQImage->myDesc->info, keyword, &type, dim, &freq); } else { /* Normal spectral cube */ freq = inQImage->myDesc->crval[inQImage->myDesc->jlocf] + inQImage->myDesc->cdelt[inQImage->myDesc->jlocf] * (inQImage->myDesc->plane - inQImage->myDesc->crpix[inQImage->myDesc->jlocf]); } in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq); plane[0] = iplane+noffset+1; /* Select correct plane */ retCode = ObitImageGetPlane (inQImage, in->inQFArrays[iplane]->array, plane, err); retCode = ObitImageGetPlane (inUImage, in->inUFArrays[iplane]->array, plane, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); /* Plane RMSes */ in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]); in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]); } /* end loop reading planes */ /* Close inputs */ retCode = ObitImageClose (inQImage, err); inQImage->extBuffer = FALSE; /* May need I/O buffer later */ retCode = ObitImageClose (inUImage, err); inUImage->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inQImage->name); /* Do actual fitting */ Fitter (in, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* Update output header to reference Frequency */ outImage->myDesc->crval[outImage->myDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); /* Write output */ WriteOutput(in, outImage, err); if (err->error) Obit_traceback_msg (err, routine, inQImage->name); /* History */ /* Copy any history */ inHist = newObitDataHistory((ObitData*)inQImage, OBIT_IO_ReadOnly, err); outHist = newObitDataHistory((ObitData*)outImage, OBIT_IO_WriteOnly, err); outHist = ObitHistoryCopy (inHist, outHist, err); /* Add parameters */ ObitHistoryOpen (outHist, OBIT_IO_ReadWrite, err); ObitHistoryTimeStamp (outHist, "ObitRMFitCube", err); g_snprintf ( hiCard, 72, "RMCube nterm = %d",in->nterm); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube refLamb2 = %lf",in->refLamb2); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minQUSNR = %f",in->minQUSNR); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minFrac = %f",in->minFrac); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube doRMSyn = %s",TF[in->doRMSyn]); ObitHistoryWriteRec (outHist, -1, hiCard, err); if (in->doRMSyn) { ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube maxRMSyn = %f",in->maxRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube minRMSyn = %f",in->minRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube delRMSyn = %f",in->delRMSyn); ObitHistoryWriteRec (outHist, -1, hiCard, err); g_snprintf ( hiCard, 72, "RMCube maxChi2 = %f", in->maxChi2); ObitHistoryWriteRec (outHist, -1, hiCard, err); } /* end doRMSyn */ ObitHistoryClose (outHist, err); if (err->error) Obit_traceback_msg (err, routine, in->name); inHist = ObitHistoryUnref(inHist); outHist = ObitHistoryUnref(outHist); } /* end ObitRMFitCube */ /** * Fit RM to an array of images * The third axis of the output image will be "SPECRM " to indicate that then * planes are spectral fit parameters. The "CRVAL" on this axis will be the reference * Frequency for the fitting. * Item "NTERM" is added to the output image descriptor to give the maximum number * of terms fitted * \param in Spectral fitting object * \li "refLamb2" OBIT_double scalar Reference frequency for fit [def average of inputs] * \li "minQUSNR" OBIT_float scalar Max. min. SNR for Q and U pixels [def 3.0] * \li "doError" OBIT_boolean scalar If true do error analysis [def False] * \param nimage Number of entries in imQArr * \param imQArr Array of Q images to be fitted * \param imUArr Array of U images to be fitted, same geometry as imQArr * \param outImage Image cube with fitted parameters. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * if doError: * Planes nterm+1->2*nterm are uncertainties in coefficients * Plane 2*nterm+1 = Chi squared of fit * \param err Obit error stack object. */ void ObitRMFitImArr (ObitRMFit* in, olong nimage, ObitImage **imQArr, ObitImage **imUArr, ObitImage *outImage, ObitErr *err) { olong i, iplane, nOut; olong naxis[2]; ObitIOSize IOBy; ObitInfoType type; ObitIOCode retCode; union ObitInfoListEquiv InfoReal; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; ofloat ipixel[2], opixel[2]; gboolean bad; odouble avgLamb2, freq; gchar *today=NULL, *SPECRM = "SPECRM "; gchar *routine = "ObitRMFitCube"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(outImage)); /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif /* Control parameters */ /* Min Q/U pixel SNR for fit */ InfoReal.flt = 3.0; type = OBIT_float; in->minQUSNR = 3.0; ObitInfoListGetTest(in->info, "minQUSNR", &type, dim, &InfoReal); if (type==OBIT_float) in->minQUSNR = InfoReal.flt; else if (type==OBIT_double) in->minQUSNR = (ofloat)InfoReal.dbl; /* Min fraction of planes in the fit */ InfoReal.flt = 0.5; type = OBIT_float; in->minFrac = 0.5; ObitInfoListGetTest(in->info, "minFrac", &type, dim, &InfoReal); if (type==OBIT_float) in->minFrac = InfoReal.flt; else if (type==OBIT_double) in->minFrac = (ofloat)InfoReal.dbl; /* Want Error analysis? */ InfoReal.itg = (olong)FALSE; type = OBIT_bool; ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal); in->doError = InfoReal.itg; /* Determine number of lambda^2 planes and initialize in */ in->nlamb2 = nimage; in->QRMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->URMS = g_malloc0(in->nlamb2*sizeof(ofloat)); in->inQFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->inUFArrays = g_malloc0(in->nlamb2*sizeof(ObitFArray*)); in->lamb2 = g_malloc0(in->nlamb2*sizeof(odouble)); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* Define term arrays */ in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*)); for (i=0; i<nOut; i++) in->outFArrays[i] = NULL; /* Loop over images */ for (iplane = 0; iplane<nimage; iplane++) { /* Open input image to get info */ IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (imQArr[iplane]->info, "IOBy", OBIT_long, dim, &IOBy); imQArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (imQArr[iplane], OBIT_IO_ReadOnly, err); ObitInfoListAlwaysPut (imUArr[iplane]->info, "IOBy", OBIT_long, dim, &IOBy); imUArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */ retCode = ObitImageOpen (imUArr[iplane], OBIT_IO_ReadOnly, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* On first image initialize */ if (iplane==0) { /* Image size */ in->nx = imQArr[iplane]->myDesc->inaxes[0]; in->ny = imQArr[iplane]->myDesc->inaxes[1]; naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis); /* Output Image descriptor */ outImage->myDesc = ObitImageDescCopy (imQArr[iplane]->myDesc, in->outDesc, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* Change third axis to type "SPECRM " and leave the reference frequency as the "CRVAL" */ outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut; outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0; outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0; strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECRM , IMLEN_KEYWORD); outImage->myDesc->bitpix = -32; /* Float it */ /* Creation date today */ today = ObitToday(); strncpy (outImage->myDesc->date, today, IMLEN_VALUE); if (today) g_free(today); /* Copy of output descriptor to in */ in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err); } else { /* On subsequent images check for consistency */ /* Check size of planes */ Obit_return_if_fail(((imQArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && (imQArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err, "%s: Image planes incompatible %d!= %d or %d!= %d", routine, imQArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], imQArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ; Obit_return_if_fail(((imUArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && (imUArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err, "%s: Image planes incompatible %d!= %d or %d!= %d", routine, imUArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], imUArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ; /* Check alignment of pixels */ ipixel[0] = 1.0; ipixel[1] = 1.0; bad = !ObitImageDescCvtPixel (imQArr[iplane]->myDesc, in->outDesc, ipixel, opixel, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[iplane]->name); Obit_return_if_fail(!bad, err, "%s: Image planes incompatible", routine); Obit_return_if_fail(((fabs(ipixel[0]-opixel[0])<0.01) && (fabs(ipixel[1]-opixel[1])<0.01)), err, "%s: Image pixels not aligned %f!=%f or %f!=%f", routine, ipixel[0], opixel[0], ipixel[1], opixel[1]) ; } /* end consistency check */ /* Read planes */ retCode = ObitImageRead (imQArr[iplane], in->inQFArrays[iplane]->array, err); retCode = ObitImageRead (imUArr[iplane], in->inUFArrays[iplane]->array, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); /* Plane RMSes */ in->QRMS[iplane] = ObitFArrayRMS(in->inQFArrays[iplane]); in->URMS[iplane] = ObitFArrayRMS(in->inUFArrays[iplane]); /* Lambda^2 */ freq = imQArr[iplane]->myDesc->crval[imQArr[iplane]->myDesc->jlocf] + imQArr[iplane]->myDesc->cdelt[imQArr[iplane]->myDesc->jlocf] * (imQArr[iplane]->myDesc->plane - imQArr[iplane]->myDesc->crpix[imQArr[iplane]->myDesc->jlocf]); in->lamb2[iplane] = (VELIGHT/freq)*(VELIGHT/freq); /* Close inputs */ retCode = ObitImageClose (imQArr[iplane], err); imQArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */ retCode = ObitImageClose (imUArr[iplane], err); imUArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imQArr[iplane]->name); } /* end loop over input images */ /* Average Lambda^2 */ avgLamb2 = 0.0; for (i=0; i<in->nlamb2; i++) avgLamb2 += in->lamb2[i]; avgLamb2 /= in->nlamb2; /* Get Reference lambda^2 , default avg. input ref. freq. */ InfoReal.dbl = avgLamb2; type = OBIT_double; in->refLamb2 = InfoReal.dbl; ObitInfoListGetTest(in->info, "refLamb2", &type, dim, &InfoReal); if (type==OBIT_float) in->refLamb2 = InfoReal.flt; else if (type==OBIT_double) in->refLamb2 = (ofloat)InfoReal.dbl; in->refLamb2 = MAX (1.0e-10, in->refLamb2); /* Avoid zero divide */ /* Update output header to reference Frequency */ outImage->myDesc->crval[outImage->myDesc->jlocf] =VELIGHT/sqrt(in->refLamb2); in->outDesc->crval[in->outDesc->jlocf] = VELIGHT/sqrt(in->refLamb2); /* Do actual fitting */ Fitter (in, err); if (err->error) Obit_traceback_msg (err, routine, imQArr[0]->name); /* Write output */ WriteOutput(in, outImage, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); } /* end ObitRMFitImArr */ /** * Fit single RM to Q, Uflux measurements * \param nlamb2 Number of entries in freq, flux, sigma * \param nterm Number of coefficients of powers of log(nu) to fit * \param refLamb2 Reference lambda^2 (m^2) * \param lamb2 Array of lambda^2 (m^2) * \param qflux Array of Q fluxes (Jy) same dim as lamb2 * \param qsigma Array of Q errors (Jy) same dim as lamb2 * \param uflux Array of U fluxes (Jy) same dim as lamb2 * \param usigma Array of U errors (Jy) same dim as lamb2 * \param err Obit error stack object. * \return Array of fitter parameters, errors for each and Chi Squares of fit * Initial terms are in Jy, other in log. */ ofloat* ObitRMFitSingle (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, ObitErr *err) { ofloat *out = NULL; ofloat fblank = ObitMagicF(); olong i, j; NLRMFitArg *arg=NULL; gchar *routine = "ObitRMFitSingle"; /* GSL implementation */ #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ /* Warn if no GSL implementation */ #ifndef HAVE_GSL Obit_log_error(err, OBIT_InfoWarn, "NO GSL available - results will be approximate"); #endif if (err->error) return out; /* Warn if ref. lambda^2 <= 0, set to 1.0 */ if (refLamb2<=0.0) { refLamb2 = 1.0; Obit_log_error(err, OBIT_InfoWarn, "%s: Setting reference lambda^2 to 1", routine); } /* Create function argument */ arg = g_malloc(sizeof(NLRMFitArg)); arg->in = NULL; /* Not needed here */ arg->nlamb2 = nlamb2; arg->maxIter = 100; /* max. number of iterations */ arg->minDelta = 1.0e-5; /* Min step size */ arg->nterm = nterm; arg->doError = TRUE; arg->minQUSNR = 3.0; /* min pixel SNR */ arg->minFrac = 0.5; /* min fraction of samples */ arg->refLamb2 = refLamb2; /* Reference Frequency */ arg->Qweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Pobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->lamb2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->x = g_malloc0(arg->nlamb2*sizeof(double)); arg->w = g_malloc0(arg->nlamb2*sizeof(double)); arg->q = g_malloc0(arg->nlamb2*sizeof(double)); arg->u = g_malloc0(arg->nlamb2*sizeof(double)); arg->wrk1 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk3 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat)); for (i=0; i<nlamb2; i++) { arg->lamb2[i] = lamb2[i]; arg->Qvar[i] = qsigma[i]*qsigma[i]; arg->Uvar[i] = usigma[i]*usigma[i]; arg->Qobs[i] = qflux[i]; arg->Uobs[i] = uflux[i]; if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) { arg->Pobs[i] = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]); arg->Qweight[i] = 1.0 / qsigma[i]; arg->Uweight[i] = 1.0 / usigma[i]; } else{ arg->Pobs[i] = 0.0; arg->Qweight[i] = 0.0; arg->Uweight[i] = 0.0; } } /* GSL implementation */ #ifdef HAVE_GSL arg->solver = NULL; arg->covar = NULL; arg->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2); /* Fitting function info */ arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); arg->funcStruc->f = &RMFitFunc; arg->funcStruc->df = &RMFitJac; arg->funcStruc->fdf = &RMFitFuncJac; arg->funcStruc->n = 2*arg->nlamb2; arg->funcStruc->p = 2; arg->funcStruc->params = arg; /* Set up work arrays */ arg->covar = gsl_matrix_alloc(2, 2); arg->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ /* Do fit */ NLRMFit(arg); /* get results parameters + errors */ out = g_malloc0((2*arg->nterm+1)*sizeof(ofloat)); for (j=0; j<nterm*2+1; j++) out[j] = arg->coef[j]; /* Cleanup */ if (arg->Qweight) g_free(arg->Qweight); if (arg->Uweight) g_free(arg->Uweight); if (arg->Qvar) g_free(arg->Qvar); if (arg->Uvar) g_free(arg->Uvar); if (arg->Qobs) g_free(arg->Qobs); if (arg->Uobs) g_free(arg->Uobs); if (arg->Pobs) g_free(arg->Pobs); if (arg->lamb2) g_free(arg->lamb2); if (arg->x) g_free(arg->x); if (arg->w) g_free(arg->w); if (arg->q) g_free(arg->q); if (arg->u) g_free(arg->u); if (arg->wrk1) g_free(arg->wrk1); if (arg->wrk2) g_free(arg->wrk2); if (arg->wrk3) g_free(arg->wrk3); if (arg->coef) g_free(arg->coef); #ifdef HAVE_GSL if (arg->solver) gsl_multifit_fdfsolver_free (arg->solver); if (arg->work) gsl_vector_free(arg->work); if (arg->covar) gsl_matrix_free(arg->covar); if (arg->funcStruc) g_free(arg->funcStruc); #endif /* HAVE_GSL */ g_free(arg); return out; } /* end ObitRMFitSingle */ /** * Make single spectrum fitting argument array * \param nlamb2 Number of entries in freq, flux, sigma * \param nterm Number of coefficients of powers of log(nu) to fit * \param refLamb2 Reference lambda^2 (m^2) * \param lamb2 Array of lambda^2 (m^2) * \param out Array for output results, should be g_freed when done * \param err Obit error stack object. * \return argument for single spectrum fitting, use ObitRMFitKillArg to dispose. */ gpointer ObitRMFitMakeArg (olong nlamb2, olong nterm, odouble refLamb2, odouble *lamb2, ofloat **out, ObitErr *err) { olong i; NLRMFitArg *arg=NULL; gchar *routine = "ObitRMFitMakeArg"; #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ if (err->error) return out; /* Warn if too many terms asked for */ if (nterm>2) { Obit_log_error(err, OBIT_InfoWarn, "%s: Asked for %d terms, will limit to 2", routine, nterm); } /* Warn if ref. lambda^2 <= 0, set to 1.0 */ if (refLamb2<=0.0) { refLamb2 = 1.0; Obit_log_error(err, OBIT_InfoWarn, "%s: Setting reference Lambda^2 to 1", routine); } /* Create function argument */ arg = g_malloc(sizeof(NLRMFitArg)); arg->in = NULL; /* Not needed here */ arg->nlamb2 = nlamb2; arg->maxIter = 100; /* max. number of iterations */ arg->minDelta = 1.0e-5; /* Min step size */ arg->nterm = nterm; arg->doError = TRUE; arg->minQUSNR = 3.0; /* min pixel SNR */ arg->minFrac = 0.5; /* min fraction of samples */ arg->refLamb2 = refLamb2; /* Reference Frequency */ arg->Qweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uweight = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uvar = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Qobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Uobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->Pobs = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->lamb2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->x = g_malloc0(arg->nlamb2*sizeof(double)); arg->w = g_malloc0(arg->nlamb2*sizeof(double)); arg->q = g_malloc0(arg->nlamb2*sizeof(double)); arg->u = g_malloc0(arg->nlamb2*sizeof(double)); arg->wrk1 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk2 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->wrk3 = g_malloc0(arg->nlamb2*sizeof(ofloat)); arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat)); for (i=0; i<nlamb2; i++) { arg->lamb2[i] = lamb2[i]; } /* GSL implementation */ #ifdef HAVE_GSL arg->solver = NULL; arg->covar = NULL; arg->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; arg->solver = gsl_multifit_fdfsolver_alloc(T, 2*arg->nlamb2, 2); /* Fitting function info */ arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); arg->funcStruc->f = &RMFitFunc; arg->funcStruc->df = &RMFitJac; arg->funcStruc->fdf = &RMFitFuncJac; arg->funcStruc->n = 2*arg->nlamb2; arg->funcStruc->p = 2; arg->funcStruc->params = arg; /* Set up work arrays */ arg->covar = gsl_matrix_alloc(2, 2); arg->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ /* output array */ *out = (ofloat*)g_malloc0((2*arg->nterm+1)*sizeof(ofloat)); return (gpointer)arg; } /* end ObitRMFitMakeArg */ /** * Fit single RM to measurements using precomputed argument * \param aarg pointer to argument for fitting * \param Qflux Array of Q values to be fitted * \param Qsigma Array of uncertainties of Qflux * \param Uflux Array of U values to be fitted * \param Usigma Array of uncertainties of Qflux * \param out Result array at least 2*nterms+1 in size. * in order, fitted parameters, error estimates, chi sq of fit. */ void ObitRMFitSingleArg (gpointer aarg, ofloat *qflux, ofloat *qsigma, ofloat *uflux, ofloat *usigma, ofloat *out) { olong i, j; NLRMFitArg *arg=(NLRMFitArg*)aarg; ofloat fblank = ObitMagicF(); gboolean allBad; /* Save flux array, sigma, Check if all data blanked */ allBad = TRUE; for (i=0; i<arg->nlamb2; i++) { if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank) && ((fabs(qflux[i])>arg->minQUSNR*qsigma[i]) || (fabs(uflux[i])>arg->minQUSNR*usigma[i]))) allBad = FALSE; arg->Qobs[i] = qflux[i]; arg->Uobs[i] = uflux[i]; arg->Qvar[i] = qsigma[i]; arg->Uvar[i] = usigma[i]; if ((arg->Qobs[i]!=fblank) && (arg->Uobs[i]!=fblank)) { arg->Pobs[i] = sqrt (qflux[i]*qflux[i] + uflux[i]*uflux[i]); /* arg->Qweight[i] = arg->Pobs[i] / arg->Qvar[i]; arg->Uweight[i] = arg->Pobs[i] / arg->Uvar[i]; */ arg->Qweight[i] = 1.0 / qsigma[i]; arg->Uweight[i] = 1.0 / usigma[i]; } else { arg->Pobs[i] = 0.0; arg->Qweight[i] = 0.0; arg->Uweight[i] = 0.0; } } /* Return fblanks/zeroes for no data */ if (allBad) { out[0] = fblank; for (j=1; j<=arg->nterm*2; j++) out[j] = 0.0; return; } /* Fit */ NLRMFit(arg); /* get results parameters + errors */ for (j=0; j<arg->nterm*2; j++) out[j] = arg->coef[j]; /* Chi squared */ out[arg->nterm*2] = arg->ChiSq; return; } /* end ObitRMFitSingleArg */ /** * Delete single fitting argument * \param aarg pointer to argument to kill */ void ObitRMFitKillArg (gpointer aarg) { NLRMFitArg *arg= (NLRMFitArg*)aarg; if (arg==NULL) return; if (arg->Qweight) g_free(arg->Qweight); if (arg->Uweight) g_free(arg->Uweight); if (arg->Qvar) g_free(arg->Qvar); if (arg->Uvar) g_free(arg->Uvar); if (arg->Qobs) g_free(arg->Qobs); if (arg->Uobs) g_free(arg->Uobs); if (arg->Pobs) g_free(arg->Pobs); if (arg->lamb2) g_free(arg->lamb2); if (arg->x) g_free(arg->x); if (arg->w) g_free(arg->w); if (arg->q) g_free(arg->q); if (arg->u) g_free(arg->u); if (arg->wrk1) g_free(arg->wrk1); if (arg->wrk2) g_free(arg->wrk2); if (arg->wrk3) g_free(arg->wrk3); if (arg->coef) g_free(arg->coef); #ifdef HAVE_GSL if (arg->solver) gsl_multifit_fdfsolver_free (arg->solver); if (arg->work) gsl_vector_free(arg->work); if (arg->covar) gsl_matrix_free(arg->covar); if (arg->funcStruc) g_free(arg->funcStruc); #endif /* HAVE_GSL */ g_free(arg); } /* end ObitRMFitKillArg */ /** * Initialize global ClassInfo Structure. */ void ObitRMFitClassInit (void) { if (myClassInfo.initialized) return; /* only once */ /* Set name and parent for this class */ myClassInfo.ClassName = g_strdup(myClassName); myClassInfo.ParentClass = ObitParentGetClass(); /* Set function pointers */ ObitRMFitClassInfoDefFn ((gpointer)&myClassInfo); myClassInfo.initialized = TRUE; /* Now initialized */ } /* end ObitRMFitClassInit */ /** * Initialize global ClassInfo Function pointers. */ static void ObitRMFitClassInfoDefFn (gpointer inClass) { ObitRMFitClassInfo *theClass = (ObitRMFitClassInfo*)inClass; ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass; if (theClass->initialized) return; /* only once */ /* Check type of inClass */ g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo)); /* Initialize (recursively) parent class first */ if ((ParentClass!=NULL) && (ParentClass->ObitClassInfoDefFn!=NULL)) ParentClass->ObitClassInfoDefFn(theClass); /* function pointers defined or overloaded this class */ theClass->ObitClassInit = (ObitClassInitFP)ObitRMFitClassInit; theClass->newObit = (newObitFP)newObitRMFit; theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitRMFitClassInfoDefFn; theClass->ObitGetClass = (ObitGetClassFP)ObitRMFitGetClass; theClass->ObitCopy = (ObitCopyFP)ObitRMFitCopy; theClass->ObitClone = NULL; theClass->ObitClear = (ObitClearFP)ObitRMFitClear; theClass->ObitInit = (ObitInitFP)ObitRMFitInit; theClass->ObitRMFitCreate = (ObitRMFitCreateFP)ObitRMFitCreate; theClass->ObitRMFitCube = (ObitRMFitCubeFP)ObitRMFitCube; theClass->ObitRMFitImArr = (ObitRMFitImArrFP)ObitRMFitImArr; theClass->ObitRMFitSingle = (ObitRMFitSingleFP)ObitRMFitSingle; } /* end ObitRMFitClassDefFn */ /*---------------Private functions--------------------------*/ /** * Creates empty member objects, initialize reference count. * Parent classes portions are (recursively) initialized first * \param inn Pointer to the object to initialize. */ void ObitRMFitInit (gpointer inn) { ObitClassInfo *ParentClass; ObitRMFit *in = inn; /* error checks */ g_assert (in != NULL); /* recursively initialize parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) ParentClass->ObitInit (inn); /* set members in this class */ in->thread = newObitThread(); in->info = newObitInfoList(); in->nterm = 2; in->nlamb2 = 0; in->minQUSNR = 3.0; in->minFrac = 0.5; in->QRMS = NULL; in->URMS = NULL; in->outDesc = NULL; in->inQFArrays = NULL; in->inUFArrays = NULL; in->outFArrays = NULL; in->lamb2 = NULL; } /* end ObitRMFitInit */ /** * Deallocates member objects. * Does (recursive) deallocation of parent class members. * \param inn Pointer to the object to deallocate. * Actually it should be an ObitRMFit* cast to an Obit*. */ void ObitRMFitClear (gpointer inn) { ObitClassInfo *ParentClass; ObitRMFit *in = inn; olong i, nOut; /* error checks */ g_assert (ObitIsA(in, &myClassInfo)); /* delete this class members */ if (in->QRMS) g_free(in->QRMS); if (in->URMS) g_free(in->URMS); in->thread = ObitThreadUnref(in->thread); in->info = ObitInfoListUnref(in->info); if (in->outDesc) in->outDesc = ObitImageDescUnref(in->outDesc); if (in->inQFArrays) { for (i=0; i<in->nlamb2; i++) in->inQFArrays[i] = ObitFArrayUnref(in->inQFArrays[i]); g_free(in->inQFArrays); } if (in->inUFArrays) { for (i=0; i<in->nlamb2; i++) in->inUFArrays[i] = ObitFArrayUnref(in->inUFArrays[i]); g_free(in->inUFArrays); } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; if (in->outFArrays) { for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayUnref(in->outFArrays[i]); g_free(in->outFArrays); } if (in->lamb2) g_free(in->lamb2); /* unlink parent class members */ ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass); /* delete parent class members */ if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) ParentClass->ObitClear (inn); } /* end ObitRMFitClear */ /** * Does RM fitting, input and output on input object * Work divided up amoung 1 or more threads * In each pixel an RM is fitted if the number of valid data points * exceeds in->nterm, otherwise the pixel is blanked. * If in->doRMSyn then the max value of an RM synthesis is used * The results are stored in outFArrays: * \li first entry is the RM at the reference lambda^2 * \li second is the EVLA (rad) at 0 lambda^2 * \li third is the polarized amplitude at 0 lambda^2 * \li fouurth is the sum of the statistical weights * Otherwise, the results are stored in outFArrays: * \li first entry is the RM at the reference lambda^2 * \li second is the EVLA (rad) at the reference lambda^2 * \li entries nterm+1->nterm*2 RMS uncertainties on coefficients * \li entry 1+nterm*2 = the Chi squared of the fit * * \param in RMFit to fit * \param err Obit error stack object. */ static void Fitter (ObitRMFit* in, ObitErr *err) { olong i, loy, hiy, nyPerThread, nThreads; gboolean OK; NLRMFitArg **threadArgs; NLRMFitArg *args=NULL; ObitThreadFunc func=(ObitThreadFunc)ThreadNLRMFit; gchar *routine = "Fitter"; /* GSL implementation */ #ifdef HAVE_GSL const gsl_multifit_fdfsolver_type *T=NULL; #endif /* HAVE_GSL */ /* error checks */ if (err->error) return; /* Warn if too many terms asked for */ if (in->nterm>2) { Obit_log_error(err, OBIT_InfoWarn, "%s: Asked for %d terms, will limit to 2", routine, in->nterm); } /* How many threads to use? */ nThreads = MAX (1, ObitThreadNumProc(in->thread)); /* Initialize threadArg array */ threadArgs = g_malloc0(nThreads*sizeof(NLRMFitArg*)); for (i=0; i<nThreads; i++) threadArgs[i] = g_malloc0(sizeof(NLRMFitArg)); /* Set up thread arguments */ for (i=0; i<nThreads; i++) { args = (NLRMFitArg*)threadArgs[i]; args->in = in; args->err = err; args->nlamb2 = in->nlamb2; args->maxIter = 100; /* max. number of iterations */ args->minDelta = 1.0e-5; /* Min step size */ args->nterm = in->nterm; args->doError = in->doError; args->minQUSNR = in->minQUSNR; /* min pixel SNR */ args->minFrac = in->minFrac; /* min fraction of samples */ args->Qweight = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uweight = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Qvar = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uvar = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Qobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Uobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->Pobs = g_malloc0(args->nlamb2*sizeof(ofloat)); args->lamb2 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->x = g_malloc0(args->nlamb2*sizeof(double)); args->w = g_malloc0(args->nlamb2*sizeof(double)); args->q = g_malloc0(args->nlamb2*sizeof(double)); args->u = g_malloc0(args->nlamb2*sizeof(double)); args->wrk1 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->wrk2 = g_malloc0(args->nlamb2*sizeof(ofloat)); args->wrk3 = g_malloc0(args->nlamb2*sizeof(ofloat)); if (args->doError) args->coef = g_malloc0(3*args->nterm*sizeof(ofloat)); else args->coef = g_malloc0(args->nterm*sizeof(ofloat)); /* GSL implementation */ #ifdef HAVE_GSL args->solver = NULL; args->covar = NULL; args->work = NULL; /* Setup solver */ T = gsl_multifit_fdfsolver_lmder; args->solver = gsl_multifit_fdfsolver_alloc(T, 2*args->nlamb2, 2); /* Fitting function info */ args->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf)); args->funcStruc->f = &RMFitFunc; args->funcStruc->df = &RMFitJac; args->funcStruc->fdf = &RMFitFuncJac; args->funcStruc->n = 2*args->nlamb2; args->funcStruc->p = 2; args->funcStruc->params = args; /* Set up work arrays */ args->covar = gsl_matrix_alloc(2, 2); args->work = gsl_vector_alloc(2); #endif /* HAVE_GSL */ } /* end initialize */ /* Divide up work */ nyPerThread = in->ny/nThreads; loy = 1; hiy = nyPerThread; hiy = MIN (hiy, in->ny); /* Set up thread arguments */ for (i=0; i<nThreads; i++) { if (i==(nThreads-1)) hiy = in->ny; /* Make sure do all */ args = (NLRMFitArg*)threadArgs[i]; args->first = loy; args->last = hiy; if (nThreads>1) args->ithread = i; else args->ithread = -1; /* Update which y */ loy += nyPerThread; hiy += nyPerThread; hiy = MIN (hiy, in->ny); } /* Do operation possibly with threads */ if (in->doRMSyn) func = (ObitThreadFunc)ThreadRMSynFit; else func = (ObitThreadFunc)ThreadNLRMFit; OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)threadArgs); /* Check for problems */ if (!OK) { Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine); } /* Shut down any threading */ ObitThreadPoolFree (in->thread); if (threadArgs) { for (i=0; i<nThreads; i++) { args = (NLRMFitArg*)threadArgs[i]; if (args->Qweight) g_free(args->Qweight); if (args->Uweight) g_free(args->Uweight); if (args->Qvar) g_free(args->Qvar); if (args->Uvar) g_free(args->Uvar); if (args->Qobs) g_free(args->Qobs); if (args->Uobs) g_free(args->Uobs); if (args->Pobs) g_free(args->Pobs); if (args->lamb2) g_free(args->lamb2); if (args->x) g_free(args->x); if (args->w) g_free(args->w); if (args->q) g_free(args->q); if (args->u) g_free(args->u); if (args->wrk1) g_free(args->wrk1); if (args->wrk2) g_free(args->wrk2); if (args->wrk3) g_free(args->wrk3); if (args->coef) g_free(args->coef); #ifdef HAVE_GSL if (args->solver) gsl_multifit_fdfsolver_free (args->solver); if (args->work) gsl_vector_free(args->work); if (args->covar) gsl_matrix_free(args->covar); if (args->funcStruc) g_free(args->funcStruc); #endif /* HAVE_GSL */ g_free(threadArgs[i]); } g_free(threadArgs); } } /* end Fitter */ /** * Write contents on in to outImage * \param in RM fitting object * \param outImage Image cube with fitted spectra. * Should be defined but not created. * Planes 1->nterm are coefficients per pixel * Planes nterm+1->2*nterm are uncertainties in coefficients * \param err Obit error stack object. */ static void WriteOutput (ObitRMFit* in, ObitImage *outImage, ObitErr *err) { olong iplane, nOut; ObitIOSize IOBy; olong i, blc[IM_MAXDIM], trc[IM_MAXDIM]; ObitIOCode retCode; gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}; gchar *routine = "WriteOutput"; /* error checks */ if (err->error) return; g_assert (ObitIsA(in, &myClassInfo)); g_assert(ObitImageIsA(outImage)); /* Open output- all, by plane */ dim[0] = IM_MAXDIM; for (i=0; i<IM_MAXDIM; i++) blc[i] = 1; for (i=0; i<IM_MAXDIM; i++) trc[i] = 0; ObitInfoListPut (outImage->info, "BLC", OBIT_long, dim, blc, err); ObitInfoListPut (outImage->info, "TRC", OBIT_long, dim, trc, err); IOBy = OBIT_IO_byPlane; dim[0] = 1; ObitInfoListAlwaysPut (outImage->info, "IOBy", OBIT_long, dim, &IOBy); outImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */ retCode = ObitImageOpen (outImage, OBIT_IO_ReadWrite, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); /* save descriptive material */ ObitImageDescCopyDesc (in->outDesc, outImage->myDesc, err); if (err->error) Obit_traceback_msg (err, routine, outImage->name); /* How many output planes? */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* always 4 for doRMSyn */ if (in->doRMSyn) nOut = 4; /* Loop writing planes */ for (iplane=0; iplane<nOut; iplane++) { retCode = ObitImageWrite (outImage, in->outFArrays[iplane]->array, err); /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); } /* end loop writing planes */ /* Save nterms on output descriptor */ dim[0] = dim[1] = dim[2] = 1; ObitInfoListAlwaysPut (outImage->myDesc->info, "NTERM", OBIT_long, dim, &in->nterm); ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, "NTERM", OBIT_long, dim, &in->nterm); /* Close output */ retCode = ObitImageClose (outImage, err); outImage->extBuffer = FALSE; /* May need I/O buffer later */ /* if it didn't work bail out */ if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name); } /* end WriteOutput */ /** * Thread function to fit a portion of the image set * \param arg NLRMFitArg structure */ static gpointer ThreadNLRMFit (gpointer arg) { NLRMFitArg *larg = (NLRMFitArg*)arg; ObitRMFit* in = (ObitRMFit*)larg->in; olong lo = larg->first-1; /* First in y range */ olong hi = larg->last; /* Highest in y range */ gboolean doError = larg->doError; /* Error analysis? */ ObitErr *err = larg->err; olong ix, iy, indx, i, nOut; ofloat fblank = ObitMagicF(); /*gchar *routine = "ThreadNLRMFit";*/ /* error checks */ if (err->error) return NULL; g_assert (ObitIsA(in, &myClassInfo)); /* Set up frequency info */ larg->refLamb2 = in->refLamb2; for (i=0; i<in->nlamb2; i++) { larg->lamb2[i] = in->lamb2[i]; } /* How many output planes */ if (in->doError) nOut = 1+in->nterm*2; else nOut = in->nterm; /* Loop over pixels in Y */ indx = lo*in->nx -1; /* Offset in pixel arrays */ for (iy=lo; iy<hi; iy++) { /* Loop over pixels in X */ for (ix=0; ix<in->nx; ix++) { indx ++; /* Collect values; */ for (i=0; i<in->nlamb2; i++) { larg->Qobs[i] = in->inQFArrays[i]->array[indx]; larg->Uobs[i] = in->inUFArrays[i]->array[indx]; /* Data valid? */ if ((larg->Qobs[i]!=fblank) && (larg->Uobs[i]!=fblank) && ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) || (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) { /* Statistical weight */ larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]); larg->Uvar[i] = (in->URMS[i]*in->URMS[i]); larg->Pobs[i] = sqrt (larg->Qobs[i]*larg->Qobs[i] + larg->Uobs[i]*larg->Uobs[i]); /* larg->Qweight[i] = larg->Pobs[i] / larg->Qvar[i]; larg->Uweight[i] = larg->Pobs[i] / larg->Uvar[i];*/ larg->Qweight[i] = 1.0 / in->QRMS[i]; larg->Uweight[i] = 1.0 / in->URMS[i]; /* End if datum valid */ } else { /* invalid pixel */ larg->Qweight[i] = 0.0; larg->Qvar[i] = 0.0; larg->Uweight[i] = 0.0; larg->Uvar[i] = 0.0; larg->Pobs[i] = 0.0; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"%3d q=%g u=%g qs=%g us=%g wt=%f\n", i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]); } */ } /* end loop over frequencies */ /* Fit */ NLRMFit(larg); /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"ix=%4d iy=%4d\n",ix+1,iy+1); fprintf (stderr,"RM=%f EVPA=%f chi2=%f\n", larg->coef[0], larg->coef[1],larg->coef[4]); } */ /* Save to output */ if (doError) { for (i=0; i<nOut; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } else { /* only values */ for (i=0; i<in->nterm; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } } /* end x loop */ } /* end y loop */ /* Indicate completion */ if (larg->ithread>=0) ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread); return NULL; } /* end ThreadNLRMFit */ /** * Fit RM and EVPA at the reference lambda^2 * Only fits for up to 5 terms * \param arg NLRMFitArg structure * fitted parameters returned in arg->in->coef * RM, EVPA, sig RM, sig EVPA, chi2 */ static void NLRMFit (NLRMFitArg *arg) { olong iter=0, i, nterm=2, nvalid; ofloat sumwt, fblank = ObitMagicF(); double chi2; int status; /* Initialize output */ if (arg->doError) for (i=0; i<2*nterm+1; i++) arg->coef[i] = 0.0; else for (i=0; i<nterm; i++) arg->coef[i] = 0.0; /* Blank */ arg->coef[0] = arg->coef[1] = fblank; /* try to unwrap EVPA, get data to be fitted, returns number of valid data and crude fits */ nvalid = RMcoarse (arg); if (nvalid<=MAX(2,nterm)) return; /* enough good data for fit? */ /* High enough fraction of valid pixels? */ if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return; /* Do fit */ #ifdef HAVE_GSL /* order EVPA, RM */ gsl_vector_set(arg->work, 0, (double)arg->coef[1]); gsl_vector_set(arg->work, 1, (double)arg->coef[0]); arg->funcStruc->n = arg->nlamb2*2; arg->funcStruc->p = nterm; arg->funcStruc->params = arg; gsl_multifit_fdfsolver_set (arg->solver, arg->funcStruc, arg->work); iter = 0; /* iteration loop */ do { iter++; status = gsl_multifit_fdfsolver_iterate(arg->solver); /*if (status) break;???*/ status = gsl_multifit_test_delta (arg->solver->dx, arg->solver->x, (double)arg->minDelta, (double)arg->minDelta); /* DEBUG if (nvalid>nterm) { sumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f); chi2 = (sumwt*sumwt)/(nvalid-nterm); } else chi2 = -1.0; for (i=0; i<nterm; i++) arg->coef[i] = (ofloat)gsl_vector_get(arg->solver->x, i); fprintf (stderr," iter=%d RM %f EVPA %f chi2 %g status %d\n", iter, arg->coef[1], arg->coef[0], chi2, status); */ /* end DEBUG */ } while ((status==GSL_CONTINUE) && (iter<arg->maxIter)); /* If it didn't work - bail */ if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) { fprintf (stderr, "Failed, status = %s\n", gsl_strerror(status)); return; } /* normalized Chi squares */ if (nvalid>nterm) { sumwt = (ofloat)gsl_blas_dnrm2(arg->solver->f); chi2 = (sumwt*sumwt)/(nvalid-nterm); } else chi2 = -1.0; /* Get fitted values - switch order to RM, EVPA*/ arg->coef[0] = (ofloat)gsl_vector_get(arg->solver->x, 1); arg->coef[1] = (ofloat)gsl_vector_get(arg->solver->x, 0); /* Errors wanted? */ if (arg->doError) { gsl_matrix *J; /* second argument removes degenerate col/row from Jacobean */ J = gsl_matrix_alloc(2*arg->nlamb2, 2); #ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC gsl_multifit_fdfsolver_jac(arg->solver, J); #else gsl_matrix_memcpy(J, arg->solver->J); #endif gsl_multifit_covar (J, 1.0e-8, arg->covar); gsl_matrix_free(J); arg->coef[nterm+0] = sqrt(gsl_matrix_get(arg->covar, 1, 1)); arg->coef[nterm+1] = sqrt(gsl_matrix_get(arg->covar, 0, 0)); arg->coef[4] = chi2; } /* end of get errors */ #endif /* HAVE_GSL */ } /* end NLRMFit */ /** * Make crude estimate of RM, EVPA and populate argument arrays * \param arg NLRMFitArg structure * Data to be fitted in x,q,u,w * RM, EVPA in coef * \return number of valid data */ static olong RMcoarse (NLRMFitArg *arg) { olong i, j, ntest, nvalid, numb; ofloat minDL, maxDL, dRM, tRM, bestRM=0.0, fblank = ObitMagicF(); ofloat bestQ, bestU, sumrQ, sumrU, penFact; double aarg, varaarg; odouble amb, res, best, test; /* get EVLA values count valid data*/ nvalid = 0; numb = 0; for (i=0; i<arg->nlamb2; i++) { if ((arg->Qobs[i]!=fblank) && (arg->Qweight[i]>0.0) && (arg->Uobs[i]!=fblank) && (arg->Uweight[i]>0.0)) { arg->x[numb] = arg->lamb2[i] - arg->refLamb2; /* Weight */ aarg = fabs(arg->Uobs[i]/arg->Qobs[i]); varaarg = aarg*aarg*(arg->Qvar[i]/(arg->Qobs[i]*arg->Qobs[i]) + arg->Uvar[i]/(arg->Uobs[i]*arg->Uobs[i])); arg->w[numb] = (1.0+aarg*aarg)/varaarg; /* arg->q[numb] = arg->Qobs[i] * arg->w[numb]; arg->u[numb] = arg->Uobs[i] * arg->w[numb];*/ arg->q[numb] = arg->Qobs[i]; arg->u[numb] = arg->Uobs[i]; /* DEBUG fprintf (stderr, "%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \n ", numb,arg->x[numb], arg->q[numb],arg->u[numb],arg->w[numb]); arg->Qweight[i] = arg->Uweight[i] = 1.0/20.0e-6; fprintf (stderr,"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\n", i,arg->lamb2[i]-arg->refLamb2, arg->Qobs[i], arg->Uobs[i],arg->Pobs[i], arg->Qweight[i], arg->Uweight[i]);*/ numb++; } } nvalid = numb; if (nvalid<=MAX(2,arg->nterm)) return nvalid; /* enough good data for fit? */ /* High enough fraction of valid pixels? */ if ((((ofloat)nvalid)/((ofloat)arg->nlamb2)) < arg->minFrac) return nvalid; arg->nvalid = nvalid; /* max and min delta lamb2 - assume lamb2 ordered */ maxDL = fabs(arg->x[0]-arg->x[numb-1]); /* range of actual delta lamb2 */ minDL = 1.0e20; for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(arg->x[i]-arg->x[i-1])); /* ambiguity = pi/min_dlamb2 resolution = pi/max_dlamb2 = RM which gives 1 turn over lamb2 range */ amb = G_PI / fabs(minDL); res = G_PI / maxDL; dRM = 0.05 * res; /* test RM interval */ /* DEBUG fprintf (stderr,"amb = %f res= %f dRM=%f\n", amb, res, dRM); */ /* end DEBUG */ /* Test +/- half ambiguity every dRM */ ntest = 1 + 0.5*amb/dRM; ntest = MIN (ntest, 1001); /* Some bounds */ /* Penalty to downweight solutions away from zero, weight 0.25 at edge of search */ penFact = 0.25 / (0.5*ntest); best = -1.0e20; for (i=0; i<ntest; i++) { tRM = (i-ntest/2) * dRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<numb; j++) arg->wrk1[j]= -2*tRM * arg->x[j]; /* sines/cosine */ ObitSinCosVec (numb, arg->wrk1, arg->wrk3, arg->wrk2); /* DEBUG if ((fabs(tRM-133.0)<0.95*dRM) || (fabs(tRM-133.)<0.95*dRM)) { for (j=0; j<numb; j++) { test = (arg->q[j]*arg->wrk2[j])*(arg->q[j]*arg->wrk2[j]) + (arg->u[j]*arg->wrk3[j])*(arg->u[j]*arg->wrk3[j]); fprintf (stderr," i=%d j=%d t phase=%f obs phase %lf q=%f u=%lf test=%f\n", i, j, arg->wrk1[j], 0.5*atan2(arg->u[j],arg->q[j]), (arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j])*1000, (arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j])*1000, test); } } */ /* end DEBUG*/ /* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */ test = 0.0; sumrQ = sumrU = 0.0; for (j=0; j<numb; j++) { sumrQ += arg->w[j]*(arg->q[j]*arg->wrk2[j] - arg->u[j]*arg->wrk3[j]); sumrU += arg->w[j]*(arg->q[j]*arg->wrk3[j] + arg->u[j]*arg->wrk2[j]); } test = sumrQ*sumrQ + sumrU*sumrU; /* Add penalty */ test *= (1.0 - penFact*abs(i-ntest/2)); /* DEBUG fprintf (stderr," i=%d test=%g tRM %f sum Q=%f sum U=%f pen %f\n", i, test, tRM, sumrQ, sumrU, penFact*abs(i-ntest/2));*/ /* end DEBUG */ if (test>best) { best = test; bestRM = tRM; bestQ = sumrQ; bestU = sumrU; } } /* Save */ arg->coef[0] = bestRM; arg->coef[1] = 0.5 * atan2(bestU, bestQ); /* DEBUG fprintf (stderr,"RM = %f EVPA= %f best=%f dRM=%f\n", arg->coef[1],arg->coef[0], best, dRM); */ /* end DEBUG */ return nvalid; } /* end RMcoarse */ #ifdef HAVE_GSL /** * Function evaluator for spectral fitting solver * Evaluates (model-observed) / sigma * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param f Vector of (model-obs)/sigma for data points * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitFunc (const gsl_vector *x, void *params, gsl_vector *f) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); olong nlamb2 = args->nlamb2; double func; odouble RM, EVPA; size_t i, j; /* DEBUG odouble sum=0.0; */ /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FitFunc RM=%f EVPA=%f\n", RM,EVPA); */ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - Residuals */ for (i=0; i<nlamb2; i++) { /* Q model = args->Pobs[i] * args->wrk2[i] */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i]; /* sum += func*func; DEBUG fprintf (stderr,"FitFunc q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\n", 2*i, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->Pobs[i]); */ gsl_vector_set(f, 2*i, func); /* Save function residual */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i, func); /* Save function residual */ } /* U model = args->Pobs[i] * args->wrk3[i] */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i]; /* sum += func*func; DEBUG fprintf (stderr,"FitFunc u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\n", 2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->wrk1[i]*28.648); */ gsl_vector_set(f, 2*i+1, func); /* Save function residual */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i+1, func); /* Save function residual */ } } /* End loop over data */ /* DEBUG fprintf (stderr,"FitFunc RMS=%g\n", sqrt(sum)); */ return GSL_SUCCESS; } /* end RMFitFunc */ /** * Jacobian evaluator for spectral fitting solver * Evaluates partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param J Jacobian matrix J[data_point, parameter] * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitJac (const gsl_vector *x, void *params, gsl_matrix *J) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); olong nlamb2 = args->nlamb2; odouble RM, EVPA; double jac; size_t i, j; /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FitJac RM=%f EVPA=%f\n", RM,EVPA);*/ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - gradients */ for (i=0; i<nlamb2; i++) { j = 0; /* EVPA */ /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i] */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i]; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i] */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i]; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } j = 1; /* RM */ /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2) */ if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { jac = -2*(args->Pobs[i] * args->wrk3[i]) * (args->lamb2[i]-args->refLamb2) * args->Qweight[i]; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } /* d U model/d RM = 2 args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */ if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { jac = 2*(args->Pobs[i] * args->wrk2[i]) * (args->lamb2[i]-args->refLamb2) * args->Uweight[i]; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } } /* End loop over data */ return GSL_SUCCESS; } /* end RMFitJac */ /** * Function and Jacobian evaluator for spectral fitting solver * Function = (model-observed) / sigma * Jacobian = partial derivatives of model wrt each parameter * \param x Vector of parameters to be fitted * Flux,array_of spectral_terms * \param param Function parameter structure (NLRMFitArg) * \param f Vector of (model-obs)/sigma for data points * in order q, u each datum * \param J Jacobian matrix J[data_point, parameter] * in order q, u each datum * \return completion code GSL_SUCCESS=OK */ static int RMFitFuncJac (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J) { NLRMFitArg *args = (NLRMFitArg*)params; ofloat fblank = ObitMagicF(); double func, jac; olong nlamb2 = args->nlamb2; odouble RM, EVPA; size_t i, j; /* DEBUG odouble sum=0.0; */ /* get model parameters */ EVPA = gsl_vector_get(x, 0); RM = gsl_vector_get(x, 1); /* DEBUG fprintf (stderr,"FuncJac RM=%f EVPA=%f\n", RM,EVPA); */ /* First compute model phases */ for (j=0; j<nlamb2; j++) args->wrk1[j] = 2*(EVPA + RM * (args->lamb2[j]-args->refLamb2)); /* then sine/cosine */ ObitSinCosVec (nlamb2, args->wrk1, args->wrk3, args->wrk2); /* Loop over data - gradients */ for (i=0; i<nlamb2; i++) { if ((args->Qobs[i]!=fblank) && (args->Qweight[i]>0.0)) { /* Q model = args->Pobs[i] * args->wrk2[i] */ func = (args->Pobs[i] * args->wrk2[i] - args->Qobs[i]) * args->Qweight[i]; /* sum += func*func; DEBUG */ /* DEBUG fprintf (stderr,"FuncJac q i=%3ld func=%lg obs=%g mod=%g wt=%g p=%f\n", 2*i, func, args->Qobs[i], args->Pobs[i] * args->wrk2[i], args->Qweight[i], args->Pobs[i]); */ gsl_vector_set(f, 2*i, func); /* Save function residual */ j = 0; /* EVPA */ /* d Q model/d EVPA = -args->Pobs[i] * args->wrk3[i] */ jac = -(args->Pobs[i] * args->wrk3[i]) * args->Qweight[i]; /* DEBUG fprintf (stderr,"FuncJac q i=%3ld j=%3ld jac=%lf\n", 2*i, j, jac); */ gsl_matrix_set(J, 2*i, j, jac); /* Save function residual */ j = 1; /* RM */ /* d Q model/d RM = -2 args->Pobs[i] * args->wrk3[i] * (args->lamb2[i]-args->refLamb2) */ jac = -2*(args->Pobs[i] * args->wrk3[i]) * (args->lamb2[i]-args->refLamb2) * args->Qweight[i]; /* DEBUG fprintf (stderr,"FuncJac q i=%3ld j=%3ld jac=%lf\n", 2*i+1, j, jac);*/ gsl_matrix_set(J, 2*i, j, jac); /* Save function gradient */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i, func); j = 0; /* EVPA */ jac = 0.0; gsl_matrix_set(J, 2*i, j, jac); j = 1; /* RM */ gsl_matrix_set(J, 2*i, j, jac); } if ((args->Uobs[i]!=fblank) && (args->Uweight[i]>0.0)) { /* U model = 2 args->Pobs[i] * args->wrk3[i] */ func = (args->Pobs[i] * args->wrk3[i] - args->Uobs[i]) * args->Uweight[i]; /* sum += func*func; DEBUG */ /* DEBUG fprintf (stderr,"FuncJac u i=%3ld func=%lg obs=%g mod=%g wt=%g phs=%f\n", 2*i+1, func, args->Uobs[i], args->Pobs[i]*args->wrk3[i], args->Uweight[i], args->wrk1[i]*28.648); */ gsl_vector_set(f, 2*i+1, func); /* Save function residual */ j = 0; /* EVPA */ /* d U model/d EVPA = args->Pobs[i] * args->wrk2[i] */ jac = (args->Pobs[i] * args->wrk2[i]) * args->Uweight[i]; /* DEBUG fprintf (stderr,"FuncJac u i=%3ld j=%3ld jac=%lf\n", 2*i, j, jac); */ gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ j = 1; /* RM */ /* d U model/d RM = args->Pobs[i] * args->wrk2[i] * (args->lamb2[i]-args->refLamb2) */ jac = 2*(args->Pobs[i] * args->wrk2[i]) * (args->lamb2[i]-args->refLamb2) * args->Uweight[i]; /* DEBUG fprintf (stderr,"FuncJac u i=%3ld j=%3ld jac=%lf\n", 2*i+1, j, jac); */ gsl_matrix_set(J, 2*i+1, j, jac); /* Save function gradient */ } else { /* Invalid data */ func = 0.0; gsl_vector_set(f, 2*i+1, func); j = 0; /* EVPA */ jac = 0.0; gsl_matrix_set(J, 2*i+1, j, jac); j = 1; /* RM */ gsl_matrix_set(J, 2*i+1, j, jac); } } /* End loop over data */ /* DEBUG fprintf (stderr,"FuncJac RMS=%g\n", sqrt(sum)); */ return GSL_SUCCESS; } /* end RMFitFuncJac */ #endif /* HAVE_GSL */ /* RM Synthesis max routines */ /** * Thread function to RM Synthesis Max fit a portion of the image set * \param arg NLRMFitArg structure * \li coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U */ static gpointer ThreadRMSynFit (gpointer arg) { NLRMFitArg *larg = (NLRMFitArg*)arg; ObitRMFit* in = (ObitRMFit*)larg->in; olong lo = larg->first-1; /* First in y range */ olong hi = larg->last; /* Highest in y range */ ObitErr *err = larg->err; olong ix, iy, indx, i, besti; ofloat fblank = ObitMagicF(); olong j, ntest, nvalid, numb; ofloat minDL, maxDL, dRM, tRM, bestRM=0.0; ofloat bestQ, bestU, sumrQ, sumrU, sumW=0.0, EVPA, amp; double aarg, varaarg; odouble amb, res, best, test; /*gchar *routine = "ThreadRMSynFit";*/ /* error checks */ if (err->error) return NULL; g_assert (ObitIsA(in, &myClassInfo)); /* Set up frequency info if in given */ if (in) { larg->refLamb2 = in->refLamb2; for (i=0; i<in->nlamb2; i++) { larg->lamb2[i] = in->lamb2[i]; } } /* Loop over pixels in Y */ indx = lo*in->nx -1; /* Offset in pixel arrays */ for (iy=lo; iy<hi; iy++) { /* Loop over pixels in X */ for (ix=0; ix<in->nx; ix++) { indx ++; /* Collect values; */ for (i=0; i<in->nlamb2; i++) { larg->Qobs[i] = in->inQFArrays[i]->array[indx]; larg->Uobs[i] = in->inUFArrays[i]->array[indx]; /* Data valid? */ if ((larg->Qobs[i]!=fblank) && (larg->Uobs[i]!=fblank) && ((fabs(larg->Qobs[i])>in->minQUSNR*in->QRMS[i]) || (fabs(larg->Uobs[i])>in->minQUSNR*in->URMS[i]))) { /* Statistical weight */ larg->Qvar[i] = (in->QRMS[i]*in->QRMS[i]); larg->Uvar[i] = (in->URMS[i]*in->URMS[i]); larg->Qweight[i] = 1.0 / in->QRMS[i]; larg->Uweight[i] = 1.0 / in->URMS[i]; /* End if datum valid */ } else { /* invalid pixel */ larg->Qweight[i] = 0.0; larg->Uweight[i] = 0.0; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"%3d q=%g u=%g qs=%g us=%g wt=%f\n", i, larg->Qobs[i], larg->Uobs[i], in->QRMS[i], in->URMS[i], larg->Qweight[i]); } */ } /* end loop over frequencies */ /* Fit coef[0]=RM, coef[1]=amp, coef[2]=phase, coef[3]=RMS Q,U */ /* get values count valid data*/ numb = 0; sumW = 0.0; for (i=0; i<larg->nlamb2; i++) { if ((larg->Qweight[i]>0.0) && (larg->Uweight[i]>0.0)) { larg->x[numb] = larg->lamb2[i] - larg->refLamb2; /* Weight of polarized amplitude */ aarg = fabs(larg->Uobs[i]/larg->Qobs[i]); varaarg = aarg*aarg*(larg->Qvar[i]/(larg->Qobs[i]*larg->Qobs[i]) + larg->Uvar[i]/(larg->Uobs[i]*larg->Uobs[i])); larg->w[numb] = (1.0+aarg*aarg)/varaarg; larg->q[numb] = larg->Qobs[i]; larg->u[numb] = larg->Uobs[i]; sumW += larg->w[numb]; /* DEBUG fprintf (stderr, "%3d x=%8.5f q=%8.5f u=%8.5f w=%8.5g \n ", numb,larg->x[numb], larg->q[numb],larg->u[numb],larg->w[numb]); larg->Qweight[i] = larg->Uweight[i] = 1.0/20.0e-6; fprintf (stderr,"%3d l2=%g q=%g u=%g p=%f qwt=%g uwt=%g\n", i,larg->lamb2[i]-larg->refLamb2, larg->Qobs[i], larg->Uobs[i],larg->Pobs[i], larg->Qweight[i], larg->Uweight[i]);*/ numb++; } } nvalid = numb; /* enough data? */ if ((nvalid<=2) || ((((ofloat)nvalid)/((ofloat)larg->nlamb2)) < larg->minFrac)) { bestRM = EVPA = fblank; amp = 0.0; sumrQ = sumrU = 1000.0; goto doneFit; } /* max and min delta lamb2 - assume lamb2 ordered */ maxDL = fabs(larg->x[0]-larg->x[numb-1]); /* range of actual delta lamb2 */ minDL = 1.0e20; for (i=1; i<numb; i++) minDL = MIN (minDL, fabs(larg->x[i]-larg->x[i-1])); /* ambiguity = pi/min_dlamb2 resolution = pi/max_dlamb2 = RM which gives 1 turn over lamb2 range */ if (in->maxRMSyn>in->minRMSyn) { dRM = MAX (0.01,in->delRMSyn); ntest = 1+(in->maxRMSyn - in->minRMSyn)/dRM; } else { amb = G_PI / fabs(minDL); res = G_PI / maxDL; dRM = 0.05 * res; /* test RM interval */ /* Test +/- 0.05 ambiguity every dRM */ ntest = 1 + amb/(0.05*dRM); dRM *= 0.05; in->minRMSyn = -(ntest/2) * dRM; } ntest = MIN (ntest, 10001); /* Some bounds */ /* DEBUG fprintf (stderr,"amb = %f res= %f dRM=%f\n", amb, res, dRM); */ /* end DEBUG */ best = -1.0e20; besti = 0; for (i=0; i<ntest; i++) { tRM = in->minRMSyn + i * dRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<numb; j++) larg->wrk1[j]= -2*tRM * larg->x[j]; /* sines/cosine */ ObitSinCosVec (numb, larg->wrk1, larg->wrk3, larg->wrk2); /* Find best sum of weighted amplitudes^2 converted to ref lambda^2 */ test = 0.0; sumrQ = sumrU = 0.0; for (j=0; j<numb; j++) { sumrQ += larg->w[j]*(larg->q[j]*larg->wrk2[j] - larg->u[j]*larg->wrk3[j]); sumrU += larg->w[j]*(larg->q[j]*larg->wrk3[j] + larg->u[j]*larg->wrk2[j]); } test = sumrQ*sumrQ + sumrU*sumrU; /* DEBUG fprintf (stderr," i=%d test=%g tRM %f sum Q=%f sum U=%f pen %f\n", i, test, tRM, sumrQ, sumrU, penFact*abs(i-ntest/2));*/ /* end DEBUG */ if (test>best) { besti = i; best = test; bestRM = tRM; bestQ = sumrQ; bestU = sumrU; } } /* Get chi sq for fit */ EVPA = 0.5 * atan2(bestU, bestQ); amp = sqrtf(bestU*bestU + bestQ*bestQ)/sumW; tRM = bestRM; /* Loop over data samples - first phases to convert to ref Lamb2 */ for (j=0; j<larg->nlamb2; j++) larg->wrk1[j]= 2*tRM * (larg->lamb2[j]-larg->refLamb2) + 2.0*EVPA; /* sines/cosine */ ObitSinCosVec (larg->nlamb2, larg->wrk1, larg->wrk3, larg->wrk2); sumrQ = sumrU = 0.0; numb = 0; for (j=0; j<larg->nlamb2; j++) { if ((larg->Qweight[j]>0.0) && (larg->Uweight[j]>0.0)) { numb += 2; sumrQ += (larg->Qobs[j]-amp*larg->wrk2[j])*(larg->Qobs[j]-amp*larg->wrk2[j])/larg->Qvar[j]; sumrU += (larg->Uobs[j]-amp*larg->wrk3[j])*(larg->Uobs[j]-amp*larg->wrk3[j])/larg->Uvar[j]; } } sumrQ /= numb; sumrU /= numb; /* Save */ doneFit: larg->coef[0] = bestRM; larg->coef[1] = EVPA; larg->coef[2] = amp; larg->coef[3] = (sumrQ+sumrU); /* Edit */ if ((larg->coef[3]>in->maxChi2) || (besti<=0) || (besti>=(ntest-1))) { larg->coef[0] = larg->coef[1] = fblank; } /* DEBUG if ((ix==669) && (iy==449)) { fprintf (stderr,"ix=%4d iy=%4d\n",ix+1,iy+1); fprintf (stderr,"RM=%f EVPA=%f chi2=%f\n", larg->coef[0], larg->coef[1],larg->coef[4]); } */ /* Save to output */ for (i=0; i<4; i++) in->outFArrays[i]->array[indx] = larg->coef[i]; } /* end x loop */ } /* end y loop */ /* Indicate completion */ if (larg->ithread>=0) ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread); return NULL; } /* end ThreadRMSynFit */
{ "alphanum_fraction": 0.6054401261, "avg_line_length": 37.0004290004, "ext": "c", "hexsha": "5e486e4b687338e6754e2332f03e485084fa130d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "kettenis/Obit", "max_forks_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "kettenis/Obit", "max_issues_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "kettenis/Obit", "max_stars_repo_path": "ObitSystem/Obit/src/ObitRMFit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 29408, "size": 86248 }
#pragma once #include <gsl/gsl> namespace Halley { // Note: it's important that this class has the same layout and binary structure as a plain pointer template <typename T> class MaybeRef { public: MaybeRef() : pointer(nullptr) {} MaybeRef(T* pointer) : pointer(pointer) {} MaybeRef(T& ref) : pointer(&ref) {} bool hasValue() const { return pointer != nullptr; } T& get() { Expects(pointer != nullptr); return *pointer; } const T& get() const { Expects(pointer != nullptr); return *pointer; } T* operator->() { Expects(pointer != nullptr); return pointer; } const T* operator->() const { Expects(pointer != nullptr); return pointer; } operator bool() const { return pointer != nullptr; } T* tryGet() { return pointer; } const T* tryGet() const { return pointer; } private: T* pointer; }; }
{ "alphanum_fraction": 0.4764808362, "avg_line_length": 18.5161290323, "ext": "h", "hexsha": "a94b7761b05b6c767802f85f40f8fef8e00a5995", "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/utils/include/halley/data_structures/maybe_ref.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/utils/include/halley/data_structures/maybe_ref.h", "max_line_length": 103, "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/utils/include/halley/data_structures/maybe_ref.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": 251, "size": 1148 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> int main(void) { const size_t N = 500; /* length of time series */ const size_t K = 11; /* window size */ gsl_movstat_workspace * w = gsl_movstat_alloc(K); gsl_vector *x = gsl_vector_alloc(N); gsl_vector *xmean = gsl_vector_alloc(N); gsl_vector *xmin = gsl_vector_alloc(N); gsl_vector *xmax = gsl_vector_alloc(N); gsl_rng *r = gsl_rng_alloc(gsl_rng_default); size_t i; for (i = 0; i < N; ++i) { double xi = cos(4.0 * M_PI * i / (double) N); double ei = gsl_ran_gaussian(r, 0.1); gsl_vector_set(x, i, xi + ei); } /* compute moving statistics */ gsl_movstat_mean(GSL_MOVSTAT_END_PADVALUE, x, xmean, w); gsl_movstat_minmax(GSL_MOVSTAT_END_PADVALUE, x, xmin, xmax, w); /* print results */ for (i = 0; i < N; ++i) { printf("%zu %f %f %f %f\n", i, gsl_vector_get(x, i), gsl_vector_get(xmean, i), gsl_vector_get(xmin, i), gsl_vector_get(xmax, i)); } gsl_vector_free(x); gsl_vector_free(xmean); gsl_rng_free(r); gsl_movstat_free(w); return 0; }
{ "alphanum_fraction": 0.5996944232, "avg_line_length": 24.6981132075, "ext": "c", "hexsha": "2d119c2a18a9ca017db386071c8c6fae8d4e2489", "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/doc/examples/movstat1.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/doc/examples/movstat1.c", "max_line_length": 72, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/movstat1.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": 394, "size": 1309 }
/* Copyright (C) 2006-2008 Luis Matos, A. Castro This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. $Id: poisson_cutoffs.c 13812 2015-04-09 01:25:06Z dstrubbe $ */ #include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_expint.h> #include <gsl/gsl_errno.h> #include <assert.h> #include <config.h> #define M_EULER_MASCHERONI 0.5772156649015328606065120 /* This file contains the definition of functions used by Fortran module poisson_cutoff_m. There are four functions to be defined: c_poisson_cutoff_3d_1d_finite: For the cutoff of 3D/0D cases, in which however we want the region of the cutoff to be a cylinder. c_poisson_cutoff_2d_0d: c_poisson_cutoff_2d_1d: */ /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_3D_1D_FINITE */ /************************************************************************/ /************************************************************************/ struct parameters { double kx; double kr; double x0; double r0; int index; }; /* the index is the type of integral. This is necessary because depending of the value of k the the integral needs to be performed in different ways */ #define PFC_F_0 0 #define PFC_F_KX 1 #define PFC_F_KR 2 static const double tol = 1e-7; static double zero = 1e-100; static double f(double w, void *p) { struct parameters *params = (struct parameters *)p; const double kx = (params->kx); double kr = (params->kr); double x0 = (params->x0); double r0 = (params->r0); int index = (params->index); double result; if (w == 0) w = zero; if (fabs(kx - w) > tol){ result = sin((kx - w)*x0)/(kx - w)* sqrt(pow(w, 2.0*index)*pow(r0, 2.0*index))/(kr*kr + w*w) *gsl_sf_bessel_Kn(index, r0*fabs(w)); } else{ result = x0*sqrt(pow(w, 2.0*index))/(kr*kr + w*w)*gsl_sf_bessel_Kn(index, r0*fabs(w)); } return result; } static double f_kx_zero(double w, void *p) { struct parameters *params = (struct parameters *)p; double kr = (params->kr); double x0 = (params->x0); double result; if (w == 0.0) w = zero; result = 2.0*M_PI*w*gsl_sf_bessel_J0(kr*w)* (log(x0 + sqrt(w*w + x0*x0)) - log(-x0 + sqrt(w*w + x0*x0))); return result; } static double f_kr_zero(double w, void *p) { struct parameters *params = (struct parameters *)p; double kx = (params->kx); double r0 = (params->r0); double result; result = 4.0*M_PI*cos(kx*w)*(sqrt(r0*r0 + w*w) - fabs(w)); return result; } static double int_aux(int index, double kx, double kr, double x0, double r0, int which_int) { /*variables*/ double result, error; double xinf = 100.0/r0; struct parameters params; /*pass the given parameters to program*/ const size_t wrk_size = 5000; /* I believe that 1e-6 is over-killing, a substantial gain in time is obtained by setting this threshold to 1e-3 */ /* const double epsilon_abs = 1e-6; */ /* const double epsilon_rel = 1e-6; */ const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; /*creating the workspace*/ gsl_integration_workspace * ws = gsl_integration_workspace_alloc (wrk_size); /*create the function*/ gsl_function F; assert(which_int == PFC_F_0 || which_int == PFC_F_KR || which_int == PFC_F_KX); params.kx = kx; params.kr = kr; params.x0 = x0; params.r0 = r0; params.index = index; F.params = &params; /*select the integration method*/ switch(which_int){ case PFC_F_0: F.function = &f; gsl_integration_qag(&F, -xinf, xinf, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; case PFC_F_KX: F.function = &f_kx_zero; gsl_integration_qag (&F, 0.0, r0, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; case PFC_F_KR: F.function = &f_kr_zero; gsl_integration_qag (&F, 0.0, x0, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); break; } /*free the integration workspace*/ gsl_integration_workspace_free (ws); /*return*/ return result; } double poisson_finite_cylinder(double kx, double kr, double x0,double r0) { double result; if ((kx>=tol) & (kr>=tol)) { result = 4.0*kr*r0*gsl_sf_bessel_Jn(1, kr*r0)*int_aux(0, kx, kr, x0, r0, PFC_F_0) - 4.0*gsl_sf_bessel_Jn(0, kr*r0)*int_aux(1, kx, kr, x0, r0, PFC_F_0) + 4.0*M_PI/(kx*kx + kr*kr)*(1.0 + exp(-kr*x0)*(kx/kr*sin(kx*x0) - cos(kx*x0))); } else if ((kx < tol) & (kr >= tol)){ result = int_aux(0, kx, kr, x0, r0, PFC_F_KX); } else if ((kx >= tol) & (kr < tol)){ result = int_aux(0, kx, kr, x0, r0, PFC_F_KR); } else result = -2.0*M_PI*( log(r0/(x0 + sqrt(r0*r0 + x0*x0))) *r0*r0 + x0*(x0 - sqrt(r0*r0 + x0*x0))); /* the 1/(4pi) factor is due to the factor on the poissonsolver3d (end)*/ return result/(4.0*M_PI); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_3d_1d_finite, C_POISSON_CUTOFF_3D_1D_FINITE) (double *gx, double *gperp, double *xsize, double *rsize) { return poisson_finite_cylinder(*gx, *gperp, *xsize, *rsize); } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_2D_0D */ /************************************************************************/ /************************************************************************/ static double bessel_J0(double w, void *p) { return gsl_sf_bessel_J0(w); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_2d_0d, C_POISSON_CUTOFF_2D_0D) (double *x, double *y) { double result, error; const size_t wrk_size = 500; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; gsl_integration_workspace * ws = gsl_integration_workspace_alloc (wrk_size); gsl_function F; F.function = &bessel_J0; gsl_integration_qag(&F, *x, *y, epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); gsl_integration_workspace_free(ws); return result; } /************************************************************************/ /************************************************************************/ /* INTCOSLOG */ /************************************************************************/ /************************************************************************/ /* Int_0^mu dy cos(a*y) log(abs(b*y)) = (1/a) * (log(|b*mu|)*sin(a*mu) - Si(a*mu) ) */ double FC_FUNC(intcoslog, INTCOSLOG)(double *mu, double *a, double *b) { if(fabs(*a)>0.0){ return (1.0/(*a)) * (log((*b)*(*mu))*sin((*a)*(*mu)) - gsl_sf_Si((*a)*(*mu)) ); }else{ return (*mu)*(log((*mu)*(*b)) - 1.0); } } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_2D_1D */ /************************************************************************/ /************************************************************************/ struct parameters_2d_1d { double gx; double gy; double rc; }; static double cutoff_2d_1d(double w, void *p) { double k0arg, k0; struct parameters_2d_1d *params = (struct parameters_2d_1d *)p; double gx = (params->gx); double gy = (params->gy); k0arg = fabs(w*gx); if(k0arg < 0.05){ k0 = - (log(k0arg/2) + M_EULER_MASCHERONI); } else if(k0arg < 50.0 ){ k0 = gsl_sf_bessel_K0(k0arg); }else{ k0 = sqrt(2.0*M_PI/k0arg)*exp(-k0arg); } return 4.0*cos(w*gy)*k0; } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_2d_1d, C_POISSON_CUTOFF_2D_1D) (double *gy, double *gx, double *rc) { double result, error, res, b; struct parameters_2d_1d params; const size_t wrk_size = 5000; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; double mu; gsl_integration_workspace * ws = gsl_integration_workspace_alloc (wrk_size); gsl_function F; mu = 0.1/(*gx); b = fabs((*gx))/2.0; params.gx = *gx; params.gy = *gy; params.rc = *rc; F.function = &cutoff_2d_1d; F.params = &params; res = -4.0 * FC_FUNC(intcoslog, INTCOSLOG)(&mu, gy, &b); if( fabs(*gy) > 0.0) { res = res - (4.0 * M_EULER_MASCHERONI / (*gy)) * sin( (*gy)*mu ); }else{ res = res - 4.0 * M_EULER_MASCHERONI * mu; } gsl_integration_qag(&F, mu, (*rc), epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); res = res + result; gsl_integration_workspace_free (ws); return res; } /************************************************************************/ /************************************************************************/ /* C_POISSON_CUTOFF_1D_0D */ /************************************************************************/ /************************************************************************/ struct parameters_1d_0d { double g; double a; }; static double cutoff_1d_0d(double w, void *p) { struct parameters_1d_0d *params = (struct parameters_1d_0d *)p; double g = (params->g); double a = (params->a); return 2.0*(cos(w)/sqrt(w*w+a*a*g*g)); } /* --------------------- Interface to Fortran ---------------------- */ double FC_FUNC_(c_poisson_cutoff_1d_0d, C_POISSON_CUTOFF_1D_0D) (double *g, double *a, double *rc) { double result, error; struct parameters_1d_0d params; const size_t wrk_size = 5000; const double epsilon_abs = 1e-3; const double epsilon_rel = 1e-3; int status; gsl_integration_workspace * ws; gsl_function F; if((*g) <= 0.0){return 2.0*asinh((*rc)/(*a));}; if((*g)*(*rc) > 100.0*M_PI){return 2.0*gsl_sf_bessel_K0((*a)*(*g));}; gsl_set_error_handler_off(); ws = gsl_integration_workspace_alloc (wrk_size); params.g = *g; params.a = *a; F.function = &cutoff_1d_0d; F.params = &params; status = gsl_integration_qag(&F, 0.0, (*rc)*(*g), epsilon_abs, epsilon_rel, wrk_size, 3, ws, &result, &error); gsl_integration_workspace_free (ws); if(status){ return 0.0; }else{ return result; } }
{ "alphanum_fraction": 0.5555962295, "avg_line_length": 27.1141439206, "ext": "c", "hexsha": "0871f593349a1d15bc3684a30f87142c80f03f9e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "gimunu/octopus-metric", "max_forks_repo_path": "src/poisson/poisson_cutoffs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "gimunu/octopus-metric", "max_issues_repo_path": "src/poisson/poisson_cutoffs.c", "max_line_length": 95, "max_stars_count": null, "max_stars_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "gimunu/octopus-metric", "max_stars_repo_path": "src/poisson/poisson_cutoffs.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3288, "size": 10927 }
/* # Program to run a Monte Carlo radiation transfer through the 2D # simulations of GRB jets. # # Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State # ver 0.1 July 8, 2015 # ver 1.1 July 20, 2015: added record of number of scatterings, included # all terms in weight. Should now give correct light curves. # ver 1.2 July 21, 2015: added parameter file to keep track of input # params of each simulation # ver 2.0 July 22, 2015: corrected the problem that arises when there is # no scattering in the time span of one frame. Fixed output arrays dimension. # ver 2.1 July 25, 2015: fixed bug that did not make the number of # scattering grow with the number of photons. # ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to # speed things up. Gained about factor 2 # ver 3.1 July 29, 2015: added radial spread of photon injection points # ver 3.2 July 31, 2015: added Gamma to the weight of photons!!! # ver 4.0 Aug 5, 2015: try to speed up by inverting cycle # ver 4.1 Aug 8, 2015: add spherical test as an option # ver 4.2 Aug 9, 2015: saving files appending rather than re-writing # ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature # ver 4.4 Aug 13, 2015: added cylindrical test # ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test # ver 4.6 Aug 21, 2015: corrected mean free path for large radii # ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings # ver 5.1 Aug 25, 2015: cleaned-up coding # ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections * * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path so you just need to supply the sub directory of MC_XXX as a command line argument */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <math.h> #include <gsl/gsl_rng.h> //#include "mclib.h" #include "mclib_3d.h" #include <omp.h> #define THISRUN "Science" #define FILEPATH "/Users/Tylerparsotan/Documents/Box\ Sync/RIKEN_HYDRO_DATA/JP_HYDRODATA/" #define FILEROOT "u" #define MC_PATH "PHOTON_TEST/" //#define MC_PATH "MC_16OI/Single_Photon_Cy_mc_total/" #define MCPAR "riken_mc.par" int main(int argc, char **argv) { //compile each time a macro is changed // Define variables char flash_prefix[200]=""; char mc_file[200]="" ; char this_run[200]=THISRUN; char *cyl="Cylindrical"; char *sph="Spherical"; char spect;//type of spectrum char restrt;//restart or not double fps, theta_jmin, theta_jmax ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians double inj_radius_small, inj_radius_large, ph_weight_suggest ;//radius at chich photons are injected into sim int frm0_small, frm0_large,last_frm, frm2_small, frm2_large, j=0, min_photons, max_photons ;//frame starting from, last frame of sim, frame of last injection int num_thread=0, angle_count=0; int half_threads=floor((num_thread/2)); int num_angles=0; int dim_switch=0; double *thread_theta=NULL; //saves ranges of thetas for each thread to go through double delta_theta=0; //new muliple threads injecting and propagating photons const gsl_rng_type *rng_t; gsl_rng **rng; gsl_rng_env_setup(); rng_t = gsl_rng_ranlxs0; //want to break up simulation by angle and injection frame & have each thread save data in its own folder //have each thread check if its directory is made and if its restarting (delete evrything) or if its continuing with a previous simulation //the angle and the injection frames will be the names of mc_dir, therefore read mc.par first in MC_XXX directory //make strings of proper directories etc. snprintf(flash_prefix,sizeof(flash_prefix),"%s%s",FILEPATH,FILEROOT ); //snprintf(mc_dir,sizeof(flash_prefix),"%s%s",FILEPATH,MC_PATH); //snprintf(mc_file,sizeof(flash_prefix),"%s%s",mc_dir, MCPAR); snprintf(mc_file,sizeof(flash_prefix),"%s%s%s",FILEPATH, MC_PATH,MCPAR); //printf(">> mc.py: Reading mc.par\n"); readMcPar(mc_file, &fps, &theta_jmin, &theta_jmax, &delta_theta, &inj_radius_small,&inj_radius_large, &frm0_small , &frm0_large ,&last_frm ,&frm2_small, &frm2_large, &ph_weight_suggest, &min_photons, &max_photons, &spect, &restrt, &num_thread, &dim_switch); //thetas that comes out is in degrees //printf("small: %d large: %d weights: %e, %c\n", min_photons, max_photons, ph_weight_suggest, restrt); if (num_thread==0) { num_thread=omp_get_max_threads(); //if user specifies 0 in mc.par, default to max number of threads possible } half_threads=floor((num_thread/2)); //thread_theta=malloc(((half_threads)+1)*sizeof(double) ); rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); rng[0] = gsl_rng_alloc (rng_t); //initalize first random number generator to seed the others with random numbers for(j=1;j<num_thread;j++) { rng[j] = gsl_rng_alloc (rng_t); gsl_rng_set(rng[j],gsl_rng_get(rng[0])); } //divide up angles and frame injections among threads DONT WANT NUMBER OF THREADS TO BE ODD //assign ranges to array that hold them /* delta_theta=(theta_jmax-theta_jmin)/(half_threads); *(thread_theta+0)=theta_jmin; //printf("%e\n", *(thread_theta+0)); for (j=1;j<(half_threads+1); j++) { *(thread_theta+j)=*(thread_theta+(j-1))+delta_theta; //printf("%e\n", *(thread_theta+j)*180/M_PI); } */ //leave angles in degrees here num_angles=(int) (((theta_jmax-theta_jmin)/delta_theta)) ;//*(180/M_PI)); thread_theta=malloc( num_angles *sizeof(double) ); *(thread_theta+0)=theta_jmin;//*(180/M_PI); printf("%e\n", *(thread_theta+0)); for (j=1;j<(num_angles); j++) { *(thread_theta+j)=*(thread_theta+(j-1))+delta_theta; printf("%e\n", *(thread_theta+j)); } //printf("half_threads: %d\n", half_threads); //start parallel section with half the threads possible and assign each thread to its value of theta by rewriting its private value of theta min and max that was read from mcrat omp_set_nested(1); //allow for nested parallelization //omp_set_dynamic(0); //omp_set_num_threads(num_thread); //#pragma omp parallel firstprivate(theta_jmin_thread, theta_jmax_thread, mc_dir, phPtr, framestart, scatt_framestart, num_ph, restrt, time_now, st, dirp, file_count, mc_filename, mc_operation, dt_max) //printf("%d\n", omp_get_num_threads() ); // for (angle_count=(int) (theta_jmin); angle_count< (int) (theta_jmax+1) ;angle_count=angle_count+delta_theta ) #pragma omp parallel for num_threads(num_thread) private(angle_count) for (angle_count=0; angle_count< num_angles ;angle_count++ ) { printf("%d\t%lf\n", omp_get_thread_num(), delta_theta ); double inj_radius; int frm2, frm0; char mc_filename[200]=""; char mc_filename_2[200]=""; char mc_operation[200]=""; char mc_dir[200]="" ; int file_count = 0; DIR * dirp; struct dirent * entry; struct stat st = {0}; double theta_jmin_thread=0, theta_jmax_thread=0; theta_jmin_thread= (*(thread_theta+angle_count))*(M_PI/180);//(*(thread_theta+omp_get_thread_num() )); theta_jmax_thread= ((*(thread_theta+angle_count))+delta_theta)*(M_PI/180);//(*(thread_theta+omp_get_thread_num()+1 )); printf("Thread %d: %0.1lf, %0.1lf \n %d %d\n", omp_get_thread_num(), theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm2_small, frm2_large ); snprintf(mc_dir,sizeof(flash_prefix),"%s%s%0.1lf-%0.1lf/",FILEPATH,MC_PATH, theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI ); //have to add angle into this printf(">> Thread %d in MCRaT: I am working on path: %s \n",omp_get_thread_num(), mc_dir ); if ((theta_jmin_thread >= 0) && (theta_jmax_thread <= (2*M_PI/180) )) //if within small angle (0-2 degrees) use _small inj_radius and frm2 { inj_radius=inj_radius_small; frm2=frm2_small; frm0=frm0_small; } else { inj_radius=inj_radius_large; frm2=frm2_large; frm0=frm0_large; } printf("Thread %d: %0.1lf, %0.1lf \n %d %e %d\n", omp_get_thread_num(), theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm2, inj_radius, frm0 ); //want to also have another set of threads that each has differing ranges of frame injections therefore do nested parallelism here so each thread can read its own checkpoint file //#pragma omp parallel num_threads(2) firstprivate(restrt) { char flash_file[200]=""; char log_file[200]=""; FILE *fPtr=NULL; //pointer to log file for each thread double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL; double *phiPtr=NULL, *velzPtr=NULL, *zPtr=NULL; double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter double dt_max=0, thescatt=0, accum_time=0; double gamma_infinity=0, time_now=0, time_step=0, avg_scatt=0; //gamma_infinity not used? double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0, ph_vzPtr=0;// *ph_cosanglePtr=NULL ; double min_r=0, max_r=0; int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0; struct photon *phPtr=NULL; //pointer to array of photons //if (omp_get_thread_num()==0) //{ //printf( "A:%d Im Thread: %d with ancestor %d working in %s\n", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), mc_dir); //} if (restrt=='c') { printf(">> mc.py: Reading checkpoint\n"); //#pragma omp critical { readCheckpoint(mc_dir, &phPtr, frm0, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now); /* for (i=0;i<num_ph;i++) { printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(phPtr+i)->p0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt ); } */ if (restrt=='c') { printf(">> Thread %d with ancestor %d: Starting from photons injected at frame: %d out of %d\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),framestart, frm2); printf(">> Thread %d with ancestor %d: Continuing scattering %d photons from frame: %d\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),num_ph, scatt_framestart); printf(">> Thread %d with ancestor %d: The time now is: %e\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),time_now); } else { printf(">> Thread %d with ancestor %d: Continuing simulation by injecting photons at frame: %d out of %d\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),framestart, frm2); //starting with new photon injection is same as restarting sim } } } else if (stat(mc_dir, &st) == -1) { mkdir(mc_dir, 0777); //make the directory with full permissions framestart=frm0; //if restarting then start from parameters given in mc.par file scatt_framestart=frm0; } else { //remove everything from MC directory to ensure no corruption of data if theres other files there besides the mc.par file //for a checkpoint implementation, need to find the latest checkpoint file and read it and not delete the files #pragma omp critical { printf(">> Thread %d with ancestor %d: Cleaning directory \n",omp_get_thread_num(), omp_get_ancestor_thread_num(1)); dirp = opendir(mc_dir); while ((entry = readdir(dirp)) != NULL) { if (entry->d_type == DT_REG) { /* If the entry is a regular file */ file_count++; //count how many files are in dorectory } } printf("File count %d\n", file_count); if (file_count>0) { for (i=0;i<=last_frm;i++) { snprintf(mc_filename,sizeof(mc_filename),"%s%s%d%s", mc_dir,"mcdata_",i,"_P0.dat"); if(( access( mc_filename, F_OK ) != -1 ) ) { snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s%d%s","exec rm ", mc_dir,"mcdata_",i,"_*.dat"); //prepares string to remove *.dat in mc_dir printf("%s\n",mc_operation); system(mc_operation); //snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s%d%s","exec rm ", mc_dir,"mcdata_",i,"_*"); //system(mc_operation); } } //snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mcdata_PW_*.dat"); //prepares string to remove *.dat in mc_dir //system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mcdata_PW.dat"); //prepares string to remove *.dat in mc_dir system(mc_operation); //snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mc_chkpt_*.dat"); //prepares string to remove *.dat in mc_dir //system(mc_operation); snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s","exec rm ", mc_dir,"mc_output_*.log"); //prepares string to remove *.log in mc_dir system(mc_operation); } } framestart=frm0; //if restarting then start from parameters given in mc.par file scatt_framestart=frm0; } dt_max=1.0/fps; //#pragma omp barrier snprintf(log_file,sizeof(log_file),"%s%s",mc_dir,"mc_output.log" ); printf("%s\n",log_file); fPtr=fopen(log_file, "w"); fprintf(fPtr, "%d Im Thread: %d with ancestor %d Starting on Frame: %d scatt_framestart: %d\n", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), framestart, scatt_framestart); fflush(fPtr); //fclose(fPtr); //#pragma omp barrier //exit(0); //loop over frames //for a checkpoint implementation, start from the last saved "frame" value and go to the saved "frm2" value //#pragma omp for for (frame=framestart;frame<=frm2;frame++) { if (restrt=='r') { time_now=frame/fps; //for a checkpoint implmentation, load the saved "time_now" value when reading the ckeckpoint file otherwise calculate it normally } //printf(">> mc.py: Working on Frame %d\n", frame); fprintf(fPtr,"%d Im Thread: %d with ancestor %d Working on Frame: %d\n", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), frame); fflush(fPtr); if (restrt=='r') { //exit(0); //read in FLASH file //for a checkpoint implmentation, dont need to read the file yet if (dim_switch==0) { //put proper number at the end of the flash file modifyFlashName(flash_file, flash_prefix, frame, dim_switch); fprintf(fPtr,">> Im Thread: %d with ancestor %d: Opening FLASH file %s\n",omp_get_thread_num(), omp_get_ancestor_thread_num(1), flash_file); fflush(fPtr); #pragma omp critical { readAndDecimate(flash_file, inj_radius, fps, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fPtr); } } else { read_hydro(FILEPATH, frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fps, fPtr); } //check for run type if(strcmp(cyl, this_run)==0) { //printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num ); } //determine where to place photons and how many should go in a given place //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data fprintf(fPtr,">> Thread: %d with ancestor %d: Injecting photons\n",omp_get_thread_num(), omp_get_ancestor_thread_num(1)); fflush(fPtr); if (dim_switch==0) { photonInjection(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rng[omp_get_thread_num()] ); } else { photonInjection3D(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, zPtr, szxPtr, szyPtr,rPtr,thetaPtr, phiPtr, tempPtr, velxPtr, velyPtr, velzPtr, rng[omp_get_thread_num()] ); } //printf("%d\n",num_ph); //num_ph is one more photon than i actually have /* for (i=0;i<num_ph;i++) printf("%e,%e,%e \n",(phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2 ); */ } //scatter photons all the way thoughout the jet //for a checkpoint implmentation, start from the last saved "scatt_frame" value eh start_frame=frame or start_frame=cont_frame if (restrt=='r') { scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint() } for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame++) { fprintf(fPtr,">>\n"); fprintf(fPtr,">> Thread %d with ancestor %d : Working on photons injected at frame: %d out of %d\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),frame, frm2); fprintf(fPtr,">> Thread %d with ancestor %d: %s - Working on frame %d\n",omp_get_thread_num(), omp_get_ancestor_thread_num(1), THISRUN, scatt_frame); fprintf(fPtr,">> Thread %d with ancestor %d: Opening file...\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1)); fflush(fPtr); if (dim_switch==0) { //put proper number at the end of the flash file modifyFlashName(flash_file, flash_prefix, scatt_frame, dim_switch); #pragma omp critical { phMinMax(phPtr, num_ph, &min_r, &max_r); readAndDecimate(flash_file, inj_radius, fps, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fPtr); } } else { phMinMax(phPtr, num_ph, &min_r, &max_r); read_hydro(FILEPATH, scatt_frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fps, fPtr); } //check for run type if(strcmp(cyl, this_run)==0) { //printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num ); } //printf("The result of read and decimate are arrays with %d elements\n", array_num); fprintf(fPtr,">> Thread %d with ancestor %d: propagating and scattering %d photons\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1),num_ph); fflush(fPtr); frame_scatt_cnt=0; while (time_now<((scatt_frame+1)/fps)) { //if simulation time is less than the simulation time of the next frame, keep scattering in this frame //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path //and choose the photon with the smallest mfp and calculate the timestep ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, &time_step, xPtr, yPtr, zPtr, velxPtr, velyPtr, velzPtr, dens_labPtr, tempPtr,\ &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_vzPtr, &ph_tempPtr, rng[omp_get_thread_num()], dim_switch); //printf("In main: %e, %d, %e, %e\n", *(ph_num_scatt+ph_scatt_index), ph_scatt_index, time_step, time_now); printf("In main: %e, %d, %e, %e\n",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); if (time_step<dt_max) { //update number of scatterings and time //(*(ph_num_scatt+ph_scatt_index))+=1; ((phPtr+ph_scatt_index)->num_scatt)+=1; frame_scatt_cnt+=1; time_now+=time_step; updatePhotonPosition(phPtr, num_ph, time_step); //scatter the photon //printf("Passed Parameters: %e, %e, %e\n", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr)); photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr), ph_vzPtr, (ph_tempPtr), rng[omp_get_thread_num()] , dim_switch, fPtr); //if (frame_scatt_cnt%1000 == 0) { fprintf(fPtr,"Scattering Number: %d\n", frame_scatt_cnt); fprintf(fPtr,"The local temp is: %e\n", (ph_tempPtr)); fprintf(fPtr,"Average photon energy is: %e\n", averagePhotonEnergy(phPtr, num_ph)); //write function to average over the photons p0 and then do (*3e10/1.6e-9) fflush(fPtr); } } else { time_now+=dt_max; //for each photon update its position based on its momentum updatePhotonPosition(phPtr, num_ph, dt_max); } //printf("In main 2: %e, %d, %e, %e\n", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); } //get scattering statistics phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt); fprintf(fPtr,"The number of scatterings in this frame is: %d\n", frame_scatt_cnt); fprintf(fPtr,"The last time step was: %lf.\nThe time now is: %lf\n", time_step,time_now); fprintf(fPtr,"The maximum number of scatterings for a photon is: %d\nThe minimum number of scattering for a photon is: %d\n", max_scatt, min_scatt); fprintf(fPtr,"The average number of scatterings thus far is: %lf\n", avg_scatt); fflush(fPtr); printPhotons(phPtr, num_ph, scatt_frame , frame, mc_dir); exit(0); //for a checkpoint implmentation,save the checkpoint file here after every 5 frames or something //save the photons data, the scattering number data, the scatt_frame value, and the frame value //WHAT IF THE PROGRAM STOPS AFTER THE LAST SCATT_FRAME, DURING THE FIRST SCATT_FRAME OF NEW FRAME VARIABLE - save restrt variable as 'r' fprintf(fPtr, ">> Thread %d with ancestor %d: Making checkpoint file\n", omp_get_thread_num(), omp_get_ancestor_thread_num(1)); fflush(fPtr); saveCheckpoint(mc_dir, frame, scatt_frame, num_ph, time_now, phPtr, last_frm); free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr); free(gammaPtr);free(dens_labPtr);free(tempPtr); xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL; szxPtr=NULL; szyPtr=NULL; tempPtr=NULL; } restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file free(phPtr); phPtr=NULL; } }//end omp parallel inner section //merge files from each worker thread within a directory //dirFileMerge(mc_dir, frm0, last_frm); } //end omp parallel section //gsl_rng_free (rand); //free rand number generator for (j=0;j<num_thread;j++) { gsl_rng_free(rng[j]); } free(rng); free(thread_theta); return 0; }
{ "alphanum_fraction": 0.556128507, "avg_line_length": 54.0862385321, "ext": "c", "hexsha": "b4b3f1255deb88a6b16e0ee470e868df11112435", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/mcrat.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/mcrat.c", "max_line_length": 299, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/mcrat.c", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "num_tokens": 7137, "size": 29477 }
#ifndef PROXIMAL_MATRIX_H_GUARD #define PROXIMAL_MATRIX_H_GUARD #include <math.h> #include <float.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> void project_sdc(gsl_matrix *X); void project_spectral_norm_ball(gsl_matrix *X); void prox_neg_log_det(gsl_matrix *X, const double rho); void prox_quad(gsl_vector *x, const double rho, gsl_matrix *A, gsl_matrix *b); #endif
{ "alphanum_fraction": 0.7784946237, "avg_line_length": 24.4736842105, "ext": "h", "hexsha": "36937e8731134253393eda4e54cf9fcf918b53e7", "lang": "C", "max_forks_count": 81, "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:22:27.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-13T07:26:39.000Z", "max_forks_repo_head_hexsha": "736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhiyuxzh/proximal", "max_forks_repo_path": "c/proximal_matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b", "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": "zhiyuxzh/proximal", "max_issues_repo_path": "c/proximal_matrix.h", "max_line_length": 78, "max_stars_count": 140, "max_stars_repo_head_hexsha": "736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "askuyue/proximal", "max_stars_repo_path": "c/proximal_matrix.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:57:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-06T20:26:13.000Z", "num_tokens": 138, "size": 465 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <string> #include <gsl/gsl> #include "onnx/onnx_pb.h" #include "core/graph/basic_types.h" namespace onnxruntime::utils { // keep these signatures in sync with DECLARE_MAKE_ATTRIBUTE_FNS below /** Creates an AttributeProto with the specified name and value. */ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, int64_t value); /** Creates an AttributeProto with the specified name and values. */ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const int64_t> values); #define DECLARE_MAKE_ATTRIBUTE_FNS(type) \ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, type value); \ ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, gsl::span<const type> values) DECLARE_MAKE_ATTRIBUTE_FNS(float); DECLARE_MAKE_ATTRIBUTE_FNS(std::string); DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TensorProto); #if !defined(DISABLE_SPARSE_TENSORS) DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::SparseTensorProto); #endif DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::TypeProto); DECLARE_MAKE_ATTRIBUTE_FNS(ONNX_NAMESPACE::GraphProto); #undef DECLARE_MAKE_ATTRIBUTE_FNS // The below overload is made so the compiler does not attempt to resolve // string literals with the gsl::span overload inline ONNX_NAMESPACE::AttributeProto MakeAttribute(std::string attr_name, const char* value) { return MakeAttribute(std::move(attr_name), std::string{value}); } /** * Sets an attribute in `node_attributes` with key `attribute.name()` and value `attribute`. * If an attribute with the same name exists, it will be overwritten. * @return Pair of (iterator to attribute, whether attribute was added (true) or updated (false)). */ std::pair<NodeAttributes::iterator, bool> SetNodeAttribute(ONNX_NAMESPACE::AttributeProto attribute, NodeAttributes& node_attributes); } // namespace onnxruntime::utils
{ "alphanum_fraction": 0.7582733813, "avg_line_length": 40.0961538462, "ext": "h", "hexsha": "94242e8d264043ef1615797384a65efa790ac6fe", "lang": "C", "max_forks_count": 140, "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_issues_count": 440, "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_line_length": 101, "max_stars_count": 669, "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_path": "onnxruntime/core/graph/node_attr_utils.h", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "num_tokens": 442, "size": 2085 }
#include <stdio.h> #include <gsl/gsl_statistics.h> int main(void) { double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6}; double mean, variance, largest, smallest; mean = gsl_stats_mean(data, 1, 5); variance = gsl_stats_variance(data, 1, 5); largest = gsl_stats_max(data, 1, 5); smallest = gsl_stats_min(data, 1, 5); printf ("The dataset is %g, %g, %g, %g, %g\n", data[0], data[1], data[2], data[3], data[4]); printf ("The sample mean is %g\n", mean); printf ("The estimated variance is %g\n", variance); printf ("The largest value is %g\n", largest); printf ("The smallest value is %g\n", smallest); return 0; }
{ "alphanum_fraction": 0.5994065282, "avg_line_length": 28.0833333333, "ext": "c", "hexsha": "f5a7558a7b6e52fec2399901a2d954d31bf28da1", "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": "587283fd972d0060815dde82a57667e74765c9ae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marketmodelbrokendown/1", "max_forks_repo_path": "notebook/demo/src/gsl-example.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_issues_repo_issues_event_max_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-18T21:55:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marketmodelbrokendown/1", "max_issues_repo_path": "notebook/demo/src/gsl-example.c", "max_line_length": 55, "max_stars_count": null, "max_stars_repo_head_hexsha": "587283fd972d0060815dde82a57667e74765c9ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marketmodelbrokendown/1", "max_stars_repo_path": "notebook/demo/src/gsl-example.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 221, "size": 674 }
#include <pygsl/error_helpers.h> #include <pygsl/function_helpers.h> #include <pygsl/pygsl_features.h> #ifdef PyGSL_DERIV_MODULE #if ( _PYGSL_GSL_HAS_DERIV == 0 ) #error "The deriv module was only introduced by GSL 1.5. You seem to compile against an older verion!" #endif #include <gsl/gsl_deriv.h> #endif /* PyGSL_DERIV_MODULE */ #include <gsl/gsl_diff.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <setjmp.h> /* * callback functions * - python function passed by user * - actual C callback * - GSL wrapper struct */ /* Used for traceback */ static PyObject *module = NULL; typedef struct{ PyObject * callback; PyObject * args; jmp_buf buffer; }pygsl_diff_args; static double diff_callback(double x, void *p) { double value; int flag; pygsl_diff_args *pargs = NULL; pargs = (pygsl_diff_args *) p; assert(pargs->callback); assert(pargs->args); flag = PyGSL_function_wrap_helper(x, &value, NULL, pargs->callback, pargs->args, (char *)__FUNCTION__); if(GSL_SUCCESS != flag){ longjmp(pargs->buffer, flag); return gsl_nan(); } return value; } /* wrapper function */ typedef int pygsl_deriv_func(const gsl_function *, double, double, double *, double *); typedef int pygsl_diff_func(const gsl_function *, double, double *, double *); static PyObject * PyGSL_diff_generic(PyObject *self, PyObject *args, #ifndef PyGSL_DIFF_MODULE pygsl_deriv_func func #else pygsl_diff_func func #endif ) { PyObject *result=NULL, *myargs=NULL; PyObject *cb=NULL; pygsl_diff_args pargs = {NULL, NULL}; /* Changed to compile using Sun's Compiler */ gsl_function diff_gsl_callback = {NULL, NULL}; double x, value, abserr; int flag; #ifndef PyGSL_DIFF_MODULE double h; if(! PyArg_ParseTuple(args, "Odd|O", &cb, &x, &h, &myargs)){ return NULL; } #else if(! PyArg_ParseTuple(args, "Od|O", &cb, &x, &myargs)){ return NULL; } #endif /* Changed to compile using Sun's Compiler */ diff_gsl_callback.function = diff_callback; diff_gsl_callback.params = (void *) &pargs; if(! PyCallable_Check(cb)) { PyErr_SetString(PyExc_TypeError, "The first parameter must be callable"); return NULL; } Py_INCREF(cb); /* Add a reference to new callback */ pargs.callback = cb; /* Remember new callback */ /* Did I get arguments? If so handle them */ if(NULL == myargs){ Py_INCREF(Py_None); pargs.args= Py_None; }else{ Py_INCREF(myargs); pargs.args= myargs; } if((flag=setjmp(pargs.buffer)) == 0){ /* Jmp buffer set, call the function */ #ifndef PyGSL_DIFF_MODULE flag = func(&diff_gsl_callback, x, h, &value, &abserr); #else flag = func(&diff_gsl_callback, x, &value, &abserr); #endif }else{ DEBUG_MESS(2, "CALLBACK called longjmp! flag =%d", flag); } /* Arguments no longer used */ Py_DECREF(pargs.args); /* Dispose of callback */ Py_DECREF(pargs.callback); if(flag != GSL_SUCCESS){ PyGSL_ERROR_FLAG(flag); return NULL; } result = Py_BuildValue("(dd)", value, abserr); return result; }
{ "alphanum_fraction": 0.6912153236, "avg_line_length": 21.7841726619, "ext": "c", "hexsha": "736e882b0a2fe01e1f4e5e9f9fb22c402780e67c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/diff_deriv_common.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 843, "size": 3028 }
#include <asm/types.h> #include <glib.h> #include <stdio.h> #include <assert.h> #include <inttypes.h> #include <float.h> #include <gsl/gsl_histogram.h> #include <blktrace_api.h> #include <blktrace.h> #include <plugins.h> #include <utils.h> #include <list_plugins.h> #include <reqsize.h> #define DECL_ASSIGN_I2C(name,data) \ struct i2c_data *name = (struct i2c_data *)data #define OIO_ALLOC (8) #define N_BINS (21) #define BINS_SEP (8) struct oio_data { #define READ 0 #define WRITE 1 gsl_histogram *op[2]; __u64 time; }; struct i2c_data { GTree *is; FILE *oio_f; __u32 outstanding; __u32 maxouts; /* oio hist */ struct oio_data *oio; __u32 oio_size; __u64 oio_prev_time; FILE *oio_hist_f; }; static void write_outs(struct i2c_data *i2c, struct blk_io_trace *t) { if(i2c->oio_f) fprintf(i2c->oio_f, "%f %u\n", NANO_ULL_TO_DOUBLE(t->time), i2c->outstanding); } static gsl_histogram *new_hist() { gsl_histogram *h; /* allocate bins and set ranges uniformally */ h = gsl_histogram_alloc(N_BINS); gsl_histogram_set_ranges_uniform(h,0,N_BINS*BINS_SEP); /* last bin should hold everything greater * than (N_BINS-1)*BINS_SEP */ h->range[h->n] = DBL_MAX; return h; } static void init_oio_data(struct oio_data *oio, int n) { int i; for (i = 0; i < n; i++) { oio[i].time = 0; oio[i].op[READ] = new_hist(); oio[i].op[WRITE] = new_hist(); } } static gboolean add_to_matrix(__u64 *__unused, struct blk_io_trace *t, struct i2c_data *i2c) { gsl_histogram_increment(i2c->oio[i2c->outstanding].op[IS_WRITE(t)], (double)(t->bytes/BLK_SIZE)); return FALSE; } static void oio_change(struct i2c_data *i2c, struct blk_io_trace *t, int inc) { /* allocate oio space if the one I had is over */ if(i2c->outstanding + 1 >= i2c->oio_size) { i2c->oio = realloc(i2c->oio, (i2c->oio_size + OIO_ALLOC)*sizeof(struct oio_data)); init_oio_data(i2c->oio + i2c->oio_size, OIO_ALLOC); i2c->oio_size += OIO_ALLOC; } /* increase the time */ if(i2c->oio_prev_time != UINT64_MAX) { i2c->oio[i2c->outstanding].time += t->time - i2c->oio_prev_time; } i2c->oio_prev_time = t->time; if(inc) { i2c->outstanding++; } else { i2c->outstanding--; } i2c->maxouts = MAX(i2c->maxouts, i2c->outstanding); g_tree_foreach(i2c->is, (GTraverseFunc)add_to_matrix, i2c); write_outs(i2c, t); } static void C(struct blk_io_trace *t, void *data) { DECL_ASSIGN_I2C(i2c,data); if(g_tree_lookup(i2c->is, &t->sector)!=NULL) { g_tree_remove(i2c->is, &t->sector); oio_change(i2c, t, FALSE); } } static void I(struct blk_io_trace *t, void *data) { DECL_ASSIGN_I2C(i2c,data); if(g_tree_lookup(i2c->is, &t->sector)==NULL) { DECL_DUP(struct blk_io_trace,new_t,t); g_tree_insert(i2c->is,&new_t->sector,new_t); oio_change(i2c, t, TRUE); } } static void add_histogram(gsl_histogram *h1, gsl_histogram *h2) { unsigned int i; for (i = 0; i < h1->n && i < h2->n; i++) { h1->bin[i] += h2->bin[i]; } } void i2c_add(void *data1, const void *data2) { DECL_ASSIGN_I2C(i2c1,data1); DECL_ASSIGN_I2C(i2c2,data2); __u32 i; i2c1->maxouts = MAX(i2c1->maxouts, i2c2->maxouts); i2c1->oio_prev_time = MAX(i2c1->oio_prev_time, i2c2->oio_prev_time); if(i2c1->oio_size < i2c2->oio_size) { __u32 diff = i2c2->oio_size - i2c1->oio_size; i2c1->oio = realloc(i2c1->oio, i2c2->oio_size*sizeof(struct oio_data)); init_oio_data(i2c1->oio + diff, diff); i2c1->oio_size = i2c2->oio_size; } for (i = 0; i <= i2c2->maxouts; i++) { i2c1->oio[i].time += i2c2->oio[i].time; add_histogram(i2c1->oio[i].op[READ],i2c2->oio[i].op[READ]); add_histogram(i2c1->oio[i].op[WRITE],i2c2->oio[i].op[WRITE]); } } void i2c_print_results(const void *data) { DECL_ASSIGN_I2C(i2c,data); double p; double avg = 0; __u32 i; __u64 tot_time = 0; for (i = 0; i <= i2c->maxouts; i++) { tot_time += i2c->oio[i].time; } for (i = 0; i <= i2c->maxouts; i++) { p = ((double)i2c->oio[i].time)/((double)tot_time); if(i2c->oio_hist_f) fprintf(i2c->oio_hist_f, "%u\t%.2lf\n",i,100*p); avg += p*i; } /* print all histograms */ if(i2c->oio_hist_f) { for (i = 1; i <= i2c->maxouts; i++) { fprintf(i2c->oio_hist_f, "\nread: %d\n",i); gsl_histogram_fprintf(i2c->oio_hist_f, i2c->oio[i].op[READ], "%g", "%g"); fprintf(i2c->oio_hist_f, "\nwrite: %d\n",i); gsl_histogram_fprintf(i2c->oio_hist_f, i2c->oio[i].op[WRITE], "%g", "%g"); } } printf("I2C Max. OIO: %u, Avg: %.2lf\n",i2c->maxouts,avg); } void i2c_init(struct plugin *p, struct plugin_set *__un1, struct plug_args *pa) { char filename[FILENAME_MAX]; struct i2c_data *i2c = p->data = g_new(struct i2c_data,1); i2c->is = g_tree_new(comp_int64); i2c->outstanding = 0; i2c->maxouts = 0; i2c->oio_f = NULL; if(pa->i2c_oio_f) { get_filename(filename, "i2c_oio", pa->i2c_oio_f, pa->end_range); i2c->oio_f = fopen(filename,"w"); if(!i2c->oio_f) perror_exit("Opening I2C detail file"); } i2c->oio_hist_f = NULL; if(pa->i2c_oio_hist_f) { get_filename(filename, "i2c_oio_hist", pa->i2c_oio_hist_f, pa->end_range); i2c->oio_hist_f = fopen(filename,"w"); if(!i2c->oio_hist_f) perror_exit("Opening I2C detail file"); } i2c->oio = NULL; i2c->oio_size = 0; i2c->oio_prev_time = UINT64_MAX; } void i2c_ops_init(struct plugin_ops *po) { po->add = i2c_add; po->print_results = i2c_print_results; /* association of event int and function */ g_tree_insert(po->event_tree,(gpointer)__BLK_TA_COMPLETE,C); g_tree_insert(po->event_tree,(gpointer)__BLK_TA_INSERT,I); } void i2c_destroy(struct plugin *p) { unsigned int i; DECL_ASSIGN_I2C(i2c,p->data); if(i2c->oio_f) fclose(i2c->oio_f); if(i2c->oio_hist_f) fclose(i2c->oio_hist_f); for (i = 0; i <= i2c->maxouts; i++) { gsl_histogram_free(i2c->oio[i].op[READ]); gsl_histogram_free(i2c->oio[i].op[WRITE]); } free(i2c->oio); g_free(p->data); }
{ "alphanum_fraction": 0.6679206566, "avg_line_length": 22.0679245283, "ext": "c", "hexsha": "d2277330ac024540f9129c6710effd163bd27131", "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": "506321419fadf99fa17eb4784a49f85fb3ae1276", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "useche/btstats", "max_forks_repo_path": "statplug/i2c.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "506321419fadf99fa17eb4784a49f85fb3ae1276", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "useche/btstats", "max_issues_repo_path": "statplug/i2c.c", "max_line_length": 98, "max_stars_count": 3, "max_stars_repo_head_hexsha": "506321419fadf99fa17eb4784a49f85fb3ae1276", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "useche/btstats", "max_stars_repo_path": "statplug/i2c.c", "max_stars_repo_stars_event_max_datetime": "2018-09-30T16:58:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-08-31T13:06:43.000Z", "num_tokens": 2227, "size": 5848 }
/*****************************************************************************/ #define this_is "FDBinary v.3 beta (test version of 21 Feb 2010)" /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_multimin.h> #include "mxfuns.h" #include "fd3sep.h" #include "triorb.h" /*****************************************************************************/ /* function and macro to kill the program with a short message */ #define FDBErrorString "\nError in FDBianry" #define DIE(s) {fprintf(stderr,"%s: %s\n",FDBErrorString,s);fdbfailure();}; void fdbfailure(void) { exit ( EXIT_FAILURE ); } /*****************************************************************************/ /* macros for reading values from keyboard */ #define GETDBL(x) {if(1!=scanf("%lg",x)) DIE("failed reading double");} #define GETINT(x) {if(1!=scanf("%d", x)) DIE("failed reading int");} #define GETLNG(x) {if(1!=scanf("%ld",x)) DIE("failed reading long");} #define GETSTR(x) {if(1!=scanf("%s", x)) DIE("failed reading string");} /*****************************************************************************/ #define SPEEDOFLIGHT 2.998E5 /* speed of light in km/s */ static char *triorb_strings[] = { /* 0 */ "period of AB--C", "day", "%.9lg", /* 1 */ "time of periast pass in AB--C", "day", "%.9lg", /* 2 */ "eccentricity of AB--C", "1", "%.9lg", /* 3 */ "periast long of AB in AB--C", "deg", "%.9lg", /* 4 */ "a sin(incl) of AB in AB--C", "light-day", "%.9lg", /* 5 */ "a sin(incl) of C in AB--C", "light-day", "%.9lg", /* 6 */ "period A--B", "day", "%.9lg", /* 7 */ "time of periast pass in A--B", "day", "%.9lg", /* 8 */ "eccentricity of A--B", "1", "%.9lg", /* 9 */ "periast long of A in A--B", "deg", "%.9lg", /* 10 */ "rv semiamp of A in A--B", "km/s", "%.9lg", /* 11 */ "rv semiamp of B in A--B", "km/s", "%.9lg", /* 12 */ "periast long adv per cycle in A--B", "deg", "%.9lg" }; static char *triorb_pname (long j) { return triorb_strings[3*j]; } static char *triorb_punit (long j) { return triorb_strings[3*j+1]; } static char *triorb_pformat (long j) { return triorb_strings[3*j+2]; } /*****************************************************************************/ static long K, M, N, Ndft, ksw[3], nfp, opsw[TRIORB_NP]; static double **dftobs, **dftmod, **dftres; static double rvstep, *otimes, *rvcorr, *sig, **lfm, **rvm; static double op0[TRIORB_NP], dop0[TRIORB_NP]; static double meritfngsl ( const gsl_vector *v, void *params ); static double meritfn ( double *op ); #define MX_FDBINARY_FORMAT "%15.8E " static char *mxfd3fmts=MX_FDBINARY_FORMAT; /* FDBinary */ int main ( void ) { long i, i0, i1, j, k, vc, vlen, nruns, niter; double **masterobs, **mod, **res, **obs, z0, z1, stoprat; char obsfn[1024], resfn[1024], modfn[1024], rvsfn[1024], logfn[1024]; char *starcode[] = {"A","B","C"}; FILE *logfp; setbuf ( stdout, NULL ); MxError( FDBErrorString, stdout, fdbfailure ); MxFormat( mxfd3fmts ); printf ( "\n %s\n", this_is ); printf ( "\n SECTION 1: LOADING OBSERVED SPECTRA\n\n" ); printf ( " observed spectra master file = " ); GETSTR ( obsfn ); printf ( "%s\n", obsfn ); vc=0; vlen=0; masterobs = MxLoad ( obsfn, &vc, &vlen ); M = vc - 1; printf ( " loaded %ld spectra with %ld data pts per spectrum\n", M, vlen ); z0 = **masterobs; z1 = *(*masterobs+vlen-1); rvstep = SPEEDOFLIGHT * ( - 1 + exp ((z1-z0)/(vlen-1)) ); printf ( " lnlambda range from %lf to %lf\n", z0, z1 ); printf ( " rv step %lg km/s per data point\n", rvstep ); printf ( " use data from lnlambda = " ); GETDBL ( &z0 ); printf ( "%lg\n", z0 ); printf ( " to lnlambda = " ); GETDBL ( &z1 ); printf ( "%lg\n", z1 ); i0 = 0; while ( *(*masterobs+i0) < z0 ) i0++; i1 = vlen-1; while ( z1 < *(*masterobs+i1) ) i1--; N = i1 - i0 + 1; printf ( " selected %ld data points per spectrum\n", N ); obs = MxAlloc ( M+1, N ); for ( i = 0 ; i < N ; i++ ) for ( j = 0 ; j <= M ; j++ ) *(*(obs+j)+i) = *(*(masterobs+j)+i0+i); MxFree ( masterobs, vc, vlen ); printf ( " write selected data to file = " ); GETSTR ( obsfn ); printf ( "%s\n", obsfn ); MxWrite ( obs, M+1, N, obsfn ); printf ( "\n SECTION 2: COMPONENT SPECTRA MODELING SWITCHES (0/1)\n\n" ); for ( K = i = 0 ; i < 3 ; i++ ) { int sw; GETINT(&sw); sw = sw ? 1 : 0; printf ( " %s = %d\n", starcode[i], sw ); if ( sw ) ksw[K++] = i; } printf ( "\n number of components to be resolved is %ld\n", K ); /* allocating memory */ Ndft = 2*(N/2 + 1); dftobs = MxAlloc ( M, Ndft ); dft_fwd ( M, N, obs+1, dftobs ); otimes = *MxAlloc ( 1, M ); rvcorr = *MxAlloc ( 1, M ); sig = *MxAlloc ( 1, M ); res = MxAlloc ( M+1, N ); dftres = MxAlloc ( M, Ndft ); mod = MxAlloc ( K+1, N ); dftmod = MxAlloc ( K, Ndft ); rvm = MxAlloc ( K, M ); lfm = MxAlloc ( K, M ); for ( i = 0 ; i < N ; i++ ) { *(*res+i) = *(*obs+i); *(*mod+i) = *(*obs+i); } printf ( "\n SECTION 3: DESCRIPTORS TO OBSERVED SPECTRA\n" ); printf ( " AND LIGHT-FACTORS ASSIGNED TO COMPONENTS\n\n" ); printf ( " %14s%12s%12s", "t_obs", "rv_corr", "noise_rms" ); for ( k = 0 ; k < K ; k++ ) printf ( " lf_%s", starcode[ksw[k]] ); printf ( "\n" ); printf ( " %14s%12s%12s", "[day]", "[km/s]", "[1]" ); for ( k = 0 ; k < K ; k++ ) printf ( " [1]" ); printf ( "\n\n" ); for ( j = 0 ; j < M ; j++ ) { GETDBL(otimes+j); printf ( " %14.5lf", *(otimes+j) ); GETDBL(rvcorr+j); printf ( "%12.4lf", *(rvcorr+j) ); GETDBL(sig+j); printf ( "%12.4lf", *(sig+j) ); for ( k = 0; k < K ; k++ ) { GETDBL(*(lfm+k)+j); printf ( "%10.4lf", *(*(lfm+k)+j) ); } putchar ( '\n' ); } printf ( "\n SECTION 4: PARAMETERS OF ORBITS\n" ); for ( nfp = i = 0 ; i < TRIORB_NP ; i++ ) { if ( 0 == i ) printf ( "\n wide (AB--C) orbit\n\n" ); if ( 6 == i ) printf ( "\n tight (A--B) orbit\n\n" ); printf ( " %s [%s] = ", triorb_pname(i), triorb_punit(i) ); GETDBL(op0+i); printf ( triorb_pformat(i), *(op0+i) ); printf ( " +/- " ); GETDBL(dop0+i); printf ( triorb_pformat(i), *(dop0+i) ); if ( *(dop0+i) ) { opsw[nfp++] = i; printf ( " *** free ***" ); } if ( 2 == i || 8 == i ) *(op0+i) = *(op0+i) / (1-*(op0+i)); /* ecc */ printf ( "\n" ); } printf ( "\n number of free orbital parameters is %ld\n", nfp ); printf ( "\n SECTION 5: OPTIMISATION DETAILS\n\n" ); if ( 0 == nfp ) { printf ( " WARNING: *** no free orbital parameters *** \n" ); printf ( " optimisation of orb. parameters will not be performed\n" ); printf ( " all input in this section is ignored\n\n" ); } GETLNG( &nruns ); printf ( " number of independent optimisation runs = %ld\n", nruns ); GETLNG( &niter ); printf ( " number of allowed iterations per run = %ld\n", niter ); GETDBL( &stoprat ); printf ( " stop when simplex shrinked by factor = %lg\n", stoprat ); printf ( "\n SECTION 6: OUTPUT FILES\n\n" ); printf ( " write model spectra to file = " ); GETSTR ( modfn ); printf ( "%s\n", modfn ); printf ( " write residuals to file = " ); GETSTR ( resfn ); printf ( "%s\n", resfn ); printf ( " write radial velocities to file = " ); GETSTR ( rvsfn ); printf ( "%s\n", rvsfn ); printf ( " write optimisation log to file = " ); scanf ( "%s", logfn ); if ( strlen ( logfn ) ) { printf ( "%s\n", logfn ); if ( NULL == ( logfp = fopen ( logfn, "w" ) ) ) DIE ( "could not open log file" ); setbuf ( logfp, NULL ); } else { printf ( "[no log file will be written]\n" ); } printf ( "\n SECTION 7: OPTIMISATION\n\n" ); if ( 0 == nfp ) { /* separation */ double chi2; printf ( " WARNING: *** no free orbital parameters *** \n" ); chi2 = meritfn ( op0 ); printf ( " separation at the starting point: chi2=%lg gof=%.2lf\n", chi2, gsl_sf_gamma_inc_Q ( N*(M-K)/2.0, chi2/2.0 ) ); dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn ); dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn ); MxWrite( rvm, K, M, rvsfn ); } else { /* disentangling */ const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; gsl_multimin_fminimizer *s = NULL; gsl_multimin_function minex_func; gsl_vector *ss, *x; size_t iter = 0, irun = 0, i; int status; double size0 = 1.0, size, chi2; const gsl_rng_type * R; gsl_rng * r; gsl_rng_env_setup (); R = gsl_rng_default; r = gsl_rng_alloc (R); minex_func.f = &meritfngsl; minex_func.n = nfp; minex_func.params = (void *) NULL; s = gsl_multimin_fminimizer_alloc (T, nfp); x = gsl_vector_alloc (nfp); /* starting point */ ss = gsl_vector_alloc (nfp); /* initial vertex size vector */ for ( i = 0 ; i < nfp ; i++ ) { gsl_vector_set ( x, i, op0[opsw[i]] ); gsl_vector_set ( ss, i, dop0[opsw[i]] ); size0 *= dop0[opsw[i]]; } chi2 = meritfngsl ( x, NULL ); printf ( " separation at the starting point: chi2=%lg gof=%.2lf\n", chi2, gsl_sf_gamma_inc_Q ( N*(M-K)/2.0, chi2/2.0 ) ); dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn ); dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn ); MxWrite( rvm, K, M, rvsfn ); printf ( " converged disentangling runs reported only if chi2 decreases\n" ); for ( irun = 0 ; irun < nruns ; irun++ ) { for ( i = 0 ; i < nfp ; i++ ) { double tmp = 2.0 * ( gsl_rng_uniform (r) - 0.5 ); gsl_vector_set ( x, i, op0[opsw[i]] + tmp * dop0[opsw[i]] ); gsl_vector_set ( ss, i, dop0[opsw[i]] ); } gsl_multimin_fminimizer_set ( s, &minex_func, x, ss ); status = GSL_FAILURE; size = size0; for ( iter = 0 ; iter < niter ; iter++ ) { if ( gsl_multimin_fminimizer_iterate (s) ) break; size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, stoprat*size0); if ( GSL_SUCCESS == status ) break; } if ( (GSL_SUCCESS == status) && (s->fval < chi2) ) { printf ( "\n irun=%d iter=%d sxshrnkf=%.2lg chi2=%lg ", irun+1, iter, size/size0, chi2 = s->fval ); printf ( "gof=%.2lf\n", gsl_sf_gamma_inc_Q ( (N*(M-K)-nfp)/2.0, chi2/2.0 ) ); for ( i = 0 ; i < nfp ; i++ ) { double xi = gsl_vector_get (s->x, i); if ( 2 == opsw[i] || 8 == opsw[i] ) xi = fabs ( xi / (1 + xi) ); printf ( " %40s = ", triorb_pname(opsw[i]) ); printf ( triorb_pformat(opsw[i]), xi ); if ( strcmp ( triorb_punit(opsw[i]), "1" ) ) printf ( " %s", triorb_punit(opsw[i]) ); printf ( "\n" ); } dft_bck ( K, N, dftmod, mod+1 ); MxWrite ( mod, K+1, N, modfn ); dft_bck ( M, N, dftres, res+1 ); MxWrite ( res, M+1, N, resfn ); MxWrite( rvm, K, M, rvsfn ); } if ( (GSL_SUCCESS == status) && strlen ( logfn ) ) { fprintf ( logfp, "%d %d %.2lg %lg ", irun+1, iter, size/size0, s->fval ); fprintf ( logfp, "%.2lf ", gsl_sf_gamma_inc_Q ( (N*(M-K)-nfp)/2.0, (s->fval)/2.0 ) ); for ( i = 0 ; i < nfp ; i++ ) { double xi = gsl_vector_get (s->x, i); if ( 2 == opsw[i] || 8 == opsw[i] ) xi = fabs ( xi / (1 + xi) ); fprintf ( logfp, " " ); fprintf ( logfp, triorb_pformat(i), xi ); } fprintf ( logfp, "\n" ); } } gsl_multimin_fminimizer_free (s); gsl_vector_free(x); gsl_vector_free(ss); printf ( "\n completed %ld optimisation runs\n\n", nruns ); } printf ( " EXITING REGULARLY\n\n" ); return EXIT_SUCCESS; } /*****************************************************************************/ double meritfngsl ( const gsl_vector *v, void *params ) { long i, j; double op[TRIORB_NP]; for ( i = j = 0 ; i < TRIORB_NP ; i++ ) op[i] = dop0[i] ? gsl_vector_get ( v, j++ ) : op0[i]; return meritfn ( op ); } /*****************************************************************************/ double meritfn ( double *opin ) { long j, k; double op[TRIORB_NP], rv[3]; op[ 0] = opin[ 0]; op[ 1] = opin[ 1]; op[ 2] = fabs ( opin[2] / (1 + opin[2]) ); op[ 3] = opin[ 3] * (M_PI/180); op[ 4] = opin[ 4]; op[ 5] = opin[ 5]; op[ 6] = opin[ 6]; op[ 7] = opin[ 7]; op[ 8] = fabs ( opin[8] / (1 + opin[8]) ); op[ 9] = opin[ 9] * (M_PI/180); op[10] = opin[10] / rvstep; op[11] = opin[11] / rvstep; op[12] = opin[12] * (M_PI/180); for ( j = 0 ; j < M ; j++ ) { triorb_rv ( op, otimes[j], rv ); for ( k = 0 ; k < K ; k++ ) *(*(rvm+k)+j) = rv[ksw[k]] + *(rvcorr+j) / rvstep; } return fd3sep ( K, M, N, dftobs, sig, rvm, lfm, dftmod, dftres ); } /*****************************************************************************/
{ "alphanum_fraction": 0.4986057729, "avg_line_length": 36.9610027855, "ext": "c", "hexsha": "3d4e91d4b1c11430119a6f9454f787ab6de15a1b", "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": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mrawls/FDBinary-tools", "max_forks_repo_path": "fdbinary.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "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": "mrawls/FDBinary-tools", "max_issues_repo_path": "fdbinary.c", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "26b78a12df53d9a1a477fcf247cbf2dad8c39836", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mrawls/FDBinary-tools", "max_stars_repo_path": "fdbinary.c", "max_stars_repo_stars_event_max_datetime": "2020-08-28T14:43:53.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-25T09:45:03.000Z", "num_tokens": 4577, "size": 13269 }
#pragma once #include <stdlib.h> #include <stdio.h> #include <MathLib/MathLibDll.h> #include <MathLib/MathLib.h> #include <MathLib/ThreeTuple.h> #include <gsl/matrix/gsl_matrix.h> #include <gsl/vector/gsl_vector.h> #include <MathLib/Matrix.h> #define VECTOR_AT(v, i) (*((v->data + (i * v->tda )))) /*====================================================================================================================================================================* | 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 MATHLIB_DECLSPEC Vector : public Matrix{ public: /** constructor - creates an n row vector that is not initialized to any particular values */ Vector(int n); /** default constructor */ Vector(); /** copy constructor - performs a deep copy of the matrix passed in as a parameter. */ Vector(const Vector& other); /** destructor. */ ~Vector(); /** copy operator - performs a deep copy of the Vector passed in as a parameter. */ Vector& operator=(const Vector &other); /** copy operator - performs a deep copy of the Vector passed in as a parameter. */ Vector& operator=(const Matrix &other); /** this method performs a shallow copy of the Vector that is passed in as a parameter. */ void shallowCopy(const Matrix& other); /** this method performs a deep copy of the vector that is passed in as a paramerer. */ void deepCopy(const Matrix& other); /** This method sets the current vector to be equal to one of the products: A * b or A'*b. The value of transA indicates if A is transposed or not */ void setToProductOf(const Matrix& A, const Matrix& B, bool transA = false, bool transB = false); /** This method sets the current vector to be equal to one of the rows of A - shallow column only! */ void setToRow(const Matrix& A, int row, int start = 0, int howMany = -1); /** This method sets the current vector to be equal to one of the cols of A - shallow column only! */ void setToCol(const Matrix& A, int col, int start = 0, int howMany = -1); /** This method prints the contents of the matrix - testing purpose only. */ void printVector() const; /** This method returns a copy of the value of the matrix at (i,j) */ double get(int i) const; /** This method sets the value of the matrix at (i,j) to newVal. */ void set(int i, double newVal); /** Computes the 2-norm squared for the current vector. */ inline double normSquared(){ int r = getRowCount(); double result = 0; for (int i=0;i<r;i++){ double n = MATRIX_AT(matrix, i, 0) ; result += n*n; } return result; } }; MATHLIB_DECLSPEC void testVectorClass();
{ "alphanum_fraction": 0.6058015267, "avg_line_length": 27.9914529915, "ext": "h", "hexsha": "2696f5ef87e564756f40fa92006bf73f145bc137", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/MathLib/Vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/MathLib/Vector.h", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/MathLib/Vector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 745, "size": 3275 }
#pragma once #include "arcana/expected.h" #include "arcana/functional/inplace_function.h" #include "arcana/iterators.h" #include "arcana/type_traits.h" #include "cancellation.h" #include <gsl/gsl> #include <memory> #include <stdexcept> #include <atomic> namespace arcana { template<typename ResultT, typename ErrorT> class task_completion_source; // // A scheduler that will invoke the continuation inline // right after the previous task. // namespace { constexpr auto inline_scheduler = [](auto&& callable) { callable(); }; } } #include "internal/internal_task.h" namespace arcana { // // Generic task system to run work with continuations on a generic scheduler. // // The scheduler on which tasks are queued must satisfy this contract: // // struct scheduler // { // template<CallableT> // void queue(CallableT&& callable) // { // callable must be usable like this: callable(); // } // }; // template<typename ResultT, typename ErrorT> class task { using payload_t = internal::task_payload_with_return<ResultT, ErrorT>; using payload_ptr = std::shared_ptr<payload_t>; static_assert(std::is_same<typename as_expected<ResultT, ErrorT>::value_type, ResultT>::value, "task can't be of expected<T>"); public: using result_type = ResultT; using error_type = ErrorT; task() = default; task(const task& other) = default; task(task&& other) = default; task(const task_completion_source<ResultT, ErrorT>& source) : m_payload{ source.m_payload } {} task(task_completion_source<ResultT, ErrorT>&& source) : m_payload{ std::move(source.m_payload) } {} task& operator=(task&& other) = default; task& operator=(const task& other) = default; bool operator==(const task& other) { return m_payload == other.m_payload; } // // Executes a callable on this scheduler once this task is finished and // returns a task that represents the callable. // // Calling .then() on the returned task will queue a task to run after the // callable is run. // template<typename SchedulerT, typename CallableT> auto then(SchedulerT& scheduler, cancellation& token, CallableT&& callable) { using traits = internal::callable_traits<CallableT, result_type>; using wrapper = internal::input_output_wrapper<result_type, error_type, traits::handles_expected::value>; static_assert(error_priority<error_type>::value <= error_priority<typename traits::error_propagation_type>::value, "The error of a parent task needs to be convertible to the error of a child task."); static_assert(std::is_same_v<typename expected_error_or<typename traits::input_type, error_type>::type, error_type>, "Continuation expected input parameter needs to use the same error type as the parent task"); auto factory{ internal::make_task_factory( internal::make_work_payload<typename traits::expected_return_type::value_type, typename traits::error_propagation_type>( [callable = wrapper::wrap_callable(std::forward<CallableT>(callable), token)] (internal::base_task_payload* self) mutable noexcept { return callable(*static_cast<payload_t*>(self)->Result); }) ) }; m_payload->create_continuation([&scheduler](auto&& c) { scheduler(std::forward<decltype(c)>(c)); }, m_payload, std::move(factory.to_run.m_payload)); return factory.to_return; } private: explicit task(payload_ptr payload) : m_payload{ std::move(payload) } {} template<typename OtherResultT, typename OtherErrorT> friend class task; friend class task_completion_source<ResultT, ErrorT>; template<typename OtherErrorT, typename OtherResultT> friend struct internal::task_factory; template<typename SchedulerT, typename CallableT> friend auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory< typename internal::callable_traits<CallableT, void>::error_propagation_type, typename internal::callable_traits<CallableT, void>::expected_return_type::value_type>::task_t; payload_ptr m_payload; }; } namespace arcana { template<typename ResultT, typename ErrorT> class task_completion_source { using payload_t = internal::task_payload_with_return<ResultT, ErrorT>; using payload_ptr = std::shared_ptr<payload_t>; public: using result_type = ResultT; using error_type = ErrorT; task_completion_source() : m_payload{ std::make_shared<payload_t>() } {} // // Completes the task this source represents. // void complete() { static_assert(std::is_same<ResultT, void>::value, "complete with no arguments can only be used with a void completion source"); m_payload->complete(basic_expected<void, ErrorT>::make_valid()); } // // Completes the task this source represents. // template<typename ValueT> void complete(ValueT&& value) { m_payload->complete(std::forward<ValueT>(value)); } // // Returns whether or not the current source has already been completed. // bool completed() const { return m_payload->completed(); } // // Converts this task_completion_source to a task object for consumers to use. // task<ResultT, ErrorT> as_task() const & { return task<ResultT, ErrorT>{ m_payload }; } task<ResultT, ErrorT> as_task() && { return task<ResultT, ErrorT>{ std::move(m_payload) }; } private: explicit task_completion_source(std::shared_ptr<payload_t> payload) : m_payload{ std::move(payload) } {} friend class task<ResultT, ErrorT>; friend class abstract_task_completion_source; template<typename E, typename R> friend struct internal::task_factory; payload_ptr m_payload; }; // // a type erased version of task_completion_source. // class abstract_task_completion_source { using payload_t = internal::base_task_payload; using payload_ptr = std::shared_ptr<payload_t>; public: abstract_task_completion_source() : m_payload{} {} template<typename T, typename E> explicit abstract_task_completion_source(const task_completion_source<T, E>& other) : m_payload{ other.m_payload } {} template<typename T, typename E> explicit abstract_task_completion_source(task_completion_source<T, E>&& other) : m_payload{ std::move(other.m_payload) } {} // // Returns whether or not the current source has already been completed. // bool completed() const { return m_payload->completed(); } template<typename T, typename E> bool operator==(const task_completion_source<T, E>& other) { return m_payload == other.m_payload; } template<typename T, typename E> task_completion_source<T, E> unsafe_cast() { return task_completion_source<T, E>{ std::static_pointer_cast<internal::task_payload_with_return<T, E>>(m_payload) }; } private: payload_ptr m_payload; }; // // creates a task and queues it to run on the given scheduler // template<typename SchedulerT, typename CallableT> inline auto make_task(SchedulerT& scheduler, cancellation& token, CallableT&& callable) -> typename internal::task_factory< typename internal::callable_traits<CallableT, void>::error_propagation_type, typename internal::callable_traits<CallableT, void>::expected_return_type::value_type>::task_t { using traits = internal::callable_traits<CallableT, void>; using wrapper = internal::input_output_wrapper<void, typename traits::error_propagation_type, false>; auto factory{ internal::make_task_factory( internal::make_work_payload<typename traits::expected_return_type::value_type, typename traits::error_propagation_type>( [callable = wrapper::wrap_callable(std::forward<CallableT>(callable), token)] (internal::base_task_payload*) mutable noexcept { return callable(basic_expected<void, typename traits::error_propagation_type>::make_valid()); }) ) }; scheduler([to_run = std::move(factory.to_run)] { to_run.m_payload->run(nullptr); }); return factory.to_return; } // // creates a completed task from the given result // template<typename ErrorT, typename ResultT> inline task<typename as_expected<ResultT, ErrorT>::value_type, ErrorT> task_from_result(ResultT&& value) { task_completion_source<typename as_expected<ResultT, ErrorT>::value_type, ErrorT> result; result.complete(std::forward<ResultT>(value)); return std::move(result); } template<typename ErrorT> inline task<void, ErrorT> task_from_result() { task_completion_source<void, ErrorT> result; result.complete(); return std::move(result); } template<typename ResultT, typename ErrorT> inline task<ResultT, std::error_code> task_from_error(const ErrorT& error) { task_completion_source<ResultT, std::error_code> result; result.complete(make_unexpected(make_error_code(error))); return std::move(result); } template<typename ResultT> inline task<ResultT, std::error_code> task_from_error(const std::error_code& error) { task_completion_source<ResultT, std::error_code> result; result.complete(make_unexpected(error)); return std::move(result); } template<typename ResultT> inline task<ResultT, std::exception_ptr> task_from_error(const std::exception_ptr& error) { task_completion_source<ResultT, std::exception_ptr> result; result.complete(make_unexpected(error)); return std::move(result); } template<typename ErrorT> inline task<void, ErrorT> when_all(gsl::span<task<void, ErrorT>> tasks) { if (tasks.empty()) { return task_from_result<ErrorT>(); } struct when_all_data { std::mutex mutex; size_t pendingCount; std::error_code error; }; task_completion_source<void, ErrorT> result; auto data = std::make_shared<when_all_data>(); data->pendingCount = tasks.size(); for (task<void, ErrorT>& task : tasks) { task.then(inline_scheduler, cancellation::none(), [data, result](const basic_expected<void, ErrorT>& exp) mutable noexcept { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pendingCount -= 1; last = data->pendingCount == 0; if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(make_unexpected(data->error)); } else { result.complete(); } } }); } return std::move(result); } template<typename T, typename ErrorT> inline task<std::vector<T>, ErrorT> when_all(gsl::span<task<T, ErrorT>> tasks) { if (tasks.empty()) { return task_from_result<ErrorT, std::vector<T>>(std::vector<T>()); } struct when_all_data { std::mutex mutex; size_t pendingCount; std::error_code error; std::vector<T> results; }; task_completion_source<std::vector<T>, ErrorT> result; auto data = std::make_shared<when_all_data>(); data->pendingCount = tasks.size(); data->results.resize(tasks.size()); //using forloop with index to be able to keep proper order of results for (auto idx = 0U; idx < data->results.size(); idx++) { tasks[idx].then(arcana::inline_scheduler, cancellation::none(), [data, result, idx](const basic_expected<T, ErrorT>& exp) mutable noexcept { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pendingCount -= 1; last = data->pendingCount == 0; if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } if (exp.has_value()) { data->results[idx] = exp.value(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(make_unexpected(data->error)); } else { result.complete(data->results); } } }); } return std::move(result); } template<typename ErrorT, typename... ArgTs> inline task<std::tuple<typename arcana::void_passthrough<ArgTs>::type...>, ErrorT> when_all(task<ArgTs, ErrorT>... tasks) { using void_passthrough_tuple = std::tuple<typename arcana::void_passthrough<ArgTs>::type...>; struct when_all_data { std::mutex mutex; int pending; ErrorT error; void_passthrough_tuple results; }; task_completion_source<void_passthrough_tuple, ErrorT> result; auto data = std::make_shared<when_all_data>(); data->pending = std::tuple_size<void_passthrough_tuple>::value; std::tuple<task<ArgTs, ErrorT>&...> taskrefs = std::make_tuple(std::ref(tasks)...); iterate_tuple(taskrefs, [&](auto& task, auto idx) { using task_t = std::remove_reference_t<decltype(task)>; task.then(inline_scheduler, cancellation::none(), [data, result](const basic_expected<typename task_t::result_type, ErrorT>& exp) mutable noexcept { bool last = false; { std::lock_guard<std::mutex> guard{ data->mutex }; data->pending -= 1; last = data->pending == 0; internal::write_expected_to_tuple<decltype(idx)::value, ErrorT>(data->results, exp); if (exp.has_error() && !data->error) { // set the first error, as it might have cascaded data->error = exp.error(); } } if (last) // we were the last task to complete { if (data->error) { result.complete(make_unexpected(data->error)); } else { result.complete(std::move(data->results)); } } return basic_expected<void, ErrorT>::make_valid(); }); }); return std::move(result); } }
{ "alphanum_fraction": 0.5649636775, "avg_line_length": 33.124260355, "ext": "h", "hexsha": "762fa6872797110f9a87fe010cb6f4aaf96bc728", "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": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/arcana.cpp", "max_forks_repo_path": "Source/Shared/arcana/threading/task.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "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": "syntheticmagus/arcana.cpp", "max_issues_repo_path": "Source/Shared/arcana/threading/task.h", "max_line_length": 152, "max_stars_count": 2, "max_stars_repo_head_hexsha": "57abe0d7a24f2d529a0f22b4ff7cfa60e45b3e0c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/arcana.cpp", "max_stars_repo_path": "Source/Shared/arcana/threading/task.h", "max_stars_repo_stars_event_max_datetime": "2021-07-07T10:25:56.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-25T10:03:17.000Z", "num_tokens": 3341, "size": 16794 }
/* randist/exppow.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The exponential power probability distribution is p(x) dx = (1/(2 a Gamma(1+1/b))) * exp(-|x/a|^b) dx for -infty < x < infty. For b = 1 it reduces to the Laplace distribution. The exponential power distribution is related to the gamma distribution by E = a * pow(G(1/b),1/b), where E is an exponential power variate and G is a gamma variate. We use this relation for b < 1. For b >=1 we use rejection methods based on the laplace and gaussian distributions which should be faster. See P. R. Tadikamalla, "Random Sampling from the Exponential Power Distribution", Journal of the American Statistical Association, September 1980, Volume 75, Number 371, pages 683-686. */ double gsl_ran_exppow (const gsl_rng * r, const double a, const double b) { if (b < 1) { double u = gsl_rng_uniform (r) ; double v = gsl_ran_gamma (r, 1/b, 1.0) ; double z = a * pow(v, 1/b) ; if (u > 0.5) { return z ; } else { return -z ; } } else if (b == 1) { /* Laplace distribution */ return gsl_ran_laplace (r, a) ; } else if (b < 2) { /* Use laplace distribution for rejection method */ double x, y, h, ratio, u ; /* Scale factor chosen by upper bound on ratio at b = 2 */ double s = 1.4489 ; do { x = gsl_ran_laplace (r, a) ; y = gsl_ran_laplace_pdf (x,a) ; h = gsl_ran_exppow_pdf (x,a,b) ; ratio = h/(s * y) ; u = gsl_rng_uniform (r) ; } while (u > ratio) ; return x ; } else if (b == 2) { /* Gaussian distribution */ return gsl_ran_gaussian (r, a/sqrt(2.0)) ; } else { /* Use gaussian for rejection method */ double x, y, h, ratio, u ; const double sigma = a / sqrt(2.0) ; /* Scale factor chosen by upper bound on ratio at b = infinity. This could be improved by using a rational function approximation to the bounding curve. */ double s = 2.4091 ; /* this is sqrt(pi) e / 2 */ do { x = gsl_ran_gaussian (r, sigma) ; y = gsl_ran_gaussian_pdf (x, sigma) ; h = gsl_ran_exppow_pdf (x, a, b) ; ratio = h/(s * y) ; u = gsl_rng_uniform (r) ; } while (u > ratio) ; return x; } } double gsl_ran_exppow_pdf (const double x, const double a, const double b) { double p ; double lngamma = gsl_sf_lngamma (1+1/b) ; p = (1/(2*a)) * exp(-pow(fabs(x/a),b) - lngamma); return p; }
{ "alphanum_fraction": 0.6242707118, "avg_line_length": 25.7744360902, "ext": "c", "hexsha": "af085aab04c966073ef2dff1cb98e2e08bf03c41", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/randist/exppow.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/randist/exppow.c", "max_line_length": 72, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/exppow.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": 1043, "size": 3428 }
/* AFS.c These are definitions / methods of the AFS object for a markov chain representation of the AFS statespace during the coalecsent process A. Kern 2012 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_matrix_int.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_sf.h> #include "AFS.h" #include "adkGSL.h" //#include "cmc_island_mle.h" #include "multimin.h" #include "sites.h" #include "cs.h" #include "adkCSparse.h" #include <glib.h> afsObject *afsObjectNew(int n1, int n2){ int i; afsObject *tmp; tmp = (afsObject *)malloc(sizeof(afsObject)); tmp->popMats =(gsl_matrix_int **) malloc(2* sizeof(gsl_matrix_int)); tmp->popMats[0] = (gsl_matrix_int *) gsl_matrix_int_alloc(n1+1,n2+1); tmp->popMats[1] = (gsl_matrix_int *) gsl_matrix_int_alloc(n1+1,n2+1); tmp->npops=2; //unneeded right now but maybe will generalize in the future tmp->matString = malloc(sizeof(char) * ((n1+1)*(n2+1)*2) + 1); for(i=0;i<(n1*n2*2);i++){tmp->matString[i] ='\0';} return(tmp); } //afsObjectNewFrom-- creates a deep copy of an afsObject afsObject *afsObjectNewFrom(afsObject *v){ afsObject *tmp; tmp = (afsObject *) malloc(sizeof(afsObject)); tmp->popMats = (gsl_matrix_int **) malloc(2* sizeof(gsl_matrix_int)); tmp->popMats[0] = (gsl_matrix_int *)gsl_matrix_int_alloc(v->popMats[0]->size1,v->popMats[0]->size2); tmp->popMats[1] = (gsl_matrix_int *)gsl_matrix_int_alloc(v->popMats[1]->size1,v->popMats[1]->size2); tmp->npops=v->npops; gsl_matrix_int_memcpy(tmp->popMats[0],v->popMats[0]); gsl_matrix_int_memcpy(tmp->popMats[1],v->popMats[1]); tmp->nalleles=afsObjectCount(tmp); tmp->matString = malloc(sizeof(char) * ((v->popMats[0]->size1 +1) * (v->popMats[0]->size2 +1) * 2) + 1); // for(i=0;i<(v->popMats[0]->size1 * v->popMats[0]->size2 * 2);i++){tmp->matString[i] ='\0';} tmp->matString[0] ='\0'; return(tmp); } void afsObjectFree(afsObject *v){ gsl_matrix_int_free(v->popMats[0]); gsl_matrix_int_free(v->popMats[1]); free(v->popMats); free(v->matString); free(v); } //sets up the initial sample of size n1 from population 1 and size n2 from // population 2 void afsObjectInit(afsObject *v, int n1, int n2){ int i, j; char c[1000]; gsl_matrix_int_set_zero(v->popMats[0]); gsl_matrix_int_set_zero(v->popMats[1]); gsl_matrix_int_set(v->popMats[0],1,0,n1); gsl_matrix_int_set(v->popMats[1],0,1,n2); v->aCounts[0]=n1; v->aCounts[1]=n2; v->nalleles = n1 + n2; for(i=0;i<= n1;i++){ for(j=0;j<=n2;j++){ itoa(gsl_matrix_int_get(v->popMats[0],i,j),c); strcat(v->matString, c); itoa(gsl_matrix_int_get(v->popMats[1],i,j),c); strcat(v->matString, c); } } //printf("from within afsObjInit: %s\n",v->matString); } void afsObjectPrint(afsObject *v){ int i, j; int m1, m2; m1 = v->popMats[0]->size1; m2 = v->popMats[0]->size2; for(i=0;i<m1;i++){ for(j=0;j<m2;j++) printf("%d ",gsl_matrix_int_get(v->popMats[0],i,j)); printf("|| "); for(j=0;j<m2;j++) printf("%d ",gsl_matrix_int_get(v->popMats[1],i,j)); printf("\n"); } } int nDescPop1(afsObject *v){ int sum, i, j; int m1, m2; m1 = v->popMats[0]->size1; m2 = v->popMats[0]->size2; sum=0; for(i=0;i<m1;i++){ for(j=0;j<m2;j++){ sum+= gsl_matrix_int_get(v->popMats[0],i,j) * i; sum+= gsl_matrix_int_get(v->popMats[1],i,j) * i; } } return(sum); } int nDescPop2(afsObject *v){ int sum, i, j; int m1, m2; m1 = v->popMats[0]->size1; m2 = v->popMats[0]->size2; sum=0; for(i=0;i<m1;i++){ for(j=0;j<m2;j++){ sum+= gsl_matrix_int_get(v->popMats[0],i,j) * j; sum+= gsl_matrix_int_get(v->popMats[1],i,j) * j; } } return(sum); } /* void gsl_matrix_prettyPrint(gsl_matrix *m){ int i, j; for(i=0;i<m->size1;i++){ for(j=0;j<m->size2;j++){ printf("%f ",gsl_matrix_get(m,i,j)); } printf("\n"); } printf("///////////\n"); } */ //compatibleAfsGivenInitial tests if correct number of ancestral lineages // are present and if each entry is >= 0, i.e. no bogus negative afs cells int compatibleAfsGivenInitial(afsObject *v, int m1, int m2){ if (nDescPop1(v) == m1 && nDescPop2(v) == m2 && gsl_matrix_int_min(v->popMats[0]) >= 0 && gsl_matrix_int_min(v->popMats[1]) >= 0) return(1); else return(0); } //nonZeroEntries -- fills a 2D list of coords for nonZero entries in matrix void nonZeroEntries(gsl_matrix_int *m, int **coords, int *count){ int i, j; *count = 0; for(i=0;i<m->size1;i++){ for(j=0;j<m->size2;j++){ if(gsl_matrix_int_get(m,i,j) != 0){ coords[*count][0]=i; coords[*count][1]=j; *count+=1; } } } } //countNegativeEntries-- returns the count of matrix entries < 0 int countNegativeEntries(gsl_matrix_int *m){ int i, j, sum=0; for(i=0;i<m->size1;i++){ for(j=0;j<m->size2;j++){ if(gsl_matrix_int_get(m,i,j) < 0) sum+=1; } } return(sum); } //entriesGreaterThan -- fills a 2D list of coords for nonZero entries in matrix void entriesGreaterThan(gsl_matrix_int *m, int **coords, int *count, int cut){ int i, j; *count = 0; for(i=0;i<m->size1;i++){ for(j=0;j<m->size2;j++){ if(gsl_matrix_int_get(m,i,j) > cut){ coords[*count][0]=i; coords[*count][1]=j; *count+=1; } } } } //entriesLessThan -- fills a 2D list of coords for nonZero entries in matrix void entriesLessThan(gsl_matrix_int *m, int **coords, int *count, int cut){ int i, j; *count = 0; for(i=0;i<m->size1;i++){ for(j=0;j<m->size2;j++){ if(gsl_matrix_int_get(m,i,j) < cut){ coords[*count][0]=i; coords[*count][1]=j; *count+=1; } } } } /* factorials */ double xchoosey(int n, int k){ if(n<k) return(0); if(n == k || k == 0) return(1); if(k == 1) return(n); if(k==2) return((float)n*(n-1.0)/2.0); return(gsl_sf_choose(n,k)); } //matrixSum -- just convenience function int matrixSum(gsl_matrix_int *m){ int i,j, sum=0; for(i=0;i<m->size1;i++) for(j=0;j<m->size2;j++) sum+= gsl_matrix_int_get(m,i,j); return(sum); } //matrixSumDouble -- just convenience function double matrixSumDouble(gsl_matrix *m){ int i,j; double sum=0; for(i=0;i<m->size1;i++) for(j=0;j<m->size2;j++) sum+= gsl_matrix_get(m,i,j); return(sum); } //matrixAllGTZ-- again a silly convenience function int matrixAllGTZ(gsl_matrix_int *m){ int i,j; for(i=0;i<m->size1;i++) for(j=0;j<m->size2;j++) if(gsl_matrix_int_get(m,i,j) <=0) return(0); return(1); } //afsObjectsEqual -- compares objects based on matrices and nothing more int afsObjectsEqual(afsObject *a, afsObject *b){ if(gsl_matrix_int_equal(a->popMats[0],b->popMats[0]) && gsl_matrix_int_equal(a->popMats[1],b->popMats[1])) return(1); else return(0); } int afsObjectQsortCompare(const void *p1, const void *p2){ afsObject **x = (afsObject **)p1; afsObject **y = (afsObject **)p2; if((*x)->nalleles < (*y)->nalleles) return 1; else if ((*x)->nalleles > (*y)->nalleles) return -1; else return 0; } //subtracts matrices from one another to aid in ID of operations afsObject *afsObjectDelta(afsObject *a, afsObject *b){ afsObject *tmp; tmp = afsObjectNewFrom(a); gsl_matrix_int_memcpy(tmp->popMats[0],a->popMats[0]); gsl_matrix_int_memcpy(tmp->popMats[1],a->popMats[1]); gsl_matrix_int_sub(tmp->popMats[0],b->popMats[0]); gsl_matrix_int_sub(tmp->popMats[1],b->popMats[1]); return(tmp); } //subtracts matrices from one another to aid in ID of operations void afsObjectDeltaPre(afsObject *a, afsObject *b,afsObject *tmp){ gsl_matrix_int_memcpy(tmp->popMats[0],a->popMats[0]); gsl_matrix_int_memcpy(tmp->popMats[1],a->popMats[1]); gsl_matrix_int_sub(tmp->popMats[0],b->popMats[0]); gsl_matrix_int_sub(tmp->popMats[1],b->popMats[1]); } //afsObjectCount-- returns the total number of lineages in the afs state int afsObjectCount(afsObject *a){ return(matrixSum(a->popMats[0])+matrixSum(a->popMats[1])); } afsStateSpace *afsStateSpaceNew(){ afsStateSpace *tmp; tmp =(afsStateSpace *) malloc(sizeof(afsStateSpace)); tmp->nstates=0; tmp->states = (afsObject **) malloc(MAXSTATES * sizeof(afsObject)); tmp->stateHash = g_hash_table_new(g_str_hash, g_str_equal); return(tmp); } afsStateSpace *afsStateSpaceCopy(afsStateSpace *S){ int i; afsStateSpace *tmp; tmp =(afsStateSpace *) malloc(sizeof(afsStateSpace)); tmp->nstates=S->nstates; tmp->states = (afsObject **) malloc(MAXSTATES * sizeof(afsObject)); for(i=0;i<S->nstates;i++) tmp->states[i] = S->states[i]; // tmp->stateHash = g_hash_table_new(g_str_hash, g_str_equal); return(tmp); } void afsStateSpaceFree(afsStateSpace *a){ int i; for(i=0;i<a->nstates;i++)afsObjectFree(a->states[i]); free(a->states); // for(i=0;i<MAXSIZE;i++){ // free(a->nstateArray[i]); // for(j=0;j<MAXSIZE;j++){ // free(a->tmpStorage[i][j]); // } // free(a->tmpStorage[i]); // } // free(a->tmpStorage); // free(a->nstateArray); g_hash_table_destroy(a->stateHash); free(a); } //afsStateSpaceContainsState-- linear search for state int afsStateSpaceContainsState(afsStateSpace *S, afsObject *aState){ int i; for(i = S->nstates -1 ; i > - 1;i--){ if(S->states[i]->nalleles == aState->nalleles) if(S->states[i]->aCounts[0] == aState->aCounts[0]) if(afsObjectsEqual(S->states[i],aState)) return(1); } return(0); } /////// Below is not needed with hash implementation //afsStateSpaceContainsStateTmpStorage-- same as above but works off of stateSpace->tmpStorage // int afsStateSpaceContainsStateTmpStorage(afsStateSpace *S, afsObject *aState){ // int i; // for(i = S->nstateArray[aState->nalleles][aState->aCounts[0]] -1 ; i > - 1;i--){ // if(afsObjectsEqual(S->tmpStorage[aState->nalleles][aState->aCounts[0]][i],aState)) // return(1); // } // return(0); // } //afsStateSpaceRemoveAbsorbing-- removes all absorbing states void afsStateSpaceRemoveAbsorbing(afsStateSpace *S){ int i,ii; afsObject *tmp; i = 0; while(i < S->nstates){ if(S->states[i]->nalleles == 1){ tmp = S->states[i]; for(ii=i;ii<S->nstates - 1;ii++) S->states[ii] = S->states[ii+1]; S->nstates--; i-=1; afsObjectFree(tmp); } i+=1; } } //afsStateSpaceMapPopn-- returns a vector mapping each state to its state if popn1 collapsed into popn0 void afsStateSpaceMapPopn(afsStateSpace *S, int *map){ int i, j,valCount,valInd[S->nstates / 2]; afsObject *tmp, *test; tmp = afsObjectNewFrom(S->states[0]); gsl_matrix_int_set_zero(tmp->popMats[1]); //find and count valid states valCount = 0; for(i=0;i<S->nstates;i++){ if(S->states[i]->aCounts[1]==0){ valInd[valCount]=i; valCount++; } } for(i=0;i<S->nstates;i++){ if(S->states[i]->aCounts[1]==0){ map[i]=i; } else{ //create folded state in tmp gsl_matrix_int_memcpy(tmp->popMats[0],S->states[i]->popMats[0]); gsl_matrix_int_add(tmp->popMats[0],S->states[i]->popMats[1]); //go through valid ones to find it for(j=0;j<valCount;j++){ test= S->states[valInd[j]]; if(S->states[i]->nalleles == test->nalleles) if(gsl_matrix_int_equal(tmp->popMats[0],test->popMats[0])) map[i]=valInd[j]; } } } } //afsStateSpaceMapAndReducePopn-- returns a vector mapping each state to its state if popn1 collapsed into popn0 (map) //adds valid states to new reducedSpace, also fills reverseMap to larger space indexing //reducedSpace is passed as ptr, assumed to be empty, initial stateSpace void afsStateSpaceMapAndReducePopn(afsStateSpace *S, int *map, afsStateSpace *reducedSpace, int *reverseMap){ int i, j,valCount,valInd[S->nstates / 2]; afsObject *tmp, *test; tmp = afsObjectNewFrom(S->states[0]); gsl_matrix_int_set_zero(tmp->popMats[1]); //find and count valid states valCount = 0; for(i=0;i<S->nstates;i++){ if(S->states[i]->aCounts[1]==0){ valInd[valCount]=i; reverseMap[valCount]=i; reducedSpace->states[valCount]=S->states[i]; reducedSpace->nstates++; valCount++; } } for(i=0;i<S->nstates;i++){ if(S->states[i]->aCounts[1]==0){ map[i]=i; } else{ //create folded state in tmp gsl_matrix_int_memcpy(tmp->popMats[0],S->states[i]->popMats[0]); gsl_matrix_int_add(tmp->popMats[0],S->states[i]->popMats[1]); //go through valid ones to find it for(j=0;j<valCount;j++){ test= S->states[valInd[j]]; if(S->states[i]->nalleles == test->nalleles) if(gsl_matrix_int_equal(tmp->popMats[0],test->popMats[0])) map[i]=valInd[j]; } } } afsObjectFree(tmp); } //afsStateSpaceRemovePopulation-- removes all states with members in specified popn void afsStateSpaceRemovePopulation(afsStateSpace *S, int popn){ int i,ii; afsObject *tmp; i = 0; while(i < S->nstates){ if(S->states[i]->aCounts[1] > 0){ tmp = S->states[i]; for(ii=i;ii<S->nstates - 1;ii++) S->states[ii] = S->states[ii+1]; S->nstates--; i-=1; afsObjectFree(tmp); } i+=1; } } afsStateSpace *afsStateSpaceImportFromFile(const char *fileName){ int m1,m2,ns; int i,j,l,c; char *tmp; FILE *infile; afsStateSpace *newStateSpace; // afsObject *newObj; int linebuf = 10000; char line[linebuf+1],*token, search[]=" "; //open file infile = fopen(fileName, "r"); if (infile == NULL){ fprintf(stderr,"Error opening infile! ARRRRR!!!!\n"); exit(1); } //initialization //define state space size and shape c=fscanf(infile,"n1: %d n2: %d nstates: %d", &m1, &m2, &ns); newStateSpace = afsStateSpaceNew(); newStateSpace->nstates = ns; tmp=fgets(line,linebuf,infile); if (tmp == NULL || c == 0){ fprintf(stderr,"Error peaking in infile!\n"); exit(1); } for(l=0;l<ns;l++){ newStateSpace->states[l] = afsObjectNew(m1,m2); for(i=0;i<m1+1;i++){ tmp=fgets(line,linebuf,infile); // printf("%s\n",line); // printf("----\n"); token = strtok(line,search); gsl_matrix_int_set(newStateSpace->states[l]->popMats[0],i,0,atoi(token)); for(j=1;j<m2+1;j++){ token = strtok(NULL,search); // printf("%s\n",token); gsl_matrix_int_set(newStateSpace->states[l]->popMats[0],i,j,atoi(token)); } token = strtok(NULL,search); for(j=0;j<m2+1;j++){ token = strtok(NULL,search); gsl_matrix_int_set(newStateSpace->states[l]->popMats[1],i,j,atoi(token)); } } tmp=fgets(line,linebuf,infile); newStateSpace->states[l]->aCounts[0] = matrixSum(newStateSpace->states[l]->popMats[0]); newStateSpace->states[l]->aCounts[1] = matrixSum(newStateSpace->states[l]->popMats[1]); newStateSpace->states[l]->nalleles = afsObjectCount(newStateSpace->states[l]); // afsObjectPrint(newStateSpace->states[l]); // printf("+++++\n"); } fclose(infile); return(newStateSpace); } //mcMatsImportFromFile -- reads in the Topology and MoveType matrices output by cmc_printMCMats program // this function only fills preallocated arrays and sets nnz void mcMatsImportFromFile(const char *fileName,int *nnz,double *topol, int *moveA, int *dim1, int *dim2){ int i,c; FILE *infile; //open file infile = fopen(fileName, "r"); if (infile == NULL){ fprintf(stderr,"Error opening infile! ARRRRR!!!!\n"); exit(1); } //initialization c=fscanf(infile,"nnz: %d", nnz); for(i=0;i<*nnz;i++){ c=fscanf(infile,"%lf\t%d\t%d\t%d\n",&topol[i],&moveA[i],&dim1[i],&dim2[i]); } fclose(infile); } //acceptOrRejectProposedState-- tests if candidate state in valid and not yet represented // in the afsStateSpace object. Adds to array if true and iterates nstates. Free's candidate if // false void acceptOrRejectProposedState(afsStateSpace *S, afsObject *child, int n1, int n2){ int i,j; char c[10]; child->nalleles=afsObjectCount(child); child->aCounts[0]=matrixSum(child->popMats[0]); child->aCounts[1]=matrixSum(child->popMats[1]); for(i=0;i <= n1;i++){ for(j=0;j <= n2;j++){ itoa(gsl_matrix_int_get(child->popMats[0],i,j),c); strcat(child->matString, c); itoa(gsl_matrix_int_get(child->popMats[1],i,j),c); strcat(child->matString, c); } } // printf("%s\n",child->matString); //Below block is the old way. new way is hash implementation // if(compatibleAfsGivenInitial(child, n1,n2) == 1 // && afsStateSpaceContainsStateTmpStorage(S,child) == 0){ // //add in new state // // S->states[S->nstates]=child; // S->nstates++; // S->tmpStorage[child->nalleles][child->aCounts[0]][S->nstateArray[child->nalleles][child->aCounts[0]]] = child; // S->nstateArray[child->nalleles][child->aCounts[0]]++; //check to make sure state array can keep up! // if(S->nstates==MAXSTATES){ // MAXSTATES = 2*MAXSTATES; // S->states = realloc(S->states, MAXSTATES * sizeof(child)); // } if(g_hash_table_lookup(S->stateHash, child->matString) == NULL && compatibleAfsGivenInitial(child, n1,n2) == 1){ //add in new state S->states[S->nstates]=child; S->nstates++; g_hash_table_insert(S->stateHash, child->matString, "TRUE"); //recurse! preorderEvolveState(S, child, n1,n2); } else{ afsObjectFree(child); } } //preorderEvolveState -- this is the workhorse that fills the entire state space // currently this only handles coalescent and migration events for 2 populations void preorderEvolveState(afsStateSpace *S, afsObject *aState, int n1, int n2){ int i,j, nlin1,nlin2, tmp1, tmp2; int **activePos1, **activePos2; //first dimension here relates to 2 popns afsObject *child; activePos1 = malloc(100*sizeof(int *)); activePos2 = malloc(100*sizeof(int *)); for(i=0;i<100;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } nonZeroEntries(aState->popMats[0], activePos1, &nlin1); nonZeroEntries(aState->popMats[1], activePos2, &nlin2); //coalescent in Popn 1? if(matrixSum(aState->popMats[0]) > 1){ //coalescent is possible; permutations of lineages for(i=0;i<nlin1;i++){ for(j=0;j<nlin1;j++){ if( i != j || gsl_matrix_int_get(aState->popMats[0],activePos1[i][0],activePos1[i][1]) > 1){ child = afsObjectNewFrom(aState); //get and set below is ugly... basically subtract one from each of coal lineages add one //to new lineage gsl_matrix_int_set(child->popMats[0],activePos1[i][0], activePos1[i][1], gsl_matrix_int_get(child->popMats[0], activePos1[i][0],activePos1[i][1]) - 1); gsl_matrix_int_set(child->popMats[0],activePos1[j][0], activePos1[j][1], gsl_matrix_int_get(child->popMats[0], activePos1[j][0],activePos1[j][1]) - 1); tmp1 = activePos1[i][0] + activePos1[j][0]; tmp2 = activePos1[i][1] + activePos1[j][1]; gsl_matrix_int_set(child->popMats[0],tmp1, tmp2, gsl_matrix_int_get(child->popMats[0], tmp1,tmp2) + 1); //now check state for compatibilty acceptOrRejectProposedState(S,child, n1, n2); } } } } //coalescent in Popn 2? if(matrixSum(aState->popMats[1]) > 1){ //coalescent is possible; permutations of lineages for(i=0;i<nlin1;i++){ for(j=0;j<nlin1;j++){ if( i != j || gsl_matrix_int_get(aState->popMats[1],activePos2[i][0],activePos2[i][1]) > 1){ child = afsObjectNewFrom(aState); //get and set below is ugly... basically subtract one from each of coal lineages add one //to new lineage gsl_matrix_int_set(child->popMats[1],activePos2[i][0], activePos2[i][1], gsl_matrix_int_get(child->popMats[1], activePos2[i][0],activePos2[i][1]) - 1); gsl_matrix_int_set(child->popMats[1],activePos2[j][0], activePos2[j][1], gsl_matrix_int_get(child->popMats[1], activePos2[j][0],activePos2[j][1]) - 1); tmp1 = activePos2[i][0] + activePos2[j][0]; tmp2 = activePos2[i][1] + activePos2[j][1]; gsl_matrix_int_set(child->popMats[0],tmp1, tmp2, gsl_matrix_int_get(child->popMats[0], tmp1,tmp2) + 1); //now check state for compatibilty acceptOrRejectProposedState(S,child, n1, n2); } } } } //migration from Pop1 to Popn 2 for(i=0;i<nlin1;i++){ child = afsObjectNewFrom(aState); gsl_matrix_int_set(child->popMats[0],activePos1[i][0], activePos1[i][1], gsl_matrix_int_get(child->popMats[0], activePos1[i][0],activePos1[i][1]) - 1); gsl_matrix_int_set(child->popMats[1],activePos1[i][0], activePos1[i][1], gsl_matrix_int_get(child->popMats[1], activePos1[i][0],activePos1[i][1]) + 1); //now check state for compatibilty //now check state for compatibilty acceptOrRejectProposedState(S,child, n1, n2); } //migration from Pop2 to Popn 1 for(i=0;i<nlin2;i++){ child = afsObjectNewFrom(aState); gsl_matrix_int_set(child->popMats[1],activePos2[i][0], activePos2[i][1], gsl_matrix_int_get(child->popMats[1], activePos2[i][0],activePos2[i][1]) - 1); gsl_matrix_int_set(child->popMats[0],activePos2[i][0], activePos2[i][1], gsl_matrix_int_get(child->popMats[0], activePos2[i][0],activePos2[i][1]) + 1); //now check state for compatibilty //now check state for compatibilty acceptOrRejectProposedState(S,child, n1, n2); } //cleanup and free for(i=0;i<100;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); } /////coalMarkovChainTopologyMatrix -- using a previously calculated state space //this fills a matrix of topological moves possible in the markov chain, //along with a lookup table of moves that are parameter dependant // // codes for lookup :: // -1 : absorb // 0 : coal popn0 // 1 : coal popn1 // 2 : mig popn0 // 3 : mig popn2 // 666: incompatible move void coalMarkovChainTopologyMatrix(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int n1, int n2){ int i,j,k,steps,x,y; double top,bottom; afsObject *delta; int **activePos1, **activePos2; //first dimension here relates to 2 popns int nlin1,nlin2,compat; if(S->nstates != topol->size1 || S->nstates != moveType->size1){ fprintf(stderr,"Error: StateSpace and matrices are not of equal size\n"); exit(1); } //arrays for finding positions of entries activePos1 = malloc(100*sizeof(int *)); activePos2 = malloc(100*sizeof(int *)); for(i=0;i<100;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } for(i=0;i<S->nstates;i++){ for(j=0;j<S->nstates;j++){ gsl_matrix_int_set(moveType,i,j,666); //is ith state root state? if(S->states[i]->nalleles == 1){ //set correct absorbing conditions if(i==j){ gsl_matrix_set(topol,i,j,1.0); gsl_matrix_int_set(moveType,i,j,-1); } else{ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,-1); } } else{ //ith not root; what is the move? delta = afsObjectDelta(S->states[i],S->states[j]); steps = S->states[i]->nalleles - S->states[j]->nalleles ; // printf("i:%d j:%d steps:%d\n",i,j,steps); switch(steps){ case 0: // 0 "steps", so no changes in nalleles between two //check counts and positions if(abs(matrixSum(delta->popMats[0])) == 1){ nonZeroEntries(delta->popMats[0], activePos1, &nlin1); nonZeroEntries(delta->popMats[1], activePos2, &nlin2); //exit(1); //migration? if(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] && (gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)) { //migration popn1? if(matrixSum(delta->popMats[0]) == 1){ gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[0], activePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]); gsl_matrix_int_set(moveType,i,j,2); } else{ //migration popn2 // printf("here %d %d %d\n",activePos2[0][0],activePos2[0][1], S->states[i]->aCounts[1]); gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[1], activePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]); gsl_matrix_int_set(moveType,i,j,3); } } } break; case 1://coalescent? //coal popn1? if(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 /*((matrixAllGTZ(delta->popMats[0]) || matrixAllGTZ(delta->popMats[1]))) */ ){ // afsObjectPrint(S->states[i]); // printf("1///////////\n"); // afsObjectPrint(S->states[j]); // printf("2///////////\n"); entriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= (float) xchoosey(gsl_matrix_int_get(S->states[i]->popMats[0],x,y), gsl_matrix_int_get(delta->popMats[0],x,y)); // printf("x: %d y: %d bottom: %0.2f top:%0.2f aCounts[0]: %d delta: %d foo:%d choose: %lf\n",x,y,bottom,top,S->states[i]->aCounts[0],gsl_matrix_int_get(delta->popMats[0],x,y),gsl_matrix_int_get(S->states[i]->popMats[0],x,y),xchoosey(3,2)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,0); } } } else{ if(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 /*((matrixAllGTZ(delta->popMats[0]) || matrixAllGTZ(delta->popMats[1]))) */ ){ // afsObjectPrint(S->states[i]); // printf("1///////////\n"); // afsObjectPrint(S->states[j]); // printf("2///////////\n"); entriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= xchoosey(gsl_matrix_int_get(S->states[i]->popMats[1],x,y), gsl_matrix_int_get(delta->popMats[1],x,y)); // top *= gsl_matrix_int_get(S->states[i]->popMats[1],x,y); // printf("x: %d y: %d bottom: %0.2f top:%0.2f aCounts[1]: %d delta: %d\n",x,y,bottom,top,S->states[i]->aCounts[1],gsl_matrix_int_get(delta->popMats[1],x,y)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,1); } } } } break; } afsObjectFree(delta); } } } //cleanup and free for(i=0;i<100;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); } //fills and transition matrix along with a vector of rates for use with calculating expected times void fillTransitionMatrix(afsStateSpace *S, gsl_matrix *topol, gsl_matrix_int *moveType, gsl_matrix *transMat, gsl_vector *rates, double theta1, double theta2, double mig1, double mig2){ int i, j; double c0r,c1r,m0r,m1r,totR; gsl_matrix_set_zero(transMat); for(i=0;i<topol->size1;i++){ c0r = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ; c1r = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2; m0r = S->states[i]->aCounts[0] * mig1 ; m1r = S->states[i]->aCounts[1] * mig2 ; totR = c0r + c1r + m0r + m1r; if(S->states[i]->nalleles > 1 && c0r >= 0 && c1r >= 0) gsl_vector_set(rates,i,1.0/totR); else gsl_vector_set(rates,i,0); for(j=0;j<topol->size2;j++){ switch(gsl_matrix_int_get(moveType,i,j)){ // case 666: // gsl_matrix_set(transMat,i,j,0); break; case 0: //coal pop0 gsl_matrix_set(transMat,i,j,c0r / totR * gsl_matrix_get(topol,i,j)); break; case 1: //coal pop1 gsl_matrix_set(transMat,i,j,c1r / totR * gsl_matrix_get(topol,i,j)); break; case 2: //mig pop0 gsl_matrix_set(transMat,i,j,m0r / totR * gsl_matrix_get(topol,i,j)); break; case 3: //mig pop1 gsl_matrix_set(transMat,i,j,m1r / totR * gsl_matrix_get(topol,i,j)); // printf("case3 -- tot:%f c0r: %f c1r: %f m0r: %f m1r: %f res:%f\n", // totR,c0r,c1r,m0r,m1r,gsl_matrix_get(transMat,i,j)); break; case -1: //absorb state gsl_matrix_set(transMat,i,j, gsl_matrix_get(topol,i,j)); break; } } } } //fills up an AFS matrix using expected times void fillExpectedAFS(afsStateSpace *S, gsl_matrix *transMat,gsl_vector *rates, gsl_matrix *expAFS, int m1, int m2){ int i, j, k, l, its, count; gsl_matrix *tmIt, *tmp, *times; gsl_vector *means; double tmpRes,max = 0.0; its = 30; //set up matrices make copy of transMat tmIt = gsl_matrix_alloc(transMat->size1,transMat->size2); tmp = gsl_matrix_alloc(transMat->size1,transMat->size2); times = gsl_matrix_alloc(transMat->size1, its); means = gsl_vector_alloc(its); gsl_matrix_set_zero(times); gsl_matrix_set_zero(expAFS); //initial state contribution to AFS; ie transMat^0 gsl_matrix_set_identity(tmIt); for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } tmpRes = 0; for(k=0;k<S->nstates;k++) tmpRes += (gsl_vector_get(rates,k) * gsl_matrix_get(tmIt,k,j)); gsl_matrix_set(times,j,0,tmpRes); } //now add transMat ^1 gsl_matrix_memcpy(tmIt,transMat); for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } tmpRes = 0; for(k=0;k<S->nstates;k++) tmpRes += ((gsl_vector_get(rates,k) + gsl_matrix_get(times,k,0)) * gsl_matrix_get(tmIt,k,j)); gsl_matrix_set(times,j,1,tmpRes ); } //now do matrix powers i = 2; while(i<its && max < 0.99){ // printf("power: %d\n",i); // gsl_matrix_prettyPrint(tmIt); //compute matrix product gsl_matrix_set_zero(tmp); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,tmIt,transMat,0.0,tmp); gsl_matrix_memcpy(tmIt,tmp); for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } // for(k=0;k<S->nstates;k++) // tmpRes += ((gsl_vector_get(rates,k) + gsl_matrix_get(times,k,i-1)) * gsl_matrix_get(tmIt,k,j)) ; // gsl_matrix_set(times,j,i,tmpRes); } //printf("computed transition matrix power %d....\n",i); max = gsl_matrix_row_max(tmIt,0); i++; } // gsl_matrix_prettyPrint(times); for(i=0;i<its;i++){ tmpRes = 0.0; for(j=0;j<S->nstates;j++){ tmpRes += gsl_matrix_get(times,j,i); } gsl_vector_set(means,i,tmpRes / (double) S->nstates); } // gsl_vector_fprintf(stdout,means,"%f"); // gsl_matrix_prettyPrint(expAFS); tmpRes = matrixSumDouble(expAFS); gsl_matrix_scale(expAFS, 1.0 / tmpRes); gsl_matrix_free(tmp); gsl_matrix_free(tmIt); gsl_matrix_free(times); gsl_vector_free(means); } //fills up an AFS matrix using expected times and a precalculated visitMat void fillExpectedAFS_visits(afsStateSpace *S, gsl_matrix *visitMat,gsl_vector *rates, gsl_matrix *expAFS){ int j, k, l, m1, m2, count; double tmpRes; m1=expAFS->size1; m2=expAFS->size2; gsl_matrix_set_zero(expAFS); for(j=0;j<S->nstates;j++){ for(k=0;k<m1;k++){ for(l=0;l<m2;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(visitMat,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } } tmpRes = matrixSumDouble(expAFS); gsl_matrix_scale(expAFS, 1.0 / tmpRes); } /////coalMarkovChainTopologyMatrix_2 -- using a previously calculated state space //this fills a matrix of topological moves possible in the markov chain, //along with a lookup table of moves that are parameter dependant // also returns list of nonzero entries and the numbers of such entries // // codes for lookup :: // -1 : absorb // 0 : coal popn0 // 1 : coal popn1 // 2 : mig popn0 // 3 : mig popn2 // 666: incompatible move int coalMarkovChainTopologyMatrix_2(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2){ int i,j,k,steps,x,y; double top,bottom; afsObject *delta; int **activePos1, **activePos2; //first dimension here relates to 2 popns int nlin1,nlin2,compat; int nonZeroCount = 0; nlin1 = nlin2 = 0; if(S->nstates != topol->size1 || S->nstates != moveType->size1){ fprintf(stderr,"Error: StateSpace and matrices are not of equal size\n"); exit(1); } //arrays for finding positions of entries activePos1 = malloc(200*sizeof(int *)); activePos2 = malloc(200*sizeof(int *)); for(i=0;i<200;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } // printf("\033[2J"); /* clear the screen */ // printf("\033[H"); /* position cursor at top-left corner */ for(i=0;i<S->nstates;i++){ for(j=0;j<S->nstates;j++){ // printf("%.4f percent done with constructing initial transition matrix...\n",(float)tCount++ / (float)tot); // sleep(0.001); // printf("\033[H"); gsl_matrix_int_set(moveType,i,j,666); //is ith state root state? if(S->states[i]->nalleles == 1){ //set correct absorbing conditions if(i==j){ gsl_matrix_set(topol,i,j,1.0); gsl_matrix_int_set(moveType,i,j,-1); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,-1); } } else{ //ith not root; what is the move? steps = S->states[i]->nalleles - S->states[j]->nalleles ; if(steps < 2){ delta = afsObjectDelta(S->states[i],S->states[j]); switch(steps){ case 0: // 0 "steps", so no changes in nalleles between two //check counts and positions if(abs(matrixSum(delta->popMats[0])) == 1){ nonZeroEntries(delta->popMats[0], activePos1, &nlin1); nonZeroEntries(delta->popMats[1], activePos2, &nlin2); //migration? if(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] && (gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)) { //migration popn1? if(matrixSum(delta->popMats[0]) == 1){ gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[0], activePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]); gsl_matrix_int_set(moveType,i,j,2); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ //migration popn2 gsl_matrix_set(topol,i,j, (double) gsl_matrix_int_get(S->states[i]->popMats[1], activePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]); gsl_matrix_int_set(moveType,i,j,3); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } break; case 1://coalescent? //coal popn1? if(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){ entriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= (float) xchoosey(gsl_matrix_int_get(S->states[i]->popMats[0],x,y), gsl_matrix_int_get(delta->popMats[0],x,y)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,0); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } else{ if(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){ entriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat != 1){ gsl_matrix_set(topol,i,j,0.0); gsl_matrix_int_set(moveType,i,j,666); } else{ top = 1.0; bottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= xchoosey(gsl_matrix_int_get(S->states[i]->popMats[1],x,y), gsl_matrix_int_get(delta->popMats[1],x,y)); } gsl_matrix_set(topol,i,j,top/bottom); gsl_matrix_int_set(moveType,i,j,1); dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } } break; } afsObjectFree(delta); } } } } //cleanup and free for(i=0;i<200;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); return(nonZeroCount); } /////coalMarkovChainTopologyMatrix_sparse -- using a previously calculated state space //fills requirements for triplet style sparse matrix for the instantaneous rate matrix // in the markov chain along with a lookup table of moves that are parameter dependant // also returns list of nonzero entries and the numbers of such entries //this fills a matrix of topological moves possible in the markov chain, // codes for lookup :: // -1 : absorb // 0 : coal popn0 // 1 : coal popn1 // 2 : mig popn0 // 3 : mig popn2 // 666: incompatible move int coalMarkovChainTopologyMatrix_sparse(afsStateSpace *S,double *topol, int *moveType, int *dim1, int *dim2){ int i,j,k,steps,x,y; double top,bottom; afsObject *delta; int **activePos1, **activePos2; //first dimension here relates to 2 popns int nlin1,nlin2,compat; int nonZeroCount; nlin1 = nlin2 = 0; //arrays for finding positions of entries activePos1 = malloc(200*sizeof(int *)); activePos2 = malloc(200*sizeof(int *)); for(i=0;i<200;i++){ activePos1[i] = malloc(2*sizeof(int)); activePos1[i][0] = activePos1[i][1] = 0; activePos2[i] = malloc(2*sizeof(int)); activePos2[i][0] = activePos2[i][1] = 0; } nonZeroCount = 0; // printf("\033[2J"); /* clear the screen */ // printf("\033[H"); /* position cursor at top-left corner */ for(i=0;i<S->nstates;i++){ for(j=0;j<S->nstates;j++){ // printf("%.4f percent done with constructing initial transition matrix...\n",(float)tCount++ / (float)tot); // sleep(0.001); // printf("\033[H"); //is ith state root state? if(S->states[i]->nalleles == 1){ //set correct absorbing conditions if(i==j){ topol[nonZeroCount] = 1.0; moveType[nonZeroCount] = -1; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } else{ //ith not root; what is the move? steps = S->states[i]->nalleles - S->states[j]->nalleles ; if(steps < 2){ delta = afsObjectDelta(S->states[i],S->states[j]); switch(steps){ case 0: // 0 "steps", so no changes in nalleles between two //check counts and positions if(abs(matrixSum(delta->popMats[0])) == 1){ nonZeroEntries(delta->popMats[0], activePos1, &nlin1); nonZeroEntries(delta->popMats[1], activePos2, &nlin2); //migration? if(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] && (gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)) { //migration popn1? if(matrixSum(delta->popMats[0]) == 1){ topol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[0], activePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]; moveType[nonZeroCount] = 2; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } else{ //migration popn2 topol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[1], activePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]; moveType[nonZeroCount] = 3; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } break; case 1://coalescent? //coal popn1? if(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){ entriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat == 1){ top = 1.0; bottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= (float) xchoosey(gsl_matrix_int_get(S->states[i]->popMats[0],x,y), gsl_matrix_int_get(delta->popMats[0],x,y)); } topol[nonZeroCount] = top/bottom; moveType[nonZeroCount] = 0; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } else{ if(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){ entriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages entriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages if(nlin2 != 0 && nlin2 < 2){ compat=0; if(nlin1 == 1){ if(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1]) compat = 1; } if(nlin1==2){ if(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] && activePos1[0][1] + activePos1[1][1] == activePos2[0][1]) compat = 1; } if(compat == 1){ top = 1.0; bottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ; for(k=0;k<nlin1;k++){ x = activePos1[k][0]; y = activePos1[k][1]; top *= xchoosey(gsl_matrix_int_get(S->states[i]->popMats[1],x,y), gsl_matrix_int_get(delta->popMats[1],x,y)); } topol[nonZeroCount] = top/bottom; moveType[nonZeroCount] = 1; dim1[nonZeroCount] = i; dim2[nonZeroCount] = j; nonZeroCount += 1; } } } } break; } afsObjectFree(delta); } } } } //cleanup and free for(i=0;i<200;i++){ free(activePos1[i]); free(activePos2[i]); } free(activePos1); free(activePos2); return(nonZeroCount); } //readTopolFile-- this function allocs sparse matrix representation of topology and movetype matrices // and then fills them from reading from a file. void readTopolFile(const char *fileName, double *topA, int *moveA, int *dim1, int *dim2){ int i, nnz,c; double tmp1; int tmp2,tmp3,tmp4; FILE *infile; //open file infile = fopen(fileName, "r"); if (infile == NULL){ fprintf(stderr,"Error opening infile! ARRRRR!!!!\n"); exit(1); } //initialization c=fscanf(infile,"nnz: %d", &nnz); topA = malloc(sizeof(double)*nnz); moveA = malloc(sizeof(int)*nnz); dim1 = malloc(sizeof(int)*nnz); dim2 = malloc(sizeof(int)*nnz); for(i=0;i<nnz;i++){ c=fscanf(infile,"%lf\t%d\t%d\t%d", &tmp1, &tmp2, &tmp3,&tmp4); topA[i] = tmp1; moveA[i]=tmp2; dim1[i]=tmp3; dim2[i]=tmp4; } } //fills a sparse transition matrix along with a vector of rates for use with calculating expected times struct cs_di_sparse *fillTransitionMatrix_2(afsStateSpace *S, gsl_matrix *topol, gsl_matrix_int *moveType, gsl_vector *rates, int nzCount, int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2){ int i, j,k; int N = topol->size1; double c0r[N],c1r[N],m0r[N],m1r[N],totR[N]; struct cs_di_sparse *triplet, *tmat; //now allocate new cs_sparse obj triplet = cs_spalloc(topol->size1, topol->size2, nzCount + topol->size2, 1, 1); //alloc sparse mat with extra space for nonzero identity mats for(i=0;i<N;i++){ c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ; c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2; m0r[i] = S->states[i]->aCounts[0] * mig1 ; m1r[i] = S->states[i]->aCounts[1] * mig2 ; totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i]; if(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0) gsl_vector_set(rates,i,1.0/totR[i]); else gsl_vector_set(rates,i,0); } for(k=0;k<nzCount;k++){ i = dim1[k]; j= dim2[k]; switch(gsl_matrix_int_get(moveType,i,j)){ case 0: //coal pop0 cs_entry(triplet,i,j,c0r[i] / totR[i] * gsl_matrix_get(topol,i,j)); break; case 1: //coal pop1 cs_entry(triplet,i,j,c1r[i] / totR[i] * gsl_matrix_get(topol,i,j)); break; case 2: //mig pop0 cs_entry(triplet,i,j,m0r[i] / totR[i] * gsl_matrix_get(topol,i,j)); break; case 3: //mig pop1 cs_entry(triplet,i,j,m1r[i] / totR[i] * gsl_matrix_get(topol,i,j)); break; } } tmat = cs_compress(triplet); cs_spfree(triplet); return(tmat); } //fills up an AFS matrix using expected times and a precalculated visitMat void fillExpectedAFS_visits_2(afsStateSpace *S, double *visitMat ,gsl_vector *rates, gsl_matrix *expAFS){ int j, k, l, m1, m2, count; double tmpRes; m1=expAFS->size1; m2=expAFS->size2; gsl_matrix_set_zero(expAFS); for(j=0;j<S->nstates;j++){ for(k=0;k<m1;k++){ for(l=0;l<m2;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * visitMat[j]); // printf("tmpRes[%d][%d]: %f rates[j]: %f visits[j]: %f count: %d\n",tmpRes,k,l,gsl_vector_get(rates,j),visitMat[j],count); gsl_matrix_set(expAFS,k,l, tmpRes); } } } tmpRes = matrixSumDouble(expAFS); gsl_matrix_scale(expAFS, 1.0 / tmpRes); } /////////////////// Likelihood stuff //fillLogAFS_ptr -- wrapper around above that uses the island_like_param struct to hold all revelant info void fillLogAFS_ptr(void * p){ // struct island_lik_params * params = (struct island_lik_params *) p; // int i,j; // // //initialize some vectors // gsl_vector_set_zero(params->rates); // //fill transMat // fillTransitionMatrix(params->stateSpace, params->topol, // params->moveType,params->transMat,params->rates, // gsl_vector_get(params->paramVector,0), gsl_vector_get(params->paramVector,1), // gsl_vector_get(params->paramVector,2), gsl_vector_get(params->paramVector,3)); // gsl_matrix_set_identity(params->visitMat); // gsl_matrix_sub(params->visitMat, params->transMat); // gsl_matrix_invert_lapack(params->visitMat); // fillExpectedAFS_visits(params->stateSpace, params->visitMat,params->rates, params->expAFS); // // fillExpectedAFS(params->stateSpace, params->transMat, params->rates, // // params->expAFS, params->n1, params->n2); // // gsl_matrix_prettyPrint(params->expAFS); // // for(i=0;i<params->expAFS->size1;i++){ // for(j=0;j<params->expAFS->size2;j++){ // gsl_matrix_set(params->expAFS,i,j,log(gsl_matrix_get(params->expAFS,i,j))); // } // } // gsl_matrix_prettyPrint(params->expAFS); } //fillLogAFS_ptr_sp -- uses cxsparse library for inversion void fillLogAFS_ptr_sp(void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int i,j,nz; struct cs_di_sparse *spMat, *mt; //initialize some vectors gsl_vector_set_zero(params->rates); //fill transMat fillTransitionMatrix(params->stateSpace, params->topol, params->moveType,params->transMat,params->rates, gsl_vector_get(params->paramVector,0), gsl_vector_get(params->paramVector,1), gsl_vector_get(params->paramVector,2), gsl_vector_get(params->paramVector,3)); gsl_matrix_set_identity(params->visitMat); gsl_matrix_sub(params->visitMat, params->transMat); nz=0; for(i=0;i<params->visitMat->size1;i++){ for(j=0;j<params->visitMat->size2;j++){ nz += (gsl_matrix_get(params->visitMat,i,j) == 0.0) ? 0 : 1; } } //create unit array for solve (params->cs_work)[0] = 1; for(i=1; i<params->visitMat->size1; i++) (params->cs_work)[i] = 0; spMat = gslMatrixToCSsparse(params->visitMat,nz); mt = cs_transpose(spMat,1); cs_lusol(0, mt, params->cs_work, 1e-12); fillExpectedAFS_visits_2(params->stateSpace, params->cs_work,params->rates, params->expAFS); for(i=0;i<params->expAFS->size1;i++){ for(j=0;j<params->expAFS->size2;j++){ gsl_matrix_set(params->expAFS,i,j,log(gsl_matrix_get(params->expAFS,i,j))); } } cs_spfree(spMat); cs_spfree(mt); } //fillLogAFS_ptr_sp2 -- uses cxsparse library for inversion -- will replace above void fillLogAFS_ptr_sp2(void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int i,j, N = params->stateSpace->nstates; cs *spMat, *mt, *ident, *eye, *tmpMat; //initialize some vectors gsl_vector_set_zero(params->rates); //fill transMat tmpMat = fillTransitionMatrix_2(params->stateSpace, params->topol, params->moveType,params->rates,params->nzCount, params->dim1, params->dim2, 1.0, gsl_vector_get(params->paramVector,0), gsl_vector_get(params->paramVector,1), gsl_vector_get(params->paramVector,2)); //add negative ident ident = cs_spalloc(N,N,N,1,1); for(i=0;i<N;i++) cs_entry(ident,i,i,1); eye = cs_compress(ident); spMat = cs_add(eye,tmpMat,1.0,-1.0); mt = cs_transpose(spMat,1); //cs_print(mt,0); //create unit array for solve (params->cs_work)[0] = 1; for(i=1; i<params->visitMat->size1; i++) (params->cs_work)[i] = 0; cs_dropzeros(mt); cs_lusol(0, mt, params->cs_work, 1e-12); fillExpectedAFS_visits_2(params->stateSpace, params->cs_work,params->rates, params->expAFS); for(i=0;i<params->expAFS->size1;i++){ for(j=0;j<params->expAFS->size2;j++){ gsl_matrix_set(params->expAFS,i,j,log(gsl_matrix_get(params->expAFS,i,j))); } } cs_spfree(spMat); cs_spfree(mt); cs_spfree(ident); cs_spfree(eye); // cs_spfree(cMat); cs_spfree(tmpMat); } void fillLogAFS_ptr_sp_hmm(int state,void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int i,j, N = params->stateSpace->nstates; int migInd = (params->nstates + 1) + (2 * state); cs *spMat, *mt, *ident, *eye; struct cs_di_sparse *tmpMat; //initialize some vectors gsl_vector_set_zero(params->rates); //fill transMat // printf("params: %f %f %f\n", gsl_vector_get(params->paramVector,0), gsl_vector_get(params->paramVector,migInd), gsl_vector_get(params->paramVector,migInd+1)); tmpMat = fillTransitionMatrix_2(params->stateSpace, params->topol, params->moveType,params->rates,params->nzCount, params->dim1, params->dim2, 1.0, gsl_vector_get(params->paramVector,0), gsl_vector_get(params->paramVector,migInd), gsl_vector_get(params->paramVector,migInd+1)); //find right lookuyp //add negative ident ident = cs_spalloc(N,N,N,1,1); for(i=0;i<N;i++) cs_entry(ident,i,i,1); eye = cs_compress(ident); spMat = cs_add(eye,tmpMat,1.0,-1.0); mt = cs_transpose(spMat,1); //create unit array for solve (params->cs_work)[0] = 1; for(i=1; i<params->visitMat->size1; i++) (params->cs_work)[i] = 0; cs_dropzeros(mt); cs_lusol(0, mt, params->cs_work, 1e-12); fillExpectedAFS_visits_2(params->stateSpace, params->cs_work,params->rates, params->expAFS); for(i=0;i<params->expAFS->size1;i++){ for(j=0;j<params->expAFS->size2;j++){ gsl_matrix_set(params->expAFS,i,j,log(gsl_matrix_get(params->expAFS,i,j))); } } cs_spfree(spMat); cs_spfree(mt); cs_spfree(ident); cs_spfree(eye); cs_spfree(tmpMat); } //likelihood function for HKA given the data; with constraints // used with multimin minimizer void island_lik_constraint(size_t n, const double *pGuess, void * p, double *result){ struct island_lik_params * params = (struct island_lik_params *) p; double lik; int i,j; for(i=0;i<n;i++){ gsl_vector_set(params->paramVector,i,pGuess[i]); // printf("params[%d]: %f\n",i,gsl_vector_get(params->paramVector,i)); } lik = 0.0; for(j=0;j < params->nstates;j++){ //calc log probs fillLogAFS_ptr_sp2(p); for(i = 0; i < params->snpNumber; i++){ //printf("here data[%d] p1: %d p2: %d\n",i,params->data[i].p1,params->data[i].p2); lik += gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2); //printf("lik:%f %f\n",lik,gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2)); } } // printf("lik: %f\n",lik); *result=-lik; } void NumericalGradient_island_lik(size_t n, const double *v, void *params, double *df){ double CurrentF, NewF ; int i,j, counter; int NumVars = n; double VarList[n], temp[n]; double epsilon=1e-5; //get initial values island_lik_constraint(n,v,params,&CurrentF); for ( i=0; i < NumVars ; i++){ VarList[i] = v[i]; } for ( counter=0; counter < NumVars ; counter++){ for( j=0; j< NumVars; j++) temp[j] = VarList[j]; temp[counter] += epsilon; island_lik_constraint(n,temp,params,&NewF); df[counter] = (NewF - CurrentF)/epsilon; } } void island_lik_fdf(const size_t n, const double *x,void *fparams,double *fval,double *grad){ island_lik_constraint(n,x,fparams,fval); NumericalGradient_island_lik(n,x, fparams, grad); } //likelihood function for model given the data; with constraints // used with multimin minimizer void island_lik_constraint_hmm(size_t n, const double *pGuess, void * p, double *result){ struct island_lik_params * params = (struct island_lik_params *) p; double lik; int i,j; for(i=0;i<n;i++){ gsl_vector_set(params->paramVector,i,pGuess[i]); // printf("params[%d]: %f\n",i,gsl_vector_get(params->paramVector,i)); } lik = 0.0; for(j=0;j < params->nstates;j++){ //calc log probs fillLogAFS_ptr_sp_hmm(j,p); for(i = 0; i < params->snpNumber; i++){ if(params->data[i].p1==0 && params->data[i].p2==0){ // printf("%d there\n",i); lik += log( 1.0 - gsl_vector_get(params->paramVector,j+1)) * gsl_matrix_get(params->posts,j,i); } else{ // printf("here data[%d] p1: %d p2: %d\n",i,params->data[i].p1,params->data[i].p2); lik += (log(gsl_vector_get(params->paramVector,j+1)) + gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2)) * gsl_matrix_get(params->posts,j,i); // printf("lik:%f %f\n",lik,gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2)); } } } // printf("lik: %f\n",lik); *result=-lik; // exit(1); } //maximize_island_lik_const-- maximizes the island_lik_constraint function using constraints via // multimin.c addon void maximize_island_lik_const(double *lik, void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int np = 3; int i; double x[np]; double minimum=6666666.6; //use Nedler-Mead Simplex struct multimin_params optim_par = {.01,1e-4,1000,1e-4,1e-10,4,1}; //define constraints unsigned type[np]; double xmin[np]; double xmax[np]; for(i=0;i<np;i++){ type[i] = 3; xmin[i] = 0.00; xmax[i] = 20; } for(i=0;i<np;i++){ x[i] = gsl_vector_get(params->paramVector,i); } printf("Initial Parameter Values:\n"); for(i=0;i<np;i++) printf("%f ",x[i]); printf("\n"); multimin(np,x,&minimum,type,xmin,xmax,&island_lik_constraint,&NumericalGradient_island_lik,&island_lik_fdf,p,optim_par); for (i = 0; i < np; i++){ gsl_vector_set(params->paramVector,i,x[i]); gsl_vector_set(params->mlParams,i,x[i]); // printf("%f ",gsl_vector_get(params->paramVector,i)); } *lik = -minimum; params->maxLik = -minimum; params->optimized=1; // printf("\n"); } //maximize_island_lik_hmm_const-- maximizes the island_lik_constraint function using constraints via // multimin.c addon void maximize_island_lik_hmm_const(double *lik, void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int np = params->nParams; int i; double x[np]; double minimum=666666666.6; //use Nedler-Mead Simplex struct multimin_params optim_par = {.01,1e-4,500,1e-3,1e-5,4,0}; //define constraints unsigned type[np]; double xmin[np]; double xmax[np]; //N2 constraint type[0] = 3; xmin[0] = 0.01; xmax[0] = 10.0; // Theta / site constraints for(i=1;i<=params->nstates;i++){ type[i] = 3; xmin[i] = 0.0001; xmax[i] = 0.8; } //migration params for(i=params->nstates + 1;i<np;i++){ type[i] = 3; xmin[i] = 0.00001; xmax[i] = 20; } for(i=0;i<np;i++) x[i] = gsl_vector_get(params->paramVector,i); multimin((size_t)np,x,&minimum,type,xmin,xmax,&island_lik_constraint_hmm,NULL,NULL,p,optim_par); for (i = 0; i < np; i++){ gsl_vector_set(params->paramVector,i,x[i]); // printf("%f ",x[i]); } *lik = -minimum; } //likelihood function for island model given the data; with constraints // used with multimin minimizer; gets the confidence interval point void island_lik_constraint_CI(size_t n, const double *pGuess, void * p, double *result){ struct island_lik_params * params = (struct island_lik_params *) p; double lik; int i,j; for(i=0;i<n;i++){ gsl_vector_set(params->paramVector,i,pGuess[i]); // printf("params[%d]: %f\n",i,gsl_vector_get(params->paramVector,i)); } lik = 0.0; for(j=0;j < params->nstates;j++){ //calc log probs fillLogAFS_ptr_sp2(p); for(i = 0; i < params->snpNumber; i++){ //printf("here data[%d] p1: %d p2: %d\n",i,params->data[i].p1,params->data[i].p2); lik += gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2); //printf("lik:%f %f\n",lik,gsl_matrix_get(params->expAFS,params->data[i].p1,params->data[i].p2)); } } // printf("lik: %f\n",lik); *result= lik - params->maxLik - 1.92; } //maximize_island_lik_CIUpper-- maximizes the island_lik_constraint function using constraints via // multimin.c addon void maximize_island_lik_CIUpper(double *lik, void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int np = 3; int i; double x[np]; double minimum=6666666.6; //use Nedler-Mead Simplex struct multimin_params optim_par = {.01,1e-4,1000,1e-4,1e-10,4,0}; //define constraints unsigned type[np]; double xmin[np]; double xmax[np]; if(params->optimized == 1){ for(i=0;i<np;i++){ type[i] = 3; xmin[i] = gsl_vector_get(params->mlParams,i); xmax[i] = 40; } for(i=0;i<np;i++){ x[i] = gsl_vector_get(params->mlParams,i) + 0.01; printf("%f %f\n",x[i],xmin[i]); } printf("Upper Initial Parameter Values:\n"); for(i=0;i<np;i++) printf("%f ",x[i]); printf("\n"); multimin(np,x,&minimum,type,xmin,xmax,&island_lik_constraint_CI,&NumericalGradient_island_lik,&island_lik_fdf,p,optim_par); for (i = 0; i < np; i++){ gsl_vector_set(params->paramCIUpper,i,x[i]); // printf("%f ",gsl_vector_get(params->paramVector,i)); } *lik = -minimum; } else{ printf("can't compute CIs on non-optimized params\n"); } // printf("\n"); } // multimin.c addon void maximize_island_lik_CILower(double *lik, void * p){ struct island_lik_params * params = (struct island_lik_params *) p; int np = 3; int i; double x[np]; double minimum=6666666.6; //use Nedler-Mead Simplex struct multimin_params optim_par = {.1,1e-4,1000,1e-4,1e-10,4,0}; //define constraints unsigned type[np]; double xmin[np]; double xmax[np]; if(params->optimized == 1){ for(i=0;i<np;i++){ type[i] = 3; xmin[i] = 0.00001; xmax[i] = gsl_vector_get(params->mlParams,i); } for(i=0;i<np;i++){ x[i] = gsl_vector_get(params->mlParams,i) - 0.5; } printf("Lower Initial Parameter Values:\n"); for(i=0;i<np;i++) printf("%f ",x[i]); printf("\n"); multimin(np,x,&minimum,type,xmin,xmax,&island_lik_constraint_CI,&NumericalGradient_island_lik,&island_lik_fdf,p,optim_par); for (i = 0; i < np; i++){ gsl_vector_set(params->paramCILower,i,x[i]); // printf("%f ",gsl_vector_get(params->paramVector,i)); } *lik = -minimum; } else{ printf("can't compute CIs on non-optimized params\n"); } // printf("\n"); } void itoa(int n, char s[]) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } /* reverse: reverse string s in place */ void reverse(char s[]) { int i, j; char c; for (i = 0, j = strlen(s)-1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } /* //////////////////////////////////////////////////////// //Population splitting stuff //fills up an AFS matrix using expected times // Currently Does not work.... void fillExpectedAFS_IM(afsStateSpace *S, gsl_matrix *transMat,gsl_vector *rates, gsl_matrix *expAFS, int m1, int m2){ int i, j, k, l, its, count; gsl_matrix *tmIt, *tmp, *times; double tmpRes, meanTime; its = 20; //set up matrices make copy of transMat tmIt = gsl_matrix_alloc(transMat->size1,transMat->size2); tmp = gsl_matrix_alloc(transMat->size1,transMat->size2); times = gsl_matrix_alloc(transMat->size1, its); means = gsl_vector_alloc(its); gsl_matrix_set_zero(times); //initial state contribution to AFS; ie transMat^0 gsl_matrix_set_identity(tmIt); meanTime = 0; for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } tmpRes = 0; for(k=0;k<S->nstates;k++) tmpRes += (gsl_vector_get(rates,k) * gsl_matrix_get(tmIt,k,j)); gsl_matrix_set(times,j,0,tmpRes); meanTime+=tmpRes; } meanTime /= S->nstates; //now add transMat ^1 gsl_matrix_memcpy(tmIt,transMat); for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } tmpRes = 0; for(k=0;k<S->nstates;k++) tmpRes += ((gsl_vector_get(rates,k) + gsl_matrix_get(times,k,0)) * gsl_matrix_get(tmIt,k,j)); gsl_matrix_set(times,j,1,tmpRes ); } //now do matrix powers for(i=2;i<its;i++){ // printf("power: %d\n",i); // gsl_matrix_prettyPrint(tmIt); //compute matrix product gsl_matrix_set_zero(tmp); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0,tmIt,transMat,0.0,tmp); gsl_matrix_memcpy(tmIt,tmp); for(j=0;j<S->nstates;j++){ for(k=0;k<m1+1;k++){ for(l=0;l<m2+1;l++){ count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l); if(gsl_vector_get(rates,j) > 0){ tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * gsl_matrix_get(tmIt,0,j)); gsl_matrix_set(expAFS,k,l, tmpRes); } } } for(k=0;k<S->nstates;k++) tmpRes += ((gsl_vector_get(rates,k) + gsl_matrix_get(times,k,i-1)) * gsl_matrix_get(tmIt,k,j)) ; gsl_matrix_set(times,j,i,tmpRes); } } for(i=0;i<its;i++){ tmpRes = 0.0; for(j=0;j<S->nstates;j++){ tmpRes += gsl_matrix_get(times,j,i); } gsl_vector_set(means,i,tmpRes / (double) S->nstates); } // gsl_vector_fprintf(stdout,means,"%f"); // exit(1); // gsl_matrix_prettyPrint(expAFS); tmpRes = matrixSumDouble(expAFS); gsl_matrix_scale(expAFS, 1.0 / tmpRes); gsl_matrix_free(tmp); gsl_matrix_free(tmIt); } void overlayPopnSplitting(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int n1, int n2){ int i,j,k,steps,x,y; double tmp,top,bottom; afsObject *delta; int nlin1,nlin2, position,compat; gsl_matrix_int_fprintf(stdout,moveType,"%d"); for(i=0;i<S->nstates;i++){ for(j=0;j<S->nstates;j++){ //is ith state root state? if(S->states[i]->nalleles != 1){ delta = afsObjectDelta(S->states[i],S->states[j]); steps = S->states[i]->nalleles - S->states[j]->nalleles ; // printf("i:%d j:%d steps:%d\n",i,j,steps); if(steps==0 && abs(matrixSum(delta->popMats[0])) >= 1){ // 0 "steps", so no changes in nalleles between two //check counts and positions if((S->states[j]->aCounts[1] == 0 || S->states[j]->aCounts[0] == 0) && (S->states[i]->aCounts[0] > 0 && S->states[i]->aCounts[1] > 0 ) ){ //population split or potentially migration compatible printf("here\n"); switch(gsl_matrix_int_get(moveType,i,j)){ case 666: gsl_matrix_int_set(moveType,i,j,4); // case 4 indicates only split possible break; case 2: //mig popn0 gsl_matrix_int_set(moveType,i,j,5); // case 5 indicates mig popn0 or split possible break; case 3: //mig popn1 gsl_matrix_int_set(moveType,i,j,6); // case 6 indicates mig popn0 or split possible break; } } } } } } gsl_matrix_int_fprintf(stdout,moveType,"%d"); } */
{ "alphanum_fraction": 0.6309567248, "avg_line_length": 30.478202847, "ext": "c", "hexsha": "760486cb1be8248845bf1e44ea710e67a3f80c97", "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": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "AFS.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kern-lab/im_clam", "max_issues_repo_path": "AFS.c", "max_line_length": 248, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kr-colab/im_clam", "max_stars_repo_path": "AFS.c", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "num_tokens": 23271, "size": 68515 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <math.h> #include <time.h> #include <fftw3.h> #include <assert.h> #include <complex.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_eigen.h> #include "gslCompute.h" #include "MVNsampling.h" #include "Input.h" #include "Basis.h" #include "SampSetUp.h" #include "Output_t0.h" #include "SampInit.h" #include "SampZinter.h" #include "SampTheta.h" #include "SampPhi2Inv.h" #include "SampLoading.h" #include "SampLatent.h" #include "SampMu.h" #include "SampAlpha.h" #include "SampBeta.h" #include "SampGamma.h" #include "Sampweights.h" #include "SampErr_e.h" #include "SampErr_zeta.h" #include "SampErr_eps.h" #include "testing_training.h" #include "SampMean.h" #include "SampOutput.h" #include <R.h> #include <Rinternals.h> //#include <Rmath.h> SEXP csblf(SEXP outputpath, SEXP seed, SEXP nburnin, SEXP niter){ gsl_set_error_handler_off(); ////////////////////////////////////////////////////////// ///// GSL Random Number Generator Initialization ///// ////////////////////////////////////////////////////////// const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_rng_set(r, asInteger(seed)); ////////////////////////////////////////////////////////// ///// Input Data ///// ////////////////////////////////////////////////////////// // Input/Output data directory char *inpathx, *inpath, *outpath; //, *outputpath; inpathx = (char *)calloc(500,sizeof(char)); inpath = (char *)calloc(500,sizeof(char)); outpath = (char *)calloc(500,sizeof(char)); char *outppath = CHAR(asChar(outputpath)); char dataSource[20] = "RealData"; // data from simulation or read data source int sim = strcmp(dataSource, "Simulation") == 0 ? 1 : 0; strcat(inpathx, outppath); strcat(inpathx, "Data/"); strcat(inpath, inpathx); strcat(outpath, outppath); strcat(outpath, "Result/"); // Input data struct Inputdata data; data = input(inpathx, inpath, sim); int L = data.sizes[0]; // number of parcels; restricted to be 1 int nobs = data.sizes[1]; // number of training observations int P = data.sizes[3]; // number of imaging predictors int nts = data.sizes[4]; // number of observations for test ///// Basis Function ///// // Define basis functions struct BasisFunc BF; double bandwidth = 1.0/10.0; int dd = 6.0; BF = genBasis(L, outpath, data, bandwidth, dd); int M = BF.M; ////////////////////////////////////////////////////////// ///// MCMC ///// ////////////////////////////////////////////////////////// // Number of latent factors int K ; K = strcmp(dataSource, "Simulation") == 0 ? 20 : 9; // Length of chain int iter = asInteger(niter); // total iterations int burnin = asInteger(nburnin); // iterations after burnin // Parameters struct Sampling PostSamp; PostSamp = setupSamp(M, nobs, nts, L, P, K, BF, data); // Initialization bool printInit = false; //set_initial2(L, nobs, nts, K, P, PostSamp, data, BF, r, outpath, printInit, inpath); set_initial(L, nobs, nts, K, P, PostSamp, data, BF, r, outpath, printInit); clock_t start, end; start = clock(); int *singular = (int *)calloc(2, sizeof(int)); int t; // Start MCMC Rprintf("************ Start MCMC ************\n"); for(t=1; t<=iter; t++){ if (t % 50 == 0) { Rprintf("**** t=%d *****\n", t); } // Post sampling of Zinter Zinter_samp(nobs, L, K, PostSamp, data, BF, r, singular); err2inv_u_samp(L, PostSamp, data, r); err2inv_e_samp(nobs, L, PostSamp, data, BF, r); // Post sampling of theta theta_samp(nobs, L, K, PostSamp, data, BF, r, singular); // Post sampling of Phi2Inv phi2inv_samp(K, nobs, L, PostSamp, data, BF, r); // Post sampling of Loadings and its hyperparameters load_samp(K, L, nobs, PostSamp, BF, r); // Update latent variables latent_samp(L, K, nobs, PostSamp, data, BF, r); // Update mu mu_samp(L, K, nobs, PostSamp, data, BF, r); // Update alpha alpha_samp(nobs, K, P, L, PostSamp, data, BF, r); // Update beta beta_samp_approx(nobs, L, K, PostSamp, data, BF, r); // Update Gamma gamma_samp(P, nobs, K, L, PostSamp, data, BF, r); // Update Error err2inv_zeta_samp(nobs, L, K, PostSamp, data, BF, r); err2inv_eps_samp(nobs, L, K, PostSamp, data, BF, r); ///////// Posterior estimations and predictions ///////// if(t>(iter-burnin) && t%1==0){ // Training set est_training(nobs, P, L, K, PostSamp, data, BF); // test if(nts>0){ est_testing(nts, nobs, P, L, K, PostSamp, data, BF); } // For posterior mean samp_mean(L, K, nobs, nts, P, PostSamp, data, BF); } // Write posterior samplings if(t%50==0){ output_samp(outpath, t, burnin, nobs, nts, M, K, L, P, singular, PostSamp, data, BF); } // Write posterior mean if(t==iter){ output_mean(L, K, nobs, nts, P, outpath, PostSamp, data, BF, burnin); } } end = clock(); double mcmc_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; Rprintf("MCMC: %.2f secs\n", mcmc_time_used); //////////////////////////////////////////////////////////// ///// Release Memory ///// //////////////////////////////////////////////////////////// Rprintf("Release Memory.\n"); gsl_rng_free(r); free(outpath); free(inpath); free(inpathx); free(singular); // Input Data free(data.sizes); free(data.parcel_len); free(data.parcel_len_sum); free(data.axes); free(data.Z); free(data.X); int l; for(l=0; l<L; l++){ free(data.Zl[l]); free(data.Xl[l]); } if(nts > 0){ free(data.Z_test); free(data.X_test); for(l=0; l<L; l++){ free(data.Zl_test[l]); free(data.Xl_test[l]); free(PostSamp.xb_test[l]); } free(data.Zl_test); free(data.Xl_test); free(PostSamp.xb_test); } // Basis Functions for(l=0; l<L; l++){ free(BF.basis[l]); free(BF.kernel_loc[l]); } free(BF.basis); free(BF.kernel_loc); free(BF.Ml); // Post Sampling for(l=0; l<L; l++){ free(PostSamp.basis2[l]); free(PostSamp.zb[l]); free(PostSamp.zb2[l]); free(PostSamp.xb[l]); free(PostSamp.rxb[l]); free(PostSamp.Zinter[l]); free(PostSamp.theta[l]); free(PostSamp.load[l]); free(PostSamp.loadstar[l]); free(PostSamp.latent[l]); free(PostSamp.latentstar[l]); free(PostSamp.latent2[l]); free(PostSamp.beta[l]); free(PostSamp.betastar[l]); free(PostSamp.alpha[l]); free(PostSamp.alphastar[l]); free(PostSamp.xba[l]); free(PostSamp.xbar[l]); free(PostSamp.mustar[l]); free(PostSamp.sumX[l]); } free(PostSamp.basis2); free(PostSamp.zb); free(PostSamp.zb2); free(PostSamp.xb); free(PostSamp.rxb); free(PostSamp.Zinter); free(PostSamp.theta); free(PostSamp.load); free(PostSamp.loadstar); free(PostSamp.latent); free(PostSamp.latentstar); free(PostSamp.latent2); free(PostSamp.Phi2Inv); free(PostSamp.beta); free(PostSamp.betastar); free(PostSamp.alpha); free(PostSamp.alphastar); free(PostSamp.xba); free(PostSamp.xbar); free(PostSamp.mustar); free(PostSamp.sumX); free(PostSamp.err2inv_e); free(PostSamp.err2inv_zeta); free(PostSamp.err2inv_eps); free(PostSamp.err2inv_u); for(l=0; l<L; l++){ free(PostSamp.mean_Zinter[l]); free(PostSamp.mean_theta[l]); free(PostSamp.mean_load[l]); free(PostSamp.mean_loadstar[l]); free(PostSamp.mean_latent[l]); free(PostSamp.mean_latentstar[l]); free(PostSamp.mean_beta[l]); free(PostSamp.mean_betastar[l]); free(PostSamp.mean_alpha[l]); free(PostSamp.mean_alphastar[l]); free(PostSamp.mean_mu[l]); } free(PostSamp.mean_Zinter); free(PostSamp.mean_theta); free(PostSamp.mean_load); free(PostSamp.mean_loadstar); free(PostSamp.mean_latent); free(PostSamp.mean_latentstar); free(PostSamp.mean_Phi2Inv); free(PostSamp.mean_beta); free(PostSamp.mean_betastar); free(PostSamp.mean_alpha); free(PostSamp.mean_alphastar); free(PostSamp.mean_mu); free(PostSamp.mean_gamma); free(PostSamp.mean_gamma_update); free(PostSamp.mean_w); free(PostSamp.err2inv_e_mean); free(PostSamp.err2inv_zeta_mean); free(PostSamp.err2inv_eps_mean); free(PostSamp.err2inv_u_mean); if(nts > 0){ for(l=0; l<L; l++){ free(PostSamp.Zinter_test[l]); free(PostSamp.latent_test[l]); free(PostSamp.theta_test[l]); free(PostSamp.outcome_test[l]); free(PostSamp.Zinter_test_mean[l]); free(PostSamp.latent_test_mean[l]); free(PostSamp.theta_test_mean[l]); free(PostSamp.outcome_test_mean[l]); free(PostSamp.outcome_test_mean2[l]); } free(PostSamp.Zinter_test); free(PostSamp.latent_test); free(PostSamp.theta_test); free(PostSamp.outcome_test); free(PostSamp.Zinter_test_mean); free(PostSamp.latent_test_mean); free(PostSamp.theta_test_mean); free(PostSamp.outcome_test_mean); free(PostSamp.outcome_test_mean2); } for(l=0; l<L; l++){ free(PostSamp.latent_train[l]); free(PostSamp.latent_train_err[l]); free(PostSamp.theta_train[l]); free(PostSamp.theta_train_err[l]); free(PostSamp.outcome_train[l]); free(PostSamp.latent_train_mean[l]); free(PostSamp.theta_train_mean[l]); free(PostSamp.outcome_train_mean[l]); free(PostSamp.outcome_train_mean2[l]); } free(PostSamp.latent_train); free(PostSamp.latent_train_err); free(PostSamp.theta_train); free(PostSamp.theta_train_err); free(PostSamp.outcome_train); free(PostSamp.latent_train_mean); free(PostSamp.theta_train_mean); free(PostSamp.outcome_train_mean); free(PostSamp.outcome_train_mean2); Rprintf("MCMC complete.\n"); return R_NilValue; }
{ "alphanum_fraction": 0.574661048, "avg_line_length": 32.2958579882, "ext": "c", "hexsha": "730ca6abf2e985f37a0d72d83e497d8240644907", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-03T05:29:23.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-03T05:29:23.000Z", "max_forks_repo_head_hexsha": "d4a26e3fd98db13282d13e374eaead26b7e4f2f7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umich-biostatistics/SBLF", "max_forks_repo_path": "src/csblf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d4a26e3fd98db13282d13e374eaead26b7e4f2f7", "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": "umich-biostatistics/SBLF", "max_issues_repo_path": "src/csblf.c", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "d4a26e3fd98db13282d13e374eaead26b7e4f2f7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umich-biostatistics/SBLF", "max_stars_repo_path": "src/csblf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3064, "size": 10916 }
/* ################################################# * # stochastic simulation of adapting populations # * # with variing constraint type # * # and exponential mutation kernel # * ################################################# * * 2012-2014, Lukas Geyrhofer * * * ################################################# * * simplest usage (population size 1e7): * ./travelingwavepeak_exp -N 1e7 1> out.txt 2> conf.txt * * ################################################# */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #include <time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> int space = 300; int space0 = 100; double dx = 1e-2; int maxSteps = 1000; int outputstep = 100; int quiet = 0; int noise = 0; double populationsize = 1.; double populationvariance; int correctformeanfitness =0; int printhistotype = 1; int allshifts = 0; int shiftthreshold = 1; double current_mean_fitness = 0.; int read_from_file = 0; int write_to_file = 0; char c_infile[128],c_outfile[128]; int have_u_infile = 0; char u_infile[128]; double *u_read,*u; int dens_ustar_latticeratio = 1; int u_space,u_space0; double u_dx; double wavespeed = 0.; double speedprefactor; double epsilon = 1e-2; double twoepssqrt; double *nn; double *tmp; double *x; double mutationrate = 1e-5; double *mutation_inflow; double mutation_outflow; double mutation_sigma = 1e-2; const gsl_rng* rg; /* gsl, global generator */ const gsl_rng_type* T; unsigned long int randseed = 0; double popdens_0thmom; double popdens_1stmom; double popdens_2ndmom; int averagepopdens = 0; int averagepopdens_center = 1; int averagepopdens_resolution = 1; int averagepopdens_havefile = 0; double *averagepopdens_dens; char averagepopdens_outputfile[128]; double averagepopdens_count = 0.; double averagepopdens_dx; int averagepopdens_space; int averagepopdens_space0; int averagepopdens_lower; int averagepopdens_higher; int fixationextinction_events = 0; double fe_expected_fixationprobability = .5; double fe_predicted_fixationprobability; double *ww,*vv; double *fe_start_ww, *fe_start_vv; double *tmpw,*tmpv; double fe_final_threshold = 1e-4; // if (current_fixation_prob > 1 - 1e-4) or (current_fixation_prob < 1e-4), then restart... double fe_subpopsize; int fe_count_extinctions = 0; int fe_count_fixations = 0; double current_fixation_prob; int print_error(char *msg) { fprintf(stderr,"ERROR: %s\n",msg); exit(1); } // ************************************************************ // ** parameters // ************************************************************ void parsecomamndline(int argn, char *argv[]) { char c; while((c = getopt(argn,argv,"s:z:d:S:e:D:O:qQi:o:R:N:CM:u:U:T:H:h:PE:")) != -1) { switch(c) { case 's': space = atoi(optarg); break; case 'z': space0 = atoi(optarg); break; case 'd': dx = atof(optarg); break; case 'i': strcpy(c_infile,optarg); read_from_file = 1; break; case 'o': strcpy(c_outfile,optarg); write_to_file = 1; break; case 'u': strcpy(u_infile,optarg); if(noise > 0) print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME)"); noise = 2; break; case 'U': if(noise == 2) { dens_ustar_latticeratio = atoi(optarg); }else{ print_error("option -u FILENAME needed before option -U RATIO"); } break; case 'S': maxSteps = atoi(optarg); break; case 'e': epsilon = atof(optarg); break; case 'D': mutationrate = atof(optarg); break; case 'O': outputstep = atoi(optarg); break; case 'q': quiet = 2; break; case 'Q': quiet = 1; break; case 'R': randseed =atoi(optarg); break; case 'N': populationsize = atof(optarg); if(noise > 0) print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME)"); noise = 1; break; case 'C': correctformeanfitness = 1; break; case 'M': mutation_sigma = atof(optarg); break; case 'T': shiftthreshold = atoi(optarg); break; case 'h': strcpy(averagepopdens_outputfile,optarg); averagepopdens_havefile = 1; averagepopdens = 1; break; case 'H': averagepopdens = 1; averagepopdens_resolution = atoi(optarg); if(averagepopdens_resolution < 0) { averagepopdens_resolution *= -1; averagepopdens_center = 0; } break; case 'P': printhistotype = 0; break; case 'E': fe_expected_fixationprobability = atof(optarg); break; } } if(randseed==0)randseed=time(NULL); } // ************************************************************ // ** input and output for configuration files // ************************************************************ void read_popdens(int importparameters) { int i; int icount,dcount; int *ival; double *dval; int c_space,c_space0; double c_dx; FILE *fp; fp = fopen(c_infile,"rb"); if(fp != NULL) { fread(&icount,sizeof(int),1,fp); fread(&dcount,sizeof(int),1,fp); fread(&c_dx,sizeof(double),1,fp); fread(&c_space,sizeof(int),1,fp); fread(&c_space0,sizeof(int),1,fp); if(importparameters) { space = c_space; space0 = c_space0; dx = c_dx; } if(icount>0) { ival = (int*)malloc(icount*sizeof(int)); fread(ival,sizeof(int),icount,fp); free(ival); } if(dcount>0) { dval = (double*)malloc(dcount*sizeof(int)); fread(dval,sizeof(double),dcount,fp); free(dval); } if(space != c_space)print_error("lattice does not match!"); nn = (double*)malloc(space*sizeof(double)); fread(nn,sizeof(double),space,fp); for(i=0;i<space;i++) { nn[i] *= dx; } fclose(fp); }else{ print_error("could not open c-infile"); } } void write_popdens() { int icount=0,dcount=0; int i; FILE *fpc; fpc=fopen(c_outfile,"wb"); if(fpc != NULL) { fwrite(&icount,sizeof(int),1,fpc); fwrite(&dcount,sizeof(int),1,fpc); fwrite(&dx,sizeof(double),1,fpc); fwrite(&space,sizeof(int),1,fpc); fwrite(&space0,sizeof(int),1,fpc); for(i=0;i<space;i++)nn[i] /= dx; fwrite(nn,sizeof(double),space,fpc); fclose(fpc); }else{ print_error("could not open c-outfile"); } } void read_constraint(int importparameters) { int icount,dcount; int *ival; double *dval; FILE *fp; fp = fopen(u_infile,"rb"); if(fp!=NULL) { fread(&icount,sizeof(int),1,fp); fread(&dcount,sizeof(int),1,fp); fread(&u_dx,sizeof(double),1,fp); fread(&u_space,sizeof(int),1,fp); fread(&u_space0,sizeof(int),1,fp); if(icount>0) { ival = (int*)malloc(icount*sizeof(int)); fread(ival,sizeof(int),icount,fp); free(ival); } if(dcount>=3) { dval = (double*)malloc(dcount*sizeof(int)); fread(dval,sizeof(double),dcount,fp); mutationrate = dval[0]; wavespeed = dval[1]; mutation_sigma = dval[2]; free(dval); }else{ print_error("not enough values in constraint file! need at least 3 double parameters: mutationrate, wavespeed, mutationsigma!"); } if(importparameters) { space = u_space/dens_ustar_latticeratio; space0 = u_space0/dens_ustar_latticeratio; dx = u_dx*dens_ustar_latticeratio; }else{ if((space*dens_ustar_latticeratio != u_space)||(space0*dens_ustar_latticeratio != u_space0))print_error("lattice does not match! u"); } u_read = (double*)malloc(u_space*sizeof(double)); fread(u_read,sizeof(double),u_space,fp); fclose(fp); } u = (double*)malloc(space*sizeof(double)); } void flat_constraint(double size) { int i; u=(double*)malloc(space*sizeof(double)); for(i=0;i<space;i++)u[i] = 1./size; } void initialize_with_gaussian_popdens() { int i; double startvariance; if(noise == 2) { startvariance = wavespeed; }else{ // Good et al., PNAS (2012) startvariance = mutation_sigma*mutation_sigma*2*log(mutation_sigma*populationsize)/(log(mutation_sigma/mutationrate)*log(mutation_sigma/mutationrate)); } for(i=0;i<space;i++) { nn[i] = exp(-(i-space0)*(i-space0)*dx*dx/(2.*startvariance)); } } // ************************************************************ // ** screen output // ************************************************************ void print_populationdensity(int timestep) { int i; double corr = allshifts*dx; if(correctformeanfitness)corr += current_mean_fitness; for(i=0;i<space;i++) { fprintf(stderr,"%lf %14.10lf %20.10e %20.10e\n",timestep*epsilon,(i-space0)*dx+corr,ww[i]+vv[i],ww[i]); if(printhistotype)fprintf(stderr,"%lf %14.10lf %20.10e %20.10e\n",timestep*epsilon,(i-space0+1)*dx+corr,ww[i]+vv[i],ww[i]); } fprintf(stderr,"\n"); } // ************************************************************ // ** initialization // ************************************************************ int initialize() { int i; if(read_from_file) { read_popdens(1); if(noise == 0)flat_constraint(1.); if(noise == 1)flat_constraint(populationsize); if(noise == 2)read_constraint(0); }else{ if(noise == 0)flat_constraint(1.); if(noise == 1)flat_constraint(populationsize); if(noise == 2)read_constraint(1); nn = (double*)calloc(space,sizeof(double)); initialize_with_gaussian_popdens(); } tmp = (double*)malloc(space*sizeof(double)); gsl_rng_env_setup(); T = gsl_rng_default; rg = gsl_rng_alloc(T); gsl_rng_set(rg, randseed); twoepssqrt = sqrt(2.*epsilon); speedprefactor = wavespeed/dx*epsilon; x = (double*)malloc(space*sizeof(double)); mutation_inflow = (double*)malloc(space*sizeof(double)); mutation_outflow = 0; for(i=1;i<space;i++) { x[i] = (i-space0)*dx; mutation_inflow[i] = epsilon*exp(-i*dx/mutation_sigma)/mutation_sigma*mutationrate*dx; mutation_outflow += mutation_inflow[i]; } if(quiet<2) { printf("#################################################################################\n"); printf("# stochastic simulation of adapting population with exponential mutation kernel #\n"); printf("#################################################################################\n"); printf("# mutationrate = %e\n",mutationrate); printf("# mutation_sigma = %e\n",mutation_sigma); if(noise==0) { printf("# constraint = deterministic\n"); } if(noise==1) { printf("# constraint = fixedN\n"); printf("# populationsize = %e\n",populationsize); } if(noise==2) { printf("# constraint = ustar\n"); printf("# wavespeed = %e\n",wavespeed); } printf("# (lattice) space = %d\n",space); printf("# (lattice) space0 = %d\n",space0); printf("# (lattice) dx = %e\n",dx); printf("# randseed = %d\n",randseed); } } // ************************************************************ // ** average popdens // ************************************************************ void init_averagepopdens() { averagepopdens_dx = dx/(1.*averagepopdens_resolution); averagepopdens_space = space*averagepopdens_resolution; averagepopdens_space0 = space0*averagepopdens_resolution; averagepopdens_dens = (double*)calloc(averagepopdens_space,sizeof(double)); averagepopdens_lower = (int)(-averagepopdens_resolution/2); averagepopdens_higher = (int)(averagepopdens_resolution/2); if(averagepopdens_higher - averagepopdens_lower < averagepopdens_resolution)averagepopdens_higher++; } void update_averagepopdens() { int i,j,idx; int offset=0; if(averagepopdens_center) { offset = (int)(current_mean_fitness/dx*averagepopdens_resolution); } for(i=0;i<space;i++) { for(j=averagepopdens_lower;j<averagepopdens_higher;j++) { idx = i*averagepopdens_resolution+j-offset; if((averagepopdens_space > idx) &&( idx >= 0)) averagepopdens_dens[idx] += nn[i]; } } averagepopdens_count += 1.; } void write_averagepopdens() { int i; FILE *fp; if(averagepopdens_havefile == 1) { fp = fopen(averagepopdens_outputfile,"w"); }else{ fp = stdout; } for(i=0;i<averagepopdens_space;i++) { fprintf(fp,"%lf %e\n",(i-averagepopdens_space0)*averagepopdens_dx,averagepopdens_dens[i]/averagepopdens_count); } if(averagepopdens_havefile == 1) { fclose(fp); } free(averagepopdens_dens); } // ************************************************************ // ** main algorithm // ************************************************************ void update_u(int timestep) { // bug if shiftthreshold -T >1, use shiftthreshold only with fixedN int i,j; int baseshift; double fracshift; if(dens_ustar_latticeratio > 1) { baseshift = (int)(timestep*epsilon*wavespeed/u_dx) - allshifts*dens_ustar_latticeratio; fracshift = timestep*epsilon*wavespeed/u_dx - 1.*(baseshift + allshifts*dens_ustar_latticeratio); i = 0; j = 0; while( (i<space) && (j<u_space) ) { if((j+baseshift)%dens_ustar_latticeratio == 0) { u[i] = (fracshift) * u_read[j]; }else if((j+baseshift)%dens_ustar_latticeratio == dens_ustar_latticeratio - 1) { u[i] += (1.-fracshift) * u_read[j]; u[i] /= (1.*dens_ustar_latticeratio); i++; }else{ u[i] += u_read[j]; } j++; } }else{ fracshift = timestep*epsilon*wavespeed/u_dx - 1.*allshifts; // ignore u[0], as it is unlikely that the population has a significant subpop there... for(i=1;i<space;i++)u[i] = fracshift * u_read[i-1] + (1.-fracshift)*u_read[i]; } } void update_mean_fit() { int i; current_mean_fitness = 0.; populationsize = 0.; for(i=0;i<space;i++) { current_mean_fitness += (i-space0)*(ww[i]+vv[i]); populationsize += ww[i] + vv[i]; } current_mean_fitness *= dx/populationsize; } void shift_population_backward(int step) { int i; for(i=0;i<space-step;i++){ ww[i] = ww[i+step]; vv[i] = vv[i+step]; } for(i=space-step;i<space;i++) { ww[i] = 0.; vv[i] = 0.; } } void shift_population_forward(int step) { int i; for(i=space-1;i>step;i--) { ww[i] = ww[i-step]; vv[i] = vv[i-step]; } for(i=step;i>=0;i--) { ww[i] = 0.; vv[i] = 0.; } } void shift_population(int timestep) { int shift = (int)floor(current_mean_fitness/dx); if(shift >= shiftthreshold) {shift_population_backward(shift);} if(shift <= -shiftthreshold) {shift_population_forward(shift);} allshifts += shift; current_mean_fitness -= shift*dx; } void reproduce(int timestep) { int i,j; double tmpn; if(noise < 2) { update_mean_fit(); }else if(noise == 2) { current_mean_fitness = timestep*wavespeed*epsilon - allshifts*dx; } if((current_mean_fitness > shiftthreshold*dx) || (current_mean_fitness < -shiftthreshold*dx)) { shift_population(timestep); } tmpw[0] = 0; tmpw[space-1] = 0; tmpv[0] = 0; tmpv[space-1] = 0; for(i=1;i<space-1;i++) { tmpw[i] = ww[i]*(1.+(x[i]-mutationrate-current_mean_fitness)*epsilon); tmpv[i] = vv[i]*(1.+(x[i]-mutationrate-current_mean_fitness)*epsilon); for(j = 1;j<=i;j++) { tmpw[i] += mutation_inflow[j]*ww[i-j]; tmpv[i] += mutation_inflow[j]*vv[i-j]; } if(tmpw[i]<0) { tmpw[i] = 0; }else if(noise > 0) { if(tmpw[i] < 1e9) { // Poisson-RNG breaks down for parameters > 1e9. see GSL doc. // use smaller bins if this occurs too often or population size too large tmpw[i] += twoepssqrt*(gsl_ran_poisson(rg,tmpw[i])-tmpw[i]); }else{ tmpw[i] = 1e9; } } if(tmpv[i]<0) { tmpv[i] = 0; }else if(noise > 0) { if(tmpv[i] < 1e9) { // Poisson-RNG breaks down for parameters > 1e9. see GSL doc. // use smaller bins if this occurs too often or population size too large tmpv[i] += twoepssqrt*(gsl_ran_poisson(rg,tmpv[i])-tmpv[i]); }else{ tmpv[i] = 1e9; } } } memcpy(ww,tmpw,space*sizeof(double)); memcpy(vv,tmpv,space*sizeof(double)); } void populationconstraint(int timestep) { int i; double sum = 0., inv; if(noise == 2) { update_u(timestep); } current_fixation_prob = 0; popdens_0thmom = 0; popdens_1stmom = 0; popdens_2ndmom = 0; fe_subpopsize = 0; for(i=0;i<space;i++) { sum += (ww[i] + vv[i])*u[i]; current_fixation_prob += ww[i]*u[i]; fe_subpopsize += ww[i]; popdens_0thmom += ww[i] + vv[i]; popdens_1stmom += (i-space0)*(ww[i] + vv[i]); popdens_2ndmom += (i-space0)*(i-space0)*(ww[i] + vv[i]); } popdens_1stmom *= dx; popdens_2ndmom *= dx*dx; populationsize = popdens_0thmom; populationvariance = popdens_2ndmom/popdens_0thmom - popdens_1stmom*popdens_1stmom/(popdens_0thmom*popdens_0thmom); inv = 1./(sum); current_fixation_prob *= inv; for(i=0;i<space;i++) { ww[i] *= inv; vv[i] *= inv; } } void initial_constraint() { int i; double sum=0; double inv; for(i=0;i<space;i++)sum += nn[i] * u[i]; inv = 1./sum; for(i=0;i<space;i++)nn[i] *= inv; } // ************************************************************ // ** extinction and fixation events // ************************************************************ int init_fe() { int i,j; int startindex = space; double fixprob = 0.,frac_lastbin; ww = (double*)malloc(space*sizeof(double)); vv = (double*)malloc(space*sizeof(double)); fe_start_ww = (double*)malloc(space*sizeof(double)); fe_start_vv = (double*)malloc(space*sizeof(double)); tmpw = (double*)malloc(space*sizeof(double)); tmpv = (double*)malloc(space*sizeof(double)); update_u(0); initial_constraint(); while (fixprob < fe_expected_fixationprobability) { startindex--; fixprob += nn[startindex]*u[startindex]; } frac_lastbin = 1. + (fe_expected_fixationprobability - fixprob)/(nn[startindex]*u[startindex]); fe_predicted_fixationprobability = fixprob; for(j=0;j<space;j++) { if(j<startindex) { ww[j] = 0; vv[j] = nn[j]; }else if(j==startindex){ ww[j] = frac_lastbin*nn[j]; vv[j] = (1-frac_lastbin)*nn[j]; }else{ ww[j] = nn[j]; vv[j] = 0; } } memcpy(fe_start_ww,ww,space*sizeof(double)); memcpy(fe_start_vv,vv,space*sizeof(double)); } double reset_fe() { allshifts = 0; memcpy(ww,fe_start_ww,space*sizeof(double)); memcpy(vv,fe_start_vv,space*sizeof(double)); } // ************************************************************ // ** cleanup // ************************************************************ void cleanup() { free(nn); free(tmp); free(x); free(mutation_inflow); free(u); if(noise == 2) { free(u_read); } free(ww); free(vv); free(tmpw); free(tmpv); free(fe_start_ww); free(fe_start_vv); } // ************************************************************ // ** main // ************************************************************ int main(int argn, char *argv[]) { int i=1; double v; parsecomamndline(argn,argv); initialize(); init_fe(); populationconstraint(0); if(averagepopdens) { init_averagepopdens(); } if (quiet<2) fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e\n",i*epsilon,0.,populationvariance,populationsize,fe_subpopsize,current_fixation_prob); // print_populationdensity(0); // exit(1); while(fe_count_extinctions + fe_count_fixations < maxSteps) { reproduce(i); populationconstraint(i); if(i%outputstep == 0) { if (quiet<2)fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e\n",i*epsilon,allshifts*dx + popdens_1stmom/popdens_0thmom,populationvariance,populationsize,fe_subpopsize,current_fixation_prob); if (quiet==0) print_populationdensity(i); if (averagepopdens) update_averagepopdens(); } if(current_fixation_prob < fe_final_threshold) { reset_fe(); fe_count_extinctions++; printf("# event ( %d of %d ): extinction %lf\n",fe_count_extinctions+fe_count_fixations,maxSteps,i*epsilon); i=0; } if(current_fixation_prob > 1-fe_final_threshold) { reset_fe(); fe_count_fixations++; printf("# event ( %d of %d ): fixation %lf\n",fe_count_extinctions+fe_count_fixations,maxSteps,i*epsilon); i=0; } i++; } if(write_to_file)write_popdens(); if(averagepopdens)write_averagepopdens(); cleanup(); return 0; }
{ "alphanum_fraction": 0.5907142161, "avg_line_length": 25.2162162162, "ext": "c", "hexsha": "c5685b5f0df44b6602c29a987f349dfe0bd621ae", "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": "073a021b3d09f162445cb2ad38a7308a3e08465d", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "lukasgeyrhofer/adaptivewaves", "max_forks_repo_path": "stochastics/travelingwavepeak_exp_event.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "lukasgeyrhofer/adaptivewaves", "max_issues_repo_path": "stochastics/travelingwavepeak_exp_event.c", "max_line_length": 203, "max_stars_count": 2, "max_stars_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "lukasgeyrhofer/adaptivewaves", "max_stars_repo_path": "stochastics/travelingwavepeak_exp_event.c", "max_stars_repo_stars_event_max_datetime": "2020-02-26T23:07:47.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-12T19:36:44.000Z", "num_tokens": 5959, "size": 20526 }
#ifndef __CNN_FC_H__ #define __CNN_FC_H__ #include <cblas.h> #include "cnn_types.h" #ifdef CNN_WITH_CUDA #include <cublas_v2.h> #include <cuda_runtime.h> #include "cnn_init.h" #endif static inline void cnn_forward_fc(union CNN_LAYER* layerRef, struct CNN_CONFIG* cfgRef, int layerIndex) { #ifdef CNN_WITH_CUDA float alpha = 1.0; float beta = 0.0; struct CNN_LAYER_FC* layerPtr = &layerRef[layerIndex].fc; struct CNN_MAT* wPtr = &layerPtr->weight; struct CNN_MAT* outData = &layerPtr->outMat.data; struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data; // Weight matrix multiplication cnn_assert_cublas(cublasSgemm( // cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_N, // outData->cols, cfgRef->batch, preOutData->cols, // &alpha, // wPtr->mat, wPtr->cols, // preOutData->mat, preOutData->cols, // &beta, // outData->mat, outData->cols)); // Add bias beta = 1.0; cnn_assert_cudnn(cudnnAddTensor(cnnInit.cudnnHandle, // &alpha, // layerPtr->biasTen, layerPtr->bias.mat, // &beta, // layerPtr->dstTen, outData->mat)); #else // Weight matrix multiplication cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, layerRef[layerIndex - 1].outMat.data.rows, layerRef[layerIndex].outMat.data.cols, layerRef[layerIndex - 1].outMat.data.cols, 1.0, layerRef[layerIndex - 1].outMat.data.mat, layerRef[layerIndex - 1].outMat.data.cols, layerRef[layerIndex].fc.weight.mat, layerRef[layerIndex].fc.weight.cols, 0.0, layerRef[layerIndex].outMat.data.mat, layerRef[layerIndex].outMat.data.cols); // Add bias for (int j = 0; j < cfgRef->batch; j++) { int dstIndex = j * layerRef[layerIndex].outMat.data.cols; cblas_saxpy(layerRef[layerIndex].fc.bias.cols, 1.0, layerRef[layerIndex].fc.bias.mat, 1, &layerRef[layerIndex].outMat.data.mat[dstIndex], 1); } #endif } static inline void cnn_backward_fc(union CNN_LAYER* layerRef, struct CNN_CONFIG* cfgRef, int layerIndex) { #ifdef CNN_WITH_CUDA float alpha = 1.0; float beta = 1.0; struct CNN_LAYER_FC* layerPtr = &layerRef[layerIndex].fc; struct CNN_MAT* wPtr = &layerPtr->weight; struct CNN_MAT* outData = &layerPtr->outMat.data; struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data; // Sum weight gradient matrix cnn_assert_cublas( // cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_T, // wPtr->cols, wPtr->rows, cfgRef->batch, // &alpha, // outData->grad, outData->cols, // preOutData->mat, preOutData->cols, // &beta, // wPtr->grad, wPtr->cols)); // Sum bias gradient matrix if (cfgRef->batch > 1) { cnn_assert_cudnn( cudnnReduceTensor(cnnInit.cudnnHandle, layerPtr->reduDesc, layerPtr->indData, layerPtr->indSize, // cnnInit.wsData, cnnInit.wsSize, // &alpha, // layerPtr->dstTen, outData->grad, // &beta, // layerPtr->biasTen, layerPtr->bias.grad)); } else { cnn_assert_cublas( // cublasSaxpy(cnnInit.blasHandle, layerPtr->bias.cols, // &alpha, // outData->grad, 1, // layerPtr->bias.grad, 1)); } #else // Sum weight gradient matrix cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, layerRef[layerIndex].fc.weight.rows, layerRef[layerIndex].fc.weight.cols, cfgRef->batch, 1.0, layerRef[layerIndex - 1].outMat.data.mat, layerRef[layerIndex - 1].outMat.data.cols, layerRef[layerIndex].outMat.data.grad, layerRef[layerIndex].outMat.data.cols, 1.0, layerRef[layerIndex].fc.weight.grad, layerRef[layerIndex].fc.weight.cols); // Sum bias gradient matrix for (int j = 0; j < cfgRef->batch; j++) { int srcShift = j * layerRef[layerIndex].outMat.data.cols; cblas_saxpy(layerRef[layerIndex].fc.bias.cols, 1.0, &layerRef[layerIndex].outMat.data.grad[srcShift], 1, layerRef[layerIndex].fc.bias.grad, 1); } #endif // Find layer gradient if (layerIndex > 1) { #ifdef CNN_WITH_CUDA beta = 0.0; cnn_assert_cublas( // cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_T, CUBLAS_OP_N, // wPtr->rows, cfgRef->batch, wPtr->cols, // &alpha, // wPtr->mat, wPtr->cols, // outData->grad, outData->cols, // &beta, // preOutData->grad, preOutData->cols)); #else cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, layerRef[layerIndex - 1].outMat.data.rows, layerRef[layerIndex - 1].outMat.data.cols, layerRef[layerIndex].outMat.data.cols, 1.0, layerRef[layerIndex].outMat.data.grad, layerRef[layerIndex].outMat.data.cols, layerRef[layerIndex].fc.weight.mat, layerRef[layerIndex].fc.weight.cols, 0.0, layerRef[layerIndex - 1].outMat.data.grad, layerRef[layerIndex - 1].outMat.data.cols); #endif } } #endif
{ "alphanum_fraction": 0.4829129981, "avg_line_length": 41.1104294479, "ext": "h", "hexsha": "23386098bc4bdffd4ffdd51c73acd759d22341c5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jamesljlster/cnn", "max_forks_repo_path": "src/cnn_fc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jamesljlster/cnn", "max_issues_repo_path": "src/cnn_fc.h", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jamesljlster/cnn", "max_stars_repo_path": "src/cnn_fc.h", "max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z", "num_tokens": 1530, "size": 6701 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "DirectionalLight.h" namespace Library { class ProxyModel; } namespace Rendering { class DiffuseLightingMaterial; class DiffuseLightingDemo final : public Library::DrawableGameComponent { public: DiffuseLightingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); DiffuseLightingDemo(const DiffuseLightingDemo&) = delete; DiffuseLightingDemo(DiffuseLightingDemo&&) = default; DiffuseLightingDemo& operator=(const DiffuseLightingDemo&) = default; DiffuseLightingDemo& operator=(DiffuseLightingDemo&&) = default; ~DiffuseLightingDemo(); bool AnimationEnabled() const; void SetAnimationEnabled(bool enabled); void ToggleAnimation(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float DirectionalLightIntensity() const; void SetDirectionalLightIntensity(float intensity); const DirectX::XMFLOAT3& LightDirection() const; void RotateDirectionalLight(DirectX::XMFLOAT2 amount); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const float RotationRate{ DirectX::XM_PI }; std::shared_ptr<DiffuseLightingMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; Library::DirectionalLight mDirectionalLight; std::unique_ptr<Library::ProxyModel> mProxyModel; float mModelRotationAngle{ 0.0f }; bool mAnimationEnabled{ false }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7819467102, "avg_line_length": 30.65, "ext": "h", "hexsha": "88dc06f1c53a9bf100911b31a670792aaf12fa86", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/7.4_Distortion_Mapping/DiffuseLightingDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 472, "size": 1839 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_errno.h> #include "ccl.h" /* * Spline the linear power spectrum for mu-Sigma MG cosmologies. * @param cosmo Cosmological parameters ^ @param psp The linear power spectrum to spline. * @param status, integer indicating the status */ void ccl_rescale_musigma_s8(ccl_cosmology* cosmo, ccl_f2d_t *psp, int mg_rescale, int* status) { int do_mg = mg_rescale && (fabs(cosmo->params.mu_0) > 1e-14); int do_s8 = isfinite(cosmo->params.sigma8) && (!isfinite(cosmo->params.A_s)); if (!do_mg && !do_s8) return; size_t na; double *aa; double rescale_extra_musig = 1; double *rescale_factor = NULL; if (*status == 0) { // Get array of scale factors if(psp->fa != NULL) { na = psp->fa->size; aa = psp->fa->x; } else if(psp->fka != NULL) { na = psp->fka->interp_object.ysize; aa = psp->fka->yarr; } else { *status = CCL_ERROR_SPLINE; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "input pk2d has no splines.\n"); } } // Alloc rescale_factor if(*status == 0) { rescale_factor = malloc(na * sizeof(double)); if(rescale_factor == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): memory allocation\n"); } } // set to 1 by default if(*status == 0) { for(int i=0; i<na; i++) rescale_factor[i]=1; } // If scale-independent mu / Sigma modified gravity is in use // and mu ! = 0 : get the unnormalized growth factor in MG and for // corresponding GR case, to rescale CLASS power spectrum if(do_mg) { // Set up another cosmology which is exactly the same as the // current one but with mu_0 and Sigma_0=0, for scaling P(k) // Get a list of the three neutrino masses already calculated double norm_pk; double mnu_list[3] = {0, 0, 0}; ccl_parameters params_GR; params_GR.m_nu = NULL; params_GR.z_mgrowth = NULL; params_GR.df_mgrowth = NULL; ccl_cosmology * cosmo_GR = NULL; for (int i=0; i< cosmo->params.N_nu_mass; i=i+1) mnu_list[i] = cosmo->params.m_nu[i]; if (isfinite(cosmo->params.A_s)) { norm_pk = cosmo->params.A_s; } else if (isfinite(cosmo->params.sigma8)) { norm_pk = cosmo->params.sigma8; } else { *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "neither A_s nor sigma8 defined.\n"); } if (*status == 0) { params_GR = ccl_parameters_create( cosmo->params.Omega_c, cosmo->params.Omega_b, cosmo->params.Omega_k, cosmo->params.Neff, mnu_list, cosmo->params.N_nu_mass, cosmo->params.w0, cosmo->params.wa, cosmo->params.h, norm_pk, cosmo->params.n_s, cosmo->params.bcm_log10Mc, cosmo->params.bcm_etab, cosmo->params.bcm_ks, 0., 0., cosmo->params.nz_mgrowth, cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, status); if (*status) { *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "could not make MG params.\n"); } } if (*status == 0) { cosmo_GR = ccl_cosmology_create(params_GR, cosmo->config); if (cosmo_GR == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "error initializing cosmology\n"); } } if (*status == 0) { ccl_cosmology_compute_growth(cosmo_GR, status); if (*status) { *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "could not init GR growth.\n"); } } // Populate rescale_factor if (*status == 0) { for (int i=0; i<na; i++) { double D_mu = ccl_growth_factor_unnorm(cosmo, aa[i], status); double D_GR = ccl_growth_factor_unnorm(cosmo_GR, aa[i], status); double renorm = D_mu/D_GR; rescale_factor[i] *= renorm*renorm; } rescale_extra_musig = rescale_factor[na-1]; if (*status) { *status = CCL_ERROR_PARAMETERS; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "could not make MG and GR growth.\n"); } } ccl_parameters_free(&params_GR); ccl_cosmology_free(cosmo_GR); } if(do_s8) { if (*status == 0) { double renorm = cosmo->params.sigma8/ccl_sigma8(cosmo, psp, status); renorm *= renorm; renorm /= rescale_extra_musig; for (int i=0; i<na; i++) rescale_factor[i] *= renorm; } } if (*status == 0) { size_t nk=0; if (psp->fka != NULL) nk=psp->fka->interp_object.xsize; // Rescale for (int i=0; i<na; i++) { if (psp->fa != NULL) { if(psp->is_log) psp->fa->y[i] += log(rescale_factor[i]); else psp->fa->y[i] *= rescale_factor[i]; } else { for(int j=0; j<nk; j++) { if(psp->is_log) psp->fka->zarr[i*nk+j] += log(rescale_factor[i]); else psp->fka->zarr[i*nk+j] *= rescale_factor[i]; } } } //Respline if(psp->fa != NULL) { gsl_spline *fa = gsl_spline_alloc(gsl_interp_cspline, psp->fa->size); if(fa == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "memory allocation\n"); } if(*status==0) { int spstatus = gsl_spline_init(fa, psp->fa->x, psp->fa->y, psp->fa->size); if(spstatus) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "Error initializing spline\n"); } } if(*status==0) { gsl_spline_free(psp->fa); psp->fa=fa; } } else { gsl_spline2d *fka = gsl_spline2d_alloc(gsl_interp2d_bicubic, psp->fka->interp_object.xsize, psp->fka->interp_object.ysize); if(fka == NULL) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "memory allocation\n"); } if(*status==0) { int spstatus = gsl_spline2d_init(fka, psp->fka->xarr, psp->fka->yarr, psp->fka->zarr, psp->fka->interp_object.xsize, psp->fka->interp_object.ysize); if(spstatus) { *status = CCL_ERROR_MEMORY; ccl_cosmology_set_status_message(cosmo, "ccl_musigma.c: ccl_rescale_musigma_s8(): " "Error initializing spline\n"); } } if(*status==0) { gsl_spline2d_free(psp->fka); psp->fka=fka; } } } free(rescale_factor); }
{ "alphanum_fraction": 0.5519230769, "avg_line_length": 30.9523809524, "ext": "c", "hexsha": "5c36cb56e3f31f087deb53bf5722eda4896ab5a9", "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": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "borisbolliet/CCL", "max_forks_repo_path": "src/ccl_musigma.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "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": "borisbolliet/CCL", "max_issues_repo_path": "src/ccl_musigma.c", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "borisbolliet/CCL", "max_stars_repo_path": "src/ccl_musigma.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2234, "size": 7800 }
#include "matrix_support.h" #include <cblas.h> int main(int argc, char *argv[]) { /* enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; */ /* enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; */ /* enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; */ /* enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; */ /* enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; */ CBLAS_ORDER order = CblasRowMajor; CBLAS_TRANSPOSE transA = CblasNoTrans; CBLAS_TRANSPOSE transB = CblasNoTrans; int m = 2; int k = 3; int n = 4; double alpha = 1; double beta = 1; double *A = create_matrix(m, k); double *B = create_matrix(k, n); double *C = create_matrix(m, n); double *D = create_matrix(n, k); double *x = create_vector(k); double *d = create_vector(m); printf("A\n"); init_matrix_vector(A, m * k, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); print_matrix(A, m, k); printf("\nB\n"); init_matrix_vector(B, k * n, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0); print_matrix(B, k, n); printf("\nD\n"); init_matrix_vector(D, n * k, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0); print_matrix(D, n, k); printf("\nx\n"); init_matrix_vector(x, k * 1, -2.0, 2.0, 10.0); print_vector(x, k); /* void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, */ /* const enum CBLAS_TRANSPOSE TransB, const int M, const int N, */ /* const int K, const double alpha, const double *A, */ /* const int lda, const double *B, const int ldb, */ /* const double beta, double *C, const int ldc); */ cblas_dgemm(order, transA, transB, m, n, k, alpha, A, k, B, n, beta, C, n); printf("\nC = A.dot(B)\n"); print_matrix(C, m, n); printf("\nd = A.dot(x)\n"); /* * dasum takes the sum of the absolute values */ /** * ddot dot product between two vectors */ /* * dnrm2 Eucledian norm of a vector */ /* * dscal scales a vector by a constant */ /* * daxpy constant times a vector plus a vector. uses unrolled loops for * increments equal to one. */ /* void cblas_dgemv(const enum CBLAS_ORDER order, */ /* const enum CBLAS_TRANSPOSE TransA, const int M, const int N, */ /* const double alpha, const double *A, const int lda, */ /* const double *X, const int incX, const double beta, */ /* double *Y, const int incY); */ cblas_dgemv(order, transA, // not transposed m, // rows of a k, // cols of a alpha, // scalar to multiply A with A, //matrix A k, // lda: leading dimension of A x, // vector x 1, // incx beta, // beta: scalar to multiply y with (0 having y as output) d, // vector d (Y in formula) 1); // incy print_vector(d, m); return 0; }
{ "alphanum_fraction": 0.5182481752, "avg_line_length": 29.8909090909, "ext": "c", "hexsha": "5d00e4ba6843ad99e30784cf1fd9fb57a1bdd057", "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": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chibby0ne/using_blas", "max_forks_repo_path": "c/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "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": "chibby0ne/using_blas", "max_issues_repo_path": "c/main.c", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chibby0ne/using_blas", "max_stars_repo_path": "c/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1036, "size": 3288 }
#include <config.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_fft_complex_float.h> #define BASE_FLOAT #include "templates_on.h" #include "c_pass.h" #include "c_init.c" #include "c_main.c" #include "c_pass_2.c" #include "c_pass_3.c" #include "c_pass_4.c" #include "c_pass_5.c" #include "c_pass_6.c" #include "c_pass_7.c" #include "c_pass_n.c" #include "bitreverse.c" #include "c_radix2.c" #include "templates_off.h" #undef BASE_FLOAT
{ "alphanum_fraction": 0.7335766423, "avg_line_length": 18.8965517241, "ext": "c", "hexsha": "ada9db42cb824fd984fa233abcc725f3506e34ad", "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/fft/c_float.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/fft/c_float.c", "max_line_length": 38, "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/fft/c_float.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": 162, "size": 548 }
#ifndef KGS_NULLSPACE_H #define KGS_NULLSPACE_H #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <string> #include <vector> #include "math/SVD.h" //#include "math/QR.h" class Molecule; //Forward declaration /** * Computes, stores, and maintains the nullspace of a gsl_matrix. * Supports projections of any gradient represented as a gsl_vector onto the null-space * and also analyzing and updating rigidity. Note that the Nullspace object only * accurately reflects the matrix (SVD) if the UpdateFromMatrix function has been called. * This is not done on construction. * * An SVD-pointer is passed to the Nullspace on construction. This pointer is kept through * the life-time of the Nullspace object (but ownership is not assumed) and if the contents * of the matrix is changed, the Nullspace can be update to reflect the change using the * abstract UpdateFromMatrix function. */ class Nullspace { protected: Nullspace(gsl_matrix* M); public: virtual ~Nullspace(); /** Projects a vector on the nullspace */ void projectOnNullSpace(gsl_vector *to_project, gsl_vector *after_project) const; /** Analyzes which dihedrals and hydrogen bonds are rigidified by constraints */ void performRigidityAnalysis(gsl_matrix *HBondJacobian,gsl_matrix *DBondJacobian,gsl_matrix *HydrophobicBondJacobian); /** Update the Nullspace (and underlying SVD/QR) to reflect an updated state of the matrix */ virtual void updateFromMatrix() = 0; /** Return the nullspace size */ int getNullspaceSize() const { return m_nullspaceSize; } /** Return number of cycle DOFs */ int getNumDOFs() const { return n; } /** Return number of dihedral DOFs that were rigidified in the last call to RigidityAnalysis. */ int getNumRigidDihedrals() const { return numRigidDihedrals; } /** Return number of h-bond dihedrals that were rigidified in the last call to RigidityAnalysis. */ int getNumRigidHBonds() const { return numRigidHBonds; } int getNumRigidDBonds() const { return numRigidDBonds; } int getNumRigidHydrophobicBonds() const { return numRigidHydrophobicBonds;} /** Return the underlying matrix. */ gsl_matrix* getMatrix() const{ return m_matrix; } /** Return the basis of the nullspace as columns of a matrix */ gsl_matrix *getBasis() const; /** * Returns true iff the angle specified by the argument is rigidified. * This result is only accurate if UpdateFromMatrix and RigidityAnalysis have both * been called. */ bool isCovBondRigid(int angle_id){ return fabs(gsl_vector_get(m_rigidCovBonds, angle_id)-1.0)<0.001; } bool isHBondRigid(int bond_id){ return fabs(gsl_vector_get(m_rigidHBonds, bond_id)-1.0)<0.001; } bool isDBondRigid(int bond_id){ return fabs(gsl_vector_get(m_rigidDBonds, bond_id)-1.0)<0.001; } bool isHydrophobicBondRigid(int bond_id){ return fabs(gsl_vector_get(m_rigidHydrophobicBonds,bond_id)-1.0)<0.001; } protected: int m_nullspaceSize; ///< Size of nullspace (rank of jacobian) int m, n; ///< Dimensions of underlying matrix (jacobian) gsl_matrix* m_matrix; ///< Original matrix. Only set if using QR decomp (as it needs to be transposed) gsl_matrix* m_nullspaceBasis;///< Basis of the nullspace private: gsl_vector* m_rigidCovBonds; ///< Binary vector indicating which m_dofs are rigid gsl_vector* m_rigidHBonds; ///< Binary vector indicating which h-bonds are rigid gsl_vector* m_rigidDBonds; ///< Binary vector indicating which d-bonds are rigid gsl_vector* m_rigidHydrophobicBonds; ///< Binary vector indicating which hydrophobic-bonds are rigid int numCoordinatedDihedrals; ///< Coordinated dihedrals int numRigidDihedrals; ///< Rigid dihedrals int numRigidHBonds;///< Rigid hydrogen bonds int numRigidDBonds;///< Rigid hydrogen bonds int numRigidHydrophobicBonds; ///< Rigid hydrophobic bonds /// These values have to be chosen according to the numerical analysis // static constexpr double SINGVAL_TOL = 1.0e-12; //0.000000000001; // only generic 10^-12 static constexpr double RIGID_TOL = 1.0e-9; //0.0000000001; //most molecules work between 1e-4 and 1e-10, exceptions only between 1e-8 and 1e-9 // friend class Configuration; }; #endif //KGS_nullptrSPACE_H
{ "alphanum_fraction": 0.7451990632, "avg_line_length": 39.537037037, "ext": "h", "hexsha": "640f597e629bfd35e8ab3df3d4f73706fe5f1ab1", "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": "9adbde319179cee13c2828628da6fdc3bb9923bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ExcitedStates/KGS", "max_forks_repo_path": "src/math/Nullspace.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "9adbde319179cee13c2828628da6fdc3bb9923bc", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ExcitedStates/KGS", "max_issues_repo_path": "src/math/Nullspace.h", "max_line_length": 147, "max_stars_count": 1, "max_stars_repo_head_hexsha": "9adbde319179cee13c2828628da6fdc3bb9923bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ExcitedStates/KGS", "max_stars_repo_path": "src/math/Nullspace.h", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "num_tokens": 1165, "size": 4270 }
/* Copyright [2019-2021] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CCPM_INTERFACES_H__ #define __CCPM_INTERFACES_H__ #include <common/byte_span.h> #include <common/types.h> #include <gsl/pointers> #include <cstddef> #include <functional> #include <vector> namespace ccpm { struct persister { using byte_span = common::byte_span; virtual void persist(byte_span span) = 0; protected: ~persister() {} }; /* * Ownership callback can resolve the ambiguity about area * ownership which occurs during phase (b) of allocate() and free() * Intended to be used by IHeap::reconstitute when a crash during * an IHeap::allocate or IHeap::free call has left area ownership * in doubt. * * In order to support ownership resolution, it is expected that a caller to * allocate or free will * (1) store and persist the initial value of ptr * (2) call allocate or free * * It is expected that IHeap::allocate() will * (1) determine an appropriate new value for ptr * (2) persist a note indicating that the allocation status of the new value * of ptr is indeterminate. * (3) store and persist the new value of ptr * (4) persist an invalidation of the note written in step 2. * * It is expected that IHeap::free() will * (1) persist a note indicating that the allocation status of the value * of ptr is indeterminate. * (2) store and persist nullptr as the new value of ptr * (3) return the area located by the original value of ptr to free status * (4) persist an invalidation of the note written in step 1. */ using ownership_callback_type = std::function<bool(const void * ptr)>; using ownership_callback_t = ownership_callback_type; inline bool accept_all(const void *) { return true; } /* * Allocators can expand to more than one coarse-grained region of * memory. */ struct region_vector_t : public std::vector<common::byte_span> { using base = std::vector<common::byte_span>; explicit region_vector_t(void * ptr_, std::size_t size_) : region_vector_t(common::make_byte_span(static_cast<common::byte *>(ptr_), size_)) {} explicit region_vector_t(const value_type &v) { push_back(v); } region_vector_t() { } const base &cbase() const { return *this; } }; using region_span = gsl::span<common::byte_span>; enum class Type_id : int64_t { None = 0, Fixed_array = 0xF0, }; /** * Heap allocator (variable sized allocations) */ class IHeap { public: virtual ~IHeap() {} /* Reconstitute/initialize slab from existing memory * * @param regions Pointer/length regions of contiguous memory * @param resolver Access to an object which can resolve the ambiguity * over area ownership which occurs during a phase of allocate() * and free() calls. If the callee of the ownership_callback_t * function might own the area located by the arument, the callee * must return true. If the callee does not own the area, it should * return false. * @param force_init If true, force re-setting to empty * * * @return : True if memory was reset to empty **/ virtual bool reconstitute(const region_span regions, ownership_callback_t resolver = [] (const void *) -> bool { return true; }, const bool force_init = false) = 0; /* Allocate memory * * @param ptr in/out: nullptr -> pointer to newly allocated memory * On a successful allocation the allocator will * first write and then persist ptr. Allocation * has three phases: * (a) ptr is not yet written; the allocator unambiguously * owns the free "area" the address of which it will * later write into ptr. * (b) allocator has written ptr, but has not yet persisted * ptr. Caller must be able to tell the allocator (see * reconstitute) whether caller has accepted ownership * of the allocated area. Acceptance is implicit. * Visibility of a non-null value in ptr, which happens * upon write in the non-crash case and upon persist in * the crash+reconstitute case, consititutes acceptance. * (c) allocator has persisted the ptr. Caller will know upon * successful return (normal case) or discovery of a * non-null value (crash+reconstitute case) that it owns * the area. * * The pointer shall be altered iff the function returns S_OK. * * @param size Size of memory to allocate in bytes * @param alignment Alignment for memory * * @return : S_OK, E_INVAL, E_BAD_PARAM, E_EMPTY **/ virtual status_t allocate(void * & ptr, std::size_t bytes, std::size_t alignment) = 0; /* Free previously allocated memory. * @param ptr in/out: Pointer to memory to free, which must have been previously * allocated with the same size and alignment. * On a successful free the allocator will first nullify ptr * and then persist ptr. Free has has three phases, similar * to allocation: * (a) ptr is not yet written; the caller unambiguously * owns the "area". * (b) allocator has nullified ptr, but has not yet persisted * ptr. Caller must be able to tell the allocator (see * reconstitute) whether caller has relinquished ownership * of the allocated area. Relinquishment is implicit. * Visibility of a null value in ptr, which happens upon * write in the non-crash case and upon persist in the * crash+reconstitute case, consititutes relinquishment. * (c) allocator has persisted the (null-valued) ptr. Caller * will know upon successful return (normal case) or * discovery of null value (crash+reconstitute case) that * the allocator now owns the area. * * The pointer shall be altered iff the function returns S_OK. * * @param size Size of memory to free in bytes * * @return : S_OK, E_INVAL **/ virtual status_t free(void * & ptr, std::size_t bytes = 0) = 0; /* Return remaining space in bytes * @param out_size Size remaining in bytes * * @return S_OK or E_NOT_IMPL **/ virtual status_t remaining(std::size_t& out_size) const = 0; /* Return a vector of all regions * * @return vector containing the initial regions and all subsequently added * regions, if the implementation keeps track of regions. Otherwise, an * empty region_vector_t. **/ virtual region_vector_t get_regions() const = 0; }; /** * Heap allocator (variable sized allocations) */ class IHeap_expandable : public IHeap { public: /* Add an additional regions to the heap * @param regions Pointer/length regions of contiguous memory **/ virtual void add_regions(const region_span regions) = 0; /** Test whether an address is in any heap region * @param addr the address to test * * @erturn true iff the address is in some heap region */ virtual bool includes(const void *ptr) const = 0; }; class ILog { public: virtual ~ILog() = default; /* * Record old value of a region to the log. */ virtual void add(void *begin, std::size_t size) = 0; /* * Record an allocation to the log. */ virtual void allocated(void *&p, std::size_t size) = 0; /* * Record a free to the log. */ virtual void freed(void *&p, std::size_t size) = 0; /* * commit all previous add/allocated/freed commands */ virtual void commit() = 0; /* * Restore all data areas added after initialization (or the most recent clear) * to the values present at their last add command. */ virtual void rollback() = 0; }; } #endif // __CCPM_INTERFACES_H__
{ "alphanum_fraction": 0.6270276317, "avg_line_length": 36.6352459016, "ext": "h", "hexsha": "370371288bc7f1de5552622ed5b3685f8d1222b3", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "omriarad/mcas", "max_forks_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_line_length": 103, "max_stars_count": 60, "max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "omriarad/mcas", "max_stars_repo_path": "src/lib/libccpm/include/ccpm/interfaces.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 2069, "size": 8939 }
/* block/gsl_block_uint.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_BLOCK_UINT_H__ #define __GSL_BLOCK_UINT_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS struct gsl_block_uint_struct { size_t size; unsigned int *data; }; typedef struct gsl_block_uint_struct gsl_block_uint; gsl_block_uint *gsl_block_uint_alloc (const size_t n); gsl_block_uint *gsl_block_uint_calloc (const size_t n); void gsl_block_uint_free (gsl_block_uint * b); int gsl_block_uint_fread (FILE * stream, gsl_block_uint * b); int gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b); int gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b); int gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format); int gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride); int gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride); int gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride); int gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format); size_t gsl_block_uint_size (const gsl_block_uint * b); unsigned int * gsl_block_uint_data (const gsl_block_uint * b); __END_DECLS #endif /* __GSL_BLOCK_UINT_H__ */
{ "alphanum_fraction": 0.7660393499, "avg_line_length": 35.4242424242, "ext": "h", "hexsha": "268cf15783ee2dd2311a9c77a8c7ff7bace2a201", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "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": "snipekill/FPGen", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_line_length": 128, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_block_uint.h", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "num_tokens": 605, "size": 2338 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_dcopy (const int N, const double *X, const int incX, double *Y, const int incY) { #define BASE double #include "source_copy_r.h" #undef BASE }
{ "alphanum_fraction": 0.7074235808, "avg_line_length": 17.6153846154, "ext": "c", "hexsha": "271d78fec0cf7dea4dea703d8dc4a4c36adc51f5", "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/dcopy.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/dcopy.c", "max_line_length": 69, "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/dcopy.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": 70, "size": 229 }
#pragma once #include <cassert> #include <cstdio> #include <cstdlib> #include <cfloat> #include <algorithm> #include <vector> #include <memory> #include <stdexcept> #include <map> #include <hip/hip_runtime.h> #include <hiprand_kernel.h> #include <gsl/gsl_assert.h> #include <nonstd/byte.hpp> #include <nonstd/expected.hpp> #include <nonstd/optional.hpp> #include <nonstd/span.hpp> #include <nonstd/ring_span.hpp> #include <nonstd/string_view.hpp> #include <nonstd/variant.hpp> #include <nonstd/value_ptr.hpp> #include "kernel_config.h" #include "logger.h" #include "math.h" using nonstd::variant; using nonstd::value_ptr; using nonstd::make_value; using nonstd::ring_span; using nonstd::expected; using nonstd::make_unexpected; using nonstd::optional; using nonstd::nullopt; using nonstd::make_optional; using nonstd::byte; using nonstd::to_integer; using nonstd::to_byte; using nonstd::to_string; using nonstd::string_view; using nonstd::span; using nonstd::make_span; using bytearray = std::vector<byte>; #define HIP_ASSERT(x) (Ensures((x)==hipSuccess)) struct hip_free_deleter { void operator()(void *p) const noexcept { hipFree(p); } }; template<typename T> using host_unique_ptr = std::unique_ptr<T, hip_free_deleter>; template<class T> struct _host_unique_if { typedef void _single_object; }; template<class T> struct _host_unique_if<T[]> { typedef host_unique_ptr<T[]> _unknown_bound; }; template<class T, std::size_t N> struct _host_unique_if<T[N]> { typedef void _known_bound; }; template<class T, class... Args> typename _host_unique_if<T>::_single_object hip_alloc_managed_unique(Args&&... args) = delete; template<class T> typename _host_unique_if<T>::_unknown_bound hip_alloc_managed_unique(std::size_t n) { typedef typename std::remove_extent<T>::type U; T *tmp; HIP_ASSERT(hipMallocManaged(&tmp, n * sizeof(U))); return host_unique_ptr<T>(reinterpret_cast<U*>(tmp)); } template<class T, class... Args> typename _host_unique_if<T>::_known_bound hip_alloc_managed_unique(Args&&...) = delete;
{ "alphanum_fraction": 0.7502439024, "avg_line_length": 24.6987951807, "ext": "h", "hexsha": "3e55968407980c42c47ed31f58b2a1498b17bb14", "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": "6b903970caa6eb56c642383c323a9bddf7b25629", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sargarass/Raytracer", "max_forks_repo_path": "src/common.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6b903970caa6eb56c642383c323a9bddf7b25629", "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": "sargarass/Raytracer", "max_issues_repo_path": "src/common.h", "max_line_length": 63, "max_stars_count": null, "max_stars_repo_head_hexsha": "6b903970caa6eb56c642383c323a9bddf7b25629", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sargarass/Raytracer", "max_stars_repo_path": "src/common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 524, "size": 2050 }
#ifndef _SPC_FITTING_H #define _SPC_FITTING_H #include <math.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_multifit.h> #include "aXe_errors.h" extern void comp_vector_average (const double *xs, double *ys, double *ws, double *yi, const int n, const int final); extern void comp_vector_median (const double *xs, double *ys, double *ws, double *yi, const int n, const int final); extern void comp_vector_linear (const double *xs, double *ys, double *ws, double *yi, const int n, const int final); extern void comp_vector_polyN (const int m, const double *xs, double *ys, double *ws, double *yi, const int n, const int final); extern void fill_const_value(double *ys, double *ws, double *yi, const int n, double cval, double stdev, const int final); extern void det_vector_average (const double *xs, double *ys, double *ws, const int n, double *avg, double *std); extern void det_vector_median (const double *xs, double *ys, double *ws, const int n, double *med, double *std); extern gsl_vector * det_vector_linear(const double *xs, double *ys, double *ws, const int n, const int weight); extern gsl_vector * det_vector_poly_N (int m, const double *const xs, double *const ys, double *const ws, const int n, gsl_vector *c, gsl_matrix *cov); extern void fill_linear_interp(const double *const xs, double *const ys, double *const ws, double *yi, const int n, gsl_vector *interp, const int final); extern void fill_polyN_interp(const double *const xs, double *const ys, double *const ws, double *yi, const int n, gsl_vector *coeffs, gsl_matrix *cov, gsl_vector *interp, const int final); #endif
{ "alphanum_fraction": 0.7106357695, "avg_line_length": 29.5263157895, "ext": "h", "hexsha": "971f39ea279c6b20de8202e3a035a4ba6fc77ad3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spce_fitting.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spce_fitting.h", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spce_fitting.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 459, "size": 1683 }
#ifndef VolViz_Types_h #define VolViz_Types_h #include <Eigen/Core> #include <Eigen/Geometry> #include <gsl/gsl> #include <phys/units/quantity.hpp> #include <array> namespace VolViz { using namespace gsl; using Vector3f = Eigen::Vector3f; using Matrix3 = Eigen::Matrix3f; using Matrix4 = Eigen::Matrix4f; /// Position in 3D euclidean space using Position = Eigen::Vector3f; /// Position in homogenous coordinates using PositionH = Eigen::Vector4f; /// Position in 2D space using Position2 = Eigen::Vector2f; using Size2 = Eigen::Matrix<std::size_t, 2, 1>; using Size3 = Eigen::Matrix<std::size_t, 3, 1>; using Size3f = Eigen::Vector3f; /// An 1D range template <class T> struct Range { T min, max; constexpr auto length() const noexcept { return max - min; } }; /// Normalized RGB color using Color = Eigen::Vector3f; namespace Colors { inline auto Black() noexcept { return Color::Zero(); } inline auto White() noexcept { return Color::Ones(); } inline auto Red() noexcept { return Color::UnitX(); } inline auto Green() noexcept { return Color::UnitY(); } inline auto Blue() noexcept { return Color::UnitZ(); } inline auto Yellow() noexcept { return Red() + Green(); } inline auto Magenta() noexcept { return Red() + Blue(); } inline auto Cyan() noexcept { return Blue() + Green(); } } /// 6-DOF orientation, represented as a quaternion using Orientation = Eigen::Quaternionf; struct DepthRange { float near{1.f}, far{-1.f}; }; enum class Axis { X, Y, Z }; using Scale = float; using Length = phys::units::quantity<phys::units::length_d>; using Angle = double; using PhysicalPosition = Eigen::Matrix<Length, 3, 1>; using phys::units::meter; using phys::units::rad; using phys::units::degree_angle; using phys::units::centi; using phys::units::milli; using phys::units::micro; using phys::units::nano; using phys::units::abs; namespace literals = phys::units::literals; using VoxelSize = std::array<Length, 3>; /// @brief Conveniance wrapper for span<> /// @{ template <class T> inline constexpr auto as_span(T *ptr, typename span<T>::index_type size) noexcept { return span<T>(ptr, size); } template < class Container, class = std::enable_if_t< !details::is_span<Container>::value && !details::is_std_array<Container>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> inline constexpr auto as_span(Container &c) { return span<typename Container::value_type>(c); } template < class Container, class = std::enable_if_t< !details::is_span<Container>::value && !details::is_std_array<Container>::value && std::is_convertible<typename Container::pointer, decltype(std::declval<Container>().data())>::value>> inline constexpr auto as_span(Container const &c) { return span<typename Container::value_type const>(c); } ///@} } // namespace VolViz #if __cplusplus < 201703L namespace std { template<class T> constexpr const T& clamp( const T& v, const T& lo, const T& hi ) { return clamp( v, lo, hi, std::less<>() ); } template<class T, class Compare> constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) { return assert( !comp(hi, lo) ), comp(v, lo) ? lo : comp(hi, v) ? hi : v; } } #endif #endif // VolViz_Types_h
{ "alphanum_fraction": 0.669300556, "avg_line_length": 25.125, "ext": "h", "hexsha": "c4ce5c3e99e47159b6be918969c3eb4d50f4d338", "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": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ithron/VolViz", "max_forks_repo_path": "include/VolViz/src/Types.h", "max_issues_count": 17, "max_issues_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_issues_repo_issues_event_max_datetime": "2016-10-28T12:23:59.000Z", "max_issues_repo_issues_event_min_datetime": "2016-06-09T07:38:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ithron/VolViz", "max_issues_repo_path": "include/VolViz/src/Types.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "e79f36563d908d9ba1bd71c3e760792521dd5e7a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ithron/VolViz", "max_stars_repo_path": "include/VolViz/src/Types.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 882, "size": 3417 }
/* min/test.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 <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include "test.h" #include "min.h" /* stopping parameters */ const double EPSABS = 0.001 ; const double EPSREL = 0.001 ; const unsigned int MAX_ITERATIONS = 100; void my_error_handler (const char *reason, const char *file, int line, int err); #define WITHIN_TOL(a, b, epsrel, epsabs) \ (fabs((a) - (b)) < (epsrel) * GSL_MIN(fabs(a), fabs(b)) + (epsabs)) int main (void) { gsl_function F_cos, F_func1, F_func2, F_func3, F_func4; const gsl_min_fminimizer_type * fminimizer[4] ; const gsl_min_fminimizer_type ** T; gsl_ieee_env_setup (); fminimizer[0] = gsl_min_fminimizer_goldensection; fminimizer[1] = gsl_min_fminimizer_brent; fminimizer[2] = gsl_min_fminimizer_quad_golden; fminimizer[3] = 0; F_cos = create_function (f_cos) ; F_func1 = create_function (func1) ; F_func2 = create_function (func2) ; F_func3 = create_function (func3) ; F_func4 = create_function (func4) ; gsl_set_error_handler (&my_error_handler); for (T = fminimizer ; *T != 0 ; T++) { test_f (*T, "cos(x) [0 (3) 6]", &F_cos, 0.0, 3.0, 6.0, M_PI); test_f (*T, "x^4 - 1 [-3 (-1) 17]", &F_func1, -3.0, -1.0, 17.0, 0.0); test_f (*T, "sqrt(|x|) [-2 (-1) 1.5]", &F_func2, -2.0, -1.0, 1.5, 0.0); test_f (*T, "func3(x) [-2 (3) 4]", &F_func3, -2.0, 3.0, 4.0, 1.0); test_f (*T, "func4(x) [0 (0.782) 1]", &F_func4, 0, 0.782, 1.0, 0.8); test_f_e (*T, "invalid range check [4, 0]", &F_cos, 4.0, 3.0, 0.0, M_PI); test_f_e (*T, "invalid range check [1, 1]", &F_cos, 1.0, 1.0, 1.0, M_PI); test_f_e (*T, "invalid range check [-1, 1]", &F_cos, -1.0, 0.0, 1.0, M_PI); } test_bracket("cos(x) [1,2]",&F_cos,1.0,2.0,15); test_bracket("sqrt(|x|) [-1,0]",&F_func2,-1.0,0.0,15); test_bracket("sqrt(|x|) [-1,-0.6]",&F_func2,-1.0,-0.6,15); test_bracket("sqrt(|x|) [-1,1]",&F_func2,-1.0,1.0,15); exit (gsl_test_summary ()); } void test_f (const gsl_min_fminimizer_type * T, const char * description, gsl_function *f, double lower_bound, double middle, double upper_bound, double correct_minimum) { int status; size_t iterations = 0; double m, a, b; double x_lower, x_upper; gsl_min_fminimizer * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_min_fminimizer_alloc (T) ; gsl_min_fminimizer_set (s, f, middle, x_lower, x_upper) ; do { iterations++ ; 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); #ifdef DEBUG printf("%.12f %.18f %.12f %.18f %.12f %.18f status=%d\n", a, GSL_FN_EVAL(f, a), m, GSL_FN_EVAL(f, m), b, GSL_FN_EVAL(f, b), status); #endif if (a > b) gsl_test (GSL_FAILURE, "interval is invalid (%g,%g)", a, b); if (m < a || m > b) gsl_test (GSL_FAILURE, "m lies outside interval %g (%g,%g)", m, a, b); if (status) break ; status = gsl_min_test_interval (a, b, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (status, "%s, %s (%g obs vs %g expected) ", gsl_min_fminimizer_name(s), description, gsl_min_fminimizer_x_minimum(s), correct_minimum); /* check the validity of the returned result */ if (!WITHIN_TOL (m, correct_minimum, EPSREL, EPSABS)) { gsl_test (GSL_FAILURE, "incorrect precision (%g obs vs %g expected)", m, correct_minimum); } gsl_min_fminimizer_free (s); } void test_f_e (const gsl_min_fminimizer_type * T, const char * description, gsl_function *f, double lower_bound, double middle, double upper_bound, double correct_minimum) { int status; size_t iterations = 0; double x_lower, x_upper; double a, b; gsl_min_fminimizer * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_min_fminimizer_alloc (T) ; status = gsl_min_fminimizer_set (s, f, middle, x_lower, x_upper) ; if (status != GSL_SUCCESS) { gsl_min_fminimizer_free (s) ; gsl_test (status == GSL_SUCCESS, "%s, %s", T->name, description); return ; } do { iterations++ ; gsl_min_fminimizer_iterate (s); a = gsl_min_fminimizer_x_lower(s); b = gsl_min_fminimizer_x_upper(s); status = gsl_min_test_interval (a, b, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (!status, "%s, %s", gsl_min_fminimizer_name(s), description, gsl_min_fminimizer_x_minimum(s) - correct_minimum); gsl_min_fminimizer_free (s); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err); } int test_bracket (const char * description,gsl_function *f,double lower_bound, double upper_bound, unsigned int max) { int status; double x_lower, x_upper; double f_upper,f_lower,f_minimum; double x_minimum; x_lower=lower_bound; x_upper=upper_bound; SAFE_FUNC_CALL (f,x_lower,&f_lower); SAFE_FUNC_CALL (f,x_upper,&f_upper); status=gsl_min_find_bracket(f,&x_minimum,&f_minimum,&x_lower,&f_lower,&x_upper,&f_upper,max); gsl_test (status,"%s, interval: [%g,%g], values: (%g,%g), minimum at: %g, value: %g", description,x_lower,x_upper,f_lower,f_upper,x_minimum,f_minimum); return status; }
{ "alphanum_fraction": 0.6454121306, "avg_line_length": 29.6313364055, "ext": "c", "hexsha": "d9b037d27c343608b3064ef37bb031c44dd80195", "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/min/test.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/min/test.c", "max_line_length": 95, "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/min/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 2065, "size": 6430 }
#include "userFunc.h" #include <math.h> #include <gsl/gsl_sf_bessel.h> /**************************************************************************/ /* This defines userFunc routines for the Pringle (1981) ring test */ /**************************************************************************/ 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) { /* alpha = nu col/pres vphi / r */ int i; double nu = *((double *) params); for (i=0; i<grd->nr; i++) alpha[i] = nu * col[i]/pres[i] * grd->vphi_g[i+1] / grd->r_g[i+1]; } 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) { fprintf(stderr, "Warning: userMassSrc function called but not implemented!\n"); return; } 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) { fprintf(stderr, "Warning: userIntEnSrc function called but not implemented!\n"); return; } 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) { double nu = ((double *) params)[0]; double r0 = ((double *) params)[1]; double m0 = ((double *) params)[2]; double colMin = ((double *) params)[3]; double pOverCol = ((double *) params)[4]; double x = grd->r_g[0]/r0; double tau = 12.0*nu*t/SQR(r0) + SMALL; double sigma0 = m0/(M_PI*SQR(r0)); double sigma; sigma = sigma0/(pow(x, 0.25)*tau) * exp(-SQR(x-1.0)/tau) * gsl_sf_bessel_Inu_scaled(0.25, 2*x/tau); sigma = (sigma < colMin) ? colMin : sigma; *ibc_pres_val = -3.0*M_PI*grd->r_g[0]*nu*grd->vphi_g[0]*sigma; *ibc_enth_val = gamma[0]/(gamma[0]-1)*pOverCol; } 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) { double nu = ((double *) params)[0]; double r0 = ((double *) params)[1]; double m0 = ((double *) params)[2]; double colMin = ((double *) params)[3]; double pOverCol = ((double *) params)[4]; double x = grd->r_g[grd->nr+1]/r0; double tau = 12.0*nu*t/SQR(r0) + SMALL; double sigma0 = m0/(M_PI*SQR(r0)); double sigma; sigma = sigma0/(pow(x, 0.25)*tau) * exp(-SQR(x-1.0)/tau) * gsl_sf_bessel_Inu_scaled(0.25, 2*x/tau); sigma = (sigma < colMin) ? colMin : sigma; *obc_pres_val = -3.0*M_PI*grd->r_g[grd->nr+1]*nu* grd->vphi_g[grd->nr+1]*sigma; *obc_enth_val = gamma[0]/(gamma[0]-1)*pOverCol; } 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.6457667732, "avg_line_length": 31.3, "ext": "c", "hexsha": "fdb71f804a765b28d4ea00458cba6a866793a348", "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_ring.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_ring.c", "max_line_length": 76, "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_ring.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1515, "size": 5008 }
#ifndef SOURCE_ROBUSTNESSMAIN_H_ #define SOURCE_ROBUSTNESSMAIN_H_ // *** source/robustness_main.h *** // Author: Kevin Wolz, date: 08/2018 // // Numerical sampling of the Robustness distribution (GP and WPL). #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <stdlib.h> #include <sys/stat.h> #include <ctime> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "utils.h" #include "lin_gauss.h" #include "rob_analyt.h" #include "print_to_file.h" #include "parse_from_init_file.h" double RobustnessWeakPriorLimit(double chi_squared_1, // subset 1 double chi_squared_2, // subset 2 double chi_squared_tot, // total data double det_fisher_1, // determinants double det_fisher_2, double det_fisher_tot, double det_prior); double RobustnessGeneralPrior(double chi_squared_1, double chi_squared_2, double chi_squared_tot, gsl_matrix* fisher_matrix_1, gsl_matrix* fisher_matrix_2, gsl_matrix* prior_matrix, gsl_vector* param_values_1, // fiducial parameters gsl_vector* param_values_2, gsl_vector* param_values_tot, gsl_vector* prior_param_values,// prior parameters unsigned int pardim); // number of parameters int NumericalSamplingOfRobustness(unsigned int repetitions, // number of samples unsigned int datdim, // number of data points bool is_weak_prior_limit, LinGauss model1, // subset 1 LinGauss model2, // subset 2 LinGauss model_tot, // total data std::string& filepath); // path of data logs #endif // SOURCE_ROBUSTNESSMAIN_H_
{ "alphanum_fraction": 0.5419407895, "avg_line_length": 36.8484848485, "ext": "h", "hexsha": "04788522157481a7bf5e8ae650e8bd8ef30a948f", "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": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kevguitar/Robustness", "max_forks_repo_path": "source/robustness_main.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "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": "kevguitar/Robustness", "max_issues_repo_path": "source/robustness_main.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kevguitar/Robustness", "max_stars_repo_path": "source/robustness_main.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 495, "size": 2432 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef string_81448b68_30d7_4d64_a67a_cecef7c90139_h #define string_81448b68_30d7_4d64_a67a_cecef7c90139_h #include <string> #include <assert.h> #include <gslib/type.h> __gslib_begin__ template<class _element> class _std_string: public std::basic_string<_element, std::char_traits<_element>, std::allocator<_element> > { public: typedef _element protoch; typedef std::char_traits<protoch> prototr; typedef std::allocator<protoch> protoalloc; typedef std::basic_string<protoch, prototr, protoalloc> protoref; friend gs_export int _vsprintf(_std_string<char>& str, const char* fmt, va_list ap); friend gs_export int _vsprintf(_std_string<wchar>& str, const wchar* fmt, va_list ap); }; template<class _element> struct _string_tool { typedef _element element; }; template<> struct _string_tool<char> { static void copy(char* des, size_t size, const char* src) { strcpy_s(des, size, src); } static int length(const char* str) { return (int)strlen(str); } static int compare(const char* s1, const char* s2) { return (int)strcmp(s1, s2); } static int compare_cl(const char* s1, const char* s2) { return (int)_stricmp(s1, s2); } static int compare(const char* s1, const char* s2, int cnt) { return (int)strncmp(s1, s2, cnt); } static int compare_cl(const char* s1, const char* s2, int cnt) { return (int)_strnicmp(s1, s2, cnt); } static int vprintf(char* des, int size, const char* fmt, va_list ap) { return _vsprintf_s_l(des, size, fmt, 0, ap); } static int printf(char* des, int size, const char* fmt, ...) { va_list ptr; va_start(ptr, fmt); return _vsprintf_s_l(des, size, fmt, 0, ptr); } static int vsscanf(const char* src, const char* fmt, va_list ap) { return vsscanf_s(src, fmt, ap); } static int sscanf(const char* src, const char* fmt, ...) { va_list ptr; va_start(ptr, fmt); return vsscanf_s(src, fmt, ptr); } static int ctlprintf(const char* src, ...) { va_list ptr; va_start(ptr, src); return ::vprintf(src, ptr); } static int to_int(const char* src) { return atoi(src); } static int to_int(const char* src, int radix) { return strtol(src, 0, radix); } static uint to_uint(const char* src, int radix) { return strtoul(src, 0, radix); } static int64 to_int64(const char* src) { return _atoi64(src); } static int64 to_int64(const char* src, int radix) { return _strtoi64(src, 0, radix); } static uint64 to_uint64(const char* src, int radix) { return _strtoui64(src, 0, radix); } static real to_real(const char* src) { return atof(src); } static void from_int(int i, char* des, int size, int radix) { _itoa_s(i, des, size, radix); } static void from_int64(int64 i, char* des, int size, int radix) { _i64toa_s(i, des, size, radix); } static void from_real(char* des, int size, real d) { from_real(des, size, d, size-2); } static void from_real(char* des, int size, real d, int precis) { _gcvt_s(des, size, d, precis); } static void to_lower(char* str, int size) { _strlwr_s(str, size); } static void to_upper(char* str, int size) { _strupr_s(str, size); } static const char* find(const char* src, const char* tar) { return strstr(src, tar); } static int test(const char* src, const char* cpset) { return (int)strcspn(src, cpset); } static const char* _test(const char* src, const char* cpset) { return strpbrk(src, cpset); } }; template<> struct _string_tool<wchar> { static void copy(wchar* des, size_t size, const wchar* src) { wcscpy_s(des, size, src); } static int length(const wchar* str) { return (int)wcslen(str); } static int compare(const wchar* s1, const wchar* s2) { return (int)wcscmp(s1, s2); } static int compare_cl(const wchar* s1, const wchar* s2) { return (int)_wcsicmp(s1, s2); } static int compare(const wchar* s1, const wchar* s2, int cnt) { return (int)wcsncmp(s1, s2, cnt); } static int compare_cl(const wchar* s1, const wchar* s2, int cnt) { return (int)_wcsnicmp(s1, s2, cnt); } static int vprintf(wchar* des, int size, const wchar* fmt, va_list ap) { return _vswprintf_s_l(des, size, fmt, 0, ap); } static int printf(wchar* des, int size, const wchar* fmt, ...) { va_list ptr; va_start(ptr, fmt); return _vswprintf_s_l(des, size, fmt, 0, ptr); } static int vsscanf(const wchar* src, const wchar* fmt, va_list ap) { return vswscanf_s(src, fmt, ap); } static int sscanf(const wchar* src, const wchar* fmt, ...) { va_list ptr; va_start(ptr, fmt); return vswscanf_s(src, fmt, ptr); } static int ctlprintf(const wchar* src, ...) { va_list ptr; va_start(ptr, src); return ::vwprintf(src, ptr); } static int to_int(const wchar* src) { return _wtoi(src); } static int to_int(const wchar* src, int radix) { return wcstol(src, 0, radix); } static uint to_uint(const wchar* src, int radix) { return wcstoul(src, 0, radix); } static int64 to_int64(const wchar* src) { return _wtoi64(src); } static int64 to_int64(const wchar* src, int radix) { return _wcstoi64(src, 0, radix); } static uint64 to_uint64(const wchar* src, int radix) { return _wcstoui64(src, 0, radix); } static real to_real(const wchar* src) { return _wtof(src); } static void from_int(int i, wchar* des, int size, int radix) { _itow_s(i, des, size, radix); } static void from_int64(int64 i, wchar* des, int size, int radix) { _i64tow_s(i, des, size, radix); } static void from_real(wchar* des, int size, real d) { from_real(des, size, d, size-2); } static void from_real(wchar* des, int size, real d, int precis) { _gcvt_s((char*)des, size, d, precis); int len = (int)strlen((char*)des); /* call it in asm wasn't available in /o2 */ __asm { mov ecx, len; mov esi, des; add esi, ecx; mov edi, esi; add edi, ecx; mov word ptr[edi], 0; std; rptag: movsb; mov byte ptr[edi], 0; dec edi; loop rptag; cld; } } static void to_lower(wchar* str, int size) { _wcslwr_s(str, size); } static void to_upper(wchar* str, int size) { _wcsupr_s(str, size); } static const wchar* find(const wchar* src, const wchar* tar) { return wcsstr(src, tar); } static int test(const wchar* src, const wchar* cpset) { return (int)wcsspn(src, cpset); } static const wchar* _test(const wchar* src, const wchar* cpset) { return wcspbrk(src, cpset); } }; gs_export extern const char* get_mbcs_elem(const char* str, uint& c); gs_export extern const char* get_mbcs_elem(const char* str, uint& c, const char* end); gs_export extern int convert_to_wide(wchar out[], int size, const char* str, int len = -1); gs_export extern int convert_to_byte(char out[], int size, const wchar* str, int len = -1); gs_export extern int convert_utf8_to_wide(wchar out[], int size, const char* str, int len = -1); gs_export extern int convert_wide_to_utf8(char out[], int size, const wchar* str, int len = -1); struct _string_caseful {}; struct _string_caseless {}; template<class _element, class _cpcase = _string_caseful> class _string: public _std_string<_element> { public: typedef _element element; typedef _std_string<element> inheritref; typedef _string_tool<element> _strtool; typedef typename inheritref::protoref protoref; typedef _string<_element, _cpcase> myref; template<class _cpcase> static int comparefunc(const _string* s, const element* str); template<class _cpcase> static int comparefunc(const _string* s, const element* str, int len); template<> static int comparefunc<_string_caseful>(const _string* s, const element* str) { return _strtool::compare(s->c_str(), str); } template<> static int comparefunc<_string_caseless>(const _string* s, const element* str) { return _strtool::compare_cl(s->c_str(), str); } template<> static int comparefunc<_string_caseful>(const _string* s, const element* str, int len) { return _strtool::compare(s->c_str(), str, len); } template<> static int comparefunc<_string_caseless>(const _string* s, const element* str, int len) { return _strtool::compare_cl(s->c_str(), str, len); } protected: #ifdef _MSC_VER #if (_MSC_VER >= 1920) element* _stl_rawstr() { return const_cast<element*>(c_str()); } const element* _stl_rawstr() const { return c_str(); } #elif (_MSC_VER >= 1914) element* _stl_rawstr() { return this->_Get_data()._Myptr(); } const element* _stl_rawstr() const { return this->_Get_data()._Myptr(); } #else element* _stl_rawstr() { return this->_Myptr(); } const element* _stl_rawstr() const { return this->_Myptr(); } #endif #if (_MSC_VER >= 1920) int _stl_cap() const { return (int)capacity(); } void _stl_fix() { resize(_strtool::length(c_str())); } #elif (_MSC_VER >= 1914) int& _stl_cap() { return (int&)this->_Get_data()._Myres; } int& _stl_size() { return (int&)this->_Get_data()._Mysize; } void _stl_fix() { this->_stl_size() = _strtool::length(this->c_str()); } #elif ((_MSC_VER >= 1900) && (_MSC_VER < 1910)) int& _stl_cap() { return (int&)this->_Myres(); } int& _stl_size() { return (int&)this->_Mysize(); } void _stl_fix() { this->_Mysize() = (size_t)_strtool::length(this->c_str()); } #else int& _stl_cap() { return (int&)this->_Myres; } int& _stl_size() { return (int&)this->_Mysize; } void _stl_fix() { this->_Mysize = (size_t)_strtool::length(this->c_str()); } #endif #if (_MSC_VER >= 1920) void _stl_eos(int pos) { this->resize(pos); } #else void _stl_eos(int pos) { this->_Eos(pos); } #endif #endif /* endif _MSC_VER */ private: template<class _element> void convert_from(const wchar* str); template<class _element> void convert_from(const char* str); template<> void convert_from<wchar>(const wchar* str) { assign(str); } template<> void convert_from<char>(const wchar* str) { int len = convert_to_byte(0, 0, str); resize(len); convert_to_byte(_stl_rawstr(), len, str); _stl_fix(); } template<> void convert_from<wchar>(const char* str) { int len = convert_to_wide(0, 0, str); resize(len); convert_to_wide(_stl_rawstr(), len, str); _stl_fix(); } template<> void convert_from<char>(const char* str) { assign(str); } template<class _element> void convert_from(const char* str, int len); template<class _element> void convert_from(const wchar* str, int len); template<> void convert_from<wchar>(const wchar* str, int len) { assign(str, len); } template<> void convert_from<wchar>(const char* str, int len) { int l = convert_to_wide(0, 0, str, len); resize(l + 1); convert_to_wide(_stl_rawstr(), l, str, len); _stl_eos(l); } template<> void convert_from<char>(const wchar* str, int len) { int l = convert_to_byte(0, 0, str, len); resize(l + 1); convert_to_byte(_stl_rawstr(), l, str, len); _stl_eos(l); } template<> void convert_from<char>(const char* str, int len) { assign(str, len); } public: _string() {} _string(const element* str) { if(str) this->assign(str); } _string(const element* str, int len) { if(str) this->assign(str, len); } _string(element c, int ctr) { this->assign(ctr, c); } void destroy() { clear(); } int length() const { return (int)this->size(); } element& front() { return this->at(0); } const element& front() const { return this->at(0); } element& back() { return this->at(this->size() - 1); } const element& back() const { return this->at(this->size() - 1); } element pop_back() { element e = back(); resize(this->size() - 1); return e; } int test(const element* cpset) const { if(this->empty()) return (int)this->npos; int pos = _strtool::test(this->c_str(), cpset); if(pos == length()) return (int)this->npos; return pos; } int test(int off, const element* cpset) const { if(this->empty() || off >= length()) return (int)this->npos; int pos = _strtool::test(this->c_str() + off, cpset); if(pos == length()) return (int)this->npos; return pos; } const element* _test(const element* cpset) const { if(this->empty()) return nullptr; return _strtool::_test(this->c_str(), cpset); } const element* _test(int off, const element* cpset) const { if(this->empty() || off >= length()) return nullptr; return _strtool::_test(this->c_str() + off, cpset); } void format(const element* fmt, ...) { va_list ptr; va_start(ptr, fmt); _vsprintf(*this, fmt, ptr); } void formatv(const element* fmt, va_list ptr) { _vsprintf(*this, fmt, ptr); } /* void format(int size, const element* fmt, ...) { _stl_grow(size, false); va_list ptr; va_start(ptr, fmt); _stl_size() = _strtool::vprintf(_stl_rawstr(), _stl_cap(), fmt, ptr); } */ _string& to_lower() { if(this->empty()) return *this; _strtool::to_lower(_stl_rawstr(), _stl_cap()); return *this; } _string& to_upper() { if(this->empty()) return *this; _strtool::to_upper(_stl_rawstr(), _stl_cap()); return *this; } int to_int() const { return _strtool::to_int(_stl_rawstr()); } int to_int(int radix) const { return _strtool::to_int(_stl_rawstr(), radix); } int64 to_int64() const { return _strtool::to_int64(_stl_rawstr()); } int64 to_int64(int radix) const { return _strtool::to_int64(_stl_rawstr(), radix); } real to_real() const { return _strtool::to_real(_stl_rawstr()); } _string& from(const char* str) { convert_from<element>(str); return *this; } _string& from(const wchar* str) { convert_from<element>(str); return *this; } _string& from(const char* str, int len) { convert_from<element>(str, len); return *this; } _string& from(const wchar* str, int len) { convert_from<element>(str, len); return *this; } _string& from_int(int i, int radix = 10) { resize(12); _strtool::from_int(i, _stl_rawstr(), _stl_cap(), radix); _stl_fix(); return *this; } _string& from_int64(int64 i, int radix = 10) { resize(24); _strtool::from_int64(i, _stl_rawstr(), _stl_cap(), radix); _stl_fix(); return *this; } _string& from_real(real d, int precis = 22) { resize(precis + 2); _strtool::from_real(_stl_rawstr(), _stl_cap(), d, precis); _stl_fix(); return *this; } bool starts_with(const element* str, int len) const { assert(str); int s = length(); if(len > s) return false; return compare(str, len) == 0; } bool ends_with(const element* str, int len) const { assert(str); int s = length(); if(len > s) return false; return compare(str + s - len, len) == 0; } bool starts_with(const element* str) const { return starts_with(str, _strtool::length(str)); } bool starts_with(const myref& str) const { return starts_with(str.c_str(), str.length()); } bool starts_with(const myref& str, int len) const { return starts_with(str.c_str(), len); } bool ends_with(const element* str) const { return ends_with(str, _strtool::length(str)); } bool ends_with(const myref& str) const { return ends_with(str.c_str(), str.length()); } bool ends_with(const myref& str, int len) const { return ends_with(str.c_str(), len); } int compare(const element* str) const { return _strtool::compare(_stl_rawstr(), str); } int compare(const element* str, int len) const { return _strtool::compare(_stl_rawstr(), str, len); } int compare(int off, const element* str, int len) const { return _strtool::compare(_stl_rawstr() + off, str, len); } int compare_cl(const element* str) const { return _strtool::compare_cl(_stl_rawstr(), str); } int compare_cl(const element* str, int len) const { return _strtool::compare_cl(_stl_rawstr(), str, len); } int compare_cl(int off, const element* str, int len) const { return _strtool::compare_cl(_stl_rawstr() + off, str, len); } bool greater(const element* str) const { return comparefunc<_cpcase>(this, str) > 0; } bool greater(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) > 0; } bool equal(const element* str) const { return comparefunc<_cpcase>(this, str) == 0; } bool equal(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) == 0; } bool less(const element* str) const { return comparefunc<_cpcase>(this, str) < 0; } bool less(const element* str, int len) const { return comparefunc<_cpcase>(this, str, len) < 0; } bool operator < (const element* str) const { return less(str); } bool operator < (const _string* str) const { return less(str->c_str(), str->length()); } bool operator < (const _string& str) const { return less(str.c_str(), str.length()); } bool operator == (const element* str) const { return equal(str); } bool operator == (const _string* str) const { return equal(str->c_str(), str->length()); } bool operator == (const _string& str) const { return equal(str.c_str(), str.length()); } bool operator != (const element* str) const { return !equal(str); } bool operator != (const _string* str) const { return !equal(str->c_str(), str->length()); } bool operator != (const _string& str) const { return !equal(str.c_str(), str.length()); } bool operator > (const element* str) const { return greater(str); } bool operator > (const _string* str) const { return greater(str->c_str(), str->length()); } bool operator > (const _string& str) const { return greater(str.c_str(), str.length()); } }; typedef _string_tool<gchar> strtool; /* * string compare tool for short const string, notify that the s1 increase: * string symmetrical check */ template<class _element> class strsymcheck { public: typedef _element mchar; typedef strsymcheck<mchar> mref; public: template<int _len> static bool check(const mchar* s1, const mchar* s2) { return *s1 ++ == *s2 ++ && mref::check<_len-1>(s1, s2); } template<> static bool check<0>(const mchar* s1, const mchar* s2) { return true; } template<> static bool check<1>(const mchar* s1, const mchar* s2) { return *s1 ++ == *s2 ++; } template<int _len> static bool check_run(const mchar*& s1, const mchar* s2) { if(check<_len>(s1, s2)) { s1 += _len; return true; } return false; } }; #ifdef _cstrcmp #undef _cstrcmp #endif #define _cstrcmp(sr, cmp) strsymcheck<gchar>::check<_cststrlen(cmp)>((sr), (cmp)) #define _cstrncmp(sr, len, cmp) \ ((len >= _cststrlen(cmp)) && strsymcheck<gchar>::check<_cststrlen(cmp)>((sr), (cmp))) #ifdef _cstrcmprun #undef _cstrcmprun #endif #define _cstrcmprun(sr, cmp) strsymcheck<gchar>::check_run<_cststrlen(cmp)>((sr), (cmp)) #define mkstr(str1, str2) (((string(str1) += str2)).c_str()) #define mkstr3(str1, str2, str3) (((string(str1) += str2) += str3).c_str()) #define mkstr4(str1, str2, str3, str4) ((((string(str1) += str2) += str3) += str4).c_str()) template<int _cmpstr> inline bool strequ(const char* str) { return *(const int*)str == _cmpstr; } template<char _cmpch> inline bool chequ(const char* str) { return *str == _cmpch; } template<char _c1, char _c2> struct chless { static const bool result = _c1 < _c2; }; template<char _c1, char _c2, bool _less = chless<_c1, _c2>::result> struct chmin {}; template<char _c1, char _c2> struct chmin<_c1, _c2, true> { static const char value = _c1; }; template<char _c1, char _c2> struct chmin<_c1, _c2, false> { static const char value = _c2; }; template<char _c1, char _c2, bool _less = chless<_c1, _c2>::result> struct chmax {}; template<char _c1, char _c2> struct chmax<_c1, _c2, true> { static const char value = _c2; }; template<char _c1, char _c2> struct chmax<_c1, _c2, false> { static const char value = _c1; }; template<int _len> inline char strhit(const char* str, const char* cmp) { return *str == *cmp++ ? *str : strhit<_len + 1>(str, cmp); } template<> inline char strhit<1>(const char* str, const char* cmp) { return *str == *cmp ? *str : 0; } template<> inline char strhit<0>(const char* str, const char* cmp) { return *str; } template<char _from, char _to> char strhit(const char* str) { return (*str >= chmin<_from, _to>::value && *str <= chmax<_from, _to>::value) ? *str : 0; } /* used by the tool chain. */ inline int conv_quadstr(const char* str) { int n = 0; if(str[0] == 0) return n; n |= str[0]; if(str[1] == 0) return n; n |= ((uint)str[1]) << 8; if(str[2] == 0) return n; n |= ((uint)str[2]) << 16; if(str[3] == 0) return n; n |= ((uint)str[3]) << 24; return n; } inline char _1of_quadstr(int quadstr) { return (char)(quadstr & 0xff); } inline char _2of_quadstr(int quadstr) { return (char)((quadstr & 0xff00) >> 8); } inline char _3of_quadstr(int quadstr) { return (char)((quadstr & 0xff0000) >> 16); } inline char _4of_quadstr(int quadstr) { return (char)((quadstr & 0xff000000) >> 24); } inline int len_of_quadstr(int quadstr) { if(!(quadstr & 0xff)) return 0; if(!(quadstr & 0xff00)) return 1; if(!(quadstr & 0xff0000)) return 2; return (quadstr & 0xff000000) ? 4 : 3; } inline int utf8_unit_len(const char* str) { if(str[0] == 0) return 0; if(!(str[0] & 0x80)) return 1; if((str[0] & 0xe0) == 0xc0) return 2; if((str[0] & 0xf0) == 0xe0) return 3; if((str[0] & 0xf8) == 0xf0) return 4; if((str[0] & 0xfc) == 0xf8) return 5; if((str[0] & 0xfe) == 0xfc) return 6; return -1; } inline bool is_utf8_head(const char* str) { assert(str); return (str[0] & 0xc0) != 0x80; } inline const char* to_utf8_head(const char* str) { assert(str); for( ; str[0] && !is_utf8_head(str); str --); return str; } inline const char* next_utf8_unit(const char* str) { assert(str); if(str[0] == 0) return str; for(str ++; !is_utf8_head(str); str ++); return str; } inline const char* prev_utf8_unit(const char* str) { assert(str); return to_utf8_head(-- str); } inline bool utf8_unit_valid(const char* str) { assert(str); return !is_utf8_head(str) ? false : next_utf8_unit(str) - str == utf8_unit_len(str); } inline int utf8_len(const char* str) { assert(str); int len = 0; for( ; str[0]; str = next_utf8_unit(str), len ++); return len; } class string: public _string<gchar> { public: typedef std::basic_string<gchar> stdstr; typedef _string<gchar> superref; typedef superref::iterator iterator; typedef superref::const_iterator const_iterator; typedef superref::protoref protoref; public: using superref::npos; using superref::begin; using superref::c_str; using superref::capacity; using superref::compare; using superref::copy; using superref::empty; using superref::find; using superref::find_first_not_of; using superref::find_first_of; using superref::find_last_not_of; using superref::find_last_of; using superref::max_size; using superref::operator+=; using superref::operator=; using superref::rbegin; using superref::reserve; using superref::rfind; using superref::substr; using superref::test; using superref::_test; using superref::to_lower; using superref::to_upper; using superref::to_int; using superref::to_int64; using superref::to_real; using superref::compare_cl; using superref::greater; using superref::less; using superref::equal; using superref::operator<; using superref::operator>; using superref::operator!=; using superref::operator==; using superref::front; using superref::back; using superref::assign; using superref::append; using superref::clear; using superref::erase; using superref::insert; using superref::push_back; using superref::replace; using superref::resize; using superref::swap; using superref::at; using superref::operator[]; using superref::format; using superref::from_int; using superref::from_int64; using superref::from_real; using superref::length; using superref::pop_back; public: string() {} string(const gchar* str): superref(str) {} string(const gchar* str, int len): superref(str, len) {} string(gchar ch, int cnt): superref(ch, cnt) {} string(protoref& rhs) { assign(rhs.c_str(), (int)rhs.size()); } int size() const { return (int)superref::size(); } bool operator<(const string& str) const { return less(str.c_str(), str.length()); } bool operator>(const string& str) const { return greater(str.c_str(), str.length()); } bool operator==(const string& str) const { return equal(str.c_str(), str.length()); } bool operator!=(const string& str) const { return !equal(str.c_str(), str.length()); } }; inline bool is_mbcs_half(const char* str) { if(!str || !(str[0] & 0x80)) return false; int i = 1; for( ; str[i] && (str[i] & 0x80); i ++); return i % 2 != 0; } inline const gchar* get_next_char(const gchar* str, uint& c) { #ifdef _UNICODE if(!str || !str[0]) { c = 0; return 0; } c = (uint)str[0]; return ++ str; #else return get_mbcs_elem(str, c); #endif } inline const gchar* get_next_char(const gchar* str, uint& c, const gchar* end) { #ifdef _UNICODE if(!str || str == end) { c = 0; return 0; } c = (uint)str[0]; return ++ str; #else return get_mbcs_elem(str, c, end); #endif } __gslib_end__ #endif
{ "alphanum_fraction": 0.6184608885, "avg_line_length": 38.4384303112, "ext": "h", "hexsha": "a01c74c8802f296ec612857acf2f305d90968dde", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/string.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/string.h", "max_line_length": 158, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/string.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 8104, "size": 28406 }
/* vector/gsl_vector_int.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_INT_H__ #define __GSL_VECTOR_INT_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_int.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; int *data; gsl_block_int *block; int owner; } gsl_vector_int; typedef struct { gsl_vector_int vector; } _gsl_vector_int_view; typedef _gsl_vector_int_view gsl_vector_int_view; typedef struct { gsl_vector_int vector; } _gsl_vector_int_const_view; typedef const _gsl_vector_int_const_view gsl_vector_int_const_view; /* Allocation */ GSL_EXPORT gsl_vector_int *gsl_vector_int_alloc (const size_t n); GSL_EXPORT gsl_vector_int *gsl_vector_int_calloc (const size_t n); GSL_EXPORT gsl_vector_int *gsl_vector_int_alloc_from_block (gsl_block_int * b, const size_t offset, const size_t n, const size_t stride); GSL_EXPORT gsl_vector_int *gsl_vector_int_alloc_from_vector (gsl_vector_int * v, const size_t offset, const size_t n, const size_t stride); GSL_EXPORT void gsl_vector_int_free (gsl_vector_int * v); /* Views */ GSL_EXPORT _gsl_vector_int_view gsl_vector_int_view_array (int *v, size_t n); GSL_EXPORT _gsl_vector_int_view gsl_vector_int_view_array_with_stride (int *base, size_t stride, size_t n); GSL_EXPORT _gsl_vector_int_const_view gsl_vector_int_const_view_array (const int *v, size_t n); GSL_EXPORT _gsl_vector_int_const_view gsl_vector_int_const_view_array_with_stride (const int *base, size_t stride, size_t n); GSL_EXPORT _gsl_vector_int_view gsl_vector_int_subvector (gsl_vector_int *v, size_t i, size_t n); GSL_EXPORT _gsl_vector_int_view gsl_vector_int_subvector_with_stride (gsl_vector_int *v, size_t i, size_t stride, size_t n); GSL_EXPORT _gsl_vector_int_const_view gsl_vector_int_const_subvector (const gsl_vector_int *v, size_t i, size_t n); GSL_EXPORT _gsl_vector_int_const_view gsl_vector_int_const_subvector_with_stride (const gsl_vector_int *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_EXPORT int gsl_vector_int_get (const gsl_vector_int * v, const size_t i); GSL_EXPORT void gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x); GSL_EXPORT int *gsl_vector_int_ptr (gsl_vector_int * v, const size_t i); GSL_EXPORT const int *gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i); GSL_EXPORT void gsl_vector_int_set_zero (gsl_vector_int * v); GSL_EXPORT void gsl_vector_int_set_all (gsl_vector_int * v, int x); GSL_EXPORT int gsl_vector_int_set_basis (gsl_vector_int * v, size_t i); GSL_EXPORT int gsl_vector_int_fread (FILE * stream, gsl_vector_int * v); GSL_EXPORT int gsl_vector_int_fwrite (FILE * stream, const gsl_vector_int * v); GSL_EXPORT int gsl_vector_int_fscanf (FILE * stream, gsl_vector_int * v); GSL_EXPORT int gsl_vector_int_fprintf (FILE * stream, const gsl_vector_int * v, const char *format); GSL_EXPORT int gsl_vector_int_memcpy (gsl_vector_int * dest, const gsl_vector_int * src); GSL_EXPORT int gsl_vector_int_reverse (gsl_vector_int * v); GSL_EXPORT int gsl_vector_int_swap (gsl_vector_int * v, gsl_vector_int * w); GSL_EXPORT int gsl_vector_int_swap_elements (gsl_vector_int * v, const size_t i, const size_t j); GSL_EXPORT int gsl_vector_int_max (const gsl_vector_int * v); GSL_EXPORT int gsl_vector_int_min (const gsl_vector_int * v); GSL_EXPORT void gsl_vector_int_minmax (const gsl_vector_int * v, int * min_out, int * max_out); GSL_EXPORT size_t gsl_vector_int_max_index (const gsl_vector_int * v); GSL_EXPORT size_t gsl_vector_int_min_index (const gsl_vector_int * v); GSL_EXPORT void gsl_vector_int_minmax_index (const gsl_vector_int * v, size_t * imin, size_t * imax); GSL_EXPORT int gsl_vector_int_add (gsl_vector_int * a, const gsl_vector_int * b); GSL_EXPORT int gsl_vector_int_sub (gsl_vector_int * a, const gsl_vector_int * b); GSL_EXPORT int gsl_vector_int_mul (gsl_vector_int * a, const gsl_vector_int * b); GSL_EXPORT int gsl_vector_int_div (gsl_vector_int * a, const gsl_vector_int * b); GSL_EXPORT int gsl_vector_int_scale (gsl_vector_int * a, const double x); GSL_EXPORT int gsl_vector_int_add_constant (gsl_vector_int * a, const double x); GSL_EXPORT int gsl_vector_int_isnull (const gsl_vector_int * v); #ifdef HAVE_INLINE extern inline int gsl_vector_int_get (const gsl_vector_int * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } extern inline void gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } extern inline int * gsl_vector_int_ptr (gsl_vector_int * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (int *) (v->data + i * v->stride); } extern inline const int * gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const int *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_INT_H__ */
{ "alphanum_fraction": 0.6689938398, "avg_line_length": 31.085106383, "ext": "h", "hexsha": "1e0f9050075c913fd074ff5fc46f63769c830af5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_vector_int.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1767, "size": 7305 }
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.openairinterface.org/?page_id=698 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include <string.h> #include <math.h> #include <unistd.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <cblas.h> #include <execinfo.h> //<<PAD>>// //#include <mpi.h> //#include "UTIL/FIFO/pad_list.h" #include "discrete_event_generator.h" #include "threadpool.h" #include <pthread.h> #include "oaisim_functions.h" //<<PAD>>// #include "SIMULATION/RF/defs.h" #include "PHY/types.h" #include "PHY/defs.h" #include "PHY/vars.h" #include "MAC_INTERFACE/vars.h" //#ifdef OPENAIR2 #include "LAYER2/MAC/defs.h" #include "LAYER2/MAC/vars.h" #include "RRC/LITE/vars.h" #include "PHY_INTERFACE/vars.h" //#endif #include "ARCH/CBMIMO1/DEVICE_DRIVER/vars.h" #ifdef IFFT_FPGA //#include "PHY/LTE_REFSIG/mod_table.h" #endif //IFFT_FPGA #include "SCHED/defs.h" #include "SCHED/vars.h" #include "oaisim.h" #include "oaisim_config.h" #include "UTIL/OCG/OCG_extern.h" #include "cor_SF_sim.h" #include "UTIL/OMG/omg_constants.h" //#include "UTIL/LOG/vcd_signal_dumper.h" #define RF //#define DEBUG_SIM #define MCS_COUNT 24//added for PHY abstraction #define N_TRIALS 1 /* DCI0_5MHz_TDD0_t UL_alloc_pdu; DCI1A_5MHz_TDD_1_6_t CCCH_alloc_pdu; DCI2_5MHz_2A_L10PRB_TDD_t DLSCH_alloc_pdu1; DCI2_5MHz_2A_M10PRB_TDD_t DLSCH_alloc_pdu2; */ #define UL_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,24) #define CCCH_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3) #define RA_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3) #define DLSCH_RB_ALLOC 0x1fff #define DECOR_DIST 100 #define SF_VAR 10 //constant for OAISIM soft realtime calibration #define SF_DEVIATION_OFFSET_NS 100000 //= 0.1ms : should be as a number of UE #define SLEEP_STEP_US 100 // = 0.01ms could be adaptive, should be as a number of UE #define K 2 // averaging coefficient #define TARGET_SF_TIME_NS 1000000 // 1ms = 1000000 ns //#ifdef OPENAIR2 //uint16_t NODE_ID[1]; //uint8_t NB_INST = 2; //#endif //OPENAIR2 extern int otg_times; extern int for_times; extern int if_times; int for_main_times = 0; frame_t frame=0; char stats_buffer[16384]; channel_desc_t *eNB2UE[NUMBER_OF_eNB_MAX][NUMBER_OF_UE_MAX]; channel_desc_t *UE2eNB[NUMBER_OF_UE_MAX][NUMBER_OF_eNB_MAX]; Signal_buffers *signal_buffers_g; //Added for PHY abstraction node_desc_t *enb_data[NUMBER_OF_eNB_MAX]; node_desc_t *ue_data[NUMBER_OF_UE_MAX]; //double sinr_bler_map[MCS_COUNT][2][16]; //double sinr_bler_map_up[MCS_COUNT][2][16]; //extern double SINRpost_eff[301]; extern int mcsPost; extern int nrbPost; extern int frbPost; extern void kpi_gen(); extern uint16_t Nid_cell; extern uint8_t target_dl_mcs; extern uint8_t rate_adaptation_flag; extern double snr_dB, sinr_dB; extern uint8_t set_seed; extern uint8_t cooperation_flag; // for cooperative communication extern uint8_t abstraction_flag, ethernet_flag; extern uint8_t ue_connection_test; extern int map1,map2; extern double **ShaF; // pointers signal buffers (s = transmit, r,r0 = receive) extern double **s_re, **s_im, **r_re, **r_im, **r_re0, **r_im0; extern Node_list ue_node_list; extern Node_list enb_node_list; extern int pdcp_period, omg_period; extern LTE_DL_FRAME_PARMS *frame_parms; // time calibration for soft realtime mode extern struct timespec time_spec; extern unsigned long time_last, time_now; extern int td, td_avg, sleep_time_us; int eMBMS_active = 0; threadpool_t * pool; #ifdef OPENAIR2 extern int pfd[2]; #endif // this should reflect the channel models in openair1/SIMULATION/TOOLS/defs.h mapping small_scale_names[] = { {"custom", custom}, {"SCM_A", SCM_A}, {"SCM_B", SCM_B}, {"SCM_C", SCM_C}, {"SCM_D", SCM_D}, {"EPA", EPA}, {"EVA", EVA}, {"ETU", ETU}, {"Rayleigh8", Rayleigh8}, {"Rayleigh1", Rayleigh1}, {"Rayleigh1_800", Rayleigh1_800}, {"Rayleigh1_corr", Rayleigh1_corr}, {"Rayleigh1_anticorr", Rayleigh1_anticorr}, {"Rice8", Rice8}, {"Rice1", Rice1}, {"Rice1_corr", Rice1_corr}, {"Rice1_anticorr", Rice1_anticorr}, {"AWGN", AWGN}, {NULL, -1} }; //static void *sigh(void *arg); void terminate(void); void help (void) { printf ("Usage: oaisim -h -a -F -C tdd_config -V -R N_RB_DL -e -x transmission_mode -m target_dl_mcs -r(ate_adaptation) -n n_frames -s snr_dB -k ricean_factor -t max_delay -f forgetting factor -A channel_model -z cooperation_flag -u nb_local_ue -U UE mobility -b nb_local_enb -B eNB_mobility -M ethernet_flag -p nb_master -g multicast_group -l log_level -c ocg_enable -T traffic model -D multicast network device\n"); printf ("-h provides this help message!\n"); printf ("-a Activates PHY abstraction mode\n"); printf ("-F Activates FDD transmission (TDD is default)\n"); printf ("-C [0-6] Sets TDD configuration\n"); printf ("-R [6,15,25,50,75,100] Sets N_RB_DL\n"); printf ("-e Activates extended prefix mode\n"); printf ("-m Gives a fixed DL mcs\n"); printf ("-r Activates rate adaptation (DL for now)\n"); printf ("-n Set the number of frames for the simulation\n"); printf ("-s snr_dB set a fixed (average) SNR, this deactivates the openair channel model generator (OCM)\n"); printf ("-S snir_dB set a fixed (average) SNIR, this deactivates the openair channel model generator (OCM)\n"); printf ("-k Set the Ricean factor (linear)\n"); printf ("-t Set the delay spread (microseconds)\n"); printf ("-f Set the forgetting factor for time-variation\n"); printf ("-A set the multipath channel simulation, options are: SCM_A, SCM_B, SCM_C, SCM_D, EPA, EVA, ETU, Rayleigh8, Rayleigh1, Rayleigh1_corr,Rayleigh1_anticorr, Rice8,, Rice1, AWGN \n"); printf ("-b Set the number of local eNB\n"); printf ("-u Set the number of local UE\n"); printf ("-M Set the machine ID for Ethernet-based emulation\n"); printf ("-p Set the total number of machine in emulation - valid if M is set\n"); printf ("-g Set multicast group ID (0,1,2,3) - valid if M is set\n"); printf ("-l Set the global log level (8:trace, 7:debug, 6:info, 4:warn, 3:error) \n"); printf ("-c [1,2,3,4] Activate the config generator (OCG) to process the scenario descriptor, or give the scenario manually: -c template_1.xml \n"); printf ("-x Set the transmission mode (1,2,5,6 supported for now)\n"); printf ("-z Set the cooperation flag (0 for no cooperation, 1 for delay diversity and 2 for distributed alamouti\n"); printf ("-T activate the traffic generator: 0 for NONE, 1 for CBR, 2 for M2M, 3 for FPS Gaming, 4 for mix\n"); printf ("-B Set the mobility model for eNB, options are: STATIC, RWP, RWALK, \n"); printf ("-U Set the mobility model for UE, options are: STATIC, RWP, RWALK \n"); printf ("-E Random number generator seed\n"); printf ("-P enable protocol analyzer : 0 for wireshark interface, 1: for pcap , 2 : for tshark \n"); printf ("-I Enable CLI interface (to connect use telnet localhost 1352)\n"); printf ("-V Enable VCD dump, file = openair_vcd_dump.vcd\n"); printf ("-G Enable background traffic \n"); printf ("-O [mme ipv4 address] Enable MME mode\n"); printf ("-Z Reserved\n"); } #ifdef OPENAIR2 void omv_end (int pfd, Data_Flow_Unit omv_data); int omv_write (int pfd, Node_list enb_node_list, Node_list ue_node_list, Data_Flow_Unit omv_data); #endif //<<<< PAD >>>>// #define PAD 1 //#define PAD_FINE 1 //#define PAD_SYNC 1 #define JOB_REQUEST_TAG 246 #define JOB_REPLY_TAG 369 #define FRAME_END 888 #define NO_JOBS_TAG 404 #define JOB_DIST_DEBUG 33 //Global Variables int worker_number; int frame_number = 1; //<<<< PAD >>>>// //<<<< DEG >>>>// extern End_Of_Sim_Event end_event; //Could later be a list of condition_events extern Event_List event_list; //<<<< DEG >>>>// extern Packet_OTG_List *otg_pdcp_buffer; void run(int argc, char *argv[]); #ifdef PAD void pad_init() { int UE_id, i; pool = threadpool_create(PAD); if (pool == NULL) { printf("ERROR threadpool allocation\n"); return; } signal_buffers_g = malloc(NB_UE_INST * sizeof(Signal_buffers)); if (abstraction_flag == 0) { for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) { signal_buffers_g[UE_id].s_re = malloc(2*sizeof(double*)); signal_buffers_g[UE_id].s_im = malloc(2*sizeof(double*)); signal_buffers_g[UE_id].r_re = malloc(2*sizeof(double*)); signal_buffers_g[UE_id].r_im = malloc(2*sizeof(double*)); signal_buffers_g[UE_id].r_re0 = malloc(2*sizeof(double*)); signal_buffers_g[UE_id].r_im0 = malloc(2*sizeof(double*)); for (i=0; i<2; i++) { signal_buffers_g[UE_id].s_re[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].s_re[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); signal_buffers_g[UE_id].s_im[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].s_im[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); signal_buffers_g[UE_id].r_re[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].r_re[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); signal_buffers_g[UE_id].r_im[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].r_im[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); signal_buffers_g[UE_id].r_re0[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].r_re0[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); signal_buffers_g[UE_id].r_im0[i] = malloc(FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); bzero(signal_buffers_g[UE_id].r_im0[i],FRAME_LENGTH_COMPLEX_SAMPLES*sizeof(double)); } } } } void pad_finalize() { int ret, i; module_id_t UE_id; ret = threadpool_destroy(pool); if (ret) printf("ERROR threadpool destroy = %d\n", ret); if (abstraction_flag == 0) { for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) { for (i = 0; i < 2; i++) { free(signal_buffers_g[UE_id].s_re[i]); free(signal_buffers_g[UE_id].s_im[i]); free(signal_buffers_g[UE_id].r_re[i]); free(signal_buffers_g[UE_id].r_im[i]); } free(signal_buffers_g[UE_id].s_re); free(signal_buffers_g[UE_id].s_im); free(signal_buffers_g[UE_id].r_re); free(signal_buffers_g[UE_id].r_im); } //free node by node here same pattern as below } free(signal_buffers_g); } void pad_inject_job(int eNB_flag, int nid, int frame, int next_slot, int last_slot, enum Job_type type, int ctime) { int ret; Job_elt *job_elt; job_elt = malloc(sizeof(Job_elt)); job_elt->next = NULL; (job_elt->job).eNB_flag = eNB_flag; (job_elt->job).nid = nid; (job_elt->job).frame = frame; (job_elt->job).next_slot = next_slot; (job_elt->job).last_slot = last_slot; (job_elt->job).type = type; (job_elt->job).ctime = ctime; ret = threadpool_add(pool, job_elt); if (ret) { printf("ERROR threadpool_add %d\n", ret); return; } } void pad_synchronize() { pthread_mutex_lock(&(pool->sync_lock)); while(pool->active > 0) { pthread_cond_wait(&(pool->sync_notify), &(pool->sync_lock)); } pthread_mutex_unlock(&(pool->sync_lock)); } #endif //<<PAD(DEG_MAIN)>>// int main (int argc, char *argv[]) { //Mobility *mobility_frame_10; //Application_Config *application_frame_20; //Here make modifications on the mobility and traffic new models //mob_frame_10 -> ... //application_frame_30 -> ... //schedule(ET_OMG, 10, NULL, mobility_frame_10); //schedule(ET_OTG, 15, NULL, application_frame_20); //event_list_display(&event_list); schedule_end_of_simulation(FRAME, 100); run(argc, argv); return 0; } //<<PAD>>// //<<PAD(RUN)>>// void run(int argc, char *argv[]) { int32_t i; module_id_t UE_id, eNB_id; Job_elt *job_elt; int ret; clock_t t; Event_elt *user_defined_event; Event event; // Framing variables int32_t slot, last_slot, next_slot; FILE *SINRpost; char SINRpost_fname[512]; sprintf(SINRpost_fname,"postprocSINR.m"); SINRpost = fopen(SINRpost_fname,"w"); // variables/flags which are set by user on command-line double snr_direction,snr_step=1.0;//,sinr_direction; lte_subframe_t direction; char fname[64],vname[64]; #ifdef XFORMS // current status is that every UE has a DL scope for a SINGLE eNB (eNB_id=0) // at eNB 0, an UL scope for every UE FD_lte_phy_scope_ue *form_ue[NUMBER_OF_UE_MAX]; FD_lte_phy_scope_enb *form_enb[NUMBER_OF_UE_MAX]; char title[255]; #endif #ifdef PROC int node_id; int port,Process_Flag=0,wgt,Channel_Flag=0,temp; #endif // uint8_t awgn_flag = 0; #ifdef PRINT_STATS int len; FILE *UE_stats[NUMBER_OF_UE_MAX], *UE_stats_th[NUMBER_OF_UE_MAX], *eNB_stats, *eNB_avg_thr, *eNB_l2_stats; char UE_stats_filename[255]; char UE_stats_th_filename[255]; char eNB_stats_th_filename[255]; #endif #ifdef SMBV uint8_t config_smbv = 0; char smbv_ip[16]; strcpy(smbv_ip,DEFAULT_SMBV_IP); #endif #ifdef OPENAIR2 Data_Flow_Unit omv_data; #endif //time_t t0,t1; //clock_t start, stop; //double **s_re2[MAX_eNB+MAX_UE], **s_im2[MAX_eNB+MAX_UE], **r_re2[MAX_eNB+MAX_UE], **r_im2[MAX_eNB+MAX_UE], **r_re02, **r_im02; //double **r_re0_d[MAX_UE][MAX_eNB], **r_im0_d[MAX_UE][MAX_eNB], **r_re0_u[MAX_eNB][MAX_UE],**r_im0_u[MAX_eNB][MAX_UE]; //default parameters //{ /* INITIALIZATIONS */ target_dl_mcs = 0; rate_adaptation_flag = 0; oai_emulation.info.n_frames = 0xffff;//1024; //10; oai_emulation.info.n_frames_flag = 0;//fixme snr_dB = 30; cooperation_flag = 0; // default value 0 for no cooperation, 1 for Delay diversity, 2 for Distributed Alamouti //Default values if not changed by the user in get_simulation_options(); pdcp_period = 1; omg_period = 10; mRAL_init_default_values(); //Default values eRAL_init_default_values(); //Default values init_oai_emulation(); //Default values get_simulation_options(argc, argv); //Command-line options oaisim_config(); // config OMG and OCG, OPT, OTG, OLG //To fix eventual conflict on the value of n_frames if (oai_emulation.info.n_frames_flag) { schedule_end_of_simulation(FRAME, oai_emulation.info.n_frames); } VCD_SIGNAL_DUMPER_INIT(); // Initialize VCD LOG module #ifdef OPENAIR2 init_omv(); #endif check_and_adjust_params(); //Before this call, NB_UE_INST and NB_eNB_INST are not set correctly init_otg_pdcp_buffer(); #ifdef PRINT_STATS for (UE_id=0; UE_id<NB_UE_INST; UE_id++) { sprintf(UE_stats_filename,"UE_stats%d.txt",UE_id); UE_stats[UE_id] = fopen (UE_stats_filename, "w"); } eNB_stats = fopen ("eNB_stats.txt", "w"); printf ("UE_stats=%p, eNB_stats=%p\n", UE_stats, eNB_stats); eNB_avg_thr = fopen ("eNB_stats_th.txt", "w"); #endif LOG_I(EMU,"total number of UE %d (local %d, remote %d) mobility %s \n", NB_UE_INST,oai_emulation.info.nb_ue_local,oai_emulation.info.nb_ue_remote, oai_emulation.topology_config.mobility.eNB_mobility.eNB_mobility_type.selected_option); LOG_I(EMU,"Total number of eNB %d (local %d, remote %d) mobility %s \n", NB_eNB_INST,oai_emulation.info.nb_enb_local,oai_emulation.info.nb_enb_remote, oai_emulation.topology_config.mobility.UE_mobility.UE_mobility_type.selected_option); LOG_I(OCM,"Running with frame_type %d, Nid_cell %d, N_RB_DL %d, EP %d, mode %d, target dl_mcs %d, rate adaptation %d, nframes %d, abstraction %d, channel %s\n", oai_emulation.info.frame_type, Nid_cell, oai_emulation.info.N_RB_DL, oai_emulation.info.extended_prefix_flag, oai_emulation.info.transmission_mode,target_dl_mcs,rate_adaptation_flag, oai_emulation.info.n_frames,abstraction_flag,oai_emulation.environment_system_config.fading.small_scale.selected_option); init_seed(set_seed); init_openair1(); init_openair2(); init_ocm(); #ifdef XFORMS init_xforms(); #endif printf ("before L2 init: Nid_cell %d\n", PHY_vars_eNB_g[0]->lte_frame_parms.Nid_cell); printf ("before L2 init: frame_type %d,tdd_config %d\n", PHY_vars_eNB_g[0]->lte_frame_parms.frame_type, PHY_vars_eNB_g[0]->lte_frame_parms.tdd_config); init_time(); #ifdef PAD pad_init(); #endif if (ue_connection_test == 1) { snr_direction = -snr_step; snr_dB=20; sinr_dB=-20; } frame = 0; slot = 0; LOG_I(EMU,">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU initialization done <<<<<<<<<<<<<<<<<<<<<<<<<<\n\n"); printf ("after init: Nid_cell %d\n", PHY_vars_eNB_g[0]->lte_frame_parms.Nid_cell); printf ("after init: frame_type %d,tdd_config %d\n", PHY_vars_eNB_g[0]->lte_frame_parms.frame_type, PHY_vars_eNB_g[0]->lte_frame_parms.tdd_config); t = clock(); while (!end_of_simulation()) { last_slot = (slot - 1)%20; if (last_slot <0) last_slot+=20; next_slot = (slot + 1)%20; oai_emulation.info.time_ms = frame * 10 + (next_slot>>1); oai_emulation.info.frame = frame; if (slot == 0) { //Frame's Prologue //Run the aperiodic user-defined events while ((user_defined_event = event_list_get_head(&event_list)) != NULL) { event = user_defined_event->event; if (event.frame == frame) { switch (event.type) { case ET_OMG: update_omg_model(event.key, event.value); //implement it with assigning the new values to that of oai_emulation & second thing is to ensure mob model is always read from oai_emulation user_defined_event = event_list_remove_head(&event_list); break; case ET_OTG: update_otg_model(event.key, event.value); user_defined_event = event_list_remove_head(&event_list); break; } } else { break; } } //Comment (handle cooperation flag) deleted here. Look at oaisim.c to see it if (ue_connection_test==1) { if ((frame%20) == 0) { snr_dB += snr_direction; sinr_dB -= snr_direction; } if (snr_dB == -20) { snr_direction=snr_step; } else if (snr_dB==20) { snr_direction=-snr_step; } } update_omg(); // frequency is defined in the omg_global params configurable by the user update_omg_ocm(); #ifdef OPENAIR2 // check if pipe is still open if ((oai_emulation.info.omv_enabled == 1) ) { omv_write(pfd[1], enb_node_list, ue_node_list, omv_data); } #endif #ifdef DEBUG_OMG if ((((int) oai_emulation.info.time_s) % 100) == 0) { for (UE_id = oai_emulation.info.first_ue_local; UE_id < (oai_emulation.info.first_ue_local + oai_emulation.info.nb_ue_local); UE_id++) { get_node_position (UE, UE_id); } } #endif update_ocm(); } direction = subframe_select(frame_parms,next_slot>>1); if((next_slot %2) ==0) clear_eNB_transport_info(oai_emulation.info.nb_enb_local); for (eNB_id=oai_emulation.info.first_enb_local; (eNB_id<(oai_emulation.info.first_enb_local+oai_emulation.info.nb_enb_local)) && (oai_emulation.info.cli_start_enb[eNB_id]==1); eNB_id++) { for_main_times += 1; //printf ("debug: Nid_cell %d\n", PHY_vars_eNB_g[eNB_id]->lte_frame_parms.Nid_cell); //printf ("debug: frame_type %d,tdd_config %d\n", PHY_vars_eNB_g[eNB_id]->lte_frame_parms.frame_type,PHY_vars_eNB_g[eNB_id]->lte_frame_parms.tdd_config); LOG_D(EMU,"PHY procedures eNB %d for frame %d, slot %d (subframe TX %d, RX %d) TDD %d/%d Nid_cell %d\n", eNB_id, frame, slot, next_slot >> 1,last_slot>>1, PHY_vars_eNB_g[eNB_id]->lte_frame_parms.frame_type, PHY_vars_eNB_g[eNB_id]->lte_frame_parms.tdd_config,PHY_vars_eNB_g[eNB_id]->lte_frame_parms.Nid_cell); //Appliation #ifdef PAD_FINE pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_OTG, oai_emulation.info.time_ms); #else update_otg_eNB(eNB_id, oai_emulation.info.time_ms); #endif //Access layer if (frame % pdcp_period == 0) { #ifdef PAD_FINE pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_PDCP, oai_emulation.info.time_ms); #else pdcp_run(frame, 1, 0, eNB_id);//PHY_vars_eNB_g[eNB_id]->Mod_id #endif } //Phy/Mac layer #ifdef PAD_FINE pad_inject_job(1, eNB_id, frame, next_slot, last_slot, JT_PHY_MAC, oai_emulation.info.time_ms); #else phy_procedures_eNB_lte (last_slot, next_slot, PHY_vars_eNB_g[eNB_id], abstraction_flag, no_relay, NULL); #endif #ifdef PRINT_STATS if(last_slot==9 && frame%10==0) if(eNB_avg_thr) fprintf(eNB_avg_thr,"%d %d\n",PHY_vars_eNB_g[eNB_id]->frame,(PHY_vars_eNB_g[eNB_id]->total_system_throughput)/((PHY_vars_eNB_g[eNB_id]->frame+1)*10)); if (eNB_stats) { len = dump_eNB_stats(PHY_vars_eNB_g[eNB_id], stats_buffer, 0); rewind (eNB_stats); fwrite (stats_buffer, 1, len, eNB_stats); fflush(eNB_stats); } #ifdef OPENAIR2 if (eNB_l2_stats) { len = dump_eNB_l2_stats (stats_buffer, 0); rewind (eNB_l2_stats); fwrite (stats_buffer, 1, len, eNB_l2_stats); fflush(eNB_l2_stats); } #endif #endif } #ifdef PAD_SYNC if ((direction == SF_DL) || ((direction == SF_S) && (next_slot%2==0)) ) pad_synchronize(); #endif // Call ETHERNET emulation here //emu_transport (frame, last_slot, next_slot, direction, oai_emulation.info.frame_type, ethernet_flag); if ((next_slot % 2) == 0) clear_UE_transport_info (oai_emulation.info.nb_ue_local); for (UE_id = oai_emulation.info.first_ue_local; (UE_id < (oai_emulation.info.first_ue_local+oai_emulation.info.nb_ue_local)) && (oai_emulation.info.cli_start_ue[UE_id]==1); UE_id++) if (frame >= (UE_id * 20)) { // activate UE only after 20*UE_id frames so that different UEs turn on separately LOG_D(EMU,"PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\n", UE_id, frame, slot, next_slot >> 1,last_slot>>1); if (PHY_vars_UE_g[UE_id]->UE_mode[0] != NOT_SYNCHED) { if (frame>0) { PHY_vars_UE_g[UE_id]->frame = frame; //Application UE #ifdef PAD_FINE pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_OTG, oai_emulation.info.time_ms); #else update_otg_UE(UE_id + NB_eNB_INST, oai_emulation.info.time_ms); #endif //Access layer UE if (frame % pdcp_period == 0) { #ifdef PAD_FINE pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_PDCP, oai_emulation.info.time_ms); #else pdcp_run(frame, 0, UE_id, 0); #endif } //Phy/Mac layer UE #ifdef PAD_FINE pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_PHY_MAC, oai_emulation.info.time_ms); #else phy_procedures_UE_lte (last_slot, next_slot, PHY_vars_UE_g[UE_id], 0, abstraction_flag, normal_txrx, no_relay, NULL); ue_data[UE_id]->tx_power_dBm = PHY_vars_UE_g[UE_id]->tx_power_dBm; #endif } } else { if (abstraction_flag==1) { LOG_E(EMU, "sync not supported in abstraction mode (UE%d,mode%d)\n", UE_id, PHY_vars_UE_g[UE_id]->UE_mode[0]); exit(-1); } if ((frame>0) && (last_slot == (LTE_SLOTS_PER_FRAME-2))) { #ifdef PAD_FINE pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_INIT_SYNC, oai_emulation.info.time_ms); #else initial_sync(PHY_vars_UE_g[UE_id],normal_txrx); #endif /* LONG write output comment DELETED here */ } } #ifdef PRINT_STATS if(last_slot==2 && frame%10==0) if (UE_stats_th[UE_id]) fprintf(UE_stats_th[UE_id],"%d %d\n",frame, PHY_vars_UE_g[UE_id]->bitrate[0]/1000); if (UE_stats[UE_id]) { len = dump_ue_stats (PHY_vars_UE_g[UE_id], stats_buffer, 0, normal_txrx, 0); rewind (UE_stats[UE_id]); fwrite (stats_buffer, 1, len, UE_stats[UE_id]); fflush(UE_stats[UE_id]); } #endif } #ifdef PAD_SYNC if ((direction == SF_UL) || ((direction == SF_S) && (next_slot%2==1)) ) pad_synchronize(); #endif emu_transport (frame, last_slot, next_slot,direction, oai_emulation.info.frame_type, ethernet_flag); if ((direction == SF_DL)|| (frame_parms->frame_type==0)) { for (UE_id=0; UE_id<NB_UE_INST; UE_id++) { #ifdef PAD pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_DL, oai_emulation.info.time_ms); #else do_DL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,eNB2UE,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,UE_id); #endif } } if ((direction == SF_UL)|| (frame_parms->frame_type==0)) { //if ((subframe<2) || (subframe>4)) do_UL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,UE2eNB,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,frame); /* int ccc; fprintf(SINRpost,"SINRdb For eNB New Subframe : \n "); for(ccc = 0 ; ccc<301; ccc++) { fprintf(SINRpost,"_ %f ", SINRpost_eff[ccc]); } fprintf(SINRpost,"SINRdb For eNB : %f \n ", SINRpost_eff[ccc]); */ } if ((direction == SF_S)) {//it must be a special subframe if (next_slot%2==0) {//DL part for (UE_id=0; UE_id<NB_UE_INST; UE_id++) { #ifdef PAD pad_inject_job(0, UE_id, frame, next_slot, last_slot, JT_DL, oai_emulation.info.time_ms); #else do_DL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,eNB2UE,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,UE_id); #endif } /* for (aarx=0;aarx<UE2eNB[1][0]->nb_rx;aarx++) for (aatx=0;aatx<UE2eNB[1][0]->nb_tx;aatx++) for (k=0;k<UE2eNB[1][0]->channel_length;k++) printf("SB(%d,%d,%d)->(%f,%f)\n",k,aarx,aatx,UE2eNB[1][0]->ch[aarx+(aatx*UE2eNB[1][0]->nb_rx)][k].r,UE2eNB[1][0]->ch[aarx+(aatx*UE2eNB[1][0]->nb_rx)][k].i); */ } else { // UL part /*#ifdef PAD pthread_mutex_lock(&(pool->sync_lock)); while(pool->active != 0) { pthread_cond_wait(&(pool->sync_notify), &(pool->sync_lock)); } pthread_mutex_unlock(&(pool->sync_lock)); #endif*/ do_UL_sig(r_re0,r_im0,r_re,r_im,s_re,s_im,UE2eNB,enb_data,ue_data,next_slot,abstraction_flag,frame_parms,frame); /* int ccc; fprintf(SINRpost,"SINRdb For eNB New Subframe : \n "); for(ccc = 0 ; ccc<301; ccc++) { fprintf(SINRpost,"_ %f ", SINRpost_eff[ccc]); } fprintf(SINRpost,"SINRdb For eNB : %f \n ", SINRpost_eff[ccc]); */ } } if ((last_slot == 1) && (frame == 0) && (abstraction_flag == 0) && (oai_emulation.info.n_frames == 1)) { write_output ("dlchan0.m", "dlch0", &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[0][0][0]), (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1); write_output ("dlchan1.m", "dlch1", &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[1][0][0]), (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1); write_output ("dlchan2.m", "dlch2", &(PHY_vars_UE_g[0]->lte_ue_common_vars.common_vars_rx_data_per_thread[subframe&0x1].dl_ch_estimates[2][0][0]), (6 * (PHY_vars_UE_g[0]->lte_frame_parms.ofdm_symbol_size)), 1, 1); write_output ("pbch_rxF_comp0.m", "pbch_comp0", PHY_vars_UE_g[0]->lte_ue_pbch_vars[0]->rxdataF_comp[0], 6 * 12 * 4, 1, 1); write_output ("pbch_rxF_llr.m", "pbch_llr", PHY_vars_UE_g[0]->lte_ue_pbch_vars[0]->llr, (frame_parms->Ncp == 0) ? 1920 : 1728, 1, 4); } if (next_slot %2 == 0) { clock_gettime (CLOCK_REALTIME, &time_spec); time_last = time_now; time_now = (unsigned long) time_spec.tv_nsec; td = (int) (time_now - time_last); if (td>0) { td_avg = (int)(((K*(long)td) + (((1<<3)-K)*((long)td_avg)))>>3); // in us LOG_T(EMU,"sleep frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\n", frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000); } if (td_avg<(TARGET_SF_TIME_NS - SF_DEVIATION_OFFSET_NS)) { sleep_time_us += SLEEP_STEP_US; LOG_D(EMU,"Faster than realtime increase the avg sleep time for %d us, frame %d\n", sleep_time_us,frame); // LOG_D(EMU,"Faster than realtime increase the avg sleep time for %d us, frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\n", sleep_time_us,frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000); } else if (td_avg > (TARGET_SF_TIME_NS + SF_DEVIATION_OFFSET_NS)) { sleep_time_us-= SLEEP_STEP_US; LOG_D(EMU,"Slower than realtime reduce the avg sleep time for %d us, frame %d, time_now\n", sleep_time_us,frame); //LOG_T(EMU,"Slower than realtime reduce the avg sleep time for %d us, frame %d, time_now %ldus,time_last %ldus,average time difference %ldns, CURRENT TIME DIFF %dus, avgerage difference from the target %dus\n", sleep_time_us,frame, time_now,time_last,td_avg, td/1000,(td_avg-TARGET_SF_TIME_NS)/1000); } } // end if next_slot%2 slot++; if (slot == 20) { //Frame's Epilogue frame++; slot = 0; // if n_frames not set by the user or is greater than max num frame then set adjust the frame counter if ( (oai_emulation.info.n_frames_flag == 0) || (oai_emulation.info.n_frames >= 0xffff) ) { frame %=(oai_emulation.info.n_frames-1); } oai_emulation.info.time_s += 0.01; if ((frame>=1)&&(frame<=9)&&(abstraction_flag==0)) { write_output("UEtxsig0.m","txs0", PHY_vars_UE_g[0]->lte_ue_common_vars.txdata[0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1); sprintf(fname,"eNBtxsig%d.m",frame); sprintf(vname,"txs%d",frame); write_output(fname,vname, PHY_vars_eNB_g[0]->lte_eNB_common_vars.txdata[0][0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1); write_output("eNBtxsigF0.m","txsF0",PHY_vars_eNB_g[0]->lte_eNB_common_vars.txdataF[0][0],PHY_vars_eNB_g[0]->lte_frame_parms.symbols_per_tti*PHY_vars_eNB_g[0]->lte_frame_parms.ofdm_symbol_size,1,1); write_output("UErxsig0.m","rxs0", PHY_vars_UE_g[0]->lte_ue_common_vars.rxdata[0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1); write_output("eNBrxsig0.m","rxs0", PHY_vars_eNB_g[0]->lte_eNB_common_vars.rxdata[0][0],FRAME_LENGTH_COMPLEX_SAMPLES,1,1); } #ifdef XFORMS do_xforms(); #endif // calibrate at the end of each frame if there is some time left if((sleep_time_us > 0)&& (ethernet_flag ==0)) { LOG_I(EMU,"[TIMING] Adjust average frame duration, sleep for %d us\n",sleep_time_us); usleep(sleep_time_us); sleep_time_us=0; // reset the timer, could be done per n SF } #ifdef SMBV if ((frame == config_frames[0]) || (frame == config_frames[1]) || (frame == config_frames[2]) || (frame == config_frames[3])) { smbv_frame_cnt++; } #endif } } t = clock() - t; printf("rrc Duration of the simulation: %f seconds\n",((float)t)/CLOCKS_PER_SEC); fclose(SINRpost); LOG_I(EMU,">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU Ending <<<<<<<<<<<<<<<<<<<<<<<<<<\n\n"); free(otg_pdcp_buffer); #ifdef SMBV if (config_smbv) { smbv_send_config (smbv_fname,smbv_ip); } #endif //Perform KPI measurements if (oai_emulation.info.otg_enabled==1) kpi_gen(); #ifdef PAD pad_finalize(); #endif // relase all rx state if (ethernet_flag == 1) { emu_transport_release (); } if (abstraction_flag == 0) { /* #ifdef IFFT_FPGA free(txdataF2[0]); free(txdataF2[1]); free(txdataF2); free(txdata[0]); free(txdata[1]); free(txdata); #endif */ for (i = 0; i < 2; i++) { free (s_re[i]); free (s_im[i]); free (r_re[i]); free (r_im[i]); } free (s_re); free (s_im); free (r_re); free (r_im); lte_sync_time_free (); } // pthread_join(sigth, NULL); // added for PHY abstraction if (oai_emulation.info.ocm_enabled == 1) { for (eNB_id = 0; eNB_id < NUMBER_OF_eNB_MAX; eNB_id++) free(enb_data[eNB_id]); for (UE_id = 0; UE_id < NUMBER_OF_UE_MAX; UE_id++) free(ue_data[UE_id]); } //End of PHY abstraction changes #ifdef OPENAIR2 mac_top_cleanup(); #endif #ifdef PRINT_STATS for(UE_id=0; UE_id<NB_UE_INST; UE_id++) { if (UE_stats[UE_id]) fclose (UE_stats[UE_id]); if(UE_stats_th[UE_id]) fclose (UE_stats_th[UE_id]); } if (eNB_stats) fclose (eNB_stats); if (eNB_avg_thr) fclose (eNB_avg_thr); if (eNB_l2_stats) fclose (eNB_l2_stats); #endif // stop OMG stop_mobility_generator(oai_emulation.info.omg_model_ue);//omg_param_list.mobility_type #ifdef OPENAIR2 if (oai_emulation.info.omv_enabled == 1) omv_end(pfd[1],omv_data); #endif if ((oai_emulation.info.ocm_enabled == 1) && (ethernet_flag == 0) && (ShaF != NULL)) destroyMat(ShaF,map1, map2); if (opt_enabled == 1 ) terminate_opt(); if (oai_emulation.info.cli_enabled) cli_server_cleanup(); //bring oai if down terminate(); logClean(); VCD_SIGNAL_DUMPER_CLOSE(); //printf("FOR MAIN TIMES = %d &&&& OTG TIMES = %d <-> FOR TIMES = %d <-> IF TIMES = %d\n", for_main_times, otg_times, for_times, if_times); } //<<PAD>>// void terminate(void) { int i; char interfaceName[8]; for (i=0; i < NUMBER_OF_eNB_MAX+NUMBER_OF_UE_MAX; i++) if (oai_emulation.info.oai_ifup[i]==1) { sprintf(interfaceName, "oai%d", i); bringInterfaceUp(interfaceName,0); } } #ifdef OPENAIR2 int omv_write (int pfd, Node_list enb_node_list, Node_list ue_node_list, Data_Flow_Unit omv_data) { int i,j; omv_data.end=0; //omv_data.total_num_nodes = NB_UE_INST + NB_eNB_INST; for (i=0; i<NB_eNB_INST; i++) { if (enb_node_list != NULL) { omv_data.geo[i].x = (enb_node_list->node->X_pos < 0.0)? 0.0 : enb_node_list->node->X_pos; omv_data.geo[i].y = (enb_node_list->node->Y_pos < 0.0)? 0.0 : enb_node_list->node->Y_pos; omv_data.geo[i].z = 1.0; omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_enb; omv_data.geo[i].node_type = 0; //eNB enb_node_list = enb_node_list->next; omv_data.geo[i].Neighbors=0; for (j=NB_eNB_INST; j< NB_UE_INST + NB_eNB_INST ; j++) { if (is_UE_active(i,j - NB_eNB_INST ) == 1) { omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors]= j; omv_data.geo[i].Neighbors++; LOG_D(OMG,"[eNB %d][UE %d] is_UE_active(i,j) %d geo (x%d, y%d) num neighbors %d\n", i,j-NB_eNB_INST, is_UE_active(i,j-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors); } } } } for (i=NB_eNB_INST; i<NB_UE_INST+NB_eNB_INST; i++) { if (ue_node_list != NULL) { omv_data.geo[i].x = (ue_node_list->node->X_pos < 0.0) ? 0.0 : ue_node_list->node->X_pos; omv_data.geo[i].y = (ue_node_list->node->Y_pos < 0.0) ? 0.0 : ue_node_list->node->Y_pos; omv_data.geo[i].z = 1.0; omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_ue; omv_data.geo[i].node_type = 1; //UE //trial omv_data.geo[i].state = 1; omv_data.geo[i].rnti = 88; omv_data.geo[i].connected_eNB = 0; omv_data.geo[i].RSRP = 66; omv_data.geo[i].RSRQ = 55; omv_data.geo[i].Pathloss = 44; omv_data.geo[i].RSSI[0] = 33; omv_data.geo[i].RSSI[1] = 22; omv_data.geo[i].RSSI[2] = 11; ue_node_list = ue_node_list->next; omv_data.geo[i].Neighbors=0; for (j=0; j< NB_eNB_INST ; j++) { if (is_UE_active(j,i-NB_eNB_INST) == 1) { omv_data.geo[i].Neighbor[ omv_data.geo[i].Neighbors]=j; omv_data.geo[i].Neighbors++; LOG_D(OMG,"[UE %d][eNB %d] is_UE_active %d geo (x%d, y%d) num neighbors %d\n", i-NB_eNB_INST,j, is_UE_active(j,i-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors); } } } } if( write( pfd, &omv_data, sizeof(struct Data_Flow_Unit) ) == -1 ) perror( "write omv failed" ); return 1; } void omv_end (int pfd, Data_Flow_Unit omv_data) { omv_data.end=1; if( write( pfd, &omv_data, sizeof(struct Data_Flow_Unit) ) == -1 ) perror( "write omv failed" ); } #endif
{ "alphanum_fraction": 0.6617647059, "avg_line_length": 32.9356521739, "ext": "c", "hexsha": "1f251de581cd666e5a00877a47bbc8e93696793d", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-10-16T04:05:07.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-11T17:18:47.000Z", "max_forks_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "danghoaison91/openairinterface", "max_forks_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "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": "danghoaison91/openairinterface", "max_issues_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_line_length": 412, "max_stars_count": 9, "max_stars_repo_head_hexsha": "ca28acccb2dfe85a0644d5fd6d379928d89f72a6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "danghoaison91/openairinterface", "max_stars_repo_path": "targets/SIMU/USER/oaisim_pad.c", "max_stars_repo_stars_event_max_datetime": "2022-02-16T02:03:51.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-09T19:57:39.000Z", "num_tokens": 11483, "size": 37876 }
#pragma once #include <set> #ifndef _NOGSL #include <gsl/gsl_vector.h> #endif #include "Util.h" using namespace std; class Interface; #ifdef _NOGSL class gsl_vector; #endif class LocalState { public: vector<gsl_vector*> startStates; vector<gsl_vector*> localSols; // local sol for different betas vector<double> errors; LocalState(int ncontrols, int nbetas) { for (int i = 0; i < nbetas; i++) { startStates.push_back(gsl_vector_alloc(ncontrols)); localSols.push_back(gsl_vector_alloc(ncontrols)); } errors.resize(nbetas); } ~LocalState() { for (size_t i = 0; i < localSols.size(); i++) { gsl_vector_free(localSols[i]); } for (size_t i = 0; i < startStates.size(); i++) { gsl_vector_free(startStates[i]); } } void print() { cout << "beta = -1: " << Util::print(localSols[0]) << endl; cout << "beta = -10: " << Util::print(localSols[1]) << endl; cout << "beta = -50: " << Util::print(localSols[2]) << endl; } }; class OptimizationWrapper { public: virtual bool optimize(Interface* inputs, gsl_vector* initState, const set<int>& constraints, int minimizeNode, bool suppressPrint, int MAX_TRIES, LocalState* localState, int level = -1) = 0; virtual gsl_vector* getMinState() = 0; virtual void randomizeCtrls(gsl_vector* x, Interface* inputs, const set<int>& constraints, int minimizeNode) = 0; virtual double getObjectiveVal() = 0; //virtual bool maximize(Interface* inputs, const gsl_vector* initState, const set<int>& assertConstraints, int minimizeNode, float beta, Predicate* pred, int predVal, int level) = 0; };
{ "alphanum_fraction": 0.6955414013, "avg_line_length": 28.5454545455, "ext": "h", "hexsha": "01f04c189225d4c449302e0da0581bc9fab8177e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/OptimizationWrapper.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/OptimizationWrapper.h", "max_line_length": 191, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/OptimizationWrapper.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 449, "size": 1570 }