Search is not available for this dataset
text
string
meta
dict
/* multfit/lmder.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 <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_permutation.h> typedef struct { size_t iter; double xnorm; double fnorm; double delta; double par; gsl_matrix *J; /* Jacobian matrix */ gsl_matrix *r; /* R matrix in J = Q R P^T */ gsl_vector *tau; gsl_vector *diag; /* scaling matrix D = diag(d1,...,dp) */ gsl_vector *qtf; /* Q^T f */ gsl_vector *newton; gsl_vector *gradient; /* gradient g = J^T f */ gsl_vector *x_trial; /* trial step x + dx */ gsl_vector *f_trial; /* trial function f(x + dx) */ gsl_vector *df; gsl_vector *sdiag; gsl_vector *rptdx; const gsl_vector *weights; /* data weights */ gsl_vector *w; gsl_vector *work1; gsl_permutation * perm; } lmder_state_t; static int lmder_alloc (void *vstate, size_t n, size_t p); static int lmder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx); static int lmsder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx); static int set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx, int scale); static int lmder_iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx); static void lmder_free (void *vstate); static int iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx, int scale); #include "lmutil.c" #include "lmpar.c" #include "lmset.c" #include "lmiterate.c" static int lmder_alloc (void *vstate, size_t n, size_t p) { lmder_state_t *state = (lmder_state_t *) vstate; gsl_matrix *r, *J; gsl_vector *tau, *diag, *qtf, *newton, *gradient, *x_trial, *f_trial, *df, *sdiag, *rptdx, *w, *work1; gsl_permutation *perm; J = gsl_matrix_alloc (n, p); if (J == 0) { GSL_ERROR ("failed to allocate space for J", GSL_ENOMEM); } state->J = J; r = gsl_matrix_alloc (n, p); if (r == 0) { GSL_ERROR ("failed to allocate space for r", GSL_ENOMEM); } state->r = r; tau = gsl_vector_calloc (GSL_MIN(n, p)); if (tau == 0) { gsl_matrix_free (r); GSL_ERROR ("failed to allocate space for tau", GSL_ENOMEM); } state->tau = tau; diag = gsl_vector_calloc (p); if (diag == 0) { gsl_matrix_free (r); gsl_vector_free (tau); GSL_ERROR ("failed to allocate space for diag", GSL_ENOMEM); } state->diag = diag; qtf = gsl_vector_calloc (n); if (qtf == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); GSL_ERROR ("failed to allocate space for qtf", GSL_ENOMEM); } state->qtf = qtf; newton = gsl_vector_calloc (p); if (newton == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); GSL_ERROR ("failed to allocate space for newton", GSL_ENOMEM); } state->newton = newton; gradient = gsl_vector_calloc (p); if (gradient == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); GSL_ERROR ("failed to allocate space for gradient", GSL_ENOMEM); } state->gradient = gradient; x_trial = gsl_vector_calloc (p); if (x_trial == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); GSL_ERROR ("failed to allocate space for x_trial", GSL_ENOMEM); } state->x_trial = x_trial; f_trial = gsl_vector_calloc (n); if (f_trial == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); GSL_ERROR ("failed to allocate space for f_trial", GSL_ENOMEM); } state->f_trial = f_trial; df = gsl_vector_calloc (n); if (df == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); GSL_ERROR ("failed to allocate space for df", GSL_ENOMEM); } state->df = df; sdiag = gsl_vector_calloc (p); if (sdiag == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); gsl_vector_free (df); GSL_ERROR ("failed to allocate space for sdiag", GSL_ENOMEM); } state->sdiag = sdiag; rptdx = gsl_vector_calloc (n); if (rptdx == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); gsl_vector_free (df); gsl_vector_free (sdiag); GSL_ERROR ("failed to allocate space for rptdx", GSL_ENOMEM); } state->rptdx = rptdx; w = gsl_vector_calloc (n); if (w == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); gsl_vector_free (df); gsl_vector_free (sdiag); gsl_vector_free (rptdx); GSL_ERROR ("failed to allocate space for w", GSL_ENOMEM); } state->w = w; work1 = gsl_vector_calloc (p); if (work1 == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); gsl_vector_free (df); gsl_vector_free (sdiag); gsl_vector_free (rptdx); gsl_vector_free (w); GSL_ERROR ("failed to allocate space for work1", GSL_ENOMEM); } state->work1 = work1; perm = gsl_permutation_calloc (p); if (perm == 0) { gsl_matrix_free (r); gsl_vector_free (tau); gsl_vector_free (diag); gsl_vector_free (qtf); gsl_vector_free (newton); gsl_vector_free (gradient); gsl_vector_free (x_trial); gsl_vector_free (f_trial); gsl_vector_free (df); gsl_vector_free (sdiag); gsl_vector_free (rptdx); gsl_vector_free (w); gsl_vector_free (work1); GSL_ERROR ("failed to allocate space for perm", GSL_ENOMEM); } state->perm = perm; return GSL_SUCCESS; } static int lmder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { int status = set (vstate, swts, fdf, x, f, dx, 0); return status ; } static int lmsder_set (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { int status = set (vstate, swts, fdf, x, f, dx, 1); return status ; } static int lmder_iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { int status = iterate (vstate, swts, fdf, x, f, dx, 0); return status; } static int lmsder_iterate (void *vstate, const gsl_vector * swts, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_vector * dx) { int status = iterate (vstate, swts, fdf, x, f, dx, 1); return status; } static int lmder_gradient (void *vstate, gsl_vector * g) { lmder_state_t *state = (lmder_state_t *) vstate; compute_gradient(state->r, state->qtf, g); return GSL_SUCCESS; } static int lmder_jac (void *vstate, gsl_matrix * J) { lmder_state_t *state = (lmder_state_t *) vstate; int s = gsl_matrix_memcpy(J, state->J); return s; } static void lmder_free (void *vstate) { lmder_state_t *state = (lmder_state_t *) vstate; if (state->perm) gsl_permutation_free (state->perm); if (state->work1) gsl_vector_free (state->work1); if (state->w) gsl_vector_free (state->w); if (state->rptdx) gsl_vector_free (state->rptdx); if (state->sdiag) gsl_vector_free (state->sdiag); if (state->df) gsl_vector_free (state->df); if (state->f_trial) gsl_vector_free (state->f_trial); if (state->x_trial) gsl_vector_free (state->x_trial); if (state->gradient) gsl_vector_free (state->gradient); if (state->newton) gsl_vector_free (state->newton); if (state->qtf) gsl_vector_free (state->qtf); if (state->diag) gsl_vector_free (state->diag); if (state->tau) gsl_vector_free (state->tau); if (state->r) gsl_matrix_free (state->r); if (state->J) gsl_matrix_free (state->J); } static const gsl_multifit_fdfsolver_type lmder_type = { "lmder", /* name */ sizeof (lmder_state_t), &lmder_alloc, &lmder_set, &lmder_iterate, &lmder_gradient, &lmder_jac, &lmder_free }; static const gsl_multifit_fdfsolver_type lmsder_type = { "lmsder", /* name */ sizeof (lmder_state_t), &lmder_alloc, &lmsder_set, &lmsder_iterate, &lmder_gradient, &lmder_jac, &lmder_free }; const gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmder = &lmder_type; const gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmsder = &lmsder_type;
{ "alphanum_fraction": 0.6440202642, "avg_line_length": 24.135371179, "ext": "c", "hexsha": "e931a58b9fee1f9d170e639a53a85efb6aaf302f", "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/lmder.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/lmder.c", "max_line_length": 152, "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/lmder.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": 3195, "size": 11054 }
#ifndef STDAFX_H #define STDAFX_H /* * Libs */ #include <qwt.h> #include <qwt_legend.h> #include <qwt_plot.h> #include <qwt_plot_curve.h> #include <qwt_plot_grid.h> #include <qwt_plot_marker.h> #include <qwt_plot_renderer.h> #include <qwt_symbol.h> #include <QtConcurrent/QtConcurrent> #include <QtCore/QtCore> #include <QtWidgets/QtWidgets> #include <gsl/gsl> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> /* * STL */ #include <memory> #include <vector> /* * UTILITIES */ #include "macros.inl" #endif // !STDAFX_H
{ "alphanum_fraction": 0.7291311755, "avg_line_length": 18.935483871, "ext": "h", "hexsha": "2cdcbe886e38b70626bf73d25237c256bf16b96a", "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": "45b4bedcedde2901729d149484eae9cadb3e32b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "philong6297/multimedia-project", "max_forks_repo_path": "multimedia-project/stdafx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "45b4bedcedde2901729d149484eae9cadb3e32b2", "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": "philong6297/multimedia-project", "max_issues_repo_path": "multimedia-project/stdafx.h", "max_line_length": 38, "max_stars_count": null, "max_stars_repo_head_hexsha": "45b4bedcedde2901729d149484eae9cadb3e32b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "philong6297/multimedia-project", "max_stars_repo_path": "multimedia-project/stdafx.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 170, "size": 587 }
#ifndef _KORALI_BASEPARAMETER_H_ #define _KORALI_BASEPARAMETER_H_ #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> namespace Korali::Parameter { class Base { public: Base(std::string name); gsl_rng* _range; std::string _name; double _lowerBound; double _upperBound; void setBounds(double lowerBound, double upperBound) { _lowerBound = lowerBound; _upperBound = upperBound; } void setName(std::string name) { _name = name; } void initializeDistribution(int seed); void checkBounds(); virtual double getDensity(double x) = 0; virtual double getDensityLog(double x) = 0; virtual double getRandomNumber() = 0; }; } // namespace Korali #endif // _KORALI_BASEPARAMETER_H_
{ "alphanum_fraction": 0.749672346, "avg_line_length": 21.1944444444, "ext": "h", "hexsha": "11348ecef422b26b75d3eb2a3cc6cf333dd0db9a", "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": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_path": "HPCII/hw04/korali/include/parameters/base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "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": "valentinjacot/backupETHZ", "max_issues_repo_path": "HPCII/hw04/korali/include/parameters/base.h", "max_line_length": 109, "max_stars_count": 1, "max_stars_repo_head_hexsha": "725eb9e0f020b665d83cfb4c55e38d68854cf75b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "anianruoss/HPCSE-II", "max_stars_repo_path": "exercise04/korali/include/parameters/base.h", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "num_tokens": 207, "size": 763 }
#pragma once #include <gsl/gsl_rng.h> #include <utility> // we are using GSL random number generation because i don't trust // random number generation to be consistent across various C++ stdlib // implementations, and for the kind of MC simulator we are writing here, // we want to be able to run it deterministically for testing purposes. class Sampler { private: gsl_rng *internal_rng_state; public: unsigned long int seed; double generate() { return gsl_rng_uniform_pos(internal_rng_state); }; Sampler(unsigned long int n) : seed (n) { internal_rng_state = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(internal_rng_state, seed); }; ~Sampler() { gsl_rng_free(internal_rng_state); }; // since we don't have access to gsl internal state, can't write // copy constructor Sampler(Sampler &other) = delete; // move constructor Sampler(Sampler &&other) : internal_rng_state (std::exchange(other.internal_rng_state, nullptr)), seed (other.seed) {}; // since we don't have access to gsl internal state, can't write // copy assignment operator Sampler &operator=(Sampler &other) = delete; // move assignment operator Sampler &operator=(Sampler &&other) { seed = other.seed; // we move the existing internal_rng_state into other so // it gets freed when other is dropped. std::swap(internal_rng_state, other.internal_rng_state); return *this; }; };
{ "alphanum_fraction": 0.667752443, "avg_line_length": 28.4259259259, "ext": "h", "hexsha": "bf1cc6ed04d207257f223ecb78f722def38f37b9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-03-07T23:03:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-06T18:48:59.000Z", "max_forks_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_forks_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_forks_repo_name": "danielbarter/SMMC", "max_forks_repo_path": "core/sampler.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_issues_repo_name": "danielbarter/SMMC", "max_issues_repo_path": "core/sampler.h", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0966e4c7919da253e69f17e268bfb2d2a7e7f873", "max_stars_repo_licenses": [ "BSD-3-Clause-LBNL" ], "max_stars_repo_name": "danielbarter/SMMC", "max_stars_repo_path": "core/sampler.h", "max_stars_repo_stars_event_max_datetime": "2022-01-08T19:24:44.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-08T19:24:44.000Z", "num_tokens": 335, "size": 1535 }
#ifndef KEYPOINTS_H_CFNIGHAG #define KEYPOINTS_H_CFNIGHAG #include <boost/histogram.hpp> #include <gsl/gsl> #include <opencv2/core/persistence.hpp> #include <opencv2/core/types.hpp> #include <sens_loc/analysis/distance.h> namespace sens_loc::analysis { /// Analyze the distribution and characteristics of detected keypoints. class keypoints { public: /// Use a regular grid with no transformation, no overflow and an axis /// title. using axis_t = distance::axis_t; /// Histogram type for the 2D distribution of keypoints in the dataset. using distribution_histo_t = decltype(boost::histogram::make_histogram(axis_t{}, axis_t{})); /// Histogram type for 'size' and 'response' of the keypoints. using histo_t = decltype(boost::histogram::make_histogram(axis_t{})); keypoints() = default; keypoints(unsigned int img_width, unsigned int img_height) : _img_width{img_width} , _img_height{img_height} {} void configure_image_dimension(unsigned int img_width, unsigned int img_height) noexcept { _img_width = img_width; _img_height = img_height; } void configure_size(unsigned int bins) noexcept { _size_bins = bins; } void configure_size(std::string axis_title) noexcept { _size_title = std::move(axis_title); } void configure_size(unsigned int bins, std::string axis_title) noexcept { _size_bins = bins; _size_title = std::move(axis_title); } void enable_size_histo(bool enabled) noexcept { _size_histo_enabled = enabled; } void configure_response(unsigned int bins) noexcept { _response_bins = bins; } void configure_response(std::string axis_title) noexcept { _response_title = std::move(axis_title); } void configure_response(unsigned int bins, std::string axis_title) noexcept { _response_bins = bins; _response_title = std::move(axis_title); } void enable_response_histo(bool enabled) noexcept { _response_histo_enabled = enabled; } void configure_distribution(unsigned int both_bins) noexcept { _dist_width_bins = both_bins; _dist_height_bins = both_bins; } void configure_distribution(unsigned int w_bins, unsigned int h_bins) noexcept { _dist_width_bins = w_bins; _dist_height_bins = h_bins; } void configure_distribution(std::string w_axis_title, std::string h_axis_title) noexcept { _dist_w_title = std::move(w_axis_title); _dist_h_title = std::move(h_axis_title); } /// Analyze the properties of a set of keypoints. The booleans are toggles /// to deactivate analysis for the specified quantity to save some /// computations. void analyze(gsl::span<const cv::KeyPoint> points, bool distribution = true, bool size = true, bool response = true) noexcept; [[nodiscard]] const distribution_histo_t& distribution() const noexcept { return _distribution; } [[nodiscard]] const histo_t& size_histo() const noexcept { return _size_histo; } [[nodiscard]] const histo_t& response_histo() const noexcept { return _response_histo; } [[nodiscard]] const statistic& size() const noexcept { return _size; } [[nodiscard]] const statistic& response() const noexcept { return _response; } private: unsigned int _img_width = 0U; unsigned int _img_height = 0U; bool _size_histo_enabled = true; statistic _size; histo_t _size_histo; unsigned int _size_bins = 50U; std::string _size_title = "size of keypoints"; bool _response_histo_enabled = true; statistic _response; histo_t _response_histo; unsigned int _response_bins = 50U; std::string _response_title = "response of keypoints"; distribution_histo_t _distribution; unsigned int _dist_width_bins = 50U; unsigned int _dist_height_bins = 50U; std::string _dist_w_title = "width - distribution of keypoints"; std::string _dist_h_title = "height - distribution of keypoints"; }; /// Write the statistics for the keypoint distribution in a file with OpenCVs /// FileStorage API. void write(cv::FileStorage& fs, const std::string& name, const keypoints& kp); } // namespace sens_loc::analysis #endif /* end of include guard: KEYPOINTS_H_CFNIGHAG */
{ "alphanum_fraction": 0.6503943722, "avg_line_length": 35.5378787879, "ext": "h", "hexsha": "7673dca6f0f62af4df960ed7d163bfbf0677bd93", "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": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "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": "JonasToth/depth-conversions", "max_issues_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_line_length": 78, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 1033, "size": 4691 }
#ifndef ALM_KATYUSHA_H #define ALM_KATYUSHA_H #include "Primal_Dual_LOOPLESS_Katyusha0.h" #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <stdio.h> /* printf */ #include <time.h> #include <fstream> #include <algorithm> #include <iomanip> #include <ctime> #include <sstream> //#include "cmd_line.h" //This class implements the method IPALM_Katyusha /* The optimization problem to solve is: min \sum_i f^i(A_ix)+ \sum_i h^i(M_ix)+ P(x) Assumption 1: For each i, f_i is 1-smooth, P(x) is seperable // Each subproblem solves problem of the form \sum_i f^i(A_ix)+ \sum_i h^i_{\beta_s}(M_ix;\lambda_s^i) +P(x)+ \beta_s/2\|x-x_s\|^2 by L_Katyuhsa */ template<typename L, typename D> class ALM_Katyusha: public Primal_Dual_LOOPLESS_Katyusha0<L, D> { private: std::vector<D> Ax_s; std::vector<D> old_Ax_s; std::vector<D> Mx_s; std::vector<D> old_Mx_s; protected: Matrix<L, D> data_A; Matrix<L, D> data_M; std::vector<D> x_s; std::vector<D> old_x_s; std::vector<D> lambda_s; std::vector<D> old_lambda_s; D beta_s; D epsilon_s; D m_s; D m_0; L m_1; L m_2; L m_3; D eta; D rho; D tau_s; std::vector<D> L_phi; D function_value; L print_every_N_ALM; D running_time_ALM; L nb_outer_iters; ofstream samp_ALM; ofstream samp_x_ALM; public: D mu_g; D lambda1; D lambda2; D L_h; virtual inline D value_of_f_j(D, L){return D(NULL);} virtual inline D value_of_h_j(D, L){return D(NULL);} virtual inline D gradient_of_f_j(D, L){return D(NULL);} virtual inline D value_of_f_star_j(D, L){return D(NULL);} virtual inline D value_of_h_star_j(D, L){return D(NULL);} virtual inline D prox_of_h_star_j(D,D, L){return D(NULL);} virtual inline D value_of_P_j(D, L){return D(NULL);} virtual inline D prox_of_P_j(D, D, L){return D(NULL);} virtual inline D feasible_dual(vector<D> &){return D(NULL);} virtual inline void compute_just_in_time_prox_grad_without_x_s(D, D, D &, L,L, D, D &, L){} virtual inline void rescale(){} virtual inline void set_matrix_M(){} virtual inline void set_matrix_A(){} ALM_Katyusha() : Primal_Dual_LOOPLESS_Katyusha0<L,D>(),data_A(),data_M() { this->gamma= 1; } ALM_Katyusha(const char* matrix_file, const char* vector_file) : Primal_Dual_LOOPLESS_Katyusha0<L,D>(matrix_file, vector_file),data_A(), data_M() { this->gamma=1; } ALM_Katyusha(const char* matrix_file) : Primal_Dual_LOOPLESS_Katyusha0<L,D>(matrix_file),data_A(), data_M() { this->gamma=1; } /* ALM_Katyusha(const char* matrix_file, const char* matrix_file2) : Primal_Dual_LOOPLESS_Katyusha0<L,D>(),data_A(matrix_file), data_M(matrix_file2) { this->matrix_merge(data_A,data_M); this->gamma=1; } */ inline void set_L_phi(){ for(int i=m_3; i<m_2+ m_3; i++){ L_phi[i]= this->nsamples; } for(int i= 0; i<m_3; i++){ L_phi[i]= this->nsamples/beta_s; } } L get_nb_features(){ return data_A.get_d(); } inline D value_of_phi_i(D x, L i) { if ( i>= data_M.nsamples){ return value_of_f_j(x, i- data_M.nsamples); } else{ D tmp= prox_of_h_star_j(1.0/beta_s*x+ lambda_s[i],beta_s,i); return beta_s*(x*tmp- value_of_h_star_j(tmp,i)- beta_s/2*(tmp- lambda_s[i])*(tmp- lambda_s[i])); } } inline D gradient_of_phi_i(D x, L i){ if (i>= data_M.nsamples){ return gradient_of_f_j(x,i- data_M.nsamples); } else{ D tmp= prox_of_h_star_j(1.0/beta_s*x+ lambda_s[i],beta_s,i); return beta_s*tmp; } } inline D value_of_phistar_i(D x, L i) { if ( i>= data_M.nsamples){ return value_of_f_star_j(x,i- data_M.nsamples); } else{ return beta_s*value_of_h_star_j(x/beta_s,i)+ 0.5*(x- beta_s*lambda_s[i])*(x- beta_s*lambda_s[i]); } } inline D value_of_g_j(D x, L j){ return value_of_P_j(x,j)+ beta_s/2*(x- x_s[j])*(x- x_s[j]); } inline D value_of_gstar(vector<D> &x){ D res= 0; L l= x.size(); D tmp= 0; for (L i= 0; i< l; i++){ tmp= prox_of_P_j(1.0/beta_s*x[i]+ x_s[i],beta_s,i); res+= x[i]*tmp- value_of_P_j(tmp,i)- beta_s/2*(tmp- x_s[i])*(tmp- x_s[i]); } return res; } inline D gradient_of_gstar_j(D x, L j){ return prox_of_P_j(1.0/beta_s*x+ x_s[j],beta_s,j); } inline D value_of_gstar_minus(vector<D> &x, D scal){ L l= x.size(); vector<D> tmp(l,0); for (L j= 0;j< l; j++){ tmp[j]= -scal*x[j]; } return value_of_gstar(tmp); } /* inline D get_lambda1(){return lambda1;} inline D get_lambda2(){return lambda2;} */ void compute_x(){ for (L i=0; i< this->nfeatures; i++){ x_s[i]= this->primal_x[i]; } for (L j=m_3; j< m_2+ m_3; j++){ Ax_s[j- m_3]= compute_AiTx_s(j); } for (L j=0; j< m_3; j++){ Mx_s[j]= compute_AiTx_s(j); } } D compute_AiTx_s(L i){ D res=0; for (L k = this->ptr[i]; k < this->ptr[i + 1];k++) { L j=this->row_idx[k]; res+= this->A[k]*x_s[j]; } return res; } inline void compute_just_in_time_prox_grad(D tau, D u, D &x, L t0,L t1, D w, D &y, L j){ D u_s=u-tau_s*beta_s*x_s[j]; compute_just_in_time_prox_grad_without_x_s(tau, u_s, x, t0, t1, w, y,j); } void compute_function_value(){ D res= 0; for (L i= 0; i< this->nfeatures; i++){ res+= value_of_P_j(x_s[i],i); } for (L i= 0; i< data_M.nsamples; i++){ res+= value_of_h_j(Mx_s[i],i); } for (L i= 0; i<data_A.nsamples; i++){ res+= value_of_f_j(Ax_s[i],i); } function_value= res; } /*void compute_infeasibility(){ D tmp1= 0; D tmp2= 0; for (L j=0; j< this->nsamples; j++){ if (1- Ax_s[j]> tmp1){ tmp1= 1- Ax_s[j]; } tmp2+= max(0.0,1- Ax_s[j]); } residual1= tmp1; residual2= tmp2/this->nsamples; }*/ inline void compute_m0(D beta0, D val_eta, D val_rho, L val_tau){ cout<<"beta0="<<beta0<<"val_eta="<<val_eta<<"; val_rho="<<val_rho<<"; val_tau="<<val_tau<<endl; m_s= this->nsamples/val_tau*1e+6; //D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0)); //cout<<"tmp7: "<<tmp7<<"; "<<val_tau/(this->n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))<<endl; //m_0=(2*log(val_rho)+log(val_eta)+log(2))/log(tmp7); cout<<" m_s="<<m_s<<endl; } void update_y(){ for(L j=0;j<m_3;j++) { D aiTx= Mx_s[j]; lambda_s[j]= prox_of_h_star_j(1.0/beta_s*aiTx+ lambda_s[j],beta_s,j); } } void Initialize(D beta_0, D epsilon_0, D val_eta, D val_rho,L val_tau, vector<D> & x0,vector<D> & y0){ cout<<"start initializing"<<endl; set_matrix_M(); set_matrix_A(); this->tau=val_tau; m_1=data_A.get_d(); m_2=data_A.get_n(); m_3=data_M.get_n(); cout<<"m_1="<<m_1<<endl; cout<<"m_2="<<m_2<<endl; cout<<"m_3="<<m_3<<endl; beta_s=beta_0; //tau_s= this->nsamples; tau_s= 1; epsilon_s=epsilon_0; compute_m0(beta_s,val_eta,val_rho,val_tau); eta=val_eta; rho=val_rho; x_s.resize(m_1,0); old_x_s.resize(m_1,0); lambda_s.resize(m_3,0); old_lambda_s.resize(m_3,0); for(L i=0;i<m_1;i++){ x_s[i]=x0[i]; old_x_s[i]= x0[i]; } for(L j=0;j<m_3;j++){ lambda_s[j]=y0[j]; old_lambda_s[j]= y0[j]; } Ax_s.clear(); Ax_s.resize(m_2,0); old_Ax_s.clear(); old_Ax_s.resize(m_2,0); Mx_s.clear(); Mx_s.resize(m_3,0); old_Mx_s.clear(); old_Mx_s.resize(m_3,0); L_phi.clear(); L_phi.resize(m_2+ m_3,0); for(int i=0; i< m_3; i++){ L_phi[i]= this->nsamples/beta_0; } for(int i=m_3; i< m_2+ m_3; i++){ L_phi[i]= this->nsamples; } } void reset_everything(){ epsilon_s*=rho; beta_s*=eta; } void update_m_s(L val_tau){ D tmp= 0; D tmpx= 0; D tmpy= 0; D tmpy2= 0; for(L j=0;j<m_3;j++) { D tmp_p= prox_of_h_star_j(Mx_s[j]/beta_s/eta+ lambda_s[j], beta_s/eta, j); tmpy+=(tmp_p- lambda_s[j])*(tmp_p- lambda_s[j]); tmp+= (lambda_s[j]- old_lambda_s[j])*(lambda_s[j]- old_lambda_s[j]); tmpy2+= (beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j])*(beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j]); } for (L i= 0; i< m_1;i++){ tmpx= (x_s[i]- old_x_s[i])*(x_s[i]- old_x_s[i]); } D tmp4= 2*epsilon_s+ beta_s*tmp; D tmp5= (1- eta)*beta_s/2*tmpy; D tmp6= sqrt(tmp)*beta_s*(1+ eta)*L_h; D tmp7= sqrt(tmp)*sqrt(tmpy2); D tmp1= log(tmp4+ tmp5+ tmp6+ tmp7+ 2/(2*eta- 1)*tau_s*beta_s/2*tmpx); D tmp2= log(epsilon_s)+ log(rho)- log(2); D tmp3= sqrt(lambda2/this->sumLi); m_s= ceil((tmp1- tmp2)/log(2)*4*max(1.0*this->nsamples,1/tmp3)/val_tau); } inline void compute_and_record_res(){ if(nb_outer_iters%print_every_N_ALM==0){ compute_function_value(); cout<<setprecision(9)<<"Iteration: "<<nb_outer_iters<<"; time="<<running_time_ALM<< "; function value="<<function_value<<endl; samp_ALM<<setprecision(9)<<nb_outer_iters<<" "<<running_time_ALM<<" "<< function_value<<" "<<endl; } } void ALM_solve_with_L_Katyusha(D beta_0, D epsilon_0, D eta, D rho,vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, string filename1, string filename2, D time){ Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0); nb_outer_iters=0; //string sampname2= ALGparam.data_dir +"/results/L_Katyusha_"+filename2; string sampname2= "results/L_Katyusha_"+filename2; this->samp.open(sampname2.c_str()); string sampname_x="results/L_Katyusha_x_"+filename1; //filename1= ALGparam.data_dir +"/results/ALM_"+filename1; filename1= "results/ALM_"+filename1; samp_x_ALM.open(sampname_x.c_str()); samp_ALM.open(filename1.c_str()); running_time_ALM=0; print_every_N_ALM=p_N_1; this->set_print_every_N(p_N_2); compute_and_record_res(); D start; start = std::clock(); //cout<<"m0="<<ceil(m_s/this->n*val_tau)<<endl; cout<<"m_s= "<< ceil(m_s/this->nsamples*val_tau)<<"; beta_s="<<beta_s<<"; epsilon_s="<<epsilon_s<<endl; //this->L_Katyusga_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1); rescale(); set_L_phi(); this->loopless_Katyusha(y0, x_s, filename2, L_phi, mu_g+ tau_s*beta_s, epsilon_s, ceil(m_s/this->nsamples*val_tau), val_tau, 1, 1, 0, 1); for(L i=0;i<m_1;i++){ old_x_s[i]=x_s[i]; } for(L i=0;i<m_2;i++){ old_Ax_s[i]=Ax_s[i]; } compute_x(); for(L i=0;i<m_3;i++){ old_lambda_s[i]=lambda_s[i]; } update_y(); update_m_s(val_tau); nb_outer_iters++; running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; compute_and_record_res(); start = std::clock(); reset_everything(); running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; while(nb_outer_iters<max_nb_outer){ start = std::clock(); cout<<"ms="<<ceil(m_s/this->nsamples*val_tau)<<"; beta_s="<<beta_s<<"; epsilon_s"<<epsilon_s<<endl; rescale(); set_L_phi(); this->loopless_Katyusha(y0, x_s, filename2, L_phi, mu_g+ tau_s*beta_s, epsilon_s, ceil(m_s/this->nsamples*val_tau), val_tau, 1, 1, 0, 1); for(L i=0;i<m_1;i++){ old_x_s[i]=x_s[i]; } for(L i=0;i<m_2;i++){ old_Ax_s[i]=Ax_s[i]; } for(L i=0;i<m_3;i++){ old_lambda_s[i]=lambda_s[i]; } compute_x(); update_y(); update_m_s(val_tau); nb_outer_iters++; running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; compute_and_record_res(); start = std::clock(); reset_everything(); running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC; if (running_time_ALM> time){ break; } } for (L i= 0; i< m_1; i++){ samp_x_ALM<< x_s[i]<< endl; } } }; #endif /* MIN_SMOOTH_CONVEX_H */
{ "alphanum_fraction": 0.6068454364, "avg_line_length": 26.0477223427, "ext": "h", "hexsha": "ea4eaad848493fd836b91095cdb94b68909bfe1e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": [ "BSD-Source-Code" ], "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_path": "IPALM/ALM_Katyusha.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-Source-Code" ], "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_path": "IPALM/ALM_Katyusha.h", "max_line_length": 189, "max_stars_count": null, "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": [ "BSD-Source-Code" ], "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_path": "IPALM/ALM_Katyusha.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4191, "size": 12008 }
/* specfunc/bessel_K0.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_exp.h" #include "gsl_sf_bessel.h" #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on SLATEC bk0(), bk0e() */ /* chebyshev expansions series for bk0 on the interval 0. to 4.00000d+00 with weighted error 3.57e-19 log weighted error 18.45 significant figures required 17.99 decimal places required 18.97 series for ak0 on the interval 1.25000d-01 to 5.00000d-01 with weighted error 5.34e-17 log weighted error 16.27 significant figures required 14.92 decimal places required 16.89 series for ak02 on the interval 0. to 1.25000d-01 with weighted error 2.34e-17 log weighted error 16.63 significant figures required 14.67 decimal places required 17.20 */ static double bk0_data[11] = { -0.03532739323390276872, 0.3442898999246284869, 0.03597993651536150163, 0.00126461541144692592, 0.00002286212103119451, 0.00000025347910790261, 0.00000000190451637722, 0.00000000001034969525, 0.00000000000004259816, 0.00000000000000013744, 0.00000000000000000035 }; static cheb_series bk0_cs = { bk0_data, 10, -1, 1, 10 }; static double ak0_data[17] = { -0.07643947903327941, -0.02235652605699819, 0.00077341811546938, -0.00004281006688886, 0.00000308170017386, -0.00000026393672220, 0.00000002563713036, -0.00000000274270554, 0.00000000031694296, -0.00000000003902353, 0.00000000000506804, -0.00000000000068895, 0.00000000000009744, -0.00000000000001427, 0.00000000000000215, -0.00000000000000033, 0.00000000000000005 }; static cheb_series ak0_cs = { ak0_data, 16, -1, 1, 10 }; static double ak02_data[14] = { -0.01201869826307592, -0.00917485269102569, 0.00014445509317750, -0.00000401361417543, 0.00000015678318108, -0.00000000777011043, 0.00000000046111825, -0.00000000003158592, 0.00000000000243501, -0.00000000000020743, 0.00000000000001925, -0.00000000000000192, 0.00000000000000020, -0.00000000000000002 }; static cheb_series ak02_cs = { ak02_data, 13, -1, 1, 8 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(x <= 2.0) { const double lx = log(x); const double ex = exp(x); int stat_I0; gsl_sf_result I0; gsl_sf_result c; cheb_eval_e(&bk0_cs, 0.5*x*x-1.0, &c); stat_I0 = gsl_sf_bessel_I0_e(x, &I0); result->val = ex * ((-lx+M_LN2)*I0.val - 0.25 + c.val); result->err = ex * ((M_LN2+fabs(lx))*I0.err + c.err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_I0; } else if(x <= 8.0) { const double sx = sqrt(x); gsl_sf_result c; cheb_eval_e(&ak0_cs, (16.0/x-5.0)/3.0, &c); result->val = (1.25 + c.val) / sx; result->err = c.err / sx; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { const double sx = sqrt(x); gsl_sf_result c; cheb_eval_e(&ak02_cs, 16.0/x-1.0, &c); result->val = (1.25 + c.val) / sx; result->err = (c.err + GSL_DBL_EPSILON) / sx; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if(x <= 2.0) { const double lx = log(x); int stat_I0; gsl_sf_result I0; gsl_sf_result c; cheb_eval_e(&bk0_cs, 0.5*x*x-1.0, &c); stat_I0 = gsl_sf_bessel_I0_e(x, &I0); result->val = (-lx+M_LN2)*I0.val - 0.25 + c.val; result->err = (fabs(lx) + M_LN2) * I0.err + c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_I0; } else { gsl_sf_result K0_scaled; int stat_K0 = gsl_sf_bessel_K0_scaled_e(x, &K0_scaled); int stat_e = gsl_sf_exp_mult_err_e(-x, GSL_DBL_EPSILON*fabs(x), K0_scaled.val, K0_scaled.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_K0); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_K0_scaled(const double x) { EVAL_RESULT(gsl_sf_bessel_K0_scaled_e(x, &result)); } double gsl_sf_bessel_K0(const double x) { EVAL_RESULT(gsl_sf_bessel_K0_e(x, &result)); }
{ "alphanum_fraction": 0.6460257107, "avg_line_length": 25.688372093, "ext": "c", "hexsha": "9ef4b73c8fd319288f3fe73faeed57ed3f856fca", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_K0.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_K0.c", "max_line_length": 76, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_K0.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": 1958, "size": 5523 }
/* Copyright 2016, Alistair Boyle, 3-clause BSD License */ #include "config.h" #include <stdio.h> #include <stdlib.h> /* malloc, free */ #include <string.h> /* memcpy, memset */ #include <math.h> /* sqrt */ #include <assert.h> /* assert */ #include <time.h> /* clock */ //#include <cblas.h> //#include <lapacke.h> #include "argv.h" #include "file.h" #include "fwd.h" #include "inv.h" #include "model.h" #include "matrix.h" static int do_fwd_solve(const char * file, double tol) { int ret = 1; model * mdl = malloc_model(); printf("-- loading from file %s --\n", file); int nret = readfile(file, mdl); const int n_meas = mdl->n_stimmeas; const int frames = mdl->n_params[1]; double meas[frames * n_meas]; if(!nret) { fprintf(stderr, "error: read %s failed\n", file); goto fwd_quit; } printf("-- forward solutions --\n"); printf("%d parameter frame%s\n", frames, frames == 1 ? "" : "s"); if(frames < 1) { fprintf(stderr, "error: nothing to do\n"); goto fwd_quit; } if(mdl->n_data[0] > 0) { assert(mdl->n_data[0] == mdl->n_stimmeas); assert(mdl->n_data[1] == mdl->n_params[1]); } nret = fwd_solve(mdl, meas); if(!nret) { fprintf(stderr, "error: bad forward solve\n"); goto fwd_quit; } for(int idx = 0; idx < frames; idx++) { /* calculated measurements to expected */ if(mdl->n_data[0] > 0) { printf("frame#%d\n", idx + 1); printf("meas# %18s %18s\n", "calculated", "from file"); double rmse = 0; /* root mean squared error from expected */ for(int i = 0; i < mdl->n_stimmeas; i++) { const double data_calc = meas[idx * n_meas + i]; const double data_expect = mdl->data[i + mdl->n_data[0] * idx]; printf("%4d %18.8g %18.8g\n", i + 1, data_calc, data_expect); const double dm = data_calc - data_expect; rmse += dm * dm; } rmse = sqrt(rmse / (double) mdl->n_data[0]); printf(" RMSE = %g\n", rmse); printf(" tolerance = %g\n", tol); if (rmse > tol) { fprintf(stderr, "fail: calculated measurements do not match expected\n"); ret = 1; goto fwd_quit; } } else { printf("frame#%d\n", idx + 1); printf("meas# %18s\n", "calculated"); for(int i = 0; i < mdl->n_stimmeas; i++) { const double data_calc = meas[idx * n_meas + i]; printf("%4d %18.04g\n", i + 1, data_calc); } } } ret = 0; printf("-- completed --\n"); fwd_quit: free_model(mdl); return ret; } #define max(a,b) (((a) > (b)) ? (a) : (b)) static int do_inv_solve(const char * file, const double tol) { int ret = 1; model * mdl = malloc_model(); printf("-- loading from file %s --\n", file); int nret = readfile(file, mdl); const int frames = mdl->n_data[1] > 1 ? mdl->n_data[1] - 1 : 0; if(!nret) { fprintf(stderr, "error: read %s failed\n", file); free_model(mdl); return 1; } printf("-- inverse solutions --\n"); printf("%d measurement frame%s\n", frames, frames == 1 ? "" : "s"); if(frames < 1) { fprintf(stderr, "error: nothing to do\n"); free_model(mdl); return 1; } printf_model(mdl, 1); assert(mdl->n_data[0] > 0); assert(mdl->n_data[0] == mdl->n_stimmeas); if(mdl->n_params[1] > 1) { assert(mdl->n_data[1] == mdl->n_params[1]); } const int is_pmap = (mdl->fwd.n_pmap > 0); int n_params = 0; if( mdl->n_params[1] > 0 ) { n_params = mdl->n_params[0]; } else if( !is_pmap ) { n_params = mdl->fwd.n_elems; } else { for(int i = 0; i < mdl->fwd.n_pmap; i++) { n_params = max(n_params, mdl->fwd.pmap_param[i]); } n_params++; } mdl->n_params[0] = n_params; double params[frames * n_params]; memset(params, 0, sizeof(double) * frames * n_params); nret = inv_solve(mdl, params); if(!nret) { fprintf(stderr, "error: bad inverse solve\n"); goto inv_quit; } for(int idx = 0; idx < frames; idx++) { /* calculated measurements to expected */ if(mdl->n_params[1] > 1) { printf("frame#%d\n", idx + 1); printf("param#%18s %18s\n", "calculated", "from file"); const int cols = mdl->n_params[1]; const int rows = mdl->n_params[0]; assert(cols == 3); /* TODO currently: params = [ J_background, ignore, expected ] */ double rmse = 0; /* root mean squared error from expected */ for(int i = 0; i < rows; i++) { const double params_calc = params[i + 0 * rows]; const double params_expect = mdl->params[i + 2 * rows]; printf("%4d %18.8e %18.8e\n", i + 1, params_calc, params_expect); const double dp = params_calc - params_expect; rmse += dp * dp; } rmse = sqrt(rmse / (double) n_params); printf(" RMSE = %g\n", rmse); if (rmse > tol) { fprintf(stderr, "fail: calculated parameters do not match expected\n"); goto inv_quit; } break; /* TODO only handle one frame in checking mode currently */ } else { printf("frame#%d\n", idx + 1); printf("param#%18s\n", "calculated"); const int rows = mdl->n_params[0]; for(int i = 0; i < n_params; i++) { const double params_calc = params[i + idx * rows]; printf("%4d %18.04g\n", i + 1, params_calc); } } } ret = 0; printf("-- completed --\n"); inv_quit: free_model(mdl); return ret; } int main(int argc, char ** argv) { int ret = 0; args_t args; const int N = 1; double dt [N]; double mean_dt = 0; double std_dt = 0; if(parse_argv(argc, argv, &args) != 0) { return 1; } for(int i = 0; i < N; i++) { clock_t start = clock(); printf("%s %s %d\n", args.file[0], args.file[1], args.mode); switch(args.mode) { case FORWARD_SOLVER: ret = do_fwd_solve(args.file[0], args.tol); break; case INVERSE_SOLVER: ret = do_inv_solve(args.file[1], args.tol); break; default: return 0; } clock_t stop = clock(); dt[i] = (stop - start) / CLOCKS_PER_SEC; mean_dt += dt[i] / N; if(ret) { break; } } if(ret) { printf("error: solve failed\n"); return ret; } for(int i = 0; i < N; i++) { const double tmp = dt[i] - mean_dt; std_dt += tmp * tmp; } std_dt = sqrt(std_dt / N); printf("%f\n", mean_dt); printf("runtime: %0.0f:%02.0f:%02.4fs ± %2.4fs\n", 0.0, 0.0, mean_dt, std_dt); printf("total: %0.0f:%02.0f:%02.4fs\n", 0.0, 0.0, mean_dt*N); return 0; }
{ "alphanum_fraction": 0.5059085222, "avg_line_length": 33.6121495327, "ext": "c", "hexsha": "0d7b3e2a140ed06704f898ea3073d223a37bc857", "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": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "boyle/zedhat", "max_forks_repo_path": "tests/perf.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_issues_repo_issues_event_max_datetime": "2018-04-12T09:34:48.000Z", "max_issues_repo_issues_event_min_datetime": "2018-03-30T02:37:55.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "boyle/zedhat", "max_issues_repo_path": "tests/perf.c", "max_line_length": 96, "max_stars_count": 2, "max_stars_repo_head_hexsha": "05a10333eda3b1569a9acd6e8b8fca245f9f012e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "boyle/zedhat", "max_stars_repo_path": "tests/perf.c", "max_stars_repo_stars_event_max_datetime": "2021-07-06T01:26:06.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-08T16:02:51.000Z", "num_tokens": 2089, "size": 7193 }
// Implementation of interface described in viewer_image.h. #include <math.h> #include <unistd.h> #include <gsl/gsl_statistics_double.h> #include "meta_read_wrapper.h" #include "utilities.h" #include "viewer_image.h" // We use a seperate thread to fill in the stuff that takes some time // to create. static gpointer create_pyramid (ViewerImage *self) { g_assert (self->pixmaps != NULL); if ( self->pyramid_cache != NULL ) { g_assert (self->scratch_dir == NULL); // We never unref this pyramid. The reason is that we don't want // to keep this thread alive just for that purpose, and since the // unreffing the pyramid triggers a pyramid_cache_release, it has // to be done by its creator. It will get reclaimed anyway by the // OS. self->pyramid = pyramid_new_using_cache (self->base_name->str, self->pixmaps, self->pyramid_cache); } else { g_assert (self->scratch_dir != NULL); g_assert (self->pyramid_cache == NULL); self->pyramid = pyramid_new (self->base_name->str, self->pixmaps, self->scratch_dir->str); } // Uncomment to get debugging snapshots of the pyramid layers. // pyramid_export_as_float_blobs (self->pyramid, "pyramid_snapshot"); // pyramid_export_as_jpeg_files (self->pyramid, "pyramid_snapshot"); g_mutex_lock (self->pyramid_mutex); self->pyramid_ready = TRUE; g_mutex_unlock (self->pyramid_mutex); // This thread isn't even joinable, but we keep the compiler happy // with a return statement anyway. return NULL; } ViewerImage * viewer_image_new (const char *base_name, PixMapsSpec *pixmaps, gdouble sigmas, size_t x_offset, size_t y_offset, PyramidCache *pyramid_cache) { ViewerImage *self = g_new (ViewerImage, 1); self->base_name = g_string_new (base_name); GString *mn = g_string_append (g_string_new (base_name), ".meta"); GString *dn = g_string_append (g_string_new (base_name), ".img"); self->meta = meta_read_wrapper (mn->str); meta_parameters *md = self->meta; // Convenience alias. self->size_x = md->general->sample_count; self->size_y = md->general->line_count; self->x_offset = x_offset; self->y_offset = y_offset; self->pixmaps = pix_maps_spec_ref (pixmaps); self->sigmas = sigmas; g_assert (self->size_x <= INT_MAX); gint sx = self->size_x; g_assert (self->size_y <= INT_MAX); gint sy = self->size_y; FILE *df = fopen (dn->str, "r"); g_assert (df != NULL); // We will form the quick look by sampling every pixel_strid'th // pixel. This number reflects a critical tradeoff -- bigger means // that we won't have a quick view of sufficiently high resolution // ready when the user tries to zoom in on an image, and interactive // performance will suffer when we create one on the fly. On the // other hand, setting this number too small may run some machines // out of RAM and into virtual memory, which is also likely to // degrade interactive performance significantly. Both these // problems go away once we have the pyramid fully biult, but of // course this takes a few seconds to do. const size_t pixel_stride = 8; self->quick_view_stride = pixel_stride; // Quick view dimensions. self->qvw = ceil ((double) sx / pixel_stride); self->qvh = ceil ((double) sy / pixel_stride); // Memory for quick_view. self->quick_view = g_new (float, self->qvw * self->qvh); // Storage for one image row. float *row_buffer = g_new (float, sx); size_t ii, jj; size_t cqvr = 0, cqvc = 0; // Current quick_view row and column. for ( jj = 0 ; jj < sy ; jj += pixel_stride, cqvr++ ) { cqvc = 0; size_t read_count = fread (row_buffer, sizeof (float), sx, df); g_assert (read_count == sx); int return_code = fseek (df, sizeof (float) * sx * (pixel_stride - 1), SEEK_CUR); g_assert (return_code == 0); for ( ii = 0 ; ii < sx ; ii += pixel_stride, cqvc++ ) { float pv = row_buffer[ii]; if ( G_BYTE_ORDER == G_LITTLE_ENDIAN ) { swap_bytes_32 ((unsigned char *) &pv); } (self->quick_view)[cqvr * self->qvw + cqvc] = pv; } } size_t qvpc = self->qvw * self->qvh; // Quick view pixel count. // Apply pixmaps. for ( ii = 0 ; ii < qvpc ; ii++ ) { (self->quick_view)[ii] = pix_maps_spec_map (self->pixmaps, (self->quick_view)[ii]); } // Double precision version of quickview data so we can use GSL // library functions for statistics. double *qvad = g_new (double, qvpc); for ( ii = 0 ; ii < qvpc ; ii++ ) { qvad[ii] = (self->quick_view)[ii]; } // Compute statistics for OpenGL to use for scaling. IMPROVEME: it // might be possible to use OpenGL to do this or near enough using // the faster functions from the OpenGL imaging subset. gsl_stats_minmax (&(self->min), &(self->max), qvad, 1, qvpc); self->mean = gsl_stats_mean (qvad, 1, qvpc); self->sdev = gsl_stats_sd_m (qvad, 1, qvpc, self->mean); g_free (qvad); g_free (row_buffer); if ( pyramid_cache == NULL ) { self->pyramid_cache = NULL; self->scratch_dir = g_string_new ("/tmp/"); } else { self->pyramid_cache = pyramid_cache_ref (pyramid_cache); self->scratch_dir = NULL; } if ( !g_thread_supported () ) { g_thread_init (NULL); } self->pyramid_ready = FALSE; self->pyramid_mutex = g_mutex_new (); self->pyramid = NULL; GThread *pyramid_thread = g_thread_create ((GThreadFunc) create_pyramid, self, FALSE, NULL); g_assert (pyramid_thread != NULL); // We try to keep things snappy for the use during the time before // the pyramids are finished. g_thread_set_priority (pyramid_thread, G_THREAD_PRIORITY_LOW); g_string_free (mn, TRUE); g_string_free (dn, TRUE); self->reference_count = 1; return self; } Pyramid * viewer_image_pyramid (ViewerImage *self) { Pyramid *result = NULL; g_mutex_lock (self->pyramid_mutex); if ( self->pyramid_ready ) { result = self->pyramid; } g_mutex_unlock (self->pyramid_mutex); return result; } ViewerImage * viewer_image_ref (ViewerImage *self) { self->reference_count++; return self; } void viewer_image_unref (ViewerImage *self) { self->reference_count--; if ( self->reference_count == 0 ) { while ( viewer_image_pyramid (self) == NULL ) { // oo icky poo a polling loop in a destructor! const guint sleep_time = 1; sleep (sleep_time); } viewer_image_free (self); } } gboolean viewer_image_free (ViewerImage *self) { if ( viewer_image_pyramid (self) == NULL ) { return FALSE; } g_string_free (self->base_name, TRUE); meta_free (self->meta); pix_maps_spec_unref (self->pixmaps); g_free (self->quick_view); if ( self->pyramid_cache != NULL ) { g_assert (self->scratch_dir == NULL); pyramid_cache_unref (self->pyramid_cache); // Note that we deliberately don't unref the pyramid here; see // comments in create_pyramid(). } else { g_assert (self->scratch_dir != NULL); g_assert (self->pyramid_cache == NULL); g_string_free (self->scratch_dir, TRUE); pyramid_unref (self->pyramid); } g_mutex_free (self->pyramid_mutex); g_free (self); return TRUE; }
{ "alphanum_fraction": 0.674675234, "avg_line_length": 28.983805668, "ext": "c", "hexsha": "8a519734d954dea8e5d7710823e828b8b3be2636", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/ssv/viewer_image.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/ssv/viewer_image.c", "max_line_length": 78, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/ssv/viewer_image.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 2007, "size": 7159 }
/* 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_CRASH_CONSISTENT_ALLOCATOR_H__ #define __CCPM_CRASH_CONSISTENT_ALLOCATOR_H__ #include <ccpm/interfaces.h> #include <common/exceptions.h> #include <gsl/pointers> #include <iosfwd> #include <memory> #include <string> #include <vector> namespace ccpm { struct area_top; struct cca : public IHeap_expandable { using byte_span = common::byte_span; using persist_type = gsl::not_null<persister *>; /* * An objection arose to requiring multiple arguments for the cca constructor. * This struct allows construction from a single argument in all cases. * cca.h may not be the best place for this, as cca does not itsenf use the struct. */ struct ctor_args { persist_type persister; region_span regions; bool force_init; ownership_callback_type callee_owns; }; private: using top_vec_t = std::vector<std::unique_ptr<area_top>>; top_vec_t _top; top_vec_t::difference_type _last_top_allocate; top_vec_t::difference_type _last_top_free; persist_type _persist; void init( region_span regions , ownership_callback_type resolver , bool force_init ); public: explicit cca(persist_type persist, region_span regions, ownership_callback_type resolver); explicit cca(persist_type persist, region_span regions); explicit cca(persist_type persist); ~cca(); cca(const cca &) = delete; const cca& operator=(const cca &) = delete; bool reconstitute( region_span regions , ownership_callback_type resolver , bool force_init ) override; status_t allocate( void * & ptr_ , std::size_t bytes_ , std::size_t alignment_ ) override; void * allocate(std::size_t bytes_, std::size_t alignment_ = 1) { void * ptr = nullptr; if(allocate(ptr, bytes_, alignment_) != 0) throw General_exception("ccpm::cca::allocate failed"); return ptr; } void * allocate_root(std::size_t bytes_, std::size_t alignment_ = 8) { void * ptr = nullptr; if(allocate(ptr, bytes_, alignment_) != 0) throw General_exception("ccpm::cca::allocate failed"); set_root(common::make_byte_span(ptr, bytes_)); return ptr; } status_t free( void * & ptr_ , std::size_t bytes_ ) override; void add_regions( region_span ) override; bool includes( const void *addr ) const override; status_t remaining( std::size_t & out_size_ ) const override; region_vector_t get_regions() const override; void set_root( byte_span ); byte_span get_root() const; void print(std::ostream &, const std::string &title = "cca") const; }; } #endif
{ "alphanum_fraction": 0.7086956522, "avg_line_length": 24.7692307692, "ext": "h", "hexsha": "a73222f3532a8ea1f9b323680fbca60b2f6f6594", "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/cca.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/cca.h", "max_line_length": 92, "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/cca.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": 833, "size": 3220 }
#include "vector.h" #include "math.h" #include "mem.h" #include "string_utils.h" #include "ut_utils.h" typedef struct { char *name; char age; } nage_t; void free_nage_t(void *pnage) { nage_t *nage = pnage; ufree(nage->name); ufree(nage); } void *copy_nage_t(const void *pnage) { const nage_t *nage = pnage; nage_t *n = umalloc(sizeof(*n)); UASSERT(n); n->name = ustring_dup(nage->name); n->age = nage->age; return n; } void test_uvector_copy(bool verbose) { (void)verbose; uvector_t *v = uvector_create(); uvector_set_void_destroyer(v, free_nage_t); uvector_set_void_copier(v, copy_nage_t); nage_t *n = umalloc(sizeof(*n)); *n = (nage_t){ustring_dup("john"), 34}; uvector_append(v, G_PTR(n)); // v owns *n data uvector_t *v2 = uvector_copy(v); // v2 has shallow copy of *n2 uvector_t *v3 = uvector_deep_copy(v); // v3 has deep copy of *n2, must set own uvector_destroy(v); uvector_destroy(v2); uvector_destroy(v3); } void test_uvector_bsearch(void) { uvector_t *v = uvector_create(); uvector_append(v, G_INT(1)); uvector_append(v, G_INT(2)); uvector_append(v, G_INT(4)); uvector_append(v, G_INT(3)); uvector_sort(v); // [1, 2, 3, 4]] UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), 1); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 2); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), 3); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX); uvector_remove_at(v, 1); // [1, 3, 4] UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 1); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), 2); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX); uvector_pop_back(v); // [1, 3] UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), 0); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 1); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX); uvector_pop_at(v, 0); // [3] UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), 0); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX); uvector_pop_at(v, 0); UASSERT_INT_EQ(uvector_get_size(v), 0); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(1)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(2)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(3)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(4)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(400)), SIZE_MAX); UASSERT_INT_EQ(uvector_bsearch(v, G_INT(-400)), SIZE_MAX); uvector_destroy(v); } void test_uvector_next_permutation(bool verbose) { uvector_t *v = uvector_create(); uvector_append(v, G_INT(4)); uvector_append(v, G_INT(3)); uvector_append(v, G_INT(1)); uvector_append(v, G_INT(2)); do { if (verbose) uvector_print(v); } while (uvector_next_permutation(v)); uvector_destroy(v); } void test_uvector_serialization(bool verbose) { char *vs; uvector_t *v = uvector_create(); vs = uvector_as_str(v); UASSERT_STR_EQ(vs, "[]"); ufree(vs); uvector_append(v, G_INT(11)); uvector_append(v, G_INT(22)); uvector_append(v, G_INT(33)); uvector_append(v, G_STR(ustring_dup("44"))); uvector_append(v, G_CSTR("5")); uvector_append(v, G_VECTOR(uvector_deep_copy(v))); uvector_append(v, G_VECTOR(uvector_deep_copy(v))); if (verbose) uvector_print(v); vs = uvector_as_str(v); UASSERT_STR_EQ(vs, "[11, 22, 33, \"44\", \"5\", [11, 22, 33, \"44\", \"5\"], [11, 22, 33, \"44\", \"5\", [11, 22, 33, \"44\", \"5\"]]]"); ufree(vs); uvector_destroy(v); } void test_uvector_api() { uvector_t *v = uvector_create(); uvector_append(v, G_INT(0)); UASSERT(uvector_get_capacity(v) >= VECTOR_INITIAL_CAPACITY); uvector_reserve_capacity(v, 1000); UASSERT_INT_EQ(uvector_get_capacity(v), 1000); uvector_destroy(v); v = uvector_create_with_size(3, G_NULL()); UASSERT_INT_EQ(uvector_get_size(v), 3); uvector_append(v, G_INT(11)); uvector_append(v, G_INT(22)); uvector_append(v, G_INT(33)); UASSERT_INT_EQ(uvector_get_size(v), 6); UASSERT(G_IS_NULL(uvector_get_at(v, 0))); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 3)), 11); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 4)), 22); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 5)), 33); uvector_swap(v, 4, 5); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 4)), 33); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 5)), 22); uvector_resize(v, 0, G_NULL()); UASSERT(uvector_is_empty(v)); uvector_append(v, G_INT(44)); UASSERT_INT_EQ(uvector_get_size(v), 1); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 44); uvector_set_at(v, 0, G_INT(2222)); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 2222); ugeneric_t *a = uvector_get_cells(v); UASSERT_INT_EQ(G_AS_INT(a[0]), 2222); uvector_destroy(v); v = uvector_create(); UASSERT_INT_EQ(uvector_get_size(v), 0); UASSERT(uvector_is_empty(v)); uvector_append(v, G_INT(11)); UASSERT(!uvector_is_empty(v)); UASSERT_INT_EQ(uvector_get_size(v), 1); UASSERT_INT_EQ(G_AS_INT(uvector_pop_back(v)), 11); UASSERT(uvector_is_empty(v)); UASSERT_INT_EQ(uvector_get_size(v), 0); uvector_resize(v, 0, G_NULL()); uvector_append(v, G_INT(200)); uvector_append(v, G_INT(100)); UASSERT_INT_EQ(uvector_get_size(v), 2); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 200); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 1)), 100); uvector_insert_at(v, 1, G_INT(300)); UASSERT_INT_EQ(uvector_get_size(v), 3); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 200); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 1)), 300); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 2)), 100); UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 200); UASSERT_INT_EQ(uvector_get_size(v), 2); UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 300); UASSERT_INT_EQ(uvector_get_size(v), 1); UASSERT_INT_EQ(G_AS_INT(uvector_pop_at(v, 0)), 100); UASSERT_INT_EQ(uvector_get_size(v), 0); uvector_resize(v, 1000, G_NULL()); UASSERT_INT_EQ(uvector_get_size(v), 1000); uvector_destroy(v); v = uvector_create(); uvector_append(v, G_STR(ustring_dup("1"))); uvector_append(v, G_STR(ustring_dup("2"))); uvector_append(v, G_STR(ustring_dup("3"))); uvector_append(v, G_STR(ustring_dup("4"))); uvector_resize(v, 2, G_NULL()); uvector_resize(v, 1, G_NULL()); uvector_clear(v); uvector_append(v, G_STR(ustring_dup("5"))); UASSERT_INT_EQ(uvector_get_size(v), 1); uvector_destroy(v); v = uvector_create(); uvector_append(v, G_STR(ustring_dup("string"))); uvector_set_at(v, 0, G_STR(ustring_dup("string2"))); uvector_destroy(v); v = uvector_create(); uvector_append(v, G_INT(123)); UASSERT_INT_EQ(G_AS_INT(uvector_get_at(v, 0)), 123); UASSERT_INT_EQ(G_AS_INT(uvector_get_back(v)), 123); uvector_t *vcopy = uvector_copy(v); UASSERT(uvector_compare(v, vcopy) == 0); uvector_destroy(v); uvector_destroy(vcopy); v = uvector_create(); uvector_reserve_capacity(v, 1024); uvector_shrink_to_size(v); uvector_destroy(v); v = uvector_create(); uvector_append(v, G_STR(ustring_dup("1"))); uvector_append(v, G_INT(42)); uvector_append(v, G_BOOL(false)); UASSERT(uvector_contains(v, G_STR("1"))); UASSERT(uvector_contains(v, G_CSTR("1"))); UASSERT(uvector_contains(v, G_BOOL(false))); UASSERT(uvector_contains(v, G_INT(42))); UASSERT(!uvector_contains(v, G_STR("2"))); UASSERT(!uvector_contains(v, G_BOOL(true))); UASSERT(!uvector_contains(v, G_INT(100))); uvector_destroy(v); #if defined(__unix__) && defined(ENABLE_UASSERT_INPUT) // Check asserts. UASSERT_ABORTS(uvector_append(NULL, G_INT(0))); UASSERT_ABORTS(uvector_pop_back(NULL)); UASSERT_ABORTS(uvector_get_cells(NULL)); UASSERT_ABORTS(uvector_get_size(NULL)); UASSERT_ABORTS(uvector_resize(NULL, 100, G_NULL())); UASSERT_ABORTS(uvector_reserve_capacity(NULL, 100)); UASSERT_ABORTS(uvector_get_capacity(NULL)); UASSERT_ABORTS(uvector_is_empty(NULL)); UASSERT_ABORTS(uvector_swap(NULL, 1, 2)); UASSERT_ABORTS(uvector_insert_at(NULL, 1, G_INT(100))); UASSERT_ABORTS(uvector_get_at(NULL, 1)); UASSERT_ABORTS(uvector_set_at(NULL, 1, G_INT(0))); uvector_destroy(NULL); v = uvector_create_with_size(0, G_NULL()); UASSERT_ABORTS(uvector_get_at(v, 1)); UASSERT_ABORTS(uvector_set_at(v, 1, G_INT(0))); uvector_resize(v, 100, G_NULL()); UASSERT_ABORTS(uvector_swap(v, 150, 250)); UASSERT_ABORTS(uvector_swap(v, 50, 250)); UASSERT_ABORTS(uvector_insert_at(v, 500, G_INT(400))); uvector_destroy(v); #endif } int cmp(const char *s1, const char *s2) { ugeneric_t gv1 = ugeneric_parse(s1); ugeneric_t gv2 = ugeneric_parse(s2); UASSERT_NO_ERROR(gv1); UASSERT_NO_ERROR(gv2); uvector_t *v1 = G_AS_PTR(gv1); uvector_t *v2 = G_AS_PTR(gv2); int diff = uvector_compare(v1, v2); uvector_destroy(v1); uvector_destroy(v2); return diff; } void test_uvector_compare(void) { uvector_t *v1 = uvector_create(); uvector_t *v2 = uvector_create(); uvector_append(v1, G_STR(ustring_dup("s1"))); uvector_append(v2, G_STR(ustring_dup("s1"))); UASSERT(uvector_compare(v1, v2) == 0); uvector_set_at(v1, 0, G_STR(ustring_dup("s3"))); UASSERT(uvector_compare(v1, v2) != 0); uvector_set_at(v2, 0, G_STR(ustring_dup("s4"))); UASSERT(uvector_compare(v1, v2) < 0); uvector_destroy(v1); uvector_destroy(v2); UASSERT(cmp("[]", "[]") == 0); UASSERT(cmp("[1]", "[1]") == 0); UASSERT(cmp("[1, 2, 3]", "[1, 2, 3]") == 0); UASSERT(cmp("[1, 2]", "[1, 2, 3]") < 0); UASSERT(cmp("[1, 2, 3]", "[1, 2]") > 0); UASSERT(cmp("[3, 2, 3]", "[1, 2, 3]") > 0); } /* double f(double x, void *p) { uvector_t *v = p; return G_AS_REAL(uvector_get_at(v, x)); } void test_gnuplot(void) { #include <gsl/gsl_math.h> #include <gsl/gsl_deriv.h> gsl_function F; double result, abserr; #define N 10 gnuplot_attrs_t a = { .xlabel = "xlabel", .ylabel = "ylabel", .data_label = "samples", .title = "chart", }; uvector_t *v = uvector_create(); for (size_t i = 0; i < N; i++) { uvector_append(v, G_REAL(sin(i/50.0))); } uvector_dump_to_gnuplot(v, &a, stdout); uvector_t *dv = uvector_create(); F.function = &f; F.params = v; for (size_t i = 0; i < N; i++) { UASSERT(gsl_deriv_central(&F, (double)i, 1e-8, &result, &abserr) == 0); uvector_append(dv, G_REAL(result)); } uvector_dump_to_gnuplot(dv, &a, stdout); uvector_destroy(v); uvector_destroy(dv); } */ void _check_slice(const uvector_t *v, size_t b, size_t e, size_t s, char *exp) { uvector_t *slice = uvector_get_slice(v, b, e, s); char *str = uvector_as_str(slice); UASSERT_STR_EQ(str, exp); ufree(str); uvector_destroy(slice); } void test_uvector_slice(void) { ugeneric_t g = ugeneric_parse("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"); UASSERT_NO_ERROR(g); uvector_t *v = G_AS_PTR(g); _check_slice(v, 0, 10, 1, "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"); _check_slice(v, 0, 10, 2, "[1, 3, 5, 7, 9]"); _check_slice(v, 1, 10, 2, "[2, 4, 6, 8, 10]"); _check_slice(v, 0, 10, 3, "[1, 4, 7, 10]"); _check_slice(v, 1, 10, 3, "[2, 5, 8]"); _check_slice(v, 0, 10, 4, "[1, 5, 9]"); _check_slice(v, 1, 10, 4, "[2, 6, 10]"); _check_slice(v, 0, 10, 5, "[1, 6]"); _check_slice(v, 1, 10, 5, "[2, 7]"); _check_slice(v, 0, 10, 6, "[1, 7]"); _check_slice(v, 1, 10, 6, "[2, 8]"); _check_slice(v, 0, 10, 9, "[1, 10]"); _check_slice(v, 1, 10, 9, "[2]"); _check_slice(v, 1, 1, 1, "[]"); _check_slice(v, 1, 1, 5, "[]"); _check_slice(v, 0, 10, 25, "[1]"); uvector_destroy(v); } void test_uvector_data_ownership(void) { uvector_t *v = uvector_create(); UASSERT(uvector_is_data_owner(v)); //uvector_append(v, G_CSTR("s1")); //uvector_append(v, G_CSTR("s1")); // shallow copy uvector_t *copy1 = uvector_copy(v); UASSERT(!uvector_is_data_owner(copy1)); // deep copy uvector_t *copy2 = uvector_deep_copy(v); UASSERT(uvector_is_data_owner(copy2)); uvector_drop_data_ownership(copy2); UASSERT(!uvector_is_data_owner(copy2)); // kick the bucket uvector_destroy(v); uvector_destroy(copy1); uvector_destroy(copy2); } void _check_reverse(const char *in, const char *rev) { ugeneric_t g = ugeneric_parse(in); UASSERT_NO_ERROR(g); uvector_t *v = G_AS_PTR(g); uvector_reverse(v); char *t = uvector_as_str(v); UASSERT_STR_EQ(t, rev); ufree(t); uvector_destroy(v); } void test_uvector_reverse(void) { _check_reverse("[]", "[]"); _check_reverse("[1]", "[1]"); _check_reverse("[1, 2]", "[2, 1]"); _check_reverse("[1, 2, 3]", "[3, 2, 1]"); _check_reverse("[1, 2, 3, 4]", "[4, 3, 2, 1]"); _check_reverse("[1, 2, 3, 4, 5]", "[5, 4, 3, 2, 1]"); } int main(int argc, char **argv) { // test_gnuplot(); (void)argv; test_uvector_api(); test_uvector_serialization(argc > 1); test_uvector_next_permutation(argc > 1); test_uvector_copy(argc > 1); test_uvector_bsearch(); test_uvector_compare(); test_uvector_slice(); test_uvector_data_ownership(); test_uvector_reverse(); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6478853449, "avg_line_length": 30.156779661, "ext": "c", "hexsha": "3131b99beca815b130a0d75d10f1091f2fb73c2f", "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": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "YauheniKaratsevich/ugeneric", "max_forks_repo_path": "test_vector.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "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": "YauheniKaratsevich/ugeneric", "max_issues_repo_path": "test_vector.c", "max_line_length": 136, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e7f83c5e79fa7cec0ed85cbd833515806236e27e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "YauheniKaratsevich/ugeneric", "max_stars_repo_path": "test_vector.c", "max_stars_repo_stars_event_max_datetime": "2018-10-29T10:08:50.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-29T10:08:42.000Z", "num_tokens": 4714, "size": 14234 }
#pragma once #include "internal/Buffer.h" #include <gsl/span> namespace ge::gl4 { using namespace gl45; class BufferView { public: BufferView(Buffer &buffer, GLenum type, gsl::span<uint8_t> range); // Mapping Functions auto map(BufferAccessMask accessFlags) -> void *; void flush(); void unmap(); void bindToIndex(GLuint index); static void unbind(GLenum target, GLuint index); auto getBuffer() const -> Buffer &; const GLenum type; const gsl::span<uint8_t> range; private: Buffer *buffer_; }; }
{ "alphanum_fraction": 0.7184466019, "avg_line_length": 16.09375, "ext": "h", "hexsha": "1775ea61a6ef898d2a243b33573491191d2f016d", "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": "5499b77cde89589abefa88618205a0db5f342443", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "mmha/gravity", "max_forks_repo_path": "src/Renderer/BufferView.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5499b77cde89589abefa88618205a0db5f342443", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "mmha/gravity", "max_issues_repo_path": "src/Renderer/BufferView.h", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "5499b77cde89589abefa88618205a0db5f342443", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "mmha/gravity", "max_stars_repo_path": "src/Renderer/BufferView.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 127, "size": 515 }
/** * * @file core_slaswp.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:44:48 2014 * **/ #include <lapacke.h> #include "common.h" #define A(m, n) BLKADDR(descA, float, m, n) /***************************************************************************//** * * @ingroup CORE_float * * CORE_slaswp performs a series of row interchanges on the matrix A. * One row interchange is initiated for each of rows I1 through I2 of A. * ******************************************************************************* * * @param[in] N * The number of columns in the matrix A. N >= 0. * * @param[in,out] A * On entry, the matrix of column dimension N to which the row * interchanges will be applied. * On exit, the permuted matrix. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,max(IPIV[I1..I2])). * * @param[in] I1 * The first element of IPIV for which a row interchange will * be done. * * @param[in] I2 * The last element of IPIV for which a row interchange will * be done. * * @param[in] IPIV * The pivot indices; Only the element in position i1 to i2 * are accessed. The pivot are offset by A.i. * * @param[in] INC * The increment between successive values of IPIV. If IPIV * is negative, the pivots are applied in reverse order. * ******************************************************************************* */ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp = PCORE_slaswp #define CORE_slaswp PCORE_slaswp #endif void CORE_slaswp(int N, float *A, int LDA, int I1, int I2, const int *IPIV, int INC) { LAPACKE_slaswp_work( LAPACK_COL_MAJOR, N, A, LDA, I1, I2, IPIV, INC ); } /***************************************************************************//** * * @ingroup CORE_float * * CORE_slaswp_ontile apply the slaswp function on a matrix stored in * tile layout * ******************************************************************************* * * @param[in,out] descA * The descriptor of the matrix A to permute. * * @param[in] i1 * The first element of IPIV for which a row interchange will * be done. * * @param[in] i2 * The last element of IPIV for which a row interchange will * be done. * * @param[in] ipiv * The pivot indices; Only the element in position i1 to i2 * are accessed. The pivot are offset by A.i. * * @param[in] inc * The increment between successive values of IPIV. If IPIV * is negative, the pivots are applied in reverse order. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************* */ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp_ontile = PCORE_slaswp_ontile #define CORE_slaswp_ontile PCORE_slaswp_ontile #endif int CORE_slaswp_ontile(PLASMA_desc descA, int i1, int i2, const int *ipiv, int inc) { int i, j, ip, it; float *A1; int lda1, lda2; /* Change i1 to C notation */ i1--; /* Check parameters */ if ( descA.nt > 1 ) { coreblas_error(1, "Illegal value of descA.nt"); return -1; } if ( i1 < 0 ) { coreblas_error(2, "Illegal value of i1"); return -2; } if ( (i2 <= i1) || (i2 > descA.m) ) { coreblas_error(3, "Illegal value of i2"); return -3; } if ( ! ( (i2 - i1 - i1%descA.mb -1) < descA.mb ) ) { coreblas_error(2, "Illegal value of i1,i2. They have to be part of the same block."); return -3; } if (inc > 0) { it = i1 / descA.mb; A1 = A(it, 0); lda1 = BLKLDD(descA, 0); for (j = i1; j < i2; ++j, ipiv+=inc) { ip = (*ipiv) - descA.i - 1; if ( ip != j ) { it = ip / descA.mb; i = ip % descA.mb; lda2 = BLKLDD(descA, it); cblas_sswap(descA.n, A1 + j, lda1, A(it, 0) + i, lda2 ); } } } else { it = (i2-1) / descA.mb; A1 = A(it, 0); lda1 = BLKLDD(descA, it); i1--; ipiv = &ipiv[(1-i2)*inc]; for (j = i2-1; j > i1; --j, ipiv+=inc) { ip = (*ipiv) - descA.i - 1; if ( ip != j ) { it = ip / descA.mb; i = ip % descA.mb; lda2 = BLKLDD(descA, it); cblas_sswap(descA.n, A1 + j, lda1, A(it, 0) + i, lda2 ); } } } return PLASMA_SUCCESS; } /***************************************************************************//** * * @ingroup CORE_float * * CORE_sswptr_ontile apply the slaswp function on a matrix stored in * tile layout, followed by a strsm on the first tile of the panel. * ******************************************************************************* * * @param[in,out] descA * The descriptor of the matrix A to permute. * * @param[in] i1 * The first element of IPIV for which a row interchange will * be done. * * @param[in] i2 * The last element of IPIV for which a row interchange will * be done. * * @param[in] ipiv * The pivot indices; Only the element in position i1 to i2 * are accessed. The pivot are offset by A.i. * * @param[in] inc * The increment between successive values of IPIV. If IPIV * is negative, the pivots are applied in reverse order. * * @param[in] Akk * The triangular matrix Akk. The leading descA.nb-by-descA.nb * lower triangular part of the array Akk contains the lower triangular matrix, and the * strictly upper triangular part of A is not referenced. The * diagonal elements of A are also not referenced and are assumed to be 1. * * @param[in] ldak * The leading dimension of the array Akk. ldak >= max(1,descA.nb). * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************* */ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_sswptr_ontile = PCORE_sswptr_ontile #define CORE_sswptr_ontile PCORE_sswptr_ontile #endif int CORE_sswptr_ontile(PLASMA_desc descA, int i1, int i2, const int *ipiv, int inc, const float *Akk, int ldak) { float zone = 1.0; int lda; int m = descA.mt == 1 ? descA.m : descA.mb; if ( descA.nt > 1 ) { coreblas_error(1, "Illegal value of descA.nt"); return -1; } if ( i1 < 1 ) { coreblas_error(2, "Illegal value of i1"); return -2; } if ( (i2 < i1) || (i2 > m) ) { coreblas_error(3, "Illegal value of i2"); return -3; } CORE_slaswp_ontile(descA, i1, i2, ipiv, inc); lda = BLKLDD(descA, 0); cblas_strsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit, m, descA.n, (zone), Akk, ldak, A(0, 0), lda ); return PLASMA_SUCCESS; } /***************************************************************************//** * * @ingroup CORE_float * * CORE_slaswpc_ontile apply the slaswp function on a matrix stored in * tile layout * ******************************************************************************* * * @param[in,out] descA * The descriptor of the matrix A to permute. * * @param[in] i1 * The first element of IPIV for which a column interchange will * be done. * * @param[in] i2 * The last element of IPIV for which a column interchange will * be done. * * @param[in] ipiv * The pivot indices; Only the element in position i1 to i2 * are accessed. The pivot are offset by A.i. * * @param[in] inc * The increment between successive values of IPIV. If IPIV * is negative, the pivots are applied in reverse order. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************* */ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswpc_ontile = PCORE_slaswpc_ontile #define CORE_slaswpc_ontile PCORE_slaswpc_ontile #endif int CORE_slaswpc_ontile(PLASMA_desc descA, int i1, int i2, const int *ipiv, int inc) { int i, j, ip, it; float *A1; int lda; /* Change i1 to C notation */ i1--; /* Check parameters */ if ( descA.mt > 1 ) { coreblas_error(1, "Illegal value of descA.mt"); return -1; } if ( i1 < 0 ) { coreblas_error(2, "Illegal value of i1"); return -2; } if ( (i2 <= i1) || (i2 > descA.n) ) { coreblas_error(3, "Illegal value of i2"); return -3; } if ( ! ( (i2 - i1 - i1%descA.nb -1) < descA.nb ) ) { coreblas_error(2, "Illegal value of i1,i2. They have to be part of the same block."); return -3; } lda = BLKLDD(descA, 0); if (inc > 0) { it = i1 / descA.nb; A1 = A(0, it); for (j = i1-1; j < i2; ++j, ipiv+=inc) { ip = (*ipiv) - descA.j - 1; if ( ip != j ) { it = ip / descA.nb; i = ip % descA.nb; cblas_sswap(descA.m, A1 + j*lda, 1, A(0, it) + i*lda, 1 ); } } } else { it = (i2-1) / descA.mb; A1 = A(0, it); i1--; ipiv = &ipiv[(1-i2)*inc]; for (j = i2-1; j > i1; --j, ipiv+=inc) { ip = (*ipiv) - descA.j - 1; if ( ip != j ) { it = ip / descA.nb; i = ip % descA.nb; cblas_sswap(descA.m, A1 + j*lda, 1, A(0, it) + i*lda, 1 ); } } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4781481481, "avg_line_length": 29.9168975069, "ext": "c", "hexsha": "18bd87836008ae037db992f5d21593d22adf72f6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_slaswp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_slaswp.c", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_slaswp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2985, "size": 10800 }
//#include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp.h> static double fun(double x) { return x + cos(x * x); } int main(void) { const double a = 1.0; const double b = 10.0; const int steps = 10; double xi, yi, x[100], y[100], dx; FILE *input, *output; int i; input = fopen("wartosci.txt", "w"); output = fopen("inter-cspline.txt", "w"); dx = (b - a) / (double)steps; for (i = 0; i <= steps; ++i) { x[i] = a + (double)i * dx + 0.5 * sin((double)i * dx); y[i] = fun(x[i]); fprintf(input, "%g %g\n", x[i], y[i]); } { gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, steps + 1); gsl_spline_init(spline, x, y, steps + 1); for (xi = a; xi <= b; xi += 0.01) { yi = gsl_spline_eval(spline, xi, acc); fprintf(output, "%g %g\n", xi, yi); } gsl_spline_free(spline); gsl_interp_accel_free(acc); } return 0; }
{ "alphanum_fraction": 0.5322299652, "avg_line_length": 21.6603773585, "ext": "c", "hexsha": "fdaccbf9f88cf5bbe029a8de6512ca2e63195a9e", "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": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kosciolek/uni.mownit2-2022", "max_forks_repo_path": "interpolacja.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "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": "kosciolek/uni.mownit2-2022", "max_issues_repo_path": "interpolacja.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kosciolek/uni.mownit2-2022", "max_stars_repo_path": "interpolacja.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 363, "size": 1148 }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the LICENSE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #pragma once #include <boost/multiprecision/cpp_int.hpp> #include <gsl/gsl> #include <spdlog/spdlog.h> using uint256_t = boost::multiprecision::checked_uint256_t; using byte = std::byte; #include "inc/exception.h" #include "inc/log.h" #include "inc/string.h" #define BETTER_ENUMS_DEFAULT_CONSTRUCTOR(Enum) \ public: \ Enum() = default; #define ENUM BETTER_ENUM
{ "alphanum_fraction": 0.693877551, "avg_line_length": 35.3888888889, "ext": "h", "hexsha": "45c4de7cf4c835e31080dba51b5bf505963309c3", "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": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "bandprotocol/bandchain-legacy", "max_forks_repo_path": "src/inc/essential.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "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": "bandprotocol/bandchain-legacy", "max_issues_repo_path": "src/inc/essential.h", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "4a5861d14dba6a69af0e7ce9fc142beb9315dcb4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "bandprotocol/bandprotocol", "max_stars_repo_path": "src/inc/essential.h", "max_stars_repo_stars_event_max_datetime": "2020-07-21T15:18:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-13T17:50:46.000Z", "num_tokens": 272, "size": 1274 }
/* specfunc/erfc.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: J. Theiler (modifications by G. Jungman) */ /* * See Hart et al, Computer Approximations, John Wiley and Sons, New York (1968) * (This applies only to the erfc8 stuff, which is the part * of the original code that survives. I have replaced much of * the other stuff with Chebyshev fits. These are simpler and * more precise than the original approximations. [GJ]) */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_erf.h" #include "check.h" #include "chebyshev.h" #include "cheb_eval.c" #define LogRootPi_ 0.57236494292470008706 static double erfc8_sum(double x) { /* estimates erfc(x) valid for 8 < x < 100 */ /* This is based on index 5725 in Hart et al */ static double P[] = { 2.97886562639399288862, 7.409740605964741794425, 6.1602098531096305440906, 5.019049726784267463450058, 1.275366644729965952479585264, 0.5641895835477550741253201704 }; static double Q[] = { 3.3690752069827527677, 9.608965327192787870698, 17.08144074746600431571095, 12.0489519278551290360340491, 9.396034016235054150430579648, 2.260528520767326969591866945, 1.0 }; double num=0.0, den=0.0; int i; num = P[5]; for (i=4; i>=0; --i) { num = x*num + P[i]; } den = Q[6]; for (i=5; i>=0; --i) { den = x*den + Q[i]; } return num/den; } inline static double erfc8(double x) { double e; e = erfc8_sum(x); e *= exp(-x*x); return e; } inline static double log_erfc8(double x) { double e; e = erfc8_sum(x); e = log(e) - x*x; return e; } #if 0 /* Abramowitz+Stegun, 7.2.14 */ static double erfcasympsum(double x) { int i; double e = 1.; double coef = 1.; for (i=1; i<5; ++i) { /* coef *= -(2*i-1)/(2*x*x); ??? [GJ] */ coef *= -(2*i+1)/(i*(4*x*x*x*x)); e += coef; /* if (fabs(coef) < 1.0e-15) break; if (fabs(coef) > 1.0e10) break; [GJ]: These tests are not useful. This function is only used below. Took them out; they gum up the pipeline. */ } return e; } #endif /* 0 */ /* Abramowitz+Stegun, 7.1.5 */ static int erfseries(double x, gsl_sf_result * result) { double coef = x; double e = coef; double del; int k; for (k=1; k<30; ++k) { coef *= -x*x/k; del = coef/(2.0*k+1.0); e += del; } result->val = 2.0 / M_SQRTPI * e; result->err = 2.0 / M_SQRTPI * (fabs(del) + GSL_DBL_EPSILON); return GSL_SUCCESS; } /* Chebyshev fit for erfc((t+1)/2), -1 < t < 1 */ static double erfc_xlt1_data[20] = { 1.06073416421769980345174155056, -0.42582445804381043569204735291, 0.04955262679620434040357683080, 0.00449293488768382749558001242, -0.00129194104658496953494224761, -0.00001836389292149396270416979, 0.00002211114704099526291538556, -5.23337485234257134673693179020e-7, -2.78184788833537885382530989578e-7, 1.41158092748813114560316684249e-8, 2.72571296330561699984539141865e-9, -2.06343904872070629406401492476e-10, -2.14273991996785367924201401812e-11, 2.22990255539358204580285098119e-12, 1.36250074650698280575807934155e-13, -1.95144010922293091898995913038e-14, -6.85627169231704599442806370690e-16, 1.44506492869699938239521607493e-16, 2.45935306460536488037576200030e-18, -9.29599561220523396007359328540e-19 }; static cheb_series erfc_xlt1_cs = { erfc_xlt1_data, 19, -1, 1, 12 }; /* Chebyshev fit for erfc(x) exp(x^2), 1 < x < 5, x = 2t + 3, -1 < t < 1 */ static double erfc_x15_data[25] = { 0.44045832024338111077637466616, -0.143958836762168335790826895326, 0.044786499817939267247056666937, -0.013343124200271211203618353102, 0.003824682739750469767692372556, -0.001058699227195126547306482530, 0.000283859419210073742736310108, -0.000073906170662206760483959432, 0.000018725312521489179015872934, -4.62530981164919445131297264430e-6, 1.11558657244432857487884006422e-6, -2.63098662650834130067808832725e-7, 6.07462122724551777372119408710e-8, -1.37460865539865444777251011793e-8, 3.05157051905475145520096717210e-9, -6.65174789720310713757307724790e-10, 1.42483346273207784489792999706e-10, -3.00141127395323902092018744545e-11, 6.22171792645348091472914001250e-12, -1.26994639225668496876152836555e-12, 2.55385883033257575402681845385e-13, -5.06258237507038698392265499770e-14, 9.89705409478327321641264227110e-15, -1.90685978789192181051961024995e-15, 3.50826648032737849245113757340e-16 }; static cheb_series erfc_x15_cs = { erfc_x15_data, 24, -1, 1, 16 }; /* Chebyshev fit for erfc(x) x exp(x^2), 5 < x < 10, x = (5t + 15)/2, -1 < t < 1 */ static double erfc_x510_data[20] = { 1.11684990123545698684297865808, 0.003736240359381998520654927536, -0.000916623948045470238763619870, 0.000199094325044940833965078819, -0.000040276384918650072591781859, 7.76515264697061049477127605790e-6, -1.44464794206689070402099225301e-6, 2.61311930343463958393485241947e-7, -4.61833026634844152345304095560e-8, 8.00253111512943601598732144340e-9, -1.36291114862793031395712122089e-9, 2.28570483090160869607683087722e-10, -3.78022521563251805044056974560e-11, 6.17253683874528285729910462130e-12, -9.96019290955316888445830597430e-13, 1.58953143706980770269506726000e-13, -2.51045971047162509999527428316e-14, 3.92607828989125810013581287560e-15, -6.07970619384160374392535453420e-16, 9.12600607264794717315507477670e-17 }; static cheb_series erfc_x510_cs = { erfc_x510_data, 19, -1, 1, 12 }; #if 0 inline static double erfc_asymptotic(double x) { return exp(-x*x)/x * erfcasympsum(x) / M_SQRTPI; } inline static double log_erfc_asymptotic(double x) { return log(erfcasympsum(x)/x) - x*x - LogRootPi_; } #endif /* 0 */ /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_erfc_e(double x, gsl_sf_result * result) { const double ax = fabs(x); double e_val, e_err; /* CHECK_POINTER(result) */ if(ax <= 1.0) { double t = 2.0*ax - 1.0; gsl_sf_result c; cheb_eval_e(&erfc_xlt1_cs, t, &c); e_val = c.val; e_err = c.err; } else if(ax <= 5.0) { double ex2 = exp(-x*x); double t = 0.5*(ax-3.0); gsl_sf_result c; cheb_eval_e(&erfc_x15_cs, t, &c); e_val = ex2 * c.val; e_err = ex2 * (c.err + 2.0*fabs(x)*GSL_DBL_EPSILON); } else if(ax < 10.0) { double exterm = exp(-x*x) / ax; double t = (2.0*ax - 15.0)/5.0; gsl_sf_result c; cheb_eval_e(&erfc_x510_cs, t, &c); e_val = exterm * c.val; e_err = exterm * (c.err + 2.0*fabs(x)*GSL_DBL_EPSILON + GSL_DBL_EPSILON); } else { e_val = erfc8(ax); e_err = (x*x + 1.0) * GSL_DBL_EPSILON * fabs(e_val); } if(x < 0.0) { result->val = 2.0 - e_val; result->err = e_err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } else { result->val = e_val; result->err = e_err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return GSL_SUCCESS; } int gsl_sf_log_erfc_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x*x < 10.0*GSL_ROOT6_DBL_EPSILON) { const double y = x / M_SQRTPI; /* series for -1/2 Log[Erfc[Sqrt[Pi] y]] */ const double c3 = (4.0 - M_PI)/3.0; const double c4 = 2.0*(1.0 - M_PI/3.0); const double c5 = -0.001829764677455021; /* (96.0 - 40.0*M_PI + 3.0*M_PI*M_PI)/30.0 */ const double c6 = 0.02629651521057465; /* 2.0*(120.0 - 60.0*M_PI + 7.0*M_PI*M_PI)/45.0 */ const double c7 = -0.01621575378835404; const double c8 = 0.00125993961762116; const double c9 = 0.00556964649138; const double c10 = -0.0045563339802; const double c11 = 0.0009461589032; const double c12 = 0.0013200243174; const double c13 = -0.00142906; const double c14 = 0.00048204; double series = c8 + y*(c9 + y*(c10 + y*(c11 + y*(c12 + y*(c13 + c14*y))))); series = y*(1.0 + y*(1.0 + y*(c3 + y*(c4 + y*(c5 + y*(c6 + y*(c7 + y*series))))))); result->val = -2.0 * series; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } /* don't like use of log1p(); added above series stuff for small x instead, should be ok [GJ] else if (fabs(x) < 1.0) { gsl_sf_result result_erf; gsl_sf_erf_e(x, &result_erf); result->val = log1p(-result_erf.val); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } */ else if(x > 8.0) { result->val = log_erfc8(x); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { gsl_sf_result result_erfc; gsl_sf_erfc_e(x, &result_erfc); result->val = log(result_erfc.val); result->err = fabs(result_erfc.err / result_erfc.val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_erf_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(fabs(x) < 1.0) { return erfseries(x, result); } else { gsl_sf_result result_erfc; gsl_sf_erfc_e(x, &result_erfc); result->val = 1.0 - result_erfc.val; result->err = result_erfc.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_erf_Z_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { const double ex2 = exp(-x*x/2.0); result->val = ex2 / (M_SQRT2 * M_SQRTPI); result->err = fabs(x * result->val) * GSL_DBL_EPSILON; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); CHECK_UNDERFLOW(result); return GSL_SUCCESS; } } int gsl_sf_erf_Q_e(double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { gsl_sf_result result_erfc; int stat = gsl_sf_erfc_e(x/M_SQRT2, &result_erfc); result->val = 0.5 * result_erfc.val; result->err = 0.5 * result_erfc.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_erfc(double x) { EVAL_RESULT(gsl_sf_erfc_e(x, &result)); } double gsl_sf_log_erfc(double x) { EVAL_RESULT(gsl_sf_log_erfc_e(x, &result)); } double gsl_sf_erf(double x) { EVAL_RESULT(gsl_sf_erf_e(x, &result)); } double gsl_sf_erf_Z(double x) { EVAL_RESULT(gsl_sf_erf_Z_e(x, &result)); } double gsl_sf_erf_Q(double x) { EVAL_RESULT(gsl_sf_erf_Q_e(x, &result)); }
{ "alphanum_fraction": 0.6695597709, "avg_line_length": 25.8703703704, "ext": "c", "hexsha": "6b3368f80e0b1387db9ce397fa433fd01287fd1b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.c", "max_line_length": 96, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/erfc.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": 4209, "size": 11176 }
#include <math.h> #include <stdio.h> #include <gsl/gsl_rng.h> #include "matrix_operations.c" #include "ellipse/parametric_function_roots.c" #include "polynomial.c" void characteristic_ellipse_matrix(double *X, double *R, double phi, double exponent) { // rotation matrix double Q[2][2] = {{ 0 }}; double Qt[2][2] = {{ 0 }}; Q[0][0] = cos(phi); Q[0][1] = sin(phi); Q[1][0] = -sin(phi); Q[1][1] = cos(phi); matrix_transpose(&Qt[0][0], &Q[0][0], 2, 2); // radii matrix double O[2][2] = {{ 0 }}; double diag_vals[2]; diag_vals[0] = pow(R[0], exponent * -2.0); diag_vals[1] = pow(R[1], exponent * -2.0); set_diagonal(&O[0][0], diag_vals, 2, 2); // characteristic ellipse matrix double X_temp[2][2] = {{ 0 }}; matrix_multiply(&X_temp[0][0], &O[0][0], &Q[0][0], 2, 2, 2); matrix_multiply(X, &Qt[0][0], &X_temp[0][0], 2, 2, 2); } double ellipse_overlap(double *rA, double *radiiA, double phiA, double *rB, double *radiiB, double phiB) { // find XA^(-1) and XB^(1/2) double XA[2][2] = {{ 0 }}; double XB[2][2] = {{ 0 }}; characteristic_ellipse_matrix(&XA[0][0], &radiiA[0], phiA, -1.0); characteristic_ellipse_matrix(&XB[0][0], &radiiB[0], phiB, 0.5); // find A_AB double A_AB[2][2] = {{ 0 }}; double A_temp[2][2] = {{ 0 }}; matrix_multiply(&A_temp[0][0], &XA[0][0], &XB[0][0], 2, 2, 2); matrix_multiply(&A_AB[0][0], &XB[0][0], &A_temp[0][0], 2, 2, 2); // find r_AB double rAB[2]; rAB[0] = rB[0] - rA[0]; rAB[1] = rB[1] - rA[1]; // find a_AB double a_AB[2]; matrix_multiply(&a_AB[0], &XB[0][0], &rAB[0], 2, 2, 1); // extract elements of the matrix A_AB and a_AB double a11, a12, a21, a22; double b1, b2; a11 = A_AB[0][0]; a12 = A_AB[0][1]; a21 = A_AB[1][0]; a22 = A_AB[1][1]; b1 = a_AB[0]; b2 = a_AB[1]; // find coefficients for the parametric polynomial derivative used to find max double h[5]; double z[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; size_t n = 5; h[0] = h0(a11, a12, a21, a22, b1, b2); h[1] = h1(a11, a12, a21, a22, b1, b2); h[2] = h2(a11, a12, a21, a22, b1, b2); h[3] = h3(a11, a12, a21, a22, b1, b2); h[4] = h4(a11, a12, a21, a22, b1, b2); // find roots size_t m; m = find_roots(&z[0], &h[0], n); double F; int i; if (m > 1) { if (f(0, a11, a12, a21, a22, b1, b2) > f(1, a11, a12, a21, a22, b1, b2)) { F = f(0, a11, a12, a21, a22, b1, b2); } else { F = f(1, a11, a12, a21, a22, b1, b2); } for(i=0; i<=m-2; i++) { if (( z[2 * i + 1] == 0 ) & (z[2 * i] > 0) & (z[2 * i] < 1)) { F = f(z[2 * i], a11, a12, a21, a22, b1, b2); } } } else { F = 0.; } return F; } double container_square_overlap_potential(double *rA, double *radiiA, double phiA) { double rB[2]; double radiiB[2]; double phiB; double top = 0; double bottom = 0; double left = 0; double right = 0; // top rB[0] = 0.5; rB[1] = 2.0; radiiB[0] = INFINITY; radiiB[1] = 1.0; phiB = 0.0; top = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB); // bottom rB[0] = 0.5; rB[1] = -1.0; radiiB[0] = INFINITY; radiiB[1] = 1.0; phiB = 0.0; bottom = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB); // left rB[0] = -1.0; rB[1] = 0.5; radiiB[0] = 1.0; radiiB[1] = INFINITY; phiB = 0.0; left = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB); // right rB[0] = 2.0; rB[1] = 0.5; radiiB[0] = 1.0; radiiB[1] = INFINITY; phiB = 0.0; right = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB); return fminf(top, fminf(bottom, fminf(left, right))); } size_t rsa_align_square(double *x, double *y, size_t npoints, double *radius, double phi, int step_limit, unsigned long randSeed) { // Setup GSL random number generator const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); // Set the seed // srand ( time(NULL) ); // unsigned long randSeed = rand(); gsl_rng_set(r, randSeed); // arrays for overlap_potential functions double rA[2]; double rB[2]; double radiiA[2]; double radiiB[2]; double F; double xn = 0.; double yn = 0.; radiiA[0] = radius[0]; radiiA[1] = radius[1]; // Set the initial position double C; C = fmaxf(radius[0], radius[1]); F = 0; while (F < 1.) { xn = gsl_rng_uniform (r); yn = gsl_rng_uniform (r); rA[0] = xn; rA[1] = yn; F = container_square_overlap_potential(&rA[0], &radiiA[0], phi); } x[0] = xn; y[0] = yn; size_t valid_pts; int k, flag, step; step = 0; valid_pts = 1; while ((valid_pts < npoints) & (step < step_limit)) { // Generate new ellipse inside the container F = 0; while (F < 1.) { xn = gsl_rng_uniform (r); yn = gsl_rng_uniform (r); rA[0] = xn; rA[1] = yn; F = container_square_overlap_potential(&rA[0], &radiiA[0], phi); } // Determine if new ellipse overlaps with existing ellipses flag = 1; for (k = 0; k < valid_pts; k++) { rA[0] = x[k]; rA[1] = y[k]; rB[0] = xn; rB[1] = yn; radiiA[0] = radius[0]; radiiA[1] = radius[1]; radiiB[0] = radius[0]; radiiB[1] = radius[1]; F = ellipse_overlap(&rA[0], &radiiA[0], phi, &rB[0], &radiiB[0], phi); if (F < 1.0) { flag = 0; break; } } if (flag == 1) { x[valid_pts] = xn; y[valid_pts] = yn; valid_pts += 1; } step += 1; } gsl_rng_free (r); return valid_pts; } size_t rsa_square(double *x, double *y, size_t npoints, double *radius, double *phi, int step_limit, unsigned long randSeed) { // Setup GSL random number generator const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); // Set the seed // srand ( time(NULL) ); // unsigned long randSeed = rand(); gsl_rng_set(r, randSeed); // arrays for overlap_potential functions double rA[2]; double rB[2]; double radiiA[2]; double radiiB[2]; double phiA; double phiB; double F; double xn = 0; double yn = 0; double phin = 0; radiiA[0] = radius[0]; radiiA[1] = radius[1]; // Set the initial position double C; C = fmaxf(radius[0], radius[1]); F = 0; while (F < 1.) { xn = gsl_rng_uniform (r); yn = gsl_rng_uniform (r); rA[0] = xn; rA[1] = yn; phiA = 2 * M_PI * gsl_rng_uniform (r); F = container_square_overlap_potential(&rA[0], &radiiA[0], phiA); } x[0] = xn; y[0] = yn; phi[0] = phiA; size_t valid_pts; int k, flag, step; step = 0; valid_pts = 1; while ((valid_pts < npoints) & (step < step_limit)) { // Generate new ellipse inside the container F = 0; while (F < 1.) { xn = gsl_rng_uniform (r); yn = gsl_rng_uniform (r); phin = 2 * M_PI * gsl_rng_uniform (r); rA[0] = xn; rA[1] = yn; phiA = phin; F = container_square_overlap_potential(&rA[0], &radiiA[0], phiA); } // Determine if new ellipse overlaps with existing ellipses flag = 1; for (k = 0; k < valid_pts; k++) { rA[0] = x[k]; rA[1] = y[k]; phiA = phi[k]; rB[0] = xn; rB[1] = yn; phiB = phin; radiiA[0] = radius[0]; radiiA[1] = radius[1]; radiiB[0] = radius[0]; radiiB[1] = radius[1]; F = ellipse_overlap(&rA[0], &radiiA[0], phiA, &rB[0], &radiiB[0], phiB); if (F < 1.0) { flag = 0; break; } } if (flag == 1) { x[valid_pts] = xn; y[valid_pts] = yn; phi[valid_pts] = phin; valid_pts += 1; } step += 1; } gsl_rng_free (r); return valid_pts; }
{ "alphanum_fraction": 0.4757126568, "avg_line_length": 18.2708333333, "ext": "c", "hexsha": "6982edd357305a135062fd5b2dfedf111a95eb78", "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": "127603a519ae25979de6c6197810a7ea38ec945b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "aluchies/particle_packing", "max_forks_repo_path": "particle_packing/cython/c/ellipse.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "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": "aluchies/particle_packing", "max_issues_repo_path": "particle_packing/cython/c/ellipse.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "aluchies/particle_packing", "max_stars_repo_path": "particle_packing/cython/c/ellipse.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3150, "size": 8770 }
/* hmm class header */ // Andrew Kern 8/24/05 // #include "adkGSL.h" #include <math.h> #include <string.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> typedef struct { int nstates; gsl_matrix *transition_matrix; gsl_matrix *transition_score_matrix; /* entries are logs of entries * in transition matrix */ gsl_vector *piStart, *piEnd, *piStart_scores, *piEnd_scores; gsl_vector *otherData; //this is meant to hold distances between obs } HMM; HMM* newHMM(gsl_matrix *mat, gsl_vector *piStart, gsl_vector *piEnd, gsl_vector *otherData); void freeHMM(HMM *hmm); void printHMM(HMM *hmm); void initHMM(HMM *hmm); double forwardSumPrevious(HMM *hmm, gsl_matrix *alphas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex); double viterbiMaxPrevious(HMM *hmm, gsl_matrix *deltas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex, int *point); double backwardSumNext(HMM *hmm, gsl_matrix *alphas, gsl_matrix *transition_score_matrix_i, gsl_matrix *emissions, int state, int obsIndex); double forwardAlg(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emissions, int length, int transitionFlag); double backwardAlg(HMM *hmm, gsl_matrix *betas, gsl_matrix *emissions, int length,int transitionPowerFlag); void posteriorProbs(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix *emissions, int length, int transitionPowerFlag); void posteriorProbsReduced(HMM *hmm, gsl_matrix *postProbMat, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emissions, int length, int transitionPowerFlag); void reestimateTransitions(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix **jpMatArray, double pFor, gsl_matrix *alphas, \ gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag); void reestimateTransitions_vanilla(HMM *hmm, double pFor, gsl_matrix *alphas, \ gsl_matrix *betas, gsl_matrix *emisLogs, int length); double viterbi(HMM *hmm, gsl_vector *viterbiPath, gsl_matrix *emissions, int length, int transitionPowerFlag); void hmm_logify_transitions(HMM *hmm); void hmm_normalize_transitions(HMM *hmm); double forwardAlgOffset(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emissions, int length, int offset, int transitionPowerFlag); double hmm_subpath_score(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion, int begin, int length, int transitionPowerFlag); double hmm_subpath_log_odds(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion1,gsl_vector *stateInclusion2,int begin, int length, int powerTransitionFlag); gsl_vector *simulatePath(HMM *h, void *r, int obsNumber); gsl_vector *simulatePathSpaced(HMM *h, void *r, int obsNumber, gsl_vector *locs, double mean); void posteriorDecode(HMM *hmm, gsl_vector *posteriorPath, gsl_matrix *posts, int length); void printTransitions(HMM *h, char *outfileName);
{ "alphanum_fraction": 0.7782837128, "avg_line_length": 62.0652173913, "ext": "h", "hexsha": "72004495b1ba4609d39dc97b8265006d00153792", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_path": "hmm/hmm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_path": "hmm/hmm.h", "max_line_length": 174, "max_stars_count": null, "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_path": "hmm/hmm.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 800, "size": 2855 }
#ifndef XYCO_RUNTIME_ASYNC_H_ #define XYCO_RUNTIME_ASYNC_H_ #include <gsl/pointers> #include "future.h" #include "poll.h" #include "runtime.h" namespace xyco::runtime { template <typename Return> class AsyncFuture : public Future<Return> { public: [[nodiscard]] auto poll(Handle<void> self) -> Poll<Return> override { if (!ready_) { ready_ = true; auto res = RuntimeCtx::get_ctx()->blocking_handle()->Register(event_); return Pending(); } gsl::owner<Return *> ret = gsl::owner<Return *>( std::get<AsyncFutureExtra>(event_.extra_).after_extra_); auto result = std::move(*ret); delete ret; return Ready<Return>{std::move(result)}; } template <typename Fn> explicit AsyncFuture(Fn &&f) requires(std::is_invocable_r_v<Return, Fn>) : Future<Return>(nullptr), f_([&]() { auto extra = AsyncFutureExtra{.after_extra_ = new Return(f())}; event_.extra_ = extra; }), ready_(false), event_(xyco::runtime::Event{ .future_ = this, .extra_ = AsyncFutureExtra{.before_extra_ = f_}}) { } AsyncFuture(const AsyncFuture<Return> &) = delete; AsyncFuture(AsyncFuture<Return> &&) = delete; auto operator=(const AsyncFuture<Return> &) -> AsyncFuture<Return> & = delete; auto operator=(AsyncFuture<Return> &&) -> AsyncFuture<Return> & = delete; ~AsyncFuture() = default; private: bool ready_; std::function<void()> f_; Event event_; }; } // namespace xyco::runtime #endif // XYCO_RUNTIME_ASYNC_H_
{ "alphanum_fraction": 0.6488599349, "avg_line_length": 26.4655172414, "ext": "h", "hexsha": "492d4925fe29c4582914cf97a162764f8fe845a2", "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": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ddxy18/xyco", "max_forks_repo_path": "src/runtime/async_future.h", "max_issues_count": 17, "max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ddxy18/xyco", "max_issues_repo_path": "src/runtime/async_future.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ddxy18/xyco", "max_stars_repo_path": "src/runtime/async_future.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 399, "size": 1535 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <gsl/gsl_multifit.h> //DEFINES #define SUCCESS 1 #define FAILURE -1 #define PROGRESS "====================" #define PRG_WIDTH 20 //FUNCTIONS DECLARATION int dcca_comp(double *, double *, double *, int, int, int, int, double *, int); int rows_number(char *); double mean(double *, int, int); void cumsum(double *, double *, int); void slice_vec(double *, double *, int, int); void polynomialFit(int, int, double *, double *, double *); //MAIN int main(int argc, char **argv) { //inputs int input_args = 7; if(argc < input_args){ printf("Not enough input arguments!\n"); return FAILURE; }else if(argc > input_args){ printf("Too many input arguments!\n"); return FAILURE; } char file_name1[255]; //path+name for the first file memset(file_name1, 0x00, sizeof(file_name1)); sprintf(file_name1, "%s", argv[1]); char file_name2[255]; //path+name for the second file memset(file_name2, 0x00, sizeof(file_name2)); sprintf(file_name2, "%s", argv[2]); int smallest_win_size = atoi(argv[3]); //minimum size for the sliding window int biggest_win_num = atoi(argv[4]); //number of windows in the last step int pol_ord = atoi(argv[5]); //polynomial order for fit char path_out[255]; //path+name for the output file memset(path_out, 0x00, sizeof(path_out)); sprintf(path_out, "%s/rho_mw=%d_Mw=%d_pol=%d.txt", argv[6], smallest_win_size, biggest_win_num, pol_ord); //files length int N1 = rows_number(file_name1); if(N1 == FAILURE){ printf("Cannot open input file (1).\n"); return FAILURE; } int N2 = rows_number(file_name2); if(N2 == FAILURE){ printf("Cannot open input file (2).\n"); return FAILURE; } //time series double *ts1, *ts2; ts1 = calloc(N1, sizeof(double)); if(!ts1){ printf("MALLOC ERROR (ts1)\n"); return FAILURE; } ts2 = calloc(N2, sizeof(double)); if(!ts2){ printf("MALLOC ERROR (ts2)\n"); return FAILURE; } FILE *f1, *f2; f1 = fopen(file_name1, "r"); if(!f1){ printf("Cannot open input file (1).\n"); return FAILURE; } for(int i = 0; i < N1; i++) fscanf(f1, "%lf", ts1+i); fclose(f1); f2 = fopen(file_name2, "r"); if(!f2){ printf("Cannot open input file (2).\n"); return FAILURE; } for(int i = 0; i < N2; i++) fscanf(f2, "%lf", ts2+i); fclose(f2); //time series must have the same length int L = N1; if(N1 < N2){ printf("Series 2 is longer than series 1. Data length reduced to: <%d>\n", L); slice_vec(ts2, ts2, 0, N1-1); }else if(N1 > N2){ slice_vec(ts1, ts1, 0, N2-1); L = N2; printf("Series 1 is longer than series 2. Data length reduced to: <%d>\n", L); }else{ printf("Data length: <%d>\n", L); } //time vector double *time; time = calloc(L, sizeof(double)); if(!time){ printf("MALLOC ERROR (time)\n"); return FAILURE; } for(int i = 0; i < L; i++) time[i] = (double)(i+1); //time series minus its mean double ts1_ave = mean(ts1, L, L); double ts2_ave = mean(ts2, L, L); double *ts1_nomean, *ts2_nomean; ts1_nomean = calloc(L, sizeof(double)); if(!ts1_nomean){ printf("MALLOC ERROR (ts1_nomean)\n"); return FAILURE; } ts2_nomean = calloc(L, sizeof(double)); if(!ts2_nomean){ printf("MALLOC ERROR (ts2_nomean)\n"); return FAILURE; } for(int i = 0; i < L; i++){ ts1_nomean[i] = ts1[i] - ts1_ave; ts2_nomean[i] = ts2[i] - ts2_ave; } //cumulative sum double *ts1_cum, *ts2_cum; ts1_cum = calloc(L, sizeof(double)); if(!ts1_cum){ printf("MALLOC ERROR (ts1_cum)\n"); return FAILURE; } ts2_cum = calloc(L, sizeof(double)); if(!ts2_cum){ printf("MALLOC ERROR (ts2_cum)\n"); return FAILURE; } printf("Data integration..."); cumsum(ts1_nomean, ts1_cum, L); cumsum(ts2_nomean, ts2_cum, L); printf("done!\n"); //dcca computation int biggest_win_size = L / biggest_win_num; int win_range = biggest_win_size - smallest_win_size + 1; double *F_DCCA, *F_DFA_x, *F_DFA_y, *rho; F_DCCA = calloc(win_range, sizeof(double)); F_DFA_x = calloc(win_range, sizeof(double)); F_DFA_y = calloc(win_range, sizeof(double)); rho = calloc(win_range, sizeof(double)); printf("Computing DCCA between series 1 and series 2...\n"); int ret = dcca_comp(time, ts1_cum, ts2_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DCCA, win_range); if(ret == FAILURE) return FAILURE; printf("Computing DCCA between series 1 and series 1...\n"); ret = dcca_comp(time, ts1_cum, ts1_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DFA_x, win_range); if(ret == FAILURE) return FAILURE; printf("Computing DCCA between series 2 and series 2...\n"); ret = dcca_comp(time, ts2_cum, ts2_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DFA_y, win_range); if(ret == FAILURE) return FAILURE; FILE *fOut; fOut = fopen(path_out, "w"); if(!fOut){ printf("Cannot open output file.\n"); return FAILURE; } printf("Computing rho..."); for(int i = 0; i < win_range; i++){ F_DFA_x[i] = sqrt(F_DFA_x[i]); F_DFA_y[i] = sqrt(F_DFA_y[i]); rho[i] = F_DCCA[i] / (double)(F_DFA_x[i] * F_DFA_y[i]); fprintf(fOut, "%lf %lf %lf %lf\n", F_DCCA[i], F_DFA_x[i], F_DFA_y[i], rho[i]); } printf("done\n"); printf("Output file..."); fclose(fOut); printf("done\n"); //free memory free(ts1); free(ts2); free(time); free(ts1_nomean); free(ts2_nomean); free(ts1_cum); free(ts2_cum); free(F_DCCA); free(F_DFA_x); free(F_DFA_y); free(rho); return 0; } //FUNCTIONS int dcca_comp(double *t, double *y1, double *y2, int N, int min_win_size, int last_win_len, int ord, double *F, int range_dcca) { //fluctuations vector and other arrays int F_len = N - min_win_size; double *F_nu, *t_fit, *y_fit1, *y_fit2, *diff_vec, *fit_coeffs1, *fit_coeffs2; F_nu = calloc(F_len, sizeof(double)); if(!F_nu){ printf("MALLOC ERROR (F_nu)\n"); return FAILURE; } t_fit = calloc((last_win_len+1), sizeof(double)); if(!t_fit){ printf("MALLOC ERROR (t_fit)\n"); return FAILURE; } y_fit1 = calloc((last_win_len+1), sizeof(double)); if(!y_fit1){ printf("MALLOC ERROR (y_fit1)\n"); return FAILURE; } y_fit2 = calloc((last_win_len+1), sizeof(double)); if(!y_fit2){ printf("MALLOC ERROR (y_fit2)\n"); return FAILURE; } diff_vec = calloc((last_win_len+1), sizeof(double)); if(!diff_vec){ printf("MALLOC ERROR (diff_vec)\n"); return FAILURE; } fit_coeffs1 = calloc(ord+1, sizeof(double)); if(!fit_coeffs1){ printf("MALLOC ERROR (fit_coeffs1)\n"); return FAILURE; } fit_coeffs2 = calloc(ord+1, sizeof(double)); if(!fit_coeffs2){ printf("MALLOC ERROR (fit_coeffs2)\n"); return FAILURE; } //computation int s, N_s, start_lim, end_lim; for(int i = 0; i < range_dcca; i++){ double perc = i * 100 / (double)range_dcca; int prg = (i * PRG_WIDTH) / range_dcca; printf(" [%.*s%*s] %.2lf%%\r", prg, PROGRESS, PRG_WIDTH-prg, "", perc); fflush(stdout); s = i + min_win_size; N_s = N - s; for(int v = 0; v < N_s; v++){ start_lim = v; end_lim = v + s; slice_vec(t, t_fit, start_lim, end_lim); slice_vec(y1, y_fit1, start_lim, end_lim); slice_vec(y2, y_fit2, start_lim, end_lim); polynomialFit(s+1, ord+1, t_fit, y_fit1, fit_coeffs1); polynomialFit(s+1, ord+1, t_fit, y_fit2, fit_coeffs2); for(int j = 0; j <= s; j++){ for(int k = 0; k < ord+1; k++){ y_fit1[j] -= fit_coeffs1[k] * pow(t_fit[j], k); y_fit2[j] -= fit_coeffs2[k] * pow(t_fit[j], k); } diff_vec[j] = y_fit1[j] * y_fit2[j]; } F_nu[v] = mean(diff_vec, s+1, s-1); } F[i] = mean(F_nu, N_s, N_s); } printf(" [%s] 100.00%%\r", PROGRESS); fflush(stdout); printf("\n"); free(F_nu); free(t_fit); free(y_fit1); free(y_fit2); free(diff_vec); free(fit_coeffs1); free(fit_coeffs2); return SUCCESS; } int rows_number(char *file_name) { FILE *f; int stop; int lines = 0; f = fopen(file_name,"r"); if(!f){ printf("Cannot open file %s\n", file_name); return FAILURE; } while(!feof(f)){ stop = fgetc(f); if(stop == '\n') lines++; } fclose(f); return lines; } double mean(double *vec, int vecL, int L) { double avg = 0.0; for(int i = 0; i < vecL; i++) avg += vec[i]; avg /= (double)L; return avg; } void cumsum(double *vec, double *sum_vec, int L) { sum_vec[0] = vec[0]; for(int i = 1; i < L; i++) sum_vec[i] = sum_vec[i-1] + vec[i]; } void slice_vec(double *all_vec, double *sliced_vec, int start, int end) { for(int i = 0; i <= (end-start); i++) sliced_vec[i] = all_vec[start+i]; } void polynomialFit(int obs, int degree, double *dx, double *dy, double *store) { gsl_multifit_linear_workspace *ws; gsl_matrix *cov, *X; gsl_vector *y, *c; double chisq; int i, j; //alloc X = gsl_matrix_alloc(obs, degree); y = gsl_vector_alloc(obs); c = gsl_vector_alloc(degree); cov = gsl_matrix_alloc(degree, degree); //computation for(i = 0; i < obs; i++){ for(j = 0; j < degree; j++) gsl_matrix_set(X, i, j, pow(dx[i], j)); gsl_vector_set(y, i, dy[i]); } ws = gsl_multifit_linear_alloc(obs, degree); gsl_multifit_linear(X, y, c, cov, &chisq, ws); for(i = 0; i < degree; i++) store[i] = gsl_vector_get(c, i); //free memory gsl_multifit_linear_free(ws); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(c); }
{ "alphanum_fraction": 0.5749300396, "avg_line_length": 31.2138554217, "ext": "c", "hexsha": "c042649dd9124a6c94f540135944553ac26e5598", "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": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stfbnc/C_fa", "max_forks_repo_path": "dcca.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "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": "stfbnc/C_fa", "max_issues_repo_path": "dcca.c", "max_line_length": 127, "max_stars_count": null, "max_stars_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stfbnc/C_fa", "max_stars_repo_path": "dcca.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3138, "size": 10363 }
/*! * Copyright (c) 2014 by Contributors * \file base.h * \brief definitions of base types, operators, macros functions * * \author Bing Xu, Tianqi Chen */ #ifndef MSHADOW_BASE_H_ #define MSHADOW_BASE_H_ #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #define NOMINMAX #endif #include <cmath> #include <cstdio> #include <cfloat> #include <climits> #include <algorithm> #include <functional> #include <sstream> #include <string> #ifdef _MSC_VER //! \cond Doxygen_Suppress typedef signed char int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; //! \endcond #else #include <inttypes.h> #endif // macro defintiions /*! * \brief if this macro is define to be 1, * mshadow should compile without any of other libs */ #ifndef MSHADOW_STAND_ALONE #define MSHADOW_STAND_ALONE 0 #endif /*! \brief whether do padding during allocation */ #ifndef MSHADOW_ALLOC_PAD #define MSHADOW_ALLOC_PAD true #endif /*! * \brief * x dimension of data must be bigger pad_size * ratio to be alloced padded memory, * otherwise use tide allocation * for example, if pad_ratio=2, GPU memory alignement size is 32, * then we will only allocate padded memory if x dimension > 64 * set it to 0 then we will always allocate padded memory */ #ifndef MSHADOW_MIN_PAD_RATIO #define MSHADOW_MIN_PAD_RATIO 2 #endif #if MSHADOW_STAND_ALONE #define MSHADOW_USE_CBLAS 0 #define MSHADOW_USE_MKL 0 #define MSHADOW_USE_CUDA 0 #endif /*! * \brief force user to use GPU stream during computation * error will be shot when default stream NULL is used */ #ifndef MSHADOW_FORCE_STREAM #define MSHADOW_FORCE_STREAM 1 #endif /*! \brief use CBLAS for CBLAS */ #ifndef MSHADOW_USE_CBLAS #define MSHADOW_USE_CBLAS 0 #endif /*! \brief use MKL for BLAS */ #ifndef MSHADOW_USE_MKL #define MSHADOW_USE_MKL 1 #endif /*! * \brief use CUDA support, must ensure that the cuda include path is correct, * or directly compile using nvcc */ #ifndef MSHADOW_USE_CUDA #define MSHADOW_USE_CUDA 1 #endif /*! * \brief use CUDNN support, must ensure that the cudnn include path is correct */ #ifndef MSHADOW_USE_CUDNN #define MSHADOW_USE_CUDNN 0 #endif /*! * \brief seems CUDAARCH is deprecated in future NVCC * set this to 1 if you want to use CUDA version smaller than 2.0 */ #ifndef MSHADOW_OLD_CUDA #define MSHADOW_OLD_CUDA 0 #endif /*! * \brief macro to decide existence of c++11 compiler */ #ifndef MSHADOW_IN_CXX11 #define MSHADOW_IN_CXX11 (defined(__GXX_EXPERIMENTAL_CXX0X__) ||\ __cplusplus >= 201103L || defined(_MSC_VER)) #endif /*! \brief whether use SSE */ #ifndef MSHADOW_USE_SSE #define MSHADOW_USE_SSE 1 #endif /*! \brief whether use NVML to get dynamic info */ #ifndef MSHADOW_USE_NVML #define MSHADOW_USE_NVML 0 #endif // SSE is conflict with cudacc #ifdef __CUDACC__ #undef MSHADOW_USE_SSE #define MSHADOW_USE_SSE 0 #endif #if MSHADOW_USE_CBLAS extern "C" { #include <cblas.h> } #elif MSHADOW_USE_MKL #include <mkl_blas.h> #include <mkl_cblas.h> #include <mkl_vsl.h> #include <mkl_vsl_functions.h> #endif #if MSHADOW_USE_CUDA #include <cuda.h> #include <cublas_v2.h> #include <curand.h> #endif #if MSHADOW_USE_CUDNN == 1 #include <cudnn.h> #endif #if MSHADOW_USE_NVML #include <nvml.h> #endif // -------------------------------- // MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code #ifdef MSHADOW_XINLINE #error "MSHADOW_XINLINE must not be defined" #endif #ifdef _MSC_VER #define MSHADOW_FORCE_INLINE __forceinline #pragma warning(disable : 4068) #else #define MSHADOW_FORCE_INLINE inline __attribute__((always_inline)) #endif #ifdef __CUDACC__ #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE __device__ __host__ #else #define MSHADOW_XINLINE MSHADOW_FORCE_INLINE #endif /*! \brief cpu force inline */ #define MSHADOW_CINLINE MSHADOW_FORCE_INLINE #if defined(__GXX_EXPERIMENTAL_CXX0X) ||\ defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L #define MSHADOW_CONSTEXPR constexpr #else #define MSHADOW_CONSTEXPR const #endif /*! * \brief default data type for tensor string * in code release, change it to default_real_t * during development, change it to empty string so that missing * template arguments can be detected */ #ifndef MSHADOW_DEFAULT_DTYPE #define MSHADOW_DEFAULT_DTYPE = default_real_t #endif /*! * \brief DMLC marco for logging */ #ifndef MSHADOW_USE_GLOG #define MSHADOW_USE_GLOG DMLC_USE_GLOG #endif // MSHADOW_USE_GLOG #if DMLC_USE_CXX11 #define MSHADOW_THROW_EXCEPTION noexcept(false) #define MSHADOW_NO_EXCEPTION noexcept(true) #else #define MSHADOW_THROW_EXCEPTION #define MSHADOW_NO_EXCEPTION #endif /*! * \brief Protected cuda call in mshadow * \param func Expression to call. * It checks for CUDA errors after invocation of the expression. */ #define MSHADOW_CUDA_CALL(func) \ { \ cudaError_t e = (func); \ if (e == cudaErrorCudartUnloading) { \ throw dmlc::Error(cudaGetErrorString(e)); \ } \ CHECK(e == cudaSuccess) \ << "CUDA: " << cudaGetErrorString(e); \ } /*! * \brief Run function and catch error, log unknown error. * \param func Expression to call. */ #define MSHADOW_CATCH_ERROR(func) \ { \ try { \ (func); \ } catch (const dmlc::Error &e) { \ std::string what = e.what(); \ if (what.find("driver shutting down") == std::string::npos) { \ LOG(ERROR) << "Ignore CUDA Error " << what; \ } \ } \ } #include "./half.h" #include "./half2.h" #include "./logging.h" /*! \brief namespace for mshadow */ namespace mshadow { /*! \brief buffer size for each random number generator */ const unsigned kRandBufferSize = 1000000; /*! \brief pi */ const float kPi = 3.1415926f; /*! \brief type that will be used for index */ typedef unsigned index_t; #ifdef _WIN32 /*! \brief openmp index for windows */ typedef int64_t openmp_index_t; #else /*! \brief openmp index for linux */ typedef index_t openmp_index_t; #endif /*! \brief float point type that will be used in default by mshadow */ typedef float default_real_t; /*! \brief data type flag */ enum TypeFlag { kFloat32 = 0, kFloat64 = 1, kFloat16 = 2, kUint8 = 3, kInt32 = 4, kInt8 = 5 }; template<typename DType> struct DataType; template<> struct DataType<float> { static const int kFlag = kFloat32; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_32F; #endif #if MSHADOW_USE_CUDNN static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_FLOAT; typedef float ScaleType; #endif #endif }; template<> struct DataType<double> { static const int kFlag = kFloat64; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_64F; #endif #if MSHADOW_USE_CUDNN static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_DOUBLE; typedef double ScaleType; #endif #endif }; template<> struct DataType<half::half_t> { static const int kFlag = kFloat16; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_16F; #endif #if MSHADOW_USE_CUDNN static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_HALF; typedef float ScaleType; #endif #endif }; template<> struct DataType<half::half2_t> { static const int kFlag = kFloat16; static const int kLanes = 2; }; template<> struct DataType<uint8_t> { static const int kFlag = kUint8; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_8U; #endif #if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6) // no uint8 in cudnn for now static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT8; typedef uint8_t ScaleType; #endif #endif }; template<> struct DataType<int8_t> { static const int kFlag = kInt8; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_8I; #endif #if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6) static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT8; typedef int8_t ScaleType; #endif #endif }; template<> struct DataType<int32_t> { static const int kFlag = kInt32; static const int kLanes = 1; #if MSHADOW_USE_CUDA #if (CUDA_VERSION >= 8000) static const cudaDataType_t kCudaFlag = CUDA_R_32I; #endif #if (MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 6) static const cudnnDataType_t kCudnnFlag = CUDNN_DATA_INT32; typedef int32_t ScaleType; #endif #endif }; /*! \brief type enum value for default real type */ const int default_type_flag = DataType<default_real_t>::kFlag; /*! layout flag */ enum LayoutFlag { kNCHW = 0, kNHWC, kCHWN, kNCW = 1 << 3, kNWC, kCWN, kNCDHW = 1 << 5, kNDHWC, kCDHWN }; template<int layout> struct LayoutType; template<> struct LayoutType<kNCHW> { static const index_t kNdim = 4; #if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4) static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NCHW; #else static const int kCudnnFlag = -1; #endif }; template<> struct LayoutType<kNHWC> { static const index_t kNdim = 4; #if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4) static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NHWC; #else static const int kCudnnFlag = -1; #endif }; /*! \brief default layout for 4d tensor */ const int default_layout = kNCHW; template<> struct LayoutType<kNCDHW> { static const index_t kNdim = 5; #if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4) static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NCHW; #else static const int kCudnnFlag = -1; #endif }; template<> struct LayoutType<kNDHWC> { static const index_t kNdim = 5; #if (MSHADOW_USE_CUDA && MSHADOW_USE_CUDNN == 1 && CUDNN_MAJOR >= 4) static const cudnnTensorFormat_t kCudnnFlag = CUDNN_TENSOR_NHWC; #else static const int kCudnnFlag = -1; #endif }; /*! \brief default layout for 5d tensor */ const int default_layout_5d = kNCDHW; /*! \brief namespace for operators */ namespace op { // binary operator /*! \brief mul operator */ struct mul{ /*! \brief map a, b to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return a * b; } }; /*! \brief plus operator */ struct plus { /*! \brief map a, b to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return a + b; } }; /*! \brief minus operator */ struct minus { /*! \brief map a, b to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return a - b; } }; /*! \brief divide operator */ struct div { /*! \brief map a, b to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return a / b; } }; /*! \brief get rhs */ struct right { /*! \brief map a, b to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return b; } }; // unary operator/ function: example // these operators can be defined by user, // in the same style as binary and unary operator // to use, simply write F<op::identity>( src ) /*! \brief identity function that maps a real number to it self */ struct identity{ /*! \brief map a to result using defined operation */ template<typename DType> MSHADOW_XINLINE static DType Map(DType a) { return a; } }; } // namespace op /*! \brief namespace for savers */ namespace sv { /*! \brief save to saver: = */ struct saveto { /*! \brief save b to a using save method */ template<typename DType> MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*) a = b; } /*! \brief helper constant to use BLAS, alpha */ inline static default_real_t AlphaBLAS(void) { return 1.0f; } /*! \brief helper constant to use BLAS, beta */ inline static default_real_t BetaBLAS(void) { return 0.0f; } /*! \brief corresponding binary operator type */ typedef op::right OPType; }; /*! \brief save to saver: += */ struct plusto { /*! \brief save b to a using save method */ template<typename DType> MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*) a += b; } /*! \brief helper constant to use BLAS, alpha */ inline static default_real_t AlphaBLAS(void) { return 1.0f; } /*! \brief helper constant to use BLAS, beta */ inline static default_real_t BetaBLAS(void) { return 1.0f; } /*! \brief corresponding binary operator type */ typedef op::plus OPType; }; /*! \brief minus to saver: -= */ struct minusto { /*! \brief save b to a using save method */ template<typename DType> MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*) a -= b; } /*! \brief helper constant to use BLAS, alpha */ inline static default_real_t AlphaBLAS(void) { return -1.0f; } /*! \brief helper constant to use BLAS, beta */ inline static default_real_t BetaBLAS(void) { return 1.0f; } /*! \brief corresponding binary operator type */ typedef op::minus OPType; }; /*! \brief multiply to saver: *= */ struct multo { /*! \brief save b to a using save method */ template<typename DType> MSHADOW_XINLINE static void Save(DType &a, DType b) { // NOLINT(*) a *= b; } /*! \brief corresponding binary operator type */ typedef op::mul OPType; }; /*! \brief divide to saver: /= */ struct divto { /*! \brief save b to a using save method */ template<typename DType> MSHADOW_XINLINE static void Save(DType& a, DType b) { // NOLINT(*) a /= b; } /*! \brief corresponding binary operator type */ typedef op::div OPType; }; } // namespace sv /*! \brief namespace for potential reducer operations */ namespace red { namespace limits { /*! * \brief minimum value of certain types * \tparam DType data type */ template<typename DType> MSHADOW_XINLINE DType MinValue(void); /*! \brief minimum value of float */ template<> MSHADOW_XINLINE float MinValue<float>(void) { return -FLT_MAX; } /*! \brief minimum value of double */ template<> MSHADOW_XINLINE double MinValue<double>(void) { return -DBL_MAX; } /*! \brief minimum value of half */ template<> MSHADOW_XINLINE half::half_t MinValue<half::half_t>(void) { return MSHADOW_HALF_MIN; } /*! \brief minimum value of uint8_t */ template<> MSHADOW_XINLINE uint8_t MinValue<uint8_t>(void) { return 0; } /*! \brief minimum value of int8_t */ template<> MSHADOW_XINLINE int8_t MinValue<int8_t>(void) { return SCHAR_MIN; } /*! \brief minimum value of int32_t */ template<> MSHADOW_XINLINE int MinValue<int32_t>(void) { return INT_MIN; } /*! * \brief maximum value of certain types * \tparam DType data type */ template<typename DType> MSHADOW_XINLINE DType MaxValue(void); /*! \brief maximum value of float */ template<> MSHADOW_XINLINE float MaxValue<float>(void) { return FLT_MAX; } /*! \brief maximum value of double */ template<> MSHADOW_XINLINE double MaxValue<double>(void) { return DBL_MAX; } /*! \brief maximum value of uint8_t */ template<> MSHADOW_XINLINE uint8_t MaxValue<uint8_t>(void) { return UCHAR_MAX; } /*! \brief maximum value of int8_t */ template<> MSHADOW_XINLINE int8_t MaxValue<int8_t>(void) { return SCHAR_MAX; } /*! \brief maximum value of int32_t */ template<> MSHADOW_XINLINE int MaxValue<int32_t>(void) { return INT_MAX; } } // namespace limits /*! \brief sum reducer */ struct sum { /*! \brief do reduction into dst */ template<typename DType> MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*) dst += src; } /*! *\brief calculate gradient of redres with respect to redsrc, * redres: reduced result, redsrc: one of reduction element */ template<typename DType> MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) { return 1; } /*! *\brief set the initial value during reduction */ template<typename DType> MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*) initv = 0; } }; /*! \brief maximum reducer */ struct maximum { /*! \brief do reduction into dst */ template<typename DType> MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*) using namespace std; #ifdef __CUDACC__ dst = ::max(dst, src); #else dst = max(dst, src); #endif // __CUDACC__ } /*! * \brief calculate gradient of redres with respect to redsrc, * redres: reduced result, redsrc: one of reduction element */ template<typename DType> MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) { return redres == redsrc ? 1: 0; } /*! *\brief set the initial value during reduction */ template<typename DType> MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*) initv = limits::MinValue<DType>(); } }; /*! \brief minimum reducer */ struct minimum { /*! \brief do reduction into dst */ template<typename DType> MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) { // NOLINT(*) using namespace std; #ifdef __CUDACC__ dst = ::min(dst, src); #else dst = min(dst, src); #endif // __CUDACC__ } /*! * \brief calculate gradient of redres with respect to redsrc, * redres: reduced result, redsrc: one of reduction element */ template<typename DType> MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) { return redres == redsrc ? 1: 0; } /*! *\brief set the initial value during reduction */ template<typename DType> MSHADOW_XINLINE static void SetInitValue(DType &initv) { // NOLINT(*) initv = -limits::MinValue<DType>(); } }; } // namespace red #define MSHADOW_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MSHADOW_TYPE_SWITCH_WITH_HALF2(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half2_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MSHADOW_REAL_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ break; \ case mshadow::kInt32: \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32";\ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MSHADOW_REAL_TYPE_SWITCH_EX(type$, DType$, DLargeType$, ...) \ switch (type$) { \ case mshadow::kFloat32: \ { \ typedef float DType$; \ typedef float DLargeType$; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType$; \ typedef double DLargeType$; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType$; \ typedef float DLargeType$; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ break; \ case mshadow::kInt32: \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32";\ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type$; \ } #define MSHADOW_LAYOUT_SWITCH(layout, Layout, ...) \ switch (layout) { \ case mshadow::kNCHW: \ { \ const int Layout = kNCHW; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kNHWC: \ { \ const int Layout = kNHWC; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kNCDHW: \ { \ const int Layout = kNCDHW; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kNDHWC: \ { \ const int Layout = kNDHWC; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown layout enum " << layout; \ } /*! \brief get data type size from type enum */ inline size_t mshadow_sizeof(int type) { int size = 0; MSHADOW_TYPE_SWITCH(type, DType, size = sizeof(DType);); return size; } } // namespace mshadow #endif // MSHADOW_BASE_H_
{ "alphanum_fraction": 0.527368568, "avg_line_length": 31.7583148559, "ext": "h", "hexsha": "d633b42900fc929a620ae474c78fcd1807cbbf35", "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": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "withinnoitatpmet/mxnetsource", "max_forks_repo_path": "mshadow/mshadow/base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "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": "withinnoitatpmet/mxnetsource", "max_issues_repo_path": "mshadow/mshadow/base.h", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "fab56d8efec12bd2af2b3ab8a8a26c733a83ffa7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "withinnoitatpmet/mxnetsource", "max_stars_repo_path": "mshadow/mshadow/base.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6738, "size": 28646 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include "allvars.h" #include "proto.h" static double logTimeBegin; static double logTimeMax; double drift_integ(double a, void *param) { double h; h = hubble_function(a); return 1 / (h * a * a * a); } double gravkick_integ(double a, void *param) { double h; h = hubble_function(a); return 1 / (h * a * a); } double hydrokick_integ(double a, void *param) { double h; h = hubble_function(a); return 1 / (h * pow(a, 3 * GAMMA_MINUS1) * a); } double growthfactor_integ(double a, void *param) { double s; s = hubble_function(a) / All.Hubble * sqrt(a * a * a); return pow(sqrt(a) / s, 3); } void init_drift_table(void) { #define WORKSIZE 100000 int i; double result, abserr; /*---------- DEBUG ! ------------*/ #ifdef DARKENERGY_DEBUG FILE *FdDKfac; char mode[2], buf[200]; strcpy(mode, "w"); sprintf(buf, "%s%s", All.OutputDir, "driftkickfac.txt"); FdDKfac = fopen(buf, mode); fprintf(FdDKfac, "i a drift GravKick HydroKick\n"); /*---------- DEBUG ! ------------*/ #endif gsl_function F; gsl_integration_workspace *workspace; logTimeBegin = log(All.TimeBegin); logTimeMax = log(All.TimeMax); workspace = gsl_integration_workspace_alloc(WORKSIZE); for(i = 0; i < DRIFT_TABLE_LENGTH; i++) { F.function = &drift_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble, /* note: absolute error just a dummy */ 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); DriftTable[i] = result; F.function = &gravkick_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble, /* note: absolute error just a dummy */ 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); GravKickTable[i] = result; F.function = &hydrokick_integ; gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), All.Hubble, /* note: absolute error just a dummy */ 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr); HydroKickTable[i] = result; #ifdef DARKENERGY_DEBUG /*---------- DEBUG ! ------------*/ fprintf(FdDKfac, "%d %e %e %e %e \n", i, exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), DriftTable[i], GravKickTable[i], HydroKickTable[i]); /*---------- DEBUG ! ------------*/ #endif } gsl_integration_workspace_free(workspace); #ifdef DARKENERGY_DEBUG /*---------- DEBUG ! ------------*/ fclose(FdDKfac); /*---------- DEBUG ! ------------*/ #endif } /*! This function integrates the cosmological prefactor for a drift * step between time0 and time1. The value returned is * \f[ \int_{a_0}^{a_1} \frac{{\rm d}a}{H(a)} * \f] * * A lookup-table is used for reasons of speed. */ double get_drift_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; static int last_time0 = -1, last_time1 = -1; static double last_value; if(time0 == last_time0 && time1 == last_time1) return last_value; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; if(logTimeMax > logTimeBegin) u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u1 = 0; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * DriftTable[0]; else df1 = DriftTable[i1 - 1] + (DriftTable[i1] - DriftTable[i1 - 1]) * (u1 - i1); if(logTimeMax > logTimeBegin) u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u2 = 0; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * DriftTable[0]; else df2 = DriftTable[i2 - 1] + (DriftTable[i2] - DriftTable[i2 - 1]) * (u2 - i2); last_time0 = time0; last_time1 = time1; return last_value = (df2 - df1); } double get_gravkick_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; static int last_time0 = -1, last_time1 = -1; static double last_value; if(time0 == last_time0 && time1 == last_time1) return last_value; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; if(logTimeMax > logTimeBegin) u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u1 = 0; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * GravKickTable[0]; else df1 = GravKickTable[i1 - 1] + (GravKickTable[i1] - GravKickTable[i1 - 1]) * (u1 - i1); if(logTimeMax > logTimeBegin) u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u2 = 0; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * GravKickTable[0]; else df2 = GravKickTable[i2 - 1] + (GravKickTable[i2] - GravKickTable[i2 - 1]) * (u2 - i2); last_time0 = time0; last_time1 = time1; return last_value = (df2 - df1); } double get_hydrokick_factor(int time0, int time1) { double a1, a2, df1, df2, u1, u2; int i1, i2; static int last_time0 = -1, last_time1 = -1; static double last_value; if(time0 == last_time0 && time1 == last_time1) return last_value; /* note: will only be called for cosmological integration */ a1 = logTimeBegin + time0 * All.Timebase_interval; a2 = logTimeBegin + time1 * All.Timebase_interval; if(logTimeMax > logTimeBegin) u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u1 = 0; i1 = (int) u1; if(i1 >= DRIFT_TABLE_LENGTH) i1 = DRIFT_TABLE_LENGTH - 1; if(i1 <= 1) df1 = u1 * HydroKickTable[0]; else df1 = HydroKickTable[i1 - 1] + (HydroKickTable[i1] - HydroKickTable[i1 - 1]) * (u1 - i1); if(logTimeMax > logTimeBegin) u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH; else u2 = 0; i2 = (int) u2; if(i2 >= DRIFT_TABLE_LENGTH) i2 = DRIFT_TABLE_LENGTH - 1; if(i2 <= 1) df2 = u2 * HydroKickTable[0]; else df2 = HydroKickTable[i2 - 1] + (HydroKickTable[i2] - HydroKickTable[i2 - 1]) * (u2 - i2); last_time0 = time0; last_time1 = time1; return last_value = (df2 - df1); }
{ "alphanum_fraction": 0.6343768458, "avg_line_length": 25.3632958801, "ext": "c", "hexsha": "9ea74830b81172dfab9bbf31ca27fe52b29480a5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_line_length": 182, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/driftfac.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2290, "size": 6772 }
#pragma once #include <list> #include <map> #include <memory> #include <string> #include <gsl/gsl_math.h> #include "Expressions/Expression.h" #include "Scanner/scanner.h" #include "Parser/parser.h" #include "Utils/Exception.h" class MathEngine { std::unique_ptr<Parser> parser; Variables variables; public: MathEngine(); std::list<Scanner::Token> scan(const std::string& input); expression parse(const std::string& input); expression operator()(const std::string& input); expression eval(const std::string& input); expression eval(expression inputExpr); std::string formatInput(const std::string& input, int& cursorPosition); std::string evaluateOutput(const std::string& input, const std::string& output); };
{ "alphanum_fraction": 0.6783919598, "avg_line_length": 23.4117647059, "ext": "h", "hexsha": "a62c4a24b4f7a14e4ef17fe4b407514bb1bd648b", "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": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_path": "MathEngine/MathEngine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "antoniojkim/CalcPlusPlus", "max_issues_repo_path": "MathEngine/MathEngine.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_path": "MathEngine/MathEngine.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 174, "size": 796 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for EOBNRv2HM reduced order model (non-spinning version). * See CQG 31 195010, 2014, arXiv:1402.4146 for details on the reduced order method. * See arXiv:1106.1021 for the EOBNRv2HM model. * * Borrows from the SEOBNR ROM LAL code written by Michael Puerrer and John Veitch. * * Put the untared data in the directory designated by the environment variable ROM_DATA_PATH. * * Parameter range: * q = 1-12 (almost) * No spin * Mtot >= 10Msun for fstart=8Hz * */ #ifndef _EOBNRV2HMROM_H #define _EOBNRV2HMROM_H #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "EOBNRv2HMROMstruct.h" #if defined(__cplusplus) extern "C" { #elif 0 } /* so that editors will match preceding brace */ #endif /********General definitions********/ #define nk_amp 10 /* number of SVD-modes == number of basis functions for amplitude */ #define nk_phi 20 /* number of SVD-modes == number of basis functions for phase */ /********External array for the list of modes********/ #define nbmodemax 5 extern const int listmode[nbmodemax][2]; /**************************************************/ /**************** Prototypes **********************/ /* Functions to load, initalize and cleanup data */ int EOBNRv2HMROM_Init_DATA(void); int EOBNRv2HMROM_Init(const char dir[]); void EOBNRHMROMdata_Init(EOBNRHMROMdata **data); void EOBNRHMROMdata_interp_Init(EOBNRHMROMdata_interp **data_interp); void EOBNRHMROMdata_coeff_Init(EOBNRHMROMdata_coeff **data_coeff); void EOBNRHMROMdata_Cleanup(EOBNRHMROMdata *data); void EOBNRHMROMdata_interp_Cleanup(EOBNRHMROMdata_interp *data_interp); void EOBNRHMROMdata_coeff_Cleanup(EOBNRHMROMdata_coeff *data_coeff); /* Function to read data */ int Read_Data_Mode(const char dir[], const int mode[2], EOBNRHMROMdata *data); /* Functions to interpolate the data and to evaluate the interpolated data for a given q */ int Evaluate_Spline_Data( const double q, /* Input: q-value for which projection coefficients should be evaluated */ const EOBNRHMROMdata_interp* data_interp, /* Input: data in interpolated form */ EOBNRHMROMdata_coeff* data_coeff /* Output: vectors of projection coefficients and shifts in time and phase */ ); int Interpolate_Spline_Data( const EOBNRHMROMdata *data, /* Input: data in vector/matrix form to interpolate */ EOBNRHMROMdata_interp *data_interp /* Output: interpolated data */ ); /* Functions for waveform reconstruction */ int EOBNRv2HMROMCore( struct tagListmodesCAmpPhaseFrequencySeries **listhlm, int nbmode, double tRef, double phiRef, double fRef, double Mtot_sec, double q, double distance, int setphiRefattRef); int SimEOBNRv2HMROM( ListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */ int nbmode, /* Number of modes to generate (starting with the 22) */ double tRef, /* Time shift with respect to the 22-fit removed waveform (s) */ double phiRef, /* Phase at reference frequency */ double fRef, /* Reference frequency (Hz); 0 defaults to fLow */ double m1SI, /* Mass of companion 1 (kg) */ double m2SI, /* Mass of companion 2 (kg) */ double distance, /* Distance of source (m) */ int setphiRefattRef); /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */ int SimEOBNRv2HMROMExtTF2( ListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */ int nbmode, /* Number of modes to generate (starting with the 22) */ double Mf_match, /* Minimum frequency using EOBNRv2HMROM in inverse total mass units*/ double minf, /* Minimum frequency required */ int tagexthm, /* Tag to decide whether or not to extend the higher modes as well */ double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */ double phiRef, /* Phase at reference frequency */ double fRef, /* Reference frequency (Hz); 0 defaults to fLow */ double m1SI, /* Mass of companion 1 (kg) */ double m2SI, /* Mass of companion 2 (kg) */ double distance, /* Distance of source (m) */ int setphiRefattRef); /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _EOBNRV2HMROM_H */
{ "alphanum_fraction": 0.6416053277, "avg_line_length": 40.1830985915, "ext": "h", "hexsha": "83dc9a4936ebcf24e674a00a3e1e9cbedce29ec0", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "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": "JohnGBaker/flare", "max_issues_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.h", "max_line_length": 232, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.h", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 1376, "size": 5706 }
/* * 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 graph_46d3170b_a19a_4663_bbf9_c7372932671b_h #define graph_46d3170b_a19a_4663_bbf9_c7372932671b_h #include <assert.h> #include <gslib/std.h> __gslib_begin__ template<class _meta> struct _mono_rel { _meta* _next; _mono_rel() { _next = nullptr; } _meta* next() const { return _next; } void set_next(_meta* ptr) { _next = ptr; } _meta* operator+(int d) const { assert(d >= 0); _meta* p = static_cast<_meta*>(this); for( ; d > 0; d --) p = p->_next; return p; } int operator-(const _meta& that) const { int c = 0; _meta* p = static_cast<_meta*>(this); for( ; p->_next; p = p->_next, c ++) { if(p == &that) return c; } assert(!"unexpected."); return -1; } int count_to_tail() const { int c = 0; for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_next, c ++); return c; } static void shake(_meta* p1, _meta* p2) { p1->_next = p2; } }; template<class _meta> struct _dual_rel { _meta *_prev, *_next; _dual_rel() { _prev = _next = nullptr; } _meta* prev() const { return _prev; } _meta* next() const { return _next; } void set_prev(_meta* ptr) { _prev = ptr; } void set_next(_meta* ptr) { _next = ptr; } _meta* operator+(int d) const { if(d < 0) return operator-(-d); _meta* p = static_cast<_meta*>(this); for( ; d > 0; d --) p = p->_next; return p; } _meta* operator-(int d) const { if(d < 0) return operator+(-d); _meta* p = static_cast<_meta*>(this); for( ; d > 0; d --) p = p->_prev; return p; } int operator-(const _meta& that) const { int c = 0; _meta* p = static_cast<_meta*>(this); for( ; p->_next; p = p->_next, c ++) { if(p == &that) return c; } assert(!"unexpected."); return -1; } int count_to_head() const { int c = 0; for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_prev, c ++); return c; } int count_to_tail() const { int c = 0; for(_meta* p = static_cast<_meta*>(this); p->_next; p = p->_next, c ++); return c; } static void shake(_meta* p1, _meta* p2) { p1->_next = p2, p2->_prev = p1; } }; template<class _meta> struct _pack_rel { _meta *_from, *_to; int _size; _pack_rel() { _from = _to = nullptr, _size = 0; } _pack_rel(_meta* from, _meta* to) { _from = from, _to = to, _size = 0; } _meta* from() const { return _from; } _meta* to() const { return _to; } bool empty() const { return !_from; } int size() const { return _size; } void set_from(_meta* ptr) { _from = ptr; } void set_to(_meta* ptr) { _to = ptr; } void increase_size() { _size ++; } void decrease_size() { _size --; } void set_size(int s) { _size = s; } bool check_mono() const { if(!_from) return false; _meta* p = static_cast<_meta*>(_from); for( ; p->_next; p = p->_next); return p == _to; } bool check_dual() const { if(!_from || _from->_prev) return false; _meta* p = static_cast<_meta*>(_from); for( ; p->_next; p = p->_next) { if(p->_prev && p != p->_prev->_next) return false; } return p == _to; } bool is_belong_to(const _meta* ptr) const { _meta* p = static_cast<_meta*>(_from); for( ; p; p = p->_next) { if(ptr == p) return true; } return false; } }; class _graph_ortho_rel: public _dual_rel<_graph_ortho_rel> { public: typedef _pack_rel<_graph_ortho_rel> hierarchic_rel; typedef _dual_rel<_graph_ortho_rel> peer_rel; typedef hierarchic_rel upper_rel; typedef hierarchic_rel lower_rel; protected: hierarchic_rel _parents, _children; public: hierarchic_rel& parents() { return _parents; } hierarchic_rel& children() { return _children; } peer_rel& siblings() { return static_cast<peer_rel&>(*this); } const hierarchic_rel& const_parents() const { return _parents; } const hierarchic_rel& const_children() const { return _children; } const peer_rel& const_siblings() const { return static_cast<const peer_rel&>(*this); } int parents_count() const { return _parents.size(); } int children_count() const { return _children.size(); } }; struct _graph_trait_copy {}; struct _graph_trait_detach {}; template<class _ty, class _rel = _graph_ortho_rel > struct _graph_ortho_cpy_wrapper: public _ty, public _rel { typedef _ty value; typedef _rel relation; typedef _graph_ortho_cpy_wrapper<_ty, _rel> wrapper; typedef _graph_trait_copy tsf_behavior; value* get_ptr() { return static_cast<value*>(this); } const value* const_ptr() const { return static_cast<const value*>(this); } value& get_ref() { return static_cast<value&>(*this); } const value& const_ref() const { return static_cast<const value&>(*this); } template<class _cst> void born() {} /* maybe a problem. */ void born() {} void kill() {} void copy(const wrapper* a) { assign<value>(a); } void attach(wrapper* a) { !!error!! } int get_parents_count() const { return parents_count(); } int get_children_count() const { return children_count(); } template<class c> void assign(const wrapper* a) { static_cast<c&>(*this) = static_cast<c&>(*a); } }; template<class _ty, class _rel = _graph_ortho_rel > struct _graph_ortho_wrapper: public _rel { typedef _ty value; typedef _rel relation; typedef _graph_ortho_wrapper<_ty, _rel> wrapper; typedef _graph_trait_detach tsf_behavior; value* _value; wrapper() { _value = nullptr; } value* get_ptr() { return _value; } const value* const_ptr() const { return _value; } value& get_ref() { return *_value; } const value& const_ref() const { return *_value; } relation& get_relation() { return static_cast<relation&>(*this); } const relation& const_relation() const { return static_cast<const relation&>(*this); } template<class _cst> void born() { _value = new _cst; } void born() { _value = new value; } void kill() { delete _value; } void copy(const wrapper* a) { assert(!"prevent."); } void attach(wrapper* a) { assert(a && a->_value); kill(); _value = a->_value; a->_value = nullptr; } int get_parents_count() const { return parents_count(); } int get_children_count() const { return children_count(); } }; template<class _wrapper> struct _graph_allocator { typedef _wrapper wrapper; static wrapper* born() { return new wrapper; } static void kill(wrapper* w) { delete w; } }; template<class _val> struct _graph_ortho_val { typedef _val value; typedef const _val const_value; union { value* _vptr; const_value* _cvptr; }; value* get_wrapper() const { return _vptr; } value* trace_front(int d) const { return _vptr->siblings() + d; } value* trace_back(int d) const { return _vptr->siblings() - d; } value* trace_up(int d) const { if(d < 0) return trace_down(-d); value* p = _vptr; for( ; d > 0; d --) { assert(!p->parents().empty()); p = p->parents().from(); } return p; } value* trace_down(int d) const { if(d < 0) return trace_up(-d); value* p = _vptr; for( ; d > 0; d --) { assert(!p->children().empty()); p = p->children().from(); } return p; } value* trace_front() const { assert(_vptr); return _vptr->next(); } value* trace_back() const { assert(_vptr); return _vptr->prev(); } }; template<class _ty, class _wrapper = _graph_ortho_cpy_wrapper<_ty> > class _graph_ortho_const_iterator: public _graph_ortho_val<_wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _graph_ortho_const_iterator<_ty, _wrapper> iterator; public: iterator(const wrapper* w = nullptr) { _cvptr = w; } bool is_valid() const { return _cvptr != nullptr; } const value* get_ptr() const { return _cvptr->const_ptr(); } const value* operator->() const { return _cvptr->const_ptr(); } const value& operator*() const { return _cvptr->const_ref(); } iterator operator+(int d) const { return iterator(trace_front(d)); } iterator operator-(int d) const { return iterator(trace_back(d)); } iterator operator<<(int d) const { return iterator(trace_up(d)); } iterator operator>>(int d) const { return iterator(trace_down(d)); } int operator-(iterator i) const { return _cvptr->peer_rel::operator-(*(i._cvptr)); } }; template<class _ty, class _wrapper = _graph_ortho_cpy_wrapper<_ty> > class _graph_ortho_iterator: public _graph_ortho_const_iterator<_ty, _wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _graph_ortho_const_iterator<_ty, _wrapper> superref; typedef _graph_ortho_const_iterator<_ty, _wrapper> const_iterator; typedef _graph_ortho_iterator<_ty, _wrapper> iterator; public: iterator(wrapper* w = nullptr) { _vptr = w; } value* get_ptr() const { return _vptr->get_ptr(); } value* operator->() const { return _vptr->get_ptr(); } value& operator*() const { return _vptr->get_ref(); } bool operator==(const iterator& that) const { return _vptr == that._vptr; } bool operator!=(const iterator& that) const { return _vptr != that._vptr; } bool operator==(const const_iterator& that) const { return _vptr == that._vptr; } bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; } void operator++() { _vptr = trace_front(); } void operator--() { _vptr = trace_back(); } void operator+=(int d) { _vptr = trace_front(d); } void operator-=(int d) { _vptr = trace_back(d); } void operator<<=(int d) { _vptr = trace_up(d); } void operator>>=(int d) { _vptr = trace_down(d); } operator const_iterator() { return const_iterator(_cvptr); } }; template<class _ty, class _wrapper = _graph_ortho_wrapper<_ty>, class _alloc = _graph_allocator<_wrapper> > class ortho_graph: public _graph_ortho_val<_wrapper> { public: typedef _ty value; typedef _wrapper wrapper; typedef _alloc alloc; typedef ortho_graph<_ty, _wrapper, _alloc> myref; typedef _graph_ortho_const_iterator const_iterator; typedef _graph_ortho_iterator iterator; public: ortho_graph() { _vptr = nullptr; } ~ortho_graph() { destroy(); } void destroy() { for(wrapper* i = _vptr; i; ) { wrapper* n = i->next(); _erase(i); i = n; } } void clear() { destroy(); } iterator get_root() { return iterator(_vptr); } const_iterator const_root() const { return const_iterator(_cvptr); } bool is_valid() const { return !_cvptr; } iterator insert_before(iterator i) { return insert_before<value>(i); } iterator insert_after(iterator i) { return insert_after<value>(i); } iterator create_child(iterator from, iterator to = from) { return create_child<value>(from, to); } iterator erase(iterator i) { iterator r(i->next()); _erase(i.get_wrapper()); return r; } public: template<class _cst> iterator insert_before(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_cst>(); wrapper* n = alloc::born(); n->born<_cst>(); _fix_peer_rel(i->prev(), n, *i); _fix_upper_rel(n, *i); _fix_lower_rel(n, *i); /* fix root, keep the root always be the top left corner. */ if(i.get_wrapper() == _vptr) _vptr = n; return iterator(n); } template<class _cst> iterator insert_after(iterator i) { if(!i.is_valid()) return _cvptr ? get_root() : _init<_cst>(); wrapper* n = alloc::born(); n->born<_cst>(); _fix_peer_rel(*i, n, i->next()); _fix_upper_rel(n, *i); _fix_lower_rel(n, *i); return iterator(n); } template<class _cst> iterator create_child(iterator from, iterator to = from) { assert(from.is_valid() && from->children().empty()); wrapper* n = alloc::born(); n->born<_cst>(); _fix_upper_rel(n, *from, *to); return iterator(n); } template<class _lambda> void _for_range(iterator from, iterator to, _lambda lam) { for(iterator i = from; ; i ++) { lam(i->get_wrapper()); if(i == to) break; } } template<class _lambda> void for_range(iterator from, iterator to, _lambda lam) { for(iterator i = from; ; i ++) { lam(*i); if(i == to) break; } } protected: template<class _cst> iterator _init() { _vptr = alloc::born(); _vptr->born<_cst>(); return iterator(_vptr); } void _erase(wrapper* w) { assert(w); _fix_upper_rel(w); _fix_lower_rel(w); peer_rel::shake(w->prev(), w->next()); lower_rel& rel = w->children(); if(!rel.empty()) _for_range(rel.from(), rel.to(), [](wrapper* w) { _erase(w); }); if(w == _vptr) _vptr = w->next(); w->kill(); alloc::kill(w); } void _set_range_upper(wrapper* from, wrapper* to, wrapper* r1, wrapper* r2, int size) { _for_range(iterator(from), iterator(to), [&r1, &r2, &size](wrapper* w) { upper_rel& rel = w->parents(); rel.set_from(r1); rel.set_to(r2); rel.set_size(size); }); } void _set_range_lower(wrapper* from, wrapper* to, wrapper* r1, wrapper* r2, int size) { _for_range(iterator(from), iterator(to), [&r1, &r2, &size](wrapper* w) { lower_rel& rel = w->children(); rel.set_from(r1); rel.set_to(r2); rel.set_size(size); }); } void _fix_peer_rel(wrapper* w1, wrapper* w2, wrapper* w3) { assert(w2 && (w1 || w3)); if(w1 != nullptr) peer_rel::shake(w1, w2); if(w3 != nullptr) peer_rel::shake(w2, w3); } void _fix_upper_rel(wrapper* n, wrapper* w) { assert(n && w); upper_rel& urel = w->parents(); wrapper* u1 = urel.from(); if(u1 == nullptr) return; wrapper* u2 = urel.to(); lower_rel& lrel = u1->children(); wrapper* l1 = lrel.from(); wrapper* l2 = lrel.to(); assert(l1 && l2); wrapper *from = l1, *to = l2; if(l1 == w && n == w->prev()) from = n; else if(l2 == w && n == w->next()) to = n; _set_range_lower(u1, u2, from, to, lrel.size() + 1); upper_rel& u = n->parents(); u.set_from(u1); u.set_to(u2); } void _fix_lower_rel(wrapper* n, wrapper* w) { assert(n && w); lower_rel& lrel = w->children(); wrapper* l1 = lrel.from(); if(l1 == nullptr) return; wrapper* l2 = lrel.to(); upper_rel& urel = l1->parents(); wrapper* u1 = urel.from(); wrapper* u2 = urel.to(); assert(u1 && u2); wrapper *from = u1, *to = u2; if(u1 == w && n == w->prev()) from = n; else if(u2 == w && n == w->next()) to = n; _set_range_upper(l1, l2, from, to, urel.size() + 1); lower_rel& l = n->children(); l.set_from(l1); l.set_to(l2); } void _fix_upper_rel(wrapper* w) { assert(w); upper_rel& urel = w->parents(); wrapper* u1 = urel.from(); if(u1 == nullptr) return; wrapper* u2 = urel.to(); assert(u2); lower_rel& lrel = u1->children(); wrapper* l1 = lrel.from(); wrapper* l2 = lrel.to(); assert(l1 && l2); wrapper *from = l1, *to = l2; if(l1 == w && l2 == w) from = to = nullptr; else if(l1 == w) from = w->next(); else if(l2 == w) to = w->prev(); _set_range_lower(u1, u2, from, to, lrel.size() - 1); urel.set_from(nullptr); urel.set_to(nullptr); urel.set_size(0); } void _fix_lower_rel(wrapper* w) { assert(w); lower_rel& lrel = w->children(); wrapper* l1 = lrel.from(); if(l1 == nullptr) return; wrapper* l2 = lrel.to(); assert(l2); upper_rel& urel = l1->parents(); wrapper* u1 = urel.from(); wrapper* u2 = urel.to(); assert(u1 && u2); wrapper *from = u1, *to = u2; if(u1 == w && u2 == w); else if(u1 == w || u2 == w) { u1 == w ? from = w->next() : to = w->prev(); lrel.set_from(nullptr); lrel.set_to(nullptr); lrel.set_size(0); } _set_range_upper(l1, l2, from, to, urel.size() - 1); } void _fix_upper_rel(wrapper* w, wrapper* u1, wrapper* u2) { assert(w && u1 && u2); upper_rel& urel = w->parents(); urel.set_from(u1); urel.set_to(u2); urel.set_size(u1->count_to_tail(u2) + 1); _set_range_lower(u1, u2, w, w, 1); } }; __gslib_end__ #endif
{ "alphanum_fraction": 0.550995592, "avg_line_length": 31.6805778491, "ext": "h", "hexsha": "99ec552b92ac06d24669695938f13031ddcda79c", "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/graph.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/graph.h", "max_line_length": 103, "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/graph.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": 5263, "size": 19737 }
#include <math.h> #include <stdlib.h> #include "fd3sep.h" /* #include "mxfuns.h" */ #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #define SVCUT 1.0e-9 /*************************************************************************/ double fd3sep ( long K, long M, long N, double **dftobs, double *sig, double **rvm, double **lfm, double **dftmod, double **dftres ) { long i, j, k, n; double s2; gsl_matrix *A, *U, *X, *V; gsl_vector *S, *w, *b, *x; /* prepare */ A = gsl_matrix_alloc ( 2*M, 2*K ); U = gsl_matrix_alloc ( 2*M, 2*K ); X = gsl_matrix_alloc ( 2*K, 2*K ); V = gsl_matrix_alloc ( 2*K, 2*K ); S = gsl_vector_alloc ( 2*K ); w = gsl_vector_alloc ( 2*K ); b = gsl_vector_alloc ( 2*M ); x = gsl_vector_alloc ( 2*K ); /* for each DFT component */ for ( s2 = n = 0 ; n <= N/2 ; n++ ) { /* assemble data vector and model matrix */ for ( j = 0 ; j < M ; j++ ) { double s = *(sig+j); gsl_vector_set ( b, 2*j, *(*(dftobs+j)+2*n) /s ); gsl_vector_set ( b, 2*j+1, *(*(dftobs+j)+2*n+1)/s ); for ( k = 0 ; k < K ; k++ ) { double q, v, fv, rez, imz; q = 2.0 * M_PI * ((double)n)/((double)N); v = *(*(rvm+k)+j); fv = floor(v); rez = *(*(lfm+k)+j) * ( ((fv+1)-v)*cos(fv*q) + (v-fv)*cos((fv+1)*q) ); imz = - *(*(lfm+k)+j) * ( ((fv+1)-v)*sin(fv*q) + (v-fv)*sin((fv+1)*q) ); gsl_matrix_set ( A, 2*j, 2*k, rez/s ); gsl_matrix_set ( A, 2*j, 2*k+1, - imz/s ); gsl_matrix_set ( A, 2*j+1, 2*k, imz/s ); gsl_matrix_set ( A, 2*j+1, 2*k+1, rez/s ); } gsl_matrix_memcpy ( U, A ); } /* solve for model parameters */ /* gsl_linalg_SV_decomp ( U, V, S, w ); */ /* gsl_linalg_SV_decomp_mod ( U, X, V, S, w ); */ /* gsl_linalg_SV_decomp_jacobi ( U, V, S ); */ gsl_linalg_SV_decomp_mod ( U, X, V, S, w ); for ( k = 0 ; k < 2*K-1 ; k++ ) if ( gsl_vector_get(S,2*K-1-k)/gsl_vector_get(S,0) < SVCUT ) gsl_vector_set ( S, 2*K-1-k, 0 ); gsl_linalg_SV_solve ( U, V, S, b, x ); /* copy to output */ for ( k = 0 ; k < K ; k++ ) { *(*(dftmod+k)+2*n ) = gsl_vector_get ( x, 2*k ); *(*(dftmod+k)+2*n+1) = gsl_vector_get ( x, 2*k+1 ); } /* compute s2 */ for ( j = 0 ; j < M ; j++ ) for ( i = 0 ; i < 2 ; i++ ) { double bc, db, s = *(sig+j); for ( bc = k = 0 ; k < K ; k++ ) { bc += gsl_matrix_get( A, 2*j+i, 2*k ) * gsl_vector_get( x, 2*k ); bc += gsl_matrix_get( A, 2*j+i, 2*k+1 ) * gsl_vector_get( x, 2*k+1 ); } db = gsl_vector_get ( b, 2*j+i ) - bc; s2 += db * db * ( n % ((N+1)/2) ? 2 : 1 ); *(*(dftres+j)+2*n+i) = db * s; } } /* close */ gsl_matrix_free ( A ); gsl_matrix_free ( U ); gsl_matrix_free ( X ); gsl_matrix_free ( V ); gsl_vector_free ( S ); gsl_vector_free ( w ); gsl_vector_free ( b ); gsl_vector_free ( x ); return s2; } /*************************************************************************/ void dft_fwd ( long m, long n, double **mxin, double **mxout ) { long i, j; double a = 1.0 / sqrt(n); gsl_fft_real_wavetable * dft_rewt; gsl_fft_real_workspace * dft_rews; dft_rewt = gsl_fft_real_wavetable_alloc (n); dft_rews = gsl_fft_real_workspace_alloc (n); for ( j = 0 ; j < m ; j++ ) { for ( i = 0; i < n; i++ ) *(*(mxout+j)+i+1) = a * *(*(mxin+j)+i); gsl_fft_real_transform ( *(mxout+j)+1, 1, n, dft_rewt, dft_rews ); *(*(mxout+j)+0) = *(*(mxout+j)+1); *(*(mxout+j)+1) = 0; if ( ! n % 2 ) *(*(mxout+j)+n+1) = 0; /* if n even */ } gsl_fft_real_wavetable_free ( dft_rewt ); gsl_fft_real_workspace_free ( dft_rews ); } /*************************************************************************/ void dft_bck ( long m, long n, double **mxin, double **mxout ) { long i, j; double a = 1.0 / sqrt(n); gsl_fft_halfcomplex_wavetable * dft_hcwt; gsl_fft_real_workspace * dft_rews; dft_hcwt = gsl_fft_halfcomplex_wavetable_alloc (n); dft_rews = gsl_fft_real_workspace_alloc (n); for ( j = 0 ; j < m ; j++ ) { *(*(mxout+j)+0) = *(*(mxin+j)+0) / a; for ( i = 1; i < n; i++ ) *(*(mxout+j)+i) = *(*(mxin+j)+i+1) / a; gsl_fft_halfcomplex_inverse ( *(mxout+j), 1, n, dft_hcwt, dft_rews ); } gsl_fft_halfcomplex_wavetable_free ( dft_hcwt ); gsl_fft_real_workspace_free ( dft_rews ); } /*************************************************************************/
{ "alphanum_fraction": 0.4665408013, "avg_line_length": 28.8909090909, "ext": "c", "hexsha": "7da8e4fc45683a3f758ed417925c30c6a2badbde", "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": "fd3_Jul2014update/fd3sep.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": "fd3_Jul2014update/fd3sep.c", "max_line_length": 79, "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": "fd3_Jul2014update/fd3sep.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": 1652, "size": 4767 }
/** * @file sad.h * @brief Voice activity detection. * @author Kenichi Kumatani and John McDonough */ #ifndef SAD_H #define SAD_H #include <stdio.h> #include <assert.h> #define _LOG_SAD_ #ifdef _LOG_SAD_ #include <stdarg.h> #endif /* _LOG_SAD_ */ #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_fit.h> #include "common/jexception.h" #include "stream/stream.h" #include "feature/feature.h" #include "sad/neural_spnsp_incl.h" // ----- definition for abstract base class `NeuralNetVAD' ----- // class NeuralNetVAD { public: NeuralNetVAD(VectorFloatFeatureStreamPtr& cep, unsigned context = 4, unsigned hiddenUnitsN = 1000, unsigned outputUnitsN = 2, float threshold = 0.1, const String& neuralNetFile = ""); ~NeuralNetVAD(); bool next(int frame_no = -5); void reset(); void read(const String& neuralNetFile); private: void shift_down_(); void increment_() { frame_no_++; } void update_buffer_(int frame_no); const VectorFloatFeatureStreamPtr cep_; const int frame_reset_no_; const unsigned cepLen_; bool is_speech_; int frame_no_; unsigned framesPadded_; unsigned context_; unsigned hiddenUnitsN_; unsigned outputUnitsN_; float threshold_; MLP* mlp_; float** frame_; }; typedef refcount_ptr<NeuralNetVAD> NeuralNetVADPtr; // ----- definition for abstract base class `VAD' ----- // class VAD { public: VAD(VectorComplexFeatureStreamPtr& samp); ~VAD(); virtual bool next(int frame_no = -5) = 0; virtual void reset() { frame_no_ = frame_reset_no_; } const gsl_vector_complex* frame() const { return frame_; } virtual void next_speaker() = 0; protected: void increment_() { frame_no_++; } const VectorComplexFeatureStreamPtr samp_; const int frame_reset_no_; const unsigned fftLen_; bool is_speech_; int frame_no_; gsl_vector_complex* frame_; }; typedef refcount_ptr<VAD> VADPtr; // ----- definition for class `EnergyVAD' ----- // class SimpleEnergyVAD : public VAD { public: SimpleEnergyVAD(VectorComplexFeatureStreamPtr& samp, double threshold, double gamma = 0.995); ~SimpleEnergyVAD(); virtual bool next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } #endif private: const double threshold_; const double gamma_; double spectral_energy_; }; typedef Inherit<SimpleEnergyVAD, VADPtr> SimpleEnergyVADPtr; // ----- definition for class `SimpleLikelihoodRatioVAD' ----- // class SimpleLikelihoodRatioVAD : public VAD { public: SimpleLikelihoodRatioVAD(VectorComplexFeatureStreamPtr& samp, double threshold, double alpha); ~SimpleLikelihoodRatioVAD(); virtual bool next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); void set_variance(const gsl_vector* variance); #ifdef ENABLE_LEGACY_BTK_API__ void setVariance(const gsl_vector* variance); void nextSpeaker(){ next_speaker(); } #endif private: double calc_Ak_(double vk, double gammak, double Rk); bool variance_set_; gsl_vector* noise_variance_; gsl_vector* prev_Ak_; gsl_vector_complex* prev_frame_; double threshold_; double alpha_; }; typedef Inherit<SimpleLikelihoodRatioVAD, VADPtr> SimpleLikelihoodRatioVADPtr; // ----- definition for class `EnergyVADFeature' ----- // class EnergyVADFeature : public VectorFloatFeatureStream { public: EnergyVADFeature(const VectorFloatFeatureStreamPtr& source, double threshold = 0.5, unsigned bufferLength = 30, unsigned energiesN = 200, const String& nm = "Energy VAD"); virtual ~EnergyVADFeature(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); void next_speaker(); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } #endif private: static int comparator_(const void* elem1, const void* elem2); virtual bool above_threshold_(const gsl_vector_float* vector); VectorFloatFeatureStreamPtr source_; bool recognizing_; gsl_vector_float** buffer_; const unsigned bufferLen_; int bufferX_; unsigned bufferedN_; unsigned abovethresholdN_; unsigned belowThresholdN_; unsigned energiesN_; double* energies_; double* sorted_energies_; const unsigned medianX_; }; typedef Inherit<EnergyVADFeature, VectorFloatFeatureStreamPtr> EnergyVADFeaturePtr; // ----- definition for abstract base class `VADMetric' ----- // class VADMetric : public Countable { public: VADMetric(); ~VADMetric(); virtual double next(int frame_no = -5) = 0; virtual void reset() = 0; double score(){ return cur_score_;} virtual void next_speaker() = 0; #ifdef _LOG_SAD_ bool openLogFile( const String & logfilename ); int writeLog( const char *format, ... ); void closeLogFile(); void initScore(){ _score=0.0; _scoreX=0; } void setScore(double score){ _score=score; _scoreX++; } double getAverageScore(){ if(_scoreX==0){return 0;} return(_score/_scoreX); } int frame_no_; #endif /* _LOG_SAD_ */ protected: double cur_score_; #ifdef _LOG_SAD_ private: FILE *logfp_; double _score; unsigned _scoreX; #endif /* _LOG_SAD_ */ }; typedef refcountable_ptr<VADMetric> VADMetricPtr; // ----- definition for class `EnergyVADMetric' ----- // class EnergyVADMetric : public VADMetric { public: EnergyVADMetric(const VectorFloatFeatureStreamPtr& source, double initialEnergy = 5.0e+07, double threshold = 0.5, unsigned headN = 4, unsigned tailN = 10, unsigned energiesN = 200, const String& nm = "Energy VAD Metric"); ~EnergyVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); double energy_percentile(double percentile = 50.0) const; #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } double energyPercentile(double percentile = 50.0){ return energy_percentile(percentile); } #endif private: static int comparator_(const void* elem1, const void* elem2); virtual bool above_threshold_(const gsl_vector_float* vector); VectorFloatFeatureStreamPtr source_; const double initial_energy_; const unsigned headN_; const unsigned tailN_; bool recognizing_; unsigned abovethresholdN_; unsigned belowThresholdN_; unsigned energiesN_; double* energies_; double* sorted_energies_; const unsigned medianX_; }; typedef Inherit<EnergyVADMetric, VADMetricPtr> EnergyVADMetricPtr; // ----- definition for class `MultiChannelVADMetric' ----- // template <typename ChannelType> class MultiChannelVADMetric : public VADMetric { public: MultiChannelVADMetric(unsigned fftLen, double sampleRate, double lowCutoff, double highCutoff, const String& nm); ~MultiChannelVADMetric(); void set_channel(ChannelType& chan); #ifdef ENABLE_LEGACY_BTK_API__ void setChannel(ChannelType& chan){ set_channel(chan); } #endif protected: unsigned set_lowX_(double lowCutoff) const; unsigned set_highX_(double highCutoff) const; unsigned set_binN_() const; typedef list<ChannelType> ChannelList_; ChannelList_ _channelList; const unsigned fftLen_; const unsigned fftLen2_; const double samplerate_; const unsigned lowX_; const unsigned highX_; const unsigned binN_; FILE *logfp_; }; template<> MultiChannelVADMetric<VectorFloatFeatureStreamPtr>::MultiChannelVADMetric(unsigned fftLen, double sampleRate, double lowCutoff, double highCutoff, const String& nm); template<> MultiChannelVADMetric<VectorComplexFeatureStreamPtr>::MultiChannelVADMetric(unsigned fftLen, double sampleRate, double lowCutoff, double highCutoff, const String& nm); template<> MultiChannelVADMetric<VectorFloatFeatureStreamPtr>::~MultiChannelVADMetric(); template<> MultiChannelVADMetric<VectorComplexFeatureStreamPtr>::~MultiChannelVADMetric(); template<> void MultiChannelVADMetric<VectorFloatFeatureStreamPtr>::set_channel(VectorFloatFeatureStreamPtr& chan); template<> void MultiChannelVADMetric<VectorComplexFeatureStreamPtr>::set_channel(VectorComplexFeatureStreamPtr& chan); typedef MultiChannelVADMetric<VectorFloatFeatureStreamPtr> FloatMultiChannelVADMetric; typedef MultiChannelVADMetric<VectorComplexFeatureStreamPtr> ComplexMultiChannelVADMetric; typedef refcountable_ptr<FloatMultiChannelVADMetric> FloatMultiChannelVADMetricPtr; typedef refcountable_ptr<ComplexMultiChannelVADMetric> ComplexMultiChannelVADMetricPtr; // ----- definition for class `PowerSpectrumVADMetric' ----- // /** @brief detect voice activity based on the energy comparison @usage 1. construct the object with PowerSpectrumVADMetric(). 2. set the channel data with set_channel(). 3. call next(). @note the first channel is associated with the target speaker. */ class PowerSpectrumVADMetric : public FloatMultiChannelVADMetric { public: PowerSpectrumVADMetric(unsigned fftLen, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "Power Spectrum VAD Metric"); PowerSpectrumVADMetric(VectorFloatFeatureStreamPtr& source1, VectorFloatFeatureStreamPtr& source2, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "Power Spectrum VAD Metric"); ~PowerSpectrumVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); gsl_vector *get_metrics() const { return powerList_;} void set_E0( double E0 ){ E0_ = E0;} void clear_channel(); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } gsl_vector *getMetrics(){ return get_metrics(); } void setE0( double E0 ){ set_E0(E0); } void clearChannel(){ clear_channel(); } #endif protected: typedef ChannelList_::iterator ChannelIterator_; gsl_vector *powerList_; double E0_; }; typedef Inherit<PowerSpectrumVADMetric, FloatMultiChannelVADMetricPtr> PowerSpectrumVADMetricPtr; // ----- definition for class `NormalizedEnergyMetric' ----- // /** @class @usage @note */ class NormalizedEnergyMetric : public PowerSpectrumVADMetric { static double initial_energy_; public: NormalizedEnergyMetric(unsigned fftLen, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "TSPS VAD Metric"); ~NormalizedEnergyMetric(); virtual double next(int frame_no = -5); virtual void reset(); }; typedef Inherit<NormalizedEnergyMetric, PowerSpectrumVADMetricPtr> NormalizedEnergyMetricPtr; // ----- definition for class `CCCVADMetric' ----- // /** @class compute cross-correlation coefficients (CCC) as a function of time delays, and average up the n-best values. @usage @note */ class CCCVADMetric : public ComplexMultiChannelVADMetric { public: CCCVADMetric(unsigned fftLen, unsigned nCand, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "CCC VAD Metric"); ~CCCVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); void set_NCand(unsigned nCand); void set_threshold(double threshold){ threshold_ = threshold;} gsl_vector *get_metrics() const { return ccList_;} void clear_channel(); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } void setNCand(unsigned nCand){ set_NCand(nCand); } void setThreshold(double threshold){ set_threshold(threshold); } gsl_vector *getMetrics(){ return get_metrics(); } void clearChannel(){ clear_channel(); } #endif protected: typedef ChannelList_::iterator ChannelIterator_; unsigned nCand_; gsl_vector *ccList_; gsl_vector_int *sample_delays_; double threshold_; double *pack_cross_spectrum_; }; typedef Inherit<CCCVADMetric, ComplexMultiChannelVADMetricPtr> CCCVADMetricPtr; // ----- definition for class `TSPSVADMetric' ----- // /** @class @usage @note */ class TSPSVADMetric : public PowerSpectrumVADMetric { static double initial_energy_; public: TSPSVADMetric(unsigned fftLen, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "TSPS VAD Metric"); ~TSPSVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); }; typedef Inherit<TSPSVADMetric,PowerSpectrumVADMetricPtr> TSPSVADMetricPtr; // ----- definition for class `NegentropyVADMetric' ----- // class NegentropyVADMetric : public VADMetric { protected: class ComplexGeneralizedGaussian_ : public Countable { public: ComplexGeneralizedGaussian_(double shapeFactor = 2.0); double logLhood(gsl_complex X, double scaleFactor) const; double shapeFactor() const { return shape_factor_; } double Bc() const { return Bc_; } double normalization() const { return normalization_; } protected: virtual double calc_Bc_() const; virtual double calc_normalization_() const; const double shape_factor_; /* const */ double Bc_; /* const */ double normalization_; }; typedef refcountable_ptr<ComplexGeneralizedGaussian_> ComplexGeneralizedGaussianPtr_; typedef list<ComplexGeneralizedGaussianPtr_> GaussianList_; typedef GaussianList_::iterator GaussianListIterator_; typedef GaussianList_::const_iterator GaussianListConstIterator_; public: NegentropyVADMetric(const VectorComplexFeatureStreamPtr& source, const VectorFloatFeatureStreamPtr& spectralEstimator, const String& shapeFactorFileName = "", double threshold = 0.5, double sampleRate = 16000.0, double lowCutoff = -1.0, double highCutoff = -1.0, const String& nm = "Negentropy VAD Metric"); ~NegentropyVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); double calc_negentropy(int frame_no); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } double calcNegentropy(int frame_no){ return calc_negentropy(frame_no); } #endif protected: virtual bool above_threshold_(int frame_no); unsigned set_lowX_(double lowCutoff) const; unsigned set_highX_(double highCutoff) const; unsigned set_binN_() const; VectorComplexFeatureStreamPtr source_; VectorFloatFeatureStreamPtr spectral_estimator_; GaussianList_ generalized_gaussians_; ComplexGeneralizedGaussianPtr_ gaussian_; const double threshold_; const unsigned fftLen_; const unsigned fftLen2_; const double samplerate_; const unsigned lowX_; const unsigned highX_; const unsigned binN_; }; typedef Inherit<NegentropyVADMetric, VADMetricPtr> NegentropyVADMetricPtr; // ----- definition for class `MutualInformationVADMetric' ----- // class MutualInformationVADMetric : public NegentropyVADMetric { public: MutualInformationVADMetric(const VectorComplexFeatureStreamPtr& source1, const VectorComplexFeatureStreamPtr& source2, const VectorFloatFeatureStreamPtr& spectralEstimator1, const VectorFloatFeatureStreamPtr& spectralEstimator2, const String& shapeFactorFileName = "", double twiddle = -1.0, double threshold = 1.3, double beta = 0.95, double sampleRate = 16000.0, double lowCutoff = 187.0, double highCutoff = 1000.0, const String& nm = "Mutual Information VAD Metric"); ~MutualInformationVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); double calc_mutual_information(int frame_no); #ifdef ENABLE_LEGACY_BTK_API__ double calcMutualInformation(int frame_no){ return calc_mutual_information(frame_no); } #endif protected: class JointComplexGeneralizedGaussian_ : public NegentropyVADMetric::ComplexGeneralizedGaussian_ { public: JointComplexGeneralizedGaussian_(const NegentropyVADMetric::ComplexGeneralizedGaussianPtr_& ggaussian); ~JointComplexGeneralizedGaussian_(); double logLhood(gsl_complex X1, gsl_complex X2, double scaleFactor1, double scaleFactor2, gsl_complex rho12) const; private: static const double sqrt_two_; static const gsl_complex complex_one_; static const gsl_complex complex_zero_; virtual double calc_Bc_() const; virtual double calc_normalization_() const; double lngamma_ratio_(double f) const; double lngamma_ratio_joint_(double f) const; double match_(double f) const; double match_score_marginal_(double f) const; double match_score_joint_(double fJ) const; static const double tolerance_; gsl_vector_complex* X_; gsl_vector_complex* scratch_; gsl_matrix_complex* SigmaX_inverse_; }; protected: typedef refcountable_ptr<JointComplexGeneralizedGaussian_> JointComplexGeneralizedGaussianPtr_; typedef list<JointComplexGeneralizedGaussianPtr_> JointGaussianList_; typedef JointGaussianList_::iterator JointGaussianListIterator_; typedef JointGaussianList_::const_iterator JointGaussianListConstIterator_; typedef vector<gsl_complex> CrossCorrelationVector_; static const double epsilon_; virtual bool above_threshold_(int frame_no); double calc_fixed_threshold_(); double calc_total_threshold_() const; void initialize_pdfs_(); VectorComplexFeatureStreamPtr source2_; VectorFloatFeatureStreamPtr spectral_estimator2_; JointGaussianList_ joint_generalized_gaussians_; CrossCorrelationVector_ ccs_; // cross correlations const double fixed_threshold_; const double twiddle_; const double threshold_; const double beta_; }; typedef Inherit<MutualInformationVADMetric, NegentropyVADMetricPtr> MutualInformationVADMetricPtr; // ----- definition for class `LikelihoodRatioVADMetric' ----- // class LikelihoodRatioVADMetric : public NegentropyVADMetric { public: LikelihoodRatioVADMetric(const VectorComplexFeatureStreamPtr& source1, const VectorComplexFeatureStreamPtr& source2, const VectorFloatFeatureStreamPtr& spectralEstimator1, const VectorFloatFeatureStreamPtr& spectralEstimator2, const String& shapeFactorFileName = "", double threshold = 0.0, double sampleRate = 16000.0, double lowCutoff = 187.0, double highCutoff = 1000.0, const String& nm = "Likelihood VAD Metric"); ~LikelihoodRatioVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); double calc_likelihood_ratio(int frame_no); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } double calcLikelihoodRatio(int frame_no){ return calc_likelihood_ratio(frame_no); } #endif private: const VectorComplexFeatureStreamPtr source2_; const VectorFloatFeatureStreamPtr spectral_estimator2_; }; typedef Inherit<LikelihoodRatioVADMetric, NegentropyVADMetricPtr> LikelihoodRatioVADMetricPtr; // ----- definition for class `LowFullBandEnergyRatioVADMetric' ----- // class LowFullBandEnergyRatioVADMetric : public VADMetric { public: LowFullBandEnergyRatioVADMetric(const VectorFloatFeatureStreamPtr& source, const gsl_vector* lowpass, double threshold = 0.5, const String& nm = "Low- Full-Band Energy Ratio VAD Metric"); ~LowFullBandEnergyRatioVADMetric(); virtual double next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } #endif private: virtual bool above_threshold_(int frame_no); void calc_auto_correlation_vector_(int frame_no); void calc_covariance_matrix_(); double calc_lower_band_energy_(); VectorFloatFeatureStreamPtr source_; const unsigned _lagsN; gsl_vector* _lowpass; gsl_vector* scratch_; double* _autocorrelation; gsl_matrix* _covariance; }; typedef Inherit<LowFullBandEnergyRatioVADMetric, VADMetricPtr> LowFullBandEnergyRatioVADMetricPtr; // ----- definition for class `HangoverVADFeature' ----- // class HangoverVADFeature : public VectorFloatFeatureStream { public: HangoverVADFeature(const VectorFloatFeatureStreamPtr& source, const VADMetricPtr& metric, double threshold = 0.5, unsigned headN = 4, unsigned tailN = 10, const String& nm = "Hangover VAD Feature"); virtual ~HangoverVADFeature(); virtual const gsl_vector_float* next(int frame_no = -5); virtual void reset(); virtual void next_speaker(); int prefixN() const { return prefixN_ - headN_; } #ifdef ENABLE_LEGACY_BTK_API__ void nextSpeaker(){ next_speaker(); } #endif protected: typedef pair<VADMetricPtr, double> MetricPair_; typedef vector<MetricPair_> MetricList_; typedef MetricList_::iterator MetricListIterator_; typedef MetricList_::const_iterator MetricListConstIterator_; static const unsigned EnergyVADMetricX = 0; static const unsigned MutualInformationVADMetricX = 1; static const unsigned LikelihoodRatioVADMetricX = 2; static int comparator_(const void* elem1, const void* elem2); virtual bool above_threshold_(int frame_no); VectorFloatFeatureStreamPtr source_; bool recognizing_; gsl_vector_float** buffer_; const unsigned headN_; const unsigned tailN_; int bufferX_; unsigned bufferedN_; unsigned abovethresholdN_; unsigned belowThresholdN_; unsigned prefixN_; MetricList_ metricList_; }; typedef Inherit<HangoverVADFeature, VectorFloatFeatureStreamPtr> HangoverVADFeaturePtr; // ----- definition for class `HangoverMIVADFeature' ----- // class HangoverMIVADFeature : public HangoverVADFeature { static const unsigned EnergyVADMetricX = 0; static const unsigned MutualInformationVADMetricX = 1; static const unsigned PowerVADMetricX = 2; public: HangoverMIVADFeature(const VectorFloatFeatureStreamPtr& source, const VADMetricPtr& energyMetric, const VADMetricPtr& mutualInformationMetric, const VADMetricPtr& powerMetric, double energythreshold = 0.5, double mutualInformationThreshold = 0.5, double powerThreshold = 0.5, unsigned headN = 4, unsigned tailN = 10, const String& nm = "Hangover VAD Feature"); int decision_metric() const { return decision_metric_; } #ifdef ENABLE_LEGACY_BTK_API__ int decisionMetric() { return decision_metric(); } #endif protected: virtual bool above_threshold_(int frame_no); int decision_metric_; }; typedef Inherit<HangoverMIVADFeature, HangoverVADFeaturePtr> HangoverMIVADFeaturePtr; // ----- definition for class `HangoverMultiStageVADFeature' ----- // class HangoverMultiStageVADFeature : public HangoverVADFeature { public: HangoverMultiStageVADFeature(const VectorFloatFeatureStreamPtr& source, const VADMetricPtr& energyMetric, double energythreshold = 0.5, unsigned headN = 4, unsigned tailN = 10, const String& nm = "HangoverMultiStageVADFeature"); ~HangoverMultiStageVADFeature(); int decision_metric() const { return decision_metric_; } void set_metric( const VADMetricPtr& metricPtr, double threshold ){ metricList_.push_back( MetricPair_( metricPtr, threshold ) ); } #ifdef ENABLE_LEGACY_BTK_API__ int decisionMetric() { return decision_metric(); } void setMetric( const VADMetricPtr& metricPtr, double threshold ){ set_metric(metricPtr, threshold); } #endif #ifdef _LOG_SAD_ void initScores(); gsl_vector *getScores(); #endif /* _LOG_SAD_ */ protected: virtual bool above_threshold_(int frame_no); int decision_metric_; #ifdef _LOG_SAD_ gsl_vector *_scores; #endif /* _LOG_SAD_ */ }; typedef Inherit<HangoverMultiStageVADFeature, HangoverVADFeaturePtr> HangoverMultiStageVADFeaturePtr; #endif
{ "alphanum_fraction": 0.7322303165, "avg_line_length": 31.3914728682, "ext": "h", "hexsha": "d7eb240fc92450573faa2fda7038468df5bef7dc", "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/sad/sad.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/sad/sad.h", "max_line_length": 189, "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/sad/sad.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": 6039, "size": 24297 }
/*System includes*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <sys/stat.h> #include <float.h> /*GSL includes*/ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_statistics_double.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cblas.h> #include <pthread.h> #include <Python.h> /*User includes*/ #include "vbgmmmodule.h" static PyObject *vbgmm_fit(PyObject *self, PyObject *args) { const char *szFileStub = NULL; int nKStart = 0, nLMin = 0, nMaxIter; unsigned long lSeed; double dEpsilon; int bCout = 0; int sts; if (!PyArg_ParseTuple(args, "siikidi", &szFileStub,&nKStart,&nLMin,&lSeed,&nMaxIter,&dEpsilon,&bCout)) return NULL; sts = driver(szFileStub,nKStart,nLMin,lSeed,nMaxIter,dEpsilon,bCout); return Py_BuildValue("i", sts); } static PyMethodDef VbgmmMethods[] = { {"fit", vbgmm_fit, METH_VARARGS, "Fit a variational Bayesian Gaussian mixture."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; /* Python 2.x code */ PyMODINIT_FUNC initvbgmm(void) { (void) Py_InitModule("vbgmm", VbgmmMethods); } int driver(const char* szFileStub, int nKStart, int nLMin, unsigned long lSeed, int nMaxIter, double dEpsilon, int bCOut) { t_Params tParams; t_Data tData; gsl_rng *ptGSLRNG = NULL; const gsl_rng_type *ptGSLRNGType = NULL; int i = 0, k = 0, nD = 0, nN = 0; char szOFile[MAX_LINE_LENGTH]; FILE *ofp = NULL; t_VBParams tVBParams; t_Cluster *ptBestCluster = NULL; gsl_matrix *ptTemp = NULL; gsl_matrix *ptTVar = NULL; /*initialise GSL RNG*/ gsl_rng_env_setup(); gsl_set_error_handler_off(); ptGSLRNGType = gsl_rng_default; ptGSLRNG = gsl_rng_alloc(ptGSLRNGType); /*get command line params*/ tParams.nKStart = nKStart; tParams.nLMin = nLMin; tParams.nMaxIter = nMaxIter; tParams.dEpsilon = dEpsilon; tParams.lSeed = lSeed; setParams(&tParams,szFileStub); /*read in input data*/ readInputData(tParams.szInputFile, &tData); readPInputData(tParams.szPInputFile, &tData); nD = tData.nD; nN = tData.nN; ptTemp = gsl_matrix_alloc(tData.nT,nD); ptTVar = gsl_matrix_alloc(tData.nT,tData.nT); setVBParams(&tVBParams, &tData); ptBestCluster = (t_Cluster *) malloc(sizeof(t_Cluster)); ptBestCluster->nN = nN; ptBestCluster->nK = tParams.nKStart; ptBestCluster->nD = nD; ptBestCluster->ptData = &tData; ptBestCluster->ptVBParams = &tVBParams; ptBestCluster->lSeed = tParams.lSeed; ptBestCluster->nMaxIter = tParams.nMaxIter; ptBestCluster->dEpsilon = tParams.dEpsilon; if(bCOut > 0){ ptBestCluster->szCOutFile = szFileStub; } else{ ptBestCluster->szCOutFile = NULL; } runRThreads((void *) &ptBestCluster); compressCluster(ptBestCluster); calcCovarMatrices(ptBestCluster,&tData); sprintf(szOFile,"%sclustering_gt%d.csv",tParams.szOutFileStub,tParams.nLMin); writeClusters(szOFile,ptBestCluster,&tData); sprintf(szOFile,"%spca_means_gt%d.csv",tParams.szOutFileStub,tParams.nLMin); writeMeans(szOFile,ptBestCluster); sprintf(szOFile,"%smeans_gt%d.csv",tParams.szOutFileStub,tParams.nLMin); writeTMeans(szOFile,ptBestCluster,&tData); for(k = 0; k < ptBestCluster->nK; k++){ sprintf(szOFile,"%spca_variances_gt%d_dim%d.csv",tParams.szOutFileStub,tParams.nLMin,k); writeSquareMatrix(szOFile, ptBestCluster->aptSigma[k], nD); /*not entirely sure this is correct?*/ gsl_blas_dgemm (CblasNoTrans,CblasNoTrans,1.0,tData.ptTMatrix,ptBestCluster->aptSigma[k],0.0,ptTemp); gsl_blas_dgemm (CblasNoTrans,CblasTrans,1.0,ptTemp,tData.ptTMatrix,0.0,ptTVar); sprintf(szOFile,"%svariances_gt%d_dim%d.csv",tParams.szOutFileStub,tParams.nLMin,k); writeSquareMatrix(szOFile, ptTVar, nD); } sprintf(szOFile,"%sresponsibilities.csv",tParams.szOutFileStub); ofp = fopen(szOFile,"w"); if(ofp){ for(i = 0; i < nN; i++){ for(k = 0; k < ptBestCluster->nK - 1; k++){ fprintf(ofp,"%f,",ptBestCluster->aadZ[i][k]); } fprintf(ofp,"%f\n",ptBestCluster->aadZ[i][ptBestCluster->nK - 1]); } fclose(ofp); } else{ fprintf(stderr,"Failed openining %s in main\n", szOFile); fflush(stderr); } sprintf(szOFile,"%svbl.csv",tParams.szOutFileStub); ofp = fopen(szOFile,"w"); if(ofp){ fprintf(ofp,"%d,%f,%d\n",ptBestCluster->nK,ptBestCluster->dVBL,ptBestCluster->nThread); fclose(ofp); } else{ fprintf(stderr,"Failed openining %s in main\n", szOFile); fflush(stderr); } /*free up memory in data object*/ destroyData(&tData); /*free up best BIC clusters*/ destroyCluster(ptBestCluster); free(ptBestCluster); destroyParams(&tParams); gsl_rng_free(ptGSLRNG); gsl_matrix_free(tVBParams.ptInvW0); gsl_matrix_free(ptTemp); gsl_matrix_free(ptTVar); return EXIT_SUCCESS; } void setParams(t_Params *ptParams, const char *szFileStub) { ptParams->szInputFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char)); if(!ptParams->szInputFile) goto memoryError; ptParams->szPInputFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char)); if(!ptParams->szInputFile) goto memoryError; sprintf(ptParams->szInputFile,"%s%s%d.csv",szFileStub,INPUT_FILE,ptParams->nLMin); sprintf(ptParams->szPInputFile,"%s%s%d.csv",szFileStub,PINPUT_FILE,ptParams->nLMin); ptParams->szOutFileStub = szFileStub; return; memoryError: fprintf(stderr, "Failed allocating memory in setParams\n"); fflush(stderr); exit(EXIT_FAILURE); } void destroyParams(t_Params *ptParams) { free(ptParams->szInputFile); free(ptParams->szPInputFile); } void setVBParams(t_VBParams *ptVBParams, t_Data *ptData) { int i = 0, nD = ptData->nD; double adVar[nD], adMu[nD]; ptVBParams->dBeta0 = DEF_BETA0; ptVBParams->dNu0 = (double) nD; ptVBParams->ptInvW0 = gsl_matrix_alloc(nD,nD); calcSampleVar(ptData,adVar, adMu); gsl_matrix_set_zero (ptVBParams->ptInvW0); for(i = 0; i < nD; i++){ double dRD = adVar[i]*((double) nD); gsl_matrix_set(ptVBParams->ptInvW0,i,i,dRD); } ptVBParams->dLogWishartB = dLogWishartB(ptVBParams->ptInvW0, nD, ptVBParams->dNu0, TRUE); } void readInputData(const char *szFile, t_Data *ptData) { double **aadX = NULL; int i = 0, j = 0, nD = 0, nN = 0; char szLine[MAX_LINE_LENGTH]; FILE* ifp = NULL; ifp = fopen(szFile, "r"); if(ifp){ char* szTok = NULL; char* pcError = NULL; if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); /*count dimensions*/ while(strtok(NULL, DELIM) != NULL){ nD++; } /*count data points*/ while(fgets(szLine, MAX_LINE_LENGTH, ifp) != NULL){ nN++; } fclose(ifp); /*reopen input file*/ ifp = fopen(szFile, "r"); if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; /*allocate memory for dimension names*/ ptData->aszDimNames = (char **) malloc(nD*sizeof(char*)); if(!ptData->aszDimNames) goto memoryError; szTok = strtok(szLine, DELIM); /*read in dim names*/ for(i = 0; i < nD; i++){ szTok = strtok(NULL, DELIM); ptData->aszDimNames[i] = strdup(szTok); } /*allocate memory for data matrix*/ aadX = (double **) malloc(nN*sizeof(double*)); if(!aadX) goto memoryError; for(i = 0; i < nN; i++){ aadX[i] = (double *) malloc(nD*sizeof(double)); if(!aadX[i]) goto memoryError; } /*read in input data*/ ptData->aszSampleNames = (char **) malloc(nN*sizeof(char*)); if(!ptData->aszSampleNames) goto memoryError; for(i = 0; i < nN; i++){ if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); ptData->aszSampleNames[i] = strdup(szTok); for(j = 0; j < nD; j++){ szTok = strtok(NULL, DELIM); aadX[i][j] = strtod(szTok,&pcError); if(*pcError != '\0'){ goto formatError; } } } } else{ fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile); fflush(stderr); exit(EXIT_FAILURE); } ptData->nD = nD; ptData->nN = nN; ptData->aadX = aadX; return; memoryError: fprintf(stderr, "Failed allocating memory in readInputData\n"); fflush(stderr); exit(EXIT_FAILURE); formatError: fprintf(stderr, "Incorrectly formatted abundance data file\n"); fflush(stderr); exit(EXIT_FAILURE); } void readPInputData(const char *szFile, t_Data *ptData) { int i = 0, j = 0, nD = ptData->nD, nT = 0; char szLine[MAX_LINE_LENGTH]; FILE* ifp = NULL; ifp = fopen(szFile, "r"); if(ifp){ char* szTok = NULL; char* pcError = NULL; nT = 1; if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto memoryError; szTok = strtok(szLine, DELIM); /*count dimensions*/ while(strtok(NULL, DELIM) != NULL){ nT++; } ptData->ptTMatrix = gsl_matrix_alloc(nT,nD); fclose(ifp); /*reopen input file*/ ifp = fopen(szFile, "r"); for(i = 0; i < nD; i++){ double dTemp = 0.0; if(fgets(szLine, MAX_LINE_LENGTH, ifp) == NULL) goto formatError; szTok = strtok(szLine, DELIM); dTemp = strtod(szTok,&pcError); if(*pcError != '\0'){ goto formatError; } gsl_matrix_set(ptData->ptTMatrix,0,i,dTemp); for(j = 1; j < nT; j++){ szTok = strtok(NULL, DELIM); dTemp = strtod(szTok,&pcError); if(*pcError != '\0'){ goto formatError; } gsl_matrix_set(ptData->ptTMatrix,j,i,dTemp); } } } else{ fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile); fflush(stderr); exit(EXIT_FAILURE); } ptData->nT = nT; return; formatError: fprintf(stderr, "Incorrectly formatted abundance data file\n"); fflush(stderr); exit(EXIT_FAILURE); memoryError: fprintf(stderr, "Failed allocating memory in readPInputFile\n"); fflush(stderr); exit(EXIT_FAILURE); } void destroyData(t_Data *ptData) { int nN = ptData->nN, nD = ptData->nD; int i = 0; gsl_matrix_free(ptData->ptTMatrix); for(i = 0; i < nD; i++){ free(ptData->aszDimNames[i]); } free(ptData->aszDimNames); for(i = 0; i < nN; i++){ free(ptData->aadX[i]); } free(ptData->aadX); for(i = 0; i < nN; i++){ free(ptData->aszSampleNames[i]); } free(ptData->aszSampleNames); return; } void destroyCluster(t_Cluster* ptCluster) { int i = 0, nN = ptCluster->nN, nKSize = ptCluster->nKSize; if(ptCluster->szCOutFile != NULL){ free(ptCluster->szCOutFile); } free(ptCluster->anMaxZ); free(ptCluster->anW); for(i = 0; i < nN; i++){ free(ptCluster->aadZ[i]); } free(ptCluster->aadZ); free(ptCluster->adLDet); free(ptCluster->adPi); free(ptCluster->adBeta); free(ptCluster->adNu); for(i = 0; i < nKSize; i++){ free(ptCluster->aadMu[i]); free(ptCluster->aadM[i]); } free(ptCluster->aadMu); free(ptCluster->aadM); for(i = 0; i < nKSize ; i++){ gsl_matrix_free(ptCluster->aptSigma[i]); gsl_matrix_free(ptCluster->aptCovar[i]); } free(ptCluster->aptSigma); free(ptCluster->aptCovar); return; } void allocateCluster(t_Cluster *ptCluster, int nN, int nK, int nD, t_Data *ptData, long lSeed, int nMaxIter, double dEpsilon, char *szCOutFile) { int i = 0, j = 0, k = 0; ptCluster->szCOutFile = szCOutFile; ptCluster->ptVBParams = NULL; ptCluster->lSeed = lSeed; ptCluster->nMaxIter = nMaxIter; ptCluster->dEpsilon = dEpsilon; ptCluster->ptData = ptData; ptCluster->nN = nN; ptCluster->nK = nK; ptCluster->nKSize = nK; ptCluster->nD = nD; ptCluster->dVBL = 0.0; ptCluster->anMaxZ = (int *) malloc(nN*sizeof(int)); /*destroyed*/ if(!ptCluster->anMaxZ) goto memoryError; ptCluster->anW = (int *) malloc(nK*sizeof(int)); /*destroyed*/ if(!ptCluster->anW) goto memoryError; for(i = 0; i < nN; i++){ ptCluster->anMaxZ[i] = NOT_SET; } for(i = 0; i < nK; i++){ ptCluster->anW[i] = 0; } ptCluster->aadZ = (double **) malloc(nN*sizeof(double *)); /*destroyed*/ if(!ptCluster->aadZ) goto memoryError; for(i = 0; i < nN; i++){ ptCluster->aadZ[i] = (double *) malloc(nK*sizeof(double)); /*destroyed*/ if(!ptCluster->aadZ[i]) goto memoryError; for(j = 0; j < nK; j++){ ptCluster->aadZ[i][j] = 0.0; } } ptCluster->adLDet = (double *) malloc(nK*sizeof(double)); /*all*/ ptCluster->adPi = (double *) malloc(nK*sizeof(double)); ptCluster->adBeta = (double *) malloc(nK*sizeof(double)); ptCluster->adNu = (double *) malloc(nK*sizeof(double)); /*destroyed*/ if(!ptCluster->adLDet || !ptCluster->adPi) goto memoryError; if(!ptCluster->adBeta || !ptCluster->adNu) goto memoryError; for(k = 0; k < nK; k++){ ptCluster->adLDet[k] = 0.0; ptCluster->adPi[k] = 0.0; ptCluster->adBeta[k] = 0.0; ptCluster->adNu[k] = 0.0; } ptCluster->aadMu = (double **) malloc(nK*sizeof(double *)); if(!ptCluster->aadMu) goto memoryError; ptCluster->aadM = (double **) malloc(nK*sizeof(double *)); if(!ptCluster->aadM) goto memoryError; for(i = 0; i < nK; i++){ ptCluster->aadM[i] = (double*) malloc (nD*sizeof(double)); if(!ptCluster->aadM[i]) goto memoryError; ptCluster->aadMu[i] = (double*) malloc (nD*sizeof(double)); if(!ptCluster->aadMu[i]) goto memoryError; } ptCluster->aptSigma = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *)); if(!ptCluster->aptSigma) goto memoryError; for(i = 0; i < nK ; i++){ ptCluster->aptSigma[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD); } ptCluster->aptCovar = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *)); if(!ptCluster->aptCovar) goto memoryError; for(i = 0; i < nK ; i++){ ptCluster->aptCovar[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD); } return; memoryError: fprintf(stderr, "Failed allocating memory in allocateCluster\n"); fflush(stderr); exit(EXIT_FAILURE); } void writeSquareMatrix(char*szFile, gsl_matrix *ptMatrix, int nD) { int i = 0, j = 0; FILE* ofp = fopen(szFile,"w"); if(ofp){ for(i = 0; i < nD; i++){ for(j = 0; j < nD - 1; j++){ fprintf(ofp,"%f,",gsl_matrix_get(ptMatrix,i,j)); } fprintf(ofp,"%f\n",gsl_matrix_get(ptMatrix,i,j)); } } else{ fprintf(stderr,"Failed to open %s for writing in writeSquareMatrix\n", szFile); fflush(stderr); } } double decomposeMatrix(gsl_matrix *ptSigmaMatrix, int nD) { double dDet = 0.0; int status; int l = 0; status = gsl_linalg_cholesky_decomp(ptSigmaMatrix); if(status == GSL_EDOM){ fprintf(stderr,"Failed Cholesky decomposition in decomposeMatrix\n"); fflush(stderr); exit(EXIT_FAILURE); } else{ for(l = 0; l < nD; l++){ double dT = gsl_matrix_get(ptSigmaMatrix,l,l); dDet += 2.0*log(dT); } gsl_linalg_cholesky_invert(ptSigmaMatrix); return dDet; } } void performMStep(t_Cluster *ptCluster, t_Data *ptData){ int i = 0, j = 0, k = 0, l = 0, m = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX; double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi; double **aadCovar = NULL, **aadInvWK = NULL; t_VBParams *ptVBParams = ptCluster->ptVBParams; gsl_matrix* ptSigmaMatrix = gsl_matrix_alloc(nD,nD); aadCovar = (double **) malloc(nD*sizeof(double*)); if(!aadCovar) goto memoryError; for(i = 0; i < nD; i++){ aadCovar[i] = (double *) malloc(nD*sizeof(double)); if(!aadCovar[i]) goto memoryError; } aadInvWK = (double **) malloc(nD*sizeof(double*)); if(!aadInvWK) goto memoryError; for(i = 0; i < nD; i++){ aadInvWK[i] = (double *) malloc(nD*sizeof(double)); if(!aadInvWK[i]) goto memoryError; } /*perform M step*/ for(k = 0; k < nK; k++){ /*loop components*/ double* adMu = ptCluster->aadMu[k]; gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k]; double dF = 0.0; /*recompute mixture weights and means*/ for(j = 0; j < nD; j++){ adMu[j] = 0.0; for(l = 0; l < nD; l++){ aadCovar[j][l] = 0.0; } } /* compute weight associated with component k*/ adPi[k] = 0.0; for(i = 0; i < nN; i++){ if(aadZ[i][k] > MIN_Z){ adPi[k] += aadZ[i][k]; for(j = 0; j < nD; j++){ adMu[j] += aadZ[i][k]*aadX[i][j]; } } } /*normalise means*/ if(adPi[k] > MIN_PI){ /*Equation 10.60*/ ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k]; for(j = 0; j < nD; j++){ /*Equation 10.61*/ ptCluster->aadM[k][j] = adMu[j]/ptCluster->adBeta[k]; adMu[j] /= adPi[k]; } ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k]; /*calculate covariance matrices*/ for(i = 0; i < nN; i++){ if(aadZ[i][k] > MIN_Z){ double adDiff[nD]; for(j = 0; j < nD; j++){ adDiff[j] = aadX[i][j] - adMu[j]; } for(l = 0; l < nD; l++){ for(m = 0; m <=l ; m++){ aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m]; } } } } for(l = 0; l < nD; l++){ for(m = l + 1; m < nD; m++){ aadCovar[l][m] = aadCovar[m][l]; } } /*save sample covariances for later use*/ for(l = 0; l < nD; l++){ for(m = 0; m < nD; m++){ double dC = aadCovar[l][m] / adPi[k]; gsl_matrix_set(ptCluster->aptCovar[k],l,m,dC); } } /*Now perform equation 10.62*/ dF = (ptVBParams->dBeta0*adPi[k])/ptCluster->adBeta[k]; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m]; } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ aadCovar[l][m] /= adPi[k]; gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } /*Implement Equation 10.65*/ adLDet[k] = ((double) nD)*log(2.0); for(l = 0; l < nD; l++){ double dX = 0.5*(ptCluster->adNu[k] - (double) l); adLDet[k] += gsl_sf_psi (dX); } adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD); } else{ /*Equation 10.60*/ adPi[k] = 0.0; ptCluster->adBeta[k] = ptVBParams->dBeta0; for(j = 0; j < nD; j++){ /*Equation 10.61*/ ptCluster->aadM[k][j] = 0.0; adMu[j] = 0.0; } ptCluster->adNu[k] = ptVBParams->dNu0; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m); } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m); } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } /*Implement Equation 10.65*/ adLDet[k] = ((double) nD)*log(2.0); for(l = 0; l < nD; l++){ double dX = 0.5*(ptCluster->adNu[k] - (double) l); adLDet[k] += gsl_sf_psi (dX); } adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD); } } /*Normalise pi*/ if(1){ double dNP = 0.0; for(k = 0; k < nK; k++){ dNP += adPi[k]; } for(k = 0; k < nK; k++){ adPi[k] /= dNP; } } /*free up memory*/ for(i = 0; i < nD; i++){ free(aadCovar[i]); free(aadInvWK[i]); } free(aadCovar); free(aadInvWK); return; memoryError: fprintf(stderr, "Failed allocating memory in performMStep\n"); fflush(stderr); exit(EXIT_FAILURE); } void calcCovarMatrices(t_Cluster *ptCluster, t_Data *ptData) { int i = 0, j = 0, k = 0, l = 0, m = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX; double *adPi = ptCluster->adPi, **aadCovar = NULL; double dN = (double) nN; aadCovar = (double **) malloc(nD*sizeof(double*)); if(!aadCovar) goto memoryError; for(i = 0; i < nD; i++){ aadCovar[i] = (double *) malloc(nD*sizeof(double)); if(!aadCovar[i]) goto memoryError; } for(k = 0; k < nK; k++){ /*loop components*/ double* adMu = ptCluster->aadMu[k]; gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k]; /*recompute mixture weights and means*/ for(j = 0; j < nD; j++){ adMu[j] = 0.0; for(l = 0; l < nD; l++){ aadCovar[j][l] = 0.0; } /*prevents singularities*/ aadCovar[j][j] = MIN_COVAR; } /* compute weight associated with component k*/ adPi[k] = 0.0; for(i = 0; i < nN; i++){ adPi[k] += aadZ[i][k]; for(j = 0; j < nD; j++){ adMu[j] += aadZ[i][k]*aadX[i][j]; } } /*normalise means*/ for(j = 0; j < nD; j++){ adMu[j] /= adPi[k]; } /*calculate covariance matrices*/ for(i = 0; i < nN; i++){ double adDiff[nD]; for(j = 0; j < nD; j++){ adDiff[j] = aadX[i][j] - adMu[j]; } for(l = 0; l < nD; l++){ for(m = 0; m <=l ; m++){ aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m]; } } } for(l = 0; l < nD; l++){ for(m = l + 1; m < nD; m++){ aadCovar[l][m] = aadCovar[m][l]; } } for(l = 0; l < nD; l++){ for(m = 0; m < nD; m++){ aadCovar[l][m] /= adPi[k]; gsl_matrix_set(ptSigmaMatrix, l, m, aadCovar[l][m]); } } adPi[k] /= dN; /*normalise weights*/ } /*free up memory*/ for(i = 0; i < nD; i++){ free(aadCovar[i]); } //gsl_matrix_free(ptSigmaMatrix); free(aadCovar); return; memoryError: fprintf(stderr, "Failed allocating memory in performMStep\n"); fflush(stderr); exit(EXIT_FAILURE); } void calcCovarMatricesVB(t_Cluster *ptCluster, t_Data *ptData){ int i = 0, j = 0, k = 0, l = 0, m = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX; double *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi; double **aadCovar = NULL, **aadInvWK = NULL; t_VBParams *ptVBParams = ptCluster->ptVBParams; aadCovar = (double **) malloc(nD*sizeof(double*)); if(!aadCovar) goto memoryError; for(i = 0; i < nD; i++){ aadCovar[i] = (double *) malloc(nD*sizeof(double)); if(!aadCovar[i]) goto memoryError; } aadInvWK = (double **) malloc(nD*sizeof(double*)); if(!aadInvWK) goto memoryError; for(i = 0; i < nD; i++){ aadInvWK[i] = (double *) malloc(nD*sizeof(double)); if(!aadInvWK[i]) goto memoryError; } /*perform M step*/ for(k = 0; k < nK; k++){ /*loop components*/ double* adMu = ptCluster->aadMu[k]; gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k]; double dF = 0.0; /*recompute mixture weights and means*/ for(j = 0; j < nD; j++){ adMu[j] = 0.0; for(l = 0; l < nD; l++){ aadCovar[j][l] = 0.0; } } /* compute weight associated with component k*/ adPi[k] = 0.0; for(i = 0; i < nN; i++){ adPi[k] += aadZ[i][k]; for(j = 0; j < nD; j++){ adMu[j] += aadZ[i][k]*aadX[i][j]; } } /*normalise means*/ if(adPi[k] > MIN_PI){ /*Equation 10.60*/ ptCluster->adBeta[k] = ptVBParams->dBeta0 + adPi[k]; for(j = 0; j < nD; j++){ /*Equation 10.61*/ ptCluster->aadM[k][j] = adMu[j]/ptCluster->adBeta[k]; adMu[j] /= adPi[k]; } ptCluster->adNu[k] = ptVBParams->dNu0 + adPi[k]; /*calculate covariance matrices*/ for(i = 0; i < nN; i++){ double adDiff[nD]; for(j = 0; j < nD; j++){ adDiff[j] = aadX[i][j] - adMu[j]; } for(l = 0; l < nD; l++){ for(m = 0; m <=l ; m++){ aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m]; } } } for(l = 0; l < nD; l++){ for(m = l + 1; m < nD; m++){ aadCovar[l][m] = aadCovar[m][l]; } } /*save sample covariances for later use*/ for(l = 0; l < nD; l++){ for(m = 0; m < nD; m++){ double dC = aadCovar[l][m] / adPi[k]; gsl_matrix_set(ptCluster->aptCovar[k],l,m,dC); } } /*Now perform equation 10.62*/ dF = (ptVBParams->dBeta0*adPi[k])/ptCluster->adBeta[k]; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m]; } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ //aadCovar[l][m] /= adPi[k]; gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } } else{ /*Equation 10.60*/ adPi[k] = 0.0; ptCluster->adBeta[k] = ptVBParams->dBeta0; for(j = 0; j < nD; j++){ /*Equation 10.61*/ ptCluster->aadM[k][j] = 0.0; adMu[j] = 0.0; } ptCluster->adNu[k] = ptVBParams->dNu0; for(l = 0; l < nD; l++){ for(m = 0; m <= l; m++){ aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m); } } for(l = 0; l < nD; l++){ for(m = 0; m <= l ; m++){ //aadCovar[l][m] /= adPi[k]; gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]); gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]); } } /*Implement Equation 10.65*/ adLDet[k] = ((double) nD)*log(2.0); for(l = 0; l < nD; l++){ double dX = 0.5*(ptCluster->adNu[k] - (double) l); adLDet[k] += gsl_sf_psi (dX); } adLDet[k] -= decomposeMatrix(ptSigmaMatrix,nD); } } /*Normalise pi*/ if(1){ double dNP = 0.0; for(k = 0; k < nK; k++){ dNP += adPi[k]; } for(k = 0; k < nK; k++){ adPi[k] /= dNP; } } /*free up memory*/ for(i = 0; i < nD; i++){ free(aadCovar[i]); free(aadInvWK[i]); } //gsl_matrix_free(ptSigmaMatrix); free(aadCovar); free(aadInvWK); return; memoryError: fprintf(stderr, "Failed allocating memory in performMStep\n"); fflush(stderr); exit(EXIT_FAILURE); } void updateMeans(t_Cluster *ptCluster, t_Data *ptData){ int i = 0, j = 0, k = 0; int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; int *anMaxZ = ptCluster->anMaxZ; int *anW = ptCluster->anW; double **aadX = ptData->aadX, **aadMu = ptCluster->aadMu; for(k = 0; k < nK; k++){ for(j = 0; j < nD; j++){ aadMu[k][j] = 0.0; } } for(i = 0; i < nN; i++){ int nZ = anMaxZ[i]; for(j = 0; j < nD; j++){ aadMu[nZ][j] += aadX[i][j]; } } for(k = 0; k < nK; k++){ /*loop components*/ /*normalise means*/ if(anW[k] > 0){ for(j = 0; j < nD; j++){ aadMu[k][j] /= (double) anW[k]; } } else{ for(j = 0; j < nD; j++){ aadMu[k][j] = 0.0; } } } return; } void initRandom(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData) { /*very simple initialisation assign each data point to random cluster*/ int i = 0, k = 0; for(i = 0; i < ptData->nN; i++){ int nIK = -1; for(k = 0; k < ptCluster->nK; k++){ ptCluster->aadZ[i][k] = 0.0; } nIK = gsl_rng_uniform_int (ptGSLRNG, ptCluster->nK); ptCluster->aadZ[i][nIK] = 1.0; } performMStep(ptCluster, ptData); return; } double calcDist(double* adX, double *adMu, int nD) { double dDist = 0.0; int i = 0; for(i = 0; i < nD; i++){ double dV = adX[i] - adMu[i]; dDist += dV*dV; } return sqrt(dDist); } void initKMeans(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData) { /*very simple initialisation assign each data point to random cluster*/ int i = 0, k = 0, nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD; double **aadMu = ptCluster->aadMu, **aadX = ptData->aadX; int *anMaxZ = ptCluster->anMaxZ, *anW = ptCluster->anW, nChange = nN; int nIter = 0, nMaxIter = ptCluster->nMaxIter; for(i = 0; i < nN; i++){ int nIK = gsl_rng_uniform_int (ptGSLRNG, nK); ptCluster->anMaxZ[i] = nIK; anW[nIK]++; } updateMeans(ptCluster, ptData); while(nChange > 0 && nIter < nMaxIter){ nChange = 0; /*reassign vectors*/ for(i = 0; i < nN; i++){ double dMinDist = DBL_MAX; int nMinK = NOT_SET; for(k = 0; k < nK; k++){ double dDist = calcDist(aadX[i],aadMu[k],nD); if(dDist < dMinDist){ nMinK = k; dMinDist = dDist; } } if(nMinK != anMaxZ[i]){ int nCurr = anMaxZ[i]; nChange++; anW[nCurr]--; anW[nMinK]++; anMaxZ[i] = nMinK; /*check for empty clusters*/ if(anW[nCurr] == 0){ int nRandI = gsl_rng_uniform_int (ptGSLRNG, nN); int nKI = 0; /*select at random from non empty clusters*/ while(anW[anMaxZ[nRandI]] == 1){ nRandI = gsl_rng_uniform_int (ptGSLRNG, nN); } nKI = anMaxZ[nRandI]; anW[nKI]--; anW[nCurr] = 1; anMaxZ[nRandI] = nCurr; } } } //printf("%d %d\n",nIter,nChange); nIter++; updateMeans(ptCluster, ptData); } for(i = 0; i < nN; i++){ for(k = 0; k < nK; k++){ ptCluster->aadZ[i][k] = 0.0; } ptCluster->aadZ[i][anMaxZ[i]] = 1.0; } performMStep(ptCluster, ptData); return; } /*note assuming you are using inverse W matrix*/ double dLogWishartB(gsl_matrix *ptInvW, int nD, double dNu, int bInv) { int i = 0; double dRet = 0.0, dT = 0.0; double dLogDet = 0.0, dD = (double) nD; gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD); gsl_matrix_memcpy(ptTemp, ptInvW); dLogDet = decomposeMatrix(ptTemp, nD); if(bInv == TRUE){ dRet = 0.5*dNu*dLogDet; } else{ dRet = -0.5*dNu*dLogDet; } dT = 0.5*dNu*dD*log(2.0); dT += 0.25*dD*(dD - 1.0)*log(M_PI); for(i = 0; i < nD; i++){ dT += gsl_sf_lngamma(0.5*(dNu - (double) i)); } gsl_matrix_free(ptTemp); return dRet - dT; } double dWishartExpectLogDet(gsl_matrix *ptW, double dNu, int nD) { int i = 0; double dRet = 0.0, dLogDet = 0.0, dD = (double) nD; gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD); gsl_matrix_memcpy(ptTemp, ptW); dLogDet = decomposeMatrix(ptW, nD); dRet = dD*log(2.0) + dLogDet; for(i = 0; i < nD; i++){ dRet += gsl_sf_psi(0.5*(dNu - (double) i)); } gsl_matrix_free(ptTemp); return dRet; } double dWishartEntropy(gsl_matrix *ptW, double dNu, int nD) { double dRet = -dLogWishartB(ptW, nD, dNu, FALSE); double dExpLogDet = dWishartExpectLogDet(ptW, dNu, nD); double dD = (double) nD; dRet -= 0.5 * (dNu - dD - 1.0)*dExpLogDet; dRet += 0.5*dNu*dD; return dRet; } double calcVBL(t_Cluster* ptCluster) { int i = 0, k = 0, l = 0, nN = ptCluster->nN; int nK = ptCluster->nK, nD = ptCluster->nD; double dBishop1 = 0.0, dBishop2 = 0.0, dBishop3 = 0.0, dBishop4 = 0.0, dBishop5 = 0.0; /*Bishop equations 10.71...*/ gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD); gsl_vector *ptDiff = gsl_vector_alloc(nD); gsl_vector *ptR = gsl_vector_alloc(nD); double dD = (double) nD; double** aadMu = ptCluster->aadMu, **aadM = ptCluster->aadM, **aadZ = ptCluster->aadZ; double* adBeta = ptCluster->adBeta, *adNu = ptCluster->adNu, *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi; double adNK[nK]; double d2Pi = 2.0*M_PI, dBeta0 = ptCluster->ptVBParams->dBeta0, dNu0 = ptCluster->ptVBParams->dNu0, dRet = 0.0; double dK = 0.0; for(k = 0; k < nK; k++){ adNK[k] = 0.0; } /*Equation 10.72*/ for(i = 0; i < nN; i++){ for(k = 0; k < nK; k++){ adNK[k] += aadZ[i][k]; if(adPi[k] > 0.0){ dBishop2 += aadZ[i][k]*log(adPi[k]); } } } for(k = 0; k < nK; k++){ if(adNK[k] > 0.0){ dK++; } } /*Equation 10.71*/ for(k = 0; k < nK; k++){ if(adNK[k] > 0.0){ double dT1 = 0.0, dT2 = 0.0, dF = 0.0; gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCluster->aptCovar[k],ptCluster->aptSigma[k],0.0,ptRes); for(l = 0; l < nD; l++){ dT1 += gsl_matrix_get(ptRes,l,l); } for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,aadMu[k][l] - aadM[k][l]); } gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptR); gsl_blas_ddot (ptDiff, ptR, &dT2); dF = adLDet[k] - adNu[k]*(dT1 + dT2) - dD*(log(d2Pi) + (1.0/adBeta[k])); dBishop1 += 0.5*adNK[k]*dF; } } /*Equation 10.74*/ for(k = 0; k < nK; k++){ if(adNK[k] > 0.0){ double dT1 = 0.0, dT2 = 0.0, dF = 0.0; gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCluster->ptVBParams->ptInvW0,ptCluster->aptSigma[k],0.0,ptRes); for(l = 0; l < nD; l++){ dT1 += gsl_matrix_get(ptRes,l,l); } for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,aadM[k][l]); } gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptR); gsl_blas_ddot (ptDiff, ptR, &dT2); dF = dD*log(dBeta0/d2Pi) + adLDet[k] - ((dD*dBeta0)/adBeta[k]) - dBeta0*adNu[k]*dT2 - adNu[k]*dT1; dBishop3 += 0.5*(dF + (dNu0 - dD - 1.0)*adLDet[k]); } } dBishop3 += dK*ptCluster->ptVBParams->dLogWishartB; /*Equation 10.75*/ for(i = 0; i < nN; i++){ for(k = 0; k < nK; k++){ if(aadZ[i][k] > 0.0){ dBishop4 += aadZ[i][k]*log(aadZ[i][k]); } } } /*Equation 10.77*/ for(k = 0; k < nK; k++){ if(adNK[k] > 0.0){ dBishop5 += 0.5*adLDet[k] + 0.5*dD*log(adBeta[k]/d2Pi) - 0.5*dD - dWishartExpectLogDet(ptCluster->aptSigma[k], adNu[k], nD); } } gsl_matrix_free(ptRes); gsl_vector_free(ptDiff); gsl_vector_free(ptR); dRet = dBishop1 + dBishop2 + dBishop3 - dBishop4 - dBishop5; return dRet; } void calcZ(t_Cluster* ptCluster, t_Data *ptData){ double **aadX = ptData->aadX, **aadZ = ptCluster->aadZ; int i = 0, k = 0, l = 0; int nK = ptCluster->nK, nD = ptCluster->nD, nN = ptData->nN; gsl_vector *ptDiff = gsl_vector_alloc(nD); gsl_vector *ptRes = gsl_vector_alloc(nD); double adDist[nK], dD = (double) nD; double** aadM = ptCluster->aadM, *adPi = ptCluster->adPi; for(i = 0; i < nN; i++){ double dMinDist = DBL_MAX; double dTotalZ = 0.0; double dNTotalZ = 0.0; for(k = 0; k < nK; k++){ if(adPi[k] > 0.){ /*set vector to data point*/ for(l = 0; l < nD; l++){ gsl_vector_set(ptDiff,l,aadX[i][l] - aadM[k][l]); } gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptRes); gsl_blas_ddot (ptDiff, ptRes, &adDist[k]); adDist[k] *= ptCluster->adNu[k]; adDist[k] -= ptCluster->adLDet[k]; adDist[k] += dD/ptCluster->adBeta[k]; if(adDist[k] < dMinDist){ dMinDist = adDist[k]; } } } for(k = 0; k < nK; k++){ if(adPi[k] > 0.){ aadZ[i][k] = adPi[k]*exp(-0.5*(adDist[k]-dMinDist)); dTotalZ += aadZ[i][k]; } else{ aadZ[i][k] = 0.0; } } for(k = 0; k < nK; k++){ double dF = aadZ[i][k] / dTotalZ; if(dF < MIN_Z){ aadZ[i][k] = 0.0; } dNTotalZ += aadZ[i][k]; } if(dNTotalZ > 0.){ for(k = 0; k < nK; k++){ aadZ[i][k] /= dNTotalZ; } } } gsl_vector_free(ptRes); gsl_vector_free(ptDiff); return; } void gmmTrainVB(t_Cluster *ptCluster, t_Data *ptData) { int i = 0, k = 0,nIter = 0; int nN = ptData->nN, nK = ptCluster->nK; /*change in log-likelihood*/ double dLastVBL = 0.0, dDelta = DBL_MAX; double **aadZ = ptCluster->aadZ; int nMaxIter = ptCluster->nMaxIter; double dEpsilon = ptCluster->dEpsilon; FILE *ofp = NULL; if(ptCluster->szCOutFile){ ofp = fopen(ptCluster->szCOutFile,"w"); if(!ofp){ fprintf(stderr, "Failed to open file %s in gmmTrainVB\n",ptCluster->szCOutFile); fflush(stderr); } } /*calculate data likelihood*/ calcZ(ptCluster,ptData); ptCluster->dVBL = calcVBL(ptCluster); while(nIter < nMaxIter && dDelta > dEpsilon){ /*update parameter estimates*/ performMStep(ptCluster, ptData); /*calculate responsibilities*/ calcZ(ptCluster,ptData); dLastVBL = ptCluster->dVBL; ptCluster->dVBL = calcVBL(ptCluster); dDelta = fabs(ptCluster->dVBL - dLastVBL); if(ofp){ fprintf(ofp,"%d,%f,%f,",nIter, ptCluster->dVBL, dDelta); for(k = 0; k < nK-1; k++){ fprintf(ofp,"%f,",ptCluster->adPi[k]); } fprintf(ofp,"%f\n",ptCluster->adPi[nK - 1]); fflush(ofp); } nIter++; } if(ofp){ fclose(ofp); } /*assign to best clusters*/ for(i = 0; i < nN; i++){ double dMaxZ = aadZ[i][0]; int nMaxK = 0; for(k = 1; k < nK; k++){ if(aadZ[i][k] > dMaxZ){ nMaxK = k; dMaxZ = aadZ[i][k]; } } ptCluster->anMaxZ[i] = nMaxK; } return; } void writeClusters(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData) { int nN = ptCluster->nN, i = 0; FILE* ofp = fopen(szOutFile,"w"); if(ofp){ for(i = 0; i < nN; i++){ fprintf(ofp,"%s,%d\n",ptData->aszSampleNames[i],ptCluster->anMaxZ[i]); } } else{ fprintf(stderr,"Failed to open %s for writing in writeClusters\n", szOutFile); fflush(stderr); } } void writeMeans(char *szOutFile, t_Cluster *ptCluster) { int nK = ptCluster->nK, nD = ptCluster->nD,i = 0, j = 0; FILE* ofp = fopen(szOutFile,"w"); if(ofp){ for(i = 0; i < nK; i++){ for(j = 0; j < nD - 1; j++){ fprintf(ofp,"%f,",ptCluster->aadMu[i][j]); } fprintf(ofp,"%f\n",ptCluster->aadMu[i][nD - 1]); } } else{ fprintf(stderr,"Failed to open %s for writing in writeMeanss\n", szOutFile); fflush(stderr); } } void writeTMeans(char *szOutFile, t_Cluster *ptCluster, t_Data *ptData) { int nK = ptCluster->nK, nD = ptCluster->nD, nT = ptData->nT, i = 0, j = 0; FILE* ofp = fopen(szOutFile,"w"); gsl_vector* ptVector = gsl_vector_alloc(nD); gsl_vector* ptTVector = gsl_vector_alloc(nT); if(ofp){ for(i = 0; i < nK; i++){ for(j = 0; j < nD; j++){ gsl_vector_set(ptVector,j,ptCluster->aadMu[i][j]); } gsl_blas_dgemv (CblasNoTrans, 1.0,ptData->ptTMatrix,ptVector,0.0, ptTVector); for(j = 0; j < nT - 1; j++){ fprintf(ofp,"%f,",gsl_vector_get(ptTVector,j)); } fprintf(ofp,"%f\n",gsl_vector_get(ptTVector,nD - 1)); } } else{ fprintf(stderr,"Failed to open %s for writing in writeMeanss\n", szOutFile); fflush(stderr); } gsl_vector_free(ptVector); gsl_vector_free(ptTVector); } void* fitEM(void *pvCluster) { t_Cluster *ptCluster = (t_Cluster *) pvCluster; gsl_rng *ptGSLRNG = NULL; const gsl_rng_type *ptGSLRNGType = NULL; /*initialise GSL RNG*/ ptGSLRNGType = gsl_rng_default; ptGSLRNG = gsl_rng_alloc(ptGSLRNGType); gsl_rng_set (ptGSLRNG, ptCluster->lSeed); initKMeans(ptGSLRNG, ptCluster, ptCluster->ptData); gmmTrainVB(ptCluster, ptCluster->ptData); gsl_rng_free(ptGSLRNG); return NULL; } void* runRThreads(void *pvpDCluster) { t_Cluster **pptDCluster = (t_Cluster **) pvpDCluster; t_Cluster *ptDCluster = (t_Cluster *) *pptDCluster; double dBestVBL = -DBL_MAX; t_Cluster** aptCluster = NULL; pthread_t atRestarts[N_RTHREADS]; /*run each restart on a separate thread*/ int iret[N_RTHREADS]; int r = 0, nBestR = -1; char *szCOutFile = NULL; aptCluster = (t_Cluster **) malloc(N_RTHREADS*sizeof(t_Cluster*)); if(!aptCluster) goto memoryError; for(r = 0; r < N_RTHREADS; r++){ if(ptDCluster->szCOutFile != NULL){ szCOutFile = (char *) malloc(sizeof(char)*MAX_LINE_LENGTH); sprintf(szCOutFile,"%sr%d.csv",ptDCluster->szCOutFile,r); } aptCluster[r] = (t_Cluster *) malloc(sizeof(t_Cluster)); allocateCluster(aptCluster[r],ptDCluster->nN,ptDCluster->nK,ptDCluster->nD,ptDCluster->ptData,ptDCluster->lSeed + r*R_PRIME,ptDCluster->nMaxIter,ptDCluster->dEpsilon,szCOutFile); aptCluster[r]->ptVBParams = ptDCluster->ptVBParams; aptCluster[r]->nThread = r; iret[r] = pthread_create(&atRestarts[r], NULL, fitEM, (void*) aptCluster[r]); } for(r = 0; r < N_RTHREADS; r++){ pthread_join(atRestarts[r], NULL); } /*free up memory associated with input cluster*/ free(ptDCluster); for(r = 0; r < N_RTHREADS; r++){ if(aptCluster[r]->dVBL > dBestVBL){ nBestR = r; dBestVBL = aptCluster[r]->dVBL; } } *pptDCluster = aptCluster[nBestR]; for(r = 0; r < N_RTHREADS; r++){ if(r != nBestR){ destroyCluster(aptCluster[r]); free(aptCluster[r]); } } free(aptCluster); return NULL; memoryError: fprintf(stderr, "Failed allocating memory in runRThreads\n"); fflush(stderr); exit(EXIT_FAILURE); } void calcSampleVar(t_Data *ptData,double *adVar, double *adMu) { double **aadX = ptData->aadX; int i = 0, n = 0; int nD = ptData->nD, nN = ptData->nN; /*sample means*/ double dN = (double) nN; for(i = 0; i < nD; i++){ adMu[i] = 0.0; adVar[i] = 0.0; } for(i = 0; i < nD; i++){ for(n = 0; n < nN; n++){ adMu[i] += aadX[n][i]; adVar[i] += aadX[n][i]*aadX[n][i]; } adMu[i] /= dN; adVar[i] = (adVar[i] - dN*adMu[i]*adMu[i])/(dN - 1.0); } return; } void compressCluster(t_Cluster *ptCluster) { int i = 0, k = 0, nNewK = 0, nN = ptCluster->nN; double **aadNewZ = NULL, dN = (double) nN; for(i = 0; i < ptCluster->nK; i++){ if(ptCluster->adPi[i] > 0.0){ nNewK++; } } aadNewZ = (double **) malloc(nN*sizeof(double *)); if(!aadNewZ) goto memoryError; for(i = 0; i < nN; i++){ aadNewZ[i] = (double *) malloc(nNewK*sizeof(double)); if(!aadNewZ[i]) goto memoryError; } for(i = 0; i < nN; i++){ int nC = 0; for(k = 0; k < ptCluster->nK; k++){ if(ptCluster->adPi[k] > 0.0){ aadNewZ[i][nC] = ptCluster->aadZ[i][k]; nC++; } } } for(i = 0; i < nN; i++){ free(ptCluster->aadZ[i]); } free(ptCluster->aadZ); /*reset Z and K*/ ptCluster->aadZ = aadNewZ; ptCluster->nK = nNewK; /*recalculate Pi*/ for(k = 0; k < ptCluster->nK; k++){ ptCluster->adPi[k] = 0.0; for(i = 0; i < nN; i++){ ptCluster->adPi[k] += ptCluster->aadZ[i][k]; } ptCluster->adPi[k] /= dN; } /*assign to best clusters*/ for(i = 0; i < nN; i++){ double dMaxZ = ptCluster->aadZ[i][0]; int nMaxK = 0; for(k = 1; k < ptCluster->nK; k++){ if(ptCluster->aadZ[i][k] > dMaxZ){ nMaxK = k; dMaxZ = ptCluster->aadZ[i][k]; } } ptCluster->anMaxZ[i] = nMaxK; } for(k = 0; k < ptCluster->nK; k++){ ptCluster->anW[k] = 0; } for(i = 0; i < nN; i++){ ptCluster->anW[ptCluster->anMaxZ[i]]++; } return; memoryError: fprintf(stderr, "Failed allocating memory in main\n"); fflush(stderr); exit(EXIT_FAILURE); }
{ "alphanum_fraction": 0.5686073294, "avg_line_length": 23.8579978237, "ext": "c", "hexsha": "3d51521ba3ee4c8e6e01483681320967c81c7826", "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": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "binnisb/CONCOCT", "max_forks_repo_path": "c-concoct/vbgmmmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "binnisb/CONCOCT", "max_issues_repo_path": "c-concoct/vbgmmmodule.c", "max_line_length": 182, "max_stars_count": null, "max_stars_repo_head_hexsha": "9246dc947b24256c4eab1f7b081c7a21aebdd95b", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "binnisb/CONCOCT", "max_stars_repo_path": "c-concoct/vbgmmmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15561, "size": 43851 }
// The top most header - contains switches and constants #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <gsl/gsl_rng.h> #define Pi acos(-1.0) #define real double // Cell shape and size //#define circle #define square #define Dia 40 // Cell radius or square side #define thickness 40 // clamped or hinged MTs int iprint, iter, t; char datadir[64] ;
{ "alphanum_fraction": 0.7070217918, "avg_line_length": 17.9565217391, "ext": "h", "hexsha": "5d37305615aa3d2e07d2c5a73f118b0483818294", "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": "27a5d17028e9bd1a526e5374f633741657e68f49", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "misragaurav/SingleMicrotubuleBuckling", "max_forks_repo_path": "switches.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "27a5d17028e9bd1a526e5374f633741657e68f49", "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": "misragaurav/SingleMicrotubuleBuckling", "max_issues_repo_path": "switches.h", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "27a5d17028e9bd1a526e5374f633741657e68f49", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "misragaurav/SingleMicrotubuleBuckling", "max_stars_repo_path": "switches.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 112, "size": 413 }
/* ode-initval/gear2.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. */ /* Gear 2 */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "odeiv_util.h" #include "gsl_odeiv.h" /* gear2 state object */ typedef struct { int primed; /* flag indicating that yim1 is ready */ double t_primed; /* system was primed for this value of t */ double last_h; /* last step size */ gsl_odeiv_step * primer; /* stepper to use for priming */ double * yim1; /* y_{i-1} */ double * k; /* work space */ double * y0; /* work space */ int stutter; } gear2_state_t; static void * gear2_alloc (size_t dim) { gear2_state_t *state = (gear2_state_t *) malloc (sizeof (gear2_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for gear2_state", GSL_ENOMEM); } state->yim1 = (double *) malloc (dim * sizeof (double)); if (state->yim1 == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for yim1", GSL_ENOMEM); } state->k = (double *) malloc (dim * sizeof (double)); if (state->k == 0) { free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for k", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->k); free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } state->primed = 0; state->primer = gsl_odeiv_step_alloc (gsl_odeiv_step_rk4imp, dim); state->last_h = 0.0; return state; } static int gear2_apply(void * vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { gear2_state_t *state = (gear2_state_t *) vstate; state->stutter = 0; if(state->primed == 0 || t == state->t_primed || h != state->last_h) { /* Execute a single-step method to prime the process. Note that * we do this if the step size changes, so frequent step size * changes will cause the method to stutter. * * Note that we reuse this method if the time has not changed, * which can occur when the adaptive driver is attempting to find * an appropriate step-size on its first iteration */ int status; DBL_MEMCPY(state->yim1, y, dim); status = gsl_odeiv_step_apply(state->primer, t, h, y, yerr, dydt_in, dydt_out, sys); /* Make note of step size and indicate readiness for a Gear step. */ state->primed = 1; state->t_primed = t; state->last_h = h; state->stutter = 1; return status; } else { /* We have a previous y value in the buffer, and the step * sizes match, so we go ahead with the Gear step. */ double * const k = state->k; double * const y0 = state->y0; double * const yim1 = state->yim1; const int iter_steps = 3; int status = 0; int nu; size_t i; DBL_MEMCPY(y0, y, dim); /* iterative solution */ if(dydt_out != NULL) { DBL_MEMCPY(k, dydt_out, dim); } for(nu=0; nu<iter_steps; nu++) { int s = GSL_ODEIV_FN_EVAL(sys, t + h, y, k); GSL_STATUS_UPDATE(&status, s); for(i=0; i<dim; i++) { y[i] = ((4.0 * y0[i] - yim1[i]) + 2.0 * h * k[i]) / 3.0; } } /* Estimate error and update the state buffer. */ for(i=0; i<dim; i++) { yerr[i] = h * h * (y[i] - y0[i]); /* error is third order */ yim1[i] = y0[i]; } /* Make note of step size. */ state->last_h = h; return status; } } static int gear2_reset(void * vstate, size_t dim) { gear2_state_t *state = (gear2_state_t *) vstate; DBL_ZERO_MEMSET (state->yim1, dim); DBL_ZERO_MEMSET (state->k, dim); DBL_ZERO_MEMSET (state->y0, dim); state->primed = 0; state->last_h = 0.0; return GSL_SUCCESS; } static unsigned int gear2_order (void *vstate) { gear2_state_t *state = (gear2_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 3; } static void gear2_free(void *vstate) { gear2_state_t *state = (gear2_state_t *) vstate; free(state->yim1); free(state->k); free(state->y0); gsl_odeiv_step_free(state->primer); free(state); } static const gsl_odeiv_step_type gear2_type = { "gear2", /* name */ 1, /* can use dydt_in */ 0, /* gives exact dydt_out */ &gear2_alloc, &gear2_apply, &gear2_reset, &gear2_order, &gear2_free }; const gsl_odeiv_step_type *gsl_odeiv_step_gear2 = &gear2_type;
{ "alphanum_fraction": 0.6155247813, "avg_line_length": 25.2903225806, "ext": "c", "hexsha": "3c49d286cd19c66d13e0cef2b731aff3e263704a", "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/gear2.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/gear2.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/ode-initval/gear2.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": 1630, "size": 5488 }
// Authors: David Blei (blei@cs.princeton.edu) // Sean Gerrish (sgerrish@cs.princeton.edu) // // Copyright 2011 Sean Gerrish and David Blei // All Rights Reserved. // // See the README for this package for details about modifying or // distributing this software. /* * state space language model variational inference * */ #ifndef SSLM_H #define SSLM_H #include "gsl-wrappers.h" #include "params.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <assert.h> #include <math.h> #include "data.h" #define SSLM_MAX_ITER 2 // maximum number of optimization iters #define SSLM_FIT_THRESHOLD 1e-6 // convergence criterion for fitting sslm #define INIT_MULT 1000 // multiplier to variance for first obs // #define OBS_NORM_CUTOFF 10 // norm cutoff after which we use all 0 obs //#define OBS_NORM_CUTOFF 8 // norm cutoff after which we use all 0 obs #define OBS_NORM_CUTOFF 2 // norm cutoff after which we use all 0 obs /* * functions for variational inference * */ // allocate new state space language model variational posterior sslm_var* sslm_var_alloc(int W, int T); // allocate extra parameters for inference void sslm_inference_alloc(sslm_var* var); // free extra parameters for inference void sslm_inference_free(sslm_var* var); // initialize with zero observations void sslm_zero_init(sslm_var* var, double obs_variance, double chain_variance); // initialize with counts void sslm_counts_init(sslm_var* var, double obs_variance, double chain_variance, const gsl_vector* counts); // initialize from variational observations void sslm_obs_file_init(sslm_var* var, double obs_variance, double chain_variance, const char* filename); // compute E[\beta_{w,t}] for t = 1:T void compute_post_mean(int w, sslm_var* var, double chain_variance); // compute Var[\beta_{w,t}] for t = 1:T void compute_post_variance(int w, sslm_var* var, double chain_variance); // optimize \hat{beta} void optimize_var_obs(sslm_var* var); // compute dE[\beta_{w,t}]/d\obs_{w,s} for t = 1:T void compute_mean_deriv(int word, int time, sslm_var* var, gsl_vector* deriv); // compute d bound/d obs_{w, t} for t=1:T. void compute_obs_deriv(int word, gsl_vector* word_counts, gsl_vector* total_counts, sslm_var* var, gsl_matrix* mean_deriv_mtx, gsl_vector* deriv); // update observations void update_obs(gsl_matrix* word_counts, gsl_vector* totals, sslm_var* var); // log probability bound double compute_bound(gsl_matrix* word_counts, gsl_vector* totals, sslm_var* var); // fit variational distribution double fit_sslm(sslm_var* var, gsl_matrix* word_counts); // read and write variational distribution void write_sslm_var(sslm_var* var, char* out); sslm_var* read_sslm_var(char* in); void compute_expected_log_prob(sslm_var* var); // !!! old function (from doc mixture...) double expected_log_prob(int w, int t, sslm_var* var); // update zeta void update_zeta(sslm_var* var); #endif
{ "alphanum_fraction": 0.6932957393, "avg_line_length": 29.5555555556, "ext": "h", "hexsha": "0ee90569c0f02744e89bbf68daeeddbc4395594c", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_path": "scripts/lib/DTM/dtm/ss-lm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "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": "iwangjian/topic-extractor", "max_issues_repo_path": "scripts/lib/DTM/dtm/ss-lm.h", "max_line_length": 73, "max_stars_count": 11, "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_path": "scripts/lib/DTM/dtm/ss-lm.h", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "num_tokens": 768, "size": 3192 }
/** * * @file core_dlag2s.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated ds Tue Jan 7 11:44:47 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_double * * CORE_PLASMA_dlag2s converts a double matrix, A, to a * float matrix, B. * ******************************************************************************* * * @param[in] m * The number of rows of the matrices A and B. m >= 0. * * @param[in] n * The number of columns of the matrices A and B. n >= 0. * * @param[in] A * The double m-by-n matrix to convert. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,m). * * @param[out] B * The float m-by-n matrix to convert. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * * @param[out] info * - 0 on successful exit. * - 1 if an entry of the matrix A is greater than the SINGLE * PRECISION overflow threshold, in this case, the content * of B in exit is unspecified. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlag2s = PCORE_dlag2s #define CORE_dlag2s PCORE_dlag2s #endif void CORE_dlag2s(int m, int n, const double *A, int lda, float *B, int ldb, int *info) { *info = LAPACKE_dlag2s_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb); } /***************************************************************************//** * * @ingroup CORE_double * * CORE_PLASMA_slag2d converts a float matrix, A, to a * double matrix, B. * ******************************************************************************* * * @param[in] m * The number of rows of the matrices A and B. m >= 0. * * @param[in] n * The number of columns of the matrices A and B. n >= 0. * * @param[in] A * The float m-by-n matrix to convert. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,m). * * @param[out] B * The double m-by-n matrix to convert. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slag2d = PCORE_slag2d #define CORE_slag2d PCORE_slag2d #endif void CORE_slag2d(int m, int n, const float *A, int lda, double *B, int ldb) { LAPACKE_slag2d_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb); }
{ "alphanum_fraction": 0.4984249212, "avg_line_length": 28.2871287129, "ext": "c", "hexsha": "aa6f9e1091b0acaed1900f7acb11e7aed17f921c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_dlag2s.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_dlag2s.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_dlag2s.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 744, "size": 2857 }
/* min/gsl_min.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 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_MIN_H__ #define __GSL_MIN_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_math.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 { const char *name; size_t size; int (*set) (void *state, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper); int (*iterate) (void *state, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper); } gsl_min_fminimizer_type; typedef struct { const gsl_min_fminimizer_type * type; gsl_function * function ; double x_minimum ; double x_lower ; double x_upper ; double f_minimum, f_lower, f_upper; void *state; } gsl_min_fminimizer; GSL_FUN gsl_min_fminimizer * gsl_min_fminimizer_alloc (const gsl_min_fminimizer_type * T) ; GSL_FUN void gsl_min_fminimizer_free (gsl_min_fminimizer * s); GSL_FUN int gsl_min_fminimizer_set (gsl_min_fminimizer * s, gsl_function * f, double x_minimum, double x_lower, double x_upper); GSL_FUN int gsl_min_fminimizer_set_with_values (gsl_min_fminimizer * s, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper); GSL_FUN int gsl_min_fminimizer_iterate (gsl_min_fminimizer * s); GSL_FUN const char * gsl_min_fminimizer_name (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_x_minimum (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_x_lower (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_x_upper (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_f_minimum (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_f_lower (const gsl_min_fminimizer * s); GSL_FUN double gsl_min_fminimizer_f_upper (const gsl_min_fminimizer * s); /* Deprecated, use x_minimum instead */ GSL_FUN double gsl_min_fminimizer_minimum (const gsl_min_fminimizer * s); GSL_FUN int gsl_min_test_interval (double x_lower, double x_upper, double epsabs, double epsrel); GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_goldensection; GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_brent; GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_quad_golden; typedef int (*gsl_min_bracketing_function)(gsl_function *f, double *x_minimum,double * f_minimum, double *x_lower, double * f_lower, double *x_upper, double * f_upper, size_t eval_max); GSL_FUN int gsl_min_find_bracket(gsl_function *f,double *x_minimum,double * f_minimum, double *x_lower, double * f_lower, double *x_upper, double * f_upper, size_t eval_max); __END_DECLS #endif /* __GSL_MIN_H__ */
{ "alphanum_fraction": 0.672723244, "avg_line_length": 36.9918032787, "ext": "h", "hexsha": "73dce773028d52d91d8673e377e3636562736185", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_min.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_min.h", "max_line_length": 164, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_min.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 1097, "size": 4513 }
#pragma once /* * (C) Copyright 2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_internals_engines_hh * * @{ * \file HH-util.h * \brief Utility functions for HDF5. */ #include <string> #include <utility> #include <vector> #include <hdf5.h> #include <gsl/gsl-lite.hpp> #include "./Handles.h" #include "ioda/defs.h" #include "ioda/Exception.h" #include "ioda/Types/Marshalling.h" namespace ioda { namespace detail { namespace Engines { namespace HH { class HH_Attribute; class HH_Variable; //#if H5_VERSION_GE(1, 12, 0) //typedef H5R_ref_t ref_t; //#else typedef hobj_ref_t ref_t; //#endif // brief Conveys information that a variable (or scale) is attached along a specified axis. //typedef std::pair<ref_t, unsigned> ref_axis_t; /// @brief Duplicate the HDF5 dataset list structure for REFERENCE_LISTs. struct ds_list_t { hobj_ref_t ref; /* object reference */ unsigned int dim_idx; /* dimension index of the dataset */ }; /// Data to pass to/from iterator classes. struct IODA_HIDDEN Iterator_find_attr_data_t { std::string search_for; hsize_t idx = 0; bool success = false; }; /// Callback function for H5Aiterate / H5Aiterate2 / H5Aiterate1. #if H5_VERSION_GE(1, 8, 0) IODA_HIDDEN herr_t iterate_find_attr(hid_t loc_id, const char* name, const H5A_info_t* info, void* op_data); #else IODA_HIDDEN herr_t iterate_find_attr(hid_t loc_id, const char* name, void* op_data); #endif /*! @brief Determine attribute creation order for a dataset. * @param obj is the dataset being queried * @param objType is the type of object (Dataset or Group). * @return H5_INDEX_CRT_ORDER if creation order is tracked. * @return H5_INDEX_NAME if creation order is not tracked. * @details Check if the variable has attribute creation order stored and/or indexed. * This is not the default, but it can speed up object list accesses considerably. */ IODA_HIDDEN H5_index_t getAttrCreationOrder(hid_t obj, H5O_type_t objType); /// @brief Linear search to find an attribute. /// @param baseObject is the object that could contain the attribute. /// @param attname is the name of the attribute. /// @param iteration_type is the type of iteration for the search. See getAttrCreationOrder. /// @return A pair of (success_flag, index). IODA_HIDDEN std::pair<bool, hsize_t> iterativeAttributeSearch(hid_t baseObject, const char* attname, H5_index_t iteration_type); /// @brief Linear search to find and open an attribute, if it exists. /// @param baseObject is the object that could contain the attribute. /// @param objType is the type of object (Dataset or Group). /// @param attname is the name of the attribute. /// @return An open handle to the attribute, if it exists. /// @return An invalid handle if the attribute does not exist or upon general failure. /// @details This function is useful because it is faster than the regular attribute /// open by name routine, which does not take advantage of attribute creation order /// indexing. Performance is particularly good when there are few attributes attached /// to the base object. IODA_HIDDEN HH_Attribute iterativeAttributeSearchAndOpen(hid_t baseObject, H5O_type_t objType, const char* attname); /*! @brief Attribute DIMENSION_LIST update function * * @details This function exists to update DIMENSION_LISTs without updating the * mirrored REFERENCE_LIST entry in the variable's scales. This is done for * performance reasons, as attaching dimension scales for hundreds of * variables sequentially is very slow. * * NOTE: This code does not use the regular atts.open(...) call * for performance reasons when we have to repeat this call for hundreds or * thousands of variables. We instead do a creation-order-preferred search. * * @param var is the variable of interest. * @param new_dim_list is the mapping of dimensions that should be added to the variable. */ IODA_HIDDEN void attr_update_dimension_list(HH_Variable* var, const std::vector<std::vector<ref_t>>& new_dim_list); /*! @brief Attribute REFERENCE_LIST update function * * @details This function exists to update REFERENCE_LISTs without updating the * mirrored DIMENSION_LIST entry. This is done for * performance reasons, as attaching dimension scales for hundreds of * variables sequentially is very slow. * * NOTE: This code does not use the regular atts.open(...) call * for performance reasons when we have to repeat this call for hundreds or * thousands of variables. We instead do a creation-order-preferred search. * * @param scale is the scale of interest. * @param ref_var_axis_list is the mapping of variables-dimension numbers that * should be added to the scale's REFERENCE_LIST attribute. */ IODA_HIDDEN void attr_update_reference_list(HH_Variable* scale, const std::vector<ds_list_t>& ref_var_axis); /// @brief A "view" of hvl_t objects. Adds C++ conveniences to an otherwise troublesome class. /// @tparam Inner is the datatype that we are really manipulating. template <class Inner> struct IODA_HIDDEN View_hvl_t { hvl_t &obj; View_hvl_t(hvl_t& obj) : obj{obj} {} size_t size() const { return obj.len; } void resize(size_t newlen) { if (newlen) { obj.p = (obj.p) ? H5resize_memory(obj.p, newlen * sizeof(Inner)) : H5allocate_memory(newlen * sizeof(Inner), false); if (!obj.p) throw Exception("Failed to allocate memory", ioda_Here()); } else { if (obj.p) if (H5free_memory(obj.p) < 0) throw Exception("Failed to free memory", ioda_Here()); obj.p = nullptr; } obj.len = newlen; } void clear() { resize(0); } Inner* at(size_t i) { if (i >= obj.len) throw Exception("Out-of-bounds access", ioda_Here()) .add("i", i).add("obj.len", obj.len); return operator[](i); } Inner* operator[](size_t i) { return &(static_cast<Inner*>(obj.p)[i]); } }; /*! Internal structure to encapsulate resources and prevent leaks. * * When reading dimension scales, calls to H5Aread return variable-length arrays * that must be reclaimed. We use a custom object to encapsulate this. */ struct IODA_HIDDEN Vlen_data { std::unique_ptr<hvl_t[]> buf; // NOLINT: C array and visibility warnings. HH_hid_t typ, space; // NOLINT: C visibility warnings. size_t sz; Vlen_data(size_t sz, HH_hid_t typ, HH_hid_t space) : buf(new hvl_t[sz]), typ{typ}, space{space}, sz{sz} { if (!buf) throw Exception("Failed to allocate buf", ioda_Here()); for (size_t i = 0; i < sz; i++) { buf[i].len = 0; buf[i].p = nullptr; } } ~Vlen_data() { if (buf) { /* for (size_t i = 0; i < sz; i++) { if (buf[i].p) delete[] buf[i].p; buf[i].len = 0; buf[i].p = nullptr; } */ H5Dvlen_reclaim(typ.get(), space.get(), H5P_DEFAULT, reinterpret_cast<void*>(buf.get())); } } Vlen_data(const Vlen_data&) = delete; Vlen_data(Vlen_data&&) = delete; Vlen_data operator=(const Vlen_data&) = delete; Vlen_data operator=(Vlen_data&&) = delete; hvl_t& operator[](size_t idx) { return (buf).get()[idx]; } }; /// @brief Gets a variable / group / link name from an id. Useful for debugging. /// @param obj_id is the object. /// @return One of the possible object names. /// @throws ioda::Exception if obj_id is invalid. IODA_HIDDEN std::string getNameFromIdentifier(hid_t obj_id); /// @brief Convert from variable-length data to fixed-length data. /// @param in_buf is the input buffer. Buffer has a sequence of pointers, serialized as chars. /// @param unitLength is the length of each fixed-length element. /// @param lengthsAreExact signifies that padding is not needed between elements. Each /// variable-length string is already of length unitLength. If false, then strlen /// is calculated for each element (which finds the first null byte). /// @returns the output buffer. IODA_HIDDEN std::vector<char> convertVariableLengthToFixedLength( gsl::span<const char> in_buf, size_t unitLength, bool lengthsAreExact); /// @brief Convert from fixed-length data to variable-length data. /// @param in_buf is the input buffer. Buffer is a sequence of fixed-length elements (*not* pointers). /// @param unitLength is the length of each fixed-length element. /// @returns the converted buffer. IODA_HIDDEN Marshalled_Data<char*, char*, true> convertFixedLengthToVariableLength( gsl::span<const char> in_buf, size_t unitLength); } // namespace HH } // namespace Engines } // namespace detail } // namespace ioda
{ "alphanum_fraction": 0.6971807256, "avg_line_length": 38.8777292576, "ext": "h", "hexsha": "7afe00133aa3b688dbf20a2e0cf03bb7e0054bb8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "NOAA-EMC/ioda", "max_forks_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "NOAA-EMC/ioda", "max_issues_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_line_length": 102, "max_stars_count": null, "max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "NOAA-EMC/ioda", "max_stars_repo_path": "src/engines/ioda/src/ioda/Engines/HH/HH/HH-util.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2189, "size": 8903 }
#ifndef VKST_WSI_INPUT_H #define VKST_WSI_INPUT_H #include <gsl.h> #include <wsi/types.h> #include <bitset> namespace wsi { enum class keys { eUnknown = 0, eSpace = 32, eApostrophe = 39, eComma = 44, eMinus = 45, ePeriod = 46, eSlash = 47, e0 = 48, e1 = 49, e2 = 50, e3 = 51, e4 = 52, e5 = 53, e6 = 54, e7 = 55, e8 = 56, e9 = 57, eSemicolon = 59, eEqual = 61, eA = 65, eB = 66, eC = 67, eD = 68, eE = 69, eF = 70, eG = 71, eH = 72, eI = 73, eJ = 74, eK = 75, eL = 76, eM = 77, eN = 78, eO = 79, eP = 80, eQ = 81, eR = 82, eS = 83, eT = 84, eU = 85, eV = 86, eW = 87, eX = 88, eY = 89, eZ = 90, eLeftBracket = 91, eBackslash = 92, eRightBracket = 93, eGraveAccent = 96, eEscape = 156, eEnter = 157, eTab = 158, eBackspace = 159, eInsert = 160, eDelete = 161, eRight = 162, eLeft = 163, eDown = 164, eUp = 165, ePageUp = 166, ePageDown = 167, eHome = 168, eEnd = 169, eCapsLock = 180, eScrollLock = 181, eNumLock = 182, ePrintScreen = 183, ePause = 184, eF1 = 190, eF2 = 191, eF3 = 192, eF4 = 193, eF5 = 194, eF6 = 195, eF7 = 196, eF8 = 197, eF9 = 198, eF10 = 199, eF11 = 200, eF12 = 201, eF13 = 202, eF14 = 203, eF15 = 204, eF16 = 205, eF17 = 206, eF18 = 207, eF19 = 208, eF20 = 209, eF21 = 210, eF22 = 211, eF23 = 212, eF24 = 213, eF25 = 214, eKeypad0 = 220, eKeypad1 = 221, eKeypad2 = 222, eKeypad3 = 223, eKeypad4 = 224, eKeypad5 = 225, eKeypad6 = 226, eKeypad7 = 227, eKeypad8 = 228, eKeypad9 = 229, eKeypadDecimal = 230, eKeypadDivide = 231, eKeypadMultiply = 232, eKeypadSubtract = 233, eKeypadAdd = 234, eKeypadEnter = 235, eKeypadEqual = 236, eLeftShift = 240, eLeftControl = 241, eLeftAlt = 242, eLeftSuper = 243, eRightShift = 244, eRightControl = 245, eRightAlt = 246, eRightSuper = 247, eMenu = 248, }; // enum class keys class keyset final { std::bitset<256> _keys; public: using reference = decltype(_keys)::reference; bool all() const { return _keys.all(); } bool any() const { return _keys.any(); } bool none() const { return _keys.none(); } constexpr bool operator[](keys key) const { return _keys[static_cast<std::size_t>(key)]; } reference operator[](keys key) { return _keys[static_cast<std::size_t>(key)]; } keyset& set(keys key, bool value = true) noexcept { _keys[static_cast<std::size_t>(key)] = value; return *this; } keyset& reset(keys key) noexcept { _keys[static_cast<std::size_t>(key)] = false; return *this; } }; // class keyset enum class buttons { e1 = 1, e2, e3, e4, e5, e6, e7, e8, e9, e10, }; // enum class buttons class buttonset final { std::bitset<32> _buttons; public: using reference = decltype(_buttons)::reference; bool all() const { return _buttons.all(); } bool any() const { return _buttons.any(); } bool none() const { return _buttons.none(); } constexpr bool operator[](buttons button) const { return _buttons[static_cast<std::size_t>(button)]; } reference operator[](buttons button) { return _buttons[static_cast<std::size_t>(button)]; } buttonset& set(buttons button, bool value = true) noexcept { _buttons[static_cast<std::size_t>(button)] = value; return *this; } buttonset& reset(buttons button) noexcept { _buttons[static_cast<std::size_t>(button)] = false; return *this; } }; // class buttonset class window; class input final { public: input(gsl::not_null<window*> win) noexcept; bool key_pressed(keys key) const noexcept { return !_prev_keys[key] && _curr_keys[key]; } bool key_released(keys key) const noexcept { return _prev_keys[key] && !_curr_keys[key]; } bool key_down(keys key) const noexcept { return _prev_keys[key] && _curr_keys[key]; } bool button_pressed(buttons button) const noexcept { return !_prev_buttons[button] && _curr_buttons[button]; } bool button_released(buttons button) const noexcept { return _prev_buttons[button] && !_curr_buttons[button]; } bool button_down(buttons button) const noexcept { return _prev_buttons[button] && _curr_buttons[button]; } int prev_scroll() const noexcept { return _prev_scroll; } int curr_scroll() const noexcept { return _curr_scroll; } int scroll_delta() const noexcept { return _curr_scroll - _prev_scroll; } offset2d cursor_pos() const noexcept; offset2d prev_cursor_pos() const noexcept { return _prev_pos; } offset2d curr_cursor_pos() const noexcept { return _curr_pos; } offset2d cursor_delta() const noexcept { return _curr_pos - _prev_pos; } void tick() noexcept; private: window* _win; keyset _prev_keys, _curr_keys; buttonset _prev_buttons, _curr_buttons; int _prev_scroll, _curr_scroll; offset2d _prev_pos, _curr_pos; }; // class input } // namespace wsi #endif // VKST_WSI_INPUT_H
{ "alphanum_fraction": 0.6343913218, "avg_line_length": 18.8560606061, "ext": "h", "hexsha": "ae6e5b645eeb10d5f97216fe65989888855cd7c8", "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": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": [ "Zlib" ], "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_path": "src/wsi/input.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib" ], "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_path": "src/wsi/input.h", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": [ "Zlib" ], "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_path": "src/wsi/input.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1773, "size": 4978 }
#ifdef DFFTW #include <dfftw.h> #endif #ifdef SFFTW #include <sfftw.h> #endif #ifdef FFTW #include <fftw.h> #endif int main() { #ifdef DOUBLE /* Cause a compile-time error if fftw_real is not double */ int _array_ [1 - 2 * !((sizeof(fftw_real)) == sizeof(double))]; #else /* Cause a compile-time error if fftw_real is not float */ int _array_ [1 - 2 * !((sizeof(fftw_real)) == sizeof(float))]; #endif return 0; }
{ "alphanum_fraction": 0.6557377049, "avg_line_length": 17.08, "ext": "c", "hexsha": "e3367760fe24c771f7b5c505111e4d5b3c07dbf0", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "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": "farajilab/gifs_release", "max_issues_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_line_length": 65, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_path": "gromacs-4.6.5/cmake/TestFFTW2.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "num_tokens": 133, "size": 427 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #else #include "CustomSolver.h" #endif #include "ValueGrad.h" #include "BooleanNodes.h" #include "BooleanDAG.h" #include "NodeVisitor.h" #include "VarStore.h" #include <map> #include "FloatSupport.h" #include "SymbolicEvaluator.h" #include <iostream> using namespace std; // AutoDiff through only the numerical structure - ignores all boolean structure class IteAutoDiff: public NodeVisitor, public SymbolicEvaluator { FloatManager& floats; BooleanDAG& bdag; map<string, int> floatCtrls; // Maps float ctrl names to indices within grad vector int nctrls; // number of float ctrls gsl_vector* ctrls; // ctrl values vector<ValueGrad*> values; // Keeps track of values along with gradients for each node map<int, int> inputValues; // Maps node id to values set by the SAT solver map<int, int> iteCtrls; double error = 0.0; gsl_vector* errorGrad; int DEFAULT_INP = -1; public: IteAutoDiff(BooleanDAG& bdag_p, FloatManager& _floats, const map<string, int>& floatCtrls_p, const map<int, int>& iteCtrls_p); ~IteAutoDiff(void); virtual void visit( SRC_node& node ); virtual void visit( DST_node& node ); virtual void visit( CTRL_node& node ); virtual void visit( PLUS_node& node ); virtual void visit( TIMES_node& node ); virtual void visit( ARRACC_node& node ); virtual void visit( DIV_node& node ); virtual void visit( MOD_node& node ); virtual void visit( NEG_node& node ); virtual void visit( CONST_node& node ); virtual void visit( LT_node& node ); virtual void visit( EQ_node& node ); virtual void visit( AND_node& node ); virtual void visit( OR_node& node ); virtual void visit( NOT_node& node ); virtual void visit( ARRASS_node& node ); virtual void visit( UFUN_node& node ); virtual void visit( TUPLE_R_node& node ); virtual void visit( ASSERT_node& node ); virtual void run(const gsl_vector* ctrls_p, const map<int, int>& inputValues_p); virtual bool checkAll(const gsl_vector* ctrls_p, const map<int, int>& inputValues_p, bool onlyBool = false){ Assert(false, "NYI"); return true; } virtual bool check(bool_node* n, int expected); virtual double computeError(bool_node* n, int expected, gsl_vector* errorGrad); virtual double computeDist(bool_node*, gsl_vector* distgrad); virtual bool hasDist(bool_node* n); virtual double computeVal(bool_node*, gsl_vector* distgrad); virtual bool hasVal(bool_node* n); virtual bool hasSqrtDist(bool_node* n); virtual double computeSqrtError(bool_node* n, gsl_vector* errorGrad); virtual double computeSqrtDist(bool_node* n, gsl_vector* errorGrad); virtual double getVal(bool_node* n); virtual gsl_vector* getGrad(bool_node* n); //virtual set<int> getConflicts(int nid); void setvalue(bool_node& bn, ValueGrad* v) { values[bn.id] = v; } ValueGrad* v(bool_node& bn) { ValueGrad* val = values[bn.id]; if (val == NULL) { gsl_vector* g = gsl_vector_alloc(nctrls); val = new ValueGrad(0, g); setvalue(bn, val); } return val; } ValueGrad* v(bool_node* bn) { return v(*bn); } virtual void print() { for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << " "; ValueGrad* val = v(bdag[i]); if (val->set) { cout << val->print() << endl; } else { cout << "UNSET" << endl; } } } virtual void printFull() { for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << endl; ValueGrad* val = v(bdag[i]); if (val->set) { cout << val->printFull() << endl; } else { cout << "UNSET" << endl; } } } bool isFloat(bool_node& bn) { return (bn.getOtype() == OutType::FLOAT); } bool isFloat(bool_node* bn) { return (bn->getOtype() == OutType::FLOAT); } int getInputValue(bool_node& bn) { if (inputValues.find(bn.id) != inputValues.end()) { int val = inputValues[bn.id]; //Assert(val == 0 || val == 1, "NYI: Integer values"); return val; } else { return DEFAULT_INP; } } int getInputValue(bool_node* bn) { return getInputValue(*bn); } };
{ "alphanum_fraction": 0.6784486991, "avg_line_length": 28.4895104895, "ext": "h", "hexsha": "021b65863122d8cf3f446bf1fe13a258b8f79b46", "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/SymbolicEvaluators/IteAutoDiff.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/SymbolicEvaluators/IteAutoDiff.h", "max_line_length": 127, "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/SymbolicEvaluators/IteAutoDiff.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": 1139, "size": 4074 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_dspmv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *Ap, const double *X, const int incX, const double beta, double *Y, const int incY) { #define BASE double #include "source_spmv.h" #undef BASE }
{ "alphanum_fraction": 0.7118644068, "avg_line_length": 23.6, "ext": "c", "hexsha": "6a8246dabe58186e9e6794bc8c7620d47e2f61ef", "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/dspmv.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/dspmv.c", "max_line_length": 70, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/dspmv.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": 105, "size": 354 }
//===--- Sudoku/Solver_remove_option.h ---===// // // Helper functions, to remove options //===----------------------------------------------------------------------===// #pragma once #include "Sudoku/Board.h" #include "Sudoku/Location.h" #include "Sudoku/Location_Utilities.h" #include "Sudoku/Options.h" #include "Sudoku/Size.h" #include "Sudoku/Value.h" #include "Sudoku/exceptions.h" #include "Sudoku/traits.h" #include <gsl/gsl> #include <vector> #include <algorithm> // none_of #include <type_traits> // is_base_of #include "Solver.fwd.h" // Forward declaration - single_option #include <cassert> /* experiment flags */ //! DO #undef at end of file! // activate algorithms on removing option #define DUAL_ON_REMOVE false // NOLINT(cppcoreguidelines-macro-usage) #define MULTIPLE_ON_REMOVE false // NOLINT(cppcoreguidelines-macro-usage) namespace Sudoku { //===----------------------------------------------------------------------===// template<int N, typename Options = Options<elem_size<N>>> int remove_option(Board<Options, N>&, Location<N>, Value); template<int N, typename Options = Options<elem_size<N>>> int remove_option(Board<Options, N>&, Location<N>, Options mask); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int remove_option_section( Board<Options, N>&, SectionT, Location<N> ignore, Value); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int remove_option_section( Board<Options, N>&, SectionT, const std::vector<Location<N>>& ignore, Value); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int remove_option_section( Board<Options, N>&, SectionT, const std::vector<Location<N>>& ignore, const Options& values); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> int remove_option_outside_block( Board<Options, N>&, SectionT, Location<N> block_loc, Value); //===----------------------------------------------------------------------===// // remove option from element, make answer if last option template<int N, typename Options> int remove_option( Board<Options, N>& board, // NOLINT(runtime/references) const Location<N> loc, const Value value) { assert(is_valid<N>(value)); int changes{}; auto& item{board.at(loc)}; if (item.test(value)) { // repeated answer in section (faster here) if (!is_option(item, value)) throw error::invalid_Board(); ++changes; const auto count = item.remove_option(value).count(); assert(count > 0); // never trigger, removed last option #if MULTIPLE_ON_REMOVE == false if (count == 1) { changes += single_option(board, loc); } #else // if (count < 4) { changes += multi_option(board, loc, count); } #endif // multiple #if DUAL_ON_REMOVE == true if (count == 2) { changes += dual_option(board, loc); } #endif // dual } return changes; } // remove all options given by the mask template<int N, typename Options> int remove_option( Board<Options, N>& board, // NOLINT(runtime/references) const Location<N> loc, const Options mask) { assert(is_answer_fast(mask)); // don't remove answer-bit assert(!mask.is_empty()); // useless auto& item{board.at(loc)}; auto changes = gsl::narrow_cast<int, size_t>(item.count_all()); if (!changes) { // ignore empty elements return 0; } // remove options item -= mask; const auto count = gsl::narrow_cast<int, size_t>(item.count_all()); if (count == 0) { // removed last option throw error::invalid_Board(); } changes -= count; if (changes && count == 1) { changes += single_option(board, loc); } return changes; } // remove [value] in [ignore] from other elements in set template<int N, typename Options, typename SectionT> int remove_option_section( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const Location<N> ignore, const Value value) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<Options, typename SectionT::value_type>); static_assert(traits::is_input<typename SectionT::iterator>); assert(is_valid(ignore)); assert(is_valid<N>(value)); assert(is_same_section(section, ignore)); assert(is_answer(board.at(ignore), value)); // first set as answer! } int changes{0}; const auto end = section.cend(); for (auto itr = section.cbegin(); itr != end; ++itr) { if (itr.location() != ignore) { changes += remove_option(board, itr.location(), value); } } return changes; } // remove [value] from set if not part of [loc]s template<int N, typename Options, typename SectionT> inline int remove_option_section( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const std::vector<Location<N>>& ignore, const Value value) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<Options, typename SectionT::value_type>); static_assert(traits::is_input<typename SectionT::iterator>); assert(is_valid(ignore)); assert(is_valid<N>(value)); assert(is_same_section(section, ignore)); } int changes{0}; const auto begin = ignore.cbegin(); const auto end = ignore.cend(); // TODO maybe faster to run get_same_row/col/block first? // and than not to check is_option(), since it is already in remove_option for (auto itr = section.cbegin(); itr != section.cend(); ++itr) { // TODO is the is_option check really faster? if (std::none_of( begin, end, [L1 = itr.location()](Location<N> L2) { return L1 == L2; }) && is_option(*itr, value)) // <algorithm> { changes += remove_option(board, itr.location(), value); } } return changes; } // remove [value]s from [section] if not part of [loc]s // the ignore Location vector must be sorted template<int N, typename Options, typename SectionT> int remove_option_section( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const std::vector<Location<N>>& ignore, const Options& values) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<Options, typename SectionT::value_type>); static_assert(traits::is_input<typename SectionT::iterator>); assert(is_valid(ignore)); assert(!values.all()); assert(!values.is_empty()); assert(is_same_section(section, ignore)); } int changes{0}; const auto begin = ignore.cbegin(); const auto end = ignore.cend(); for (auto itr = section.cbegin(); itr != section.cend(); ++itr) { if (std::none_of( begin, end, [L1 = itr.location()](Location<N> L2) { return L1 == L2; }) && not(itr->is_answer())) // <algorithm> { changes += remove_option(board, itr.location(), values); } } return changes; } // remove [value] from elements not in same block as [block_loc] template<int N, typename Options, typename SectionT> int remove_option_outside_block( Board<Options, N>& board, // NOLINT(runtime/references) const SectionT section, const Location<N> block_loc, const Value value) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert( !Board_Section::traits::is_Block_v<SectionT>, "remove_option_outside_block is useless on a Block"); static_assert(std::is_same_v<Options, typename SectionT::value_type>); static_assert(traits::is_input<typename SectionT::iterator>); assert(is_valid(block_loc)); assert(is_valid<N>(value)); assert(intersect_block(section, block_loc)); } int changes{0}; const auto end = section.cend(); for (auto itr = section.cbegin(); itr != end; ++itr) { if (not is_same_block(itr.location(), block_loc)) { changes += remove_option(board, itr.location(), value); } } return changes; } /* Remove local macros */ #undef DUAL_ON_REMOVE #undef MULTIPLE_ON_REMOVE } // namespace Sudoku
{ "alphanum_fraction": 0.6827217125, "avg_line_length": 27.9288256228, "ext": "h", "hexsha": "c8322d73c2c041a2cc90675e5512b559267396dc", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z", "max_forks_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Farwaykorse/fwkSudoku", "max_forks_repo_path": "Sudoku/Strategic/Solvers_remove_option.h", "max_issues_count": 38, "max_issues_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Farwaykorse/fwkSudoku", "max_issues_repo_path": "Sudoku/Strategic/Solvers_remove_option.h", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Farwaykorse/fwkSudoku", "max_stars_repo_path": "Sudoku/Strategic/Solvers_remove_option.h", "max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z", "num_tokens": 1972, "size": 7848 }
#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 compute_MCMC_ln_likelihood_default(MCMC_info *MCMC, double ** M, double * P, double * ln_likelihood_DS, int * n_DoF_DS, double * ln_likelihood_all, int * n_DoF_all) { int i_DS; int i_M; int n_M; double * M_target; double * dM_target; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; (*ln_likelihood_all) = 0.; (*n_DoF_all) = 0; i_DS = 0; current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; n_M = current_DS->n_M; M_target = current_DS->M_target; dM_target = current_DS->dM_target; ln_likelihood_DS[i_DS] = 0.; n_DoF_DS[i_DS] = 0; for(i_M = 0; i_M < n_M; i_M++) { ln_likelihood_DS[i_DS] += pow((M_target[i_M] - M[i_DS][i_M]) / dM_target[i_M], 2.); n_DoF_DS[i_DS]++; } (*ln_likelihood_all) += ln_likelihood_DS[i_DS]; ln_likelihood_DS[i_DS] *= -0.5; (*n_DoF_all) += n_DoF_DS[i_DS]; n_DoF_DS[i_DS] -= MCMC->n_P; i_DS++; current_DS = next_DS; } (*n_DoF_all) -= MCMC->n_P; (*ln_likelihood_all) *= -0.5; }
{ "alphanum_fraction": 0.463079565, "avg_line_length": 34.2549019608, "ext": "c", "hexsha": "1fbf2ba479daeea286df9a44e2090493bbd5a833", "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/compute_MCMC_ln_likelihood_default.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/compute_MCMC_ln_likelihood_default.c", "max_line_length": 95, "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/compute_MCMC_ln_likelihood_default.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": 466, "size": 1747 }
/* randist/sphere.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void gsl_ran_dir_2d (const gsl_rng * r, double *x, double *y) { /* This method avoids trig, but it does take an average of 8/pi = * 2.55 calls to the RNG, instead of one for the direct * trigonometric method. */ double u, v, s; do { u = -1 + 2 * gsl_rng_uniform (r); v = -1 + 2 * gsl_rng_uniform (r); s = u * u + v * v; } while (s > 1.0 || s == 0.0); /* This is the Von Neumann trick. See Knuth, v2, 3rd ed, p140 * (exercise 23). Note, no sin, cos, or sqrt ! */ *x = (u * u - v * v) / s; *y = 2 * u * v / s; /* Here is the more straightforward approach, * s = sqrt (s); *x = u / s; *y = v / s; * It has fewer total operations, but one of them is a sqrt */ } void gsl_ran_dir_2d_trig_method (const gsl_rng * r, double *x, double *y) { /* This is the obvious solution... */ /* It ain't clever, but since sin/cos are often hardware accelerated, * it can be faster -- it is on my home Pentium -- than von Neumann's * solution, or slower -- as it is on my Sun Sparc 20 at work */ double t = 6.2831853071795864 * gsl_rng_uniform (r); /* 2*PI */ *x = cos (t); *y = sin (t); } void gsl_ran_dir_3d (const gsl_rng * r, double *x, double *y, double *z) { double s, a; /* This is a variant of the algorithm for computing a random point * on the unit sphere; the algorithm is suggested in Knuth, v2, * 3rd ed, p136; and attributed to Robert E Knop, CACM, 13 (1970), * 326. */ /* Begin with the polar method for getting x,y inside a unit circle */ do { *x = -1 + 2 * gsl_rng_uniform (r); *y = -1 + 2 * gsl_rng_uniform (r); s = (*x) * (*x) + (*y) * (*y); } while (s > 1.0); *z = -1 + 2 * s; /* z uniformly distributed from -1 to 1 */ a = 2 * sqrt (1 - s); /* factor to adjust x,y so that x^2+y^2 * is equal to 1-z^2 */ *x *= a; *y *= a; } void gsl_ran_dir_nd (const gsl_rng * r, size_t n, double *x) { double d; size_t i; /* See Knuth, v2, 3rd ed, p135-136. The method is attributed to * G. W. Brown, in Modern Mathematics for the Engineer (1956). * The idea is that gaussians G(x) have the property that * G(x)G(y)G(z)G(...) is radially symmetric, a function only * r = sqrt(x^2+y^2+...) */ d = 0; do { for (i = 0; i < n; ++i) { x[i] = gsl_ran_gaussian (r, 1.0); d += x[i] * x[i]; } } while (d == 0); d = sqrt (d); for (i = 0; i < n; ++i) { x[i] /= d; } }
{ "alphanum_fraction": 0.5864640092, "avg_line_length": 29.0583333333, "ext": "c", "hexsha": "a93615e62b5b9ba663cbcd0b66480fc89ee01422", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/sphere.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/sphere.c", "max_line_length": 84, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/sphere.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": 1154, "size": 3487 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_system_linux_udev_inl_h_ #define SQ_INCLUDE_GUARD_system_linux_udev_inl_h_ #include "core/errors.h" #include "core/typeutil.h" #include <fmt/format.h> #include <gsl/gsl> namespace sq::system::linux { template <typename T> UdevPtr<T>::UdevPtr(SQ_MU std::nullptr_t np) noexcept {} template <typename T> UdevPtr<T>::UdevPtr(const UdevPtr &other) noexcept : t_{other.t_.p_} { if (t_.p_ != nullptr) { t_.add_ref(); } } template <typename T> UdevPtr<T>::UdevPtr(UdevPtr &&other) noexcept : t_{other.t_.p_} { other.t_.p_ = nullptr; } // When a raw pointer is first obtained from libudev it already has a reference // count of 1 so we don't need to adjust it here. template <typename T> UdevPtr<T>::UdevPtr(RawPtr p) noexcept : t_{p} { Expects(p != nullptr); Ensures(t_.p_ != nullptr); } template <typename T> UdevPtr<T> &UdevPtr<T>::operator=(const UdevPtr &other) noexcept { // Note: must call add_ref before remove_ref to deal with the case where // *this == other if (other.t_.p_ != nullptr) { other.t_.add_ref(); } if (t_.p_ != nullptr) { t_.remove_ref(); } t_.p_ = other.t_.p_; return *this; } template <typename T> UdevPtr<T>::~UdevPtr() noexcept { if (t_.p_ != nullptr) { t_.remove_ref(); } } template <typename T> UdevPtr<T> &UdevPtr<T>::operator=(UdevPtr &&other) noexcept { std::swap(t_.p_, other.t_.p_); return *this; } template <typename T> void UdevPtr<T>::reset() noexcept { UdevPtr<T>{}.swap(*this); } template <typename T> void UdevPtr<T>::swap(UdevPtr &other) noexcept { std::swap(t_.p_, other.t_.p_); } template <typename T> T *UdevPtr<T>::get() const noexcept { if (t_.p_ == nullptr) { return nullptr; } return &t_; } template <typename T> T &UdevPtr<T>::operator*() const noexcept { Expects(t_.p_ != nullptr); return t_; } template <typename T> T *UdevPtr<T>::operator->() const noexcept { return get(); } template <typename T> UdevPtr<T>::operator bool() const noexcept { return t_.p_ != nullptr; } template <typename T> auto UdevPtr<T>::operator<=>(const UdevPtr<T> &other) const noexcept { return std::compare_three_way{}(t_.p_, other.t_.p_); } template <typename T> bool UdevPtr<T>::operator==(const UdevPtr<T> &other) const noexcept { return t_.p_ == other.t_.p_; } template <typename T> auto UdevPtr<T>::operator<=>(std::nullptr_t np) const noexcept { return std::compare_three_way{}(t_.p_, static_cast<decltype(t_.p_)>(np)); } template <typename T> bool UdevPtr<T>::operator==(std::nullptr_t np) const noexcept { return t_.p_ == static_cast<decltype(t_.p_)>(np); } template <typename U, typename... Args> UdevPtr<U> make_udev(Args &&...args) { auto *const p = U::create_new(SQ_FWD(args)...); if (p == nullptr) { throw UdevError{fmt::format("Failed to create new {}", base_type_name(p))}; } return UdevPtr<U>{p}; } } // namespace sq::system::linux #endif // SQ_INCLUDE_GUARD_system_linux_udev_inl_h_
{ "alphanum_fraction": 0.6457483527, "avg_line_length": 25.9105691057, "ext": "h", "hexsha": "7190706ef86f451d5f0de4052ee838596e642b57", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/system/include/system/linux/udev.inl.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/system/include/system/linux/udev.inl.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/system/include/system/linux/udev.inl.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 922, "size": 3187 }
/****************************************************************************** * * * ESTIMATE_THETAE.C * * * * ESTIMATE THETAE AT END OF TIMESTEP DUE TO RADIATION SOURCES * * * ******************************************************************************/ #include "decs.h" #if RADIATION #if ESTIMATE_THETAE #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #define NTHREADS (24) // ESTIMATE THETAE BEFORE PUSH TO AVOID ISSUES WITH MPI COMMUNICATION double Thetae_est[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]; double Thetae_old[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]; double Ucon[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM]; double Ucov[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM]; double Bcov[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM]; double Ne[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]; double Bmag[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]; int Nsph_zone[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; int Nsph_cntd[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; double * w[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; double * nu[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; double * dlam[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; double * theta[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS]; static int type = 0; // TODO: remove me when type loops are in place. static int interaction = 0; // TODO: remove me when type loops are in place. double get_Thetae_est(int i, int j, int k) { return Thetae_est[i][j][k]; } // Rootfinding parameters and function struct of_params { int i, j, k; double rho, Ne, Bmag, Thetaei, Ucon0, dt; double extra[EOS_NUM_EXTRA]; }; double dEdt(double Thetae, void *params) { struct of_params *p = (struct of_params *)params; int i = p->i; int j = p->j; int k = p->k; double rho = p->rho; double dt = p->dt; double * extra = p->extra; // TODO: encapsulate electrons in EOS framework. double uei, uef; #if ELECTRONS && EOS == EOS_TYPE_GAMMA uei = Ne[i][j][k] * Thetae_old[i][j][k] * ME * CL * CL / (game - 1.); uef = Ne[i][j][k] * Thetae * ME * CL * CL / (game - 1.); #else uei = EOS_u_N_Theta(rho, Ne[i][j][k], Thetae_old[i][j][k], extra); uef = EOS_u_N_Theta(rho, Ne[i][j][k], Thetae, extra); #endif struct of_microphysics micro; micro.Thetae = Thetae; micro.Ne = Ne[i][j][k]; micro.B = Bmag[i][j][k]; double J = get_J(&m); double vol = ggeom[i][j][CENT].g * dx[1] * dx[2] * dx[3] * dt; // Loop over superphotons double udotG_abs = 0.; double udotG_scatt = 0.; for (int n = 0; n < nthreads; n++) { for (int m = 0; m < Nsph_zone[i][j][k][n]; m++) { double udotk = HPL * nu[i][j][k][n][m] / (ME * CL * CL); // Absorption double alpha_inv_a = alpha_inv_abs(nu[i][j][k][n][m], type, &micro, theta[i][j][k][n][m]); double dtau_a = alpha_inv_a * L_unit * HPL / (ME * CL * CL) * dlam[i][j][k][n][m]; double dw_a = w[i][j][k][n][m] * (1. - exp(-dtau_a)); udotG_abs += kphys_to_num * dw_a * udotk / vol; // dEtau_abs += HPL*nu[i][j][k][n][m]*w[i][j][k][n][m]*(1. - // exp(-dtau_a)); // Scattering (assuming h \nu << k_B T_e) double alpha_inv_s = alpha_inv_scatt(nu[i][j][k][n][m], type, interaction, &micro); double dtau_s = alpha_inv_s * L_unit * HPL / (ME * CL * CL) * dlam[i][j][k][n][m]; double dw_s = w[i][j][k][n][m] * (1. - exp(-dtau_s)); double amp = 1. + 4. * Thetae - 2. * pow(Thetae, 3. / 2.) + 16. * pow(Thetae, 2.); udotG_scatt += kphys_to_num * (1. - amp) * dw_s * udotk / vol; // dEdtau_scatt -= HPL*nu[i][j][k][n][m]*; } } // dEdtau_abs *= Ucon[i][j][k][0]/(/* d3xi! */dt*T_unit); // dEdtau_scatt *= Ucon[i][j][k][0]/(dt*T_unit); udotG_abs *= U_unit / T_unit; udotG_scatt *= U_unit / T_unit; // if (udotG_abs != 0. || udotG_scatt != 0.) { /*if (i == 80 && j == 64) { printf("Thetae Ne Bmag = %e %e %e\n", Thetae, Ne[i][j][k], Bmag[i][j][k]); printf("%e %e %e %e\n", Ucon[i][j][k][0]*(uef - uei)/dt, J, udotG_abs, udotG_scatt); }*/ // Solve entropy equation in cgs: // d u_e / d \tau = -emission + absorption - upscattering double resid = Ucon[i][j][k][0] * (uef - uei) / (dt * T_unit); resid += J; resid += udotG_abs; resid += udotG_scatt; return resid; } void estimate_Thetae( grid_prim_type P, grid_eosvar_type extra, double t, double dt) { if (NTHREADS != nthreads) { fprintf(stderr, "NTHREADS = %i nthreads = %i! Exiting...\n", NTHREADS, nthreads); exit(-1); } struct of_microphysics micro; // Count superphotons in each zone #pragma omp parallel { int n = omp_get_thread_num(); struct of_photon *ph = photon_lists[n]; while (ph != NULL) { int i, j, k; double X[NDIM], Kcov[NDIM], Kcon[NDIM]; get_X_K_interp(ph, t, P, X, Kcov, Kcon); Xtoijk(X, &i, &j, &k); Nsph_zone[i][j][k][n]++; ph = ph->next; } } // omp parallel // malloc required memory and store ucon for convenience #pragma omp parallel for collapse(3) ZLOOP { double Bcon[NDIM]; get_fluid_zone(i, j, k, P, extra, &micro, Ucon[i][j][k], Ucov[i][j][k], Bcon, Bcov[i][j][k]); Ne[i][j][k] = micro.Ne; Thetae_old[i][j][k] = micro.Thetae; Bmag[i][j][k] = micro.B; for (int n = 0; n < nthreads; n++) { w[i][j][k][n] = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double)); nu[i][j][k][n] = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double)); dlam[i][j][k][n] = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double)); theta[i][j][k][n] = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double)); Nsph_cntd[i][j][k][n] = 0; } } // omp parallel // Create per-zone lists of w, nu, dlam #pragma omp parallel { int n = omp_get_thread_num(); struct of_photon *ph = photon_lists[n]; while (ph != NULL) { int i, j, k; double X[NDIM], Kcov[NDIM], Kcon[NDIM]; get_X_K_interp(ph, t, P, X, Kcov, Kcon); Xtoijk(X, &i, &j, &k); if (i < NG || i > NG + N1 - 1 || j < NG || j > NG + N2 - 1 || k < NG || k > NG + N3 - 1) { printf("BAD PH????\n"); printf("[%i] %i %i %i X[] = %e %e %e %e\n", n, i, j, k, X[0], X[1], X[2], X[3]); for (int mu = 0; mu < 3; mu++) { printf("X[%i][] = %e %e %e %e\n", mu, ph->X[mu][0], ph->X[mu][1], ph->X[mu][2], ph->X[mu][3]); printf("Kcov[%i][] = %e %e %e %e\n", mu, ph->Kcov[mu][0], ph->Kcov[mu][1], ph->Kcov[mu][2], ph->Kcov[mu][3]); printf("Kcon[%i][] = %e %e %e %e\n", mu, ph->Kcon[mu][0], ph->Kcon[mu][1], ph->Kcon[mu][2], ph->Kcon[mu][3]); } printf("origin %i %i %i %i\n", ph->origin[0], ph->origin[1], ph->origin[2], ph->origin[3]); printf("nscatt = %i\n", ph->nscatt); exit(-1); } double freq = 0.; for (int mu = 0; mu < NDIM; mu++) { freq -= Ucon[i][j][k][mu] * Kcov[mu]; } freq *= ME * CL * CL / HPL; w[i][j][k][n][Nsph_cntd[i][j][k][n]] = ph->w; nu[i][j][k][n][Nsph_cntd[i][j][k][n]] = freq; dlam[i][j][k][n][Nsph_cntd[i][j][k][n]] = dt / Kcon[0]; theta[i][j][k][n][Nsph_cntd[i][j][k][n]] = get_bk_angle(X, Kcon, Ucov[i][j][k], Bcov[i][j][k], Bmag[i][j][k]); Nsph_cntd[i][j][k][n]++; ph = ph->next; } } // omp parallel // In each zone, rootfind to Thetae that matches sources. If failure, simply // return current Thetae #pragma omp parallel { const gsl_root_fsolver_type *T; gsl_root_fsolver * s; gsl_function F; F.function = &dEdt; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc(T); static double extra[EOS_NUM_EXTRA]; #pragma omp threadprivate(extra) #if EOS == EOS_TYPE_GAMMA EOS_ELOOP { extra[e] = 0.0; } #endif #pragma omp for collapse(3) ZLOOP { #if EOS == EOS_TYPE_TABLE extra[EOS_YE] = P[i][j][k][YE]; #endif // fill parameters struct of_params params; params.i = i; params.j = j; params.k = k; params.rho = P[i][j][k][RHO]; params.Ne = Ne[i][j][k]; params.Bmag = Bmag[i][j][k]; params.Thetaei = Thetae_old[i][j][k]; params.Ucon0 = Ucon[i][j][k][0]; params.dt = dt; // hopefully this doesn't break openmp EOS_ELOOP { params.extra[e] = extra[e]; } F.params = &params; double r = 0.; double Thetae_lo = 0.5 * Thetae_old[i][j][k]; double Thetae_hi = 2. * Thetae_old[i][j][k]; // Test interval for sanity double rmin = dEdt(Thetae_lo, &params); double rmax = dEdt(Thetae_hi, &params); if (rmin * rmax > 0.) { fprintf(stderr, "[%i %i %i] Root not bracketed!\n", i, j, k); Thetae_est[i][j][k] = Thetae_old[i][j][k]; continue; } gsl_root_fsolver_set(s, &F, Thetae_lo, Thetae_hi); int iter = 0, max_iter = 100; int status; do { status = gsl_root_fsolver_iterate(s); r = gsl_root_fsolver_root(s); Thetae_lo = gsl_root_fsolver_x_lower(s); Thetae_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(Thetae_lo, Thetae_hi, 0, 0.001); } while (status == GSL_CONTINUE && iter < max_iter); if (status != GSL_SUCCESS) { Thetae_est[i][j][k] = Thetae_old[i][j][k]; } else { Thetae_est[i][j][k] = r; } } gsl_root_fsolver_free(s); } // omp parallel // Clean up mallocs and reset counters #pragma omp parallel for collapse(3) ZLOOP { for (int n = 0; n < nthreads; n++) { free(w[i][j][k][n]); free(nu[i][j][k][n]); free(dlam[i][j][k][n]); free(theta[i][j][k][n]); Nsph_zone[i][j][k][n] = 0.; } } // omp parallel } #endif // ESTIMATE_THETAE #endif // RADIATION
{ "alphanum_fraction": 0.4990421456, "avg_line_length": 34.3421052632, "ext": "c", "hexsha": "83abe0c982fd25386fccfaff1e788eaae6a24a3e", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_path": "core/estimate_thetae.c", "max_issues_count": 13, "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_path": "core/estimate_thetae.c", "max_line_length": 80, "max_stars_count": 16, "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_path": "core/estimate_thetae.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z", "num_tokens": 3676, "size": 10440 }
// Copyright 2019 Victor Hugo Schulz // 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 STAR_IDENTIFICATION_H #define STAR_IDENTIFICATION_H extern "C"{ #include <cblas.h> } #include <algorithm> #include <limits> #include <vector> #include <string.h> #include <opencv2/core/core.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "structures_st.h" #include "centroiding.h" #include "standard_structures.h" namespace st { enum Stmode {REFERENCE, REFERENCE_BIN, BINARY, BINARY_INDEX, K}; class StarIdentification { public: StarIdentification(); ~StarIdentification(); std_str::Sky identifyStars(std_str::Sky csky); void reload(); StarIdConfiguration config; private: void bit_descriptor (unsigned long *bucket, unsigned int bucket_size, std::vector<cv::Point2d> &translated); void initialize_catalog(void *ptr, size_t size, std::string filename); void translate_rotate (std::vector<cv::Point2d> &translated, double &nn_dist, std::vector<std_str::Star> stars, uint ref); int normalized_coordinate (double pixel_coordinate); int cell(double x, double y); void descriptor(std::vector<int> &desc, std::vector<cv::Point2d> &translated); void pixel_to_unit_vector(cv::Point3d *unit_vector, cv::Point2d star); int array_intersection(int* array0, int size0, int* array1, int size1, int max_element); int binSearch(double what); int binSearch2(float what, float *data, int len); int classify(int *max, int *desc_size, std::vector<cv::Point2d> &translated); int classifyK(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle); int classify_binary(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle); int classify_binary_index(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle); int classify_binary_ref(int *max, int *desc_size, std::vector<cv::Point2d> &translated); void classifier(std::vector<Candidate> &candidates, std::vector<std_str::Star> stars); cv::Point3d cross(cv::Point3d a, cv::Point3d b); double vector_angle(cv::Point3d a, cv::Point3d b); void filter(std::vector<Candidate> & cluster, double fov); void cluster (std::vector<std::vector<Candidate> > &output, std::vector<Candidate> &candidates, double v_fov); std::vector<Candidate>* verify (std::vector<std::vector<Candidate> > &clustered); double fov(double size, double focus); std_str::Star to_star(Candidate cd); std::vector<std_str::Star> format_output(std::vector<Candidate> *verified); void loadConfig(); void loadDatabase(); double **ref_cat; unsigned long long **bin_cat; short **lut_cat; float **lut_nn_cat; short *index; Stmode mode; }; } #endif // STAR_IDENTIFICATION_H
{ "alphanum_fraction": 0.7285925926, "avg_line_length": 38.3522727273, "ext": "h", "hexsha": "218b0f7618eafc03d7d0cd32648fad12bf0f1f9e", "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": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_forks_repo_path": "src/tcp_dut_client/star_identification.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_issues_repo_issues_event_max_datetime": "2020-10-30T06:25:21.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-30T06:25:21.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_issues_repo_path": "src/tcp_dut_client/star_identification.h", "max_line_length": 126, "max_stars_count": 3, "max_stars_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_stars_repo_path": "src/tcp_dut_client/star_identification.h", "max_stars_repo_stars_event_max_datetime": "2022-01-18T21:14:26.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:32:00.000Z", "num_tokens": 845, "size": 3375 }
#include "mirbooking-broker.h" #include "mirbooking-score-table-private.h" #include <stdlib.h> #include <math.h> #include <pb.h> #include <string.h> #include <odeint.h> #if HAVE_OPENMP #include <omp.h> #endif #include <sparse.h> #include <stdio.h> #if HAVE_MKL_CBLAS #include <mkl_cblas.h> #elif HAVE_OPENBLAS #include <openblas/cblas.h> #else #include <cblas.h> #endif #define RTOL 1e-6 #define ATOL 1e-8 #define COALESCE(x,d) (x == NULL ? (d) : (x)) typedef struct _MirbookingTargetPositions { gsize *positions; gsize positions_len; GPtrArray *occupants; } MirbookingTargetPositions; static void mirbooking_target_positions_clear (MirbookingTargetPositions *tss) { g_free (tss->positions); g_ptr_array_unref (tss->occupants); } typedef struct { gint rank; gsize prime5_footprint; gsize prime3_footprint; MirbookingScoreTable *score_table; GPtrArray *targets; GPtrArray *mirnas; GHashTable *quantification; // #MirbookingSequence -> #gfloat (initial quantity) /* whether or not the system has been initialized */ gsize init; /* all the target sites, stored contiguously */ GArray *target_sites; GHashTable *target_sites_by_target; GPtrArray *target_sites_by_target_index; GArray *target_positions; // (target, mirna) -> positions, scores and occupants in the target GArray *occupants; /* transcription */ gdouble *targets_ktr; gdouble *mirnas_ktr; /* state of the system */ /* state of the system, which corresponds to the concatenation of the * various concentration vectors * * [E] [S] [ES] [P] */ gdouble t; gdouble *y; gsize y_len; /* shortcuts over 'y' */ gdouble *E; // len(mirnas) gdouble *S; // len(targets) gdouble *ES; // len(occupants) gdouble *P; // len(S) /* odeint */ OdeIntIntegrator *integrator; gdouble *F; /* shortcuts over 'F' */ gdouble *dEdt; gdouble *dSdt; gdouble *dESdt; gdouble *dPdt; /* steady-state solver */ MirbookingBrokerSparseSolver sparse_solver; SparseSolver *solver; /* for compactness and efficiency, the Jacobian is only defined over [ES] */ SparseMatrix *J; // len(ES) * len(ES) gdouble *ES_delta; // len(ES) } MirbookingBrokerPrivate; struct _MirbookingBroker { GObject parent_instance; MirbookingBrokerPrivate *priv; }; G_DEFINE_TYPE_WITH_PRIVATE (MirbookingBroker, mirbooking_broker, G_TYPE_OBJECT) static void mirbooking_broker_init (MirbookingBroker *self) { self->priv = g_new0 (MirbookingBrokerPrivate, 1); self->priv->targets = g_ptr_array_new_with_free_func (g_object_unref); self->priv->mirnas = g_ptr_array_new_with_free_func (g_object_unref); self->priv->quantification = g_hash_table_new ((GHashFunc) mirbooking_sequence_hash, (GEqualFunc) mirbooking_sequence_equal); } enum { PROP_RANK = 1, PROP_5PRIME_FOOTPRINT, PROP_3PRIME_FOOTPRINT, PROP_SCORE_TABLE, PROP_SPARSE_SOLVER }; static void mirbooking_broker_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { MirbookingBroker *self = MIRBOOKING_BROKER (object); switch (property_id) { case PROP_RANK: self->priv->rank = g_value_get_int (value); break; case PROP_5PRIME_FOOTPRINT: self->priv->prime5_footprint = g_value_get_uint (value); break; case PROP_3PRIME_FOOTPRINT: self->priv->prime3_footprint = g_value_get_uint (value); break; case PROP_SCORE_TABLE: mirbooking_broker_set_score_table (self, g_value_get_object (value)); break; case PROP_SPARSE_SOLVER: mirbooking_broker_set_sparse_solver (self, g_value_get_enum (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static void mirbooking_broker_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { MirbookingBroker *self = MIRBOOKING_BROKER (object); switch (property_id) { case PROP_RANK: g_value_set_int (value, self->priv->rank); break; case PROP_5PRIME_FOOTPRINT: g_value_set_uint (value, self->priv->prime5_footprint); break; case PROP_3PRIME_FOOTPRINT: g_value_set_uint (value, self->priv->prime3_footprint); break; case PROP_SCORE_TABLE: g_value_set_object (value, self->priv->score_table); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static size_t _mirbooking_broker_get_occupant_index (MirbookingBroker *self, const MirbookingOccupant *occupant) { return occupant - &g_array_index (self->priv->occupants, MirbookingOccupant, 0); } gdouble _mirbooking_broker_get_occupant_quantity (MirbookingBroker *self, const MirbookingOccupant *occupant, const gdouble *ES) { gsize k = _mirbooking_broker_get_occupant_index (self, occupant); g_assert_cmpint (k, >=, 0); g_assert_cmpint (k, <, self->priv->occupants->len); return ES[k]; } gdouble mirbooking_broker_get_occupant_quantity (MirbookingBroker *self, const MirbookingOccupant *occupant) { g_return_val_if_fail (self->priv->init, 0.0); return _mirbooking_broker_get_occupant_quantity (self, occupant, self->priv->ES); } #if !GLIB_CHECK_VERSION(2,54,0) static gboolean g_ptr_array_find_with_equal_func (GPtrArray *array, gconstpointer elem, GEqualFunc equal_func, guint *index) { guint i; for (i = 0; i < array->len; i++) { if (equal_func (g_ptr_array_index (array, i), elem)) { if (index) *index = i; return TRUE; } } return FALSE; } #endif /** * mirbooking_broker_set_occupant_quantity: * @self: A #MirbookingBroker * @occupant: A #MirbookingOccupant previously obtained from #mirbooking_broker_get_target_sites * @quantity: The new quantity of that occupant * * Set the concentration of an occupant to the given value. */ void mirbooking_broker_set_occupant_quantity (MirbookingBroker *self, const MirbookingOccupant *occupant, gdouble quantity) { g_return_if_fail (self->priv->init); g_return_if_fail (quantity >= 0); guint i; g_return_if_fail (g_ptr_array_find_with_equal_func (self->priv->mirnas, occupant->mirna, (GEqualFunc) mirbooking_sequence_equal, &i)); gsize k = _mirbooking_broker_get_occupant_index (self, occupant); self->priv->ES[k] = quantity; } static void mirbooking_target_site_clear (MirbookingTargetSite *self) { g_object_unref (self->target); g_slist_free_full (self->occupants, (GDestroyNotify) mirbooking_occupant_clear); } static void mirbooking_broker_finalize (GObject *object) { MirbookingBroker *self = MIRBOOKING_BROKER (object); if (self->priv->score_table) { g_object_unref (self->priv->score_table); } g_hash_table_unref (self->priv->quantification); g_ptr_array_unref (self->priv->targets); g_ptr_array_unref (self->priv->mirnas); if (self->priv->target_sites) { g_array_unref (self->priv->target_sites); g_hash_table_unref (self->priv->target_sites_by_target); g_ptr_array_unref (self->priv->target_sites_by_target_index); g_array_unref (self->priv->target_positions); g_array_unref (self->priv->occupants); } if (self->priv->integrator) { g_free (self->priv->y); g_free (self->priv->F); g_free (self->priv->targets_ktr); g_free (self->priv->mirnas_ktr); odeint_integrator_free (self->priv->integrator); } if (self->priv->J) { sparse_matrix_clear (self->priv->J); g_free (self->priv->J); } if (self->priv->ES_delta) g_free (self->priv->ES_delta); sparse_solver_free (self->priv->solver); g_free (self->priv); G_OBJECT_CLASS (mirbooking_broker_parent_class)->finalize (object); } static void mirbooking_broker_class_init (MirbookingBrokerClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->set_property = mirbooking_broker_set_property; object_class->get_property = mirbooking_broker_get_property; object_class->finalize = mirbooking_broker_finalize; g_object_class_install_property (object_class, PROP_RANK, g_param_spec_int ("rank", "", "", 0, G_MAXINT, 0, G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_5PRIME_FOOTPRINT, g_param_spec_uint ("prime5-footprint", "", "", 0, G_MAXUINT, MIRBOOKING_BROKER_DEFAULT_5PRIME_FOOTPRINT, G_PARAM_CONSTRUCT | G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_3PRIME_FOOTPRINT, g_param_spec_uint ("prime3-footprint", "", "", 0, G_MAXUINT, MIRBOOKING_BROKER_DEFAULT_3PRIME_FOOTPRINT, G_PARAM_CONSTRUCT | G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SCORE_TABLE, g_param_spec_object ("score-table", "", "", MIRBOOKING_TYPE_SCORE_TABLE, G_PARAM_CONSTRUCT | G_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SPARSE_SOLVER, g_param_spec_enum ("sparse-solver", "", "", MIRBOOKING_BROKER_SPARSE_SOLVER_ENUM, MIRBOOKING_BROKER_DEFAULT_SPARSE_SOLVER, G_PARAM_CONSTRUCT | G_PARAM_READWRITE)); } /** * mirbooking_broker_new: * * Returns: (transfer full): A plain #Mirbooking instance */ MirbookingBroker * mirbooking_broker_new (void) { return g_object_new (MIRBOOKING_BROKER_TYPE, NULL); } /** * mirbooking_broker_new_with_rank: * * Returns: (transfer full): A plain #Mirbooking instance with specified rank */ MirbookingBroker * mirbooking_broker_new_with_rank (gint rank) { return g_object_new (MIRBOOKING_BROKER_TYPE, "rank", rank, NULL); } /** * mirbooking_broker_get_rank: * * Obtain the rank of this broker in a distributed context. */ gint mirbooking_broker_get_rank (MirbookingBroker *self) { return self->priv->rank; } void mirbooking_broker_set_5prime_footprint (MirbookingBroker *self, gsize footprint) { self->priv->prime5_footprint = footprint; } void mirbooking_broker_set_3prime_footprint (MirbookingBroker *self, gsize footprint) { self->priv->prime3_footprint = footprint; } void mirbooking_broker_set_sparse_solver (MirbookingBroker *self, MirbookingBrokerSparseSolver sparse_solver) { if (self->priv->solver == NULL || self->priv->sparse_solver != sparse_solver) { if (self->priv->solver) { sparse_solver_free (self->priv->solver); } self->priv->sparse_solver = sparse_solver; self->priv->solver = sparse_solver_new ((SparseSolverMethod) sparse_solver); g_return_if_fail (self->priv->solver != NULL); g_object_notify (G_OBJECT (self), "sparse-solver"); } } /** * mirbooking_broker_get_score_table: * Obtain the #MirbookingScoreTable used by this for computing duplex scores. * * Returns: (transfer none) */ MirbookingScoreTable * mirbooking_broker_get_score_table (MirbookingBroker *self) { return self->priv->score_table; } void mirbooking_broker_set_score_table (MirbookingBroker *self, MirbookingScoreTable *score_table) { g_return_if_fail (!self->priv->init); if (score_table != self->priv->score_table) { g_clear_object (&self->priv->score_table); self->priv->score_table = g_object_ref (score_table); g_object_notify (G_OBJECT (self), "score-table"); } } union gfloatptr { gfloat f; gpointer p; }; static gfloat gfloat_from_gpointer (gpointer ptr) { union gfloatptr flt = { .p = ptr }; return flt.f; } static gpointer gpointer_from_gfloat (gfloat flt) { union gfloatptr ptr = { .f = flt }; return ptr.p; } /** * mirbooking_broker_get_bound_mirna_quantity: * * Obtain the bound quantity of @mirna. */ gdouble mirbooking_broker_get_bound_mirna_quantity (MirbookingBroker *self, MirbookingMirna *mirna) { g_return_val_if_fail (self->priv->init, 0.0); gdouble bound_quantity = 0; gsize k; #pragma omp parallel for reduction(+:bound_quantity) for (k = 0; k < self->priv->occupants->len; k++) { MirbookingOccupant *occupant = &g_array_index (self->priv->occupants, MirbookingOccupant, k); if (occupant->mirna == mirna) { bound_quantity += self->priv->ES[_mirbooking_broker_get_occupant_index (self, occupant)]; } } return bound_quantity; } /** * mirbooking_broker_get_sequence_quantity: * @sequence: A #MirbookingSequence to retrieve quantity * * Retrieve the free quantity of @sequence. */ gdouble mirbooking_broker_get_sequence_quantity (MirbookingBroker *self, MirbookingSequence *sequence) { g_return_val_if_fail (g_hash_table_contains (self->priv->quantification, sequence), 0.0); if (self->priv->init) { if (MIRBOOKING_IS_MIRNA (sequence)) { guint i; if (g_ptr_array_find_with_equal_func (self->priv->mirnas, sequence, (GEqualFunc) mirbooking_sequence_equal, &i)) { return self->priv->E[i]; } } else { guint i; if (g_ptr_array_find_with_equal_func (self->priv->targets, sequence, (GEqualFunc) mirbooking_sequence_equal, &i)) { return self->priv->S[i]; } } } else { return gfloat_from_gpointer (g_hash_table_lookup (self->priv->quantification, sequence)); } g_return_val_if_reached (0.0); } /** * mirbooking_broker_get_product_quantity: */ gdouble mirbooking_broker_get_product_quantity (MirbookingBroker *self, MirbookingTarget *target) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i), 0.0); return self->priv->P[i]; } /** * mirbooking_broker_set_product_quantity: */ void mirbooking_broker_set_product_quantity (MirbookingBroker *self, MirbookingTarget *target, gdouble quantity) { g_return_if_fail (self->priv->init); g_return_if_fail (quantity >= 0); guint i; g_return_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i)); self->priv->P[i] = quantity; } /** * mirbooking_set_sequence_quantity: * @sequence: A #MirbookingSequence being quantified for the * upcoming execution * * Set the free concentration of @sequence to @quantity. If @sequence is not * part of the system, it is added. * * The concentration of a #MirbookingMirna can be set to a negative value, as * long as the total amount present (see #mirbooking_broker_get_bound_mirna_quantity) * is positive. * * Note that no new sequence can be added this way once * #mirbooking_broker_evaluate has been called. */ void mirbooking_broker_set_sequence_quantity (MirbookingBroker *self, MirbookingSequence *sequence, gdouble quantity) { g_return_if_fail (MIRBOOKING_IS_MIRNA (sequence) || MIRBOOKING_IS_TARGET (sequence)); g_return_if_fail (self->priv->init == 0 || g_hash_table_contains (self->priv->quantification, sequence)); g_return_if_fail (MIRBOOKING_IS_MIRNA (sequence) || quantity >= 0); /* update the system */ // TODO: have reverse-index for these use cases if (self->priv->init) { if (MIRBOOKING_IS_MIRNA (sequence)) { g_return_if_fail (quantity + mirbooking_broker_get_bound_mirna_quantity (self, MIRBOOKING_MIRNA (sequence)) >= 0); guint i; if (g_ptr_array_find_with_equal_func (self->priv->mirnas, sequence, (GEqualFunc) mirbooking_sequence_equal, &i)) { self->priv->E[i] = quantity; } } else { guint i; if (g_ptr_array_find_with_equal_func (self->priv->targets, sequence, (GEqualFunc) mirbooking_sequence_equal, &i)) { self->priv->S[i] = quantity; } } } if (!g_hash_table_contains (self->priv->quantification, sequence)) { if (MIRBOOKING_IS_MIRNA (sequence)) { g_ptr_array_add (self->priv->mirnas, g_object_ref (sequence)); } else { g_ptr_array_add (self->priv->targets, g_object_ref (sequence)); } } g_hash_table_insert (self->priv->quantification, sequence, gpointer_from_gfloat (quantity)); } /** * mirbooking_broker_get_time: * * Get the time in seconds of the system. * * This is much more accurate to retrieve the time this way than to keep an * external counter because of some numerical errors that can accumulate when * stepping. */ gdouble mirbooking_broker_get_time (MirbookingBroker *self) { return self->priv->t; } /** * mirbooking_broker_set_time: * * Set the initial time for the numerical integration. */ void mirbooking_broker_set_time (MirbookingBroker *self, gdouble time) { g_return_if_fail (!self->priv->init); self->priv->t = time; } /* * Compute the footprint window in which two microRNA can have overlapping * footprint at this position. */ static void _mirbooking_broker_get_footprint_window (MirbookingBroker *self, const MirbookingTargetSite *target_site, gsize prime5_footprint, gsize prime3_footprint, const MirbookingTargetSite **from_target_site, const MirbookingTargetSite **to_target_site) { // find the lower target site *from_target_site = target_site - MIN (prime5_footprint, target_site->position); // find the upper target site *to_target_site = target_site + MIN (prime3_footprint, mirbooking_sequence_get_sequence_length (MIRBOOKING_SEQUENCE (target_site->target)) - target_site->position - 1); g_assert ((*from_target_site)->target == target_site->target); g_assert ((*to_target_site)->target == target_site->target); } gdouble _mirbooking_broker_get_target_site_occupants_quantity (MirbookingBroker *self, const MirbookingTargetSite *target_site, const gdouble *ES) { gdouble total_ES = 0; GSList *occupants_list; for (occupants_list = target_site->occupants; occupants_list != NULL; occupants_list = occupants_list->next) { MirbookingOccupant *occupant = occupants_list->data; total_ES += _mirbooking_broker_get_occupant_quantity (self, occupant, ES); } return total_ES; } gdouble _mirbooking_broker_get_target_site_vacancy (MirbookingBroker *self, const MirbookingTargetSite *target_site, gsize prime5_footprint, gsize prime3_footprint, gdouble St, const gdouble *ES) { gdouble vacancy = 1.0; const MirbookingTargetSite *from_target_site, *to_target_site; _mirbooking_broker_get_footprint_window (self, target_site, prime5_footprint, prime3_footprint, &from_target_site, &to_target_site); /* * Curiously, this corresponds to the following factorization of the joint * distribution of having all positions simultaneously unbound. * * Pr(p_1,p_2,...,p_n) = Pr(p_1) * Pr(p_2|p_1) * ... * Pr(p_n|p_1, p_2,... p_{n-1}) * * Pr(p_1) is straightforward to calculate. * * For every other position, we compute the vacancy by assuming that every * preceding positions are unbounded as well. */ const MirbookingTargetSite *last_tts = NULL; const MirbookingTargetSite *ts; for (ts = from_target_site; ts <= to_target_site; ts++) { /* * Here, we invert the footprint because we want to know where other * occupants can overlap this position. */ const MirbookingTargetSite *fts, *tts; _mirbooking_broker_get_footprint_window (self, ts, prime3_footprint, prime5_footprint, &fts, &tts); gdouble quantity = 0; const MirbookingTargetSite *nearby_target_site; for (nearby_target_site = fts; nearby_target_site <= tts; nearby_target_site++) { if (nearby_target_site > last_tts) { quantity += _mirbooking_broker_get_target_site_occupants_quantity (self, nearby_target_site, ES); } } vacancy *= (1 - (quantity / St)); last_tts = tts; } return vacancy; } typedef struct _MirbookingScoredTargetSite { MirbookingTargetSite *target_site; MirbookingScore score; } MirbookingScoredTargetSite; static gint cmp_gsize (gconstpointer a, gconstpointer b) { return *(const gsize*)a - *(const gsize*)b; } static gboolean _mirbooking_broker_prepare_step (MirbookingBroker *self, GError **error) { guint64 prepare_begin = g_get_monotonic_time (); gsize target_sites_len = 0; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (self->priv->score_table != NULL, FALSE); g_return_val_if_fail (self->priv->solver != NULL, FALSE); guint i; #pragma omp parallel for reduction(+:target_sites_len) for (i = 0; i < self->priv->targets->len; i++) { target_sites_len += mirbooking_sequence_get_sequence_length (g_ptr_array_index (self->priv->targets, i)); } // prepare an contiguous array self->priv->target_sites = g_array_sized_new (FALSE, FALSE, sizeof (MirbookingTargetSite), target_sites_len); // automatically clear the target sites g_array_set_clear_func (self->priv->target_sites, (GDestroyNotify) mirbooking_target_site_clear); // bookkeep each target site self->priv->target_sites_by_target = g_hash_table_new ((GHashFunc) mirbooking_sequence_hash, (GEqualFunc) mirbooking_sequence_equal); // intialize sites for (i = 0; i < self->priv->targets->len; i++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); g_hash_table_insert (self->priv->target_sites_by_target, target, &g_array_index (self->priv->target_sites, MirbookingTargetSite, self->priv->target_sites->len)); gsize seq_len = mirbooking_sequence_get_sequence_length (MIRBOOKING_SEQUENCE (target)); gsize position; for (position = 0; position < seq_len; position++) { MirbookingTargetSite target_site; target_site.target = g_object_ref (target); target_site.position = position; target_site.occupants = NULL; g_array_append_val (self->priv->target_sites, target_site); } } // memoize in a array-friendly way the target sites self->priv->target_sites_by_target_index = g_ptr_array_new (); for (i = 0; i < self->priv->targets->len; i++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); MirbookingTargetSite *target_site = g_hash_table_lookup (self->priv->target_sites_by_target, target); g_ptr_array_add (self->priv->target_sites_by_target_index, target_site); } // memoize score vectors self->priv->target_positions = g_array_sized_new (FALSE, FALSE, sizeof (MirbookingTargetPositions), self->priv->targets->len * self->priv->mirnas->len); g_array_set_clear_func (self->priv->target_positions, (GDestroyNotify) mirbooking_target_positions_clear); g_array_set_size (self->priv->target_positions, self->priv->targets->len * self->priv->mirnas->len); // compute scores gsize occupants_len = 0; guint j; gboolean anyerror = FALSE; #pragma omp parallel for collapse(2) reduction(+:occupants_len) for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); MirbookingMirna *mirna = g_ptr_array_index (self->priv->mirnas, j); MirbookingTargetPositions *seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, i * self->priv->mirnas->len + j); anyerror |= !mirbooking_score_table_compute_positions (MIRBOOKING_SCORE_TABLE (self->priv->score_table), mirna, target, &seed_positions->positions, &seed_positions->positions_len, error); occupants_len += seed_positions->positions_len; } } if (anyerror) { return FALSE; } g_debug ("Number of duplexes: %lu", occupants_len); // pre-allocate occupants in contiguous memory self->priv->occupants = g_array_sized_new (FALSE, FALSE, sizeof (MirbookingOccupant), occupants_len); g_array_set_size (self->priv->occupants, occupants_len); // intitialize occupants MirbookingOccupant *occupants = (MirbookingOccupant*) self->priv->occupants->data; gint k = 0; #pragma omp parallel for collapse(2) ordered for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingMirna *mirna = g_ptr_array_index (self->priv->mirnas, j); MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); MirbookingTargetPositions *seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, i * self->priv->mirnas->len + j); gint _k; #pragma omp ordered { _k = k; k += seed_positions->positions_len; } seed_positions->occupants = g_ptr_array_sized_new (seed_positions->positions_len); guint p; for (p = 0; p < seed_positions->positions_len; p++) { MirbookingTargetSite *target_site = &target_sites[seed_positions->positions[p]]; g_assert_cmpint (target_site->position, ==, seed_positions->positions[p]); MirbookingScore score = {0}; anyerror |= !mirbooking_score_table_compute_score (self->priv->score_table, mirna, target_site->target, seed_positions->positions[p], &score, error); mirbooking_occupant_init (&occupants[_k + p], target_site->target, seed_positions->positions[p], mirna, score); /* * Multiple microRNA might share this target site and prepended * at once. */ #pragma omp critical target_site->occupants = g_slist_prepend (target_site->occupants, &occupants[_k + p]); g_ptr_array_add (seed_positions->occupants, &occupants[_k + p]); } } } if (anyerror) { return FALSE; } g_assert_cmpint (self->priv->occupants->len, ==, occupants_len); self->priv->targets_ktr = g_new0 (gdouble, self->priv->targets->len); self->priv->mirnas_ktr = g_new0 (gdouble, self->priv->mirnas->len); self->priv->y_len = self->priv->mirnas->len + self->priv->targets->len + self->priv->occupants->len + self->priv->targets->len; // state of the system self->priv->y = g_new0 (gdouble, self->priv->y_len); // add shortcuts self->priv->E = self->priv->y; self->priv->S = self->priv->E + self->priv->mirnas->len; self->priv->ES = self->priv->S + self->priv->targets->len; self->priv->P = self->priv->ES + self->priv->occupants->len; // setup initial conditions #pragma omp parallel for for (j = 0; j < self->priv->mirnas->len; j++) { gdouble q = gfloat_from_gpointer (g_hash_table_lookup (self->priv->quantification, g_ptr_array_index (self->priv->mirnas, j))); self->priv->E[j] = q; } #pragma omp parallel for for (i = 0; i < self->priv->targets->len; i++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); gdouble q = gfloat_from_gpointer (g_hash_table_lookup (self->priv->quantification, target)); self->priv->S[i] = q; } // allocate memory for the integrator and the solver self->priv->F = g_new0 (gdouble, self->priv->y_len); // add shortcuts self->priv->dEdt = self->priv->F; self->priv->dSdt = self->priv->dEdt + self->priv->mirnas->len; self->priv->dESdt = self->priv->dSdt + self->priv->targets->len; self->priv->dPdt = self->priv->dESdt + self->priv->occupants->len; self->priv->ES_delta = g_new0 (gdouble, self->priv->occupants->len); // integrator self->priv->integrator = odeint_integrator_new (ODEINT_METHOD_DORMAND_PRINCE, &self->priv->t, self->priv->y, self->priv->y_len, ODEINT_INTEGRATOR_DEFAULT_RTOL, ODEINT_INTEGRATOR_DEFAULT_ATOL); g_debug ("Prepared the first step in %lums", 1000 * (g_get_monotonic_time () - prepare_begin) / G_USEC_PER_SEC); return TRUE; } static gsize absdiff (gsize a, gsize b) { return MAX (a, b) - MIN (a, b); } static gdouble _compute_kother (MirbookingBroker *self, gsize i, gsize position, const gdouble *ES, gdouble St) { gdouble kother = 0; guint j; for (j = 0; j < self->priv->mirnas->len; j++) { // all the position of the other microrna MirbookingTargetPositions *tss = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, self->priv->mirnas->len * i + j); guint q; for (q = 0; q < tss->positions_len; q++) { if (absdiff (tss->positions[q], position) > (self->priv->prime5_footprint + self->priv->prime3_footprint)) { MirbookingOccupant *occupant_q = g_ptr_array_index (tss->occupants, q); kother += occupant_q->score.kcat * (_mirbooking_broker_get_occupant_quantity (self, occupant_q, ES) / St); } } } return kother; } /* * Compute the system state. */ static void _compute_F (double t, const double *y, double *F, void *user_data) { MirbookingBroker *self = user_data; const gdouble *E = y; const gdouble *S = E + self->priv->mirnas->len; const gdouble *ES = S + self->priv->targets->len; const gdouble *P = ES + self->priv->occupants->len; gdouble *dEdt = F; gdouble *dSdt = dEdt + self->priv->mirnas->len; gdouble *dESdt = dSdt + self->priv->targets->len; gdouble *dPdt = dESdt + self->priv->occupants->len; gsize prime5_footprint = self->priv->prime5_footprint; gsize prime3_footprint = self->priv->prime3_footprint; // basic transcription and degradation // dEdt = ktr - KDEGE * [E] cblas_dcopy (self->priv->mirnas->len, self->priv->mirnas_ktr, 1, dEdt, 1); cblas_daxpy (self->priv->mirnas->len, -KDEGE, E, 1, dEdt, 1); // dSdt = ktr - KDEGS * [S] cblas_dcopy (self->priv->targets->len, self->priv->targets_ktr, 1, dSdt, 1); cblas_daxpy (self->priv->targets->len, -KDEGS, S, 1, dSdt, 1); // dPdt = -KDEGP * P cblas_dcopy (self->priv->targets->len, P, 1, dPdt, 1); cblas_dscal (self->priv->targets->len, -KDEGP, dPdt, 1); guint i, j; #pragma omp parallel for collapse(2) for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); g_assert (target_sites->target == target); g_assert_cmpint (target_sites->position, ==, 0); MirbookingMirna *mirna = g_ptr_array_index (self->priv->mirnas, j); // fetch free energies for candidate MREs MirbookingTargetPositions *seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, self->priv->mirnas->len * i + j); guint p; for (p = 0; p < seed_positions->positions_len; p++) { MirbookingOccupant *occupant = g_ptr_array_index (seed_positions->occupants, p); MirbookingTargetSite *target_site = &target_sites[seed_positions->positions[p]]; gsize k = _mirbooking_broker_get_occupant_index (self, occupant); g_assert (target_site->target == target); g_assert_cmpint (target_site->position, ==, seed_positions->positions[p]); g_assert (occupant->mirna == mirna); gdouble kf = occupant->score.kf; gdouble kr = occupant->score.kr; gdouble kcat = occupant->score.kcat; gdouble Stp = S[i] * _mirbooking_broker_get_target_site_vacancy (self, target_site, prime5_footprint, prime3_footprint, S[i], ES); gdouble kother = _compute_kother (self, i, seed_positions->positions[p], ES, S[i]); #pragma omp atomic dEdt[j] += -kf * E[j] * Stp + kr * ES[k] + kcat * ES[k] + kother * ES[k]; #pragma omp atomic dSdt[i] += - kcat * ES[k]; dESdt[k] = kf * E[j] * Stp - kr * ES[k] - kcat * ES[k] - kother * ES[k]; #pragma omp atomic dPdt[i] += kcat * ES[k]; } } } } static void _prepare_J (MirbookingBroker *self) { self->priv->J = g_new0 (SparseMatrix, 1); // count nnz entries in the Jacobian gsize nnz = 0; guint i, j; #pragma omp parallel for collapse(2) reduction(+:nnz) for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); MirbookingTargetPositions *seed_scores = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, i * self->priv->mirnas->len + j); guint p; for (p = 0; p < seed_scores->positions_len; p++) { // substitute targets guint z; for (z = 0; z < self->priv->targets->len; z++) { MirbookingTargetPositions *alternative_seed_scores = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, z * self->priv->mirnas->len + j); nnz += alternative_seed_scores->positions_len; } // substitute miRNAs (excluding this one as we consider it as a substitute target) nnz += g_slist_length (target_sites[seed_scores->positions[p]].occupants) - 1; } } } g_debug ("nnz: %lu, sparsity: %.2f%%", nnz, 100.0 * (1.0 - (gdouble) nnz / pow (self->priv->occupants->len, 2))); size_t shape[2] = {self->priv->occupants->len, self->priv->occupants->len}; sparse_matrix_init (self->priv->J, self->priv->sparse_solver == MIRBOOKING_BROKER_SPARSE_SOLVER_LAPACK ? SPARSE_MATRIX_STORAGE_DENSE : SPARSE_MATRIX_STORAGE_CSR, SPARSE_MATRIX_TYPE_DOUBLE, shape, nnz); self->priv->J->hints |= SPARSE_MATRIX_HINT_SYMMETRIC_STRUCTURE; self->priv->J->hints |= SPARSE_MATRIX_HINT_POSITIVE_DEFINITE; // initialize the sparse slots beforehand because it is not thread-safe and // we want to keep the in order for fast access // TODO: find a way to remove the ordered clause #pragma omp parallel for collapse(2) ordered for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); MirbookingTargetPositions *seed_scores = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, i * self->priv->mirnas->len + j); guint p; for (p = 0; p < seed_scores->positions_len; p++) { // footprint interactions MirbookingTargetSite *target_site = &target_sites[seed_scores->positions[p]]; MirbookingOccupant *occupant = g_ptr_array_index (seed_scores->occupants, p); gsize colind[self->priv->J->shape[0]]; gsize row_nnz = 0; // substitute target guint z; for (z = 0; z < self->priv->targets->len; z++) { MirbookingTargetPositions *alternative_seed_scores = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, z * self->priv->mirnas->len + j); guint w; for (w = 0; w < alternative_seed_scores->occupants->len; w++) { MirbookingOccupant *other_occupant = g_ptr_array_index (alternative_seed_scores->occupants, w); colind[row_nnz++] = _mirbooking_broker_get_occupant_index (self, other_occupant); } } // substitute miRNAs GSList *occupant_list; for (occupant_list = target_site->occupants; occupant_list != NULL; occupant_list = occupant_list->next) { MirbookingOccupant *other_occupant = occupant_list->data; if (other_occupant->mirna != g_ptr_array_index (self->priv->mirnas, j)) { colind[row_nnz++] = _mirbooking_broker_get_occupant_index (self, other_occupant); } } // sort colind qsort (colind, row_nnz, sizeof (gsize), cmp_gsize); #pragma omp ordered sparse_matrix_reserve_range (self->priv->J, _mirbooking_broker_get_occupant_index (self, occupant), colind, row_nnz); } } } } /* * Compute the system Jacobian. */ static void _compute_J (double t, const double *y, SparseMatrix *J, void *user_data) { MirbookingBroker *self = user_data; const gdouble *E = y; const gdouble *S = y + self->priv->mirnas->len; const gdouble *ES = S + self->priv->targets->len; gsize prime5_footprint = self->priv->prime5_footprint; gsize prime3_footprint = self->priv->prime3_footprint; guint i, j; #pragma omp parallel for collapse(2) for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); g_assert (target_sites->target == target); g_assert_cmpint (target_sites->position, ==, 0); MirbookingMirna *mirna = g_ptr_array_index (self->priv->mirnas, j); // fetch free energies for candidate MREs MirbookingTargetPositions *seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, self->priv->mirnas->len * i + j); guint p; for (p = 0; p < seed_positions->positions_len; p++) { MirbookingOccupant *occupant = g_ptr_array_index (seed_positions->occupants, p); MirbookingTargetSite *target_site = &target_sites[seed_positions->positions[p]]; gsize k = _mirbooking_broker_get_occupant_index (self, occupant); g_assert (target_site->target == target); g_assert_cmpint (target_site->position, ==, seed_positions->positions[p]); g_assert (occupant->mirna == mirna); gdouble kf = occupant->score.kf; gdouble kr = occupant->score.kr; gdouble kcat = occupant->score.kcat; gdouble Stp = S[i] * _mirbooking_broker_get_target_site_vacancy (self, target_site, prime5_footprint, prime3_footprint, S[i], ES); // substitute target for the microRNA guint z; for (z = 0; z < self->priv->targets->len; z++) { MirbookingTargetPositions *alternative_seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, z * self->priv->mirnas->len + j); guint w; for (w = 0; w < alternative_seed_positions->occupants->len; w++) { MirbookingOccupant *other_occupant = g_ptr_array_index (alternative_seed_positions->occupants, w); g_assert (other_occupant->mirna == g_ptr_array_index (self->priv->mirnas, j)); gsize other_k = _mirbooking_broker_get_occupant_index (self, other_occupant); gdouble kother = 0; if (occupant == other_occupant) { kother = _compute_kother (self, i, seed_positions->positions[p], ES, S[i]); } else if (i == z && absdiff (seed_positions->positions[p], alternative_seed_positions->positions[w]) > (self->priv->prime5_footprint + self->priv->prime3_footprint)) { /* * Here, we account for the kother if a microRNA is * shared for the pair of complexes because it's * essentially free and speeds up the convergence. * * Ideally we would do if for all pair of * complexes, but it has a combinatorial cost. */ kother = occupant->score.kcat * (_mirbooking_broker_get_occupant_quantity (self, occupant, ES) / self->priv->S[i]); } gdouble dEdES = -1; // always gdouble dSdES = (z == i && seed_positions->positions[p] == alternative_seed_positions->positions[w]) ? -1 : 0; gdouble dESdES = kf * (E[j] * dSdES + Stp * dEdES) - (kr + kcat) * (occupant == other_occupant ? 1 : 0) - kother; sparse_matrix_set_double (J, k, other_k, -dESdES); } } // substitute miRNA for the target GSList *other_occupant_list; for (other_occupant_list = target_site->occupants; other_occupant_list != NULL; other_occupant_list = other_occupant_list->next) { MirbookingOccupant *other_occupant = other_occupant_list->data; gsize other_k = _mirbooking_broker_get_occupant_index (self, other_occupant); gdouble kother = occupant == other_occupant ? _compute_kother (self, i, seed_positions->positions[p], ES, S[i]) : 0; gdouble dEdES = occupant->mirna == other_occupant->mirna ? -1 : 0; gdouble dSdES = -1; gdouble dESdES = kf * (E[j] * dSdES + Stp * dEdES) - (kr + kcat) * (occupant == other_occupant ? 1 : 0) - kother; sparse_matrix_set_double (J, k, other_k, -dESdES); } } } } } /** * mirbooking_broker_evaluate: * @self: A #MirbookingBroker * @error_ratio: (out) (optional): Error-to-tolerance ratio * * Evaluate the current state of the system. * * Returns: %TRUE if the evaluation is successful, otherwise %FALSE and @error * is set accordingly */ gboolean mirbooking_broker_evaluate (MirbookingBroker *self, gdouble *error_ratio, GError **error) { if (g_once_init_enter (&self->priv->init)) { g_return_val_if_fail (_mirbooking_broker_prepare_step (self, error), FALSE); g_once_init_leave (&self->priv->init, 1); } _compute_F (self->priv->t, self->priv->y, self->priv->F, self); if (error_ratio) { gdouble _error_ratio = 0; gsize i; for (i = 0; i < self->priv->y_len; i++) { _error_ratio = fmax (_error_ratio, fabs (self->priv->F[i]) / (RTOL * fabs (self->priv->y[i]) + ATOL)); } *error_ratio = _error_ratio; } return TRUE; } /** * mirbooking_broker_step: * @step_mode: A #MirbookingBrokerStepMode * @step_size: A step size for integration or a fraction of the step for the * Newton-Raphson update * * Perform a step based on the current state of the system. * * Returns: %TRUE on success, otherwise @error is set */ gboolean mirbooking_broker_step (MirbookingBroker *self, MirbookingBrokerStepMode step_mode, gdouble step_size, GError **error) { if (g_once_init_enter (&self->priv->init)) { g_return_val_if_fail (_mirbooking_broker_prepare_step (self, error), FALSE); g_once_init_leave (&self->priv->init, 1); } if (step_mode == MIRBOOKING_BROKER_STEP_MODE_SOLVE_STEADY_STATE) { if (self->priv->rank == 0) { _compute_F (self->priv->t, self->priv->y, self->priv->F, self); if (self->priv->J == NULL) { _prepare_J (self); } _compute_J (self->priv->t, self->priv->y, self->priv->J, self); } gboolean ret; ret = sparse_solver_solve (self->priv->solver, self->priv->J, self->priv->ES_delta, self->priv->dESdt); if (!ret) { g_set_error_literal (error, MIRBOOKING_ERROR, MIRBOOKING_ERROR_FAILED, "The solve step has failed."); return FALSE; } SparseSolverStatistics stats = sparse_solver_get_statistics (self->priv->solver); g_debug ("reorder-time: %fs factor-time: %fs solve-time: %fs flops: %f", stats.reorder_time, stats.factor_time, stats.solve_time, stats.flops); // apply the update guint i, j; #pragma omp parallel for collapse(2) for (i = 0; i < self->priv->targets->len; i++) { for (j = 0; j < self->priv->mirnas->len; j++) { MirbookingTarget *target = g_ptr_array_index (self->priv->targets, i); MirbookingTargetSite *target_sites = g_ptr_array_index (self->priv->target_sites_by_target_index, i); g_assert (target_sites->target == target); g_assert_cmpint (target_sites->position, ==, 0); MirbookingMirna *mirna = g_ptr_array_index (self->priv->mirnas, j); // fetch free energies for candidate MREs MirbookingTargetPositions *seed_positions = &g_array_index (self->priv->target_positions, MirbookingTargetPositions, self->priv->mirnas->len * i + j); guint p; for (p = 0; p < seed_positions->positions_len; p++) { MirbookingOccupant *occupant = g_ptr_array_index (seed_positions->occupants, p); g_assert (occupant->mirna == mirna); gsize k = _mirbooking_broker_get_occupant_index (self, occupant); #pragma omp atomic self->priv->E[j] -= step_size * self->priv->ES_delta[k]; self->priv->ES[k] += step_size * self->priv->ES_delta[k]; } } } // Under the steady-state assumption, all substrate degradation is // compensated by transcription of new targets. // The system must be however reevaluated as we have applied an update. _compute_F (self->priv->t, self->priv->y, self->priv->F, self); { // ktr = ktr - dEdt cblas_daxpy (self->priv->mirnas->len, -1, self->priv->dEdt, 1, self->priv->mirnas_ktr, 1); // ktr = ktr - dSdt cblas_daxpy (self->priv->targets->len, -1, self->priv->dSdt, 1, self->priv->targets_ktr, 1); // P = -(dSdt - ktr) / KDEGP // P = dSdt; P = -ktr + P; P = -1/KDEGP * P cblas_dcopy (self->priv->targets->len, self->priv->dSdt, 1, self->priv->P, 1); cblas_daxpy (self->priv->targets->len, -1, self->priv->targets_ktr, 1, self->priv->P, 1); cblas_dscal (self->priv->targets->len, -1.0 / KDEGP, self->priv->P, 1); } } else if (step_mode == MIRBOOKING_BROKER_STEP_MODE_INTEGRATE) { odeint_integrator_integrate (self->priv->integrator, _compute_F, self, self->priv->t + step_size); } else { g_assert_not_reached (); } return TRUE; } /** * mirbooking_broker_get_mirna_transcription_rate: * * Get the rate of transcription of the given #MirbookingTarget. * * This is resolved when stepping with @MIRBOOKING_BROKER_STEP_MODE_SOLVE_STEADY_STATE * using the steady-state assumption. */ gdouble mirbooking_broker_get_mirna_transcription_rate (MirbookingBroker *self, MirbookingMirna *mirna) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->mirnas, mirna, (GEqualFunc) mirbooking_sequence_equal, &i), 0); return self->priv->mirnas_ktr[i]; } /** * mirbooking_broker_set_mirna_transcription_rate: * * Set the rate of transcription of @mirna to @transcription_rate. */ void mirbooking_broker_set_mirna_transcription_rate (MirbookingBroker *self, MirbookingMirna *mirna, gdouble transcription_rate) { g_return_if_fail (self->priv->init); g_return_if_fail (transcription_rate >= 0); guint i; g_return_if_fail (g_ptr_array_find_with_equal_func (self->priv->mirnas, mirna, (GEqualFunc) mirbooking_sequence_equal, &i)); self->priv->mirnas_ktr[i] = transcription_rate; } /** * mirbooking_broker_get_mirna_degradation_rate: * * Obtain @mirna degradation rate. */ gdouble mirbooking_broker_get_mirna_degradation_rate (MirbookingBroker *self, MirbookingMirna *mirna) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->mirnas, mirna, (GEqualFunc) mirbooking_sequence_equal, &i), 0.0); return KDEGE * self->priv->E[i]; } /** * mirbooking_broker_get_target_transcription_rate: * * Get the rate of transcription of the given #MirbookingTarget. * * This is resolved when stepping with @MIRBOOKING_BROKER_STEP_MODE_SOLVE_STEADY_STATE * using the steady-state assumption. */ gdouble mirbooking_broker_get_target_transcription_rate (MirbookingBroker *self, MirbookingTarget *target) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i), 0); return self->priv->targets_ktr[i]; } /** * mirbooking_broker_get_target_degradation_rate: * * Get the rate of degradation of the given #MirbookingTarget. */ gdouble mirbooking_broker_get_target_degradation_rate (MirbookingBroker *self, MirbookingTarget *target) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i), 0); return KDEGS * self->priv->S[i]; } /** * mirbooking_broker_set_target_transcription_rate: * * Set the rate of transcription of @target to @transcription_rate. */ void mirbooking_broker_set_target_transcription_rate (MirbookingBroker *self, MirbookingTarget *target, gdouble transcription_rate) { g_return_if_fail (self->priv->init); g_return_if_fail (transcription_rate >= 0); guint i; g_return_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i)); self->priv->targets_ktr[i] = transcription_rate; } /** * mirbooking_broker_get_product_degradation_rate: * * Get the rate of product degradation. * * This is resolved when stepping with @MIRBOOKING_BROKER_STEP_MODE_SOLVE_STEADY_STATE * using the steady-state assumption. */ gdouble mirbooking_broker_get_product_degradation_rate (MirbookingBroker *self, MirbookingTarget *target) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target, (GEqualFunc) mirbooking_sequence_equal, &i), 0); return KDEGP * self->priv->P[i]; } /** * mirbooking_broker_get_target_sites: * * Obtain the computed #MirbookingTargetSite array by this #MirbookingBroker. * * Returns: (element-type MirbookingTargetSite) (transfer none): A view of the * computed #MirbookingTargetSite */ const GArray * mirbooking_broker_get_target_sites (MirbookingBroker *self) { g_return_val_if_fail (self != NULL, NULL); g_return_val_if_fail (self->priv->init, NULL); return self->priv->target_sites; } /** * mirbooking_broker_get_target_site_quantity: * * Obtain the expected concentration of a #MirbookingTargetSite which account * for overlapping miRISC in the neighborhood. */ gdouble mirbooking_broker_get_target_site_quantity (MirbookingBroker *self, const MirbookingTargetSite *target_site) { g_return_val_if_fail (self->priv->init, 0.0); gdouble St = mirbooking_broker_get_sequence_quantity (self, MIRBOOKING_SEQUENCE (target_site->target)); return _mirbooking_broker_get_target_site_vacancy (self, target_site, self->priv->prime5_footprint, self->priv->prime3_footprint, St, self->priv->ES) * St; } /** * mirbooking_broker_get_target_site_occupants_quantity: * * Obtain the total concentration of occupants occupying this target site * either directly or indirectly via the footprint. */ gdouble mirbooking_broker_get_target_site_occupants_quantity (MirbookingBroker *self, const MirbookingTargetSite *target_site) { gdouble total_occupants_quantity = 0; const MirbookingTargetSite *fts, *tts; _mirbooking_broker_get_footprint_window (self, target_site, self->priv->prime3_footprint, self->priv->prime5_footprint, &fts, &tts); const MirbookingTargetSite *ts; for (ts = fts; ts <= tts; ts++) { total_occupants_quantity += _mirbooking_broker_get_target_site_occupants_quantity (self, ts, self->priv->ES); } return total_occupants_quantity; } /** * mirbooking_broker_get_target_site_catalytic_rate: * * Obtain the target site catalytic rate. */ gdouble mirbooking_broker_get_target_site_kother (MirbookingBroker *self, const MirbookingTargetSite *target_site) { g_return_val_if_fail (self->priv->init, 0.0); guint i; g_return_val_if_fail (g_ptr_array_find_with_equal_func (self->priv->targets, target_site->target, (GEqualFunc) mirbooking_sequence_equal, &i), 0.0); return _compute_kother (self, i, target_site->position, self->priv->ES, self->priv->S[i]); } /** * mirbooking_broker_get_mirnas: * * Returns: (element-type MirbookingMirna) (transfer none): */ const GPtrArray * mirbooking_broker_get_mirnas (MirbookingBroker *self) { return self->priv->mirnas; } /** * mirbooking_broker_get_targets: * * Returns: (element-type MirbookingTarget) (transfer none): */ const GPtrArray * mirbooking_broker_get_targets (MirbookingBroker *self) { return self->priv->targets; } /** * mirbooking_broker_get_occupants: * * This is much faster to manipulate if the intent is to traverse all the * complexes regardless of their actual location. * * Returns: (element-type MirbookingOccupant) (transfer none): A view over the * occupants */ const GArray * mirbooking_broker_get_occupants (MirbookingBroker *self) { g_return_val_if_fail (self->priv->init, NULL); return self->priv->occupants; } /** * mirbooking_broker_get_target_occupants_pmf: * @target: The #MirbookingTarget for which we are retrieving the silencing * @pmf_len: (out): Length of the PMF which correspond to the number * of occupied sites plus one * * Compute the probability mass function of the number of occupied target sites * on a given target by modeling them with a Poisson-Binomial distribution. * * Returns: (array length=pmf_len): The probability mass function of the number * of bound miRISC complexes or %NULL if it cannot be computed */ gdouble * mirbooking_broker_get_target_occupants_pmf (MirbookingBroker *self, MirbookingTarget *target, gsize *pmf_len) { g_return_val_if_fail (self->priv->init, NULL); g_return_val_if_fail (g_hash_table_contains (self->priv->quantification, target), NULL); gfloat target_quantity = mirbooking_broker_get_sequence_quantity (self, MIRBOOKING_SEQUENCE (target)); g_autoptr (GArray) probability_by_position = g_array_new (FALSE, FALSE, sizeof (gdouble)); MirbookingTargetSite *target_site = g_hash_table_lookup (self->priv->target_sites_by_target, target); while (target_site < &g_array_index (self->priv->target_sites, MirbookingTargetSite, self->priv->target_sites->len) && target_site->target == target) { gdouble occupants_quantity = _mirbooking_broker_get_target_site_occupants_quantity (self, target_site, self->priv->ES); if (occupants_quantity > 0) { gdouble p = occupants_quantity / target_quantity; g_array_append_val (probability_by_position, p); } ++target_site; } PoissonBinomial pb; pb_init (&pb, (gdouble*) probability_by_position->data, probability_by_position->len); gdouble* pmf = g_new (gdouble, 1 + probability_by_position->len); memcpy (pmf, pb.pmf, (1 + probability_by_position->len) * sizeof (gdouble)); if (pmf_len) *pmf_len = 1 + probability_by_position->len; pb_destroy (&pb); return pmf; } /** * mirbooking_broker_get_target_expressed_fraction: * * Obtain the fraction of substrate @target that is expressed. */ gdouble mirbooking_broker_get_target_expressed_fraction (MirbookingBroker *broker, MirbookingTarget *target) { gdouble ef = 0; gdouble lambda = .27; gsize pmf_len; g_autofree gdouble *pmf = mirbooking_broker_get_target_occupants_pmf (broker, target, &pmf_len); gsize i; for (i = 0; i < pmf_len; i++) { ef += exp (-lambda * i) * pmf[i]; } return ef; } static gboolean write_output_to_tsv (MirbookingBroker *mirbooking, GOutputStream *out, GError **error) { g_autoptr (GDataOutputStream) output_f = g_data_output_stream_new (out); gchar *header = "gene_accession\t" "gene_name\t" "target_accession\t" "target_name\t" "target_quantity\t" "position\t" "mirna_accession\t" "mirna_name\t" "mirna_quantity\t" "score\t" "quantity\n"; if (!g_data_output_stream_put_string (output_f, header, NULL, error)) { return FALSE; } const GArray *target_sites = mirbooking_broker_get_target_sites (mirbooking); gfloat target_quantity = 0; const MirbookingTargetSite *target_site; MirbookingTarget *cur_target = NULL; for (target_site = &g_array_index (target_sites, MirbookingTargetSite, 0); target_site < &g_array_index (target_sites, MirbookingTargetSite, target_sites->len); target_site++) { // recompute each time the target changes if (cur_target != target_site->target) { cur_target = target_site->target; target_quantity = mirbooking_broker_get_sequence_quantity (mirbooking, MIRBOOKING_SEQUENCE (target_site->target)); } // report individual occupants GSList *occupants; for (occupants = target_site->occupants; occupants != NULL; occupants = occupants->next) { MirbookingOccupant *occupant = occupants->data; g_autofree gchar* line = g_strdup_printf ("%s\t%s\t%s\t%s\t%e\t%lu\t%s\t%s\t%e\t%e\t%e\n", COALESCE (mirbooking_sequence_get_gene_accession (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), COALESCE (mirbooking_sequence_get_gene_name (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (target_site->target)), COALESCE (mirbooking_sequence_get_name (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), target_quantity, target_site->position + 1, // 1-based mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (occupant->mirna)), COALESCE (mirbooking_sequence_get_name (MIRBOOKING_SEQUENCE (occupant->mirna)), "N/A"), mirbooking_broker_get_sequence_quantity (mirbooking, MIRBOOKING_SEQUENCE (occupant->mirna)) + mirbooking_broker_get_bound_mirna_quantity (mirbooking, occupant->mirna), MIRBOOKING_SCORE_KM (occupant->score) + (mirbooking_broker_get_target_site_kother (mirbooking, target_site) / occupant->score.kf), mirbooking_broker_get_occupant_quantity (mirbooking, occupant)); if (!g_data_output_stream_put_string (output_f, line, NULL, error)) { return FALSE; } } } return TRUE; } static gboolean write_output_to_tsv_detailed (MirbookingBroker *mirbooking, GOutputStream *out, GError **error) { g_autoptr (GDataOutputStream) output_f = g_data_output_stream_new (out); gchar *header = "gene_accession\t" "gene_name\t" "target_accession\t" "target_name\t" "target_quantity\t" "position\t" "mirna_accession\t" "mirna_name\t" "mirna_quantity\t" "kf\t" "kr\t" "kcleave\t" "krelease\t" "kcat\t" "kother\t" "kd\t" "km\t" "quantity\n"; if (!g_data_output_stream_put_string (output_f, header, NULL, error)) { return FALSE; } const GArray *target_sites = mirbooking_broker_get_target_sites (mirbooking); gfloat target_quantity = 0; const MirbookingTargetSite *target_site; MirbookingTarget *cur_target = NULL; for (target_site = &g_array_index (target_sites, MirbookingTargetSite, 0); target_site < &g_array_index (target_sites, MirbookingTargetSite, target_sites->len); target_site++) { // recompute each time the target changes if (cur_target != target_site->target) { cur_target = target_site->target; target_quantity = mirbooking_broker_get_sequence_quantity (mirbooking, MIRBOOKING_SEQUENCE (target_site->target)); } // report individual occupants GSList *occupants; for (occupants = target_site->occupants; occupants != NULL; occupants = occupants->next) { MirbookingOccupant *occupant = occupants->data; g_autofree gchar *line = g_strdup_printf ("%s\t%s\t%s\t%s\t%e\t%lu\t%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\n", COALESCE (mirbooking_sequence_get_gene_accession (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), COALESCE (mirbooking_sequence_get_gene_name (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (target_site->target)), COALESCE (mirbooking_sequence_get_name (MIRBOOKING_SEQUENCE (target_site->target)), "N/A"), target_quantity, target_site->position + 1, // 1-based mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (occupant->mirna)), COALESCE (mirbooking_sequence_get_name (MIRBOOKING_SEQUENCE (occupant->mirna)), "N/A"), mirbooking_broker_get_sequence_quantity (mirbooking, MIRBOOKING_SEQUENCE (occupant->mirna)) + mirbooking_broker_get_bound_mirna_quantity (mirbooking, occupant->mirna), occupant->score.kf, occupant->score.kr, occupant->score.kcleave, occupant->score.krelease, occupant->score.kcat, mirbooking_broker_get_target_site_kother (mirbooking, target_site), MIRBOOKING_SCORE_KD (occupant->score), MIRBOOKING_SCORE_KM (occupant->score) + (mirbooking_broker_get_target_site_kother (mirbooking, target_site) / occupant->score.kf), mirbooking_broker_get_occupant_quantity (mirbooking, occupant)); if (!g_data_output_stream_put_string (output_f, line, NULL, error)) { return FALSE; } } } return TRUE; } static gboolean write_output_to_gff3 (MirbookingBroker *mirbooking, GOutputStream *out, GError **error) { g_autoptr (GDataOutputStream) output_f = g_data_output_stream_new (out); if (!g_data_output_stream_put_string (output_f, "##gff-version 3\n", NULL, error)) { return FALSE; } const GArray *target_sites = mirbooking_broker_get_target_sites (mirbooking); gint i = 1; const MirbookingTargetSite *target_site; for (target_site = &g_array_index (target_sites, MirbookingTargetSite, 0); target_site < &g_array_index (target_sites, MirbookingTargetSite, target_sites->len); target_site++) { // report individual occupants GSList *occupants; for (occupants = target_site->occupants; occupants != NULL; occupants = occupants->next) { // the sequence ontology for 'miRNA_target_site' is 'SO:0000934' MirbookingOccupant *occupant = occupants->data; g_autofree gchar *line = g_strdup_printf ("%s\tmiRBooking\tmiRNA_target_site\t%lu\t%lu\t%e\t.\t.\tID=%d;Name=%s;Alias=%s\n", mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (target_site->target)), (gsize) MAX (1, (gssize) target_site->position + 1 - (gssize) mirbooking->priv->prime5_footprint), MIN (mirbooking_sequence_get_sequence_length (MIRBOOKING_SEQUENCE (target_site->target)), target_site->position + 1 + mirbooking->priv->prime3_footprint), mirbooking_broker_get_occupant_quantity (mirbooking, occupant), i++, mirbooking_sequence_get_name (MIRBOOKING_SEQUENCE (occupant->mirna)), mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (occupant->mirna))); if (!g_data_output_stream_put_string (output_f, line, NULL, error)) { return FALSE; } } } return TRUE; } static gboolean write_output_to_wiggle (MirbookingBroker *broker, GOutputStream *out, GError **error) { g_autoptr (GDataOutputStream) output_f = g_data_output_stream_new (out); const GArray *target_sites = mirbooking_broker_get_target_sites (broker); if (!g_data_output_stream_put_string (output_f, "track type=wiggle_0\n", NULL, error)) { return FALSE; } MirbookingTarget *target = NULL; const MirbookingTargetSite *target_site; for (target_site = &g_array_index (target_sites, MirbookingTargetSite, 0); target_site < &g_array_index (target_sites, MirbookingTargetSite, target_sites->len); target_site++) { if (target != target_site->target) { g_autofree gchar *line = g_strdup_printf ("variableStep chrom=%s\n", mirbooking_sequence_get_accession (MIRBOOKING_SEQUENCE (target_site->target))); if (!g_data_output_stream_put_string (output_f, line, NULL, error)) { return FALSE; } target = target_site->target; } gdouble St = mirbooking_broker_get_sequence_quantity (broker, MIRBOOKING_SEQUENCE (target_site->target)); gdouble Stp = mirbooking_broker_get_target_site_occupants_quantity (broker, target_site); // only report positions with activity if (Stp > 0) { g_autofree gchar *line = g_strdup_printf ("%lu %f\n", target_site->position + 1, Stp / St); if (!g_data_output_stream_put_string (output_f, line, NULL, error)) { return FALSE; } } } return TRUE; } typedef struct _MirbookingBrokerOutputFormatMeta { MirbookingBrokerOutputFormat output_format; const gchar *nick; gboolean (*write) (MirbookingBroker *broker, GOutputStream *output, GError **error); } MirbookingBrokerOutputFormatMeta; static const MirbookingBrokerOutputFormatMeta OUTPUT_FORMAT_META[] = { {MIRBOOKING_BROKER_OUTPUT_FORMAT_TSV, "tsv", write_output_to_tsv}, {MIRBOOKING_BROKER_OUTPUT_FORMAT_TSV_DETAILED, "tsv-detailed", write_output_to_tsv_detailed}, {MIRBOOKING_BROKER_OUTPUT_FORMAT_GFF3, "gff3", write_output_to_gff3}, {MIRBOOKING_BROKER_OUTPUT_FORMAT_WIG, "wig", write_output_to_wiggle} }; gboolean mirbooking_broker_write_output_to_stream (MirbookingBroker *self, GOutputStream *out, MirbookingBrokerOutputFormat output_format, GError **error) { g_return_val_if_fail (self->priv->init, FALSE); gsize i; for (i = 0; i < sizeof (OUTPUT_FORMAT_META); i++) { if (OUTPUT_FORMAT_META[i].output_format == output_format) { return OUTPUT_FORMAT_META[i].write (self, out, error); } } g_return_val_if_reached (FALSE); } gboolean mirbooking_broker_write_output_to_file (MirbookingBroker *self, GFile *output_file, MirbookingBrokerOutputFormat output_format, GError **error) { g_autoptr (GOutputStream) out = G_OUTPUT_STREAM (g_file_replace (output_file, NULL, FALSE, G_FILE_CREATE_NONE, NULL, error)); g_return_val_if_fail (out != NULL, FALSE); return mirbooking_broker_write_output_to_stream (self, out, output_format, error); }
{ "alphanum_fraction": 0.5531917468, "avg_line_length": 37.5784447476, "ext": "c", "hexsha": "ddba8ed578a45947ff59e57f64add76b6829f71d", "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": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "major-lab/mirbooking", "max_forks_repo_path": "src/mirbooking-broker.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "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": "major-lab/mirbooking", "max_issues_repo_path": "src/mirbooking-broker.c", "max_line_length": 221, "max_stars_count": null, "max_stars_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "major-lab/mirbooking", "max_stars_repo_path": "src/mirbooking-broker.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 18336, "size": 82635 }
/* histogram/file2d.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 <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_block.h> #include <gsl/gsl_histogram2d.h> int gsl_histogram2d_fread (FILE * stream, gsl_histogram2d * h) { int status = gsl_block_raw_fread (stream, h->xrange, h->nx + 1, 1); if (status) return status; status = gsl_block_raw_fread (stream, h->yrange, h->ny + 1, 1); if (status) return status; status = gsl_block_raw_fread (stream, h->bin, h->nx * h->ny, 1); return status; } int gsl_histogram2d_fwrite (FILE * stream, const gsl_histogram2d * h) { int status = gsl_block_raw_fwrite (stream, h->xrange, h->nx + 1, 1); if (status) return status; status = gsl_block_raw_fwrite (stream, h->yrange, h->ny + 1, 1); if (status) return status; status = gsl_block_raw_fwrite (stream, h->bin, h->nx * h->ny, 1); return status; } int gsl_histogram2d_fprintf (FILE * stream, const gsl_histogram2d * h, const char *range_format, const char *bin_format) { size_t i, j; const size_t nx = h->nx; const size_t ny = h->ny; int status; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { status = fprintf (stream, range_format, h->xrange[i]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, range_format, h->xrange[i + 1]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, range_format, h->yrange[j]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, range_format, h->yrange[j + 1]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc (' ', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } status = fprintf (stream, bin_format, h->bin[i * ny + j]); if (status < 0) { GSL_ERROR ("fprintf failed", GSL_EFAILED); } status = putc ('\n', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } } status = putc ('\n', stream); if (status == EOF) { GSL_ERROR ("putc failed", GSL_EFAILED); } } return GSL_SUCCESS; } int gsl_histogram2d_fscanf (FILE * stream, gsl_histogram2d * h) { size_t i, j; const size_t nx = h->nx; const size_t ny = h->ny; double xupper, yupper; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { int status = fscanf (stream, "%lg %lg %lg %lg %lg", h->xrange + i, &xupper, h->yrange + j, &yupper, h->bin + i * ny + j); if (status != 5) { GSL_ERROR ("fscanf failed", GSL_EFAILED); } } h->yrange[ny] = yupper; } h->xrange[nx] = xupper; return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5276793623, "avg_line_length": 24.4108108108, "ext": "c", "hexsha": "26877840a3a3ee6e8d33010064c0721ca846e0d6", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/file2d.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/histogram/file2d.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/histogram/file2d.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": 1199, "size": 4516 }
/** * * @file testing_cgetri.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @date 2010-11-15 * @generated c Tue Jan 7 11:45:17 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_cmain.h" static int check_factorization(int, PLASMA_Complex32_t*, PLASMA_Complex32_t*, int, int*, float); static int check_inverse(int, PLASMA_Complex32_t *, PLASMA_Complex32_t *, int, int*, float); int testing_cgetri(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 2){ USAGE("GETRI", "N LDA", " - N : the size of the matrix\n" " - LDA : leading dimension of the matrix A\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); float eps; int info_inverse, info_factorization; int i, j; PLASMA_Complex32_t *A1 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *A2 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *WORK = (PLASMA_Complex32_t *)malloc(2*LDA*sizeof(PLASMA_Complex32_t)); float *D = (float *)malloc(LDA*sizeof(float)); int *IPIV = (int *)malloc(N*sizeof(int)); /* Check if unable to allocate memory */ if ( (!A1) || (!A2) || (!IPIV) ){ printf("Out of Memory \n "); return -2; } eps = LAPACKE_slamch_work('e'); /*------------------------------------------------------------- * TESTING CGETRI */ /* Initialize A1 and A2 Matrix */ PLASMA_cplrnt(N, N, A1, LDA, 3453); for ( i = 0; i < N; i++) for ( j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i]; printf("\n"); printf("------ TESTS FOR PLASMA CGETRI ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* PLASMA CGETRF */ PLASMA_cgetrf(N, N, A2, LDA, IPIV); /* Check the factorization */ info_factorization = check_factorization( N, A1, A2, LDA, IPIV, eps); /* PLASMA CGETRI */ PLASMA_cgetri(N, A2, LDA, IPIV); /* Check the inverse */ info_inverse = check_inverse(N, A1, A2, LDA, IPIV, eps); if ( (info_inverse == 0) && (info_factorization == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING CGETRI ..................... PASSED !\n"); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING CGETRI ... FAILED !\n"); printf("***************************************************\n"); } free(A1); free(A2); free(IPIV); free(WORK); free(D); return 0; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ static int check_factorization(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int *IPIV, float eps) { int info_factorization; float Rnorm, Anorm, Xnorm, Bnorm, result; PLASMA_Complex32_t alpha, beta; alpha = 1.0; beta = -1.0; PLASMA_Complex32_t *b = (PLASMA_Complex32_t *)malloc(LDA*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *x = (PLASMA_Complex32_t *)malloc(LDA*sizeof(PLASMA_Complex32_t)); LAPACKE_clarnv_work(1, ISEED, LDA, x); LAPACKE_clacpy_work(LAPACK_COL_MAJOR, 'A', N, 1, x, LDA, b, LDA); PLASMA_cgetrs( PlasmaNoTrans, N, 1, A2, LDA, IPIV, x, LDA ); Xnorm = PLASMA_clange(PlasmaInfNorm, N, 1, x, LDA); Anorm = PLASMA_clange(PlasmaInfNorm, N, N, A1, LDA); Bnorm = PLASMA_clange(PlasmaInfNorm, N, 1, b, LDA); PLASMA_cgemm( PlasmaNoTrans, PlasmaNoTrans, N, 1, N, alpha, A1, LDA, x, LDA, beta, b, LDA); Rnorm = PLASMA_clange(PlasmaInfNorm, N, 1, b, LDA); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- The factorization is CORRECT ! \n"); info_factorization = 0; } free(x); free(b); return info_factorization; } /*------------------------------------------------------------------------ * Check the accuracy of the computed inverse */ static int check_inverse(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int *IPIV, float eps ) { int info_inverse; int i; float Rnorm, Anorm, Ainvnorm, result; PLASMA_Complex32_t alpha, beta, zone; PLASMA_Complex32_t *work = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t)); alpha = -1.0; beta = 0.0; zone = 1.0; PLASMA_cgemm( PlasmaNoTrans, PlasmaNoTrans, N, N, N, alpha, A2, LDA, A1, LDA, beta, work, N); /* Add the identity matrix to work */ for(i=0; i<N; i++) *(work+i+i*N) = *(work+i+i*N) + zone; Rnorm = PLASMA_clange(PlasmaInfNorm, N, N, work, N); Anorm = PLASMA_clange(PlasmaInfNorm, N, N, A1, LDA); Ainvnorm = PLASMA_clange(PlasmaInfNorm, N, N, A2, LDA); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_1=%f\n||Ainv||_1=%f\n||Id - A*Ainv||_1=%e\n", Anorm, Ainvnorm, Rnorm ); result = Rnorm / ( (Anorm*Ainvnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the inverse \n"); printf("-- ||Id - A*Ainv||_1/((||A||_1||Ainv||_1).N.eps) = %e \n", result); if ( isnan(Ainvnorm) || isinf(Ainvnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The inverse is suspicious ! \n"); info_inverse = 1; } else{ printf("-- The inverse is CORRECT ! \n"); info_inverse = 0; } free(work); return info_inverse; }
{ "alphanum_fraction": 0.553445956, "avg_line_length": 32.4708737864, "ext": "c", "hexsha": "c4b0388aff715bada41a65b25fff54f0f0076ffc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_cgetri.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_cgetri.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_cgetri.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2143, "size": 6689 }
#ifndef __GSL_PERMUTE_VECTOR_H__ #define __GSL_PERMUTE_VECTOR_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <gsl/gsl_permute_vector_complex_long_double.h> #include <gsl/gsl_permute_vector_complex_double.h> #include <gsl/gsl_permute_vector_complex_float.h> #include <gsl/gsl_permute_vector_long_double.h> #include <gsl/gsl_permute_vector_double.h> #include <gsl/gsl_permute_vector_float.h> #include <gsl/gsl_permute_vector_ulong.h> #include <gsl/gsl_permute_vector_long.h> #include <gsl/gsl_permute_vector_uint.h> #include <gsl/gsl_permute_vector_int.h> #include <gsl/gsl_permute_vector_ushort.h> #include <gsl/gsl_permute_vector_short.h> #include <gsl/gsl_permute_vector_uchar.h> #include <gsl/gsl_permute_vector_char.h> #endif /* __GSL_PERMUTE_VECTOR_H__ */
{ "alphanum_fraction": 0.8053830228, "avg_line_length": 27.6, "ext": "h", "hexsha": "71604c9c4f25318fb578c4fa4bd7b66c1a13dacb", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_line_length": 55, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_permute_vector.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 272, "size": 966 }
#ifndef H_MATH_UTILS_GSL #define H_MATH_UTILS_GSL #include <gsl/gsl_math.h> //#include <egsl/egsl.h> #include </home/alecone/catkin_graph/src/csm/sm/lib/egsl/egsl.h> #include "laser_data.h" #define gvg gsl_vector_get #define gvs gsl_vector_set /* GSL stuff */ const char* gsl_friendly_pose(gsl_vector*v); gsl_vector * vector_from_array(unsigned int n, double *x); void vector_to_array(const gsl_vector*v, double*); void copy_from_array(gsl_vector*v, double*); void oplus(const gsl_vector*x1,const gsl_vector*x2, gsl_vector*res); void ominus(const gsl_vector*x, gsl_vector*res); void pose_diff(const gsl_vector*pose2,const gsl_vector*pose1,gsl_vector*res); void transform(const gsl_vector* point2d, const gsl_vector* pose, gsl_vector*result2d); void gsl_vector_set_nan(gsl_vector*v); double distance(const gsl_vector* a,const gsl_vector* b); double distance_squared(const gsl_vector* a,const gsl_vector* b); /** Returns norm of 2D point p */ double norm(const gsl_vector*p); const char* egsl_friendly_pose(val pose); const char* egsl_friendly_cov(val cov); /** Returns Fisher's information matrix. You still have to multiply it by (1/sigma^2). */ val ld_fisher0(LDP ld); #endif
{ "alphanum_fraction": 0.7661157025, "avg_line_length": 28.1395348837, "ext": "h", "hexsha": "eb3abad94559292b9ad721189eeb177077854167", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/csm/math_utils_gsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/csm/math_utils_gsl.h", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/csm/math_utils_gsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 317, "size": 1210 }
/* specfunc/bessel_Jnu.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, 2017 Konrad Griessinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_sincos_pi.h> #include "error.h" #include "bessel.h" #include "bessel_olver.h" #include "bessel_temme.h" /* Evaluate at large enough nu to apply asymptotic * results and apply backward recurrence. */ #if 0 static int bessel_J_recur_asymp(const double nu, const double x, gsl_sf_result * Jnu, gsl_sf_result * Jnup1) { const double nu_cut = 25.0; int n; int steps = ceil(nu_cut - nu) + 1; gsl_sf_result r_Jnp1; gsl_sf_result r_Jn; int stat_O1 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps + 1.0, x, &r_Jnp1); int stat_O2 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps, x, &r_Jn); double r_fe = fabs(r_Jnp1.err/r_Jnp1.val) + fabs(r_Jn.err/r_Jn.val); double Jnp1 = r_Jnp1.val; double Jn = r_Jn.val; double Jnm1; double Jnp1_save; for(n=steps; n>0; n--) { Jnm1 = 2.0*(nu+n)/x * Jn - Jnp1; Jnp1 = Jn; Jnp1_save = Jn; Jn = Jnm1; } Jnu->val = Jn; Jnu->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jn); Jnup1->val = Jnp1_save; Jnup1->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jnp1_save); return GSL_ERROR_SELECT_2(stat_O1, stat_O2); } #endif /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_Jnupos_e(const double nu, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x == 0.0) { if(nu == 0.0) { result->val = 1.0; result->err = 0.0; } else { result->val = 0.0; result->err = 0.0; } return GSL_SUCCESS; } else if(x*x < 10.0*(nu+1.0)) { return gsl_sf_bessel_IJ_taylor_e(nu, x, -1, 100, GSL_DBL_EPSILON, result); } else if(nu > 50.0) { return gsl_sf_bessel_Jnu_asymp_Olver_e(nu, x, result); } else if(x > 1000.0) { /* We need this to avoid feeding large x to CF1; note that * due to the above check, we know that n <= 50. See similar * block in bessel_Jn.c. */ return gsl_sf_bessel_Jnu_asympx_e(nu, x, result); } else { /* -1/2 <= mu <= 1/2 */ int N = (int)(nu + 0.5); double mu = nu - N; /* Determine the J ratio at nu. */ double Jnup1_Jnu; double sgn_Jnu; const int stat_CF1 = gsl_sf_bessel_J_CF1(nu, x, &Jnup1_Jnu, &sgn_Jnu); if(x < 2.0) { /* Determine Y_mu, Y_mup1 directly and recurse forward to nu. * Then use the CF1 information to solve for J_nu and J_nup1. */ gsl_sf_result Y_mu, Y_mup1; const int stat_mu = gsl_sf_bessel_Y_temme(mu, x, &Y_mu, &Y_mup1); double Ynm1 = Y_mu.val; double Yn = Y_mup1.val; double Ynp1 = 0.0; int n; for(n=1; n<N; n++) { Ynp1 = 2.0*(mu+n)/x * Yn - Ynm1; Ynm1 = Yn; Yn = Ynp1; } result->val = 2.0/(M_PI*x) / (Jnup1_Jnu*Yn - Ynp1); result->err = GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_mu, stat_CF1); } else { /* Recurse backward from nu to mu, determining the J ratio * at mu. Use this together with a Steed method CF2 to * determine the actual J_mu, and thus obtain the normalization. */ double Jmu; double Jmup1_Jmu; double sgn_Jmu; double Jmuprime_Jmu; double P, Q; const int stat_CF2 = gsl_sf_bessel_JY_steed_CF2(mu, x, &P, &Q); double gamma; double Jnp1 = sgn_Jnu * GSL_SQRT_DBL_MIN * Jnup1_Jnu; double Jn = sgn_Jnu * GSL_SQRT_DBL_MIN; double Jnm1; int n; for(n=N; n>0; n--) { Jnm1 = 2.0*(mu+n)/x * Jn - Jnp1; Jnp1 = Jn; Jn = Jnm1; } Jmup1_Jmu = Jnp1/Jn; sgn_Jmu = GSL_SIGN(Jn); Jmuprime_Jmu = mu/x - Jmup1_Jmu; gamma = (P - Jmuprime_Jmu)/Q; Jmu = sgn_Jmu * sqrt(2.0/(M_PI*x) / (Q + gamma*(P-Jmuprime_Jmu))); result->val = Jmu * (sgn_Jnu * GSL_SQRT_DBL_MIN) / Jn; result->err = 2.0 * GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_CF2, stat_CF1); } } } int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if (nu < 0.0) { int Jstatus = gsl_sf_bessel_Jnupos_e(-nu, x, result); double Jval = result->val; double Jerr = result->err; int Ystatus = gsl_sf_bessel_Ynupos_e(-nu, x, result); double Yval = result->val; double Yerr = result->err; /* double s = sin(M_PI*nu), c = cos(M_PI*nu); */ int sinstatus = gsl_sf_sin_pi_e(nu, result); double s = result->val; double serr = result->err; int cosstatus = gsl_sf_cos_pi_e(nu, result); double c = result->val; double cerr = result->err; result->val = s*Yval + c*Jval; result->err = fabs(c*Yerr) + fabs(s*Jerr) + fabs(cerr*Yval) + fabs(serr*Jval); return GSL_ERROR_SELECT_4(Jstatus, Ystatus, sinstatus, cosstatus); } else return gsl_sf_bessel_Jnupos_e(nu, x, result); } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_Jnu(const double nu, const double x) { EVAL_RESULT(gsl_sf_bessel_Jnu_e(nu, x, &result)); }
{ "alphanum_fraction": 0.6188850967, "avg_line_length": 28.8873239437, "ext": "c", "hexsha": "aa219bd914d95cf53c98bbfdc148050c5de846c9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/specfunc/bessel_Jnu.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/specfunc/bessel_Jnu.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Jnu.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": 2135, "size": 6153 }
#pragma once #include "options.h" #include <cstdio> #include <fmt/color.h> #include <fmt/printf.h> #include <gsl/gsl-lite.hpp> namespace angonoka::cli { /** Print text to stdout if not in quiet mode. @param options CLI options */ template <typename... T> void print( const Options& options, fmt::format_string<T...> fmt, T&&... args) { if (options.quiet) return; fmt::print(fmt, std::forward<T>(args)...); } /** Prints red text. Conditionally disables the color depending on CLI options. @param options CLI options */ template <typename... T> void print_error( const Options& options, std::FILE* output, fmt::format_string<T...> fmt, T&&... args) { if (options.color) { fmt::print( output, fg(fmt::terminal_color::red), fmt::string_view{fmt}, std::forward<T>(args)...); } else { fmt::print(output, fmt, std::forward<T>(args)...); } } /** Critical error message. Used for progress messages with ellipsis like Progress message... <die()>Error An error has occured. @param options CLI options */ template <typename... T> void die( const Options& options, fmt::format_string<T...> fmt, T&&... args) { if (!options.quiet) print_error(options, stdout, "Error\n"); print_error(options, stderr, fmt, std::forward<T>(args)...); } } // namespace angonoka::cli
{ "alphanum_fraction": 0.6047320807, "avg_line_length": 19.9583333333, "ext": "h", "hexsha": "c9eea6fe2582875dbe0e6b7105b93d0947ef6599", "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": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_path": "src/cli/utils.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_path": "src/cli/utils.h", "max_line_length": 64, "max_stars_count": 2, "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_path": "src/cli/utils.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "num_tokens": 363, "size": 1437 }
/* How to use blas and lapack with the standard interfaces provided by their respective projects, repectively through `cblas.h` and `lapacke.h` */ #include <assert.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <cblas.h> #include <lapacke.h> /** * assert two integers are equal * if not, print them to stderr and assert false */ void assert_eqi(int i1, int i2) { if (i1 != i2) { fprintf(stderr, "%d\n%d\n\n\n", i1, i2); assert(false); } } /** * assert two doubles are equal within err precision * if not, print them to stderr */ void assert_eqd(double d1, double d2, double err) { if (fabs(d1 - d2) > err) { fprintf(stderr, "%f\n%f\n\n\n", d1, d2); assert(false); } } /** print an array of doubles to stderr */ void print_vecd(int n, double * v) { int i; for (i=0; i<n; i++) { fprintf(stderr, "%.2f ", v[i]); } printf("\n"); } /* bool eq_vecd2(int n, double * v1, double * v2, double err) { if(fabs(d1 - d2) > err) return false return true; } void assert_eqvd(int n, double * v1, double * v2, double err){ if(eq_vecd(n, v1, v2, err) != true){ print_vecd(n, v1); print_vecd(n, v2); } } */ int main(void) { int info, ipiv2[2]; float err = 1e-6; float x2[2], b2[2], c2[2]; float a2x2[2][2]; /* cblas */ { x2[0] = 1.0; x2[1] = -2.0; assert_eqd(cblas_snrm2(2, x2, 1), sqrt(5.0), err); } /* lapacke */ { /* sgesv Matrix vector multiply. */ { a2x2[0][0] = 1.0; a2x2[1][0] = 2.0; a2x2[0][1] = 3.0; a2x2[1][1] = 4.0; b2[0] = 5.; b2[1] = 11.; info = LAPACKE_sgesv( LAPACK_COL_MAJOR, 2, 1, &a2x2[0][0], 2, &ipiv2[0], &b2[0], 2 ); c2[0] = 1.0; c2[1] = 2.0; assert_eqi(info, 0); assert_eqd(b2[0], c2[0], err); assert_eqd(b2[1], c2[1], err); } } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5363128492, "avg_line_length": 17.7387387387, "ext": "c", "hexsha": "0d37554076a40f5c114f8d8e0dc95db158ee77b2", "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/lapack/c.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/lapack/c.c", "max_line_length": 69, "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/lapack/c.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": 746, "size": 1969 }
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~* ** ** ** This file forms part of the Underworld geophysics modelling application. ** ** ** ** For full license and copyright information, please refer to the LICENSE.md file ** ** located at the project root, or contact the authors. ** ** ** **~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/ #include <petsc.h> #include <petscmat.h> #include "common-driver-utils.h" #include <StGermain/libStGermain/src/StGermain.h> #include <StgDomain/libStgDomain/src/StgDomain.h> #include <StgFEM/libStgFEM/src/StgFEM.h> #include <PICellerator/libPICellerator/src/PICellerator.h> #include <Underworld/libUnderworld/src/Underworld.h> #include "Solvers/SLE/src/SLE.h" /* to give the AugLagStokes_SLE type */ #include "Solvers/KSPSolvers/src/KSPSolvers.h" /* for __KSP_COMMON */ #include "BSSCR.h" #include "writeMatVec.h" #if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR==0) ) #define FILE_OPTION PETSC_FILE_RDONLY #endif #if( (PETSC_VERSION_MAJOR==2) && (PETSC_VERSION_MINOR==3) && (PETSC_VERSION_SUBMINOR>=2) ) #define FILE_OPTION FILE_MODE_READ #endif #if( PETSC_VERSION_MAJOR==3 ) #define FILE_OPTION FILE_MODE_READ #endif PetscErrorCode BSSCR_FormSchurApproximation1( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym ); PetscErrorCode BSSCR_FormSchurApproximationDiag( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym ); PetscErrorCode BSSCR_BSSCR_StokesReadPCSchurMat_binary( MPI_Comm comm, Mat *S ) { PetscViewer mat_view_file; char op_name[PETSC_MAX_PATH_LEN]; PetscTruth flg; PetscOptionsGetString( PETSC_NULL,"-stokes_Smat",op_name,PETSC_MAX_PATH_LEN-1,&flg ); *S = PETSC_NULL; if (flg) { if (!S) Stg_SETERRQ(1,"Memory space for Smat is NULL"); PetscViewerBinaryOpen( comm, op_name, FILE_OPTION, &mat_view_file ); Stg_MatLoad( mat_view_file, MATAIJ, S ); Stg_PetscViewerDestroy(&mat_view_file ); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_BSSCR_StokesReadPCSchurMat_ascii( MPI_Comm comm, Mat *S ) { char op_name[PETSC_MAX_PATH_LEN]; PetscTruth flg; PetscOptionsGetString( PETSC_NULL,"-stokes_Smat",op_name,PETSC_MAX_PATH_LEN-1,&flg ); *S = PETSC_NULL; if (flg) { if (!S) Stg_SETERRQ(1,"Memory space for Smat is NULL"); Stg_SETERRQ(1,"Currently Disabled"); //MatAIJLoad_MatrixMarket( comm, op_name, S ); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_StokesReadPCSchurMat( MPI_Comm comm, Mat *S ) { char op_name[PETSC_MAX_PATH_LEN]; PetscTruth flg; PetscOptionsGetString( PETSC_NULL,"-stokes_ascii",op_name,PETSC_MAX_PATH_LEN-1,&flg ); if (flg==PETSC_TRUE) { BSSCR_BSSCR_StokesReadPCSchurMat_ascii( comm, S ); } else { BSSCR_BSSCR_StokesReadPCSchurMat_binary( comm, S ); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_StokesCreatePCSchur( Mat K, Mat G, PC pc_S ) { char pc_type[PETSC_MAX_PATH_LEN]; PetscTruth flg; PetscOptionsGetString( PETSC_NULL, "-Q22_pc_type", pc_type, PETSC_MAX_PATH_LEN-1, &flg ); if( !flg ) { Stg_SETERRQ( PETSC_ERR_SUP, "OPTION: -Q22_pc_type must be set" ); } /* 1. define S pc to be "none" */ if( strcmp(pc_type,"none")==0 ) { /* none */ PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"none\" \n" ); PCSetType( pc_S, "none" ); } else if( strcmp(pc_type,"uw")==0 ) { /* diag */ Mat S, Amat; MatStructure mstruct; MPI_Comm comm; PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"uw\" \n" ); PetscObjectGetComm( (PetscObject)pc_S, &comm ); S = PETSC_NULL; BSSCR_StokesReadPCSchurMat( comm, &S ); if (!S) { Stg_SETERRQ(1,"Must indicate location of file for SchurPC matrix with the stokes_Smat option"); } Stg_PCGetOperators( pc_S, &Amat, &Amat, &mstruct ); Stg_PCSetOperators( pc_S, Amat, S, SAME_NONZERO_PATTERN ); MatView( S, PETSC_VIEWER_STDOUT_WORLD ); } else { /* not valid option */ Stg_SETERRQ( PETSC_ERR_SUP, "OPTION: -seg_schur_pc_type is not valid" ); } PetscFunctionReturn(0); } PetscErrorCode BSSCR_BSSCR_StokesCreatePCSchur2( Mat K, Mat G, Mat D, Mat C, Mat Smat, PC pc_S, PetscTruth sym, KSP_BSSCR * bsscrp ) { char pc_type[PETSC_MAX_PATH_LEN]; PetscTruth flg; PetscOptionsGetString( PETSC_NULL, "-Q22_pc_type", pc_type, PETSC_MAX_PATH_LEN-1, &flg ); if( !flg ) { strcpy(pc_type, "uw"); //Stg_SETERRQ( PETSC_ERR_SUP, "OPTION: -Q22_pc_type must be set" ); } /* 1. define S pc to be "none" */ if( strcmp(pc_type,"none")==0 ) { /* none */ /* Mat Amat,Pmat; */ /* MatStructure mstruct; */ PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"none\" \n" ); /* PCGetOperators( pc_S, &Amat, &Pmat, &mstruct ); */ /* PCSetOperators( pc_S, Amat, Amat, SAME_NONZERO_PATTERN ); */ PCSetType( pc_S, "none" ); } else if( strcmp(pc_type,"uw")==0 ) { /* diag */ Mat Amat,Pmat; MatStructure mstruct; PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"uw\" \n" ); if (!Smat) { Stg_SETERRQ(1,"Smat cannot be NULL if -Q22_pc_type = uw"); } Stg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct ); Stg_PCSetOperators( pc_S, Amat, Smat, SAME_NONZERO_PATTERN ); } else if( strcmp(pc_type,"uwscale")==0 ) { /* diag */ Mat Amat, Shat, Pmat; MatStructure mstruct; PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"uwscale\" \n" ); if (!Smat) { Stg_SETERRQ(1,"Smat cannot be NULL if -Q22_pc_type = uwscale"); } BSSCR_FormSchurApproximation1( K, G, D, C, &Shat, sym ); Stg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct ); Stg_PCSetOperators( pc_S, Amat, Shat, SAME_NONZERO_PATTERN ); Stg_MatDestroy(&Shat); } else if( strcmp(pc_type,"gkgdiag")==0 ) { /* diag */ Mat Amat, Shat, Pmat; MatStructure mstruct; PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"gkgdiag\" \n" ); if (!Smat) { Stg_SETERRQ(1,"Smat cannot be NULL if -Q22_pc_type = uwscale"); } BSSCR_FormSchurApproximationDiag( K, G, D, C, &Shat, sym ); Stg_PCGetOperators( pc_S, &Amat, &Pmat, &mstruct ); Stg_PCSetOperators( pc_S, Amat, Shat, SAME_NONZERO_PATTERN ); Stg_MatDestroy(&Shat); } else if( strcmp(pc_type,"gtkg")==0 ) { /* GtKG */ PetscPrintf(PETSC_COMM_WORLD," Setting schur_pc to \"gtkg\" \n" ); /* Build the schur pc GtKG */ PCSetType( pc_S, "gtkg" ); //AugLagStokes_SLE * stokesSLE = (AugLagStokes_SLE*)bsscrp->st_sle; StokesBlockKSPInterface* Solver = bsscrp->solver; Mat M=0; if (Solver->vmStiffMat){ M = Solver->vmStiffMat->matrix; } BSSCR_PCGtKGSet_Operators( pc_S, K, G, M ); //BSSCR_PCGtKGAttachNullSpace( pc_S ); } else { /* not valid option */ Stg_SETERRQ( PETSC_ERR_SUP, "OPTION: -Q22_pc_type is not valid" ); } PetscFunctionReturn(0); } /* Recomended usage: Stg_KSPSetOperators( ksp_S, S, Shat, SAME_NONZERO_PATTERN ); KSPGetPC( ksp_S, &pc_S ); PCSetType( pc_S, "jacobi" ); NOTE: In pracise "jacobi" works better than keep the entire matrix and factoring it using something like "cholesky" */ PetscErrorCode BSSCR_FormSchurApproximation1( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym ) { Mat Shat, A21_cpy; Vec diag; MatGetVecs( A11, &diag, PETSC_NULL ); MatGetDiagonal( A11, diag ); VecReciprocal( diag ); /* if( sym ) { */ /* #if( PETSC_VERSION_MAJOR <= 2 ) */ /* MatTranspose( A12, &A21_cpy ); */ /* #else */ /* MatTranspose( A12, MAT_INITIAL_MATRIX, &A21_cpy ); */ /* #endif */ /* MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); */ /* } */ /* else { */ MatDuplicate( A21, MAT_COPY_VALUES, &A21_cpy ); MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); /* } */ MatMatMult( A21_cpy, A12, MAT_INITIAL_MATRIX, 1.2, &Shat ); /* A21 diag(K)^{-1} A12 */ if( A22 != PETSC_NULL ) MatAXPY( Shat, -1.0, A22, DIFFERENT_NONZERO_PATTERN ); /* S <- -C + A21 diag(K)^{-1} A12 */ *(void**)_Shat = (void*)Shat; Stg_MatDestroy(&A21_cpy); Stg_VecDestroy(&diag); PetscFunctionReturn(0); } PetscErrorCode BSSCR_FormSchurApproximationDiag( Mat A11, Mat A12, Mat A21, Mat A22, Mat *_Shat, PetscTruth sym ) { Mat Shat, A21_cpy; Vec diag; MatGetVecs( A11, &diag, PETSC_NULL ); MatGetDiagonal( A11, diag ); VecReciprocal( diag ); /* if( sym ) { */ /* #if( PETSC_VERSION_MAJOR <= 2 ) */ /* MatTranspose( A12, &A21_cpy ); */ /* #else */ /* MatTranspose( A12, MAT_INITIAL_MATRIX, &A21_cpy ); */ /* #endif */ /* MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); */ /* } */ /* else { */ MatDuplicate( A21, MAT_COPY_VALUES, &A21_cpy ); MatDiagonalScale(A21_cpy, PETSC_NULL, diag ); /* } */ MatMatMult( A21_cpy, A12, MAT_INITIAL_MATRIX, 1.2, &Shat ); /* A21 diag(K)^{-1} A12 */ if( A22 != PETSC_NULL ) MatAXPY( Shat, -1.0, A22, DIFFERENT_NONZERO_PATTERN ); /* S <- -C + A21 diag(K)^{-1} A12 */ Stg_MatDestroy(&A21_cpy); Stg_VecDestroy(&diag); MatGetVecs( Shat, &diag, PETSC_NULL ); MatGetDiagonal( Shat, diag ); MatZeroEntries( Shat ); MatDiagonalSet( Shat, diag, INSERT_VALUES ); *(void**)_Shat = (void*)Shat; Stg_VecDestroy(&diag); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6495118846, "avg_line_length": 29.45, "ext": "c", "hexsha": "082d973755bf70ac924f065f7c749f947976c5e0", "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": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "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": "rbeucher/underworld2", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/preconditioner.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3256, "size": 9424 }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_randist.h> #include "allvars.h" #include "proto.h" void mcmc_con_run() { char fname_mcmc[100]; strcpy(fname_mcmc, "data/mcmc_con.txt"); printf("*******con mcmc\n"); mcmc_con_init(); if(flag_mcmc==1) { mcmc_sampling(fname_mcmc, &probability_con); mcmc_stats(fname_mcmc); } else { nc = nc_lim_low; printf("reading par.txt\n"); read_input(); } reconstruct_con(); memcpy(theta_best_con, theta_best, ntheta*sizeof(double)); memcpy(theta_best_var_con, theta_best_var, ntheta*2*sizeof(double)); } void mcmc_con_init() { int i; ntheta = 2; i=0; theta_range[i][0] = log(1.0e-6); theta_range[i++][1] = log(10.0); theta_range[i][0] = log(1.0e-2); theta_range[i++][1] = log(1.0e5); i = 0; theta_input[i++] = log(0.1); theta_input[i++] = log(100.0); i = 0; sigma_input[i++] = 0.1; sigma_input[i++] = 0.5; i = 0; theta_fixed[i++] = 0; theta_fixed[i++] = 0; } /* * probability for continuum mcmc. */ double probability_con(double *theta)//double sigmahat, double taud, double alpha) { double sigmahat, taud, alpha; double prob, prior, lndet, lndet_ICq, sigma; double *ybuf, *Larr, *Cq, *ICq, *ave, *yave, *ysub; int i, nq, info; nq = (flag_detrend + 1); ybuf = workspace; Larr = workspace+ncon_data; Cq = Larr + nq*ncon_data; ICq = Cq + nq*nq; ave = ICq + nq*nq; yave = ave + nq; ysub = yave + ncon_data; alpha = 1.0; sigmahat = exp(theta[0]); taud = exp(theta[1]); sigma = sigmahat * sqrt(taud / 2.0); set_covar_mat_con(sigma, taud, alpha); for(i=0;i<ncon_data*ncon_data; i++) { Cmat[i] = Smat[i] + Nmat[i]; } memcpy(ICmat, Cmat, ncon_data*ncon_data*sizeof(double)); inverse_mat(ICmat, ncon_data, &info); for(i=0;i<ncon_data;i++) { if(flag_detrend==0) { Larr[i]=1.0; } else { Larr[i*nq + 0] = 1.0; Larr[i*nq + 1] = Tcon_data[i]; } } //multiply_matvec(ICmat, Larr, ncon_data, ybuf); multiply_mat_MN(ICmat, Larr, Tmat1, ncon_data, nq, ncon_data); multiply_mat_MN_transposeA(Larr, Tmat1, ICq, nq, nq, ncon_data); memcpy(Cq, ICq, nq*nq*sizeof(double)); inverse_mat(Cq, nq, &info); multiply_mat_MN_transposeA(Larr, ICmat, Tmat1, nq, ncon_data, ncon_data); multiply_mat_MN(Cq, Tmat1, Tmat2, nq, ncon_data, nq); multiply_mat_MN(Tmat2, Fcon_data, ave, nq, 1, ncon_data); multiply_mat_MN(Larr, ave, yave, ncon_data, 1, nq); // lambda = cblas_ddot(ncon_data, Larr, 1, ybuf, 1); // multiply_matvec(ICmat, Fcon_data, ncon_data, ybuf); // ave_con = cblas_ddot(ncon_data, Larr, 1, ybuf, 1); // ave_con /=lambda; for(i=0;i<ncon_data;i++)ysub[i] = Fcon_data[i] - yave[i]; multiply_matvec(ICmat, ysub, ncon_data, ybuf); prob = -0.5 * cblas_ddot(ncon_data, ysub, 1, ybuf, 1); lndet = lndet_mat(Cmat, ncon_data, &info); lndet_ICq = lndet_mat(ICq, nq, &info); prob = prob - 0.5*lndet - 0.5*lndet_ICq; /* penalize on larger tau than the length of continuum */ prior = 0.0; prior += - theta[0]; if(theta[1] > log(cad_con) ) { prior = ( log(cad_con) - theta[1]); } else { prior += - (log(cad_con) - theta[1]); } return prob + prior; } /* calculate covariance matrix */ void set_covar_mat_con(double sigma, double tau, double alpha) { double t1, t2, nerr; int i, j; for(i=0; i<ncon_data; i++) { t1 = Tcon_data[i]; for(j=0; j<=i; j++) { t2 = Tcon_data[j]; Smat[i*ncon_data+j] = sigma*sigma * exp (- pow (fabs(t1-t2) / tau, alpha)); Smat[j*ncon_data+i] = Smat[i*ncon_data+j]; Nmat[i*ncon_data+j] = Nmat[j*ncon_data+i] = 0.0; } nerr = Fcerrs_data[i]; Nmat[i*ncon_data+i] = nerr*nerr; } return; } void set_covar_Umat_con(double sigma, double tau, double alpha) { double t1, t2; int i, j; for(i=0; i<ncon; i++) { t1 = Tcon[i]; for(j=0; j<ncon_data; j++) { t2 = Tcon_data[j]; USmat[i*ncon_data+j] = sigma*sigma * exp (- pow (fabs(t1-t2) / tau, alpha) ); } } return; } /* reconstruction */ void reconstruct_con() { double sigma, tau, alpha, sigmahat; double *ybuf, *Larr, *Larr_rec, *yave, *yave_rec, *Cq, *ICq, *ysub, *ave; double *Tmp1, *Tmp2, *Tmp3, *Tmp4; int i, nq, info, nmax; nq = 1+flag_detrend; yave = workspace; ysub = yave + ncon_data; Larr_rec = ysub + ncon_data; //Larr_rec is a nq*ncon matrix yave_rec = Larr_rec + nq*ncon; //yave_rec is ncon matrix ybuf = yave_rec + ncon; Larr = ybuf + ncon_data; // Larr is a nq*n matrix Cq = Larr + nq*ncon_data; ICq = Cq + nq*nq; ave = ICq + nq*nq; nmax = max(ncon, ncon_data); Tmp1 = array_malloc(nmax*nmax); // temporary matrixes Tmp2 = array_malloc(nmax*nmax); Tmp3 = array_malloc(nmax*nmax); Tmp4 = array_malloc(nmax*nmax); sigmahat = exp(theta_best[0]); tau = exp(theta_best[1]); sigma = sigmahat * sqrt(tau/2.0); alpha = 1.0; set_covar_mat_con(sigma, tau, alpha); set_covar_Umat_con(sigma, tau, alpha); for(i=0;i<ncon_data*ncon_data; i++) { Cmat[i] = Smat[i] + Nmat[i]; } memcpy(ICmat, Cmat, ncon_data*ncon_data*sizeof(double)); inverse_mat(ICmat, ncon_data, &info); /* the best estimate for average */ for(i=0;i<ncon_data;i++) { if(flag_detrend==0) { Larr[i]=1.0; } else { Larr[i*nq + 0] = 1.0; Larr[i*nq + 1] = Tcon_data[i]; } } for(i=0;i<ncon;i++) { if(flag_detrend==0) { Larr_rec[i]=1.0; } else { Larr_rec[i*nq + 0] = 1.0; Larr_rec[i*nq + 1] = Tcon[i]; } } // calculate the covariance matrix Cq for q. // Cq = (L^T x C^-1 x L)^-1 multiply_mat_MN(ICmat, Larr, Tmat1, ncon_data, nq, ncon_data); multiply_mat_MN_transposeA(Larr, Tmat1, ICq, nq, nq, ncon_data); memcpy(Cq, ICq, nq*nq*sizeof(double)); inverse_mat(Cq, nq, &info); // calculate the best estimate of q. // q = Cq x L^T x C^-1 x y multiply_mat_MN_transposeA(Larr, ICmat, Tmat1, nq, ncon_data, ncon_data); multiply_mat_MN(Cq, Tmat1, Tmat2, nq, ncon_data, nq); multiply_mat_MN(Tmat2, Fcon_data, ave, nq, 1, ncon_data); // subtract the linear trend multiply_mat_MN(Larr, ave, yave, ncon_data, 1, nq); for(i=0;i<ncon_data;i++)ysub[i] = Fcon_data[i] - yave[i]; // calculate the best estimate for s. // s = S x C^-1 x (y - Lxq) multiply_matvec(ICmat, ysub, ncon_data, ybuf); multiply_matvec_MN(USmat, ncon, ncon_data, ybuf, Fcon); multiply_mat_MN(Larr_rec, ave, yave_rec, ncon, 1, nq); for(i=0; i<ncon; i++)Fcon[i] = Fcon[i] + yave_rec[i]; multiply_mat_MN(USmat, ICmat, Tmp1, ncon, ncon_data, ncon_data); multiply_mat_MN_transposeB(Tmp1, USmat, Tmp2, ncon, ncon, ncon_data); multiply_mat_MN(Tmp1, Larr, Tmp3, ncon, nq, ncon_data); for(i=0; i<ncon*nq; i++)Tmp3[i] -= Larr_rec[i]; multiply_mat_MN(Tmp3, Cq, Tmp1, ncon, nq, nq); multiply_mat_MN_transposeB(Tmp1, Tmp3, Tmp4, ncon, ncon, nq); for(i=0; i<ncon; i++) { Fcerrs[i] = sqrt(sigma*sigma - Tmp2[i*ncon+i] + Tmp4[i*ncon+i]); } FILE *fp; fp = fopen("data/scon.txt", "w"); for(i=0; i<ncon; i++) { fprintf(fp, "%f %f %f\n", Tcon[i], Fcon[i]*scale_con, Fcerrs[i]*scale_con); } fclose(fp); free(Tmp1); free(Tmp2); free(Tmp3); free(Tmp4); }
{ "alphanum_fraction": 0.6157823129, "avg_line_length": 24.4186046512, "ext": "c", "hexsha": "b126251a310dcc4bbf411e272e576cc10f698651", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z", "max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/MICA", "max_forks_repo_path": "src/mcmc_con.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "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": "LiyrAstroph/MICA", "max_issues_repo_path": "src/mcmc_con.c", "max_line_length": 83, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/MICA", "max_stars_repo_path": "src/mcmc_con.c", "max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z", "num_tokens": 2831, "size": 7350 }
#ifndef main_H_INCLUDED #define main_H_INCLUDED #include "wf.h" #include "glasma.h" #include "jet.h" #include "bfkl.h" #include "time.h" #include "single.h" #include <gsl/gsl_errno.h> char tag[256]; //* //* // This section of code initializes and reads in the // following global variables from file //* //* #define X_FIELDS \ X(int, wfTAG, "%d") \ X(int, A1, "%d") \ X(int, A2, "%d") \ X(double, rts, "%lf") \ #include "ReadParameters.cxx" // #endif
{ "alphanum_fraction": 0.6332622601, "avg_line_length": 15.1290322581, "ext": "h", "hexsha": "aba644605cca988445b58850fe0a98bd9a819025", "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": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_path": "src/main.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "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": "kdusling/mpc", "max_issues_repo_path": "src/main.h", "max_line_length": 52, "max_stars_count": null, "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_path": "src/main.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 140, "size": 469 }
// Geocode a DEM stored in ASF .meta format. // Standard libraries. #include <limits.h> #include <math.h> #include <string.h> // Libraries from packages outside ASF. #include <gsl/gsl_math.h> // Libraries developed at ASF. #include <asf.h> #include <asf_meta.h> #include <asf_raster.h> #include <float_image.h> #include <libasf_proj.h> // Headers defined by this library. #include "asf_geocode.h" // Return true iff (x, y) falls in the region // ([0, image->size_x - 1), [0, image->size_y - 1)) static int in_image (FloatImage *image, ssize_t x, ssize_t y) { g_assert (image->size_x <= SSIZE_MAX && image->size_y <= SSIZE_MAX); ssize_t sz_x = image->size_x, sz_y = image->size_y; return 0 <= x && x < sz_x && 0 <= y && y < sz_y; } // Given a projected image with metadata md, an unproject_input // function, and pixel indicies (x, y), return the latitude and // longitude of x, y (relative to whatever libasf_proj input spheroid // is in effect at the time this function is called. Probably easiest // to see the purpose of this routine from the context in which it is // called. static int get_pixel_lat_long (const meta_parameters *md, projector_t unproject_input, size_t x, size_t y, double *lat, double *lon) { // Convenience aliases. meta_projection *pb = md->projection; project_parameters_t *pp = &(md->projection->param); double xpc = pb->startX + pb->perX * x; double ypc = pb->startY + pb->perY * y; // Pseudoprojected images are in degrees and the projection and // unprojection function deal in radians. if ( md->projection->type == LAT_LONG_PSEUDO_PROJECTION ) { xpc *= D2R; ypc *= D2R; } int return_code = unproject_input (pp, xpc, ypc, ASF_PROJ_NO_HEIGHT, lat, lon, NULL, md->projection->datum); g_assert (return_code); return return_code; } int geocode_dem (projection_type_t projection_type, // What we are projection to. project_parameters_t *pp, // Parameters we project to. datum_type_t datum, // Datum we project to. // Pixel size of output image, in output projection units // (meters or possibly degrees, if we decide to support // projecting to pseudoprojected form). double pixel_size, resample_method_t resample_method, // How to resample pixels. const char *input_image, // Base name of input image. const meta_parameters *imd, // Input DEM image metadata. const char *output_image // Base name of output image. ) { int return_code; // Holds return codes from functions. // Function to use to project or unproject between latlon and input // or output coordinates. projector_t project_input; // latlon => input image map projection projector_t unproject_input; // input image_map_projection => latlon projector_t project_output; // latlon => output image map projection projector_t unproject_output; // output image map projection => latlon // Like the above, but act on arrays. array_projector_t array_project_input, array_unproject_input; array_projector_t array_project_output, array_unproject_output; // We only deal with reprojection map projected DEMs. g_assert (imd->projection != NULL); // FIXME: what to do with background value is something that still // needs to be determined (probably in consultation with the guys // working on terrain correction). const float background_value = 0.0; // Geocoding to pseudoprojected form presents issues, for example // with the meaning of the pixel_size argument, which is taken as a // distance in map projection coordinates for all other projections // (deciding how to interpret it when projecting to pseudoprojected // form is tough), and since there probably isn't much need, we // don't allow it. g_assert (projection_type != LAT_LONG_PSEUDO_PROJECTION); // Get the functions we want to use for projecting and unprojecting. set_projection_functions (imd->projection->type, &project_input, &unproject_input, &array_project_input, &array_unproject_input); set_projection_functions (projection_type, &project_output, &unproject_output, &array_project_output, &array_unproject_output); // Input image dimensions in pixels in x and y directions. size_t ii_size_x = imd->general->sample_count; size_t ii_size_y = imd->general->line_count; // Convenience aliases. meta_projection *ipb = imd->projection; project_parameters_t *ipp = &imd->projection->param; // First we march around the entire outside of the image and compute // projection coordinates for every pixel, keeping track of the // minimum and maximum projection coordinates in each dimension. // This lets us determine the exact extent of the DEM in // output projection coordinates. asfPrintStatus ("Determining input image extent in projection coordinate " "space... "); double min_x = DBL_MAX; double max_x = -DBL_MAX; double min_y = DBL_MAX; double max_y = -DBL_MAX; // In going around the edge, we are just trying to determine the // extent of the image in the horizontal, so we don't care about // height yet. { // Scoping block. // Number of pixels in the edge of the image. size_t edge_point_count = 2 * ii_size_x + 2 * ii_size_y - 4; double *lats = g_new0 (double, edge_point_count); double *lons = g_new0 (double, edge_point_count); size_t current_edge_point = 0; size_t ii = 0, jj = 0; for ( ; ii < ii_size_x - 1 ; ii++ ) { return_code = get_pixel_lat_long (imd, unproject_input, ii, jj, &(lats[current_edge_point]), &(lons[current_edge_point])); g_assert (return_code); current_edge_point++; } for ( ; jj < ii_size_y - 1 ; jj++ ) { return_code = get_pixel_lat_long (imd, unproject_input, ii, jj, &(lats[current_edge_point]), &(lons[current_edge_point])); g_assert (return_code); current_edge_point++; } for ( ; ii > 0 ; ii-- ) { return_code = get_pixel_lat_long (imd, unproject_input, ii, jj, &(lats[current_edge_point]), &(lons[current_edge_point])); g_assert (return_code); current_edge_point++; } for ( ; jj > 0 ; jj-- ) { return_code = get_pixel_lat_long (imd, unproject_input, ii, jj, &(lats[current_edge_point]), &(lons[current_edge_point])); g_assert (return_code); current_edge_point++; } g_assert (current_edge_point == edge_point_count); // Pointers to arrays of projected coordinates to be filled in. // The projection function will allocate this memory itself. double *x = NULL, *y = NULL; // Project all the edge pixels. return_code = array_project_output (pp, lats, lons, NULL, &x, &y, NULL, edge_point_count, datum); g_assert (return_code == TRUE); // Find the extents of the image in projection coordinates. for ( ii = 0 ; ii < edge_point_count ; ii++ ) { if ( x[ii] < min_x ) { min_x = x[ii]; } if ( x[ii] > max_x ) { max_x = x[ii]; } if ( y[ii] < min_y ) { min_y = y[ii]; } if ( y[ii] > max_y ) { max_y = y[ii]; } } free (y); free (x); g_free (lons); g_free (lats); } asfPrintStatus ("done.\n\n"); // Issue a warning when the chosen pixel size is smaller than the // input pixel size. FIXME: this condition will really never fire // for pseudoprojected image, since the pixels size of the input is // tiny (degrees per pixel) and the pixel_size has already been // computed in asf_geocode function itself as an arc length on the // ground. if ( GSL_MIN(imd->general->x_pixel_size, imd->general->y_pixel_size) > pixel_size ) { asfPrintWarning ("Requested pixel size %lf is smaller then the input image resolution " "(%le meters).\n", pixel_size, GSL_MIN (imd->general->x_pixel_size, imd->general->y_pixel_size)); } // The pixel size requested by the user better not oversample by the // factor of 2. Specifying --force will skip this check. FIXME: // same essential problem as the above condition, but in this case // it always goes off. // if (!force_flag && GSL_MIN(imd->general->x_pixel_size, // imd->general->y_pixel_size) > (2*pixel_size) ) { // report_func // ("Requested pixel size %lf is smaller then the minimum implied by half \n" // "the input image resolution (%le meters), this is not supported.\n", // pixel_size, GSL_MIN (imd->general->x_pixel_size, // imd->general->y_pixel_size)); // } asfPrintStatus ("Opening input DEM image... "); char *input_data_file = (char *) MALLOC(sizeof(char)*(strlen(input_image)+5)); sprintf(input_data_file, "%s.img", input_image); FloatImage *iim = float_image_new_from_file (ii_size_x, ii_size_y, input_data_file, 0, FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN); FREE(input_data_file); asfPrintStatus ("done.\n\n"); // Maximum pixel indicies in output image. size_t oix_max = ceil ((max_x - min_x) / pixel_size); size_t oiy_max = ceil ((max_y - min_y) / pixel_size); // Output image dimensions. size_t oi_size_x = oix_max + 1; size_t oi_size_y = oiy_max + 1; // Output image. FloatImage *oim = float_image_new (oi_size_x, oi_size_y); // Translate the command line notion of the resampling method into // the lingo known by the float_image class. The compiler is // reassured with a default. float_image_sample_method_t float_image_sample_method = FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR; switch ( resample_method ) { case RESAMPLE_NEAREST_NEIGHBOR: float_image_sample_method = FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR; break; case RESAMPLE_BILINEAR: float_image_sample_method = FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR; break; case RESAMPLE_BICUBIC: float_image_sample_method = FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC; break; default: g_assert_not_reached (); } // We need to find the z coordinates in the output projection of all // the pixels in the input DEM. We store these values in their own // FloatImage instance. //FloatImage *x_coords = float_image_new (ii_size_x, ii_size_y); //FloatImage *y_coords = float_image_new (ii_size_x, ii_size_y); FloatImage *z_coords = float_image_new (ii_size_x, ii_size_y); // We transform the points using the array transformation function // for efficiency, but we don't want to do them all at once, since // that would require huge gobs of memory. const size_t max_transform_chunk_pixels = 5000000; size_t rows_per_chunk = max_transform_chunk_pixels / ii_size_x; size_t chunk_pixels = rows_per_chunk * ii_size_x; double *chunk_x = g_new0 (double, chunk_pixels); double *chunk_y = g_new0 (double, chunk_pixels); double *chunk_z = g_new0 (double, chunk_pixels); double *lat = g_new0 (double, chunk_pixels); double *lon = g_new0 (double, chunk_pixels); double *height = g_new0 (double, chunk_pixels); asfPrintStatus ("Determining Z coordinates of input pixels in output " "projection space... "); // Transform all the chunks, storing results in the z coordinate image. size_t ii, jj, kk; // Index variables. for ( ii = 0 ; ii < ii_size_y ; ) { size_t rows_remaining = ii_size_y - ii; size_t rows_to_load = rows_per_chunk < rows_remaining ? rows_per_chunk : rows_remaining; for ( jj = 0 ; jj < rows_to_load ; jj++ ) { size_t current_image_row = ii + jj; for ( kk = 0 ; kk < ii_size_x ; kk++ ) { size_t current_chunk_pixel = jj * ii_size_x + kk; chunk_x[current_chunk_pixel] = ipb->startX + kk * ipb->perX; chunk_y[current_chunk_pixel] = ipb->startY + current_image_row * ipb->perY; if ( imd->projection->type == LAT_LONG_PSEUDO_PROJECTION ) { chunk_x[current_chunk_pixel] *= D2R; chunk_y[current_chunk_pixel] *= D2R; } chunk_z[current_chunk_pixel] = float_image_get_pixel (iim, kk, current_image_row); } } long current_chunk_pixels = rows_to_load * ii_size_x; array_unproject_input (ipp, chunk_x, chunk_y, chunk_z, &lat, &lon, &height, current_chunk_pixels, ipb->datum); array_project_output (pp, lat, lon, height, &chunk_x, &chunk_y, &chunk_z, current_chunk_pixels, datum); for ( jj = 0 ; jj < rows_to_load ; jj++ ) { size_t current_image_row = ii + jj; for ( kk = 0 ; kk < ii_size_x ; kk++ ) { size_t current_chunk_pixel = jj * ii_size_x + kk; // Current pixel x, y, z coordinates. //float cp_x = (float) chunk_x[current_chunk_pixel]; //float cp_y = (float) chunk_y[current_chunk_pixel]; float cp_z = (float) chunk_z[current_chunk_pixel]; //float_image_set_pixel (x_coords, kk, current_image_row, cp_x); //float_image_set_pixel (y_coords, kk, current_image_row, cp_y); float_image_set_pixel (z_coords, kk, current_image_row, cp_z); } } ii += rows_to_load; } asfPrintStatus ("done.\n\n"); #ifdef DEBUG_GEOCODE_DEM_Z_COORDS_IMAGE_AS_JPEG // Take a look at the z_coordinate image (for debugging). float_image_export_as_jpeg_with_mask_interval (z_coords, "z_coords.jpg", GSL_MAX (z_coords->size_x, z_coords->size_y), -FLT_MAX, -100); #endif g_free (chunk_x); g_free (chunk_y); g_free (chunk_z); g_free (lat); g_free (lon); g_free (height); // Now we want to determine the pixel coordinates in the input which // correspond to each of the output pixels. We can then sample the // new height value already computed for that input pixel to // determine the pixel value to use as output. // We want to proceed in chunks as we did when going in the other // direction. rows_per_chunk = max_transform_chunk_pixels / oi_size_x; chunk_pixels = rows_per_chunk * oi_size_x; chunk_x = g_new0 (double, chunk_pixels); chunk_y = g_new0 (double, chunk_pixels); // We don't have height information in this direction, nor do we care. chunk_z = NULL; lat = g_new0 (double, chunk_pixels); lon = g_new0 (double, chunk_pixels); // We don't have height information in this direction, nor do we care. height = NULL; asfPrintStatus ("Sampling Z coordinates to form pixels in output projection " "space... "); // Transform all the chunks, using the results to form the output image. for ( ii = 0 ; ii < oi_size_y ; ) { size_t rows_remaining = oi_size_y - ii; size_t rows_to_load = rows_per_chunk < rows_remaining ? rows_per_chunk : rows_remaining; for ( jj = 0 ; jj < rows_to_load ; jj++ ) { size_t current_image_row = ii + jj; for ( kk = 0 ; kk < oi_size_x ; kk++ ) { size_t current_chunk_pixel = jj * oi_size_x + kk; chunk_x[current_chunk_pixel] = min_x + kk * pixel_size; chunk_y[current_chunk_pixel] = max_y - current_image_row * pixel_size; } } long current_chunk_pixels = rows_to_load * oi_size_x; array_unproject_output (pp, chunk_x, chunk_y, NULL, &lat, &lon, NULL, current_chunk_pixels, datum); array_project_input (ipp, lat, lon, NULL, &chunk_x, &chunk_y, NULL, current_chunk_pixels, ipb->datum); if ( imd->projection->type == LAT_LONG_PSEUDO_PROJECTION ) { ssize_t ll; // For (semi)clarity we don't reuse index variable :) for ( ll = 0 ; ll < current_chunk_pixels ; ll++ ) { chunk_x[ll] *= R2D; chunk_y[ll] *= R2D; } } for ( jj = 0 ; jj < rows_to_load ; jj++ ) { size_t current_image_row = ii + jj; for ( kk = 0 ; kk < oi_size_x ; kk++ ) { size_t current_chunk_pixel = jj * oi_size_x + kk; // Compute pixel coordinates in input image. ssize_t in_x = (chunk_x[current_chunk_pixel] - ipb->startX) / ipb->perX; ssize_t in_y = (chunk_y[current_chunk_pixel] - ipb->startY) / ipb->perY; if ( in_image (z_coords, in_x, in_y) ) { // FIXME: something needs to be done somewhere about // propogating no data values. float_image_set_pixel (oim, kk, current_image_row, float_image_sample (z_coords, in_x, in_y, resample_method)); } else { float_image_set_pixel (oim, kk, current_image_row, background_value); } } } ii += rows_to_load; } asfPrintStatus ("done.\n\n"); g_free (chunk_x); g_free (chunk_y); g_free (lat); g_free (lon); #ifdef DEBUG_GEOCODE_DEM_OUTPUT_IMAGE_AS_JPEG // Take a look at the output image (for debugging). float_image_export_as_jpeg_with_mask_interval (oim, "oim.jpg", GSL_MAX (oim->size_x, oim->size_y), -FLT_MAX, -100); #endif // Store the output image. asfPrintStatus ("Storing output image... "); char *output_data_file = (char *) MALLOC(sizeof(char)*(strlen(output_image)+5)); sprintf(output_data_file, "%s.img", output_image); return_code = float_image_store (oim, output_data_file, FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN); g_assert (return_code == 0); asfPrintStatus ("done.\n\n"); // Now we need some metadata for the output image. We will just // start with the metadata from the input image and add the // geocoding parameters. char *input_meta_file = (char *) MALLOC(sizeof(char)*(strlen(input_image)+6)); sprintf(input_meta_file, "%s.meta", input_image); char *output_meta_file = (char *) MALLOC(sizeof(char)*(strlen(output_image)+6)); sprintf(output_meta_file, "%s.meta", output_image); meta_parameters *omd = meta_read (input_meta_file); // Adjust the metadata to correspond to the output image instead of // the input image. omd->general->x_pixel_size = pixel_size; omd->general->y_pixel_size = pixel_size; omd->general->line_count = oi_size_y; omd->general->sample_count = oi_size_x; // SAR block is not really appropriate for map projected images, but // since it ended up with this value that can signify map // projectedness in it somehow, we fill it in for safety. omd->sar->image_type = 'P'; // Note that we have already verified that the input image is // projected, and since we initialize the output metadata from there // we know we will have a projection block. omd->projection->type = projection_type; omd->projection->startX = min_x; omd->projection->startY = max_y; omd->projection->perX = pixel_size; omd->projection->perY = -pixel_size; strcpy (omd->projection->units, "meters"); // Set the spheroid axes lengths as appropriate for the output datum. spheroid_axes_lengths (datum_spheroid (datum), &(omd->projection->re_major), &(omd->projection->re_minor)); // What the heck, might as well set the ones in the general block as // well. spheroid_axes_lengths (datum_spheroid (datum), &(omd->general->re_major), &(omd->general->re_minor)); // Latitude and longitude at center of the output image. We will // set these relative to the spheroid underlying the datum in use // for the projected image. Yeah, that seems appropriate. double lat_0, lon_0; double center_x = omd->projection->startX + (omd->projection->perX * omd->general->line_count / 2); double center_y = (omd->projection->startY + (omd->projection->perY * omd->general->sample_count / 2)); unproject_output (pp, center_x, center_y, ASF_PROJ_NO_HEIGHT, &lat_0, &lon_0, NULL, datum); omd->general->center_latitude = R2D * lat_0; omd->general->center_longitude = R2D * lon_0; // FIXME: We are ignoring the meta_location fields for now since I'm // not sure whether they are supposed to refer to the corner pixels // or the corners of the data itself. if ( lat_0 > 0.0 ) { omd->projection->hem = 'N'; } else { omd->projection->hem = 'S'; } // Convert the projection parameter values back into degrees. to_degrees (projection_type, pp); omd->projection->param = *pp; meta_write (omd, output_meta_file); float_image_free (oim); FREE(output_data_file); meta_free (omd); FREE(input_meta_file); FREE(output_meta_file); return 0; }
{ "alphanum_fraction": 0.6929181621, "avg_line_length": 37.4678030303, "ext": "c", "hexsha": "3c7e617319e9a13d6e31becdbfc14a2eb6622e87", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_geocode/geocode_dem.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_geocode/geocode_dem.c", "max_line_length": 84, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_geocode/geocode_dem.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 5368, "size": 19783 }
#include <stdio.h> #include <gsl/gsl_matrix.h> #include "bstrlib/bstrlib.h" #include "paths.h" #include "ParseSCF.h" #include "HTightBinding.h" #include "BandEnergy.h" #include "SpinOrbit.h" int main(int argc, char *argv[]) { if (argc < 8) { printf("SOC-induced anisotropy calculation -- invoke with:\n"); printf("anisotropy.out (system_name) (na) (nb) (nc) (soc_strength) (theta1) (phi1) (theta2) (phi2)\n"); return 1; } char *system_name = argv[1]; int na = atoi(argv[2]); int nb = atoi(argv[3]); int nc = atoi(argv[4]); double soc_strength = atof(argv[5]); double theta1 = atof(argv[6]); double phi1 = atof(argv[7]); double theta2 = atof(argv[8]); double phi2 = atof(argv[9]); char *scf_path = cwannier_data_path(system_name, "wannier", "\0", "scf.out"); double num_electrons, alat; gsl_matrix *R = gsl_matrix_alloc(3, 3); int err = ParseSCF(scf_path, &num_electrons, &alat, R); if (err != CWANNIER_PARSESCF_OK) { printf("Error code = %d returned from ParseSCF\n", err); return err; } bcstrfree(scf_path); char *hr_up_path = cwannier_data_path(system_name, "wannier", system_name, "_up_hr.dat"); HTightBinding *Hrs_up = ExtractHTightBinding(hr_up_path); bcstrfree(hr_up_path); char *hr_dn_path = cwannier_data_path(system_name, "wannier", system_name, "_dn_hr.dat"); HTightBinding *Hrs_dn = ExtractHTightBinding(hr_dn_path); bcstrfree(hr_dn_path); printf("Hamiltonian loaded.\n"); HTightBinding *Hrs_soc_1 = HamiltonianWithSOC(soc_strength, theta1, phi1, Hrs_up, Hrs_dn); HTightBinding *Hrs_soc_2 = HamiltonianWithSOC(soc_strength, theta2, phi2, Hrs_up, Hrs_dn); bool use_cache = true; double E_Fermi_1 = 0.0; double E_Fermi_2 = 0.0; double energy1 = BandEnergy(&E_Fermi_1, Hrs_soc_1, R, num_electrons, na, nb, nc, use_cache); printf("Got energy1 = %f\n", energy1); double energy2 = BandEnergy(&E_Fermi_2, Hrs_soc_2, R, num_electrons, na, nb, nc, use_cache); printf("Got energy2 = %f\n", energy2); printf("energy1 - energy2 = %e\n", energy1 - energy2); FreeHTightBinding(Hrs_up); FreeHTightBinding(Hrs_dn); FreeHTightBinding(Hrs_soc_1); FreeHTightBinding(Hrs_soc_2); return 0; }
{ "alphanum_fraction": 0.6662315057, "avg_line_length": 33.7941176471, "ext": "c", "hexsha": "21c12a3ed32aa39577027a2bebe5627073c18963", "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": "Anisotropy.c", "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": "Anisotropy.c", "max_line_length": 111, "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": "Anisotropy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 733, "size": 2298 }
/** * * @file core_zpemv.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Dulceneia Becker * @date 2011-06-29 * @precisions normal z -> c d s * **/ #include <cblas.h> #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex64_t * * CORE_zpemv performs one of the matrix-vector operations * * y = alpha*op( A )*x + beta*y * * where op( A ) is one of * * op( A ) = A or op( A ) = A**T or op( A ) = A**H, * * alpha and beta are scalars, x and y are vectors and A is a * pentagonal matrix (see further details). * * * Arguments * ========== * * @param[in] storev * * @arg PlasmaColumnwise : array A stored columwise * @arg PlasmaRowwise : array A stored rowwise * * @param[in] trans * * @arg PlasmaNoTrans : y := alpha*A*x + beta*y. * @arg PlasmaTrans : y := alpha*A**T*x + beta*y. * @arg PlasmaConjTrans : y := alpha*A**H*x + beta*y. * * @param[in] M * Number of rows of the matrix A. * M must be at least zero. * * @param[in] N * Number of columns of the matrix A. * N must be at least zero. * * @param[in] L * Order of triangle within the matrix A (L specifies the shape * of the matrix A; see further details). * * @param[in] ALPHA * Scalar alpha. * * @param[in] A * Array of size LDA-by-N. On entry, the leading M by N part * of the array A must contain the matrix of coefficients. * * @param[in] LDA * Leading dimension of array A. * * @param[in] X * On entry, the incremented array X must contain the vector x. * * @param[in] INCX * Increment for the elements of X. INCX must not be zero. * * @param[in] BETA * Scalar beta. * * @param[in,out] Y * On entry, the incremented array Y must contain the vector y. * * @param[out] INCY * Increment for the elements of Y. INCY must not be zero. * * @param[out] WORK * Workspace array of size at least L. * * Further Details * =============== * * | N | * _ ___________ _ * | | * A: | | * M-L | | * | | M * _ |..... | * \ : | * L \ : | * _ \:_____| _ * * | L | N-L | * * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zpemv = PCORE_zpemv #define CORE_zpemv PCORE_zpemv #endif int CORE_zpemv(PLASMA_enum trans, int storev, int M, int N, int L, PLASMA_Complex64_t ALPHA, const PLASMA_Complex64_t *A, int LDA, const PLASMA_Complex64_t *X, int INCX, PLASMA_Complex64_t BETA, PLASMA_Complex64_t *Y, int INCY, PLASMA_Complex64_t *WORK) { /* * y = alpha * op(A) * x + beta * y */ int K; static PLASMA_Complex64_t zzero = 0.0; /* Check input arguments */ if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans) && (trans != PlasmaConjTrans)) { coreblas_error(1, "Illegal value of trans"); return -1; } if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) { coreblas_error(2, "Illegal value of storev"); return -2; } if (!( ((storev == PlasmaColumnwise) && (trans != PlasmaNoTrans)) || ((storev == PlasmaRowwise) && (trans == PlasmaNoTrans)) )) { coreblas_error(2, "Illegal values of trans/storev"); return -2; } if (M < 0) { coreblas_error(3, "Illegal value of M"); return -3; } if (N < 0) { coreblas_error(4, "Illegal value of N"); return -4; } if (L > min(M ,N)) { coreblas_error(5, "Illegal value of L"); return -5; } if (LDA < max(1,M)) { coreblas_error(8, "Illegal value of LDA"); return -8; } if (INCX < 1) { coreblas_error(10, "Illegal value of INCX"); return -10; } if (INCY < 1) { coreblas_error(13, "Illegal value of INCY"); return -13; } /* Quick return */ if ((M == 0) || (N == 0)) return PLASMA_SUCCESS; if ((ALPHA == zzero) && (BETA == zzero)) return PLASMA_SUCCESS; /* If L < 2, there is no triangular part */ if (L == 1) L = 0; /* Columnwise */ if (storev == PlasmaColumnwise) { /* * ______________ * | | | A1: A[ 0 ] * | | | A2: A[ M-L ] * | A1 | | A3: A[ (N-L) * LDA ] * | | | * |______| A3 | * \ | | * \ A2 | | * \ | | * \|_____| * */ /* Columnwise / NoTrans */ if (trans == PlasmaNoTrans) { coreblas_error(1, "The case PlasmaNoTrans / PlasmaColumnwise is not yet implemented"); return -1; } /* Columnwise / [Conj]Trans */ else { /* L top rows of y */ if (L > 0) { /* w = A_2' * x_2 */ cblas_zcopy( L, &X[INCX*(M-L)], INCX, WORK, 1); cblas_ztrmv( CblasColMajor, (CBLAS_UPLO)PlasmaUpper, (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)PlasmaNonUnit, L, &A[M-L], LDA, WORK, 1); if (M > L) { /* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */ cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)trans, M-L, L, CBLAS_SADDR(ALPHA), A, LDA, X, INCX, CBLAS_SADDR(BETA), Y, INCY); /* y_1 = y_1 + alpha * w */ cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY); } else { /* y_1 = y_1 + alpha * w */ if (BETA == zzero) { cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1); cblas_zcopy(L, WORK, 1, Y, INCY); } else { cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY); cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY); } } } /* N-L bottom rows of Y */ if (N > L) { K = N - L; cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)trans, M, K, CBLAS_SADDR(ALPHA), &A[LDA*L], LDA, X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY); } } } /* Rowwise */ else { /* * -------------- * | | \ A1: A[ 0 ] * | A1 | \ A2: A[ (N-L) * LDA ] * | | A2 \ A3: A[ L ] * |--------------------\ * | A3 | * ---------------------- * */ /* Rowwise / NoTrans */ if (trans == PlasmaNoTrans) { /* L top rows of A and y */ if (L > 0) { /* w = A_2 * x_2 */ cblas_zcopy( L, &X[INCX*(N-L)], INCX, WORK, 1); cblas_ztrmv( CblasColMajor, (CBLAS_UPLO)PlasmaLower, (CBLAS_TRANSPOSE)PlasmaNoTrans, (CBLAS_DIAG)PlasmaNonUnit, L, &A[LDA*(N-L)], LDA, WORK, 1); if (N > L) { /* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */ cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans, L, N-L, CBLAS_SADDR(ALPHA), A, LDA, X, INCX, CBLAS_SADDR(BETA), Y, INCY); /* y_1 = y_1 + alpha * w */ cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY); } else { /* y_1 = y_1 + alpha * w */ if (BETA == zzero) { cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1); cblas_zcopy(L, WORK, 1, Y, INCY); } else { cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY); cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY); } } } /* M-L bottom rows of Y */ if (M > L) { cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans, M-L, N, CBLAS_SADDR(ALPHA), &A[L], LDA, X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY); } } /* Rowwise / [Conj]Trans */ else { coreblas_error(1, "The case Plasma[Conj]Trans / PlasmaRowwise is not yet implemented"); return -1; } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4142784294, "avg_line_length": 30.3560371517, "ext": "c", "hexsha": "9cc2320c19affb70f62486dcdd95a42451c5bbdc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_zpemv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_zpemv.c", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_zpemv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2701, "size": 9805 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <iniparser.h> #include <limits.h> #include "prepmt/prepmt.h" #include "ispl/process.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #define PROGRAM_NAME "xgrnsTeleB" static void printUsage(void); static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX], char section[256]); struct sacData_struct * prepmt_grnsTeleB_readData(const char *archiveFile, int *nobs, int *ierr); int prepmt_grnsTeleB_readParameters(const char *iniFile, const char *section, char archiveFile[PATH_MAX], char parmtDataFile[PATH_MAX], bool *luseCrust1, char crustDir[PATH_MAX], bool *luseSourceModel, char sourceModel[PATH_MAX], bool *luseTstarTable, double *defaultTstar, char tstarTable[PATH_MAX], bool *lrepickGrns, double *staWin, double *ltaWin, double *staltaThreshPct, bool *lalignXC, bool *luseEnvelope, bool *lnormalizeXC, double *maxXCtimeLag, int *ndepth, double **depths); int prepmt_grnsTeleB_loadTstarTable(const char *tstarTable, const double defaultTstar, const int nobs, struct sacData_struct *data, double **tstars); int main(int argc, char **argv) { char iniFile[PATH_MAX], archiveFile[PATH_MAX], tstarTable[PATH_MAX], parmtDataFile[PATH_MAX], crustDir[PATH_MAX], sourceModel[PATH_MAX], section[256]; struct prepmtCommands_struct cmds; struct vmodel_struct *recmod, telmod, srcmod; struct prepmtEventParms_struct event; struct hudson96_parms_struct hudson96Parms; struct hpulse96_parms_struct hpulse96Parms; struct prepmtModifyCommands_struct options; struct sacData_struct *sacData, *grns, *ffGrns, *locFF; const char *hudsonSection = "hudson96\0"; const char *hpulseSection = "hpulse96\0"; const int ntstar = 1; double *depths, *tstars, defaultTstar, ltaWin, maxXCtimeLag, staltaThreshPct, staWin; int i, ierr, iobs, k, kndx, ndepth, nobs; bool lalignXC, lnormalizeXC, lrepickGrns, luseCrust1, luseSourceModel, luseEnvelope, luseTstarTable; iscl_init(); depths = NULL; memset(&options, 0, sizeof(struct prepmtModifyCommands_struct)); ierr = parseArguments(argc, argv, iniFile, section); if (ierr != 0) { if (ierr ==-2){return EXIT_FAILURE;} return EXIT_SUCCESS; } // Load the event ierr = prepmt_event_initializeFromIniFile(iniFile, &event); if (ierr != 0) { printf("%s: Error reading event info\n", PROGRAM_NAME); return EXIT_FAILURE; } // Read the forward modeling parameters ierr = prepmt_hudson96_readHudson96Parameters(iniFile, hudsonSection, &hudson96Parms); if (ierr != 0) { printf("%s: Failed to read hudson parameters\n", PROGRAM_NAME); return EXIT_FAILURE; } ierr = prepmt_hpulse96_readHpulse96Parameters(iniFile, hpulseSection, &hpulse96Parms); if (ierr != 0) { printf("%s: Failed to read hpulse parameters\n", PROGRAM_NAME); return EXIT_FAILURE; } ierr = prepmt_grnsTeleB_readParameters(iniFile, section, archiveFile, parmtDataFile, &luseCrust1, crustDir, &luseSourceModel, sourceModel, &luseTstarTable, &defaultTstar, tstarTable, &lrepickGrns, &staWin, &ltaWin, &staltaThreshPct, &lalignXC, &luseEnvelope, &lnormalizeXC, &maxXCtimeLag, &ndepth, &depths); if (ierr != 0) { printf("%s: Failed to read modeling parameters\n", PROGRAM_NAME); return EXIT_FAILURE; } // Read how the default commands will be modified options.iodva = hpulse96Parms.iodva; options.ldeconvolution = false; // We are working with the greens fns ierr = prepmt_prepData_getDefaultDTAndWindowFromIniFile(iniFile, section, &options.targetDt, &options.cut0, &options.cut1); if (ierr != 0) { printf("%s: Failed to read default command info\n", PROGRAM_NAME); return EXIT_FAILURE; } // Load the data //memset(archiveFile, 0, PATH_MAX*sizeof(char)); //strcpy(archiveFile, "windowedPData/observedWaveforms.h5\0"); printf("%s: Loading data...\n", PROGRAM_NAME); sacData = prepmt_prepData_readArchivedWaveforms(archiveFile, &nobs, &ierr); if (ierr != 0) { printf("%s: Error loading data\n", PROGRAM_NAME); return EXIT_FAILURE; } if (luseTstarTable) { printf("%s: Loading tstar table...\n", PROGRAM_NAME); ierr = prepmt_grnsTeleB_loadTstarTable(tstarTable, defaultTstar, nobs, sacData, &tstars); if (ierr != 0) { printf("%s: Failed to load t* table\n", PROGRAM_NAME); return EXIT_FAILURE; } } else { printf("%s: Using default tstar: %f\n", PROGRAM_NAME, defaultTstar); tstars = array_set64f(nobs, defaultTstar, &ierr); } printf("%s: Reading pre-processing commands...\n", PROGRAM_NAME); cmds = prepmt_commands_readFromIniFile(iniFile, section, nobs, sacData, &ierr); if (ierr != 0) { printf("%s: Error loading grns prep commands\n", PROGRAM_NAME); return -1; } printf("%s: Loading velocity models...\n", PROGRAM_NAME); recmod = (struct vmodel_struct *) calloc((size_t) nobs, sizeof(struct vmodel_struct)); ierr = hudson96_getModels(nobs, sacData, luseCrust1, crustDir, luseSourceModel, sourceModel, &telmod, &srcmod, recmod); if (ierr != 0) { printf("%s: Failed to load models\n", PROGRAM_NAME); return EXIT_FAILURE; } printf("%s: Computing fundamental fault solutions...\n", PROGRAM_NAME); ffGrns = (struct sacData_struct *) calloc((size_t) (ndepth*nobs*ntstar*10), sizeof(struct sacData_struct)); for (k=0; k<nobs; k++) { locFF = prepmt_hudson96_computeGreensFF(hudson96Parms, hpulse96Parms, telmod, srcmod, recmod, ntstar, &tstars[1], ndepth, depths, 1, &sacData[k], &ierr); for (i=0; i<10*ndepth; i++) { kndx = k*10*ndepth + i; sacio_copy(locFF[i], &ffGrns[kndx]); sacio_freeData(&locFF[i]); } free(locFF); } printf("%s: Contextualing Green's functions...\n", PROGRAM_NAME); grns = (struct sacData_struct *) calloc((size_t) (6*ndepth*nobs*ntstar), sizeof(struct sacData_struct)); ierr = prepmt_greens_ffGreensToGreens(nobs, sacData, ndepth, ntstar, ffGrns, grns); if (ierr != 0) { printf("%s: Error contextualizing Greens functions\n", PROGRAM_NAME); return EXIT_FAILURE; } for (k=0; k<10*nobs*ndepth*ntstar; k++){sacio_freeData(&ffGrns[k]);} free(ffGrns); // Release memory for (k=0; k<nobs; k++) { cps_utils_freeVmodelStruct(&recmod[k]); } free(recmod); cps_utils_freeVmodelStruct(&srcmod); cps_utils_freeVmodelStruct(&telmod); // Process the Green's functions printf("%s: Modifying Green's functions processing commands...\n", PROGRAM_NAME); for (k=0; k<cmds.nobs; k++) { ierr = prepmt_commands_modifyCommandsCharsStruct(options, sacData[k], &cmds.cmds[k]); /* for (int l=0; l<cmds.cmds[k].ncmds; l++) { printf("%s\n", cmds.cmds[k].cmds[l]); } printf("\n"); */ if (ierr != 0) { printf("%s: Failed to modify processing commands\n", PROGRAM_NAME); return EXIT_FAILURE; } } printf("%s: Processing Green's functions...\n", PROGRAM_NAME); ierr = prepmt_greens_processHudson96Greens(nobs, ntstar, ndepth, cmds, grns); if (ierr != 0) { printf("%s: Error processing Green's functions\n", PROGRAM_NAME); return EXIT_FAILURE; } // Repick the Green's functions with an STA/LTA if (lrepickGrns) { printf("%s: Repicking Green's functions...\n", PROGRAM_NAME); for (k=0; k<ndepth*ntstar*nobs*6; k=k+6) { ierr = prepmt_greens_repickGreensWithSTALTA(staWin, ltaWin, staltaThreshPct, &grns[k]); if (ierr != 0) { printf("%s: Error repicking Green's functions\n", PROGRAM_NAME); return EXIT_FAILURE; } } } // Shift if (lalignXC) { printf("%s: Refining waveform alignment with cross-correlation\n", PROGRAM_NAME); for (iobs=0; iobs<nobs; iobs++) { for (k=0; k<ndepth*ntstar; k++) { kndx = iobs*ndepth*ntstar*6 + k*6; ierr = prepmt_greens_xcAlignGreensToData(sacData[iobs], luseEnvelope, lnormalizeXC, maxXCtimeLag, &grns[kndx]); if (ierr != 0) { printf("%s: Error aligning with XC\n", PROGRAM_NAME); return EXIT_FAILURE; } } } } // Trim printf("%s: Windowing Green's functions to data\n", PROGRAM_NAME); ierr = prepmt_greens_cutHudson96FromData(nobs, sacData, ndepth, ntstar, grns); if (ierr != 0) { printf("%s: Error trimming Green's functions\n", PROGRAM_NAME); return EXIT_FAILURE; } // Dump archive /* sacio_writeTimeSeriesFile("test_gxx.sac", grns[11*ndepth*6+6]); sacio_writeTimeSeriesFile("test_gyy.sac", grns[11*ndepth*6+7]); sacio_writeTimeSeriesFile("test_gzz.sac", grns[11*ndepth*6+8]); sacio_writeTimeSeriesFile("test_gxy.sac", grns[11*ndepth*6+9]); sacio_writeTimeSeriesFile("test_gxz.sac", grns[11*ndepth*6+10]); sacio_writeTimeSeriesFile("test_gyz.sac", grns[11*ndepth*6+11]); */ printf("%s: Writing archive: %s\n", PROGRAM_NAME, parmtDataFile); ierr = prepmt_greens_writeArchive(parmtDataFile, //"./", "pwave", nobs, ndepth, event.latitude, event.longitude, depths, sacData, grns); if (ierr != 0) { printf("%s: Failed to write archive file\n", PROGRAM_NAME); return EXIT_FAILURE; } // release rest of memory for (k=0; k<nobs; k++){sacio_freeData(&sacData[k]);} for (k=0; k<ndepth*ntstar*nobs*6; k++){sacio_freeData(&grns[k]);} memory_free64f(&tstars); free(grns); free(sacData); iscl_finalize(); return EXIT_SUCCESS; } //============================================================================// /*! * @brief Obtains the forward modeling t* values for each teleseismic * waveform observation from a text file. * * @param[in] tstarTable Name of tstar table. * @param[in] defaultTstar Default t* if a piece of data cannot be found in * the table. * @param[in] nobs Number of observations. * @param[in] data List of teleseismic waveforms to map t* values to. * This is an array of dimension [nobs]. * * @param[out] tstars tstar values corresponding to each station. * If a SNCL in the data list cannot be found in the * tstarTable file then this tstar will be set to the * default value. * This is an array of length [nobs]. * * @result 0 indicates success. * * @author Ben Baker * */ int prepmt_grnsTeleB_loadTstarTable(const char *tstarTable, const double defaultTstar, const int nobs, struct sacData_struct *data, double **tstars) { FILE *tsf; char cline[64], search[64], item[64]; double *tstar, tin; int i, ierr, k, nlines; bool lfound; *tstars = NULL; tstar = NULL; if (!os_path_isfile(tstarTable)) { fprintf(stderr, "%s: Error tstar table %s does not exist\n", __func__, tstarTable); return -1; } if (nobs < 1 || data == NULL) { fprintf(stderr, "%s: No data\n", __func__); return -1; } // Initialize to default tstar = array_set64f(nobs, defaultTstar, &ierr); // Get number of lines in text file tsf = fopen(tstarTable, "r"); nlines = 0; while (fgets(cline, 64, tsf) != NULL){nlines = nlines + 1;} rewind(tsf); // Loop through and match observations to tstar's in table for (k=0; k<nobs; k++) { memset(search, 0, 64*sizeof(char)); sprintf(search, "%s.%s.%s.%s", data[k].header.knetwk, data[k].header.kstnm, data[k].header.kcmpnm, data[k].header.khole); lfound = false; for (i=0; i<nlines; i++) { memset(cline, 0, 64*sizeof(char)); memset(item, 0, 64*sizeof(char)); fgets(cline, 64, tsf); sscanf(cline, "%s %lf\n", item, &tin); if (strcasecmp(search, item) == 0) { tstar[k] = defaultTstar; lfound = true; break; } } if (!lfound) { fprintf(stderr, "%s: Setting %s tstar to: %f\n", __func__, search, defaultTstar); } rewind(tsf); } fclose(tsf); *tstars = tstar; return 0; } //============================================================================// /*! * @brief TODO: delete this function. */ int prepmt_grnsTeleB_windowHudson96( const int nobs, const int ntstar, const int ndepth, const struct sacData_struct *data, struct sacData_struct *grns) { double epoch, epochGrns; int indices[6], idep, ierr, iobs, it; for (iobs=0; iobs<nobs; iobs++) { // Figure out the origin time ierr = sacio_getEpochalStartTime(data[iobs].header, &epoch); if (ierr != 0) { fprintf(stderr, "%s: Failed to get start time\n", __func__); break; } for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { ierr = prepmt_greens_getHudson96GreensFunctionsIndices( nobs, ntstar, ndepth, iobs, it, idep, indices); // Figure out the origin time ierr = sacio_getEpochalStartTime(grns[indices[0]].header, &epochGrns); if (ierr != 0) { fprintf(stderr, "%s: Failed to get start time\n", __func__); break; } // Fig } } } return 0; } //============================================================================// /*! * @brief Processes the Green's functions. * * @param[in,out] grns On input contains the Green's functions for all * observations, depths, and t*'s as well as the * processing chains. \n * On output contains the filtered Green's functions * for all observations, depths, and t*'s. * * @result 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_grnsTeleB_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, 0, 0); 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; 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); 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[i]], grns[indices[i]].data); } else { ierr = array_copy64f_work(npts, &G[dataPtr[i]], 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 Green's functions gxx, gyy, ... } // Loop on t* } // Loop on depths process_freeSerialCommands(&commands); process_freeParallelCommands(&parallelCommands); memory_free64f(&G); } ERROR:; memory_free32i(&dataPtr); return 0; } //============================================================================// /*! * @brief Reads the teleseismic body wave Green's functions modeling parameters. * * @param[in] iniFile Name of initialization file. * @param[in] section Section of initalization file to read. For * example, this may be prepmt:telePGrns. * @param[out] archiveFile This is the HDF5 file with the observed waveforms. * @param[out] parmtDataFile This is the name of the data archive file to * be used by parmt. * @param[out] luseCrust1 If true then the modeling may use crust1 * at the source and receiver (unless superseded * by a specified local model). \n * Otherwise, use a local model or the global * ak135 earth model. * @param[out] crustDir The crust1.0 directory. This is only relevant * if luseCrust1 is true. * @param[out] luseSourceModel If true then use a local source model. * @param[out] sourceModel If luseSourceModel is true then this is the * filename with the local source model. * @param[out] luseTstarTable If true then read the t* attenuation factors * from a table. * @param[out] defaultTstar This is the default t* (e.g., 0.4). * @param[out] tstarTable If luseTstarTable is true then this is the file * with the station/t* table pairings. * @param[out] lreprickGrns If true then repick the Green's functions with * an STA/LTA function. This is in the context of * severe attenutation which noticeably effect * theoretical arrival times. * @param[out] staWin If repicking Green's functions then this * is the short term window (seconds). * @param[out] ltaWin If repicking Green's functions then this * is the long term window (seconds). * @param[out] staltaThreshPct This is the fraction (0,1) after which an * arrival is declared in the STA/LTA repicking. * @param[out] lalignXC If true the the Green's functions will be * re-aligned with cross-correlation. * @param[out] luseEnvelope If true and lalignXC is true then the * Green's functions will be aligned based on * the cross-correlation of their envelopes. * @param[out] lnormalizeXC If true then each Green's function is normalized * in the Green's function cross-correlation thus * Green's functions with larger amplitudes may * bias the result. * @param[out] maxXCtimeLag This is the max time lag (seconds) available to * the waveform cross-correlation alignment. * @param[out] ndepth Number of depths in modeling. * @param[in,out] depths On input this is a NULL pointer. * On output this is a pointer to an array * of dimension [ndepth] with the modeling depths * (km). * * @result 0 indicates success. * * @author Ben Baker, ISTI * */ int prepmt_grnsTeleB_readParameters(const char *iniFile, const char *section, char archiveFile[PATH_MAX], char parmtDataFile[PATH_MAX], bool *luseCrust1, char crustDir[PATH_MAX], bool *luseSourceModel, char sourceModel[PATH_MAX], bool *luseTstarTable, double *defaultTstar, char tstarTable[PATH_MAX], bool *lrepickGrns, double *staWin, double *ltaWin, double *staltaThreshPct, bool *lalignXC, bool *luseEnvelope, bool *lnormalizeXC, double *maxXCtimeLag, int *ndepth, double **depths) { const char *s; char vname[256]; dictionary *ini; char *dirName; double *deps, dmin, dmax; int ierr; ierr = 0; deps = NULL; memset(archiveFile, 0, PATH_MAX*sizeof(char)); memset(crustDir, 0, PATH_MAX*sizeof(char)); memset(sourceModel, 0, PATH_MAX*sizeof(char)); memset(tstarTable, 0, PATH_MAX*sizeof(char)); memset(parmtDataFile, 0, PATH_MAX*sizeof(char)); if (!os_path_isfile(iniFile)) { fprintf(stderr, "%s: Error ini file does not exist\n", __func__); return -1; } ini = iniparser_load(iniFile); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:dataH5File", section); s = iniparser_getstring(ini, vname, NULL); if (!os_path_isfile(s)) { fprintf(stderr, "%s: Data file %s does not exist\n", __func__, s); ierr = 1; goto ERROR; } strcpy(archiveFile, s); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:parmtDataFile", section); s = iniparser_getstring(ini, vname, "bodyWave.h5"); strcpy(parmtDataFile, s); dirName = os_dirname(parmtDataFile, &ierr); if (!os_path_isdir(dirName)) { ierr = os_makedirs(dirName); if (ierr != 0) { fprintf(stderr, "%s: Failed to make directory: %s\n", __func__, dirName); goto ERROR; } } memory_free8c(&dirName); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:lrepickGrns", section); *lrepickGrns = iniparser_getboolean(ini, vname, false); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:staWin", section); *staWin = iniparser_getdouble(ini, vname, 0.2); if (*staWin <= 0.0) { fprintf(stderr, "%s: Invalid STA length %f\n", __func__, *staWin); ierr = 1; goto ERROR; } memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:ltaWin", section); *ltaWin = iniparser_getdouble(ini, vname, 1.2); if (*ltaWin <= *staWin) { fprintf(stderr, "%s: Invalid LTA/STA lengths %f %f\n", __func__, *staWin, *ltaWin); ierr = 1; goto ERROR; } memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:staltaThreshPct", section); *staltaThreshPct = iniparser_getdouble(ini, vname, 0.8); if (*staltaThreshPct <= 0.0 || *staltaThreshPct > 1.0) { fprintf(stderr, "%s: Invalid STA/LTA thresh pct %f\n", __func__, *staltaThreshPct); ierr = 1; goto ERROR; } memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:luseTstarTable", section); *luseTstarTable = iniparser_getboolean(ini, vname, false); if (*luseTstarTable) { memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:tstarTable", section); s = iniparser_getstring(ini, vname, NULL); if (!os_path_isfile(s)) { fprintf(stderr, "%s: tstar table %s doesn't exist\n", __func__, s); ierr = 1; goto ERROR; } strcpy(tstarTable, s); } memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:ndepths\0"); *ndepth = iniparser_getint(ini, vname, 0); if (*ndepth < 1) { fprintf(stderr, "%s: Inadequate number of depths %d\n", __func__, *ndepth); ierr = 1; goto ERROR; } memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:depthMin\0"); dmin = iniparser_getdouble(ini, vname, -1.0); memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:depthMax\0"); dmax = iniparser_getdouble(ini, vname, -1.0); if (dmin < 0.0 || dmin > dmax) { fprintf(stderr, "%s: Invalid dmin/dmax %f %f\n", __func__, dmin, dmax); ierr = 1; goto ERROR; } deps = array_linspace64f(dmin, dmax, *ndepth, &ierr); memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:luseCrust1\0"); *luseCrust1 = iniparser_getboolean(ini, vname, true); if (*luseCrust1) { memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:crustDir\0"); s = iniparser_getstring(ini, vname, CPS_DEFAULT_CRUST1_DIRECTORY); if (!os_path_isdir(s)) { fprintf(stderr, "%s: crust1.0 directory %s doesn't exist\n", __func__, s); ierr = 1; goto ERROR; } strcpy(crustDir, s); } memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:luseSourceModel\0"); *luseSourceModel = iniparser_getboolean(ini, vname, false); if (*luseSourceModel) { memset(vname, 0, 256*sizeof(char)); strcpy(vname, "precompute:sourceModel\0"); s = iniparser_getstring(ini, vname, NULL); if (!os_path_isfile(s)) { fprintf(stderr, "%s: Source model %s does not exist\n", __func__, s); ierr = 1; goto ERROR; } strcpy(sourceModel, s); } memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:defaultTstar", section); *defaultTstar = iniparser_getdouble(ini, vname, 0.4); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:lalignXC", section); *lalignXC = iniparser_getboolean(ini, vname, false); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:luseEnvelope", section); *luseEnvelope = iniparser_getboolean(ini, vname, false); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:lnormalizeXC", section); *lnormalizeXC = iniparser_getboolean(ini, vname, false); memset(vname, 0, 256*sizeof(char)); sprintf(vname, "%s:maxXCtimeLag", section); *maxXCtimeLag = iniparser_getdouble(ini, vname, -1.0); ERROR:; *depths = deps; iniparser_freedict(ini); return ierr; } //============================================================================// /*! * @brief Utility function for reading the data for which the Green's functions * will be generated. * * @param[in] archiveFile Name of HDF5 archive file containing the * observations. * * @param[out] nobs Number of observations. * @param[out] ierr 0 indicates success. * * @result The SAC data from the H5 archive for which the Green's functions * will be created. This is an array of dimension [nobs]. * * @author Ben Baker, ISTI * */ struct sacData_struct * prepmt_grnsTeleB_readData(const char *archiveFile, int *nobs, int *ierr) { char **sacFiles; hid_t groupID, fileID; int i, nfiles; struct sacData_struct *sacData; *nobs = 0; sacData = NULL; if (!os_path_isfile(archiveFile)) { fprintf(stderr, "%s: Error archive file %s doesn't exist\n", __func__, archiveFile); *ierr = 1; return sacData; } fileID = H5Fopen(archiveFile, H5F_ACC_RDONLY, H5P_DEFAULT); groupID = H5Gopen2(fileID, "/ObservedWaveforms", H5P_DEFAULT); sacFiles = sacioh5_getFilesInGroup(groupID, &nfiles, ierr); if (*ierr != 0 || sacFiles == NULL) { fprintf(stderr, "%s: Error getting names of SAC flies\n", __func__); *ierr = 1; return sacData; } sacData = sacioh5_readTimeSeriesList(nfiles, (const char **) sacFiles, groupID, nobs, ierr); if (*ierr != 0) { fprintf(stderr, "%s: Errors while reading SAC files\n", __func__); } if (*nobs != nfiles) { fprintf(stderr, "%s: Warning - subset of data was read\n", __func__); } // Clean up and close archive file for (i=0; i<nfiles; i++) { if (sacFiles[i] != NULL){free(sacFiles[i]);} } free(sacFiles); H5Gclose(groupID); H5Fclose(fileID); return sacData; } //============================================================================// /*! * @brief Parses the command line arguments for the ini file. * * @param[in] argc Number of arguments input to the program. * @param[in] argv Command line arguments. * * @param[out] iniFile If the result is 0 then this is the ini file. * @param[out] section Section of ini file to read. The default is * prepmt:telePGrns. * * @result 0 indicates success. \n * -1 indicates the user inquired about the usage. \n * -2 indicates the command line argument is invalid. * * @author Ben Baker, ISTI * */ static int parseArguments(int argc, char *argv[], char iniFile[PATH_MAX], char section[256]) { bool linFile, lsection; linFile = false; lsection = false; memset(iniFile, 0, PATH_MAX*sizeof(char)); memset(section, 0, 256*sizeof(char)); while (true) { static struct option longOptions[] = { {"help", no_argument, 0, '?'}, {"help", no_argument, 0, 'h'}, {"ini_file", required_argument, 0, 'i'}, {"section", required_argument, 0, 's'}, {0, 0, 0, 0} }; int c, optionIndex; c = getopt_long(argc, argv, "?hi:s:", longOptions, &optionIndex); if (c ==-1){break;} if (c == 'i') { strcpy(iniFile, (const char *) optarg); linFile = true; } else if (c == 's') { strcpy(section, (const char *) optarg); lsection = true; } else if (c == 'h' || c == '?') { printUsage(); return -2; } else { printf("%s: Unknown options: %s\n", PROGRAM_NAME, argv[optionIndex]); } } if (!linFile) { printf("%s: Error must specify ini file\n\n", PROGRAM_NAME); printUsage(); return -1; } else { if (!os_path_isfile(iniFile)) { printf("%s: Error - ini file: %s does not exist\n", PROGRAM_NAME, iniFile); return EXIT_FAILURE; } } if (!lsection){strcpy(section, "prepmt:telePGrns\0");} return 0; } //============================================================================// static void printUsage(void) { printf("Usage:\n %s -i ini_file\n\n", PROGRAM_NAME); printf("Required arguments:\n"); printf(" -i ini_file specifies the initialization file\n"); printf("\n"); printf("Optional arguments:\n"); printf(" -h displays this message\n"); printf(" -s section of ini file to read\n"); return; }
{ "alphanum_fraction": 0.4891584147, "avg_line_length": 38.0255731922, "ext": "c", "hexsha": "06d1d5c5af8518df9d0acc4b5c4e2973b8c7f5b9", "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/grnsTeleB.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/grnsTeleB.c", "max_line_length": 82, "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/grnsTeleB.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10240, "size": 43121 }
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. // libCEED + PETSc Example: Surface Area // // This example demonstrates a simple usage of libCEED with PETSc to calculate // the surface area of a simple closed surface, such as the one of a cube or a // tensor-product discrete sphere via the mass operator. // // The code uses higher level communication protocols in DMPlex. // // Build with: // // make area [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>] // // Sample runs: // Sequential: // // ./area -problem cube -degree 3 -dm_refine 2 // ./area -problem sphere -degree 3 -dm_refine 2 // // In parallel: // // mpiexec -n 4 ./area -problem cube -degree 3 -dm_refine 2 // mpiexec -n 4 ./area -problem sphere -degree 3 -dm_refine 2 // // The above example runs use 2 levels of refinement for the mesh. // Use -dm_refine k, for k levels of uniform refinement. // //TESTARGS -ceed {ceed_resource} -test -degree 3 -dm_refine 1 /// @file /// libCEED example using the mass operator to compute a cube or a cubed-sphere surface area using PETSc with DMPlex static const char help[] = "Compute surface area of a cube or a cubed-sphere using DMPlex in PETSc\n"; #include <stdbool.h> #include <string.h> #include <ceed.h> #include <petsc.h> #include <petscdmplex.h> #include "area.h" #include "include/areaproblemdata.h" #include "include/petscutils.h" #include "include/petscversion.h" #include "include/matops.h" #include "include/structs.h" #include "include/libceedsetup.h" #if PETSC_VERSION_LT(3,12,0) #ifdef PETSC_HAVE_CUDA #include <petsccuda.h> // Note: With PETSc prior to version 3.12.0, providing the source path to // include 'cublas_v2.h' will be needed to use 'petsccuda.h'. #endif #endif #ifndef M_PI # define M_PI 3.14159265358979323846 #endif int main(int argc, char **argv) { PetscInt ierr; MPI_Comm comm; char filename[PETSC_MAX_PATH_LEN], ceed_resource[PETSC_MAX_PATH_LEN] = "/cpu/self"; PetscInt l_size, g_size, xl_size, q_extra = 1, // default number of extra quadrature points num_comp_x = 3, // number of components of 3D physical coordinates num_comp_u = 1, // dimension of field to which apply mass operator topo_dim = 2, // topological dimension of manifold degree = 3; // default degree for finite element bases PetscBool read_mesh = PETSC_FALSE, test_mode = PETSC_FALSE, simplex = PETSC_FALSE; Vec U, U_loc, V, V_loc; DM dm; UserO user; Ceed ceed; CeedData ceed_data; ProblemType problem_choice; VecType vec_type; PetscMemType mem_type; ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr; comm = PETSC_COMM_WORLD; // Read command line options ierr = PetscOptionsBegin(comm, NULL, "CEED surface area problem with PETSc", NULL); CHKERRQ(ierr); problem_choice = SPHERE; ierr = PetscOptionsEnum("-problem", "Problem to solve", NULL, problem_types, (PetscEnum)problem_choice, (PetscEnum *)&problem_choice, NULL); CHKERRQ(ierr); ierr = PetscOptionsInt("-q_extra", "Number of extra quadrature points", NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-ceed", "CEED resource specifier", NULL, ceed_resource, ceed_resource, sizeof(ceed_resource), NULL); CHKERRQ(ierr); ierr = PetscOptionsBool("-test", "Testing mode (do not print unless error is large)", NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr); ierr = PetscOptionsString("-mesh", "Read mesh from file", NULL, filename, filename, sizeof(filename), &read_mesh); CHKERRQ(ierr); ierr = PetscOptionsBool("-simplex", "Use simplices, or tensor product cells", NULL, simplex, &simplex, NULL); CHKERRQ(ierr); ierr = PetscOptionsInt("-degree", "Polynomial degree of tensor product basis", NULL, degree, &degree, NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // Setup DM if (read_mesh) { ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, NULL, PETSC_TRUE, &dm); CHKERRQ(ierr); } else { // Create the mesh as a 0-refined sphere. This will create a cubic surface, not a box ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, topo_dim, simplex, 1., &dm); CHKERRQ(ierr); // Set the object name ierr = PetscObjectSetName((PetscObject)dm, problem_types[problem_choice]); CHKERRQ(ierr); // Distribute mesh over processes { DM dm_dist = NULL; PetscPartitioner part; ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr); ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr); ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr); if (dm_dist) { ierr = DMDestroy(&dm); CHKERRQ(ierr); dm = dm_dist; } } // Refine DMPlex with uniform refinement using runtime option -dm_refine ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr); ierr = DMSetFromOptions(dm); CHKERRQ(ierr); if (problem_choice == SPHERE) { ierr = ProjectToUnitSphere(dm); CHKERRQ(ierr); } // View DMPlex via runtime option ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRQ(ierr); } // Create DM ierr = SetupDMByDegree(dm, degree, num_comp_u, topo_dim, false, (BCFunction)NULL); CHKERRQ(ierr); // Create vectors ierr = DMCreateGlobalVector(dm, &U); CHKERRQ(ierr); ierr = VecGetLocalSize(U, &l_size); CHKERRQ(ierr); ierr = VecGetSize(U, &g_size); CHKERRQ(ierr); ierr = DMCreateLocalVector(dm, &U_loc); CHKERRQ(ierr); ierr = VecGetSize(U_loc, &xl_size); CHKERRQ(ierr); ierr = VecDuplicate(U, &V); CHKERRQ(ierr); ierr = VecDuplicate(U_loc, &V_loc); CHKERRQ(ierr); // Setup user structure ierr = PetscMalloc1(1, &user); CHKERRQ(ierr); // Set up libCEED CeedInit(ceed_resource, &ceed); CeedMemType mem_type_backend; CeedGetPreferredMemType(ceed, &mem_type_backend); ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr); if (!vec_type) { // Not yet set by user -dm_vec_type switch (mem_type_backend) { case CEED_MEM_HOST: vec_type = VECSTANDARD; break; case CEED_MEM_DEVICE: { const char *resolved; CeedGetResource(ceed, &resolved); if (strstr(resolved, "/gpu/cuda")) vec_type = VECCUDA; else if (strstr(resolved, "/gpu/hip/occa")) vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678 else if (strstr(resolved, "/gpu/hip")) vec_type = VECHIP; else vec_type = VECSTANDARD; } } ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr); } // Print summary if (!test_mode) { PetscInt P = degree + 1, Q = P + q_extra; const char *used_resource; CeedGetResource(ceed, &used_resource); ierr = PetscPrintf(comm, "\n-- libCEED + PETSc Surface Area of a Manifold --\n" " libCEED:\n" " libCEED Backend : %s\n" " libCEED Backend MemType : %s\n" " Mesh:\n" " Number of 1D Basis Nodes (p) : %d\n" " Number of 1D Quadrature Points (q) : %d\n" " Global nodes : %D\n" " DoF per node : %D\n" " Global DoFs : %D\n", used_resource, CeedMemTypes[mem_type_backend], P, Q, g_size/num_comp_u, num_comp_u, g_size); CHKERRQ(ierr); } // Setup libCEED's objects and apply setup operator ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr); ierr = SetupLibceedByDegree(dm, ceed, degree, topo_dim, q_extra, num_comp_x, num_comp_u, g_size, xl_size, problem_options[problem_choice], ceed_data, false, (CeedVector)NULL, (CeedVector *)NULL); CHKERRQ(ierr); // Setup output vector PetscScalar *v; ierr = VecZeroEntries(V_loc); CHKERRQ(ierr); ierr = VecGetArrayAndMemType(V_loc, &v, &mem_type); CHKERRQ(ierr); CeedVectorSetArray(ceed_data->y_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, v); // Compute the mesh volume using the mass operator: area = 1^T \cdot M \cdot 1 if (!test_mode) { ierr = PetscPrintf(comm, "Computing the mesh area using the formula: area = 1^T M 1\n"); CHKERRQ(ierr); } // Initialize u with ones CeedVectorSetValue(ceed_data->x_ceed, 1.0); // Apply the mass operator: 'u' -> 'v' CeedOperatorApply(ceed_data->op_apply, ceed_data->x_ceed, ceed_data->y_ceed, CEED_REQUEST_IMMEDIATE); // Gather output vector CeedVectorTakeArray(ceed_data->y_ceed, CEED_MEM_HOST, NULL); ierr = VecRestoreArrayAndMemType(V_loc, &v); CHKERRQ(ierr); ierr = VecZeroEntries(V); CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(dm, V_loc, ADD_VALUES, V); CHKERRQ(ierr); // Compute and print the sum of the entries of 'v' giving the mesh surface area PetscScalar area; ierr = VecSum(V, &area); CHKERRQ(ierr); // Compute the exact surface area and print the result CeedScalar exact_surface_area = 4 * M_PI; if (problem_choice == CUBE) { PetscScalar l = 1.0/PetscSqrtReal(3.0); // half edge of the cube exact_surface_area = 6 * (2*l) * (2*l); } PetscReal error = fabs(area - exact_surface_area); PetscReal tol = 5e-6; if (!test_mode || error > tol) { ierr = PetscPrintf(comm, "Exact mesh surface area : % .14g\n", exact_surface_area); CHKERRQ(ierr); ierr = PetscPrintf(comm, "Computed mesh surface area : % .14g\n", area); CHKERRQ(ierr); ierr = PetscPrintf(comm, "Area error : % .14g\n", error); CHKERRQ(ierr); } // Cleanup ierr = DMDestroy(&dm); CHKERRQ(ierr); ierr = VecDestroy(&U); CHKERRQ(ierr); ierr = VecDestroy(&U_loc); CHKERRQ(ierr); ierr = VecDestroy(&V); CHKERRQ(ierr); ierr = VecDestroy(&V_loc); CHKERRQ(ierr); ierr = PetscFree(user); CHKERRQ(ierr); ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr); CeedDestroy(&ceed); return PetscFinalize(); }
{ "alphanum_fraction": 0.6368662002, "avg_line_length": 39.3775510204, "ext": "c", "hexsha": "bb8f925bfc4fbaf8799ffafa8f0ca27d9525c77d", "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": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_path": "examples/petsc/area.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_path": "examples/petsc/area.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_path": "examples/petsc/area.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3030, "size": 11577 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gbpLib.h> #include <gbpMath.h> #include <gbpCosmo_core.h> #include <gbpCosmo_NFW_etc.h> #include <gsl/gsl_sf_expint.h> void init_Vmax_to_Mvir_NFW(cosmo_info **cosmo, int mode, double z) { interp_info *interp; if(!ADaPS_exist((*cosmo), "lVmax_to_lMvir_%.5f_interp", z)) { SID_log("Initializing Vmax->M_vir interpolation...", SID_LOG_OPEN); int n_k; double *lk_P; double *lM; double *lVmax; int n_M = 201; double lM_lo = 0.; double lM_hi = 20.; double dlM = (lM_hi - lM_lo) / (double)(n_M - 1); lM = (double *)SID_malloc(sizeof(double) * n_M); lVmax = (double *)SID_malloc(sizeof(double) * n_M); int i_M; for(i_M = 0; i_M < n_M; i_M++) { if(i_M == 0) lM[i_M] = lM_lo; else if(i_M == (n_M - 1)) lM[i_M] = lM_hi; else lM[i_M] = lM[i_M - 1] + dlM; } for(i_M = 0; i_M < n_M; i_M++) { lM[i_M] += take_log10(M_SOL); lVmax[i_M] = take_log10(V_max_NFW(take_alog10(lM[i_M]), z, mode, cosmo)); } init_interpolate(lVmax, lM, (size_t)n_M, gsl_interp_cspline, &interp); ADaPS_store_interp(cosmo, (void *)(interp), "lVmax_to_lMvir_%.5f_interp", z); SID_free(SID_FARG lM); SID_free(SID_FARG lVmax); SID_log("Done.", SID_LOG_CLOSE); } } double Vmax_to_Mvir_NFW(double V_max, double z, int mode, cosmo_info **cosmo) { double c_vir; double R_vir; double V2_vir; double g_c; double r_val = 0.; if(V_max > 0.) { interp_info *interp; init_Vmax_to_Mvir_NFW(cosmo, mode, z); interp = (interp_info *)ADaPS_fetch(*cosmo, "lVmax_to_lMvir_%.5f_interp", z); r_val = take_alog10(interpolate(interp, take_log10(V_max))); } return (r_val); }
{ "alphanum_fraction": 0.5631364562, "avg_line_length": 33.8620689655, "ext": "c", "hexsha": "2c96bd1477e691777b3c5435b8a79ab0d3f6def6", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/Vmax_to_Mvir_NFW.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/Vmax_to_Mvir_NFW.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/Vmax_to_Mvir_NFW.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 643, "size": 1964 }
/* Copyright 2017 InitialDLab Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once //#include <gsl/gsl_rng.h> //#include <gsl/gsl_randist.h> #include <random> #include <cassert> inline size_t next_fanout(size_t size, size_t min_fanout, size_t max_fanout) { if(size >= min_fanout + max_fanout) return max_fanout; if(size < max_fanout) { return size; } return size - min_fanout; } inline size_t calc_node_count(size_t size, size_t min_fanout, size_t max_fanout) { return (size % max_fanout) ? (size / max_fanout + 1) : (size / max_fanout) ; } template<typename Point> void dump_point(std::ostream & out, Point const& point) { out << boost::geometry::wkt(point); } template<typename Box> void dump_box(std::ostream & out, Box const& box) { out << boost::geometry::wkt(box.min_corner()) << ' ' << boost::geometry::wkt(box.max_corner()); } /* template<typename RNG> size_t alternate_binomial(size_t n, double p, RNG & rng) { if(p > 0.5) return n - alternate_binomial(n, 1.0-p, rng); std::uniform_real_distribution<float> coin_dist(0,1); double log_q = std::log(1.0 - p); size_t x = 0; double sum = 0; for(;;) { sum += std::log(coin_dist(rng)) / (n - x); if(sum < log_q) return x; ++x; } } */ template<typename RNG> inline size_t next_sample_size(size_t total_sample_size, size_t cur_subtree_size, size_t total_subtree_size, RNG & rng) { if(cur_subtree_size == 0) return 0; if(cur_subtree_size == total_sample_size) return total_sample_size; if(total_sample_size < 10) { size_t s = 0; std::uniform_real_distribution<float> dist(0,1); float prob = ((float)cur_subtree_size) / total_sample_size; for(size_t i = 0; i < total_sample_size; ++i) if(dist(rng) < prob) ++s; return s; } //std::binomial_distribution<int> distribution(((double)cur_subtree_size) / total_subtree_size, total_sample_size); std::binomial_distribution<int> distribution(total_sample_size, ((double)cur_subtree_size) / total_subtree_size); return distribution(rng); //static gsl_rng *_gsl_rng = nullptr; //if(!_gsl_rng){ _gsl_rng = gsl_rng_alloc (gsl_rng_taus); } //return gsl_ran_binomial(_gsl_rng, ((double)cur_subtree_size)/total_subtree_size, total_sample_size); /* return alternate_binomial( total_sample_size, ((double)cur_subtree_size) / total_subtree_size, rng ); */ /* return std::binomial_distribution<size_t>( total_sample_size, ((double)cur_subtree_size) / total_subtree_size )(rng); */ } template<typename RNG> inline void next_sample_size_bulk(int trials, const std::vector<int64_t> &prefix_weights, std::vector<int> &output_counts, RNG & rng) { assert(prefix_weights.size() == output_counts.size()); // special case if (prefix_weights.size() == 1) { output_counts[0] = trials; return; } int64_t accum = 0; for (int i = 0; i < prefix_weights.size(); ++i) { output_counts[i] = next_sample_size(trials, prefix_weights[i] - accum, prefix_weights.back(), rng); accum = prefix_weights[i]; } //std::vector<int64_t> each_trial; //each_trial.resize(trials); //std::uniform_int_distribution<int64_t> dist(0, prefix_weights.back()); //std::generate(each_trial.begin(), each_trial.end(), [&rng, &dist]() {return dist(rng);}); //std::sort(each_trial.begin(), each_trial.end()); //auto last_max = each_trial.begin(); //auto output_itr = output_counts.begin(); //for (auto weight : prefix_weights) //{ // auto next_max = std::lower_bound(last_max, each_trial.end(), weight); // *output_itr = std::distance(last_max, next_max); // ++output_itr; // last_max = next_max; //} //if (last_max != each_trial.end()) // output_counts.back() += std::distance(last_max, each_trial.end()); //for (int64_t samples_inserted = 0; samples_inserted < trials; ++samples_inserted) //{ // int64_t r_val = dist(rng); // auto i_itr = std::lower_bound(prefix_weights.begin(), prefix_weights.end(), r_val); // int index = i_itr - prefix_weights.begin(); // ++output_counts[index]; //} //std::uniform_int_distribution<int64_t> dist(0, prefix_weights.back()); //for (int64_t samples_inserted = 0; samples_inserted < trials; ++samples_inserted) //{ // int64_t r_val = dist(rng); // auto i_itr = std::lower_bound(prefix_weights.begin(), prefix_weights.end(), r_val); // int index = i_itr - prefix_weights.begin(); // ++output_counts[index]; //} }
{ "alphanum_fraction": 0.6678266922, "avg_line_length": 30.7326203209, "ext": "h", "hexsha": "bd6a3fcea86ae5c3c1bc63ef31e72df62b9f1874", "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": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_forks_repo_path": "util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "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": "InitialDLab/SONAR-SamplingIndex", "max_issues_repo_path": "util.h", "max_line_length": 121, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "InitialDLab/SampleIndex", "max_stars_repo_path": "util.h", "max_stars_repo_stars_event_max_datetime": "2019-07-18T21:21:35.000Z", "max_stars_repo_stars_event_min_datetime": "2017-09-30T22:34:57.000Z", "num_tokens": 1480, "size": 5747 }
/* -*- mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: sw=4 ts=8 et tw=80 */ /* filter.c * * This file contains a few time-domain processing routines, copied * without much modification from moby. * * These are mostly needed for filtering during mapping, and for * various pathologies processing. */ #include "pyactpol.h" #include "myassert.h" #include <stdbool.h> #include <fftw3.h> #include <gsl/gsl_cblas.h> static PyObject *remove_mean(PyObject *self, PyObject *args) { PyArrayObject *tod_array; PyArrayObject *dets_array; PyArrayObject *means_array; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &tod_array, &PyArray_Type, &dets_array )) po_raise("invalid arguments"); ASSERT_CARRAY_TYPE_NDIM(tod_array, NPY_FLOAT32, 2); ASSERT_CARRAY_TYPE_NDIM(dets_array, NPY_INT64, 1); long int ndata = PyArray_DIMS(tod_array)[1]; int ndet = PyArray_DIMS(dets_array)[0]; long int *dets = PyArray_DATA(dets_array); float *data = PyArray_DATA(tod_array); npy_intp dims[1]; dims[0] = ndet; means_array = (PyArrayObject *)PyArray_SimpleNew(1, dims, NPY_DOUBLE); double *means = (double *)PyArray_DATA(means_array); #pragma omp parallel for shared(data,ndata,dets,ndet) for (int d=0; d<ndet; d++) { double m = 0.0; for (long int i = dets[d]*ndata; i < (dets[d]+1)*ndata; i++) m += (double)data[i]; m /= ndata; means[d] = m; for (long int i = dets[d]*ndata; i < (dets[d]+1)*ndata; i++) data[i] -= m; } return PyArray_Return(means_array); } static void filter_one_detector( fftwf_complex *data, const float *real, const float *imag, int ndata, fftwf_plan p_forward, fftwf_plan p_back, int detrend, int retrend); static void mbTODFourierFilter( float *tod, /// 2d data (nd,nsamps) to filter int nsamps, ///< data size, fast dimension const int *dets, ///< tod detector numbers -- designates ///< which detectors to filter int ndets, ///< length of the dets vector const float *freq, ///> frequency vector (nsamps) const float *real, ///< real component of filter, (nsamps) const float *imag, ///< imaginary component of filter, (nsamps) const float *tau, ///< time constants to deconvolve (ndets) int tau_do_inverse,///< true if deconvolving time constants int detrend, ///< whether to detrend the data before filtering int retrend) ///< whether to retrend the detrended data after filtering { //float *freqs; //freqs = genFreqs(tod->ndata, tod->sampleTime); int n = nsamps; fftwf_complex *data = fftwf_malloc(n * sizeof(fftwf_complex)); fftwf_plan p_forward; fftwf_plan p_back; p_forward = fftwf_plan_dft_1d(n, data, data, FFTW_FORWARD, FFTW_ESTIMATE); p_back = fftwf_plan_dft_1d(n, data, data, FFTW_BACKWARD, FFTW_ESTIMATE); fftwf_free(data); #pragma omp parallel shared(tod,real,imag,dets,ndets,freq,tau,tau_do_inverse, \ detrend,retrend,n,p_forward,p_back) default (none) { fftwf_complex *fftdata = fftwf_malloc(n * sizeof(fftwf_complex)); // Customize the filter with a time constant per-detector float *tmp_real = malloc(n * sizeof(float)); float *tmp_imag = malloc(n * sizeof(float)); if (tau == NULL) { for (int j=0; j<n; j++) { tmp_real[j] = real[j]; tmp_imag[j] = imag[j]; } } #pragma omp for for (int i = 0; i < ndets; i++) { for (int j = 0; j < n; j++) { if (tau != NULL) { float gain, dtc; dtc = 2.0*tau[i]*freq[j]*M_PI; if (tau_do_inverse) { gain = 1.0; } else { gain = 1.0 / (1.0 + dtc*dtc); dtc = -dtc; } tmp_real[j] = gain * (real[j] - imag[j]*dtc); tmp_imag[j] = gain * (real[j]*dtc + imag[j]); } fftdata[j][0] = tod[dets[i]*n+j]; fftdata[j][1] = 0.0; } filter_one_detector(fftdata, tmp_real, tmp_imag, n, p_forward, p_back, detrend, retrend); for (int j = 0; j < n; j++) tod[dets[i]*n+j] = fftdata[j][0]; } fftwf_free(fftdata); free(tmp_real); free(tmp_imag); } #pragma omp critical { fftwf_destroy_plan(p_forward); fftwf_destroy_plan(p_back); } } /*--------------------------------------------------------------------------------*/ /*! * Filter a detector from a TOD with a give Fourier-domain filter. * \param data The data vector to be filtered. Modified and returns the filtered result. * \param real The real part of the filter. * \param imag The imaginary part of the filter. * \param p_forward The FFTW plan for going to the frequency domain. * \param p_back The FFTW plan for going back to the time domain. * \param ndata The length of the data set. */ static void filter_one_detector(fftwf_complex *data, const float *real, const float *imag, int ndata, fftwf_plan p_forward, fftwf_plan p_back, int detrend, int retrend) { float tmp; double x0 = 0.0, x1 = 0.0, m = 0, trendSlope = 0; int win = 1000; if (win > ndata/2) win = ndata/2; if (detrend) { for (int i = 0; i < win; i++) { x0 += data[i][0]; x1 += data[ndata-1 - i][0]; } x0 /= (double)win; x1 /= (double)win; m = (x0+x1)/2.0; trendSlope = (x1-x0)/(double)(ndata-1.0-win); for (int j = 0; j < ndata; j++) data[j][0] -= (x0 - m + trendSlope*((double) (j - win/2))); } fftwf_execute_dft(p_forward, data, data); for (int j = 0; j < ndata; j++) { // Multiply by complex filter tmp = data[j][0]*real[j] - data[j][1]*imag[j]; data[j][1] = (data[j][0]*imag[j] + data[j][1]*real[j]) / (float)ndata; data[j][0] = tmp / (float)ndata; } fftwf_execute_dft(p_back, data, data); if (retrend && detrend) for (int j = 0; j < ndata; j++) data[j][0] += (x0 - m + trendSlope*((double) (j - win/2))); } /*--------------------------------------------------------------------------------*/ /*! * Apply a pre-calculated smoothing filter to a data vector. Then do one of * (1) Just smooth the data if (do_smooth). * (2) Preserve the data, replacing with smoothed data only during large glitches if (apply_glitch). * (3) Fill a vector cutvec saying whether to cut each point due to glitches if (do_cuts). * You can call any combination that doesn't involve both #1 and #2. * If apply_glitch is true, then replace anything flagged as over the cut threshold (defined as a * smoothed value differing from raw by at least nsig*median absolute deviation of smoothed values) * with the smoothed value. Since the glitch filter should have zero in the middle, height of * cosmic ray doesn't matter. */ typedef float actData; static void glitch_one_detector( fftwf_complex *fftdata, ///< Real data vector to filter. Modified and returned. const float *real, ///< The pre-calculated smoothing filter to use (real part). char *cutvec, ///< Pre-allocated vector of length n. Returns cut list if (do_cuts). int n, ///< Length of the input data vector mydat. fftwf_plan p_forward, ///< The FFTW plan for going to the frequency domain. fftwf_plan p_back, ///< The FFTW plan for going back to the time domain. actData nsig, ///< The cut threshold is this factor times the median abs deviation of smooths. int minSep) ///< Min separation between cut detections to consider them different cuts. { // Save a copy of the input data, then apply the smoothing filter only. actData *mydat = malloc(sizeof(actData)*n); float *imag = malloc(n * sizeof(float)); for (int i = 0; i < n; i++) { mydat[i] = fftdata[i][0]; imag[i] = 0.0; } filter_one_detector(fftdata, real, imag, n, p_forward, p_back, true, false); free(imag); // tmpclean is the absolute difference between smooth and raw vectors. // Find its median (for use in cuts). float *tmpclean = malloc(n*sizeof(actData)); for (int j = 0; j < n; j++) tmpclean[j] = fabs(fftdata[j][0]); actData thresh = pyactpol_sselect((n*3)/4, n, tmpclean); thresh -= pyactpol_sselect(n/4, n, tmpclean); thresh *= 0.741*nsig; // Find cuts and reset raw data int lind = 0; memset(cutvec,0,sizeof(*cutvec)*n); for (int j = 0; j < n; j++) { if (fabs(fftdata[j][0]) > thresh) { cutvec[j] = 1; if (j-lind < minSep) for (int k = lind+1; k < j; k++) cutvec[k] = 1; lind = j; } fftdata[j][0] = mydat[j]; } free(mydat); free(tmpclean); } /*--------------------------------------------------------------------------------*/ /*! * Remove glitches from multiple detector data vectors in a TOD using a pre-computed smoothing (and * glitch removal) filter. Also, if (do_cuts), then also apply all glitches as new cuts in the cuts * object. */ static void mbGlitchC( float *tod_data, ///< The TOD to modify. int nsamps, ///< tod.shape[1] const float *filt, ///< The pre-calculated smoothing filter to use. const int *dets, ///< List of detectors (by index) to clean. int ndet, ///< Number of detectors to clean (length of dets) PyObject **cuts, ///< An array of pointers to PyObjects, where we should put the cuts. actData nsig, ///< The cut threshold is this factor times the median abs deviation of smooths. int maxGlitch, ///< Maximum allowed number of glitches. If exceeded, cut whole detector. int minSep) ///< Minimum separation between cuts to consider them different cuts. { int **cuts_data = malloc(ndet * sizeof(*cuts_data)); int *n_cuts = malloc(ndet * sizeof(*n_cuts)); assert(cuts_data != NULL && n_cuts != NULL); #pragma omp parallel shared(tod_data,filt,nsamps,dets,ndet,cuts_data,n_cuts,nsig,maxGlitch,minSep) default(none) { fftwf_plan p_forward; fftwf_plan p_back; const int n = nsamps; fftwf_complex *fftdata = fftwf_malloc(sizeof(fftwf_complex)*n); char *cutvec = malloc(n*sizeof(int)); #pragma omp critical { p_forward = fftwf_plan_dft_1d(n, fftdata, fftdata, FFTW_FORWARD, FFTW_ESTIMATE); p_back = fftwf_plan_dft_1d(n, fftdata, fftdata, FFTW_BACKWARD, FFTW_ESTIMATE); } #pragma omp for for (int i = 0; i < ndet; i++) { for (int j = 0; j < n; j++) { fftdata[j][0] = tod_data[dets[i]*nsamps+j]; fftdata[j][1] = 0.0; } glitch_one_detector(fftdata, filt, cutvec ,n, p_forward, p_back, nsig, minSep); for (int j = 0; j < n; j++) tod_data[dets[i]*nsamps+j] = fftdata[j][0]; /* Convert cuts vector start / stop positions */ cuts_data[i] = pyactpol_cuts_vector_from_mask(cutvec, nsamps, &n_cuts[i]); } #pragma omp critical { fftwf_destroy_plan(p_forward); fftwf_destroy_plan(p_back); fftwf_free(fftdata); free(cutvec); } } /* Non-parallel: create arrays for the resulting cuts vectors. */ npy_intp dims[2] = {0, 2}; for (int i=0; i<ndet; i++) { dims[0] = n_cuts[i]; cuts[i] = PyArray_SimpleNew(2, dims, NPY_INT); if (n_cuts[i] > 0) { int *dest = PyArray_DATA((PyArrayObject *)cuts[i]); memcpy(dest, cuts_data[i], 2*n_cuts[i]*sizeof(*dest)); free(cuts_data[i]); } } } /* filter_tod_data * * Apply an arbitrary Fourier filter to time ordered data. Possibly * also convolve or deconvolve the effects of a time constant. * * Input: * data: (ndet,nsamps) time-ordered data to filter (modified in place). * dets: (ndet_used) index of data vectors to actually filter. * filter: (nsamps) complex filter to apply to the data * taus: (ndet_used) time constants, in seconds, to convolve/deconvolve. * dt: the sample separation, in seconds. * tau_gain: boolean, set to true for time constant deconvolution. * detrend: boolean, set to true to remove a trend prior to filtering. * retrend: boolean, set to true to restore the removed trend after filtering. */ PyDoc_STRVAR(filter_tod_data__doc__, "filter_tod_data(data, dets, filter, time_const)\n" "\n" "The dets array gives indices into the first dimension of data, " "so the largest value in dets must be smaller than data.shape[0].\n" "\n" "Applies\n" " data[dets,:] *= cal[:,None]\n" ); static PyObject *filter_tod_data(PyObject *self, PyObject *args) { PyArrayObject *tod_array; PyArrayObject *det_idx_array; PyArrayObject *filter_array; PyObject *taus_object; double dt; int tau_do_inverse; int detrend; int retrend; if (!PyArg_ParseTuple(args, "O!O!O!Odiii", &PyArray_Type, &tod_array, &PyArray_Type, &det_idx_array, &PyArray_Type, &filter_array, &taus_object, &dt, &tau_do_inverse, &detrend, &retrend )) po_raise("invalid arguments"); // Make a frequency vector int nsamps = PyArray_DIMS(tod_array)[1]; float *freq = malloc(nsamps*sizeof(*freq)); float df = 1.0/nsamps/dt; int i=0; for (; i<nsamps/2; i++) freq[i] = i*df; for (; i<nsamps; i++) freq[i] = (i-nsamps)*df; // Copy filter to real and imaginary pieces ASSERT_CARRAY_TYPE_NDIM(filter_array, NPY_COMPLEX64, 1); po_assert(PyArray_DIMS(filter_array)[0] == nsamps); float *filter = PyArray_DATA(filter_array); float *real = malloc(nsamps*sizeof(*real)); float *imag = malloc(nsamps*sizeof(*imag)); for (i=0; i<nsamps; i++) { real[i] = filter[i*2]; imag[i] = filter[i*2+1]; } // Those other vectors po_assert(PyArray_TYPE(tod_array) == NPY_FLOAT32); float *tod = PyArray_DATA(tod_array); ASSERT_CARRAY_TYPE_NDIM(det_idx_array, NPY_INT32, 1); int *det_idx = PyArray_DATA(det_idx_array); float *tau = NULL; if (taus_object != Py_None) { PyArrayObject *taus_array = (PyArrayObject*)taus_object; ASSERT_CARRAY_TYPE_NDIM(taus_array, NPY_FLOAT32, 1); po_assert( PyArray_DIMS(det_idx_array)[0] == PyArray_DIMS(taus_array)[0]); tau = PyArray_DATA(taus_array); } // Go mbTODFourierFilter(tod, nsamps, det_idx, PyArray_SIZE(det_idx_array), freq, real, imag, tau, tau_do_inverse, detrend, retrend); free(freq); free(real); free(imag); Py_RETURN_NONE; } /* deglitch_tod_data * * Input: * data: (ndet,nsamps) time-ordered data to filter (modified in place). * dets: (ndet_used) index of data vectors to actually filter. * filter: (real!) low-pass filter that will be used to remove low * frequency signal * nsig: float that controls strength of glitch rejection. * maxGlitch: maximum number of allowed glitches; when limit is reached * the whole detector will be cut. * minSep: integer, minimum separation cuts must have to not get * auto-joined. * * Returns: * cuts: list of cuts vectors, indicating which samples were deglitched. * */ static PyObject *get_glitch_cuts(PyObject *self, PyObject *args) { PyArrayObject *tod_array; PyArrayObject *det_idx_array; PyArrayObject *filter_array; double nsig; int maxGlitch; int minSep; if (!PyArg_ParseTuple(args, "O!O!O!dii", &PyArray_Type, &tod_array, &PyArray_Type, &det_idx_array, &PyArray_Type, &filter_array, &nsig, &maxGlitch, &minSep )) po_raise("invalid arguments."); int nsamps = PyArray_DIMS(tod_array)[1]; ASSERT_CARRAY_TYPE_NDIM(filter_array, NPY_FLOAT32, 1); float *filter = PyArray_DATA(filter_array); // Those other vectors po_assert(PyArray_TYPE(tod_array) == NPY_FLOAT32); float *tod = PyArray_DATA(tod_array); ASSERT_CARRAY_TYPE_NDIM(det_idx_array, NPY_INT32, 1); int *det_idx = PyArray_DATA(det_idx_array); // Deglitcher will return some cuts information int ndets = PyArray_DIMS(det_idx_array)[0]; PyObject **cuts = malloc(ndets*sizeof(PyObject*)); assert(cuts != NULL); // Go mbGlitchC(tod, nsamps, filter, det_idx, PyArray_SIZE(det_idx_array), cuts, nsig, maxGlitch, minSep); // Turn the cuts into a list. PyObject *cuts_list = PyList_New(ndets); for (int i=0; i<ndets; i++) PyList_SET_ITEM(cuts_list, i, cuts[i]); free(cuts); return cuts_list; } // -------------------------------------------------------------------- // Analyzes the scan to determine scan frequency, amplitude, speed, and // identify sections of good and bad scan /* Error codes: 0: Good scan 1: No scan 2: Bad scan ending 3: Bad scan beginning 4: Multiple scan sections 5: Too many scan sections */ typedef struct { int min_chunk; float min_scan; float max_scan; float freq; float speed; float az_max; float az_min; int *section_limits; int nsection; int max_sections; } mbScan; static int mbAnalyzeScan(double *az, double *ctime, int ndata, mbScan *scan) { // Hack the downsampleLevel to none... int downsampleLevel = 1; double sampleTime = ctime[1] - ctime[0]; // Consider N_chunk segments of length chunck int N_chunk = (ndata*downsampleLevel)/scan->min_chunk; if (N_chunk == 0) N_chunk = 1; int chunk = ndata/N_chunk; int i, k, nSamp; double y, Sy, Sxy; double az_Hi, az_Low; float *az_max = (float *)malloc(N_chunk * sizeof(float)); float *az_min = (float *)malloc(N_chunk * sizeof(float)); float *freq = (float *)malloc(N_chunk * sizeof(float)); float *speeds = (float *)malloc(N_chunk * sizeof(float)); // For each chunk for (int c = 0; c < N_chunk; c++) { i = c*chunk + 1; /* Determine az_min and az_max by finding the first two * turn-arounds in this chunk, if possible. */ if (az[i] > az[i-1]) { while ((az[i] >= az[i-1]) && (i < (c+1)*chunk)) i++; az_max[c] = az[i-1]; if (i > c*chunk + 1 + chunk/2) { freq[c] = -1; continue; } i += 100; while ((az[i] <= az[i-1]) && (i < (c+1)*chunk)) i++; az_min[c] = az[i-1]; } else { while ((az[i] <= az[i-1]) && (i < (c+1)*chunk)) i++; az_min[c] = az[i-1]; if (i > c*chunk + 1 + chunk/2) { freq[c] = -1; continue; } i += 100; while ((az[i] >= az[i-1]) && (i < (c+1)*chunk)) i++; az_max[c] = az[i-1]; } /* Reject weird scan amplitudes */ if ((az_max[c] - az_min[c] < scan->min_scan) || (az_max[c] - az_min[c] > scan->max_scan) || (i == (c+1)*chunk)) { freq[c] = -1; continue; } /* Now go through chunk again, getting speed measurements at * every sample that lies in the central 20% of the az range. * Also get the mean time of each such segment, and basically * fit a line to those times to get the scan frequency. */ az_Hi = az_max[c]*0.6 + az_min[c]*0.4; az_Low = az_max[c]*0.4 + az_min[c]*0.6; nSamp = 0; Sy = 0; Sxy = 0; speeds[c] = 0.0; i = c*chunk; /* Skip any initial segment that is in the central range */ while ((az[i] > az_Low) && (az[i] < az_Hi) && (i < (c+1)*chunk)) i++; while (i < (c+1)*chunk) { if ((az[i] > az_Low) && (az[i] < az_Hi)) { nSamp++; k = 0; y = 0.0; while ((az[i] > az_Low) && (az[i] < az_Hi) && (i < (c+1)*chunk)) { y += ctime[i] - ctime[0]; k++; i++; } speeds[c] += fabs(az[i-1]-az[i-k-1])/k; y /= k; Sy += y; Sxy += nSamp*y; } else i++; } speeds[c] /= nSamp*sampleTime; if (nSamp > 1) freq[c] = nSamp*(nSamp-1) / 12.0 / (2*Sxy/(nSamp+1) - Sy); else { freq[c] = -1; } } /* Now just throw out any bad chunks, collapsing the various * arrays. */ k = 0; for (int c = 0; c < N_chunk; c++) { /* printf("freq[%d] = %f; speed[%d] = %f; az_max[%d] = %f; az_min[%d] = %f\n", */ /* c,freq[c], c, speeds[c], c, az_max[c], c, az_min[c]); */ if (freq[c] != -1) { az_max[k] = az_max[c]; az_min[k] = az_min[c]; freq[k] = freq[c]; speeds[k] = speeds[c]; k++; } } /* You either of zero, many, or a small number of good chunks. So * compute and store nothing, the median, or the mean, * respectively. */ if (k == 0) { // This TOD seems to have no scanning return 1; } if (k > 2) { scan->az_max = compute_median(k, az_max); scan->az_min = compute_median(k, az_min); scan->freq = compute_median(k, freq); scan->speed = compute_median(k,speeds); } else { scan->az_max = scan->az_min = scan->freq = scan->speed = 0.0; for (i = 0; i < k; i++) { scan->az_max += az_max[i]/k; scan->az_min += az_min[i]/k; scan->freq += freq[i]/k; scan->speed += speeds[i]/k; } } free(az_max); free(az_min); free(freq); free(speeds); //printf("freq_m = %f; speed_m = %f\n", scan->freq, scan->speed); /* * ACT 2 * * Look for bad turn-arounds. Construct list of segments over which * scanning looks ok. Return 0 only if the whole scan looks like one * good scan session. */ int turn = 0, pivot = 0; int hperiod = (int)(1./2/scan->freq/sampleTime); float speed, speed300; float delta = scan->az_max - scan->az_min; float margin1 = delta*0.08; float margin2 = delta*0.01; scan->nsection = 0; i = 3; /* Loop over half-scans... hopefully */ while (i+hperiod < ndata) { while (turn == 0) { if (scan->nsection == scan->max_sections) { return 5; // Too many scan sections } speed = (az[i] - az[i-3])/sampleTime/3; // Case in middle of the scan if ((fabs(fabs(speed) - scan->speed)/scan->speed < 0.1) && (az[i] <= scan->az_max - margin1) && (az[i] >= scan->az_min + margin1)) { // good speed if (speed > 0) turn = 1; else turn = -1; scan->nsection++; scan->section_limits[(scan->nsection-1)*2] = i-3; i++; // Search for pivot while ((speed*turn > 0) && (i < ndata)) { speed = (az[i] - az[i-1])/sampleTime; i++; } pivot = i-1; turn *= -1; //printf("Add1: az_pivot = %f, turn = %d\n", az[pivot], turn); break; } // Case in the lower or upper turnarounds else if (((az[i] > scan->az_max - margin1) && (az[i] < scan->az_max + margin2)) || ((az[i] < scan->az_min + margin1) && (az[i] > scan->az_min - margin2))) { if (i >= ndata - 300) { return 2; // Bad scan end } speed300 = (az[i+300] - az[i+297])/sampleTime/3; if ((((speed300 < 0) && (az[i] > (scan->az_max + scan->az_min)/2)) || ((speed300 > 0) && (az[i] < (scan->az_max + scan->az_min)/2))) && (fabs(fabs(speed300) - scan->speed)/scan->speed < 0.1)) { //good turnaround while (speed == 0) { i++; speed = (az[i] - az[i-1])/sampleTime; } scan->nsection++; scan->section_limits[(scan->nsection-1)*2] = i-3; if (az[i] > (scan->az_max + scan->az_min)/2) turn = -1; else turn = 1; // Search for pivot while ((speed*turn < 0) && (i < ndata-300)) { i++; speed = (az[i] - az[i-1])/sampleTime; } pivot = i-1; if (((turn == -1) && (fabs(az[pivot] - scan->az_max) > margin2)) || ((turn == 1) && (fabs(az[pivot] - scan->az_min) > margin2))) { while ((speed*turn > 0) && (i < ndata-300)) { i++; speed = (az[i] - az[i-1])/sampleTime; } turn *= -1; } pivot = i-1; //printf("Add2: speed300 = %f; az = %f; az_m = %f\n", // speed300, az[i], (scan->az_max + scan->az_min)/2); break; } else i++; } else { i++; } if (i > ndata - hperiod) { if (scan->nsection > 1) return 4; //multiple scan sections else return 2; // Bad scan end } } //printf("pivot = %d; turn = %d; az = %f\n",pivot, turn, az[pivot+hperiod]); i = pivot; // Check if we are on a turnarond if (((turn == 1) && (fabs(az[pivot+hperiod] - scan->az_max) > margin2)) || ((turn == -1) && (fabs(az[pivot+hperiod] - scan->az_min) > margin2))) { // not good //printf("az = %f\n",fabs(az[pivot+hperiod])); //printf("turn = %d\n",turn); turn = 0; scan->section_limits[(scan->nsection-1)*2+1] = i; i += hperiod; } else { // Reset the pivot every time to avoid numerical errors speed = (az[i] - az[i-1])/sampleTime; if (speed*turn < 0) { while (speed*turn < 0) { i++; speed = (az[i] - az[i-1])/sampleTime; } pivot = i-1; } else { while (speed*turn > 0) { i--; speed = (az[i] - az[i-1])/sampleTime; } pivot = i+1; } pivot += hperiod; i = pivot; turn *= -1; } } if (turn != 0) scan->section_limits[(scan->nsection-1)*2+1] = ndata-1; if (scan->nsection > 1) return 4; //multiple scan sections else if ((scan->section_limits[0] == 0) && (scan->section_limits[1] == ndata-1)) return 0; // Good scan else return 3; // Bad beginning of scan } PyDoc_STRVAR(analyze_scan__doc__, "analyze_scan(az, times)\n" "\n" "Determine basic properties of a triangle-wave azimuth scan. " "Each vector should be a simple ndarray of doubles, with az " "in radians and times in seconds.\n" "\n" "Returns a tuple of items:\n" " (status, speed, scan_freq, az_max, az_min, sections_array)\n" "\n" "Units are combinations of radians and seconds. status=0 is " "good; otherwise there is something weird with the scan, which " "can you can figure out from sections_array.\n"); static PyObject *analyze_scan(PyObject *self, PyObject *args) { PyArrayObject *az_array; PyArrayObject *ctime_array; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &az_array, &PyArray_Type, &ctime_array )) po_raise("invalid arguments."); double *az = PyArray_DATA(az_array); ASSERT_CARRAY_TYPE_NDIM(az_array, NPY_FLOAT64, 1); double *ctime = PyArray_DATA(ctime_array); ASSERT_CARRAY_TYPE_NDIM(ctime_array, NPY_FLOAT64, 1); int nsamps = PyArray_DIMS(ctime_array)[0]; mbScan scan; scan.min_chunk = 24000; scan.min_scan = 0.00873; // Half a degree in azimuth scan.max_scan = 0.34907; // 20 degrees in azimuth scan.freq = 0.0; scan.speed = 0.0; scan.az_max = 0.0; scan.az_min = 0.0; scan.nsection = 0; scan.max_sections = 5; scan.section_limits = (int*)malloc(2*scan.max_sections * sizeof(int)); for (int i = 0; i < 2*scan.max_sections; i++) scan.section_limits[i] = -1; int scan_err = mbAnalyzeScan(az, ctime, nsamps, &scan); // Pack up the scan sections in a little array... npy_intp dims[2] = {scan.nsection, 2}; PyArrayObject* sections_array = (PyArrayObject*) PyArray_SimpleNew(2, dims, NPY_INT32); for (int i=0; i<scan.nsection*2; i++) ((int*)PyArray_DATA(sections_array))[i] = scan.section_limits[i]; free(scan.section_limits); /* Return everything in a tuple. Update the docstring ^^^ if you * alter this. */ return Py_BuildValue("iffffN", scan_err, scan.speed, scan.freq, scan.az_max, scan.az_min, sections_array); } /// ------------------------------------------------------------------------ /// Simple search for TOD jumps static PyObject *find_jumps(PyObject *self, PyObject *args) { PyArrayObject *data_array; int dsStep, window; if (!PyArg_ParseTuple(args, "O!ii", &PyArray_Type, &data_array, &dsStep, &window )) po_raise("invalid arguments."); // Types and ordering... the ordering is stricter than we really need. ASSERT_CARRAY_TYPE_NDIM(data_array, NPY_FLOAT32, 2); int ndet = PyArray_DIMS(data_array)[0]; int nsamps = PyArray_DIMS(data_array)[1]; int ndata = nsamps/dsStep; float *tod_data = PyArray_DATA(data_array); npy_intp dims[1]; dims[0] = ndet; PyObject *jump_array = PyArray_SimpleNew(1, dims, NPY_FLOAT32); float *jump = PyArray_DATA((PyArrayObject*) jump_array); // Downsample data float *data = (float *)malloc(ndet * ndata * sizeof(float)); for (int i = 0; i < ndet; i++) { float *this_data = tod_data + nsamps * i; for (int j = 0; j < ndata; j++) { data[i*ndata + j] = this_data[dsStep * j]; } } // Find jumps int w = window; int nj = ndata-2*w+1; float jump_j; for (int i = 0; i < ndet; i++) { int d = i*ndata; jump[i] = 0; for (int j = 0; j < nj; j++) { jump_j = 0; for (int k=0; k<w; k++) jump_j += data[d+j+k] - data[d+j+k+w]; jump_j /= w; if (fabs(jump_j) > jump[i]) jump[i] = fabs(jump_j); } } free(data); return jump_array; } /// ------------------------------------------------------------------------ /// Perform preselection of detectors depending on correlation with common /// mode and gain with respect to the common mode. The common mode is /// obtained using the median of the initial set of candidates. static PyObject *preselect_dets(PyObject *self, PyObject *args) { PyArrayObject *data_array; PyArrayObject *sel_array; double min_corr, norm_factor; int dsStep; if (!PyArg_ParseTuple(args, "O!O!ddi", &PyArray_Type, &data_array, &PyArray_Type, &sel_array, &min_corr, &norm_factor, &dsStep )) po_raise("invalid arguments."); // Types and ordering... the ordering is stricter than we really need. ASSERT_CARRAY_TYPE_NDIM(data_array, NPY_FLOAT32, 2); int ndet = PyArray_DIMS(data_array)[0]; int nsamps = PyArray_DIMS(data_array)[1]; int ndata = nsamps/dsStep; // Selections array ASSERT_CARRAY_TYPE_NDIM(sel_array, NPY_INT32, 1); po_assert(PyArray_DIMS(sel_array)[0] == ndet); float *tod_data = PyArray_DATA(data_array); int *sel = PyArray_DATA(sel_array); // Produce list of detector candidates int N = 0; for (int i = 0; i < ndet; i++) if (sel[i]) N++; int *dets = (int *)malloc(N * sizeof(int)); int j = 0; for (int i = 0; i < ndet; i++) if (sel[i]) {dets[j] = i; j++;} // Downsample data and obtain norm of every detector TOD int NN = N; float *norm = (float *)malloc(N * sizeof(float)); float *norm2 = (float *)malloc(N * sizeof(float)); float *data = (float *)malloc(N * ndata * sizeof(float)); for (int i = 0; i < N; i++) { float *this_data = tod_data + nsamps * dets[i]; norm[i] = 0.0; for (int j = 0; j < ndata; j++) { data[i*ndata + j] = this_data[dsStep * j]; norm[i] += this_data[dsStep * j]*this_data[dsStep * j]; } norm[i] = sqrt(norm[i]); norm2[i] = norm[i]; } float norm_m = compute_median(N,norm2); for (int i = 0; i < N; i++) { if ((norm[i]/norm_m > norm_factor) || (norm[i]/norm_m < 1./norm_factor)) { sel[dets[i]] = 0; NN--; } } // Obtain median common mode float cm2 = 0.0; float *cm = (float *)malloc(ndata * sizeof(float)); float *temp = (float *)malloc(N * sizeof(int)); int k; for (int s = 0; s < ndata; s++) { k = 0; for (int j = 0; j < N; j++) { if (sel[dets[j]]) { temp[k] = data[j*ndata + s]/norm[j]; k++; } } cm[s] = compute_median(NN, temp); cm2 += cm[s] * cm[s]; } // Select according to correlation and gain float *dot = (float *)malloc(N * sizeof(float)); cblas_sgemv(CblasRowMajor, CblasNoTrans, N, ndata, 1.0, data, ndata, cm, 1, 0.0, dot, 1); // Select according to correlation first double c; for (int i = 0; i < N; i++) { if (sel[dets[i]]) { if (norm[i] != 0.0) c = dot[i]/norm[i]/sqrt(cm2); else c = 0.0; if (c < min_corr) { sel[dets[i]] = 0; NN--; } } } free(norm); free(data); free(dets); free(cm); free(temp); free(dot); Py_RETURN_NONE; } PyDoc_STRVAR(preselect_dets__doc__, "preselect_dets(data, sel, min_corr, norm_factor, dsStep)\n" ); PyDoc_STRVAR( get_drift_tests__doc__, "get_drift_tests(...)\n" ); //////////////////////////////////////////////////////////////////////////// // CLAPACK WRAPPER // //////////////////////////////////////////////////////////////////////////// static int sgesdd(char JOBZ, int M, int N, float *A, int LDA, float *S, float *U, int LDU, float *VT, int LDVT, float *WORK, int LWORK, int *IWORK) { extern void sgesdd_(char *JOBZp, int *Mp, int *Np, float *A, int *LDAp, float *S, float *U, int *LDUp, float *VT, int *LDVTp, float *WORK, int *LWORKp, int *IWORK, int *INFOp); int INFO; sgesdd_(&JOBZ, &M, &N, A, &LDA, S, U, &LDU, VT, &LDVT, WORK, &LWORK, IWORK, &INFO); return INFO; } static PyObject *get_drift_tests(PyObject *self, PyObject *args) { PyArrayObject *tod_array; PyArrayObject *row_array; PyArrayObject *col_array; PyArrayObject *ldet_array; PyArrayObject *ddet_array; PyArrayObject *temp_array; int dsStep, nBlock, nModes, removeDarkCM; if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!iiii", &PyArray_Type, &tod_array, &PyArray_Type, &row_array, &PyArray_Type, &col_array, &PyArray_Type, &ldet_array, &PyArray_Type, &ddet_array, &PyArray_Type, &temp_array, &dsStep, &nBlock, &nModes, &removeDarkCM )) po_raise("invalid arguments."); // Check TOD data... ASSERT_CARRAY_TYPE_NDIM(tod_array, NPY_FLOAT32, 2); int ndet = PyArray_DIMS(tod_array)[0]; int tod_ndata = PyArray_DIMS(tod_array)[1]; float *tod_data = PyArray_DATA(tod_array); // Check row and col ASSERT_CARRAY_TYPE_NDIM(row_array, NPY_INT32, 1); ASSERT_CARRAY_TYPE_NDIM(col_array, NPY_INT32, 1); int *tod_rows = PyArray_DATA(row_array); int *tod_cols = PyArray_DATA(col_array); po_assert(PyArray_DIMS(row_array)[0] == ndet); po_assert(PyArray_DIMS(col_array)[0] == ndet); // Check det lists... ASSERT_CARRAY_TYPE_NDIM(ldet_array, NPY_INT32, 1); ASSERT_CARRAY_TYPE_NDIM(ddet_array, NPY_INT32, 1); int *ldet = PyArray_DATA(ldet_array); int nldet = PyArray_DIMS(ldet_array)[0]; int *ddet = PyArray_DATA(ddet_array); int nddet = PyArray_DIMS(ddet_array)[0]; // Check temperature vector ASSERT_CARRAY_TYPE_NDIM(temp_array, NPY_FLOAT32, 1); po_assert(PyArray_DIMS(temp_array)[0] == tod_ndata); int ndata = tod_ndata / dsStep; float *temp = PyArray_DATA(temp_array); bool valid_temp = false; if ((temp[0] != temp[ndata/2]) || (temp[0] != temp[ndata/3])) valid_temp = true; // Downsampling -- ndata is the downsampled size. // Sanity checks assert((nBlock == 1) || (nBlock == 4) || (nBlock = 9) || (nBlock == 16)); assert(ndet > 0); assert(ndata > 0); if (nModes > nBlock) nModes = nBlock; // Ready output arrays. npy_intp dims[2]; /* Time-like... */ dims[0] = ndata; PyObject *cm_array = PyArray_SimpleNew(1, dims, NPY_FLOAT32); PyObject *dcm_array = PyArray_SimpleNew(1, dims, NPY_FLOAT32); float *cm = PyArray_DATA((PyArrayObject*) cm_array); float *dcm = PyArray_DATA((PyArrayObject*) dcm_array); /* Det-like... */ dims[0] = ndet; /* Template: PyObject *X_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *X = PyArray_DATA((PyArrayObject*) X_array); */ PyObject *norm_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *norm = PyArray_DATA((PyArrayObject*) norm_array); PyObject *corrLive_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *corrLive = PyArray_DATA((PyArrayObject*) corrLive_array); PyObject *DELive_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *DELive = PyArray_DATA((PyArrayObject*) DELive_array); PyObject *gainLive_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *gainLive = PyArray_DATA((PyArrayObject*) gainLive_array); PyObject *corrDark_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *corrDark = PyArray_DATA((PyArrayObject*) corrDark_array); PyObject *DEDark_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *DEDark = PyArray_DATA((PyArrayObject*) DEDark_array); PyObject *gainDark_array = PyArray_SimpleNew(1, dims, NPY_FLOAT64); double *gainDark = PyArray_DATA((PyArrayObject*) gainDark_array); /* Resume original moby code... */ int side = (int)sqrt((float)nBlock); int nSide = (int)ceil(32.0/side); int rmin, cmin, N, zeros = 0; int *bdet = (int *)malloc(ndet*sizeof(int)); int *rows = (int *)malloc(nldet*sizeof(int)); int *cols = (int *)malloc(nldet*sizeof(int)); for (int i = 0; i < nldet; i++) { rows[i] = tod_rows[ldet[i]]; cols[i] = tod_cols[ldet[i]]; } // Downsample data for every detector TOD float *data = (float *)malloc(ndet * ndata * sizeof(float)); for (int i = 0; i < ndet; i++) { double mean = 0.; for (int j = 0; j < ndata; j++) { data[i*ndata + j] = tod_data[i*tod_ndata + dsStep * j]; mean += data[i*ndata+j]; } mean /= ndata; for (int j = 0; j < ndata; j++) { data[i*ndata + j] -= mean; } } float *dot = (float *)malloc(ndet * sizeof(float)); if (valid_temp) { // Downsample temperature float *dstemp = (float *)malloc(ndata * sizeof(float)); double mean = 0; double temp2 = 0; for (int j = 0; j < ndata; j++) { dstemp[j] = temp[dsStep * j]; mean += dstemp[j]; } // Remove mean and obtain norm^2 of temp mean /= ndata; for (int j = 0; j < ndata; j++) { dstemp[j] -= mean; temp2 += dstemp[j] * dstemp[j]; } if (temp2==0.) temp2 = 1.; // Obtain fit temperature to data cblas_sgemv(CblasRowMajor, CblasNoTrans, ndet, ndata, 1.0, data, ndata, dstemp, 1, 0.0, dot, 1); // Remove temperature signal //#pragma omp parallel shared(ndet, ndata, data, dot, dstemp) { //#pragma omp for for (int d = 0; d < ndet; d++) { for (int i = 0; i < ndata; i++) data[d*ndata + i] -= dot[d]*dstemp[i]/temp2; } } free(dstemp); } // Obtain dark common mode float cm2 = 0; for (int s = 0; s < ndata; s++) { dcm[s] = 0; for (int j = 0; j < nddet; j++) dcm[s] += data[ddet[j]*ndata + s]/nddet; cm2 += dcm[s] * dcm[s]; } // Obtain dark correlation and gain cblas_sgemv(CblasRowMajor, CblasNoTrans, ndet, ndata, 1.0, data, ndata, dcm, 1, 0.0, dot, 1); for (int i = 0; i < ndet; i++) { norm[i] = 0.0; for (int j = 0; j < ndata; j++) norm[i] += data[i*ndata+j]*data[i*ndata+j]; norm[i] = sqrt(norm[i]/ndata); if (norm[i] != 0.0) corrDark[i] = dot[i]/norm[i]/sqrt(cm2*ndata); else corrDark[i] = 0.0; gainDark[i] = dot[i]/cm2; } // Obtain dark drift error //#pragma omp parallel shared(DEDark, ndet, ndata, data, gainDark) { //#pragma omp for for (int d = 0; d < ndet; d++) { float dat; // Remove dark common mode DEDark[d] = 0.0; for (int i = 0; i < ndata; i++) { dat = data[d*ndata + i] - gainDark[d]*dcm[i]; DEDark[d] += dat * dat / ndata; if (removeDarkCM==1) data[d*ndata + i] = dat; } DEDark[d] = sqrt(DEDark[d]); if (norm[d] != 0.0) DEDark[d] /= norm[d]; } } //Note that DEDark here constitutes, for live detectors, the norm of the //data minus the dark common mode // Remove slope int Ns = ((ndata+1)/2)*2 - 1; float Ns2 = (float)(Ns/2); long int sx2 = (long int)(Ns2*Ns2*Ns2/3 + Ns2*Ns2/2 + Ns2/6)*2; double a, A; A = 0; for (int j = 0; j < ndet; j++) { a = 0; for (int s = 0; s < Ns; s++) a += (s - Ns2)*data[j*ndata + s]; for (int d = 0; d < nldet; d++) if (j == ldet[d]) A += a; for (int s = 0; s < ndata; s++) data[j*ndata + s] -= (s - Ns2)*a/sx2; } A /= nldet; // Obtain live common mode cm2 = 0; for (int s = 0; s < ndata; s++) { cm[s] = 0; for (int j = 0; j < nldet; j++) cm[s] += data[ldet[j]*ndata + s]/nldet; cm2 += cm[s] * cm[s]; } // Obtain live correlation and gain cblas_sgemv(CblasRowMajor, CblasNoTrans, ndet, ndata, 1.0, data, ndata, cm, 1, 0.0, dot, 1); for (int d = 0; d < ndet; d++) { norm[d] = 0.0; for (int j = 0; j < ndata; j++) norm[d] += data[d*ndata+j]*data[d*ndata+j]; norm[d] = sqrt(norm[d]/ndata); if (norm[d] != 0.0) corrLive[d] = dot[d]/norm[d]/sqrt(cm2*ndata); else corrLive[d] = 0.0; gainLive[d] = dot[d]/cm2; } // Obtain block common modes, weighted by the number of detectors in // each block. float *cmodes = (float *)malloc(nBlock * ndata * sizeof(float)); for (int i = 0; i < nBlock; i++) { rmin = nSide * (i/side); cmin = nSide*i - rmin*side; N = 0; for (int j = 0; j < nldet; j++) { if (rows[j] >= rmin && rows[j] < rmin + nSide && cols[j] >= cmin && cols[j] < cmin + nSide) { bdet[N] = ldet[j]; N++; } } if (N > 0) { for (int s = 0; s < ndata; s++) { cmodes[(i-zeros)*ndata + s] = 0; for (int j = 0; j < N; j++) cmodes[(i-zeros)*ndata + s] += data[bdet[j]*ndata + s]; } } else { zeros++; } } nBlock -= zeros; if (nModes > nBlock) nModes = nBlock; // Obtain the SVD // A (M-by-N) with M rows and N columns // JOBZ = 'S' // M = ndata // N = nBlock // LDA = ndata float *S = (float *)malloc(nBlock * sizeof(float)); float *U = (float *)malloc(nBlock * ndata * sizeof(float)); float *VT = (float *)malloc(nBlock * nBlock * sizeof(float)); int LWORK = nBlock * ndata; float *WORK = (float *)malloc(LWORK * sizeof(float)); int *IWORK = (int *)malloc(8 * nBlock * sizeof(int)); // Apply Lapack SVD sgesdd('S', ndata, nBlock, cmodes, ndata, S, U, ndata, VT, nBlock, WORK, LWORK, IWORK); // Find fit coefficients (mT A). // Note that matrices are transposed in this definition float *coeff = (float *)malloc(nBlock * ndet * sizeof(float)); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, ndet, nBlock, ndata, 1.0, data, ndata, U, ndata, 0.0, coeff, nBlock); // Rearrange coeff matrix to contain only nModes modes for (int i = 0; i < ndet; i++) { for (int j = 0; j < nModes; j ++) { coeff[i*nModes + j] = coeff[i*nBlock + j]; } } // Remove modes (A - m mT A) cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, ndet, ndata, nModes, -1.0, coeff, nModes, U, ndata, 1.0, data, ndata); // Obtain drift error //#pragma omp parallel shared(DELive, ndet, ndata, data) { //#pragma omp for for (int d = 0; d < ndet; d++) { DELive[d] = 0.0; for (int i = 0; i < ndata; i++) { DELive[d] += data[d*ndata + i] * data[d*ndata + i] / ndata; } if (norm[d] != 0.0) DELive[d] = sqrt(DELive[d])/norm[d]; } } //Note that we have normalized the DriftError to cancel the effect of the gain in //the value, because we want to represent differences in shape with respect to the //common mode //Re-add the slope to the common-mode for (int s = 0; s < ndata; s++) cm[s] += (s - Ns2)*A/sx2; free(bdet); free(rows); free(cols); free(data); free(dot); free(cmodes); free(S); free(U); free(VT); free(WORK); free(IWORK); free(coeff); return Py_BuildValue("NNNNNNNNN", cm_array, dcm_array, norm_array, corrLive_array, DELive_array, gainLive_array, corrDark_array, DEDark_array, gainDark_array); } PyMethodDef pyactpol_filter_methods[] = { {"remove_mean", remove_mean, METH_VARARGS, ""}, {"filter_tod_data", filter_tod_data, METH_VARARGS, filter_tod_data__doc__}, {"get_glitch_cuts", get_glitch_cuts, METH_VARARGS, ""}, {"analyze_scan", analyze_scan, METH_VARARGS, analyze_scan__doc__}, {"preselect_dets", preselect_dets, METH_VARARGS, preselect_dets__doc__}, {"find_jumps", find_jumps, METH_VARARGS, ""}, {"get_drift_tests", get_drift_tests, METH_VARARGS, get_drift_tests__doc__}, {NULL, NULL, 0, NULL} /* Sentinel */ };
{ "alphanum_fraction": 0.5380887287, "avg_line_length": 34.315565032, "ext": "c", "hexsha": "66212752a27c53dc13f6f7f01a3c332d6a67e9a3", "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/filter.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/filter.c", "max_line_length": 112, "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/filter.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": 13952, "size": 48282 }
/*-------------------------------------------------------------------- * $Id$ * * This file is part of libRadtran. * Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer, * Claudia Emde, Robert Buras * * ######### Contact info: http://www.libradtran.org ######### * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *--------------------------------------------------------------------*/ #include <math.h> #include <string.h> #include <time.h> #include <assert.h> #include "solve_rte.h" #include "uvspec.h" #include "uvspecrandom.h" #include "ascii.h" #include "ancillary.h" #include "numeric.h" #include "fortran_and_c.h" #include "cloud.h" #include "molecular.h" #include "rodents.h" #include "twostrebe.h" #include "twomaxrnd.h" #include "dynamic_twostream.h" #include "dynamic_tenstream.h" #if HAVE_TWOMAXRND3C #include "twomaxrnd3C.h" #endif #include "cdisort.h" #include "c_tzs.h" #include "sslidar.h" #include "errors.h" #include "Corefinder.h" #include "LinArray.h" #include "wcloud3d.h" #include "allocnd.h" #include "redistribute.h" #if HAVE_MYSTIC #include "mystic.h" #endif #if HAVE_TIPA #include "tipa.h" #endif #if HAVE_SOS #include "sos.h" #endif #include "f77-uscore.h" #include "solver.h" #ifndef PI #define PI 3.14159265358979323846264338327 #endif #if HAVE_LIBGSL #include <gsl/gsl_math.h> #include <gsl/gsl_diff.h> #endif /* Definitions for numerical recipes functions */ #define NRANSI #define SIGN(a, b) ((b) >= 0.0 ? fabs (a) : -fabs (a)) /* internal structures */ typedef struct { char* deltam; char* ground_type; char polscat[15]; pol_complex ground_index; double albedo; double btemp; double flux; double* gas_extinct; double* height; double mu; double sky_temp; double* temperatures; double wavelength; int* outlevels; int nummu; /* Number of quadrature angles (per hemisphere). */ } polradtran_input; typedef struct { char header[127]; /* A 127- (or less) character header for prints */ float accur; /* Convergence criterion for azimuthal series. */ float fbeam; /* Intensity of incident parallel beam at top boundary. */ /* [same units as PLKAVG (default W/sq m) if thermal */ /* sources active, otherwise arbitrary units]. */ float fisot; /* Intensity of top-boundary isotropic illumination. */ /* [same units as PLKAVG (default W/sq m) if thermal */ /* sources active, otherwise arbitrary units]. */ /* Corresponding incident flux is pi (3.14159...) */ /* times FISOT. */ float* hl; /* K = 0 to NSTR. Coefficients in Legendre- */ /* polynomial expansion of bottom bidirectional */ /* reflectivity */ int planck; /* TRUE, include thermal emission */ /* FALSE, ignore thermal emission (saves computer time) */ float btemp; /* Temperature of bottom boundary (K) */ /* (bottom emissivity is calculated from ALBEDO or HL, */ /* so it need not be specified). */ /* Needed only if PLANK is TRUE. */ float ttemp; /* Temperature of top boundary (K) */ /* Needed only if PLANK is TRUE. */ float temis; /* Emissivity of top boundary. */ /* Needed only if PLANK is TRUE. */ float* utau; float umu0; int ierror_d[47]; int ierror_s[33]; int ierror_t[22]; int prndis[7]; int prndis2[5]; int prntwo[2]; int ibcnd; /* 0 : General case. */ /* 1 : Return only albedo and transmissivity of the */ /* entire medium vs. incident beam angle. */ int lamber; /* TRUE, isotropically reflecting bottom boundary. */ /* FALSE, bidirectionally reflecting bottom boundary. */ int onlyfl; /* TRUE, return fluxes, flux divergences, and mean */ /* intensities. */ /* FALSE, return fluxes, flux divergences, mean */ /* intensities, azimuthally averaged intensities */ /* (at the user angles) AND intensities. */ int quiet; int usrang; int usrtau; /* sdisort-specific variables */ int nil; int newgeo; int spher; /* qdisort-specific variables */ int gsrc; /* Flag for general source for qdisort */ double*** qsrc; /* The general source, in FORTRAN: REAL*4 qsrc( MXCMU, 0:MXULV, MXCMU )*/ /* At computational angles */ double*** qsrcu; /* The general source, in FORTRAN: REAL*4 qsrc( MXUMU, 0:MXULV, MXCMU )*/ /* At user angles */ /* PolRadtran-specific variables */ polradtran_input pol; } rte_input; typedef struct { float* dfdt; float* flup; float* rfldir; float* rfldn; float* uavgso; float* uavgdn; float* uavgup; float* uavg; float* heat; float* emis; float* w_zout; float** u0u; float*** uu; float*** uum; /* Fourier components of intensities, returned by qdisort */ float* sslidar_nphot; float* sslidar_nphot_q; float* sslidar_ratio; float*** rfldir3d; float*** rfldn3d; float*** flup3d; float***** fl3d_is; /* importance sampling */ float*** uavgso3d; float*** uavgdn3d; float*** uavgup3d; float*** abs3d; float*** absback3d; float**** radiance3d; float****** radiance3d_is; /*importance sampling*/ float****** jacobian; /* corresponding variances */ float*** rfldir3d_var; float*** rfldn3d_var; float*** flup3d_var; float*** uavgso3d_var; float*** uavgdn3d_var; float*** uavgup3d_var; float*** abs3d_var; float*** absback3d_var; float**** radiance3d_var; float* albmed; float* trnmed; double** polradtran_down_flux; double** polradtran_up_flux; double**** polradtran_down_rad_q; /* _q indicates radiances at quadrature angels. */ double**** polradtran_up_rad_q; double**** polradtran_down_rad; double**** polradtran_up_rad; double* polradtran_mu_values; // triangular surface output struct t_triangle_radiation_field* triangle_results; } rte_output; typedef struct { float* tauw; float* taui; float* g1d; float* g2d; float* fd; float* g1i; float* g2i; float* fi; float* ssaw; float* ssai; } save_optprop; typedef struct { double** dtauc; double* fbeam; double**** uum; double ** uavgso, **uavgdn, **uavgup; double ** rfldir, **rfldn, **flup; double*** u0u; double**** uu; } raman_qsrc_components; /* prototypes of internal functions */ static int reverse_profiles (input_struct input, output_struct* output); static rte_output* calloc_rte_output (input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Ncsample, int Nlambda, int Nxsample, int Nysample, int Nlyr, int* threed, int passback3D, const size_t N_triangles); static int reset_rte_output (rte_output** rte, input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Nxsample, int Nysample, int Ncsample, int Nlambda, int Nlyr, int* threed, int passback3D, const size_t N_triangles); static int free_rte_output (rte_output* result, input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Nxsample, int Nysample, int Ncsample, int Nlyr, int Nlambda, int* threed, int passback3D); static int add_rte_output (rte_output* rte, const rte_output* add, const double factor, const double* factor_spectral, const input_struct input, const int nzout, const int Nxcld, const int Nycld, const int Nzcld, const int Nc, const int Nlyr, const int Nlambda, const int* threed, const int passback3D, const int islower, const int isupper, const int jslower, const int jsupper, const int isstep, const int jsstep); static int init_rte_input (rte_input* rte, input_struct input, output_struct* output); static int setup_and_call_solver (input_struct input, output_struct* output, rte_input* rte_in, rte_output* rte_out, raman_qsrc_components* raman_qsrc_components, int iv, int ib, int ir, int* threed, int mc_loaddata); static int call_solver (input_struct input, output_struct* output, int rte_solver, rte_input* rte_in, raman_qsrc_components* raman_qsrc_components, int iv, int ib, int ir, rte_output* rte_out, int* threed, int mc_loaddata, int verbose); static void fourier2azimuth (double**** down_rad_rt3, double**** up_rad_rt3, double**** down_rad, double**** up_rad, int nzout, int aziorder, int nstr, int numu, int nstokes, int nphi, float* phi); static int calc_spectral_heating (input_struct input, output_struct* output, float* dz, double* rho_mass_zout, float* k_abs, float* k_abs_layer, int* zout_index, rte_output* rte_out, float* heat, float* emis, float* w_zout, int iv); static float*** calloc_abs3d (int Nx, int Ny, int Nz, int* threed); static void free_abs3d (float*** abs3d, int Nx, int Ny, int Nz, int* threed); static float**** calloc_spectral_abs3d (int Nx, int Ny, int Nz, int nlambda, int* threed); double get_unit_factor (input_struct input, output_struct* output, int iv); static int generate_effective_cloud (input_struct input, output_struct* output, save_optprop* save_cloud, int iv, int iq, int verbose); static int set_raman_source (double*** qsrc, double*** qsrcu, int maxphi, int nlev, int nzout, int nstr, int n_shifts, float wanted_wl, double* wl_shifts, float umu0, float* zd, float* zout, float zenang, float fbeam, float radius, float* dens, double** crs_RL, double** crs_RG, float* ssalb, int numu, float* umu, int usrang, int* cmuind, float*** pmom, raman_qsrc_components* raman_qsrc_components, int* zout_comp_index, float altitude, int last, int verbose); static save_optprop* calloc_save_optprop (int Nlev); raman_qsrc_components* calloc_raman_qsrc_components (int raman_fast, int nzout, int maxumu, int nphi, int nstr, int nlambda_shift); static void free_raman_qsrc_components (raman_qsrc_components* result, int raman_fast, int nzout, int maxumu, int nphi, int nstr); void F77_FUNC (swde, SWDE) (float* g_scaled, float* pref, float* prmuz, float* tau, float* ssa_gas, float* pre1, float* pre2, float* ptr1, float* ptr2); float zbrent_taueff (float mu_eff, float g_scaled, float ssa_gas, float transmission_cloud, float transmission_layer, float x1, float x2, float tol); void F77_FUNC (qgausn, QGAUSN) (int* n, float* cmu, float* cwt); void F77_FUNC (lepolys, LEPOLYS) (int* nn, int* mazim, int* mxcmu, int* nstr, float* cmu, float* ylmc); /*********************************************************************/ /* Main function. Loop over wavelengths or wavelength bands, */ /* correlated-k quadrature points, and independent pixels. */ /*********************************************************************/ int solve_rte (input_struct input, output_struct* output) { static int first = TRUE; int status = 0, add = 0; int isp = 0, ipa = 0, is = 0, js = 0, ks = 0, ivs = 0, iv_alis = 0, iv_alis_ref = 0; int iipa = 0, jipa = 0; int iv = 0, iu = 0, j = 0, lu = 0, ip = 0, iz = 0, ic = 0; int iq = 0, lc = 0, nr = 0, ir = 0, irs = 0; int ijac = 0; int lower_wl_id = 0, upper_wl_id = 0, lower_iq_id = 0, upper_iq_id = 0, ivr = 0; int nlambda = 0; float* dz = NULL; double weight = 1; double* rho_mass_zout = NULL; float* k_abs = NULL; float* k_abs_layer = NULL; float* k_abs_outband = NULL; int mc_loaddata = 1; double weight2 = 0; double unit_factor = 0; double ffactor = 0.0, rfactor = 0.0, hfactor = 1.0; double** u0u_raman = NULL; double* uavgso_raman = NULL; double* uavgdn_raman = NULL; double* uavgup_raman = NULL; double* rfldir_raman = NULL; double* rfldn_raman = NULL; double* flup_raman = NULL; double*** uu_raman = NULL; /* The radiance at user angles for the general source for qdisort */ /* Only used if raman scattering is on */ /* float heating_rate_emission = 0.0; */ rte_input* rte_in = NULL; rte_output* rte_out = NULL; rte_output* rte_outband = NULL; save_optprop* save_cloud = NULL; raman_qsrc_components* raman_qsrc_components = NULL; char function_name[] = "solve_rte"; char file_name[] = "solve_rte.c"; double* weight_spectral = NULL; //FIX 3DAbs not initialized when aerosol setup not done, should be redundant now // output->mc.alis.Nc = 1; if (first) { first = FALSE; /* this is not the right place to do this! This should be done somewhere else! Please clean up! BCA */ if (input.ipa3d) { output->mc.sample.passback3D = 1; /* like for mystic, I set passback3d to 1 */ /* ipa3d and tipa were configured and tested only with 3D-cloudfiles containing lwc and reff, thus check: */ for (isp = 0; isp < input.n_caoth; isp++) if (!(output->caoth3d[isp].cldproperties == 3 || output->caoth3d[isp].cldproperties == 4)) { fprintf (stderr, "Error: ipa3d/tipa does not work with cldproperties flag different from 3\n"); return -1; } /* finally, we add normalization to the number of pixels to ipaweight, BM 3.7.2020 */ /* ipaweight[] either considers cloudcover or normalization for ipa3d */ for (ipa = 0; ipa < output->nipa; ipa++) output->ipaweight[ipa] /= ((double)output->niipa * (double)output->njipa); } rte_in = calloc (1, sizeof (rte_input)); rte_out = calloc_rte_output (input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->mc.alis.nlambda_abs, output->atm.nlev - 1, output->atm.threed, output->mc.sample.passback3D, output->mc.triangular_surface.N_triangles); rte_outband = calloc_rte_output (input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->mc.alis.nlambda_abs, output->atm.nlev - 1, output->atm.threed, output->mc.sample.passback3D, output->mc.triangular_surface.N_triangles); save_cloud = calloc_save_optprop (output->atm.nlev); /* initialize RTE input */ status = init_rte_input (rte_in, input, output); if (status != 0) { fprintf (stderr, "Error %d initializing rte input in %s (%s)\n", status, function_name, file_name); return status; } /* allocate memory for the output result structures */ status = setup_result (input, output, &dz, &rho_mass_zout, &k_abs_layer, &k_abs, &k_abs_outband); if (status != 0) { fprintf (stderr, "Error %d allocating memory for the model output in %s (%s)\n", status, function_name, file_name); return status; } if (input.raman) { nr = 2; if ((status = ASCII_calloc_double_3D (&uu_raman, output->atm.nzout, input.rte.nphi, input.rte.numu)) != 0) return status; if ((status = ASCII_calloc_double (&u0u_raman, output->atm.nzout, input.rte.numu)) != 0) return status; uavgso_raman = calloc (output->atm.nzout, sizeof (double)); uavgdn_raman = calloc (output->atm.nzout, sizeof (double)); uavgup_raman = calloc (output->atm.nzout, sizeof (double)); rfldir_raman = calloc (output->atm.nzout, sizeof (double)); rfldn_raman = calloc (output->atm.nzout, sizeof (double)); flup_raman = calloc (output->atm.nzout, sizeof (double)); /* Number of wavelength shifts considered is independent of primary wavelength, */ /* hence use output->atm.nq_t[0] below */ if (input.raman_fast) nlambda = output->wl.nlambda_r; else nlambda = output->crs.number_of_ramanwavelengths; raman_qsrc_components = calloc_raman_qsrc_components (input.raman_fast, output->atm.nzout, input.rte.maxumu, input.rte.nphi, input.rte.nstr, nlambda); } else { nr = 1; } } if (input.raman) { /* For Raman scattering only include wavelengths that the user asked. */ /* Internally we have to include more wavelengths to account for */ /* Raman scattered radiation, see loop over quadrature points below. */ lower_wl_id = output->wl.raman_start_id; upper_wl_id = output->wl.raman_end_id; } else { lower_wl_id = output->wl.nlambda_rte_lower; upper_wl_id = output->wl.nlambda_rte_upper; } /* concentration importance sampling */ if (input.rte.mc.concentration_is) { weight_spectral = calloc (1, sizeof (double)); weight_spectral[0] = 1.0; } if (input.rte.mc.spectral_is) { weight_spectral = calloc (output->mc.alis.nlambda_abs, sizeof (double)); /* Take wavelength in center of spectrum if not specified explicitly, FIXCE should also check whether absorption is not too high here */ if (input.rte.mc.spectral_is_wvl[0] == 0.) { lower_wl_id = (int)(0.5 * ((float)output->wl.nlambda_rte_lower + (float)output->wl.nlambda_rte_upper)); output->mc.alis.nlambda_ref = 1; output->mc.alis.ilambda_ref = calloc (1, sizeof (int)); output->mc.alis.ilambda_ref[0] = lower_wl_id; } else if (input.rte.mc.spectral_is_wvl[0] > 0.) { /* Find wavelength index for specified wavelength */ lower_wl_id = 0; for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { if (output->mc.alis.lambda[iv_alis] > input.rte.mc.spectral_is_wvl[0]) { lower_wl_id = iv_alis - 1; output->mc.alis.nlambda_ref = 1; output->mc.alis.ilambda_ref = calloc (1, sizeof (int)); output->mc.alis.ilambda_ref[0] = lower_wl_id; break; } } } else { /* several calc wvls do not work so far */ lower_wl_id = (int)(0.5 * ((float)output->wl.nlambda_rte_lower + (float)output->wl.nlambda_rte_upper)); output->mc.alis.nlambda_ref = input.rte.mc.spectral_is_nwvl; output->mc.alis.ilambda_ref = calloc (output->mc.alis.nlambda_ref, sizeof (int)); for (iv_alis_ref = 0; iv_alis_ref < output->mc.alis.nlambda_ref; iv_alis_ref++) { for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { if (output->mc.alis.lambda[iv_alis] > input.rte.mc.spectral_is_wvl[iv_alis_ref]) { output->mc.alis.ilambda_ref[iv_alis_ref] = iv_alis; } } } } upper_wl_id = lower_wl_id; if (!input.quiet) { fprintf (stderr, "... ALIS calculation wavelength: %g nm \n", output->mc.alis.lambda[lower_wl_id]); if (output->mc.alis.nlambda_ref > 1) for (iv_alis_ref = 1; iv_alis_ref < output->mc.alis.nlambda_ref; iv_alis_ref++) { fprintf (stderr, "... helper ALIS wavelength: %g nm \n", output->mc.alis.lambda[output->mc.alis.ilambda_ref[iv_alis_ref]]); } } } #if HAVE_TIPA /* ulrike: TIPA DIR. The "tilted cloud matrix" is used only for the calculation of the DIRECT radiation Tilting for every z-level is done here (outside the loop over the wavelength) */ if (input.tipa == TIPA_DIR || input.rte.mc.tipa == TIPA_DIR) { for (isp = 0; isp < input.n_caoth; isp++) if (input.caoth[isp].source == CAOTH_FROM_3D) { if (!input.quiet) fprintf (stderr, " ... performing the tilting for tipa dir (water clouds)\n"); status = tipa_dirtilt (&(output->caoth3d[isp]), output->atm, output->alt, &(output->caoth[isp].tipa), input.tipa, input.atm.sza, input.atm.phi0, lower_wl_id, upper_wl_id, input.rte.mc.tipa); if (status) return fct_err_out (status, "tipa_dirtilt", ERROR_POSITION); } } #endif /************************/ /* loop over wavelength */ /************************/ int iv_count = 0; for (iv = lower_wl_id; iv <= upper_wl_id; iv++) { /***********************************************************/ /* iterate over wavelengths, required for raman scattering */ /***********************************************************/ irs = 0; if (input.raman_fast && iv > lower_wl_id) irs = 1; /* AK20110407: All the elastic wavelengths are done for */ /* iv=lower_wl_id and stored. Thus only need to do */ /* the inelastic part for remaining wavelengths. */ for (ir = irs; ir < nr; ir++) { /* solar zenith angle at this wavelength */ rte_in->umu0 = cos (output->atm.sza_r[iv] * PI / 180.0); /* calculate 3D caoth properties for this wavelength */ if (input.rte.solver == SOLVER_MONTECARLO || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) { int isp_hiddencore = -1, isp_wc3D = -1; for (isp = 0; isp < input.n_caoth; isp++) { if (strcmp (input.caoth[isp].name, "molecular_3d") != 0) { status = convert_caoth_mystic (input, input.caoth[isp], output, &(output->caoth[isp]), &(output->caoth3d[isp]), iv); if (status) return fct_err_out (status, "convert_caoth_mystic", ERROR_POSITION); if (strcmp (input.caoth[isp].name, "hiddencore_dummy") == 0) isp_hiddencore = isp; if (strcmp (input.caoth[isp].name, "wc") == 0) isp_wc3D = isp; } } /** Section to find the veiled core. Author: Paul Ockenfuß, Bernhard Mayer Modifies the parameters ext, g1, g2, ssa and ff in the profiles "wc" and "hiddencore_dummy" Important developer information: Units in caoth3d: ext[...] 1/m; atm.dxcld & atm.dycld in m, atm.zd_common in km! -z-Index="0" means surface in caoth3d. -z-Index="0" means TOA in "atm"! */ if (input.rte.mc.core_isactive && (iv_count == 0 || output->caoth3d[isp_wc3D].cldproperties == CLD_LWCREFF || output->caoth3d[isp_wc3D].cldproperties == CLD_LWCREFFCF)) { assert (isp_hiddencore >= 0); assert (isp_wc3D >= 0); assert ((output->caoth3d[isp_wc3D]).nthreed > 0); assert ((output->caoth3d[isp_hiddencore]).nthreed > 0); if (!input.quiet) fprintf (stderr, "Found wc3D; starting to modify core\n"); int nx = (output->caoth3d[isp_wc3D]).Nx; int ny = (output->caoth3d[isp_wc3D]).Ny; int nz = (output->caoth3d[isp_wc3D]).nlyr; int* threed = (output->caoth3d[isp_wc3D]).threed; float dx = output->atm.dxcld, dy = output->atm.dycld; float*** core; float*** distances; if (!(distances = calloc_float_3D (nz, nx, ny, "distances"))) return -1; if (input.rte.mc.core_inputfile) { /*If the user specified the cloud core*/ int core_nx, core_ny, core_nz, core_rows, core_flag = 0, status = 0; double core_dx, core_dy; float* core_dz; status = read_3D_caoth_header (input.rte.mc.core_inputfile, &core_nx, &core_ny, &core_nz, &core_flag, &core_dx, &core_dy, &core_dz, &core_rows); if (status != 0) { return -1; } if (core_flag != 4) { fprintf ( stderr, "!!Warning: when reading %s, another flag than 4 was found! Is this really a file describing a cloud core?\n", input.rte.mc.core_inputfile); } core_dx *= 1000; core_dy *= 1000; if (nx != core_nx || ny != core_ny || dx != core_dx || dy != core_dy) { fprintf (stderr, "Error when reading core profile %s: The horizontal grid of the core must be the same as in wc_file 3D!\n", input.rte.mc.core_inputfile); return -1; } float*** column4; int* core_threed = calloc (core_nz, sizeof (int)); if (!(column4 = calloc_float_3D (core_nz, core_nx, core_ny, "column4"))) return -1; int* indz = calloc (core_rows - 2, sizeof (int)); status = read_3D_caoth_data (input.rte.mc.core_inputfile, core_nx, core_ny, core_nz, core_rows, &column4, NULL, NULL, NULL, NULL, indz); if (status != 0) { return -1; } for (size_t i = 0; i < core_rows - 2; i++) { core_threed[indz[i]] = 1; } status = redistribute_3D (&column4, nx, ny, core_dz, core_nz, output->atm.zd_common, nz, core_threed, threed, 0); core = column4; free (indz); free (core_threed); } else { /*If the user specified no cloud core, start the corefinder*/ if (!(core = calloc_float_3D (nz, nx, ny, "core"))) return -1; // Initialize array with scattering coefficients from wc3D profile // This profile can contain layers which are not 3D. They are coming from interpolation // to other grids (e.g. ic_file). Therefore, wc scattering is always zero in these layers. arr3d_f* k_scat = calloc3d_float (nx, ny, nz); for (size_t i = 0; i < k_scat->nx; i++) { for (size_t j = 0; j < k_scat->ny; j++) { for (size_t k = 0; k < k_scat->nz; k++) { if ((output->caoth3d[isp_wc3D]).threed[k]) set3d_f (k_scat, i, j, k, ((output->caoth3d[isp_wc3D]).ext[k][i][j]) * ((output->caoth3d[isp_wc3D]).ssa[k][i][j])); else set3d_f (k_scat, i, j, k, 0.0); } } } //calculate layer distances in atmosphere float* deltaz = malloc (k_scat->nz * sizeof (float)); for (size_t i = 0; i < k_scat->nz; i++) deltaz[i] = 1000 * (output->atm.zd_common[k_scat->nz - i - 1] - output->atm.zd_common[k_scat->nz - i]); //convert to meters // Calculate starting points for the corefinder: every specified zout-level will create one xy-layer of starting points // Notebook entry 21 size_t total_starts = output->atm.nzout_user * k_scat->nx * k_scat->ny; size_t* xstart = calloc (total_starts, sizeof (size_t)); size_t* ystart = calloc (total_starts, sizeof (size_t)); size_t* zstart = calloc (total_starts, sizeof (size_t)); size_t* z_index = calloc (output->atm.nzout_user, sizeof (size_t)); int iz_index = 0; int kc = 0; for (kc = 0; kc < (output->caoth3d[isp_wc3D]).nlyr; kc++) if (output->mc.sample.sample[kc]) z_index[iz_index++] = kc; // At TOA, the first layer below TOA is used for starting points if (output->mc.sample.sample[kc]) z_index[iz_index++] = kc - 1; if (!input.quiet) { fprintf (stderr, "Corefinder starting points:\n"); for (size_t i = 0; i < output->atm.nzout_user; i++) fprintf (stderr, "%d\n", (int)z_index[i]); } // consistency check if (iz_index != output->atm.nzout_user) { fprintf (stderr, "Error, number of output levels not matching in corefinder\n"); return -1; } for (size_t k = 0; k < output->atm.nzout_user; k++) for (size_t j = 0; j < k_scat->ny; j++) for (size_t i = 0; i < k_scat->nx; i++) { xstart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = i; ystart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = j; zstart[k * k_scat->ny * k_scat->nx + j * k_scat->nx + i] = z_index[k]; } //Start to find the core arr3d_i* core_linarray = calloc3d_int (k_scat->nx, k_scat->ny, k_scat->nz); if (!input.quiet) fprintf (stderr, "...start finding core. Threshold: %.2f\n", input.rte.mc.core_threshold); arr3d_f* distances_linarray = get_distances2 (*k_scat, dx, dy, deltaz, xstart, ystart, zstart, total_starts, input.rte.mc.core_threshold); black_white_filter (distances_linarray, input.rte.mc.core_threshold, core_linarray); for (size_t i = 0; i < nx; i++) { for (size_t j = 0; j < ny; j++) { for (size_t k = 0; k < nz; k++) { core[k][i][j] = (float)get3d_i (core_linarray, i, j, k); distances[k][i][j] = get3d_f (distances_linarray, i, j, k); } } } free (xstart); free (ystart); free (zstart); free (z_index); free (deltaz); free3d_float (k_scat); free3d_int (core_linarray); free3d_float (distances_linarray); } /*END Corefinder*/ //Optionally: Save the core to the file given by input.rte.mc.core_savefile if (input.rte.mc.core_savefile) { if (!input.quiet) fprintf (stderr, "...saving core to %s\n", input.rte.mc.core_savefile); FILE* fp; if ((fp = fopen (input.rte.mc.core_savefile, "w")) == NULL) { fprintf (stderr, "Could not open %s!\n", input.rte.mc.core_savefile); return -1; } fprintf (fp, "%d %d %d 4\n", nx, ny, nz); fprintf (fp, "%g %g", output->atm.dxcld / 1000.0, output->atm.dycld / 1000.0); for (size_t i = 0; i < nz + 1; i++) fprintf (fp, " %g", output->atm.zd_common[nz - i]); fprintf (fp, "\n#IndexX IndexY IndexZ Core Distance\n"); for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++) { for (int k = 0; k < nz; k++) { if (threed[k]) { if (core[k][i][j] == 0.0 && input.rte.mc.core_inputfile == NULL) { fprintf (fp, "%d\t%d\t%d\t%.1f\t%g\n", i + 1, j + 1, k + 1, core[k][i][j], distances[k][i][j]); } else { fprintf (fp, "%d\t%d\t%d\t%.1f\tnan\n", i + 1, j + 1, k + 1, core[k][i][j]); } } // else //do also print the non-threed (non-cloud) zeros // { // fprintf(fp, "%d\t%d\t%d\t%.1f\n", i + 1, j + 1, k + 1, 0.0); // } } } } fclose (fp); } //Start to create a delta-scaled profile for the area inside the core if (!input.quiet) fprintf (stderr, "...start delta scaling core\n"); int counter = 0; int counter3d = 0; for (size_t k = 0; k < nz; k++) { if (threed[k]) { counter3d++; for (size_t i = 0; i < nx; i++) { for (size_t j = 0; j < ny; j++) { if (core[k][i][j] > 0.5) { counter++; float g = (output->caoth3d[isp_wc3D]).g1[k][i][j]; float w0 = (output->caoth3d[isp_wc3D]).ssa[k][i][j]; float ext = (output->caoth3d[isp_wc3D]).ext[k][i][j]; float f_scaling = input.rte.mc.core_scale; if (f_scaling < 0.0) f_scaling = g; (output->caoth3d[isp_wc3D]).ext[k][i][j] = 0.0; (output->caoth3d[isp_hiddencore]).ext[k][i][j] = (1 - w0 * f_scaling) * ext; (output->caoth3d[isp_hiddencore]).ssa[k][i][j] = (1 - f_scaling) * w0 / (1 - w0 * f_scaling); (output->caoth3d[isp_hiddencore]).g1[k][i][j] = (g - f_scaling) / (1 - f_scaling); (output->caoth3d[isp_hiddencore]).g2[k][i][j] = 0.0; (output->caoth3d[isp_hiddencore]).ff[k][i][j] = 0.0; } else { (output->caoth3d[isp_hiddencore]).ext[k][i][j] = 0.0; } } } } } if (!input.quiet) fprintf (stderr, "scaled %d pixels of %d 3d pixels! (%.2f%%)\n", counter, counter3d * nx * ny, 100 * counter / ((float)counter3d * nx * ny)); free_float_3D (core); free_float_3D (distances); } /* End Section to find hidden core */ } /********************************/ /* loop over independent pixels */ /********************************/ for (ipa = 0; ipa < output->nipa; ipa++) { for (iipa = 0; iipa < output->niipa; iipa++) { for (jipa = 0; jipa < output->njipa; jipa++) { if (!input.quiet && (output->niipa > 1 || output->njipa > 1)) fprintf (stderr, " ... ipa loop over iipa=%d, jipa=%d\n", iipa, jipa); if (input.verbose && output->nipa == 1) fprintf (stderr, "\n\n*** wavelength: iv = %d, %f nm, albedo = %f \n", iv, output->wl.lambda_r[iv], output->alb.albedo_r[iv]); if (input.verbose && output->nipa > 1) fprintf (stderr, "\n\n*** wavelength: iv = %d, %f nm, looking at column %d, albedo = %f\n", iv, output->wl.lambda_r[iv], ipa, output->alb.albedo_r[iv]); /* copy pixel number ipa to 1D caoth data, ulrike: allow ipa3d (and tipa dir) for caoth */ for (isp = 0; isp < input.n_caoth; isp++) { if (input.caoth[isp].ipa || (input.ipa3d && input.caoth[isp].source == CAOTH_FROM_3D)) { /* copy everything except the single scattering properties */ if (input.caoth[isp].ipa) { status = cp_caoth_out (&(output->caoth[isp]), output->caoth_ipa[isp][ipa], 0, 0, input.quiet); if (status) return fct_err_out (status, "cp_cld_out", ERROR_POSITION); } if (input.ipa3d) { if (!input.quiet) fprintf (stderr, " ... copying 3d to 1d for %s\n", output->caoth[isp].fullname); status = cp_caoth3d_out (&(output->caoth[isp]), output->caoth3d[isp], input.quiet, iipa, jipa); if (status) return fct_err_out (status, "cp_caoth3d_out", ERROR_POSITION); /* copy cloud fraction, if available */ if (output->caoth3d[isp].cldproperties == CLD_LWCREFFCF) { if (!input.quiet) fprintf (stderr, " ... copying cloud fraction from caoth %d\n", isp); /* need to allocate memory for cloud fraction profile? */ if (output->cf.nlev == 0) { if (!input.quiet) fprintf (stderr, " ... allocating memory for cloud fraction profile\n"); output->cf.nlev = output->atm.nlev - 1; output->cf.zd = calloc (output->cf.nlev, sizeof (float)); output->cf.cf = calloc (output->cf.nlev, sizeof (float)); for (lu = 0; lu < output->cf.nlev; lu++) output->cf.zd[lu] = output->atm.zd[lu]; } status = cp_caoth3d_cf_out (output->cf.cf, output->caoth3d[isp], input.quiet, iipa, jipa); if (status) return fct_err_out (status, "cp_caoth3d_cf_out", ERROR_POSITION); } } #if HAVE_TIPA if (input.tipa == TIPA_DIR) { /* ulrike: calculate tilted dtau for caoth */ status = tipa_calcdtau (input.caoth[isp], output->caoth3d[isp], iipa, jipa, iv, input, output->wl, &(output->caoth[isp]), &(output->caoth[isp].tipa)); if (status) return fct_err_out (status, "tipa_calcdtau", ERROR_POSITION); } #endif /* calculate optical properties for the caoth properties specified in the input-file (ulrike) */ status = caoth_prop_switch (input, input.caoth[isp], output->wl, iv, &(output->caoth[isp])); if (status) return fct_err_out (status, "caoth_prop_switch", ERROR_POSITION); /* overwrite these properties with user-defined optical thickness, ssa, etc */ status = apply_user_defined_properties_to_caoth (input.caoth[isp], output->wl.nlambda_r, output->wl.lambda_r, output->alt.altitude, &(output->caoth[isp])); if (status) return fct_err_out (status, "apply_user_defined_properties_to_cld", ERROR_POSITION); } /*ulrike: end of "if (input.caoth[isp].ipa || input.ipa3d)"*/ } /* end loop isp */ if (input.rte.solver == SOLVER_TWOMAXRND && output->cf.nlev == 0) { fprintf (stderr, "Error, rte_solver twomaxrnd makes only sense with cloud_fraction_file\n"); fprintf (stderr, "or cloud fraction defined in 3D cloud file.\n"); return -1; } /* ulrike: for testing */ /* if (input.tipa==TIPA_DIR) { fprintf(stderr,"\nThus, for water clouds we have\n"); for (iz=0; iz<(output->wc.tipa.nztilt); iz++) { fprintf(stderr,"\nAt level= %e km there are totlev[iz=%d]=%d intersection levels\n",output->wc.tipa.level[iz],iz,output->wc.tipa.totlev[iz]); fprintf(stderr," tipa->taudircld[iv=%d][iz=%d]=%e\n",iv,iz,output->wc.tipa.taudircld[iv][iz]); } fprintf(stderr,"\nThus, for ice clouds we have \n"); for (iz=0; iz<(output->ic.tipa.nztilt); iz++) { fprintf(stderr,"\nAt level= %e km there are totlev[iz=%d]=%d intersection levels\n",output->ic.tipa.level[iz],iz,output->ic.tipa.totlev[iz]); fprintf(stderr," tipa->taudircld[iv=%d][iz=%d]=%e\n",iv,iz,output->ic.tipa.taudircld[iv][iz]); } }*/ /* *************************************************************** */ if (input.ipa) { /* copy cloud fraction structure, if needed */ switch (input.cloud_overlap) { case CLOUD_OVERLAP_MAX: case CLOUD_OVERLAP_MAXRAND: /* target */ /* source */ /* alloc */ if (input.rte.solver != SOLVER_TWOMAXRND && input.rte.solver != SOLVER_TWOMAXRND3C && input.rte.solver != SOLVER_DYNAMIC_TWOSTREAM) { status = copy_cloud_fraction (&(output->cf), output->cfipa[ipa], FALSE); /* in cloud.c */ if (status != 0) { fprintf (stderr, "Error %d copying output->cfipa[ipa] to output->cf\n", status); return status; } } /* For (lc=0;lc<output->cf.nlev;lc++) fprintf (stderr, " %s ipa=%3d lc=%3d %f \n", __func__, ipa, lc, output->cf.cf[lc]); */ break; case CLOUD_OVERLAP_RAND: case CLOUD_OVERLAP_OFF: /* nothing to do here */ break; default: fprintf (stderr, "Error, unknown cloud_overlap assumption %d. (line %d, function %s in %s)\n", input.cloud_overlap, __LINE__, __func__, __FILE__); return -1; } } /* IPA molecular absorption and aerosols */ /* these lines also optimise the iq-loop for corr-k schemes, also if there is no ipa */ /* CE: with spectral importance sampling number of calculations always corresponds to maximum number of bands */ if (input.ck_scheme == CK_LOWTRAN && !input.rte.mc.spectral_is) output->atm.nq_r[iv] = output->crs_ck.profile[0][iv].ngauss; /* If only one subband is used in the LOWTRAN parameterization, */ /* the photon weights of the three subbands are added; this is */ /* necessary because the number of subbands changes with */ /* concentration and is therefore not known beforehand. */ /* The correct use of mc_photons_file for LOWTRAN is then */ /* to always distribute the photons over three subbands; */ /* uvspec decides automatically if only one is needed */ if (input.ck_scheme == CK_LOWTRAN) { if (output->atm.nq_r[iv] == 1) for (iq = 1; iq < LOWTRAN_MAXINT; iq++) output->mc_photons_r[iv][0] += output->mc_photons_r[iv][iq]; /* fprintf (stderr, "mc_photons = %f\n", output->mc_photons_r[iv][0]); */ } /* if (input.verbose) { */ /* fprintf (stderr, "*** wavelength: iv = %d, %f nm, albedo = %f\n", iv, output->wl.lambda_r[iv], output->alb.albedo_r[iv]); */ /* fprintf (stderr, " atm.nmom + 1 = %d phase function moments\n", output->atm.nmom+1); */ /* fprintf (stderr, " --------------------------------------------------------------------------------------------\n"); */ /* fprintf (stderr, " lu | z[km] | aerosol | water cloud | ice cloud | tau_molecular \n"); */ /* fprintf (stderr, " | | dtau nmom | dtau nmom | dtau nmom | \n"); */ /* fprintf (stderr, " --------------------------------------------------------------------------------------------\n"); */ /* for (lu=0; lu<output->atm.nlyr; lu++) */ /* fprintf (stderr, "%5d | %8.2f | %11.6f %5d | %11.6f %5d | %11.6f %5d | %11.6f \n", */ /* lu, output->atm.zd[lu+1], */ /* 0.0,0, /\*output->aer.dtau[iv][lu], output->aer.nmom[iv][lu],*\/ */ /* output->wc.optprop.dtau [iv][lu], output->wc.optprop.nmom[iv][lu], */ /* output->ic.optprop.dtau [iv][lu], output->ic.optprop.nmom[iv][lu], */ /* output->atm.optprop.tau_molabs_r[lu][iv][0]); */ /* fprintf (stderr, " ---------------------------------------------------------------------------\n"); */ /* } */ /* need to load data during first call of mystic() for each band/wavelength */ mc_loaddata = 1; /* reset band integral */ reset_rte_output (&rte_outband, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->mc.alis.nlambda_abs, output->atm.nlev - 1, output->atm.threed, output->mc.sample.passback3D, output->mc.triangular_surface.N_triangles); if (input.raman) { if (ir == 0) { if (input.raman_fast) { lower_iq_id = output->wl.nlambda_rte_lower; output->atm.nq_r[iv] = output->wl.nlambda_rte_upper; } else { output->atm.nq_r[iv] = output->crs.number_of_ramanwavelengths; } upper_iq_id = output->atm.nq_r[iv]; } else if (ir == 1) { output->atm.nq_r[iv] = 1; lower_iq_id = 0; upper_iq_id = output->atm.nq_r[iv]; } } else { lower_iq_id = 0; upper_iq_id = output->atm.nq_r[iv]; } /******************************************/ /* loop over quadrature points (subbands) */ /******************************************/ for (iq = lower_iq_id; iq < upper_iq_id; iq++) { if (input.verbose && (input.ck_scheme != CK_CRS)) fprintf (stderr, "\n*** wavelength: iv = %d, %f nm, looking at column %d, quadrature point nr %d, albedo = %f\n", iv, output->wl.lambda_r[iv], ipa, iq, output->alb.albedo_r[iv]); if (input.verbose && (input.ck_scheme == CK_RAMAN)) fprintf (stderr, "\n*** wavelength: iv = %d, %f nm, looking at column %d, quadrature point nr %d, wvl = %f\n", iv, output->wl.lambda_r[iv], ipa, iq, output->wl.lambda_r[iq]); /* set number of photons for this band */ if (input.rte.solver == SOLVER_MONTECARLO && !input.rte.mc.spectral_is) output->mc_photons = (long int)(output->mc_photons_r[iv][iq] * (double)input.rte.mc.photons + 0.5); /* run at least MIN_MCPHOTONS for each band */ /* no need to increase for backward direct because backward direct is (nearly) exact */ if (output->mc.sample.backward != MCBACKWARD_EDIR && output->mc.sample.backward != MCBACKWARD_FDIR) { if (input.rte.mc.minphotons) { /* set by user */ if (output->mc_photons < (long int)input.rte.mc.minphotons) output->mc_photons = input.rte.mc.minphotons; } else { /* default */ if (output->mc_photons < MIN_MCPHOTONS) output->mc_photons = MIN_MCPHOTONS; } } else { /* however, we need at least one photon for direct */ if (output->mc_photons < 1) output->mc_photons = 1; } /* For spectral importance sampling, only one wavelength is */ /* calculated, therefore no distribution of photons required. */ if (input.rte.mc.spectral_is) output->mc_photons = input.rte.mc.photons; if (input.verbose) fprintf (stderr, " ... ck weight %9.7f\n", output->atm.wght_r[iv][iq]); /* if the level number of cloud fraction data is more than 0, than ... */ if (input.cloud_overlap != CLOUD_OVERLAP_OFF && input.rte.solver != SOLVER_TWOMAXRND && input.rte.solver != SOLVER_TWOMAXRND3C && input.rte.solver != SOLVER_DYNAMIC_TWOSTREAM) { /* Save optical properties for wavelength iv. This is necessary because averaged optical properties are calulated for each subband and put into output->wc.optprop.... */ if (iq == 0) { for (lc = 0; lc < output->atm.nlev - 1; lc++) { if (input.i_wc != -1) { /* optical depth */ save_cloud->tauw[lc] = output->caoth[input.i_wc].optprop.dtau[iv][lc]; /* asymmetry parameter */ save_cloud->g1d[lc] = output->caoth[input.i_wc].optprop.g1[iv][lc]; save_cloud->g2d[lc] = output->caoth[input.i_wc].optprop.g2[iv][lc]; save_cloud->fd[lc] = output->caoth[input.i_wc].optprop.ff[iv][lc]; /* single scattering albedo */ save_cloud->ssaw[lc] = output->caoth[input.i_wc].optprop.ssa[iv][lc]; } else { save_cloud->tauw[lc] = 0.0; save_cloud->g1d[lc] = 0.0; save_cloud->g2d[lc] = 0.0; save_cloud->fd[lc] = 0.0; save_cloud->ssaw[lc] = 0.0; } if (input.i_ic != -1) { /* optical depth */ save_cloud->taui[lc] = output->caoth[input.i_ic].optprop.dtau[iv][lc]; /* asymmetry parameter */ save_cloud->g1i[lc] = output->caoth[input.i_ic].optprop.g1[iv][lc]; save_cloud->g2i[lc] = output->caoth[input.i_ic].optprop.g2[iv][lc]; save_cloud->fi[lc] = output->caoth[input.i_ic].optprop.ff[iv][lc]; /* single scattering albedo */ save_cloud->ssai[lc] = output->caoth[input.i_ic].optprop.ssa[iv][lc]; } else { save_cloud->taui[lc] = 0.0; save_cloud->g1i[lc] = 0.0; save_cloud->g2i[lc] = 0.0; save_cloud->fi[lc] = 0.0; save_cloud->ssai[lc] = 0.0; } } } /* calculate effective cloud optical properties for fractional cloud cover */ status = generate_effective_cloud (input, output, save_cloud, iv, iq, input.verbose); /* in solve_rte.c */ CHKERR (status); } /* 3DAbs include caoth3d for 3D molecular atmosphere, right place here ??? */ if (input.rte.solver == SOLVER_MONTECARLO && output->molecular3d) optical_properties_molecular3d (input, output, &(output->caoth3d[CAOTH_FIR]), iv, iq); /* setup optical properties and call the RTE solver */ status = setup_and_call_solver (input, output, rte_in, rte_out, raman_qsrc_components, iv, iq, ir, output->atm.threed, mc_loaddata); CHKERR (status); /* verbose output */ if (input.verbose) { fprintf (stderr, " iv = %d, %f nm, iq = %d, flux_dir[lu=0] = %13.7e, flux_dn[lu=0] = %13.7e, flux_up[lu=0] = %13.7e, " "weight_r = %13.7e \n", iv, output->wl.lambda_r[iv], iq, rte_out->rfldir[0], rte_out->rfldn[0], rte_out->flup[0], output->atm.wght_r[iv][iq]); } /* data need to be loaded only once per iv */ mc_loaddata = 0; if (input.heating != HEAT_NONE) calc_spectral_heating (input, output, dz, rho_mass_zout, k_abs, k_abs_layer, rte_in->pol.outlevels, rte_out, rte_out->heat, rte_out->emis, rte_out->w_zout, iv); /**********************************************************************/ /* Store intensities for later use in second round of raman iteration */ /**********************************************************************/ if (input.raman) { if (ir == 0) { if (input.raman_fast) { for (lu = 0; lu < output->atm.nlyr; lu++) raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu]; raman_qsrc_components->fbeam[iq] = rte_in->fbeam; for (lu = 0; lu < output->atm.nzout; lu++) { raman_qsrc_components->uavgso[lu][iq] = (double)rte_out->uavgso[lu]; raman_qsrc_components->uavgdn[lu][iq] = (double)rte_out->uavgdn[lu]; raman_qsrc_components->uavgup[lu][iq] = (double)rte_out->uavgup[lu]; raman_qsrc_components->rfldir[lu][iq] = (double)rte_out->rfldir[lu]; raman_qsrc_components->rfldn[lu][iq] = (double)rte_out->rfldn[lu]; raman_qsrc_components->flup[lu][iq] = (double)rte_out->flup[lu]; for (iu = 0; iu < input.rte.nstr; iu++) { raman_qsrc_components->u0u[lu][input.rte.cmuind[iu]][iq] = (double)rte_out->u0u[lu][input.rte.cmuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { raman_qsrc_components->uu[lu][j][input.rte.cmuind[iu]][iq] = (double)rte_out->uu[j][lu][input.rte.cmuind[iu]]; } } for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) { raman_qsrc_components->u0u[lu][input.rte.umuind[iu]][iq] = (double)rte_out->u0u[lu][input.rte.umuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { raman_qsrc_components->uu[lu][j][input.rte.umuind[iu]][iq] = (double)rte_out->uu[j][lu][input.rte.umuind[iu]]; } } } for (lu = 0; lu < output->atm.nzout; lu++) { for (j = 0; j < input.rte.nstr; j++) { for (iu = 0; iu < input.rte.numu; iu++) { raman_qsrc_components->uum[lu][j][iu][iq] = (double)rte_out->uum[j][lu][iu]; } } } } else { raman_qsrc_components->fbeam[iq] = (double)rte_in->fbeam; if (input.verbose) fprintf (stderr, "Storing Raman quantities for iq: %3d out of %3d.\n", iq, output->crs.number_of_ramanwavelengths - 1); if (iq == output->crs.number_of_ramanwavelengths - 1) { /* Only store radiation for the wanted wavelength which should be at the last index */ for (lu = 0; lu < output->atm.nlyr; lu++) raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu]; for (lu = 0; lu < output->atm.nzout; lu++) { uavgso_raman[lu] = rte_out->uavgso[lu]; uavgdn_raman[lu] = rte_out->uavgdn[lu]; uavgup_raman[lu] = rte_out->uavgup[lu]; rfldir_raman[lu] = rte_out->rfldir[lu]; rfldn_raman[lu] = rte_out->rfldn[lu]; flup_raman[lu] = rte_out->flup[lu]; rte_out->rfldir[lu] = 0; rte_out->rfldn[lu] = 0; rte_out->flup[lu] = 0; for (iu = 0; iu < input.rte.nstr; iu++) { u0u_raman[lu][input.rte.cmuind[iu]] = rte_out->u0u[lu][input.rte.cmuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { uu_raman[lu][j][input.rte.cmuind[iu]] = rte_out->uu[j][lu][input.rte.cmuind[iu]]; } } for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) { u0u_raman[lu][input.rte.umuind[iu]] = rte_out->u0u[lu][input.rte.umuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { uu_raman[lu][j][input.rte.umuind[iu]] = rte_out->uu[j][lu][input.rte.umuind[iu]]; } } } } /* Store source components at all shifted wavelengths. Store uum for all wavelengths, */ /* including the last index which contains the wanted wavelength */ for (lu = 0; lu < output->atm.nlyr; lu++) raman_qsrc_components->dtauc[lu][iq] = (double)output->dtauc[lu]; for (lu = 0; lu < output->atm.nzout; lu++) { for (j = 0; j < input.rte.nstr; j++) { for (iu = 0; iu < input.rte.numu; iu++) { raman_qsrc_components->uum[lu][j][iu][iq] = (double)rte_out->uum[j][lu][iu]; } } } } } else if (ir == 1) { add = 1; if (input.raman_fast) { ivr = iv + output->wl.nlambda_rte_lower; for (lu = 0; lu < output->atm.nzout; lu++) { rte_out->uavgso[lu] += (double)raman_qsrc_components->uavgso[lu][ivr]; rte_out->uavgup[lu] += (double)raman_qsrc_components->uavgup[lu][ivr]; rte_out->uavgdn[lu] += (double)raman_qsrc_components->uavgdn[lu][ivr]; rte_out->rfldir[lu] += (double)raman_qsrc_components->rfldir[lu][ivr]; rte_out->rfldn[lu] += (double)raman_qsrc_components->rfldn[lu][ivr]; rte_out->flup[lu] += (double)raman_qsrc_components->flup[lu][ivr]; for (iu = 0; iu < input.rte.nstr; iu++) { rte_out->u0u[lu][input.rte.cmuind[iu]] += (double)raman_qsrc_components->u0u[lu][input.rte.cmuind[iu]][ivr]; for (j = 0; j < input.rte.nphi; j++) { rte_out->uu[j][lu][input.rte.cmuind[iu]] += (double)raman_qsrc_components->uu[lu][j][input.rte.cmuind[iu]][ivr]; } } for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) { rte_out->u0u[lu][input.rte.umuind[iu]] += (double)raman_qsrc_components->u0u[lu][input.rte.umuind[iu]][ivr]; for (j = 0; j < input.rte.nphi; j++) { rte_out->uu[j][lu][input.rte.umuind[iu]] += (double)raman_qsrc_components->uu[lu][j][input.rte.umuind[iu]][ivr]; } } } } else { for (lu = 0; lu < output->atm.nzout; lu++) { if (add) { rte_out->uavgso[lu] += uavgso_raman[lu]; rte_out->uavgdn[lu] += uavgdn_raman[lu]; rte_out->uavgup[lu] += uavgup_raman[lu]; rte_out->rfldir[lu] += rfldir_raman[lu]; rte_out->rfldn[lu] += rfldn_raman[lu]; rte_out->flup[lu] += flup_raman[lu]; for (iu = 0; iu < input.rte.nstr; iu++) { rte_out->u0u[lu][input.rte.cmuind[iu]] += u0u_raman[lu][input.rte.cmuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { rte_out->uu[j][lu][input.rte.cmuind[iu]] += uu_raman[lu][j][input.rte.cmuind[iu]]; } } for (iu = 0; iu < input.rte.numu - input.rte.nstr; iu++) { rte_out->u0u[lu][input.rte.umuind[iu]] += u0u_raman[lu][input.rte.umuind[iu]]; for (j = 0; j < input.rte.nphi; j++) { rte_out->uu[j][lu][input.rte.umuind[iu]] += uu_raman[lu][j][input.rte.umuind[iu]]; } } } } } } } /* add result for the current quadrature point considering quadrature weight */ if (!input.raman || (input.raman && ir == 0 && iq == output->crs.number_of_ramanwavelengths - 1) || (input.raman && ir == 1)) { if (input.raman) { if (ir == 0) weight = 0; else if (ir == 1) weight = 1; } else weight = output->atm.wght_r[iv][iq]; if (input.rte.mc.spectral_is) for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) weight_spectral[iv_alis] = output->atm.wght_r[iv_alis][iq]; status = add_rte_output (rte_outband, rte_out, weight, weight_spectral, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.alis.Nc, output->atm.nlev - 1, output->mc.alis.nlambda_abs, output->atm.threed, output->mc.sample.passback3D, output->islower, output->isupper, output->jslower, output->jsupper, output->isstep, output->jsstep); CHKERR (status); } } /* for (iq=0; iq<output->atm.nq_r[iv]; iq++) { ... == 'loop over quadrature points' */ /************************************************/ /* add result for the current independent pixel */ /************************************************/ if (input.rte.solver == SOLVER_POLRADTRAN) { for (lu = 0; lu < output->atm.nzout; lu++) { output->rfldir_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldir[lu]; output->heat_r[lu][iv] += output->ipaweight[ipa] * rte_outband->heat[lu]; output->emis_r[lu][iv] += output->ipaweight[ipa] * rte_outband->emis[lu]; output->w_zout_r[lu][iv] += output->ipaweight[ipa] * rte_outband->w_zout[lu]; for (is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) { output->up_flux_r[lu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_up_flux[lu][is]; output->down_flux_r[lu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_down_flux[lu][is]; for (j = 0; j < input.rte.nphi; j++) { for (iu = 0; iu < input.rte.numu; iu++) { output->down_rad_r[lu][j][iu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_down_rad[lu][j][iu][is]; output->up_rad_r[lu][j][iu][is][iv] += output->ipaweight[ipa] * rte_outband->polradtran_up_rad[lu][j][iu][is]; } } } } } else if (rte_in->ibcnd) { for (iu = 0; iu < input.rte.numu; iu++) { output->albmed_r[iu][iv] += rte_outband->albmed[iu]; output->trnmed_r[iu][iv] += rte_outband->trnmed[iu]; } } else { for (lu = 0; lu < output->atm.nzout; lu++) { output->rfldir_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldir[lu]; output->rfldn_r[lu][iv] += output->ipaweight[ipa] * rte_outband->rfldn[lu]; output->flup_r[lu][iv] += output->ipaweight[ipa] * rte_outband->flup[lu]; output->uavg_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavg[lu]; output->uavgdn_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgdn[lu]; output->uavgso_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgso[lu]; output->uavgup_r[lu][iv] += output->ipaweight[ipa] * rte_outband->uavgup[lu]; output->heat_r[lu][iv] += output->ipaweight[ipa] * rte_outband->heat[lu]; output->emis_r[lu][iv] += output->ipaweight[ipa] * rte_outband->emis[lu]; output->w_zout_r[lu][iv] += output->ipaweight[ipa] * rte_outband->w_zout[lu]; output->sslidar_nphot_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_nphot[lu]; output->sslidar_nphot_q_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_nphot_q[lu]; output->sslidar_ratio_r[lu][iv] += output->ipaweight[ipa] * rte_outband->sslidar_ratio[lu]; /* intensities */ for (iu = 0; iu < input.rte.numu; iu++) { output->u0u_r[lu][iu][iv] += output->ipaweight[ipa] * rte_outband->u0u[lu][iu]; for (j = 0; j < input.rte.nphi; j++) output->uu_r[lu][j][iu][iv] += output->ipaweight[ipa] * rte_outband->uu[j][lu][iu]; } /* 3D fields */ /* ulrike: I added "&& input.rte.solver == SOLVER_MONTECARLO" */ if (output->mc.sample.passback3D && input.rte.solver == SOLVER_MONTECARLO) { for (is = output->islower; is <= output->isupper; is += output->isstep) { for (js = output->jslower; js <= output->jsupper; js += output->jsstep) { output->rfldir3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->rfldir3d[lu][is][js]; output->rfldn3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->rfldn3d[lu][is][js]; output->flup3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->flup3d[lu][is][js]; output->uavgso3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgso3d[lu][is][js]; output->uavgdn3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgdn3d[lu][is][js]; output->uavgup3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->uavgup3d[lu][is][js]; if (output->mc.sample.spectral_is || output->mc.sample.concentration_is) for (ic = 0; ic < output->mc.alis.Nc; ic++) { for (ivs = 0; ivs < output->mc.alis.nlambda_abs; ivs++) { output->fl3d_is_r[lu][is][js][ic][ivs] += output->ipaweight[ipa] * rte_outband->fl3d_is[lu][ic][is][js][ivs]; } } for (ip = 0; ip < input.rte.mc.nstokes; ip++) { if (output->mc.sample.spectral_is || output->mc.sample.concentration_is) { for (ivs = 0; ivs < output->mc.alis.nlambda_abs; ivs++) { for (ic = 0; ic < output->mc.alis.Nc; ic++) { output->radiance3d_r[lu][is][js][ip][ic][ivs] += output->ipaweight[ipa] * rte_outband->radiance3d_is[lu][ic][is][js][ip][ivs]; } } } else output->radiance3d_r[lu][is][js][ip][0][iv] += output->ipaweight[ipa] * rte_outband->radiance3d[lu][is][js][ip]; } if (input.rte.mc.jacobian[DIM_1D]) { for (isp = 0; isp < input.n_caoth + 2; isp++) { for (ijac = 0; ijac < 2; ijac++) { /* scattering and absorption */ for (lc = 0; lc < output->atm.nlyr; lc++) { output->jacobian_r[lu][is][js][isp][ijac][lc][iv] += output->ipaweight[ipa] * rte_outband->jacobian[lu][is][js][isp][ijac][lc]; } } } } if (input.rte.mc.backward.absorption) output->absback3d_r[lu][is][js][iv] += output->ipaweight[ipa] * rte_outband->absback3d[lu][is][js]; /* variances */ if (input.rte.mc.std) { /* variance is weighted with square of weight */ weight2 = output->ipaweight[ipa] * output->ipaweight[ipa]; output->rfldir3d_var_r[lu][is][js][iv] += weight2 * rte_outband->rfldir3d_var[lu][is][js]; output->rfldn3d_var_r[lu][is][js][iv] += weight2 * rte_outband->rfldn3d_var[lu][is][js]; output->flup3d_var_r[lu][is][js][iv] += weight2 * rte_outband->flup3d_var[lu][is][js]; output->uavgso3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgso3d_var[lu][is][js]; output->uavgdn3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgdn3d_var[lu][is][js]; output->uavgup3d_var_r[lu][is][js][iv] += weight2 * rte_outband->uavgup3d_var[lu][is][js]; for (ip = 0; ip < input.rte.mc.nstokes; ip++) output->radiance3d_var_r[lu][is][js][ip][iv] += weight2 * rte_outband->radiance3d_var[lu][is][js][ip]; if (input.rte.mc.backward.absorption) output->absback3d_var_r[lu][is][js][iv] += weight2 * rte_outband->absback3d_var[lu][is][js]; } } } } else if (input.ipa3d) { /*ulrike: 3d-fields (without _r) are not needed*/ /* BM 3.7.2020: removed factor ipaweight[]; see comment above */ output->rfldir3d_r[lu][iipa][jipa][iv] += rte_outband->rfldir[lu]; output->rfldn3d_r[lu][iipa][jipa][iv] += rte_outband->rfldn[lu]; output->flup3d_r[lu][iipa][jipa][iv] += rte_outband->flup[lu]; output->uavgso3d_r[lu][iipa][jipa][iv] += rte_outband->uavgso[lu]; output->uavgdn3d_r[lu][iipa][jipa][iv] += rte_outband->uavgdn[lu]; output->uavgup3d_r[lu][iipa][jipa][iv] += rte_outband->uavgup[lu]; /* ulrike: missing: emis, w_zout ????????????? */ /*ulrike: 4.5.2010 use absback3d_r to save the ipa_3d-heating rates!*/ if (input.rte.mc.backward.absorption) output->absback3d_r[lu][iipa][jipa][iv] += output->ipaweight[ipa] * rte_outband->heat[lu]; } /*ulrike: end of: else if (input.ipa3d)*/ } /*ulrike: end for-loop over lev lu*/ /* 3D absorption; ulrike added && input.rte.solver == SOLVER_MONTECARLO */ if (output->mc.sample.passback3D && input.rte.mc.absorption != MCFORWARD_ABS_NONE && input.rte.solver == SOLVER_MONTECARLO) for (ks = 0; ks < output->atm.Nzcld; ks++) if (output->atm.threed[ks]) /* only for 3D layers, BM07122005 */ for (is = 0; is < output->atm.Nxcld; is++) for (js = 0; js < output->atm.Nycld; js++) { /* **CK added bracket */ output->abs3d_r[ks][is][js][iv] += output->ipaweight[ipa] * rte_outband->abs3d[ks][is][js]; if (input.rte.mc.std) /* **CK added for forward mc_std */ output->abs3d_var_r[ks][is][js][iv] += output->ipaweight[ipa] * rte_outband->abs3d_var[ks][is][js]; } } /* endof of if(input.rte.solver == SOLVER_POLRADTRAN) elsif {rte_in->ibcnd} else {} */ if (rte_outband->triangle_results) { // Add triangle result -> output->result const double factor = output->ipaweight[ipa]; status = add_triangular_surface_result (factor, rte_outband->triangle_results, output->triangle_results_r[iv]); CHKERR (status); } /* verbose output */ if (input.verbose) { fprintf (stderr, " iv = %d, %f nm, sum iq, flux_dir[lu=0] = %13.7e, flux_dn[lu=0] = %13.7e, flux_up[lu=0] = %13.7e \n", iv, output->wl.lambda_r[iv], output->rfldir_r[0][iv], output->rfldn_r[0][iv], output->flup_r[0][iv]); } } /* for (jipa=0; ipa<output->njipa; jipa++) independent pixel (ulrike) */ } /* for (iipa=0; ipa<output->niipa; iipa++) independent pixel (ulrike) */ } /* for (ipa=0; ipa<output->nipa; ipa++) independent pixel */ /* change unit of the solar spectrum [e.g. W/(m2 nm)] or terrestral spectrum [e.g. W/(m2 cm-1)] */ /* to output units wanted by the user: 'output per_nm', 'output per_cm', or 'output per_band' */ /* but only, when dealing with unit (not transmission or reflectivity). */ /* Unit conversion must happen before interpolate transmittance, as some unit conversions */ /* use the internal thermal bandwidths or correlated-k bandwidth. */ /* UH 2006-03 */ if (output->wl.use_reptran) unit_factor = 1; /* conversion is done in internal_to_transmittance_grid() */ else unit_factor = get_unit_factor (input, output, iv); if (unit_factor <= 0) { fprintf (stderr, "Error, calculating unit_factor = %f in %s (%s)\n", unit_factor, function_name, file_name); return -1; } switch (input.source) { case SRC_THERMAL: ffactor = unit_factor; rfactor = unit_factor; break; case SRC_SOLAR: case SRC_BLITZ: /* BCA */ case SRC_LIDAR: /* BCA */ switch (input.processing) { case PROCESS_INT: case PROCESS_SUM: case PROCESS_RGB: case PROCESS_RGBNORM: ffactor = unit_factor; rfactor = unit_factor; break; case PROCESS_NONE: case PROCESS_RAMAN: switch (input.calibration) { case OUTCAL_ABSOLUTE: ffactor = unit_factor; rfactor = unit_factor; break; case OUTCAL_TRANSMITTANCE: ffactor = 1.0; rfactor = 1.0; break; case OUTCAL_REFLECTIVITY: ffactor = 1.0; rfactor = 1.0; break; default: fprintf (stderr, "Error, unknown output calibration %d\n", input.calibration); return -1; } break; default: fprintf (stderr, "Error, unknown output processing %d\n", input.processing); return -1; } break; default: fprintf (stderr, "Error, unknown source %d\n", input.source); return -1; } hfactor = unit_factor; /*****************************************************************************************/ /* now scale irradiances with ffactor, radiances with rfactor, heating rate with hfactor */ /*****************************************************************************************/ status = scale_output (input, &(output->rfldir_r), &(output->rfldn_r), &(output->flup_r), &(output->albmed_r), &(output->trnmed_r), &(output->uavgso_r), &(output->uavgdn_r), &(output->uavgup_r), &(output->uavg_r), &(output->u0u_r), &(output->uu_r), &(output->heat_r), &(output->emis_r), &(output->w_zout_r), &(output->down_flux_r), &(output->up_flux_r), &(output->down_rad_r), &(output->up_rad_r), &(output->rfldir3d_r), &(output->rfldn3d_r), &(output->flup3d_r), &(output->fl3d_is_r), &(output->uavgso3d_r), &(output->uavgdn3d_r), &(output->uavgup3d_r), &(output->radiance3d_r), &(output->jacobian_r), &(output->absback3d_r), &(output->rfldir3d_var_r), &(output->rfldn3d_var_r), &(output->flup3d_var_r), &(output->uavgso3d_var_r), &(output->uavgdn3d_var_r), &(output->uavgup3d_var_r), &(output->radiance3d_var_r), &(output->abs3d_var_r), &(output->absback3d_var_r), output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.alis.Nc, output->atm.nlev - 1, output->atm.threed, output->mc.sample.passback3D, output->islower, output->isupper, output->jslower, output->jsupper, output->isstep, output->jsstep, &(output->abs3d_r), output->triangle_results_r, ffactor, rfactor, hfactor, iv); /* in ancillary.c */ /* **CK added &(output->abs3d_var_r), for forward mc_std */ CHKERR (status); /* free 3D cloud properties */ if (input.rte.solver == SOLVER_MONTECARLO) for (isp = 0; isp < input.n_caoth; isp++) { status = free_caoth_mystic (input.caoth[isp].properties, &(output->caoth3d[isp])); CHKERR (status); } } /* for (ir=0; ir<nr; ir++) */ iv_count++; } /* for (iv=output->wl.nlambda_rte_lower; iv<=output->wl.nlambda_rte_upper; iv++) */ /* ulrike: free msorted and zsorted (for tipa dir!!! for tipa dirdiff msorted is freed already), output->(w/i)c.tipa.taudircld, ... */ if (input.tipa == TIPA_DIR || input.rte.mc.tipa == TIPA_DIR) { for (isp = 0; isp < input.n_caoth; isp++) if (input.caoth[isp].source == CAOTH_FROM_3D) { /* free m-and z-sorted for caoth */ for (iz = 0; iz < (output->caoth[isp].tipa.nztilt); iz++) { for (ks = 0; ks < (output->caoth[isp].tipa.totlev[iz]); ks++) free ((output->caoth[isp].tipa.msorted)[iz][ks]); free ((output->caoth[isp].tipa.msorted)[iz]); free ((output->caoth[isp].tipa.zsorted)[iz]); } free (output->caoth[isp].tipa.msorted); free (output->caoth[isp].tipa.zsorted); for (js = 0; js < (upper_wl_id - lower_wl_id + 1); js++) /* free taudircld for wc */ free ((output->caoth[isp].tipa.taudircld)[js]); free (output->caoth[isp].tipa.taudircld); } } /* free temporary memory */ status = free_rte_output (rte_out, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->atm.nlyr - 1, output->mc.alis.nlambda_abs, output->atm.threed, output->mc.sample.passback3D); CHKERR (status); status = free_rte_output (rte_outband, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->atm.nlyr - 1, output->mc.alis.nlambda_abs, output->atm.threed, output->mc.sample.passback3D); CHKERR (status); if (input.rte.solver == SOLVER_POLRADTRAN) { free (rte_in->pol.height); free (rte_in->pol.temperatures); free (rte_in->pol.gas_extinct); } free (rte_in->pol.outlevels); free (rte_in->hl); free (rte_in->utau); free (rte_in); if (input.rte.solver == SOLVER_DISORT && input.raman) { if (uu_raman != NULL) ASCII_free_double_3D (uu_raman, output->atm.nzout, input.rte.nphi); ASCII_free_double (u0u_raman, output->atm.nzout); free (uavgso_raman); free (uavgdn_raman); free (uavgup_raman); free (rfldir_raman); free (rfldn_raman); free (flup_raman); } if (input.raman) { free_raman_qsrc_components (raman_qsrc_components, input.raman_fast, output->atm.nzout, input.rte.maxumu, input.rte.nphi, input.rte.nstr); } if (input.heating != HEAT_NONE) { free (dz); free (k_abs_layer); free (k_abs); } if (save_cloud != NULL) { free (save_cloud->tauw); free (save_cloud->taui); free (save_cloud->g1d); free (save_cloud->g2d); free (save_cloud->fd); free (save_cloud->g1i); free (save_cloud->g2i); free (save_cloud->fi); free (save_cloud->ssaw); free (save_cloud->ssai); free (save_cloud); } #if HAVE_LIBGSL #ifdef WRITERANDOMSTATUS if (remove (input.filename[FN_RANDOMSTATUS]) != 0) fprintf (stderr, "Error deleting randomstatusfile"); #endif #endif return 0; } /* small function to get factor for unit conversion */ double get_unit_factor (input_struct input, output_struct* output, int iv) { double unit_factor = 0.0; char function_name[] = "get_unit_factor"; char file_name[] = "solve_rte.c"; switch (output->spectrum_unit) { case UNIT_PER_NM: switch (input.output_unit) { case UNIT_PER_NM: unit_factor = 1.0; break; case UNIT_PER_CM_1: /* unit_factor = (lambda/k) */ /* (lambda/k) = (lambda**2) / 1.0e+7 */ /* 1.0e+7 == cm -> nm; */ unit_factor = (output->wl.lambda_r[iv] * output->wl.lambda_r[iv]) / 1.0e+7; break; case UNIT_PER_BAND: /* unit_factor = delta_lambda */ /* lambda_max = 1.0e+7 / k_lower; lambda_min = 1.0e+7 / k_upper */ unit_factor = 1.0e+7 / output->wl.wvnmlo_r[iv] - 1.0e+7 / output->wl.wvnmhi_r[iv]; break; case UNIT_NOT_DEFINED: unit_factor = 1.0; break; default: fprintf (stderr, "Error: Program bug, unsupported output unit %d in %s (%s). \n", input.output_unit, function_name, file_name); return -1; } break; case UNIT_PER_CM_1: switch (input.output_unit) { case UNIT_PER_NM: /* unit_factor = (k/lambda) */ /* (k/lambda)= 1.0e+7 / (lambda**2) */ /* 1.0e+7 == cm -> nm; */ /* k wavenumber in 1/cm**-1, lambda in nm */ unit_factor = 1.0e+7 / (output->wl.lambda_r[iv] * output->wl.lambda_r[iv]); break; case UNIT_PER_CM_1: unit_factor = 1.0; break; case UNIT_PER_BAND: /* unit_factor = delta_k */ unit_factor = output->wl.wvnmhi_r[iv] - output->wl.wvnmlo_r[iv]; break; case UNIT_NOT_DEFINED: unit_factor = 1.0; break; default: fprintf (stderr, "Error: Program bug, unsupported output unit %d in %s (%s). \n", input.output_unit, function_name, file_name); return -1; } break; case UNIT_PER_BAND: switch (input.output_unit) { case UNIT_PER_NM: /* unit_factor = 1 / delta_lambda */ /* lambda_max = 1.0e+7 / k_lower; lambda_min = 1.0e+7 / k_upper */ unit_factor = 1.0 / (1.0e7 / output->wl.wvnmlo_r[iv] - 1.0e7 / output->wl.wvnmhi_r[iv]); break; case UNIT_PER_CM_1: /* unit_factor = 1 / delta_k */ unit_factor = 1.0 / (output->wl.wvnmhi_r[iv] - output->wl.wvnmlo_r[iv]); break; case UNIT_PER_BAND: unit_factor = 1.0; break; case UNIT_NOT_DEFINED: /* not defined */ unit_factor = 1.0; break; default: fprintf (stderr, "Error, program bug, unsupported output unit %d\n", input.output_unit); return -1; } break; case UNIT_NOT_DEFINED: switch (input.output_unit) { case UNIT_PER_NM: case UNIT_PER_CM_1: case UNIT_PER_BAND: fprintf (stderr, "Error, can not convert undefined solar spectrum to output with units\n"); fprintf (stderr, " please use 'solar_file filename unit' in order to specify the unit of the spectrum\n"); return -1; break; case UNIT_NOT_DEFINED: /* not defined */ unit_factor = 1.0; break; default: fprintf (stderr, "Error, program bug, unsupported output unit %d\n", input.output_unit); return -1; } break; default: fprintf (stderr, "Error: Program bug, unsupported unit of solar_file %d\n", output->spectrum_unit); return -1; } return unit_factor; } int setup_result (input_struct input, output_struct* output, float** p_dz, double** p_rho_mass_zout, float** p_k_abs_layer, float** p_k_abs, float** p_k_abs_outband) { int status = 0; int nlambda = 0; int lc = 0, lu = 0, is = 0, js = 0, ip = 0, ic = 0; /* FIX 3DAbs need to be initialized when aerosol is not set up, now redundant ??? */ /* output->mc.alis.Nc=1; */ if ((status = ASCII_calloc_float (&output->flup_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->rfldir_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->rfldn_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavg_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgdn_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgso_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgup_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->heat_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->emis_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->w_zout_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_nphot_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_nphot_q_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_ratio_r, output->atm.nzout, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->albmed_r, input.rte.numu, output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float (&output->trnmed_r, input.rte.numu, output->wl.nlambda_r)) != 0) return status; /* variables in order to calculate heating rates (by actinic flux) */ if (input.heating != HEAT_NONE) { *p_dz = calloc (output->atm.nlyr, sizeof (float)); /* dz in m for all (nlyr) layers */ CHKPOINTER (*p_dz); /* Initialisation */ for (lc = 0; lc < output->atm.nlyr; lc++) { (*p_dz)[lc] = (output->atm.zd[lc] - output->atm.zd[lc + 1]) * 1000.0; /* km -> m */ } *p_rho_mass_zout = calloc (output->atm.nzout, sizeof (double)); CHKPOINTER (*p_rho_mass_zout); *p_k_abs_layer = calloc (output->atm.nlyr, sizeof (float)); CHKPOINTER (*p_k_abs_layer); *p_k_abs = calloc (output->atm.nzout, sizeof (float)); CHKPOINTER (*p_k_abs); *p_k_abs_outband = calloc (output->atm.nzout, sizeof (float)); CHKPOINTER (*p_k_abs_outband); } if (input.rte.numu > 0) { status = ASCII_calloc_float_3D (&output->u0u_r, output->atm.nzout, input.rte.numu, output->wl.nlambda_r); CHKERR (status); } if (input.rte.numu > 0 && input.rte.nphi > 0) { status = ASCII_calloc_float_4D (&output->uu_r, output->atm.nzout, input.rte.nphi, input.rte.numu, output->wl.nlambda_r); CHKERR (status); } if (output->mc.sample.passback3D) { if (!input.quiet) fprintf (stderr, " ... allocating %d x %d x %d x %d = %d pixels (%d bytes) for 3D output\n", output->atm.nzout, (output->isupper - output->islower + 1), (output->jsupper - output->jslower + 1), output->wl.nlambda_r, output->atm.nzout * (output->isupper - output->islower + 1) * (output->jsupper - output->jslower + 1) * output->wl.nlambda_r, output->atm.nzout * (output->isupper - output->islower + 1) * (output->jsupper - output->jslower + 1) * output->wl.nlambda_r * (int)sizeof (float)); /* allocate only output pixels which are actually required */ /* (defined by mc_backward islower jslower isupper jsupper) */ output->rfldir3d_r = calloc (output->atm.nzout, sizeof (float***)); output->rfldn3d_r = calloc (output->atm.nzout, sizeof (float***)); output->flup3d_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgso3d_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgdn3d_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgup3d_r = calloc (output->atm.nzout, sizeof (float***)); output->radiance3d_r = calloc (output->atm.nzout, sizeof (float*****)); if (input.rte.mc.spectral_is || input.rte.mc.concentration_is) if ((status = ASCII_calloc_float_5D (&output->fl3d_is_r, output->atm.nzout, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->wl.nlambda_r)) != 0) return status; /* So far we allow only 1D output for postprocessing */ if (input.rte.mc.jacobian[DIM_1D]) if ((status = ASCII_calloc_float_7D (&output->jacobian_r, output->atm.nzout, 1, 1, input.n_caoth + 2, 2, output->atm.nlev - 1, output->wl.nlambda_r)) != 0) return status; if (input.rte.mc.backward.absorption) output->absback3d_r = calloc (output->atm.nzout, sizeof (float***)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->rfldn3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->flup3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgso3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgdn3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->uavgup3d_var_r = calloc (output->atm.nzout, sizeof (float***)); output->radiance3d_var_r = calloc (output->atm.nzout, sizeof (float****)); if (input.rte.mc.backward.absorption) output->absback3d_var_r = calloc (output->atm.nzout, sizeof (float***)); } for (lu = 0; lu < output->atm.nzout; lu++) { output->rfldir3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->rfldn3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->flup3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgso3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgdn3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgup3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->radiance3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float****)); if (input.rte.mc.backward.absorption) output->absback3d_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->rfldn3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->flup3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgso3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgdn3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgup3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->radiance3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float***)); if (input.rte.mc.backward.absorption) output->absback3d_var_r[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); } for (is = output->islower; is <= output->isupper; is += output->isstep) { output->rfldir3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->rfldn3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->flup3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgso3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgdn3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgup3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->radiance3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float***)); if (input.rte.mc.backward.absorption) output->absback3d_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->rfldn3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->flup3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgso3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgdn3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgup3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->radiance3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float**)); if (input.rte.mc.backward.absorption) output->absback3d_var_r[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); } for (js = output->jslower; js <= output->jsupper; js += output->jsstep) { output->rfldir3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->rfldn3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->flup3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgso3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgdn3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgup3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->radiance3d_r[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float**)); for (ip = 0; ip < input.rte.mc.nstokes; ip++) { output->radiance3d_r[lu][is][js][ip] = calloc (output->mc.alis.Nc, sizeof (float*)); for (ic = 0; ic < output->mc.alis.Nc; ic++) output->radiance3d_r[lu][is][js][ip][ic] = calloc (output->wl.nlambda_r, sizeof (float)); } if (input.rte.mc.backward.absorption) output->absback3d_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->rfldir3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->rfldn3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->flup3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgso3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgdn3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->uavgup3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); output->radiance3d_var_r[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float*)); for (ip = 0; ip < input.rte.mc.nstokes; ip++) output->radiance3d_var_r[lu][is][js][ip] = calloc (output->wl.nlambda_r, sizeof (float)); if (input.rte.mc.backward.absorption) output->absback3d_var_r[lu][is][js] = calloc (output->wl.nlambda_r, sizeof (float)); } } } } /* 3d absorption */ if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) { /*ulrike: added || input.ipa3d*/ /* **CK added bracket */ output->abs3d_r = calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->wl.nlambda_r, output->atm.threed); CHKPOINTEROUT (output->abs3d_r, "Error allocating memory for output->abs3d_r"); if (input.rte.mc.std) { output->abs3d_var_r = calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->wl.nlambda_r, output->atm.threed); CHKPOINTEROUT (output->abs3d_var_r, "Error allocating memory for output->abs3d_var_r"); } } } /* need to allocate enough memory for both output->wl.nlambda_s */ /* and output->wl.nlambda_h, hence using whichever is larger */ nlambda = (output->wl.nlambda_h > output->wl.nlambda_s ? output->wl.nlambda_h : output->wl.nlambda_s); if ((status = ASCII_calloc_float (&output->flup, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->rfldn, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->rfldir, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavg, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgdn, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgso, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->uavgup, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->heat, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->emis, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->albmed, input.rte.numu, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->trnmed, input.rte.numu, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->w_zout, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float_3D (&output->down_flux, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) != 0) return status; if ((status = ASCII_calloc_float_3D (&output->down_flux_r, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float_3D (&output->up_flux, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) != 0) return status; if ((status = ASCII_calloc_float_3D (&output->up_flux_r, output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], output->wl.nlambda_r)) != 0) return status; if (input.rte.nphi > 0) { if ((status = ASCII_calloc_float_5D (&output->down_rad, output->atm.nzout, input.rte.nphi, input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) != 0) return status; if ((status = ASCII_calloc_float_5D (&output->down_rad_r, output->atm.nzout, input.rte.nphi, input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], output->wl.nlambda_r)) != 0) return status; if ((status = ASCII_calloc_float_5D (&output->up_rad, output->atm.nzout, input.rte.nphi, input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], nlambda)) != 0) return status; if ((status = ASCII_calloc_float_5D (&output->up_rad_r, output->atm.nzout, input.rte.nphi, input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], output->wl.nlambda_r)) != 0) return status; } if (input.rte.numu > 0) if ((status = ASCII_calloc_float_3D (&output->u0u, output->atm.nzout, input.rte.numu, nlambda)) != 0) return status; if (input.rte.numu > 0 && input.rte.nphi > 0) if ((status = ASCII_calloc_float_4D (&output->uu, output->atm.nzout, input.rte.nphi, input.rte.numu, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_nphot, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_nphot_q, output->atm.nzout, nlambda)) != 0) return status; if ((status = ASCII_calloc_float (&output->sslidar_ratio, output->atm.nzout, nlambda)) != 0) return status; if (output->mc.sample.passback3D) { /* allocate only output pixels which are actually required */ /* (defined by mc_backward islower jslower isupper jsupper) */ output->rfldir3d = calloc (output->atm.nzout, sizeof (float***)); output->rfldn3d = calloc (output->atm.nzout, sizeof (float***)); output->flup3d = calloc (output->atm.nzout, sizeof (float***)); output->uavgso3d = calloc (output->atm.nzout, sizeof (float***)); output->uavgdn3d = calloc (output->atm.nzout, sizeof (float***)); output->uavgup3d = calloc (output->atm.nzout, sizeof (float***)); output->radiance3d = calloc (output->atm.nzout, sizeof (float*****)); if (input.rte.mc.spectral_is || input.rte.mc.concentration_is) { if ((status = ASCII_calloc_float_5D (&output->fl3d_is, output->atm.nzout, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, nlambda)) != 0) return status; } if (input.rte.mc.jacobian[DIM_1D]) if ((status = ASCII_calloc_float_7D (&output->jacobian, output->atm.nzout, 1, 1, input.n_caoth + 2, 2, output->atm.nlev - 1, nlambda)) != 0) return status; if (input.rte.mc.backward.absorption) output->absback3d = calloc (output->atm.nzout, sizeof (float***)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var = calloc (output->atm.nzout, sizeof (float***)); output->rfldn3d_var = calloc (output->atm.nzout, sizeof (float***)); output->flup3d_var = calloc (output->atm.nzout, sizeof (float***)); output->uavgso3d_var = calloc (output->atm.nzout, sizeof (float***)); output->uavgdn3d_var = calloc (output->atm.nzout, sizeof (float***)); output->uavgup3d_var = calloc (output->atm.nzout, sizeof (float***)); output->radiance3d_var = calloc (output->atm.nzout, sizeof (float****)); if (input.rte.mc.backward.absorption) output->absback3d_var = calloc (output->atm.nzout, sizeof (float***)); } for (lu = 0; lu < output->atm.nzout; lu++) { output->rfldir3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->rfldn3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->flup3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgso3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgdn3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgup3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->radiance3d[lu] = calloc (output->mc.sample.Nx, sizeof (float****)); if (input.rte.mc.backward.absorption) output->absback3d[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->rfldn3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->flup3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgso3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgdn3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->uavgup3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); output->radiance3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float***)); if (input.rte.mc.backward.absorption) output->absback3d_var[lu] = calloc (output->mc.sample.Nx, sizeof (float**)); } for (is = output->islower; is <= output->isupper; is += output->isstep) { output->rfldir3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->rfldn3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->flup3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgso3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgdn3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgup3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->radiance3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float***)); if (input.rte.mc.backward.absorption) output->absback3d[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->rfldn3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->flup3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgso3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgdn3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->uavgup3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); output->radiance3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float**)); if (input.rte.mc.backward.absorption) output->absback3d_var[lu][is] = calloc (output->mc.sample.Ny, sizeof (float*)); } for (js = output->jslower; js <= output->jsupper; js += output->jsstep) { output->rfldir3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->rfldn3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->flup3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgso3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgdn3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgup3d[lu][is][js] = calloc (nlambda, sizeof (float)); output->radiance3d[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float**)); for (ip = 0; ip < input.rte.mc.nstokes; ip++) { output->radiance3d[lu][is][js][ip] = calloc (output->mc.alis.Nc, sizeof (float*)); for (ic = 0; ic < output->mc.alis.Nc; ic++) { output->radiance3d[lu][is][js][ip][ic] = calloc (nlambda, sizeof (float)); } } if (input.rte.mc.backward.absorption) output->absback3d[lu][is][js] = calloc (nlambda, sizeof (float)); /* variances */ if (input.rte.mc.std) { output->rfldir3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->rfldn3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->flup3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgso3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgdn3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->uavgup3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); output->radiance3d_var[lu][is][js] = calloc (input.rte.mc.nstokes, sizeof (float*)); for (ip = 0; ip < input.rte.mc.nstokes; ip++) output->radiance3d_var[lu][is][js][ip] = calloc (nlambda, sizeof (float)); if (input.rte.mc.backward.absorption) output->absback3d_var[lu][is][js] = calloc (nlambda, sizeof (float)); } } } } /* 3D absorption */ if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) { output->abs3d = calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, nlambda, output->atm.threed); CHKPOINTEROUT (output->abs3d, "Error allocating memory for output->abs3d"); if (input.rte.mc.std) { output->abs3d_var = calloc_spectral_abs3d (output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, nlambda, output->atm.threed); CHKPOINTEROUT (output->abs3d_var, "Error allocating memory for output->abs3d_var"); } } } output->sza_h = calloc (output->wl.nlambda_h, sizeof (float)); CHKPOINTER (output->sza_h); { // allocate triangle output output->triangle_results_r = NULL; output->triangle_results_t = NULL; output->triangle_results_o = NULL; const int ierr = init_spectral_triangular_surface_result_struct (output->wl.nlambda_r, output->mc.triangular_surface.N_triangles, &(output->triangle_results_r)); CHKERR (ierr); } return 0; } /*ulrike: end of setup_result*/ static int reverse_profiles (input_struct input, output_struct* output) { int lu = 0, iu = 0; double tmp = 0; for (lu = 0; lu < output->atm.nlyr / 2; lu++) { /* reverse profile of optical depth dtauc */ tmp = output->dtauc[output->atm.nlyr - lu - 1]; output->dtauc[output->atm.nlyr - lu - 1] = output->dtauc[lu]; output->dtauc[lu] = tmp; /* reverse profile of single scattering albedo ssalb */ tmp = output->ssalb[output->atm.nlyr - lu - 1]; output->ssalb[output->atm.nlyr - lu - 1] = output->ssalb[lu]; output->ssalb[lu] = tmp; /* reverse profile of phase function pmom */ for (iu = 0; iu <= input.rte.nstr; iu++) { tmp = output->pmom[output->atm.nlyr - lu - 1][0][iu]; output->pmom[output->atm.nlyr - lu - 1][0][iu] = output->pmom[lu][0][iu]; output->pmom[lu][0][iu] = tmp; } } return 0; } /* allocate memory for Raman scattering components needed for calculation of */ /* source function for second iteration */ raman_qsrc_components* calloc_raman_qsrc_components (int raman_fast, int nzout, int maxumu, int nphi, int nstr, int nlambda) { raman_qsrc_components* result = calloc (1, sizeof (raman_qsrc_components)); if (raman_fast) { ASCII_calloc_double (&result->uavgso, nzout, nlambda); ASCII_calloc_double (&result->uavgdn, nzout, nlambda); ASCII_calloc_double (&result->uavgup, nzout, nlambda); ASCII_calloc_double (&result->rfldir, nzout, nlambda); ASCII_calloc_double (&result->rfldn, nzout, nlambda); ASCII_calloc_double (&result->flup, nzout, nlambda); ASCII_calloc_double_3D (&result->u0u, nzout, maxumu, nlambda); ASCII_calloc_double_4D (&result->uu, nzout, maxumu, maxumu, nlambda); } result->fbeam = (double*)calloc (nlambda, sizeof (double)); ASCII_calloc_double (&result->dtauc, nzout, nlambda); ASCII_calloc_double_4D (&result->uum, nzout, maxumu, maxumu, nlambda); return result; } /* free memory for Raman scattering components needed for calculation of */ /* source function for second iteration */ static void free_raman_qsrc_components (raman_qsrc_components* result, int raman_fast, int nzout, int maxumu, int nphi, int nstr) { if (raman_fast) { if (result->uavgso != NULL) ASCII_free_double (result->uavgso, nzout); if (result->uavgup != NULL) ASCII_free_double (result->uavgup, nzout); if (result->uavgdn != NULL) ASCII_free_double (result->uavgdn, nzout); if (result->rfldir != NULL) ASCII_free_double (result->rfldir, nzout); if (result->rfldn != NULL) ASCII_free_double (result->rfldn, nzout); if (result->flup != NULL) ASCII_free_double (result->flup, nzout); if (result->u0u != NULL) ASCII_free_double_3D (result->u0u, nzout, maxumu); if (result->uu != NULL) ASCII_free_double_4D (result->uu, nzout, maxumu, maxumu); } if (result->fbeam != NULL) free (result->fbeam); if (result->dtauc != NULL) ASCII_free_double (result->dtauc, nzout); if (result->uum != NULL) ASCII_free_double_4D (result->uum, nzout, maxumu, maxumu); free (result); } /* allocate temporary memory optical properties */ static save_optprop* calloc_save_optprop (int Nlev) { save_optprop* result = calloc (1, sizeof (save_optprop)); result->tauw = (float*)calloc (Nlev, sizeof (float)); result->taui = (float*)calloc (Nlev, sizeof (float)); result->g1d = (float*)calloc (Nlev, sizeof (float)); result->g2d = (float*)calloc (Nlev, sizeof (float)); result->fd = (float*)calloc (Nlev, sizeof (float)); result->g1i = (float*)calloc (Nlev, sizeof (float)); result->g2i = (float*)calloc (Nlev, sizeof (float)); result->fi = (float*)calloc (Nlev, sizeof (float)); result->ssaw = (float*)calloc (Nlev, sizeof (float)); result->ssai = (float*)calloc (Nlev, sizeof (float)); return result; } /* allocate temporary memory for the RTE solvers */ static rte_output* calloc_rte_output (input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Nxsample, int Nysample, int Ncsample, int Nlambda, int Nlyr, int* threed, int passback3D, const size_t N_triangles) { int status = 0; rte_output* result = calloc (1, sizeof (rte_output)); result->albmed = calloc (input.rte.maxumu, sizeof (float)); result->trnmed = calloc (input.rte.maxumu, sizeof (float)); result->dfdt = calloc (nzout, sizeof (float)); result->flup = calloc (nzout, sizeof (float)); result->rfldir = calloc (nzout, sizeof (float)); result->rfldn = calloc (nzout, sizeof (float)); result->uavg = calloc (nzout, sizeof (float)); result->uavgdn = calloc (nzout, sizeof (float)); result->uavgso = calloc (nzout, sizeof (float)); result->uavgup = calloc (nzout, sizeof (float)); result->heat = calloc (nzout, sizeof (float)); result->emis = calloc (nzout, sizeof (float)); result->w_zout = calloc (nzout, sizeof (float)); result->sslidar_nphot = calloc (nzout, sizeof (float)); result->sslidar_nphot_q = calloc (nzout, sizeof (float)); result->sslidar_ratio = calloc (nzout, sizeof (float)); if (input.rte.maxumu > 0) if ((status = ASCII_calloc_float (&(result->u0u), nzout, input.rte.maxumu)) != 0) return NULL; if (input.rte.maxphi > 0 && input.rte.maxumu > 0) if ((status = ASCII_calloc_float_3D (&(result->uu), input.rte.maxphi, nzout, input.rte.maxumu)) != 0) return NULL; if (input.rte.solver == SOLVER_DISORT && input.raman) if ((status = ASCII_calloc_float_3D (&(result->uum), input.rte.nstr, nzout, input.rte.maxumu)) != 0) return NULL; /* PolRadtran-specific */ if (input.rte.solver == SOLVER_POLRADTRAN) { result->polradtran_mu_values = (double*)calloc (input.rte.nstr / 2 + input.rte.numu, sizeof (double)); if ((status = ASCII_calloc_double (&(result->polradtran_up_flux), nzout, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; if ((status = ASCII_calloc_double (&(result->polradtran_down_flux), nzout, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; if ((status = ASCII_calloc_double_4D (&(result->polradtran_up_rad), nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; if ((status = ASCII_calloc_double_4D (&(result->polradtran_down_rad), nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; if ((status = ASCII_calloc_double_4D (&(result->polradtran_up_rad_q), nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; if ((status = ASCII_calloc_double_4D (&(result->polradtran_down_rad_q), nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES])) != 0) return NULL; } /* 3d fields */ if (passback3D) { status += ASCII_calloc_float_3D (&(result->rfldir3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->rfldn3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->flup3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgso3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgdn3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgup3d), nzout, Nxsample, Nysample); status += ASCII_calloc_float_4D (&(result->radiance3d), nzout, Nxsample, Nysample, input.rte.mc.nstokes); status += ASCII_calloc_float_6D (&(result->radiance3d_is), nzout, Ncsample, Nxsample, Nysample, input.rte.mc.nstokes, Nlambda); if (input.rte.mc.spectral_is || input.rte.mc.concentration_is) status += ASCII_calloc_float_5D (&(result->fl3d_is), nzout, Ncsample, Nxsample, Nysample, Nlambda); if (input.rte.mc.jacobian[DIM_1D]) { /* fprintf(stderr, "calloc jacobian nzout %d Nxsample %d Nysample %d input.n_caoth %d abs/sca %d Nzcld %d \n", nzout, Nxsample, Nysample, input.n_caoth, 2, Nlyr); */ status += ASCII_calloc_float_6D (&(result->jacobian), nzout, 1, 1, input.n_caoth + 2, 2, Nlyr); } if (input.rte.mc.backward.absorption) status += ASCII_calloc_float_3D (&(result->absback3d), nzout, Nxsample, Nysample); if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/ if ((result->abs3d = calloc_abs3d (Nxcld, Nycld, Nzcld, threed)) == NULL) return NULL; /* variances */ if (input.rte.mc.std) { status += ASCII_calloc_float_3D (&(result->rfldir3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->rfldn3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->flup3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgso3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgdn3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_3D (&(result->uavgup3d_var), nzout, Nxsample, Nysample); status += ASCII_calloc_float_4D (&(result->radiance3d_var), nzout, Nxsample, Nysample, input.rte.mc.nstokes); if (input.rte.mc.backward.absorption) status += ASCII_calloc_float_3D (&(result->absback3d_var), nzout, Nxsample, Nysample); if (input.rte.mc.absorption != MCFORWARD_ABS_NONE) if ((result->abs3d_var = calloc_abs3d (Nxcld, Nycld, Nzcld, threed)) == NULL) return NULL; } } result->triangle_results = NULL; status += init_triangular_surface_result_struct (N_triangles, &(result->triangle_results)); if (status != 0) { fprintf (stderr, "Error allocating memory for 3D fields\n"); return NULL; } return result; } /* reset rte_output structure */ static int reset_rte_output (rte_output** rte, input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Nxsample, int Nysample, int Ncsample, int Nlambda, int Nlyr, int* threed, int passback3D, const size_t N_triangles) { const int ierr = free_rte_output (*rte, input, nzout, Nxcld, Nycld, Nzcld, Nxsample, Nysample, Ncsample, Nlyr, Nlambda, threed, passback3D); CHKERR (ierr); *rte = calloc_rte_output (input, nzout, Nxcld, Nycld, Nzcld, Nxsample, Nysample, Ncsample, Nlambda, Nlyr, threed, passback3D, N_triangles); return 0; /* if o.k. */ } static int add_rte_output (rte_output* rte, const rte_output* add, const double factor, const double* factor_spectral, const input_struct input, const int nzout, const int Nxcld, const int Nycld, const int Nzcld, const int Nc, const int Nlyr, const int Nlambda, const int* threed, const int passback3D, const int islower, const int isupper, const int jslower, const int jsupper, const int isstep, const int jsstep) { const double factor2 = factor * factor; for (int lu = 0; lu < nzout; lu++) { rte->rfldir[lu] += factor * add->rfldir[lu]; rte->rfldn[lu] += factor * add->rfldn[lu]; rte->flup[lu] += factor * add->flup[lu]; rte->uavg[lu] += factor * add->uavg[lu]; rte->uavgdn[lu] += factor * add->uavgdn[lu]; rte->uavgso[lu] += factor * add->uavgso[lu]; rte->uavgup[lu] += factor * add->uavgup[lu]; rte->dfdt[lu] += factor * add->dfdt[lu]; rte->heat[lu] += factor * add->heat[lu]; rte->emis[lu] += factor * add->emis[lu]; rte->w_zout[lu] += factor * add->w_zout[lu]; rte->sslidar_nphot[lu] += factor * add->sslidar_nphot[lu]; rte->sslidar_nphot_q[lu] += factor * add->sslidar_nphot_q[lu]; rte->sslidar_ratio[lu] += factor * add->sslidar_ratio[lu]; for (int iu = 0; iu < input.rte.numu; iu++) { rte->u0u[lu][iu] += factor * add->u0u[lu][iu]; for (int j = 0; j < input.rte.nphi; j++) rte->uu[j][lu][iu] += factor * add->uu[j][lu][iu]; } } for (int iu = 0; iu < input.rte.numu; iu++) { rte->albmed[iu] += factor * add->albmed[iu]; rte->trnmed[iu] += factor * add->trnmed[iu]; } /* PolRadtran-specific */ if (input.rte.solver == SOLVER_POLRADTRAN) { for (int lu = 0; lu < nzout; lu++) { for (int is = 0; is < input.rte.polradtran[POLRADTRAN_NSTOKES]; is++) { rte->polradtran_up_flux[lu][is] += factor * add->polradtran_up_flux[lu][is]; rte->polradtran_down_flux[lu][is] += factor * add->polradtran_down_flux[lu][is]; for (int j = 0; j < input.rte.nphi; j++) { for (int iu = 0; iu < input.rte.nstr / 2 + input.rte.numu; iu++) { rte->polradtran_up_rad[lu][j][iu][is] += factor * add->polradtran_up_rad[lu][j][iu][is]; rte->polradtran_down_rad[lu][j][iu][is] += factor * add->polradtran_down_rad[lu][j][iu][is]; } } } } } if (passback3D) { for (int ks = 0; ks < nzout; ks++) { for (int is = islower; is <= isupper; is += isstep) { for (int js = jslower; js <= jsupper; js += jsstep) { rte->rfldir3d[ks][is][js] += factor * add->rfldir3d[ks][is][js]; rte->rfldn3d[ks][is][js] += factor * add->rfldn3d[ks][is][js]; rte->flup3d[ks][is][js] += factor * add->flup3d[ks][is][js]; rte->uavgso3d[ks][is][js] += factor * add->uavgso3d[ks][is][js]; rte->uavgdn3d[ks][is][js] += factor * add->uavgdn3d[ks][is][js]; rte->uavgup3d[ks][is][js] += factor * add->uavgup3d[ks][is][js]; if (input.rte.mc.concentration_is) for (int ic = 0; ic < Nc; ic++) rte->fl3d_is[ks][ic][is][js][0] += factor * add->fl3d_is[ks][ic][is][js][0]; else if (input.rte.mc.spectral_is) for (int iv_alis = 0; iv_alis < Nlambda; iv_alis++) { rte->fl3d_is[ks][0][is][js][iv_alis] += factor_spectral[iv_alis] * add->fl3d_is[ks][0][is][js][iv_alis]; } for (int ip = 0; ip < input.rte.mc.nstokes; ip++) { rte->radiance3d[ks][is][js][ip] += factor * add->radiance3d[ks][is][js][ip]; /* FIXCE spectral and concentration importance sampling together not */ /* yet working correctly */ if (input.rte.mc.concentration_is) for (int ic = 0; ic < Nc; ic++) { rte->radiance3d_is[ks][ic][is][js][ip][0] += factor * add->radiance3d_is[ks][ic][is][js][ip][0]; } if (input.rte.mc.spectral_is) { for (int ic = 0; ic < Nc; ic++) { for (int iv_alis = 0; iv_alis < Nlambda; iv_alis++) { rte->radiance3d_is[ks][ic][is][js][ip][iv_alis] += factor_spectral[iv_alis] * add->radiance3d_is[ks][ic][is][js][ip][iv_alis]; } } } } if (input.rte.mc.backward.absorption) rte->absback3d[ks][is][js] += factor * add->absback3d[ks][is][js]; /* variances */ if (input.rte.mc.std) { rte->rfldir3d_var[ks][is][js] += factor2 * add->rfldir3d_var[ks][is][js]; rte->rfldn3d_var[ks][is][js] += factor2 * add->rfldn3d_var[ks][is][js]; rte->flup3d_var[ks][is][js] += factor2 * add->flup3d_var[ks][is][js]; rte->uavgso3d_var[ks][is][js] += factor2 * add->uavgso3d_var[ks][is][js]; rte->uavgdn3d_var[ks][is][js] += factor2 * add->uavgdn3d_var[ks][is][js]; rte->uavgup3d_var[ks][is][js] += factor2 * add->uavgup3d_var[ks][is][js]; for (int ip = 0; ip < input.rte.mc.nstokes; ip++) rte->radiance3d_var[ks][is][js][ip] += factor2 * add->radiance3d_var[ks][is][js][ip]; if (input.rte.mc.backward.absorption) rte->absback3d_var[ks][is][js] += factor2 * add->absback3d_var[ks][is][js]; } } } } if (input.rte.mc.absorption != MCFORWARD_ABS_NONE) for (int ks = 0; ks < Nzcld; ks++) if (threed[ks]) /* only for 3D layers, BM07122005 */ for (int is = 0; is < Nxcld; is++) for (int js = 0; js < Nycld; js++) { /* **CK added bracket */ rte->abs3d[ks][is][js] += factor * add->abs3d[ks][is][js]; if (input.rte.mc.std) /* **CK added for forward mc_std */ rte->abs3d_var[ks][is][js] += factor2 * add->abs3d_var[ks][is][js]; } } if (rte->triangle_results) { const int ierr = add_triangular_surface_result (factor, add->triangle_results, rte->triangle_results); CHKERR (ierr); } return 0; /* if o.k. */ } /* free temporary memory for the RTE solvers */ static int free_rte_output (rte_output* result, input_struct input, int nzout, int Nxcld, int Nycld, int Nzcld, int Nxsample, int Nysample, int Ncsample, int Nlyr, int Nlambda, int* threed, int passback3D) { CHKPOINTEROUT (result, "rte_output cannot be freed, it is not allocated!"); free (result->albmed); result->albmed = NULL; free (result->trnmed); result->trnmed = NULL; free (result->dfdt); result->dfdt = NULL; free (result->flup); result->flup = NULL; free (result->rfldir); result->rfldir = NULL; free (result->rfldn); result->rfldn = NULL; free (result->uavg); result->uavg = NULL; free (result->uavgdn); result->uavgdn = NULL; free (result->uavgso); result->uavgso = NULL; free (result->uavgup); result->uavgup = NULL; free (result->heat); result->heat = NULL; free (result->emis); result->emis = NULL; free (result->w_zout); result->w_zout = NULL; free (result->sslidar_nphot); result->sslidar_nphot = NULL; free (result->sslidar_nphot_q); result->sslidar_nphot_q = NULL; free (result->sslidar_ratio); result->sslidar_ratio = NULL; if (result->u0u != NULL) { ASCII_free_float (result->u0u, nzout); result->u0u = NULL; } if (result->uu != NULL) { ASCII_free_float_3D (result->uu, input.rte.nphi, nzout); result->uu = NULL; } if (result->uum != NULL) { ASCII_free_float_3D (result->uum, input.rte.nstr, nzout); result->uum = NULL; } if (input.rte.solver == SOLVER_POLRADTRAN) { free (result->polradtran_mu_values); result->polradtran_mu_values = NULL; if (result->polradtran_up_flux != NULL) { ASCII_free_double (result->polradtran_up_flux, nzout); result->polradtran_up_flux = NULL; } if (result->polradtran_down_flux != NULL) { ASCII_free_double (result->polradtran_down_flux, nzout); result->polradtran_down_flux = NULL; } if (result->polradtran_up_rad != NULL) { ASCII_free_double_4D (result->polradtran_up_rad, nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu); result->polradtran_up_rad = NULL; } if (result->polradtran_down_rad != NULL) { ASCII_free_double_4D (result->polradtran_down_rad, nzout, input.rte.nphi, input.rte.nstr / 2 + input.rte.numu); result->polradtran_down_rad = NULL; } if (result->polradtran_up_rad_q != NULL) { ASCII_free_double_4D (result->polradtran_up_rad_q, nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu); result->polradtran_up_rad_q = NULL; } if (result->polradtran_down_rad_q != NULL) { ASCII_free_double_4D (result->polradtran_down_rad_q, nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu); result->polradtran_down_rad_q = NULL; } } /* free 3d fields */ if (passback3D) { if (result->rfldir3d != NULL) { ASCII_free_float_3D (result->rfldir3d, nzout, Nxsample); result->rfldir3d = NULL; } if (result->rfldn3d != NULL) { ASCII_free_float_3D (result->rfldn3d, nzout, Nxsample); result->rfldn3d = NULL; } if (result->flup3d != NULL) { ASCII_free_float_3D (result->flup3d, nzout, Nxsample); result->flup3d = NULL; } if (result->uavgso3d != NULL) { ASCII_free_float_3D (result->uavgso3d, nzout, Nxsample); result->uavgso3d = NULL; } if (result->uavgdn3d != NULL) { ASCII_free_float_3D (result->uavgdn3d, nzout, Nxsample); result->uavgdn3d = NULL; } if (result->uavgup3d != NULL) { ASCII_free_float_3D (result->uavgup3d, nzout, Nxsample); result->uavgup3d = NULL; } if (result->radiance3d != NULL) { ASCII_free_float_4D (result->radiance3d, nzout, Nxsample, Nysample); result->radiance3d = NULL; } if (input.rte.mc.spectral_is || input.rte.mc.concentration_is) if (result->fl3d_is != NULL) { ASCII_free_float_5D (result->fl3d_is, nzout, Ncsample, Nxsample, Nysample); result->fl3d_is = NULL; } if (result->radiance3d_is != NULL) { ASCII_free_float_6D (result->radiance3d_is, nzout, Ncsample, Nxsample, Nysample, input.rte.mc.nstokes); result->radiance3d_is = NULL; } if (input.rte.mc.jacobian[DIM_1D]) if (result->jacobian != NULL) { ASCII_free_float_6D (result->jacobian, nzout, Nxsample, Nysample, input.n_caoth + 2, 2); result->jacobian = NULL; } if (input.rte.mc.backward.absorption) if (result->absback3d != NULL) { ASCII_free_float_3D (result->absback3d, nzout, Nxsample); result->absback3d = NULL; } if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/ if (result->abs3d != NULL) { free_abs3d (result->abs3d, Nxcld, Nycld, Nzcld, threed); result->abs3d = NULL; } /* variances */ if (input.rte.mc.std) { if (result->rfldir3d_var != NULL) { ASCII_free_float_3D (result->rfldir3d_var, nzout, Nxsample); result->rfldir3d_var = NULL; } if (result->rfldn3d != NULL) { ASCII_free_float_3D (result->rfldn3d_var, nzout, Nxsample); result->rfldn3d = NULL; } if (result->flup3d != NULL) { ASCII_free_float_3D (result->flup3d_var, nzout, Nxsample); result->flup3d = NULL; } if (result->uavgso3d != NULL) { ASCII_free_float_3D (result->uavgso3d_var, nzout, Nxsample); result->uavgso3d = NULL; } if (result->uavgdn3d != NULL) { ASCII_free_float_3D (result->uavgdn3d_var, nzout, Nxsample); result->uavgdn3d = NULL; } if (result->uavgup3d != NULL) { ASCII_free_float_3D (result->uavgup3d_var, nzout, Nxsample); result->uavgup3d = NULL; } if (result->radiance3d != NULL) { ASCII_free_float_4D (result->radiance3d_var, nzout, Nxsample, Nysample); result->radiance3d = NULL; } if (input.rte.mc.backward.absorption) if (result->absback3d != NULL) { ASCII_free_float_3D (result->absback3d_var, nzout, Nxsample); result->absback3d = NULL; } if (input.rte.mc.absorption != MCFORWARD_ABS_NONE || input.ipa3d) /*ulrike: added || input.ipa3d*/ if (result->abs3d != NULL) { free_abs3d (result->abs3d_var, Nxcld, Nycld, Nzcld, threed); result->abs3d = NULL; } } } const int ierr = free_triangular_surface_result_struct (result->triangle_results); CHKERR (ierr); free (result); return 0; } /******************************************************/ /* setup optical properties, do some initializations, */ /* and call the RTE solver. */ /******************************************************/ static int setup_and_call_solver (input_struct input, output_struct* output, rte_input* rte_in, rte_output* rte_out, raman_qsrc_components* raman_qsrc_components, int iv, int ib, int ir, int* threed, int mc_loaddata) { int status = 0, lu = 0, iv1 = 0, iv2 = 0, iv_alis = 0, il = 0, isp = 0; static int first = 1; static int verbose = 0; int rte_solver = NOT_DEFINED_INTEGER; int skip_optical_properties = FALSE; /* change rte solver to NULL solver for */ /* solar simulations with sza > 90 degrees done by plane paralell solvers */ rte_solver = input.rte.solver; switch (input.source) { case SRC_THERMAL: /* do not change solver */ break; case SRC_SOLAR: case SRC_BLITZ: /* BCA */ case SRC_LIDAR: /* BCA */ if (output->atm.sza_r[iv] >= 90.0) { switch (input.rte.solver) { /* plane parallel solvers */ case SOLVER_FDISORT1: case SOLVER_FDISORT2: case SOLVER_RODENTS: case SOLVER_TWOSTREBE: case SOLVER_TWOMAXRND: case SOLVER_TWOMAXRND3C: case SOLVER_DYNAMIC_TWOSTREAM: case SOLVER_DYNAMIC_TENSTREAM: case SOLVER_POLRADTRAN: case SOLVER_SSS: case SOLVER_SSSI: case SOLVER_DISORT: // aky 24022011, cdisort may produce results for sza>90 if intensity correction // are turned off. But results are a bit dubious if compared with mystic. /* change solver to SOLVER_NULL, as output is 0 anyway */ /* It is only 0 if pseudospherical is off aky 05022014 */ if (!input.rte.pseudospherical) { rte_solver = SOLVER_NULL; skip_optical_properties = TRUE; if (input.verbose) fprintf (stderr, " ... solar calculation with SZA>90 and pp solver, switch solver to NULL-solver \n"); } break; /* spherical solvers */ case SOLVER_SDISORT: case SOLVER_SPSDISORT: case SOLVER_FTWOSTR: case SOLVER_TWOSTR: case SOLVER_SOS: /* do not change solver as these solvers should be */ /* able to do solar calculations for sza > 90 degree */ break; /* special solvers */ case SOLVER_MONTECARLO: /* user must know it */ case SOLVER_TZS: /* only thermal anyway */ case SOLVER_SSLIDAR: /* do nothing */ break; case SOLVER_NULL: break; default: fprintf (stderr, "Error, unknown RTE solver %d\n", input.rte.solver); break; } } break; default: fprintf (stderr, "Error, unknown source %d\n", input.source); return -1; } if (input.raman) { /* Optical properties are calculated just before calling qdisort in solve_rte.c */ skip_optical_properties = TRUE; /* For raman_fast optical properties are calculated as usual */ if (input.raman_fast && ir == 0) skip_optical_properties = FALSE; } verbose = input.verbose; if (input.verbose && input.ck_scheme == CK_LOWTRAN) verbose = 0; /* no verbose output for the following call of optical properties */ /* calculate optical properties from model input */ if (input.raman_fast) { iv1 = ib; iv2 = ib; } else { iv1 = iv; iv2 = iv; } if (input.rte.mc.spectral_is) { if (ib == 0) { /* fprintf(stderr, "alloc ALIS struct iv %d\n", iv); */ output->mc.alis.dt = calloc (output->mc.alis.nlambda_abs, sizeof (double**)); output->mc.alis.om = calloc (output->mc.alis.nlambda_abs, sizeof (double**)); for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { output->mc.alis.dt[iv_alis] = calloc (input.n_caoth + 2, sizeof (double*)); output->mc.alis.om[iv_alis] = calloc (input.n_caoth + 2, sizeof (double*)); } for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { for (isp = 0; isp < input.n_caoth + 2; isp++) { output->mc.alis.dt[iv_alis][isp] = calloc (output->atm.nlev_common - 1, sizeof (double)); output->mc.alis.om[iv_alis][isp] = calloc (output->atm.nlev_common - 1, sizeof (double)); } } } for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { status = optical_properties (input, output, 0.0, ir, iv_alis, iv_alis, ib, verbose, skip_optical_properties); } /* spatially constant spectral Lambertian albedo */ output->mc.alis.albedo = calloc (output->mc.alis.nlambda_abs, sizeof (double)); for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) output->mc.alis.albedo[iv_alis] = output->alb.albedo_r[iv_alis]; /* 2D spectral Lambertian albedo */ if (output->surfaces.n > 0 && output->surfaces.albedo_r != NULL) { output->mc.alis.alb_type = calloc (output->surfaces.n, sizeof (double*)); for (il = 0; il < output->surfaces.n; il++) { output->mc.alis.alb_type[il] = calloc (output->mc.alis.nlambda_abs, sizeof (double)); for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) output->mc.alis.alb_type[il][iv_alis] = output->surfaces.albedo_r[il][iv_alis]; } } if (output->mc.alis.dt[iv][0][output->atm.nlev_common - 2] * (1.0 - output->mc.alis.om[iv][0][output->atm.nlev_common - 2]) > 0.5) { fprintf (stderr, " ... Warning: Absorption is very high at the calculation wavelength for\n"); fprintf (stderr, " ... spectral importance sampling. In order to improve the result \n"); fprintf (stderr, " ... please select another calculation wavelength using the option\n"); fprintf (stderr, " ... *mc_spectral_is_wvl*. \n"); fprintf (stderr, " ... (Absorption optical depth in lowest layer is %g) \n", output->mc.alis.dt[iv][0][output->atm.nlev_common - 2] * (1.0 - output->mc.alis.om[iv][0][output->atm.nlev_common - 2])); } } //TODO: else statement? call optical properties twice -> double allocating etc status = optical_properties (input, output, 0.0, ir, iv1, iv2, ib, verbose, skip_optical_properties); /* in ancillary.c */ if (status != 0) { fprintf (stderr, "Error %d returned by optical_properties (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } /* 3DAbs may be here ??? */ /* else{ */ /* status = optical_properties_atmosphere3D(input, output, iv, ib, verbose); */ /* if (status!=0) { */ /* fprintf (stderr, "Error %d returned by optical_properties_atmosphere3D (line %d, function %s in %s)\n", */ /* status, __LINE__, __func__, __FILE__); */ /* return status; */ /* } */ /* } */ if (input.ck_scheme == CK_LOWTRAN) { /* this is a little inefficient as we need first the scattering optical */ /* properties to calculate the absorption coefficients and then */ /* recalculate the optical properties; the reason is that SBDART */ /* requires the total scattering cross section as input, and this */ /* quantity is only available after the call to optical_properties */ /* ??? where to get the mixing ratio of N2 from ??? */ /* ??? setting this value to -1 ??? */ status = sbdart_profile (output->atm.microphys.temper, output->atm.microphys.press, output->atm.zd, output->atm.microphys.dens[MOL_H2O], output->atm.microphys.dens[MOL_O3], -1.0, output->mixing_ratio[MX_O2], output->mixing_ratio[MX_CO2], output->mixing_ratio[MX_CH4], output->mixing_ratio[MX_N2O], output->mixing_ratio[MX_NO2], input.ck_abs[CK_ABS_O4], input.ck_abs[CK_ABS_N2], input.ck_abs[CK_ABS_CO], input.ck_abs[CK_ABS_SO2], input.ck_abs[CK_ABS_NH3], input.ck_abs[CK_ABS_NO], input.ck_abs[CK_ABS_HNO3], output->dtauc, output->ssalb, output->atm.nlev, output->atm.sza_r[iv], output->wl.lambda_r[iv], iv, output->crs_ck.profile[0], input.rte.mc.spectral_is); if (status != 0) { fprintf (stderr, "Error %d returned by sbdart_profile (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } /* allocate memory for absorption coefficient profile */ if (first) { status = ASCII_calloc_float (&output->kabs.kabs, output->atm.nlev, output->wl.nlambda_r); if (status != 0) { fprintf (stderr, "Error %d allocating memory for output->kabs.kabs\n", status); return status; } first = 0; } /* set absorption coefficient */ for (lu = 0; lu < output->atm.nlyr; lu++) output->kabs.kabs[lu][iv] = output->crs_ck.profile[0][iv].crs[0][0][lu][ib]; if (input.rte.mc.spectral_is) { for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) { status = optical_properties (input, output, 0.0, ir, iv_alis, iv_alis, ib, verbose, skip_optical_properties); } } /* calculate optical properties from model input */ status = optical_properties (input, output, 0.0, ir, iv, iv, ib, input.verbose, skip_optical_properties); /* in ancillaries.c */ if (status != 0) { fprintf (stderr, "Error %d returned by optical_properties (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } } /* translate output altitudes (zout) to optical depths (utau) */ switch (input.rte.solver) { case SOLVER_FDISORT1: case SOLVER_SDISORT: case SOLVER_FTWOSTR: case SOLVER_SOS: case SOLVER_POLRADTRAN: case SOLVER_FDISORT2: case SOLVER_SPSDISORT: case SOLVER_TZS: case SOLVER_SSS: case SOLVER_SSSI: /* "very old" version, recycled */ F77_FUNC (setout, SETOUT) (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur); break; case SOLVER_TWOSTR: case SOLVER_TWOSTREBE: case SOLVER_TWOMAXRND: case SOLVER_TWOMAXRND3C: case SOLVER_DYNAMIC_TWOSTREAM: case SOLVER_DYNAMIC_TENSTREAM: case SOLVER_RODENTS: case SOLVER_DISORT: /* "old" version */ /* status = set_out (output->atm.zd, output->dtauc, output->atm.nlyr, input.atm.zout, output->atm.nzout, rte_in->utau); if (status!=0) { fprintf (stderr, "Error %d returned by set_out()\n", status); return status; } */ status = c_setout (output->dtauc, output->atm.nlyr, output->atm.nzout, rte_in->utau, output->atm.zd, output->atm.zout_sur); if (status) { fprintf (stderr, "Error returned by c_setout\n"); return -1; } break; case SOLVER_MONTECARLO: case SOLVER_SSLIDAR: case SOLVER_NULL: break; default: fprintf (stderr, "Error, unknown rte_solver %d (line %d, function '%s' in '%s')\n", input.rte.solver, __LINE__, __func__, __FILE__); return -1; } /* reverse profiles, if required */ if (input.rte.reverse) { status = reverse_profiles (input, output); if (status != 0) { fprintf (stderr, "Error %d reversing profiles\n", status); return status; } } /**** Switch to SOLVER_NULL to run optical_properties tests without solving RTE, Bettina Richter ****/ if (input.test_optical_properties) { fprintf (stderr, " ... switch rte_solver to null_solver\n"); input.rte.solver = SOLVER_NULL; rte_solver = SOLVER_NULL; } /* call RTE solver */ status = call_solver (input, output, rte_solver, rte_in, raman_qsrc_components, iv, ib, ir, rte_out, threed, mc_loaddata, input.verbose); if (status != 0) { fprintf (stderr, "Error %d calling solver\n", status); return status; } return 0; /* if o.k. */ } static int call_solver (input_struct input, output_struct* output, int rte_solver, rte_input* rte_in, raman_qsrc_components* raman_qsrc_comp, int iv, int ib, int ir, rte_output* rte_out, int* threed, int mc_loaddata, int verbose) { int status = 0; int lev = 0, ivi = 0, imu = 0, iv_alis = 0; double start = 0, end = 0, last = 0; int lu = 0, is = 0; raman_qsrc_components* tmp_raman_qsrc_comp = NULL; double * tmp_in_int = NULL, *tmp_out_int = NULL, *tmp_wl = NULL; #if HAVE_SOS int k = 0; #endif double*** tmp_crs = NULL; /* CE: commented since I have introduced the option earth_radius, default value is 6370.0 */ /* float radius= 6370.0; */ /* Earth's radius in km */ /* c_disort and c_twostr double declarations as they expect all input in double */ /* and f77 disort and twostr is all float. AK 23.09.2010 */ disort_state ds_in, twostr_ds; disort_output ds_out, twostr_out; double* c_twostr_gg = NULL; double* c_zd = NULL; double c_r_earth = (double)input.r_earth; int lc = 0, j = 0, maz = 0, iq = 0; float* twostr_gg = NULL; float* twostr_gg_clr = NULL; float* twostr_gg_cldk = NULL; float* twostr_gg_cldn = NULL; float* twostr_cf = NULL; float* twostr_ff = NULL; float* sdisort_beta = NULL; float* sdisort_sig = NULL; float** sdisort_denstab = NULL; float* tosdisort_denstab = NULL; float * disort_pmom = NULL, *disort2_pmom = NULL, *sss_pmom = NULL, *disort2_phaso = NULL; int disort2_ntheta_default = 0; int* disort2_ntheta = &disort2_ntheta_default; double* disort2_mup = NULL; int intensity_correction = TRUE; int old_intensity_correction = FALSE; int rodents_delta_method = 0; float qwanted_wvl[1]; float qfbeam[1]; float qalbedo[1]; int iv1 = 0, iv2 = 0; int skip_optical_properties = FALSE; int planck_tempoff = 0; char function_name[] = "call_solver"; char file_name[] = "solve_rte.c"; double** phase_back = NULL; #if HAVE_SOS float** pmom_sos = NULL; #endif #if HAVE_POLRADTRAN int iu = 0; double* polradtran_down_flux = NULL; double* polradtran_up_flux = NULL; double* polradtran_down_rad = NULL; double* polradtran_up_rad = NULL; #endif /* temporary Fortran arrays */ float *disort_u0u = NULL, *disort_uu = NULL; /* float *tzs_u0u = NULL, *tzs_uu = NULL; */ float *sss_u0u = NULL, *sss_uu = NULL; #if HAVE_MYSTIC int il = 0; int source = 0; int thermal_photons = 0; double* weight_spectral = NULL; /* temporary MC output (for thermal MC calculations, two calls */ /* to mystic() are required, one for the surface and one for the */ /* atmospheric contribution */ rte_output* tmp_out = NULL; /* rpv arrays */ float* alb_type = NULL; float* rpv_rho0 = NULL; float* rpv_k = NULL; float* rpv_theta = NULL; float* rpv_scale = NULL; float* rpv_sigma = NULL; float* rpv_t1 = NULL; float* rpv_t2 = NULL; float* rossli_iso = NULL; float* rossli_vol = NULL; float* rossli_geo = NULL; float* hapke_h = NULL; float* hapke_b0 = NULL; float* hapke_w = NULL; int write_files = 0; /* write MYSTIC monochromatic output only if monochromatic, non-ck uvspec calculation */ write_files = (output->wl.nlambda_r * output->atm.nq_r[output->wl.nlambda_rte_lower] > 1 ? 0 : 1); /* RPB very dirty trick, please dont kill me for this!!! */ if (output->mc.sample.LidarLocEst) write_files = 1; /* write files for spectral/concentration importance sampling, but only if not spectrally post-processed */ if ((input.rte.mc.spectral_is || input.rte.mc.concentration_is) && input.processing == PROCESS_NONE) write_files = 1; #endif if (input.rte.mc.backward.writeback == 1) write_files = 1; if (verbose) start = clock(); switch (rte_solver) { /* this is the ONLY use of rte_solver, everywhere else still input.rte.solver is used */ case SOLVER_MONTECARLO: #if HAVE_MYSTIC if (ib == 0) if (input.verbose) fprintf (stderr, " ... start Monte Carlo simulation for lambda = %10.2f nm \n", output->wl.lambda_r[iv]); /* create rpv arrays */ /* BCA: this is not nice, especially case surf.n=0 and il=0, affects mystic.c and albedo.c */ if (output->surfaces.n > 0 && output->surfaces.rpv != NULL) { rpv_rho0 = calloc (output->surfaces.n, sizeof (float)); rpv_k = calloc (output->surfaces.n, sizeof (float)); rpv_theta = calloc (output->surfaces.n, sizeof (float)); rpv_scale = calloc (output->surfaces.n, sizeof (float)); rpv_sigma = calloc (output->surfaces.n, sizeof (float)); rpv_t1 = calloc (output->surfaces.n, sizeof (float)); rpv_t2 = calloc (output->surfaces.n, sizeof (float)); for (il = 0; il < output->surfaces.n; il++) { rpv_rho0[il] = output->surfaces.rpv[il].rho0_r[iv]; rpv_k[il] = output->surfaces.rpv[il].k_r[iv]; rpv_theta[il] = output->surfaces.rpv[il].theta_r[iv]; rpv_scale[il] = output->surfaces.rpv[il].scale_r[iv]; rpv_sigma[il] = output->surfaces.rpv[il].sigma_r[iv]; rpv_t1[il] = output->surfaces.rpv[il].t1_r[iv]; rpv_t2[il] = output->surfaces.rpv[il].t2_r[iv]; } } else { rpv_rho0 = calloc (1, sizeof (float)); rpv_k = calloc (1, sizeof (float)); rpv_theta = calloc (1, sizeof (float)); rpv_scale = calloc (1, sizeof (float)); rpv_sigma = calloc (1, sizeof (float)); rpv_t1 = calloc (1, sizeof (float)); rpv_t2 = calloc (1, sizeof (float)); rpv_rho0[0] = output->rpv.rho0_r[iv]; rpv_k[0] = output->rpv.k_r[iv]; rpv_theta[0] = output->rpv.theta_r[iv]; rpv_scale[0] = output->rpv.scale_r[iv]; rpv_sigma[0] = output->rpv.sigma_r[iv]; rpv_t1[0] = output->rpv.t1_r[iv]; rpv_t2[0] = output->rpv.t2_r[iv]; } if (output->surfaces.n > 0 && output->surfaces.albedo_r != NULL) { alb_type = calloc (output->surfaces.n, sizeof (float)); for (il = 0; il < output->surfaces.n; il++) alb_type[il] = output->surfaces.albedo_r[il][iv]; } else { alb_type = calloc (1, sizeof (float)); alb_type[0] = output->alb.albedo_r[iv]; } /* for rossli we don't have a surface type yet, but that */ /* would be straightforward to implement */ if (output->surfaces.n > 0 && output->surfaces.rossli != NULL) { rossli_iso = calloc (output->surfaces.n, sizeof (float)); rossli_vol = calloc (output->surfaces.n, sizeof (float)); rossli_geo = calloc (output->surfaces.n, sizeof (float)); for (il = 0; il < output->surfaces.n; il++) { rossli_iso[il] = output->surfaces.rossli[il].iso_r[iv]; rossli_vol[il] = output->surfaces.rossli[il].vol_r[iv]; rossli_geo[il] = output->surfaces.rossli[il].geo_r[iv]; } } else { rossli_iso = calloc (1, sizeof (float)); rossli_vol = calloc (1, sizeof (float)); rossli_geo = calloc (1, sizeof (float)); rossli_iso[0] = output->rossli.iso_r[iv]; rossli_vol[0] = output->rossli.vol_r[iv]; rossli_geo[0] = output->rossli.geo_r[iv]; } /* for hapke we don't have a surface type yet, but that */ /* would be straightforward to implement */ hapke_w = calloc (1, sizeof (float)); hapke_b0 = calloc (1, sizeof (float)); hapke_h = calloc (1, sizeof (float)); /* also, wavelength dependence is missing, but that */ /* would also be straightforward to implement */ hapke_w[0] = output->hapke.w_r[iv]; hapke_b0[0] = output->hapke.b0_r[iv]; hapke_h[0] = output->hapke.h_r[iv]; if (input.rte.mc.spectral_is) weight_spectral = calloc (output->mc.alis.nlambda_abs, sizeof (double)); switch (input.source) { case SRC_SOLAR: /* solar source */ case SRC_BLITZ: /* blitz source */ case SRC_LIDAR: /* lidar source */ switch (input.source) { case SRC_SOLAR: /* solar source */ source = MCSRC_SOLAR; break; case SRC_BLITZ: /* blitz source */ source = MCSRC_BLITZ; break; case SRC_LIDAR: /* lidar source */ source = MCSRC_LIDAR; break; default: fprintf (stderr, "Error, source %d should not turn up here!\n", input.source); return -1; } status = mystic (&output->atm.nlyr, threed, input.n_caoth + 2, output->mc.dt, output->mc.om, output->mc.g1, output->mc.g2, output->mc.ff, output->mc.ds, &(output->mc.alis), output->mc.refind, input.r_earth * 1000.0, input.rte.mc.refractive_index_pv, &(output->rayleigh_depol[iv]), output->caoth3d, output->mc.re, output->mc.temper, input.atmosphere3d, output->mc.z, output->mc.momaer, output->mc.nmomaer, output->mc.nthetaaer, output->mc.thetaaer, output->mc.muaer, output->mc.phaseaer, output->mc.nphamataer, &output->alb.albedo_r[iv], alb_type, output->atm.sza_r[iv], output->atm.phi0_r[iv], input.atm.sza_spher, input.atm.phi0_spher, output->mc_photons, &source, &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->wl.lambda_r[iv]), output->atm.zout_sur, &(output->atm.nzout), rpv_rho0, rpv_k, rpv_theta, rpv_scale, rpv_sigma, rpv_t1, rpv_t2, hapke_h, hapke_b0, hapke_w, rossli_iso, rossli_vol, rossli_geo, input.rossli.hotspot, &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &(input.cm.param[BRDF_CAM_UPHI]), &(input.cm.solar_wind), &(input.bpdf.u10), &(input.rte.mc.tenstream), input.rte.mc.tenstream_options, &(input.rte.mc.nca), /* Carolin Klinger 2019 */ input.rte.mc.nca_options, &(input.rte.mc.ipa), &(input.rte.mc.absorption), &(input.rte.mc.backward.thermal_heating_method), &mc_loaddata, &(output->mc.sample), &(output->mc.elev), &(output->mc.triangular_surface), &(output->mc.surftemp), input.rte.mc.filename[FN_MC_BASENAME], input.rte.mc.filename[FN_MC_UMU], input.rte.mc.filename[FN_MC_SUNSHAPE_FILE], input.rte.mc.filename[FN_MC_ALBEDO], input.rte.mc.filename[FN_MC_AMBRALS], input.rte.mc.filename[FN_MC_ROSSLI], input.rte.mc.filename[FN_MC_ALBEDO_TYPE], input.rte.mc.filename[FN_MC_RPV2D_TYPE], input.rte.mc.filename[FN_MC_AMBRALS_TYPE], output->surfaces.label, &(output->surfaces.n), &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/ &(input.rte.mc.truncate), &(input.rte.mc.reflectalways), input.quiet, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->uavgso, rte_out->uavgdn, rte_out->uavgup, rte_out->rfldir3d, rte_out->rfldn3d, rte_out->flup3d, rte_out->fl3d_is, rte_out->uavgso3d, rte_out->uavgdn3d, rte_out->uavgup3d, rte_out->radiance3d, rte_out->absback3d, rte_out->abs3d, rte_out->radiance3d_is, rte_out->jacobian, rte_out->rfldir3d_var, rte_out->rfldn3d_var, rte_out->flup3d_var, rte_out->uavgso3d_var, rte_out->uavgdn3d_var, rte_out->uavgup3d_var, rte_out->radiance3d_var, rte_out->absback3d_var, rte_out->abs3d_var, rte_out->triangle_results, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->atm.dxcld, output->atm.dycld, input.filename[FN_PATH], input.filename[FN_RANDOMSTATUS], input.rte.mc.readrandomstatus, input.write_output_as_netcdf, write_files, input.rte.mc.visualize); CHKERR (status); break; case SRC_THERMAL: /* thermal source */ /* normal atmospheric + surface emission */ switch (input.rte.mc.absorption) { case MCFORWARD_ABS_NONE: case MCFORWARD_ABS_ABSORPTION: case MCFORWARD_ABS_HEATING: if (!input.rte.mc.backward.yes) { /*TZ bt*/ thermal_photons = 0.5 * output->mc_photons; /* thermal emission of the atmosphere */ if (ib == 0 && !input.quiet) fprintf (stderr, " ... thermal emission of the atmosphere\n"); } else { /*TZ bt*/ thermal_photons = 1.0 * output->mc_photons; /*TZ bt*/ /* CE for spectral importance sampling, we run a MC */ /* calculation at only one wavelengths, even if input */ /* wavelength is not exactly included in */ /* molecular_tau_file */ if (input.rte.mc.spectral_is) thermal_photons = input.rte.mc.photons; /* thermal emission into the atmosphere TZ bt*/ if (ib == 0 && !input.quiet) fprintf (stderr, " ... thermal backward emission into atmosphere\n"); /*TZ*/ } /*TZ bt*/ if (!input.rte.mc.backward.yes) /*TZ bt*/ source = MCSRC_THERMAL_ATMOSPHERE; else /*TZ bt*/ source = MCSRC_THERMAL_BACKWARD; /*TZ bt*/ status = mystic (&output->atm.nlyr, threed, input.n_caoth + 2, output->mc.dt, output->mc.om, output->mc.g1, output->mc.g2, output->mc.ff, output->mc.ds, &(output->mc.alis), output->mc.refind, input.r_earth * 1000.0, input.rte.mc.refractive_index_pv, &(output->rayleigh_depol[iv]), output->caoth3d, output->mc.re, output->mc.temper, input.atmosphere3d, output->mc.z, output->mc.momaer, output->mc.nmomaer, output->mc.nthetaaer, output->mc.thetaaer, output->mc.muaer, output->mc.phaseaer, output->mc.nphamataer, &output->alb.albedo_r[iv], alb_type, output->atm.sza_r[iv], output->atm.phi0_r[iv], input.atm.sza_spher, input.atm.phi0_spher, thermal_photons, &source, &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->wl.lambda_r[iv]), output->atm.zout_sur, &(output->atm.nzout), rpv_rho0, rpv_k, rpv_theta, rpv_scale, rpv_sigma, rpv_t1, rpv_t2, hapke_h, hapke_b0, hapke_w, rossli_iso, rossli_vol, rossli_geo, input.rossli.hotspot, &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &(input.cm.param[BRDF_CAM_UPHI]), &(input.cm.solar_wind), &(input.bpdf.u10), &(input.rte.mc.tenstream), input.rte.mc.tenstream_options, &(input.rte.mc.nca), /* Carolin Klinger 2019 */ input.rte.mc.nca_options, &(input.rte.mc.ipa), &(input.rte.mc.absorption), &(input.rte.mc.backward.thermal_heating_method), &mc_loaddata, &(output->mc.sample), &(output->mc.elev), &(output->mc.triangular_surface), &(output->mc.surftemp), input.rte.mc.filename[FN_MC_BASENAME], input.rte.mc.filename[FN_MC_UMU], input.rte.mc.filename[FN_MC_SUNSHAPE_FILE], input.rte.mc.filename[FN_MC_ALBEDO], input.rte.mc.filename[FN_MC_AMBRALS], input.rte.mc.filename[FN_MC_ROSSLI], input.rte.mc.filename[FN_MC_ALBEDO_TYPE], input.rte.mc.filename[FN_MC_RPV2D_TYPE], input.rte.mc.filename[FN_MC_AMBRALS_TYPE], output->surfaces.label, &(output->surfaces.n), &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/ &(input.rte.mc.truncate), &(input.rte.mc.reflectalways), input.quiet, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->uavgso, rte_out->uavgdn, rte_out->uavgup, rte_out->rfldir3d, rte_out->rfldn3d, rte_out->flup3d, rte_out->fl3d_is, rte_out->uavgso3d, rte_out->uavgdn3d, rte_out->uavgup3d, rte_out->radiance3d, rte_out->absback3d, rte_out->abs3d, rte_out->radiance3d_is, rte_out->jacobian, rte_out->rfldir3d_var, rte_out->rfldn3d_var, rte_out->flup3d_var, rte_out->uavgso3d_var, rte_out->uavgdn3d_var, rte_out->uavgup3d_var, rte_out->radiance3d_var, rte_out->absback3d_var, rte_out->abs3d_var, rte_out->triangle_results, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->atm.dxcld, output->atm.dycld, input.filename[FN_PATH], input.filename[FN_RANDOMSTATUS], input.rte.mc.readrandomstatus, input.write_output_as_netcdf, write_files, input.rte.mc.visualize); CHKERR (status); /* thermal emission of the surface */ if (!input.rte.mc.backward.yes && !input.rte.mc.tenstream && !input.rte.mc.nca) { /*TZ bt, no separate surface emission needed*/ /* Carolin Klinger 2019 */ if (ib == 0 && !input.quiet) fprintf (stderr, " ... thermal emission of the surface\n"); /* data have already been loaded during the last MYSTIC call */ mc_loaddata = 0; tmp_out = calloc_rte_output (input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->mc.alis.nlambda_abs, output->atm.nlyr - 1, output->atm.threed, output->mc.sample.passback3D, output->mc.triangular_surface.N_triangles); source = MCSRC_THERMAL_SURFACE; status = mystic (&output->atm.nlyr, threed, input.n_caoth + 2, output->mc.dt, output->mc.om, output->mc.g1, output->mc.g2, output->mc.ff, output->mc.ds, &(output->mc.alis), output->mc.refind, input.r_earth * 1000.0, input.rte.mc.refractive_index_pv, &(output->rayleigh_depol[iv]), output->caoth3d, output->mc.re, output->mc.temper, input.atmosphere3d, output->mc.z, output->mc.momaer, output->mc.nmomaer, output->mc.nthetaaer, output->mc.thetaaer, output->mc.muaer, output->mc.phaseaer, output->mc.nphamataer, &output->alb.albedo_r[iv], alb_type, output->atm.sza_r[iv], output->atm.phi0_r[iv], input.atm.sza_spher, input.atm.phi0_spher, thermal_photons, &source, &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->wl.lambda_r[iv]), output->atm.zout_sur, &(output->atm.nzout), rpv_rho0, rpv_k, rpv_theta, rpv_scale, rpv_sigma, rpv_t1, rpv_t2, hapke_h, hapke_b0, hapke_w, rossli_iso, rossli_vol, rossli_geo, input.rossli.hotspot, &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &(input.cm.param[BRDF_CAM_UPHI]), &(input.cm.solar_wind), &(input.bpdf.u10), &(input.rte.mc.tenstream), input.rte.mc.tenstream_options, &(input.rte.mc.nca), /* Carolin Klinger 2019 */ input.rte.mc.nca_options, &(input.rte.mc.ipa), &(input.rte.mc.absorption), &(input.rte.mc.backward.thermal_heating_method), &mc_loaddata, &(output->mc.sample), &(output->mc.elev), &(output->mc.triangular_surface), &(output->mc.surftemp), input.rte.mc.filename[FN_MC_BASENAME], input.rte.mc.filename[FN_MC_UMU], input.rte.mc.filename[FN_MC_SUNSHAPE_FILE], input.rte.mc.filename[FN_MC_ALBEDO], input.rte.mc.filename[FN_MC_AMBRALS], input.rte.mc.filename[FN_MC_ROSSLI], input.rte.mc.filename[FN_MC_ALBEDO_TYPE], input.rte.mc.filename[FN_MC_RPV2D_TYPE], input.rte.mc.filename[FN_MC_AMBRALS_TYPE], output->surfaces.label, &(output->surfaces.n), &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/ &(input.rte.mc.truncate), &(input.rte.mc.reflectalways), input.quiet, tmp_out->rfldir, tmp_out->rfldn, tmp_out->flup, tmp_out->uavgso, tmp_out->uavgdn, tmp_out->uavgup, tmp_out->rfldir3d, tmp_out->rfldn3d, tmp_out->flup3d, tmp_out->fl3d_is, tmp_out->uavgso3d, tmp_out->uavgdn3d, tmp_out->uavgup3d, tmp_out->radiance3d, rte_out->absback3d, tmp_out->abs3d, rte_out->radiance3d_is, rte_out->jacobian, tmp_out->rfldir3d_var, tmp_out->rfldn3d_var, tmp_out->flup3d_var, tmp_out->uavgso3d_var, tmp_out->uavgdn3d_var, tmp_out->uavgup3d_var, tmp_out->radiance3d_var, rte_out->absback3d_var, tmp_out->abs3d_var, rte_out->triangle_results, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->atm.dxcld, output->atm.dycld, input.filename[FN_PATH], input.filename[FN_RANDOMSTATUS], input.rte.mc.readrandomstatus, input.write_output_as_netcdf, write_files, input.rte.mc.visualize); CHKERR (status); /* add atmosphere and surface contributions to get total (rte_out) */ if (input.rte.mc.spectral_is) for (iv_alis = 0; iv_alis < output->mc.alis.nlambda_abs; iv_alis++) weight_spectral[iv_alis] = 1.0; status = add_rte_output (rte_out, tmp_out, 1.0, weight_spectral, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.alis.Nc, output->atm.nlyr - 1, output->mc.alis.nlambda_abs, output->atm.threed, output->mc.sample.passback3D, output->islower, output->isupper, output->jslower, output->jsupper, output->isstep, output->jsstep); CHKERR (status); status = free_rte_output (tmp_out, input, output->atm.nzout, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->mc.sample.Nx, output->mc.sample.Ny, output->mc.alis.Nc, output->atm.nlyr - 1, output->mc.alis.nlambda_abs, output->atm.threed, output->mc.sample.passback3D); CHKERR (status); } /*TZ bt, no surface emission needed*/ break; case MCFORWARD_ABS_EMISSION: thermal_photons = 0; /* 3D emission field */ if (!input.quiet) fprintf (stderr, " ... calculate 3D emission field \n"); source = MCSRC_THERMAL_ATMOSPHERE; status = mystic (&output->atm.nlyr, threed, input.n_caoth + 2, output->mc.dt, output->mc.om, output->mc.g1, output->mc.g2, output->mc.ff, output->mc.ds, &(output->mc.alis), output->mc.refind, input.r_earth * 1000.0, input.rte.mc.refractive_index_pv, &(output->rayleigh_depol[iv]), output->caoth3d, output->mc.re, output->mc.temper, input.atmosphere3d, output->mc.z, output->mc.momaer, output->mc.nmomaer, output->mc.nthetaaer, output->mc.thetaaer, output->mc.muaer, output->mc.phaseaer, output->mc.nphamataer, &output->alb.albedo_r[iv], alb_type, output->atm.sza_r[iv], output->atm.phi0_r[iv], input.atm.sza_spher, input.atm.phi0_spher, thermal_photons, &source, &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->wl.lambda_r[iv]), output->atm.zout_sur, &(output->atm.nzout), rpv_rho0, rpv_k, rpv_theta, rpv_scale, rpv_sigma, rpv_t1, rpv_t2, hapke_h, hapke_b0, hapke_w, rossli_iso, rossli_vol, rossli_geo, input.rossli.hotspot, &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &(input.cm.param[BRDF_CAM_UPHI]), &(input.cm.solar_wind), &(input.bpdf.u10), &(input.rte.mc.tenstream), input.rte.mc.tenstream_options, &(input.rte.mc.nca), /* Carolin Klinger 2019 */ input.rte.mc.nca_options, &(input.rte.mc.ipa), &(input.rte.mc.absorption), &(input.rte.mc.backward.thermal_heating_method), &mc_loaddata, &(output->mc.sample), &(output->mc.elev), &(output->mc.triangular_surface), &(output->mc.surftemp), input.rte.mc.filename[FN_MC_BASENAME], input.rte.mc.filename[FN_MC_UMU], input.rte.mc.filename[FN_MC_SUNSHAPE_FILE], input.rte.mc.filename[FN_MC_ALBEDO], input.rte.mc.filename[FN_MC_AMBRALS], input.rte.mc.filename[FN_MC_ROSSLI], input.rte.mc.filename[FN_MC_ALBEDO_TYPE], input.rte.mc.filename[FN_MC_RPV2D_TYPE], input.rte.mc.filename[FN_MC_AMBRALS_TYPE], output->surfaces.label, &(output->surfaces.n), &(input.rte.mc.delta_scaling_mucut), /*TZ ds*/ &(input.rte.mc.truncate), &(input.rte.mc.reflectalways), input.quiet, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->uavgso, rte_out->uavgdn, rte_out->uavgup, rte_out->rfldir3d, rte_out->rfldn3d, rte_out->flup3d, rte_out->fl3d_is, rte_out->uavgso3d, rte_out->uavgdn3d, rte_out->uavgup3d, rte_out->radiance3d, rte_out->absback3d, rte_out->abs3d, rte_out->radiance3d_is, rte_out->jacobian, rte_out->rfldir3d_var, rte_out->rfldn3d_var, rte_out->flup3d_var, rte_out->uavgso3d_var, rte_out->uavgdn3d_var, rte_out->uavgup3d_var, rte_out->radiance3d_var, rte_out->absback3d_var, rte_out->abs3d_var, rte_out->triangle_results, output->atm.Nxcld, output->atm.Nycld, output->atm.Nzcld, output->atm.dxcld, output->atm.dycld, input.filename[FN_PATH], input.filename[FN_RANDOMSTATUS], input.rte.mc.readrandomstatus, input.write_output_as_netcdf, write_files, input.rte.mc.visualize); CHKERR (status) break; default: fprintf (stderr, "Error, unknown absorption type %d\n", input.rte.mc.absorption); CHKERR (-1); } break; default: CHKERROUT (-1, "unknown source"); } /* free RPV arrays */ free (rpv_rho0); free (rpv_k); free (rpv_theta); free (rpv_scale); free (rpv_sigma); free (rpv_t1); free (rpv_t2); /* free ROSSLI arrays */ free (rossli_iso); free (rossli_vol); free (rossli_geo); /* free HAPKE arrays */ free (hapke_h); free (hapke_b0); free (hapke_w); break; #else fprintf (stderr, "Error: MYSTIC solver not included in uvspec build.\n"); fprintf (stderr, "Error: Please contact bernhard.mayer@lmu.de\n"); CHKERR (-1); #endif case SOLVER_FDISORT1: case SOLVER_FDISORT2: case SOLVER_DISORT: if (rte_solver != SOLVER_DISORT) { disort_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float)); disort_uu = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float)); } /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } if (input.rte.solver == SOLVER_FDISORT1) { if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } disort_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom); if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) || (input.source == SRC_THERMAL)) { /* no need to call disort otherwise as sun below horizon */ F77_FUNC (disort, DISORT) (&output->atm.nlyr, output->dtauc, output->ssalb, disort_pmom, output->atm.microphys.temper[0][0], &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(rte_in->usrtau), &output->atm.nzout, rte_in->utau, &input.rte.nstr, &(rte_in->usrang), &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &(rte_in->ibcnd), &(rte_in->fbeam), &(rte_in->umu0), &output->atm.phi0_r[iv], &(rte_in->fisot), &(rte_in->lamber), &output->alb.albedo_r[iv], rte_in->hl, &(rte_in->btemp), &(rte_in->ttemp), &(rte_in->temis), &input.rte.deltam, &(rte_in->planck), &(rte_in->onlyfl), &(rte_in->accur), rte_in->prndis, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.nstr, &input.rte.maxphi, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, disort_uu, disort_u0u, rte_out->albmed, rte_out->trnmed, rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup, &(input.quiet)); for (lev = 0; lev < output->atm.nzout; lev++) rte_out->uavg[lev] = rte_out->uavgso[lev] + rte_out->uavgdn[lev] + rte_out->uavgup[lev]; } } else if (input.rte.solver == SOLVER_FDISORT2) { if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } /* BRDF or Lambertian albedo */ if (input.disort2_brdf != BRDF_NONE) rte_in->lamber = 0; else rte_in->lamber = 1; disort2_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom); switch (input.rte.disort_icm) { case DISORT_ICM_OFF: intensity_correction = FALSE; break; case DISORT_ICM_MOMENTS: intensity_correction = TRUE; old_intensity_correction = TRUE; break; case DISORT_ICM_PHASE: intensity_correction = TRUE; old_intensity_correction = FALSE; disort2_ntheta = &(output->ntheta[0][0]); disort2_phaso = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->ntheta[0][0], output->phase); disort2_mup = c2fortran_3D_double_ary (1, 1, output->ntheta[0][0], output->mu); break; default: fprintf (stderr, "Error: unknown disort_icm %d\n", input.rte.disort_icm); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) || (input.source == SRC_THERMAL)) { /* no need to call disort2 otherwise, as sun below horizon */ F77_FUNC (disort2, DISORT2) (&output->atm.nlyr, output->dtauc, output->ssalb, &output->atm.nmom, disort2_pmom, disort2_ntheta, disort2_phaso, disort2_mup, output->atm.microphys.temper[0][0], &output->wl.wvnmlo_r[iv], &output->wl.wvnmhi_r[iv], &rte_in->usrtau, &output->atm.nzout, rte_in->utau, &input.rte.nstr, &rte_in->usrang, &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &rte_in->ibcnd, &rte_in->fbeam, &rte_in->umu0, &output->atm.phi0_r[iv], &rte_in->fisot, &rte_in->lamber, &output->alb.albedo_r[iv], &rte_in->btemp, &rte_in->ttemp, &rte_in->temis, &rte_in->planck, &rte_in->onlyfl, &rte_in->accur, rte_in->prndis2, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.maxphi, &output->atm.nmom, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, disort_uu, disort_u0u, rte_out->albmed, rte_out->trnmed, rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup, &(input.disort2_brdf), &(output->rpv.rho0_r[iv]), &(output->rpv.k_r[iv]), &(output->rpv.theta_r[iv]), &(output->rpv.sigma_r[iv]), &(output->rpv.t1_r[iv]), &(output->rpv.t2_r[iv]), &(output->rpv.scale_r[iv]), &(output->rossli.iso_r[iv]), &(output->rossli.vol_r[iv]), &(output->rossli.geo_r[iv]), &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &intensity_correction, &old_intensity_correction, &(input.quiet)); for (lev = 0; lev < output->atm.nzout; lev++) rte_out->uavg[lev] = rte_out->uavgso[lev] + rte_out->uavgdn[lev] + rte_out->uavgup[lev]; } } else if (input.rte.solver == SOLVER_DISORT) { if (input.flu.source != NOT_DEFINED_INTEGER) { // We have included fluorescence as radiation source rte_in->fbeam = output->wl.fbeam[iv]; // Need to do calibrated simulation. } if (input.raman) { rte_in->gsrc = 0; ds_in.flag.general_source = FALSE; /* No extra source term for zero Raman scattering. */ if (ir == 0 && input.raman_fast) { rte_in->fbeam = output->wl.fbeam[ib]; } else if (ir == 0 && !input.raman_fast) { if (ib == 0) { if ((status = ASCII_calloc_double_3D (&tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths, 3)) != 0) { fprintf (stderr, "Error %d allocating memory for tmp_crs\n", status); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return status; } /* First time for each user wavelength calculate Raman shifted wavelengths and Raman cross section */ for (lu = 0; lu < output->atm.nlev; lu++) { ivi = 0; status = crs_raman_N2 (output->wl.lambda_r[iv], input.n_raman_transitions_N2, output->atm.microphys.temper[lu][0][0], &tmp_crs[lu], &ivi, verbose); status = crs_raman_O2 (output->wl.lambda_r[iv], input.n_raman_transitions_O2, output->atm.microphys.temper[lu][0][0], &tmp_crs[lu], &ivi, verbose); /* Put the wanted wavelength last in the tmp_crs by doing the following */ /* and set correctly after sort */ tmp_crs[lu][output->crs.number_of_ramanwavelengths - 1][0] = 999e+9; /* sort cross section data in ascending order */ status = ASCII_sortarray (tmp_crs[lu], output->crs.number_of_ramanwavelengths, 3, 0, 0); for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) { output->crs.wvl_of_ramanshifts[ivi] = tmp_crs[0][ivi][0]; output->crs.crs_raman_RL[lu][ivi] = tmp_crs[lu][ivi][1]; output->crs.crs_raman_RG[lu][ivi] = tmp_crs[lu][ivi][2]; } ivi = output->crs.number_of_ramanwavelengths - 1; output->crs.wvl_of_ramanshifts[ivi] = output->wl.lambda_r[iv]; output->crs.crs_raman_RL[lu][ivi] = 0.0; output->crs.crs_raman_RG[lu][ivi] = 0.0; } if (tmp_crs != NULL) ASCII_free_double_3D (tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths); } /* Interpolate all optical quantities to the Raman shifted wavelength */ qwanted_wvl[0] = (float)output->crs.wvl_of_ramanshifts[ib]; status = arb_wvn (output->wl.nlambda_r, output->wl.lambda_r, output->wl.fbeam, 1, qwanted_wvl, qfbeam, INTERP_METHOD_LINEAR, 0); if (status != 0) { fprintf (stderr, " Error, interpolation of 'fbeam' for raman option\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } /* FIXME, redistribute photons instead of interpolating spectrum */ rte_in->fbeam = qfbeam[0]; status = arb_wvn (output->wl.nlambda_r, output->wl.lambda_r, output->alb.albedo_r, 1, qwanted_wvl, qalbedo, INTERP_METHOD_LINEAR, 0); if (status != 0) { fprintf (stderr, " Error, interpolation of 'albedo_r' for raman option\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } /* Find iv indices closest to ib wavelength above and below */ iv1 = closest_above (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r); iv2 = closest_below (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r); /* Calculate optical properties for closest wavelength above and below wanted wavelength,*/ /* and interpolate optical properties to wanted wavelength. */ status = optical_properties (input, output, qwanted_wvl[0], ir, iv1, iv2, 0, verbose, skip_optical_properties); /* in ancillary.c */ if (status != 0) { fprintf (stderr, "Error %d returned by optical_properties_raman (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } /* We also need utau at the "new" interpolated optical depth. */ /* "very old" version, recycled */ /* zd is altitude which defines dtauc */ /* zout is the altitudes at which tau is wanted */ F77_FUNC (setout, SETOUT) (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur); } else if (ir == 1) { rte_in->fbeam = 0.0; rte_in->gsrc = 1; ds_in.flag.general_source = TRUE; /* Include extra source term for first order Raman scattering. */ if ((status = ASCII_calloc_double_3D (&(rte_in->qsrc), input.rte.nstr, output->atm.nzout, input.rte.nstr)) != 0) return status; if (rte_in->usrang) { if ((status = ASCII_calloc_double_3D (&(rte_in->qsrcu), input.rte.nstr, output->atm.nzout, input.rte.numu)) != 0) return status; } if (input.raman_fast) { /* Calculate Raman crs at wanted wavelength. */ if ((status = ASCII_calloc_double_3D (&tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths, 3)) != 0) { fprintf (stderr, "Error %d allocating memory for tmp_crs\n", status); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return status; } /* For each user wavelength calculate Raman shifted wavelengths and Raman cross section */ for (lu = 0; lu < output->atm.nlev; lu++) { ivi = 0; status = crs_raman_N2 (output->wl.lambda_r[iv + output->wl.nlambda_rte_lower], input.n_raman_transitions_N2, output->atm.microphys.temper[0][0][lu], &tmp_crs[lu], &ivi, verbose); status = crs_raman_O2 (output->wl.lambda_r[iv + output->wl.nlambda_rte_lower], input.n_raman_transitions_O2, output->atm.microphys.temper[0][0][lu], &tmp_crs[lu], &ivi, verbose); /* Put the wanted wavelength last in the tmp_crs by doing the following */ /* and set correctly after sort */ tmp_crs[lu][output->crs.number_of_ramanwavelengths - 1][0] = 999e+9; /* sort cross section data in ascending order */ status = ASCII_sortarray (tmp_crs[lu], output->crs.number_of_ramanwavelengths, 3, 0, 0); for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) { output->crs.wvl_of_ramanshifts[ivi] = tmp_crs[0][ivi][0]; output->crs.crs_raman_RL[lu][ivi] = tmp_crs[lu][ivi][1]; // Cross sections are reversed in wavelength. This because photons are scattered into the // wavelength of interest, lambda_1, from these wavelengths (lambda_j). If lambda_j > // lambda_1, then the photon gains energy. Thus, the original cross section indices // must be reversed to account for this, and vice versa. AK, 20130513. output->crs.crs_raman_RG[lu][output->crs.number_of_ramanshifts - ivi] = tmp_crs[lu][ivi][2]; } ivi = output->crs.number_of_ramanwavelengths - 1; output->crs.wvl_of_ramanshifts[ivi] = output->wl.lambda_r[iv]; output->crs.crs_raman_RL[lu][ivi] = 0.0; output->crs.crs_raman_RG[lu][ivi] = 0.0; } if (tmp_crs != NULL) ASCII_free_double_3D (tmp_crs, output->atm.nlev, output->crs.number_of_ramanwavelengths); /* Interpolate raman_qsrc_comp at wl.lambda_r resolution to raman_wavelength grid */ tmp_raman_qsrc_comp = calloc_raman_qsrc_components (input.raman_fast, output->atm.nzout, input.rte.maxumu, input.rte.nphi, input.rte.nstr, output->crs.number_of_ramanwavelengths); /* Interpolate dtauc */ if ((tmp_in_int = (double*)calloc (output->wl.nlambda_r, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((tmp_wl = (double*)calloc (output->wl.nlambda_r, sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((tmp_out_int = (double*)calloc (output->crs.number_of_ramanshifts + 1, sizeof (double))) == NULL) return ASCII_NO_MEMORY; for (ivi = 0; ivi < output->wl.nlambda_r; ivi++) tmp_wl[ivi] = output->wl.lambda_r[ivi]; for (lu = 0; lu < output->atm.nzout - 1; lu++) { for (ivi = 0; ivi < output->wl.nlambda_r; ivi++) tmp_in_int[ivi] = raman_qsrc_comp->dtauc[lu][ivi]; status = arb_wvn_double (output->wl.nlambda_r, tmp_wl, tmp_in_int, output->crs.number_of_ramanshifts, output->crs.wvl_of_ramanshifts, tmp_out_int, INTERP_METHOD_LINEAR, 0); for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) tmp_raman_qsrc_comp->dtauc[lu][ivi] = tmp_out_int[ivi]; /* The wavelength we are calculating is stored last in the ary */ tmp_raman_qsrc_comp->dtauc[lu][output->crs.number_of_ramanshifts] = raman_qsrc_comp->dtauc[lu][iv]; } /* Interpolate fbeam */ for (ivi = 0; ivi < output->wl.nlambda_r; ivi++) tmp_in_int[ivi] = raman_qsrc_comp->fbeam[ivi]; status = arb_wvn_double (output->wl.nlambda_r, tmp_wl, tmp_in_int, output->crs.number_of_ramanshifts, output->crs.wvl_of_ramanshifts, tmp_out_int, INTERP_METHOD_LINEAR, 0); for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) tmp_raman_qsrc_comp->fbeam[ivi] = tmp_out_int[ivi]; /* The wavelength we are calculating is stored last in the ary */ tmp_raman_qsrc_comp->fbeam[output->crs.number_of_ramanshifts] = raman_qsrc_comp->fbeam[iv]; /* Interpolate uum */ for (lu = 0; lu < output->atm.nzout; lu++) { for (maz = 0; maz < input.rte.nstr; maz++) { for (iq = 0; iq < input.rte.numu; iq++) { for (ivi = 0; ivi < output->wl.nlambda_r; ivi++) tmp_in_int[ivi] = raman_qsrc_comp->uum[lu][maz][iq][ivi]; status = arb_wvn_double (output->wl.nlambda_r, tmp_wl, tmp_in_int, output->crs.number_of_ramanshifts, output->crs.wvl_of_ramanshifts, tmp_out_int, INTERP_METHOD_LINEAR, 0); for (ivi = 0; ivi < output->crs.number_of_ramanshifts; ivi++) tmp_raman_qsrc_comp->uum[lu][maz][iq][ivi] = tmp_out_int[ivi]; /* The wavelength we are calculating is stored last in the ary */ tmp_raman_qsrc_comp->uum[lu][maz][iq][output->crs.number_of_ramanshifts] = raman_qsrc_comp->uum[lu][maz][iq][iv]; } } } qwanted_wvl[0] = tmp_wl[iv]; /* Needed later in set_raman_source */ free (tmp_in_int); free (tmp_out_int); free (tmp_wl); status = optical_properties (input, output, output->wl.lambda_r[iv], ir, iv, iv, 0, verbose, skip_optical_properties); /* in ancillary.c */ if (status != 0) { fprintf (stderr, "Error %d returned by optical_properties (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } /* We also need utau. */ /* "very old" version, recycled */ F77_FUNC (setout, SETOUT) (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur); /* Set the general inhomogeneous source applicable for Raman scattering */ if (iv == output->wl.raman_end_id) last = 1; status = set_raman_source (rte_in->qsrc, rte_in->qsrcu, input.rte.maxphi, output->atm.nlyr + 1, output->atm.nzout, input.rte.nstr, output->crs.number_of_ramanshifts, qwanted_wvl[0], output->crs.wvl_of_ramanshifts, rte_in->umu0, output->atm.zd, output->atm.zout_sur, output->atm.sza_r[iv], output->wl.fbeam[iv], input.r_earth, output->atm.microphys.dens[MOL_AIR][0][0], output->crs.crs_raman_RL, output->crs.crs_raman_RG, output->ssalb, input.rte.numu, input.rte.umu, rte_in->usrang, input.rte.cmuind, output->pmom, tmp_raman_qsrc_comp, output->atm.zout_comp_index, output->alt.altitude, last, verbose); free_raman_qsrc_components (tmp_raman_qsrc_comp, input.raman_fast, output->atm.nzout, input.rte.maxumu, input.rte.nphi, input.rte.nstr); } /* END if ( input.raman_fast ) */ else { /* Find iv indices closest to ib wavelength above and below */ qwanted_wvl[0] = (float)output->crs.wvl_of_ramanshifts[output->crs.number_of_ramanwavelengths - 1]; iv1 = closest_above (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r); iv2 = closest_below (qwanted_wvl[0], output->wl.lambda_r, output->wl.nlambda_r); /* Calculate optical properties for closest wavelength above and below wanted wavelength,*/ /* and interpolate optical properties to wanted wavelength. */ status = optical_properties (input, output, qwanted_wvl[0], ir, iv1, iv2, 0, verbose, skip_optical_properties); /* in ancillary.c */ if (status != 0) { fprintf (stderr, "Error %d returned by optical_properties (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } /* We also need utau at the "new" interpolated optical depth. */ /* "very old" version, recycled */ F77_FUNC (setout, SETOUT) (output->dtauc, &(output->atm.nlyr), &(output->atm.nzout), rte_in->utau, output->atm.zd, output->atm.zout_sur); /* Set the general inhomogeneous source applicable for Raman scattering */ status = set_raman_source (rte_in->qsrc, rte_in->qsrcu, input.rte.maxphi, output->atm.nlyr + 1, output->atm.nzout, input.rte.nstr, output->crs.number_of_ramanshifts, qwanted_wvl[0], output->crs.wvl_of_ramanshifts, rte_in->umu0, output->atm.zd, output->atm.zout_sur, output->atm.sza_r[iv], output->wl.fbeam[iv], input.r_earth, output->atm.microphys.dens[MOL_AIR][0][0], output->crs.crs_raman_RL, output->crs.crs_raman_RG, output->ssalb, input.rte.numu, input.rte.umu, rte_in->usrang, input.rte.cmuind, output->pmom, raman_qsrc_comp, output->atm.zout_comp_index, output->alt.altitude, last, verbose); } } /* END if ( input.raman_fast ) {} else */ } /* END if ( input.raman ) */ /* BRDF or Lambertian albedo */ if (input.disort2_brdf != BRDF_NONE) rte_in->lamber = 0; else rte_in->lamber = 1; ds_in.nlyr = output->atm.nlyr; ds_in.ntau = output->atm.nzout; ds_in.nstr = input.rte.nstr; ds_in.numu = input.rte.numu; ds_in.nmom = output->atm.nmom; ds_in.nphi = input.rte.nphi; ds_in.accur = rte_in->accur; if (input.rte.disort_icm == DISORT_ICM_PHASE) ds_in.nphase = output->ntheta[0][0]; /* choose how to do intensity correction */ switch (input.rte.disort_icm) { case DISORT_ICM_OFF: ds_in.flag.intensity_correction = FALSE; break; case DISORT_ICM_MOMENTS: ds_in.flag.intensity_correction = TRUE; ds_in.flag.old_intensity_correction = TRUE; break; case DISORT_ICM_PHASE: ds_in.flag.intensity_correction = TRUE; ds_in.flag.old_intensity_correction = FALSE; break; default: fprintf (stderr, "Error: unknown disort_icm %d\n", input.rte.disort_icm); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } ds_in.flag.quiet = input.quiet; ds_in.flag.ibcnd = rte_in->ibcnd; ds_in.flag.planck = rte_in->planck; ds_in.flag.lamber = rte_in->lamber; ds_in.flag.usrtau = rte_in->usrtau; ds_in.flag.usrang = rte_in->usrang; ds_in.flag.onlyfl = rte_in->onlyfl; if (input.raman) { ds_in.flag.output_uum = TRUE; if (ir == 1) { ds_in.flag.general_source = TRUE; ds_in.bc.fluor = 0.0; // Only fluorescence source for the zeroth iteration // Otherwise source is included twice. } else { ds_in.flag.general_source = FALSE; ds_in.bc.fluor = (double)output->flu.fluorescence_r[ib]; } ds_in.bc.albedo = (double)output->alb.albedo_r[ib]; } else { ds_in.flag.output_uum = FALSE; ds_in.flag.general_source = FALSE; ds_in.bc.albedo = (double)output->alb.albedo_r[iv]; ds_in.bc.fluor = (double)output->flu.fluorescence_r[iv]; } ds_in.flag.spher = rte_in->spher; ds_in.radius = c_r_earth; /* ds_in.flag.spher = input.rte.pseudospherical; */ ds_in.bc.btemp = (double)rte_in->btemp; ds_in.bc.fbeam = (double)rte_in->fbeam; ds_in.bc.fisot = (double)rte_in->fisot; ds_in.bc.temis = (double)rte_in->temis; ds_in.bc.ttemp = (double)rte_in->ttemp; ds_in.bc.umu0 = (double)rte_in->umu0; ds_in.bc.phi0 = (double)output->atm.phi0_r[iv]; ds_in.wvnmlo = output->wl.wvnmlo_r[iv]; ds_in.wvnmhi = output->wl.wvnmhi_r[iv]; ds_in.flag.prnt[0] = rte_in->prndis2[0]; ds_in.flag.prnt[1] = rte_in->prndis2[1]; ds_in.flag.prnt[2] = rte_in->prndis2[2]; ds_in.flag.prnt[3] = rte_in->prndis2[3]; ds_in.flag.prnt[4] = rte_in->prndis2[4]; ds_in.flag.brdf_type = input.disort2_brdf; c_disort_state_alloc (&ds_in); c_disort_out_alloc (&ds_in, &ds_out); for (lc = 0; lc < output->atm.nlyr; lc++) { ds_in.dtauc[lc] = (double)output->dtauc[lc]; ds_in.ssalb[lc] = (double)output->ssalb[lc]; for (k = 0; k <= output->atm.nmom; k++) { ds_in.pmom[k + lc * (ds_in.nmom_nstr + 1)] = (double)output->pmom[lc][0][k]; } } for (lc = 0; lc < output->atm.nzout; lc++) { ds_in.utau[lc] = (double)rte_in->utau[lc]; } for (iu = 0; iu < input.rte.numu; iu++) { ds_in.umu[iu] = (double)input.rte.umu[iu]; } for (iu = 0; iu < input.rte.nphi; iu++) { ds_in.phi[iu] = (double)input.rte.phi[iu]; } for (lu = 0; lu <= output->atm.nlyr; lu++) { if (rte_in->planck) ds_in.temper[lu] = (double)output->atm.microphys.temper[0][0][lu]; } if (ds_in.flag.spher) { for (lu = 0; lu <= output->atm.nlyr; lu++) { ds_in.zd[lu] = (double)output->atm.zd[lu]; } } if (input.rte.disort_icm == DISORT_ICM_PHASE) { for (imu = 0; imu < ds_in.nphase; imu++) ds_in.mu_phase[imu] = output->mu[0][0][imu]; for (imu = 0; imu < ds_in.nphase; imu++) for (lc = 0; lc < ds_in.nlyr; lc++) { ds_in.phase[imu + lc * (ds_in.nphase)] = (double)output->phase[lc][0][imu]; } } /* albedo stuff */ switch (ds_in.flag.brdf_type) { case BRDF_RPV: ds_in.brdf.rpv->rho0 = output->rpv.rho0_r[iv]; ds_in.brdf.rpv->k = output->rpv.k_r[iv]; ds_in.brdf.rpv->theta = output->rpv.theta_r[iv]; ds_in.brdf.rpv->sigma = output->rpv.sigma_r[iv]; ds_in.brdf.rpv->t1 = output->rpv.t1_r[iv]; ds_in.brdf.rpv->t2 = output->rpv.t2_r[iv]; ds_in.brdf.rpv->scale = output->rpv.scale_r[iv]; break; case BRDF_CAM: ds_in.brdf.cam->u10 = input.cm.param[BRDF_CAM_U10]; ds_in.brdf.cam->pcl = input.cm.param[BRDF_CAM_PCL]; ds_in.brdf.cam->xsal = input.cm.param[BRDF_CAM_SAL]; break; case BRDF_HAPKE: ds_in.brdf.hapke->b0 = output->hapke.b0_r[iv]; ds_in.brdf.hapke->h = output->hapke.h_r[iv]; ds_in.brdf.hapke->w = output->hapke.w_r[iv]; break; case BRDF_ROSSLI: ds_in.brdf.rossli->iso = output->rossli.iso_r[iv]; ds_in.brdf.rossli->vol = output->rossli.vol_r[iv]; ds_in.brdf.rossli->geo = output->rossli.geo_r[iv]; ds_in.brdf.rossli->hotspot = input.rossli.hotspot; break; default: break; } if (input.raman && ir == 1) { for (maz = 0; maz < ds_in.nstr; maz++) { for (lc = 0; lc < ds_in.nlyr; lc++) { for (iq = 0; iq < ds_in.nstr; iq++) { ds_in.gensrc[iq + (lc + maz * ds_in.nlyr) * ds_in.nstr] = (double)rte_in->qsrc[maz][lc][iq]; } } } for (maz = 0; maz < ds_in.nstr; maz++) { for (lc = 0; lc < ds_in.nlyr; lc++) { for (iu = 0; iu < ds_in.numu; iu++) { ds_in.gensrcu[iu + (lc + maz * ds_in.nlyr) * ds_in.numu] = (double)rte_in->qsrcu[maz][lc][iu]; } } } } if (ir == 1) { if (rte_in->qsrc != NULL) ASCII_free_double_3D (rte_in->qsrc, input.rte.nstr, output->atm.nzout); if (rte_in->qsrcu != NULL) ASCII_free_double_3D (rte_in->qsrcu, input.rte.nstr, output->atm.nzout); } if (((input.source == SRC_SOLAR) && (rte_in->umu0 > 0)) /* no need to call plane-parralel cdisort, as sun below horizon */ || ((input.source == SRC_SOLAR) && (input.rte.pseudospherical)) /* pseudo-spherical cdisort */ || (input.source == SRC_THERMAL)) { c_disort (&ds_in, &ds_out); } if (rte_in->ibcnd) { for (iu = 0; iu < input.rte.numu; iu++) { rte_out->albmed[iu] = (float)ds_out.albmed[iu]; rte_out->trnmed[iu] = (float)ds_out.trnmed[iu]; } } for (lu = 0; lu < output->atm.nzout; lu++) { rte_out->dfdt[lu] = (float)ds_out.rad[lu].dfdt; rte_out->rfldir[lu] = (float)ds_out.rad[lu].rfldir; rte_out->rfldn[lu] = (float)ds_out.rad[lu].rfldn; rte_out->flup[lu] = (float)ds_out.rad[lu].flup; rte_out->uavg[lu] = (float)ds_out.rad[lu].uavg; rte_out->uavgdn[lu] = (float)ds_out.rad[lu].uavgdn; rte_out->uavgup[lu] = (float)ds_out.rad[lu].uavgup; rte_out->uavgso[lu] = (float)ds_out.rad[lu].uavgso; for (j = 0; j < input.rte.nphi; j++) for (iu = 0; iu < input.rte.numu; iu++) rte_out->uu[j][lu][iu] = ds_out.uu[iu + (lu + j * ds_in.ntau) * ds_in.numu]; if (input.raman) for (j = 0; j < input.rte.nstr; j++) // j is the same as mazim in c_disort for (iu = 0; iu < input.rte.numu; iu++) rte_out->uum[j][lu][iu] = ds_out.uum[iu + (lu + j * ds_in.ntau) * ds_in.numu]; for (iu = 0; iu < input.rte.numu; iu++) rte_out->u0u[lu][iu] = ds_out.u0u[iu + lu * ds_in.numu]; } c_disort_out_free (&ds_in, &ds_out); c_disort_state_free (&ds_in); } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } if (rte_solver != SOLVER_DISORT) { /* convert temporary Fortran arrays to permanent result for the fortran solver, not cdisort*/ fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u); fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu); free (disort_pmom); free (disort2_pmom); free (disort2_phaso); free (disort2_mup); free (disort_u0u); free (disort_uu); } break; case SOLVER_TZS: /* tzs_u0u = (float *) calloc (output->atm.nzout*input.rte.maxumu, sizeof(float)); */ /* tzs_uu = (float *) calloc (output->atm.nzout*input.rte.maxumu*input.rte.maxphi, sizeof(float)); */ /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } /* call RTE solver */ /* old call to fortran tzs, now replaced by c_tzs which includes also blackbody clouds */ /* F77_FUNC (tzs, TZS) (&output->atm.nlyr, output->dtauc, output->ssalb, */ /* output->atm.microphys.temper, &output->wl.wvnmlo_r[iv], */ /* &output->wl.wvnmhi_r[iv], &rte_in->usrtau, &output->atm.nzout, rte_in->utau, */ /* &rte_in->usrang, &input.rte.numu, input.rte.umu, */ /* &input.rte.nphi, input.rte.phi, */ /* &output->alb.albedo_r[iv], &rte_in->btemp, &rte_in->ttemp, */ /* &rte_in->temis, &rte_in->planck, */ /* rte_in->prndis, rte_in->header, &output->atm.nlyr, */ /* &output->atm.nzout, &input.rte.maxumu, &input.rte.maxphi, */ /* rte_out->rfldir, rte_out->rfldn, rte_out->flup, */ /* rte_out->dfdt, rte_out->uavg, */ /* tzs_uu, rte_out->albmed, rte_out->trnmed, */ /* rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup); */ /* call RTE solver */ status = c_tzs (output->atm.nlyr, output->dtauc, output->atm.nlev_common, output->atm.zd_common, output->atm.nzout, output->atm.zout_sur, output->ssalb, output->atm.microphys.temper[0][0], output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], rte_in->usrtau, output->atm.nzout, rte_in->utau, rte_in->usrang, input.rte.numu, input.rte.umu, input.rte.nphi, input.rte.phi, output->alb.albedo_r[iv], rte_in->btemp, rte_in->ttemp, rte_in->temis, rte_in->planck, rte_in->prndis, rte_in->header, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, rte_out->uu, input.quiet); if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } /* convert temporary Fortran arrays to permanent result */ /* fortran2c_2D_float_ary_noalloc (output->atm.nzout, */ /* input.rte.maxumu, tzs_u0u, rte_out->u0u); */ /* fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, */ /* input.rte.maxumu, tzs_uu, rte_out->uu); */ /* free(tzs_u0u); */ /* free(tzs_uu); */ break; case SOLVER_SSS: sss_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float)); sss_uu = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float)); /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } /* call RTE solver */ sss_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom); F77_FUNC (sss, SSS) (&output->atm.nlyr, output->dtauc, output->ssalb, &output->atm.nmom, sss_pmom, output->atm.microphys.temper[0][0], &output->wl.wvnmlo_r[iv], &output->wl.wvnmhi_r[iv], &rte_in->usrtau, &output->atm.nzout, rte_in->utau, &input.rte.nstr, &rte_in->usrang, &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &rte_in->ibcnd, &rte_in->fbeam, &rte_in->umu0, &output->atm.phi0_r[iv], &rte_in->fisot, &rte_in->lamber, &output->alb.albedo_r[iv], &rte_in->btemp, &rte_in->ttemp, &rte_in->temis, &rte_in->planck, &rte_in->onlyfl, &rte_in->accur, rte_in->prndis2, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.maxphi, &output->atm.nmom, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, sss_uu, rte_out->albmed, rte_out->trnmed, rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup, &(input.disort2_brdf), &(output->rpv.rho0_r[iv]), &(output->rpv.k_r[iv]), &(output->rpv.theta_r[iv]), &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL])); if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } /* convert temporary Fortran arrays to permanent result */ fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, sss_u0u, rte_out->u0u); fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, sss_uu, rte_out->uu); free (sss_pmom); free (sss_u0u); free (sss_uu); break; case SOLVER_SSSI: #if HAVE_SSSI /* get cloud reflectivity from lookup table */ status = read_isccp_reflectivity (output->sssi.type, output->atm.sza_r[iv], output->sssi.tautot, input.filename[FN_PATH], input.quiet, &(output->sssi.ref)); if (status != 0) { fprintf (stderr, "Error %d returned by read_isccp_reflectivity()\n", status); return status; } if (input.verbose) { fprintf (stderr, "*** SSSI cloud properties:\n"); fprintf (stderr, " top level: zd[%d] = %f\n", output->sssi.lctop, output->atm.zd[output->sssi.lctop]); switch (output->sssi.type) { case ISCCP_WATER: fprintf (stderr, " type: water\n"); break; case ISCCP_ICE: fprintf (stderr, " type: ice\n"); break; default: fprintf (stderr, "Error, unknown ISCCP cloud type %d\n", output->sssi.type); return -1; } fprintf (stderr, " optical thickness: %f\n", output->sssi.tautot); fprintf (stderr, " reflectivity: %f\n", output->sssi.ref); } fflush (stderr); sss_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float)); sss_uu = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float)); /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } /* call RTE solver */ sss_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, output->atm.nmom + 1, output->pmom); F77_FUNC (sssi, SSSI) (&output->atm.nlyr, output->dtauc, output->ssalb, &output->atm.nmom, sss_pmom, output->atm.microphys.temper[0][0], &output->wl.wvnmlo_r[iv], &output->wl.wvnmhi_r[iv], &rte_in->usrtau, &output->atm.nzout, rte_in->utau, &input.rte.nstr, &rte_in->usrang, &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &rte_in->ibcnd, &rte_in->fbeam, &rte_in->umu0, &output->atm.phi0_r[iv], &rte_in->fisot, &rte_in->lamber, &output->alb.albedo_r[iv], &rte_in->btemp, &rte_in->ttemp, &rte_in->temis, &rte_in->planck, &rte_in->onlyfl, &rte_in->accur, rte_in->prndis2, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.maxphi, &output->atm.nmom, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, sss_uu, rte_out->albmed, rte_out->trnmed, rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup, &(input.disort2_brdf), &(output->rpv.rho0_r[iv]), &(output->rpv.k_r[iv]), &(output->rpv.theta_r[iv]), &(input.cm.param[BRDF_CAM_U10]), &(input.cm.param[BRDF_CAM_PCL]), &(input.cm.param[BRDF_CAM_SAL]), &(output->sssi.ref), &(output->sssi.lctop)); if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } /* convert temporary Fortran arrays to permanent result */ fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, sss_u0u, rte_out->u0u); fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, sss_uu, rte_out->uu); free (sss_pmom); free (sss_u0u); free (sss_uu); #else fprintf (stderr, "Error, SSSI solver not available!\n"); return -1; #endif break; case SOLVER_POLRADTRAN: #if HAVE_POLRADTRAN rte_in->pol.nummu = input.rte.nstr / 2 + input.rte.numu; rte_in->pol.albedo = (double)output->alb.albedo_r[iv]; rte_in->pol.btemp = (double)(rte_in->btemp); rte_in->pol.flux = (double)(rte_in->fbeam * rte_in->umu0); /* Polradtran wants flux on horizontal surface */ rte_in->pol.mu = (double)(rte_in->umu0); rte_in->pol.sky_temp = (double)(rte_in->ttemp); rte_in->pol.wavelength = 0.0; /* Not used for solar source */ for (lu = 0; lu < output->atm.nlyr; lu++) { /* rte_in->pol.gas_extinct[lu] = (double) output->atm.optprop.tau_molabs_r[lu][iv][0]; fprintf(stderr, "test 1-ssa %g tauc %g molabs %g \n ", 1.0-output->ssalb[lu],output->atm.optprop.tau_rayleigh_r[lu][iv][0], output->atm.optprop.tau_molabs_r[lu][iv][0] ); */ /* ????? CE: Something wrong here?? If not set to zero, results for radiances are totally wrong */ rte_in->pol.gas_extinct[lu] = 0.0; } polradtran_down_flux = (double*)calloc (output->atm.nzout * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double)); polradtran_up_flux = (double*)calloc (output->atm.nzout * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double)); polradtran_down_rad = (double*)calloc (output->atm.nzout * (input.rte.polradtran[POLRADTRAN_AZIORDER] + 1) * (input.rte.nstr / 2 + input.rte.numu) * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double)); polradtran_up_rad = (double*)calloc (output->atm.nzout * (input.rte.polradtran[POLRADTRAN_AZIORDER] + 1) * (input.rte.nstr / 2 + input.rte.numu) * input.rte.polradtran[POLRADTRAN_NSTOKES], sizeof (double)); for (iu = 0; iu < rte_in->pol.nummu; iu++) rte_out->polradtran_mu_values[iu] = (double)fabs (output->mu_values[iu]); /* Take fabs since radtran will calculate both up_rad and down_rad for the value of mu. */ /* The user wants one of these. That is sorted out in the output section of uvspec_lex.l */ F77_FUNC (radtran, RADTRAN) (&input.rte.polradtran[POLRADTRAN_NSTOKES], &(rte_in->pol.nummu), &input.rte.polradtran[POLRADTRAN_AZIORDER], &input.rte.pol_max_delta_tau, &input.rte.polradtran[POLRADTRAN_SRC_CODE], input.rte.pol_quad_type, rte_in->pol.deltam, &(rte_in->pol.flux), &(rte_in->pol.mu), &(rte_in->pol.btemp), (rte_in->pol.ground_type), &(rte_in->pol.albedo), &(rte_in->pol.ground_index), &(rte_in->pol.sky_temp), &(rte_in->pol.wavelength), &output->atm.nlyr, (rte_in->pol.height), (rte_in->pol.temperatures), (rte_in->pol.gas_extinct), output->atm.pol_scat_files, &output->atm.nzout, (rte_in->pol.outlevels), rte_out->polradtran_mu_values, polradtran_up_flux, polradtran_down_flux, polradtran_up_rad, polradtran_down_rad); fortran2c_2D_double_ary_noalloc (output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], polradtran_up_flux, rte_out->polradtran_up_flux); fortran2c_2D_double_ary_noalloc (output->atm.nzout, input.rte.polradtran[POLRADTRAN_NSTOKES], polradtran_down_flux, rte_out->polradtran_down_flux); if (input.rte.polradtran[POLRADTRAN_AZIORDER] > 0) { fortran2c_4D_double_ary_noalloc (output->atm.nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], polradtran_down_rad, rte_out->polradtran_down_rad_q); fortran2c_4D_double_ary_noalloc (output->atm.nzout, input.rte.polradtran[POLRADTRAN_AZIORDER] + 1, input.rte.nstr / 2 + input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], polradtran_up_rad, rte_out->polradtran_up_rad_q); fourier2azimuth (rte_out->polradtran_down_rad_q, rte_out->polradtran_up_rad_q, rte_out->polradtran_down_rad, rte_out->polradtran_up_rad, output->atm.nzout, input.rte.polradtran[POLRADTRAN_AZIORDER], input.rte.nstr, input.rte.numu, input.rte.polradtran[POLRADTRAN_NSTOKES], input.rte.nphi, input.rte.phi); } free (polradtran_down_flux); free (polradtran_up_flux); free (polradtran_down_rad); free (polradtran_up_rad); #else fprintf (stderr, "Error: RTE polradtran solver not included in uvspec build.\n"); fprintf (stderr, "Error: Get solver and rebuild uvspec.\n"); return -1; #endif break; case SOLVER_SDISORT: if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } sdisort_beta = (float*)calloc (output->atm.nlyr + 1, sizeof (float)); disort_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom); disort_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float)); disort_uu = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float)); sdisort_sig = (float*)calloc (output->atm.nlyr + 1, sizeof (float)); if ((status = ASCII_calloc_float (&sdisort_denstab, output->atm.microphys.nsza_denstab, output->atm.nlyr + 1)) != 0) return status; if (output->atm.microphys.denstab_id > 0) { for (lu = 0; lu <= output->atm.nlyr; lu++) { sdisort_sig[lu] = output->crs.crs_amf[iv][lu]; for (is = 0; is < output->atm.microphys.nsza_denstab; is++) sdisort_denstab[is][lu] = output->atm.microphys.denstab_amf[is][lu]; } tosdisort_denstab = c2fortran_2D_float_ary (output->atm.microphys.nsza_denstab, output->atm.nlyr + 1, sdisort_denstab); if (sdisort_denstab != NULL) ASCII_free_float (sdisort_denstab, output->atm.microphys.nsza_denstab); } /* Definition of refind in (refractive index - 1), function SOLVER_SDISORT takes refractive index */ for (lu = 0; lu <= output->atm.nlyr; lu++) output->atm.microphys.refind[iv][lu] += 1.; F77_FUNC (sdisort, SDISORT) (&output->atm.nlyr, output->dtauc, output->ssalb, disort_pmom, output->atm.microphys.temper[0][0], &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(rte_in->usrtau), &output->atm.nzout, rte_in->utau, &input.rte.nstr, &(rte_in->usrang), &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &(rte_in->fbeam), sdisort_beta, &(rte_in->nil), &(rte_in->umu0), &output->atm.phi0_r[iv], &(rte_in->newgeo), output->atm.zd, &(rte_in->spher), &input.r_earth, &(rte_in->fisot), &output->alb.albedo_r[iv], &(rte_in->btemp), &(rte_in->ttemp), &(rte_in->temis), &input.rte.deltam, &(rte_in->planck), &(rte_in->onlyfl), &(rte_in->accur), &(rte_in->quiet), rte_in->ierror_s, rte_in->prndis, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.nstr, &input.rte.maxphi, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, disort_uu, disort_u0u, &input.rte.sdisort[SDISORT_NSCAT], rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup, &input.rte.sdisort[SDISORT_NREFRAC], &input.rte.sdisort[SDISORT_ICHAPMAN], output->atm.microphys.refind[iv], &output->atm.microphys.nsza_denstab, output->atm.microphys.sza_denstab, sdisort_sig, tosdisort_denstab, output->dtauc_md); /* convert temporary Fortran arrays to permanent result */ fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u); fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu); free (sdisort_beta); free (disort_pmom); free (disort_u0u); free (disort_uu); break; case SOLVER_SPSDISORT: if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (dcheck, DCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) { fprintf (stderr, "Error %d returned by dcheck in %s (%s)\n", status, function_name, file_name); return status; } } sdisort_beta = (float*)calloc (output->atm.nlyr + 1, sizeof (float)); disort_pmom = c2fortran_3D_float_ary (output->atm.nlyr, 1, input.rte.nstr + 1, output->pmom); disort_u0u = (float*)calloc (output->atm.nzout * input.rte.maxumu, sizeof (float)); disort_uu = (float*)calloc (output->atm.nzout * input.rte.maxumu * input.rte.maxphi, sizeof (float)); F77_FUNC (spsdisort, SPSDISORT) (&output->atm.nlyr, output->dtauc, output->ssalb, disort_pmom, output->atm.microphys.temper[0][0], &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(rte_in->usrtau), &output->atm.nzout, rte_in->utau, &input.rte.nstr, &(rte_in->usrang), &input.rte.numu, input.rte.umu, &input.rte.nphi, input.rte.phi, &(rte_in->fbeam), sdisort_beta, &(rte_in->nil), &(rte_in->umu0), &output->atm.phi0_r[iv], &(rte_in->newgeo), output->atm.zd, &(rte_in->spher), &input.r_earth, &(rte_in->fisot), &output->alb.albedo_r[iv], &(rte_in->btemp), &(rte_in->ttemp), &(rte_in->temis), &input.rte.deltam, &(rte_in->planck), &(rte_in->onlyfl), &(rte_in->accur), &(rte_in->quiet), rte_in->ierror_s, rte_in->prndis, rte_in->header, &output->atm.nlyr, &output->atm.nzout, &input.rte.maxumu, &input.rte.nstr, &input.rte.maxphi, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->dfdt, rte_out->uavg, disort_uu, disort_u0u, rte_out->uavgdn, rte_out->uavgso, rte_out->uavgup); /* convert temporary Fortran arrays to permanent result */ fortran2c_2D_float_ary_noalloc (output->atm.nzout, input.rte.maxumu, disort_u0u, rte_out->u0u); fortran2c_3D_float_ary_noalloc (input.rte.maxphi, output->atm.nzout, input.rte.maxumu, disort_uu, rte_out->uu); free (sdisort_beta); free (disort_pmom); free (disort_u0u); free (disort_uu); break; case SOLVER_FTWOSTR: if (iv == output->wl.nlambda_rte_lower && ib == 0) { status = F77_FUNC (tcheck, TCHECK) (&output->atm.nlyr, &output->atm.nzout, &input.rte.nstr, &input.rte.numu, &input.rte.nphi, &input.optimize_fortran, &input.optimize_delta); if (status != 0) return status; } twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) twostr_gg[lu] = output->pmom[lu][0][1]; /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } F77_FUNC (twostr, TWOSTR) (&output->alb.albedo_r[iv], &(rte_in->btemp), &input.rte.deltam, output->dtauc, &(rte_in->fbeam), &(rte_in->fisot), twostr_gg, rte_in->header, rte_in->ierror_t, &output->atm.nlyr, &output->atm.nzout, &(rte_in->newgeo), &output->atm.nlyr, &(rte_in->planck), &output->atm.nzout, rte_in->prntwo, &(rte_in->quiet), &input.r_earth, &(rte_in->spher), output->ssalb, &(rte_in->temis), output->atm.microphys.temper[0][0], &(rte_in->ttemp), &(rte_in->umu0), &(rte_in->usrtau), rte_in->utau, &(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), output->atm.zd, rte_out->dfdt, rte_out->flup, rte_out->rfldir, rte_out->rfldn, rte_out->uavg); free (twostr_gg); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; case SOLVER_TWOSTR: twostr_ds.nlyr = output->atm.nlyr; twostr_ds.ntau = output->atm.nzout; twostr_ds.flag.planck = rte_in->planck; twostr_ds.flag.quiet = rte_in->quiet; twostr_ds.flag.spher = rte_in->spher; /* twostr_ds.flag.spher = input.rte.pseudospherical; */ twostr_ds.flag.usrtau = rte_in->usrtau; c_twostr_state_alloc (&twostr_ds); c_twostr_out_alloc (&twostr_ds, &twostr_out); c_twostr_gg = (double*)calloc (output->atm.nlyr, sizeof (double)); for (lu = 0; lu < output->atm.nlyr; lu++) { c_twostr_gg[lu] = (double)output->pmom[lu][0][1]; twostr_ds.dtauc[lu] = (double)output->dtauc[lu]; twostr_ds.ssalb[lu] = (double)output->ssalb[lu]; } for (lu = 0; lu < output->atm.nzout; lu++) { twostr_ds.utau[lu] = (double)rte_in->utau[lu]; } for (lu = 0; lu <= output->atm.nlyr; lu++) { twostr_ds.zd[lu] = (double)output->atm.zd[lu]; if (rte_in->planck) twostr_ds.temper[lu] = (double)output->atm.microphys.temper[0][0][lu]; } twostr_ds.bc.albedo = (double)output->alb.albedo_r[iv]; twostr_ds.bc.btemp = (double)rte_in->btemp; twostr_ds.bc.fbeam = (double)rte_in->fbeam; twostr_ds.bc.fisot = (double)rte_in->fisot; twostr_ds.bc.temis = (double)rte_in->temis; twostr_ds.bc.ttemp = (double)rte_in->ttemp; twostr_ds.bc.umu0 = (double)rte_in->umu0; twostr_ds.flag.prnt[0] = rte_in->prntwo[0]; twostr_ds.flag.prnt[1] = rte_in->prntwo[1]; twostr_ds.wvnmlo = output->wl.wvnmlo_r[iv]; twostr_ds.wvnmhi = output->wl.wvnmhi_r[iv]; /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } c_twostr (&twostr_ds, &twostr_out, input.rte.deltam, c_twostr_gg, rte_in->ierror_t, c_r_earth); for (lu = 0; lu < output->atm.nzout; lu++) { rte_out->dfdt[lu] = (float)twostr_out.rad[lu].dfdt; rte_out->rfldir[lu] = (float)twostr_out.rad[lu].rfldir; rte_out->rfldn[lu] = (float)twostr_out.rad[lu].rfldn; rte_out->flup[lu] = (float)twostr_out.rad[lu].flup; rte_out->uavg[lu] = (float)twostr_out.rad[lu].uavg; } free (c_twostr_gg); free (c_zd); c_twostr_state_free (&twostr_ds); c_twostr_out_free (&twostr_ds, &twostr_out); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; case SOLVER_RODENTS: /* ulrike, Robert Buras' two-stream model */ if (input.tipa == TIPA_DIR) /* BCA this should be somewhere else */ /* for tipa_dir, delta-scaling is not yet implemented!!! */ rodents_delta_method = RODENTS_DELTA_METHOD_OFF; else /* test showed that f=g*g is better than f=p2; master thesis to improve this! */ rodents_delta_method = RODENTS_DELTA_METHOD_HG; twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) twostr_gg[lu] = output->pmom[lu][0][1]; twostr_ff = (float*)calloc (output->atm.nlyr, sizeof (float)); if (rodents_delta_method == RODENTS_DELTA_METHOD_ON) /* use second moment for delta-scaling */ /* BCA this should be somewhere else */ for (lu = 0; lu < output->atm.nlyr; lu++) twostr_ff[lu] = output->pmom[lu][0][2]; else /* f is set to zero, and evtl set to g*g internally */ for (lu = 0; lu < output->atm.nlyr; lu++) twostr_ff[lu] = 0.0; /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } status = rodents (/* INPUT */ output->atm.nlyr, output->dtauc, output->ssalb, twostr_gg, twostr_ff, rodents_delta_method, output->atm.microphys.temper[0][0], output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], rte_in->usrtau, output->atm.nzout, rte_in->utau, rte_in->fbeam, rte_in->umu0, output->alb.albedo_r[iv], rte_in->btemp, rte_in->planck, /* NECESSARY FOR TIPA DIR */ input.tipa, /* if ==2, then tipa dir */ output->tausol, /* OUTPUT */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by rodents()\n", status); return status; } free (twostr_gg); free (twostr_ff); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END of rodents */ case SOLVER_TWOSTREBE: /* ulrike 22.06.2010, Bernhard Mayers twostream*/ twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) twostr_gg[lu] = output->pmom[lu][0][1]; /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } status = twostrebe (output->dtauc, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb, /* omega_0 */ twostr_gg, /* g (rodents) = g_org (twostrebe) */ output->atm.nlyr + 1, /* nlev */ rte_in->fbeam, /* S_0 */ rte_in->umu0, /* mu_0 */ output->alb.albedo_r[iv], /* surface albedo */ rte_in->planck, /* whether to use planck */ input.rte.deltam, /* delta scaling */ output->atm.nzout, /* nzout */ output->atm.zd, /* z-levels */ output->atm.microphys.temper[0][0], rte_in->btemp, /* surface temperature */ output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], input.atm.zout_sur, /* zout's (in km) */ /* output */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by twostrebe()\n", status); return status; } free (twostr_gg); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END twostrebe */ case SOLVER_TWOMAXRND: /* Bernhard Mayer, 7.7.2016, Nina Crnivec twostream with Maximum Random Overlap */ twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float)); twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) { twostr_gg[lu] = output->pmom[lu][0][1]; twostr_gg_clr[lu] = output->pmom01_clr[lu]; } /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } twostr_cf = calloc (output->atm.nlyr, sizeof (float)); if (output->cf.nlev != 0) { if (output->atm.nlyr != output->cf.nlev) { fprintf (stderr, "Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\n", output->cf.nlev + 1, output->atm.nlyr + 1); return -1; } else { for (lu = 0; lu < output->atm.nlyr; lu++) twostr_cf[lu] = output->cf.cf[lu]; } } status = twomaxrnd (output->dtauc, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb, /* omega_0 */ twostr_gg, /* g (rodents) = g_org (twostrebe) */ output->dtauc_clr, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_clr, /* omega_0 */ twostr_gg_clr, /* g (rodents) = g_org (twostrebe) */ twostr_cf, /* cloud fraction */ output->atm.nlyr + 1, /* nlev */ rte_in->fbeam, /* S_0 */ rte_in->umu0, /* mu_0 */ output->alb.albedo_r[iv], /* surface albedo */ rte_in->planck, /* whether to use planck */ input.rte.deltam, /* delta scaling */ output->atm.nzout, /* nzout */ output->atm.zd, /* z-levels */ output->atm.microphys.temper[0][0], rte_in->btemp, /* surface temperature */ output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], input.atm.zout_sur, /* zout's (in km) */ /* output */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by twomaxrnd()\n", status); return status; } free (twostr_gg); free (twostr_gg_clr); free (twostr_cf); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END twomaxrnd */ case SOLVER_DYNAMIC_TWOSTREAM: /* Bernhard Mayer, 23.7.2020, Richard Maier, dynamic twostream */ twostr_gg = (float*)calloc (output->atm.nlyr, sizeof (float)); twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) { twostr_gg[lu] = output->pmom[lu][0][1]; twostr_gg_clr[lu] = output->pmom01_clr[lu]; } /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } twostr_cf = calloc (output->atm.nlyr, sizeof (float)); if (output->cf.nlev != 0) { if (output->atm.nlyr != output->cf.nlev) { fprintf (stderr, "Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\n", output->cf.nlev, output->atm.nlyr + 1); return -1; } else { for (lu = 0; lu < output->atm.nlyr; lu++) twostr_cf[lu] = output->cf.cf[lu]; } } status = dynamic_twostream (input.rte.dynamic_iterations, /* number of iterations */ output->dtauc, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb, /* omega_0 */ twostr_gg, /* g (rodents) = g_org (twostrebe) */ output->dtauc_clr, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_clr, /* omega_0 */ twostr_gg_clr, /* g (rodents) = g_org (twostrebe) */ twostr_cf, /* cloud fraction */ output->atm.nlyr + 1, /* nlev */ rte_in->fbeam, /* S_0 */ rte_in->umu0, /* mu_0 */ output->alb.albedo_r[iv], /* surface albedo */ rte_in->planck, /* whether to use planck */ input.rte.deltam, /* delta scaling */ output->atm.nzout, /* nzout */ output->atm.zd, /* z-levels */ output->atm.microphys.temper[0][0], rte_in->btemp, /* surface temperature */ output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], input.atm.zout_sur, /* zout's (in km) */ /* output */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by dynamic_twostream()\n", status); return status; } free (twostr_gg); free (twostr_gg_clr); free (twostr_cf); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END dynamic_twostream */ case SOLVER_DYNAMIC_TENSTREAM: /* Bernhard Mayer, 6.12.2020, Richard Maier, dynamic tenstream */ twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) twostr_gg_clr[lu] = output->pmom01_clr[lu]; /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } status = dynamic_tenstream (input.rte.dynamic_iterations, /* number of iterations */ output->caoth3d, input.n_caoth + 2, output->dtauc_clr, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_clr, /* omega_0 */ twostr_gg_clr, /* g (rodents) = g_org (twostrebe) */ output->atm.nlyr + 1, /* nlev */ rte_in->fbeam, /* S_0 */ rte_in->umu0, /* mu_0 */ output->alb.albedo_r[iv], /* surface albedo */ rte_in->planck, /* whether to use planck */ input.rte.deltam, /* delta scaling */ output->atm.nzout, /* nzout */ output->atm.zd, /* z-levels */ output->atm.microphys.temper[0][0], rte_in->btemp, /* surface temperature */ output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], input.atm.zout_sur, /* zout's (in km) */ /* output */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by dynamic_tenstream()\n", status); return status; } free (twostr_gg); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END dynamic_tenstream */ case SOLVER_TWOMAXRND3C: /* Bernhard Mayer, 11.4.2018, Nina Crnivec twostream with Maximum Random Overlap and tripleclouds */ twostr_gg_cldk = (float*)calloc (output->atm.nlyr, sizeof (float)); twostr_gg_cldn = (float*)calloc (output->atm.nlyr, sizeof (float)); twostr_gg_clr = (float*)calloc (output->atm.nlyr, sizeof (float)); for (lu = 0; lu < output->atm.nlyr; lu++) { twostr_gg_cldk[lu] = output->pmom01_cldk[lu]; twostr_gg_cldn[lu] = output->pmom01_cldn[lu]; twostr_gg_clr[lu] = output->pmom01_clr[lu]; } /* ??? no need for thermal below 2um; ??? */ /* ??? need to do that to avoid numerical underflow; ??? */ /* ??? however, this could be done without actually ??? */ /* ??? calling the solver ??? */ if (rte_in->planck && output->wl.lambda_r[iv] < 2000.0) { rte_in->planck = 0; planck_tempoff = 1; } twostr_cf = calloc (output->atm.nlyr, sizeof (float)); if (output->cf.nlev != 0) { if (output->atm.nlyr != output->cf.nlev) { fprintf (stderr, "Fatal error! Cloud fraction grid different from atmospheric grid. %d levels vs. %d levels\n", output->cf.nlev, output->atm.nlyr + 1); return -1; } else { for (lu = 0; lu < output->atm.nlyr; lu++) twostr_cf[lu] = output->cf.cf[lu]; } } #if HAVE_TWOMAXRND3C status = twomaxrnd3C (output->dtauc_cldk, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_cldk, /* omega_0 */ twostr_gg_cldk, /* g (rodents) = g_org (twostrebe) */ output->dtauc_cldn, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_cldn, /* omega_0 */ twostr_gg_cldn, /* g (rodents) = g_org (twostrebe) */ output->dtauc_clr, /* dtau (rodents) = dtau_org (twostrebe) */ output->ssalb_clr, /* omega_0 */ twostr_gg_clr, /* g (rodents) = g_org (twostrebe) */ twostr_cf, /* cloud fraction */ input.rte.twomaxrnd3C_scale_cf, output->atm.nlyr + 1, /* nlev */ rte_in->fbeam, /* S_0 */ rte_in->umu0, /* mu_0 */ output->alb.albedo_r[iv], /* surface albedo */ rte_in->planck, /* whether to use planck */ input.rte.deltam, /* delta scaling */ output->atm.nzout, /* nzout */ output->atm.zd, /* z-levels */ output->atm.microphys.temper[0][0], rte_in->btemp, /* surface temperature */ output->wl.wvnmlo_r[iv], output->wl.wvnmhi_r[iv], input.atm.zout_sur, /* zout's (in km) */ /* output */ rte_out->rfldn, /* e_minus */ rte_out->flup, /* e_plus */ rte_out->rfldir, /* s_direct */ rte_out->uavg); /* KST ???? */ if (status != 0) { fprintf (stderr, "Error %d returned by twomaxrnd3C()\n", status); return status; } #else fprintf (stderr, "Error: twomaxrnd3C solver not included in uvspec build.\n"); return -1; #endif free (twostr_gg_cldk); free (twostr_gg_cldn); free (twostr_gg_clr); free (twostr_cf); for (lev = 0; lev < output->atm.nzout; lev++) { rte_out->uavgso[lev] = NAN; rte_out->uavgdn[lev] = NAN; rte_out->uavgup[lev] = NAN; } if (planck_tempoff) { rte_in->planck = 1; planck_tempoff = 0; } break; /* END twomaxrnd3C */ case SOLVER_SOS: #if HAVE_SOS ASCII_calloc_float (&pmom_sos, output->atm.nlyr, output->atm.nmom + 1); for (lu = 0; lu < output->atm.nlyr; lu++) for (k = 0; k < output->atm.nmom + 1; k++) pmom_sos[lu][k] = output->pmom[lu][0][k]; status = sos (output->atm.nlyr, rte_in->newgeo, input.rte.nstr, input.rte.sos_nscat, output->alb.albedo_r[iv], input.r_earth, output->atm.zd, output->ssalb, pmom_sos, output->dtauc, output->atm.sza_r[iv], output->atm.nzout, input.rte.numu, input.rte.umu, rte_in->utau, rte_out->rfldir, rte_out->rfldn, rte_out->flup, rte_out->uavgso, rte_out->uavgdn, rte_out->uavgup, rte_out->u0u); if (status != 0) { fprintf (stderr, "Error %d returned by sos()\n", status); return status; } break; #else fprintf (stderr, "Error: sos solver not included in uvspec build.\n"); fprintf (stderr, "Error: Please contact arve.kylling@gmail.com\n"); return -1; #endif case SOLVER_SSLIDAR: /* NOTE! Lidar only uses one umu!!! */ phase_back = calloc ((size_t)output->atm.nlyr, sizeof (double*)); for (lu = 0; lu < output->atm.nlyr; lu++) phase_back[lu] = calloc ((size_t)output->nphamat, sizeof (double)); /* this only works because mu[0] = -1.0 */ for (lu = 0; lu < output->atm.nlyr; lu++) for (is = 0; is < output->nphamat; is++) phase_back[lu][is] = output->phase[lu][is][0]; status = ss_lidar (/* input: atmosphere */ output->atm.nlyr, output->atm.zd, /* z-levels */ output->alt.altitude, output->dtauc, /* optical depth */ output->ssalb, /* omega_0 */ phase_back, /* phase function in backward direction */ output->alb.albedo_r[iv], /* albedo (rodents) = Ag (twostrebe) */ /* input: lidar */ output->wl.lambda_r[iv], /* lidar wavelength */ input.sslidar[SSLIDAR_E0], input.sslidar[SSLIDAR_POSITION], input.rte.umu[0], /* only first umu is lidar direction */ input.sslidar_nranges, input.sslidar[SSLIDAR_RANGE], output->atm.zout_sur, /* ranges (in km) */ input.sslidar[SSLIDAR_EFF], input.sslidar[SSLIDAR_AREA], input.sslidar_polarisation, /* OUTPUT / RESULT */ rte_out->sslidar_nphot, rte_out->sslidar_nphot_q, rte_out->sslidar_ratio); if (status != 0) { fprintf (stderr, "Error %d returned by ss_lidar()\n", status); return status; } for (lu = 0; lu < output->atm.nlyr; lu++) free (phase_back[lu]); free (phase_back); break; case SOLVER_NULL: /* do nothing */ break; default: fprintf (stderr, "Error: RTE solver %d not yet implemented, call_solver (solve_rte.c)\n", input.rte.solver); return -1; } if (verbose) { end = clock(); fprintf (stderr, "*** last solver call: %f seconds\n", ((double)(end - start)) / CLOCKS_PER_SEC); } return 0; /* if o.k. */ } static int init_rte_input (rte_input* rte, input_struct input, output_struct* output) { int i = 0, found = 0; int ip = 0, is = 0, lu = 0; int status = 0; strcpy (rte->header, ""); rte->accur = 1.0e-5; switch (input.source) { case SRC_NONE: case SRC_BLITZ: case SRC_LIDAR: rte->planck = 0; rte->fbeam = 0.0; rte->fisot = 0.0; break; case SRC_SOLAR: rte->planck = 0; if (input.rte.fisot > 0) { rte->fbeam = 0.0; rte->fisot = 1.0; } else { rte->fbeam = 1.0; rte->fisot = 0.0; } break; case SRC_THERMAL: rte->planck = 1; rte->fbeam = 0.0; rte->fisot = 0.0; rte->btemp = output->surface_temperature; rte->ttemp = output->atm.microphys.temper[0][0][0]; rte->temis = 0.0; break; default: fprintf (stderr, "Error, unknown source\n"); return -1; } rte->umu0 = 0.0; rte->ierror_d[0] = 0; rte->ierror_s[0] = 0; rte->ierror_t[0] = 0; for (i = 0; i < 7; i++) rte->prndis[i] = 0; for (i = 0; i < 5; i++) rte->prndis2[i] = 0; for (i = 0; i < 2; i++) rte->prntwo[i] = 0; rte->ibcnd = input.rte.ibcnd; rte->lamber = 1; rte->newgeo = 1; rte->nil = 0; rte->onlyfl = 1; rte->quiet = input.quiet; rte->usrang = 0; rte->usrtau = 1; if (input.rte.pseudospherical || input.rte.solver == SOLVER_SDISORT || input.rte.solver == SOLVER_SPSDISORT) /* these solvers are spherical by default */ rte->spher = 1; else rte->spher = 0; rte->hl = (float*)calloc (input.rte.maxumu + 1, sizeof (float)); rte->utau = (float*)calloc (output->atm.nzout, sizeof (float)); if (input.rte.numu > 0) { rte->onlyfl = 0; rte->usrang = 1; } /* PolRadtran */ rte->pol.deltam = "Y"; rte->pol.ground_type = "L"; strcpy (rte->pol.polscat, ""); rte->pol.albedo = 0.0; rte->pol.btemp = 0.0; rte->pol.flux = 1.0; rte->pol.gas_extinct = NULL; rte->pol.height = NULL; rte->pol.mu = 1.0; rte->pol.sky_temp = 0.0; rte->pol.temperatures = NULL; rte->pol.wavelength = 0.0; rte->pol.outlevels = NULL; rte->pol.nummu = 0; rte->pol.ground_index.re = 0.0; rte->pol.ground_index.im = 0.0; /* get the indices of the zout levels in the z-scale */ rte->pol.outlevels = (int*)calloc (output->atm.nzout, sizeof (int)); found = 0; for (i = 0; i < output->atm.nzout; i++) for (lu = 0; lu < output->atm.nlev; lu++) { if (fabs (output->atm.zout_sur[i] - output->atm.zd[lu]) <= 0) { rte->pol.outlevels[found++] = lu + 1; break; } } switch (input.rte.solver) { case SOLVER_MONTECARLO: /* set number of photons */ output->mc_photons = input.rte.mc.photons; break; case SOLVER_SDISORT: case SOLVER_SPSDISORT: case SOLVER_FDISORT1: case SOLVER_SSS: case SOLVER_SSSI: case SOLVER_TZS: for (ip = 0; ip < input.rte.nprndis; ip++) (rte->prndis)[input.rte.prndis[ip] - 1] = 1; break; case SOLVER_DISORT: case SOLVER_FDISORT2: for (ip = 0; ip < input.rte.nprndis; ip++) (rte->prndis2)[input.rte.prndis[ip] - 1] = 1; break; case SOLVER_POLRADTRAN: /* Need to do a little checking of polradtran specific input stuff here...*/ if (found != output->atm.nzout) { fprintf (stderr, "*** zout does not correspond to atmosphere file levels.\n"); fprintf (stderr, "*** zout must do so for the polradtran solver.\n"); status--; } if (input.rte.deltam == 0) rte->pol.deltam = "N"; else if (input.rte.deltam == 1) rte->pol.deltam = "Y"; if ((output->mu_values = (float*)calloc (input.rte.nstr / 2 + input.rte.numu, sizeof (float))) == NULL) return -1; if (strncmp (input.rte.pol_quad_type, "E", 1) == 0) for (i = 0; i < input.rte.numu; i++) output->mu_values[input.rte.nstr / 2 + i] = input.rte.umu[i]; rte->pol.gas_extinct = (double*)calloc (output->atm.nlyr + 1, sizeof (double)); rte->pol.height = (double*)calloc (output->atm.nlyr + 1, sizeof (double)); rte->pol.temperatures = (double*)calloc (output->atm.nlyr + 1, sizeof (double)); output->atm.pol_scat_files = (char*)calloc (64 * output->atm.nlyr, sizeof (char)); for (is = 0; is < 64 * output->atm.nlyr; is++) output->atm.pol_scat_files[is] = ' '; for (lu = 0; lu < output->atm.nlyr; lu++) { is = lu * 64; if (lu > 998) return err_out ("nlyr must be < 999, or a sprintf buffer overflow would occur,fix this", output->atm.nlyr); sprintf (rte->pol.polscat, ".scat_file_%03d", lu); strcpy (&output->atm.pol_scat_files[is], rte->pol.polscat); } for (lu = 0; lu <= output->atm.nlyr; lu++) { rte->pol.height[lu] = (double)lu; /* Weird hey???? Well, the story goes as follows: polradtran wants extinction and scattering in terms of 1/(layerthickness). However, we feed it optical depth. Hence, we need to make delta_height of each layer equal one. One simple remedy is the one used. Arve 15.03.2000 */ rte->pol.temperatures[lu] = (double)output->atm.microphys.temper[0][0][lu]; } break; case SOLVER_TWOSTR: case SOLVER_FTWOSTR: for (ip = 0; ip < input.rte.nprndis; ip++) if (input.rte.prndis[ip] == 1 || input.rte.prndis[ip] == 2) (rte->prntwo)[input.rte.prndis[ip] - 1] = 1; break; case SOLVER_SOS: case SOLVER_NULL: case SOLVER_RODENTS: case SOLVER_TWOSTREBE: case SOLVER_TWOMAXRND: case SOLVER_TWOMAXRND3C: case SOLVER_DYNAMIC_TWOSTREAM: case SOLVER_DYNAMIC_TENSTREAM: case SOLVER_SSLIDAR: break; default: fprintf (stderr, "Error: RTE solver %d not yet implemented, init_rte_input (solve_rte.c)\n", input.rte.solver); return -1; break; } return status; } static void fourier2azimuth (double**** down_rad_rt3, double**** up_rad_rt3, double**** down_rad, double**** up_rad, int nzout, int aziorder, int nstr, int numu, int nstokes, int nphi, float* phi) { /* For each azimuth and polar angle sum the Fourier azimuth series appropriate for the particular Stokes parameter to produce the radiance. Only used for the polradtran solver */ int i = 0, j = 0, je = 0, k = 0, lu = 0, m = 0; double sumd = 0, sumu = 0; float phir; for (lu = 0; lu < nzout; lu++) { for (k = 0; k < nphi; k++) { phir = PI * phi[k] / 180.0; /* Up- and downwelling irradiances at user angles only*/ /* for (j=0;j<nstr/2+numu;j++) { */ for (j = 0; j < numu; j++) { je = j + nstr / 2; for (i = 0; i < nstokes; i++) { sumd = 0.0; sumu = 0.0; for (m = 0; m <= aziorder; m++) { if (i < 2) { sumd += cos (m * phir) * down_rad_rt3[lu][m][je][i]; sumu += cos (m * phir) * up_rad_rt3[lu][m][je][i]; } else { sumd += sin (m * phir) * down_rad_rt3[lu][m][je][i]; sumu += sin (m * phir) * up_rad_rt3[lu][m][je][i]; } } down_rad[lu][k][j][i] = sumd; up_rad[lu][k][j][i] = sumu; } } } } } /***************************************************************/ /* calc_spectral_heating calculates the divergence of the flux */ /* either by differences of the flux or */ /* with the help of the actinic flux */ /***************************************************************/ static int calc_spectral_heating (input_struct input, output_struct* output, float* dz, double* rho_mass_zout, float* k_abs, float* k_abs_layer, int* zout_index, rte_output* rte_out, float* heat, float* emis, float* w_zout, int iv) { int status = 0; int lz = NOT_DEFINED_INTEGER; int lc = NOT_DEFINED_INTEGER; int nzout = NOT_DEFINED_INTEGER; int nlev = NOT_DEFINED_INTEGER; int nlyr = NOT_DEFINED_INTEGER; /* float *Fup = NULL; */ /* float *Fdn = NULL; */ float* F_net = NULL; float dFdz = 0; float* c_p = 0; float* dtheta_dz_layer = NULL; float* dtheta_dz = NULL; float* dFdz_array = NULL; int lz1 = NOT_DEFINED_INTEGER, lz2 = NOT_DEFINED_INTEGER, n_lz = NOT_DEFINED_INTEGER; float M_AIR = MOL_MASS_AIR / 1000.0; /* molecular weight of air (kg mol-1) */ float planck_radiance = 0.0; float* z_center = NULL; float* zout_in_m = NULL; int outside = 0; int start = 0; /* int additional_verbose_output=FALSE; */ nlev = output->atm.nlev; nlyr = nlev - 1; nzout = output->atm.nzout; /* center heights of the atmosphere layers in m */ if (((z_center) = (float*)calloc (nlyr, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'z_center'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } for (lc = 0; lc < nlyr; lc++) z_center[lc] = output->atm.zd[lc] * 1000.0 - dz[lc] / 2; /* 1000 == km -> m */ /* zout_in_m == levels (layer boundaries) of zout levels in m above surface */ if (((zout_in_m) = (float*)calloc (nzout, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'zout_in_m'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } for (lz = 0; lz < nzout; lz++) { zout_in_m[lz] = output->atm.zout_sur[lz] * 1000.0; /* 1000 == km -> m */ /* if (iv == 0) fprintf(stderr,"zout in metern %3d = %10.3f\n", lz, zout_in_m[lz] ); */ } if (((dtheta_dz) = (float*)calloc (nzout, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'dtheta_dz'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } /* calculate normalized (1/incident_flux) spectral heating rate */ switch (input.heating) { case HEAT_LAYER_CD: case HEAT_LAYER_FD: /* /\* additional verbose output *\/ */ /* if (additional_verbose_output) { */ /* if (((Fup) = (float *) calloc (nzout, sizeof(float))) == NULL) { */ /* fprintf (stderr, "Error allocating memory for (Fup) in %s (%s)\n", function_name, file_name); */ /* return -1; */ /* } */ /* if (((Fdn) = (float *) calloc (nzout, sizeof(float))) == NULL) { */ /* fprintf (stderr, "Error allocating memory for (Fdn) in %s (%s)\n", function_name, file_name); */ /* return -1; */ /* } */ /* } */ if (((F_net) = (float*)calloc (nzout, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'dF'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } if (((dFdz_array) = (float*)calloc (nzout, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'dFdz_array'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } if (((c_p) = (float*)calloc (nzout, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'c_p'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } switch (input.rte.solver) { case SOLVER_FDISORT1: case SOLVER_SDISORT: case SOLVER_FTWOSTR: case SOLVER_TWOSTR: case SOLVER_RODENTS: case SOLVER_TWOSTREBE: case SOLVER_TWOMAXRND: case SOLVER_TWOMAXRND3C: case SOLVER_DYNAMIC_TWOSTREAM: case SOLVER_DYNAMIC_TENSTREAM: case SOLVER_SOS: case SOLVER_MONTECARLO: case SOLVER_FDISORT2: case SOLVER_DISORT: case SOLVER_SPSDISORT: case SOLVER_TZS: case SOLVER_SSS: case SOLVER_SSSI: case SOLVER_NULL: for (lz = 0; lz < nzout; lz++) { /* if (additional_verbose_output) { */ /* Fdn[lz] = rte_out->rfldir[lz] + rte_out->rfldn[lz]; */ /* Fup[lz] = rte_out->flup[lz]; */ /* } */ F_net[lz] = (rte_out->rfldir[lz] + rte_out->rfldn[lz]) - rte_out->flup[lz]; } break; case SOLVER_POLRADTRAN: for (lz = 0; lz < nzout; lz++) { /* if (additional_verbose_output) { */ /* Fdn[lz] = rte_out->polradtran_down_flux[lz][0]; */ /* Fup[lz] = rte_out->polradtran_up_flux[lz][0]; */ /* } */ F_net[lz] = rte_out->polradtran_down_flux[lz][0] - rte_out->polradtran_up_flux[lz][0]; } break; default: fprintf (stderr, "Error: unknown solver id number %d\n", input.rte.solver); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; break; } if (input.heating == HEAT_LAYER_CD) n_lz = nzout; if (input.heating == HEAT_LAYER_FD) n_lz = nzout - 1; for (lz = 0; lz < n_lz; lz++) { if (input.heating == HEAT_LAYER_CD) { if (lz == 0) { lz1 = lz; lz2 = lz + 1; } else if (lz == output->atm.nzout - 1) { lz1 = lz - 1; lz2 = lz; } else { lz1 = lz - 1; lz2 = lz + 1; } if (lz != 0 && lz != output->atm.nzout - 1) { /* centered difference */ /* 1.0e+6: convert from cm-3 to m-3 */ rho_mass_zout[lz] = output->atm.microphys.dens_zout[MOL_AIR][lz] * 1.0e+6 * M_AIR / AVOGADRO; /* mass weighted mean of specific heating rates */ c_p[lz] = output->atm.microphys.c_p[lz]; } else { /* boundary, no centered difference possible, (log) average density for forward difference */ rho_mass_zout[lz] = log_average (output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]) * 1.0e+6 * M_AIR / AVOGADRO; /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */ c_p[lz] = mass_weighted_average (output->atm.microphys.c_p[lz1], output->atm.microphys.c_p[lz2], output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]); } } else if (input.heating == HEAT_LAYER_FD) { /* forward difference */ lz1 = lz; lz2 = lz + 1; /* effective density for one layer (logarithmic) */ /* 1.0e+6: convert from cm-3 to m-3 */ rho_mass_zout[lz] = log_average (output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]) * 1.0e+6 * M_AIR / AVOGADRO; /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */ c_p[lz] = mass_weighted_average (output->atm.microphys.c_p[lz1], output->atm.microphys.c_p[lz2], output->atm.microphys.dens_zout[MOL_AIR][lz1], output->atm.microphys.dens_zout[MOL_AIR][lz2]); } else { fprintf (stderr, "Error, unknown processing scheme %d\n", input.processing); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); } /* Compute the derivative dF/dz using a two-point formula */ if (fabs ((F_net[lz1] - F_net[lz2]) / F_net[lz1]) > 1.0E-6 || fabs ((output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2]) * rho_mass_zout[lz]) > 1.0E-6) { dFdz = (F_net[lz1] - F_net[lz2]) / (output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2]); } else dFdz = NAN; dFdz_array[lz] = 0.001 * dFdz; /* 1/1000 = km -> m, for dz */ /* if (additional_verbose_output) { */ /* if (lz==0) { */ /* fprintf (stderr, " ... calling calc_spectral_heating()\n"); */ /* if (input.heating == HEAT_LAYER_CD) fprintf (stderr, " ... calculate heating_rate with centered differences \n"); */ /* if (input.heating == HEAT_LAYER_FD) fprintf (stderr, " ... calculate heating_rate with forward differences \n"); */ /* fprintf (stderr, "\n#--------------------------------------------------------------------------------------------------------------------------------\n"); */ /* fprintf (stderr, "#lvl z l1 l2 z(l1) z(l2) E(l1) E(l2) dE/dz |dE/E| Edn Eup Edn/dz Eup/dz \n"); */ /* fprintf (stderr, "# km km km W/m2 W/m2 W/(m2 m) W/m2 W/m2 W/(m2 km) W/(m2 km) \n"); */ /* fprintf (stderr, "#----------------------------------------------------------------------------------------------------------------------------------\n"); */ /* } */ /* fprintf (stderr, "%3d %9.3f %3d %3d %8.3f %8.3f %9.4f %9.4f %12.5e %10.5e %9.4f %9.4f %12.5e %12.5e\n", */ /* lz, output->atm.zout_sur[lz], lz1, lz2, output->atm.zout_sur[lz1],output->atm.zout_sur[lz2], */ /* F_net[lz1],F_net[lz2],dFdz_array[lz],fabs((F_net[lz1]-F_net[lz2])/F_net[lz1]),Fdn[lz],Fup[lz], */ /* (Fdn[lz1]-Fdn[lz2])/(output->atm.zout_sur[lz1]-output->atm.zout_sur[lz2]),(Fup[lz1]-Fup[lz2])/(output->atm.zout_sur[lz1]-output->atm.zout_sur[lz2])); */ /* } */ heat[lz] = dFdz_array[lz] / (rho_mass_zout[lz] * c_p[lz]); /* calculate dtheta_dz from zout-levels */ dtheta_dz[lz] = (output->atm.microphys.theta_zout[lz1] - output->atm.microphys.theta_zout[lz2]) / (1000.0 * (output->atm.zout_sur[lz1] - output->atm.zout_sur[lz2])); w_zout[lz] = (output->atm.microphys.theta_zout[lz] / output->atm.microphys.temper_zout[lz]) * 1.0 / dtheta_dz[lz] * heat[lz]; } /* if (additional_verbose_output) { */ /* free(Fup); */ /* free(Fdn); */ /* } */ free (F_net); free (dFdz_array); free (c_p); break; case HEAT_LOCAL: /* spline interpolation of all level EXEPT LOWEST AND HIGHEST LEVEL */ /* they are outside of the range of layer midpoints and must therefor be extrapolated !!!! */ if (((dtheta_dz_layer) = (float*)calloc (nlyr, sizeof (float))) == NULL) { fprintf (stderr, "Error allocating memory for 'dtheta_dz_layer'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } outside = 0; /* k_abs_layer == absorption coefficient representative for one layer (layer midpoint is z_center) */ for (lc = 0; lc < nlyr; lc++) { k_abs_layer[lc] = (1.0 - output->ssalb[lc]) * output->dtauc[lc] / dz[lc]; dtheta_dz_layer[lc] = (output->atm.microphys.theta[lc + 1] - output->atm.microphys.theta[lc]) / ((output->atm.zd[lc + 1] - output->atm.zd[lc]) * 1000.0); } /* if uppermost zout level is above the uppermost layer midpoint (e.g. zout TOA), */ /* than extrapolate k_abs from the uppermost 2 layers */ if (zout_in_m[nzout - 1] > z_center[0]) { outside = 1; /* exponentiell extrapolation, as linear might cause negative values */ if (k_abs_layer[1] != 0.0) k_abs[nzout - 1] = k_abs_layer[0] * pow (k_abs_layer[0] / k_abs_layer[1], dz[0] / ((output->atm.zd[0] - output->atm.zd[2]) * 1000.0)); else /* if not possible, take value from the last layer, in most cases also 0.0 */ k_abs[nzout - 1] = k_abs_layer[0]; /* first difference */ dtheta_dz[nzout - 1] = dtheta_dz_layer[0]; /* zout is sorted ascending, z_atm descending */ } /* if lowermost zout level is below the lowest layer midpoint (e.g. zout surface), */ /* than extrapolate k_abs from the lowermost 2 layers */ if (zout_in_m[0] < z_center[nlyr - 1]) { outside = outside + 1; start = 1; /* linear extrapolation */ k_abs[0] = k_abs_layer[nlyr - 1] - dz[nlyr - 1] * (k_abs_layer[nlyr - 1] - k_abs_layer[nlyr - 2]) / ((output->atm.zd[nlyr] - output->atm.zd[nlyr - 2]) * 1000.0); /* 1000 = km -> m */ /* canceled 2/2 in (dz/2)/((z[2]-z[0])/2) */ /* last difference */ dtheta_dz[0] = dtheta_dz_layer[nlyr - 1]; /* zout is sorted ascending, z_atm descending */ } /* interpolate the rest, attention pointer arithmetic, last argument 1 means descending order of z_center */ /* in versions before Jan 2008 also INTERP_METHOD_SPLINE was tested */ /* but this caused overshootings, if clouds are present. */ /* thereforwe use linear PLUS additional levels around the zout level, UH Feb 2008 */ status = arb_wvn (nlyr, z_center, k_abs_layer, nzout - outside, zout_in_m + start, k_abs + start, INTERP_METHOD_LINEAR, 1); if (status != 0) { fprintf (stderr, " Error, interpolation of 'k_abs'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } /* interpolate the rest, attention pointer arithmetic, last argument 1 means descending order of z_center */ status = arb_wvn (nlyr, z_center, dtheta_dz_layer, nzout - outside, zout_in_m + start, dtheta_dz + start, INTERP_METHOD_LINEAR, 1); if (status != 0) { fprintf (stderr, " Error, interpolation of 'dtheta_dz'\n"); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } for (lz = 0; lz < nzout; lz++) { /* level (local) property */ /* 1.0e+6: convert from cm-3 to m-3 */ rho_mass_zout[lz] = output->atm.microphys.dens_zout[MOL_AIR][lz] * 1.0e+6 * M_AIR / AVOGADRO; /* correction of the emission term of the heating rate, when calculated with actinic flux */ if (input.source == SRC_THERMAL) { F77_FUNC (cplkavg, CPLKAVG) (&(output->wl.wvnmlo_r[iv]), &(output->wl.wvnmhi_r[iv]), &(output->atm.microphys.temper_zout[lz]), &(planck_radiance)); } /* (else (in the solar case) planck_radiance == 0) */ heat[lz] = k_abs[lz] * 4.0 * PI * (rte_out->uavg[lz] - planck_radiance) / (rho_mass_zout[lz] * output->atm.microphys.c_p[lz]); emis[lz] = k_abs[lz] * 4.0 * PI * (-planck_radiance) / (rho_mass_zout[lz] * output->atm.microphys.c_p[lz]); w_zout[lz] = (output->atm.microphys.theta_zout[lz] / output->atm.microphys.temper_zout[lz]) * 1.0 / dtheta_dz[lz] * heat[lz]; } /* overwrite heating rate in case of dynamic twostream; in that case uavg contains dEnet */ if (input.rte.solver == SOLVER_DYNAMIC_TWOSTREAM || input.rte.solver == SOLVER_DYNAMIC_TENSTREAM) { if (!input.quiet) fprintf (stderr, " ... overwriting heating rate by uavg (dynamic_twostream special)\n"); for (lz = 0; lz < nzout - 1; lz++) { /* BM, 18.9.2020: copied from layer_fd above */ double rho_mass_tmp = log_average (output->atm.microphys.dens_zout[MOL_AIR][lz], output->atm.microphys.dens_zout[MOL_AIR][lz + 1]) * 1.0e+6 * M_AIR / AVOGADRO; /* mass weighted mean of specific heating rates, assuming exponential change of density and linear change of c_p */ double c_p_tmp = mass_weighted_average (output->atm.microphys.c_p[lz], output->atm.microphys.c_p[lz + 1], output->atm.microphys.dens_zout[MOL_AIR][lz], output->atm.microphys.dens_zout[MOL_AIR][lz + 1]); // factor 1000.0 converts z from km to m heat[lz] = rte_out->uavg[lz] / (rho_mass_tmp * c_p_tmp) / (output->atm.zout_sur[lz + 1] - output->atm.zout_sur[lz]) / 1000.0; emis[lz] = NAN; } } break; default: fprintf (stderr, "Error, unknown processing scheme %d\n", input.processing); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return -1; } free (z_center); free (zout_in_m); free (dtheta_dz); return status; } static float*** calloc_abs3d (int Nx, int Ny, int Nz, int* threed) { int lc = 0, lx = 0; float*** tmp; tmp = calloc (Nz, sizeof (float**)); if (tmp == NULL) return NULL; for (lc = 0; lc < Nz; lc++) if (threed[lc]) { tmp[lc] = calloc (Nx, sizeof (float*)); if (tmp[lc] == NULL) return NULL; for (lx = 0; lx < Nx; lx++) { tmp[lc][lx] = calloc (Ny, sizeof (float)); if (tmp[lc][lx] == NULL) return NULL; } } return tmp; } static void free_abs3d (float*** abs3d, int Nx, int Ny, int Nz, int* threed) { int lc = 0, lx = 0; for (lc = 0; lc < Nz; lc++) if (threed[lc]) { for (lx = 0; lx < Nx; lx++) free (abs3d[lc][lx]); free (abs3d[lc]); } free (abs3d); } static float**** calloc_spectral_abs3d (int Nx, int Ny, int Nz, int nlambda, int* threed) { int lx = 0, ly = 0, lc = 0; float**** tmp = NULL; if ((tmp = (float****)calloc (Nz, sizeof (float***))) == NULL) return NULL; for (lc = 0; lc < Nz; lc++) { if (threed[lc]) { if ((tmp[lc] = (float***)calloc (Nx, sizeof (float**))) == NULL) return NULL; for (lx = 0; lx < Nx; lx++) { if ((tmp[lc][lx] = (float**)calloc (Ny, sizeof (float*))) == NULL) return NULL; for (ly = 0; ly < Ny; ly++) if ((tmp[lc][lx][ly] = (float*)calloc (nlambda, sizeof (float))) == NULL) return NULL; } } } return tmp; } /***********************************************************************************/ /* Function: generate_effective_cloud */ /* */ /* Description: */ /* * Generates an effective cloud assuming random overlap (as in ECHAM) */ /* given cloud profiles and cloud fraction. */ /* * save the effective cloud optical property on the wc-structure */ /* * ic-structure is set to 0.0, as wc-structure contrains both now */ /* */ /* Parameters (input/output): */ /* input uvspec input structure */ /* output uvspec output structure */ /* save_cloud unmodified cloud properties for given wavelength */ /* iv wavelength index */ /* iq subband index */ /* verbose flag for verbose output */ /* */ /* */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* */ /* Example: */ /* Files: solver_rte.c */ /* Known bugs: - */ /* Author: */ /* xxx 200x C. Emde Created */ /* */ /***********************************************************************************/ static int generate_effective_cloud (input_struct input, output_struct* output, save_optprop* save_cloud, int iv, int iq, int verbose) { int lc = 0, i = 0, isp = 0; float tauw = 0.0, taui = 0.0, taua = 0.0, taum = 0.0, taur = 0.0, tau_clear = 0.0, tau_cloud = 0.0; float g1d = 0.0, g2d = 0.0, fd = 0.0, g1i = 0.0, g2i = 0.0, fi = 0.0, gi = 0.0, gw = 0.0; float ssai = 0.0, ssaw = 0.0; float *ssa = NULL, *tau = NULL, *g = NULL; /* Reflectivity of underlying layer, should be zero, because here we calculate just the effective optical thickness of one layer. This optical thickness is used in the RTE solver, where then of course the reflectivity of the neighbour layers is considered. */ float pref = 0.0; /* Solar zenith angle */ float mu = 0.0; /* Effective solar zenith angle, accounts for the decrease of the direct solar beam and the corresponding increase of the diffuse part of the radiation (in ECHAM). Here always the solar zenith angle is used (see below). */ float mu_eff = 0.0; /* Diffusivity factor, 1.66 in ECHAM */ float r = 1.66; /* Effective cloudyness */ float C_eff = 0.0, product = 1.0; /* Output variables of swde */ float pre1 = 0.0, pre2 = 0.0, ptr2 = 0.0; /* Transmission of clear and cloudy parts and of the layer */ float transmission_clear = 0.0, transmission_cloud = 0.0, transmission_layer = 0.0; /* Variables for iteratiom */ float taueff = 0.0; /* cloud fraction to scale the optical thickness */ /* Attention: ECHAM input is already scaled to cloudy part */ float cf = 1.0; int first_verbose = TRUE; /* if ( input.cloud_overlap == CLOUD_OVERLAP_OFF ) { */ /* fprintf (stderr, "Error: call of %s, but cloud overlap schema is switched off\n", __func__ ); */ /* return -1; */ /* } */ if (verbose && output->cf.nlev > 0) { fprintf (stderr, " ... generate effective cloud\n"); } ssa = (float*)calloc (output->atm.nlev - 1, sizeof (float)); tau = (float*)calloc (output->atm.nlev - 1, sizeof (float)); g = (float*)calloc (output->atm.nlev - 1, sizeof (float)); mu = cos (output->atm.sza_r[iv] * PI / 180); /* scattering properties */ for (lc = 0; lc < output->atm.nlev - 1; lc++) { /* Ice and water clouds */ tauw = save_cloud->tauw[lc]; taui = save_cloud->taui[lc]; g1d = save_cloud->g1d[lc]; g2d = save_cloud->g2d[lc]; fd = save_cloud->fd[lc]; gw = g1d * fd + (1.0 - fd) * g2d; g1i = save_cloud->g1i[lc]; g2i = save_cloud->g2i[lc]; fi = save_cloud->fi[lc]; gi = g1i * fi + (1.0 - fi) * g2i; ssaw = save_cloud->ssaw[lc]; ssai = save_cloud->ssai[lc]; /* molecular absorption */ taum = output->atm.optprop.tau_molabs_r[0][0][lc][iv][iq]; /* aerosol */ taua = output->aer.optprop.dtau[iv][lc]; //20120816ak stuff below is not in use, commented // ssaa = output->aer.optprop.ssa[iv][lc]; // g1a = output->aer.optprop.g1[iv][lc]; // g2a = output->aer.optprop.g2[iv][lc]; // fa = output->aer.optprop.ff[iv][lc]; // ga = g1a*fa+(1.0-fa)*g2a; /*Rayleigh*/ switch (input.ck_scheme) { case CK_FU: taur = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][iq]; break; case CK_KATO: case CK_KATO2: case CK_KATO2_96: case CK_KATO2ANDWANDJI: case CK_AVHRR_KRATZ: case CK_FILE: case CK_LOWTRAN: case CK_CRS: case CK_REPTRAN: case CK_REPTRAN_CHANNEL: case CK_RAMAN: taur = output->atm.optprop.tau_rayleigh_r[0][0][lc][iv][0]; break; default: fprintf (stderr, "Error: unsupported correlated-k scheme %d\n", input.ck_scheme); return -1; break; } /* Calculate mean optical properties of the layer */ cf = 0.0; for (isp = 0; isp < input.n_caoth; isp++) if (input.caoth[isp].source == CAOTH_FROM_ECHAM || input.caoth[isp].source == CAOTH_FROM_1D) cf = 1.0; if (cf == 0.0) { /* else */ if (output->cf.cf[lc] != 0.0) cf = output->cf.cf[lc]; else cf = 1.0; } /* total optical thickness */ /* fprintf(stderr, " scaling tau: tauw = %f, taui = %f, cf = %f\n", tauw, taui, cf); */ tau_cloud = (tauw + taui) / cf; /* Water and Ice cloud */ tau_clear = taum + taua + taur; /* Molecular, Aerosol, and Rayleigh */ /* Calculate effective Cloudiness */ /* Total optical thickness */ tau[lc] = tau_cloud + tau_clear; if ((tauw || taui) != 0.0) { g[lc] = (tauw * ssaw * gw + taui * ssai * gi) / (tauw * ssaw + taui * ssai); /* effective single scattering albedo */ ssa[lc] = (tauw * ssaw + taui * ssai) / (tauw + taui); } else { g[lc] = 1.; ssa[lc] = 1.; } if (input.source == SRC_THERMAL) mu_eff = 1. / r; else { /*Calculate effective zenith angle */ for (i = lc; i >= 0; i--) { if (mu != 0.0) product *= 1.0 - output->cf.cf[i] * (1.0 - exp (-((1.0 - ssa[i] * g[i] * g[i]) * (tau[lc])) / mu)); else product *= 1.0 - output->cf.cf[i]; } C_eff = 1.0 - product; mu_eff = mu / (1.0 - C_eff + mu * r * C_eff); } /* Call ECHAM radiation routine SWDE. */ if ((tauw || taui) != 0.0) { /*Initialize inputs for swde.*/ pre1 = 0.0; pre2 = 0.0; transmission_cloud = 0.0; transmission_clear = 0.0; ptr2 = 0.0; if (verbose) { if (first_verbose) { fprintf ( stderr, " lc g pref theta_eff tau tau_clear ptr1 ptr2 ssa cf taueff\n"); first_verbose = FALSE; } fprintf (stderr, " %4d %9.6f %9.6f %9.3f %12.6e %12.6e %9.6f %9.6f %9.6f %8.5f", lc, g[lc], pref, acos (mu_eff) * 180 / PI, tau[lc], tau_clear, transmission_cloud, ptr2, ssa[lc], output->cf.cf[lc]); } if (ssa[lc] == 1.0) ssa[lc] = 0.99999; /* Perform radiative transfer (twostream) with scaled optical properties to calculate effective optical thickness. */ /* Scattering + sbsorption + rayleigh + aerosol*/ F77_FUNC (swde, SWDE) (&g[lc], &pref, &mu_eff, &tau[lc], &ssa[lc], &pre1, &pre2, &transmission_cloud, &ptr2); ptr2 = 0.0; /* Only absorption, rayleigh, aerosol */ F77_FUNC (swde, SWDE) (&g[lc], &pref, &mu_eff, &tau_clear, &ssa[lc], &pre1, &pre2, &transmission_clear, &ptr2); /* Transmission of the layer*/ transmission_layer = output->cf.cf[lc] * transmission_cloud + (1.0 - output->cf.cf[lc]) * transmission_clear; /* fprintf (stderr, */ /* "transmission_cloud %g, transmission_clear %g, transmission_layer %g cloud cover %g \n", */ /* transmission_cloud, transmission_clear, transmission_layer, output->cf.cf[lc+1]); */ /* Calculate effective optical thickness */ taueff = zbrent_taueff (mu_eff, g[lc], ssa[lc], transmission_cloud, transmission_layer, tau_clear, tau[lc], 0.00001); /* in solve_rte.c, next function */ /* fprintf (stderr, "test %d %g %g %g %g %g %g %g %g \n", lc, */ /* output->atm.zd[lc]+output->alt.altitude, tau[lc], mu_eff, */ /* output->cf.cf[lc], transmission_cloud, transmission_clear, transmission_layer, taueff); */ /* if (taueff > 0 && taueff < 1e-7) */ if (verbose) fprintf (stderr, " %g\n", taueff); /* Set the optical properties to be used in rte calculation.*/ /* wc is now representing both, water and ice clouds */ output->caoth[input.i_wc].optprop.dtau[iv][lc] = taueff; output->caoth[input.i_wc].optprop.g1[iv][lc] = g[lc]; output->caoth[input.i_wc].optprop.g2[iv][lc] = 0.0; output->caoth[input.i_wc].optprop.ff[iv][lc] = 1.0; output->caoth[input.i_wc].optprop.ssa[iv][lc] = ssa[lc]; /* ic is now not needed any more */ output->caoth[input.i_ic].optprop.dtau[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.g1[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.g2[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.ff[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.ssa[iv][lc] = 0.0; } else { /* wc is now representing both, water and ice clouds */ output->caoth[input.i_wc].optprop.dtau[iv][lc] = 0.0; output->caoth[input.i_wc].optprop.g1[iv][lc] = 0.0; output->caoth[input.i_wc].optprop.g2[iv][lc] = 0.0; output->caoth[input.i_wc].optprop.ff[iv][lc] = 0.0; output->caoth[input.i_wc].optprop.ssa[iv][lc] = 0.0; /* ic is now not needed any more */ output->caoth[input.i_ic].optprop.dtau[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.g1[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.g2[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.ff[iv][lc] = 0.0; output->caoth[input.i_ic].optprop.ssa[iv][lc] = 0.0; } } free (ssa); free (tau); free (g); return 0; } /** * *zbrent_taueff* returns the effective optical depth of a layer. * * The function is a slightly modified version of the "zbrent" function in the * "Numerical Recipes in C" (p. 352 ff.) for finding roots of an arbitrary function. * The function is here the ECHAM radiative tarnsfer routine swde.f and the root of it * is the effective optical thickness. * * @param mu_eff effective zenith angle * @param g asymmetry parameter * @param ssa single scattering albedo * @param transmission_cloud transmission cloudy part * @param transmission_layer total transmission * @param x1 clear optical depth * @param x2 cloudy optical depth * @param tol accuracy * * @return effective tau */ float zbrent_taueff (float mu_eff, float g, float ssa, float transmission_cloud, float transmission_layer, float x1, float x2, float tol) { int iter = 0; float a = x1, b = x2, c = x2, d = 0, e = 0, min1 = 0, min2 = 0; float fa = 0, fb = 0; float fc = 0, p = 0, q = 0, r = 0, s = 0, tol1 = 0, xm = 0; int itmax = 100; float eps = 3.0e-8; float dummy = 0.0; float pref = 0.0; F77_FUNC (swde, SWDE) (&g, &pref, &mu_eff, &x1, &ssa, &dummy, &dummy, &transmission_cloud, &dummy); fa = transmission_cloud - transmission_layer; dummy = 0.0; pref = 0.0; F77_FUNC (swde, SWDE) (&g, &pref, &mu_eff, &x2, &ssa, &dummy, &dummy, &transmission_cloud, &dummy); fb = transmission_cloud - transmission_layer; if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) { fprintf (stderr, "Root must be bracketed in zbrent \n"); fprintf (stderr, "Please check whether the cloud effective optical thickness has been \n"); fprintf (stderr, "calculated correctly. \n"); } fc = fb; for (iter = 1; iter <= itmax; iter++) { if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) { c = a; fc = fa; e = d = b - a; } if (fabs (fc) < fabs (fb)) { a = b; b = c; c = a; fa = fb; fb = fc; fc = fa; } tol1 = 2.0 * eps * fabs (b) + 0.5 * tol; xm = 0.5 * (c - b); if (fabs (xm) <= tol1 || fb == 0.0) return b; if (fabs (e) >= tol1 && fabs (fa) > fabs (fb)) { s = fb / fa; if (a == c) { p = 2.0 * xm * s; q = 1.0 - s; } else { q = fa / fc; r = fb / fc; p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0)); q = (q - 1.0) * (r - 1.0) * (s - 1.0); } if (p > 0.0) q = -q; p = fabs (p); min1 = 3.0 * xm * q - fabs (tol1 * q); min2 = fabs (e * q); if (2.0 * p < (min1 < min2 ? min1 : min2)) { e = d; d = p / q; } else { d = xm; e = d; } } else { d = xm; e = d; } a = b; fa = fb; if (fabs (d) > tol1) b += d; else b += SIGN (tol1, xm); dummy = 0.0; pref = 0.0; F77_FUNC (swde, SWDE) (&g, &dummy, &mu_eff, &b, &ssa, &dummy, &dummy, &transmission_cloud, &dummy); fb = transmission_cloud - transmission_layer; } fprintf (stderr, "Maximum number of iterations exceeded in zbrent \n"); return 0.0; } static int set_raman_source (double*** qsrc, double*** qsrcu, int maxphi, int nlev, int nzout, int nstr, int n_shifts, float wanted_wl, double* wl_shifts, float umu0, float* zd, float* zout, float zenang, float fbeam, float radius, float* dens, double** crs_RL, double** crs_RG, float* ssalb, int numu, float* umu, int usrang, int* cmuind, float*** pmom, raman_qsrc_components* raman_qsrc_comp, int* zout_comp_index, float altitude, int last, int verbose) { /* Equation numbers in this function refer to equations in ESAS-LIGHT */ /* report for WP2200. */ int status = 0, twonm1, test = 0; #if HAVE_SOS int* nfac = NULL; #endif int static first = 1, nlyr = 0; int lu = 0, lua = 0, lub = 0, lv = 0, iq = 0, iu = 0, jq = 0, k = 0, l = 0, nn = 0, lc = 0, maz = 0, is = 0; double sum = 0, sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0; double static *cmu = NULL, *cwt = NULL, ***ylmc = NULL, ***ylmu = NULL, ***ylm0 = NULL, sgn = 0, *tmpumu = NULL; double * tmp = NULL, *tmpylmc = NULL, *tmpylmu = NULL, *tmpylm0 = NULL; double static *trs = NULL, **trs_shifted = NULL, *tmp_shifted = NULL, *tmp_dtauc = NULL, *chtau = NULL; double static* tmp_dtauc_shifted = NULL; double static *tmp_dens = NULL, *tmp_dens_org = NULL, **tmp_crs_RG = NULL, **tmp_crs_RL = NULL; double static *tmp_in = NULL, *tmp_out = NULL; double static *tmp_cumtau = NULL, *tmp_cumtauint = NULL, **tmp_user_dtauc = NULL, *tmp_zd = NULL, *tmp_zd_org = NULL; int static ntmp_zd = 0; #if HAVE_SOS double static** fac = NULL; #endif double g2_R = 1 / 100.; /* Legendre expansion coefficients for Raman scattering */ double PI_R_b = 0, PI_R_d = 0; /* PIs in Eq. (28)-(29) */ double ssalbRL = 0; /* ssalb for Raman loss, Eq. (40) in Spurr et al 2008 */ double ssalbRG = 0; /* ssalb for Raman gain, Eq. (39) in Spurr et al 2008 */ double deltaz = 0, km2cm = 1E+5; ; double delm0 = 1; double crs_RL_tot = 0; double crs_RG_tot = 0; double lambda_fact = 0; /* Conversion factor lambdap**2/lambda**2, Eq. A3 Edgington et al. 1999 */ if (first) { nlyr = nlev - 1; ntmp_zd = nlev; /* Need quadrature angles and weights and Legendre polynomials */ cmu = (double*)calloc (nstr, sizeof (double)); cwt = (double*)calloc (nstr, sizeof (double)); nn = nstr / 2; c_gaussian_quadrature (nn, cmu, cwt); /* Rearrange cmu and cwt such that they are ascending order. qsrc should */ /* have cmu in ascending order, however, internally qdisort does not treat*/ /* cmu in ascending order. This feature is inherited from disort. */ for (iq = 0; iq < nn; iq++) { cmu[nn + iq] = cmu[iq]; cwt[nn + iq] = cwt[iq]; } for (iq = 0; iq < nn; iq++) { cmu[iq] = -cmu[nstr - 1 - iq]; cwt[iq] = cwt[nstr - 1 - iq]; } /* Calculate Legendre polynomials for each m */ if ((tmpylmc = (double*)calloc ((size_t) ((nstr + 1) * nstr), sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((tmpylm0 = (double*)calloc ((size_t) ((nstr + 1) * nstr), sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((status = ASCII_calloc_double_3D (&ylmc, nstr, nstr, nstr + 1)) != 0) return ASCII_NO_MEMORY; if ((status = ASCII_calloc_double_3D (&ylm0, nstr, nstr, nstr + 1)) != 0) return ASCII_NO_MEMORY; if (usrang) { if ((tmpylmu = (double*)calloc ((size_t) ((nstr + 1) * numu), sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((status = ASCII_calloc_double_3D (&ylmu, nstr, numu, nstr + 1)) != 0) return ASCII_NO_MEMORY; } for (maz = 0; maz < nstr; maz++) { twonm1 = nstr - 1; nn = 1; if ((tmp = (double*)calloc ((size_t) (1), sizeof (double))) == NULL) return ASCII_NO_MEMORY; tmp[0] = -umu0; c_legendre_poly (nn, maz, nstr, twonm1, tmp, tmpylm0); free (tmp); fortran2c_2D_double_ary_noalloc (nstr, nstr + 1, tmpylm0, ylm0[maz]); nn = nstr / 2; c_legendre_poly (nn, maz, nstr, twonm1, cmu, tmpylmc); fortran2c_2D_double_ary_noalloc (nstr, nstr + 1, tmpylmc, ylmc[maz]); /* Evaluate Legendre polynomials with negative -cmu- from those with*/ /* positive -cmu-; Dave Armstrong Eq. (15) */ sgn = -1.0; for (l = 0; l < nstr; l++) { sgn = -sgn; for (iq = nn; iq < nstr; iq++) { ylmc[maz][iq][l] = sgn * ylmc[maz][nstr - 1 - iq][l]; } } if (usrang) { if ((tmpumu = (double*)calloc ((size_t) (numu), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmpumu, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } for (iu = 0; iu < numu; iu++) tmpumu[iu] = umu[iu]; c_legendre_poly (numu, maz, nstr, twonm1, tmpumu, tmpylmu); fortran2c_2D_double_ary_noalloc (numu, nstr + 1, tmpylmu, ylmu[maz]); free (tmpumu); } } free (tmpylmc); free (tmpylm0); if (usrang) { free (tmpylmu); } if ((trs = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for trs, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((status = ASCII_calloc_double (&trs_shifted, ntmp_zd, n_shifts)) != 0) { fprintf (stderr, "Unable to allocate memory for trs_shifted, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((chtau = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for chtau, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_dtauc = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_dtauc, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_dens = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_dens, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_dens_org = (double*)calloc ((size_t) (nlev), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_dens_org, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_dtauc_shifted = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_dtauc_shifted, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_in = (double*)calloc ((size_t) (nzout), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_in, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_out = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_out, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((tmp_shifted = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) { status = ASCII_NO_MEMORY; fprintf (stderr, "Unable to allocate memory for tmp_shifted, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } if ((status = ASCII_calloc_double (&tmp_crs_RG, ntmp_zd, n_shifts)) != 0) { fprintf (stderr, "Error %d allocating memory for crs_RG \n", status); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return status; } if ((status = ASCII_calloc_double (&tmp_crs_RL, ntmp_zd, n_shifts)) != 0) { fprintf (stderr, "Error %d allocating memory for crs_RG \n", status); fprintf (stderr, " (line %d, function '%s' in '%s')\n", __LINE__, __func__, __FILE__); return status; } if ((status = ASCII_calloc_double (&tmp_user_dtauc, ntmp_zd, n_shifts + 1)) != 0) { fprintf (stderr, "Unable to allocate memory for user_dtauc, status: %d returned at (line %d, function %s in %s)\n", status, __LINE__, __func__, __FILE__); return status; } first = 0; } /* if ( first ) */ /* Find all unique altitudes */ ntmp_zd = nlev; if ((tmp_zd = calloc (ntmp_zd, sizeof (double))) == NULL) { fprintf (stderr, "Error, allocating memory for tmp_zd\n"); fprintf (stderr, " (line %d, function %s in %s) \n", __LINE__, __func__, __FILE__); return -1; } if ((tmp_zd_org = calloc (nlyr + 1, sizeof (double))) == NULL) { fprintf (stderr, "Error, allocating memory for tmp_zd_org\n"); fprintf (stderr, " (line %d, function %s in %s) \n", __LINE__, __func__, __FILE__); return -1; } for (lc = 0; lc <= nlyr; lc++) { tmp_zd_org[lc] = (double)zd[lc]; tmp_dens_org[lc] = (double)dens[lc]; } lv = 0; for (lu = 0; lu < nlev - 1; lu++) { if (zd[lu] >= 0.0) tmp_zd[lv++] = (double)zd[lu]; } if (zd[nlev] < 0.0) tmp_zd[lv] = 0.0; else tmp_zd[lv] = (double)zd[nlev]; // aky20042012 removed this, made source zero at bottom level if altitude was set different from level. // Probably a leftover from when source varied within layers and forgotten to clean up..... // if ( altitude != 0) { //aky ntmp_zd = lv; /* Number of output levels may be reduced due to altitude option */ // } #if HAVE_SOS /* Calculate geometric correction factor needed for chapman function */ if ((nfac = (int*)calloc ((size_t) (ntmp_zd - 1), sizeof (int))) == NULL) return ASCII_NO_MEMORY; if ((status = ASCII_calloc_double (&fac, ntmp_zd - 1, 2 * (ntmp_zd - 1))) != 0) return status; /* Share dtauc from zd layering to zout */ for (lu = 0; lu < ntmp_zd - 1; lu++) tmp_dtauc[lu] = raman_qsrc_comp->dtauc[lu][n_shifts]; chtau[0] = 0; for (lc = 1; lc <= ntmp_zd - 1; lc++) chtau[lc] = c_chapman_simpler (lc, 0.5, ntmp_zd, tmp_zd, tmp_dtauc, zenang, radius); /* Transmittance of the atmosphere at wanted wavelength */ trans_double (ntmp_zd - 1, chtau, trs); for (is = 0; is < n_shifts; is++) { for (lu = 0; lu < ntmp_zd - 1; lu++) { tmp_dtauc_shifted[lu] = raman_qsrc_comp->dtauc[lu][is]; } chtau[0] = 0; for (lc = 1; lc <= ntmp_zd - 1; lc++) chtau[lc] = c_chapman_simpler (lc, 0.5, ntmp_zd, tmp_zd, tmp_dtauc_shifted, zenang, radius); trans_double (ntmp_zd - 1, chtau, tmp_shifted); for (lu = 0; lu < ntmp_zd; lu++) trs_shifted[lu][is] = tmp_shifted[lu]; } #else fprintf (stderr, "Error, need SOS source code for Raman scattering!\n"); return -1; #endif /* Interpolate density and Raman cross sections from zd to zout grid */ status = arb_wvn_double (nlev, tmp_zd_org, tmp_dens_org, ntmp_zd, tmp_zd, tmp_dens, INTERP_METHOD_LOG, 1); for (is = 0; is < n_shifts; is++) { for (lu = 0; lu < nlev; lu++) tmp_in[lu] = crs_RG[lu][is]; status = arb_wvn_double (nlev, tmp_zd_org, tmp_in, ntmp_zd, tmp_zd, tmp_out, INTERP_METHOD_LINEAR, 1); for (lu = 0; lu < ntmp_zd; lu++) tmp_crs_RG[lu][is] = tmp_out[lu]; } for (is = 0; is < n_shifts; is++) { for (lu = 0; lu < nlev; lu++) tmp_in[lu] = crs_RL[lu][is]; status = arb_wvn_double (nlev, tmp_zd_org, tmp_in, ntmp_zd, tmp_zd, tmp_out, INTERP_METHOD_LINEAR, 1); for (lu = 0; lu < ntmp_zd; lu++) tmp_crs_RL[lu][is] = tmp_out[lu]; } test = 0; if (test) { /*************************************************************/ /* To check that all angles etc. are correctly treated test */ /* with the direct beam source. This should give identical */ /* results for the diffuse radiation as the first raman */ /* wavelength loop */ /*************************************************************/ delm0 = 1; fbeam = 1; for (maz = 0; maz < nstr; maz++) { if (maz > 0) delm0 = 0; for (lu = 0; lu < nzout - 1; lu++) { lc = lu; for (iq = 0; iq < nstr; iq++) { sum = 0; for (k = maz; k < nstr; k++) { sum += (2 * k + 1) * ssalb[lc] * pmom[lc][0][k] * ylmc[maz][iq][k] * ylm0[maz][0][k]; } qsrc[maz][lu][iq] = sum * (2 - delm0) * fbeam / (4 * M_PI); if (lu == nzout) { /* Set source at bottom level */ qsrc[maz][lu + 1][iq] = qsrc[maz][lu][iq] * trs[lu + 1]; } qsrc[maz][lu][iq] = qsrc[maz][lu][iq] * trs[lu]; } if (usrang) { for (iu = 0; iu < numu; iu++) { sum = 0; for (k = maz; k < nstr; k++) { sum += (2 * k + 1) * ssalb[lc] * pmom[lc][0][k] * ylmu[maz][iu][k] * ylm0[maz][0][k]; } qsrcu[maz][lu][iu] = sum * (2 - delm0) * fbeam / (4 * M_PI); if (lu == nzout - 2) { /* Set source at bottom level */ qsrcu[maz][lu + 1][iu] = qsrcu[maz][lu][iu] * trs[lu + 1]; } qsrcu[maz][lu][iu] = qsrcu[maz][lu][iu] * trs[lu]; } } } } } else { /* Raman scattering source */ if (verbose) fprintf (stderr, "Raman_src %1s %2s %2s %2s %3s %4s %4s %4s %4s %4s %9s %9s " "%9s %9s )\n", "m", "lu", "iq", "zd", "cmu", "sum1", "sum2", "sum3", "sum4", "qsrc", "ssalbRL", "ssalbRG", "PI_R_b", "PI_R_d"); delm0 = 1; /* dtauc is not necessarily at all user altitudes. So first interpolate to all user altitudes.... */ if ((tmp_cumtau = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) return ASCII_NO_MEMORY; if ((tmp_cumtauint = (double*)calloc ((size_t) (ntmp_zd), sizeof (double))) == NULL) return ASCII_NO_MEMORY; for (is = 0; is <= n_shifts; is++) { /* Start by calculating the cumulative optical depth. */ lu = 0; tmp_cumtau[lu] = 0.0; for (lu = 1; lu < ntmp_zd; lu++) tmp_cumtau[lu] = tmp_cumtau[lu - 1] + raman_qsrc_comp->dtauc[lu - 1][is]; /* Interpolate the cumulative optical depth to all user altitudes. */ status = arb_wvn_double (ntmp_zd, tmp_zd, tmp_cumtau, ntmp_zd, tmp_zd, tmp_cumtauint, INTERP_METHOD_LINEAR, 1); /* Finally calculate the optical depth of each layer. */ lu = 0; tmp_user_dtauc[lu][is] = 0.0; for (lu = 1; lu < ntmp_zd; lu++) tmp_user_dtauc[lu][is] = tmp_cumtauint[lu] - tmp_cumtauint[lu - 1]; } free (tmp_cumtau); free (tmp_cumtauint); for (maz = 0; maz < nstr; maz++) { if (maz > 0) delm0 = 0; for (lu = 1; lu < ntmp_zd; lu++) { /* No need to include first level as source is calculated at middle of layer */ lua = lu - 1; lub = lu; deltaz = (tmp_zd[lua] - tmp_zd[lub]) * km2cm; ssalbRL = 0; //aky tmpsum=0.0; for (is = 0; is < n_shifts; is++) { //aky ssalbRL += 0.5 * deltaz * (tmp_dens[lua]*tmp_crs_RL[lua][is] + tmp_dens[lub]*tmp_crs_RL[lub][is]) / ssalbRL += deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RL[lua][is], tmp_dens[lub] * tmp_crs_RL[lub][is]) / tmp_user_dtauc[lub][n_shifts]; //aky tmpsum += dlog_average(tmp_crs_RL[lua][is], tmp_crs_RL[lub][is]); } verbose = 0; if (verbose && maz == 0) { crs_RL_tot = 0; crs_RG_tot = 0; for (is = 0; is < n_shifts; is++) { crs_RL_tot += tmp_crs_RL[lu][is]; crs_RG_tot += tmp_crs_RG[lu][is]; } fprintf (stderr, "%3d, zout: %7.2f, crs_RL_tot: %13.6e, crs_RG_tot: %13.6e\n", lu, zout[lu], crs_RL_tot, crs_RG_tot); } for (iq = 0; iq < nstr; iq++) { sum1 = 0; sum2 = 0; sum3 = 0; sum4 = 0; /* Calculate PI_R_b (Eq. 28) for Raman scattering */ if (maz == 0) PI_R_b = ylmc[maz][iq][0] * ylm0[maz][0][0] + 5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2]; else if (maz == 1) PI_R_b = -5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2]; else if (maz == 2) PI_R_b = +5 * g2_R * ylmc[maz][iq][2] * ylm0[maz][0][2]; else PI_R_b = 0; /* First part of Raman scattering source term, Eq. (31). */ ssalbRG = 0; for (is = 0; is < n_shifts; is++) { lambda_fact = (wl_shifts[is] * wl_shifts[is]) / (wanted_wl * wanted_wl); sum = 0; for (jq = 0; jq < nstr; jq++) { /* Calculate PI_R_d (Eq. 29) for Raman scattering */ if (maz == 0) PI_R_d = ylmc[maz][iq][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else if (maz == 1) PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else if (maz == 2) PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else PI_R_d = 0; sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][is]; } //aky ssalbRG = 0.5 * deltaz * lambda_fact * (tmp_dens[lua] * tmp_crs_RG[lua][is] + //aky tmp_dens[lub] * tmp_crs_RG[lub][is]) / ssalbRG = deltaz * lambda_fact * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts]; sum1 += ssalbRG * sum; } sum1 *= +1. / 2.; /* Second part of Raman scattering source term, Eq. (31). */ for (is = 0; is < n_shifts; is++) { lambda_fact = (wl_shifts[is] * wl_shifts[is]) / (wanted_wl * wanted_wl); //aky ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] * //aky tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts]; ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts]; sum2 += raman_qsrc_comp->fbeam[is] * ssalbRG * trs_shifted[lub][is] * lambda_fact; } sum2 *= +((2 - delm0) / (4 * M_PI)) * PI_R_b; /* Third part of Raman scattering source term, Eq. (31). */ sum = 0; for (jq = 0; jq < nstr; jq++) { /* Calculate PI_R_d (Eq. 29) for Raman scattering */ if (maz == 0) PI_R_d = ylmc[maz][iq][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else if (maz == 1) PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else if (maz == 2) PI_R_d = +5 * g2_R * ylmc[maz][iq][2] * ylmc[maz][jq][2]; else PI_R_d = 0; sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][n_shifts]; } sum3 = -(ssalbRL / 2) * sum; /* Fourth part of Raman scattering source term, Eq. (31). */ sum4 = -((ssalbRL * fbeam) / (4 * M_PI)) * (2 - delm0) * PI_R_b * trs[lub]; qsrc[maz][lu - 1][iq] = sum1 + sum2 + sum3 + sum4; /* lu starts at 1, source index is one less */ //aky verbose = 0; if (verbose) { if (maz == 0 && iq == 0) fprintf (stderr, "Raman_src %2d %2d %2d %7.3f %7.3f %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e %7.3f %7.3f %13.6e\n", maz, lu, iq, zout[lu], cmu[iq], sum1, sum2, sum3, sum4, qsrc[maz][lu - 1][iq], ssalbRL, ssalbRG, PI_R_b, PI_R_d, trs[lu]); } } /* for (iq=0;iq<nstr;iq++) */ if (usrang) { /* Also have to calculate the source for all user angles */ for (iu = 0; iu < numu; iu++) { sum1 = 0; sum2 = 0; sum3 = 0; sum4 = 0; /* Calculate PI_R_b (Eq. 28) for Raman scattering */ if (maz == 0) PI_R_b = ylmu[maz][iu][0] * ylm0[maz][0][0] + 5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2]; else if (maz == 1) PI_R_b = -5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2]; else if (maz == 2) PI_R_b = +5 * g2_R * ylmu[maz][iu][2] * ylm0[maz][0][2]; else PI_R_b = 0; /* First part of Raman scattering source term, Eq. (31). */ ssalbRG = 0; for (is = 0; is < n_shifts; is++) { sum = 0; for (jq = 0; jq < nstr; jq++) { /* Calculate PI_R_d (Eq. 29) for Raman scattering */ if (maz == 0) PI_R_d = ylmu[maz][iu][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else if (maz == 1) PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else if (maz == 2) PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else PI_R_d = 0; sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][is]; } //aky ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] * //aky tmp_crs_RG[lub][is])/ ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts]; sum1 += ssalbRG * sum; } sum1 *= +1. / 2.; /* Second part of Raman scattering source term, Eq. (31). */ for (is = 0; is < n_shifts; is++) { //aky ssalbRG = 0.5 * deltaz * (tmp_dens[lua] * tmp_crs_RG[lua][is] + tmp_dens[lub] * //aky tmp_crs_RG[lub][is])/tmp_user_dtauc[lub][n_shifts]; ssalbRG = deltaz * dlog_average (tmp_dens[lua] * tmp_crs_RG[lua][is], tmp_dens[lub] * tmp_crs_RG[lub][is]) / tmp_user_dtauc[lub][n_shifts]; sum2 += raman_qsrc_comp->fbeam[is] * ssalbRG * trs_shifted[lub][is]; } sum2 *= +((2 - delm0) / (4 * M_PI)) * PI_R_b; /* Third part of Raman scattering source term, Eq. (31). */ sum = 0; for (jq = 0; jq < nstr; jq++) { /* Calculate PI_R_d (Eq. 29) for Raman scattering */ if (maz == 0) PI_R_d = ylmu[maz][iu][0] * ylmc[maz][jq][0] + 5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else if (maz == 1) PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else if (maz == 2) PI_R_d = +5 * g2_R * ylmu[maz][iu][2] * ylmc[maz][jq][2]; else PI_R_d = 0; sum += cwt[jq] * PI_R_d * raman_qsrc_comp->uum[zout_comp_index[lub]][maz][cmuind[jq]][n_shifts]; } sum3 = -(ssalbRL / 2) * sum; /* Fourth part of Raman scattering source term, Eq. (31). */ sum4 = -((ssalbRL * fbeam) / (4 * M_PI)) * (2 - delm0) * PI_R_b * trs[lub]; qsrcu[maz][lu - 1][iu] = sum1 + sum2 + sum3 + sum4; /* lu starts at 1, source index is one less */ verbose = 0; if (verbose) { if (maz == 0 && iu == 0) fprintf (stderr, "Raman_srcu %2d %2d %2d %7.3f %7.3f %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e %13.6e %7.3f %7.3f\n", maz, lu, iu, zout[lu], umu[iu], sum1, sum2, sum3, sum4, qsrcu[maz][lu][iu], ssalbRL, ssalbRG, PI_R_b, PI_R_d); } } /* for (iq=0;iq<nstr;iq++) */ } /* if ( usrang ) { */ } /* for (lu=0;lu<nzout;lu++) */ } } free (tmp_zd); free (tmp_zd_org); free (nfac); if (last) { free (cmu); free (cwt); } return status; } #undef NRANSI
{ "alphanum_fraction": 0.4879458169, "avg_line_length": 42.1506578181, "ext": "c", "hexsha": "3ac24798c76aad46fd63ecafc6778e81aa3e6581", "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": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "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": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_line_length": 176, "max_stars_count": null, "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/solve_rte.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 97920, "size": 362032 }
#pragma once #define NOMINMAX #define WEBRTC_WIN #define ABSL_USES_STD_STRING_VIEW #include <unknwn.h> #include <ppltasks.h> #include <pplawait.h> #include <gsl/gsl> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.Diagnostics.h> #include <winrt/Windows.Foundation.Collections.h> #include <winrt/Windows.Data.Json.h> #include <winrt/Windows.Networking.Sockets.h> #include <winrt/Windows.System.Threading.h> #include <winrt/Windows.Storage.Streams.h> #include <wrl/client.h>
{ "alphanum_fraction": 0.786, "avg_line_length": 27.7777777778, "ext": "h", "hexsha": "4706f5bd31c981fc1641a8ac449a82bcee1ae7ea", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-10-16T18:09:59.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-19T12:02:28.000Z", "max_forks_repo_head_hexsha": "3fd70f650ffdc4521795b2bd3c74d901a04312bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "UnicordDev/Unicord.Universal.Voice", "max_forks_repo_path": "Unicord.Universal.Voice/pch.h", "max_issues_count": 57, "max_issues_repo_head_hexsha": "3fd70f650ffdc4521795b2bd3c74d901a04312bd", "max_issues_repo_issues_event_max_datetime": "2021-09-30T17:34:08.000Z", "max_issues_repo_issues_event_min_datetime": "2019-06-07T12:53:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "UnicordDev/Unicord.Universal.Voice", "max_issues_repo_path": "Unicord.Universal.Voice/pch.h", "max_line_length": 49, "max_stars_count": 106, "max_stars_repo_head_hexsha": "47c74e665ebb2bff3ef93b068357d3bf2f912e17", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "WamWooWam/Unicord", "max_stars_repo_path": "Unicord.Universal.Voice/pch.h", "max_stars_repo_stars_event_max_datetime": "2021-10-29T23:40:01.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-10T18:08:08.000Z", "num_tokens": 128, "size": 500 }
/* specfunc/expint.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_expint.h" #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* Chebyshev expansions: based on SLATEC e1.f, W. Fullerton Series for AE11 on the interval -1.00000D-01 to 0. with weighted error 1.76E-17 log weighted error 16.75 significant figures required 15.70 decimal places required 17.55 Series for AE12 on the interval -2.50000D-01 to -1.00000D-01 with weighted error 5.83E-17 log weighted error 16.23 significant figures required 15.76 decimal places required 16.93 Series for E11 on the interval -4.00000D+00 to -1.00000D+00 with weighted error 1.08E-18 log weighted error 17.97 significant figures required 19.02 decimal places required 18.61 Series for E12 on the interval -1.00000D+00 to 1.00000D+00 with weighted error 3.15E-18 log weighted error 17.50 approx significant figures required 15.8 decimal places required 18.10 Series for AE13 on the interval 2.50000D-01 to 1.00000D+00 with weighted error 2.34E-17 log weighted error 16.63 significant figures required 16.14 decimal places required 17.33 Series for AE14 on the interval 0. to 2.50000D-01 with weighted error 5.41E-17 log weighted error 16.27 significant figures required 15.38 decimal places required 16.97 */ static double AE11_data[39] = { 0.121503239716065790, -0.065088778513550150, 0.004897651357459670, -0.000649237843027216, 0.000093840434587471, 0.000000420236380882, -0.000008113374735904, 0.000002804247688663, 0.000000056487164441, -0.000000344809174450, 0.000000058209273578, 0.000000038711426349, -0.000000012453235014, -0.000000005118504888, 0.000000002148771527, 0.000000000868459898, -0.000000000343650105, -0.000000000179796603, 0.000000000047442060, 0.000000000040423282, -0.000000000003543928, -0.000000000008853444, -0.000000000000960151, 0.000000000001692921, 0.000000000000607990, -0.000000000000224338, -0.000000000000200327, -0.000000000000006246, 0.000000000000045571, 0.000000000000016383, -0.000000000000005561, -0.000000000000006074, -0.000000000000000862, 0.000000000000001223, 0.000000000000000716, -0.000000000000000024, -0.000000000000000201, -0.000000000000000082, 0.000000000000000017 }; static cheb_series AE11_cs = { AE11_data, 38, -1, 1, 20 }; static double AE12_data[25] = { 0.582417495134726740, -0.158348850905782750, -0.006764275590323141, 0.005125843950185725, 0.000435232492169391, -0.000143613366305483, -0.000041801320556301, -0.000002713395758640, 0.000001151381913647, 0.000000420650022012, 0.000000066581901391, 0.000000000662143777, -0.000000002844104870, -0.000000000940724197, -0.000000000177476602, -0.000000000015830222, 0.000000000002905732, 0.000000000001769356, 0.000000000000492735, 0.000000000000093709, 0.000000000000010707, -0.000000000000000537, -0.000000000000000716, -0.000000000000000244, -0.000000000000000058 }; static cheb_series AE12_cs = { AE12_data, 24, -1, 1, 15 }; static double E11_data[19] = { -16.11346165557149402600, 7.79407277874268027690, -1.95540581886314195070, 0.37337293866277945612, -0.05692503191092901938, 0.00721107776966009185, -0.00078104901449841593, 0.00007388093356262168, -0.00000620286187580820, 0.00000046816002303176, -0.00000003209288853329, 0.00000000201519974874, -0.00000000011673686816, 0.00000000000627627066, -0.00000000000031481541, 0.00000000000001479904, -0.00000000000000065457, 0.00000000000000002733, -0.00000000000000000108 }; static cheb_series E11_cs = { E11_data, 18, -1, 1, 13 }; static double E12_data[16] = { -0.03739021479220279500, 0.04272398606220957700, -0.13031820798497005440, 0.01441912402469889073, -0.00134617078051068022, 0.00010731029253063780, -0.00000742999951611943, 0.00000045377325690753, -0.00000002476417211390, 0.00000000122076581374, -0.00000000005485141480, 0.00000000000226362142, -0.00000000000008635897, 0.00000000000000306291, -0.00000000000000010148, 0.00000000000000000315 }; static cheb_series E12_cs = { E12_data, 15, -1, 1, 10 }; static double AE13_data[25] = { -0.605773246640603460, -0.112535243483660900, 0.013432266247902779, -0.001926845187381145, 0.000309118337720603, -0.000053564132129618, 0.000009827812880247, -0.000001885368984916, 0.000000374943193568, -0.000000076823455870, 0.000000016143270567, -0.000000003466802211, 0.000000000758754209, -0.000000000168864333, 0.000000000038145706, -0.000000000008733026, 0.000000000002023672, -0.000000000000474132, 0.000000000000112211, -0.000000000000026804, 0.000000000000006457, -0.000000000000001568, 0.000000000000000383, -0.000000000000000094, 0.000000000000000023 }; static cheb_series AE13_cs = { AE13_data, 24, -1, 1, 15 }; static double AE14_data[26] = { -0.18929180007530170, -0.08648117855259871, 0.00722410154374659, -0.00080975594575573, 0.00010999134432661, -0.00001717332998937, 0.00000298562751447, -0.00000056596491457, 0.00000011526808397, -0.00000002495030440, 0.00000000569232420, -0.00000000135995766, 0.00000000033846628, -0.00000000008737853, 0.00000000002331588, -0.00000000000641148, 0.00000000000181224, -0.00000000000052538, 0.00000000000015592, -0.00000000000004729, 0.00000000000001463, -0.00000000000000461, 0.00000000000000148, -0.00000000000000048, 0.00000000000000016, -0.00000000000000005 }; static cheb_series AE14_cs = { AE14_data, 25, -1, 1, 13 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_expint_E1_e(const double x, gsl_sf_result * result) { const double xmaxt = -GSL_LOG_DBL_MIN; /* XMAXT = -LOG (R1MACH(1)) */ const double xmax = xmaxt - log(xmaxt); /* XMAX = XMAXT - LOG(XMAXT) */ /* CHECK_POINTER(result) */ if(x < -xmax) { OVERFLOW_ERROR(result); } else if(x <= -10.0) { const double s = exp(-x)/x; gsl_sf_result result_c; cheb_eval_e(&AE11_cs, 20.0/x+1.0, &result_c); result->val = s * (1.0 + result_c.val); result->err = s * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * (fabs(x) + 1.0) * fabs(result->val); return GSL_SUCCESS; } else if(x <= -4.0) { const double s = exp(-x)/x; gsl_sf_result result_c; cheb_eval_e(&AE12_cs, (40.0/x+7.0)/3.0, &result_c); result->val = s * (1.0 + result_c.val); result->err = s * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x <= -1.0) { const double ln_term = -log(fabs(x)); gsl_sf_result result_c; cheb_eval_e(&E11_cs, (2.0*x+5.0)/3.0, &result_c); result->val = ln_term + result_c.val; result->err = result_c.err + GSL_DBL_EPSILON * fabs(ln_term); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x == 0.0) { DOMAIN_ERROR(result); } else if(x <= 1.0) { const double ln_term = -log(fabs(x)); gsl_sf_result result_c; cheb_eval_e(&E12_cs, x, &result_c); result->val = ln_term - 0.6875 + x + result_c.val; result->err = result_c.err + GSL_DBL_EPSILON * fabs(ln_term); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x <= 4.0) { const double s = exp(-x)/x; gsl_sf_result result_c; cheb_eval_e(&AE13_cs, (8.0/x-5.0)/3.0, &result_c); result->val = s * (1.0 + result_c.val); result->err = s * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x <= xmax) { const double s = exp(-x)/x; gsl_sf_result result_c; cheb_eval_e(&AE14_cs, 8.0/x-1.0, &result_c); result->val = s * (1.0 + result_c.val); result->err = s * (GSL_DBL_EPSILON + result_c.err); result->err += 2.0 * (x + 1.0) * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { UNDERFLOW_ERROR(result); } } int gsl_sf_expint_E2_e(const double x, gsl_sf_result * result) { const double xmaxt = -GSL_LOG_DBL_MIN; const double xmax = xmaxt - log(xmaxt); /* CHECK_POINTER(result) */ if(x < -xmax) { OVERFLOW_ERROR(result); } else if(x < 100.0) { const double ex = exp(-x); gsl_sf_result result_E1; int stat_E1 = gsl_sf_expint_E1_e(x, &result_E1); result->val = ex - x*result_E1.val; result->err = fabs(x) * (GSL_DBL_EPSILON*ex + result_E1.err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_E1; } else if(x < xmax) { const double c1 = -2.0; const double c2 = 6.0; const double c3 = -24.0; const double c4 = 120.0; const double c5 = -720.0; const double c6 = 5040.0; const double c7 = -40320.0; const double c8 = 362880.0; const double c9 = -3628800.0; const double c10 = 39916800.0; const double c11 = -479001600.0; const double c12 = 6227020800.0; const double c13 = -87178291200.0; const double y = 1.0/x; const double sum6 = c6+y*(c7+y*(c8+y*(c9+y*(c10+y*(c11+y*(c12+y*c13)))))); const double sum = y*(c1+y*(c2+y*(c3+y*(c4+y*(c5+y*sum6))))); result->val = exp(-x) * (1.0 + sum)/x; result->err = 2.0 * (x + 1.0) * GSL_DBL_EPSILON * result->val; return GSL_SUCCESS; } else { UNDERFLOW_ERROR(result); } } int gsl_sf_expint_Ei_e(const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { int status = gsl_sf_expint_E1_e(-x, result); result->val = -result->val; return status; } } #if 0 static double recurse_En(int n, double x, double E1) { int i; double En = E1; double ex = exp(-x); for(i=2; i<=n; i++) { En = 1./(i-1) * (ex - x * En); } return En; } #endif /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_expint_E1(const double x) { EVAL_RESULT(gsl_sf_expint_E1_e(x, &result)); } double gsl_sf_expint_E2(const double x) { EVAL_RESULT(gsl_sf_expint_E2_e(x, &result)); } double gsl_sf_expint_Ei(const double x) { EVAL_RESULT(gsl_sf_expint_Ei_e(x, &result)); }
{ "alphanum_fraction": 0.6663178092, "avg_line_length": 25.5367483296, "ext": "c", "hexsha": "fa53aa745d48620a3da94e86dc470a4d5dc8db2c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.c", "max_line_length": 79, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/expint.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": 4288, "size": 11466 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "tests.h" void test_gemm (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha = 1.0f; float beta = 0.0f; float A[] = { 0.199f, 0.237f, 0.456f, 0.377f }; int lda = 4; float B[] = { 0.842f, -0.734f, 0.323f, -0.957f, -0.303f, -0.873f, -0.871f, -0.819f }; int ldb = 2; float C[] = { 0.498f, -0.925f }; int ldc = 2; float C_expected[] = { -0.222426f, -1.07973f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1466)"); } }; }; { int order = 102; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha = 1.0f; float beta = 0.0f; float A[] = { -0.83f, 0.922f, -0.228f, -0.003f }; int lda = 1; float B[] = { 0.072f, 0.345f, 0.944f, -0.39f, -0.577f, 0.656f, -0.693f, -0.453f }; int ldb = 4; float C[] = { 0.583f, 0.522f }; int ldc = 1; float C_expected[] = { 0.044268f, 1.24311f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1467)"); } }; }; { int order = 101; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha = 0.1f; float beta = 0.1f; float A[] = { -0.838f, 0.622f, -0.494f, 0.304f }; int lda = 4; float B[] = { 0.147f, 0.134f, 0.169f, 0.734f, -0.7f, 0.541f, -0.794f, -0.256f }; int ldb = 4; float C[] = { -0.632f, -0.559f }; int ldc = 2; float C_expected[] = { -0.0532188f, 0.0678514f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1468)"); } }; }; { int order = 102; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha = 0.1f; float beta = 0.1f; float A[] = { -0.937f, 0.635f, 0.596f, -0.51f }; int lda = 1; float B[] = { -0.688f, -0.265f, 0.049f, 0.133f, -0.918f, -0.147f, 0.977f, -0.21f }; int ldb = 2; float C[] = { 0.844f, 0.999f }; int ldc = 1; float C_expected[] = { 0.0474373f, 0.135125f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1469)"); } }; }; { int order = 101; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha = -0.3f; float beta = 0.1f; float A[] = { -0.165f, 0.638f, 0.346f, -0.697f }; int lda = 1; float B[] = { 0.499f, -0.73f, 0.262f, 0.759f, 0.664f, 0.997f, -0.702f, -0.839f }; int ldb = 2; float C[] = { 0.17f, 0.425f }; int ldc = 2; float C_expected[] = { -0.224158f, -0.417831f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1470)"); } }; }; { int order = 102; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha = -0.3f; float beta = 0.1f; float A[] = { -0.603f, -0.714f, -0.893f, 0.046f }; int lda = 4; float B[] = { 0.859f, -0.694f, -0.868f, -0.98f, -0.103f, 0.567f, -0.277f, -0.734f }; int ldb = 4; float C[] = { 0.517f, -0.622f }; int ldc = 1; float C_expected[] = { -0.160575f, -0.0234604f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1471)"); } }; }; { int order = 101; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha = 0.1f; float beta = 1.0f; float A[] = { -0.087f, -0.047f, -0.051f, -0.615f }; int lda = 1; float B[] = { -0.722f, -0.077f, 0.563f, 0.501f, 0.855f, 0.605f, 0.556f, -0.627f }; int ldb = 4; float C[] = { -0.181f, -0.89f }; int ldc = 2; float C_expected[] = { -0.208039f, -0.864557f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1472)"); } }; }; { int order = 102; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha = 0.1f; float beta = 1.0f; float A[] = { -0.753f, -0.074f, -0.247f, -0.19f }; int lda = 4; float B[] = { 0.061f, 0.743f, 0.22f, -0.682f, 0.733f, 0.417f, 0.772f, 0.665f }; int ldb = 2; float C[] = { -0.253f, 0.972f }; int ldc = 1; float C_expected[] = { -0.291994f, 0.898164f }; cblas_sgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "sgemm(case 1473)"); } }; }; { int order = 101; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha = 0; double beta = 0; double A[] = { 0.017, 0.191, 0.863, -0.97 }; int lda = 4; double B[] = { -0.207, -0.916, -0.278, 0.403, 0.885, 0.409, -0.772, -0.27 }; int ldb = 2; double C[] = { -0.274, -0.858 }; int ldc = 2; double C_expected[] = { 0.0, 0.0 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1474)"); } }; }; { int order = 102; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha = 0; double beta = 0; double A[] = { 0.571, 0.081, 0.109, 0.988 }; int lda = 1; double B[] = { -0.048, -0.753, -0.8, -0.89, -0.535, -0.017, -0.018, -0.544 }; int ldb = 4; double C[] = { -0.876, -0.792 }; int ldc = 1; double C_expected[] = { 0.0, 0.0 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1475)"); } }; }; { int order = 101; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha = -0.3; double beta = 1; double A[] = { 0.939, 0.705, 0.977, 0.4 }; int lda = 4; double B[] = { -0.089, -0.822, 0.937, 0.159, 0.789, -0.413, -0.172, 0.88 }; int ldb = 4; double C[] = { -0.619, 0.063 }; int ldc = 2; double C_expected[] = { -0.7137904, -0.1270986 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1476)"); } }; }; { int order = 102; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha = -0.3; double beta = 1; double A[] = { -0.795, 0.81, 0.388, 0.09 }; int lda = 1; double B[] = { -0.847, 0.031, -0.938, 0.09, -0.286, -0.478, -0.981, 0.881 }; int ldb = 2; double C[] = { -0.242, -0.02 }; int ldc = 1; double C_expected[] = { -0.1562981, -0.0026243 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1477)"); } }; }; { int order = 101; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha = -1; double beta = 0; double A[] = { -0.556, 0.532, 0.746, 0.673 }; int lda = 1; double B[] = { -0.525, 0.967, 0.687, -0.024, 0.527, 0.485, 0.109, -0.46 }; int ldb = 2; double C[] = { -0.495, 0.859 }; int ldc = 2; double C_expected[] = { -1.123883, 0.49819 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1478)"); } }; }; { int order = 102; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha = -1; double beta = 0; double A[] = { -0.358, 0.224, -0.941, 0.513 }; int lda = 4; double B[] = { -0.201, -0.159, -0.586, -0.016, -0.324, 0.411, 0.115, -0.229 }; int ldb = 4; double C[] = { 0.558, 0.596 }; int ldc = 1; double C_expected[] = { -0.57956, 0.017636 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1479)"); } }; }; { int order = 101; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha = -0.3; double beta = 1; double A[] = { -0.586, 0.809, 0.709, -0.524 }; int lda = 1; double B[] = { 0.768, 0.7, 0.619, -0.478, -0.129, -0.778, -0.432, 0.454 }; int ldb = 4; double C[] = { 0.042, 0.252 }; int ldc = 2; double C_expected[] = { -0.1996785, 0.5813976 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1480)"); } }; }; { int order = 102; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha = -0.3; double beta = 1; double A[] = { -0.164, 0.522, 0.948, -0.624 }; int lda = 4; double B[] = { -0.142, 0.778, 0.359, 0.622, -0.637, -0.757, -0.282, -0.805 }; int ldb = 2; double C[] = { -0.09, 0.183 }; int ldc = 1; double C_expected[] = { -0.0248334, 0.1884672 }; cblas_dgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dgemm(case 1481)"); } }; }; { int order = 101; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.0f}; float A[] = { -0.082f, -0.281f, -0.096f, 0.913f, 0.974f, -0.706f, -0.773f, 0.522f }; int lda = 4; float B[] = { 0.745f, -0.664f, 0.352f, -0.733f, 0.304f, -0.555f, -0.493f, -0.089f, 0.188f, 0.631f, 0.235f, 0.152f, -0.299f, -0.731f, -0.686f, -0.332f }; int ldb = 2; float C[] = { -0.179f, -0.284f, -0.996f, -0.414f }; int ldc = 2; float C_expected[] = { -1.06679f, 1.47116f, 0.599689f, 0.933532f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1482) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1482) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.0f}; float A[] = { 0.044f, -0.33f, 0.279f, 0.712f, -0.363f, -0.788f, -0.768f, -0.551f }; int lda = 1; float B[] = { 0.138f, 0.927f, -0.178f, -0.864f, 0.888f, 0.844f, -0.199f, 0.706f, -0.034f, 0.483f, 0.499f, 0.664f, 0.648f, 0.324f, 0.97f, 0.609f }; int ldb = 4; float C[] = { -0.129f, 0.842f, 0.214f, -0.626f }; int ldc = 1; float C_expected[] = { 1.81122f, 1.76205f, 1.0574f, -0.564966f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1483) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1483) imag"); }; }; }; { int order = 101; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.812f, -0.471f, 0.241f, 0.795f, 0.439f, 0.131f, -0.636f, 0.531f }; int lda = 4; float B[] = { 0.062f, 0.807f, 0.873f, 0.372f, 0.239f, 0.804f, 0.537f, -0.954f, -0.396f, 0.838f, 0.081f, 0.15f, 0.489f, -0.438f, 0.165f, 0.429f }; int ldb = 4; float C[] = { 0.868f, 0.329f, -0.509f, 0.724f }; int ldc = 2; float C_expected[] = { -0.868f, -0.329f, 0.509f, -0.724f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1484) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1484) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.832f, 0.198f, 0.794f, -0.522f, -0.319f, 0.578f, 0.332f, 0.746f }; int lda = 1; float B[] = { -0.361f, 0.187f, -0.163f, -0.781f, 0.536f, 0.888f, -0.969f, 0.899f, 0.961f, -0.583f, 0.753f, 0.29f, -0.997f, 0.729f, -0.352f, -0.2f }; int ldb = 2; float C[] = { 0.864f, 0.735f, -0.074f, -0.228f }; int ldc = 1; float C_expected[] = { -0.864f, -0.735f, 0.074f, 0.228f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1485) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1485) imag"); }; }; }; { int order = 101; int transA = 111; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { 0.149f, 0.187f, 0.263f, -0.715f, -0.882f, -0.907f, 0.87f, -0.527f }; int lda = 4; float B[] = { -0.915f, -0.249f, -0.986f, -0.799f, -0.136f, 0.712f, 0.964f, 0.799f, -0.569f, 0.686f, 0.603f, 0.758f, 0.161f, -0.698f, -0.263f, -0.256f }; int ldb = 4; float C[] = { 0.622f, -0.824f, -0.482f, -0.161f }; int ldc = 2; float C_expected[] = { -0.246901f, 0.083044f, 1.25556f, 0.009106f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1486) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1486) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 0.1f}; float A[] = { 0.963f, -0.943f, -0.734f, -0.253f, 0.832f, 0.545f, -0.815f, -0.434f }; int lda = 1; float B[] = { 0.23f, -0.211f, 0.906f, 0.232f, -0.339f, 0.597f, -0.919f, 0.793f, 0.535f, 0.526f, 0.119f, 0.053f, 0.751f, 0.044f, 0.752f, -0.469f }; int ldb = 2; float C[] = { 0.483f, -0.266f, -0.224f, -0.692f }; int ldc = 1; float C_expected[] = { -0.047537f, 0.667177f, 1.02025f, 0.823778f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1487) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1487) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { -0.657f, -0.497f, -0.293f, -0.168f, -0.943f, -0.181f, 0.569f, 0.91f }; int lda = 1; float B[] = { -0.047f, 0.796f, -0.913f, 0.998f, 0.365f, 0.467f, -0.627f, -0.523f, 0.885f, 0.234f, -0.494f, 0.071f, -0.361f, -0.154f, -0.055f, -0.32f }; int ldb = 2; float C[] = { 0.956f, 0.268f, 0.152f, 0.717f }; int ldc = 2; float C_expected[] = { -0.668685f, 0.134477f, -0.715786f, -0.478065f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1488) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1488) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.394f, -0.482f, 0.631f, -0.833f, 0.221f, 0.672f, 0.2f, 0.967f }; int lda = 4; float B[] = { 0.708f, 0.695f, 0.111f, -0.912f, 0.376f, 0.606f, -0.997f, -0.741f, 0.349f, 0.543f, 0.372f, -0.563f, 0.129f, -0.295f, -0.672f, -0.95f }; int ldb = 4; float C[] = { 0.436f, 0.752f, 0.074f, 0.209f }; int ldc = 1; float C_expected[] = { -0.325083f, -0.301952f, -0.283022f, 0.339919f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1489) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1489) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {1.0f, 0.0f}; float beta[2] = {-0.3f, 0.1f}; float A[] = { 0.827f, -0.862f, 0.373f, -0.265f, -0.9f, 0.892f, -0.319f, 0.151f }; int lda = 1; float B[] = { 0.603f, 0.816f, -0.511f, 0.831f, -0.36f, -0.954f, -0.978f, 0.485f, 0.675f, 0.186f, 0.463f, 0.144f, 0.851f, -0.458f, 0.766f, -0.213f }; int ldb = 4; float C[] = { -0.335f, 0.333f, -0.4f, 0.422f }; int ldc = 2; float C_expected[] = { 2.7126f, 0.702111f, 0.437661f, 0.691294f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1490) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1490) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {1.0f, 0.0f}; float beta[2] = {-0.3f, 0.1f}; float A[] = { 0.966f, 0.476f, -0.013f, -0.655f, 0.773f, -0.543f, -0.231f, -0.353f }; int lda = 4; float B[] = { -0.684f, 0.144f, 0.018f, -0.77f, -0.688f, 0.909f, -0.094f, -0.938f, -0.757f, 0.574f, -0.479f, 0.473f, 0.0f, 0.064f, -0.168f, 0.858f }; int ldb = 2; float C[] = { -0.912f, 0.54f, 0.756f, 0.024f }; int ldc = 1; float C_expected[] = { -0.156236f, 0.839112f, -0.230206f, -0.106256f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1491) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1491) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { 0.66f, -0.113f, -0.663f, -0.856f, 0.614f, -0.344f, -0.964f, -0.532f }; int lda = 1; float B[] = { -0.606f, -0.965f, -0.279f, -0.312f, 0.63f, 0.967f, 0.041f, -0.557f, 0.663f, 0.619f, -0.134f, 0.261f, -0.388f, 0.525f, 0.222f, 0.538f }; int ldb = 4; float C[] = { 0.114f, -0.376f, -0.851f, -0.682f }; int ldc = 2; float C_expected[] = { 0.114f, -0.376f, -0.851f, -0.682f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1492) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1492) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { 0.212f, -0.752f, 0.679f, 0.49f, -0.029f, -0.488f, 0.567f, 0.374f }; int lda = 4; float B[] = { -0.914f, 0.734f, -0.845f, 0.059f, -0.297f, 0.152f, -0.417f, -0.669f, 0.831f, -0.544f, 0.022f, 0.102f, -0.379f, -0.357f, -0.394f, -0.588f }; int ldb = 2; float C[] = { -0.584f, 0.373f, 0.235f, 0.521f }; int ldc = 1; float C_expected[] = { -0.584f, 0.373f, 0.235f, 0.521f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1493) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1493) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.135f, 0.128f, 0.909f, -0.963f, 0.299f, -0.944f, 0.944f, 0.942f }; int lda = 1; float B[] = { 0.924f, -0.317f, -0.992f, -0.854f, -0.435f, 0.102f, 0.126f, 0.862f, 0.952f, 0.68f, 0.545f, 0.168f, 0.752f, 0.549f, 0.687f, -0.76f }; int ldb = 2; float C[] = { -0.369f, -0.33f, 0.849f, -0.632f }; int ldc = 2; float C_expected[] = { 0.326537f, 0.37603f, -0.86067f, 0.529817f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1494) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1494) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 111; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {-1.0f, 0.0f}; float A[] = { 0.061f, -0.271f, -0.043f, -0.023f, 0.694f, 0.333f, 0.733f, -0.967f }; int lda = 4; float B[] = { 0.088f, -0.607f, 0.589f, 0.375f, -0.897f, -0.954f, -0.216f, -0.195f, -0.865f, -0.511f, -0.219f, 0.535f, 0.976f, 0.582f, 0.464f, -0.041f }; int ldb = 4; float C[] = { 0.533f, -0.63f, 0.405f, 0.667f }; int ldc = 1; float C_expected[] = { -0.459906f, 0.552595f, -0.425391f, -0.533626f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1495) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1495) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { -0.676f, -0.116f, 0.707f, -0.256f, -0.893f, -0.966f, 0.159f, -0.246f }; int lda = 1; float B[] = { 0.059f, 0.281f, -0.93f, -0.263f, 0.583f, -0.11f, 0.639f, -0.96f, -0.878f, 0.984f, 0.058f, 0.977f, -0.567f, 0.561f, -0.048f, -0.798f }; int ldb = 4; float C[] = { 0.362f, -0.808f, 0.428f, -0.112f }; int ldc = 2; float C_expected[] = { 0.362f, -0.808f, 0.428f, -0.112f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1496) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1496) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 112; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { -0.915f, 0.439f, 0.171f, -0.019f, 0.843f, 0.944f, -0.581f, 0.856f }; int lda = 4; float B[] = { -0.284f, 0.207f, -0.27f, 0.832f, 0.894f, -0.626f, -0.305f, -0.006f, 0.562f, -0.744f, -0.533f, 0.126f, -0.375f, -0.333f, 0.275f, 0.748f }; int ldb = 2; float C[] = { -0.763f, -0.829f, 0.708f, -0.613f }; int ldc = 1; float C_expected[] = { -0.763f, -0.829f, 0.708f, -0.613f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1497) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1497) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {0.0f, 1.0f}; float A[] = { 0.496f, -0.9f, 0.825f, -0.678f, 0.41f, -0.585f, -0.264f, 0.308f }; int lda = 1; float B[] = { 0.907f, 0.972f, -0.724f, 0.745f, -0.601f, 0.589f, 0.759f, -0.521f, -0.161f, -0.321f, 0.341f, -0.981f, -0.378f, -0.671f, -0.314f, -0.878f }; int ldb = 4; float C[] = { -0.293f, 0.07f, 0.087f, -0.542f }; int ldc = 2; float C_expected[] = { 0.10357f, -0.163927f, 0.444626f, -0.0076744f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1498) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1498) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 113; int M = 1; int N = 2; int K = 4; float alpha[2] = {0.0f, 0.1f}; float beta[2] = {0.0f, 1.0f}; float A[] = { -0.225f, -0.629f, -0.939f, -0.836f, -0.841f, -0.794f, 0.836f, -0.65f }; int lda = 4; float B[] = { 0.869f, -0.453f, 0.8f, -0.947f, 0.545f, 0.716f, -0.507f, -0.228f, 0.722f, 0.372f, 0.77f, 0.317f, -0.153f, -0.524f, -0.465f, -0.684f }; int ldb = 2; float C[] = { -0.896f, 0.91f, -0.973f, -0.269f }; int ldc = 1; float C_expected[] = { -1.18974f, -1.0134f, 0.189027f, -1.14494f }; cblas_cgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cgemm(case 1499) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cgemm(case 1499) imag"); }; }; }; { int order = 101; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {1, 0}; double beta[2] = {-1, 0}; double A[] = { -0.33, 0.457, 0.428, -0.19, 0.86, -0.53, 0.058, -0.942 }; int lda = 4; double B[] = { 0.434, 0.653, -0.124, 0.191, -0.112, -0.84, -0.72, 0.075, -0.503, -0.109, 0.3, -0.898, 0.489, 0.384, 0.993, -0.804 }; int ldb = 2; double C[] = { -0.792, -0.155, -0.608, -0.243 }; int ldc = 2; double C_expected[] = { 0.042563, -0.465908, -0.649991, -1.621116 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1500) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1500) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {1, 0}; double beta[2] = {-1, 0}; double A[] = { 0.726, -0.438, -0.23, -0.054, -0.019, 0.902, -0.883, -0.235 }; int lda = 1; double B[] = { 0.159, -0.18, 0.386, -0.167, 0.971, -0.072, 0.87, -0.839, 0.474, 0.956, -0.235, 0.332, 0.826, -0.056, -0.941, 0.01 }; int ldb = 4; double C[] = { -0.799, 0.973, -0.549, -0.177 }; int ldc = 1; double C_expected[] = { -0.181084, 0.257841, 2.251901, 1.558195 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1501) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1501) imag"); }; }; }; { int order = 101; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0.1}; double beta[2] = {1, 0}; double A[] = { 0.109, 0.892, -0.723, 0.793, 0.109, -0.419, -0.534, 0.448 }; int lda = 4; double B[] = { -0.875, -0.31, -0.027, 0.067, 0.274, -0.126, -0.548, 0.497, 0.681, 0.388, 0.909, 0.889, 0.982, -0.074, -0.788, 0.233 }; int ldb = 4; double C[] = { 0.503, 0.067, 0.239, 0.876 }; int ldc = 2; double C_expected[] = { 0.6553584, 0.0864583, 0.2559136, 0.7518389 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1502) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1502) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0.1}; double beta[2] = {1, 0}; double A[] = { 0.334, 0.192, -0.992, -0.168, 0.154, -0.75, -0.797, -0.76 }; int lda = 1; double B[] = { -0.82, 0.147, -0.237, 0.68, 0.317, 0.257, -0.406, -0.802, 0.058, 0.012, -0.832, 0.949, -0.263, -0.085, -0.064, 0.492 }; int ldb = 2; double C[] = { 0.079, -0.602, -0.392, 0.316 }; int ldc = 1; double C_expected[] = { 0.0980569, -0.6430449, -0.539207, 0.4226848 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1503) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1503) imag"); }; }; }; { int order = 101; int transA = 111; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0}; double beta[2] = {-1, 0}; double A[] = { -0.305, -0.698, -0.072, -0.383, 0.364, -0.656, 0.819, 0.194 }; int lda = 4; double B[] = { 0.682, 0.498, -0.389, 0.923, -0.853, -0.558, -0.722, -0.085, -0.27, 0.026, -0.107, -0.036, 0.644, -0.327, -0.894, 0.34 }; int ldb = 4; double C[] = { 0.981, -0.336, -0.377, -0.41 }; int ldc = 2; double C_expected[] = { -0.981, 0.336, 0.377, 0.41 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1504) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1504) imag"); }; }; }; { int order = 102; int transA = 111; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0}; double beta[2] = {-1, 0}; double A[] = { -0.306, -0.709, -0.196, 0.285, 0.873, -0.802, 0.715, -0.179 }; int lda = 1; double B[] = { 0.028, 0.109, 0.87, -0.446, 0.735, 0.731, 0.021, -0.186, 0.541, 0.97, -0.333, 0.002, -0.089, -0.01, 0.331, 0.851 }; int ldb = 2; double C[] = { 0.902, -0.584, -0.695, -0.607 }; int ldc = 1; double C_expected[] = { -0.902, 0.584, 0.695, 0.607 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1505) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1505) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {-1, 0}; double beta[2] = {1, 0}; double A[] = { 0.517, -0.136, 0.72, -0.237, 0.121, -0.66, 0.005, 0.759 }; int lda = 1; double B[] = { -0.606, 0.049, 0.807, -0.236, -0.258, -0.412, 0.75, -0.659, 0.993, -0.029, -0.968, 0.707, -0.362, -0.005, 0.096, -0.241 }; int ldb = 2; double C[] = { 0.63, 0.922, 0.025, -0.535 }; int ldc = 2; double C_expected[] = { 1.117044, 1.983417, -1.276831, -0.447092 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1506) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1506) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {-1, 0}; double beta[2] = {1, 0}; double A[] = { 0.064, 0.371, -0.01, -0.262, 0.143, -0.081, 0.1, -0.062 }; int lda = 4; double B[] = { -0.749, 0.289, -0.239, -0.226, 0.284, 0.668, 0.305, 0.075, -0.36, 0.166, -0.416, 0.234, -0.267, 0.525, 0.116, -0.561 }; int ldb = 4; double C[] = { 0.671, 0.763, 0.444, -0.246 }; int ldc = 1; double C_expected[] = { 0.753107, 0.896395, 0.481996, -0.263126 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1507) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1507) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.956, -0.751, 0.671, -0.633, 0.648, -0.042, 0.948, 0.826 }; int lda = 1; double B[] = { 0.921, 0.506, -0.609, 0.817, -0.686, 0.991, 0.616, -0.482, -0.02, -0.34, 0.559, 0.976, 0.431, 0.385, -0.164, -0.778 }; int ldb = 4; double C[] = { 0.074, -0.01, 0.165, 0.166 }; int ldc = 2; double C_expected[] = { 0.166046, 0.491557, 1.473191, -0.033821 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1508) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1508) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.698, -0.062, 0.023, 0.704, 0.443, -0.46, 0.541, 0.296 }; int lda = 4; double B[] = { 0.787, -0.199, 0.835, -0.276, -0.515, 0.467, -0.76, -0.483, 0.015, -0.394, -0.748, 0.02, 0.573, 0.3, -0.088, -0.238 }; int ldb = 2; double C[] = { 0.935, -0.655, -0.797, 0.071 }; int ldc = 1; double C_expected[] = { -1.070679, 0.178755, -0.344714, -0.308137 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1509) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1509) imag"); }; }; }; { int order = 101; int transA = 112; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0.1}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.202, -0.219, 0.741, 0.527, 0.054, 0.16, -0.359, 0.338 }; int lda = 1; double B[] = { -0.872, 0.995, 0.722, 0.618, -0.27, 0.939, -0.743, 0.547, -0.864, 0.376, -0.997, -0.63, 0.887, -0.454, 0.436, -0.039 }; int ldb = 4; double C[] = { -0.684, 0.463, -0.386, -0.524 }; int ldc = 2; double C_expected[] = { 0.1423153, -0.066679, 0.1175618, 0.0012949 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1510) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1510) imag"); }; }; }; { int order = 102; int transA = 112; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0.1}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.855, -0.173, -0.679, 0.824, 0.469, 0.786, 0.757, -0.109 }; int lda = 4; double B[] = { 0.483, -0.888, -0.757, 0.551, -0.81, 0.23, -0.078, 0.725, -0.592, 0.394, 0.884, 0.802, -0.813, -0.016, -0.853, 0.783 }; int ldb = 2; double C[] = { 0.181, -0.368, -0.864, -0.784 }; int ldc = 1; double C_expected[] = { 0.1728438, 0.1183508, 0.2526999, 0.3004174 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1511) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1511) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {-1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { 0.446, -0.65, -0.724, 0.014, 0.792, -0.695, -0.81, -0.358 }; int lda = 1; double B[] = { -0.08, 0.216, 0.689, 0.699, 0.073, -0.346, 0.821, -0.668, -0.798, 0.869, 0.451, -0.061, -0.41, 0.316, 0.104, -0.514 }; int ldb = 2; double C[] = { -0.476, 0.211, -0.912, -0.243 }; int ldc = 2; double C_expected[] = { 1.372475, -0.135616, 0.549353, -1.968747 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1512) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1512) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 111; int M = 1; int N = 2; int K = 4; double alpha[2] = {-1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { 0.669, 0.046, -0.094, 0.666, 0.23, 0.448, -0.795, -0.142 }; int lda = 4; double B[] = { 0.037, -0.154, -0.739, 0.905, 0.793, -0.53, -0.34, 0.428, 0.072, -0.263, -0.603, -0.905, 0.681, -0.083, -0.511, -0.337 }; int ldb = 4; double C[] = { 0.247, 0.575, -0.836, -0.883 }; int ldc = 1; double C_expected[] = { -0.975939, 0.415528, 0.275533, 0.002716 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1513) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1513) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0}; double beta[2] = {-1, 0}; double A[] = { 0.369, 0.506, 0.217, -0.739, -0.395, 0.16, -0.329, -0.954 }; int lda = 1; double B[] = { -0.622, -0.945, 0.416, -0.884, 0.797, -0.74, 0.519, -0.789, -0.348, 0.563, -0.398, -0.956, 0.227, 0.84, -0.079, 0.847 }; int ldb = 4; double C[] = { 0.833, 0.761, 0.074, -0.448 }; int ldc = 2; double C_expected[] = { -0.833, -0.761, -0.074, 0.448 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1514) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1514) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 112; int M = 1; int N = 2; int K = 4; double alpha[2] = {0, 0}; double beta[2] = {-1, 0}; double A[] = { -0.141, 0.275, 0.717, 0.775, -0.701, -0.689, -0.883, -0.077 }; int lda = 4; double B[] = { -0.526, -0.437, 0.133, -0.209, -0.83, 0.328, 0.916, -0.337, 0.762, -0.664, -0.566, 0.955, 0.168, 0.488, -0.172, -0.535 }; int ldb = 2; double C[] = { -0.88, 0.945, 0.416, 0.99 }; int ldc = 1; double C_expected[] = { 0.88, -0.945, -0.416, -0.99 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1515) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1515) imag"); }; }; }; { int order = 101; int transA = 113; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {-0.3, 0.1}; double beta[2] = {0, 0.1}; double A[] = { -0.534, -0.013, -0.258, -0.31, -0.211, -0.883, -0.89, -0.499 }; int lda = 1; double B[] = { -0.185, -0.798, -0.34, 0.716, 0.035, 0.968, -0.26, 0.784, -0.889, -0.344, -0.685, -0.647, -0.764, 0.03, 0.626, -0.989 }; int ldb = 4; double C[] = { -0.793, -0.551, 0.182, 0.838 }; int ldc = 2; double C_expected[] = { -0.5507177, -0.0286821, 0.2222276, 0.5197398 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1516) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1516) imag"); }; }; }; { int order = 102; int transA = 113; int transB = 113; int M = 1; int N = 2; int K = 4; double alpha[2] = {-0.3, 0.1}; double beta[2] = {0, 0.1}; double A[] = { 0.575, -0.128, -0.702, 0.758, 0.383, -0.914, 0.157, 0.368 }; int lda = 4; double B[] = { 0.572, -0.841, 0.223, -0.334, -0.823, -0.84, 0.671, -0.871, 0.241, 0.927, -0.344, 0.281, -0.034, -0.104, 0.587, -0.329 }; int ldb = 2; double C[] = { -0.612, 0.167, 0.647, 0.447 }; int ldc = 1; double C_expected[] = { -0.7876717, 0.0341179, -0.0800018, 0.5717566 }; cblas_zgemm(order, transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zgemm(case 1517) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zgemm(case 1517) imag"); }; }; }; }
{ "alphanum_fraction": 0.5068645289, "avg_line_length": 30.2278571429, "ext": "c", "hexsha": "aafa4f305eb726d4123260ca747fc7244c85ba95", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_gemm.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_gemm.c", "max_line_length": 156, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_gemm.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": 20219, "size": 42319 }
#pragma once #include <complex> #include <cstddef> #include <cstdint> #include <iosfwd> #include <string> #include <utility> #include <vector> #include <gsl/gsl> #include "chainerx/error.h" #include "chainerx/float16.h" namespace chainerx { // NOTE: The dtype list is not fixed yet!!! enum class Dtype { kBool = 1, kInt8, kInt16, kInt32, kInt64, kUInt8, kFloat16, kFloat32, kFloat64, }; inline bool IsValidDtype(Dtype dtype) { using Underlying = std::underlying_type_t<Dtype>; auto value = static_cast<Underlying>(dtype); return 1 <= value && value <= static_cast<Underlying>(Dtype::kFloat64); } std::ostream& operator<<(std::ostream& os, Dtype dtype); } // namespace chainerx namespace std { template <> struct hash<::chainerx::Dtype> { size_t operator()(::chainerx::Dtype dtype) const { using T = std::underlying_type_t<::chainerx::Dtype>; return hash<T>()(static_cast<T>(dtype)); } }; } // namespace std namespace chainerx { // Kind of dtypes. enum class DtypeKind { kBool = 0, kInt, kUInt, kFloat, }; // Gets the single character identifier compatible to NumPy's dtype kind inline char GetDtypeKindChar(DtypeKind kind) { switch (kind) { case DtypeKind::kBool: return 'b'; case DtypeKind::kInt: return 'i'; case DtypeKind::kUInt: return 'u'; case DtypeKind::kFloat: return 'f'; default: throw DtypeError{"invalid dtype kind"}; } } template <typename T> constexpr bool IsFloatingPointV = std::is_floating_point<T>::value || std::is_same<std::remove_const_t<T>, Float16>::value; // Tag type used for dynamic dispatching with dtype value. // // This class template is used to resolve mapping from runtime dtype values to compile-time primitive types. template <typename T> struct PrimitiveType; #define CHAINERX_DEFINE_PRIMITIVE_TYPE(name, code, dtype, kind, t, dst) \ template <> \ struct PrimitiveType<t> { \ using type = t; \ using device_storage_type = dst; \ static constexpr char kCharCode = code; \ static constexpr Dtype kDtype = dtype; \ static constexpr int64_t kElementSize = sizeof(type); \ static constexpr DtypeKind kKind = kind; \ static const char* GetName() { return name; } \ } // TODO(niboshi): Char codes are mapped according to current development environment. They should be remapped depending on the executing // environment, as in NumPy. CHAINERX_DEFINE_PRIMITIVE_TYPE("bool", '?', Dtype::kBool, DtypeKind::kBool, bool, bool); CHAINERX_DEFINE_PRIMITIVE_TYPE("int8", 'b', Dtype::kInt8, DtypeKind::kInt, int8_t, int8_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("int16", 'h', Dtype::kInt16, DtypeKind::kInt, int16_t, int16_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("int32", 'i', Dtype::kInt32, DtypeKind::kInt, int32_t, int32_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("int64", 'l', Dtype::kInt64, DtypeKind::kInt, int64_t, int64_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("uint8", 'B', Dtype::kUInt8, DtypeKind::kUInt, uint8_t, uint8_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("float16", 'e', Dtype::kFloat16, DtypeKind::kFloat, chainerx::Float16, uint16_t); CHAINERX_DEFINE_PRIMITIVE_TYPE("float32", 'f', Dtype::kFloat32, DtypeKind::kFloat, float, float); CHAINERX_DEFINE_PRIMITIVE_TYPE("float64", 'd', Dtype::kFloat64, DtypeKind::kFloat, double, double); #undef CHAINERX_DEFINE_PRIMITIVE_TYPE namespace dtype_detail { template <typename To, typename From> using WithConstnessOf = std::conditional_t<std::is_const<From>::value, std::add_const_t<To>, std::remove_const_t<To>>; } template <typename T> using TypeToDeviceStorageType = dtype_detail::WithConstnessOf<typename PrimitiveType<std::remove_const_t<T>>::device_storage_type, T>; // Dtype mapped from primitive type. template <typename T> constexpr Dtype TypeToDtype = PrimitiveType<std::remove_const_t<T>>::kDtype; // Invokes a function by passing PrimitiveType<T> corresponding to given dtype value. // // For example, // VisitDtype(Dtype::kInt32, f, args...); // is equivalent to // f(PrimtiveType<int>, args...); // Note that the dtype argument can be a runtime value. This function can be used for dynamic dispatching based on dtype values. // // Note (beam2d): This function should be constexpr, but GCC 5.x does not allow it because of the throw statement, so currently not marked // as constexpr. template <typename F, typename... Args> auto VisitDtype(Dtype dtype, F&& f, Args&&... args) { switch (dtype) { case Dtype::kBool: return std::forward<F>(f)(PrimitiveType<bool>{}, std::forward<Args>(args)...); case Dtype::kInt8: return std::forward<F>(f)(PrimitiveType<int8_t>{}, std::forward<Args>(args)...); case Dtype::kInt16: return std::forward<F>(f)(PrimitiveType<int16_t>{}, std::forward<Args>(args)...); case Dtype::kInt32: return std::forward<F>(f)(PrimitiveType<int32_t>{}, std::forward<Args>(args)...); case Dtype::kInt64: return std::forward<F>(f)(PrimitiveType<int64_t>{}, std::forward<Args>(args)...); case Dtype::kUInt8: return std::forward<F>(f)(PrimitiveType<uint8_t>{}, std::forward<Args>(args)...); case Dtype::kFloat16: return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...); case Dtype::kFloat32: return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...); case Dtype::kFloat64: return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...); default: throw DtypeError{"invalid dtype: ", static_cast<std::underlying_type_t<Dtype>>(dtype)}; } } // Invokes a function by passing PrimitiveType<T> corresponding to given numeric dtype value. // See VisitDtype for more detail. template <typename F, typename... Args> auto VisitNumericDtype(Dtype dtype, F&& f, Args&&... args) { switch (dtype) { case Dtype::kInt8: return std::forward<F>(f)(PrimitiveType<int8_t>{}, std::forward<Args>(args)...); case Dtype::kInt16: return std::forward<F>(f)(PrimitiveType<int16_t>{}, std::forward<Args>(args)...); case Dtype::kInt32: return std::forward<F>(f)(PrimitiveType<int32_t>{}, std::forward<Args>(args)...); case Dtype::kInt64: return std::forward<F>(f)(PrimitiveType<int64_t>{}, std::forward<Args>(args)...); case Dtype::kUInt8: return std::forward<F>(f)(PrimitiveType<uint8_t>{}, std::forward<Args>(args)...); case Dtype::kFloat16: return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...); case Dtype::kFloat32: return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...); case Dtype::kFloat64: return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...); default: throw DtypeError{"invalid dtype"}; } } // Invokes a function by passing PrimitiveType<T> corresponding to given floating-point dtype value. // See VisitDtype for more detail. template <typename F, typename... Args> auto VisitFloatingPointDtype(Dtype dtype, F&& f, Args&&... args) { switch (dtype) { case Dtype::kFloat16: return std::forward<F>(f)(PrimitiveType<chainerx::Float16>{}, std::forward<Args>(args)...); case Dtype::kFloat32: return std::forward<F>(f)(PrimitiveType<float>{}, std::forward<Args>(args)...); case Dtype::kFloat64: return std::forward<F>(f)(PrimitiveType<double>{}, std::forward<Args>(args)...); default: throw DtypeError{"invalid dtype"}; } } // Gets the single character identifier compatible to NumPy's char code inline char GetCharCode(Dtype dtype) { return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kCharCode; }); } // Gets the element size of the dtype in bytes. inline int64_t GetItemSize(Dtype dtype) { return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kElementSize; }); } // Gets the kind of dtype. inline DtypeKind GetKind(Dtype dtype) { return VisitDtype(dtype, [](auto pt) { return decltype(pt)::kKind; }); } Dtype PromoteTypes(Dtype dt1, Dtype dt2); // const char* representation of dtype compatible to NumPy's dtype name. inline const char* GetDtypeName(Dtype dtype) { return VisitDtype(dtype, [](auto pt) { return decltype(pt)::GetName(); }); } // Gets the dtype of given name. Dtype GetDtype(const std::string& name); // Returns a vector of all possible dtype values. std::vector<Dtype> GetAllDtypes(); // Throws an exception if two dtypes mismatch. void CheckEqual(Dtype lhs, Dtype rhs); } // namespace chainerx
{ "alphanum_fraction": 0.6477359939, "avg_line_length": 38.6483050847, "ext": "h", "hexsha": "2c1fcf71c6e1b287a30ab9d5cd3360b02a9f0593", "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": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hitsgub/chainer", "max_forks_repo_path": "chainerx_cc/chainerx/dtype.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "20d4d70f5cdacc1f24f243443f5bebc2055c8f8e", "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": "hitsgub/chainer", "max_issues_repo_path": "chainerx_cc/chainerx/dtype.h", "max_line_length": 138, "max_stars_count": 1, "max_stars_repo_head_hexsha": "324a1bc1ea3edd63d225e4a87ed0a36af7fd712f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hikjik/chainer", "max_stars_repo_path": "chainerx_cc/chainerx/dtype.h", "max_stars_repo_stars_event_max_datetime": "2019-03-09T07:39:07.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-09T07:39:07.000Z", "num_tokens": 2312, "size": 9121 }
#ifndef STDEVSTOOL_H #define STDEVSTOOL_H #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <sys/time.h> #include "pdevslib.h" #include <algorithm> // std::binary_search, std::sort #include <vector> //#include "sink/ParameterReader.h" #define STDEVS_REPRODUCIBLE_SEED 0 // Random reproducible generation. reproducibility of results #define STDEVS_UNIQUE_SEED -1 // Random unique generation #define STDEVS_DEFAULT_SEED STDEVS_UNIQUE_SEED // default in case no configuration #define SCILAB_VARNAME_REPRODUCIBLE_SIMULATION "ReproducibleSimu" // name to be used in the configuration //* Forward declare the functions in ParameterReader.h. Including creates circular inclusion problems*/ //#include "sinks/ParameterReader.h" void printLog(int level, const char *fmt,...); template<typename T> T readDefaultParameterValue(std::string paramName); /* * Class to generate random numbers. * It provides 3 singleton which can be used (it is advised to use always the first one): * 1) Random number generation based on the configuration (probably one of the instances below or a custom seeded) * 2) Reproducible random numbers (uses always the same seed) * 3) need unique random numbers (generates a new seed for every simulation) * It is advisable to use the IDistributionParameter instances, so that random number generation is based on the configuration. * If you don't want to read from the configuration, it is advisable to use the singleton instances available in this class. Only create new instances if you know what you are doing */ class STDEVS { public: // Use this instance in models which need reproducible random numbers (uses always the same seed) static STDEVS* getReproducibleGenerationInstance(); // Use this instance in models which need unique random numbers (generates a new seed) static STDEVS* getUniqueGenerationInstance(); // Unless for specific needs, always use this instance which will point one of the previous based on the configuration or to a custom seeded. static STDEVS* getConfigurationInstance(); /* * It is advisable to use the IDistributionParameter instances, so that random number generation is based on the configuration. * If you don't want to read from the configuration, it is advisable to use the singleton instances available in this class. Only create new instances if you know what you are doing. * If you are creating several instances of STDEVS in a very short time (for example when using VectorialDEVS), evaluate using the singletons available in this class to avoid generating the same seed in several instances. * */ STDEVS(int randSeed); ~STDEVS() {printLog(10, "STDEVS Destroyed \n");}; unsigned int poisson(double mu) { return gsl_ran_poisson (this->r, mu); } double bernoulli (double p) { return gsl_ran_bernoulli (this->r, p); } double exponential(double mu) { return gsl_ran_exponential (this->r, mu); } double uniform () { return gsl_rng_uniform (this->r); } double normal(double mu, double var) { return gsl_ran_gaussian(this -> r, var) + mu;} double pareto(double order, double minValue) { return gsl_ran_pareto(this -> r, order, minValue); } double getWeightedElement(std::vector<double> elements, std::vector<double> weights); std::vector<double> calculateAccumulatedWeights(std::vector<double> weights); std::vector<int> getSortedByWeightSubset(std::vector<double> elements, std::vector<double> weights, const int length); std::vector<int> getWeightedSubset(std::vector<double> elements, std::vector<double> weights, const uint length); double modifyCumsumAvoidIndex(const int avoidIndex, std::vector<double>& cumsum, std::vector<double>& weights, std::vector<double>& elements); private: // Use this instance in models which need reproducible random numbers (uses always the same seed) static STDEVS* ReproducibleGenerationInstance; // Use this instance in models which need unique random numbers (generates a new seed) static STDEVS* UniqueGenerationInstance; // Unless for specific needs, always use this instance which will point one of the previous based on the configuration or to a custom seeded. static STDEVS* ConfigurationInstance; static STDEVS* getConfiguredSTDEVS(); gsl_rng * r; // random seed for the instance struct WeightedComparator { const std::vector<double> & value_vector; WeightedComparator(const std::vector<double> & val_vec): value_vector(val_vec) {} bool operator()(int i1, int i2) { return value_vector[i1] < value_vector[i2]; } }; }; #endif
{ "alphanum_fraction": 0.7582154516, "avg_line_length": 44.1826923077, "ext": "h", "hexsha": "d886a540afea141101d2ca4e2d803a44ae1ad12d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-05T18:05:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-05T18:05:11.000Z", "max_forks_repo_head_hexsha": "dd1697fdc4590de8d687816ec470e40193619b8f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jorexe/haikunet", "max_forks_repo_path": "debug/atomics/hybrid/stdevstool.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dd1697fdc4590de8d687816ec470e40193619b8f", "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": "jorexe/haikunet", "max_issues_repo_path": "debug/atomics/hybrid/stdevstool.h", "max_line_length": 223, "max_stars_count": 2, "max_stars_repo_head_hexsha": "dd1697fdc4590de8d687816ec470e40193619b8f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jorexe/haikunet", "max_stars_repo_path": "debug/atomics/hybrid/stdevstool.h", "max_stars_repo_stars_event_max_datetime": "2022-01-21T13:50:27.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-05T18:22:19.000Z", "num_tokens": 1074, "size": 4595 }
/* This file is part of p4est. p4est is a C library to manage a collection (a forest) of multiple connected adaptive quadtrees or octrees in parallel. Copyright (C) 2010 The University of Texas System Additional copyright (C) 2011 individual authors Written by Carsten Burstedde, Lucas C. Wilcox, and Tobin Isaac p4est 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. p4est 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 p4est; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef P4_TO_P8 #include <p4est_plex.h> #include <p4est_extended.h> #include <p4est_bits.h> #else #include <p8est_plex.h> #include <p8est_extended.h> #include <p8est_bits.h> #endif #ifdef P4EST_WITH_PETSC #include <petsc.h> #include <petscdmplex.h> #include <petscsf.h> const char help[] = "test creating DMPlex from " P4EST_STRING "\n"; static void locidx_to_PetscInt (sc_array_t * array) { sc_array_t *newarray; size_t zz, count = array->elem_count; P4EST_ASSERT (array->elem_size == sizeof (p4est_locidx_t)); if (sizeof (p4est_locidx_t) == sizeof (PetscInt)) { return; } newarray = sc_array_new_size (sizeof (PetscInt), array->elem_count); for (zz = 0; zz < count; zz++) { p4est_locidx_t il = *((p4est_locidx_t *) sc_array_index (array, zz)); PetscInt *ip = (PetscInt *) sc_array_index (newarray, zz); *ip = (PetscInt) il; } sc_array_reset (array); sc_array_init_size (array, sizeof (PetscInt), count); sc_array_copy (array, newarray); sc_array_destroy (newarray); } static void coords_double_to_PetscScalar (sc_array_t * array) { sc_array_t *newarray; size_t zz, count = array->elem_count; P4EST_ASSERT (array->elem_size == 3 * sizeof (double)); if (sizeof (double) == sizeof (PetscScalar)) { return; } newarray = sc_array_new_size (3 * sizeof (PetscScalar), array->elem_count); for (zz = 0; zz < count; zz++) { double *id = (double *) sc_array_index (array, zz); PetscScalar *ip = (PetscScalar *) sc_array_index (newarray, zz); ip[0] = (PetscScalar) id[0]; ip[1] = (PetscScalar) id[1]; ip[2] = (PetscScalar) id[2]; } sc_array_reset (array); sc_array_init_size (array, 3 * sizeof (PetscScalar), count); sc_array_copy (array, newarray); sc_array_destroy (newarray); } static void locidx_pair_to_PetscSFNode (sc_array_t * array) { sc_array_t *newarray; size_t zz, count = array->elem_count; P4EST_ASSERT (array->elem_size == 2 * sizeof (p4est_locidx_t)); newarray = sc_array_new_size (sizeof (PetscSFNode), array->elem_count); for (zz = 0; zz < count; zz++) { p4est_locidx_t *il = (p4est_locidx_t *) sc_array_index (array, zz); PetscSFNode *ip = (PetscSFNode *) sc_array_index (newarray, zz); ip->rank = (PetscInt) il[0]; ip->index = (PetscInt) il[1]; } sc_array_reset (array); sc_array_init_size (array, sizeof (PetscSFNode), count); sc_array_copy (array, newarray); sc_array_destroy (newarray); } #endif #ifndef P4_TO_P8 static int refine_level = 5; #else static int refine_level = 3; #endif static int refine_fn (p4est_t * p4est, p4est_topidx_t which_tree, p4est_quadrant_t * quadrant) { int cid; if (which_tree == 2 || which_tree == 3) { return 0; } cid = p4est_quadrant_child_id (quadrant); if (cid == P4EST_CHILDREN - 1 || (quadrant->x >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2) && quadrant->y >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2) #ifdef P4_TO_P8 && quadrant->z >= P4EST_LAST_OFFSET (P4EST_MAXLEVEL - 2) #endif )) { return 1; } if ((int) quadrant->level >= (refine_level - (int) (which_tree % 3))) { return 0; } if (quadrant->level == 1 && cid == 2) { return 1; } if (quadrant->x == P4EST_QUADRANT_LEN (2) && quadrant->y == P4EST_LAST_OFFSET (2)) { return 1; } if (quadrant->y >= P4EST_QUADRANT_LEN (2)) { return 0; } return 1; } static int refine_tree_one_fn (p4est_t * p4est, p4est_topidx_t which_tree, p4est_quadrant_t * quadrant) { return ! !which_tree; } static int test_forest (int argc, char **argv, p4est_t * p4est, int overlap) { sc_MPI_Comm mpicomm; int mpiret; int mpisize, mpirank; sc_array_t *points_per_dim, *cone_sizes, *cones, *cone_orientations, *coords, *children, *parents, *childids, *leaves, *remotes; p4est_locidx_t first_local_quad = -1; /* initialize MPI */ mpicomm = p4est->mpicomm; mpiret = sc_MPI_Comm_size (mpicomm, &mpisize); SC_CHECK_MPI (mpiret); mpiret = sc_MPI_Comm_rank (mpicomm, &mpirank); SC_CHECK_MPI (mpiret); points_per_dim = sc_array_new (sizeof (p4est_locidx_t)); cone_sizes = sc_array_new (sizeof (p4est_locidx_t)); cones = sc_array_new (sizeof (p4est_locidx_t)); cone_orientations = sc_array_new (sizeof (p4est_locidx_t)); coords = sc_array_new (3 * sizeof (double)); children = sc_array_new (sizeof (p4est_locidx_t)); parents = sc_array_new (sizeof (p4est_locidx_t)); childids = sc_array_new (sizeof (p4est_locidx_t)); leaves = sc_array_new (sizeof (p4est_locidx_t)); remotes = sc_array_new (2 * sizeof (p4est_locidx_t)); p4est_get_plex_data (p4est, P4EST_CONNECT_FULL, (mpisize > 1) ? overlap : 0, &first_local_quad, points_per_dim, cone_sizes, cones, cone_orientations, coords, children, parents, childids, leaves, remotes); #ifdef P4EST_WITH_PETSC { PetscErrorCode ierr; DM plex, refTree; PetscInt pStart, pEnd; PetscSection parentSection; PetscSF pointSF; size_t zz, count; locidx_to_PetscInt (points_per_dim); locidx_to_PetscInt (cone_sizes); locidx_to_PetscInt (cones); locidx_to_PetscInt (cone_orientations); coords_double_to_PetscScalar (coords); locidx_to_PetscInt (children); locidx_to_PetscInt (parents); locidx_to_PetscInt (childids); locidx_to_PetscInt (leaves); locidx_pair_to_PetscSFNode (remotes); P4EST_GLOBAL_PRODUCTION ("Begin PETSc routines\n"); ierr = PetscInitialize (&argc, &argv, 0, help); CHKERRQ (ierr); ierr = DMPlexCreate (mpicomm, &plex); CHKERRQ (ierr); ierr = DMSetDimension (plex, P4EST_DIM); CHKERRQ (ierr); ierr = DMSetCoordinateDim (plex, 3); CHKERRQ (ierr); ierr = DMPlexCreateFromDAG (plex, P4EST_DIM, (PetscInt *) points_per_dim->array, (PetscInt *) cone_sizes->array, (PetscInt *) cones->array, (PetscInt *) cone_orientations->array, (PetscScalar *) coords->array); CHKERRQ (ierr); ierr = PetscSFCreate (mpicomm, &pointSF); CHKERRQ (ierr); ierr = DMPlexCreateDefaultReferenceTree (mpicomm, P4EST_DIM, PETSC_FALSE, &refTree); CHKERRQ (ierr); ierr = DMPlexSetReferenceTree (plex, refTree); CHKERRQ (ierr); ierr = DMDestroy (&refTree); CHKERRQ (ierr); ierr = PetscSectionCreate (mpicomm, &parentSection); CHKERRQ (ierr); ierr = DMPlexGetChart (plex, &pStart, &pEnd); CHKERRQ (ierr); ierr = PetscSectionSetChart (parentSection, pStart, pEnd); CHKERRQ (ierr); count = children->elem_count; for (zz = 0; zz < count; zz++) { PetscInt child = *((PetscInt *) sc_array_index (children, zz)); ierr = PetscSectionSetDof (parentSection, child, 1); CHKERRQ (ierr); } ierr = PetscSectionSetUp (parentSection); CHKERRQ (ierr); ierr = DMPlexSetTree (plex, parentSection, (PetscInt *) parents->array, (PetscInt *) childids->array); CHKERRQ (ierr); ierr = PetscSectionDestroy (&parentSection); CHKERRQ (ierr); ierr = PetscSFSetGraph (pointSF, pEnd - pStart, (PetscInt) leaves->elem_count, (PetscInt *) leaves->array, PETSC_COPY_VALUES, (PetscSFNode *) remotes->array, PETSC_COPY_VALUES); CHKERRQ (ierr); ierr = DMSetPointSF (plex, pointSF); CHKERRQ (ierr); ierr = PetscSFDestroy (&pointSF); CHKERRQ (ierr); ierr = DMViewFromOptions (plex, NULL, "-dm_view"); CHKERRQ (ierr); /* TODO: test with rigid body modes as in plex ex3 */ ierr = DMDestroy (&plex); CHKERRQ (ierr); ierr = PetscFinalize (); P4EST_GLOBAL_PRODUCTION ("End PETSc routines\n"); } #endif sc_array_destroy (points_per_dim); sc_array_destroy (cone_sizes); sc_array_destroy (cones); sc_array_destroy (cone_orientations); sc_array_destroy (coords); sc_array_destroy (children); sc_array_destroy (parents); sc_array_destroy (childids); sc_array_destroy (leaves); sc_array_destroy (remotes); return 0; } static int test_big (int argc, char **argv) { sc_MPI_Comm mpicomm; int mpiret; p4est_t *p4est; p4est_connectivity_t *conn; /* initialize MPI */ mpicomm = sc_MPI_COMM_WORLD; #ifndef P4_TO_P8 conn = p4est_connectivity_new_moebius (); #else conn = p8est_connectivity_new_rotcubes (); #endif p4est = p4est_new_ext (mpicomm, conn, 0, 1, 1, 0, NULL, NULL); p4est_refine (p4est, 1, refine_fn, NULL); p4est_balance (p4est, P4EST_CONNECT_FULL, NULL); p4est_partition (p4est, 0, NULL); mpiret = test_forest (argc, argv, p4est, 2); if (mpiret) { return mpiret; } p4est_destroy (p4est); p4est_connectivity_destroy (conn); return 0; } static int test_small (int argc, char **argv) { sc_MPI_Comm mpicomm; int mpiret; p4est_t *p4est; p4est_connectivity_t *conn; /* initialize MPI */ mpicomm = sc_MPI_COMM_WORLD; #ifndef P4_TO_P8 conn = p4est_connectivity_new_brick (2, 1, 0, 0); #else conn = p8est_connectivity_new_brick (2, 1, 1, 0, 0, 0); #endif p4est = p4est_new (mpicomm, conn, 0, NULL, NULL); p4est_refine (p4est, 0, refine_tree_one_fn, NULL); mpiret = test_forest (argc, argv, p4est, 0); if (mpiret) { return mpiret; } p4est_partition (p4est, 0, NULL); mpiret = test_forest (argc, argv, p4est, 0); if (mpiret) { return mpiret; } p4est_destroy (p4est); p4est_connectivity_destroy (conn); return 0; } int main (int argc, char **argv) { sc_MPI_Comm mpicomm; int mpiret; /* initialize MPI */ mpiret = sc_MPI_Init (&argc, &argv); SC_CHECK_MPI (mpiret); mpicomm = sc_MPI_COMM_WORLD; sc_init (mpicomm, 1, 1, NULL, SC_LP_DEFAULT); p4est_init (NULL, SC_LP_DEFAULT); mpiret = test_small (argc, argv); if (mpiret) { return mpiret; } mpiret = test_big (argc, argv); if (mpiret) { return mpiret; } sc_finalize (); mpiret = sc_MPI_Finalize (); SC_CHECK_MPI (mpiret); return 0; }
{ "alphanum_fraction": 0.6460484081, "avg_line_length": 28.5321782178, "ext": "c", "hexsha": "8ae01ba7885464f2756f49e0a758835032516230", "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": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jmark/p4wrap", "max_forks_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "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": "jmark/p4wrap", "max_issues_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_line_length": 78, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6d237ab8fbe03c8ca985778ac1f65678ecbcccb3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jmark/p4wrap", "max_stars_repo_path": "sites/workstation/gcc/p4est/test/test_plex2.c", "max_stars_repo_stars_event_max_datetime": "2018-06-27T14:29:52.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-02T12:26:35.000Z", "num_tokens": 3527, "size": 11527 }
/* sys/gsl_sys.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_SYS_H__ #define __GSL_SYS_H__ #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS GSL_EXPORT double gsl_log1p (const double x); GSL_EXPORT double gsl_expm1 (const double x); GSL_EXPORT double gsl_hypot (const double x, const double y); GSL_EXPORT double gsl_acosh (const double x); GSL_EXPORT double gsl_asinh (const double x); GSL_EXPORT double gsl_atanh (const double x); GSL_EXPORT int gsl_isnan (const double x); GSL_EXPORT int gsl_isinf (const double x); GSL_EXPORT int gsl_finite (const double x); GSL_EXPORT double gsl_nan (void); GSL_EXPORT double gsl_posinf (void); GSL_EXPORT double gsl_neginf (void); GSL_EXPORT double gsl_fdiv (const double x, const double y); GSL_EXPORT double gsl_coerce_double (const double x); GSL_EXPORT float gsl_coerce_float (const float x); GSL_EXPORT long double gsl_coerce_long_double (const long double x); GSL_EXPORT double gsl_ldexp(const double x, const int e); GSL_EXPORT double gsl_frexp(const double x, int * e); GSL_EXPORT int gsl_fcmp (const double x1, const double x2, const double epsilon); __END_DECLS #endif /* __GSL_SYS_H__ */
{ "alphanum_fraction": 0.7671232877, "avg_line_length": 32.5692307692, "ext": "h", "hexsha": "8f831580f53a84e77b877e7396960b3da4721136", "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_sys.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_sys.h", "max_line_length": 81, "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_sys.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 553, "size": 2117 }
#ifndef LOGGER_INCLUDE #define LOGGER_INCLUDE #include <gsl/string_span> #include "log.h" BOOST_LOG_GLOBAL_LOGGER( exec_helper_log_logger, execHelper::log::LoggerType); // NOLINT(modernize-use-using) static const gsl::czstring<> LOG_CHANNEL = "log"; #define LOG(x) \ BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_log_logger::get(), LOG_CHANNEL, \ x) \ << boost::log::add_value(fileLog, __FILE__) \ << boost::log::add_value(lineLog, __LINE__) #endif /* LOGGER_INCLUDE */
{ "alphanum_fraction": 0.536036036, "avg_line_length": 35.0526315789, "ext": "h", "hexsha": "edd5ed8a5a95fbf2c183eae122622efb06f0a496", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "src/log/include/log/logger.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "exec-helper/source", "max_issues_repo_path": "src/log/include/log/logger.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "src/log/include/log/logger.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 128, "size": 666 }
#ifdef __cplusplus extern "C" { #endif // __cplusplus #ifdef USE_BLAS #include <cblas.h> int _use_blas() { return 1; } #else // USE_BLAS #include <xmmintrin.h> #if defined(_MSC_VER) #define ALIGNAS(byte_alignment) __declspec(align(byte_alignment)) #elif defined(__GNUC__) #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment))) #endif float cblas_snrm2(const int N, const float *m1, const int incX) { if (N % 4 != 0) { fprintf(stderr, "cblas_snrm2() expects N to be a multiple of 4.\n"); exit(EXIT_FAILURE); } float norm = 0; ALIGNAS(16) float z[4]; __m128 X; __m128 Z = _mm_setzero_ps(); for (int i=0; i<N; i+=4) { X = _mm_load_ps(&m1[i]); X = _mm_mul_ps(X, X); Z = _mm_add_ps(X, Z); } _mm_store_ps(z, Z); norm += z[0] + z[1] + z[2] + z[3]; return sqrtf(norm); } float cblas_sdot(const int N, const float *m1, const int incX, const float *m2, const int incY) { if (N % 4 != 0) { fprintf(stderr, "cblas_sdot() expects N to be a multiple of 4.\n"); exit(EXIT_FAILURE); } float dot = 0; ALIGNAS(16) float z[4]; __m128 X, Y; __m128 Z = _mm_setzero_ps(); for (int i=0; i<N; i+=4) { X = _mm_load_ps(&m1[i]); Y = _mm_load_ps(&m2[i]); X = _mm_mul_ps(X, Y); Z = _mm_add_ps(X, Z); } _mm_store_ps(z, Z); dot += z[0] + z[1] + z[2] + z[3]; return dot; } int _use_blas() { return 0; } #endif // USE_BLAS #ifdef __cplusplus } #endif // __cplusplus
{ "alphanum_fraction": 0.5751759437, "avg_line_length": 20.2987012987, "ext": "h", "hexsha": "96c9b90d2727734abcb77790bbf2e8b21ea46a89", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-01-13T02:45:52.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-13T02:45:52.000Z", "max_forks_repo_head_hexsha": "91a181d68fd877dff87624495c86e31438bcd432", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sreyemnayr/sense2vec", "max_forks_repo_path": "include/cblas_shim.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91a181d68fd877dff87624495c86e31438bcd432", "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": "sreyemnayr/sense2vec", "max_issues_repo_path": "include/cblas_shim.h", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "91a181d68fd877dff87624495c86e31438bcd432", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sreyemnayr/sense2vec", "max_stars_repo_path": "include/cblas_shim.h", "max_stars_repo_stars_event_max_datetime": "2019-06-27T13:01:14.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-27T13:01:14.000Z", "num_tokens": 522, "size": 1563 }
/* block/gsl_block_int.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_INT_H__ #define __GSL_BLOCK_INT_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_int_struct { size_t size; int *data; }; typedef struct gsl_block_int_struct gsl_block_int; gsl_block_int *gsl_block_int_alloc (const size_t n); gsl_block_int *gsl_block_int_calloc (const size_t n); void gsl_block_int_free (gsl_block_int * b); int gsl_block_int_fread (FILE * stream, gsl_block_int * b); int gsl_block_int_fwrite (FILE * stream, const gsl_block_int * b); int gsl_block_int_fscanf (FILE * stream, gsl_block_int * b); int gsl_block_int_fprintf (FILE * stream, const gsl_block_int * b, const char *format); int gsl_block_int_raw_fread (FILE * stream, int * b, const size_t n, const size_t stride); int gsl_block_int_raw_fwrite (FILE * stream, const int * b, const size_t n, const size_t stride); int gsl_block_int_raw_fscanf (FILE * stream, int * b, const size_t n, const size_t stride); int gsl_block_int_raw_fprintf (FILE * stream, const int * b, const size_t n, const size_t stride, const char *format); size_t gsl_block_int_size (const gsl_block_int * b); int * gsl_block_int_data (const gsl_block_int * b); __END_DECLS #endif /* __GSL_BLOCK_INT_H__ */
{ "alphanum_fraction": 0.7600886918, "avg_line_length": 34.1666666667, "ext": "h", "hexsha": "8004f765fb8d6665ab1dd49b905c4e1d66d6f7a4", "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_int.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_int.h", "max_line_length": 118, "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_int.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": 599, "size": 2255 }
/* bccgls.c $Revision: 281 $ $Date: 2006-12-13 09:03:53 -0800 (Wed, 13 Dec 2006) $ ---------------------------------------------------------------------- This file is part of BCLS (Bound-Constrained Least Squares). Copyright (C) 2006 Michael P. Friedlander, Department of Computer Science, University of British Columbia, Canada. All rights reserved. E-mail: <mpf@cs.ubc.ca>. BCLS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. BCLS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with BCLS; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ---------------------------------------------------------------------- */ /*! \file This file implements conjugate gradients for the normal equations (CGLS). */ #include <cblas.h> #include <string.h> #include <assert.h> #include <float.h> #include "bcls.h" #include "bclib.h" #include "bccgls.h" /*! \brief Mat-vec routine called by CGLS. CGLS call this routine, which in turn calls bcls_aprod: - If mode == BCLS_PROD_A, y = A dxFree. - else if mode == BCLS_PROD_At, dxFree = A'y. This routine is declared "static" so that it won't be confused with the user's own Aprod routine. \param[in,out] ls BCLS solver context. \param[in] mode Specifies if the product with A or A' is required. \param[in] m Number of rows in A. \param[in] nFree Length of dxFree (and ix which is recovered via ls). \param[in,out] dxFree RHS or LHS (depending on the mode). \param[in,out] y RHS or LHS (depending on the mode). */ static void aprod_free( BCLS *ls, const int mode, const int m, const int nFree, double dxFree[], double y[] ) { int *ix = ls->ix; double *dx = ls->dx; // Used as workspace. assert( mode == BCLS_PROD_A || mode == BCLS_PROD_At ); if (mode == BCLS_PROD_A) { bcls_scatter( nFree, ix, dxFree, dx ); // dx(ix) = dxFree. bcls_aprod( ls, BCLS_PROD_A, nFree, ix, dx, y );// y = A dx. } else { bcls_aprod( ls, BCLS_PROD_At, nFree, ix, dx, y );// dx = A' y. bcls_gather( nFree, ix, dx, dxFree ); // dxFree = dx(ix); } return; } /*! \brief CG for least squares. This routine implements CG for solving the symmetric linear system ( N'N + damp I ) x = N'r + c where N is an m-by-n submatrix of the general matrix A. This implementation is adapted from Hestenes and Stiefel's CG for least-squares method to accomodate the damping term and the additional vector on the RHS. (See, eg, Bjork, Numerical Methods for Least-Squares Problems, 1996, p. 289.) \param[in,out] ls BCLS solver context. \param[in] m No. of rows in A. \param[in] n No. of cols in A. \param[in] kmax Maximum no. of CG iterations. \param[in] tol Required optimality tolerance: - norm( A'A x - A'b ) / norm(A'b) \param[in] damp Regularization term on x. \param[in] c Additional vector (set NULL if not present). \param[out] x Solution vector. \param[in,out] r On entry, r must be defined.\n On exit, r is the residual. \param[in,out] s Work vector. \param[in,out] p Work vector. \param[out] itns No. of CG iterations. \param[out] opt Relative residual (see tol, above). \param[in] nout File for log output (set NULL if not needed). \returns - 0: Required accuracy was achieved. - 1: The iteration limit (kmax) was reached. - 2: N'N appears to be singular. \todo Update normx rather than recompute at each iteration. */ static int bcls_cgls( BCLS *ls, int m, int n, int kmax, double tol, double damp, double c[], double x[], double r[], double s[], double p[], int *itns, double *opt, FILE *nout ) { int k = 0, info = 0, converged = 0, unstable = 0; double xmax = 0.0, resNE, Arnorm, Arnorm0, normp, norms, normx = 0.0, alpha, beta, gamma, gamma1, delta; const int damped = damp > 0.0; const double eps = DBL_EPSILON; // Initialize. bcls_dload( n, 0.0, x, 1 ); // x = 0 aprod_free( ls, BCLS_PROD_At, m, n, s, r ); // s = A'r if (c) cblas_daxpy( n, 1.0, c, 1, s, 1 ); // s += c cblas_dcopy( n, s, 1, p, 1 ); // p = s Arnorm0 = cblas_dnrm2( n, s, 1 ); gamma = Arnorm0 * Arnorm0; if (nout) { fprintf(nout,"\n CGLS:\n"); fprintf(nout," Rows............. %8d\t", m); fprintf(nout," Columns.......... %8d\n", n); fprintf(nout," Optimality tol... %8.1e\t", tol); fprintf(nout," Iteration limit.. %8d\n", kmax); fprintf(nout," Damp............. %8.1e\t", damp); fprintf(nout," Linear term...... %8s\n", (c) ? "yes" : "no" ); fprintf(nout, "\n\n%5s %17s %17s %9s %10s\n", "k", "x(1)","x(n)","normx","resNE"); fprintf(nout, "%5d %17.10e %17.10e %9.2e %10.2e\n", k, x[0], x[n-1], normx, 1.0 ); } // ----------------------------------------------------------------- // Main loop. // ----------------------------------------------------------------- while ( k < kmax && !converged && !unstable ) { k++; aprod_free( ls, BCLS_PROD_A, m, n, p, s ); // s = A p norms = cblas_dnrm2( m, s, 1 ); delta = norms * norms; if (damped) { normp = cblas_dnrm2( n, p, 1 ); delta += damp * normp * normp; } if (delta <= eps) delta = eps; alpha = gamma / delta; cblas_daxpy( n, alpha, p, 1, x, 1 ); // x = x + alpha*p cblas_daxpy( m, -alpha, s, 1, r, 1 ); // r = r - alpha*s aprod_free( ls, BCLS_PROD_At, m, n, s, r ); // s = A'r if (damped) cblas_daxpy( n, -damp, x, 1, s, 1 ); // s += - damp*x if (c) cblas_daxpy( n, 1.0, c, 1, s, 1 ); // s += c Arnorm = cblas_dnrm2( n, s, 1 ); gamma1 = gamma; gamma = Arnorm * Arnorm; beta = gamma / gamma1; cblas_dscal( n, beta, p, 1 ); // p = beta*p cblas_daxpy( n, 1.0, s, 1, p, 1); // p += s // Check convergence. normx = cblas_dnrm2( n, x, 1 ); xmax = fmax( xmax, normx ); converged = Arnorm <= Arnorm0 * tol; unstable = normx * tol >= 1.0; // Output. resNE = Arnorm / Arnorm0; if (nout) fprintf(nout, "%5d %17.10e %17.10e %9.2e %10.2e\n", k, x[0], x[n-1], normx, resNE ); } // while double shrink = normx / xmax; if (converged) info = 0; else if (k >= kmax) info = 1; else if (shrink <= sqrt(tol)) info = 2; // Output. if (nout) fprintf(nout,"\n"); *itns = k; *opt = resNE; return info; } /*! \brief Compute a Newton step using CGLS. See the description of #bcls_newton_step. \param[in,out] ls BCLS solver context \param[in] m No. of rows in A. \param[in] nFree No. of free columns, i.e., no. of cols in N. \param[in] ix Index of vars for which a Newton step is computed. \param[in] damp Regularization term on dxFree. \param[in] itnLim Maximum no. of CG iterations. \param[in] tol Required optimality tolerance: - norm( N'N x - N'b ) / norm(N'b). \param[in] dxFree Newton direction in the free vars (len = nFree). \param[in] x Current iterate. \param[in] c Linear term. (Set to NULL if not present.) \param[in,out] r On entry, r is current residual: r = b - Ax. \n Will be used as workspace. \param[in] itns No. of CG iterations. \param[in] opt Relative residual (see tol, above). \return The termination flag returned by #bcls_cgls. */ int bcls_newton_step_cgls( BCLS *ls, int m, int nFree, int ix[], double damp, int itnLim, double tol, double dxFree[], double x[], double c[], double r[], int *itns, double *opt ) { int j; double *u; const double damp2 = damp*damp; if (c) { u = ls->wrk_u; bcls_gather( nFree, ix, c, u ); // u = c(ix). cblas_dscal( nFree, -1.0, u, 1 ); // u = - c(ix). if ( damp > 0.0 ) // u += - damp2 x(ix). for (j = 0; j < nFree; j++) u[j] -= damp2 * x[ix[j]]; } else u = NULL; return bcls_cgls( ls, m, nFree, itnLim, tol, damp2, u, dxFree, r, ls->wrk_v, ls->wrk_w, itns, opt, ls->minor_file ); }
{ "alphanum_fraction": 0.5265228022, "avg_line_length": 33.5964285714, "ext": "c", "hexsha": "31624219b8b8f3ba347d6a67c50d9d0f22e6244e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_path": "bcls-0.1/src/bccgls.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_path": "bcls-0.1/src/bccgls.c", "max_line_length": 77, "max_stars_count": 3, "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_path": "bcls-0.1/src/bccgls.c", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "num_tokens": 2905, "size": 9407 }
#include "asf.h" #include "asf_meta.h" #include <unistd.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> struct refine_offset_params { meta_parameters *meta; double x_off, y_off; }; static double err_at_pixel(struct refine_offset_params *p, double off_t, double off_x, double line, double samp) { const double huge_err = 999999.9; meta_parameters *meta = p->meta; double line_out, samp_out; double lat, lon; int bad=0; double saved_timeOffset = meta->sar->time_shift; double saved_slant = meta->sar->slant_shift; // converting the pixel's location back to lat/lon is done before // applying the prospective slant and range shifts. bad = meta_get_latLon(meta, line, samp, 0.0, &lat, &lon); if (bad) { printf("bad: meta_get_latLon\n"); return huge_err; } meta->sar->time_shift += off_t; meta->sar->slant_shift += off_x; bad = meta_get_lineSamp(meta, lat, lon, 0.0, &line_out, &samp_out); meta->sar->time_shift = saved_timeOffset; meta->sar->slant_shift = saved_slant; // meta_get_lineSamp returns a non-zero value if, for the specified // lat&lon, we weren't able to determine a line & sample. In this case, // we just return a giant error value. if (bad) { printf("bad: meta_get_lineSamp\n"); return huge_err; } //printf("trying %f,%f\n",off_t,off_x); //printf("at %7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f -> %7.3f\n", // off_t, off_x, line, samp, line_out, samp_out, p->y_off, p->x_off, // fabs(line-line_out-p->y_off)+fabs(samp-samp_out-p->x_off)); double xdiff = line_out - line - p->y_off; double ydiff = samp_out - samp - p->x_off; return sqrt(xdiff*xdiff + ydiff*ydiff); } static int getObjective(const gsl_vector *x, void *params, gsl_vector *f) { double off_t = gsl_vector_get(x,0); double off_x = gsl_vector_get(x,1); if (!meta_is_valid_double(off_x) || !meta_is_valid_double(off_t)) { // This does happen sometimes, when we've already found the root return GSL_FAILURE; } struct refine_offset_params *p = (struct refine_offset_params *)params; meta_parameters *meta = p->meta; int nl = meta->general->line_count; int ns = meta->general->sample_count; double err = 0.0; err += err_at_pixel(p, off_t, off_x, nl/8, ns/8); err += err_at_pixel(p, off_t, off_x, 7*nl/8, ns/8); err += err_at_pixel(p, off_t, off_x, nl/8, 7*ns/8); err += err_at_pixel(p, off_t, off_x, 7*nl/8, 7*ns/8); err += err_at_pixel(p, off_t, off_x, nl/8, ns/2); err += err_at_pixel(p, off_t, off_x, 7*nl/8, ns/2); err += err_at_pixel(p, off_t, off_x, nl/2, 7*ns/8); err += err_at_pixel(p, off_t, off_x, nl/2, ns/8); err += err_at_pixel(p, off_t, off_x, nl/2, ns/2); gsl_vector_set(f,0,err); gsl_vector_set(f,1,err); return GSL_SUCCESS; } /* static void print_state(int iter, gsl_multiroot_fsolver *s) { printf("iter = %3d x = (%.3f %.3f) f(x) = %.8f\n", iter, gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1), gsl_vector_get(s->f, 0)); } */ static void coarse_search(double t_extent_min, double t_extent_max, double x_extent_min, double x_extent_max, double *t_min, double *x_min, struct refine_offset_params *params) { double the_min = 9999999; double min_t=99, min_x=99; int i,j,k=6; double t_extent = t_extent_max - t_extent_min; double x_extent = x_extent_max - x_extent_min; gsl_vector *v = gsl_vector_alloc(2); gsl_vector *u = gsl_vector_alloc(2); //printf(" "); //for (j = 0; j <= k; ++j) { // double x = x_extent_min + ((double)j)/k*x_extent; // printf("%9.3f ", x); //} //printf("\n "); //for (j = 0; j <= k; ++j) // printf("--------- "); //printf("\n"); for (i = 0; i <= k; ++i) { double t = t_extent_min + ((double)i)/k*t_extent; //printf("%9.3f | ", t); for (j = 0; j <= k; ++j) { double x = x_extent_min + ((double)j)/k*x_extent; gsl_vector_set(v, 0, t); gsl_vector_set(v, 1, x); getObjective(v,(void*)params, u); double n = gsl_vector_get(u,0); //printf("%9.3f ", n); if (n<the_min) { the_min=n; min_t=gsl_vector_get(v,0); min_x=gsl_vector_get(v,1); } } //printf("\n"); } *t_min = min_t; *x_min = min_x; gsl_vector_free(v); gsl_vector_free(u); } static void generate_start(struct refine_offset_params *params, double *start_t, double *start_x) { int i; double extent_t_min = -10; double extent_t_max = 10; double extent_x_min = -5000; double extent_x_max = 5000; double t_range = extent_t_max - extent_t_min; double x_range = extent_x_max - extent_x_min; for (i = 0; i < 12; ++i) { coarse_search(extent_t_min, extent_t_max, extent_x_min, extent_x_max, start_t, start_x, params); t_range /= 3; x_range /= 3; extent_t_min = *start_t - t_range/2; extent_t_max = *start_t + t_range/2; extent_x_min = *start_x - x_range/2; extent_x_max = *start_x + x_range/2; //printf("refining search to region: (%9.3f,%9.3f)\n" // " (%9.3f,%9.3f)\n", // extent_t_min, extent_t_max, // extent_x_min, extent_x_max); } } void refine_offset(double x_off, double y_off, meta_parameters *meta, double *out_t, double *out_x) { int status; int iter = 0, max_iter = 1000; const gsl_multiroot_fsolver_type *T; gsl_multiroot_fsolver *s; gsl_error_handler_t *prev; struct refine_offset_params params; const size_t n = 2; params.meta = meta; params.x_off = x_off; params.y_off = y_off; gsl_multiroot_function F = {&getObjective, n, &params}; gsl_vector *x = gsl_vector_alloc(n); double start_t, start_x; generate_start(&params, &start_t, &start_x); //printf("Starting point at (%f,%f)\n", start_t, start_x); gsl_vector_set (x, 0, start_t); gsl_vector_set (x, 1, start_x); T = gsl_multiroot_fsolver_hybrid; s = gsl_multiroot_fsolver_alloc(T, n); gsl_multiroot_fsolver_set(s, &F, x); prev = gsl_set_error_handler_off(); do { ++iter; status = gsl_multiroot_fsolver_iterate(s); //print_state(iter, s); // abort if stuck if (status) break; status = gsl_multiroot_test_residual (s->f, 1e-8); } while (status == GSL_CONTINUE && iter < max_iter); *out_t = gsl_vector_get(s->x, 0); *out_x = gsl_vector_get(s->x, 1); gsl_vector *retrofit = gsl_vector_alloc(n); gsl_vector_set(retrofit, 0, *out_t); gsl_vector_set(retrofit, 1, *out_x); gsl_vector *output = gsl_vector_alloc(n); getObjective(retrofit, (void*)&params, output); //double val= gsl_vector_get(output,0); //printf("GSL Result: %f at (%f,%f)\n", val, *out_t, *out_x); gsl_vector_free(retrofit); gsl_vector_free(output); gsl_multiroot_fsolver_free(s); gsl_vector_free(x); gsl_set_error_handler(prev); }
{ "alphanum_fraction": 0.5971030043, "avg_line_length": 30.1862348178, "ext": "c", "hexsha": "eb86850f5725bae2db0c91acea875da4f5c30ea6", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_sar/refine_offset.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_sar/refine_offset.c", "max_line_length": 78, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_sar/refine_offset.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 2236, "size": 7456 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifndef NOMPI #include <mpi.h> #endif #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/file.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include "allvars.h" #include "proto.h" /*! \file restart.c * \brief Code for reading and writing restart files */ static FILE *fd; static void in(int *x, int modus); static void byten(void *x, size_t n, int modus); /*! This function reads or writes the restart files. Each processor writes * its own restart file, with the I/O being done in parallel. To avoid * congestion of the disks you can tell the program to restrict the number of * files that are simultaneously written to NumFilesWrittenInParallel. * * If modus>0 the restart()-routine reads, if modus==0 it writes a restart * file. */ void restart(int modus) { char buf[200], buf_bak[200], buf_mv[500]; double save_PartAllocFactor, save_TreeAllocFactor; int i, nprocgroup, masterTask, groupTask, old_MaxPart, old_MaxNodes; struct global_data_all_processes all_task0; sprintf(buf, "%s%s.%d", All.OutputDir, All.RestartFile, ThisTask); sprintf(buf_bak, "%s%s.%d.bak", All.OutputDir, All.RestartFile, ThisTask); sprintf(buf_mv, "mv %s %s", buf, buf_bak); if((NTask < All.NumFilesWrittenInParallel)) { printf ("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n"); endrun(2131); } nprocgroup = NTask / All.NumFilesWrittenInParallel; if((NTask % All.NumFilesWrittenInParallel)) { nprocgroup++; } masterTask = (ThisTask / nprocgroup) * nprocgroup; for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */ { if(modus) { if(!(fd = fopen(buf, "r"))) { printf("Restart file '%s' not found.\n", buf); endrun(7870); } } else { system(buf_mv); /* move old restart files to .bak files */ if(!(fd = fopen(buf, "w"))) { printf("Restart file '%s' cannot be opened.\n", buf); endrun(7878); } } save_PartAllocFactor = All.PartAllocFactor; save_TreeAllocFactor = All.TreeAllocFactor; /* common data */ byten(&All, sizeof(struct global_data_all_processes), modus); if(ThisTask == 0 && modus > 0) all_task0 = All; #ifndef NOMPI if(modus > 0 && groupTask == 0) /* read */ { MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD); } #endif old_MaxPart = All.MaxPart; old_MaxNodes = All.TreeAllocFactor * All.MaxPart; if(modus) /* read */ { if(All.PartAllocFactor != save_PartAllocFactor) { All.PartAllocFactor = save_PartAllocFactor; All.MaxPart = All.PartAllocFactor * (All.TotNumPart / NTask); All.MaxPartSph = All.PartAllocFactor * (All.TotN_gas / NTask); save_PartAllocFactor = -1; } if(All.TreeAllocFactor != save_TreeAllocFactor) { All.TreeAllocFactor = save_TreeAllocFactor; save_TreeAllocFactor = -1; } if(all_task0.Time != All.Time) { printf("The restart file on task=%d is not consistent with the one on task=0\n", ThisTask); fflush(stdout); endrun(16); } allocate_memory(); } in(&NumPart, modus); if(NumPart > All.MaxPart) { printf ("it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n", NumPart / (((double) All.TotNumPart) / NTask)); printf("fatal error\n"); endrun(22); } /* Particle data */ byten(&P[0], NumPart * sizeof(struct particle_data), modus); in(&N_gas, modus); if(N_gas > 0) { if(N_gas > All.MaxPartSph) { printf ("SPH: it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n", N_gas / (((double) All.TotN_gas) / NTask)); printf("fatal error\n"); endrun(222); } /* Sph-Particle data */ byten(&SphP[0], N_gas * sizeof(struct sph_particle_data), modus); } /* write state of random number generator */ byten(gsl_rng_state(random_generator), gsl_rng_size(random_generator), modus); /* now store relevant data for tree */ if(modus) /* read */ { ngb_treeallocate(MAX_NGB); force_treeallocate(All.TreeAllocFactor * All.MaxPart, All.MaxPart); } in(&Numnodestree, modus); if(Numnodestree > MaxNodes) { printf ("Tree storage: it seems you have reduced(!) 'PartAllocFactor' below the value needed to load the restart file (task=%d). " "Numnodestree=%d MaxNodes=%d\n", ThisTask, Numnodestree, MaxNodes); endrun(221); } byten(Nodes_base, Numnodestree * sizeof(struct NODE), modus); byten(Extnodes_base, Numnodestree * sizeof(struct extNODE), modus); byten(Father, NumPart * sizeof(int), modus); byten(Nextnode, NumPart * sizeof(int), modus); byten(Nextnode + All.MaxPart, MAXTOPNODES * sizeof(int), modus); byten(DomainStartList, NTask * sizeof(int), modus); byten(DomainEndList, NTask * sizeof(int), modus); byten(DomainTask, MAXTOPNODES * sizeof(int), modus); byten(DomainNodeIndex, MAXTOPNODES * sizeof(int), modus); byten(DomainTreeNodeLen, MAXTOPNODES * sizeof(FLOAT), modus); byten(DomainHmax, MAXTOPNODES * sizeof(FLOAT), modus); byten(DomainMoment, MAXTOPNODES * sizeof(struct DomainNODE), modus); byten(DomainCorner, 3 * sizeof(double), modus); byten(DomainCenter, 3 * sizeof(double), modus); byten(&DomainLen, sizeof(double), modus); byten(&DomainFac, sizeof(double), modus); byten(&DomainMyStart, sizeof(int), modus); byten(&DomainMyLast, sizeof(int), modus); if(modus) /* read */ if(All.PartAllocFactor != save_PartAllocFactor || All.TreeAllocFactor != save_TreeAllocFactor) { for(i = 0; i < NumPart; i++) Father[i] += (All.MaxPart - old_MaxPart); for(i = 0; i < NumPart; i++) if(Nextnode[i] >= old_MaxPart) { if(Nextnode[i] >= old_MaxPart + old_MaxNodes) Nextnode[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxPart); else Nextnode[i] += (All.MaxPart - old_MaxPart); } for(i = 0; i < Numnodestree; i++) { if(Nodes_base[i].u.d.sibling >= old_MaxPart) { if(Nodes_base[i].u.d.sibling >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart); } if(Nodes_base[i].u.d.father >= old_MaxPart) { if(Nodes_base[i].u.d.father >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart); } if(Nodes_base[i].u.d.nextnode >= old_MaxPart) { if(Nodes_base[i].u.d.nextnode >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart); } } for(i = 0; i < MAXTOPNODES; i++) if(Nextnode[i + All.MaxPart] >= old_MaxPart) { if(Nextnode[i + All.MaxPart] >= old_MaxPart + old_MaxNodes) Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart); } for(i = 0; i < MAXTOPNODES; i++) if(DomainNodeIndex[i] >= old_MaxPart) { if(DomainNodeIndex[i] >= old_MaxPart + old_MaxNodes) DomainNodeIndex[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else DomainNodeIndex[i] += (All.MaxPart - old_MaxPart); } } fclose(fd); } else /* wait inside the group */ { #ifndef NOMPI if(modus > 0 && groupTask == 0) /* read */ { MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, GADGET_WORLD); } #endif } #ifndef NOMPI MPI_Barrier(GADGET_WORLD); #endif } } /*! reads/writes n bytes in restart routine */ void byten(void *x, size_t n, int modus) { if(modus) my_fread(x, n, 1, fd); else my_fwrite(x, n, 1, fd); } /*! reads/writes one `int' variable in restart routine */ void in(int *x, int modus) { if(modus) my_fread(x, 1, sizeof(int), fd); else my_fwrite(x, 1, sizeof(int), fd); }
{ "alphanum_fraction": 0.6374152839, "avg_line_length": 27.2547770701, "ext": "c", "hexsha": "8f10a7fa26cce58ece69e04a63c630b2f83cd473", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rieder/amuse", "max_forks_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_issues_count": 690, "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rknop/amuse", "max_issues_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_line_length": 125, "max_stars_count": 131, "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rknop/amuse", "max_stars_repo_path": "src/amuse/community/gadget2/src/restart.c", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "num_tokens": 2550, "size": 8558 }
#include <stdio.h> #include <gsl/gsl_math.h> int main() { printf("PI: %lf\n", M_PI); }
{ "alphanum_fraction": 0.606741573, "avg_line_length": 11.125, "ext": "c", "hexsha": "4ec526fdd7457c61387da9f81154fc04f4ab4e8e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-06-17T13:20:39.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-17T13:20:39.000Z", "max_forks_repo_head_hexsha": "8cee69e09c8557d53d8d30382cec8ea5c1f82f6e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SrikanthParsha14/test", "max_forks_repo_path": "testgsl/testmath.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8cee69e09c8557d53d8d30382cec8ea5c1f82f6e", "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": "SrikanthParsha14/test", "max_issues_repo_path": "testgsl/testmath.c", "max_line_length": 27, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dd1dde14a69d9e8b2c9ed3efbf536df7840f0487", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "quchunguang/test", "max_stars_repo_path": "testgsl/testmath.c", "max_stars_repo_stars_event_max_datetime": "2021-05-06T02:02:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-06T02:02:59.000Z", "num_tokens": 30, "size": 89 }
/* * 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 xml_f13c2b07_0230_4967_8a16_0c276e19b8a2_h #define xml_f13c2b07_0230_4967_8a16_0c276e19b8a2_h #include <gslib/std.h> #include <gslib/tree.h> __gslib_begin__ struct xml_kvpair { string key, value; }; typedef xml_kvpair xml_attr; struct xml_key: public xml_kvpair { xml_key(const string& k) { key = k; } xml_key(const gchar* c) { key.assign(c); } }; struct xml_kvp_hash { size_t operator()(const xml_kvpair& kvp) const { return string_hash(kvp.key); } }; struct xml_kvp_equalto { bool operator()(const xml_kvpair& p1, const xml_kvpair& p2) const { return p1.key == p2.key; } }; template<class _kvpvsl> struct xml_kvp_search { static string* find(_kvpvsl& v, const string& k) { auto i = v.find(xml_key(k)); return i != v.end() ? &(const_cast<string&>(i->value)) : nullptr; } static const string* find(const _kvpvsl& v, const string& k) { auto i = v.find(xml_key(k)); return i != v.end() ? &(i->value) : nullptr; } }; struct __gs_novtable xml_node abstract { typedef unordered_set<xml_kvpair, xml_kvp_hash, xml_kvp_equalto> kvplist; typedef kvplist::iterator iterator; typedef kvplist::const_iterator const_iterator; public: virtual bool is_value() const = 0; virtual void add_attribute(const xml_attr& attr) = 0; virtual string* get_attribute(const string& k) = 0; virtual const string* get_attribute(const string& k) const = 0; virtual void set_attribute(const gchar* k, int len1, const gchar* v, int len2) = 0; virtual void set_attribute(const string& k, const string& v) = 0; virtual int get_attribute_count() const = 0; virtual const string& get_name() const = 0; virtual void set_name(const gchar* str, int len) = 0; virtual string to_string() const = 0; /* for debug */ public: string* get_attribute(const gchar* k) { return get_attribute(string(k)); } const string* get_attribute(const gchar* k) const { return get_attribute(string(k)); } string* get_attribute(const gchar* k, int len) { return get_attribute(string(k, len)); } const string* get_attribute(const gchar* k, int len) const { return get_attribute(string(k, len)); } bool has_attributes() const { return get_attribute_count() != 0; } void set_name(const string& str) { set_name(str.c_str(), str.length()); } }; struct xml_element: public xml_node { string key; kvplist attrlist; public: bool is_value() const override { return false; } void add_attribute(const xml_attr& attr) override { attrlist.insert(attr); } string* get_attribute(const string& k) override { return xml_kvp_search<kvplist>::find(attrlist, k); } const string* get_attribute(const string& k) const override { return xml_kvp_search<kvplist>::find(attrlist, k); } void set_attribute(const gchar* k, int len1, const gchar* v, int len2) override { assert(k && v); string* vstr = get_attribute(string(k, len1)); if(vstr) { vstr->assign(v, len2); return; } xml_attr attr; attr.key.assign(k, len1); attr.value.assign(v, len2); add_attribute(attr); } void set_attribute(const string& k, const string& v) override { string* vstr = get_attribute(k); if(vstr) { vstr->assign(v); return; } xml_attr attr; attr.key = k; attr.value = v; add_attribute(attr); } int get_attribute_count() const override { return (int)attrlist.size(); } const string& get_name() const override { return key; } void set_name(const gchar* str, int len) override { key.assign(str, len); } void set_value(const string& v) { __super::set_name(v); } kvplist& get_attributes() { return attrlist; } const kvplist& const_attributes() const { return attrlist; } string to_string() const override; }; struct xml_value: public xml_node { string value; public: bool is_value() const override { return true; } void add_attribute(const xml_attr& attr) override { assert(!"error!"); } string* get_attribute(const string& k) override { return nullptr; } const string* get_attribute(const string& k) const override { return nullptr; } void set_attribute(const gchar* k, int len1, const gchar* v, int len2) override { assert(!"error!"); } void set_attribute(const string& k, const string& v) override { assert(!"error!"); } int get_attribute_count() const override { return 0; } const string& get_name() const override { return value; } void set_name(const gchar* str, int len) override { value.assign(str, len); } string to_string() const override; }; struct xml_enum { typedef xml_node::iterator iterator; typedef xml_node::const_iterator const_iterator; xml_element* node; iterator iter; xml_enum(xml_node* n) { assert(n && !n->is_value()); node = static_cast<xml_element*>(n); iter = node->attrlist.begin(); } xml_enum(xml_node* n, iterator i) { assert(n && !n->is_value()); node = static_cast<xml_element*>(n); iter = i; } void rewind(iterator i) { iter = i; } const xml_attr& get_attribute() const { return *iter; } bool next() { if(iter == node->attrlist.end()) return false; return ++ iter != node->attrlist.end(); } template<class _lambda> void for_each(_lambda lam) { for_each(node->attrlist.end(), lam); } template<class _lambda> void for_each(iterator end, _lambda lam) { iterator i = iter; for( ; i != end; ++ i) lam(*i); } template<class _lambda> void const_for_each(_lambda lam) const { const_for_each(node->attrlist.end(), lam); } template<class _lambda> void const_for_each(const_iterator end, _lambda lam) const { const_iterator i = iter; for( ; i != end; ++ i) lam(*i); } }; struct xml_const_enum { typedef xml_node::iterator iterator; typedef xml_node::const_iterator const_iterator; const xml_element* node; const_iterator iter; xml_const_enum(const xml_node* n) { assert(n && !n->is_value()); node = static_cast<const xml_element*>(n); iter = node->attrlist.begin(); } xml_const_enum(const xml_node* n, const_iterator i) { assert(n && !n->is_value()); node = static_cast<const xml_element*>(n); iter = i; } void rewind(const_iterator i) { iter = i; } const xml_attr& get_attribute() const { return *iter; } bool next() { if(iter == node->attrlist.end()) return false; return ++ iter != node->attrlist.end(); } template<class _lambda> void const_for_each(_lambda lam) const { const_for_each(node->attrlist.end(), lam); } template<class _lambda> void const_for_each(const_iterator end, _lambda lam) const { const_iterator i = iter; for( ; i != end; ++ i) lam(*i); } }; typedef _treenode_wrapper<xml_node> xml_wrapper; class xmltree: public tree<xml_node, xml_wrapper> { public: enum encodesys { encodesys_unknown, encodesys_ascii, encodesys_mbc, /* multi-byte compatible */ encodesys_wstr, /* wide string */ }; enum encode { encode_unknown, encode_ansi, encode_gb2312, encode_utf8, encode_utf16, }; encodesys _encodesys; encode _encode; protected: static const gchar* skip(const gchar* str); static const gchar* skip(const gchar* str, const gchar* skp); static void replace(string& str, const gchar* s1, const gchar* s2); static void filter_entity_reference(string& s); static void recover_entity_reference(string& s); static void write_attribute(string& str, const gchar* prefix, const xml_attr& attr, const gchar* postfix); static void close_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix); static void begin_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix); static void end_write_item(string& str, const gchar* prefix, const xml_node* node, const gchar* postfix); protected: const gchar* check_header(const gchar* str, string& version, string& encoding); const gchar* read_attribute(const gchar* str, string& k, string& v); const gchar* read_item(const gchar* str, iterator p); void setup_encoding_info(const string& enc); void write_header(string& str) const; void write_item(string& str, const_iterator i) const; public: xmltree(); bool load(const gchar* filename); bool parse(const gchar* src); void output(string& str) const; void save(const gchar* filename) const; void set_encode(encode enc) { _encode = enc; } public: /* * Unique path locater * It was designed to access the DOM easier by a specified string path. * Usage: * 1.basically, we use the string "xx/yy/zz" to specify a path, which means in current position, find a sub node named "xx", * go to the sub node; then find "yy", then "zz", and so on. * the separator could be "/", or backslash "\", as well. * 2.about the name selector "$". * you might also write the path as "$xx/$yy/$zz", it was the same as above; the selector "$" was skippable. * 3.about the counter "@" * you could add a counter into the path, like "$xx@3/yy/zz", in this case, the selector "$" was unskippable. * you could make a nameless selection, like "$@3/yy/zz", which means in the first jump, it would always choose the third node. * or simply wrote "$/yy/zz", which means it would always choose the first node in the first jump. * 4.about the condition specifier "#" * you could add a condition content into the selector; * a condition was defined like: "$xx#aa,bb=cc,!dd|!ee,ff~=gg", * there were two major binary connectors of conditions, "," refer to logic "AND", and "|" refer to logic "OR"; * the priority of "OR" was higher than "AND". * if you need a negative condition, use "!" to reverse the logic, and the "!" should always follow "|" * if a condition content was like the above "aa", which means the selected node must have the attribute named "aa" * if a condition content was wrote like "bb=cc", which means the selected node must have an attribute named "bb" and valued "cc" * if a condition content was wrote like "ff~=gg", which means the selected node must have an attribute named "ff" and valued "gg", * the comparison was case insensitive. * 5.the "$", "@", "#" could be used as a combo, and the announcement should always be in the specified order, $#@ */ iterator unique_path_locater(const gchar* ctlstr) { return unique_path_locater(get_root(), ctlstr); } static iterator unique_path_locater(iterator i, const gchar* ctlstr) { assert(ctlstr); string cpyctlstr(ctlstr); ctlstr = cpyctlstr.c_str(); /* for trap */ ctlstr = upl_run_over(i, ctlstr); if(ctlstr && !ctlstr[0]) return i; return iterator(nullptr); } public: static const gchar* upl_run_once(iterator& i, const gchar* ctlstr); static const gchar* upl_run_over(iterator& i, const gchar* ctlstr) { while(ctlstr && ctlstr[0]) { const gchar* ctlret = upl_run_once(i, ctlstr); if(!ctlret) return ctlstr; ctlstr = ctlret; } return ctlstr; } }; __gslib_end__ #endif
{ "alphanum_fraction": 0.6360776088, "avg_line_length": 37.4971910112, "ext": "h", "hexsha": "c7eb1fad48b07b08d580926818c2aad14fdb4f79", "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/xml.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/xml.h", "max_line_length": 138, "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/xml.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": 3281, "size": 13349 }
/* ieee-utils/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <string.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_test.h> #if defined(HAVE_IRIX_IEEE_INTERFACE) /* don't test denormals on IRIX */ #else #define TEST_DENORMAL 1 #endif int main (void) { float zerof = 0.0f, minus_onef = -1.0f ; double zero = 0.0, minus_one = -1.0 ; /* Check for +ZERO (float) */ { float f = 0.0f; const char mantissa[] = "00000000000000000000000"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = 0, sign is +"); gsl_test_int (r.exponent, -127, "float x = 0, exponent is -127"); gsl_test_str (r.mantissa, mantissa, "float x = 0, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, "float x = 0, type is ZERO"); } /* Check for -ZERO (float) */ { float f = minus_onef; const char mantissa[] = "00000000000000000000000"; gsl_ieee_float_rep r; while (f < 0) { f *= 0.1f; } gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 1, "float x = -1*0, sign is -"); gsl_test_int (r.exponent, -127, "float x = -1*0, exponent is -127"); gsl_test_str (r.mantissa, mantissa, "float x = -1*0, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, "float x = -1*0, type is ZERO"); } /* Check for a positive NORMAL number (e.g. 2.1) (float) */ { float f = 2.1f; const char mantissa[] = "00001100110011001100110"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = 2.1, sign is +"); gsl_test_int (r.exponent, 1, "float x = 2.1, exponent is 1"); gsl_test_str (r.mantissa, mantissa, "float x = 2.1, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = 2.1, type is NORMAL"); } /* Check for a negative NORMAL number (e.g. -1.3304...) (float) */ { float f = -1.3303577090924210f ; const char mantissa[] = "01010100100100100101001"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 1, "float x = -1.3304..., sign is -"); gsl_test_int (r.exponent, 0, "float x = -1.3304..., exponent is 0"); gsl_test_str (r.mantissa, mantissa, "float x = -1.3304..., mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = -1.3304..., type is NORMAL"); } /* Check for a large positive NORMAL number (e.g. 3.37e31) (float) */ { float f = 3.37e31f; const char mantissa[] = "10101001010110101001001"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = 3.37e31, sign is +"); gsl_test_int (r.exponent, 104, "float x = 3.37e31, exponent is 104"); gsl_test_str (r.mantissa, mantissa, "float x = 3.37e31, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = 3.37e31, type is NORMAL"); } /* Check for a small positive NORMAL number (e.g. 3.37e-31) (float) */ { float f = 3.37e-31f; const char mantissa[] = "10110101011100110111011"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = 3.37e-31, sign is +"); gsl_test_int (r.exponent, -102, "float x = 3.37e-31, exponent is -102"); gsl_test_str (r.mantissa, mantissa, "float x = 3.37e-31, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = 3.37e-31, type is NORMAL"); } /* Check for FLT_MIN (smallest possible number that is not denormal) */ { float f = 1.17549435e-38f; /* FLT_MIN (float) */ const char mantissa[] = "00000000000000000000000"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = FLT_MIN, sign is +"); gsl_test_int (r.exponent, -126, "float x = FLT_MIN, exponent is -126"); gsl_test_str (r.mantissa, mantissa, "float x = FLT_MIN, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = FLT_MIN, type is NORMAL"); } /* Check for FLT_MAX (largest possible number that is not Inf) */ { float f = 3.40282347e+38f; /* FLT_MAX */ const char mantissa[] = "11111111111111111111111"; gsl_ieee_float_rep r; gsl_ieee_float_to_rep (&f, &r); gsl_test_int (r.sign, 0, "float x = FLT_MAX, sign is +"); gsl_test_int (r.exponent, 127, "float x = FLT_MAX, exponent is 127"); gsl_test_str (r.mantissa, mantissa, "float x = FLT_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "float x = FLT_MAX, type is NORMAL"); } /* Check for DENORMAL numbers (e.g. FLT_MIN/2^n) */ #ifdef TEST_DENORMAL { float f = 1.17549435e-38f; /* FLT_MIN */ char mantissa[] = "10000000000000000000000"; int i; gsl_ieee_float_rep r; for (i = 0; i < 23; i++) { float x = f / (float)pow (2.0, 1 + (float) i); mantissa[i] = '1'; gsl_ieee_float_to_rep (&x, &r); gsl_test_int (r.sign, 0, "float x = FLT_MIN/2^%d, sign is +", i + 1); gsl_test_int (r.exponent, -127, "float x = FLT_MIN/2^%d, exponent is -127", i + 1); gsl_test_str (r.mantissa, mantissa, "float x = FLT_MIN/2^%d, mantissa", i + 1); gsl_test_int (r.type, GSL_IEEE_TYPE_DENORMAL, "float x = FLT_MIN/2^%d, type is DENORMAL", i + 1); mantissa[i] = '0'; } } #endif /* Check for positive INFINITY (e.g. 2*FLT_MAX) */ { float f = 3.40282347e+38f; /* FLT_MAX */ const char mantissa[] = "00000000000000000000000"; gsl_ieee_float_rep r; float x; x = 2 * f; gsl_ieee_float_to_rep (&x, &r); gsl_test_int (r.sign, 0, "float x = 2*FLT_MAX, sign is +"); gsl_test_int (r.exponent, 128, "float x = 2*FLT_MAX, exponent is 128"); gsl_test_str (r.mantissa, mantissa, "float x = 2*FLT_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_INF, "float x = -2*FLT_MAX, type is INF"); } /* Check for negative INFINITY (e.g. -2*FLT_MAX) */ { float f = 3.40282347e+38f; /* FLT_MAX */ const char mantissa[] = "00000000000000000000000"; gsl_ieee_float_rep r; float x; x = -2 * f; gsl_ieee_float_to_rep (&x, &r); gsl_test_int (r.sign, 1, "float x = -2*FLT_MAX, sign is -"); gsl_test_int (r.exponent, 128, "float x = -2*FLT_MAX, exponent is 128"); gsl_test_str (r.mantissa, mantissa, "float x = -2*FLT_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_INF, "float x = -2*FLT_MAX, type is INF"); } /* Check for NAN (e.g. Inf - Inf) (float) */ { gsl_ieee_float_rep r; float x = 1.0f, y = 2.0f, z = zerof; x = x / z; y = y / z; z = y - x; gsl_ieee_float_to_rep (&z, &r); /* We don't check the sign and we don't check the mantissa because they could be anything for a NaN */ gsl_test_int (r.exponent, 128, "float x = NaN, exponent is 128"); gsl_test_int (r.type, GSL_IEEE_TYPE_NAN, "float x = NaN, type is NAN"); } /* Check for +ZERO */ { double d = 0.0; const char mantissa[] = "0000000000000000000000000000000000000000000000000000"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = 0, sign is +"); gsl_test_int (r.exponent, -1023, "double x = 0, exponent is -1023"); gsl_test_str (r.mantissa, mantissa, "double x = 0, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, "double x = 0, type is ZERO"); } /* Check for -ZERO */ { double d = minus_one; const char mantissa[] = "0000000000000000000000000000000000000000000000000000"; gsl_ieee_double_rep r; while (d < 0) { d *= 0.1; } gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 1, "double x = -1*0, sign is -"); gsl_test_int (r.exponent, -1023, "double x = -1*0, exponent is -1023"); gsl_test_str (r.mantissa, mantissa, "double x = -1*0, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_ZERO, "double x = -1*0, type is ZERO"); } /* Check for a positive NORMAL number (e.g. 2.1) */ { double d = 2.1; const char mantissa[] = "0000110011001100110011001100110011001100110011001101"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = 2.1, sign is +"); gsl_test_int (r.exponent, 1, "double x = 2.1, exponent is 1"); gsl_test_str (r.mantissa, mantissa, "double x = 2.1, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = 2.1, type is NORMAL"); } /* Check for a negative NORMAL number (e.g. -1.3304...) */ { double d = -1.3303577090924210146738460025517269968986511230468750; const char mantissa[] = "0101010010010010010100101010010010001000100011101110"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 1, "double x = -1.3304..., sign is -"); gsl_test_int (r.exponent, 0, "double x = -1.3304..., exponent is 0"); gsl_test_str (r.mantissa, mantissa, "double x = -1.3304..., mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = -1.3304..., type is NORMAL"); } /* Check for a large positive NORMAL number (e.g. 3.37e297) */ { double d = 3.37e297; const char mantissa[] = "0100100111001001100101111001100000100110011101000100"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = 3.37e297, sign is +"); gsl_test_int (r.exponent, 988, "double x = 3.37e297, exponent is 998"); gsl_test_str (r.mantissa, mantissa, "double x = 3.37e297, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = 3.37e297, type is NORMAL"); } /* Check for a small positive NORMAL number (e.g. 3.37e-297) */ { double d = 3.37e-297; const char mantissa[] = "0001101000011011101011100001110010100001001100110111"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = 3.37e-297, sign is +"); gsl_test_int (r.exponent, -985, "double x = 3.37e-297, exponent is -985"); gsl_test_str (r.mantissa, mantissa, "double x = 3.37e-297, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = 3.37e-297, type is NORMAL"); } /* Check for DBL_MIN (smallest possible number that is not denormal) */ { double d = 2.2250738585072014e-308; /* DBL_MIN */ const char mantissa[] = "0000000000000000000000000000000000000000000000000000"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = DBL_MIN, sign is +"); gsl_test_int (r.exponent, -1022, "double x = DBL_MIN, exponent is -1022"); gsl_test_str (r.mantissa, mantissa, "double x = DBL_MIN, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = DBL_MIN, type is NORMAL"); } /* Check for DBL_MAX (largest possible number that is not Inf) */ { double d = 1.7976931348623157e+308; /* DBL_MAX */ const char mantissa[] = "1111111111111111111111111111111111111111111111111111"; gsl_ieee_double_rep r; gsl_ieee_double_to_rep (&d, &r); gsl_test_int (r.sign, 0, "double x = DBL_MAX, sign is +"); gsl_test_int (r.exponent, 1023, "double x = DBL_MAX, exponent is 1023"); gsl_test_str (r.mantissa, mantissa, "double x = DBL_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_NORMAL, "double x = DBL_MAX, type is NORMAL"); } /* Check for DENORMAL numbers (e.g. DBL_MIN/2^n) */ #ifdef TEST_DENORMAL { double d = 2.2250738585072014e-308; /* DBL_MIN */ char mantissa[] = "1000000000000000000000000000000000000000000000000000"; int i; gsl_ieee_double_rep r; for (i = 0; i < 52; i++) { double x = d / pow (2.0, 1 + (double) i); mantissa[i] = '1'; gsl_ieee_double_to_rep (&x, &r); gsl_test_int (r.sign, 0, "double x = DBL_MIN/2^%d, sign is +", i + 1); gsl_test_int (r.exponent, -1023, "double x = DBL_MIN/2^%d, exponent", i + 1); gsl_test_str (r.mantissa, mantissa, "double x = DBL_MIN/2^%d, mantissa", i + 1); gsl_test_int (r.type, GSL_IEEE_TYPE_DENORMAL, "double x = DBL_MIN/2^%d, type is DENORMAL", i + 1); mantissa[i] = '0'; } } #endif /* Check for positive INFINITY (e.g. 2*DBL_MAX) */ { double d = 1.7976931348623157e+308; /* DBL_MAX */ const char mantissa[] = "0000000000000000000000000000000000000000000000000000"; gsl_ieee_double_rep r; double x; x = 2.0 * d; gsl_ieee_double_to_rep (&x, &r); gsl_test_int (r.sign, 0, "double x = 2*DBL_MAX, sign is +"); gsl_test_int (r.exponent, 1024, "double x = 2*DBL_MAX, exponent is 1024"); gsl_test_str (r.mantissa, mantissa, "double x = 2*DBL_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_INF, "double x = 2*DBL_MAX, type is INF"); } /* Check for negative INFINITY (e.g. -2*DBL_MAX) */ { double d = 1.7976931348623157e+308; /* DBL_MAX */ const char mantissa[] = "0000000000000000000000000000000000000000000000000000"; gsl_ieee_double_rep r; double x; x = -2.0 * d; gsl_ieee_double_to_rep (&x, &r); gsl_test_int (r.sign, 1, "double x = -2*DBL_MAX, sign is -"); gsl_test_int (r.exponent, 1024, "double x = -2*DBL_MAX, exponent is 1024"); gsl_test_str (r.mantissa, mantissa, "double x = -2*DBL_MAX, mantissa"); gsl_test_int (r.type, GSL_IEEE_TYPE_INF,"double x = -2*DBL_MAX, type is INF"); } /* Check for NAN (e.g. Inf - Inf) */ { gsl_ieee_double_rep r; double x = 1.0, y = 2.0, z = zero; x = x / z; y = y / z; z = y - x; gsl_ieee_double_to_rep (&z, &r); /* We don't check the sign and we don't check the mantissa because they could be anything for a NaN */ gsl_test_int (r.exponent, 1024, "double x = NaN, exponent is 1024"); gsl_test_int (r.type, GSL_IEEE_TYPE_NAN, "double x = NaN, type is NAN"); } exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.6392218645, "avg_line_length": 31.3956989247, "ext": "c", "hexsha": "30136128adeaf18ec3c04d2d7bdbb1174151532f", "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/ieee-utils/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/ieee-utils/test.c", "max_line_length": 85, "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/ieee-utils/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": 5043, "size": 14599 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gbpLib.h> #include <gbpMath.h> #include <gbpHalos.h> #include <gsl/gsl_sf_zeta.h> #define READ_MATCHES_GOODNESS_A 1.4421650782960167E+01 #define READ_MATCHES_GOODNESS_B 2.7010890377990435E+01 #define READ_MATCHES_GOODNESS_C ONE_THIRD #define READ_MATCHES_GOODNESS_D -2.4490239433470165E+00 #define MAXIMUM_SCORE_COEFF 2.61 // Only if MATCH_SCORE_RANK_INDEX=-1.5. This comes from Wolfram Alpha. Query "sum k^(-1.5) from k = 1 to N" #define EULER_MASCHERONI_CONST 0.5772 // Used if MATCH_SCORE_RANK_INDEX=-1 float maximum_match_score(double n_particles) { if(n_particles < 1) return (0); if(MATCH_SCORE_RANK_INDEX == (-1.5)) return (MAXIMUM_SCORE_COEFF - gsl_sf_hzeta(-MATCH_SCORE_RANK_INDEX, n_particles)); else if(MATCH_SCORE_RANK_INDEX == (-1.)) return (EULER_MASCHERONI_CONST + take_ln(n_particles)); else if(MATCH_SCORE_RANK_INDEX == (-TWO_THIRDS)) return ((float)pow(READ_MATCHES_GOODNESS_A + READ_MATCHES_GOODNESS_B * n_particles, READ_MATCHES_GOODNESS_C) + READ_MATCHES_GOODNESS_D); else SID_exit_error( "Invalid MATCH_SCORE_RANK_INDEX passed to maximum_match_score(). Please update the code to accomodate MATCH_SCORE_RANK_INDEX=%lf.", SID_ERROR_LOGIC, MATCH_SCORE_RANK_INDEX); }
{ "alphanum_fraction": 0.7441860465, "avg_line_length": 43, "ext": "c", "hexsha": "eac93a09b83a676b395777d76218b87425da2e39", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpAstro/gbpHalos/maximum_match_score.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpAstro/gbpHalos/maximum_match_score.c", "max_line_length": 148, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpAstro/gbpHalos/maximum_match_score.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": 390, "size": 1376 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <string.h> //** Init Multinomial gsl_rng* init_gsl_rng(){ gsl_rng* r; const gsl_rng_type* T2; srand(time(NULL)); unsigned int seed; seed= rand(); gsl_rng_env_setup(); T2 = gsl_rng_default; r = gsl_rng_alloc (T2); gsl_rng_set (r, seed); return r; } unsigned int substract(unsigned int val){ if(val>0) return val-1; else return 0; } //** Data must be dictionated //** Doc-Word-topic void dt2b_inference(int** data , unsigned int** uKu, unsigned int** pKp, unsigned int** KuKp, const int it, const int Ku,const int Kp, const int nusers, const int nplaces, const int nrecs){ float l,prev_l,prob=0; //** Allocate Dynamic Tables unsigned int zu[Ku]; memset( zu, 0, Ku*sizeof(unsigned int) ); unsigned int zp[Kp]; memset( zp, 0, Kp*sizeof(unsigned int) ); double p_zuzp[Ku][Kp]; //** Initialization gsl_rng * r; r=init_gsl_rng(); //** Initialize Dynamic Tables unsigned int oneutopic,oneptopic; size_t rowid; for(rowid=0;rowid<nrecs;rowid++){ oneutopic=data[rowid][2]; oneptopic=data[rowid][3]; zu[(size_t)oneutopic]++; zp[(size_t)oneptopic]++; } //** Iterate size_t i,s,kp,ku; int curr_u,curr_p,curr_ku,curr_kp; for(i=0;i<it;i++){ l=0; //printf("iteration %zu\n",i); for(rowid=0;rowid<nrecs;rowid++){ //** Discount curr_u=data[rowid][0]; curr_p=data[rowid][1]; curr_ku=data[rowid][2]; curr_kp=data[rowid][3]; uKu[curr_u][curr_ku]=substract(uKu[curr_u][curr_ku]); pKp[curr_p][curr_kp]=substract(pKp[curr_p][curr_kp]); KuKp[curr_ku][curr_kp]=substract(KuKp[curr_ku][curr_kp]); zu[curr_ku]=substract(zu[curr_ku]); zp[curr_kp]=substract(zp[curr_kp]); //** Obtain Posterior prob=0; for(ku=0;ku<Ku;ku++){ for(kp=0;kp<Kp;kp++){ p_zuzp[ku][kp]=((KuKp[ku][kp]+0.5)*(uKu[curr_u][ku]+0.5)*(pKp[curr_p][kp]+0.5))/((zu[ku]+0.5*nusers)*(zp[kp]+0.5*nplaces)); prob+=p_zuzp[ku][kp]; } } l+=log(prob); //** Obtain one sample unsigned int samples[Ku*Kp]; double* p_z = (double*) p_zuzp; gsl_ran_multinomial(r, Ku*Kp, 1, p_z, samples); size_t chosen_ku,chosen_kp; for(s=0;s<Ku*Kp;s++){ if (samples[s]>0){ //get two indexes from one chosen_ku=(unsigned int) (s/Kp); chosen_kp=(unsigned int) (s%Kp); break; } } //** Update data[rowid][2]=chosen_ku; data[rowid][3]=chosen_kp; uKu[curr_u][chosen_ku]+=1; pKp[curr_p][chosen_kp]+=1; KuKp[chosen_ku][chosen_kp]+=1; zu[chosen_ku]+=1; zp[chosen_kp]+=1; } if (i==0) prev_l=l; //** Check convergence if (l<prev_l && i>50){ printf("Stopped at iteration %zu",i); break; } printf("Likelihood at iteration %zu: %f \n",i,l); } gsl_rng_free (r); }
{ "alphanum_fraction": 0.5994650619, "avg_line_length": 20.3469387755, "ext": "c", "hexsha": "4660b5d285cd2a125be188536a015537f3c914a3", "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": "284730d538167342f9d215b6fea0c1a3c186568a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "danrugeles/YLDA", "max_forks_repo_path": "C/DT2B/dt2b_inference.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "284730d538167342f9d215b6fea0c1a3c186568a", "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": "danrugeles/YLDA", "max_issues_repo_path": "C/DT2B/dt2b_inference.c", "max_line_length": 191, "max_stars_count": null, "max_stars_repo_head_hexsha": "284730d538167342f9d215b6fea0c1a3c186568a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "danrugeles/YLDA", "max_stars_repo_path": "C/DT2B/dt2b_inference.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1095, "size": 2991 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <nubspline.h> #include "SimulationSteps.h" #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> void eval_NUBspline_1d_d(NUBspline_1d_d * restrict spline, double x, double* restrict val); void eval_NUBspline_1d_d_vg(NUBspline_1d_d * restrict spline, double x, double* restrict val, double* restrict grad); void eval_NUBspline_1d_d_vgl(NUBspline_1d_d * restrict spline, double x, double* restrict val, double* restrict grad, double* restrict lapl); void InterpolateWithSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* NodalX, double *func, double *NodalFunc, double* NodalDeriv) { NUgrid* myGrid = create_general_grid(x, NumPointsToInterpolate); BCtype_d myBC; myBC.lCode = NATURAL; myBC.rCode = NATURAL; NUBspline_1d_d *mySpline = create_NUBspline_1d_d(myGrid, myBC, func); for(int i =0; i < NumPointsToEvaluate; i++) { if (NodalDeriv != NULL) eval_NUBspline_1d_d_vg(mySpline, NodalX[i], &NodalFunc[i], &NodalDeriv[i]); else eval_NUBspline_1d_d(mySpline, NodalX[i], &NodalFunc[i]); } } void InterpolateWithGSLSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* NodalX, double* func, double* NodalFunc, double* NodalDeriv) { gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline* spline = gsl_spline_alloc(gsl_interp_cspline, NumPointsToInterpolate); gsl_spline_init(spline, x, func, NumPointsToInterpolate); for(int j = 0; j < NumPointsToEvaluate; j++) { NodalFunc[j] = gsl_spline_eval(spline, NodalX[j], acc); if (NodalDeriv != NULL) NodalDeriv[j] = gsl_spline_eval_deriv(spline, NodalX[j], acc); } }
{ "alphanum_fraction": 0.7583135392, "avg_line_length": 33.0196078431, "ext": "c", "hexsha": "bcde33b00f2dac74ed0a3515b1de3aa2c23869ed", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_path": "1DCode/SplineInterpolation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "evalseth/DG-RAIN", "max_issues_repo_path": "1DCode/SplineInterpolation.c", "max_line_length": 163, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_path": "1DCode/SplineInterpolation.c", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "num_tokens": 547, "size": 1684 }
/* rng/gsl_rng.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_RNG_H__ #define __GSL_RNG_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #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 { const char *name; unsigned long int max; unsigned long int min; size_t size; void (*set) (void *state, unsigned long int seed); unsigned long int (*get) (void *state); double (*get_double) (void *state); } gsl_rng_type; typedef struct { const gsl_rng_type * type; void *state; } gsl_rng; /* These structs also need to appear in default.c so you can select them via the environment variable GSL_RNG_TYPE */ GSL_VAR const gsl_rng_type *gsl_rng_borosh13; GSL_VAR const gsl_rng_type *gsl_rng_coveyou; GSL_VAR const gsl_rng_type *gsl_rng_cmrg; GSL_VAR const gsl_rng_type *gsl_rng_fishman18; GSL_VAR const gsl_rng_type *gsl_rng_fishman20; GSL_VAR const gsl_rng_type *gsl_rng_fishman2x; GSL_VAR const gsl_rng_type *gsl_rng_gfsr4; GSL_VAR const gsl_rng_type *gsl_rng_knuthran; GSL_VAR const gsl_rng_type *gsl_rng_knuthran2; GSL_VAR const gsl_rng_type *gsl_rng_knuthran2002; GSL_VAR const gsl_rng_type *gsl_rng_lecuyer21; GSL_VAR const gsl_rng_type *gsl_rng_minstd; GSL_VAR const gsl_rng_type *gsl_rng_mrg; GSL_VAR const gsl_rng_type *gsl_rng_mt19937; GSL_VAR const gsl_rng_type *gsl_rng_mt19937_1999; GSL_VAR const gsl_rng_type *gsl_rng_mt19937_1998; GSL_VAR const gsl_rng_type *gsl_rng_r250; GSL_VAR const gsl_rng_type *gsl_rng_ran0; GSL_VAR const gsl_rng_type *gsl_rng_ran1; GSL_VAR const gsl_rng_type *gsl_rng_ran2; GSL_VAR const gsl_rng_type *gsl_rng_ran3; GSL_VAR const gsl_rng_type *gsl_rng_rand; GSL_VAR const gsl_rng_type *gsl_rng_rand48; GSL_VAR const gsl_rng_type *gsl_rng_random128_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random128_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random128_libc5; GSL_VAR const gsl_rng_type *gsl_rng_random256_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random256_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random256_libc5; GSL_VAR const gsl_rng_type *gsl_rng_random32_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random32_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random32_libc5; GSL_VAR const gsl_rng_type *gsl_rng_random64_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random64_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random64_libc5; GSL_VAR const gsl_rng_type *gsl_rng_random8_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random8_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random8_libc5; GSL_VAR const gsl_rng_type *gsl_rng_random_bsd; GSL_VAR const gsl_rng_type *gsl_rng_random_glibc2; GSL_VAR const gsl_rng_type *gsl_rng_random_libc5; GSL_VAR const gsl_rng_type *gsl_rng_randu; GSL_VAR const gsl_rng_type *gsl_rng_ranf; GSL_VAR const gsl_rng_type *gsl_rng_ranlux; GSL_VAR const gsl_rng_type *gsl_rng_ranlux389; GSL_VAR const gsl_rng_type *gsl_rng_ranlxd1; GSL_VAR const gsl_rng_type *gsl_rng_ranlxd2; GSL_VAR const gsl_rng_type *gsl_rng_ranlxs0; GSL_VAR const gsl_rng_type *gsl_rng_ranlxs1; GSL_VAR const gsl_rng_type *gsl_rng_ranlxs2; GSL_VAR const gsl_rng_type *gsl_rng_ranmar; GSL_VAR const gsl_rng_type *gsl_rng_slatec; GSL_VAR const gsl_rng_type *gsl_rng_taus; GSL_VAR const gsl_rng_type *gsl_rng_taus2; GSL_VAR const gsl_rng_type *gsl_rng_taus113; GSL_VAR const gsl_rng_type *gsl_rng_transputer; GSL_VAR const gsl_rng_type *gsl_rng_tt800; GSL_VAR const gsl_rng_type *gsl_rng_uni; GSL_VAR const gsl_rng_type *gsl_rng_uni32; GSL_VAR const gsl_rng_type *gsl_rng_vax; GSL_VAR const gsl_rng_type *gsl_rng_waterman14; GSL_VAR const gsl_rng_type *gsl_rng_zuf; GSL_FUN const gsl_rng_type ** gsl_rng_types_setup(void); GSL_VAR const gsl_rng_type *gsl_rng_default; GSL_VAR unsigned long int gsl_rng_default_seed; GSL_FUN gsl_rng *gsl_rng_alloc (const gsl_rng_type * T); GSL_FUN int gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src); GSL_FUN gsl_rng *gsl_rng_clone (const gsl_rng * r); GSL_FUN void gsl_rng_free (gsl_rng * r); GSL_FUN void gsl_rng_set (const gsl_rng * r, unsigned long int seed); GSL_FUN unsigned long int gsl_rng_max (const gsl_rng * r); GSL_FUN unsigned long int gsl_rng_min (const gsl_rng * r); GSL_FUN const char *gsl_rng_name (const gsl_rng * r); GSL_FUN int gsl_rng_fread (FILE * stream, gsl_rng * r); GSL_FUN int gsl_rng_fwrite (FILE * stream, const gsl_rng * r); GSL_FUN size_t gsl_rng_size (const gsl_rng * r); GSL_FUN void * gsl_rng_state (const gsl_rng * r); GSL_FUN void gsl_rng_print_state (const gsl_rng * r); GSL_FUN const gsl_rng_type * gsl_rng_env_setup (void); GSL_FUN INLINE_DECL unsigned long int gsl_rng_get (const gsl_rng * r); GSL_FUN INLINE_DECL double gsl_rng_uniform (const gsl_rng * r); GSL_FUN INLINE_DECL double gsl_rng_uniform_pos (const gsl_rng * r); GSL_FUN INLINE_DECL unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n); #ifdef HAVE_INLINE INLINE_FUN unsigned long int gsl_rng_get (const gsl_rng * r) { return (r->type->get) (r->state); } INLINE_FUN double gsl_rng_uniform (const gsl_rng * r) { return (r->type->get_double) (r->state); } INLINE_FUN double gsl_rng_uniform_pos (const gsl_rng * r) { double x ; do { x = (r->type->get_double) (r->state) ; } while (x == 0) ; return x ; } /* Note: to avoid integer overflow in (range+1) we work with scale = range/n = (max-min)/n rather than scale=(max-min+1)/n, this reduces efficiency slightly but avoids having to check for the out of range value. Note that range is typically O(2^32) so the addition of 1 is negligible in most usage. */ INLINE_FUN unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n) { unsigned long int offset = r->type->min; unsigned long int range = r->type->max - offset; unsigned long int scale; unsigned long int k; if (n > range || n == 0) { GSL_ERROR_VAL ("invalid n, either 0 or exceeds maximum value of generator", GSL_EINVAL, 0) ; } scale = range / n; do { k = (((r->type->get) (r->state)) - offset) / scale; } while (k >= n); return k; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_RNG_H__ */
{ "alphanum_fraction": 0.7505615009, "avg_line_length": 33.1973684211, "ext": "h", "hexsha": "bc343e18d87f3aa079d9d4841d6e2b9e7424e4e2", "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": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_path": "deps/include/gsl/gsl_rng.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_path": "deps/include/gsl/gsl_rng.h", "max_line_length": 100, "max_stars_count": 2, "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_path": "deps/include/gsl/gsl_rng.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 2212, "size": 7569 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_sf_gamma.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* very simple approximation */ double st_gamma(double x) { return sqrt(2.0*M_PI/x)*pow(x/M_E, x); } #define A 12 double sp_gamma(double z) { const int a = A; static double c_space[A]; static double *c = NULL; int k; double accm; if ( c == NULL ) { double k1_factrl = 1.0; /* (k - 1)!*(-1)^k with 0!==1*/ c = c_space; c[0] = sqrt(2.0*M_PI); for(k=1; k < a; k++) { c[k] = exp(a-k) * pow(a-k, k-0.5) / k1_factrl; k1_factrl *= -k; } } accm = c[0]; for(k=1; k < a; k++) { accm += c[k] / ( z + k ); } accm *= exp(-(z+a)) * pow(z+a, z+0.5); /* Gamma(z+1) */ return accm/z; } int main() { double x; printf("%15s%15s%15s%15s\n", "Stirling", "Spouge", "GSL", "libm"); for(x=1.0; x <= 10.0; x+=1.0) { printf("%15.8lf%15.8lf%15.8lf%15.8lf\n", st_gamma(x/3.0), sp_gamma(x/3.0), gsl_sf_gamma(x/3.0), tgamma(x/3.0)); } return 0; }
{ "alphanum_fraction": 0.5445829338, "avg_line_length": 19.679245283, "ext": "c", "hexsha": "81dcdc28a9966ca55713c786507f286cbddad6af", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_path": "lang/C/gamma-function.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "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": "ethansaxenian/RosettaDecode", "max_issues_repo_path": "lang/C/gamma-function.c", "max_line_length": 78, "max_stars_count": 2, "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_path": "lang/C/gamma-function.c", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "num_tokens": 427, "size": 1043 }
/* linalg/invtri_complex.c * * Copyright (C) 2019 Patrick Alken * * This 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, or (at your option) any * later version. * * This source is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This module contains code to invert complex triangular matrices */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include "recurse.h" static int complex_tri_invert_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T); static int complex_tri_invert_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T); static int triangular_singular(const gsl_matrix_complex * T); /* gsl_linalg_complex_tri_invert() Invert a complex triangular matrix T using Level 3 BLAS Inputs: Uplo - CblasUpper or CblasLower Diag - unit triangular? T - on output the upper (or lower) part of T is replaced by its inverse Return: success/error */ int gsl_linalg_complex_tri_invert(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { int status; status = triangular_singular(T); if (status) return status; return complex_tri_invert_L3(Uplo, Diag, T); } } /* complex_tri_invert_L2() Invert a complex triangular matrix T Inputs: Uplo - CblasUpper or CblasLower Diag - unit triangular? T - on output the upper (or lower) part of T is replaced by its inverse Return: success/error Notes: 1) Based on LAPACK routine ZTRTI2 using Level 2 BLAS */ static int complex_tri_invert_L2(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else { size_t i; if (Uplo == CblasUpper) { for (i = 0; i < N; ++i) { gsl_complex * Tii = gsl_matrix_complex_ptr(T, i, i); gsl_complex aii; if (Diag == CblasNonUnit) { *Tii = gsl_complex_inverse(*Tii); GSL_REAL(aii) = -GSL_REAL(*Tii); GSL_IMAG(aii) = -GSL_IMAG(*Tii); } else aii = GSL_COMPLEX_NEGONE; if (i > 0) { gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, 0, 0, i, i); gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, i, 0, i); gsl_blas_ztrmv(CblasUpper, CblasNoTrans, Diag, &m.matrix, &v.vector); gsl_blas_zscal(aii, &v.vector); } } } else { for (i = 0; i < N; ++i) { size_t j = N - i - 1; gsl_complex * Tjj = gsl_matrix_complex_ptr(T, j, j); gsl_complex ajj; if (Diag == CblasNonUnit) { *Tjj = gsl_complex_inverse(*Tjj); GSL_REAL(ajj) = -GSL_REAL(*Tjj); GSL_IMAG(ajj) = -GSL_IMAG(*Tjj); } else ajj = GSL_COMPLEX_NEGONE; if (j < N - 1) { gsl_matrix_complex_view m = gsl_matrix_complex_submatrix(T, j + 1, j + 1, N - j - 1, N - j - 1); gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(T, j, j + 1, N - j - 1); gsl_blas_ztrmv(CblasLower, CblasNoTrans, Diag, &m.matrix, &v.vector); gsl_blas_zscal(ajj, &v.vector); } } } return GSL_SUCCESS; } } /* complex_tri_invert_L3() Invert a complex triangular matrix T Inputs: Uplo - CblasUpper or CblasLower Diag - unit triangular? T - on output the upper (or lower) part of T is replaced by its inverse Return: success/error Notes: 1) Based on ReLAPACK using Level 3 BLAS */ static int complex_tri_invert_L3(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_complex * T) { const size_t N = T->size1; if (N != T->size2) { GSL_ERROR ("matrix must be square", GSL_ENOTSQR); } else if (N <= CROSSOVER_INVTRI) { /* use Level 2 algorithm */ return complex_tri_invert_L2(Uplo, Diag, T); } else { /* * partition matrix: * * T11 T12 * T21 T22 * * where T11 is N1-by-N1 */ int status; const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N); const size_t N2 = N - N1; gsl_matrix_complex_view T11 = gsl_matrix_complex_submatrix(T, 0, 0, N1, N1); gsl_matrix_complex_view T12 = gsl_matrix_complex_submatrix(T, 0, N1, N1, N2); gsl_matrix_complex_view T21 = gsl_matrix_complex_submatrix(T, N1, 0, N2, N1); gsl_matrix_complex_view T22 = gsl_matrix_complex_submatrix(T, N1, N1, N2, N2); /* recursion on T11 */ status = complex_tri_invert_L3(Uplo, Diag, &T11.matrix); if (status) return status; if (Uplo == CblasLower) { /* T21 = - T21 * T11 */ gsl_blas_ztrmm(CblasRight, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_NEGONE, &T11.matrix, &T21.matrix); /* T21 = T22 * T21^{-1} */ gsl_blas_ztrsm(CblasLeft, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_ONE, &T22.matrix, &T21.matrix); } else { /* T12 = - T11 * T12 */ gsl_blas_ztrmm(CblasLeft, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_NEGONE, &T11.matrix, &T12.matrix); /* T12 = T12 * T22^{-1} */ gsl_blas_ztrsm(CblasRight, Uplo, CblasNoTrans, Diag, GSL_COMPLEX_ONE, &T22.matrix, &T12.matrix); } /* recursion on T22 */ status = complex_tri_invert_L3(Uplo, Diag, &T22.matrix); if (status) return status; return GSL_SUCCESS; } } static int triangular_singular(const gsl_matrix_complex * T) { size_t i; for (i = 0; i < T->size1; ++i) { gsl_complex z = gsl_matrix_complex_get(T, i, i); if (GSL_REAL(z) == 0.0 && GSL_IMAG(z) == 0.0) return GSL_ESING; } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5961455487, "avg_line_length": 27.812, "ext": "c", "hexsha": "38a43e7d2828ae3d48dc5f6becf220e8c045db43", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/invtri_complex.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/linalg/invtri_complex.c", "max_line_length": 114, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/linalg/invtri_complex.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": 1973, "size": 6953 }
/* specfunc/elljac.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_pow_int.h" #include "gsl_sf_elljac.h" /* See [Thompson, Atlas for Computing Mathematical Functions] */ int gsl_sf_elljac_e(double u, double m, double * sn, double * cn, double * dn) { if(fabs(m) > 1.0) { *sn = 0.0; *cn = 0.0; *dn = 0.0; GSL_ERROR ("|m| > 1.0", GSL_EDOM); } else if(fabs(m) < 2.0*GSL_DBL_EPSILON) { *sn = sin(u); *cn = cos(u); *dn = 1.0; return GSL_SUCCESS; } else if(fabs(m - 1.0) < 2.0*GSL_DBL_EPSILON) { *sn = tanh(u); *cn = 1.0/cosh(u); *dn = *cn; return GSL_SUCCESS; } else { int status = GSL_SUCCESS; const int N = 16; double a[16]; double b[16]; double c[16]; double phi[16]; double psi[16]; /* psi[i] := phi[i] - Pi 2^{i-1} */ double two_N; int n = 0; a[0] = 1.0; b[0] = sqrt(1.0 - m); c[0] = sqrt(m); while( fabs(c[n]) > 4.0 * GSL_DBL_EPSILON) { a[n+1] = 0.5 * (a[n] + b[n]); b[n+1] = sqrt(a[n] * b[n]); c[n+1] = 0.5 * (a[n] - b[n]); if(n >= N - 2) { status = GSL_EMAXITER; c[N-1] = 0.0; break; } ++n; } --n; two_N = (double)(1 << n ); /* 2^n */ /* gsl_sf_pow_int(2.0, n); */ phi[n] = two_N * a[n] * u; psi[n] = two_N * (a[n]*u - 0.5*M_PI); while(n > 0) { const double psi_sgn = ( n == 1 ? -1.0 : 1.0 ); const double phi_asin_arg = c[n] * sin(phi[n])/a[n]; const double psi_asin_arg = c[n]/a[n] * psi_sgn * sin(psi[n]); const double phi_asin = asin(phi_asin_arg); const double psi_asin = asin(psi_asin_arg); phi[n-1] = 0.5 * (phi[n] + phi_asin); psi[n-1] = 0.5 * (psi[n] + psi_asin); --n; } *sn = sin(phi[0]); *cn = cos(phi[0]); { /* const double dn_method_1 = *cn / cos(phi[1] - phi[0]); */ const double dn_method_2 = sin(psi[0])/sin(psi[1] - psi[0]); *dn = dn_method_2; /* printf("%18.16g %18.16g\n", dn_method_1, dn_method_2); */ } return status; } }
{ "alphanum_fraction": 0.5627810446, "avg_line_length": 26.5229357798, "ext": "c", "hexsha": "bddaad2a265b5913889c235f6ba20ed8f92daff3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/elljac.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/elljac.c", "max_line_length": 74, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/elljac.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": 1020, "size": 2891 }
#pragma once #include <gsl/gsl> #include <iostream> #include "../utils/Concepts.h" #include "General.h" #include "Random.h" namespace math { using gsl::narrow_cast; using utils::concepts::SignedNumeric, utils::concepts::Integral, utils::concepts::SignedIntegral, utils::concepts::FloatingPoint; enum class Vec2Idx : size_t { X = 0ULL, Y }; template<SignedNumeric T = float> class Vec2 { public: /// @brief Creates a default `Vec2` constexpr Vec2() noexcept = default; /// @brief Creates a new `Vec2` with the given x and y components /// /// @param x - The x component /// @param y - The y component constexpr Vec2(T x, T y) noexcept : elements{x, y} { } constexpr Vec2(const Vec2& vec) noexcept = default; constexpr Vec2(Vec2&& vec) noexcept = default; constexpr ~Vec2() noexcept = default; /// @brief Returns the x component /// /// @return a const ref to the x component [[nodiscard]] inline constexpr auto x() const noexcept -> const T& { return elements[X]; } /// @brief Returns the x component /// /// @return a mutable (ie: non-const) ref to the x component inline constexpr auto x() noexcept -> T& { return elements[X]; } /// @brief Returns the y component /// /// @return a const ref to the y component [[nodiscard]] inline constexpr auto y() const noexcept -> const T& { return elements[Y]; } /// @brief Returns the y component /// /// @return a mutable (ie: non-const) ref to the y component inline constexpr auto y() noexcept -> T& { return elements[Y]; } /// @brief Returns the magnitude (length) of the vector /// /// @return The magnitude template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto magnitude() const noexcept -> TT { return General::sqrt(narrow_cast<TT>(magnitude_squared())); } /// @brief Returns the dot product of this and `vec` /// /// @param vec - The vector to perform the dot product with /// /// @return The dot product template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto dot_prod(const Vec2<TT>& vec) const noexcept -> TT { return narrow_cast<TT>(x()) * vec.x() + narrow_cast<TT>(y()) * vec.y(); } /// @brief Returns the dot product of this and `vec` /// /// @param vec - The vector to perform the dot product with /// /// @return The dot product template<SignedIntegral TT = int> [[nodiscard]] inline constexpr auto dot_prod(const Vec2<TT>& vec) const noexcept -> T { return x() * narrow_cast<T>(vec.x()) + y() * narrow_cast<T>(vec.y()); } /// @brief Performs the 2D equivalent to the cross product /// @note This is equivalent to the z component of a 3D cross product /// /// @param vec The vector to perform the cross product with /// /// @return The 2D cross product template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto cross_prod(const Vec2<TT>& vec) const noexcept -> TT { return narrow_cast<TT>(x()) * vec.y() - narrow_cast<TT>(y()) * vec.x(); } /// @brief Performs the 2D equivalent to the cross product /// @note This is equivalent to the z component of a 3D cross product /// /// @param vec The vector to perform the cross product with /// /// @return The 2D cross product template<SignedIntegral TT = int> [[nodiscard]] inline constexpr auto cross_prod(const Vec2<TT>& vec) const noexcept -> T { return x() * narrow_cast<T>(vec.y()) - y() * narrow_cast<T>(vec.x()); } /// @brief Returns **a** vector normal to this one /// @note this is not necessarily the **only** vector normal to this one /// /// @return a vector normal to this template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto normal() const noexcept -> Vec2<TT> { constexpr auto _x = narrow_cast<TT>(1.0); const auto _y = (-_x * narrow_cast<TT>(x())) / narrow_cast<TT>(y()); return {_x, _y}; } /// @brief Returns this vector with normalized magnitude /// /// @return this vector, normalized template<FloatingPoint TT = float> [[nodiscard]] inline constexpr auto normalized() const noexcept -> Vec2<TT> { return std::move(*this / magnitude<TT>()); } template<SignedNumeric TT = float> [[nodiscard]] inline static constexpr auto random() noexcept -> Vec2<TT> { return {random_value<TT>(), random_value<TT>()}; } template<SignedNumeric TT = float> [[nodiscard]] inline static constexpr auto random(TT min, TT max) noexcept -> Vec2<TT> { return {random_value<TT>(min, max), random_value<TT>(min, max)}; } template<FloatingPoint TT = float> [[nodiscard]] inline static constexpr auto random_in_unit_circle() noexcept -> Vec2<TT> { do { auto val = random(narrow_cast<TT>(-1), narrow_cast<TT>(1)); if(val.magnitude_squared() < narrow_cast<TT>(1)) { return val; } } while(true); } constexpr auto operator=(const Vec2& vec) noexcept -> Vec2& = default; constexpr auto operator=(Vec2&& vec) noexcept -> Vec2& = default; template<FloatingPoint TT = float> inline constexpr auto operator==(const Vec2<TT>& vec) const noexcept -> bool { const auto xEqual = General::abs<TT>(narrow_cast<TT>(x()) - vec.x()) < narrow_cast<TT>(0.01); const auto yEqual = General::abs<TT>(narrow_cast<TT>(y()) - vec.y()) < narrow_cast<TT>(0.01); return xEqual && yEqual; } template<SignedIntegral TT = int> inline constexpr auto operator==(const Vec2<TT>& vec) const noexcept -> bool { if constexpr(FloatingPoint<T>) { const auto xEqual = General::abs<T>(x() - narrow_cast<T>(vec.x())) < narrow_cast<TT>(0.01); const auto yEqual = General::abs<T>(y() - narrow_cast<T>(vec.y())) < narrow_cast<TT>(0.01); return xEqual && yEqual; } else { return x() == narrow_cast<T>(vec.x()) && y() == narrow_cast<T>(vec.y()); } } template<SignedNumeric TT = T> inline constexpr auto operator!=(const Vec2<TT>& vec) const noexcept -> bool { return !(*this == vec); } inline constexpr auto operator-() const noexcept -> Vec2 { return {-x(), -y()}; } inline constexpr auto operator[](Vec2Idx i) const noexcept -> T { const auto index = static_cast<size_t>(i); return elements[index]; // NOLINT } inline constexpr auto operator[](Vec2Idx i) noexcept -> T& { const auto index = static_cast<size_t>(i); return elements[index]; // NOLINT } template<FloatingPoint TT = float> inline constexpr auto operator+(const Vec2<TT>& vec) const noexcept -> Vec2<TT> { return {narrow_cast<TT>(x()) + vec.x(), narrow_cast<TT>(y()) + vec.y()}; } template<SignedIntegral TT = int> inline constexpr auto operator+(const Vec2<TT>& vec) const noexcept -> Vec2<T> { return {x() + narrow_cast<T>(vec.x()), y() + narrow_cast<T>(vec.y())}; } template<SignedNumeric TT = T> inline constexpr auto operator+=(const Vec2<TT>& vec) noexcept -> Vec2& { x() += narrow_cast<T>(vec.x()); y() += narrow_cast<T>(vec.y()); return *this; } template<FloatingPoint TT = float> inline constexpr auto operator-(const Vec2<TT>& vec) const noexcept -> Vec2<TT> { return {narrow_cast<TT>(x()) - vec.x(), narrow_cast<TT>(y()) - vec.y()}; } template<SignedIntegral TT = int> inline constexpr auto operator-(const Vec2<TT>& vec) const noexcept -> Vec2<T> { return {x() - narrow_cast<T>(vec.x()), y() - narrow_cast<T>(vec.y())}; } template<SignedNumeric TT = T> inline constexpr auto operator-=(const Vec2<TT>& vec) noexcept -> Vec2& { x() -= narrow_cast<T>(vec.x()); y() -= narrow_cast<T>(vec.y()); return *this; } inline constexpr auto operator*(FloatingPoint auto s) const noexcept -> Vec2<decltype(s)> { using TT = decltype(s); return {narrow_cast<TT>(x()) * s, narrow_cast<TT>(y()) * s}; } inline constexpr auto operator*(SignedIntegral auto s) const noexcept -> Vec2 { auto scalar = narrow_cast<T>(s); return {x() * scalar, y() * scalar}; } inline constexpr auto operator*=(FloatingPoint auto s) noexcept -> Vec2& { using TT = decltype(s); x() = narrow_cast<T>(narrow_cast<TT>(x()) * s); y() = narrow_cast<T>(narrow_cast<TT>(y()) * s); return *this; } inline constexpr auto operator*=(SignedIntegral auto s) noexcept -> Vec2& { auto scalar = narrow_cast<T>(s); x() *= scalar; y() *= scalar; return *this; } friend inline constexpr auto operator*(FloatingPoint auto lhs, const Vec2& rhs) noexcept -> Vec2<decltype(lhs)> { return rhs * lhs; } friend inline constexpr auto operator*(SignedIntegral auto lhs, const Vec2& rhs) noexcept -> Vec2 { return rhs * lhs; } inline constexpr auto operator/(FloatingPoint auto s) const noexcept -> Vec2<decltype(s)> { using TT = decltype(s); return {narrow_cast<TT>(x()) / s, narrow_cast<TT>(y()) / s}; } inline constexpr auto operator/(SignedIntegral auto s) const noexcept -> Vec2 { auto scalar = narrow_cast<T>(s); return {x() / scalar, y() / scalar}; } friend inline constexpr auto operator/(FloatingPoint auto lhs, const Vec2& rhs) noexcept -> Vec2<decltype(lhs)> { return rhs / lhs; } friend inline constexpr auto operator/(SignedIntegral auto lhs, const Vec2& rhs) noexcept -> Vec2 { return rhs / lhs; } inline constexpr auto operator/=(FloatingPoint auto s) noexcept -> Vec2 { using TT = decltype(s); x() = narrow_cast<T>(narrow_cast<TT>(x()) / s); y() = narrow_cast<T>(narrow_cast<TT>(y()) / s); return *this; } inline constexpr auto operator/=(SignedIntegral auto s) noexcept -> Vec2 { auto scalar = narrow_cast<T>(s); x() /= scalar; y() /= scalar; return *this; } friend inline constexpr auto operator<<(std::ostream& out, const Vec2& vec) noexcept -> std::ostream& { return out << vec.x() << ' ' << vec.y(); } private: static constexpr size_t NUM_ELEMENTS = static_cast<size_t>(Vec2Idx::Y) + 1; T elements[NUM_ELEMENTS] = {narrow_cast<T>(0), narrow_cast<T>(0)}; // NOLINT /// @brief Calculates the magnitude squared of this vector /// /// @return The magnitude squared [[nodiscard]] inline constexpr auto magnitude_squared() const noexcept -> T { return x() * x() + y() * y(); } /// Index for x component static constexpr size_t X = static_cast<size_t>(Vec2Idx::X); /// Index for y component static constexpr size_t Y = static_cast<size_t>(Vec2Idx::Y); }; template<FloatingPoint T> explicit Vec2(T, T) -> Vec2<T>; template<SignedIntegral T> explicit Vec2(T, T) -> Vec2<T>; } // namespace math
{ "alphanum_fraction": 0.6488804192, "avg_line_length": 31.9969512195, "ext": "h", "hexsha": "9adccd77bd5a94e542677ed4966856172bf60fcd", "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": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_path": "src/math/Vec2.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "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": "braxtons12/ray_tracer", "max_issues_repo_path": "src/math/Vec2.h", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_path": "src/math/Vec2.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2982, "size": 10495 }
#ifndef TSNE_H #define TSNE_H /* Cmake will define ${LIBRARY_NAME}_EXPORTS on Windows when it configures to build a shared library. If you are going to use another build system on windows or create the visual studio projects by hand you need to define ${LIBRARY_NAME}_EXPORTS when building a DLL on windows. */ // We are using the Visual Studio Compiler and building Shared libraries #if defined (_WIN32) #if defined(examplelib_EXPORTS) #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT __declspec(dllimport) #endif #else #define DLLEXPORT #endif #ifndef SWIG #include <math.h> #include <iostream> // std::cout, std::fixed #include <iomanip> // std::setprecision #include <stdlib.h> #include <cstring> #include <time.h> #include <stdlib.h> #include <algorithm> #include <vector> #include <stdio.h> #include <queue> #include <limits> #include <iostream> #include <cfloat> #include <limits> #include <armadillo> using namespace std; using namespace arma; #include "quadtree.h" #include "vptree.h" extern "C" { #include <cblas.h> } #else #endif /* * tsne.h * Header file for t-SNE. * * Created by Laurens van der Maaten. * Copyright 2012, Delft University of Technology. All rights reserved. * */ static inline double sign(double x) { return (x == .0 ? .0 : (x < .0 ? -1.0 : 1.0)); } class DLLEXPORT TSNE { public: void run(double* X, int N, int D, double* Y, int no_dims, double perplexity, double theta); bool load_data(const char * filename,double** data, int* n, int* d, double* theta, double* perplexity); void save_data(const char* filename,double* data, int* landmarks, double* costs, int n, int d); void symmetrizeMatrix(int** row_P, int** col_P, double** val_P, int N); // should be static?! private: void computeGradient(double* P, int* inp_row_P, int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta); void computeExactGradient(double* P, double* Y, int N, int D, double* dC); double evaluateError(double* P, double* Y, int N); double evaluateError(int* row_P, int* col_P, double* val_P, double* Y, int N, double theta); void zeroMean(double* X, int N, int D); void computeGaussianPerplexity(double* X, int N, int D, double* P, double perplexity); void computeGaussianPerplexity(double* X, int N, int D, int** _row_P, int** _col_P, double** _val_P, double perplexity, int K); void computeGaussianPerplexity(double* X, int N, int D, int** _row_P, int** _col_P, double** _val_P, double perplexity, double threshold); void computeSquaredEuclideanDistance(double* X, int N, int D, double* DD); double randn(); }; /* the following Math class is used to test the python wrapper work for basic pointer manipulation*/ class DLLEXPORT Math4py { public: Math4py(); int pi() const; void pi(int pi); private: int _pi; }; int DLLEXPORT fact(int n); #endif
{ "alphanum_fraction": 0.7070567986, "avg_line_length": 29.6428571429, "ext": "h", "hexsha": "adb7b25104196e45382e9ca920155b107459672f", "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": "dff66e307877de3f205621ac4da86e5c8159f878", "max_forks_repo_licenses": [ "BSD-4-Clause-UC" ], "max_forks_repo_name": "lyase/barnes-hut-sne", "max_forks_repo_path": "tsnelib/tsne.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-4-Clause-UC" ], "max_issues_repo_name": "lyase/barnes-hut-sne", "max_issues_repo_path": "tsnelib/tsne.h", "max_line_length": 142, "max_stars_count": null, "max_stars_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_stars_repo_licenses": [ "BSD-4-Clause-UC" ], "max_stars_repo_name": "lyase/barnes-hut-sne", "max_stars_repo_path": "tsnelib/tsne.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 802, "size": 2905 }
#ifndef WALK_H_ #define WALK_H_ #include <iostream> #include <sstream> #include <string> #include <vector> #include <gsl/gsl_rng.h> #include "Lattice.h" /* Random number generator parameters used across this program */ namespace WalkRNG { /* GSL random number generator, if using */ extern gsl_rng *rng; /* Whether or not to use the GSL random number generator */ extern bool use_GSL; /* Whether or not we've generated a new random seed since program start */ extern bool random_seeded; }; /* Class to perform a random walk on an N-dimensional lattice */ template<unsigned int N> class Walk : public std::vector<Vector<N> > { private: Lattice<N> lattice; public: Walk(Lattice<N> lattice) : lattice(lattice) { /* If we haven't seeded the RNG yet... */ if (!WalkRNG::random_seeded) { if (!WalkRNG::use_GSL) /* If not using GSL's random number generator, seed with time */ std::srand(std::time(0)); else { /* else set up GSL random number generator */ const gsl_rng_type *T; gsl_rng_env_setup(); T = gsl_rng_default; WalkRNG::rng = gsl_rng_alloc(T); } WalkRNG::random_seeded = true; } } /** * Generate random walk on the lattice of length `length` modifying in place * with non-basis transformed vectors and also returning the walk. * Clears the current walk. */ Walk<N> &generate(int length) { this->clear(); /* Get the new translation set for this lattice */ std::vector<Vector<N> > translation_set = this->lattice.getTranslationSet(); for (int i = 0; i < length; ++i) { /* Get random index for the translation_set */ size_t random_index; if (WalkRNG::use_GSL) random_index = gsl_rng_get(WalkRNG::rng) % translation_set.size(); else random_index = std::rand() % translation_set.size(); /* Get the element */ Vector<N> random_element = translation_set.at(random_index); /* Add it to the walk */ this->push_back(random_element); } return *this; } /** * Step walk for one iteration, returning single vector and adding to Walk. * Same as generate(int length) with a length == 1, and doesn't clear the walk. * Returns the generated Vector<N> */ Vector<N> step() { std::vector<Vector<N> > translation_set = this->lattice.getTranslationSet(); size_t random_index; if (WalkRNG::use_GSL) random_index = gsl_rng_get(WalkRNG::rng) % translation_set.size(); else random_index = std::rand() % translation_set.size(); Vector<N> random_element = translation_set.at(random_index); this->push_back(random_element); return random_element; } /** * Apply this->lattice's basis to each vector in the walk */ Walk &applyBasis() { for (int i = 0; i < this->size(); ++i) { this->at(i) = this->lattice.applyBasis(this->at(i)); } return *this; } /** * Get distance between start and end points of walk */ double getDistance() { return this->getDistanceBetween(0, this->size()); } /** * Get distance between inclusive point `start` and * exclusive point `end` of walk */ double getDistanceBetween(size_t start, size_t end) { Vector<N> res; for (int i = start; i < end; ++i) { res += this->at(i); } return res.getMagnitude(); } /** * Return new walk with each step added, so each step corresponds to the * current position on the lattice. */ Walk<N> accumulateVectors() { Walk<N> walk(this->lattice); Vector<N> running_total = this->at(0); // Initial value walk.push_back(running_total); /* Accumulate each vector to the running total, and push it * to the walk */ for (int i = 1; i < this->size(); ++i) { running_total += this->at(i); walk.push_back(running_total); } return walk; } /** * Return as string of newline-seperated comma seperated rows * with first column as x-component, second column as y-component, etc. */ std::string toCSV() { std::stringstream ss; ss << *this; return ss.str(); } // Display each vector in walk, one on each line friend std::ostream& operator<<(std::ostream& os, const Walk<N> &walk) { for (int i = 0; i < walk.size(); ++i) os << walk.at(i) << std::endl; return os; } }; #endif /* WALK_H_ */
{ "alphanum_fraction": 0.6389209131, "avg_line_length": 24.5028248588, "ext": "h", "hexsha": "788079525bb52d6986ef300ee12761eb32852106", "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": "7ca4de57bed78e771440cd52282be897d73c0e34", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joebentley/walk-gen", "max_forks_repo_path": "src/Walk.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7ca4de57bed78e771440cd52282be897d73c0e34", "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": "joebentley/walk-gen", "max_issues_repo_path": "src/Walk.h", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "7ca4de57bed78e771440cd52282be897d73c0e34", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joebentley/walk-gen", "max_stars_repo_path": "src/Walk.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1115, "size": 4337 }
#pragma once #include <memory_resource> #include <vector> #include <thrust/execution_policy.h> #include <thrust/functional.h> #include <thrust/inner_product.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/merge.h> #include <thrust/reduce.h> #include <thrust/sort.h> #include <thrust/tuple.h> #include <gsl-lite/gsl-lite.hpp> #include <cuda/define_specifiers.hpp> #include <thrustshift/copy.h> #include <thrustshift/equal.h> #include <thrustshift/managed-vector.h> #include <thrustshift/math.h> #include <thrustshift/memory-resource.h> #include <thrustshift/not-a-vector.h> #include <thrustshift/transform.h> namespace thrustshift { enum class storage_order_t { row_major, col_major, none }; template <typename DataType, typename IndexType> class COO { public: using value_type = DataType; using index_type = IndexType; COO() : num_cols_(0), num_rows_(0) { } template <class MemoryResource> COO(size_t nnz, size_t num_rows, size_t num_cols, MemoryResource& memory_resource) : values_(nnz, &memory_resource), row_indices_(nnz, &memory_resource), col_indices_(nnz, &memory_resource), num_rows_(num_rows), num_cols_(num_cols), storage_order_(storage_order_t::none) { } COO(size_t nnz, size_t num_rows, size_t num_cols) : COO(nnz, num_rows, num_cols, pmr::default_resource) { } template <class DataRange, class RowIndRange, class ColIndRange, class MemoryResource> COO(DataRange&& values, RowIndRange&& row_indices, ColIndRange&& col_indices, size_t num_rows, size_t num_cols, storage_order_t storage_order, MemoryResource& memory_resource) : values_(values.begin(), values.end(), &memory_resource), row_indices_(row_indices.begin(), row_indices.end(), &memory_resource), col_indices_(col_indices.begin(), col_indices.end(), &memory_resource), num_rows_(num_rows), num_cols_(num_cols), storage_order_(storage_order) { gsl_Expects(values.size() == row_indices.size()); gsl_Expects(values.size() == col_indices.size()); } template <class DataRange, class RowIndRange, class ColIndRange, class MemoryResource> COO(DataRange&& values, RowIndRange&& row_indices, ColIndRange&& col_indices, size_t num_rows, size_t num_cols, MemoryResource& memory_resource) : COO(std::forward<DataRange>(values), std::forward<RowIndRange>(row_indices), std::forward<ColIndRange>(col_indices), num_rows, num_cols, storage_order_t::none, memory_resource) { } template <class DataRange, class ColIndRange, class RowIndRange> COO(DataRange&& values, RowIndRange&& row_indices, ColIndRange&& col_indices, size_t num_rows, size_t num_cols) : COO(std::forward<DataRange>(values), std::forward<RowIndRange>(row_indices), std::forward<ColIndRange>(col_indices), num_rows, num_cols, pmr::default_resource) { } // The copy constructor is declared explicitly to ensure // managed memory is used per default. COO(const COO& other) : COO(other.values(), other.row_indices(), other.col_indices(), other.num_rows(), other.num_cols(), other.get_storage_order(), pmr::default_resource) { } COO(COO&& other) = default; void change_storage_order(storage_order_t new_storage_order) { IndexType* primary_keys_first; IndexType* secondary_keys_first; if (new_storage_order == storage_order_) { return; } switch (new_storage_order) { case storage_order_t::row_major: primary_keys_first = row_indices_.data(); secondary_keys_first = col_indices_.data(); break; case storage_order_t::col_major: primary_keys_first = col_indices_.data(); secondary_keys_first = row_indices_.data(); break; case storage_order_t::none: return; } // Thrust's relational operators are overloaded for thrust::pair. // This ensures that we sort with respect to the second key if the first key is equal. auto key_it = thrust::make_zip_iterator( thrust::make_tuple(primary_keys_first, secondary_keys_first)); thrust::sort_by_key( thrust::cuda::par, key_it, key_it + values_.size(), values_.data()); storage_order_ = new_storage_order; } // If the storage order is changed externally void set_storage_order(storage_order_t new_storage_order) { storage_order_ = new_storage_order; } void transpose() { std::swap(col_indices_, row_indices_); std::swap(num_rows_, num_cols_); switch (storage_order_) { case storage_order_t::none: break; case storage_order_t::row_major: storage_order_ = storage_order_t::col_major; break; case storage_order_t::col_major: storage_order_ = storage_order_t::row_major; break; } } gsl_lite::span<DataType> values() { return gsl_lite::make_span(values_); } gsl_lite::span<const DataType> values() const { return gsl_lite::make_span(values_); } gsl_lite::span<IndexType> row_indices() { return gsl_lite::make_span(row_indices_); } gsl_lite::span<const IndexType> row_indices() const { return gsl_lite::make_span(row_indices_); } gsl_lite::span<IndexType> col_indices() { return gsl_lite::make_span(col_indices_); } gsl_lite::span<const IndexType> col_indices() const { return gsl_lite::make_span(col_indices_); } size_t num_rows() const { return num_rows_; } size_t num_cols() const { return num_cols_; } storage_order_t get_storage_order() const { return storage_order_; } //! Return row_ptrs or col_ptrs depending on the current storage order thrustshift::managed_vector<index_type> get_ptrs() const { gsl_Expects(storage_order_ != storage_order_t::none); auto indices = storage_order_ == storage_order_t::row_major ? row_indices() : col_indices(); auto size = storage_order_ == storage_order_t::row_major ? num_rows() : num_cols(); if (indices.size() > 0) { thrustshift::managed_vector<index_type> ptrs(size + 1, -1); for (int nns_id = gsl_lite::narrow<int>(indices.size()) - 1; nns_id >= 0; --nns_id) { ptrs[indices[nns_id]] = nns_id; } ptrs[0] = 0; ptrs.back() = indices.size(); index_type k = indices.size(); for (int id = gsl_lite::narrow<int>(ptrs.size()) - 1; id > 0; --id) { if (ptrs[id] == -1) { ptrs[id] = k; } else { k = ptrs[id]; } } return ptrs; } else { return {0}; } } private: std::pmr::vector<DataType> values_; std::pmr::vector<IndexType> row_indices_; std::pmr::vector<IndexType> col_indices_; size_t num_rows_; size_t num_cols_; storage_order_t storage_order_; }; //! Storage order does not affect comparison operator. Therefore this operator is defined explicitly. template <typename DataType, typename IndexType> bool operator==(const COO<DataType, IndexType>& a, const COO<DataType, IndexType>& b) { return equal(a.values(), b.values()) && equal(a.row_indices(), b.row_indices()) && equal(a.col_indices(), b.col_indices()) && a.num_rows() == b.num_rows() && a.num_cols() == b.num_cols(); } template <typename DataType, typename IndexType> class COO_view { public: using value_type = DataType; using index_type = IndexType; template <typename OtherDataType, typename OtherIndexType> COO_view(COO<OtherDataType, OtherIndexType>& owner) : values_(owner.values()), row_indices_(owner.row_indices()), col_indices_(owner.col_indices()), num_rows_(owner.num_rows()), num_cols_(owner.num_cols()) { } template <typename OtherDataType, typename OtherIndexType> COO_view(const COO<OtherDataType, OtherIndexType>& owner) : values_(owner.values()), row_indices_(owner.row_indices()), col_indices_(owner.col_indices()), num_rows_(owner.num_rows()), num_cols_(owner.num_cols()) { } template <class ValueRange, class ColIndRange, class RowIndRange> COO_view(ValueRange&& values, RowIndRange&& row_indices, ColIndRange&& col_indices, size_t num_rows, size_t num_cols) : values_(values), row_indices_(row_indices), col_indices_(col_indices), num_rows_(num_rows), num_cols_(num_cols) { const auto nnz = values.size(); gsl_Expects(col_indices.size() == nnz); gsl_Expects(row_indices.size() == nnz); } COO_view(const COO_view& other) = default; CUDA_FHD gsl_lite::span<DataType> values() { return values_; } CUDA_FHD gsl_lite::span<const DataType> values() const { return values_; } CUDA_FHD gsl_lite::span<IndexType> row_indices() { return row_indices_; } CUDA_FHD gsl_lite::span<const IndexType> row_indices() const { return row_indices_; } CUDA_FHD gsl_lite::span<IndexType> col_indices() { return col_indices_; } CUDA_FHD gsl_lite::span<const IndexType> col_indices() const { return col_indices_; } CUDA_FHD size_t num_rows() const { return num_rows_; } CUDA_FHD size_t num_cols() const { return num_cols_; } private: gsl_lite::span<DataType> values_; gsl_lite::span<IndexType> row_indices_; gsl_lite::span<IndexType> col_indices_; size_t num_rows_; size_t num_cols_; }; namespace kernel { template <typename T, typename T0, typename I0, typename T1, typename I1> __global__ void diagmm(gsl_lite::span<const T> diag, COO_view<const T0, const I0> mtx, COO_view<T1, I1> result_mtx) { const auto nnz = mtx.values().size(); const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; if (gtid < nnz) { result_mtx.values()[gtid] = diag[mtx.row_indices()[gtid]] * mtx.values()[gtid]; } } } // namespace kernel namespace async { //! Calculate the product `result_coo_mtx = (diag_mtx * coo_mtx)` //! result_coo_mtx can be equal to coo_mtx. Then the multiplication is in place. template <class Range, class COO_C0, class COO_C1> void diagmm(cuda::stream_t& stream, Range&& diag_mtx, COO_C0&& coo_mtx, COO_C1&& result_coo_mtx) { gsl_Expects(coo_mtx.values().size() == result_coo_mtx.values().size()); gsl_Expects(coo_mtx.num_cols() == result_coo_mtx.num_cols()); gsl_Expects(coo_mtx.num_rows() == result_coo_mtx.num_rows()); gsl_Expects(diag_mtx.size() == coo_mtx.num_rows()); // Only square matrices are allowed gsl_Expects(coo_mtx.num_rows() == coo_mtx.num_cols()); using RangeT = typename std::remove_reference<Range>::type::value_type; using COO_T0 = typename std::remove_reference<COO_C0>::type::value_type; using COO_I0 = typename std::remove_reference<COO_C0>::type::index_type; using COO_T1 = typename std::remove_reference<COO_C1>::type::value_type; using COO_I1 = typename std::remove_reference<COO_C1>::type::index_type; const auto nnz = coo_mtx.values().size(); constexpr cuda::grid::block_dimension_t block_dim = 128; const cuda::grid::dimension_t grid_dim = ceil_divide(nnz, block_dim); cuda::enqueue_launch(kernel::diagmm<RangeT, COO_T0, COO_I0, COO_T1, COO_I1>, stream, cuda::make_launch_config(grid_dim, block_dim), diag_mtx, coo_mtx, result_coo_mtx); } } // namespace async namespace kernel { template <typename T0, typename I, typename T1> __global__ void get_diagonal(COO_view<const T0, const I> mtx, gsl_lite::span<T1> diag) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; const auto values = mtx.values(); const auto nnz = values.size(); if (gtid < nnz) { const auto row_id = mtx.row_indices()[gtid]; const auto col_id = mtx.col_indices()[gtid]; if (row_id == col_id) { diag[row_id] = values[gtid]; } } } } // namespace kernel namespace async { template <typename T, class COO> void get_diagonal(cuda::stream_t& stream, COO&& mtx, gsl_lite::span<T> diag) { gsl_Expects(diag.size() == std::min(mtx.num_rows(), mtx.num_cols())); using I = typename std::remove_reference<COO>::type::index_type; using T0 = typename std::remove_reference<COO>::type::value_type; const auto nnz = mtx.values().size(); constexpr cuda::grid::block_dimension_t block_dim = 128; const cuda::grid::dimension_t grid_dim = ceil_divide(gsl_lite::narrow<cuda::grid::dimension_t>(nnz), gsl_lite::narrow<cuda::grid::dimension_t>(block_dim)); fill(stream, diag, 0); if (nnz != 0) { cuda::enqueue_launch(kernel::get_diagonal<T0, I, T>, stream, cuda::make_launch_config(grid_dim, block_dim), mtx, diag); } } } // namespace async /* \brief Transform two sparse COO matrices coefficient-wise `op(op_a(a), op_b(b))`. * \param a first sparse COO matrix. * \param b second sparse COO matrix. * \param op Binary operator how coefficients at the same positions are combined. * \param op_a Unary operator which is applied to all non-zero coefficients of `a`. * \param op_b Unary operator which is applied to all non-zero coefficients of `b`. * \return COO matrix allocated with `memory_resource` * \note It might be misleading that the binary operator is **not** applied to coefficients, which * only appear in one of the two matrices. E.g. `op=minus`, `op_a=identity`, `op_b=identity` and `a` is a zero matrix the result * is `result != a - b = -b`. Also note that it cannot be ensured that the left operand of the binary operator * is always an element of `a`. Therefore the unary operators are required. */ template <typename DataType, typename IndexType, class BinaryOperator, class UnaryOperatorA, class UnaryOperatorB, class MemoryResource> thrustshift::COO<DataType, IndexType> transform( thrustshift::COO_view<const DataType, const IndexType> a, thrustshift::COO_view<const DataType, const IndexType> b, BinaryOperator&& op, UnaryOperatorA&& op_a, UnaryOperatorB&& op_b, MemoryResource& memory_resource) { const auto nnz_a = a.values().size(); const auto nnz_b = b.values().size(); const auto num_rows = a.num_rows(); const auto num_cols = b.num_cols(); gsl_Expects(b.num_rows() == num_rows); gsl_Expects(b.num_cols() == num_cols); auto [tmp0, values] = make_not_a_vector_and_span<DataType>(nnz_a + nnz_b, memory_resource); auto [tmp1, row_indices] = make_not_a_vector_and_span<IndexType>(nnz_a + nnz_b, memory_resource); auto [tmp2, col_indices] = make_not_a_vector_and_span<IndexType>(nnz_a + nnz_b, memory_resource); auto device = cuda::device::current::get(); auto stream = device.default_stream(); async::transform(stream, a.values(), values.first(nnz_a), op_a); async::copy(stream, a.row_indices(), row_indices.first(nnz_a)); async::copy(stream, a.col_indices(), col_indices.first(nnz_a)); async::transform(stream, b.values(), values.subspan(nnz_a), op_b); async::copy(stream, b.row_indices(), row_indices.subspan(nnz_a)); async::copy(stream, b.col_indices(), col_indices.subspan(nnz_a)); using KeyT = thrust::tuple<IndexType, IndexType>; auto keys_begin = thrust::make_zip_iterator( thrust::make_tuple(row_indices.begin(), col_indices.begin())); auto keys_end = keys_begin + nnz_a + nnz_b; std::pmr::polymorphic_allocator<KeyT> alloc(&memory_resource); thrust::sort_by_key( thrust::cuda::par(alloc), keys_begin, keys_end, values.begin()); const std::size_t nnz_result = thrust::inner_product(thrust::cuda::par(alloc), keys_begin, keys_end - 1, keys_begin + 1, std::size_t(0), thrust::plus<std::size_t>(), thrust::not_equal_to<KeyT>()) + std::size_t(1); // ```cpp // auto memory_resource = ...; // auto res = transform(..., memory_resource); // // ``` // should work fine because the dtor of `res` is called before the dtor of `memory_resource` COO<DataType, IndexType> result( nnz_result, num_rows, num_cols, memory_resource); auto keys_result_begin = thrust::make_zip_iterator(thrust::make_tuple( result.row_indices().begin(), result.col_indices().begin())); thrust::reduce_by_key(thrust::cuda::par(alloc), keys_begin, keys_end, values.begin(), keys_result_begin, result.values().begin(), thrust::equal_to<KeyT>(), op); result.set_storage_order(storage_order_t::row_major); return result; } template <typename DataType, typename IndexType, class MemoryResource> COO<DataType, IndexType> symmetrize_abs( COO_view<const DataType, const IndexType> mtx, MemoryResource& memory_resource) { if (mtx.values().empty()) { return COO<DataType, IndexType>( 0, mtx.num_rows(), mtx.num_cols(), memory_resource); } COO_view<const DataType, const IndexType> mtx_trans(mtx.values(), mtx.col_indices(), mtx.row_indices(), mtx.num_rows(), mtx.num_cols()); auto abs = [] __device__(DataType x) { return std::abs(x); }; return transform( mtx, mtx_trans, [] __device__(DataType x, DataType y) { return x + y; }, abs, abs, memory_resource); } template <typename DataType, typename IndexType, class MemoryResource> COO<DataType, IndexType> make_pattern_symmetric( COO_view<const DataType, const IndexType> mtx, MemoryResource& memory_resource) { if (mtx.values().empty()) { return COO<DataType, IndexType>( 0, mtx.num_rows(), mtx.num_cols(), memory_resource); } COO_view<const DataType, const IndexType> mtx_trans(mtx.values(), mtx.col_indices(), mtx.row_indices(), mtx.num_rows(), mtx.num_cols()); auto identity = [] __device__(DataType x) { return x; }; auto make_zero = [] __device__(DataType x) { return DataType(0); }; return transform( mtx, mtx_trans, [] __device__(DataType x, DataType y) { return x + y; }, identity, make_zero, memory_resource); } } // namespace thrustshift
{ "alphanum_fraction": 0.6534795043, "avg_line_length": 31.5225375626, "ext": "h", "hexsha": "48cd49ee9e82032f6cb3370c88b3e8e2163a3a50", "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": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "codecircuit/thrustshift", "max_forks_repo_path": "include/thrustshift/COO.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "codecircuit/thrustshift", "max_issues_repo_path": "include/thrustshift/COO.h", "max_line_length": 130, "max_stars_count": 1, "max_stars_repo_head_hexsha": "533ed68f6aa201f54b9622dcaa203fdf6844b466", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "codecircuit/thrustshift", "max_stars_repo_path": "include/thrustshift/COO.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 4652, "size": 18882 }
/* Copyright [2017-2020] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __API_FABRIC_ITF__ #define __API_FABRIC_ITF__ #include <component/base.h> /* component::IBase, DECLARE_COMPONENT_UUID, DECLARE_INTERFACE_UUID */ #include <common/byte_span.h> #include <common/string_view.h> #include <gsl/span> #include <chrono> #include <cstddef> /* size_t */ #include <cstdint> /* uint16_t, uint64_t */ #include <functional> #include <stdexcept> /* runtime_error */ #include <vector> #ifndef FABRIC_H #define FI_READ (1ULL << 8) #define FI_WRITE (1ULL << 9) #define FI_RECV (1ULL << 10) #define FI_SEND (1ULL << 11) #define FI_TRANSMIT FI_SEND #define FI_REMOTE_READ (1ULL << 12) #define FI_REMOTE_WRITE (1ULL << 13) #define FI_MULTI_RECV (1ULL << 16) #define FI_REMOTE_CQ_DATA (1ULL << 17) #define FI_MORE (1ULL << 18) #define FI_PEEK (1ULL << 19) #define FI_TRIGGER (1ULL << 20) #define FI_FENCE (1ULL << 21) #define FI_COMPLETION (1ULL << 24) #define FI_EVENT FI_COMPLETION #define FI_INJECT (1ULL << 25) #define FI_INJECT_COMPLETE (1ULL << 26) #define FI_TRANSMIT_COMPLETE (1ULL << 27) #define FI_DELIVERY_COMPLETE (1ULL << 28) #define FI_AFFINITY (1ULL << 29) #define FI_COMMIT_COMPLETE (1ULL << 30) #define FI_VARIABLE_MSG (1ULL << 48) #define FI_RMA_PMEM (1ULL << 49) #define FI_SOURCE_ERR (1ULL << 50) #define FI_LOCAL_COMM (1ULL << 51) #define FI_REMOTE_COMM (1ULL << 52) #define FI_SHARED_AV (1ULL << 53) #define FI_PROV_ATTR_ONLY (1ULL << 54) #define FI_NUMERICHOST (1ULL << 55) #define FI_RMA_EVENT (1ULL << 56) #define FI_SOURCE (1ULL << 57) #define FI_NAMED_RX_CTX (1ULL << 58) #define FI_DIRECTED_RECV (1ULL << 59) #endif struct iovec; /* definition in <sys/uio.h> */ namespace component { class IFabric_runtime_error : public std::runtime_error { public: explicit IFabric_runtime_error(const common::string_view what_arg); /** * @return The libfabric error code (enumeration in <rdma/fi_errno.h>) */ virtual unsigned id() const noexcept = 0; }; /** * Fabric/RDMA-based network component * */ #pragma GCC diagnostic push #if defined __GNUC__ && 6 < __GNUC__ #pragma GCC diagnostic ignored "-Wnoexcept-type" #endif struct IFabric_memory_region; class IFabric_op_completer { public: virtual ~IFabric_op_completer() {} /* * Functionality which probably belongs to a higher layer, but which landed * here. Callbacks which return DEFER are enqueued, to be retried after * later callbacks are given a first chance to run. */ enum class cb_acceptance { ACCEPT, DEFER }; /** * Poll completion events; service completion queues and store * events not belonging to group (stall them). This method will * BOTH service the completion queues and service those events * stalled previously * * completion_flags, * FI_{SEND,RECV,RMA,ATOMIC,MSG,TAGGED,MULTICAST,(REMOTE_)?READ,(REMOTE_)?WRITE,REMOTE_CQ_DATA,MULTI_RECV}, * are described in "man fi_cq" and defined in * libfabric/include/rdma/fabric.h * * @param completion_callback (context_t, completion_flags, std::size_t len, * status_t status, void* error_data) * * @return Number of completions processed */ using complete_old = std::function<void(void *context, ::status_t)>; using complete_definite = std::function<void(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data)>; using complete_tentative = std::function< cb_acceptance(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data)>; using complete_param_definite = std::function< void(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void *error_data, void *param)>; using complete_param_tentative = std::function<cb_acceptance(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void * error_data, void * param)>; using complete_param_definite_ptr_noexcept = void (*)(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void * error_data, void * param) #if 201703L <= __cplusplus noexcept #endif ; using complete_param_tentative_ptr_noexcept = cb_acceptance (*)(void *context, ::status_t, std::uint64_t completion_flags, std::size_t len, void * error_data, void * param) #if 201703L <= __cplusplus noexcept #endif ; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions(const complete_old &completion_callback) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions(const complete_definite &completion_callback) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions_tentative(const complete_tentative &completion_callback) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions(const complete_param_definite &completion_callback, void *callback_param) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions_tentative(const complete_param_tentative &completion_callback, void * callback_param) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions(complete_param_definite_ptr_noexcept completion_callback, void * callback_param) = 0; /** * @throw IFabric_runtime_error - cq_read unhandled error * @throw std::logic_error - called on closed connection */ virtual std::size_t poll_completions_tentative(complete_param_tentative_ptr_noexcept completion_callback, void * callback_param) = 0; /** * Get count of stalled completions. * * @throw std::system_error, e.g. for locking */ virtual std::size_t stalled_completion_count() = 0; /** * Block and wait for next completion. * * @param polls_limit Maximum number of polls * * @return (was next completion context. But poll_completions can retrieve * that) * * @throw IFabric_runtime_error - ::fi_control fail * @throw std::system_error - pselect fail */ virtual void wait_for_next_completion(unsigned polls_limit = 0) = 0; /** * Block and wait for next completion. * * @param polls_limit Maximum time to wait * * @return (was next completion context. But poll_completions can retrieve * that) * * @throw IFabric_runtime_error - ::fi_control fail * @throw std::system_error - pselect fail */ virtual void wait_for_next_completion(std::chrono::milliseconds timeout) = 0; /** * Unblock any threads waiting on completions * * @throw std::system_error, e.g. for locking */ virtual void unblock_completions() = 0; /* Additional TODO: - support for completion and event counters - support for statistics collection */ }; class IFabric_memory_control { public: using const_byte_span = common::const_byte_span; virtual ~IFabric_memory_control() {} using memory_region_t = IFabric_memory_region *; /** * Register buffer for RDMA * * @param contig_addr Pointer to contiguous region * @param size Size of buffer in bytes * @param key Requested key for the remote memory. Note: if the fabric * provider uses the key (i.e., the fabric provider memory region attributes * do not include the FI_MR_PROV_KEY bit), then the key must be * unique among registered memory regions. As this API does not * expose these attributes, the only safe strategy is to assume * that the key must be unique among registered memory regsions. * @param flags Flags e.g., FI_REMOTE_READ|FI_REMOTE_WRITE. Flag definitions * are in <rdma/fabric.h> * * @return Memory region handle * * @throw std::range_error - address already registered * @throw std::logic_error - inconsistent memory registry */ virtual memory_region_t register_memory(const void * contig_addr, std::size_t size, std::uint64_t key, std::uint64_t flags) { return register_memory(common::make_const_byte_span(contig_addr, size), key, flags); } virtual memory_region_t register_memory(const_byte_span contig_, std::uint64_t key, std::uint64_t flags) = 0; /** * De-register memory region * * @param memory_region Memory region to de-register * * @throw std::range_error - address not registered * @throw std::logic_error - inconsistent memory registry */ virtual void deregister_memory(memory_region_t memory_region) = 0; virtual std::uint64_t get_memory_remote_key(memory_region_t) const noexcept = 0; virtual void * get_memory_descriptor(memory_region_t) const noexcept = 0; /** * Asynchronously post a buffer to receive data * * @param buffers Buffer span (containing regions should be registered) * * @return Work (context) identifier * * @throw IFabric_runtime_error - ::fi_recvv fail */ virtual void post_recv(gsl::span<const ::iovec> buffers, void **descriptors, void *context) = 0; void post_recv(const ::iovec *first, const ::iovec *last, void **descriptors, void *context) { return post_recv( {first, last}, descriptors, context); } virtual void post_recv(gsl::span<const ::iovec> buffers, void *context) = 0; }; class IFabric_client; class IFabric_client_grouped; /** * IFabric_initiator * operations unique to a connected endpoint */ class IFabric_initiator { public: virtual ~IFabric_initiator() {} /** * Asynchronously post a buffer to the connection * * @param buffers Buffer span (containing regions should be registered) * * @return Work (context) identifier * * @throw IFabric_runtime_error std::runtime_error - ::fi_sendv fail */ virtual void post_send(gsl::span<const ::iovec> buffers, void **descriptors, void *context) = 0; void post_send(const ::iovec *first, const ::iovec *last, void **descriptors, void *context) { return post_send( {first, last}, descriptors, context); } virtual void post_send(gsl::span<const ::iovec> buffers, void *context) = 0; /** * Post RDMA read operation * * @param buffers Destination buffer span * @param remote_addr Remote address * @param key Key for remote address * @param out_context * * @throw IFabric_runtime_error - ::fi_readv fail * */ virtual void post_read(gsl::span<const ::iovec> buffers, void ** descriptors, std::uint64_t remote_addr, std::uint64_t key, void * context) = 0; void post_read(const ::iovec *first, const ::iovec *last, void ** descriptors, std::uint64_t remote_addr, std::uint64_t key, void * context) { return post_read( { first, last }, descriptors, remote_addr, key, context); } virtual void post_read(gsl::span<const ::iovec> buffers, std::uint64_t remote_addr, std::uint64_t key, void * context) = 0; /** * Post RDMA write operation * * @param buffers Source buffer span * @param remote_addr Remote address * @param key Key for remote address * @param out_context * * @throw IFabric_runtime_error - ::fi_writev fail * */ virtual void post_write(const gsl::span<const ::iovec> buffers, void ** descriptors, std::uint64_t remote_addr, std::uint64_t key, void * context) = 0; void post_write(const ::iovec *first, const ::iovec *last, void ** descriptors, std::uint64_t remote_addr, std::uint64_t key, void * context) { return post_write( gsl::span<const ::iovec>(first, last), descriptors, remote_addr, key, context); } virtual void post_write(const gsl::span<const ::iovec> buffers, std::uint64_t remote_addr, std::uint64_t key, void * context) = 0; /** * Send message without completion * * @param connection Connection to inject on * @param buf Data to send * @param buf Length of data to send (must not exceed * IFabric_connection::max_inject_size()) * * @throw IFabric_runtime_error - ::fi_inject fail */ virtual void inject_send(const void *buf, std::size_t len) = 0; /* TODO: atomic RMA operations */ }; /** * IFabric_endpoint_connected * operations available to a connected endpoint */ class IFabric_endpoint_connected : public IFabric_memory_control , public IFabric_initiator , public IFabric_op_completer { /* TODO: statistics collection */ }; class IFabric_endpoint_unconnected : public IFabric_memory_control { }; /** * Fabric/RDMA-based network component * an acrive bit not connected endpoint */ class IFabric_endpoint_unconnected_client : public IFabric_endpoint_unconnected { public: /** * Open a fabric client (active endpoint) connection to a server. Active * endpoints usually correspond with hardware resources, e.g. verbs queue * pair. Options may not conflict with those specified for the fabric. * * @param json_configuration Configuration string in JSON * @param remote_endpoint The IP address (URL) of the server * @param port The IP port on the server * * @return the endpoint * * @throw std::bad_alloc - destination address alloc failed * @throw std::bad_alloc - libfabric out of memory * @throw std::bad_alloc - libfabric out of memory (creating a new server) * @throw std::bad_alloc - out of memory * @throw std::domain_error : json file parse-detected error * @throw std::logic_error : socket initialized with a negative value (from * ::socket) in Fd_control * @throw std::logic_error : unexpected event * @throw std::system_error : error receiving fabric server name * @throw std::system_error : pselect fail (expecting event) * @throw std::system_error : resolving address * @throw std::system_error : pselect fail * @throw std::system_error : read error on event pipe * @throw std::system_error - writing event pipe (normal callback) * @throw std::system_error - writing event pipe (readerr_eq) * @throw std::system_error - receiving data on socket * @throw IFabric_runtime_error - ::fi_domain fail * @throw IFabric_runtime_error - ::fi_connect fail * @throw IFabric_runtime_error - ::fi_ep_bind fail * @throw IFabric_runtime_error - ::fi_enable fail * @throw IFabric_runtime_error - ::fi_ep_bind fail (event registration) * */ virtual IFabric_client *make_open_client() = 0; /** * Open a fabric endpoint for which communications are divided into smaller * entities (groups). Options may not conflict with those specified for the * fabric. * * @param json_configuration Configuration string in JSON * @param remote_endpoint The IP address (URL) of the server * @param port The IP port on the server * * @return the endpoint * * @throw std::bad_alloc - destination address alloc failed * @throw std::bad_alloc - libfabric out of memory * @throw std::bad_alloc - libfabric out of memory (creating a new server) * @throw std::bad_alloc - out of memory * @throw std::domain_error : json file parse-detected error * @throw std::logic_error : socket initialized with a negative value (from * ::socket) in Fd_control * @throw std::logic_error : unexpected event * @throw std::system_error : error receiving fabric server name * @throw std::system_error : pselect fail (expecting event) * @throw std::system_error : resolving address * @throw std::system_error : pselect fail * @throw std::system_error : read error on event pipe * @throw std::system_error - writing event pipe (normal callback) * @throw std::system_error - writing event pipe (readerr_eq) * @throw std::system_error - receiving data on socket * @throw IFabric_runtime_error - ::fi_domain fail * @throw IFabric_runtime_error - ::fi_connect fail * @throw IFabric_runtime_error - ::fi_ep_bind fail * @throw IFabric_runtime_error - ::fi_enable fail * @throw IFabric_runtime_error - ::fi_ep_bind fail (event registration) * */ virtual IFabric_client_grouped *make_open_client_grouped() = 0; }; class IFabric_connection { public: virtual ~IFabric_connection() {} /** * Get address of connected peer (taken from fi_getpeer during * connection instantiation). The fi_getpeer documentation says * "The address must be in the same format as that specified using * fi_info: addr_format when the endpoint was created". Presumably * this means that the address returned by fi_getpeer *will* be in * that same form, and is thus dependent on the implementation of * endpoint creation. * * * @return Peer endpoint address * @throw std::bad_alloc, e.g. */ virtual std::string get_peer_addr() = 0; /** * Get local address of connection (taken from fi_getname during * connection instantiation). * * * @return Local endpoint address * @throw std::bad_alloc, e.g. */ virtual std::string get_local_addr() = 0; /** * Get the maximum message size for the provider * * @return Max message size in bytes */ virtual std::size_t max_message_size() const noexcept = 0; /** * Get the maximum inject message size for the provider * * @return Max inject message size in bytes */ virtual std::size_t max_inject_size() const noexcept = 0; /* Additional TODO: - support for atomic RMA operations - support for completion and event counters - support for statistics collection */ }; /** * An endpoint with a communication channel. Distinguished from a connection * which can provide grouped communications channels, but does not of itself * provide communications. * */ class IFabric_endpoint_comm : public IFabric_connection , public IFabric_endpoint_connected { }; /** * An endpoint established as a server. * */ class IFabric_server : public IFabric_endpoint_comm { }; /** * An endpoint established as a client. * */ class IFabric_client : public IFabric_endpoint_comm { }; /* A group: memory control, commands, and completions */ class IFabric_group : public IFabric_endpoint_connected { }; /** * An endpoint "grouped", without a communication channel. * Can provide communications channels, but does not initiate operations * */ class IFabric_endpoint_grouped : public IFabric_connection , public IFabric_memory_control , public IFabric_op_completer { public: /** * Allocate group (for partitioned completion handling) * * @throw std::system_error, e.g. for locking * @throw std::bad_alloc, e.g. */ virtual IFabric_group *allocate_group() = 0; }; /** * A client endpoint which cannot initiate commands but which * can allocate "commuicators" which can initiate commands. * */ class IFabric_client_grouped : public IFabric_endpoint_grouped { }; /** * A server endpoint which cannot initiate commands but which * can allocate "commuicators" which can initiate commands. * */ class IFabric_server_grouped : public IFabric_endpoint_grouped { }; /** * Fabric passive endpoint. Instantiation of this interface normally creates * an active thread that uses the fabric connection manager to handle * connections (see man fi_cm). On release of the interface, the endpoint * is destroyed. */ class IFabric_passive_endpoint { public: virtual ~IFabric_passive_endpoint() {} /** * Get the maximum message size for the provider * * @return Max message size in bytes */ virtual std::size_t max_message_size() const noexcept = 0; /** * Get provider name * * * @return Provider name * * @throw std::bad_alloc, e.g. */ virtual std::string get_provider_name() const = 0; }; class IFabric_endpoint_unconnected_server : public IFabric_endpoint_unconnected { }; /** * Fabric passive endpoint providing servers with ordinary (not grouped) * communicators. */ class IFabric_server_factory : public IFabric_passive_endpoint { public: /** * Server/accept side handling of new connections (handled by the * active thread) are queued so that they can be taken by a polling * thread and integrated into the processing loop. This method is * normally invoked until NULL is returned. * * @return New connection, or NULL if no new connection. * * @throw std::system_error, e.g. for locking * @throw std::logic_error : unexpected event * @throw std::system_error : read error on event pipe * @throw std::system_error : failure to listen for connections */ virtual IFabric_endpoint_unconnected_server *get_new_endpoint_unconnected() = 0; virtual IFabric_server *open_connection(IFabric_endpoint_unconnected_server *) = 0; /** * Close connection and release any associated resources * * @param connection * * @throw std::system_error, e.g. for locking */ virtual void close_connection(IFabric_server *connection) = 0; /** * Used to get a vector of active connection belonging to this * end point. * * @return Vector of active connections * * @throw std::bad_alloc, e.g. */ virtual std::vector<IFabric_server *> connections() = 0; /** * Get provider name * * * @return Provider name * * @throw std::bad_alloc, e.g. */ virtual std::string get_provider_name() const = 0; }; /* Fabric passive endpoint providing servers with grouped communicators. */ class IFabric_server_grouped_factory : public IFabric_passive_endpoint { public: /** * Server/accept side handling of new connections (handled by the * active thread) are queued so that they can be taken by a polling * thread an integrated into the processing loop. This method is * normally invoked until NULL is returned. * * * @return New connection, or NULL if no new connection. * * @throw std::logic_error : unexpected event * @throw std::system_error, e.g. for locking * @throw std::system_error : read error on event pipe */ virtual IFabric_endpoint_unconnected_server *get_new_endpoint_unconnected() = 0; virtual IFabric_server_grouped *open_connection(IFabric_endpoint_unconnected_server *) = 0; /** * Close connection and release any associated resources * * @param connection * * @throw std::system_error, e.g. for locking */ virtual void close_connection(IFabric_server_grouped *connection) = 0; /** * Used to get a vector of active connection belonging to this * end point. * * @return Vector of active connections * @throw std::bad_alloc, e.g. */ virtual std::vector<IFabric_server_grouped *> connections() = 0; }; class IFabric { public: using memory_region_t = IFabric_memory_region *; DECLARE_INTERFACE_UUID(0xc373d083, 0xe629, 0x46c9, 0x86fa, 0x6f, 0x96, 0x40, 0x61, 0x10, 0xdf); virtual ~IFabric() {} /** * Open a fabric server factory. Endpoints usually correspond with hardware * resources, e.g. verbs queue pair. Options may not conflict with those * specified for the fabric. * * @param json_configuration Configuration string in JSON * * @return the endpoint * * @throw std::domain_error : json file parse-detected error * @throw IFabric_runtime_error - ::fi_passive_ep fail * @throw IFabric_runtime_error - ::fi_pep_bind fail * @throw IFabric_runtime_error - ::fi_listen fail */ virtual IFabric_server_factory *open_server_factory(const common::string_view json_configuration, std::uint16_t port) = 0; /** * Open a fabric "server grouped" factory. Endpoints usually correspond with * hardware resources, e.g. verbs queue pair. Options may not conflict with * those specified for the fabric. "Server groups" are servers in which each * operation is assigned to a "communication group." Each "completion group" * may be separately polled for completions. * * @param json_configuration Configuration string in JSON * * @return the endpoint * * @throw std::domain_error : json file parse-detected error * @throw IFabric_runtime_error - ::fi_passive_ep fail * @throw IFabric_runtime_error - ::fi_pep_bind fail * @throw IFabric_runtime_error - ::fi_listen fail */ virtual IFabric_server_grouped_factory *open_server_grouped_factory(const common::string_view json_configuration, std::uint16_t port) = 0; virtual IFabric_endpoint_unconnected_client *make_endpoint(const common::string_view json_configuration, common::string_view remote_endpoint, std::uint16_t port) = 0; /* * provider name in the fabric. */ virtual const char *prov_name() const noexcept = 0; }; class IFabric_factory : public component::IBase { public: DECLARE_INTERFACE_UUID(0xfac3d083, 0xe629, 0x46c9, 0x86fa, 0x6f, 0x96, 0x40, 0x61, 0x10, 0xdf); /** * Open a fabric endpoint. Endpoints usually correspond with hardware * resources, e.g. verbs queue pair Options should include provider, * capabilities, active thread core. * * @param json_configuration Configuration string in JSON * form. e.g. { "caps":["FI_MSG","FI_RMA"], "preferred_provider" : "verbs"} * @return */ virtual ~IFabric_factory() {} /** * @throw std::bad_alloc - out of memory * @throw std::domain_error : json file parse-detected error * @throw IFabric_runtime_error - ::fi_control fail */ virtual IFabric *make_fabric(const common::string_view json_configuration) = 0; }; } // namespace component #endif // __API_FABRIC_ITF__
{ "alphanum_fraction": 0.658169544, "avg_line_length": 34.9827798278, "ext": "h", "hexsha": "9b00735a33b312e8e5cfd05d6fb7c33c53892d5f", "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/components/api/fabric_itf.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "omriarad/mcas", "max_issues_repo_path": "src/components/api/fabric_itf.h", "max_line_length": 168, "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/components/api/fabric_itf.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 6737, "size": 28441 }
/**************************************************************************** * * * Copyright (C) 2005 ~ 2015 Neutrino International Inc. * * * * Author : Brian Lin <lin.foxman@gmail.com>, Skype: wolfram_lin * * * * QtGSL acts as an interface between Qt and GNU GSL library. * * Please keep QtGSL as simple as possible. * * * * Qt Version : 5.4.1 * * CIOS Version : 1.6.0 * * * ****************************************************************************/ #ifndef QT_GSL_H #define QT_GSL_H #include <QtCore> #include <Essentials> extern "C" { #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_const.h> #include <gsl/gsl_const_cgs.h> #include <gsl/gsl_const_cgsm.h> #include <gsl/gsl_const_mks.h> #include <gsl/gsl_const_mksa.h> #include <gsl/gsl_const_num.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_qrng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sum.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permute.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_combination.h> #include <gsl/gsl_multiset.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_heapsort.h> #include <gsl/gsl_dht.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_histogram2d.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_chebyshev.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_complex_math.h> } QT_BEGIN_NAMESPACE #ifndef QT_STATIC # if defined(QT_BUILD_QTGSL_LIB) # define Q_GSL_EXPORT Q_DECL_EXPORT # else # define Q_GSL_EXPORT Q_DECL_IMPORT # endif #else # define Q_GSL_EXPORT #endif class Q_GSL_EXPORT vcomplex { // GSL complex number public: double x ; double y ; explicit vcomplex (void) ; explicit vcomplex (double x,double y) ; vcomplex (const vcomplex & complex) ; virtual ~vcomplex (void) ; double real (void) ; double imaginary (void) ; double argument (void) ; double magnitude (void) ; // abs , |z| double squared (void) ; // squared magnitude , |z|^2 double logabs (void) ; // log|z| vcomplex & operator = (vcomplex & complex) ; vcomplex & operator += (vcomplex & complex) ; vcomplex & operator -= (vcomplex & complex) ; vcomplex & operator *= (vcomplex & complex) ; vcomplex & operator /= (vcomplex & complex) ; vcomplex & rectangular (double x,double y) ; // equal to operator = vcomplex & polar (double r,double theta) ; vcomplex & conjugate (void) ; // z^* = x - i y vcomplex & inverse (void) ; // 1/z = (x - i y)/(x^2 + y^2) vcomplex & negative (void) ; // -z = (-x) + i(-y) void sin (vcomplex & value) ; void cos (vcomplex & value) ; void tan (vcomplex & value) ; void sec (vcomplex & value) ; void csc (vcomplex & value) ; void cot (vcomplex & value) ; void arcsin (vcomplex & value) ; void arccos (vcomplex & value) ; void arctan (vcomplex & value) ; void arcsec (vcomplex & value) ; void arccsc (vcomplex & value) ; void arccot (vcomplex & value) ; void sinh (vcomplex & value) ; void cosh (vcomplex & value) ; void tanh (vcomplex & value) ; void sech (vcomplex & value) ; void csch (vcomplex & value) ; void coth (vcomplex & value) ; void arcsinh (vcomplex & value) ; void arccosh (vcomplex & value) ; void arctanh (vcomplex & value) ; void arcsech (vcomplex & value) ; void arccsch (vcomplex & value) ; void arccoth (vcomplex & value) ; protected: private: }; typedef QList < vcomplex > vcomplexes ; namespace N { class Q_GSL_EXPORT Random ; class Q_GSL_EXPORT Histogram ; class Q_GSL_EXPORT Chebyshev ; class Q_GSL_EXPORT Permutation ; class Q_GSL_EXPORT Combination ; class Q_GSL_EXPORT Multisets ; class Q_GSL_EXPORT MultiFit ; class Q_GSL_EXPORT BSplines ; class Q_GSL_EXPORT Interpolation ; class Q_GSL_EXPORT Vector ; class Q_GSL_EXPORT Matrix ; class Q_GSL_EXPORT LevinWithError ; class Q_GSL_EXPORT Levin ; namespace Math { Q_GSL_EXPORT QList<int> Differential (QList<int> & discrete); Q_GSL_EXPORT QList<long long> Differential (QList<long long> & discrete); Q_GSL_EXPORT QList<float> Differential (QList<float> & discrete); Q_GSL_EXPORT QList<double> Differential (QList<double> & discrete); Q_GSL_EXPORT QList<double> VectorMultiply (QList<double> & discrete,double v); Q_GSL_EXPORT double SquareSigma (QList<double> & discrete); Q_GSL_EXPORT double VectorMin (QList<double> & discrete); Q_GSL_EXPORT double VectorMax (QList<double> & discrete); Q_GSL_EXPORT QByteArray VectorByteArray (QList<double> & discrete); Q_GSL_EXPORT QList<double> VectorFromByteArray (QByteArray & B); Q_GSL_EXPORT double Average (int total,double * values) ; Q_GSL_EXPORT int AddValues (int total,double * values,double value) ; Q_GSL_EXPORT int Multiply (int total,double * values,double value) ; Q_GSL_EXPORT int FaPb (int total,double * values,double a,double b) ; // F = a * ( x[i] + b ) Q_GSL_EXPORT int FaXb (int total,double * values,double a,double b) ; // F = a * x[i] + b Q_GSL_EXPORT int Divide (int total,double * values,double value) ; Q_GSL_EXPORT void CutOff (int total,double * values,double minimum,double maximum) ; Q_GSL_EXPORT int toByteArray (const vcomplexes & complexes,QByteArray & body) ; Q_GSL_EXPORT int toComplexes (const QByteArray & body,vcomplexes & complexes) ; Q_GSL_EXPORT int toDouble (int items,char * CHARS ,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,unsigned char * UCHARS ,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,short * SHORTS ,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,unsigned short * USHORTS,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,int * INTS ,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,unsigned int * UINTS ,double * DOUBLEs) ; Q_GSL_EXPORT int toDouble (int items,float * FLOATS ,double * DOUBLEs) ; Q_GSL_EXPORT int Addition (int items,double * A,double * B ) ; // A += B Q_GSL_EXPORT int Addition (int items,double * A,double * B,double * C) ; // A = B + C Q_GSL_EXPORT int Subtract (int items,double * A,double * B ) ; // A -= B Q_GSL_EXPORT int Subtract (int items,double * A,double * B,double * C) ; // A = B - C Q_GSL_EXPORT int Multiply (int items,double * A,double * B ) ; // A *= B Q_GSL_EXPORT int Multiply (int items,double * A,double * B,double * C) ; // A = B * C Q_GSL_EXPORT int Divide (int items,double * A,double * B ) ; // A /= B Q_GSL_EXPORT int Divide (int items,double * A,double * B,double * C) ; // A = B / C Q_GSL_EXPORT void Sort (double * data,const size_t stride,size_t n) ; Q_GSL_EXPORT void Sort (float * data,const size_t stride,size_t n) ; Q_GSL_EXPORT void Sort (int * data,const size_t stride,size_t n) ; Q_GSL_EXPORT void SortIndex (size_t * p,const double * data,size_t stride,size_t n) ; Q_GSL_EXPORT void SortIndex (size_t * p,const float * data,size_t stride,size_t n) ; Q_GSL_EXPORT void SortIndex (size_t * p,const int * data,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallest (double * dest,size_t k,const double * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallest (float * dest,size_t k,const float * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallest (int * dest,size_t k,const int * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargest (double * dest,size_t k,const double * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargest (float * dest,size_t k,const float * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargest (int * dest,size_t k,const int * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallestIndex (size_t * p,size_t k,const double * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallestIndex (size_t * p,size_t k,const float * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortSmallestIndex (size_t * p,size_t k,const int * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargestIndex (size_t * p,size_t k,const double * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargestIndex (size_t * p,size_t k,const float * src,size_t stride,size_t n) ; Q_GSL_EXPORT int SortLargestIndex (size_t * p,size_t k,const int * src,size_t stride,size_t n) ; Q_GSL_EXPORT double Mean (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double Variance (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double VarianceMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double StandardDeviation (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double StandardDeviationMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double TotalSumSquares (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double TotalSumSquaresMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double VarianceFixedMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double StandardDeviationFixedMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double AbsoluteDeviation (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double AbsoluteDeviationMean (const double data [],size_t stride,size_t n,double mean) ; Q_GSL_EXPORT double Skew (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double SkewMeanSD (const double data [],size_t stride,size_t n,double mean,double sd) ; Q_GSL_EXPORT double Kurtosis (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double KurtosisMeanSD (const double data [],size_t stride,size_t n,double mean,double sd) ; Q_GSL_EXPORT double Lag1AutoCorrelation (const double data [],const size_t stride,const size_t n); Q_GSL_EXPORT double Lag1AutoCorrelationMean (const double data [],const size_t stride,const size_t n,const double mean) ; Q_GSL_EXPORT double Covariance (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n) ; Q_GSL_EXPORT double CovarianceMean (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n,const double mean1,const double mean2) ; Q_GSL_EXPORT double Correlation (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n) ; Q_GSL_EXPORT double WeightedMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedVariance (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedVarianceMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ; Q_GSL_EXPORT double WeightedSd (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedSdMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ; Q_GSL_EXPORT double WeightedVarianceFixedMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n,const double mean) ; Q_GSL_EXPORT double WeightedSdFixedMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n,const double mean) ; Q_GSL_EXPORT double WeightedTss (const double w [],const size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedTssMean (const double w [],const size_t wstride,const double data[],size_t stride,size_t n,double wmean) ; Q_GSL_EXPORT double WeightedAbsoluteDeviation (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedAbsoluteDeviationMean (const double w [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ; Q_GSL_EXPORT double WeightedSkew (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedSkewMeanSd (const double w [],size_t wstride,const double data[],size_t stride,size_t n,double wmean,double wsd) ; Q_GSL_EXPORT double WeightedKurtosis (const double w [],size_t wstride,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT double WeightedKurtosisMeanSd (const double w [],size_t wstride,const double data[],size_t stride,size_t n,double wmean,double wsd) ; Q_GSL_EXPORT double MaxValue (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double MinValue (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT size_t MaxIndex (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT size_t MinIndex (const double data [],size_t stride,size_t n) ; Q_GSL_EXPORT double MedianFromSorted (const double sorted_data[],size_t stride,size_t n) ; Q_GSL_EXPORT double QuantileFromSorted (const double sorted_data[],size_t stride,size_t n,double f) ; Q_GSL_EXPORT void MinMax (double * min,double * max,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT void MinMaxIndex (size_t * min_index,size_t * max_index,const double data[],size_t stride,size_t n) ; Q_GSL_EXPORT int FitLinear (const double * x,const size_t xstride,const double * y,const size_t ystride,size_t n,double * c0,double * c1,double * cov00,double * cov01,double * cov11,double * sumsq) ; Q_GSL_EXPORT int FitMul (const double * x,const size_t xstride,const double * y,const size_t ystride,size_t n,double * c1,double * cov11,double * sumsq) ; Q_GSL_EXPORT int WeightedFitLinear (const double * x,const size_t xstride,const double * w,const size_t wstride,const double * y,const size_t ystride,size_t n,double * c0,double * c1,double * cov00,double * cov01,double * cov11,double * chisq) ; Q_GSL_EXPORT int WeightedFitMul (const double * x,const size_t xstride,const double * w,const size_t wstride,const double * y,const size_t ystride,size_t n,double * c1,double * cov11,double * sumsq) ; Q_GSL_EXPORT int FitLinearest (double x,double c0,double c1,double cov00,double cov01,double cov11,double * y,double * y_err) ; Q_GSL_EXPORT int FitMulest (double x,double c1,double cov11,double * y,double * y_err) ; Q_GSL_EXPORT int DerivativeCentral (double x,double h,double * result,double * abserr,MathFunction function,void * params) ; Q_GSL_EXPORT int DerivativeForward (double x,double h,double * result,double * abserr,MathFunction function,void * params) ; Q_GSL_EXPORT int DerivativeBackward (double x,double h,double * result,double * abserr,MathFunction function,void * params) ; Q_GSL_EXPORT void IntegerMiddleArray (int items,unsigned char * array,int gaps,void * funcdata) ; } namespace Polynomial { Q_GSL_EXPORT double Eval (const double c[] ,const int len,const double x) ; Q_GSL_EXPORT vcomplex Eval (const double c[] ,const int len,const vcomplex z) ; Q_GSL_EXPORT vcomplex Eval (const vcomplexes & c,const int len,const vcomplex z) ; Q_GSL_EXPORT int Derivatives (const double c[],const size_t lenc,const double x,double res[],const size_t lenres) ; Q_GSL_EXPORT int ddInit (double dd[],const double xa[],const double ya[],size_t size) ; Q_GSL_EXPORT double ddEval (const double dd[],const double xa[],const size_t size,const double x) ; Q_GSL_EXPORT int ddTaylor (double c[],double xp,const double dd[],const double xa[],size_t size,double w[]) ; Q_GSL_EXPORT int Quadratic (double a,double b,double c,double * x0,double * x1) ; Q_GSL_EXPORT int Quadratic (double a,double b,double c,vcomplex & z0,vcomplex & z1) ; Q_GSL_EXPORT int Cubic (double a,double b,double c,double * x0,double * x1,double * x2) ; Q_GSL_EXPORT int Cubic (double a,double b,double c,vcomplex & z0,vcomplex & z1,vcomplex & z2) ; } namespace Cpp { Q_GSL_EXPORT int SizeOf (Cpp::ValueTypes type) ; } /***************************************************************************** * * * Statistics * * * *****************************************************************************/ class Q_GSL_EXPORT Random { public: gsl_rng_type * Type ; gsl_rng * Generator ; gsl_qrng_type * qType ; gsl_qrng * Quasi ; explicit Random (unsigned long int seed = 0) ; explicit Random (gsl_rng_type * type,unsigned long int seed = 0 ) ; explicit Random (gsl_qrng_type * type,unsigned int dimension) ; virtual ~Random (void) ; static const gsl_rng_type ** All (void) ; QString Name (void) ; unsigned long int Max (void) ; unsigned long int Min (void) ; bool State (QByteArray & state) ; bool Create (gsl_rng_type * type,unsigned long int seed = 0 ) ; unsigned long int Get (void) ; // [min,max] unsigned long int Get (unsigned long int n) ; // [0,n-1] double Uniform (void) ; // [0,1) double Positive (void) ; // (0,1) bool Create (gsl_qrng_type * type,unsigned int dimension) ; int QuasiGet (double x[]) ; QString QuasiName (void) ; bool QuasiState (QByteArray & state) ; void QuasiReset (void) ; Random & operator = (Random & source) ; double Gaussian (double sigma) ; double GaussianPDF (double x,double sigma) ; double GaussianZiggurat (double sigma) ; double GaussianRatioMethod (double sigma) ; double UnitGaussian (void) ; double UnitGaussianPDF (double x) ; double UnitGaussianRatioMethod (void) ; double CdfGaussianP (double x,double sigma) ; double CdfGaussianQ (double x,double sigma) ; double CdfGaussianPinv (double P,double sigma) ; double CdfGaussianQinv (double Q,double sigma) ; double CdfUnitGaussianP (double x) ; double CdfUnitGaussianQ (double x) ; double CdfUnitGaussianPinv (double P) ; double CdfUnitGaussianQinv (double Q) ; double GaussianTail (double a,double sigma) ; double GaussianTailPDF (double x,double a,double sigma) ; double UnitGaussianTail (double a) ; double UnitGaussianTailPDF (double x, double a) ; bool BivariateGaussian (double sigma_x , double sigma_y , double rho , double & x , double & y ) ; double BivariateGaussianPDF (double x , double y , double sigma_x , double sigma_y , double rho ) ; double Exponential (double mu) ; double ExponentialPDF (double x,double mu) ; double CdfExponentialP (double x,double mu) ; double CdfExponentialQ (double x,double mu) ; double CdfExponentialPinv (double P,double mu) ; double CdfExponentialQinv (double Q,double mu) ; double Laplace (double a) ; double LaplacePDF (double x,double a) ; double CdfLaplaceP (double x,double a) ; double CdfLaplaceQ (double x,double a) ; double CdfLaplacePinv (double P,double a) ; double CdfLaplaceQinv (double Q,double a) ; double ExpPow (double a,double b) ; double ExpPowPDF (double x,double a,double b) ; double CdfExpPowP (double x,double a,double b) ; double CdfExpPowQ (double x,double a,double b) ; double Cauchy (double a) ; double CauchyPDF (double x,double a) ; double CdfCauchyP (double x,double a) ; double CdfCauchyQ (double x,double a) ; double CdfCauchyPinv (double P,double a) ; double CdfCauchyQinv (double Q,double a) ; double Rayleigh (double sigma) ; double RayleighPDF (double x,double sigma) ; double CdfRayleighP (double x,double sigma) ; double CdfRayleighQ (double x,double sigma) ; double CdfRayleighPinv (double P,double sigma) ; double CdfRayleighQinv (double Q,double sigma) ; double RayleighTail (double a,double sigma) ; double RayleighTailPDF (double x,double a, double sigma) ; double Landau (void) ; double LandauPDF (double x) ; double Levy (double c,double alpha) ; double LevySkew (double c,double alpha,double beta) ; double Gamma (double a,double b) ; double GammaKnuth (double a,double b) ; double GammaKnuthPDF (double x,double a,double b) ; double CdfGammaP (double x,double a,double b) ; double CdfGammaQ (double x,double a,double b) ; double CdfGammaPinv (double P,double a,double b) ; double CdfGammaQinv (double Q,double a,double b) ; double Flat (double a,double b) ; double FlatPDF (double x,double a,double b) ; double CdfFlatP (double x,double a,double b) ; double CdfFlatQ (double x,double a,double b) ; double CdfFlatPinv (double P,double a,double b) ; double CdfFlatQinv (double Q,double a,double b) ; double LogNormal (double zeta,double sigma) ; double LogNormalPDF (double x,double zeta,double sigma) ; double CdfLogNormalP (double x,double zeta,double sigma) ; double CdfLogNormalQ (double x,double zeta,double sigma) ; double CdfLogNormalPinv (double P,double zeta,double sigma) ; double CdfLogNormalQinv (double Q,double zeta,double sigma) ; double ChiSquared (double nu) ; double ChiSquaredPDF (double x,double nu) ; double CdfChiSquaredP (double x,double nu) ; double CdfChiSquaredQ (double x,double nu) ; double CdfChiSquaredPinv (double P,double nu) ; double CdfChiSquaredQinv (double Q,double nu) ; double Fdist (double a,double b) ; double FdistPDF (double x,double a,double b) ; double CdfFdistP (double x,double a,double b) ; double CdfFdistQ (double x,double a,double b) ; double CdfFdistPinv (double P,double a,double b) ; double CdfFdistQinv (double Q,double a,double b) ; double Tdist (double a) ; double TdistPDF (double x,double a) ; double CdfTdistP (double x,double a) ; double CdfTdistQ (double x,double a) ; double CdfTdistPinv (double P,double a) ; double CdfTdistQinv (double Q,double a) ; double Beta (double a,double b) ; double BetaPDF (double x,double a,double b) ; double CdfBetaP (double x,double a,double b) ; double CdfBetaQ (double x,double a,double b) ; double CdfBetaPinv (double P,double a,double b) ; double CdfBetaQinv (double Q,double a,double b) ; double Logistic (double a) ; double LogisticPDF (double x,double a) ; double CdfLogisticP (double x,double a) ; double CdfLogisticQ (double x,double a) ; double CdfLogisticPinv (double P,double a) ; double CdfLogisticQinv (double Q,double a) ; double Pareto (double a,double b) ; double ParetoPDF (double x,double a,double b) ; double CdfParetoP (double x,double a,double b) ; double CdfParetoQ (double x,double a,double b) ; double CdfParetoPinv (double P,double a,double b) ; double CdfParetoQinv (double Q,double a,double b) ; double Weibull (double a,double b) ; double WeibullPDF (double x,double a,double b) ; double CdfWeibullP (double x,double a,double b) ; double CdfWeibullQ (double x,double a,double b) ; double CdfWeibullPinv (double P,double a,double b) ; double CdfWeibullQinv (double Q,double a,double b) ; double Gumbell (double a,double b) ; double GumbellPDF (double x,double a,double b) ; double CdfGumbellP (double x,double a,double b) ; double CdfGumbellQ (double x,double a,double b) ; double CdfGumbellPinv (double P,double a,double b) ; double CdfGumbellQinv (double Q,double a,double b) ; double Gumbell2 (double a,double b) ; double Gumbell2PDF (double x,double a,double b) ; double CdfGumbell2P (double x,double a,double b) ; double CdfGumbell2Q (double x,double a,double b) ; double CdfGumbell2Pinv (double P,double a,double b) ; double CdfGumbell2Qinv (double Q,double a,double b) ; unsigned int Poisson (double mu) ; double PoissonPDF (unsigned int k,double mu) ; double CdfPoissonP (unsigned int k,double mu) ; double CdfPoissonQ (unsigned int k,double mu) ; unsigned int Bernoulli (double p) ; double BernoulliPDF (unsigned int k,double p) ; unsigned int Binomial (double p,unsigned int n) ; double BinomialPDF (unsigned int k,double p,unsigned int n) ; double CdfBinomialP (unsigned int k,double p,unsigned int n) ; double CdfBinomialQ (unsigned int k,double p,unsigned int n) ; void Multinomial (size_t K , unsigned int N , const double p[] , unsigned int n[] ) ; double MultinomialPDF (size_t K , const double p[] , const unsigned int n[] ) ; double MultinomialLnPDF (size_t K , const double p[] , const unsigned int n[] ) ; unsigned int NegativeBinomial (double p,double n) ; double NegativeBinomialPDF (unsigned int k,double p,double n) ; double CdfNegativeBinomialP (unsigned int k,double p,double n) ; double CdfNegativeBinomialQ (unsigned int k,double p,double n) ; unsigned int Pascal (double p,unsigned int n) ; double PascalPDF (unsigned int k,double p,unsigned int n) ; double CdfPascalP (unsigned int k,double p,unsigned int n) ; double CdfPascalQ (unsigned int k,double p,unsigned int n) ; unsigned int Geometric (double p) ; double GeometricPDF (unsigned int k,double p) ; double CdfGeometricP (unsigned int k,double p) ; double CdfGeometricQ (unsigned int k,double p) ; unsigned int Hypergeometric (unsigned int n1 , unsigned int n2 , unsigned int t ) ; double HypergeometricPDF (unsigned int k , unsigned int n1 , unsigned int n2 , unsigned int t ) ; double CdfHypergeometricP (unsigned int k , unsigned int n1 , unsigned int n2 , unsigned int t ) ; double CdfHypergeometricQ (unsigned int k , unsigned int n1 , unsigned int n2 , unsigned int t ) ; unsigned int Logarithmic (double p) ; double LogarithmicPDF (unsigned int k, double p) ; void Dirichlet (int K,const double alpha[],double theta[]) ; double DirichletPDF (int K,const double alpha[],const double theta[]) ; double DirichletLnPDF (int K,const double alpha[],const double theta[]) ; void SphericalDir2D (double & x,double & y) ; void SphericalDir2DTrigMethod (double & x,double & y) ; void SphericalDir3D (double & x,double & y,double & z) ; void SphericalDirN (int n, double * x) ; gsl_ran_discrete_t * PrepareDiscrete (int K,const double * P) ; size_t Discrete (const gsl_ran_discrete_t * g) ; double DiscretePDF (size_t k,const gsl_ran_discrete_t * g) ; void DiscreteFree (gsl_ran_discrete_t * g) ; void Shuffle (void * base,size_t n,size_t size) ; void Choose (void * dest,size_t k,void * src,size_t n,size_t size) ; void Sample (void * dest,size_t k,void * src,size_t n,size_t size) ; }; class Q_GSL_EXPORT Histogram { public: gsl_histogram * histo ; gsl_histogram_pdf * histoPdf ; gsl_histogram2d * histo2d ; gsl_histogram2d_pdf * histo2dPdf ; explicit Histogram (void) ; explicit Histogram (int n) ; Histogram (const Histogram & histogram) ; virtual ~Histogram (void) ; bool allocate (int n) ; int setRanges (const double range[],int size) ; int uniformRanges (double xmin, double xmax) ; int increment (double x) ; int accumulate (double x,double weight) ; double get (int i) ; int getRange (int i,double * lower,double * upper) ; double Max (void) ; double Min (void) ; int bins (void) ; void reset (void) ; int find (double x,size_t * i) ; double maxValue (void) ; double minValue (void) ; double mean (void) ; double sigma (void) ; double sum (void) ; int maxBin (void) ; int minBin (void) ; int scale (double scale) ; int shift (double offset) ; bool equalBins (Histogram & histogram) ; int add (Histogram & histogram) ; int sub (Histogram & histogram) ; int mul (Histogram & histogram) ; int div (Histogram & histogram) ; bool allocatePdf (int n) ; double sample (double r) ; bool allocate2d (int nx,int ny) ; int setRanges2d (const double xrange[],int xsize,const double yrange[],int ysize) ; int uniformRanges2d (double xmin,double xmax,double ymin,double ymax) ; int increment2d (double x,double y) ; int accumulate2d (double x,double y,double weight) ; double get2d (int i,int j) ; int getXrange2d (int i,double * xlower,double * xupper) ; int getYrange2d (int j,double * ylower,double * yupper) ; double xmax2d (void) ; double xmin2d (void) ; int nx2d (void) ; int ny2d (void) ; double ymax2d (void) ; double ymin2d (void) ; void reset2d (void) ; int find2d (double x,double y,size_t * i,size_t * j) ; double maxValue2d (void) ; double minValue2d (void) ; void maxBin2d (size_t * i,size_t * j) ; void minBin2d (size_t * i,size_t * j) ; double xmean2d (void) ; double ymean2d (void) ; double xsigma2d (void) ; double ysigma2d (void) ; double cov2d (void) ; double sum2d (void) ; int scale2d (double scale) ; int shift2d (double offset); bool equalBins2d (Histogram & histogram) ; int add2d (Histogram & histogram) ; int sub2d (Histogram & histogram) ; int mul2d (Histogram & histogram) ; int div2d (Histogram & histogram) ; bool allocatePdf2d (int nx,int ny) ; int sample2d (double r1,double r2,double * x,double * y) ; protected: private: }; class Q_GSL_EXPORT Chebyshev { public: gsl_cheb_series * chebyshev ; gsl_function * function ; explicit Chebyshev (void) ; explicit Chebyshev (int n) ; Chebyshev (const Chebyshev & cheb) ; virtual ~Chebyshev (void) ; bool Allocate (int n) ; int Initialize (const double a , const double b , MathFunction equation , void * params ) ; size_t Order (void) ; size_t Size (void) ; double * Coefficients (void) ; double Eval (double x) ; double EvalN (size_t order , double x ) ; int EvalAbsErr (const double x , double * result , double * abserr ) ; int EvalNAbserr (const size_t order , const double x , double * result , double * abserr ) ; int Derivative (Chebyshev & cheb) ; int Integral (Chebyshev & cheb) ; protected: private: }; /***************************************************************************** * * * Permutation and Combination * * * *****************************************************************************/ class Q_GSL_EXPORT Permutation : public QByteArray { public: explicit Permutation (void) ; explicit Permutation (int size) ; explicit Permutation (QString m) ; Permutation (const Permutation & permutation) ; virtual ~Permutation (void) ; int isValid (void) ; // gsl_permutation_valid int toCUIDs (CUIDs & Cuids) ; QString toString (void) ; int toByteArray (QByteArray & blob) ; int setElements (int size) ; int elements (void) const ; size_t * array (void) const ; Permutation & operator = (const Permutation & permutation) ; Permutation & assign (const Permutation & permutation) ; Permutation & toIdentity (void) ; // gsl_permutation_init Permutation & Reverse (void) ; // gsl_permutation_reverse void swap (int a,int b) ; // gsl_permutation_swap void setValue (int index,int value) ; void setValue (int index,char value) ; void setValue (int index,QChar value) ; void setValue (QString m) ; int operator [] (int index) ; // gsl_permutation_get int next (void) ; // gsl_permutation_next int previous (void) ; // gsl_permutation_prev int inverse (Permutation & inv) ; // gsl_permutation_inverse(inv,this) int toCanonical (Permutation & canonical); //gsl_permutation_linear_to_canonical(canonical,this) int toLinear (Permutation & linear); //gsl_permutation_canonical_to_linear(linear,this) int inversions (void) ; // gsl_permutation_inversions int linearCycles (void) ; // gsl_permutation_linear_cycles int canonicalCycles (void) ; // gsl_permutation_canonical_cycles static int permute (const size_t * p,double * data,size_t stride,size_t n) ; // gsl_permute static int inverse (const size_t * p,double * data,size_t stride,size_t n) ; // gsl_permute_inverse // gsl_permute_vector // gsl_permute_vector_inverse // gsl_permutation_mul protected: private: }; class Q_GSL_EXPORT Combination : public QByteArray { public: explicit Combination (void) ; explicit Combination (int n,int k) ; Combination (const Combination & combination) ; virtual ~Combination (void) ; int isValid (void) ; // gsl_combination_valid int toCUIDs (CUIDs & Cuids) ; int toByteArray (QByteArray & blob) ; int setElements (int n,int k) ; int setChosen (int k) ; int elements (void) const ; int chosen (void) const ; size_t * array (void) const ; Combination & operator = (const Combination & combination) ; Combination & assign (const Combination & combination) ; Combination & toFirst (void) ; // gsl_combination_init_first Combination & toLast (void) ; // gsl_combination_init_last void setValue (int index,int value) ; void setValue (int index,char value) ; void setValue (int index,QChar value) ; int operator [] (int index) ; // gsl_combination_get int next (void) ; // gsl_combination_next int previous (void) ; // gsl_combination_prev protected: private: }; class Q_GSL_EXPORT Multisets : public QByteArray { public: explicit Multisets (void) ; explicit Multisets (int n,int k) ; Multisets (const Multisets & multisets) ; virtual ~Multisets (void) ; int isValid (void) ; // gsl_combination_valid int toCUIDs (CUIDs & Cuids) ; int toByteArray (QByteArray & blob) ; int setElements (int n,int k) ; int setChosen (int k) ; int elements (void) const ; int chosen (void) const ; size_t * array (void) const ; Multisets & operator = (const Multisets & multisets) ; Multisets & assign (const Multisets & multisets) ; Multisets & toFirst (void) ; // gsl_combination_init_first Multisets & toLast (void) ; // gsl_combination_init_last void setValue (int index,int value) ; void setValue (int index,char value) ; void setValue (int index,QChar value) ; int operator [] (int index) ; // gsl_combination_get int next (void) ; // gsl_combination_next int previous (void) ; // gsl_combination_prev protected: private: }; /***************************************************************************** * * * Linear algebra * * * *****************************************************************************/ class Q_GSL_EXPORT MultiFit { public: gsl_multifit_linear_workspace * work ; explicit MultiFit (void) ; explicit MultiFit (int n,int p) ; MultiFit (const MultiFit & fit) ; virtual ~MultiFit (void) ; bool Allocate (int n,int p) ; int Linear (const gsl_matrix * X , const gsl_vector * y , gsl_vector * c , gsl_matrix * cov , double * chisq ) ; int WeightedLinear (const gsl_matrix * X , const gsl_vector * w , const gsl_vector * y , gsl_vector * c , gsl_matrix * cov , double * chisq ) ; int svdLinear (const gsl_matrix * X ) ; int svdWeightedLinear (const gsl_matrix * X , const gsl_vector * w , const gsl_vector * y , double tol , size_t * rank , gsl_vector * c , gsl_matrix * cov , double * chisq ) ; int usvdWeightedLinear (const gsl_matrix * X , const gsl_vector * w , const gsl_vector * y , double tol , size_t * rank , gsl_vector * c , gsl_matrix * cov , double * chisq ) ; int Linearest (const gsl_vector * x , const gsl_vector * c , const gsl_matrix * cov , double * y , double * y_err ) ; int Residuals (const gsl_matrix * X , const gsl_vector * y , const gsl_vector * c , gsl_vector * r ) ; protected: private: }; class Q_GSL_EXPORT BSplines { public: gsl_bspline_workspace * work ; explicit BSplines (void) ; explicit BSplines (int k,int nbreak) ; BSplines (const BSplines & bsplines) ; virtual ~BSplines (void) ; bool Allocate (int k,int nbreak) ; int Knots (const gsl_vector * breakpts) ; int uniformKnots (const double a,const double b) ; int Eval (const double x,gsl_vector * B) ; int EvalNonZero (const double x , gsl_vector * Bk , size_t * istart , size_t * iend ) ; int Coefficients (void) ; double GrevilleAbscissa (int i) ; int DerivativeEval (const double x , const int nderiv , gsl_matrix * dB ) ; int DerivativeEvalNonZero (const double x , const int nderiv , gsl_matrix * dB , size_t * istart , size_t * iend ) ; protected: private: }; class Q_GSL_EXPORT Interpolation { public: gsl_interp * work ; gsl_interp_accel * accel ; gsl_spline * spline ; explicit Interpolation (void) ; explicit Interpolation (const gsl_interp_type * T,int size) ; Interpolation (const Interpolation & interpolation) ; virtual ~Interpolation (void) ; bool Allocate (const gsl_interp_type * T,int size) ; bool AllocateAccel (void) ; bool AllocateSpline (const gsl_interp_type * T,int size) ; int Initialize (const double xa[] , const double ya[] , int size ) ; int InitializeSpline (const double xa[] , const double ya[] , int size ) ; QString Name (void) ; QString SplineName (void) ; unsigned int MinSize (void) ; unsigned int MinSize (const gsl_interp_type * T) ; unsigned int SplineMinSize (void) ; int BSearch (const double x_array[] , double x , int index_lo , int index_hi ) ; int Find (const double x_array[] , int size , double x ) ; int Reset (void) ; double Eval (const double xa[] , const double ya[] , double x ) ; int EvalE (const double xa[] , const double ya[] , double x , double * y ) ; double EvalDerivative (const double xa[] , const double ya[] , double x ) ; double EvalDerivative2 (const double xa[] , const double ya[] , double x ) ; double EvalIntegral (const double xa[] , const double ya[] , double a , double b ) ; double SplineEval (double x) ; double SplineEvalDerivative (double x) ; double SplineEvalDerivative2 (double x) ; double SplineEvalIntegral (double a,double b) ; int EvalDerivativeE (const double xa[] , const double ya[] , double x , double * d ) ; int EvalDerivative2E (const double xa[] , const double ya[] , double x , double * d2 ) ; int EvalIntegralE (const double xa[] , const double ya[] , double a , double b , double * result ) ; int SplineEvalE (double x,double * y) ; int SplineEvalDerivativeE (double x,double * d) ; int SplineEvalDerivative2E (double x,double * d2) ; int SplineEvalIntegralE (double a,double b,double * result) ; protected: private: }; class Q_GSL_EXPORT Vector : public QByteArray { public: explicit Vector (void) ; explicit Vector (Cpp::ValueTypes type,int items) ; Vector (const Vector & vector) ; virtual ~Vector (void) ; Cpp::ValueTypes Type (void); int BytesPerCell (void) ; Vector & operator = (const Vector & vector) ; bool subVector (Vector & vector,int offset,int items) ; // get sub-vector bool setVector (int offset,Vector & vector) ; void reset (void); void set (Cpp::ValueTypes type,int items) ; void * array (void); int count (void) ; void setZero (void) ; void setAll (double x) ; void setBasis (int index) ; bool swap (int i,int j) ; bool reverse (void) ; int take (int pos,int items) ; int append (int items,const char * source) ; int append (int items,int gap,const char * source) ; int insert (int pos,int items,const char * source) ; int insert (int pos,int items,int gap,const char * source) ; Vector & operator += (Vector & vector) ; Vector & operator -= (Vector & vector) ; Vector & operator *= (Vector & vector) ; Vector & operator /= (Vector & vector) ; Vector & operator += (double x) ; Vector & operator -= (double x) ; Vector & operator *= (double x) ; QString toCpp (void) ; QString toCpp (QString variableName) ; // P(x) = c[0] + c[1] x + c[2] x^2 + ... + c[len-1] x^{len-1} double polynomial (double x) ; bool polynomial (vcomplex & x,vcomplex & result) ; int derivatives (double x,int length,double * results) ; protected: private: }; class Q_GSL_EXPORT Matrix : public QByteArray { public: explicit Matrix (void); explicit Matrix (Cpp::ValueTypes type,int rows,int columns) ; Matrix (const Matrix & matrix) ; virtual ~Matrix (void); Cpp::ValueTypes Type (void); Matrix & operator = (const Matrix & matrix) ; Matrix & operator += (const Matrix & matrix) ; Matrix & operator += (int value) ; Matrix & operator += (double value) ; Matrix & operator -= (const Matrix & matrix) ; Matrix & operator -= (int value) ; Matrix & operator -= (double value) ; Matrix & operator *= (int value) ; Matrix & operator *= (double value) ; Matrix & operator /= (int value) ; Matrix & operator /= (double value) ; void reset (void); void assign (const Matrix & matrix) ; void set (Cpp::ValueTypes type,int rows,int columns); void zerofill (void); int Rows (void); int Columns (void); int at (int row,int column) ; void * array (void); bool swapRows (int i,int j) ; bool swapColumns (int i,int j) ; bool transpose (void) ; bool transpose (const Matrix & T) ; bool inverse (Matrix & T) ; static double sum (double * v,int items) ; static void dispatch (int shift,int column,int items,double * R,double * S) ; static double multiple (int length,double * a,double * b) ; static double multiple (int length,double * R,double * a,double * b) ; QString toCpp (void) ; QString toCpp (QString variableName) ; void vertical (double * R,double * V) ; protected: private: }; /***************************************************************************** * * * Fourier, Wavelet, and other series transformation * * * *****************************************************************************/ class Q_GSL_EXPORT LevinWithError { public: gsl_sum_levin_u_workspace * work ; explicit LevinWithError (void) ; explicit LevinWithError (int n) ; LevinWithError (const LevinWithError & levin) ; virtual ~LevinWithError (void) ; bool Allocate (int n) ; int Acceleration (const double * array , const size_t n , double * sum_accel , double * abserr ) ; int MinMax (const double * array , const size_t n , const size_t min_terms , const size_t max_terms , double * sum_accel , double * abserr ) ; int Step (const double term , const size_t n , const size_t nmax , double * sum_accel ) ; protected: private: }; class Q_GSL_EXPORT Levin { public: gsl_sum_levin_utrunc_workspace * work ; explicit Levin (void) ; explicit Levin (int n) ; Levin (const Levin & levin) ; virtual ~Levin (void) ; bool Allocate (int n) ; int Acceleration (const double * array , const size_t n , double * sum_accel , double * abserr_trunc ) ; int MinMax (const double * array , const size_t n , const size_t min_terms , const size_t max_terms , double * sum_accel , double * abserr_trunc ) ; int Step (const double term , const size_t n , double * sum_accel ) ; protected: private: }; } Q_DECLARE_METATYPE(vcomplex) Q_DECLARE_METATYPE(vcomplexes) Q_DECLARE_METATYPE(N::Random) Q_DECLARE_METATYPE(N::Histogram) Q_DECLARE_METATYPE(N::Chebyshev) Q_DECLARE_METATYPE(N::Permutation) Q_DECLARE_METATYPE(N::Combination) Q_DECLARE_METATYPE(N::Multisets) Q_DECLARE_METATYPE(N::MultiFit) Q_DECLARE_METATYPE(N::BSplines) Q_DECLARE_METATYPE(N::Interpolation) Q_DECLARE_METATYPE(N::Vector) Q_DECLARE_METATYPE(N::Matrix) Q_DECLARE_METATYPE(N::LevinWithError) Q_DECLARE_METATYPE(N::Levin) QT_END_NAMESPACE #endif
{ "alphanum_fraction": 0.4870793858, "avg_line_length": 51.7060810811, "ext": "h", "hexsha": "adc5ceeb3167f1bff5eaca3db0de1acea5863d47", "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": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Vladimir-Lin/QtGSL", "max_forks_repo_path": "include/QtGSL/qtgsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "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": "Vladimir-Lin/QtGSL", "max_issues_repo_path": "include/QtGSL/qtgsl.h", "max_line_length": 270, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Vladimir-Lin/QtGSL", "max_stars_repo_path": "include/QtGSL/qtgsl.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13259, "size": 61220 }
//This example involves taking two arrays as input and returning their pearson coefficient as output #include <stdio.h> #include <gsl/gsl_statistics.h> double co_var(double* x, double* y, int n) { const size_t stride = 1; const size_t n1 = n; double pearson = gsl_stats_correlation(x, stride, y, stride, n1); return pearson; } //The main function has been provided solely for the sake of testing the function. It will be removed when the problem set is formally passed on. /* int main(void) { double x[5] = {1.0, 7.7 , 2.5, 3.1, 2.444}; double y[5] = {1.4, 3.2 , 8.1, 6.7, 2.12}; int n = 5; double p =co_var(x,y,n); printf ("%f\n",p); return 0; }*/
{ "alphanum_fraction": 0.6746626687, "avg_line_length": 23.8214285714, "ext": "c", "hexsha": "6afa453030224d3a7d8db0fecc2e96acb00c6b47", "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": "5836c24e21e53f31a43074468064a6c17c67845e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RITUait/OpenModelica", "max_forks_repo_path": "TestSample/Resources/Include/p2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "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": "RITUait/OpenModelica", "max_issues_repo_path": "TestSample/Resources/Include/p2.c", "max_line_length": 145, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RITUait/OpenModelica", "max_stars_repo_path": "Resources/Include/p2.c", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:23:39.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-03T04:23:39.000Z", "num_tokens": 213, "size": 667 }
/* SI POPULATION DYNAMICS SIMULATION MODEL */ /* Source code: SIMO.C; Last modified on 17/06/2017 */ //* Compilation lines: /// gcc -std=c99 -I/usr/include/gsl -Wall -o acacia simodel_rescue_seedbank.c vector.c -lgsl -lgslcblas -lncurses -lm // gcc -std=c99 -I/usr/include/gsl -Wall -o acacia simodel_rescue_seedbank_cluster.c vector.c -lgsl -lgslcblas -ltinfo -lncurses -lm // ./rescue -r 1 -g 500 -o 250 -n 3 -s 10 -f 0.25 -m 1.0 -v 0.0 -l 100 -x -z -k 0.2 -p 10 -t 50 -a 0.2 -b 0.1 -c 2 -d 2 -e demo -h gen -i fit -u indiv // ./simo_cluster -r 100 -g 500 -o 250 -n 3 -s 10 -f 0.25 -m 1.0 -v 0.0 -l 100 -p 10 -t 50 -a 0.2 -b 0.1 -c 2 -d 2 -e demo_control.dat -h gen_control.dat -i fit_control.dat -u indiv_control.dat #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <curses.h> #include <ncurses.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #include "vector.h" #include <getopt.h> /* PROGRAM CONSTANTS NOT IN MENUS */ #define IN 0 /* entry value for loops and if statements */ #define OUT 1 /* exit value for loops and if statements */ #define LEN 100 /* length of population grid size */ #define GENES 6 /* total number of loci (including the SI locus) */ #define ALL 2 /* number of alleles carried at each locus */ #define SDMAX 10 /* maximum number of seeds landing per cell */ #define SBMAX 20 /* maximum number of seeds landing per cell */ #define NR_END 1 #define FREE_ARG char* /* GENERAL SIMULATION PARAMETERS */ #define RUNS 100 /* number of replicate runs per treatment */ #define GEN 500 /* default value for number of generations */ #define INUM 250 /* initial number of occupied cells */ #define LINT 100 /* interval for data output (other than dynamics) */ #define NLOC 3 /* number of alleles per neutral locus */ #define SLOC 10 /* number of alleles per SI locus */ #define SITES 0.25 /* default fraction of safe sites */ #define LM 10.0 /* mean of lognormal distribution of ages */ #define LV 0.0 /* variance of lognormal distribution of ages */ /* WITHIN POPULATION DYNAMICS PARAMETERS */ #define D 0.05 /* death rate for adult plants */ #define MINR 2 /* default age for first reproduction */ #define PDIST 142 /* default radius for local pollen pool */ #define SDIST 50 /* default radius for seed dispersal */ #define EST 0.05 /* probability of seed establishment */ #define B0 100.0 /* maximum per-capita ovule production */ #define PLPR 0 /* probability of pollen contribution: random (0), size-dependent (1), distance-dependent (2) */ #define SITYPE 2 /* SI MODEL: gametophytic (0), codominant sporophytic (1), dominant sporophytic (2), neutral (3) */ #define SAFE_SITES_BOOL 0 /* Implement spatial rescue */ #define DEMO_RESCUE_BOOL 0 /* Implement demographic rescue */ #define GEN_RESCUE_POOL 0 /* Implement genetic rescue */ #define SITES_INCREASE 0.1 /* Fraction of safe sites increase */ #define POP_SIZE_INT 10 /* Population size to increase */ #define PNEW_S_ALLELE 0.2 /* Probability of new S alleles */ #define PNEW_N_ALLELE 0.0 /* Probability of new neutral alleles */ #define INT_THRESHOLD 50 /* Threshold of population size to intervene */ #define FIRE 0 /* Presence of fire events */ #define FIRE_SERO 1 /* Positive effect of fire on seed germination */ #define FIRE_PROB 0.5 /* Frequency of fire events */ #define FIRE_PROB_DEATH 0.075 /* Death rate by fire events */ #define FIRE_EST 0.075 /* Increased probability of seed establishment with fire */ #define SEEDBANK_MORT 0.1 /* Probability of seedbank seed mortality */ /* FUNCTION PROTOTYPES */ void free_fmatrix(float **,long int,long int,long int,long int); void free_fvector(float *,long int,long int); void free_imatrix(int **,long int,long int,long int,long int); void free_ivector(int *,long int,long int); void gene_data(int,int,int,int,float **,float **,float **,float **,float **, float **,float **,float **,float *,float *); void getfile(void); void grand_mean1(int,float **,float **,float **,int *,float **,float **,float **, int *, Vector *); void grand_mean2(int,int *,float **,float **,float **,float **,float **,float **, float **); void grand_mean3(int,int *,float **,float **,float **,float **,float **,float **, float **,float **); void genetic_rescue(gsl_rng *, int, int, int, int, float, float, Vector *,Vector *); void header(FILE *,int,int,int,double,double,int,int,float,int,float,int,int,int, int); void id_val(int,int,int,int *,int,int); void init_arrays(int,float **,float **,float **,int *,float **,float **,float **, float **,float **,float **,float **,float **,float **,float **,int *, float **,float **,float **,float **,float **,float **,float **,float **); void init_plants(gsl_rng *,int,int,int,float,float, Vector *,Vector *); void init_values(void); void kill_plants(gsl_rng *,double); void kill_plants_agedep(gsl_rng *,double,double); void make_ovule(gsl_rng *,int,int,int *,int *); void make_pollen_pool_r(int,int,int,int **,float *,int,int); void make_pollen_pool_s(int,int,int,int **,float *,int,int); void make_pollen_pool_d(int,int,int,int **,float *,int,float); void make_seed(gsl_rng *,int,int,int *,int *,int,int,int); void mate_system(int,int,void (**)(),void (**)()); void means1(int,float **,float **,float **,int,int,int); void means2(int,int,float **,float **,float **,float **,float **,float **, float **,Vector *,Vector *); void means3_g(int,int,int,int,int,float **,float **,float **,int *); void means3_n(int,int,int,int,int,float **,float **,float **,int *); void means3_scd(int,int,int,int,int,float **,float **,float **,int *); void means3_sd(int,int,int,int,int,float **,float **,float **,int *); void means3_sd2(int,int,int,int,int,float **,float **,float **,int *); void means4(int,int,int,float **,float **,float **); void means5(int,int,float **,float **,float **); void menu(void); void n_dads(int,int,int,int,int *,int *,float *); void new_plants(gsl_rng *,float); void seedbank_mortality(gsl_rng *,float); void nrerror(char []); void parms1(int *,int *,int *,int *,int *,float *,float *,float *,int *, int *, int *, int *); void parms2(double *,int *,int *,int *,double *,float *,int *,int *, float *, int *, int *, float *,float *); void persist(int,int,int); void plant_data(int,int,int); void reproduce_gr(int,int,int,int,int,float **,float **,double,double); void reproduce_gs(int,int,int,int,int,float **,float **,double,double); void reproduce_gd(int,int,int,int,int,float **,float **,double,double); void reproduce_nr(int,int,int,int,int,float **,float **,double,double); void reproduce_ns(int,int,int,int,int,float **,float **,double,double); void reproduce_nd(int,int,int,int,int,float **,float **,double,double); void reproduce_scdr(int,int,int,int,int,float **,float **,double,double); void reproduce_scds(int,int,int,int,int,float **,float **,double,double); void reproduce_scdd(int,int,int,int,int,float **,float **,double,double); void reproduce_sdr(int,int,int,int,int,float **,float **,double,double); void reproduce_sds(int,int,int,int,int,float **,float **,double,double); void reproduce_sdd(int,int,int,int,int,float **,float **,double,double); void reproduce_sdr2(int,int,int,int,int,float **,float **,double,double); void reproduce_sds2(int,int,int,int,int,float **,float **,double,double); void reproduce_sdd2(int,int,int,int,int,float **,float **,double,double); void safe_sites(gsl_rng *r, float); void SI_model(int,int,double,int,int,float,float **,float **,float **,int *,int, int,int,float **,float **,float **,float **,float **,float **,float **, float **,float **,float **,int *,float **,float **,float **,float **, float **,float **,float **,float **,int,void (*)(),void (*)(),double,int, int, int, float, float, float, float, int, Vector *, Vector *,Vector *, int, float, float, float, int, float); int **imatrix(long int,long int,long int,long int); int *ivector(long int,long int); int log_ages(gsl_rng *,float,float); int make_pollen(gsl_rng *r,int *,int **,float *,int,int *); int nplants(int *,int *,int *,int); float **fmatrix(long int,long int,long int,long int); float *fvector(long int,long int); //gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); struct plant{ int safe; int age; int sds; int gtype[GENES][ALL]; int stype[SDMAX][GENES+1][ALL]; /*GENES+1 to keep ids of seed parents */ int seedbankid[SBMAX][GENES+1][ALL]; int seedbank_age[SBMAX]; int mom; int dad; int fsd; /* seeds fathered pre-dispersal */ int msd; /* seeds mothered pre-dispersal */ int fsp; /* seeds fathered post-dispersal */ int msp; /* seeds mothered post-dispersal */ }pop[LEN][LEN]; FILE *fpw1,*fpw2,*fpw3,*fpw4; //char fout1[20],fout2[20],fout3[20],fout4[20]; char *fout11 = NULL,*fout22= NULL,*fout33= NULL,*fout44= NULL; int rcnt; float per1,per2; const gsl_rng_type * T; gsl_rng *r; int main(int argc, char *argv[]) { int option = 0; unsigned long int randSeed; r = gsl_rng_alloc(gsl_rng_mt19937); srand(time(NULL)); /* initialization for rand() */ randSeed = rand(); /* returns a non-negative integer */ gsl_rng_set (r, randSeed); /* seed the PRNG */ void (*repro)(),(*mean3)(); int minr=MINR,pdist=PDIST,sdist=SDIST,sloc=SLOC,*nrn,*nrp,plpr=PLPR,lint=LINT; int rr,runs=RUNS,gen=GEN,inum=INUM,nloc=NLOC,sitype=SITYPE; // float est=EST,sites=SITES,**ec1,**ec2,**ec3; float **mnv,**mnr,**myr,**gn1,**gn2,**gn3,**gn4,**gn5,**gn6,**gn7; float **ft1,**ft2,**ft3,**ft4,**ft5,**ft6,**ft7,**ft8,lm=LM,lv=LV; double d=D,b0=B0; int safe_sites_bool = SAFE_SITES_BOOL, demo_rescue_bool = DEMO_RESCUE_BOOL, gen_rescue_pool = GEN_RESCUE_POOL, pop_size_interv = POP_SIZE_INT, interv_threshold = INT_THRESHOLD, fire_flag = FIRE, fire_postive_seeds = FIRE_SERO; float sites_increase = SITES_INCREASE, prob_new_S_allele = PNEW_S_ALLELE, prob_new_allele = PNEW_N_ALLELE, fire_prob = FIRE_PROB, fire_prob_death = FIRE_PROB_DEATH, est_fire = FIRE_EST, seedbank_mort = SEEDBANK_MORT; // declare and initialize a new vector Vector vector_S_alleles; Vector vector_N_alleles; Vector vector_quasi_ext; while((option = getopt(argc, argv,"r:g:o:n:s:f:m:v:l:L:X:xyzk:p:t:a:b:c:d:j:F:A:B:C:D:e:h:i:u:")) != -1) { switch (option) { case 'r' : runs = atoi(optarg); break; case 'g' : gen = atoi(optarg); break; case 'o' : inum = atoi(optarg); break; case 'n' : nloc = atoi(optarg); break; case 's' : sloc = atoi(optarg); break; case 'f' : sites = atof(optarg); break; case 'm' : lm = atof(optarg); break; case 'v' : lv = atof(optarg); break; case 'l' : lint = atoi(optarg); break; case 'L' : b0 = atof(optarg); break; case 'X' : d = atof(optarg); break; case 'x' : safe_sites_bool = 1; break; case 'y' : demo_rescue_bool = 1; break; case 'z' : gen_rescue_pool = 1; break; case 'k' : sites_increase = atof(optarg); break; case 'p' : pop_size_interv = atoi(optarg); break; case 't' : interv_threshold = atoi(optarg); break; case 'a' : prob_new_S_allele = atof(optarg); break; case 'b' : prob_new_allele = atof(optarg); break; case 'c' : plpr = atoi(optarg); break; case 'd' : sitype = atoi(optarg); break; case 'j': fire_flag = atoi(optarg); break; case 'F': fire_prob = atof(optarg); break; case 'A': fire_prob_death = atof(optarg); break; case 'B': fire_postive_seeds = atoi(optarg); break; case 'C': est_fire = atof(optarg); break; case 'D' : seedbank_mort = atof(optarg); break; case 'e' : fout11 = optarg; break; case 'h' : fout22 = optarg; break; case 'i' : fout33 = optarg; break; case 'u' : fout44 = optarg; break; case '?': fprintf (stderr, "Unknown option `-%c'.\n", optopt); //break; //default: print_usage(); exit(EXIT_FAILURE); default: exit(EXIT_FAILURE); } } if(fout11 == NULL){ printf("Initialize demography file name with -e option\n"); exit(2); } if(! (fpw1 = fopen(fout11,"w"))){ perror(fout11); exit(2); } // while(sflg==IN) //IN // { //system("clear");//system("cls"); // char choice; // menu(); // scanf("%c", &choice); //system("clear");//system("cls"); //refresh(); //switch(choice) //{ //case 'i': //parms1(&runs,&gen,&inum,&nloc,&sloc,&sites,&lm,&lv,&lint,&safe_sites_bool,&demo_rescue_bool,&gen_rescue_pool); //break; //case 'w': // parms2(&d,&minr,&pdist,&sdist,&b0,&est,&plpr,&sitype,&sites_increase,&pop_size_interv,&interv_threshold,&prob_new_S_allele,&prob_new_allele); // break; //case 'r': getfile(); rcnt = 0; per1 = per2 = 0.0; mnv = fmatrix(0,gen,0,1); /* avg number of vegetative plants */ mnr = fmatrix(0,gen,0,1); /* avg number of reproductive plants */ myr = fmatrix(0,gen,0,1); /* avg plant age */ ec1 = fmatrix(0,gen,0,1); /* avg number of empty sites/plants */ ec2 = fmatrix(0,gen,0,1); /* avg number of potential mates/plant */ ec3 = fmatrix(0,gen,0,1); /* avg number of compatible mates/plant */ gn1 = fmatrix(0,gen,0,1); /* avg number of alleles/neutral locus */ gn2 = fmatrix(0,gen,0,1); /* avg number of alleles/SI locus */ gn3 = fmatrix(0,gen,0,1); /* avg variance in neutral allele frequencies */ gn4 = fmatrix(0,gen,0,1); /* avg variance in SI allele frequencies */ gn5 = fmatrix(0,gen,0,1); /* average observed heterozygosity */ gn6 = fmatrix(0,gen,0,1); /* average expected heterozygosity */ gn7 = fmatrix(0,gen,0,1); /* avg value of Fis */ ft1 = fmatrix(0,gen,0,1); /* avg number of pollen donors/plant */ ft2 = fmatrix(0,gen,0,1); /* avg variance in pollen donors/plant */ ft3 = fmatrix(0,gen,0,1); /* avg seeds/plant pre-dispersal */ ft4 = fmatrix(0,gen,0,1); /* avg variance: pre-dispersal seeds/father */ ft5 = fmatrix(0,gen,0,1); /* avg variance: pre-dispersal seeds/mother */ ft6 = fmatrix(0,gen,0,1); /* avg seeds/plant post-dispersal */ ft7 = fmatrix(0,gen,0,1); /* avg variance: post-dispersal seeds/father */ ft8 = fmatrix(0,gen,0,1); /* avg variance: post-dispersal seeds/mother */ nrn = ivector(0,gen); nrp = ivector(0,gen); vector_init(&vector_quasi_ext); /* Quasi-extinction probability vector init */ vector_set(&vector_quasi_ext, gen, 0); /* Quasi-extinction probability vector fill with zeroes till maximum generations per run */ header(fpw1,runs,gen,minr,b0,d,pdist,sdist,est,inum,sites,nloc,sloc, plpr,sitype); header(fpw2,runs,gen,minr,b0,d,pdist,sdist,est,inum,sites,nloc,sloc, plpr,sitype); header(fpw3,runs,gen,minr,b0,d,pdist,sdist,est,inum,sites,nloc,sloc, plpr,sitype); header(fpw4,runs,gen,minr,b0,d,pdist,sdist,est,inum,sites,nloc,sloc, plpr,sitype); fprintf(fpw4," GEN XC YC AGE SID SI1 SI2 ID1 N11 N12 ID2 N21 N22"); fprintf(fpw4," ID3 N31 N32 ID4 N41 N42 ID5 N51 N52\n"); init_arrays(gen,mnv,mnr,myr,nrn,gn1,gn2,gn3,gn4,gn5,gn6,gn7,ec1,ec2,ec3, nrp,ft1,ft2,ft3,ft4,ft5,ft6,ft7,ft8); mate_system(plpr,sitype,&repro,&mean3); for(rr=0;rr<runs;rr++) { vector_init(&vector_S_alleles); vector_init(&vector_N_alleles); init_values(); safe_sites(r,sites); init_plants(r,inum,nloc,sloc,lm,lv,&vector_S_alleles,&vector_N_alleles); printf("Current Run: %d\n",rr+1); SI_model(gen,minr,d,pdist,sdist,est,mnv,mnr,myr,nrn,sloc,nloc,lint,gn1, gn2,gn3,gn4,gn5,gn6,gn7,ec1,ec2,ec3,nrp,ft1,ft2,ft3,ft4,ft5, ft6,ft7,ft8,rr,repro,mean3,b0,safe_sites_bool,demo_rescue_bool,gen_rescue_pool,sites_increase,pop_size_interv,prob_new_S_allele,prob_new_allele,interv_threshold,&vector_S_alleles,&vector_N_alleles, &vector_quasi_ext, fire_flag, fire_prob, fire_prob_death, est_fire, fire_postive_seeds, seedbank_mort); /// Add free_vector possibly to free memory of vector_S_alleles vector_free(&vector_S_alleles); vector_free(&vector_N_alleles); } persist(runs,rcnt,gen); grand_mean1(gen,mnv,mnr,myr,nrn,ec1,ec2,ec3,nrp,&vector_quasi_ext); grand_mean2(gen,nrn,gn1,gn2,gn3,gn4,gn5,gn6,gn7); grand_mean3(gen,nrp,ft1,ft2,ft3,ft4,ft5,ft6,ft7,ft8); free_ivector(nrn,0,gen); free_ivector(nrp,0,gen); printf("FLAG VECTOR"); vector_free(&vector_quasi_ext); free_fmatrix(mnv,0,gen,0,1); free_fmatrix(mnr,0,gen,0,1); free_fmatrix(myr,0,gen,0,1); free_fmatrix(ec1,0,gen,0,1); free_fmatrix(ec2,0,gen,0,1); free_fmatrix(ec3,0,gen,0,1); free_fmatrix(gn1,0,gen,0,1); free_fmatrix(gn2,0,gen,0,1); free_fmatrix(gn3,0,gen,0,1); free_fmatrix(gn4,0,gen,0,1); free_fmatrix(gn5,0,gen,0,1); free_fmatrix(gn6,0,gen,0,1); free_fmatrix(gn7,0,gen,0,1); free_fmatrix(ft1,0,gen,0,1); free_fmatrix(ft2,0,gen,0,1); free_fmatrix(ft3,0,gen,0,1); free_fmatrix(ft4,0,gen,0,1); free_fmatrix(ft5,0,gen,0,1); free_fmatrix(ft6,0,gen,0,1); free_fmatrix(ft7,0,gen,0,1); free_fmatrix(ft8,0,gen,0,1); fclose(fpw1); fclose(fpw2); fclose(fpw3); fclose(fpw4); // break; //case 'e': // sflg = OUT; // break; //default: break; //} //} gsl_rng_free (r); return 0; } /* prints main menu to screen */ //void menu(void) // { // printf("MAIN MENU\n\n"); // printf("Enter One Of The Following Choices:\n\n"); // printf("I = initialisation and general simulation parameters\n"); // printf("W = set parameters for within-population dynamics\n"); // printf("R = run the simulation model\n"); // printf("E = exit program (Return to DOS)\n"); // return; // } /* assigns pointer to appropriate functions for reproduction under a given mating system */ void mate_system(int plpr,int sitype,void (**repro)(),void (**mean3)()) { if(sitype==0) { *mean3 = &means3_g; if(plpr==0) *repro = &reproduce_gr; else if(plpr==1) *repro = &reproduce_gs; else if(plpr==2) *repro = &reproduce_gd; } else if(sitype==1) { *mean3 = &means3_scd; if(plpr==0) *repro = &reproduce_scdr; else if(plpr==1) *repro = &reproduce_scds; else if(plpr==2) *repro = &reproduce_scdd; } else if(sitype==2) { *mean3 = &means3_sd; if(plpr==0) *repro = &reproduce_sdr; else if(plpr==1) *repro = &reproduce_sds; else if(plpr==2) *repro = &reproduce_sdd; } else if(sitype==3) { *mean3 = &means3_n; if(plpr==0) *repro = &reproduce_nr; else if(plpr==1) *repro = &reproduce_ns; else if(plpr==2) *repro = &reproduce_nd; } else if(sitype==4) { *mean3 = &means3_sd2; if(plpr==0) *repro = &reproduce_sdr2; else if(plpr==1) *repro = &reproduce_sds2; else if(plpr==2) *repro = &reproduce_sdd2; } return; } /* prompts user for output file names; opens files fpw1, fpw2, fpw3 */ void getfile(void) { printf("Enter output filename for demographic data\n"); //scanf("%s",fout1); fpw1 = fopen(fout11,"w"); printf("Enter output filename for genetic data\n"); //scanf("%s",fout2); fpw2 = fopen(fout22,"w"); printf("Enter output filename for fitness data\n"); //scanf("%s",fout3); fpw3 = fopen(fout33,"w"); printf("Enter output filename for individual data\n"); //scanf("%s",fout4); fpw4 = fopen(fout44,"w"); //system("clear");//system("cls"); return; } /* prints header containing input variable values to output files */ void header(FILE *fpw,int runs,int gen,int minr,double b0,double d,int pdist, int sdist,float est,int inum,float sites,int nloc,int sloc,int plpr,int sitype) { if(sitype==0) fprintf(fpw,"Mating System: Gametophytic Self Incompatibility, "); else if(sitype==1) fprintf(fpw,"Mating System: Codominant Sporophytic Self Incompatibility, "); else if(sitype==2) fprintf(fpw,"Mating System: Maternal Dominant Sporophytic Self Incompatibility, "); else if(sitype==3) fprintf(fpw,"Mating System: Neutral, "); else if(sitype==4) fprintf(fpw,"Mating System: Paternal Dominant Sporophytic Self Incompatibility, "); if(plpr==0) fprintf(fpw,"with Random Pollination\n\n"); else if(plpr==1) fprintf(fpw,"with Size-Dependent Pollination\n\n"); else if(plpr==2) fprintf(fpw,"with Distance-Dependent Pollination\n\n"); fprintf(fpw,"Runs=%d, Generations=%d, Initial PopSize=%d, Safe Sites=%.3f, First " "Reproduction=%d\n",runs,gen,inum,sites,minr); fprintf(fpw,"Maximum Per-Capita Ovule Production=%.3lf, Seed Establishment=%.3f, " "Deathrate=%.3lf\n",b0,est,d); fprintf(fpw,"Pollen Dispersal Range=%d, Seed Dispersal Range=%d, SI Alleles=%d, " "Neutral Alleles=%d\n\n",pdist,sdist,sloc,nloc); return; } /* sets elements of output data arrays to zero */ void init_arrays(int gen,float **mnv,float **mnr,float **myr,int *nrn,float **gn1, float **gn2,float **gn3,float **gn4,float **gn5,float **gn6,float **gn7, float **ec1,float **ec2,float **ec3,int *nrp,float **ft1,float **ft2, float **ft3,float **ft4,float **ft5,float **ft6,float **ft7,float **ft8) { int i,j; for(i=0;i<=gen;i++) { nrn[i] = 0; nrp[i] = 0; for(j=0;j<ALL;j++) { mnv[i][j] = 0.0; mnr[i][j] = 0.0; myr[i][j] = 0.0; ec1[i][j] = 0.0; ec2[i][j] = 0.0; ec3[i][j] = 0.0; gn1[i][j] = 0.0; gn2[i][j] = 0.0; gn3[i][j] = 0.0; gn4[i][j] = 0.0; gn5[i][j] = 0.0; gn6[i][j] = 0.0; gn7[i][j] = 0.0; ft1[i][j] = 0.0; ft2[i][j] = 0.0; ft3[i][j] = 0.0; ft4[i][j] = 0.0; ft5[i][j] = 0.0; ft6[i][j] = 0.0; ft7[i][j] = 0.0; ft8[i][j] = 0.0; } } return; } /* initializes elements of the population arrays for use in simod() */ void init_values(void) { int xc,yc,i,j,k; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { pop[xc][yc].safe = 0; pop[xc][yc].age = 0; pop[xc][yc].sds = 0; pop[xc][yc].mom = 0; pop[xc][yc].dad = 0; pop[xc][yc].fsd = 0; pop[xc][yc].msd = 0; pop[xc][yc].fsp = 0; pop[xc][yc].msp = 0; for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++) pop[xc][yc].gtype[i][j] = 0; } for(i=0;i<SDMAX;i++) { for(j=0;j<=GENES;j++) { for(k=0;k<ALL;k++) pop[xc][yc].stype[i][j][k] = 0; } } // seedbank for(i=0;i<SBMAX;i++) { for(j=0;j<=GENES;j++) { for(k=0;k<ALL;k++) pop[xc][yc].seedbankid[i][j][k] = 0; } pop[xc][yc].seedbank_age[i]= 0; } } } return; } /* randomly determines a fraction of 'safe' sites (i.e. suitable for occupancy) */ void safe_sites(gsl_rng *r, float sites) { int xc,yc,cnt=0; sites = sites*LEN*LEN; if(sites==(LEN*LEN)) { for(xc=0;xc<LEN;xc++) for(yc=0;yc<LEN;yc++) pop[xc][yc].safe = 1; } else if(sites<(LEN*LEN)) { while(cnt<=sites) { xc = gsl_rng_uniform_int(r,LEN-1); //g05dyc(0,LEN-1); yc = gsl_rng_uniform_int(r,LEN-1); //g05dyc(0,LEN-1); if(pop[xc][yc].safe==0) { pop[xc][yc].safe = 1; cnt += 1; } } } //gsl_rng_free (r); return; } /* Check if there is a new S allele (and neutral allele)*/ int check_new_Sallele(int S_allele, Vector *vector){ int var, max = vector->size; for(int index=0;index < max; index++){ if(S_allele == vector_get(vector, index)){ var = 0; break; }else var = 1; } return var; } /* calculates genotypes and randomly assigns initial positions for plants; assumes that individuals can be heterozygous at each neutral locus */ // CREATE VECTOR OF S ALLELES TO UPDATE THE LIST OF S ALLELES CREATED BY NEW MUTATIONS AT THE S LOCUS DURING THE GENETIC RESCUE void init_plants(gsl_rng *r, int inum,int nloc,int sloc,float lm,float lv, Vector *vector_S_alleles, Vector *vector_N_alleles) { int is_new_S_allele,i,j,xc,yc,al,cnt=0; while(cnt<inum) { xc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); yc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); if(pop[xc][yc].age==0 && pop[xc][yc].safe==1) { for(i=0;i<GENES;i++) { if(i==0) /* SI locus - must be heterozygous */ { al = gsl_rng_uniform_int(r,sloc);//g05dyc(1,sloc); pop[xc][yc].gtype[i][0] = al; if(cnt == 0){ vector_append(vector_S_alleles,al); }else{ is_new_S_allele = check_new_Sallele(al, vector_S_alleles); if(is_new_S_allele != 0) //->> Change made vector_append(vector_S_alleles,al); } al = gsl_rng_uniform_int(r,sloc); while(al==pop[xc][yc].gtype[i][0]){ al = gsl_rng_uniform_int(r,sloc);//g05dyc(1,sloc); } pop[xc][yc].gtype[i][1] = al; is_new_S_allele = check_new_Sallele(al, vector_S_alleles); if(is_new_S_allele != 0) //->> Change made vector_append(vector_S_alleles,al); } else if(i>0) /* Neutral loci */ { for(j=0;j<ALL;j++) { al = gsl_rng_uniform_int(r,nloc);//g05dyc(1,nloc); pop[xc][yc].gtype[i][j] = al; is_new_S_allele = check_new_Sallele(al, vector_N_alleles); if(is_new_S_allele != 0) //->> Change made vector_append(vector_N_alleles,al); } } } pop[xc][yc].age = log_ages(r,lm,lv); cnt += 1; } } //gsl_rng_free (r); return; } /* Demographic rescue --- Put N individuals in the lattice doing random mating to produce incalculates genotypes and randomly assigns initial positions for plants; assumes that individuals can be heterozygous at each neutral locus */ void demographic_rescue(gsl_rng *r, int inum, int minr) { int i,xc,xc_dad,yc,yc_dad,xc_mom,yc_mom,al,al2,cnt=0,count; int coords_mom[2] = {}, coords_dad[2] = {}; while(cnt<inum) { xc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); yc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); if(pop[xc][yc].age==0 && pop[xc][yc].safe==1) { //printf(" Coord x: %d\n",xc); //printf(" Coord y: %d\n",yc); // Find "parents": // Dad count = 0; while(count<1){ xc_dad = gsl_rng_uniform_int(r,LEN-1); yc_dad = gsl_rng_uniform_int(r,LEN-1); if(pop[xc_dad][yc_dad].age>=minr){ coords_dad[0] = xc_dad; coords_dad[1] = yc_dad; count=1; } } // Mom count = 0; while(count<1){ xc_mom = gsl_rng_uniform_int(r,LEN-1); yc_mom = gsl_rng_uniform_int(r,LEN-1); if(pop[xc_mom][yc_mom].age>=minr){ coords_mom[0] = xc_mom; coords_mom[1] = yc_mom; count=1; } } // Assigning the genes to introduced reproductive individual from chosen individual(s) (parents) for(i=0;i<GENES;i++) { if(i==0) /* SI locus - must be heterozygous */ { al = pop[coords_dad[0]][coords_dad[1]].gtype[i][0]; // Assign S allele 1 pop[xc][yc].gtype[i][0] = al; if(al != pop[coords_mom[0]][coords_mom[1]].gtype[i][1]){ al2 = pop[coords_mom[0]][coords_mom[1]].gtype[i][1]; }else{ al2 = pop[coords_mom[0]][coords_mom[1]].gtype[i][0]; } if(al2 == al) al2 = pop[coords_dad[0]][coords_dad[1]].gtype[i][1]; pop[xc][yc].gtype[i][1] = al2; // Assign S allele 2 printf(" S allele 1: %d\n",pop[xc][yc].gtype[i][0]); printf(" S allele 2: %d\n",pop[xc][yc].gtype[i][1]); //if(pop[xc][yc].gtype[i][0] > 100 || pop[xc][yc].gtype[i][1] > 100){ //printf(" S allele 1: %d\n",pop[xc][yc].gtype[i][0]); //printf(" S allele 2: %d\n",pop[xc][yc].gtype[i][1]); //printf(" S allele 1 dad: %d\n",pop[coords_dad[0]][coords_dad[1]].gtype[i][0]); //printf(" S allele 2 dad: %d\n",pop[coords_dad[0]][coords_dad[1]].gtype[i][1]); //printf(" S allele 1 mom: %d\n",pop[coords_mom[0]][coords_mom[1]].gtype[i][0]); //printf(" S allele 2 mom: %d\n",pop[coords_mom[0]][coords_mom[1]].gtype[i][1]); //} } else if(i>0) /* Neutral loci */ { //Assign neutral allele, nloc: number of neutral alleles pop[xc][yc].gtype[i][0] = pop[coords_dad[0]][coords_dad[1]].gtype[i][0]; pop[xc][yc].gtype[i][1] = pop[coords_mom[0]][coords_mom[1]].gtype[i][1]; } } coords_dad[0] = 0; coords_dad[1] = 0; coords_mom[0] = 0; coords_mom[1] = 0; pop[xc][yc].age = 1;//log_ages(r,lm,lv); cnt += 1; } } return; } /* Genetic rescue --- Put N individuals with 20% different genetic diversity in the lattice doing random mating to produce incalculates genotypes and randomly assigns initial positions for plants; assumes that individuals can be heterozygous at each neutral locus */ void genetic_rescue(gsl_rng *r, int inum, int minr, int sloc, int nloc, float prob_new_S_allele, float prob_new_allele, Vector *Stype, Vector *vector_N_alleles) { int i,xc,xc_dad,yc,yc_dad,xc_mom,yc_mom,al,al2,cnt=0,count,update_sloc=sloc,check; int coords_mom[2] = {}, coords_dad[2] = {}; while(cnt<inum) { xc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); yc = gsl_rng_uniform_int(r,LEN-1);//g05dyc(0,LEN-1); if(pop[xc][yc].age==0 && pop[xc][yc].safe==1) { //printf(" Coord x: %d\n",xc); //printf(" Coord y: %d\n",yc); // Find "parents": // Dad count = 0; while(count<1){ xc_dad = gsl_rng_uniform_int(r,LEN-1); yc_dad = gsl_rng_uniform_int(r,LEN-1); if(pop[xc_dad][yc_dad].age>=minr){ coords_dad[0] = xc_dad; coords_dad[1] = yc_dad; count=1; } } // Mom count = 0; while(count<1){ xc_mom = gsl_rng_uniform_int(r,LEN-1); yc_mom = gsl_rng_uniform_int(r,LEN-1); if(pop[xc_mom][yc_mom].age>=minr){ coords_mom[0] = xc_mom; coords_mom[1] = yc_mom; count=1; } } // Assigning the genes to introduced reproductive individual from chosen individual(s) (parents) for(i=0;i<GENES;i++) { if(i==0) /* SI locus - must be heterozygous */ { if(prob_new_S_allele > gsl_rng_uniform(r)){ al = gsl_rng_uniform_int(r,sloc) + 10; // Assign S allele 1 update_sloc ++; }else{ al = pop[coords_dad[0]][coords_dad[1]].gtype[i][0]; } pop[xc][yc].gtype[i][0] = al; if(prob_new_S_allele > gsl_rng_uniform(r)){ al2 = gsl_rng_uniform_int(r,sloc) + 10; // Assign S allele 2 }else{ al2 = pop[coords_mom[0]][coords_mom[1]].gtype[i][1]; } if(al == al2){ al2 = pop[coords_mom[0]][coords_mom[1]].gtype[i][0]; }else{ update_sloc ++; } if(al == al2){ if(prob_new_S_allele > gsl_rng_uniform(r)){ al2 = gsl_rng_uniform_int(r,sloc) + 10; //////// --------------------> rethink this, may be gsl_rng_uniform_int(r,HUGE_NUMBER) or different distribution }else{ al2 = pop[coords_dad[0]][coords_dad[1]].gtype[i][1]; } } pop[xc][yc].gtype[i][1] = al2; // Assign S allele 2 //printf(" S allele 1: %d\n",pop[xc][yc].gtype[i][0]); //printf(" S allele 2: %d\n",pop[xc][yc].gtype[i][1]); check = check_new_Sallele(pop[xc][yc].gtype[i][0], Stype); if(check != 0) vector_append(Stype,pop[xc][yc].gtype[i][0]); check = check_new_Sallele(pop[xc][yc].gtype[i][1], Stype); if(check != 0) vector_append(Stype,pop[xc][yc].gtype[i][1]); //if(pop[xc][yc].gtype[i][0] > 100 || pop[xc][yc].gtype[i][1] > 100){ //printf(" S allele 1: %d\n",pop[xc][yc].gtype[i][0]); //printf(" S allele 2: %d\n",pop[xc][yc].gtype[i][1]); //printf(" S allele 1 dad: %d\n",pop[coords_dad[0]][coords_dad[1]].gtype[i][0]); //printf(" S allele 2 dad: %d\n",pop[coords_dad[0]][coords_dad[1]].gtype[i][1]); //printf(" S allele 1 mom: %d\n",pop[coords_mom[0]][coords_mom[1]].gtype[i][0]); //printf(" S allele 2 mom: %d\n",pop[coords_mom[0]][coords_mom[1]].gtype[i][1]); //} } else if(i>0) /* Neutral loci */ { //Assign neutral allele, nloc: number of neutral alleles if(prob_new_allele > gsl_rng_uniform(r)){ pop[xc][yc].gtype[i][0] = gsl_rng_uniform_int(r,nloc) + 5; }else{ pop[xc][yc].gtype[i][0] = pop[coords_dad[0]][coords_dad[1]].gtype[i][0]; } if(prob_new_allele > gsl_rng_uniform(r)){ pop[xc][yc].gtype[i][1] = gsl_rng_uniform_int(r,nloc) + 5; }else{ pop[xc][yc].gtype[i][1] = pop[coords_mom[0]][coords_mom[1]].gtype[i][1]; } check = check_new_Sallele(pop[xc][yc].gtype[i][0], Stype); // Check if there are new neutral alleles, if yes add to the vector of neutral alleles if(check != 0) vector_append(vector_N_alleles,pop[xc][yc].gtype[i][0]); check = check_new_Sallele(pop[xc][yc].gtype[i][1], vector_N_alleles); if(check != 0) vector_append(vector_N_alleles,pop[xc][yc].gtype[i][1]); } } coords_dad[0] = 0; coords_dad[1] = 0; coords_mom[0] = 0; coords_mom[1] = 0; pop[xc][yc].age = 1;//log_ages(r,lm,lv); cnt += 1; } } return; } /* assigns ages from a lognormal distribution, with mean (lm) and variance (lv) */ int log_ages(gsl_rng *r,float lm, float lv) { int flg=OUT; float nm,nv,sd,tmp; nm = log(lm) - 0.5*log(lv/(lm*lm) + 1.0); nv = log(lv/(lm*lm) + 1.0); sd = sqrt(nv); while(flg==OUT) { tmp= exp((gsl_ran_gaussian(r,sd) + nm));//exp(g05ddc(nm,sd)); ((tmp-floor(tmp))<0.5)?(tmp=floor(tmp)):(tmp=ceil(tmp)); if(tmp>=1) flg = IN; } //gsl_rng_free (r); return (int)tmp; } /* self-incompatibility population dynamical model */ void SI_model(int gen,int minr,double d,int pdist,int sdist,float est,float **mnv, float **mnr,float **myr,int *nrn,int sloc,int nloc,int lint,float **gn1, float **gn2,float **gn3,float **gn4,float **gn5,float **gn6,float **gn7, float **ec1,float **ec2,float **ec3,int *nrp,float **ft1,float **ft2, float **ft3,float **ft4,float **ft5,float **ft6,float **ft7,float **ft8,int rr, void (*repro)(),void (*mean3)(),double b0, int safe_sites_bool, int demo_rescue_bool, int gen_rescue_pool, float sites_increase, float pop_size_interv, float prob_new_S_allele, float prob_new_allele, int interv_threshold, Vector *Stype, Vector *vector_N_alleles, Vector *vector_quasi_ext, int fire_flag, float fire_prob, float fire_prob_death, float est_fire, int fire_postive_seeds, float seedbank_mort) { int g,i,plants,rep,veg,age,cnt=0, number_interv=0, rcnt_fake, update_quasi_prob = 0; //int pop_size_interv = 100, new_sloc = sloc + 10, new_nloc = nloc + 5; //float sites_increase = 0.2; //float prob_new_S_allele = 0.5, prob_new_allele = 0.5; double lambda = 0.2; for(g=0;g<=gen;g++) { //printf(" FLAG 4 \n"); if((plants=nplants(&veg,&rep,&age,minr))>1) { means1(g,mnv,mnr,myr,veg,rep,age); //printf(" FLAG 5 \n"); means2(g,plants,gn1,gn2,gn3,gn4,gn5,gn6,gn7,Stype,vector_N_alleles);//means2(g,plants,new_sloc,new_nloc,gn1,gn2,gn3,gn4,gn5,gn6,gn7); //printf(" FLAG 6 \n"); (*mean3)(g,rep,minr,pdist,sdist,ec1,ec2,ec3,nrp); //printf(" FLAG 7 \n"); (*repro)(g,rep,minr,pdist,sdist,ft1,ft2,b0,d); //printf(" FLAG 8 \n"); means4(g,rep,minr,ft3,ft4,ft5); if(cnt==0 && rr==0) plant_data(g,sloc,nloc); (cnt==lint-1)?(cnt=0):(cnt+=1); printf(" Population size: %d\n",plants); printf(" --------------------------------------------------------------------Generation: %d\n",g); if(plants < interv_threshold && number_interv == 0){ if(safe_sites_bool == 1) safe_sites(r, sites_increase); if(demo_rescue_bool == 1) demographic_rescue(r, pop_size_interv, minr); if(gen_rescue_pool == 1) genetic_rescue(r, pop_size_interv, minr, sloc, nloc, prob_new_S_allele, prob_new_allele, Stype, vector_N_alleles); plants=nplants(&veg,&rep,&age,minr); //printf(" Population size after rescue: %d\n",plants); printf(" Genetic rescue: %d\n",gen_rescue_pool); number_interv=1; } // Filling vector to calculate quasi-extinction probability risk curve if(plants < interv_threshold){ update_quasi_prob = vector_get(vector_quasi_ext,g) + 1; vector_set(vector_quasi_ext,g, update_quasi_prob); } //printf(" Genetic rescue: %d\n",gen_rescue_pool); //printf(" Demographic rescue: %d\n",demo_rescue_bool); //printf(" Spatial rescue: %d\n",safe_sites_bool); /// FIRE if(fire_flag == 1){ /// Flags if there will be fire events in the simulations or not at all if(fire_prob > gsl_rng_uniform(r)){ /// prob_fire_freq: frequency of fire events along one simulation kill_plants_agedep(r,lambda,fire_prob_death + d); /// fire_death_prob: increased (compared to "d") probability of death by a fire event //kill_plants(r,fire_prob_death); printf(" -----> FIRE!\n"); if(fire_postive_seeds == 1){ seedbank_mortality(r,seedbank_mort); new_plants(r,est+est_fire); /// Add positive effect of fire in seed germination probability when species is serotinous }else{ seedbank_mortality(r,seedbank_mort); new_plants(r,est); /// No serotinous } }else{ kill_plants_agedep(r,lambda,d); //kill_plants(r,d); } }else{ /// NO FIRE kill_plants_agedep(r,lambda,d); //kill_plants(r,d); //printf(" FLAG SB \n"); seedbank_mortality(r,seedbank_mort); new_plants(r,est); } //printf(" FLAG 2 \n"); means5(g,rep,ft6,ft7,ft8); //printf(" FLAG 3 \n"); } else break; } for(i=0;i<g;i++) nrn[i] += 1; rcnt_fake = rcnt; /* number of runs with plants present */ (g<gen+1)?(rcnt=rcnt_fake):(rcnt+=1); per1 += (g-1); per2 += (g-1)*(g-1); return; } /* calculates number of vegetatives, number of reproductives and total ages; returns the total population size */ int nplants(int *veg,int *rep,int *age,int minr) { int xc,yc; *veg = 0; *rep = 0; *age = 0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>0) { *age += pop[xc][yc].age; if(pop[xc][yc].age<minr) *veg += 1; else if(pop[xc][yc].age>=minr) *rep += 1; } } } return (*veg + *rep); } /* sums and squared sums of demographic variables for average dynamics */ void means1(int g,float **mnv,float **mnr,float **myr,int veg,int rep,int age) { mnv[g][0] += (float)veg; mnv[g][1] += (float)veg*veg; mnr[g][0] += (float)rep; mnr[g][1] += (float)rep*rep; myr[g][0] += (float)age/(veg+rep); myr[g][1] += (float)(age/(veg+rep))*(age/(veg+rep)); return; } /* calculates number of alleles and number of heterozygous individuals at each locus across the entire population; calls function gene_data() */ void means2(int g,int plants,float **gn1,float **gn2,float **gn3, float **gn4,float **gn5,float **gn6,float **gn7,Vector *Stype, Vector *vector_N_alleles) { int xc,yc,i,j; float *si_gene,*heteros,**n_genes; int sloc = Stype->size; int nloc = vector_N_alleles->size; n_genes = fmatrix(1,GENES-1,1,nloc); //printf(" Sloc size of S locus (alleles) %d \n", sloc); si_gene = fvector(1,sloc); heteros = fvector(1,GENES-1); for(i=1;i<GENES;i++) { heteros[i] = 0.0; for(j=1;j<=nloc;j++) n_genes[i][j] = 0.0; } for(i=1;i<=sloc;i++) si_gene[i] = 0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>0) { for(i=1;i<GENES;i++) { if(pop[xc][yc].gtype[i][0]!=pop[xc][yc].gtype[i][1]) heteros[i] += 1.0; n_genes[i][pop[xc][yc].gtype[i][0]] += 1.0; n_genes[i][pop[xc][yc].gtype[i][1]] += 1.0; } //printf("%d %d\n",pop[xc][yc].gtype[0][0],pop[xc][yc].gtype[0][1]); si_gene[pop[xc][yc].gtype[0][0]] += 1.0; si_gene[pop[xc][yc].gtype[0][1]] += 1.0; } } } gene_data(g,plants,nloc,sloc,gn1,gn2,gn3,gn4,gn5,gn6,gn7,n_genes,si_gene,heteros); //printf(" Flag means2 \n"); free_fmatrix(n_genes,1,GENES-1,1,nloc); //printf(" Flag means3 \n"); free_fvector(si_gene,1,sloc); //printf(" Flag means4 \n"); free_fvector(heteros,1,GENES-1); //printf(" Flag means5 \n"); return; } /* sums and squared sums of additional demographic variables for average dynamics assuming gametophytic self-incompatibility */ void means3_g(int g,int rep,int minr,int pdist,int sdist,float **ec1,float **ec2, float **ec3,int *nrp) { int i,j,k,l,xc,yc,dads=0,open=0,tmp; float mate=0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { tmp = 0; dads += 1; for(k=0;k<ALL;k++) for(l=0;l<ALL;l++) if(pop[xc][yc].gtype[0][k]!=pop[i][j].gtype[0][l]) tmp += 1; if(tmp==4) mate += 1.0; else if(tmp==3) mate += 0.5; } } } } for(i=xc-sdist;i<=xc+sdist;i++) { for(j=yc-sdist;j<=yc+sdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age==0) open += 1; } } } } } } if(rep>0) { nrp[g] += 1; /* number of runs with reproductives present */ ec1[g][0] += open/rep; /* empty sites w/in seed dispersal range */ ec1[g][1] += (open/rep)*(open/rep); ec2[g][0] += dads/rep; /* reproductive plants w/in pollen dispersal range */ ec2[g][1] += (dads/rep)*(dads/rep); ec3[g][0] += mate/rep; /* compatible males w/in pollen dispersal range */ ec3[g][1] += (mate/rep)*(mate/rep); } return; } /* sums and squared sums of additional demographic variables for average dynamics assuming neutral self-incompatibility */ void means3_n(int g,int rep,int minr,int pdist,int sdist,float **ec1,float **ec2, float **ec3,int *nrp) { int i,j,xc,yc,dads=0,open=0; float mate=0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) dads += 1; } } } for(i=xc-sdist;i<=xc+sdist;i++) { for(j=yc-sdist;j<=yc+sdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age==0) open += 1; } } } } } } mate = (float)dads; if(rep>0) { nrp[g] += 1; /* number of runs with reproductives present */ ec1[g][0] += open/rep; /* empty sites w/in seed dispersal range */ ec1[g][1] += (open/rep)*(open/rep); ec2[g][0] += dads/rep; /* reproductive plants w/in pollen dispersal range */ ec2[g][1] += (dads/rep)*(dads/rep); ec3[g][0] += mate/rep; /* compatible males w/in pollen dispersal range */ ec3[g][1] += (mate/rep)*(mate/rep); } return; } /* sums and squared sums of additional demographic variables for average dynamics assuming codominant sporophytic self-incompatibility */ void means3_scd(int g,int rep,int minr,int pdist,int sdist,float **ec1,float **ec2, float **ec3,int *nrp) { int i,j,k,l,xc,yc,dads=0,open=0,flg; float mate=0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { dads += 1; flg = IN; for(k=0;k<ALL;k++) for(l=0;l<ALL;l++) if(pop[xc][yc].gtype[0][k]==pop[i][j].gtype[0][l]) flg = OUT; if(flg==IN) mate += 1.0; } } } } for(i=xc-sdist;i<=xc+sdist;i++) { for(j=yc-sdist;j<=yc+sdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age==0) open += 1; } } } } } } if(rep>0) { nrp[g] += 1; /* number of runs with reproductives present */ ec1[g][0] += open/rep; /* empty sites w/in seed dispersal range */ ec1[g][1] += (open/rep)*(open/rep); ec2[g][0] += dads/rep; /* reproductive plants w/in pollen dispersal range */ ec2[g][1] += (dads/rep)*(dads/rep); ec3[g][0] += mate/rep; /* compatible males w/in pollen dispersal range */ ec3[g][1] += (mate/rep)*(mate/rep); } return; } /* sums and squared sums of additional demographic variables for average dynamics assuming maternal dominant sporophytic self-incompatibility */ void means3_sd(int g,int rep,int minr,int pdist,int sdist,float **ec1,float **ec2, float **ec3,int *nrp) { int i,j,k,xc,yc,dads=0,open=0,flg,al; float mate=0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { dads += 1; flg = IN; if((al=pop[xc][yc].gtype[0][0])<pop[xc][yc].gtype[0][1]) al = pop[xc][yc].gtype[0][1]; for(k=0;k<ALL;k++) if(pop[i][j].gtype[0][k]==al) flg = OUT; if(flg==IN) mate += 1.0; } } } } for(i=xc-sdist;i<=xc+sdist;i++) { for(j=yc-sdist;j<=yc+sdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age==0) open += 1; } } } } } } if(rep>0) { nrp[g] += 1; /* number of runs with reproductives present */ ec1[g][0] += open/rep; /* empty sites w/in seed dispersal range */ ec1[g][1] += (open/rep)*(open/rep); ec2[g][0] += dads/rep; /* reproductive plants w/in pollen dispersal range */ ec2[g][1] += (dads/rep)*(dads/rep); ec3[g][0] += mate/rep; /* compatible males w/in pollen dispersal range */ ec3[g][1] += (mate/rep)*(mate/rep); } return; } /* sums and squared sums of additional demographic variables for average dynamics assuming paternal dominant sporophytic self-incompatibility */ void means3_sd2(int g,int rep,int minr,int pdist,int sdist,float **ec1,float **ec2, float **ec3,int *nrp) { int i,j,k,xc,yc,dads=0,open=0,flg,al; float mate=0.0; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { dads += 1; flg = IN; if((al=pop[i][j].gtype[0][0])<pop[i][j].gtype[0][1]) al = pop[i][j].gtype[0][1]; for(k=0;k<ALL;k++) if(pop[xc][yc].gtype[0][k]==al) flg = OUT; if(flg==IN) mate += 1.0; } } } } for(i=xc-sdist;i<=xc+sdist;i++) { for(j=yc-sdist;j<=yc+sdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age==0) open += 1; } } } } } } if(rep>0) { nrp[g] += 1; /* number of runs with reproductives present */ ec1[g][0] += open/rep; /* empty sites w/in seed dispersal range */ ec1[g][1] += (open/rep)*(open/rep); ec2[g][0] += dads/rep; /* reproductive plants w/in pollen dispersal range */ ec2[g][1] += (dads/rep)*(dads/rep); ec3[g][0] += mate/rep; /* compatible males w/in pollen dispersal range */ ec3[g][1] += (mate/rep)*(mate/rep); } return; } /* sums and squared sums of fitness variables (pre-dispersal) for average dynamics */ void means4(int g,int rep,int minr,float **ft3,float **ft4,float **ft5) { int xc,yc; float fsm1=0.0,fsm2=0.0,msm1=0.0,msm2=0.0,vfs,vms; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { fsm1 += pop[xc][yc].fsd; fsm2 += (pop[xc][yc].fsd)*(pop[xc][yc].fsd); msm1 += pop[xc][yc].msd; msm2 += (pop[xc][yc].msd)*(pop[xc][yc].msd); } pop[xc][yc].fsd = 0; pop[xc][yc].msd = 0; } } if(rep>0) { ft3[g][0] += fsm1/rep; /* mean seeds/parent before dispersal */ ft3[g][1] += (fsm1/rep)*(fsm1/rep); (rep==1)?(vfs=0.0):(vfs=(fsm2-(fsm1*fsm1)/rep)/(rep-1)); ft4[g][0] += vfs; /* variance in seeds/father before dispersal */ ft4[g][1] += vfs*vfs; (rep==1)?(vms=0.0):(vms=(msm2-(msm1*msm1)/rep)/(rep-1)); ft5[g][0] += vms; /* variance in seeds/mother before dispersal */ ft5[g][1] += vms*vms; } return; } /* sums and squared sums of fitness variables (post-dispersal) for average dynamics */ void means5(int g,int rep,float **ft6,float **ft7,float **ft8) { int xc,yc,xn,yn; float fsp1=0.0,fsp2=0.0,msp1=0.0,msp2=0.0,vfs,vms; double ival,fval,len=LEN; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age==1) { fval = modf(pop[xc][yc].dad/len,&ival); xn = ival; yn = fval*LEN; pop[xn][yn].fsp += 1; fval = modf(pop[xc][yc].mom/len,&ival); xn = ival; yn = fval*LEN; pop[xn][yn].msp += 1; } } } for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { fsp1 += pop[xc][yc].fsp; fsp2 += (pop[xc][yc].fsp)*(pop[xc][yc].fsp); msp1 += pop[xc][yc].msp; msp2 += (pop[xc][yc].msp)*(pop[xc][yc].msp); pop[xc][yc].fsp = 0; pop[xc][yc].msp = 0; } } if(rep>0) { ft6[g][0] += fsp1/rep; /* mean seeds/parent after dispersal */ ft6[g][1] += (fsp1/rep)*(fsp1/rep); (rep==1)?(vfs=0.0):(vfs=(fsp2-(fsp1*fsp1)/rep)/(rep-1)); ft7[g][0] += vfs; /* variance in seeds/father after dispersal */ ft7[g][1] += vfs*vfs; (rep==1)?(vms=0.0):(vms=(msp2-(msp1*msp1)/rep)/(rep-1)); ft8[g][0] += vms; /* variance in seeds/mother after dispersal */ ft8[g][1] += vms*vms; } return; } /* sums and squared sums of genetic variables for average dynamics */ void gene_data(int g,int plants,int nloc,int sloc,float **gn1,float **gn2, float **gn3,float **gn4,float **gn5,float **gn6,float **gn7,float **n_genes, float *si_gene,float *heteros) { int i,j; float NallL,TNall=0.0,SIall=0.0,Nvar=0.0,SIvar=0.0,Nmfrq,SIfrq=0.0,Ho=0.0; float He=0.0; for(i=1;i<GENES;i++) { NallL = 0.0; Nmfrq = 0.0; Ho += heteros[i]/plants; for(j=1;j<=nloc;j++) { if(n_genes[i][j]>0.0) { NallL += 1.0; Nmfrq += (n_genes[i][j]/(2.0*plants))*(n_genes[i][j]/(2.0*plants)); } } He += 1.0 - Nmfrq; if(NallL>1.0) Nvar += (Nmfrq-1.0/NallL)/(NallL-1.0); TNall += NallL; } for(i=1;i<=sloc;i++) { if(si_gene[i]>0.0) { SIall += 1.0; SIfrq += (si_gene[i]/(2.0*plants))*(si_gene[i]/(2.0*plants)); } } if(SIall>1.0) SIvar = (SIfrq-1.0/SIall)/(SIall-1.0); gn1[g][0] += TNall/(GENES-1); /* mean number of alleles per neutral locus */ gn1[g][1] += (TNall/(GENES-1))*(TNall/(GENES-1)); gn2[g][0] += SIall; /* mean number of alleles per SI locus */ gn2[g][1] += SIall*SIall; gn3[g][0] += Nvar/(GENES-1); /* variance in neutral allele frequencies */ gn3[g][1] += (Nvar/(GENES-1))*(Nvar/(GENES-1)); gn4[g][0] += SIvar; /* variance in SI allele frequencies */ gn4[g][1] += SIvar*SIvar; gn5[g][0] += Ho/(GENES-1); /* observed heterozygosity (neutral loci) */ gn5[g][1] += (Ho/(GENES-1))*(Ho/(GENES-1)); gn6[g][0] += He/(GENES-1); /* expected heterozygosity (neutral loci) */ gn6[g][1] += (He/(GENES-1))*(He/(GENES-1)); if(He>0.0) { gn7[g][0] += 1-(Ho/He); /* Fis (neutral loci) */ gn7[g][1] += (1-(Ho/He))*(1-(Ho/He)); } return; } /* assumes gametophytic self-incompatibility and random pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_gr(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_r(xc,yc,pdist,xyval,probs,minr,dads); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) if(ptype[0]==pop[xc][yc].gtype[0][j]) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes neutral self-incompatibility and random pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_nr(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_r(xc,yc,pdist,xyval,probs,minr,dads); for(i=0;i<ovn;i++) { pd = make_pollen(r,ptype,xyval,probs,dads,&did); donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes co-dominant sporophytic self-incompatibility and random pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_scdr(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,k,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_r(xc,yc,pdist,xyval,probs,minr,dads); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) { for(k=0;k<ALL;k++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==\ pop[xc][yc].gtype[0][k]) flg=OUT; } if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes maternally dominant sporophytic self-incompatibility and random pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sdr(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_r(xc,yc,pdist,xyval,probs,minr,dads); //printf("FLAG 1\n"); for(i=0;i<ovn;i++) { flg = IN; //printf("FLAG POLLEN\n"); pd = make_pollen(r,ptype,xyval,probs,dads,&did); //printf("FLAG 2\n"); if((md=pop[xc][yc].gtype[0][0])<pop[xc][yc].gtype[0][1]) md = pop[xc][yc].gtype[0][1]; //printf("MD: %d\n", md); for(j=0;j<ALL;j++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; //printf("FLAG 3\n"); make_ovule(r,xc,yc,otype,&mid); //printf("FLAG 4\n"); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); //printf("FLAG 5\n"); } } //printf("DADS %d\n", dads); for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; //printf("FLAG 6\n"); tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes paternally dominant sporophytic self-incompatibility and random pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sdr2(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_r(xc,yc,pdist,xyval,probs,minr,dads); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][0]; if(md<pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]) md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]; for(j=0;j<ALL;j++) if(pop[xc][yc].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes gametophytic self-incompatibility and size-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_gs(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_s(xc,yc,pdist,xyval,probs,minr,tage); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) if(ptype[0]==pop[xc][yc].gtype[0][j]) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes neutral self-incompatibility and size-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_ns(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_s(xc,yc,pdist,xyval,probs,minr,tage); for(i=0;i<ovn;i++) { pd = make_pollen(r,ptype,xyval,probs,dads,&did); donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes co-dominant sporophytic self-incompatibility and size-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_scds(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,k,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_s(xc,yc,pdist,xyval,probs,minr,tage); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) { for(k=0;k<ALL;k++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==\ pop[xc][yc].gtype[0][k]) flg=OUT; } if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes maternally dominant sporophytic self-incompatibility and size-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sds(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_s(xc,yc,pdist,xyval,probs,minr,tage); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); if((md=pop[xc][yc].gtype[0][0])<pop[xc][yc].gtype[0][1]) md = pop[xc][yc].gtype[0][1]; for(j=0;j<ALL;j++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes paternally dominant sporophytic self-incompatibility and size-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sds2(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_s(xc,yc,pdist,xyval,probs,minr,tage); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][0]; if(md<pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]) md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]; for(j=0;j<ALL;j++) if(pop[xc][yc].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes gametophytic self-incompatibility and distance-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_gd(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_d(xc,yc,pdist,xyval,probs,minr,tdst); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) if(ptype[0]==pop[xc][yc].gtype[0][j]) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes neutral self-incompatibility and distance-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_nd(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; //printf("REPRO 1 \n"); (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); if(dads < 2) continue; xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_d(xc,yc,pdist,xyval,probs,minr,tdst); for(i=0;i<ovn;i++) { pd = make_pollen(r,ptype,xyval,probs,dads,&did); //printf("REPRO 4 \n"); donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); //printf("REPRO 5 \n"); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; //printf("REPRO \n"); free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes co-dominant sporophytic self-incompatibility and distance-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_scdd(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,k,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_d(xc,yc,pdist,xyval,probs,minr,tdst); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); for(j=0;j<ALL;j++) { for(k=0;k<ALL;k++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==\ pop[xc][yc].gtype[0][k]) flg=OUT; } if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes maternally dominant sporophytic self-incompatibility and distance-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sdd(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_d(xc,yc,pdist,xyval,probs,minr,tdst); //printf("FLAG_sdd\n"); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); if((md=pop[xc][yc].gtype[0][0])<pop[xc][yc].gtype[0][1]) md = pop[xc][yc].gtype[0][1]; for(j=0;j<ALL;j++) if(pop[xyval[pd][0]][xyval[pd][1]].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* assumes paternally dominant sporophytic self-incompatibility and distance-dependent pollen donors: for each reproductive adult, calls functions that determines the local pollen pool, create ovules and pollen grains, makes seeds and disperses them to empty sites; also calculates information used for fitness data output */ void reproduce_sdd2(int g,int rep,int minr,int pdist,int sdist,float **ft1, float **ft2,double b0,double d) { int i,j,flg,xc,yc,otype[GENES],ptype[GENES],dads,tage,**xyval,did,mid; int *donor,pd=0,lpd,md; float ovn,*probs,tpd1=0.0,tpd2=0.0,vpd,tdst; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>=minr) { lpd = 0; (pop[xc][yc].age<=(1.0/d))?(ovn=b0*d*pop[xc][yc].age):(ovn=b0); ((ovn-floor(ovn))<0.5)?(ovn=floor(ovn)):(ovn=ceil(ovn)); n_dads(xc,yc,pdist,minr,&dads,&tage,&tdst); xyval = imatrix(0,dads-1,0,1); probs = fvector(0,dads-1); donor = ivector(0,dads-1); for(i=0;i<dads;i++) donor[i] = OUT; make_pollen_pool_d(xc,yc,pdist,xyval,probs,minr,tdst); for(i=0;i<ovn;i++) { flg = IN; pd = make_pollen(r,ptype,xyval,probs,dads,&did); md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][0]; if(md<pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]) md = pop[xyval[pd][0]][xyval[pd][1]].gtype[0][1]; for(j=0;j<ALL;j++) if(pop[xc][yc].gtype[0][j]==md) flg=OUT; if(flg==IN) { donor[pd] = IN; pop[xyval[pd][0]][xyval[pd][1]].fsd += 1; pop[xc][yc].msd += 1; make_ovule(r,xc,yc,otype,&mid); make_seed(r,xc,yc,ptype,otype,sdist,did,mid); } } for(i=0;i<dads;i++) /* count for local pollen donors */ if(donor[i]==IN) lpd += 1; tpd1 += lpd; tpd2 += lpd*lpd; free_imatrix(xyval,0,dads-1,0,1); free_fvector(probs,0,dads-1); free_ivector(donor,0,dads-1); } } } if(rep>0) { ft1[g][0] += tpd1/rep; /* average number of pollen donors */ ft1[g][1] += (tpd1/rep)*(tpd1/rep); (rep==1)?(vpd=0.0):(vpd=(tpd2-(tpd1*tpd1)/rep)/(rep-1)); ft2[g][0] += vpd; /* variance in number of pollen donors */ ft2[g][1] += vpd*vpd; } return; } /* calculates # potential pollen donors within a local area determined by pdist; sums ages for calculating probabilities of size-dependent pollen dispersal; sums distances for calculating probabilities of distance-dependent pollen dispersal */ void n_dads(int xc,int yc,int pdist,int minr,int *dads,int *tage,float *tdst) { int i,j; *dads = 0; *tage = 0; *tdst = 0.0; for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { *dads += 1; *tage += pop[i][j].age; *tdst += sqrt((xc-i)*(xc-i)+(yc-j)*(yc-j)); } } } } return; } /* makes an ovule by randomly choosing one of the alleles at each locus of a maternal parent (stored in otype[]) */ void make_ovule(gsl_rng *r, int xc,int yc,int *otype,int *mid) { int i,al; for(i=0;i<GENES;i++) { al = gsl_rng_uniform_int(r,2);//g05dyc(0,1); otype[i] = pop[xc][yc].gtype[i][al]; } *mid = LEN*xc + yc; //gsl_rng_free (r); return; } /* constructs the pool of pollen donors and calculates their relative probabilities of reproductive success assuming no dependence on size/age or distance */ void make_pollen_pool_r(int xc,int yc,int pdist,int **xyval,float *probs,int minr, int dads) { int i,j,cnt=0; for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { probs[cnt] = (float)1.0/dads; if(cnt>0) probs[cnt] += probs[cnt-1]; xyval[cnt][0] = i; xyval[cnt][1] = j; cnt += 1; } } } } return; } /* constructs the pool of pollen donors and calculates their relative probabilities of reproductive success assuming size/age-dependence */ void make_pollen_pool_s(int xc,int yc,int pdist,int **xyval,float *probs,int minr, int tage) { int i,j,cnt=0; for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { probs[cnt] = (float)pop[i][j].age/tage; if(cnt>0) probs[cnt] += probs[cnt-1]; xyval[cnt][0] = i; xyval[cnt][1] = j; cnt += 1; } } } } return; } /* constructs the pool of pollen donors and calculates their relative probabilities of reproductive success assuming distance-dependence */ void make_pollen_pool_d(int xc,int yc,int pdist,int **xyval,float *probs,int minr, float tdst) { int i,j,cnt=0,dst; for(i=xc-pdist;i<=xc+pdist;i++) { for(j=yc-pdist;j<=yc+pdist;j++) { if(i>=0 && i<LEN && j>=0 && j<LEN) { if(pop[i][j].age>=minr) { dst = sqrt((xc-i)*(xc-i)+(yc-j)*(yc-j)); probs[cnt] = 1.0 - dst/tdst; if(cnt>0) probs[cnt] += probs[cnt-1]; xyval[cnt][0] = i; xyval[cnt][1] = j; cnt += 1; } } } } return; } /* randomly chooses a pollen donor and makes a pollen grain using one of the alleles at each locus of a paternal parent (stored in ptype[]) */ int make_pollen(gsl_rng *r, int *ptype,int **xyval,float *probs,int dads, int *did) { int i,j,al,flg=0; double rnum = 1.0;//gsl_rng_uniform(r) - 0.001; if(rnum == 1.0){ //printf(" For Rnum1= %.3f\n",rnum); while(rnum == 1.0){ rnum = gsl_rng_uniform(r) - 0.001;//g05cac(); //printf(" For Rnum1= %.3f\n",rnum); } } //printf(" dads= %d\n",dads); for(i=0;i<=dads && !flg;i++){ //printf("FLG = %d\n",flg); flg = rnum <= probs[i]; //printf(" For dads= %d\n",flg); //printf(" For Probs= %.3f\n",probs[i]); //printf(" For Rnum2= %.3f\n",rnum); //printf(" i= %d\n",i); } for(j=0;j<GENES;j++) { al = gsl_rng_uniform_int(r,2);//g05dyc(0,1); //printf("xyval x: %d", xyval[i-1][0]); //printf(" y: %d\n", xyval[i-1][1]); ptype[j] = pop[xyval[i-1][0]][xyval[i-1][1]].gtype[j][al]; //printf("HIT ! gen=%d\n",j); } *did = LEN*xyval[i-1][0] + xyval[i-1][1]; //gsl_rng_free (r); return i-1; } /* makes a seed and disperses it into an empty site if possible */ void make_seed(gsl_rng *r, int xc,int yc,int *ptype,int *otype,int sdist,int did,int mid) { int i,xn,yn; xn = gsl_rng_uniform_int(r,sdist+1) + xc;//g05dyc(xc-sdist,xc+sdist); yn = gsl_rng_uniform_int(r,sdist+1) + yc;//g05dyc(yc-sdist,yc+sdist); if(xn>=0 && xn<LEN && yn>=0 && yn<LEN) { if(pop[xn][yn].safe==1 && pop[xn][yn].age==0 && pop[xn][yn].sds<SDMAX) { for(i=0;i<GENES;i++) { pop[xn][yn].stype[pop[xn][yn].sds][i][0] = otype[i]; pop[xn][yn].stype[pop[xn][yn].sds][i][1] = ptype[i]; } pop[xn][yn].stype[pop[xn][yn].sds][GENES][0] = mid; pop[xn][yn].stype[pop[xn][yn].sds][GENES][1] = did; pop[xn][yn].sds += 1; } } //gsl_rng_free (r); return; } /* determines mortality for adult plants assuming constant death rate */ void kill_plants(gsl_rng *r, double d) { int i,j,xc,yc; //double rnum; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>0) { if((gsl_rng_uniform(r))<=d) //g05cac() { pop[xc][yc].age = 0; pop[xc][yc].mom = 0; pop[xc][yc].dad = 0; for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++) pop[xc][yc].gtype[i][j] = 0; } } else if(gsl_rng_uniform(r)>d) //rnum>d pop[xc][yc].age += 1; } } } //gsl_rng_free (r); return; } /* determines mortality for adult plants assuming age-dependent death rate and senescence */ void kill_plants_agedep(gsl_rng *r, double lambda, double d) { int i,j,xc,yc; double death_age_prob; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].age>0 && pop[xc][yc].age < 20) { death_age_prob = lambda*exp(-lambda*pop[xc][yc].age) + d; //if(death_age_prob < 0.005) death_age_prob = 0.005; //printf("Age-dependent mortality rate: %.2f \n", death_age_prob); //printf("D (lambda): %.2f \n", lambda); if((gsl_rng_uniform(r))<=death_age_prob) //g05cac() { pop[xc][yc].age = 0; pop[xc][yc].mom = 0; pop[xc][yc].dad = 0; for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++) pop[xc][yc].gtype[i][j] = 0; } } else if(gsl_rng_uniform(r)>death_age_prob) //rnum>d pop[xc][yc].age += 1; } else if(pop[xc][yc].age > 20) { if(gsl_rng_uniform(r)< 0.9) //g05cac() { pop[xc][yc].age = 0; pop[xc][yc].mom = 0; pop[xc][yc].dad = 0; for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++) pop[xc][yc].gtype[i][j] = 0; } } } } } //gsl_rng_free (r); return; } int seedbank_size(int xc, int yc){ int sizesb=0; for(int i=0; i<SBMAX; i++){ if(pop[xc][yc].seedbank_age[i] > 0) sizesb++; } return sizesb; } void empty_slots(int xc, int yc, Vector *tempvec){ for(int i=0;i<SBMAX;i++){ if(pop[xc][yc].seedbank_age[i]==0) vector_append(tempvec,i); } } /* adds new seedlings at time t+1 to the population (after adult mortality) */ /* Function to add probability of germination from seed bank */ void new_plants(gsl_rng *r,float est) { int i,j,k,xc,yc,sn,counter,sbsize, min_value; double rnum; Vector tempvec; //Vector *tempvecptr = &tempvec; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { sbsize = seedbank_size(xc,yc); vector_init(&tempvec); empty_slots(xc,yc,&tempvec); if(pop[xc][yc].sds>0) // sds is number of seeds per individual { if((rnum=gsl_rng_uniform(r))<=est) //g05cac() { sn = gsl_rng_uniform_int(r,pop[xc][yc].sds);//g05dyc(0,pop[xc][yc].sds-1); Pick one seed randomly to survive for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++) pop[xc][yc].gtype[i][j] = pop[xc][yc].stype[sn][i][j]; } pop[xc][yc].mom = pop[xc][yc].stype[sn][GENES][0]; pop[xc][yc].dad = pop[xc][yc].stype[sn][GENES][1]; pop[xc][yc].age = 1; }else{ // IF NO seed germinates then they become part of the seedbank, //printf("No seed germination - seeds go to bank \n"); min_value = (pop[xc][yc].sds) < (tempvec.size) ? (pop[xc][yc].sds):(tempvec.size); //printf("MIN value -> %d \n", min_value); if(sbsize < SBMAX){ for(i=0;i<min_value;i++){ counter = vector_get(&tempvec,i); // Assign genetic data to seedbank seed //printf("vector stype: "); //printf("vector seedbankid: "); for(j=0;j<GENES;j++){ for(k=0;k<ALL;k++){ pop[xc][yc].seedbankid[counter][j][k] = pop[xc][yc].stype[i][j][k]; // Given genetic identity to seed bank seeds //printf(" %d ",pop[xc][yc].stype[i][j][k]); //printf(" %d ",pop[xc][yc].seedbankid[counter][j][k]); } } //printf(" \n"); pop[xc][yc].seedbank_age[counter] = 1; } } } pop[xc][yc].sds = 0; for(i=0;i<SDMAX;i++) { for(j=0;j<GENES;j++) { for(k=0;k<ALL;k++) pop[xc][yc].stype[i][j][k] = 0; } } }else if(sbsize > 0){ sn = gsl_rng_uniform_int(r,SBMAX);// Pick one seed randomly to survive // Check if seedbank seed is dead or alive while(pop[xc][yc].seedbank_age[sn] == 0) sn = gsl_rng_uniform_int(r,SBMAX);// Pick one seed randomly to survive //printf("Age of seedbank seed -> %d - seedbank number %d \n",pop[xc][yc].seedbank_age[sn], sn); //printf("Checking if seedbank seed exists!! S1: %d - S2: %d \n", pop[xc][yc].seedbankid[sn][0][0], pop[xc][yc].seedbankid[sn][0][1]); //if(pop[xc][yc].seedbankid[sn][0][0] == pop[xc][yc].seedbankid[sn][0][1]) exit(1); for(i=0;i<GENES;i++) { for(j=0;j<ALL;j++){ pop[xc][yc].gtype[i][j] = pop[xc][yc].seedbankid[sn][i][j]; pop[xc][yc].seedbankid[sn][i][j] = 0; } } pop[xc][yc].mom = pop[xc][yc].seedbankid[sn][GENES][0]; pop[xc][yc].dad = pop[xc][yc].seedbankid[sn][GENES][1]; pop[xc][yc].age = 1; pop[xc][yc].seedbank_age[sn] = 0; } vector_free(&tempvec); } } return; } void seedbank_mortality(gsl_rng *r, float mort_seed_seedbank_prob){ int i,j,k,xc,yc; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(seedbank_size(xc,yc)>0) // sds is number of seeds per individual { //// Increase AGE of seedbank seeds older than 1 year for(i=0; i < SBMAX; i++){ if(pop[xc][yc].seedbank_age[i] > 0) pop[xc][yc].seedbank_age[i] ++; } //// Seedbank seeds mortality for(i=0;i<SBMAX;i++){ // Seedbank seeds that are older than 10 years die if(pop[xc][yc].seedbank_age[i] > 10){ pop[xc][yc].seedbank_age[i] = 0; for(j=0;j<GENES;j++){ for(k=0;k<ALL;k++) pop[xc][yc].seedbankid[i][j][k] = 0; } }else if(pop[xc][yc].seedbank_age[i] > 0){ //Seedbank seeds mortality age-independent if(mort_seed_seedbank_prob > gsl_rng_uniform(r)){ //printf("SEED MORTALITY \n"); pop[xc][yc].seedbank_age[i] = 0; for(j=0;j<GENES;j++){ for(k=0;k<ALL;k++) pop[xc][yc].seedbankid[i][j][k] = 0; } } } } } } } } /* allocates a float vector */ float *fvector(long nl,long nh) { float *v; v = (float *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(float))); if(!v) nrerror("allocation failure in fvector()"); return v-nl+NR_END; } /* frees a float vector allocated by fvector() */ void free_fvector(float *v,long int nl,long int nh) { free((FREE_ARG) (v+nl-NR_END)); } /* allocates an int vector */ int *ivector(long nl,long nh) { int *v; v = (int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int))); if(!v) nrerror("allocation failure in ivector()"); return v-nl+NR_END; } /* frees an int vector allocated by ivector() */ void free_ivector(int *v,long int nl,long int nh) { free((FREE_ARG) (v+nl-NR_END)); } /* allocates an int matrix with subscript range m[nrl..nrh][ncl..nch] */ int **imatrix(long int nrl, long int nrh, long int ncl, long int nch) { long int i,nrow=nrh-nrl+1,ncol=nch-ncl+1; int **m; m = (int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); if(!m) nrerror("allocation failure 1 in imatrix()"); m += NR_END; m -= nrl; m[nrl] = (int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); if(!m[nrl]) nrerror("allocation failure 2 in imatrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i] = m[i-1] + ncol; return m; } /* frees an int matrix allocated by imatrix() */ void free_imatrix(int **m, long int nrl, long int nrh, long int ncl, long int nch) { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } /* allocates a float matrix with subscript range m[nrl..nrh][ncl..nch] */ float **fmatrix(long int nrl, long int nrh, long int ncl, long int nch) { long int i,nrow=nrh-nrl+1,ncol=nch-ncl+1; float **m; m = (float **) malloc((size_t)((nrow+NR_END)*sizeof(float*))); if(!m) nrerror("allocation failure 1 in fmatrix()"); m += NR_END; m -= nrl; m[nrl] = (float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float))); if(!m[nrl]) nrerror("allocation failure 2 in fmatrix()"); m[nrl] += NR_END; m[nrl] -= ncl; for(i=nrl+1;i<=nrh;i++) m[i] = m[i-1] + ncol; return m; } /* frees a float matrix allocated by fmatrix() */ void free_fmatrix(float **m, long int nrl, long int nrh, long int ncl, long int nch) { free((FREE_ARG) (m[nrl]+ncl-NR_END)); free((FREE_ARG) (m+nrl-NR_END)); } /* Numerical Recipes standard error handler */ void nrerror(char error_text[]) { fprintf(stderr,"Numerical Recipes run-time error...\n"); fprintf(stderr,"%s\n",error_text); fprintf(stderr,"...now exiting to system...\n"); exit(1); } /* calculates means and standard errors for demographic data; prints to file fpw1 */ void grand_mean1(int gen,float **mnv,float **mnr,float **myr,int *nrn,float **ec1, float **ec2,float **ec3,int *nrp, Vector *vector_quasi_ext) { int g; float se; fprintf(fpw1,"GEN\tNRUN\tTVEG\tERR1\tTREP\tERR2\tAGE\tERR3\t"); fprintf(fpw1,"EMPTY\tERR4\tLREP\tERR5\tMATE\tERR6\tQUASI\n"); for(g=0;g<=gen;g++) { fprintf(fpw1,"%d\t%d\t",g,nrn[g]); if(nrn[g]==0) fprintf(fpw1,".\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\n"); else if(nrn[g]==1) { fprintf(fpw1,"%.1f\t.\t%.1f\t.\t%.1f\t.\t",mnv[g][0],mnr[g][0],myr[g][0]); if(nrp[g]==0) fprintf(fpw1,".\t.\t.\t.\t.\t.\n"); else if(nrp[g]==1) fprintf(fpw1,"%.1f\t.\t%.1f\t.\t%.1f\t%3d\t\n",ec1[g][0],ec2[g][0],ec3[g][0],vector_get(vector_quasi_ext,g)); } else { fprintf(fpw1,"%.1f\t",(mnv[g][0]/nrn[g])); mnv[g][0] *= mnv[g][0]; se = (sqrt(fabs((mnv[g][1]-(mnv[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw1,"%.3f\t",se); fprintf(fpw1,"%.1f\t",(mnr[g][0]/nrn[g])); mnr[g][0] *= mnr[g][0]; se = (sqrt(fabs((mnr[g][1]-(mnr[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw1,"%.3f\t",se); fprintf(fpw1,"%.1f\t",(myr[g][0]/nrn[g])); myr[g][0] *= myr[g][0]; se = (sqrt(fabs((myr[g][1]-(myr[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw1,"%.3f\t",se); if(nrp[g]==0) fprintf(fpw1,".\t.\t.\t.\t.\t.\n"); else if(nrp[g]==1) fprintf(fpw1,"%.1f\t.\t%.1f\t.\t%.1f\t%3d\t\n",ec1[g][0],ec2[g][0],ec3[g][0],vector_get(vector_quasi_ext,g)); else { fprintf(fpw1,"%.1f\t",(ec1[g][0]/nrp[g])); ec1[g][0] *= ec1[g][0]; se=(sqrt(fabs((ec1[g][1]-(ec1[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw1,"%.3f\t",se); fprintf(fpw1,"%.1f\t",(ec2[g][0]/nrp[g])); ec2[g][0] *= ec2[g][0]; se=(sqrt(fabs((ec2[g][1]-(ec2[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw1,"%.3f\t",se); fprintf(fpw1,"%.1f\t",(ec3[g][0]/nrp[g])); ec3[g][0] *= ec3[g][0]; se=(sqrt(fabs((ec3[g][1]-(ec3[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw1,"%.3f\t",se); fprintf(fpw1,"%3d\n",vector_get(vector_quasi_ext,g)); } } } return; } /* calculates means and standard errors for genetic data; prints to file fpw2 */ void grand_mean2(int gen,int *nrn,float **gn1,float **gn2,float **gn3,float **gn4, float **gn5,float **gn6,float **gn7) { int g; float se; fprintf(fpw2,"GEN\tNRUN\tNGENE\tERR1\tSGENE\tERR2\tNVAR\tERR3\tSVAR\tERR4\t"); fprintf(fpw2,"HO\tERR5\tHE\tERR6\tFIS\tERR7\n"); for(g=0;g<=gen;g++) { fprintf(fpw2,"%d\t%d\t",g,nrn[g]); if(nrn[g]==0) fprintf(fpw2,".\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\n"); else if(nrn[g]==1) { fprintf(fpw2,"%.3f\t.\t%.3f\t.\t%.3f\t.\t%.3f\t.\t%.3f\t.\t",gn1[g][0], gn2[g][0],gn3[g][0],gn4[g][0],gn5[g][0]); fprintf(fpw2,"%.3f\t.\t%.3f\t.\n",gn6[g][0],gn7[g][0]); } else { fprintf(fpw2,"%.3f\t",(gn1[g][0]/nrn[g])); gn1[g][0] *= gn1[g][0]; se = (sqrt(fabs((gn1[g][1]-(gn1[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn2[g][0]/nrn[g])); gn2[g][0] *= gn2[g][0]; se = (sqrt(fabs((gn2[g][1]-(gn2[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn3[g][0]/nrn[g])); gn3[g][0] *= gn3[g][0]; se = (sqrt(fabs((gn3[g][1]-(gn3[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn4[g][0]/nrn[g])); gn4[g][0] *= gn4[g][0]; se = (sqrt(fabs((gn4[g][1]-(gn4[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn5[g][0]/nrn[g])); gn5[g][0] *= gn5[g][0]; se = (sqrt(fabs((gn5[g][1]-(gn5[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn6[g][0]/nrn[g])); gn6[g][0] *= gn6[g][0]; se = (sqrt(fabs((gn6[g][1]-(gn6[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\t",se); fprintf(fpw2,"%.3f\t",(gn7[g][0]/nrn[g])); gn7[g][0] *= gn7[g][0]; se = (sqrt(fabs((gn7[g][1]-(gn7[g][0]/nrn[g]))/(nrn[g]-1))))/sqrt(nrn[g]); fprintf(fpw2,"%.3f\n",se); } } return; } /* calculates means and standard errors for fitness data; prints to file fpw3 */ void grand_mean3(int gen,int *nrp,float **ft1,float **ft2,float **ft3,float **ft4, float **ft5,float **ft6,float **ft7,float **ft8) { int g; float se; fprintf(fpw3,"GEN\tNPOLL\tERR1\tVPOLL\tERR2\tSDS1\tERR3\tVFSD1\tERR4\t"); fprintf(fpw3,"VMSD1\tERR5\tSDS2\tERR6\tVFSD2\tERR7\tVMSD2\tERR8\n"); for(g=0;g<=gen;g++) { fprintf(fpw3,"%d\t",g); if(nrp[g]==0) fprintf(fpw3,".\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\n"); else if(nrp[g]==1) { fprintf(fpw3,"%.3f\t.\t%.3f\t.\t%.3f\t.\t",ft1[g][0],ft2[g][0],ft3[g][0]); fprintf(fpw3,"%.3f\t.\t%.3f\t.\t%.3f\t.\t%.3f\t.\t%.3f\t.\n",ft4[g][0], ft5[g][0],ft6[g][0],ft7[g][0],ft8[g][0]); } else { fprintf(fpw3,"%.3f\t",(ft1[g][0]/nrp[g])); ft1[g][0] *= ft1[g][0]; se = (sqrt(fabs((ft1[g][1]-(ft1[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft2[g][0]/nrp[g])); ft2[g][0] *= ft2[g][0]; se = (sqrt(fabs((ft2[g][1]-(ft2[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft3[g][0]/nrp[g])); ft3[g][0] *= ft3[g][0]; se = (sqrt(fabs((ft3[g][1]-(ft3[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft4[g][0]/nrp[g])); ft4[g][0] *= ft4[g][0]; se = (sqrt(fabs((ft4[g][1]-(ft4[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft5[g][0]/nrp[g])); ft5[g][0] *= ft5[g][0]; se = (sqrt(fabs((ft5[g][1]-(ft5[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft6[g][0]/nrp[g])); ft6[g][0] *= ft6[g][0]; se = (sqrt(fabs((ft6[g][1]-(ft6[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft7[g][0]/nrp[g])); ft7[g][0] *= ft7[g][0]; se = (sqrt(fabs((ft7[g][1]-(ft7[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\t",se); fprintf(fpw3,"%.3f\t",(ft8[g][0]/nrp[g])); ft8[g][0] *= ft8[g][0]; se = (sqrt(fabs((ft8[g][1]-(ft8[g][0]/nrp[g]))/(nrp[g]-1))))/sqrt(nrp[g]); fprintf(fpw3,"%.3f\n",se); } } return; } /* calculates mean and standard error for persistence; prints to file fpw1 */ void persist(int runs,int rcnt,int gen) { float se; fprintf(fpw1,"Number of Runs Persisting to %d Generations: %d\n",gen,rcnt); fprintf(fpw1,"Average Persistence: %.1f\t",(per1/runs)); if(runs>1) { per1 *= per1; se = (sqrt(fabs((per2-(per1/runs))/(runs-1))))/sqrt(runs); fprintf(fpw1,"Standard Error: %.3f\n\n",se); } else fprintf(fpw1,"Standard error: N/A\n\n"); return; } /* prints genetic and fitness data for individual plants to file fpw4 */ void plant_data(int g,int sloc,int nloc) { int i,id,xc,yc; for(xc=0;xc<LEN;xc++) { for(yc=0;yc<LEN;yc++) { if(pop[xc][yc].safe==1) { fprintf(fpw4,"%4d %2d %2d %3d",g,xc,yc,pop[xc][yc].age); if(pop[xc][yc].age>0) { for(i=0;i<GENES;i++) { id_val(xc,yc,i,&id,sloc,nloc); fprintf(fpw4," %3d %3d %3d",id,pop[xc][yc].gtype[i][0], pop[xc][yc].gtype[i][1]); //printf(" %3d %3d %3d\n",id,pop[xc][yc].gtype[i][0], //pop[xc][yc].gtype[i][1]); } } else if(pop[xc][yc].age==0) for(i=0;i<GENES;i++) fprintf(fpw4," %3d %3d %3d",0,0,0); fprintf(fpw4,"\n"); } } } return; } /* calculates genotype id values for each locus */ void id_val(int xc,int yc,int i,int *id,int sloc,int nloc) { int j,sum=0,loc; (i==0)?(loc=sloc):(loc=nloc); if(pop[xc][yc].gtype[i][0]<=pop[xc][yc].gtype[i][1]) { for(j=0;j<pop[xc][yc].gtype[i][0];j++) sum += j; *id = pop[xc][yc].gtype[i][1]+(loc*(pop[xc][yc].gtype[i][0]-1))-sum; } else if(pop[xc][yc].gtype[i][0]>pop[xc][yc].gtype[i][1]) { for(j=0;j<pop[xc][yc].gtype[i][1];j++) sum += j; *id = pop[xc][yc].gtype[i][0]+(loc*(pop[xc][yc].gtype[i][1]-1))-sum; } return; }
{ "alphanum_fraction": 0.4667596892, "avg_line_length": 38.5058719906, "ext": "c", "hexsha": "d3a5a27742460787a06822191752e1305b7c37d7", "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": "4e1e5553eff89f2f2ea9571e296f3e9c4c675e4c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "franeviso/pva-gisera", "max_forks_repo_path": "simodel_rescue_seedbank_cluster.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4e1e5553eff89f2f2ea9571e296f3e9c4c675e4c", "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": "franeviso/pva-gisera", "max_issues_repo_path": "simodel_rescue_seedbank_cluster.c", "max_line_length": 328, "max_stars_count": null, "max_stars_repo_head_hexsha": "4e1e5553eff89f2f2ea9571e296f3e9c4c675e4c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "franeviso/pva-gisera", "max_stars_repo_path": "simodel_rescue_seedbank_cluster.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 39155, "size": 131151 }
//CELL operation: does output side of Jordan RNN layer. //The inputs here are from the IN stage, so reduced to N driving input time-series in X. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int jordan_s (float *Y, const float *X, const float *U, float *Y1, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int jordan_d (double *Y, const double *X, const double *U, double *Y1, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int jordan_s (float *Y, const float *X, const float *U, float *Y1, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; float *H; if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in jordan_s: problem with malloc. "); perror("malloc"); return 1; } if (N==1u) { H[0] = 1.0f / (1.0f+expf(-X[0]-U[0]*Y1[0])); Y[0] = 1.0f / (1.0f+expf(-B[0]-W[0]*H[0])); for (size_t t=1; t<T; ++t) { H[0] = 1.0f / (1.0f+expf(-X[t]-U[0]*Y[t-1])); Y[t] = 1.0f / (1.0f+expf(-B[0]-W[0]*H[0])); } } else { if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { cblas_scopy((int)T,&B[n],0,&Y[n],(int)N); } cblas_scopy((int)N,&X[0],1,H,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],1); for (size_t n=0u; n<N; ++n) { Y[n] = 1.0f/(1.0f+expf(-Y[n])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t*N],1,H,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,&Y[(t-1)*N],1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t*N],1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0f/(1.0f+expf(-Y[t*N+n])); } } } else { for (size_t n=0u; n<N; ++n) { cblas_scopy((int)T,&B[n],0,&Y[n*T],1); } cblas_scopy((int)N,&X[0],(int)T,H,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],(int)T); for (size_t n=0u; n<N; ++n) { Y[n*T] = 1.0f/(1.0f+expf(-Y[n*T])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,H,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,&Y[t-1],(int)T,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0f/(1.0f+expf(-Y[t+n*T])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { cblas_scopy((int)T,&B[n],0,&Y[n*T],1); } cblas_scopy((int)N,&X[0],(int)T,H,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],(int)T); for (size_t n=0u; n<N; ++n) { Y[n*T] = 1.0f/(1.0f+expf(-Y[n*T])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,H,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,&Y[t-1],(int)T,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0f/(1.0f+expf(-Y[t+n*T])); } } } else { for (size_t n=0u; n<N; ++n) { cblas_scopy((int)T,&B[n],0,&Y[n],(int)N); } cblas_scopy((int)N,&X[0],1,H,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],1); for (size_t n=0u; n<N; ++n) { Y[n] = 1.0f/(1.0f+expf(-Y[n])); } for (size_t t=1; t<T; ++t) { cblas_scopy((int)N,&X[t*N],1,H,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,&Y[(t-1)*N],1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-H[n])); } cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t*N],1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0f/(1.0f+expf(-Y[t*N+n])); } } } } else { fprintf(stderr,"error in jordan_s: dim must be 0 or 1.\n"); return 1; } } return 0; } int jordan_d (double *Y, const double *X, const double *U, double *Y1, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; double *H; if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in jordan_d: problem with malloc. "); perror("malloc"); return 1; } if (N==1u) { H[0] = 1.0 / (1.0+exp(-X[0]-U[0]*Y1[0])); Y[0] = 1.0 / (1.0+exp(-B[0]-W[0]*H[0])); for (size_t t=1; t<T; ++t) { H[0] = 1.0 / (1.0+exp(-X[t]-U[0]*Y[t-1])); Y[t] = 1.0 / (1.0+exp(-B[0]-W[0]*H[0])); } } else { if (dim==0u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { cblas_dcopy((int)T,&B[n],0,&Y[n],(int)N); } cblas_dcopy((int)N,&X[0],1,H,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],1); for (size_t n=0u; n<N; ++n) { Y[n] = 1.0/(1.0+exp(-Y[n])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t*N],1,H,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,&Y[(t-1)*N],1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t*N],1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0/(1.0+exp(-Y[t*N+n])); } } } else { for (size_t n=0u; n<N; ++n) { cblas_dcopy((int)T,&B[n],0,&Y[n*T],1); } cblas_dcopy((int)N,&X[0],(int)T,H,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],(int)T); for (size_t n=0u; n<N; ++n) { Y[n*T] = 1.0/(1.0+exp(-Y[n*T])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,H,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,&Y[t-1],(int)T,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0/(1.0+exp(-Y[t+n*T])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t n=0u; n<N; ++n) { cblas_dcopy((int)T,&B[n],0,&Y[n*T],1); } cblas_dcopy((int)N,&X[0],(int)T,H,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],(int)T); for (size_t n=0u; n<N; ++n) { Y[n*T] = 1.0/(1.0+exp(-Y[n*T])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,H,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,&Y[t-1],(int)T,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t],(int)T); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0/(1.0+exp(-Y[t+n*T])); } } } else { for (size_t n=0u; n<N; ++n) { cblas_dcopy((int)T,&B[n],0,&Y[n],(int)N); } cblas_dcopy((int)N,&X[0],1,H,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,Y1,1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[0],1); for (size_t n=0u; n<N; ++n) { Y[n] = 1.0/(1.0+exp(-Y[n])); } for (size_t t=1; t<T; ++t) { cblas_dcopy((int)N,&X[t*N],1,H,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,&Y[(t-1)*N],1,o,H,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-H[n])); } cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,&Y[t*N],1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0/(1.0+exp(-Y[t*N+n])); } } } } else { fprintf(stderr,"error in jordan_d: dim must be 0 or 1.\n"); return 1; } } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.44527956, "avg_line_length": 47.850877193, "ext": "c", "hexsha": "506ac6989e70b21c6f96fd9423dd49491ff104f3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_path": "c/jordan.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/nn", "max_issues_repo_path": "c/jordan.c", "max_line_length": 178, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_path": "c/jordan.c", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "num_tokens": 4227, "size": 10910 }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Portions Copyright (c) Microsoft Corporation #pragma once #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <gsl/pointers> #include "core/common/common.h" #include "core/common/callback.h" #include "core/platform/env_time.h" #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif namespace onnxruntime { #ifdef _WIN32 using PIDType = unsigned long; #else using PIDType = pid_t; #endif /// \brief An interface used by the onnxruntime implementation to /// access operating system functionality like the filesystem etc. /// /// Callers may wish to provide a custom Env object to get fine grain /// control. /// /// All Env implementations are safe for concurrent access from /// multiple threads without any external synchronization. class Env { public: virtual ~Env() = default; /// \brief Returns a default environment suitable for the current operating /// system. /// /// Sophisticated users may wish to provide their own Env /// implementation instead of relying on this default environment. /// /// The result of Default() belongs to this library and must never be deleted. static const Env& Default(); virtual int GetNumCpuCores() const = 0; /// \brief Returns the number of micro-seconds since the Unix epoch. virtual uint64_t NowMicros() const { return env_time_->NowMicros(); } /// \brief Returns the number of seconds since the Unix epoch. virtual uint64_t NowSeconds() const { return env_time_->NowSeconds(); } /// Sleeps/delays the thread for the prescribed number of micro-seconds. /// On Windows, it's the min time to sleep, not the actual one. virtual void SleepForMicroseconds(int64_t micros) const = 0; #ifndef _WIN32 /** * * \param file_path file_path must point to a regular file, which can't be a pipe/socket/... * \param[out] p allocated buffer with the file data * \param[in] offset file offset. If offset>0, then len must also be >0. * \param[in, out] len length to read(or has read). If len==0, read the whole file. * @return */ virtual common::Status ReadFileAsString(const char* file_path, off_t offset, void*& p, size_t& len, OrtCallback& deleter) const = 0; #else virtual common::Status ReadFileAsString(const wchar_t* file_path, int64_t offset, void*& p, size_t& len, OrtCallback& deleter) const = 0; #endif #ifdef _WIN32 //Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0; #endif //Mainly for use with protobuf library virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0; //Mainly for use with protobuf library virtual common::Status FileClose(int fd) const = 0; //This functions is always successful. It can't fail. virtual PIDType GetSelfPid() const = 0; // \brief Load a dynamic library. // // Pass "library_filename" to a platform-specific mechanism for dynamically // loading a library. The rules for determining the exact location of the // library are platform-specific and are not documented here. // // On success, returns a handle to the library in "*handle" and returns // OK from the function. // Otherwise returns nullptr in "*handle" and an error status from the // function. virtual common::Status LoadDynamicLibrary(const std::string& library_filename, void** handle) const = 0; virtual common::Status UnloadDynamicLibrary(void* handle) const = 0; // \brief Get a pointer to a symbol from a dynamic library. // // "handle" should be a pointer returned from a previous call to LoadDynamicLibrary. // On success, store a pointer to the located symbol in "*symbol" and return // OK from the function. Otherwise, returns nullptr in "*symbol" and an error // status from the function. virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0; // \brief build the name of dynamic library. // // "name" should be name of the library. // "version" should be the version of the library or NULL // returns the name that LoadDynamicLibrary() can use virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0; protected: Env(); private: ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env); EnvTime* env_time_ = EnvTime::Default(); }; } // namespace onnxruntime
{ "alphanum_fraction": 0.7129390018, "avg_line_length": 37.3103448276, "ext": "h", "hexsha": "d27cdbaae68332b88f3c475fd128327ff8782b78", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-04-13T12:00:20.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-03T16:23:35.000Z", "max_forks_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dahburj/onnxruntime", "max_forks_repo_path": "onnxruntime/core/platform/env.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_issues_repo_issues_event_max_datetime": "2021-04-19T16:56:52.000Z", "max_issues_repo_issues_event_min_datetime": "2019-10-08T14:20:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dahburj/onnxruntime", "max_issues_repo_path": "onnxruntime/core/platform/env.h", "max_line_length": 117, "max_stars_count": 1, "max_stars_repo_head_hexsha": "cd5f74be6250a5a672decc1fd234e200dac36878", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dahburj/onnxruntime", "max_stars_repo_path": "onnxruntime/core/platform/env.h", "max_stars_repo_stars_event_max_datetime": "2020-07-12T16:33:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-12T16:33:33.000Z", "num_tokens": 1292, "size": 5410 }
#pragma once #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include "defines.h" // Pass matrices a, b // Matrix c is already allocated and is the correct size // c = [a b]' int gsl_matrix_vstack(gsl_matrix *c, const gsl_matrix *a, const gsl_matrix *b); // Multiply matrices c = a*b // Use gsl_blas_dgemm() instead: // gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A, B, 0.0, C); int gsl_matrix_mul(gsl_matrix *c, const gsl_matrix *a, const gsl_matrix *b); // Helper function for matrix multiplication to multiply specified row by // specified column // Number of columns in a must be equal to number of rows in b double gsl_matrix_rowcol_mul(const gsl_matrix *a, const gsl_matrix *b, int r, int c); // Pass vectors a, b // Vector c is already allocated and is the correct size // c = [a b]' int gsl_vector_vstack(gsl_vector *c, const gsl_vector *a, const gsl_vector *b); double gsl_vector_infnorm(const gsl_vector *v); void gsl_vector_print(const gsl_vector *v, char *name);
{ "alphanum_fraction": 0.7366863905, "avg_line_length": 31.6875, "ext": "h", "hexsha": "b904de9e73d30b2beb491cf687287f82502540f9", "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": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umd-agrc/SimpleControlSim", "max_forks_repo_path": "matrix_vector_ops.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "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": "umd-agrc/SimpleControlSim", "max_issues_repo_path": "matrix_vector_ops.h", "max_line_length": 85, "max_stars_count": null, "max_stars_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umd-agrc/SimpleControlSim", "max_stars_repo_path": "matrix_vector_ops.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 286, "size": 1014 }
// An interface to GSL - hides all the gsl calls behind easier to use functions // Jason Sanders #ifndef GSLINTERFACE_H #define GSLINTERFACE_H #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sort_double.h> #include <gsl/gsl_permute.h> #include <gsl/gsl_odeiv2.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_erf.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_ellint.h> #include <gsl/gsl_monte_vegas.h> #include <gsl/gsl_siman.h> #include <stdlib.h> #include <iostream> //================================================================================================= // RANDOM NUMBERS // // random number generators - rand_uniform returns random numbers uniformly distributed in the // interval [0,1], rand_gaussian returns gaussian distributed random numbers with sd = sigma class rand_base{ private: const gsl_rng_type * TYPE; unsigned long int seed; public: gsl_rng * r; rand_base(unsigned long int s){ // construct random number generator with seed s seed = s; gsl_rng_env_setup(); TYPE = gsl_rng_default; r = gsl_rng_alloc (TYPE); gsl_rng_set(r, seed); } ~rand_base(){gsl_rng_free (r);} void reseed(unsigned long int newseed){ // give new seed seed = newseed; gsl_rng_set(r,newseed); } }; class rand_uniform:public rand_base{ public: rand_uniform(unsigned long int SEED=0):rand_base(SEED){} ~rand_uniform(){} // return uniformly distributed random numbers double nextnumber(){return gsl_rng_uniform (r);} }; class rand_gaussian:public rand_base{ public: double sigma; rand_gaussian(double s, unsigned long int SEED=0):rand_base(SEED){sigma = s;} ~rand_gaussian(){} // return gaussian distributed random numbers double nextnumber(){return gsl_ran_gaussian (r,sigma);} void newsigma(double newsigma){sigma=newsigma;} }; //================================================================================================= // ROOT FINDING // // finds root by Brent's method. Constructor initialises function and tolerances, findroot finds // root in given interval. Function must be of form double(*func)(double,void*) class root_find{ private: int status; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; gsl_function F; double xlo,xhi,eps,root,tol; int iter, max_iter; public: root_find(double tol,int max_iter) : tol(tol), max_iter(max_iter){ iter=0;eps=1.e-8; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); } ~root_find(){gsl_root_fsolver_free (s);} void bracket(){ // crude bracketing routine. Expands interval till root found if(xhi<xlo){double xt = xlo; xlo=xhi; xhi=xt;} double diff = (xhi-xlo)/2.; while(GSL_FN_EVAL(&F,xlo)*GSL_FN_EVAL(&F,xhi)>0.){ xlo-=diff;xhi+=diff; } } double findroot(double(*func)(double,void *),double xlo1,double xhi1, void *p=NULL){ // finds root in interval [xlo1,xhi1] F.function = func;F.params=p;xhi = xhi1; xlo = xlo1; if(GSL_FN_EVAL(&F,xlo)*GSL_FN_EVAL(&F,xhi)>0.){ bracket(); } gsl_root_fsolver_set (s, &F, xlo, xhi); do{ iter++; status = gsl_root_fsolver_iterate (s); root = gsl_root_fsolver_root (s); xlo = gsl_root_fsolver_x_lower (s); xhi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (xlo, xhi, tol, eps); } while (status == GSL_CONTINUE && iter < max_iter); return root; } }; //================================================================================================= // INTEGRATION // // Simple 1d numerical integration using adaptive Gauss-Kronrod which can deal with singularities // constructor takes function and tolerances and integrate integrates over specified region. // integrand function must be of the form double(*func)(double,void*) class integrator{ private: gsl_integration_workspace *w; void *p; double result,err,eps; gsl_function F; size_t neval; public: integrator(double eps): eps(eps){ w= gsl_integration_workspace_alloc (1000); F.params = &p; } ~integrator(){gsl_integration_workspace_free (w);} double integrate(double(*func)(double,void*),double xa, double xb){ F.function = func; gsl_integration_qags (&F, xa, xb, 0, eps, 1000,w, &result, &err); //gsl_integration_qng(&F, xa, xb, 0, eps, &result, &err, &neval); return result; } double error(){return err;} }; inline double integrate(double(*func)(double,void*),double xa, double xb, double eps){ double result,err; size_t neval;void *p;gsl_function F;F.function = func;F.params = &p; gsl_integration_qng(&F, xa, xb, 0, eps, &result, &err, &neval); return result; } class MCintegrator{ private: gsl_monte_vegas_state *s; const gsl_rng_type *T; gsl_rng *r; size_t dim; public: MCintegrator(size_t Dim){ dim=Dim; gsl_rng_env_setup (); T = gsl_rng_default; r = gsl_rng_alloc (T); s=gsl_monte_vegas_alloc(Dim); } ~MCintegrator(){ gsl_monte_vegas_free(s); gsl_rng_free(r); } double integrate(double(*func)(double*,size_t,void*),double *xlow, double *xhigh, size_t calls, double *err, int burnin=10000){ gsl_monte_function G = { func, dim, 0 }; double res; if(burnin)gsl_monte_vegas_integrate(&G,xlow,xhigh,dim,burnin,r,s,&res,err); gsl_monte_vegas_integrate(&G,xlow,xhigh,dim,calls,r,s,&res,err); return res; } }; //================================================================================================= // 1D INTERPOLATION // // Interpolation using cubic splines class interpolator{ private: gsl_interp_accel *acc; gsl_spline *spline; public: interpolator(double *x, double *y, int n){ acc = gsl_interp_accel_alloc(); spline = gsl_spline_alloc(gsl_interp_cspline,n); gsl_spline_init (spline, x, y, n); } ~interpolator(){ gsl_spline_free (spline); gsl_interp_accel_free (acc); } double interpolate(double xi){ return gsl_spline_eval (spline, xi, acc); } double derivative(double xi){ return gsl_spline_eval_deriv(spline, xi, acc); } void new_arrays(double *x, double *y,int n){ spline = gsl_spline_alloc(gsl_interp_cspline,n); gsl_spline_init (spline, x, y, n); } }; //================================================================================================= // SORTING // // sorting algorithm // sort2 sorts first argument and then applies the sorted permutation to second list class sorter{ private: const gsl_rng_type * T; gsl_rng * r; public: sorter(){ gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); } ~sorter(){gsl_rng_free (r);} void sort(double *data, int n){ gsl_sort(data,1,n); } void sort2(double *data, int n, double *data2){ size_t p[n]; gsl_sort_index(p,data,1,n); gsl_permute(p,data2,1,n); } }; //================================================================================================= // ODE SOLVER // // Simple ODE integrator using Runge-Kutta Dormand-Prince 8 adaptive stepping // dy_i/dt = f_i(t) where int (*f)(double t, const double y, double f, void *params) class ode{ private: const gsl_odeiv2_step_type * T; gsl_odeiv2_step * s; gsl_odeiv2_control * c; gsl_odeiv2_evolve * e; gsl_odeiv2_system sys; int N;double h,eps; double direction; public: ode(int (*derivs)(double,const double *,double*,void*),int N,double eps, void *params=NULL):N(N),eps(eps){ sys.function=derivs;sys.jacobian=NULL;sys.dimension=N;sys.params=params; T = gsl_odeiv2_step_rk8pd;s = gsl_odeiv2_step_alloc (T, N); c = gsl_odeiv2_control_y_new (eps, 0.0);e = gsl_odeiv2_evolve_alloc (N); gsl_ieee_env_setup(); } ~ode(){ gsl_odeiv2_evolve_free(e); gsl_odeiv2_control_free(c); gsl_odeiv2_step_free(s); } void step(double tstart, double tfinish, double *y, double step){ h = step; direction = (h>0?1.:-1.); while ((tfinish-tstart)*direction>0){ int status = gsl_odeiv2_evolve_apply (e, c, s, &sys, &tstart, tfinish, &h, y); if (status != GSL_SUCCESS)break; } } }; //================================================================================================= // MINIMISER // // finds a minimum of a function of the form double(*func)(const gsl_vector *v, void *params) // using a downhill simplex algorithm. Setup minimiser with initial guesses and required tolerance // with constructor and then minimise with minimise(). class minimiser{ private: const gsl_multimin_fminimizer_type *T; ; gsl_multimin_fminimizer *s; gsl_vector *ss, *x; gsl_multimin_function minex_func; size_t iter; int status,N_params; double size; double eps; public: minimiser(double(*func)(const gsl_vector *v, void *params),double *parameters, int N, double *sizes, double eps):N_params(N), eps(eps){ T = gsl_multimin_fminimizer_nmsimplex2rand; ss = gsl_vector_alloc (N_params);x = gsl_vector_alloc (N_params); for(int i=0;i<N_params;i++){ gsl_vector_set (x, i, parameters[i]);gsl_vector_set(ss,i,sizes[i]);} minex_func.n = N; minex_func.f = func; minex_func.params = NULL; s = gsl_multimin_fminimizer_alloc (T, N_params); gsl_multimin_fminimizer_set (s, &minex_func, x, ss); status = 0; iter = 0; } ~minimiser(){ gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free (s); } double minimise(double *results,unsigned int maxiter,bool vocal){ do { iter++; status = gsl_multimin_fminimizer_iterate(s); if(status)break; size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, eps); if(vocal){ std::cout<<iter<<" "; for(int i=0; i<N_params;i++)std::cout<<gsl_vector_get(s->x,i)<<" "; std::cout<<s->fval<<" "<<size<<std::endl; } } while (status == GSL_CONTINUE && iter < maxiter); for(int i=0;i<N_params;i++){results[i] = gsl_vector_get(s->x,i);} return s->fval; } }; class minimiser1D{ private: const gsl_min_fminimizer_type *T; ; gsl_min_fminimizer *s; size_t iter; int status; double size; double m, a, b, eps; public: minimiser1D(double(*func)(double, void *params), double m, double a, double b, double eps) :m(m), a(a), b(b), eps(eps){ gsl_function F;F.function = func;F.params = 0; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc (T); gsl_min_fminimizer_set (s, &F, m, a, b); status = 0; iter = 0; } ~minimiser1D(){ gsl_min_fminimizer_free (s); } double minimise(unsigned int maxiter){ do { iter++; status = gsl_min_fminimizer_iterate(s); m = gsl_min_fminimizer_x_minimum (s); a = gsl_min_fminimizer_x_lower (s); b = gsl_min_fminimizer_x_upper (s); status = gsl_min_test_interval (a, b, eps, 0.0); } while (status == GSL_CONTINUE && iter < maxiter); return m; } }; /* double Distance(void *xp, void *yp){ double x = *((double *) xp); double y = *((double *) yp); return fabs(x - y); } void Step(const gsl_rng * r, void *xp, double step_size){ double old_x = *((double *) xp); double new_x; double u = gsl_rng_uniform(r); new_x = u * 2 * step_size - step_size + old_x; memcpy(xp, &new_x, sizeof(new_x)); } void Print(void *xp){ printf ("%12g", *((double *) xp)); } class sim_anneal{ private: const gsl_rng_type * T; gsl_rng * r; int N_TRIES, ITER_FIXED_T; double STEP_SIZE, K, T_INITIAL, MU_T, T_MIN; gsl_siman_params_t params; public: sim_anneal(int N_TRIES, int ITER_FIXED_T, double STEP_SIZE): N_TRIES(N_TRIES), ITER_FIXED_T(ITER_FIXED_T),STEP_SIZE(STEP_SIZE){ gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); //params[0]=N_TRIES;params[1]=ITER_FIZED_T;params[2]=STEP_SIZE; //K=1.; params[3]=K; T_INITIAL=0.008; params[4]=T_INITIAL; //MU_T=1.003; params[5]=MU_T; T_MIN=2.0e-6; params[6]=T_MIN; gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; } ~sim_anneal(){ gsl_rng_free(r); } double minimise(double(*func)(void *xp), double x){ double x_initial=x; gsl_siman_solve(r, &x_initial, &func, Step, Distance, Print, NULL, NULL, NULL, sizeof(double), params); return x_initial; } };*/ //================================================================================================= // SPECIAL FUNCTIONS // inline double erf(double x){return gsl_sf_erf (x);} inline double erfc(double x){return gsl_sf_erfc (x);} inline double besselI(double x, int n){return gsl_sf_bessel_In (n,x);} inline double besselJ(double x, int n){return gsl_sf_bessel_Jn (n,x);} inline double gamma(double x){return gsl_sf_gamma (x);} inline double ellint_first(double phi, double k){ return gsl_sf_ellint_F(phi,k,1e-15);} // F(\phi,k) = \int_0^\phi \d t \, \frac{1}{\sqrt{1-k^2\sin^2 t}} inline double ellint_second(double phi, double k){ return gsl_sf_ellint_E(phi,k,1e-15);} // E(\phi,k) = \int_0^\phi \d t \, \sqrt{1-k^2\sin^2 t} inline double ellint_third(double phi, double k, double n){ return gsl_sf_ellint_P(phi,k,n,1e-15);} // \Pi(\phi,k,n) = \int_0^\phi \d t \, \frac{1}{(1+n\sin^2 t)\sqrt{1-k^2\sin^2 t}} #endif
{ "alphanum_fraction": 0.6193124368, "avg_line_length": 32.2750582751, "ext": "h", "hexsha": "52b452f8fed9d6372c70bd7eb6e542d0ad6d5369", "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": "6a608a21651be37462e42289c0a15233b8e29bbb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlsanders/genfunc", "max_forks_repo_path": "new_struct/inc/GSLInterface.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6a608a21651be37462e42289c0a15233b8e29bbb", "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": "jlsanders/genfunc", "max_issues_repo_path": "new_struct/inc/GSLInterface.h", "max_line_length": 108, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6a608a21651be37462e42289c0a15233b8e29bbb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlsanders/genfunc", "max_stars_repo_path": "new_struct/inc/GSLInterface.h", "max_stars_repo_stars_event_max_datetime": "2019-10-14T01:06:54.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-12T13:24:27.000Z", "num_tokens": 3989, "size": 13846 }
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #pragma once #include <gsl/gsl-lite.hpp> #include <nlohmann/json.hpp> // Used by most unit test files. #include <folly/portability/GTest.h> // Used throughout the codebase #include <folly/SharedMutex.h> #include <folly/Synchronized.h> // MB-46844: // Included by collections/vbucket_manifest.h, which in turn included // by 50+ other files. // Consider changing collections/vbucket_manifest.h to use pimpl for // Manifest::map which would avoid the need to include F14Map.h. #include <folly/container/F14Map.h> #include <map> #include <string>
{ "alphanum_fraction": 0.7387198321, "avg_line_length": 29.78125, "ext": "h", "hexsha": "274bcb3ddfe9a3e9885191a2169f15516c2f72c2", "lang": "C", "max_forks_count": 71, "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z", "max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_forks_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_forks_repo_name": "nawazish-couchbase/kv_engine", "max_forks_repo_path": "precompiled_headers.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z", "max_issues_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_issues_repo_name": "nawazish-couchbase/kv_engine", "max_issues_repo_path": "precompiled_headers.h", "max_line_length": 78, "max_stars_count": 104, "max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd", "max_stars_repo_licenses": [ "MIT", "BSD-3-Clause" ], "max_stars_repo_name": "nawazish-couchbase/kv_engine", "max_stars_repo_path": "precompiled_headers.h", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z", "num_tokens": 239, "size": 953 }