Search is not available for this dataset
text string | meta dict |
|---|---|
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <math.h>
#ifdef __INTEL_COMPILER
#include <mkl_cblas.h>
#else
#include <cblas.h>
#define kmp_set_blocktime(k)
#endif
static inline float minf (float a, float b) { return a < b ? a : b; }
static inline float maxf (float a, float b) { return a < b ? b : a; }
PyObject * compute_overlap (float bbx1, float bby1, float bbx2, float bby2,
int fdimy, int fdimx, int dimy, int dimx,
float scale, int pady, int padx, int h, int w) {
int im_area = h*w;
int bbox_area = (bbx2-bbx1)*(bby2-bby1);
int im_clip = ((double)bbox_area / (double)im_area) < 0.7;
npy_intp dims[2] = { dimy, dimx };
int x, y;
PyArrayObject * pyoverlap = (PyArrayObject*)PyArray_SimpleNew ((npy_intp)2, dims, NPY_FLOAT);
for (x = 0; x < dimx; ++x) {
for (y = 0; y < dimy; ++y) {
float x1 = (x - padx) * scale;
float y1 = (y - pady) * scale;
float x2 = x1 + fdimx*scale - 1;
float y2 = y1 + fdimy*scale - 1;
if (im_clip) {
x1 = minf(maxf(x1, 0.0f), w-1);
y1 = minf(maxf(y1, 0.0f), h-1);
x2 = minf(maxf(x2, 0.0f), w-1);
y2 = minf(maxf(y2, 0.0f), h-1);
}
float xx1 = maxf(x1, bbx1);
float yy1 = maxf(y1, bby1);
float xx2 = minf(x2, bbx2);
float yy2 = minf(y2, bby2);
float intw = xx2 - xx1 + 1;
float inth = yy2 - yy1 + 1;
if (intw > 0 && inth > 0) {
float filterw = x2 - x1 + 1;
float filterh = y2 - y1 + 1;
float filter_area = filterw*filterh;
float int_area = intw*inth;
float union_area = filter_area + bbox_area - int_area;
*(float*)PyArray_GETPTR2(pyoverlap, y, x) = int_area / union_area;
} else {
*(float*)PyArray_GETPTR2(pyoverlap, y, x) = 0;
}
}
}
return Py_BuildValue("N", pyoverlap);
}
#if 0
PyObject * objective_function (PyObject * pyexamples) {
int i;
int j;
int k;
for (i = 0; i < PyList_Size(pyexamples); ++i) {
PyObject * pyexample = PyList_GetItem (pyexamples, i);
if (!PyList_Check(pyexample)) {
PyErr_SetString(PyExc_TypeError, "example list elements must be list.");
return NULL;
}
for (j = 0; j < PyList_Size(pyexample); ++j) {
PyObject * pyentry = PyList_GetItem(pyexample, j);
if (!PyTuple_Check(pyentry)) {
PyErr_SetString(PyExc_TypeError, "entries must be tuples.");
return NULL;
}
if (PyTuple_Size(pyentry) != 2) {
PyErr_SetString(PyExc_TypeError, "entry tuples must be of size 2");
return NULL;
}
PyObject * pyfeatures = PyTuple_GetItem(pyentry, 0);
if (!PyDict_Check(pyfeatures)) {
PyErr_SetString(PyExc_TypeError, "features must be a dict");
return NULL;
}
PyObject * pyfeatureslist = PyDict_Items(pyfeatures);
float score = 0;
for (k = 0; k < PyDict_Size(pyfeatureslist); ++k) {
PyObject * pyfeature = PyList_GetItem(pyfeatureslist, k);
PyObject * pyblock = PyTuple_GetItem(pyfeature, 0);
PyObject * pyw = PyTuple_GetItem(pyfeature, 1);
if (!PyArray_Check(pyw)) {
PyErr_SetString(PyExc_TypeError, "w must be a numpy array");
return NULL;
}
PyArrayObject * pywarray = (PyArrayObject*)pyw;
}
PyObject * pydetection = PyTuple_GetItem(pyentry, 1);
}
}
return Py_BuildValue("i", 0);
}
PyObject * gradient (PyObject * examples, PyObject * gradients) {
Py_RETURN_NONE;
}
#endif
static PyObject * ComputeOverlap(PyObject * self, PyObject * args)
{
float x1, x2, y1, y2;
int fdimy, fdimx, dimy, dimx;
float scale;
int pady, padx;
int w, h;
if (!PyArg_ParseTuple(args, "ffffiiiifiiii", &x1, &y1, &x2, &y2, &fdimy, &fdimx, &dimy, &dimx, &scale, &pady, &padx, &h, &w))
return NULL;
return compute_overlap(x1, y1, x2, y2, fdimy, fdimx, dimy, dimx, scale, pady, padx, h, w);
}
#if 0
static PyObject * ObjectiveFunction (PyObject * self, PyObject * args) {
PyObject * pyexamples;
if (!PyArg_ParseTuple (args, "O!", &PyList_Type, &pyexamples)) {
return NULL;
}
return objective_function (pyexamples);
}
static PyObject * Gradient (PyObject * self, PyObject * args) {
PyObject * pyexamples;
PyObject * pygradients;
if (!PyArg_ParseTuple (args, "O!O!", &PyList_Type, &pyexamples, &PyDict_Type, &pygradients)) {
return NULL;
}
return gradient (pyexamples, pygradients);
}
#endif
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_train",
"Routines for training the DPM.",
-1,
NULL,
NULL,
NULL,
NULL,
NULL
};
#endif
#if PY_MAJOR_VERSION < 3
static PyMethodDef _train_methods[] = {
{"compute_overlap", ComputeOverlap, METH_VARARGS, "Compute detection overlaps with bbox."},
#if 0
{"ObjectiveFunction", ObjectiveFunction, METH_VARARGS, "WL-SSVM objective function."},
{"Gradient", Gradient, METH_VARARGS, "WL-SSVM gradient."},
#endif
{NULL}
};
#endif
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC
PyInit__train(void)
#else
PyMODINIT_FUNC
init_train(void)
#endif
{
import_array();
#if PY_MAJOR_VERSION >= 3
PyObject *m = PyModule_Create(&moduledef);
#else
Py_InitModule3("_train", _train_methods, "Compute detection overlaps with bbox.");
#endif
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
| {
"alphanum_fraction": 0.5689828802,
"avg_line_length": 28.7826086957,
"ext": "c",
"hexsha": "dd2656065d494b60a13a0697e645be124e8406b0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-04-30T07:30:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-08-20T14:21:54.000Z",
"max_forks_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kmatzen/pydro",
"max_forks_repo_path": "src/pydro/_train.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_issues_repo_issues_event_max_datetime": "2017-02-06T07:54:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-06T07:54:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "caomw/pydro",
"max_issues_repo_path": "src/pydro/_train.c",
"max_line_length": 130,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "00286cb99a58e4c49fe79b08d8ae041cf8ee173c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "caomw/pydro",
"max_stars_repo_path": "src/pydro/_train.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-24T01:25:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T23:41:08.000Z",
"num_tokens": 1692,
"size": 5958
} |
#include "stdio.h"
#include "gsl/gsl_integration.h"
#include "gsl/gsl_errno.h"
//include "limber.h"
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_sf_bessel.h>
// The integrated C_ell are in general allowed to be zero or negative if
// they describe cross-correlations. We use these statuses to describe
// errors where a log was requested also.
// LIMBER_STATUS_NEGATIVE is probably always an error
// but LIMBER_STATUS_ZERO is not necessarily
#define LIMBER_STATUS_OK 0
#define LIMBER_STATUS_ZERO 1
#define LIMBER_STATUS_NEGATIVE 2
#define LIMBER_STATUS_ERROR 3
// These are the options you can set for
// the Limber integrator.
typedef struct cl_config{
int n_ell; // Number of ell values you want in the spline
int * ell; // The chosen ell values you want
double prefactor; //Scaling prefactor
int status; // did everything go okay?
double delta_range_factor;
double log_nu_range;
double absolute_tolerance;
double relative_tolerance;
} cl_config;
int cl_integral(cl_config * config, gsl_spline * WX_red,
gsl_spline * WY_red, gsl_spline2d * P, gsl_spline * D_chi,
double * cl_out, double * cl_err_out); | {
"alphanum_fraction": 0.756568779,
"avg_line_length": 34.0526315789,
"ext": "h",
"hexsha": "3590a1ed3625484bc3d33c9c60c659ed4f857f7c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h",
"max_line_length": 72,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z",
"num_tokens": 356,
"size": 1294
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include "stats.h"
double ttest_equalvar(const double *data1, int n1, const double *data2, int n2)
{
double mean1, mean2, var1, var2, num, sp, denom, t, dof, p;
mean1 = gsl_stats_mean(data1, 1, n1);
mean2 = gsl_stats_mean(data2, 1, n2);
var1 = gsl_stats_variance(data1, 1, n1);
var2 = gsl_stats_variance(data2, 1, n2);
num = mean1 - mean2;
sp = sqrt((((n1 - 1) * var1) + ((n2 - 1) * var2)) / (n1 + n2 - 2));
denom = sp * sqrt((1 / (double) n1) + (1 / (double) n2));
t = fabs(num / denom);
dof = (double) n1 + n2 - 2;
p = (1 - gsl_cdf_tdist_P(t, dof)) * 2;
return p;
}
double ttest_unequalvar(const double *data1, int n1, const double *data2, int n2)
{
double mean1, mean2, var1, var2, r1, r2, t, dof, p;
mean1 = gsl_stats_mean(data1, 1, n1);
mean2 = gsl_stats_mean(data2, 1, n2);
var1 = gsl_stats_variance(data1, 1, n1);
var2 = gsl_stats_variance(data2, 1, n2);
r1 = var1 / n1;
r2 = var2 / n2;
// Compute t-statistic
t = fabs((mean1 - mean2) / sqrt(r1 + r2));
dof = pow(r1 + r2, 2) / ((pow(r1, 2) / (n1 - 1)) + (pow(r2, 2) / (n2 - 1)));
p = (1 - gsl_cdf_tdist_P(t, dof)) * 2;
return p;
}
double ttest_paired(const double *data1, const double *data2, int n)
{
double data[n];
double mean, sd, t, dof, p;
for (int i = 0; i < n; i++)
{
data[i] = data1[i] - data2[i];
}
p = ttest(data, n);
return p;
}
double ttest(const double *data, int n)
{
double mean, sd, t, dof, p;
mean = gsl_stats_mean(data, 1, n);
sd = gsl_stats_sd(data, 1, n);
t = fabs((mean - 0) / (sd / sqrt((double) n)));
dof = (double) n - 1;
p = (1 - gsl_cdf_tdist_P(t, dof)) * 2;
return p;
}
| {
"alphanum_fraction": 0.5708935259,
"avg_line_length": 29.6666666667,
"ext": "c",
"hexsha": "64ede97a8b59ee9d71617b4d68f6804fd999d90c",
"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": "96a89cf9ee32a074185ffce842a999975ba0de19",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kgoettler/python-c-ext",
"max_forks_repo_path": "python-c-api/v3/stats.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19",
"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": "kgoettler/python-c-ext",
"max_issues_repo_path": "python-c-api/v3/stats.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "96a89cf9ee32a074185ffce842a999975ba0de19",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kgoettler/python-c-ext",
"max_stars_repo_path": "python-c-api/v3/stats.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 717,
"size": 1869
} |
/* randist/wishart.c
*
* Copyright (C) 2017 Timothée Flutre
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sf_gamma.h>
/* Generate a random matrix from a Wishart distribution using the Bartlett
* decomposition, following Smith and Hocking, Journal of the Royal Statistical
* Society. Series C (Applied Statistics), Vol. 21, No. 3 (1972), pp. 341-345.
*
* df degrees of freedom
* L matrix resulting from the Cholesky decomposition of
* the scale matrix V = L L^T (dimension d x d)
* result output matrix (dimension d x d)
* work matrix used for intermediate computations (dimension d x d)
*/
int
gsl_ran_wishart (const gsl_rng * r,
const double df,
const gsl_matrix * L,
gsl_matrix * result,
gsl_matrix * work)
{
if (L->size1 != L->size2)
{
GSL_ERROR("L should be a square matrix", GSL_ENOTSQR);
}
else if (result->size1 != result->size2)
{
GSL_ERROR("result should be a square matrix", GSL_ENOTSQR);
}
else if (work->size1 != work->size2)
{
GSL_ERROR("work should be a square matrix", GSL_ENOTSQR);
}
else if (result->size1 != L->size1)
{
GSL_ERROR("incompatible dimensions of result matrix", GSL_EBADLEN);
}
else if (work->size1 != L->size1)
{
GSL_ERROR("incompatible dimensions of work matrix", GSL_EBADLEN);
}
else if (df <= L->size1 - 1)
{
GSL_ERROR("incompatible degrees of freedom", GSL_EDOM);
}
else
{
/* result: X = L A A^T L^T */
size_t d = L->size1, i, j;
/* insure the upper part of A is zero before filling its lower part */
gsl_matrix_set_zero(work);
for (i = 0; i < d; ++i)
{
gsl_matrix_set(work, i, i, sqrt(gsl_ran_chisq(r, df - i)));
for (j = 0; j < i; ++j)
{
gsl_matrix_set(work, i, j, gsl_ran_ugaussian(r));
}
}
/* compute L * A */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, 1.0,
L, work);
/* compute (L * A) * (L * A)^T */
gsl_blas_dsyrk(CblasUpper, CblasNoTrans, 1.0, work, 0.0, result);
for (i = 0; i < d; ++i)
{
for (j = 0; j < i; ++j)
{
gsl_matrix_set(result, i, j, gsl_matrix_get(result, j, i));
}
}
return GSL_SUCCESS;
}
}
/* Compute the log of the probability density function at a given quantile
* matrix for a Wishart distribution using the Cholesky decomposition of the
* scale matrix.
*
* X quantile matrix at which to evaluate the PDF (dimension d x d)
* L_X matrix resulting from the Cholesky decomposition of
* of the quantile matrix at which to evaluate the PDF
* X = L_X L_X^T (dimension d x d)
* df degrees of freedom
* L matrix resulting from the Cholesky decomposition of
* the scale matrix V = L L^T (dimension d x d)
* result output of the density (dimension 1)
* work matrix used for intermediate computations (dimension d x d)
*/
int
gsl_ran_wishart_log_pdf (const gsl_matrix * X,
const gsl_matrix * L_X,
const double df,
const gsl_matrix * L,
double * result,
gsl_matrix * work)
{
if (L->size1 != L->size2)
{
GSL_ERROR("L should be a square matrix", GSL_ENOTSQR);
}
else if (X->size1 != X->size2)
{
GSL_ERROR("X should be a square matrix", GSL_ENOTSQR);
}
else if (L_X->size1 != L_X->size2)
{
GSL_ERROR("L_X should be a square matrix", GSL_ENOTSQR);
}
else if (X->size1 != L->size1)
{
GSL_ERROR("incompatible dimensions of X matrix", GSL_EBADLEN);
}
else if (L_X->size1 != L->size1)
{
GSL_ERROR("incompatible dimensions of L_X matrix", GSL_EBADLEN);
}
else if (df <= L->size1 - 1)
{
GSL_ERROR("incompatible degrees of freedom", GSL_EDOM);
}
else
{
size_t d = L->size1, i;
int status;
double log_mv_Ga, log_det_V, log_det_X, tr_Vinv_X;
/* compute the log of the multivariate Gamma */
log_mv_Ga = d * (d-1) * 0.25 * log(M_PI);
for (i = 0; i < d; ++i)
{
log_mv_Ga += gsl_sf_lngamma((df - i + 1) * 0.5);
}
/* compute the log of the determinant of the scale matrix */
log_det_V = log(gsl_matrix_get(L, 0, 0));
for (i = 1; i < d; ++i)
{
log_det_V += log(gsl_matrix_get(L, i, i));
}
log_det_V = 2 * log_det_V;
/* compute the log of the determinant of the quantile matrix */
log_det_X = log(gsl_matrix_get(L_X, 0, 0));
for (i = 1; i < d; ++i)
{
log_det_X += log(gsl_matrix_get(L_X, i, i));
}
log_det_X = 2 * log_det_X;
/* compute the trace of V^(-1) X */
status = gsl_linalg_cholesky_solve_mat(L, X, work);
if (status)
return status;
tr_Vinv_X = gsl_matrix_get(work, 0, 0);
for (i = 1; i < d; ++i)
{
tr_Vinv_X += gsl_matrix_get(work, i, i);
}
/* add all to get the log of the PDF */
*result = - (0.5 * df * d) * log(2.0)
- (0.5 * df) * log_det_V
- log_mv_Ga
+ 0.5 * (df - d - 1) * log_det_X
- 0.5 * tr_Vinv_X;
return GSL_SUCCESS;
}
}
int
gsl_ran_wishart_pdf (const gsl_matrix * X,
const gsl_matrix * L_X,
const double df,
const gsl_matrix * L,
double * result,
gsl_matrix * work)
{
double logpdf;
int status = gsl_ran_wishart_log_pdf(X, L_X, df, L, &logpdf, work);
if (status == GSL_SUCCESS)
*result = exp(logpdf);
return status;
}
| {
"alphanum_fraction": 0.5782724057,
"avg_line_length": 30.6968325792,
"ext": "c",
"hexsha": "70facdf4b951fc5bd5e1c241cdaa12d805f38be7",
"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/randist/wishart.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/randist/wishart.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/randist/wishart.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": 1911,
"size": 6784
} |
static const char help[] =
"Solves doubly-nonlinear obstacle problems in 2D. Option prefix dnl_.\n"
"The PDE (interior condition) of such problems has solution u(x,y):\n"
" - div (u^q |grad(u+b)|^{p-2} grad(u+b)) = f\n"
"subject to a obstacle constraint\n"
" u >= psi\n"
"FIXME Includes the steady-state, nonlinear ice sheet problem in 2D in which u=H\n"
"is ice thickness, b is bed elevation, and s = H + b is surface elevation:\n"
" - div (D grad H) - div(W H^{n+2}) = m\n"
"The diffusivity D and pseudo-velocity W (Bueler, 2016) are from the\n"
"nonsliding shallow ice approximation (SIA) flux:\n"
" D = Gamma H^{n+2} |grad H + grad b|^{n-1}\n"
" W = - Gamma |grad H + grad b|^{n-1} grad b\n"
"The climatic mass balance f = m(x,y,H) is from one of two models.\n"
"Constants are n >= 1 and Gamma = 2 A (rho g)^n / (n+2) where A is the ice\n"
"softness. The domain is square (0,L)^2 with zero Dirichlet boundary conditions.\n"
"The equation is discretized by a Q1 structured-grid FVE method (Bueler, 2016).\n"
"Requires SNESVI (-snes_type vinewton{rsls|ssls}) because of constraint;\n"
"defaults to SSLS.\n\n";
/*
1. shows basic success with SSLS but DIVERGES AT LEVEL 4:
mpiexec -n 4 ./ice -ice_verif -snes_converged_reason -snes_grid_sequence LEV
2. consider making CMB model smooth
3. add CMB to dump and create plotting script (.py)
4. using exact init shows convergence depends strongly on eps for fine grids:
for LEV in 1 2 3 4 5; do ./ice -ice_verif -ice_exact_init -snes_converged_reason -ksp_type gmres -pc_type gamg -da_refine $LEV -ice_eps EPS; done
result:
(a) works at all levels if EPS=0.005; last KSP somewhat constant but SNES iters growing
(b) fails on level 3 if EPS=0.003,0.002
5. convergent and nearly optimal GMG in flops *but cheating with exact init*, and *avoiding -snes_grid_sequence* and *significant eps=0.01 regularization*:
for LEV in 1 2 3 4 5 6 7 8; do ./ice -ice_verif -ice_exact_init -snes_converged_reason -ksp_type gmres -pc_type mg -da_refine $LEV -snes_type vinewtonrsls -ice_eps 0.01; done
6. visualizing -snes_grid_sequence:
./ice -ice_verif -snes_grid_sequence 2 -ice_eps 0.005 -snes_converged_reason -snes_monitor_solution draw
(was -snes_grid_sequence bug with periodic BCs? see PETSc issue #300)
8. even seems to work in parallel:
mpiexec -n 4 ./ice -ice_verif -snes_grid_sequence 5 -ice_eps 0.005 -snes_converged_reason -snes_monitor_solution draw
9. same outcome with -ice_exact_init and -da_refine 5
mpiexec -n 4 ./ice -ice_verif -da_refine 5 -ice_eps 0.005 -snes_converged_reason -snes_monitor_solution draw -ice_exact_init
10. unpredictable response to changing -snes_linesearch_type bt|l2|basic (cp seems rarely to work)
*/
/* see comments on runtime stuff in icet/icet.c, the time-dependent version */
#include <petsc.h>
#include "icecmb.h"
typedef struct {
double secpera, // number of seconds in a year
L, // spatial domain is (0,L) x (0,L)
g, // acceleration of gravity
rho_ice, // ice density
n_ice, // Glen exponent for SIA flux term
A_ice, // ice softness
Gamma, // coefficient for SIA flux term
D0, // representative value of diffusivity (used in regularizing D)
eps, // regularization parameter for diffusivity D
delta, // dimensionless regularization for slope in SIA formulas
lambda; // amount of upwinding; lambda=0 is none and lambda=1 is "full"
PetscBool verif, // use dome formulas if true
check_admissible; // check admissibility at start of FormFunctionLocal()
CMBModel *cmb; // defined in cmbmodel.h
} AppCtx;
// compute radius from center of (0,L) x (0,L)
double radialcoord(double x, double y, AppCtx *user) {
const double xc = x - user->L/2.0,
yc = y - user->L/2.0;
return PetscSqrtReal(xc * xc + yc * yc);
}
double DomeCMB(double x, double y, AppCtx *user) {
const double domeR = 750.0e3, // radius of exact ice sheet (m)
domeH0 = 3600.0, // center thickness of exact ice sheet (m)
n = user->n_ice,
pp = 1.0 / n,
CC = user->Gamma * PetscPowReal(domeH0,2.0*n+2.0)
/ PetscPowReal(2.0 * domeR * (1.0-1.0/n),n);
double r, s, tmp1, tmp2;
r = radialcoord(x, y, user);
// avoid singularities at center and margin
if (r < 0.01)
r = 0.01;
if (r > domeR - 0.01)
r = domeR - 0.01;
s = r / domeR;
tmp1 = PetscPowReal(s,pp) + PetscPowReal(1.0-s,pp) - 1.0;
tmp2 = 2.0 * PetscPowReal(s,pp) + PetscPowReal(1.0-s,pp-1.0) * (1.0 - 2.0*s) - 1.0;
return (CC / r) * PetscPowReal(tmp1,n-1.0) * tmp2;
}
PetscErrorCode DomeThicknessLocal(DMDALocalInfo *info, double **aH, AppCtx *user) {
const double domeR = 750.0e3, // radius of exact ice sheet (m)
domeH0 = 3600.0, // center thickness of exact ice sheet (m)
n = user->n_ice,
mm = 1.0 + 1.0 / n,
qq = n / (2.0 * n + 2.0),
CC = domeH0 / PetscPowReal(1.0 - 1.0 / n,qq),
dx = user->L / (double)(info->mx-1),
dy = user->L / (double)(info->my-1);
double x, y, r, s, tmp;
int j, k;
PetscFunctionBeginUser;
for (k=info->ys; k<info->ys+info->ym; k++) {
y = k * dy;
for (j=info->xs; j<info->xs+info->xm; j++) {
x = j * dx;
r = radialcoord(x, y, user);
// avoid singularities at margin and center
if (r > domeR - 0.01)
aH[k][j] = 0.0;
else {
if (r < 0.01)
r = 0.01;
s = r / domeR;
tmp = mm * s - (1.0/n) + PetscPowReal(1.0-s,mm) - PetscPowReal(s,mm);
aH[k][j] = CC * PetscPowReal(tmp,qq);
}
}
}
PetscFunctionReturn(0);
}
extern PetscErrorCode SetFromOptionsAppCtx(AppCtx*);
extern PetscErrorCode FormBedLocal(DMDALocalInfo*, int, double**, AppCtx*);
extern PetscErrorCode FormBounds(SNES,Vec,Vec);
extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, double**, double**, AppCtx*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
DM da;
SNES snes;
KSP ksp;
Vec H;
AppCtx user;
CMBModel cmb;
PetscBool exact_init = PETSC_FALSE, // initialize using dome exact solution
dump = PETSC_FALSE; // dump state (H,b) in binary file ice_MXxMY.dat after solve
DMDALocalInfo info;
double **aH;
SNESConvergedReason reason;
int snesit,kspit;
PetscInitialize(&argc,&argv,(char*)0,help);
user.secpera = 31556926.0; // number of seconds in a year
user.L = 1800.0e3; // m; compare domeR=750.0e3 radius
user.g = 9.81; // m/s^2
user.rho_ice = 910.0; // kg/m^3
user.n_ice = 3.0; // Glen exponent
user.A_ice = 3.1689e-24; // 1/(Pa^3 s); EISMINT I value
user.D0 = 1.0; // m^2 / s
user.eps = 0.001;
user.delta = 1.0e-4;
user.lambda = 0.25;
user.verif = PETSC_FALSE;
user.check_admissible = PETSC_FALSE;
user.cmb = NULL;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"ice_","options to ice","");CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-A", "set value of ice softness A in units Pa-3 s-1",
"ice.c",user.A_ice,&user.A_ice,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool(
"-check_admissible", "check admissibility of iterate at start of residual evaluation FormFunctionLocal()",
"ice.c",user.check_admissible,&user.check_admissible,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-D0", "representative value of diffusivity (used in regularizing D) in units m2 s-1",
"ice.c",user.D0,&user.D0,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-delta", "dimensionless regularization for slope in SIA formulas",
"ice.c",user.delta,&user.delta,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool(
"-dump", "save final state (H, b)",
"ice.c",dump,&dump,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-eps", "dimensionless regularization for diffusivity D",
"ice.c",user.eps,&user.eps,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool(
"-exact_init", "initialize with dome exact solution",
"ice.c",exact_init,&exact_init,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-L", "side length of domain in meters",
"ice.c",user.L,&user.L,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-lambda", "amount of upwinding; lambda=0 is none and lambda=1 is full",
"ice.c",user.lambda,&user.lambda,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal(
"-n", "value of Glen exponent n",
"ice.c",user.n_ice,&user.n_ice,NULL);CHKERRQ(ierr);
if (user.n_ice <= 1.0) {
SETERRQ1(PETSC_COMM_WORLD,1,
"ERROR: n = %f not allowed ... n > 1.0 is required\n",user.n_ice);
}
ierr = PetscOptionsReal(
"-rho", "ice density in units kg m3",
"ice.c",user.rho_ice,&user.rho_ice,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool(
"-verif", "use dome exact solution for verification",
"ice.c",user.verif,&user.verif,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd();CHKERRQ(ierr);
// derived constant computed after other ice properties are set
user.Gamma = 2.0 * PetscPowReal(user.rho_ice*user.g,user.n_ice)
* user.A_ice / (user.n_ice+2.0);
ierr = SetFromOptions_CMBModel(&cmb,user.secpera);
user.cmb = &cmb;
// DMDA for the cell-centered grid
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,
DMDA_STENCIL_BOX,
5,5, PETSC_DECIDE,PETSC_DECIDE,
1, 1, // dof=1, stencilwidth=1
NULL,NULL,&da);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates
ierr = DMDASetUniformCoordinates(da,0.0,user.L,0.0,user.L,-1.0,-1.0);CHKERRQ(ierr);
ierr = DMSetApplicationContext(da, &user);CHKERRQ(ierr);
// create and configure the SNES to solve a NCP/VI at each step
ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
ierr = SNESSetDM(snes,da);CHKERRQ(ierr);
ierr = SNESSetApplicationContext(snes,&user);CHKERRQ(ierr);
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);
ierr = SNESSetType(snes,SNESVINEWTONSSLS); CHKERRQ(ierr);
ierr = SNESVISetComputeVariableBounds(snes,&FormBounds); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
// set up initial iterate
ierr = DMCreateGlobalVector(da,&H);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject)H,"H"); CHKERRQ(ierr);
if (exact_init) {
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,H,&aH); CHKERRQ(ierr);
ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da,H,&aH); CHKERRQ(ierr);
} else {
ierr = VecSet(H,0.0); CHKERRQ(ierr);
}
// solve
ierr = SNESSolve(snes,NULL,H); CHKERRQ(ierr);
ierr = SNESGetConvergedReason(snes,&reason); CHKERRQ(ierr);
if (reason <= 0) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"WARNING: SNES not converged ... use -snes_converged_reason to check\n"); CHKERRQ(ierr);
}
// get solution & DM on fine grid (which may have changed) after solve
ierr = VecDestroy(&H); CHKERRQ(ierr);
ierr = DMDestroy(&da); CHKERRQ(ierr);
ierr = SNESGetDM(snes,&da); CHKERRQ(ierr); /* do not destroy da */
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = SNESGetSolution(snes,&H); CHKERRQ(ierr); /* do not destroy H */
ierr = PetscObjectSetName((PetscObject)H,"H"); CHKERRQ(ierr);
// compute performance measures; note utility of reporting last grid,
// last snesit/kspit when doing -snes_grid_sequence
ierr = SNESGetIterationNumber(snes,&snesit); CHKERRQ(ierr); //
ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);
ierr = KSPGetIterationNumber(ksp,&kspit); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"done on %d x %d grid ... SNES iters = %d, last KSP iters = %d\n",
info.mx,info.my,snesit,kspit); CHKERRQ(ierr);
// dump state (H,b) if requested
if (dump) {
char filename[1024];
PetscViewer viewer;
Vec b;
double **ab;
ierr = VecDuplicate(H,&b); CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject)b,"b"); CHKERRQ(ierr);
if (user.verif) {
ierr = VecSet(b,0.0); CHKERRQ(ierr);
} else {
ierr = DMDAVecGetArray(da,b,&ab); CHKERRQ(ierr);
ierr = FormBedLocal(&info,0,ab,&user); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da,b,&ab); CHKERRQ(ierr);
}
ierr = sprintf(filename,"ice_%dx%d.dat",info.mx,info.my);
ierr = PetscPrintf(PETSC_COMM_WORLD,"writing PETSC binary file %s ...\n",filename); CHKERRQ(ierr);
ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr);
ierr = VecView(b,viewer); CHKERRQ(ierr);
ierr = VecView(H,viewer); CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr);
VecDestroy(&b);
}
// compute error in verification case
if (user.verif) {
Vec Hexact;
double infnorm, onenorm;
ierr = VecDuplicate(H,&Hexact); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,Hexact,&aH); CHKERRQ(ierr);
ierr = DomeThicknessLocal(&info,aH,&user); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da,Hexact,&aH); CHKERRQ(ierr);
ierr = VecAXPY(H,-1.0,Hexact); CHKERRQ(ierr); // H <- H + (-1.0) Hexact
VecDestroy(&Hexact);
ierr = VecNorm(H,NORM_INFINITY,&infnorm); CHKERRQ(ierr);
ierr = VecNorm(H,NORM_1,&onenorm); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"numerical errors: |H-Hexact|_inf = %.3f, |H-Hexact|_average = %.3f\n",
infnorm,onenorm/(double)(info.mx*info.my)); CHKERRQ(ierr);
}
SNESDestroy(&snes);
return PetscFinalize();
}
PetscErrorCode FormBedLocal(DMDALocalInfo *info, int stencilwidth, double **ab, AppCtx *user) {
int j,k,r,s;
const double dx = user->L / (double)(info->mx-1),
dy = user->L / (double)(info->my-1),
Z = PETSC_PI / user->L;
double x, y, b;
// vaguely-random frequencies and coeffs generated by fiddling; see randbed.py
const int nc = 4,
jc[4] = {1, 3, 6, 8},
kc[4] = {1, 3, 4, 7};
const double scalec = 750.0,
C[4][4] = { { 2.00000000, 0.33000000, -0.55020034, 0.54495520},
{ 0.50000000, 0.45014486, 0.60551833, -0.52250644},
{ 0.93812068, 0.32638429, -0.24654812, 0.33887052},
{ 0.17592361, -0.35496741, 0.22694547, -0.05280704} };
PetscFunctionBeginUser;
// go through owned portion of grid and compute b(x,y)
for (k = info->ys-stencilwidth; k < info->ys + info->ym+stencilwidth; k++) {
y = k * dy;
for (j = info->xs-stencilwidth; j < info->xs + info->xm+stencilwidth; j++) {
if (j < 0 || j >= info->mx-1 || k < 0 || k >= info->my-1)
continue;
x = j * dx;
// b(x,y) is sum of a few sines
b = 0.0;
for (r = 0; r < nc; r++) {
for (s = 0; s < nc; s++) {
b += C[r][s] * sin(jc[r] * Z * x) * sin(kc[s] * Z * y);
}
}
ab[k][j] = scalec * b;
}
}
PetscFunctionReturn(0);
}
// for call-back: tell SNESVI (variational inequality) that we want
// 0.0 <= H < +infinity
PetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = VecSet(Xl,0.0); CHKERRQ(ierr);
ierr = VecSet(Xu,PETSC_INFINITY); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// value of gradient at a point
typedef struct {
double x,y;
} Grad;
/* We factor the SIA flux as
q = - H^{n+2} sigma(|grad s|) grad s
where sigma is the slope-dependent part
sigma(z) = Gamma z^{n-1}.
Also
D = H^{n+2} sigma(|grad s|)
so that q = - D grad s. */
static double sigma(Grad gH, Grad gb, const AppCtx *user) {
const double sx = gH.x + gb.x,
sy = gH.y + gb.y,
slopesqr = sx * sx + sy * sy + user->delta * user->delta;
return user->Gamma * PetscPowReal(slopesqr,(user->n_ice-1.0)/2);
}
/* Pseudo-velocity from bed slope: W = - sigma * grad b. */
static Grad W(double sigma, Grad gb) {
Grad W;
W.x = - sigma * gb.x;
W.y = - sigma * gb.y;
return W;
}
/* DCS = diffusivity from the continuation scheme:
D(eps) = (1-eps) sigma H^{n+2} + eps D_0
so D(1)=D_0 and D(0)=sigma H^{n+2}. */
static double DCS(double sigma, double H, const AppCtx *user) {
return (1.0 - user->eps) * sigma * PetscPowReal(PetscAbsReal(H),user->n_ice+2.0)
+ user->eps * user->D0;
}
/* Flux component from the non-sliding SIA on a general bed. */
PetscErrorCode SIAflux(Grad gH, Grad gb, double H, double Hup, PetscBool xdir,
double *D, double *q, const AppCtx *user) {
const double mysig = sigma(gH,gb,user),
myD = DCS(mysig,H,user);
const Grad myW = W(mysig,gb);
PetscFunctionBeginUser;
if (D) {
*D = myD;
}
if (xdir && q) {
*q = - myD * gH.x + myW.x * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0);
} else {
*q = - myD * gH.y + myW.y * PetscPowReal(PetscAbsReal(Hup),user->n_ice+2.0);
}
PetscFunctionReturn(0);
}
// gradients of weights for Q^1 interpolant
static const double gx[4] = {-1.0, 1.0, 1.0, -1.0},
gy[4] = {-1.0, -1.0, 1.0, 1.0};
static double fieldatpt(double xi, double eta, double f[4]) {
// weights for Q^1 interpolant
double x[4] = { 1.0-xi, xi, xi, 1.0-xi},
y[4] = {1.0-eta, 1.0-eta, eta, eta};
return x[0] * y[0] * f[0] + x[1] * y[1] * f[1]
+ x[2] * y[2] * f[2] + x[3] * y[3] * f[3];
}
static double fieldatptArray(int u, int v, double xi, double eta, double **f) {
double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]};
return fieldatpt(xi,eta,ff);
}
static Grad gradfatpt(double xi, double eta, double dx, double dy, double f[4]) {
Grad gradf;
double x[4] = { 1.0-xi, xi, xi, 1.0-xi},
y[4] = {1.0-eta, 1.0-eta, eta, eta};
gradf.x = gx[0] * y[0] * f[0] + gx[1] * y[1] * f[1]
+ gx[2] * y[2] * f[2] + gx[3] * y[3] * f[3];
gradf.y = x[0] *gy[0] * f[0] + x[1] *gy[1] * f[1]
+ x[2] *gy[2] * f[2] + x[3] *gy[3] * f[3];
gradf.x /= dx;
gradf.y /= dy;
return gradf;
}
static Grad gradfatptArray(int u, int v, double xi, double eta, double dx, double dy,
double **f) {
double ff[4] = {f[v][u], f[v][u+1], f[v+1][u+1], f[v+1][u]};
return gradfatpt(xi,eta,dx,dy,ff);
}
// indexing of the 8 quadrature points along the boundary of the control volume in M*
// point s=0,...,7 is in element (j,k) = (j+je[s],k+ke[s])
static const int je[8] = {0, 0, -1, -1, -1, -1, 0, 0},
ke[8] = {0, 0, 0, 0, -1, -1, -1, -1},
ce[8] = {0, 3, 1, 0, 2, 1, 3, 2};
// direction of flux at 4 points in each element
static const PetscBool xdire[4] = {PETSC_TRUE, PETSC_FALSE, PETSC_TRUE, PETSC_FALSE};
// local (element-wise) coords of quadrature points for M*
static const double locx[4] = { 0.5, 0.75, 0.5, 0.25},
locy[4] = { 0.25, 0.5, 0.75, 0.5};
/* FormFunctionLocal = call-back by SNES using DMDA info.
Evaluates residual FF on local process patch:
FF_{j,k} = \int_{\partial V_{j,k}} \mathbf{q} \cdot \mathbf{n}
- m_{j,k} \Delta x \Delta y
where V_{j,k} is the control volume centered at (x_j,y_k).
Regarding indexing locations along the boundary of the control volume where
flux is evaluated, this figure shows the control volume centered at (x_j,y_k)
and the four elements it meets. Quadrature uses 8 points on the boundary of
the control volume, numbered s=0,...,7:
-------------------
| | |
| ..2..|..1.. |
| 3: | :0 |
k |--------- ---------|
| 4: | :7 |
| ..5..|..6.. |
| | |
-------------------
j
Regarding flux-component indexing on the element indexed by (j,k) node,
the value (aqquad[c])[k][j] for c=0,1,2,3 is an x-component at "*" and
a y-component at "%"; note (x_j,y_k) is lower-left corner:
-------------------
| : |
| *2 |
| 3 : 1 |
|....%.... ....%....|
| : |
| *0 |
| : |
@-------------------
(j,k)
*/
PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, double **aHin,
double **FF, AppCtx *user) {
PetscErrorCode ierr;
const double dx = user->L / (double)(info->mx-1),
dy = user->L / (double)(info->my-1);
// coefficients of quadrature evaluations along the boundary of the control volume in M*
const double coeff[8] = {dy/2, dx/2, dx/2, -dy/2, -dy/2, -dx/2, -dx/2, dy/2};
const PetscBool upwind = (user->lambda > 0.0);
const double upmin = (1.0 - user->lambda) * 0.5,
upmax = (1.0 + user->lambda) * 0.5;
int c, j, k, s;
double H, Hup, lxup, lyup, **aqquad[4], **ab, **aH, DSIA_ckj, qSIA_ckj,
M, x, y;
Grad gH, gb;
Vec qquad[4], Hcopy, b;
PetscFunctionBeginUser;
// copy and set boundary conditions to zero
ierr = DMGetLocalVector(info->da, &Hcopy); CHKERRQ(ierr);
ierr = DMDAVecGetArray(info->da,Hcopy,&aH); CHKERRQ(ierr);
for (k = info->ys-1; k <= info->ys + info->ym; k++) {
for (j = info->xs-1; j <= info->xs + info->xm; j++) {
if (j < 0 || j > info->mx-1 || k < 0 || k > info->my-1)
continue;
if (user->check_admissible && aHin[k][j] < 0.0) {
SETERRQ3(PETSC_COMM_WORLD,1,
"ERROR: non-admissible value H[k][j] = %.3e < 0.0 at j,k = %d,%d\n",
aHin[k][j],j,k);
}
if (j == 0 || j == info->mx-1 || k == 0 || k == info->my-1) {
if (j >= info->xs && j < info->xs+info->xm && k >= info->ys && k < info->ys+info->ym)
FF[k][j] = aHin[k][j]; // FIXME scaling?
aH[k][j] = 0.0;
} else
aH[k][j] = aHin[k][j];
}
}
// get bed elevation b(x,y) on this grid
ierr = DMGetLocalVector(info->da, &b); CHKERRQ(ierr);
ierr = DMDAVecGetArray(info->da,b,&ab); CHKERRQ(ierr);
if (user->verif) {
ierr = VecSet(b,0.0); CHKERRQ(ierr);
} else {
ierr = FormBedLocal(info,1,ab,user); CHKERRQ(ierr); // get stencil width
}
// working space for fluxes; see text for face location of flux evaluation
for (c = 0; c < 4; c++) {
ierr = DMGetLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr);
ierr = DMDAVecGetArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr);
}
// loop over locally-owned elements, including ghosts, to get fluxes q at
// c = 0,1,2,3 points in element; note start at (xs-1,ys-1)
for (k = info->ys-1; k < info->ys + info->ym; k++) {
for (j = info->xs-1; j < info->xs + info->xm; j++) {
if (j < 0 || j >= info->mx-1 || k < 0 || k >= info->my-1)
continue;
for (c=0; c<4; c++) {
H = fieldatptArray(j,k,locx[c],locy[c],aH);
gH = gradfatptArray(j,k,locx[c],locy[c],dx,dy,aH);
gb = gradfatptArray(j,k,locx[c],locy[c],dx,dy,ab);
if (upwind) {
if (xdire[c] == PETSC_TRUE) {
lxup = (gb.x <= 0.0) ? upmin : upmax;
lyup = locy[c];
} else {
lxup = locx[c];
lyup = (gb.y <= 0.0) ? upmin : upmax;
}
Hup = fieldatptArray(j,k,lxup,lyup,aH);
} else
Hup = H;
ierr = SIAflux(gH,gb,H,Hup,xdire[c],
&DSIA_ckj,&qSIA_ckj,user); CHKERRQ(ierr);
aqquad[c][k][j] = qSIA_ckj;
}
}
}
// loop over nodes, not including ghosts, to get function F(H) from quadature over
// s = 0,1,...,7 points on boundary of control volume (rectangle) around node
for (k=info->ys; k<info->ys+info->ym; k++) {
for (j=info->xs; j<info->xs+info->xm; j++) {
if (j == 0 || j == info->mx-1 || k == 0 || k == info->my-1)
continue;
// climatic mass balance
if (user->verif) {
x = j * dx;
y = k * dy;
M = DomeCMB(x,y,user);
} else {
M = M_CMBModel(user->cmb,ab[k][j] + aH[k][j]); // s=b+H is surface elevation
}
FF[k][j] = - M * dx * dy;
// now add integral over control volume boundary using two
// quadrature points on each side
for (s=0; s<8; s++)
FF[k][j] += coeff[s] * aqquad[ce[s]][k+ke[s]][j+je[s]];
}
}
// restore working space and bed
for (c = 0; c < 4; c++) {
ierr = DMDAVecRestoreArray(info->da,qquad[c],&(aqquad[c])); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(info->da, &(qquad[c])); CHKERRQ(ierr);
}
ierr = DMDAVecRestoreArray(info->da,Hcopy,&aH); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(info->da, &Hcopy); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(info->da,b,&ab); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(info->da, &b); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.5695725707,
"avg_line_length": 41.164556962,
"ext": "c",
"hexsha": "be1ff68643a943e795c9722f978cfa6fcdeca696",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch12/dnl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch12/dnl.c",
"max_line_length": 178,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch12/dnl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8391,
"size": 26016
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#define RND gsl_rng_uniform(r)
double gsl_ran_gaussian(const gsl_rng *r, double sigma);
double gsl_ran_gaussian_pdf(double x, double sigma);
double gsl_ran_beta_pdf(double x, double a, double b);
double gsl_ran_flat(const gsl_rng *r, double a, double b);
double gsl_ran_flat_pdf(double x, double a, double b);
unsigned int gsl_ran_binomial(const gsl_rng * r, double p, unsigned int n);
double mean_int(int array[], int array_size) {
double avg = 0;
int h;
for (h=0; h<array_size; h++) {
avg += array[h];
}
avg /= array_size;
return avg;
}
// double ABC_distance_BLR(double y[], double y_s[], int size_data) {
// double dist = 0;
// int k;
// for (k=0; k<size_data; k++) {
// dist += (y[k] - y_s[k]) * (y[k] - y_s[k]);
// }
// return dist;
// }
// double prior(int l, double theta_star, double a, double b) {
// double res;
// if (l==0) {
// res = gsl_ran_flat_pdf(theta_star, a, b);
// return res;
// }
// if (l==1) {
// res = gsl_ran_flat_pdf(theta_star, a, b);
// return res;
// }
// else {return -1;}
// }
double prior_BB(double theta_star, double a, double b) {
double res;
res = gsl_ran_beta_pdf(theta_star, a, b);
return res;
}
// double sort(double number[], int n) {
// int i, j;
// double a;
// for (i = 0; i < n; i++) {
// for (j = i + 1; j < n; j++) {
// if (number[i] > number[j]) {
// a = number[i];
// number[i] = number[j];
// number[j] = a;
// }
// }
// }
// return 0;
// }
int select_particle(double *weights, double *theta, int time, int n_particles, const gsl_rng *r) {
FILE * w_theta;
char weights_theta[500];
double r2;
double aux = 0.;
int i = 0;
int indicator = -1;
double* theta_vec;
theta_vec = malloc((n_particles) * sizeof(double*));
sprintf(weights_theta, "w_theta_time_%d_part_%d.txt", time, n_particles);
w_theta = fopen(weights_theta, "r");
if (w_theta == NULL) {
printf("File %s not found!!!\n", weights_theta);
return 1;
}
fscanf(w_theta, "%*[^\n]");
r2 = RND;
for (i=0; i<n_particles; i++) {
fscanf(w_theta, "%lf %lf", &weights[i], &theta_vec[i]);
aux += weights[i];
if (r2 > aux && indicator < 0) {
*theta = theta_vec[i];
indicator = 1;
}
}
// for (i=0; i<n_particles; i++) {
// fscanf(w_theta, "%lf %lf", &weights[i], &theta_vec[i]);
// aux += weights[i];
// if (r2<aux) {
// if (i_th<0) {
// i_th = i;
// }
// }
// }
fclose(w_theta);
free(theta_vec);
return 0;
}
void calculate_weight_BB(double *weight, double *weights, double theta, double theta_star, int n_particles, double a0, double b0, double std_ker) {
// Calculates the new weights for the successive ABC round
int i;
double tot_prior_pdf = 1.;
double kernel_value_pdf[n_particles];
for (i=0; i<n_particles; i++) {kernel_value_pdf[i] = 1.;}
tot_prior_pdf *= prior_BB(theta_star, a0, b0);
double denominator = 0.;
for (i=0; i<n_particles; i++) {
kernel_value_pdf[i] *= gsl_ran_gaussian_pdf(theta_star - theta, std_ker);
denominator += weights[i] * kernel_value_pdf[i];
}
*weight = tot_prior_pdf/(float)(denominator);
}
int ker_perturb(double *theta_star, const gsl_rng *r, double theta, double a0, double b0, double std_ker) {
//Perturb the i_th parameter theta via a gaussian kernel with std = std_ker
*theta_star = gsl_ran_gaussian(r, std_ker) + theta;
//If the prior on theta_star[l] is zero when calculated in theta_star[l],
//the new particle is rejected and we start over
if (prior_BB(*theta_star, a0, b0) == 0.) {
return 1;
}
return 0;
}
int read_threshold(double* epsilon_t, int time) {
FILE * epsilon;
char epsilon_file[500];
sprintf(epsilon_file, "epsilon_%d.txt", time);
epsilon = fopen(epsilon_file, "r");
if (epsilon == NULL) {
printf("File %s not found!!!\n", epsilon_file);
return 1;
}
fscanf(epsilon, "%lf", epsilon_t);
fclose(epsilon);
return 0;
}
// Distance function equal to zero for sample to be accepted
int verify_par_BB(double theta_star, double mean_y, const gsl_rng *r, int size_data, int n, double epsilon_t, int time, int seed) {
int k;
int g[size_data];
double mean_g;
for (k=0; k<size_data; k++) {g[k] = gsl_ran_binomial(r, theta_star, n);}
mean_g = mean_int(g, size_data);
printf("mean g: %f\nmean_y: %f\nepsilon_t: %f\n\n", mean_g, mean_y, epsilon_t);
if ( fabs(mean_g - mean_y) <= epsilon_t ) {
FILE* epsilon_file;
char epsilon_char[500];
sprintf(epsilon_char, "epsilon_%d_%d.txt", time+1, seed);
epsilon_file = fopen(epsilon_char, "w");
fprintf(epsilon_file, "%f", fabs(mean_g - mean_y));
fclose(epsilon_file);
return 0;
}
return 1;
}
void write_particles_BB(double theta_star, int time, int seed, int striding_size, double weight) {
// Writes ABC particles on file
FILE *output_file;
char output_char[500];
sprintf(output_char, "w_theta_time_%d_%d.txt", time+1, 1+(seed-1)/striding_size);
output_file = fopen(output_char, "a");
fprintf(output_file, "%.10f %.5f\n", weight, theta_star);
fclose(output_file);
}
int import_data_BB(int *y, int size_data) {
// Import data for beta-binomial model
int d;
FILE *file_data;
char file_name[500];
sprintf(file_name, "data_bb.txt");
file_data = fopen("data_bb.txt", "r");
if (file_data == NULL) {
return 1;
}
for (d=0; d<size_data; d++) {
fscanf(file_data, "%d", &y[d]);
}
fclose(file_data);
return 0;
}
void write_epsilon(double distance, int time, int seed, int striding_size) {
// Write epsilon for successive ABC round to file
FILE *epsilon_;
char eps_char[500];
sprintf(eps_char, "epsilon_%d_%d.txt", time+1, 1+(seed-1)/striding_size);
epsilon_ = fopen(eps_char, "a");
fprintf(epsilon_, "%f\n", distance);
fclose(epsilon_);
}
int read_epsilon_3d(double *eps_t, int time) {
// Read 3d epsilon
FILE *epsilon_;
char eps_char[500];
sprintf(eps_char, "epsilon_%d.txt", time);
epsilon_ = fopen(eps_char, "r");
if (epsilon_ == NULL) {
return 1;
}
fscanf(epsilon_, "%lf %lf %lf", &eps_t[0], &eps_t[1], &eps_t[2]);
fclose(epsilon_);
return 0;
}
void write_epsilon_3d(double *distance, int time, int seed, int striding_size) {
FILE *epsilon_;
char eps_char[500];
sprintf(eps_char, "epsilon_%d_%d.txt", time+1, 1+(seed-1)/striding_size);
epsilon_ = fopen(eps_char, "a");
fprintf(epsilon_, "%f %f %f\n", distance[0], distance[1], distance[2]);
fclose(epsilon_);
}
| {
"alphanum_fraction": 0.6190266137,
"avg_line_length": 24.1170212766,
"ext": "h",
"hexsha": "2bdf4da9db9a405d97ca380541c34390613b2f50",
"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": "137dd743498c3ff554d971d83f0ade4045049d0a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "espoma/Data_Science",
"max_forks_repo_path": "bb_model/bb_smc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a",
"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": "espoma/Data_Science",
"max_issues_repo_path": "bb_model/bb_smc.h",
"max_line_length": 148,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "espoma/Data_Science",
"max_stars_repo_path": "bb_model/bb_smc.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-28T09:06:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-27T12:57:31.000Z",
"num_tokens": 2005,
"size": 6801
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "BaseFeatureMatcher.h"
#include "OnlineBow.h"
#include <gsl\gsl>
#include <unordered_map>
namespace mage
{
class Keyframe;
class OnlineBowFeatureMatcher : public BaseFeatureMatcher
{
public:
OnlineBowFeatureMatcher(const OnlineBow& onlineBow, const Id<Keyframe>& id, gsl::span<const ORBDescriptor> features);
virtual size_t QueryFeatures(const ORBDescriptor& descriptor, std::vector<ptrdiff_t>& matches) const override;
virtual const Id<Keyframe>& GetId() const override;
private:
// a Map of NodeId <==> the indexes of the features which are assigned to the Node.
std::unordered_map<ptrdiff_t, std::vector<ptrdiff_t>> m_featureMap;
const OnlineBow& m_onlineBow;
const Id<Keyframe> m_id;
};
} | {
"alphanum_fraction": 0.7069555302,
"avg_line_length": 28.2903225806,
"ext": "h",
"hexsha": "d6a53ab9a6cc761cddabe95557a3938c9088d405",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h",
"max_line_length": 125,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Core/MAGESLAM/Source/BoW/OnlineBowFeatureMatcher.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 202,
"size": 877
} |
#ifndef __SPATIAL_STATISTICS_H__
#define __SPATIAL_STATISTICS_H__
#include <cmath>
#include <gsl/gsl_sf_bessel.h>
extern "C" double gsl_sf_gamma(const double);
extern "C" double gsl_sf_hyperg_1F1(double, double, double);
template <typename T> struct Spatial_Statistics
{
private:
T phi, nu;
T con;
int d;
public:
Spatial_Statistics(T phi, T nu, int dim)
{
this->phi = phi;
this->nu = nu;
// this->alpha = alpha;
this->d = dim;
con = pow(2, (nu - 1)) * tgamma(nu);
con = 1.0 / con;
// c1 = pow(h / sigma, d) / pow(sigma, alpha);
// c2 = -pow(2.0, alpha) * gsl_sf_gamma((alpha + (T)d) / 2) / pow(M_PI, (T)d / 2) / gsl_sf_gamma((T)d / 2);
}
// T G(T x) const
//{
// return c2 * gsl_sf_hyperg_1F1((alpha + (T)d) / 2, (T)d / 2, -x * x);
//}
T operator()(T *pt_x, T *pt_y) const
{
T diff = 0.0;
for (int i = 0; i < d; i++)
diff += (pt_x[i] - pt_y[i]) * (pt_x[i] - pt_y[i]);
T dist = sqrt(diff);
dist = 4.0 * sqrt(2.0 * nu) * (dist / phi);
if (dist == 0.0)
{
return 1.0;
}
else
{
return con * pow(dist, nu) * gsl_sf_bessel_Knu(nu, dist);
}
}
};
template <typename T> struct MaternKernel
{
private:
T h, sigma, alpha;
T c1, c2;
int d;
public:
MaternKernel(T h, T sigma, T alpha, int dim)
{
this->h = h;
this->sigma = sigma;
this->alpha = alpha;
this->d = dim;
c1 = pow(h / sigma, d) / pow(sigma, alpha);
c2 = -pow(2.0, alpha) * gsl_sf_gamma((alpha + (T)d) / 2.0) / pow(M_PI, (T)d / 2.0) / gsl_sf_gamma((T)d / 2.0);
}
T G(T x) const
{
return c2 * gsl_sf_hyperg_1F1((alpha + (T)d) / 2.0, (T)d / 2.0, -x * x);
}
T operator()(T *pt_x, T *pt_y) const
{
T diff = 0.0;
for (int i = 0; i < d; i++)
diff += (pt_x[i] - pt_y[i]) * (pt_x[i] - pt_y[i]);
T dist = sqrt(diff);
return c1 * G(dist / sigma);
}
};
#endif
| {
"alphanum_fraction": 0.4823977165,
"avg_line_length": 22.847826087,
"ext": "h",
"hexsha": "7a4740ba493ab46fb1d67b8a770d04220fe73566",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-15T10:28:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-25T03:44:15.000Z",
"max_forks_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ecrc/h2opus",
"max_forks_repo_path": "examples/spatialstatistics/spatial_statistics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4",
"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": "ecrc/h2opus",
"max_issues_repo_path": "examples/spatialstatistics/spatial_statistics.h",
"max_line_length": 118,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "c75d74cc96d728c11b7bf0f291ba71dc369a89f4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ecrc/h2opus",
"max_stars_repo_path": "examples/spatialstatistics/spatial_statistics.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-25T18:47:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-09T14:26:56.000Z",
"num_tokens": 736,
"size": 2102
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h> // high level interface to blas
#include <gsl/gsl_linalg.h> // lapack
void print_matrix(gsl_matrix* m, int nx, int ny);
int main (void) {
int i, j;
int signum = 0;
double determinant_m = 0.0;
gsl_permutation *m_LU_permutation = gsl_permutation_alloc(8);
gsl_matrix *m_test = gsl_matrix_alloc(8, 8);
gsl_matrix *m_original = gsl_matrix_alloc(8,8);
gsl_matrix *m_inverted = gsl_matrix_alloc(8,8);
/*for (i = 0; i < 8; i++){
for(j = 0; j < 8; j++){
gsl_matrix_set(m_test, i, j, 1);
}
}*/
gsl_matrix_set(m_test, 0, 7, 1);
gsl_matrix_set(m_test, 7,0, 1);
gsl_matrix_set(m_test, 3,2, 5);
gsl_matrix_set(m_test, 5,2, 5);
for( i = 0; i < 8; i++){
gsl_matrix_set(m_test, i, i, 3);
}
// set the oritinal one too
gsl_matrix_memcpy(m_original, m_test);
// now print the matrix out
//print_matrix(m_test, 8, 8);
printf("\n");
print_matrix(m_original, 8,8);
// simple matrix operations
//gsl_matrix_add(m_test, m_test);
//gsl_matrix_add_constant(m_test, 1.05);
//print_matrix(m_test, 8,8);
// creates the lu decomp of the matrix
// need to allocate the permutation
gsl_linalg_LU_decomp(m_test, m_LU_permutation, &signum);
// calculate the determinant of m_test from the lu
determinant_m = gsl_linalg_LU_det(m_test, signum);
printf("det_m = %g\n", determinant_m);
// invert the matrix
gsl_linalg_LU_invert(m_test, m_LU_permutation, m_inverted);
// multiply the inverse and the matrix together (can't use the LU one bc it's fucked up)
// m_test should be I
gsl_blas_dgemm( CblasNoTrans,CblasNoTrans , 1.0, m_original, m_inverted, 0.0, m_test);
print_matrix(m_test, 8,8);
gsl_permutation_free(m_LU_permutation);
gsl_matrix_free(m_inverted);
gsl_matrix_free(m_test);
return(0);
}
void print_matrix(gsl_matrix* m, int nx, int ny){
int i,j;
for(i = 0; i < nx; i++){
for(j= 0; j < ny; j++){
printf("%g ", gsl_matrix_get(m, i, j));
}
printf("\n");
}
}
| {
"alphanum_fraction": 0.6860522425,
"avg_line_length": 24.743902439,
"ext": "c",
"hexsha": "e96cfcdf5d65f3235d99871d43cc6266920fb6ba",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/test/array-test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/test/array-test.c",
"max_line_length": 90,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/test/array-test.c",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 696,
"size": 2029
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
// convex hull is obtained as cvh(n_bin[0],...,n_bin[end])
// inputs are y = Ef(x). x:n_data by 4, y:n_data by 1
void obtain_convex_h_Nd(int n_data, double *ef2cvh, int *x, double *y, int Ndim, int *nCat_min, int *nCat_max, double *E0) {
int i, j, k, l, nid, id1, id2, ctr;
double tmp;
int convex_h_ids[n_data]; //preallocated, not all filled
double convex_h_x[n_data][Ndim]; //preallocated, not all filled
double convex_h_y[n_data]; //preallocated, not all filled
printf("Convex hull is created.\n");
printf("Input data\n");
printf("---------------------------\n");
printf(" nL nN nM nC nV Ef\n");
for (i=0;i<n_data;i++) {
for (j=0;j<Ndim;j++)
printf("%4d ",x[Ndim*i+j]);
printf(" % .4f\n",y[i]);
}
printf("---------------------------\n");
// calculate the gradient and find Ndim base convex hull points
double dEdx[n_data][Ndim];
double dx[n_data][Ndim];
for (i=0;i<n_data;i++) {
printf("%d-data:%d,%d,%d,%d,%d, dE/dx=[",i,x[i*Ndim],x[i*Ndim+1],x[i*Ndim+2],x[i*Ndim+3],x[i*Ndim+4]);
for (j=0;j<Ndim;j++) {
dx[i][j] = (double) (nCat_max[j]-x[i*Ndim+j])*1.0/(nCat_max[j]-nCat_min[j]);
if (dx[i][j] == 0.0) // case of convex hull
dEdx[i][j] = 0.0;
else
dEdx[i][j] = (E0[j]-y[i]) / dx[i][j];
printf("% .2e ",dEdx[i][j]);
}
printf("]\n");
}
// check if the point is the convex hull
int ctr_set[Ndim];
nid = 0;
for (i=0;i<n_data;i++) {
if (dx[i][j] == 0.0) {
convex_h_ids[nid] = i;
for (j=0;j<Ndim;j++)
convex_h_x[nid][j] = (double) x[i*Ndim+j]*1.0;
convex_h_y[nid] = y[i];
nid++;
continue;
}
for (k=0;k<Ndim;k++) {
ctr_set[k] = 1;
for (j=0;j<n_data;j++) {
if (j==i)
continue;
if (dEdx[j][k] < dEdx[i][k]) {
ctr_set[k] = 0;
break;
}
}
}
ctr = 0;
for (k=0;k<Ndim;k++)
ctr += ctr_set[k];
if (ctr > 0) {
convex_h_ids[nid] = i;
for (j=0;j<Ndim;j++)
convex_h_x[nid][j] = (double) x[i*Ndim+j]*1.0;
convex_h_y[nid] = y[i];
nid++;
}
}
printf("%d cvh points were identified.\n",nid);
for (i=0;i<nid;i++) {
printf("%d ",convex_h_ids[i]);
for (j=0;j<Ndim;j++)
printf("%f ",convex_h_x[i][j]);
printf("%f\n",convex_h_y[i]);
}
// A*c = b
gsl_matrix * A = gsl_matrix_alloc (Ndim,Ndim);
gsl_matrix * V = gsl_matrix_alloc (Ndim,Ndim);
gsl_vector * S = gsl_vector_alloc (Ndim);
gsl_vector * work = gsl_vector_alloc (Ndim);
gsl_vector * b = gsl_vector_alloc (Ndim);
gsl_vector * c = gsl_vector_alloc (Ndim);
double dij2[nid];
int ids[nid];
double ef_cvh;
for (i=0;i<n_data;i++) {
for (j=0;j<nid;j++) {
dij2[j] = 0.0;
for (k=0;k<Ndim;k++) {
tmp = (double) x[i*Ndim+k]*1.0;
dij2[j] += pow(tmp - convex_h_x[j][k],2);
}
ids[j] = j;
}
sort_array_ids(dij2,ids,nid);
if (dij2[0]==0.0)
ef2cvh[i] = 0.0;
else {
for (j=0;j<Ndim;j++) {
for (k=0;k<Ndim;k++)
gsl_matrix_set (A,k,j,convex_h_x[ids[j]][k]);
gsl_vector_set(b,j,x[i*Ndim+j]*1.0);
}
gsl_linalg_SV_decomp(A, V, S, work);
gsl_linalg_SV_solve (A, V, S, b, c);
ef_cvh = 0.0;
for (j=0;j<Ndim;j++)
ef_cvh += gsl_vector_get(c,j)*convex_h_y[ids[j]];
ef2cvh[i] = y[i]-ef_cvh;
}
}
gsl_matrix_free(A);
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(b);
gsl_vector_free(c);
}
| {
"alphanum_fraction": 0.4643705463,
"avg_line_length": 29.0344827586,
"ext": "c",
"hexsha": "918e41ec94269ba67768c86534b181b5043ee65f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eunseok-lee/spin_atom_CE3",
"max_forks_repo_path": "src_data_to_corr_mat3/obtain_convex_h_Nd.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "eunseok-lee/spin_atom_CE3",
"max_issues_repo_path": "src_data_to_corr_mat3/obtain_convex_h_Nd.c",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eunseok-lee/spin_atom_CE3",
"max_stars_repo_path": "src_data_to_corr_mat3/obtain_convex_h_Nd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1349,
"size": 4210
} |
/* err/gsl_errno.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __GSL_ERRNO_H__
#define __GSL_ERRNO_H__
#include <stdio.h>
#include <errno.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
enum {
GSL_SUCCESS = 0,
GSL_FAILURE = -1,
GSL_CONTINUE = -2, /* iteration has not converged */
GSL_EDOM = 1, /* input domain error, e.g sqrt(-1) */
GSL_ERANGE = 2, /* output range error, e.g. exp(1e100) */
GSL_EFAULT = 3, /* invalid pointer */
GSL_EINVAL = 4, /* invalid argument supplied by user */
GSL_EFAILED = 5, /* generic failure */
GSL_EFACTOR = 6, /* factorization failed */
GSL_ESANITY = 7, /* sanity check failed - shouldn't happen */
GSL_ENOMEM = 8, /* malloc failed */
GSL_EBADFUNC = 9, /* problem with user-supplied function */
GSL_ERUNAWAY = 10, /* iterative process is out of control */
GSL_EMAXITER = 11, /* exceeded max number of iterations */
GSL_EZERODIV = 12, /* tried to divide by zero */
GSL_EBADTOL = 13, /* user specified an invalid tolerance */
GSL_ETOL = 14, /* failed to reach the specified tolerance */
GSL_EUNDRFLW = 15, /* underflow */
GSL_EOVRFLW = 16, /* overflow */
GSL_ELOSS = 17, /* loss of accuracy */
GSL_EROUND = 18, /* failed because of roundoff error */
GSL_EBADLEN = 19, /* matrix, vector lengths are not conformant */
GSL_ENOTSQR = 20, /* matrix not square */
GSL_ESING = 21, /* apparent singularity detected */
GSL_EDIVERGE = 22, /* integral or series is divergent */
GSL_EUNSUP = 23, /* requested feature is not supported by the hardware */
GSL_EUNIMPL = 24, /* requested feature not (yet) implemented */
GSL_ECACHE = 25, /* cache limit exceeded */
GSL_ETABLE = 26, /* table limit exceeded */
GSL_ENOPROG = 27, /* iteration is not making progress towards solution */
GSL_ENOPROGJ = 28, /* jacobian evaluations are not improving the solution */
GSL_ETOLF = 29, /* cannot reach the specified tolerance in F */
GSL_ETOLX = 30, /* cannot reach the specified tolerance in X */
GSL_ETOLG = 31, /* cannot reach the specified tolerance in gradient */
GSL_EOF = 32 /* end of file */
} ;
void gsl_error (const char * reason, const char * file, int line,
int gsl_errno);
void gsl_stream_printf (const char *label, const char *file,
int line, const char *reason);
const char * gsl_strerror (const int gsl_errno);
typedef void gsl_error_handler_t (const char * reason, const char * file,
int line, int gsl_errno);
typedef void gsl_stream_handler_t (const char * label, const char * file,
int line, const char * reason);
gsl_error_handler_t *
gsl_set_error_handler (gsl_error_handler_t * new_handler);
gsl_error_handler_t *
gsl_set_error_handler_off (void);
gsl_stream_handler_t *
gsl_set_stream_handler (gsl_stream_handler_t * new_handler);
FILE * gsl_set_stream (FILE * new_stream);
/* GSL_ERROR: call the error handler, and return the error code */
#define GSL_ERROR(reason, gsl_errno) \
do { \
gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \
return gsl_errno ; \
} while (0)
/* GSL_ERROR_VAL: call the error handler, and return the given value */
#define GSL_ERROR_VAL(reason, gsl_errno, value) \
do { \
gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \
return value ; \
} while (0)
/* GSL_ERROR_VOID: call the error handler, and then return
(for void functions which still need to generate an error) */
#define GSL_ERROR_VOID(reason, gsl_errno) \
do { \
gsl_error (reason, __FILE__, __LINE__, gsl_errno) ; \
return ; \
} while (0)
/* GSL_ERROR_NULL suitable for out-of-memory conditions */
#define GSL_ERROR_NULL(reason, gsl_errno) GSL_ERROR_VAL(reason, gsl_errno, 0)
/* Sometimes you have several status results returned from
* function calls and you want to combine them in some sensible
* way. You cannot produce a "total" status condition, but you can
* pick one from a set of conditions based on an implied hierarchy.
*
* In other words:
* you have: status_a, status_b, ...
* you want: status = (status_a if it is bad, or status_b if it is bad,...)
*
* In this example you consider status_a to be more important and
* it is checked first, followed by the others in the order specified.
*
* Here are some dumb macros to do this.
*/
#define GSL_ERROR_SELECT_2(a,b) ((a) != GSL_SUCCESS ? (a) : ((b) != GSL_SUCCESS ? (b) : GSL_SUCCESS))
#define GSL_ERROR_SELECT_3(a,b,c) ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_2(b,c))
#define GSL_ERROR_SELECT_4(a,b,c,d) ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_3(b,c,d))
#define GSL_ERROR_SELECT_5(a,b,c,d,e) ((a) != GSL_SUCCESS ? (a) : GSL_ERROR_SELECT_4(b,c,d,e))
#define GSL_STATUS_UPDATE(sp, s) do { if ((s) != GSL_SUCCESS) *(sp) = (s);} while(0)
__END_DECLS
#endif /* __GSL_ERRNO_H__ */
| {
"alphanum_fraction": 0.6737958909,
"avg_line_length": 38.3096774194,
"ext": "h",
"hexsha": "d0be1b9bbc7ccd29aea8b8d7d724e02d465284e9",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z",
"max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "gsl_subset/err/gsl_errno.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "gsl_subset/err/gsl_errno.h",
"max_line_length": 107,
"max_stars_count": 30,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "gsl_subset/err/gsl_errno.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 1609,
"size": 5938
} |
/*
* vbHmmGauss.c
* Model-specific core functions for VB-HMM-GAUSS.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2015
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.1.0
* Last modified on 2016.11.04
*/
#include "vbHmmGauss.h"
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <string.h>
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
static int isGlobalAnalysis = 0;
void setFunctions_gauss(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_gauss;
funcs.freeModelParameters = freeModelParameters_gauss;
funcs.newModelStats = newModelStats_gauss;
funcs.freeModelStats = freeModelStats_gauss;
funcs.initializeVbHmm = initializeVbHmm_gauss;
funcs.pTilde_z1 = pTilde_z1_gauss;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gauss;
funcs.pTilde_xn_zn = pTilde_xn_zn_gauss;
funcs.calcStatsVars = calcStatsVars_gauss;
funcs.maximization = maximization_gauss;
funcs.varLowerBound = varLowerBound_gauss;
funcs.reorderParameters = reorderParameters_gauss;
funcs.outputResults = outputResults_gauss;
setFunctions( funcs );
}
void setGFunctions_gauss(){
gCommonFunctions funcs;
funcs.newModelParameters = newModelParameters_gauss;
funcs.freeModelParameters = freeModelParameters_gauss;
funcs.newModelStats = newModelStats_gauss;
funcs.freeModelStats = freeModelStats_gauss;
funcs.newModelStatsG = newModelStatsG_gauss;
funcs.freeModelStatsG = freeModelStatsG_gauss;
funcs.initializeVbHmmG = initializeVbHmmG_gauss;
funcs.pTilde_z1 = pTilde_z1_gauss;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gauss;
funcs.pTilde_xn_zn = pTilde_xn_zn_gauss;
funcs.calcStatsVarsG = calcStatsVarsG_gauss;
funcs.maximizationG = maximizationG_gauss;
funcs.varLowerBoundG = varLowerBoundG_gauss;
funcs.reorderParametersG = reorderParametersG_gauss;
funcs.outputResultsG = outputResultsG_gauss;
setGFunctions( funcs );
isGlobalAnalysis = 1;
}
void outputResults_gauss( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputGaussResults( xn, gv, iv, logFP );
}
void outputResultsG_gauss( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
outputGaussResultsG( xns, gv, ivs, logFP );
}
void *newModelParameters_gauss( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
gaussParameters *p = (void*)malloc( sizeof(gaussParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
p->uAMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUAArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgA = (double **)malloc( sNo * sizeof(double*) );
p->avgLnA = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgA[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgMu = (double *)malloc( sNo * sizeof(double) );
p->avgLm = (double *)malloc( sNo * sizeof(double) );
p->avgLnLm = (double *)malloc( sNo * sizeof(double) );
p->uBtArr = (double *)malloc( sNo * sizeof(double) );
p->uMuArr = (double *)malloc( sNo * sizeof(double) );
p->uAArr = (double *)malloc( sNo * sizeof(double) );
p->uBArr = (double *)malloc( sNo * sizeof(double) );
p->btMu = (double *)malloc( sNo * sizeof(double) );
p->aLm = (double *)malloc( sNo * sizeof(double) );
p->bLm = (double *)malloc( sNo * sizeof(double) );
p->mu0 = (double *)malloc( sNo * sizeof(double) );
return p;
}
void freeModelParameters_gauss( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
gaussParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uAMat[i] );
}
free( gp->uAMat );
free( gp->sumUAArr );
free( gp->avgPi );
free( gp->avgLnPi );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgA[i] );
free( gp->avgLnA[i] );
}
free( gp->avgA );
free( gp->avgLnA );
free( gp->avgMu );
free( gp->avgLm );
free( gp->avgLnLm );
free( gp->uBtArr );
free( gp->uMuArr );
free( gp->uAArr );
free( gp->uBArr );
free( gp->btMu );
free( gp->aLm );
free( gp->bLm );
free( gp->mu0 );
free( *p );
*p = NULL;
}
void *newModelStats_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
gaussStats *s = (gaussStats*)malloc( sizeof(gaussStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }
s->Nii = (double *)malloc( sNo * sizeof(double) );
s->barX = (double *)malloc( sNo * sizeof(double) );
s->NiSi = (double *)malloc( sNo * sizeof(double) );
return s;
} else {
return NULL;
}
}
void freeModelStats_gauss( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
gaussStats *gs = *s;
int i;
free( gs->Ni );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs->Nii );
free( gs->barX );
free( gs->NiSi );
free( gs );
*s = NULL;
}
}
void *newModelStatsG_gauss( xns, gv, ivs)
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
gaussGlobalStats *gs = (gaussGlobalStats*)malloc( sizeof(gaussGlobalStats) );
int i;
gs->NiR = (double *)malloc( sNo * sizeof(double) );
gs->NijR = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); }
gs->NiiR = (double *)malloc( sNo * sizeof(double) );
gs->barXR = (double *)malloc( sNo * sizeof(double) );
gs->NiSiR = (double *)malloc( sNo * sizeof(double) );
gs->z1iR = (double *)malloc( sNo * sizeof(double) );
return gs;
}
void freeModelStatsG_gauss( gs, xns, gv, ivs )
void **gs;
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
gaussGlobalStats *ggs = *gs;
int i;
free( ggs->NiR );
for( i = 0 ; i < sNo ; i++ )
{ free( ggs->NijR[i] ); }
free( ggs->NijR );
free( ggs->NiiR );
free( ggs->barXR );
free( ggs->NiSiR );
free( ggs->z1iR );
free( *gs );
*gs = NULL;
}
void initializeVbHmm_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussData *d = xn->data;
size_t dLen = xn->N;
int sNo = gv->sNo;
gaussParameters *p = gv->params;
int i, j;
double totalX = 0.0, precX, varX = 0.0;
for( i = 0 ; i < dLen ; i++ ){
totalX += d->v[i];
}
double meanX = totalX / (double)dLen;
for( i = 0 ; i < dLen ; i++ ){
varX += pow(d->v[i] - meanX, 2.0);
}
varX /= (double)(dLen - 1);
precX = 1.0 / varX;
// hyper parameter for p( pi(i) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyper parameter for p( A(i,j) )
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( mu(k), lm(k) )
for( i = 0 ; i < sNo ; i++ ){
p->uBtArr[i] = 0.25;
p->uMuArr[i] = meanX;
p->uAArr[i] = 0.01 * varX;
p->uBArr[i] = 0.01;
}
initialize_indVars_gauss( xn, gv, iv );
calcStatsVars_gauss( xn, gv, iv );
maximization_gauss( xn, gv, iv );
}
void initializeVbHmmG_gauss( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussData *d;
size_t dLen, totalN;
int sNo = gv->sNo, rNo = xns->R;
gaussParameters *p = gv->params;
int i, j, r;
double totalX, precX, varX, meanX;
totalX = 0.0;
totalN = 0;
for( r = 0 ; r < rNo ; r++ ){
d = xns->xn[r]->data;
dLen = xns->xn[r]->N;
for( i = 0 ; i < dLen ; i++ ){
totalX += d->v[i];
}
totalN += dLen;
}
meanX = totalX / (double)totalN;
varX = 0.0;
for( r = 0 ; r < rNo ; r++ ){
d = xns->xn[r]->data;
dLen = xns->xn[r]->N;
for( i = 0 ; i < dLen ; i++ ){
varX += pow(d->v[i] - meanX, 2.0);
}
}
varX /= (double)(totalN - 1);
precX = 1.0 / varX;
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( mu(k), lm(k) )
for( i = 0 ; i < sNo ; i++ ){
p->uBtArr[i] = 0.25;
p->uMuArr[i] = meanX;
p->uAArr[i] = 0.01 * varX;
p->uBArr[i] = 0.01;
}
for( r = 0 ; r < rNo ; r++ ){
initialize_indVars_gauss( xns->xn[r], gv, ivs->indVars[r] );
}
calcStatsVarsG_gauss( xns, gv, ivs );
maximizationG_gauss( xns, gv, ivs );
}
void initialize_indVars_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_gauss( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (gaussData*)malloc( sizeof(gaussData) );
gaussData *d = (gaussData*)xn->data;
d->v = NULL;
return xn;
}
void freeXnDataSet_gauss( xn )
xnDataSet **xn;
{
gaussData *d = (gaussData*)(*xn)->data;
free( d->v );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_gauss( i, params )
int i;
void *params;
{
gaussParameters *p = (gaussParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_gauss( i, j, params )
int i, j;
void *params;
{
gaussParameters *p = (gaussParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn_gauss( xn, n, i, params )
xnDataSet *xn;
size_t n;
int i;
void *params;
{
gaussParameters *p = (gaussParameters*)params;
gaussData *d = (gaussData*)xn->data;
double val;
val = p->avgLnLm[i] - log(2.0 * M_PI);
val -= 1.0/p->btMu[i] + p->aLm[i] / p->bLm[i] * pow( d->v[n] - p->avgMu[i], 2.0);
return exp(val / 2.0);
}
void calcStatsVars_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussData *d = (gaussData*)xn->data;
gaussStats *s = (gaussStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Nii = s->Nii, **Nij = s->Nij, *Ni = s->Ni;
double *barX = s->barX, *NiSi = s->NiSi;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Nii[i] = 1e-10;
barX[i] = 1e-10;
NiSi[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
Nij[i][j] = 1e-10;
}
for( n = 0 ; n < dLen ; n++ ){
Ni[i] += gmMat[n][i];
barX[i] += gmMat[n][i] * d->v[n];
for( j = 0 ; j < sNo ; j++ ){
Nii[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
barX[i] /= Ni[i];
for( n = 0 ; n < dLen ; n++ ){
NiSi[i] += gmMat[n][i] * pow( d->v[n] - barX[i], 2.0);
}
}
}
void calcStatsVarsG_gauss( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussData *d;
gaussGlobalStats *gs = (gaussGlobalStats*)ivs->stats;
int sNo = gv->sNo, rNo = xns->R;
double **gmMat, ***xiMat;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *NiR = gs->NiR;
double *barXR = gs->barXR, *NiSiR = gs->NiSiR, *z1iR = gs->z1iR;
size_t dLen, n;
int i, j, r;
for( i = 0 ; i < sNo ; i++ ){
NiR[i] = 1e-10;
NiiR[i] = 1e-10;
barXR[i] = 1e-10;
NiSiR[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
NijR[i][j] = 1e-10;
}
z1iR[i] = 1e-10;
}
for( r = 0 ; r < rNo ; r++ ){
d = (gaussData*)xns->xn[r]->data;
dLen = xns->xn[r]->N;
gmMat = ivs->indVars[r]->gmMat;
xiMat = ivs->indVars[r]->xiMat;
for( i = 0 ; i < sNo ; i++ ){
z1iR[i] += gmMat[0][i];
for( n = 0 ; n < dLen ; n++ ){
NiR[i] += gmMat[n][i];
barXR[i] += gmMat[n][i] * d->v[n];
for( j = 0 ; j < sNo ; j++ ){
NiiR[i] += xiMat[n][i][j];
NijR[i][j] += xiMat[n][i][j];
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){
barXR[i] /= NiR[i];
for( r = 0 ; r < rNo ; r++ ){
d = (gaussData*)xns->xn[r]->data;
dLen = xns->xn[r]->N;
gmMat = ivs->indVars[r]->gmMat;
for( n = 0 ; n < dLen ; n++ ){
NiSiR[i] += gmMat[n][i] * pow( d->v[n] - barXR[i], 2.0);
}
}
}
}
void maximization_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussParameters *p = (gaussParameters*)gv->params;
gaussStats *s = (gaussStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uBtArr = p->uBtArr, *uMuArr = p->uMuArr, *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgMu = p->avgMu, *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *mu0 = p->mu0, *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
double *Ni = s->Ni, *Nii = s->Nii, **Nij = s->Nij, *barX = s->barX, *NiSi = s->NiSi;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );
}
btMu[i] = uBtArr[i] + Ni[i];
mu0[i] = (uBtArr[i] * uMuArr[i] + Ni[i] * barX[i]) / btMu[i];
aLm[i] = uAArr[i] + Ni[i] / 2.0;
bLm[i] = uBArr[i] + (NiSi[i] / 2.0);
bLm[i] += uBtArr[i] * Ni[i] * pow( barX[i] - uMuArr[i], 2.0) / 2.0 / (uBtArr[i] + Ni[i]);
avgMu[i] = mu0[i];
avgLm[i] = aLm[i] / bLm[i];
avgLnLm[i] = gsl_sf_psi( aLm[i] ) - log( bLm[i] );
}
}
void maximizationG_gauss( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
gaussParameters *p = (gaussParameters*)gv->params;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uBtArr = p->uBtArr, *uMuArr = p->uMuArr, *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgMu = p->avgMu, *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *mu0 = p->mu0, *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
gaussGlobalStats *gs = (gaussGlobalStats*)ivs->stats;
double *NiR = gs->NiR, *NiiR = gs->NiiR, **NijR = gs->NijR, *barXR = gs->barXR, *NiSiR = gs->NiSiR;
double *z1iR = gs->z1iR, dR = (double)(xns->R);
int sNo = gv->sNo;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );
}
btMu[i] = uBtArr[i] + NiR[i];
mu0[i] = (uBtArr[i] * uMuArr[i] + NiR[i] * barXR[i]) / btMu[i];
aLm[i] = uAArr[i] + NiR[i] / 2.0;
bLm[i] = uBArr[i] + (NiSiR[i] / 2.0);
bLm[i] += uBtArr[i] * NiR[i] * pow( barXR[i] - uMuArr[i], 2.0) / 2.0 / (uBtArr[i] + NiR[i]);
avgMu[i] = mu0[i];
avgLm[i] = aLm[i] / bLm[i];
avgLnLm[i] = gsl_sf_psi( aLm[i] ) - log( bLm[i] );
}
}
double varLowerBound_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussParameters *p = (gaussParameters*)gv->params;
gaussStats *s = (gaussStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uBtArr = p->uBtArr, *uMuArr = p->uMuArr, *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *mu0 = p->mu0, *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
double *Nii = s->Nii, **Nij = s->Nij;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpMuLm = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqMuLm = - sNo / 2.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpMuLm += log(uBtArr[i]) / 2.0;
lnpMuLm -= uBtArr[i] / 2.0 *( 1.0 / btMu[i] + aLm[i] / bLm[i] * pow(mu0[i] - uMuArr[i], 2.0) );
lnpMuLm += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);
lnpMuLm += (uAArr[i] - 0.5) * avgLnLm[i] - uBArr[i] * avgLm[i];
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
lnqMuLm += log(btMu[i]) / 2.0 - gsl_sf_lngamma(aLm[i]) + aLm[i] * log(bLm[i]);
lnqMuLm += (aLm[i] - 0.5) * avgLnLm[i] - aLm[i];
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpMuLm;
val -= lnqPi + lnqA + lnqMuLm;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
double varLowerBoundG_gauss( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo, rNo = xns->R;
gaussParameters *p = (gaussParameters*)gv->params;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uBtArr = p->uBtArr, *uMuArr = p->uMuArr, *uAArr = p->uAArr, *uBArr = p->uBArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *mu0 = p->mu0, *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
gaussGlobalStats *gs = (gaussGlobalStats*)ivs->stats;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;
size_t n;
int i, j, r;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpMuLm = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + dR);
double lnqA = 0.0;
double lnqMuLm = - sNo / 2.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpMuLm += log(uBtArr[i]) / 2.0;
lnpMuLm -= uBtArr[i] / 2.0 *( 1.0 / btMu[i] + aLm[i] / bLm[i] * pow(mu0[i] - uMuArr[i], 2.0) );
lnpMuLm += - gsl_sf_lngamma(uAArr[i]) + uAArr[i] * log(uBArr[i]);
lnpMuLm += (uAArr[i] - 0.5) * avgLnLm[i] - uBArr[i] * avgLm[i];
lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );
}
lnqMuLm += log(btMu[i]) / 2.0 - gsl_sf_lngamma(aLm[i]) + aLm[i] * log(bLm[i]);
lnqMuLm += (aLm[i] - 0.5) * avgLnLm[i] - aLm[i];
}
double lnpX = 0.0;
for( r = 0 ; r < rNo ; r++ ){
size_t dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( ivs->indVars[r]->cn[n] );
}
}
double val;
val = lnpPi + lnpA + lnpMuLm;
val -= lnqPi + lnqA + lnqMuLm;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
void reorderParameters_gauss( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
gaussParameters *p = (gaussParameters*)gv->params;
gaussStats *s = (gaussStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgMu = p->avgMu, *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
double *Ni = s->Ni;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgMu values (0=biggest avgMu -- sNo=smallest avgMu).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgMu[i] < avgMu[j] ){
index[i]--;
} else if( avgMu[i] == avgMu[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgMu[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgMu[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLm[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnLm[i] = store[i]; }
//
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = btMu[i]; }
for( i = 0 ; i < sNo ; i++ ){ btMu[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = aLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ aLm[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = bLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ bLm[i] = store[i]; }
//
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void reorderParametersG_gauss( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
size_t dLen;
int sNo = gv->sNo, rNo = xns->R;
gaussParameters *p = (gaussParameters*)gv->params;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgMu = p->avgMu, *avgLm = p->avgLm, *avgLnLm = p->avgLnLm;
double *btMu = p->btMu, *aLm = p->aLm, *bLm = p->bLm;
size_t n;
int i, j, r;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgMu values (0=biggest avgMu -- sNo=smallest avgMu).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgMu[i] < avgMu[j] ){
index[i]--;
} else if( avgMu[i] == avgMu[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgMu[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgMu[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLm[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnLm[i] = store[i]; }
//
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = btMu[i]; }
for( i = 0 ; i < sNo ; i++ ){ btMu[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = aLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ aLm[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = bLm[i]; }
for( i = 0 ; i < sNo ; i++ ){ bLm[i] = store[i]; }
//
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
double *NiR = ((gaussGlobalStats*)ivs->stats)->NiR;
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = NiR[i]; }
for( i = 0 ; i < sNo ; i++ ){ NiR[i] = store[i]; }
for( r = 0 ; r < rNo ; r++ ){
double **gmMat = ivs->indVars[r]->gmMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
}
for( r = 0 ; r < rNo ; r++ ){
double ***xiMat = ivs->indVars[r]->xiMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void outputGaussResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
gaussParameters *p = (gaussParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " means: ( %g", p->avgMu[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgMu[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " lambda: ( %g", p->avgLm[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgLm[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "mu, lambda, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g, %g", p->avgMu[i], p->avgLm[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
#ifdef OUTPUT_MAX_GAMMA
sprintf( fn, "%s.maxG%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->gammaTraj[n] );
}
fclose(fp);
}
#endif
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
void outputGaussResultsG( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
int sNo = gv->sNo, rNo = xns->R;
gaussParameters *p = (gaussParameters*)gv->params;
int i, j, r;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " means: ( %g", p->avgMu[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgMu[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " lambda: ( %g", p->avgLm[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgLm[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.g.param%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "mu, lambda, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g, %g", p->avgMu[i], p->avgLm[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.g.Lq%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
int flag;
#ifdef OUTPUT_MAX_GAMMA
sprintf( fn, "%s.g.maxG%03d", xns->xn[0]->name, sNo );
flag = 0;
if( (fp = fopen( fn, "w")) != NULL ){
n = 0;
do{
flag = 1;
for( r = 0 ; r < rNo ; r++ ){
xnDataSet *xn = xns->xn[r];
indVars *iv = ivs->indVars[r];
if( r > 0 ){
fprintf( fp, "," );
}
if( n < xn->N ){
fprintf( fp, "%d", iv->gammaTraj[n] );
}
flag &= (n >= (xn->N - 1));
}
fprintf( fp, "\n" );
n++;
}while( !flag );
fclose(fp);
}
#endif
sprintf( fn, "%s.g.maxS%03d", xns->xn[0]->name, sNo );
flag = 0;
if( (fp = fopen( fn, "w")) != NULL ){
n = 0;
do{
flag = 1;
for( r = 0 ; r < rNo ; r++ ){
xnDataSet *xn = xns->xn[r];
indVars *iv = ivs->indVars[r];
if( r > 0 ){
fprintf( fp, "," );
}
if( n < xn->N ){
fprintf( fp, "%d", iv->stateTraj[n] );
}
flag &= (n >= (xn->N - 1));
}
fprintf( fp, "\n" );
n++;
}while( !flag );
fclose(fp);
}
}
//
| {
"alphanum_fraction": 0.4672954743,
"avg_line_length": 30.1510548523,
"ext": "c",
"hexsha": "06e08987e96ce357750f22cea0f20c4be2c015ce",
"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": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmmGauss.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"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": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmmGauss.c",
"max_line_length": 126,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmmGauss.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 13680,
"size": 35729
} |
/**
* File: trfit_utils.h
*
*/
#ifndef _TRFIT_UTILS_H
#define _TRFIT_UTILS_H
#include "aper_conf.h"
#include <gsl/gsl_multifit_nlin.h>
#define N_COLUMNS_FIT 6
#define N_KAPPASIG_ITER 3
#define N_KAPPASIG_SIG 3.0
#define N_ITER_IPC 5
#define KAPPA_IPC 3.0
// the ipc fit to the
// data must be lower than this number
// to initialize a correction of the spectrum
#define MIN_IPC_LENGTH 60.0
typedef struct
{
int n_data;
double *x_values;
double *y_values;
double *e_values;
}
fit_data;
struct function_data {
int n;
double * x;
double * y;
double * sig;
};
extern gsl_vector *
fit_beamtrace(const aperture_conf *conf, observation *obs,
const int beamID, beam act_beam);
double
gagauss(const double x, const double *params);
extern gsl_vector *
fit_wuttke(const fit_data *f_data);
extern gsl_vector *
fit_wuttke_talk(const fit_data *f_data);
extern d_point
find_grav_center(const fit_data *f_data);
extern px_point
get_fit_xrange(const aperture_conf *conf, const observation *obs,
beam act_beam);
extern gsl_vector *
fit_function(const fit_data *f_data);
extern fit_data *
get_fitdata(observation *obs, int np, px_point tr_point);
extern fit_data *
alloc_fit_data(const int n_data);
void
print_fit_data(fit_data *f_data);
extern void
free_fit_data(fit_data *f_data);
int
gauss_f(const gsl_vector *x, void *params, gsl_vector *f);
int
gauss_df(const gsl_vector *x, void *params, gsl_matrix *J);
int
gauss_fdf (const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J);
extern void
print_fit_state (size_t iter, gsl_multifit_fdfsolver * s);
extern double
comp_intrel_max(const fit_data *f_data);
extern gsl_matrix *
bcksub_observation(observation *obs, observation *bck);
extern double *
evaluate_ipc_fit(fit_data *f_data, double *gpars, double *fpars);
extern void
write_ipc_fit(fit_data *f_data, double *y_values, const char *ipc_file, const double qual, double *yfract);
extern double
fit_ipc_data(fit_data *fdata, double *gpars, int n_gpars,
double *fpars, int n_fpars);
extern fit_data *
get_ipc_fdata(const aperture_conf *conf, observation *obs,
gsl_matrix *data_vals, beam act_beam);
extern double *
get_wf_special(const aperture_conf *conf, observation *obs,
gsl_matrix *data_vals, beam act_beam, double yoffs);
extern gsl_vector *
get_ipc_coldata(gsl_matrix *img_data, int np, px_point tr_point);
extern fit_data *
strip_fitdata(fit_data *old_fdata, int i_max);
extern double *
strip_wf_special(fit_data *old_fdata, double *y_fract, int i_max);
extern d_point
kappa_sigma_klipp_ipc(const aperture_conf *conf, observation *obs,
gsl_matrix *data_matrix, beam act_beam,
const char *ipc_file);
extern void
reject_kappasigma(fit_data *f_data, double *y_values, double max_diff);
extern double
calculate_sigma(fit_data *f_data, double *y_values);
#endif
| {
"alphanum_fraction": 0.7594585213,
"avg_line_length": 22.1615384615,
"ext": "h",
"hexsha": "7a887d890e9f94ed0687b91888bcbb378716a5fe",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/trfit_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/trfit_utils.h",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/trfit_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 796,
"size": 2881
} |
/* Copyright 2017 International Business Machines 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. */
#pragma once
#include <kernelpp/types.h>
#include <kernelpp/kernel.h>
#include <gsl.h>
namespace mwe {
namespace kernels
{
using kernelpp::compute_mode;
using kernelpp::error_code;
/* Declare a kernel 'add' which is overloaded to operate
* on single or array-like inputs.
*
* Also, declare the compute modes (CPU,GPU) which
* this kernel will support.
*/
KERNEL_DECL(add,
compute_mode::CPU, compute_mode::CUDA)
{
template <compute_mode> static kernelpp::variant<int, error_code> op(
int a, int b
);
template <compute_mode> static error_code op(
const gsl::span<int> a, const gsl::span<int> b, gsl::span<int> result
);
};
}
} | {
"alphanum_fraction": 0.6904231626,
"avg_line_length": 29.2826086957,
"ext": "h",
"hexsha": "502e7c7612d85078b27a949ca7b484ab11e0560e",
"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": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rayglover-ibm/cuda-bindings",
"max_forks_repo_path": "src/kernels/add.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd",
"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": "rayglover-ibm/cuda-bindings",
"max_issues_repo_path": "src/kernels/add.h",
"max_line_length": 81,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rayglover-ibm/cuda-bindings",
"max_stars_repo_path": "src/kernels/add.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-25T10:01:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-18T02:56:15.000Z",
"num_tokens": 307,
"size": 1347
} |
/*
* harvest.c -- compute solutions of harvest equation
*
* (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil
*/
#include <stdlib.h>
#include <stdio.h>
#define __USE_XOPEN
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
typedef struct param_s {
double a;
double h;
} param_t;
param_t p0 = { .a = 5, .h = 0.8 };
int f(double x, const double y[], double f[], void *params) {
param_t *p = (param_t *)params;
f[0] = p->a * y[0] * (1 - y[0]) - p->h * (1 + sin(2 * M_PI * x));
return GSL_SUCCESS;
}
int singlecurve(FILE *out, const char *name, double x0, double y0,
int direction) {
printf("%s: %f\n", name, y0);
gsl_odeiv2_system system = { f, NULL, 1, &p0 };
gsl_odeiv2_driver *driver
= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,
1e-6 * direction, 1e-6, 0.0);
fprintf(out, "path %s;\n", name);
double x = x0;
double y[1] = { y0 };
fprintf(out, "%s = (%.3f,%.3f)", name, x, y[0]);
for (int i = 1; i < 500; i++) {
double xnext = x + 0.01 * direction;
int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y);
if (status != GSL_SUCCESS) {
fprintf(stderr, "error: rc = %d\n", status);
fprintf(out, ";\n");
return -1;
}
if (fabs(y[0]) > 100) {
goto end;
}
fprintf(out, "\n --(%.3f,%.3f)", x, y[0]);
}
end:
fprintf(out, ";\n");
gsl_odeiv2_driver_free(driver);
return 1;
}
int centercurve(FILE *out, const char *name, double y0) {
printf("%s: %f\n", name, y0);
gsl_odeiv2_system system = { f, NULL, 1, &p0 };
gsl_odeiv2_driver *driver
= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,
-1e-6, 1e-6, 0.0);
fprintf(out, "path %s;\n", name);
double x = 2.5;
double y[1] = { y0 };
// integrate backwards to the initial value
gsl_odeiv2_driver_apply(driver, &x, 0, y);
gsl_odeiv2_driver_free(driver);
driver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,
1e-6, 1e-6, 0.0);
if (fabs(y[0]) > 100) {
goto end;
}
fprintf(out, "%s = (%.3f,%.3f)", name, x, y[0]);
for (int i = 1; i < 501; i++) {
double xnext = x + 0.01;
int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y);
if (status != GSL_SUCCESS) {
fprintf(stderr, "error: rc = %d\n", status);
fprintf(out, ";\n");
return -1;
}
if (fabs(y[0]) > 100) {
goto end;
}
fprintf(out, "\n --(%.3f,%.3f)", x, y[0]);
}
end:
fprintf(out, ";\n");
gsl_odeiv2_driver_free(driver);
return 1;
}
int limitcurve(FILE *out, const char *name, int direction) {
gsl_odeiv2_system system = { f, NULL, 1, &p0 };
gsl_odeiv2_driver *driver
= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,
direction * 1e-6, 1e-6, 0.0);
double x = 0;
double y[1] = { 0.5 };
double xnext = 1000 * direction;
int status = gsl_odeiv2_driver_apply(driver, &x, xnext, y);
printf("integration from %f to %f: %f (%d)\n", x, xnext, y[0], status);
gsl_odeiv2_driver_free(driver);
// now use this as the initial value
return singlecurve(out, name, 2.5 * (1 - direction), y[0], direction);
}
int main(int argc, char *argv[]) {
FILE *out = fopen("harvest.mp", "w");
char suffix = 'a';
char curvename[10];
for (int i = 0; i < 5; i++) {
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
double y0 = 0.7 + 0.2 * i;
singlecurve(out, curvename, 0, y0, 1);
}
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 0, 0.318, 1);
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 0, 0.315, 1);
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 0, 0.300, 1);
for (int i = 0; i < 5; i++) {
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
double y0 = 0.3 - 0.2 * i;
singlecurve(out, curvename, 5, y0, -1);
}
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 5, 0.892, -1);
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 5, 0.895, -1);
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
singlecurve(out, curvename, 5, 0.91, -1);
for (int i = -3; i <= 3; i++) {
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
double y0 = 0.395 + 0.0945 * i;
centercurve(out, curvename, y0);
}
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
limitcurve(out, curvename, -1);
snprintf(curvename, sizeof(curvename), "path%c", suffix++);
limitcurve(out, curvename, 1);
fclose(out);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6303571429,
"avg_line_length": 29.8666666667,
"ext": "c",
"hexsha": "72e00f90f8b2a566deee933786d3e7551a14d4dc",
"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": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "MatthiasRubin/SeminarDGL",
"max_forks_repo_path": "skript/chapters/images/harvest.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "MatthiasRubin/SeminarDGL",
"max_issues_repo_path": "skript/chapters/images/harvest.c",
"max_line_length": 72,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "MatthiasRubin/SeminarDGL",
"max_stars_repo_path": "skript/chapters/images/harvest.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z",
"num_tokens": 1664,
"size": 4480
} |
/*
* Dsp.c
* Hamilton Kibbe
* Copyright 2013 Hamilton Kibbe
*/
#include "Dsp.h"
#include "Utilities.h"
#include <string.h>
#include <float.h>
#include <math.h>
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#elif defined(USE_BLAS)
#include <cblas.h>
#endif
/*******************************************************************************
FloatBufferToInt16 */
Error_t
FloatBufferToInt16(signed short* dest, const float* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
float scale = (float)INT16_MAX;
float temp[length];
vDSP_vsmul(src, 1, &scale, temp, 1, length);
vDSP_vfix16(temp,1,dest,1,length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = floatToInt16(*src++);
dest[i + 1] = floatToInt16(*src++);
dest[i + 2] = floatToInt16(*src++);
dest[i + 3] = floatToInt16(*src++);
}
for (i = end; i < length; ++i)
{
dest[i] = floatToInt16(*src++);
}
#endif
return NOERR;
}
/*******************************************************************************
DoubleBufferToInt16 */
Error_t
DoubleBufferToInt16(signed short* dest, const double* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
double scale = (float)INT16_MAX;
double temp[length];
vDSP_vsmulD(src, 1, &scale, temp, 1, length);
vDSP_vfix16D(temp,1,dest,1,length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = floatToInt16(*src++);
dest[i + 1] = floatToInt16(*src++);
dest[i + 2] = floatToInt16(*src++);
dest[i + 3] = floatToInt16(*src++);
}
for (i = end; i < length; ++i)
{
dest[i] = floatToInt16(*src++);
}
#endif
return NOERR;
}
/*******************************************************************************
Int16BufferToFloat */
Error_t
Int16BufferToFloat(float* dest, const signed short* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
float temp[length];
float scale = 1.0 / (float)INT16_MAX;
vDSP_vflt16(src,1,temp,1,length);
vDSP_vsmul(temp, 1, &scale, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = int16ToFloat(*src++);
dest[i + 1] = int16ToFloat(*src++);
dest[i + 2] = int16ToFloat(*src++);
dest[i + 3] = int16ToFloat(*src++);
}
for (i = end; i < length; ++i)
{
dest[i] = int16ToFloat(*src++);
}
#endif
return NOERR;
}
/*******************************************************************************
Int16BufferToDouble */
Error_t
Int16BufferToDouble(double* dest, const signed short* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
double temp[length];
double scale = 1.0 / (double)INT16_MAX;
vDSP_vflt16D(src,1,temp,1,length);
vDSP_vsmulD(temp, 1, &scale, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = int16ToFloat(*src++);
dest[i + 1] = int16ToFloat(*src++);
dest[i + 2] = int16ToFloat(*src++);
dest[i + 3] = int16ToFloat(*src++);
}
for (i = end; i < length; ++i)
{
dest[i] = int16ToFloat(*src++);
}
#endif
return NOERR;
}
/*******************************************************************************
DoubleToFloat */
Error_t
DoubleToFloat(float* dest, const double* src, unsigned length)
{
#ifdef __APPLE__
vDSP_vdpsp(src, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = (float)src[i];
dest[i + 1] = (float)src[i + 1];
dest[i + 2] = (float)src[i + 2];
dest[i + 3] = (float)src[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = (float)src[i];
}
#endif
return NOERR;
}
/*******************************************************************************
Float To Double */
Error_t
FloatToDouble(double* dest, const float* src, unsigned length)
{
#ifdef __APPLE__
vDSP_vspdp(src, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = (double)(src[i]);
dest[i + 1] = (double)(src[i + 1]);
dest[i + 2] = (double)(src[i + 2]);
dest[i + 3] = (double)(src[i + 3]);
}
for (i = end; i < length; ++i)
{
dest[i] = (double)(src[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
FillBuffer */
Error_t
FillBuffer(float *dest, unsigned length, float value)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vfill(&value, dest, 1, length);
#else
// Otherwise do it manually
unsigned i = 0;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = value;
dest[i + 1] = value;
dest[i + 2] = value;
dest[i + 3] = value;
}
for (i = end; i < length; ++i)
{
dest[i] = value;
}
#endif
return NOERR;
}
/*******************************************************************************
FillBufferD */
Error_t
FillBufferD(double *dest, unsigned length, double value)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vfillD(&value, dest, 1, length);
#else
// Otherwise do it manually
unsigned i = 0;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = value;
dest[i + 1] = value;
dest[i + 2] = value;
dest[i + 3] = value;
}
for (i = end; i < length; ++i)
{
dest[i] = value;
}
#endif
return NOERR;
}
/*******************************************************************************
ClearBuffer */
Error_t
ClearBuffer(float *dest, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vclr(dest, 1, length);
#else
// Otherwise do it manually. Yes this works for floats
memset(dest, 0, length * sizeof(float));
#endif
return NOERR;
}
/*******************************************************************************
ClearBufferD */
Error_t
ClearBufferD(double *dest, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vclrD(dest, 1, length);
#else
// Otherwise do it manually. Yes this works for doubles
memset(dest, 0, length * sizeof(double));
#endif
return NOERR;
}
/*******************************************************************************
CopyBuffer */
Error_t
CopyBuffer(float* dest, const float* src, unsigned length)
{
if (src != dest)
{
#if defined(__APPLE__) || defined(USE_BLAS)
// Use the Accelerate framework if we have it
cblas_scopy(length, src, 1, dest, 1);
#else
// Do it the boring way. Prefer memmove to memcpy in case src and dest
// overlap
memmove(dest, src, length * sizeof(float));
#endif
}
return NOERR;
}
/*******************************************************************************
CopyBufferD */
Error_t
CopyBufferD(double* dest, const double* src, unsigned length)
{
if (src != dest)
{
#if defined(__APPLE__) || defined(USE_BLAS)
// Use the Accelerate framework if we have it
cblas_dcopy(length, src, 1, dest, 1);
#else
// Do it the boring way. Prefer memmove to memcpy in case src and dest
// overlap
memmove(dest, src, length * sizeof(double));
#endif
}
return NOERR;
}
/*******************************************************************************
CopyBufferStride */
Error_t
CopyBufferStride(float* dest,
unsigned dest_stride,
const float* src,
unsigned src_stride,
unsigned length)
{
#if defined(__APPLE__) || defined(USE_BLAS)
// Use the Accelerate framework if we have it
cblas_scopy(length, src, src_stride, dest, dest_stride);
#else
for (unsigned i = 0; i < length; ++i)
{
dest[i * dest_stride] = src[i * src_stride];
}
#endif
return NOERR;
}
/*******************************************************************************
CopyBufferStrideD */
Error_t
CopyBufferStrideD(double* dest,
unsigned dest_stride,
const double* src,
unsigned src_stride,
unsigned length)
{
#if defined(__APPLE__) || defined(USE_BLAS)
// Use the Accelerate framework if we have it
cblas_dcopy(length, src, src_stride, dest, dest_stride);
#else
for (unsigned i = 0; i < length; ++i)
{
dest[i * dest_stride] = src[i * src_stride];
}
#endif
return NOERR;
}
/*******************************************************************************
SplitToInterleaved */
Error_t
SplitToInterleaved(float* dest, const float* real, const float* imag, unsigned length)
{
#if defined(__APPLE__)
DSPSplitComplex in = {.realp = (float*)real, .imagp = (float*)imag};
vDSP_ztoc(&in, 1, (DSPComplex*)dest, 2, length);
#elif defined(USE_BLAS)
cblas_scopy(length, real, 1, dest, 2);
cblas_scopy(length, imag, 1, dest + 1, 2);
#else
unsigned i;
unsigned i2;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
i2 = i * 2;
dest[i2] = real[i];
dest[i2 + 2] = real[i + 1];
dest[i2 + 4] = real[i + 2];
dest[i2 + 6] = real[i + 3];
dest[i2 + 1] = imag[i];
dest[i2 + 3] = imag[i + 1];
dest[i2 + 5] = imag[i + 2];
dest[i2 + 7] = imag[i + 3];
}
for (i = end; i < length; ++i)
{
i2 = i * 2;
dest[i2] = real[i];
dest[i2 + 1] = imag[i];
}
#endif
return NOERR;
}
Error_t
SplitToInterleavedD(double* dest, const double* real, const double* imag, unsigned length)
{
#if defined(__APPLE__)
DSPDoubleSplitComplex in = {.realp = (double*)real, .imagp = (double*)imag};
vDSP_ztocD(&in, 1, (DSPDoubleComplex*)dest, 2, length);
#elif defined(USE_BLAS)
cblas_dcopy(length, real, 1, dest, 2);
cblas_dcopy(length, imag, 1, dest + 1, 2);
#else
unsigned i;
unsigned i2;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
i2 = i * 2;
dest[i2] = real[i];
dest[i2 + 2] = real[i + 1];
dest[i2 + 4] = real[i + 2];
dest[i2 + 6] = real[i + 3];
dest[i2 + 1] = imag[i];
dest[i2 + 3] = imag[i + 1];
dest[i2 + 5] = imag[i + 2];
dest[i2 + 7] = imag[i + 3];
}
for (i = end; i < length; ++i)
{
i2 = i * 2;
dest[i2] = real[i];
dest[i2 + 1] = imag[i];
}
#endif
return NOERR;
}
/*******************************************************************************
InterleavedToSplit */
Error_t
InterleavedToSplit(float* real,
float* imag,
const float* input,
unsigned length)
{
#if defined(__APPLE__)
DSPSplitComplex out = {.realp = real, .imagp = imag};
vDSP_ctoz((const DSPComplex*)input, 2, &out, 1, length);
#elif defined(USE_BLAS)
cblas_scopy(length, input, 2, real, 1);
cblas_scopy(length, input + 1, 2, imag, 1);
#else
unsigned i;
unsigned i2;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
i2 = i * 2;
real[i] = input[i2];
real[i + 1] = input[i2 + 2];
real[i + 2] = input[i2 + 4];
real[i + 3] = input[i2 + 6];
imag[i] = input[i2 + 1];
imag[i + 1] = input[i2 + 3];
imag[i + 2] = input[i2 + 5];
imag[i + 3] = input[i2 + 7];
}
for (i = end; i < length; ++i)
{
i2 = i * 2;
real[i] = input[i2];
imag[i] = input[i2 + 1];
}
#endif
return NOERR;
}
Error_t
InterleavedToSplitD(double* real,
double* imag,
const double* input,
unsigned length)
{
#if defined(__APPLE__)
DSPDoubleSplitComplex out = {.realp = real, .imagp = imag};
vDSP_ctozD((const DSPDoubleComplex*)input, 2, &out, 1, length);
#elif defined(USE_BLAS)
cblas_dcopy(length, input, 2, real, 1);
cblas_dcopy(length, input + 1, 2, imag, 1);
#else
unsigned i;
unsigned i2;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
i2 = i * 2;
real[i] = input[i2];
real[i + 1] = input[i2 + 2];
real[i + 2] = input[i2 + 4];
real[i + 3] = input[i2 + 6];
imag[i] = input[i2 + 1];
imag[i + 1] = input[i2 + 3];
imag[i + 2] = input[i2 + 5];
imag[i + 3] = input[i2 + 7];
}
for (i = end; i < length; ++i)
{
i2 = i * 2;
real[i] = input[i2];
imag[i] = input[i2 + 1];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorAbs */
Error_t
VectorAbs(float *dest, const float *in, unsigned length)
{
#ifdef __APPLE__
vDSP_vabs(in, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i = 0;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = fabsf(in[i]);
dest[i + 1] = fabsf(in[i + 1]);
dest[i + 2] = fabsf(in[i + 2]);
dest[i + 3] = fabsf(in[i + 3]);
}
for (unsigned i = end; i < length; ++i)
{
dest[i] = fabsf(in[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorAbsD */
Error_t
VectorAbsD(double *dest, const double *in, unsigned length)
{
#ifdef __APPLE__
vDSP_vabsD(in, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i = 0;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = fabs(in[i]);
dest[i + 1] = fabs(in[i + 1]);
dest[i + 2] = fabs(in[i + 2]);
dest[i + 3] = fabs(in[i + 3]);
}
for (unsigned i = end; i < length; ++i)
{
dest[i] = fabs(in[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorNegate */
Error_t
VectorNegate(float *dest,
const float *in,
unsigned length)
{
#if defined(__APPLE__)
// Use the Accelerate framework if we have it
vDSP_vneg(in, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = -in[i];
dest[i + 1] = -in[i + 1];
dest[i + 2] = -in[i + 2];
dest[i + 3] = -in[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = -in[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorNegateD */
Error_t
VectorNegateD(double *dest,
const double *in,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vnegD(in, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = -in[i];
dest[i + 1] = -in[i + 1];
dest[i + 2] = -in[i + 2];
dest[i + 3] = -in[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = -in[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorSum */
float
VectorSum(const float* src, unsigned length)
{
float res = 0.0;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_sve(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
res += src[i];
}
#endif
return res;
}
/*******************************************************************************
VectorSumD */
double
VectorSumD(const double* src, unsigned length)
{
double res = 0.0;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_sveD(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
res += src[i];
}
#endif
return res;
}
/*******************************************************************************
VectorMax */
float
VectorMax(const float* src, unsigned length)
{
float res = FLT_MIN;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_maxv(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
if (src[i] > res)
{
res = src[i];
}
}
#endif
return res;
}
/*******************************************************************************
VectorMax */
double
VectorMaxD(const double* src, unsigned length)
{
double res = DBL_MIN;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_maxvD(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
if (src[i] > res)
{
res = src[i];
}
}
#endif
return res;
}
/*******************************************************************************
VectorMaxVI */
Error_t
VectorMaxVI(float* value, unsigned* index, const float* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_maxvi(src, 1, value, (unsigned long*)index, length);
#else
float res = FLT_MIN;
for (unsigned i = 0; i < length; ++i)
{
if (src[i] > res)
{
*value = res = src[i];
*index = i;
}
}
#endif
return NOERR;
}
/*******************************************************************************
VectorMaxVID*/
Error_t
VectorMaxVID(double* value, unsigned* index, const double* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_maxviD(src, 1, value, (unsigned long*)index, length);
#else
double res = src[0];
for (unsigned i = 0; i < length; ++i)
{
if (src[i] > res)
{
*value = res = src[i];
*index = i;
}
}
#endif
return NOERR;
}
/*******************************************************************************
VectorMin */
float
VectorMin(const float* src, unsigned length)
{
float res = FLT_MAX;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_minv(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
if (src[i] < res)
{
res = src[i];
}
}
#endif
return res;
}
/*******************************************************************************
VectorMinD */
double
VectorMinD(const double* src, unsigned length)
{
double res = DBL_MAX;
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_minvD(src, 1, &res, length);
#else
for (unsigned i = 0; i < length; ++i)
{
if (src[i] < res)
{
res = src[i];
}
}
#endif
return res;
}
/*******************************************************************************
VectorMinVI */
Error_t
VectorMinVI(float* value, unsigned* index, const float* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_minvi(src, 1, value, (unsigned long*)index, length);
#else
float res = src[0];
for (unsigned i = 0; i < length; ++i)
{
if (src[i] < res)
{
*value = res = src[i];
*index = i;
}
}
#endif
return NOERR;
}
/*******************************************************************************
VectorMinVID */
Error_t
VectorMinVID(double* value, unsigned* index, const double* src, unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_minviD(src, 1, value, (unsigned long*)index, length);
#else
double res = src[0];
for (unsigned i = 0; i < length; ++i)
{
if (src[i] < res)
{
*value = res = src[i];
*index = i;
}
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorAdd */
Error_t
VectorVectorAdd(float *dest,
const float *in1,
const float *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vadd(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] + in2[i];
dest[i + 1] = in1[i + 1] + in2[i + 1];
dest[i + 2] = in1[i + 2] + in2[i + 2];
dest[i + 3] = in1[i + 3] + in2[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] + in2[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorAddD */
Error_t
VectorVectorAddD(double *dest,
const double *in1,
const double *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vaddD(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] + in2[i];
dest[i + 1] = in1[i + 1] + in2[i + 1];
dest[i + 2] = in1[i + 2] + in2[i + 2];
dest[i + 3] = in1[i + 3] + in2[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] + in2[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorSub */
Error_t
VectorVectorSub(float *dest,
const float *in1,
const float *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsub(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in2[i] - in1[i];
dest[i + 1] = in2[i + 1] - in1[i + 1];
dest[i + 2] = in2[i + 2] - in1[i + 2];
dest[i + 3] = in2[i + 3] - in1[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in2[i] - in1[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorSubD */
Error_t
VectorVectorSubD(double *dest,
const double *in1,
const double *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsubD(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in2[i] - in1[i];
dest[i + 1] = in2[i + 1] - in1[i + 1];
dest[i + 2] = in2[i + 2] - in1[i + 2];
dest[i + 3] = in2[i + 3] - in1[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in2[i] - in1[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorScalarAdd */
Error_t
VectorScalarAdd(float *dest,
const float *in1,
const float scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsadd(in1, 1, &scalar, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] + scalar;
dest[i + 1] = in1[i + 1] + scalar;
dest[i + 2] = in1[i + 2] + scalar;
dest[i + 3] = in1[i + 3] + scalar;
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] + scalar;
}
#endif
return NOERR;
}
/*******************************************************************************
VectorScalarAddD */
Error_t
VectorScalarAddD(double *dest,
const double *in1,
const double scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsaddD(in1, 1, &scalar, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] + scalar;
dest[i + 1] = in1[i + 1] + scalar;
dest[i + 2] = in1[i + 2] + scalar;
dest[i + 3] = in1[i + 3] + scalar;
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] + scalar;
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorMultiply */
Error_t
VectorVectorMultiply(float *dest,
const float *in1,
const float *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vmul(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] * in2[i];
dest[i + 1] = in1[i + 1] * in2[i + 1];
dest[i + 2] = in1[i + 2] * in2[i + 2];
dest[i + 3] = in1[i + 3] * in2[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] * in2[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorMultiplyD */
Error_t
VectorVectorMultiplyD(double *dest,
const double *in1,
const double *in2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vmulD(in1, 1, in2, 1, dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] * in2[i];
dest[i + 1] = in1[i + 1] * in2[i + 1];
dest[i + 2] = in1[i + 2] * in2[i + 2];
dest[i + 3] = in1[i + 3] * in2[i + 3];
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] * in2[i];
}
#endif
return NOERR;
}
/*******************************************************************************
VectorScalarMultiply */
Error_t
VectorScalarMultiply(float *dest,
const float *in1,
const float scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsmul(in1, 1, &scalar,dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] * scalar;
dest[i + 1] = in1[i + 1] * scalar;
dest[i + 2] = in1[i + 2] * scalar;
dest[i + 3] = in1[i + 3] * scalar;
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] * scalar;
}
#endif
return NOERR;
}
/*******************************************************************************
VectorScalarMultiplyD */
Error_t
VectorScalarMultiplyD(double *dest,
const double *in1,
const double scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsmulD(in1, 1, &scalar,dest, 1, length);
#else
// Otherwise do it manually
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = in1[i] * scalar;
dest[i + 1] = in1[i + 1] * scalar;
dest[i + 2] = in1[i + 2] * scalar;
dest[i + 3] = in1[i + 3] * scalar;
}
for (i = end; i < length; ++i)
{
dest[i] = in1[i] * scalar;
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorMix */
Error_t
VectorVectorMix(float *dest,
const float *in1,
const float *scalar1,
const float *in2,
const float *scalar2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsmsma(in1, 1, scalar1, in2, 1, scalar2, dest, 1, length);
#else
unsigned i;
for (i = 0; i < length; ++i)
{
dest[i] = (in1[i] * (*scalar1)) + (in2[i] * (*scalar2));
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorMixD */
Error_t
VectorVectorMixD(double *dest,
const double *in1,
const double *scalar1,
const double *in2,
const double *scalar2,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vsmsmaD(in1, 1, scalar1, in2, 1, scalar2, dest, 1, length);
#else
unsigned i;
for (i = 0; i < length; ++i)
{
dest[i] = (in1[i] * (*scalar1)) + (in2[i] * (*scalar2));
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorSumScale */
Error_t
VectorVectorSumScale(float *dest,
const float *in1,
const float *in2,
const float *scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vasm(in1, 1, in2, 1, scalar, dest, 1, length);
#else
unsigned i;
for (i = 0; i < length; ++i)
{
dest[i] = (in1[i] + in2[i]) * (*scalar);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorVectorSumScaleD */
Error_t
VectorVectorSumScaleD(double *dest,
const double *in1,
const double *in2,
const double *scalar,
unsigned length)
{
#ifdef __APPLE__
// Use the Accelerate framework if we have it
vDSP_vasmD(in1, 1, in2, 1, scalar, dest, 1, length);
#else
unsigned i;
for (i = 0; i < length; ++i)
{
dest[i] = (in1[i] + in2[i]) * (*scalar);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorPower */
Error_t
VectorPower(float* dest, const float* in, float power, unsigned length)
{
#ifdef __APPLE__
if (power == 2.0)
{
vDSP_vsq(in, 1, dest, 1, length);
}
else
{
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = powf(in[i], power);
dest[i + 1] = powf(in[i + 1], power);
dest[i + 2] = powf(in[i + 2], power);
dest[i + 3] = powf(in[i + 3], power);
}
for (i = end; i < length; ++i)
{
dest[i] = powf(in[i], power);
}
}
#else
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = powf(in[i], power);
dest[i + 1] = powf(in[i + 1], power);
dest[i + 2] = powf(in[i + 2], power);
dest[i + 3] = powf(in[i + 3], power);
}
for (i = end; i < length; ++i)
{
dest[i] = powf(in[i], power);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorPowerD */
Error_t
VectorPowerD(double* dest, const double* in, double power, unsigned length)
{
#ifdef __APPLE__
if (power == 2.0)
{
vDSP_vsqD(in, 1, dest, 1, length);
}
else
{
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = pow(in[i], power);
dest[i + 1] = pow(in[i + 1], power);
dest[i + 2] = pow(in[i + 2], power);
dest[i + 3] = pow(in[i + 3], power);
}
for (i = end; i < length; ++i)
{
dest[i] = pow(in[i], power);
}
}
#else
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
dest[i] = pow(in[i], power);
dest[i + 1] = pow(in[i + 1], power);
dest[i + 2] = pow(in[i + 2], power);
dest[i + 3] = pow(in[i + 3], power);
}
for (i = end; i < length; ++i)
{
dest[i] = pow(in[i], power);
}
#endif
return NOERR;
}
/*******************************************************************************
Convolve */
Error_t
Convolve(float *in1,
unsigned in1_length,
float *in2,
unsigned in2_length,
float *dest)
{
unsigned resultLength = in1_length + (in2_length - 1);
#ifdef __APPLE__
//Use Native vectorized convolution function if available
float *in2_end = in2 + (in2_length - 1);
unsigned signalLength = (in2_length + resultLength);
float padded[signalLength];
//float zero = 0.0;
ClearBuffer(padded, signalLength);
// Pad the input signal with (filter_length - 1) zeros.
cblas_scopy(in1_length, in1, 1, (padded + (in2_length - 1)), 1);
vDSP_conv(padded, 1, in2_end, -1, dest, 1, resultLength, in2_length);
#else
// Use (boring, slow) canonical implementation
unsigned i;
for (i = 0; i <resultLength; ++i)
{
unsigned kmin, kmax, k;
dest[i] = 0;
kmin = (i >= (in2_length - 1)) ? i - (in2_length - 1) : 0;
kmax = (i < in1_length - 1) ? i : in1_length - 1;
for (k = kmin; k <= kmax; k++)
{
dest[i] += in1[k] * in2[i - k];
}
}
#endif
return NOERR;
}
/*******************************************************************************
ConvolveD */
Error_t
ConvolveD(double *in1,
unsigned in1_length,
double *in2,
unsigned in2_length,
double *dest)
{
unsigned resultLength = in1_length + (in2_length - 1);
#ifdef __APPLE__
//Use Native vectorized convolution function if available
double *in2_end = in2 + (in2_length - 1);
double signalLength = (in2_length + resultLength);
// So there's some hella weird requirement that the signal input to
//vDSP_conv has to be larger than (result_length + filter_length - 1),
// (the output vector length) and it has to be zero-padded. What. The. Fuck!
double padded[(unsigned)ceil(signalLength)];
//float zero = 0.0;
FillBufferD(padded, signalLength, 0.0);
// Pad the input signal with (filter_length - 1) zeros.
cblas_dcopy(in1_length, in1, 1, (padded + (in2_length - 1)), 1);
vDSP_convD(padded, 1, in2_end, -1, dest, 1, resultLength, in2_length);
#else
// Use (boring, slow) canonical implementation
unsigned i;
for (i = 0; i <resultLength; ++i)
{
unsigned kmin, kmax, k;
dest[i] = 0;
kmin = (i >= (in2_length - 1)) ? i - (in2_length - 1) : 0;
kmax = (i < in1_length - 1) ? i : in1_length - 1;
for (k = kmin; k <= kmax; k++)
{
dest[i] += in1[k] * in2[i - k];
}
}
#endif
return NOERR;
}
/*******************************************************************************
VectorDbConvert */
Error_t
VectorDbConvert(float* dest,
const float* in,
unsigned length)
{
#ifdef __APPLE__
float one = 1.0;
vDSP_vdbcon(in, 1, &one, dest, 1, length, 1);
#else
for (unsigned i = 0; i < length; ++i)
{
dest[i] = AMP_TO_DB(in[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorDbConvertD */
Error_t
VectorDbConvertD(double* dest,
const double* in,
unsigned length)
{
#ifdef __APPLE__
double one = 1.0;
vDSP_vdbconD(in, 1, &one, dest, 1, length, 1);
#else
for (unsigned i = 0; i < length; ++i)
{
dest[i] = AMP_TO_DBD(in[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
ComplexMultiply */
Error_t
ComplexMultiply(float* re,
float* im,
const float* re1,
const float* im1,
const float* re2,
const float* im2,
unsigned length)
{
#if defined(__APPLE__)
DSPSplitComplex in1 = {.realp = (float*)re1, .imagp = (float*)im1};
DSPSplitComplex in2 = {.realp = (float*)re2, .imagp = (float*)im2};
DSPSplitComplex out = {.realp = re, .imagp = im};
vDSP_zvmul(&in1, 1, &in2, 1, &out, 1, length, 1);
#else
for (unsigned i = 0; i < length; ++i)
{
float ire1 = re1[i];
float iim1 = im1[i];
float ire2 = re2[i];
float iim2 = im2[i];
re[i] = (ire1 * ire2 - iim1 * iim2);
im[i] = (iim1 * ire2 + iim2 * ire1);
}
#endif
return NOERR;
}
/*******************************************************************************
ComplexMultiplyD */
Error_t
ComplexMultiplyD(double* re,
double* im,
const double* re1,
const double* im1,
const double* re2,
const double* im2,
unsigned length)
{
#if defined(__APPLE__)
DSPDoubleSplitComplex in1 = {.realp = (double*)re1, .imagp = (double*)im1};
DSPDoubleSplitComplex in2 = {.realp = (double*)re2, .imagp = (double*)im2};
DSPDoubleSplitComplex out = {.realp = re, .imagp = im};
vDSP_zvmulD(&in1, 1, &in2, 1, &out, 1, length, 1);
#else
for (unsigned i = 0; i < length; ++i)
{
double ire1 = re1[i];
double iim1 = im1[i];
double ire2 = re2[i];
double iim2 = im2[i];
re[i] = (ire1 * ire2 - iim1 * iim2);
im[i] = (iim1 * ire2 + iim2 * ire1);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorRectToPolar */
Error_t
VectorRectToPolar(float* magnitude,
float* phase,
const float* real,
const float* imaginary,
unsigned length)
{
#ifdef __APPLE__
float dest[2*length];
SplitToInterleaved(dest, real, imaginary, length);
vDSP_polar(dest, 2, dest, 2, length);
InterleavedToSplit(magnitude, phase, dest, length);
#else
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
RectToPolar(real[i], imaginary[i], &magnitude[i], &phase[i]);
RectToPolar(real[i+1], imaginary[i+1], &magnitude[i+1], &phase[i+1]);
RectToPolar(real[i+2], imaginary[i+2], &magnitude[i+2], &phase[i+2]);
RectToPolar(real[i+3], imaginary[i+3], &magnitude[i+3], &phase[i+3]);
}
for (i = end; i < length; ++i)
{
RectToPolar(real[i], imaginary[i], &magnitude[i], &phase[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
VectorRectToPolarD */
Error_t
VectorRectToPolarD(double* magnitude,
double* phase,
const double* real,
const double* imaginary,
unsigned length)
{
#ifdef __APPLE__
double dest[2*length];
SplitToInterleavedD(dest, real, imaginary, length);
vDSP_polarD(dest, 2, dest, 2, length);
InterleavedToSplitD(magnitude, phase, dest, length);
#else
unsigned i;
const unsigned end = 4 * (length / 4);
for (i = 0; i < end; i+=4)
{
RectToPolarD(real[i], imaginary[i], &magnitude[i], &phase[i]);
RectToPolarD(real[i+1], imaginary[i+1], &magnitude[i+1], &phase[i+1]);
RectToPolarD(real[i+2], imaginary[i+2], &magnitude[i+2], &phase[i+2]);
RectToPolarD(real[i+3], imaginary[i+3], &magnitude[i+3], &phase[i+3]);
}
for (i = end; i < length; ++i)
{
RectToPolarD(real[i], imaginary[i], &magnitude[i], &phase[i]);
}
#endif
return NOERR;
}
/*******************************************************************************
MeanSquare */
float
MeanSquare(const float* data, unsigned length)
{
float result = 0.;
#ifdef __APPLE__
vDSP_measqv(data, 1, &result, length);
#else
float scratch[length];
VectorPower(scratch, data, 2, length);
result = VectorSum(scratch, length) / length;
#endif
return result;
}
/*******************************************************************************
MeanSquareD */
double
MeanSquareD(const double* data, unsigned length)
{
double result = 0.;
#ifdef __APPLE__
vDSP_measqvD(data, 1, &result, length);
#else
double scratch[length];
VectorPowerD(scratch, data, 2, length);
result = VectorSumD(scratch, length) / length;
#endif
return result;
}
| {
"alphanum_fraction": 0.4685538344,
"avg_line_length": 24.8352104327,
"ext": "c",
"hexsha": "13355e90d2b15d9bebe36567102b568c05c8e814",
"lang": "C",
"max_forks_count": 15,
"max_forks_repo_forks_event_max_datetime": "2021-01-07T15:46:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-13T15:17:32.000Z",
"max_forks_repo_head_hexsha": "40c6335150d36b212f2d15d0f6fdf971daecdaab",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hamiltonkibbe/FutureTechAudio",
"max_forks_repo_path": "FxDSP/src/Dsp.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "40c6335150d36b212f2d15d0f6fdf971daecdaab",
"max_issues_repo_issues_event_max_datetime": "2018-04-27T15:15:49.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-27T15:15:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "hamiltonkibbe/FutureTechAudio",
"max_issues_repo_path": "FxDSP/src/Dsp.c",
"max_line_length": 90,
"max_stars_count": 46,
"max_stars_repo_head_hexsha": "b96820fa8a7916e4c925657eed70d92ae3d6b917",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "akshaynannaware/FxDSP",
"max_stars_repo_path": "FxDSP/src/Dsp.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-08T15:58:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-06T13:26:12.000Z",
"num_tokens": 11718,
"size": 41897
} |
/// @file
/// @brief shared pointers to gsl types
/// @details We use gsl for linear algebra routines. However, the interface is C-like and is based on
/// raw pointers. The file contains code to leverage on boost shared pointer and use it with gsl types
/// such as vector and matrix.
///
/// @copyright (c) 2008 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
#ifndef ASKAP_SCIMATH_SHARED_GSL_TYPES_H
#define ASKAP_SCIMATH_SHARED_GSL_TYPES_H
// boost includes
#include <boost/shared_ptr.hpp>
#include <boost/static_assert.hpp>
// gsl includes
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_eigen.h>
// own includes
#include "askap/AskapError.h"
namespace askap {
namespace utility {
// typedefs for shared pointers, we can add more here when needed
/// @brief shared pointer to gsl vector
/// @ingroup utils
typedef boost::shared_ptr<gsl_vector> SharedGSLVector;
/// @brief shared pointer to gsl matrix
/// @ingroup utils
typedef boost::shared_ptr<gsl_matrix> SharedGSLMatrix;
/// @brief custom deleter for gsl types
/// @details This is a custom deleter class to allow deallocation of
/// a gsl object. Exact operation should be present in specialised types
/// @ingroup utils
template<typename GSLType> struct CustomGSLDeleter {
/// @brief this method frees the object
/// @param[in] obj pointer to gsl object
void operator()(GSLType *obj) const { BOOST_STATIC_ASSERT_MSG(sizeof(GSLType) == 0,
"Generic version is not supposed to be used - specialise it for your type"); }
};
/// @brief specialised deleter for a gsl vector
/// @ingroup utils
template<> struct CustomGSLDeleter<gsl_vector> {
/// @brief this method frees the object
/// @param[in] obj pointer to gsl vector
void operator()(gsl_vector *obj) const;
};
/// @brief specialised deleter for a gsl matrix
/// @ingroup utils
template<> struct CustomGSLDeleter<gsl_matrix> {
/// @brief this method frees the object
/// @param[in] obj pointer to gsl matrix
void operator()(gsl_matrix *obj) const;
};
/// @brief specialised deleter for a gsl eigen_symmv_workspace
/// @ingroup utils
template<> struct CustomGSLDeleter<gsl_eigen_symmv_workspace> {
/// @brief this method frees the object
/// @param[in] obj pointer to gsl eigen_symmv_workspace
void operator()(gsl_eigen_symmv_workspace *obj) const;
};
/// @brief templated helper method to wrap newly allocated gsl object
/// @details This method processes a pointer to a gsl object and transfers the ownership (i.e.
/// responsibility for deallocation to the boost shared pointer. Templates are used to automatically
/// deduce the object type and add an appropriate deleter.
/// @note the pointer passed as a parameter is tested to be non-zero. Otherwise an exception is thrown.
/// @param[in] obj a pointer to gsl object
/// @return boost shared pointer to the object
template<typename GSLType>
inline boost::shared_ptr<GSLType> createGSLObject(GSLType *obj)
{ ASKAPASSERT(obj); return boost::shared_ptr<GSLType>(obj, CustomGSLDeleter<GSLType>()); }
/// @brief helper method to allocate gsl vector
/// @details This method allocates a gsl vector of requested length and returns a
/// shared pointer.
/// @param[in] size size of the vector
/// @return shared pointer to gsl vector
inline SharedGSLVector createGSLVector(size_t size) { return createGSLObject(gsl_vector_alloc(size));}
/// @brief helper method to allocate gsl matrix
/// @details This method allocates a gsl matrix of requested shape and returns a
/// shared pointer.
/// @param[in] nrow number of rows
/// @param[in] ncol number of columns
/// @return shared pointer to gsl matrix
inline SharedGSLMatrix createGSLMatrix(size_t nrow, size_t ncol) { return createGSLObject(gsl_matrix_alloc(nrow,ncol));}
} // namespace utility
} // namespace askap
#endif // #ifndef ASKAP_SCIMATH_SHARED_GSL_TYPES_H
| {
"alphanum_fraction": 0.7391922062,
"avg_line_length": 37.3257575758,
"ext": "h",
"hexsha": "8e70ef5aa18a44f03652c4626e89ec47b804d437",
"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": "d839c052d5c62ad8a511e58cd4b6548491a6006f",
"max_forks_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_forks_repo_name": "ATNF/askapsoft",
"max_forks_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_issues_repo_name": "ATNF/askapsoft",
"max_issues_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h",
"max_line_length": 120,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e",
"max_stars_repo_licenses": [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
],
"max_stars_repo_name": "rtobar/askapsoft",
"max_stars_repo_path": "Code/Base/scimath/current/utils/SharedGSLTypes.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z",
"num_tokens": 1194,
"size": 4927
} |
/*
* VGMTrans (c) 2002-2019
* Licensed under the zlib license,
* refer to the included LICENSE.txt file
*/
#pragma once
#include <string>
#include <sstream>
#include <cassert>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <climits>
#include <algorithm>
#include <vector>
#include <gsl-lite.hpp>
#include "helper.h"
#define VERSION "1.0.3"
/* Type aliases to save some typing */
using size_t = std::size_t;
using s8 = std::int8_t;
using s16 = std::int16_t;
using s32 = std::int32_t;
using s64 = std::int64_t;
using sptr = std::intptr_t;
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using uptr = std::uintptr_t;
std::string removeExtFromPath(const std::string &s);
std::string StringToUpper(std::string myString);
std::string StringToLower(std::string myString);
uint32_t StringToHex(const std::string &str);
std::string ConvertToSafeFileName(const std::string &str);
inline int CountBytesOfVal(uint8_t *buf, uint32_t numBytes, uint8_t val) {
int count = 0;
for (uint32_t i = 0; i < numBytes; i++)
if (buf[i] == val)
count++;
return count;
}
struct SizeOffsetPair {
uint32_t size;
uint32_t offset;
SizeOffsetPair() : size(0), offset(0) {}
SizeOffsetPair(uint32_t offset_, uint32_t size_) : size(size_), offset(offset_) {}
};
char *GetFileWithBase(const char *f, const char *newfile);
std::vector<char> zdecompress(gsl::span<const char> data);
std::vector<char> zdecompress(std::vector<char> &data);
| {
"alphanum_fraction": 0.6951456311,
"avg_line_length": 22.3913043478,
"ext": "h",
"hexsha": "051df407ac6c24a278726803bd92e8a2f2eb2c12",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-10-19T16:40:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-19T16:40:12.000Z",
"max_forks_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe",
"max_forks_repo_licenses": [
"Zlib"
],
"max_forks_repo_name": "sykhro/vgmtrans-qt",
"max_forks_repo_path": "src/main/util/common.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe",
"max_issues_repo_issues_event_max_datetime": "2021-09-10T15:26:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-19T16:47:19.000Z",
"max_issues_repo_licenses": [
"Zlib"
],
"max_issues_repo_name": "sykhro/vgmtrans-qt",
"max_issues_repo_path": "src/main/util/common.h",
"max_line_length": 86,
"max_stars_count": 18,
"max_stars_repo_head_hexsha": "6d0780bdaaac29ffe118b9be2e2ad87401b426fe",
"max_stars_repo_licenses": [
"Zlib"
],
"max_stars_repo_name": "sykhro/vgmtrans-qt",
"max_stars_repo_path": "src/main/util/common.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-26T02:52:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-04T17:42:15.000Z",
"num_tokens": 442,
"size": 1545
} |
///
/// @file
///
/// @author Angelika Schwarz (angies@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_config.h>
#include <starneig/configuration.h>
#include "typedefs.h"
#include "cpu.h"
// #include "tasks.h" // <--- moved to misc/
#include "robust.h"
#include "../../common/common.h"
#include "../../common/tiles.h"
#include <starpu.h>
#include <cblas.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
static double vec_real_infnorm(int n, const double *x)
{
double norm = 0.0;
for (int i = 0; i < n; ++i) {
double abs = fabs(x[i]);
if (abs > norm)
norm = abs;
}
return norm;
}
static double vec_cmplx_infnorm(int n, const double *x_re, const double *x_im)
{
double norm = 0.0;
for (int i = 0; i < n; ++i) {
// Compute len = sqrt(x_re[i]*x_re[i]+x_im[i]*x_im[i]) robustly.
double maxabs = MAX(fabs(x_re[i]), fabs(x_im[i]));
double len = maxabs*sqrt( (x_re[i]/maxabs)*(x_re[i]/maxabs)
+ (x_im[i]/maxabs)*(x_im[i]/maxabs));
if (len > norm)
norm = len;
}
return norm;
}
static double mat_infnorm(int m, int n, const double *A, int ldA)
{
#define A(i,j) A[(i) + (j) * (size_t)ldA]
double *rowsums = calloc(m, sizeof(double));
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; i++)
rowsums[i] += fabs(A(i,j));
double norm = rowsums[0];
for (int i = 1; i < m; i++)
if (rowsums[i] > norm)
norm = rowsums[i];
free(rowsums);
return norm;
#undef A
}
static void find_max(
int num_rows, int num_selected, int n,
const double *restrict const X, int ldX,
const int *restrict const lambda_type, const int *restrict const selected,
double *restrict emax)
{
int si = num_selected-1;
for (int ki = n-1; ki >= 0; ki--) {
if (!selected[ki]) {
// Proceed with the next eigenvalue.
if (lambda_type[ki] == 1) { // CMPLX
// A complex conjugate pair of eigenvalues is not selected, so
// skip the next diagonal entry.
ki--;
}
}
else { // ki-th eigenvalue is selected
if (lambda_type[ki] == 0) { // REAL
// Locate eigenvector to ki-th eigenvalue.
const double *X_re = X+si*(size_t)ldX;
// Find max entry.
emax[si] = vec_real_infnorm(num_rows, X_re);
si--;
}
else { // CMPLX
// Locate real and imaginary part of complex eigenvector for
// complex conjugate pair of eigenvalues (ki, ki-1).
const double *X_re = X+(si-1)*(size_t)ldX;
const double *X_im = X+si*(size_t)ldX;
// Find max entry.
emax[si] = 0.0;
for (int i = 0; i < num_rows; i++)
if (fabs(X_re[i])+fabs(X_im[i]) > emax[si])
emax[si] = fabs(X_re[i])+fabs(X_im[i]);
// Duplicate max entry for real and imaginary column.
emax[si-1] = emax[si];
ki--;
si -= 2;
}
}
}
}
void starneig_eigvec_std_unify_scaling(int num_tiles, int *first_row, int *first_col,
scaling_t *restrict scales,
double *restrict X, int ldX,
const int *restrict lambda_type, const int *restrict selected)
{
// TODO: Is it possible to add a #pragma parallel for here?
const int num_selected = first_col[num_tiles];
//
// Compute the most constraining scaling factor.
//
scaling_t *smin = (scaling_t *) malloc(num_selected*sizeof(scaling_t));
starneig_eigvec_std_init_scaling_factor(num_selected, smin);
starneig_eigvec_std_find_smallest_scaling(num_tiles, num_selected, scales, smin);
#ifndef STARNEIG_ENABLE_INTEGER_SCALING
//
// Check if the range of double-precision scaling factors was sufficient
// and replace flushed entries with 1/Omega to avoid NaNs.
//
for (int i = 0; i < num_selected; i++) {
if (smin[i] == 0.0) {
if (lambda_type[i] == 1) { // CMPLX
starneig_warning("Scaling factor of complex eigenvector "
"X(:,%d:%d) was flushed. Rerun with integer "
"scaling factors.", i, i+1);
smin[i] = DBL_MIN;
smin[i+1] = DBL_MIN;
i++;
}
else { // REAL
starneig_warning("Scaling factor of real eigenvector X(:,%d) "
"was flushed. Rerun with integer "
"scaling factors.", i);
smin[i] = DBL_MIN;
}
}
}
for (int i = 0; i < (size_t)num_tiles*num_selected;i++)
if (scales[i] == 0.0)
scales[i] = DBL_MIN;
#endif
double *tmp = (double *) malloc(num_selected * sizeof(double));
double *emax = (double *) malloc(num_selected * sizeof(double));
memset(emax, 0.0, num_selected * sizeof(double));
#define scales(col, tilerow) scales[(col) + (tilerow) * (size_t)num_selected]
for (int blkj = 0; blkj < num_tiles; blkj++) {
for (int blki = 0; blki <= blkj; blki++) {
const int num_rows = first_row[blki+1]-first_row[blki];
const int num_sel = first_col[blkj+1]-first_col[blkj];
const int num_cols = first_row[blkj+1]-first_row[blkj];
double *tile = X+(size_t)first_col[blkj]*ldX+first_row[blki];
const int *lambda_type_tile = lambda_type+first_row[blkj];
const int *selected_tile = selected+first_row[blkj];
double *tmp_tile = tmp+first_col[blkj];
memset(tmp_tile, 0.0, num_sel*sizeof(double));
find_max(num_rows, num_sel, num_cols,
tile, ldX, lambda_type_tile, selected_tile, tmp_tile);
// Reduce to maximum normalization factor.
for (int j = first_col[blkj]; j < first_col[blkj+1]; j++) {
// Compute normalization factor simulating consistent scaling.
double s = starneig_eigvec_std_compute_upscaling(smin[j], scales(j, blki));
emax[j] = MAX(s * tmp[j], emax[j]);
}
}
// Apply scaling.
for (int blki = 0; blki <= blkj; blki++) {
const int num_rows = first_row[blki+1]-first_row[blki];
const int num_cols = first_col[blkj+1]-first_col[blkj];
// Scale column.
for (int j = 0; j < num_cols; j++) {
// The current column index.
size_t col = (size_t)first_col[blkj]+j;
// The current column.
double *x = X+col*ldX+first_row[blki];
double s =
starneig_eigvec_std_compute_upscaling(smin[col], scales(col, blki));
// Avoid oo.
if (isinf(s))
s = DBL_MIN;
for (int i = 0; i < num_rows; i++)
x[i] = (s*x[i])/emax[col];
}
}
}
free(tmp);
free(emax);
#undef scales
}
void starneig_eigvec_std_cpu_bound_DM(void *buffers[], void *cl_args)
{
struct packing_info packing_info;
starpu_codelet_unpack_args(cl_args, &packing_info);
// extract tile dimensions from the packing information struct
int m = packing_info.rend - packing_info.rbegin;
int n = packing_info.cend - packing_info.cbegin;
int k = 0;
double *norm = (double *) STARPU_VARIABLE_GET_PTR(buffers[k]);
k++;
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldT = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += packing_info.handles;
starneig_join_diag_window(&packing_info, ldT, A_i, T, 0);
*norm = mat_infnorm(m, n, T, ldT);
}
void starneig_eigvec_std_cpu_bound(void *buffers[], void *cl_args)
{
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int ldT = STARPU_MATRIX_GET_LD(buffers[0]);
int m = STARPU_MATRIX_GET_NX(buffers[0]);
int n = STARPU_MATRIX_GET_NY(buffers[0]);
double *tnorm = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);
double ub = mat_infnorm(m, n, T, ldT);
*tnorm = ub;
}
static void backsolve(
int n, const double *restrict T, int ldT, double tnorm,
double *restrict X, int ldX, scaling_t *restrict const scales,
double *restrict Xnorms, const int *restrict lambda_type,
const int *restrict selected, int num_selected,
double smlnum, int *restrict infos)
{
#define T(i,j) T[(i) + (j) * (size_t)ldT]
// Solve T * X = X * \Lambda.
// The i-th selected eigenvalue.
int si = num_selected-1;
// Loop over eigenvalues from bottom to top.
for (int ki = n-1; ki >= 0; ki--) {
if (!selected[ki]) {
// Proceed with the next eigenvalue.
if (lambda_type[ki] == 1) { // CMPLX
// A complex conjugate pair of eigenvalues is not selected,
// so skip the next diagonal entry.
ki--;
}
}
else { // ki-th eigenvalue is selected
// Error flag.
int info = 0;
if (lambda_type[ki] == 0) {
// Compute a real right eigenvector.
double lambda = T(ki,ki);
// Locate eigenvector to ki-th eigenvalue.
double *X_re = X+si*(size_t)ldX;
// Locate corresponding scaling factor.
scaling_t *beta = scales+si;
// Critical threshold to detect unsafe divisions.
const double smin = MAX(DBL_EPSILON/2*fabs(lambda), smlnum);
// Form right-hand side.
X_re[ki] = 1.0;
for (int i = 0; i < ki; i++)
X_re[i] = -T(i, ki);
for (int i = ki+1; i < n; i++)
X_re[i] = 0.0;
// Compute norm of entire vector.
double norm = vec_real_infnorm(ki+1, X_re);
// Solve the upper quasi-triangular system.
// (T(0:ki-1,0:ki-1) - lambda I) \ X.
for (int j = ki-1; j >= 0; j--) {
// if next block is 1-by-1 diagonal block:
if (lambda_type[j] == 0) { // REAL
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_1x1_real_system(
smin, T(j,j), lambda, X_re+j, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale remaining parts of the vector.
starneig_eigvec_std_scale(j, X_re, &phi);
starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the linear update.
phi =
starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
// Now it is safe to execute the linear update.
for (int i = 0; i < j; i++)
X_re[i] = X_re[i]-T(i,j)*X_re[j];
// Recompute norm excluding the entries j:n.
norm = vec_real_infnorm(j, X_re);
}
// if next block is 2-by-2 diagonal block:
else {
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_2x2_real_system(smin,
&T(j-1,j-1), ldT, lambda, &X_re[j-1], &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale remaining parts of vector.
starneig_eigvec_std_scale(j-1, X_re, &phi);
starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the first linear update.
phi = starneig_eigvec_std_protect_update(
tnorm, fabs(X_re[j-1]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
// Now it is safe to execute the first linear update.
for (int i = 0; i < j-1; i++)
X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];
// Recompute norm excluding the entries j:n.
norm = vec_real_infnorm(j, X_re);
// Protect against overflow in the second linear update.
phi =
starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
// Now it is safe to execute the second linear update.
for (int i = 0; i < j-1; i++)
X_re[i] = X_re[i]-T(i,j)*X_re[j];
// Recompute norm excluding the entries j-1:n.
norm = vec_real_infnorm(j-1, X_re);
// We processed a 2-by-2 block, so skip the next entry.
j--;
}
}
// The ki-th real eigenvector has been computed. Recompute norm.
Xnorms[si] = vec_real_infnorm(ki+1, X_re);
// Record error flag.
infos[si] = info;
// This eigenvector spans 1 column. Update selected counter.
si--;
}
else { // lambda_type[ki] == CMPLX
// Locate real and imaginary part of complex eigenvector for
// complex conjugate pair of eigenvalues (ki, ki-1).
double *X_re = X+(si-1)*(size_t)ldX;
double *X_im = X+si*(size_t)ldX;
// Locate corresponding scaling factor, one per complex pair.
scaling_t *beta = scales+si;
// Compute eigenvalue as lambda = lambda_re + i * lambda_im.
// A 2-by-2 block in canonical Schur form has the shape
// [ T(ki-1,ki-1) T(ki-1,ki) ] = [ a b ] or [ a -b ]
// [ T(ki, ki-1) T(ki, ki) ] [-c a ] [ c a ].
double lambda_re = T(ki,ki);
double lambda_im =
sqrt(fabs(T(ki,ki-1)))*sqrt(fabs(T(ki-1,ki)));
// Critical threshold to detect unsafe divisions.
const double smin = MAX(
DBL_EPSILON/2*(fabs(lambda_re)+fabs(lambda_im)), smlnum);
// Form right-hand side.
if (fabs(T(ki-1,ki)) >= fabs(T(ki,ki-1))) {
X_re[ki-1] = 1.0;
X_im[ki] = lambda_im/T(ki-1,ki);
}
else {
X_re[ki-1] = -lambda_im/T(ki,ki-1);
X_im[ki] = 1.0;
}
X_re[ki] = 0.0;
X_im[ki-1] = 0.0;
for (int i = 0; i < ki-1; i++) {
X_re[i] = -X_re[ki-1]*T(i,ki-1);
X_im[i] = -X_im[ki]*T(i,ki);
}
for (int i = ki+1; i < n; i++) {
X_re[i] = 0.0;
X_im[i] = 0.0;
}
// Compute norm of the entire vector.
double norm = vec_cmplx_infnorm(ki+1, X_re, X_im);
// Solve the upper quasi-triangular system
// (T(0:ki-2,0:ki-2) - (lambda * I) \ (X_re + i * X_im).
// Loop over triangular matrix above the eigenvalue. Note ki-2!
for (int j = ki-2; j >= 0; j--) {
// If next block is 1-by-1 diagonal bock:
if (lambda_type[j] == 0) { // REAL
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_1x1_cmplx_system(
smin, T(j,j), lambda_re, lambda_im,
X_re+j, X_im+j, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale the remaining parts of the vector.
starneig_eigvec_std_scale(j, X_re, &phi);
starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_scale(j, X_im, &phi);
starneig_eigvec_std_scale(ki-(j+1), X_im+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the linear update.
double absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
starneig_eigvec_std_scale(ki+1, X_im, &phi);
// Now it is safe to execute the linear update.
for (int i = 0; i < j; i++) {
X_re[i] = X_re[i]-T(i,j)*X_re[j];
X_im[i] = X_im[i]-T(i,j)*X_im[j];
}
// Recompute norm excluding the entries j:n.
norm = vec_cmplx_infnorm(j, X_re, X_im);
}
// If next block is 2-by-2 diagonal block:
else {
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_2x2_cmplx_system(
smin, &T(j-1,j-1), ldT, lambda_re, lambda_im,
X_re+j-1, X_im+j-1, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale the remaining parts of the vector.
starneig_eigvec_std_scale(j-1, X_re, &phi);
starneig_eigvec_std_scale(ki-j, X_re+(j+1), &phi);
starneig_eigvec_std_scale(j-1, X_im, &phi);
starneig_eigvec_std_scale(ki-j, X_im+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the first linear update.
double absmax = MAX(fabs(X_re[j-1]), fabs(X_im[j-1]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
starneig_eigvec_std_scale(ki+1, X_im, &phi);
// Now it is safe to execute the first linear update.
for (int i = 0; i < j-1; i++) {
X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];
X_im[i] = X_im[i]-T(i,j-1)*X_im[j-1];
}
// Recompute norm excluding the entries j+1:n.
norm = vec_cmplx_infnorm(j+1, X_re, X_im);
// Protect against overflow in the second linear update.
absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(ki+1, X_re, &phi);
starneig_eigvec_std_scale(ki+1, X_im, &phi);
// Now it is safe to execute the second linear update.
for (int i = 0; i < j-1; i++) {
X_re[i] = X_re[i]-T(i,j)*X_re[j];
X_im[i] = X_im[i]-T(i,j)*X_im[j];
}
// Recompute norm excluding the entries j:n.
norm = vec_cmplx_infnorm(j-1, X_re, X_im);
// We processed a 2-by-2 block, so skip the next entry.
j--;
}
}
// Note that the second column of a complex conjugate pair is
// never allocated or computed. Obtaining it is left to the
// user. If the positions si - 1, si mark a 2-by-2 block, then
// the eigenvector corresponding to lambda = alpha + i beta
// is X(:, si - 1) + i * X(:, si).
// The complex conjugate eigenvector corresponding to
// lambda = alpha - i beta can be derived as
// conj(X) := X(:, si -1) - i * X(:, si).
// The real part and the imaginary part are scaled alike.
scales[si-1] = scales[si];
// The ki-th complex eigenvector has been computed. Recompute
// norm of the complex eigenvector.
Xnorms[si] = vec_cmplx_infnorm(ki+1, X_re, X_im);
Xnorms[si-1] = Xnorms[si];
// Record error flag.
infos[si] = info;
infos[si-1] = info;
// We processed a complex conjugate pair of eigenvalues,
// so skip the next entry.
ki--;
// This eigenvector spans 2 columns. Update selected counter.
si -= 2;
}
}
}
// Note that the eigenvectors are not normalized.
#undef T
}
void starneig_eigvec_std_cpu_backsolve(void *buffers[], void *cl_args)
{
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int n = STARPU_MATRIX_GET_NX(buffers[0]);
int ldT = STARPU_MATRIX_GET_LD(buffers[0]);
double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);
double tnorm = *ubT;
double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);
int num_selected = STARPU_MATRIX_GET_NY(buffers[2]);
int ldX = STARPU_MATRIX_GET_LD(buffers[2]);
scaling_t *scales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);
double *Xnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);
int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[5]);
int *selected = (int *) STARPU_VECTOR_GET_PTR(buffers[6]);
int *infos = (int *) STARPU_VECTOR_GET_PTR(buffers[7]);
double smlnum;
starpu_codelet_unpack_args(cl_args, &smlnum);
backsolve(n, T, ldT, tnorm, X, ldX, scales, Xnorms, lambda_type,
selected, num_selected, smlnum, infos);
}
void starneig_eigvec_std_cpu_solve(void *buffers[], void *cl_args)
{
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int n = STARPU_MATRIX_GET_NX(buffers[0]);
int ldT = STARPU_MATRIX_GET_LD(buffers[0]);
double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);
double tnorm = *ubT;
double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);
int num_selected = STARPU_MATRIX_GET_NY(buffers[2]);
int ldX = STARPU_MATRIX_GET_LD(buffers[2]);
scaling_t *scales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);
double *Xnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);
double *lambda = (double *) STARPU_VECTOR_GET_PTR(buffers[5]);
int num_rhs = STARPU_VECTOR_GET_NX(buffers[5]);
int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[6]);
int *selected = (int *) STARPU_VECTOR_GET_PTR(buffers[7]);
int *diag_type = (int *) STARPU_VECTOR_GET_PTR(buffers[8]);
int *infos = (int *) STARPU_VECTOR_GET_PTR(buffers[9]);
double smlnum;
starpu_codelet_unpack_args(cl_args, &smlnum);
#define T(i,j) T[(i) + (j) * (size_t)ldT]
// The i-th selected eigenvalue.
int si = num_selected-1;
// Loop over eigenvalues.
for (int k = num_rhs-1; k >= 0; k--) {
if (!selected[k]) {
// Proceed with the next eigenvalue.
if (lambda_type[k] == 1) { // CMPLX
// A complex conjugate pair of eigenvalues is not selected,
// so skip the next diagonal entry.
k--;
}
}
else { // k-th eigenvalue is selected
// Error flag.
int info = 0;
if (lambda_type[k] == 0) { // REAL
// Locate eigenvector to k-th eigenvalue.
double *X_re = X+si*(size_t)ldX;
// Locate corresponding scaling factor.
scaling_t *beta = scales+si;
// Compute norm of entire vector.
double norm = vec_real_infnorm(n, X_re);
// Critical threshold to detect unsafe divisions.
const double smin = MAX(DBL_EPSILON/2*fabs(lambda[k]), smlnum);
for (int j = n-1; j >= 0; j--) {
// if next block is 1-by-1 diagonal block:
if (diag_type[j] == 0) { // REAL
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_1x1_real_system(
smin, T(j,j), lambda[k], X_re+j, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale remaining parts of vector.
starneig_eigvec_std_scale(j, X_re, &phi);
starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the linear update.
phi =
starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
// Now it is safe to execute the linear update.
for (int i = 0; i < j; i++)
X_re[i] = X_re[i]-T(i,j)*X_re[j];
// Recompute norm excluding the entries j:n.
norm = vec_real_infnorm(j, X_re);
}
// if next block is 2-by-2 block:
else {
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_2x2_real_system(smin,
&T(j-1,j-1), ldT, lambda[k], &X_re[j-1], &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale remaining parts of vector.
starneig_eigvec_std_scale(j-1, X_re, &phi);
starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect first linear update against overflow.
phi = starneig_eigvec_std_protect_update(
tnorm, fabs(X_re[j-1]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
// Now it is safe to execute the linear udpate.
for (int i = 0; i < j-1; i++)
X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];
// Recompute norm excluding the entries j:n.
norm = vec_real_infnorm(j, X_re);
// Protect second linear update against overflow.
phi =
starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply the scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
// Now it is safe to execute the linear update.
for (int i = 0; i < j - 1; i++)
X_re[i] = X_re[i]-T(i,j)*X_re[j];
// Recompute norm excluding the entries j-1:n.
norm = vec_real_infnorm(j-1, X_re);
// We processed a 2-by-2 block, so skip the next
// diagonal entry.
j--;
}
}
// The k-th real eigenvector has been computed.
// Recompute norm.
Xnorms[si] = vec_real_infnorm(n, X_re);
// Record error flag.
infos[si] = info;
// This eigenvalue spans 1 column. Update selected counter.
si--;
}
else { // lambda_type[k] == CMPLX
// Locate real and imaginary part of complex eigenvector
// for complex conjugate pair of eigenvalues (k, k-1).
double *X_re = X+(si-1)*(size_t)ldX;
double *X_im = X+si*(size_t)ldX;
// The eigenvalue is lambda = lambda_re+i*lambda_im.
double lambda_re = lambda[k-1];
double lambda_im = fabs(lambda[k]);
// Locate corresponding scaling factor.
scaling_t *beta = scales+si;
// Compute norm of entire vector.
double norm = vec_cmplx_infnorm(n, X_re, X_im);
// Critical threshold to detect unsafe divisions.
const double smin = MAX(
DBL_EPSILON/2*(fabs(lambda_re)+fabs(lambda_im)), smlnum);
for (int j = n-1; j >= 0; j--) {
// if the next block is 1-by-1 diagonal block:
if (diag_type[j] == 0) { // REAL
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_1x1_cmplx_system(smin, T(j,j),
lambda_re, lambda_im, X_re+j, X_im+j, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale the remaining parts of the 2 columns.
starneig_eigvec_std_scale(j, X_re, &phi);
starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_scale(j, X_im, &phi);
starneig_eigvec_std_scale(n-(j+1), X_im+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the linear update.
double absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
starneig_eigvec_std_scale(n, X_im, &phi);
// Now it is safe to execute the linear update.
for (int i = 0; i < j; i++) {
X_re[i] = X_re[i]-T(i,j)*X_re[j];
X_im[i] = X_im[i]-T(i,j)*X_im[j];
}
// Recompute norm excluding the entries j:n.
norm = vec_cmplx_infnorm(j, X_re, X_im);
}
// if next block is 2-by-2 diagonal block:
else {
scaling_t phi;
starneig_eigvec_std_init_scaling_factor(1, &phi);
info |= starneig_eigvec_std_solve_2x2_cmplx_system(smin,
&T(j-1,j-1), ldT, lambda_re, lambda_im,
X_re+j-1, X_im+j-1, &phi);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Scale remaining parts of vector.
starneig_eigvec_std_scale(j-1, X_re, &phi);
starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);
starneig_eigvec_std_scale(j-1, X_im, &phi);
starneig_eigvec_std_scale(n-(j+1), X_im+(j+1), &phi);
starneig_eigvec_std_update_norm(&norm, phi);
// Protect against overflow in the first linear update.
double absmax = MAX(fabs(X_re[j-1]), fabs(X_im[j-1]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
starneig_eigvec_std_scale(n, X_im, &phi);
// Now it is safe to execute the first linear update.
for (int i = 0; i < j-1; i++) {
X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];
X_im[i] = X_im[i]-T(i,j-1)*X_im[j-1];
}
// Recompute norm excluding the entries j+1:n.
norm = vec_cmplx_infnorm(j+1, X_re, X_im);
// Protect against overflow in the second linear update.
absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));
phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);
starneig_eigvec_std_update_global_scaling(beta, phi);
// Apply scaling to the whole eigenvector.
starneig_eigvec_std_scale(n, X_re, &phi);
starneig_eigvec_std_scale(n, X_im, &phi);
// Now it is safe to execute the second linear update.
for (int i = 0; i < j-1; i++) {
X_re[i] = X_re[i]-T(i,j)*X_re[j];
X_im[i] = X_im[i]-T(i,j)*X_im[j];
}
// Recompute norm excluding the entries j-1:n.
norm = vec_cmplx_infnorm(j-1, X_re, X_im);
// We processed a 2-by-2 block, so skip the next
// diagonal entry.
j--;
}
}
// Note that the second column of a complex conjugate pair is
// never allocated or computed. Obtaining it is left to the
// user. If the positions si - 1, si mark a 2-by-2 block, then
// the eigenvector corresponding to lambda = alpha + i beta
// is X(:, si - 1) + i * X(:, si).
// The complex conjugate eigenvector corresponding to
// lambda = alpha - i beta can be derived as
// conj(X) := X(:, si -1) - i * X(:, si).
// The real part and the imaginary part are scaled alike.
scales[si-1] = scales[si];
// The ki-th complex eigenvector has been computed.
// Recompute norm of the complex eigenvector.
Xnorms[si] = vec_cmplx_infnorm(n, X_re, X_im);
Xnorms[si-1] = Xnorms[si];
// Record error flag.
infos[si] = info;
infos[si-1] = info;
// We processed a complex conjugate pair of eigenvalues,
// so skip the next entry.
k--;
// This eigenvector spans 2 cols. Update selected counter.
si -= 2;
}
}
}
#undef T
}
void starneig_eigvec_std_cpu_update(void *buffers[], void *cl_args)
{
// T is n-by-m.
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int ldT = STARPU_MATRIX_GET_LD(buffers[0]);
int n = STARPU_MATRIX_GET_NX(buffers[0]);
int m = STARPU_MATRIX_GET_NY(buffers[0]);
double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);
double tnorm = *ubT;
double *Xin = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);
int num_rhs = STARPU_MATRIX_GET_NY(buffers[2]);
int ldX = STARPU_MATRIX_GET_LD(buffers[2]);
scaling_t *Xscales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);
double *Xinnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);
double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[5]);
int ldY = STARPU_MATRIX_GET_LD(buffers[5]);
scaling_t *Yscales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[6]);
double *Ynorms = (double *) STARPU_VECTOR_GET_PTR(buffers[7]);
int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[8]);
// Pointer to X - either a copy or the original memory.
double *X;
// Pointer to norms of X - either a copy or the original memory.
double *Xnorms;
// Status flag if X has to be rescaled.
int rescale_X = 0;
// Status flag if Y has to be rescaled.
int rescale_Y = 0;
// Indicator if xinnorms has to be rescaled. Note that this only affects
// consistency scaling and not overflow protection.
int rescale_xnorms = 0;
// Workspace to store locally computed scaling factors.
scaling_t tmp_scales[num_rhs];
//
// Compute scaling factor.
//
for (int k = 0; k < num_rhs; k++) {
if (Yscales[k] < Xscales[k]) {
rescale_xnorms = 1;
break;
}
}
if (rescale_xnorms) {
// As X is read-only, copy xnorms.
Xnorms = (double *) malloc(num_rhs * sizeof(double));
memcpy(Xnorms, Xinnorms, num_rhs * sizeof(double));
// Simulate the consistency scaling.
for (int k = 0; k < num_rhs; k++) {
if (Yscales[k] < Xscales[k]) {
// The common scaling factor is Yscales[k].
const double s =
starneig_eigvec_std_compute_upscaling(Yscales[k], Xscales[k]);
// Mark X for scaling. Physical rescaling is deferred.
rescale_X = 1;
// Update norm.
Xnorms[k] = s*Xinnorms[k];
}
else if (Xscales[k] < Yscales[k]) {
// The common scaling factor is Xscales[k].
const double s =
starneig_eigvec_std_compute_upscaling(Xscales[k], Yscales[k]);
// Mark Y for scaling. Physical rescaling is deferred.
rescale_Y = 1;
// Update norm: norm(s * Y) = s * norm(Y).
Ynorms[k] = s*Ynorms[k];
}
}
}
else { // !rescale_xnorms
// No changes to Xinnorms necessary. Operate on original memory.
Xnorms = Xinnorms;
// Xnorms does not need scaling, but Ynorms may do.
for (int k = 0; k < num_rhs; k++) {
if (Xscales[k] < Yscales[k]) {
// The common scaling factor is Xscales[k].
const double s =
starneig_eigvec_std_compute_upscaling(Xscales[k], Yscales[k]);
// Mark Y for scaling. Phyiscal rescaling is deferred.
rescale_Y = 1;
// Update norm: norm(s * Y) = s * norm(Y).
Ynorms[k] = s*Ynorms[k];
}
}
}
//
// Apply scaling.
//
// Status flag if update is safe to execute or if rescaling is required.
int rescale;
// Compute scaling factors needed to survive the linear update.
rescale = starneig_eigvec_std_protect_multi_rhs_update(
Xnorms, num_rhs, tnorm, Ynorms, lambda_type, tmp_scales);
if (rescale) {
rescale_X = 1;
rescale_Y = 1;
}
// If X has to be rescaled, take a copy of X and do scaling on the copy.
if (rescale_X) {
X = (double *) malloc((size_t)ldX * num_rhs * sizeof(double));
for (int k = 0; k < num_rhs; k++) {
if (Yscales[k] < Xscales[k]) {
// Copy X and simultaneously rescale.
const double s = starneig_eigvec_std_compute_combined_upscaling(
Yscales[k], Xscales[k], tmp_scales[k]);
for (int i = 0; i < m; i++)
X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];
}
else if (Xscales[k] < Yscales[k]) {
// Copy X and simultaneously rescale with robust update factor.
const double s = starneig_eigvec_std_convert_scaling(tmp_scales[k]);
for (int i = 0; i < m; i++)
X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];
}
else {
// Xscales[k] == Yscales[k].
// Copy X and simultaneously rescale with robust update factor.
const double s = starneig_eigvec_std_convert_scaling(tmp_scales[k]);
for (int i = 0; i < m; i++)
X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];
}
}
}
else { // !rescale_X
// No changes to X necessary. Operate on original memory.
X = Xin;
}
// If Y has to be rescaled, directly modify Y.
if (rescale_Y) {
for (int k = 0; k < num_rhs; k++) {
if (Yscales[k] < Xscales[k]) {
// The common scaling factor is Yscales[k]. Rescale Y with
// robust update factor, if necessary.
starneig_eigvec_std_scale(n, Y+(size_t)ldY*k, tmp_scales+k);
}
else if (Xscales[k] < Yscales[k]) {
// The common scaling factor is Xscales[k]. Combine with
// robust update scaling factor.
const double s = starneig_eigvec_std_compute_combined_upscaling(
Xscales[k], Yscales[k], tmp_scales[k]);
for (int i = 0; i < n; i++)
Y[(size_t)ldY*k+i] = s*Y[(size_t)ldY*k+i];
}
else {
// Xscales[k] == Yscales[k].
// Rescale Y with robust update factor, if necessary.
starneig_eigvec_std_scale(n, Y+(size_t)ldY*k, tmp_scales+k);
}
}
}
//
// Update global scaling of Y.
//
#ifdef STARNEIG_ENABLE_INTEGER_SCALING
for (int k = 0; k < num_rhs; k++)
Yscales[k] = MIN(Yscales[k], Xscales[k])+tmp_scales[k];
#else
for (int k = 0; k < num_rhs; k++)
Yscales[k] = MIN(Yscales[k], Xscales[k])*tmp_scales[k];
#endif
//
// Compute update.
//
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n, num_rhs, m, -1.0, T, ldT, X, ldX, 1.0, Y, ldY);
//
// Recompute norms.
//
for (int k = 0; k < num_rhs; k++) {
if (lambda_type[k] == 1) { // CMPLX
// We store only one scaling factor per complex eigenvector pair.
// So interpret columns as real and imaginary part.
const double *Y_re = Y+(size_t)k*ldY;
const double *Y_im = Y+(size_t)(k+1)*ldY;
Ynorms[k] = vec_cmplx_infnorm(n, Y_re, Y_im);
// Duplicate norm for real and imaginary column.
Ynorms[k+1] = Ynorms[k];
k++;
}
else { // lambda_type[k] == REAL
Ynorms[k] = vec_real_infnorm(n, Y+(size_t)k*ldY);
}
}
//
// Clean up.
//
if (rescale_X)
free(X);
if (rescale_xnorms)
free(Xnorms);
}
void starneig_eigvec_std_cpu_backtransform(void *buffers[], void *cl_args)
{
double *Q = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int ldQ = STARPU_MATRIX_GET_LD(buffers[0]);
double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[1]);
int ldX = STARPU_MATRIX_GET_LD(buffers[1]);
double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);
int ldY = STARPU_MATRIX_GET_LD(buffers[2]);
int m = STARPU_MATRIX_GET_NX(buffers[2]);
int n = STARPU_MATRIX_GET_NY(buffers[2]);
int k;
starpu_codelet_unpack_args(cl_args, &k);
// Yij := Qi: * X:j
// (m x n) (m x k) (k x n)
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
m, n, k, 1.0, Q, ldQ, X, ldX, 0.0, Y, ldY);
}
| {
"alphanum_fraction": 0.5146150766,
"avg_line_length": 38.6094385679,
"ext": "c",
"hexsha": "b968012e9057e7c9963bb5a30a84c7ce785c3932",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "src/eigenvectors/standard/cpu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "src/eigenvectors/standard/cpu.c",
"max_line_length": 91,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "src/eigenvectors/standard/cpu.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 11857,
"size": 47451
} |
#if !defined(ISPLAINASCII_H_INCLUDED)
#define ISPLAINASCII_H_INCLUDED
#include "FileEnumerator.h"
#include "Utils.h"
#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <string>
class IsPlainAscii
{
public:
static int usage(::std::ostream& strm, const ::std::string& progName,
const char* pMsg);
IsPlainAscii(::gsl::span<const char*const> args);
int run() const;
IsPlainAscii(const IsPlainAscii&) = delete;
IsPlainAscii& operator=(const IsPlainAscii&) = delete;
IsPlainAscii(IsPlainAscii&&) = delete;
IsPlainAscii& operator=(IsPlainAscii&&) = delete;
PRIVATE_EXCEPT_IN_TEST:
using Path = ::std::filesystem::path;
static void scanFile(const Path& filePath);
static void scanFile2(const Path& filePath, ::std::istream& in,
::std::ostream& out);
static void reportNonAsciiRun(const Path& filePath, unsigned long lineNum,
unsigned long approxColNum, ::std::string& nonAsciiRun, ::std::ostream& out);
FileEnumerator m_fileEnumerator;
};
#endif // ISPLAINASCII_H_INCLUDED
| {
"alphanum_fraction": 0.7465346535,
"avg_line_length": 25.25,
"ext": "h",
"hexsha": "6aac436b4e23e8fb7467ca16705ff079f47f2c62",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "IanEmmons/CmdLineUtil",
"max_forks_repo_path": "IsPlainAscii.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "IanEmmons/CmdLineUtil",
"max_issues_repo_path": "IsPlainAscii.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "IanEmmons/CmdLineUtil",
"max_stars_repo_path": "IsPlainAscii.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 263,
"size": 1010
} |
//
// emu.c
// Created by Earl Lawrence on 11/10/16.
// Modified E Chisari 05/10/17 for CCL
// For details on the license, see ../LICENSE_COSMICEMU
// in this repository.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
#include "ccl_emu17_params.h"
#include "ccl_emu17.h"
// Sizes of stuff
static int m[2] = {111, 36}, neta=2808, peta[2]={7, 28}, rs=8, p=8;
// Kriging basis computed by emuInit
// Sizes of each basis will be peta[ee] and m[ee]
static double KrigBasis[2][28][111];
// Need to combine some things into a big thing.
static double beta[2][28][8];
static double w[2][28][111];
static double lamws[2][28];
static double lamz[2][28];
// Initialization to compute the kriging basis for the two parts
static void emuInit() {
int ee, i, j, k, l;
double cov;
gsl_matrix *SigmaSim;
gsl_vector *b;
// Because of the structure of this emu, I need to do this horrible part first.
// Fill in the correlation lenghths
for(i=0; i<7; i++) {
for(j=0; j<8; j++) {
beta[0][i][j] = beta1[i][j];
}
}
for(i=0; i<28; i++) {
for(j=0; j<8; j++) {
beta[1][i][j] = beta2[i][j];
}
}
// Fill in the PC weights
for(i=0; i<7; i++) {
for(j=0; j<111; j++) {
w[0][i][j] = w1[i][j];
}
}
for(i=0; i<28; i++) {
for(j=0; j<36; j++) {
w[1][i][j] = w2[i][j];
}
}
// Fill in the precisions
for(i=0; i<7; i++) {
lamws[0][i] = lamws1[i];
lamz[0][i] = lamz1[i];
}
for(i=0; i<28; i++) {
lamws[1][i] = lamws2[i];
lamz[1][i] = lamz2[i];
}
// This emu has two parts: one that uses all m[0] of the data for the the first peta[0] components
// and another that uses only the m[1] complete data for the next peta[1] components.
for(ee=0; ee<2; ee++) {
// Allocate some stuff
SigmaSim = gsl_matrix_alloc(m[ee], m[ee]);
b = gsl_vector_alloc(m[ee]);
// Loop over the basis
for(i=0; i<peta[ee]; i++) {
// Loop over the number of simulations
for(j=0; j<m[ee]; j++) {
// Diagonal term
gsl_matrix_set(SigmaSim, j, j, (1.0/lamz[ee][i]) + (1.0/lamws[ee][i]));
// Off-diagonals
for(k=0; k<j; k++) {
// compute the covariance
cov = 0.0;
for(l=0; l<p; l++) {
cov -= beta[ee][i][l]*pow(x[j][l] - x[k][l], 2.0);
} // for(l=0; l<p; l++)
cov = exp(cov) / lamz[ee][i];
// put the covariance where it belongs
gsl_matrix_set(SigmaSim, j, k, cov);
gsl_matrix_set(SigmaSim, k, j, cov);
} // for(k=0; k<j; k++)
// Vector for the PC weights
gsl_vector_set(b, j, w[ee][i][j]);
} // for(j=0; j<m[ee]; j++)
// Cholesky and solve
gsl_linalg_cholesky_decomp(SigmaSim);
gsl_linalg_cholesky_svx(SigmaSim, b);
// Put b where it belongs in the Kriging basis
for(j=0; j<m[ee]; j++) {
KrigBasis[ee][i][j] = gsl_vector_get(b, j);
}
} // for(i=0; i<peta[ee]; i++)
// Clean this up
gsl_matrix_free(SigmaSim);
gsl_vector_free(b);
} // for(ee=0; ee<2; ee+)
} // emuInit()
// Actual emulation
void ccl_pkemu(double *xstar, double **ystar, int* status, ccl_cosmology* cosmo) {
static double inited=0;
int ee, i, j, k;
double wstar[peta[0]+peta[1]];
double Sigmastar[2][peta[1]][m[0]];
double ystaremu[neta];
*ystar=(double *)malloc(sizeof(double)*NK_EMU);
double ybyz[rs];
double logc;
double xstarstd[p];
int zmatch;
gsl_spline *zinterp = gsl_spline_alloc(gsl_interp_cspline, rs);
gsl_interp_accel *accel = gsl_interp_accel_alloc();
// Initialize if necessary
if(inited==0) {
emuInit();
inited = 1;
}
// Transform w_a into (-w_0-w_a)^(1/4)
xstar[6] = pow(-xstar[5]-xstar[6], 0.25);
// Check the inputs to make sure we're interpolating.
for(i=0; i<p; i++) {
if((xstar[i] < xmin[i]) || (xstar[i] > xmax[i])) {
switch(i) {
case 0:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): omega_m must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 1:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): omega_b must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 2:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): sigma8 must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 3:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): h must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 4:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): n_s must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 5:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): w_0 must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 6:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): (-w_0-w_a)^(1/4) must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
case 7:
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): omega_nu must be between %f and %f.\n",
xmin[i], xmax[i]);
break;
}
*status = CCL_ERROR_EMULATOR_BOUND;
ccl_raise_exception(*status, cosmo->status_message);
gsl_spline_free(zinterp);
gsl_interp_accel_free(accel);
return;
}
} // for(i=0; i<p; i++)
if((xstar[p] < z[0]) || (xstar[p] > z[rs-1])) {
ccl_cosmology_set_status_message(cosmo,
"ccl_pkemu(): z must be between %f and %f.\n",
z[0], z[rs-1]);
*status = CCL_ERROR_EMULATOR_BOUND;
ccl_raise_exception(*status, cosmo->status_message);
gsl_spline_free(zinterp);
gsl_interp_accel_free(accel);
return;
}
// Standardize the inputs
for(i=0; i<p; i++) {
xstarstd[i] = (xstar[i] - xmin[i]) / xrange[i];
}
// compute the covariances between the new input and sims for all the PCs.
for(ee=0; ee<2; ee++) {
for(i=0; i<peta[ee]; i++) {
for(j=0; j<m[ee]; j++) {
logc = 0.0;
for(k=0; k<p; k++) {
logc -= beta[ee][i][k]*pow(x[j][k] - xstarstd[k], 2.0);
}
Sigmastar[ee][i][j] = exp(logc) / lamz[ee][i];
}
}
}
// Compute wstar for the first chunk.
for(i=0; i<peta[0]; i++) {
wstar[i]=0.0;
for(j=0; j<m[0]; j++) {
wstar[i] += Sigmastar[0][i][j] * KrigBasis[0][i][j];
}
}
// Compute wstar for the second chunk.
for(i=0; i<peta[1]; i++) {
wstar[peta[0]+i]=0.0;
for(j=0; j<m[1]; j++) {
wstar[peta[0]+i] += Sigmastar[1][i][j] * KrigBasis[1][i][j];
}
}
/*
for(i=0; i<peta[0]+peta[1]; i++) {
printf("%f\n", wstar[i]);
}
*/
// Compute ystar, the new output
for(i=0; i<neta; i++) {
ystaremu[i] = 0.0;
for(j=0; j<peta[0]+peta[1]; j++) {
ystaremu[i] += K[i][j]*wstar[j];
}
ystaremu[i] = ystaremu[i]*sd + mean[i];
// Convert to P(k)
//ystaremu[i] = ystaremu[i] - 1.5*log10(mode[i % NK_EMU]);
//ystaremu[i] = 2*M_PI*M_PI*pow(10, ystaremu[i]);
}
// Interpolate to the desired redshift
// Natural cubic spline interpolation over z.
// First check to see if the requested z is one of the training z.
zmatch = -1;
for(i=0; i<rs; i++) {
if(xstar[p] == z[i]) {
zmatch = rs-i-1;
}
}
// z doesn't match a training z, interpolate
if(zmatch == -1) {
for(i=0; i<NK_EMU; i++) {
for(j=0; j<rs; j++) {
ybyz[rs-j-1] = ystaremu[j*NK_EMU+i];
}
gsl_spline_init(zinterp, z, ybyz, rs);
(*ystar)[i] = gsl_spline_eval(zinterp, xstar[p], accel);
gsl_interp_accel_reset(accel);
}
} else { //otherwise, copy in the emulated z without interpolating
for(i=0; i<NK_EMU; i++) {
(*ystar)[i] = ystaremu[zmatch*NK_EMU + i];
}
}
gsl_spline_free(zinterp);
gsl_interp_accel_free(accel);
// Convert to P(k)
for(i=0; i<NK_EMU; i++) {
(*ystar)[i] = (*ystar)[i] - 1.5*log10(mode[i]) + log10(2) + 2*log10(M_PI);
(*ystar)[i] = pow(10, (*ystar)[i]);
}
}
| {
"alphanum_fraction": 0.4599738194,
"avg_line_length": 31.034375,
"ext": "c",
"hexsha": "3a750c0df156b2bb45ae5d650f58cad86edc1776",
"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": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Russell-Jones-OxPhys/CCL",
"max_forks_repo_path": "src/ccl_emu17.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"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": "Russell-Jones-OxPhys/CCL",
"max_issues_repo_path": "src/ccl_emu17.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Russell-Jones-OxPhys/CCL",
"max_stars_repo_path": "src/ccl_emu17.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2972,
"size": 9931
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_mass_functions.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
// Scaled mass functions
double scaled_mass_function(double sigma, int mode, double *P) {
double rval;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_WATSON)) { // Watson et al. (2013) universal FoF mass function
double A = 0.282;
double alpha = 2.163;
double beta = 1.406;
double gamma = 1.210;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {
A = P[0];
alpha = P[1];
beta = P[2];
gamma = P[3];
}
rval = A * (pow(beta / sigma, alpha) + 1.) * exp(-gamma / (sigma * sigma));
} else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_TIAMAT)) { // Poole et al. (2013) universal FoF mass function for Tiamat
double A = 0.03331;
double alpha = 1.153;
double beta = 12.33;
double gamma = 1.009;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {
A = P[0];
alpha = P[1];
beta = P[2];
gamma = P[3];
}
rval = A * (pow(beta / sigma, alpha) + 1.) * exp(-gamma / (sigma * sigma));
} else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_JENKINS)) { // Jenkins et al. (2001)
double A = 0.315;
double B = 0.61;
double C = 3.8;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {
A = P[0];
B = P[1];
C = P[2];
}
rval = A * exp(-pow((double)fabs((float)(take_ln(1. / sigma) + B)), C));
} else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_ST)) { // Sheth-Torman (1999)
double delta_k = 1.686;
double A = 0.3222;
double B = 0.707;
double C = 0.3;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {
A = P[0];
B = P[1];
C = P[2];
}
rval = A * sqrt(2. * B / PI) * (delta_k / sigma) * exp(-B * delta_k * delta_k / (2. * sigma * sigma)) *
(1. + pow(sigma * sigma / (B * delta_k * delta_k), C));
} else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PS)) { // Press-Schechter (1974)
double delta_k = 1.686;
if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {
delta_k = P[0];
}
rval = sqrt(2. / PI) * (delta_k / sigma) * exp(-delta_k * delta_k / (2. * sigma * sigma));
} else
SID_exit_error("A valid mass function was not specified with mode (%d) in scaled_mass_function().\n",
SID_ERROR_LOGIC, mode);
return (rval);
}
| {
"alphanum_fraction": 0.5372862859,
"avg_line_length": 38.1805555556,
"ext": "c",
"hexsha": "abff6cd7c090aa0c0bc6478415e2e62ca405adb1",
"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/mass_functions/scaled_mass_function.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/mass_functions/scaled_mass_function.c",
"max_line_length": 121,
"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/mass_functions/scaled_mass_function.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": 816,
"size": 2749
} |
#ifndef UTIL_H
#define UTIL_H
#include <vector>
#include <gsl/gsl_matrix.h>
class Matrices_keeper {
private:
std::vector<gsl_matrix*> matrices;
public:
Matrices_keeper();
Matrices_keeper(const Matrices_keeper& keeper);
Matrices_keeper& operator=(const Matrices_keeper& keeper);
gsl_matrix* alloc_next(int s1, int s2);
void dalloc_all();
~Matrices_keeper();
};
bool validate_inputs(char **args);
void usage();
void exit_on_status(int status, char *msg);
void exit_on_null(void *p, char *msg);
#endif // UTIL_H
| {
"alphanum_fraction": 0.6718213058,
"avg_line_length": 19.4,
"ext": "h",
"hexsha": "8deab7b7dbcf3171c220470625f8a6a297713129",
"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": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bainit/hextexsim",
"max_forks_repo_path": "src/includes/util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9",
"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": "bainit/hextexsim",
"max_issues_repo_path": "src/includes/util.h",
"max_line_length": 66,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c613ccb2603f0f89ee4c177047e16fa2eaf4ddd9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bainit/hextexsim",
"max_stars_repo_path": "src/includes/util.h",
"max_stars_repo_stars_event_max_datetime": "2018-03-20T14:07:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-24T13:21:03.000Z",
"num_tokens": 137,
"size": 582
} |
/* rng/tt.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is the TT800 twisted GSFR generator for 32 bit integers. It
has been superceded by MT19937 (mt.c). The period is 2^800.
This implementation is based on tt800.c, July 8th 1996 version by
M. Matsumoto, email: matumoto@math.keio.ac.jp
From: Makoto Matsumoto and Yoshiharu Kurita, "Twisted GFSR
Generators II", ACM Transactions on Modelling and Computer
Simulation, Vol. 4, No. 3, 1994, pages 254-266. */
static inline unsigned long int tt_get (void *vstate);
static double tt_get_double (void *vstate);
static void tt_set (void *state, unsigned long int s);
#define N 25
#define M 7
typedef struct
{
int n;
unsigned long int x[N];
}
tt_state_t;
static inline unsigned long int
tt_get (void *vstate)
{
tt_state_t *state = (tt_state_t *) vstate;
/* this is the magic vector, a */
const unsigned long mag01[2] =
{0x00000000, 0x8ebfd028UL};
unsigned long int y;
unsigned long int *const x = state->x;
int n = state->n;
if (n >= N)
{
int i;
for (i = 0; i < N - M; i++)
{
x[i] = x[i + M] ^ (x[i] >> 1) ^ mag01[x[i] % 2];
}
for (; i < N; i++)
{
x[i] = x[i + (M - N)] ^ (x[i] >> 1) ^ mag01[x[i] % 2];
};
n = 0;
}
y = x[n];
y ^= (y << 7) & 0x2b5b2500UL; /* s and b, magic vectors */
y ^= (y << 15) & 0xdb8b0000UL; /* t and c, magic vectors */
y &= 0xffffffffUL; /* you may delete this line if word size = 32 */
/* The following line was added by Makoto Matsumoto in the 1996
version to improve lower bit's correlation. Delete this line
to use the code published in 1994. */
y ^= (y >> 16); /* added to the 1994 version */
state->n = n + 1;
return y;
}
static double
tt_get_double (void * vstate)
{
return tt_get (vstate) / 4294967296.0 ;
}
static void
tt_set (void *vstate, unsigned long int s)
{
tt_state_t *state = (tt_state_t *) vstate;
const tt_state_t init_state =
{0,
{0x95f24dabUL, 0x0b685215UL, 0xe76ccae7UL,
0xaf3ec239UL, 0x715fad23UL, 0x24a590adUL,
0x69e4b5efUL, 0xbf456141UL, 0x96bc1b7bUL,
0xa7bdf825UL, 0xc1de75b7UL, 0x8858a9c9UL,
0x2da87693UL, 0xb657f9ddUL, 0xffdc8a9fUL,
0x8121da71UL, 0x8b823ecbUL, 0x885d05f5UL,
0x4e20cd47UL, 0x5a9ad5d9UL, 0x512c0c03UL,
0xea857ccdUL, 0x4cc1d30fUL, 0x8891a8a1UL,
0xa6b7aadbUL}};
if (s == 0) /* default seed is given explicitly in the original code */
{
*state = init_state;
}
else
{
int i;
state->n = 0;
state->x[0] = s & 0xffffffffUL;
for (i = 1; i < N; i++)
state->x[i] = (69069 * state->x[i - 1]) & 0xffffffffUL;
}
return;
}
static const gsl_rng_type tt_type =
{"tt800", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (tt_state_t),
&tt_set,
&tt_get,
&tt_get_double};
const gsl_rng_type *gsl_rng_tt800 = &tt_type;
| {
"alphanum_fraction": 0.6509867532,
"avg_line_length": 25.6875,
"ext": "c",
"hexsha": "8e9e040955b4eaee37fd1af6056d835e769cb40d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/rng/tt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/rng/tt.c",
"max_line_length": 73,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/tt.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": 1305,
"size": 3699
} |
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include "../../include/timing.h"
double* default_matrix;
double** results;
int max(int a, int b){
if(a > b) return a;
return b;
}
void save_res_to_csv(double** results, int max_size, int stride, int trials, char* file_name){
FILE* csv = fopen(file_name, "w");
if(csv == NULL) perror("Error creating file!");
// header of the .csv
fprintf(csv, "size,result\n" );
// measurement results
for(int i = 0; i < max_size; i++){
for (int j = 0; j < trials; j++) {
fprintf(csv, "%d,%lf\n", i * stride, results[i][j]);
}
}
fclose(csv);
}
void init_matrix(int max_size, int stride){
int actual_size = max_size * stride;
default_matrix = (double*) malloc(actual_size* actual_size * sizeof(double));
for (int i = 0; i < actual_size; i++) {
for (int j = 0; j < actual_size; j++) {
default_matrix[actual_size * i + j] = actual_size * i + j;
}
}
}
void init_results(int max_size, int trials){
results = (double**) malloc(max_size * sizeof(double*));
for (int i = 0; i < max_size; i++) {
results[i] = (double*) malloc(trials * sizeof(double));
}
}
void cleanup_matrix(int max_size, int stride){
free(default_matrix);
}
void cleanup_results(int max_size){
for (int i = 0; i < max_size; i++) {
free(results[i]);
}
free(results);
}
double matrix_naive_test(int size){
gsl_matrix* new_mat = gsl_matrix_alloc(size, size);
gsl_matrix_view tmp_m = gsl_matrix_view_array(default_matrix, size, size);
double res;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
gsl_matrix_set(new_mat, i, j, 0);
}
}
double start = get_real_time();
for(int j = 0; j< size; j++){
for (int k = 0; k < size; k++) {
for (int i = 0; i < size; i++) {
double tmp_res = gsl_matrix_get(&tmp_m.matrix, i, k) * gsl_matrix_get(&tmp_m.matrix, k, j);
gsl_matrix_set(new_mat, i, j, gsl_matrix_get(new_mat, i, j) + tmp_res);
}
}
}
double end = get_real_time();
gsl_matrix_free(new_mat);
return end - start;
}
double matrix_better_test(int size){
gsl_matrix* new_mat = gsl_matrix_alloc(size, size);
gsl_matrix_view tmp_m = gsl_matrix_view_array(default_matrix, size, size);
double res;
double start = get_real_time();
for(int i = 0; i< size; i++){
for (int j = 0; j < size; j++) {
double tmp_res = 0;
for (int k = 0; k < size; k++) {
tmp_res += gsl_matrix_get(&tmp_m.matrix, i, k) * gsl_matrix_get(&tmp_m.matrix, k, j);
}
gsl_matrix_set(new_mat, i, j, tmp_res);
}
}
double end = get_real_time();
gsl_matrix_free(new_mat);
return end - start;
}
double matrix_blas_test(int size){
gsl_matrix_view tmp_m = gsl_matrix_view_array(default_matrix, size, size);
double res;
double start = get_real_time();
gsl_blas_dsymm(CblasLeft, CblasUpper, 1, &tmp_m.matrix, &tmp_m.matrix, 0,&tmp_m.matrix);
double end = get_real_time();
return end - start;
}
void matrix_naive_analysis(int max_size, int stride, int trials){
init_matrix(max_size, stride);
for(int i = 1; i < max_size; i++){
for (int j = 0; j < trials; j++) {
results[i][j] = matrix_naive_test(i * stride);
}
}
save_res_to_csv(results, max_size, stride, trials, "naive.csv");
cleanup_matrix(max_size, stride);
}
void matrix_better_analysis(int max_size, int stride, int trials){
init_matrix(max_size, stride);
for(int i = 1; i < max_size; i++){
for (int j = 0; j < trials; j++) {
results[i][j] = matrix_better_test(i * stride);
}
}
save_res_to_csv(results, max_size, stride, trials, "better.csv");
cleanup_matrix(max_size, stride);
}
void matrix_blas_analysis(int max_size, int stride, int trials){
init_matrix(max_size, stride);
for(int i = 1; i < max_size; i++){
for (int j = 0; j < trials; j++) {
results[i][j] = matrix_blas_test(i * stride);
}
}
save_res_to_csv(results, max_size, stride, trials, "blas.csv");
cleanup_matrix(max_size, stride);
}
int
main (void)
{
int max_size = 25;
int stride = 20;
int trials = 10;
int results_size = max_size;
init_results(results_size, trials);
printf("Analyzing naive multiplication.\n" );
matrix_naive_analysis(max_size, stride, trials);
printf("Analyzing better multiplication.\n" );
matrix_better_analysis(max_size, stride, trials);
printf("Analyzing blas multiplication.\n" );
matrix_blas_analysis(max_size, stride, trials);
cleanup_results(results_size);
return 0;
}
| {
"alphanum_fraction": 0.6460137686,
"avg_line_length": 27.2909090909,
"ext": "c",
"hexsha": "034ea07083da6083ec59579cbea6c088a8c499a3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-05-29T10:19:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-10T09:35:51.000Z",
"max_forks_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mprzewie/MOwNiT_2",
"max_forks_repo_path": "lab3/matrices/matrices.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"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": "mprzewie/MOwNiT_2",
"max_issues_repo_path": "lab3/matrices/matrices.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mprzewie/MOwNiT_2",
"max_stars_repo_path": "lab3/matrices/matrices.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1312,
"size": 4503
} |
/* histogram/ntuple.h
*
* Copyright (C) 2000 Simone Piccardi
*
* 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.
*
*/
/* Jan/2001 Modified by Brian Gough. Minor changes for GSL */
#ifndef __GSL_NTUPLE_H__
#define __GSL_NTUPLE_H__
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.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 {
FILE * file;
void * ntuple_data;
size_t size;
} gsl_ntuple;
typedef struct {
int (* function) (void * ntuple_data, void * params);
void * params;
} gsl_ntuple_select_fn;
typedef struct {
double (* function) (void * ntuple_data, void * params);
void * params;
} gsl_ntuple_value_fn;
gsl_ntuple *
gsl_ntuple_open (char * filename, void * ntuple_data, size_t size);
gsl_ntuple *
gsl_ntuple_create (char * filename, void * ntuple_data, size_t size);
int gsl_ntuple_write (gsl_ntuple * ntuple);
int gsl_ntuple_read (gsl_ntuple * ntuple);
int gsl_ntuple_bookdata (gsl_ntuple * ntuple); /* synonym for write */
int gsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple,
gsl_ntuple_value_fn *value_func,
gsl_ntuple_select_fn *select_func);
int gsl_ntuple_close (gsl_ntuple * ntuple);
__END_DECLS
#endif /* __GSL_NTUPLE_H__ */
| {
"alphanum_fraction": 0.721265705,
"avg_line_length": 25.8915662651,
"ext": "h",
"hexsha": "14789a4c85e3193746c6433c66148302a50c97e0",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/ntuple/gsl_ntuple.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 561,
"size": 2149
} |
/* randist/binomial.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
/* The binomial distribution has the form,
prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n
This is the algorithm from Knuth */
unsigned int
gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n)
{
unsigned int i, a, b, k = 0;
while (n > 10) /* This parameter is tunable */
{
double X;
a = 1 + (n / 2);
b = 1 + n - a;
X = gsl_ran_beta (r, (double) a, (double) b);
if (X >= p)
{
n = a - 1;
p /= X;
}
else
{
k += a;
n = b - 1;
p = (p - X) / (1 - X);
}
}
for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
if (u < p)
k++;
}
return k;
}
double
gsl_ran_binomial_pdf (const unsigned int k, const double p,
const unsigned int n)
{
if (k > n)
{
return 0 ;
}
else
{
double a = k;
double b = n - k;
double P;
double Cnk = gsl_sf_choose (n, k) ;
P = Cnk * pow (p, a) * pow (1 - p, b);
return P;
}
}
| {
"alphanum_fraction": 0.5867768595,
"avg_line_length": 22,
"ext": "c",
"hexsha": "23dea82af3b18c839b7327bedd7892e9c1dfb8a3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/randist/binomial.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/randist/binomial.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/randist/binomial.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": 612,
"size": 1936
} |
/**
*
* @file qwrapper_dlaset2.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:59 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaset2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
double alpha, double *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_dlaset2_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(double), &alpha, VALUE,
sizeof(double)*M*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaset2_quark = PCORE_dlaset2_quark
#define CORE_dlaset2_quark PCORE_dlaset2_quark
#endif
void CORE_dlaset2_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
double alpha;
double *A;
int LDA;
quark_unpack_args_6(quark, uplo, M, N, alpha, A, LDA);
CORE_dlaset2(uplo, M, N, alpha, A, LDA);
}
| {
"alphanum_fraction": 0.5204216074,
"avg_line_length": 27.6,
"ext": "c",
"hexsha": "e168d5899b17226a649ebabb251435bf422d7343",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_dlaset2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_dlaset2.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-qwrapper/qwrapper_dlaset2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 414,
"size": 1518
} |
//
// syr2k.h
// Linear Algebra Template Library
//
// Created by Rodney James on 1/4/12.
// Copyright (c) 2012 University of Colorado Denver. All rights reserved.
//
#ifndef _syr2k_h
#define _syr2k_h
/// @file syr2k.h Performs multiplication of two matrices resulting in a symmetric matrix.
#include <cctype>
#include "latl.h"
namespace LATL
{
/// @brief Performs multiplcation of real matrices resulting in a symmetric matrix.
///
/// For real matrices A and B, real symmetric matrix C, and real scalars alpha and beta
///
/// C := alpha*A*B'+alpha*B*A'+beta*C
/// or
///
/// C := alpha*A'*B+alpha*B'*A+beta*C
/// is computed.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C
/// is to be referenced:
///
/// if uplo = 'U' or 'u' then C is upper triangular,
/// if uplo = 'L' or 'l' then C is lower triangular.
/// @param trans Specifies the operation to be perfomed as follows:
///
/// if trans = 'N' or 'n' then C := alpha*A*B'+alpha*B*A'+beta*C
/// if trans = 'T' or 't' then C := alpha*A'*B+alpha*B'*A+beta*C
/// if trans = 'C' or 'c' then C := alpha*A'*B+alpha*B'*A+beta*C
/// @param n Specifies the order of the complex Hermitian matrix C. n>=0
/// @param k Specifies the other dimension of the complex matrices A and B.
///
/// if trans = 'N' or 'n' then A and B are n-by-k
/// if trans = 'T' or 't' then A and B are k-by-n
/// if trans = 'C' or 'c' then A and B are k-by-n
/// @param alpha Real scalar.
/// @param A Pointer to real matrix.
/// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.
/// @param B Pointer to real matrix.
/// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k.
/// @param beta Real scalar.
/// @param C Pointer to real symmetric n-by-n matrix C.
/// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.
/// @param ldC Column length of the matrix C. ldC>=n
/// @ingroup BLAS
template <typename real_t>
int SYR2K(char uplo, char trans, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC)
{
using std::toupper;
const real_t zero(0.0);
const real_t one(1.0);
int_t i,j,l;
real_t *a,*b,*c,*at,*bt;
real_t s,t;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one)))
return 0;
if(alpha==zero)
{
if(uplo=='U')
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<=j;i++)
c[i]*=beta;
c+=ldC;
}
}
else
{
c=C;
for(j=0;j<n;j++)
{
for(i=j;i<n;i++)
c[i]*=beta;
c+=ldC;
}
}
}
else if(trans=='N')
{
if(uplo=='U')
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<=j;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
s=alpha*b[j];
t=alpha*a[j];
for(i=0;i<=j;i++)
c[i]+=s*a[i]+t*b[i];
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
else
{
c=C;
for(j=0;j<n;j++)
{
for(i=j;i<n;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
s=alpha*b[j];
t=alpha*a[j];
for(i=j;i<n;i++)
c[i]+=s*a[i]+t*b[i];
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
}
else
{
if(uplo=='U')
{
c=C;
at=A;
bt=B;
for(j=0;j<n;j++)
{
a=A;
b=B;
for(i=0;i<=j;i++)
{
s=zero;
t=zero;
for(l=0;l<k;l++)
{
s+=b[l]*at[l];
t+=a[l]*bt[l];
}
c[i]=alpha*t+alpha*s+beta*c[i];
a+=ldA;
b+=ldB;
}
at+=ldA;
bt+=ldB;
c+=ldC;
}
}
else
{
c=C;
at=A;
bt=B;
for(j=0;j<n;j++)
{
a=A+j*ldA;
b=B+j*ldB;
for(i=j;i<n;i++)
{
s=zero;
t=zero;
for(l=0;l<k;l++)
{
s+=b[l]*at[l];
t+=a[l]*bt[l];
}
c[i]=alpha*t+alpha*s+beta*c[i];
a+=ldA;
b+=ldB;
}
at+=ldA;
bt+=ldB;
c+=ldC;
}
}
}
return 0;
}
/// @brief Performs multiplcation of complex matrices resulting in a symmetric matrix.
///
/// For complex matrices A and B, complex Hermitian matrix C, and complex scalars alpha and beta
///
/// C := alpha*A*B.'+alpha*B*A.'+beta*C
/// or
///
/// C := alpha*A.'*B+alpha*B.'*A+beta*C
/// is computed.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C
/// is to be referenced:
///
/// if uplo = 'U' or 'u' then C is upper triangular,
/// if uplo = 'L' or 'l' then C is lower triangular.
/// @param trans Specifies the operation to be perfomed as follows:
///
/// if trans = 'N' or 'n' then C := alpha*A*B.'+alpha*B*A.'+beta*C
/// if trans = 'T' or 'T' then C := alpha*A.'*B+alpha*B.'*A+beta*C
/// @param n Specifies the order of the complex symmetric matrix C. n>=0
/// @param k Specifies the other dimension of the complex matrices A and B.
///
/// if trans = 'N' or 'n' then A and B are n-by-k
/// if trans = 'T' or 't' then A and B are k-by-n
/// @param alpha Complex scalar.
/// @param A Pointer to complex matrix.
/// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.
/// @param B Pointer to complex matrix.
/// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k.
/// @param beta Complex scalar.
/// @param C Pointer to complex symmetric n-by-n matrix C.
/// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.
/// @param ldC Column length of the matrix C. ldC>=n
/// @ingroup BLAS
template <typename real_t>
int SYR2K(char uplo, char trans, int_t n, int_t k, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB, complex<real_t> beta, complex<real_t> *C, int_t ldC)
{
using std::toupper;
const complex<real_t> zero(0.0,0.0);
const complex<real_t> one(1.0,0.0);
int_t i,j,l;
complex<real_t> *a,*b,*c,*at,*bt;
complex<real_t> s,t;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
else if((n==0)||(((alpha==zero)||(k==0))&&(beta==one)))
return 0;
if(alpha==zero)
{
if(uplo=='U')
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<=j;i++)
c[i]*=beta;
c+=ldC;
}
}
else
{
c=C;
for(j=0;j<n;j++)
{
for(i=j;i<n;i++)
c[i]*=beta;
c+=ldC;
}
}
}
else if(trans=='N')
{
if(uplo=='U')
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<=j;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
s=alpha*b[j];
t=alpha*a[j];
for(i=0;i<=j;i++)
c[i]+=s*a[i]+t*b[i];
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
else
{
c=C;
for(j=0;j<n;j++)
{
for(i=j;i<n;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
s=alpha*b[j];
t=alpha*a[j];
for(i=j;i<n;i++)
c[i]+=s*a[i]+t*b[i];
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
}
else
{
if(uplo=='U')
{
c=C;
at=A;
bt=B;
for(j=0;j<n;j++)
{
a=A;
b=B;
for(i=0;i<=j;i++)
{
s=zero;
t=zero;
for(l=0;l<k;l++)
{
s+=b[l]*at[l];
t+=a[l]*bt[l];
}
c[i]=alpha*t+alpha*s+beta*c[i];
a+=ldA;
b+=ldB;
}
at+=ldA;
bt+=ldB;
c+=ldC;
}
}
else
{
c=C;
at=A;
bt=B;
for(j=0;j<n;j++)
{
a=A+j*ldA;
b=B+j*ldB;
for(i=j;i<n;i++)
{
s=zero;
t=zero;
for(l=0;l<k;l++)
{
s+=b[l]*at[l];
t+=a[l]*bt[l];
}
c[i]=alpha*t+alpha*s+beta*c[i];
a+=ldA;
b+=ldB;
}
at+=ldA;
bt+=ldB;
c+=ldC;
}
}
}
return 0;
}
#ifdef __latl_cblas
#include <cblas.h>
template <> int SYR2K<float>(char uplo, char trans, int_t n, int_t k, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC)
{
using std::toupper;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
cblas_ssyr2k(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,B,ldB,beta,C,ldC);
return 0;
}
template <> int SYR2K<double>(char uplo, char trans, int_t n, int_t k, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC)
{
using std::toupper;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T')&&(trans!='C'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
cblas_dsyr2k(CblasColMajor,Uplo,Trans,n,k,alpha,A,ldA,B,ldB,beta,C,ldC);
return 0;
}
template <> int SYR2K<float>(char uplo, char trans, int_t n, int_t k, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB, complex<float> beta, complex<float> *C, int_t ldC)
{
using std::toupper;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
cblas_csyr2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
template <> int SYR2K<double>(char uplo, char trans, int_t n, int_t k, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB, complex<double> beta, complex<double> *C, int_t ldC)
{
using std::toupper;
uplo=toupper(uplo);
trans=toupper(trans);
if((uplo!='U')&&(uplo!='L'))
return -1;
else if((trans!='N')&&(trans!='T'))
return -2;
else if(n<0)
return -3;
else if(k<0)
return -4;
else if(ldA<((trans=='N')?n:k))
return -7;
else if(ldB<((trans=='N')?n:k))
return -9;
else if(ldC<n)
return -12;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
const CBLAS_TRANSPOSE Trans=(trans=='N')?CblasNoTrans:((trans=='T')?CblasTrans:CblasConjTrans);
cblas_zsyr2k(CblasColMajor,Uplo,Trans,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
#endif
}
#endif
| {
"alphanum_fraction": 0.423628079,
"avg_line_length": 28.3046728972,
"ext": "h",
"hexsha": "5f64ee3a30db7a218a323d4a729baf841266e0dd",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z",
"max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "langou/latl",
"max_forks_repo_path": "include/syr2k.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "langou/latl",
"max_issues_repo_path": "include/syr2k.h",
"max_line_length": 211,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "langou/latl",
"max_stars_repo_path": "include/syr2k.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z",
"num_tokens": 4298,
"size": 15143
} |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Contains the PERDIF program that implements personalized diffusions for
recommendations.
Code by: Dimitris Berberidis and Athanasios N. Nikolakopoulos
University of Minnesota 2018-2019
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//#include <cblas.h>
#include <mkl.h>
#include "perdif_fit.h"
#include "rec_defs.h"
#if DEBUG
static double cost_func(double *, double *, double *, sz_med_t);
#endif
static void matrix_matrix_product(double *C, double *A, double *B, int, int, int);
static double *unfold_matrix(d_mat_t);
static void constr_QP_with_PG(double *, double *, double *, sz_med_t);
static void grammian_matrix(double *, double *, int, int);
static double max_abs_dif(double *, double *, sz_long_t);
// static void project_to_simplex(double *, sz_med_t);
// static void project_to_simplex_thanos(double *, double *, sz_med_t length);
static void simplexproj_Duchi(double *y, double *x, const unsigned int length);
static void matvec(double *, double *, double *, int, int);
static double frob_norm(double *, sz_med_t);
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
void k_simplex(double *theta, d_mat_t P, int max_walk, double *dummy, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
// Unfold P for BLAS compatibility
double *P_unfold = unfold_matrix(P);
// Prepare parameters for constraned QP
// first the Hessian matrix
double A[max_walk * max_walk];
grammian_matrix(A, P_unfold, (int)P.num_rows, (int)P.num_cols);
// then the linear part
double b[max_walk];
if (rmse) {
for (int i = 0; i < max_walk; i++)
b[i] = -2.0 * (P_unfold[i]);
} else {
for (int i = 0; i < max_walk; i++) {
b[i] = 0.0;
for (int j = 0; j < P.num_rows; j++) {
b[i] += P.val[i][j];
}
b[i] *= -2.0;
}
}
constr_QP_with_PG(theta, A, b, (sz_med_t)max_walk);
// free
free(P_unfold);
}
// Simple search returns the single best step ( i.e. theta = [0 0 0 1 0 0 .... 0
// 0 ] )
void single_best(double *theta, d_mat_t P, int max_walk, double *dummy, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
for (int k = 0; k < max_walk; k++)
theta[k] = 0.0;
double loss[max_walk];
// Compute loss of each k-step and find smallest
int best_k = 0;
double min_loss = 1.0e5;
for (int k = 0; k < max_walk; k++) {
loss[k] += pow(1.0 - P.val[0][k], 2);
if (rmse) {
for (int j = 1; j < P.num_rows; j++)
loss[k] += P.val[j][k] * P.val[j][k];
} else {
for (int j = 1; j < P.num_rows; j++)
loss[k] += pow(1.0 - P.val[j][k], 2);
}
if (loss[k] < min_loss) {
min_loss = loss[k];
best_k = k;
}
}
theta[best_k] = 1.0;
}
void ppr_grid(double *theta, d_mat_t P, int max_walk, double *ppr_c, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
// Unfold P for BLAS compatibility
double *P_unfold = unfold_matrix(P);
// Candidate diffusions
double *C = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));
matrix_matrix_product(C, P_unfold, ppr_c, P.num_rows, max_walk, GRID_POINTS);
// find the best one
double loss[GRID_POINTS];
int best_point = 0;
double min_loss = 1.0e5;
for (int i = 0; i < GRID_POINTS; i++) {
// first the regularizer
loss[i] = 0.0;
// then the ratings
if (rmse) {
loss[i] += pow(1.0 - C[i], 2);
for (int j = 1; j < P.num_rows; j++)
loss[i] += pow(C[j * GRID_POINTS + i], 2);
} else {
for (int j = 0; j < P.num_rows; j++)
loss[i] += pow(1.0 - C[j * GRID_POINTS + i], 2);
}
if (loss[i] < min_loss) {
min_loss = loss[i];
best_point = i;
}
}
// return the best one
for (int k = 0; k < max_walk; k++)
theta[k] = ppr_c[k * GRID_POINTS + best_point];
// free
free(P_unfold);
free(C);
}
void hk_grid(double *theta, d_mat_t P, int max_walk, double *hk_c, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
// Unfold P for BLAS compatibility
double *P_unfold = unfold_matrix(P);
double *C = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));
matrix_matrix_product(C, P_unfold, hk_c, P.num_rows, max_walk, GRID_POINTS);
// find the best one
double loss[GRID_POINTS];
int best_point = 0;
double min_loss = 1.0e5;
for (int i = 0; i < GRID_POINTS; i++) {
// first the regularizer
loss[i] = 0.0;
// then the ratings
if (rmse) {
loss[i] += pow(1.0 - C[i], 2);
for (int j = 1; j < P.num_rows; j++)
loss[i] += pow(C[j * GRID_POINTS + i], 2);
} else {
for (int j = 0; j < P.num_rows; j++)
loss[i] += pow(1.0 - C[j * GRID_POINTS + i], 2);
}
if (loss[i] < min_loss) {
min_loss = loss[i];
best_point = i;
}
}
// return the best one
for (int k = 0; k < max_walk; k++)
theta[k] = hk_c[k * GRID_POINTS + best_point];
// free
free(P_unfold);
free(C);
}
void dictionary_single(double *theta, d_mat_t P, int max_walk, double *dict, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
// Unfold P for BLAS compatibility
double *P_unfold = unfold_matrix(P);
// Prepare matrices
double *PD = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));
matrix_matrix_product(PD, P_unfold, dict, (int)P.num_rows, (int)P.num_cols,
GRID_POINTS);
double DD[GRID_POINTS * GRID_POINTS];
grammian_matrix(DD, dict, max_walk, GRID_POINTS);
double A[GRID_POINTS * GRID_POINTS];
grammian_matrix(A, PD, (int)P.num_rows, GRID_POINTS);
double g_D[GRID_POINTS];
for (int i = 0; i < GRID_POINTS; i++) {
g_D[i] = 0.0;
}
if (rmse) {
for (int i = 0; i < GRID_POINTS; i++)
g_D[i] += -2.0 * PD[i];
} else {
for (int i = 0; i < GRID_POINTS; i++) {
for (int j = 0; j < P.num_rows; j++)
g_D[i] += -2.0 * PD[j * GRID_POINTS + i];
}
}
double theta_dict[GRID_POINTS];
// call QP solver for dictionary coefficients
constr_QP_with_PG(theta_dict, A, g_D, (sz_med_t)GRID_POINTS);
// construct diffusion from dictionary coefficients
matvec(theta, dict, theta_dict, max_walk, GRID_POINTS);
// free
free(PD);
free(P_unfold);
}
void dictionary(double *theta, d_mat_t P, int max_walk, double *dict, bool rmse) {
if (!rmse) {
// adjust for BPR metric
for (int i = 1; i < P.num_rows; i++) {
for (int j = 0; j < P.num_cols; j++)
P.val[i][j] = P.val[0][j] - P.val[i][j];
}
}
// Unfold P for BLAS compatibility
double *P_unfold = unfold_matrix(P);
// Prepare matrices
double *PD = (double *)malloc(P.num_rows * 2 * GRID_POINTS * sizeof(double));
matrix_matrix_product(PD, P_unfold, dict, (int)P.num_rows, (int)P.num_cols,
2 * GRID_POINTS);
double DD[4 * GRID_POINTS * GRID_POINTS];
grammian_matrix(DD, dict, max_walk, 2 * GRID_POINTS);
double A[4 * GRID_POINTS * GRID_POINTS];
grammian_matrix(A, PD, (int)P.num_rows, 2 * GRID_POINTS);
double g_D[2 * GRID_POINTS];
for (int i = 0; i < 2 * GRID_POINTS; i++) {
g_D[i] = 0.0;
}
if (rmse) {
for (int i = 0; i < 2 * GRID_POINTS; i++)
g_D[i] += -2.0 * PD[i];
} else {
for (int i = 0; i < 2 * GRID_POINTS; i++) {
for (int j = 0; j < P.num_rows; j++)
g_D[i] += -2.0 * PD[j * 2 * GRID_POINTS + i];
}
}
double theta_dict[2 * GRID_POINTS];
// call QP solver for dictionary coefficients
constr_QP_with_PG(theta_dict, A, g_D, (sz_med_t)2 * GRID_POINTS);
// construct diffusion from dictionary coefficients
matvec(theta, dict, theta_dict, max_walk, 2 * GRID_POINTS);
// free
free(PD);
free(P_unfold);
}
// Returns PPR coefficients for given points on a grid of parameter a
double *ppr_coefficients(int max_walk) {
int grid_points = GRID_POINTS;
double *coef = (double *)malloc(max_walk * grid_points * sizeof(double));
double width = 1.0 / (double)(grid_points + 2);
double col_sum[grid_points];
for (int j = 0; j < grid_points; j++)
col_sum[j] = 0.0;
for (int i = 0; i < max_walk; i++) {
for (int j = 0; j < grid_points; j++) {
// pagerank weights per step
coef[i * grid_points + j] = (i == 0)
? (1 - (0.01 + width * ((double)j)))
: (1 - (0.01 + width * ((double)j))) *
pow(0.01 + width * ((double)j), i);
col_sum[j] += coef[i * grid_points + j];
}
}
// Normalize coefficients so tha they sum to 1
for (int i = 0; i < max_walk; i++) {
for (int j = 0; j < grid_points; j++)
coef[i * grid_points + j] /= col_sum[j];
}
return coef;
}
// Returns HK coefficients for given points on a grid of parameter \tau
double *hk_coefficients(int max_walk) {
int grid_points = GRID_POINTS;
double *coef = (double *)malloc(max_walk * grid_points * sizeof(double));
double width = (double)MAX_HK_COEF / (double)(grid_points + 2);
// compute factorials from 1 to max_walk
sz_long_t factorial[max_walk];
factorial[0] = 1;
for (int j = 1; j < max_walk; j++)
factorial[j] = factorial[j - 1] * j;
double col_sum[grid_points];
for (int j = 0; j < grid_points; j++)
col_sum[j] = 0.0;
for (int i = 0; i < max_walk; i++) {
for (int j = 0; j < grid_points; j++) {
coef[i * grid_points + j] =
pow(1.0 + width * ((double)j), i) / (double)factorial[i];
col_sum[j] += coef[i * grid_points + j];
}
}
// Normalize coefficients so that they sum to 1
for (int i = 0; i < max_walk; i++) {
for (int j = 0; j < grid_points; j++)
coef[i * grid_points + j] /= col_sum[j];
}
return coef;
}
// Returns dictionary coefficients by concatenating PPR and HK
double *dict_coefficients(int max_walk) {
int grid_points = GRID_POINTS;
double *coef = (double *)malloc(2 * max_walk * grid_points * sizeof(double));
double *hk = hk_coefficients(max_walk);
double *ppr = ppr_coefficients(max_walk);
for (int i = 0; i < max_walk; i++) {
for (int j = 0; j < grid_points; j++) {
coef[2 * i * grid_points + j] = ppr[i * grid_points + j];
}
for (int j = grid_points; j < 2 * grid_points; j++) {
coef[2 * i * grid_points + j] = hk[i * grid_points + j - grid_points];
}
}
// free temporary coefs
free(ppr);
free(hk);
return coef;
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// AUXILIARY FUNCTIONS
// Interface for CBLAS mutrix matrix product
// C =A*B
// A : m x k
// B : k x n
static void matrix_matrix_product(double *C, double *A, double *B, int m, int k,
int n) {
for (int i = 0; i < m * n; i++)
C[i] = 0.0f;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f, A, k, B,
n, 0.0f, C, n);
}
// Unfold matrix from A[i[j] to A[i*M + j]
static double *unfold_matrix(d_mat_t A) {
double *A_u = (double *)malloc(A.num_cols * A.num_rows * sizeof(double));
for (sz_long_t i = 0; i < A.num_rows; i++)
memcpy(A_u + i * A.num_cols, A.val[i], A.num_cols * sizeof(double));
return A_u;
}
// Solving constrained quadratic minimization via projected gradient descent
// The following function returns x =arg min {x^T*A*x +x^T*B} s.t. x in Prob.
// Simplex
static void constr_QP_with_PG(double *x, double *A, double *b, sz_med_t K) {
double inf_norm, step_size;
double x_temp[K];
double x_prev[K];
step_size = STEPSIZE_2 / frob_norm(A, K);
// Initialize to uniform
for (sz_med_t i = 0; i < K; i++)
x[i] = 1.0f / (double)K;
sz_med_t iter = 0;
memcpy(x_prev, x, K * sizeof(double));
// int count=0;
do {
iter++;
// step_size = 1 / ((double)iter) * step_size;
// step_size = 1/(sqrt(iter));//*step_size;
// step_size = 1/(double)iter;
// Take gradient step
matvec(x_temp, A, x, K, K);
for (sz_med_t j = 0; j < K; j++)
x[j] -= step_size * (2.0f * x_temp[j] + b[j]);
// project to feasible set
simplexproj_Duchi(x, x, K);
#if DEBUG
printf("\n COST: ");
printf(" %lf ", cost_func(A, b, x, K));
#endif
inf_norm = max_abs_dif(x_prev, x, (sz_long_t)K);
memcpy(x_prev, x, K * sizeof(double));
} while (iter < MAXIT_GD && inf_norm > GD_TOL_2);
// printf("\n Counter = %d", count);
// printf("\n Optimization finished after: %"PRIu32" iterations\n", (uint32_t)
// iter);
}
// Grammian matrix G =A'*A using CBLAS
// A : m x n
static void grammian_matrix(double *G, double *A, int m, int n) {
for (int i = 0; i < n * n; i++)
G[i] = 0.0f;
double *A_copy = (double *)malloc(m * n * sizeof(double));
memcpy(A_copy, A, m * n * sizeof(double));
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, m, 1.0f, A_copy, n,
A, n, 0.0f, G, n);
free(A_copy);
}
// Interface for CBLAS matrix vector product
// A : M x N
static void matvec(double *y, double *A, double *x, int M, int N) {
// for (int i = 0; i < M; i++)
// {
// y[i] = 0.0f;
// }
cblas_dgemv(CblasRowMajor, CblasNoTrans, M, N, 1.0f, A, N, x, 1, 0.0f, y, 1);
}
//
/* Algorithm using partitioning with respect to a pivot, chosen randomly,
as given by Duchi et al. in "Efficient Projections onto the l1-Ball for
Learning in High Dimensions" */
static void simplexproj_Duchi(double *y, double *x, const unsigned int length) {
double *auxlower = (x == y ? (double *)malloc(length * sizeof(double)) : x);
double *auxupper = (double *)malloc(length * sizeof(double));
double *aux = auxlower;
double pivot;
int auxlowerlength = 0;
int auxupperlength = 1;
int upperlength;
int auxlength;
int i = 0;
int pospivot = (int)(rand() / (((double)RAND_MAX + 1.0) / length));
double tauupper;
double tau = (pivot = y[pospivot]) - 1.0;
while (i < pospivot)
if (y[i] < pivot)
auxlower[auxlowerlength++] = y[i++];
else {
auxupper[auxupperlength++] = y[i];
tau += (y[i++] - tau) / auxupperlength;
}
i++;
while (i < length)
if (y[i] < pivot)
auxlower[auxlowerlength++] = y[i++];
else {
auxupper[auxupperlength++] = y[i];
tau += (y[i++] - tau) / auxupperlength;
}
if (tau < pivot) {
upperlength = auxupperlength;
tauupper = tau;
auxlength = auxlowerlength;
} else {
tauupper = 0.0;
upperlength = 0;
aux = auxupper + 1;
auxlength = auxupperlength - 1;
}
while (auxlength > 0) {
pospivot = (int)(rand() / (((double)RAND_MAX + 1.0) / auxlength));
if (upperlength == 0)
tau = (pivot = aux[pospivot]) - 1.0;
else
tau = tauupper + ((pivot = aux[pospivot]) - tauupper) / (upperlength + 1);
i = 0;
auxlowerlength = 0;
auxupperlength = 1;
while (i < pospivot)
if (aux[i] < pivot)
auxlower[auxlowerlength++] = aux[i++];
else {
auxupper[auxupperlength++] = aux[i];
tau += (aux[i++] - tau) / (upperlength + auxupperlength);
}
i++;
while (i < auxlength)
if (aux[i] < pivot)
auxlower[auxlowerlength++] = aux[i++];
else {
auxupper[auxupperlength++] = aux[i];
tau += (aux[i++] - tau) / (upperlength + auxupperlength);
}
if (tau < pivot) {
upperlength += auxupperlength;
tauupper = tau;
auxlength = auxlowerlength;
aux = auxlower;
} else {
aux = auxupper + 1;
auxlength = auxupperlength - 1;
}
}
for (i = 0; i < length; i++)
x[i] = (y[i] > tau ? y[i] - tauupper : 0.0000000001);
double sum = 0.0;
for (i = 0; i < length; i++)
sum += x[i];
for (i = 0; i < length; i++)
x[i] /= sum;
if (x == y)
free(auxlower);
free(auxupper);
}
// Infinity norm
static double max_abs_dif(double *a, double *b, sz_long_t len) {
double dif, max = 0.0;
for (sz_long_t i = 0; i < len; i++) {
dif = fabs(a[i] - b[i]);
max = (dif > max) ? dif : max;
}
return max;
}
#if DEBUG
// Evaluates quadratic with Hessian A and linear part b at x
static double cost_func(double *A, double *b, double *x, sz_med_t len) {
double quad = 0.0f, lin = 0.0f;
for (sz_med_t i = 0; i < len; i++) {
for (sz_med_t j = 0; j < len; j++) {
quad += A[i * len + j] * x[i] * x[j];
}
lin += b[i] * x[i];
}
return quad + lin;
}
#endif
// frobenious norm of double-valued square matrix
static double frob_norm(double *A, sz_med_t dim) {
double norm = 0.0f;
for (sz_med_t i = 0; i < dim * dim; i++) {
norm += pow(A[i], 2.0f);
}
return sqrt(norm);
}
| {
"alphanum_fraction": 0.5536852701,
"avg_line_length": 27.6383307573,
"ext": "c",
"hexsha": "5b37b7a5810aabc17921e1caa2a9ac0f4d82982e",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2020-05-14T18:50:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-16T15:02:04.000Z",
"max_forks_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "nikolakopoulos/Personalized-Diffusions",
"max_forks_repo_path": "src/perdif_fit.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2",
"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": "nikolakopoulos/Personalized-Diffusions",
"max_issues_repo_path": "src/perdif_fit.c",
"max_line_length": 135,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "nikolakopoulos/Personalized-Diffusions",
"max_stars_repo_path": "src/perdif_fit.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-03T00:07:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-18T10:40:07.000Z",
"num_tokens": 5656,
"size": 17882
} |
#ifndef SMSVM_E_H
#define SMSVM_E_H
#include "Matrix.h"
#include "LADMM.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 <math.h>
//This class solves problem: min_{x,omega} \sum_i max(1- b_i^T(A_ix+ omega), 0)+ P(x) by LADMM
// where P(x)=\frac{lambda2}{2}\|x\|_2^2 +lambda1\|x\|_1.
// Let X= (x; omega), M= (b.*A b), b_i^T(A_ix+ omega)= M_iX
// phi_i(x)= 0, h_i(x)= max(1- x,0), g(X)= P(x).
template<typename L, typename D>
class SMSVM_e: public LADMM<L, D>
{
private:
D lambda1;
D lambda2;
Matrix<L,D> my_M;
D val_lambda_f;
protected:
public:
SMSVM_e(const char* Matrix_file,D val_lambda1, D val_lambda2)
:LADMM<L,D>(),my_M(Matrix_file)
{
lambda1=val_lambda1;
lambda2=val_lambda2;
this->lambda_f=0;
my_M.matrix_modified_to_svm(my_M);
}
L get_n(){return my_M.nfeatures;}
L get_m(){return my_M.nsamples;}
inline D gradient_of_f_j(D x1, L i){
return 0;
}
inline D value_of_g_j(D x, L i){
if(i== this->m_1-1){
return 0;
}
else{
return lambda2*x*x/2+lambda1*fabs(x);
}
}
inline D value_of_f_j(D x1, L i){return 0;}
inline D value_of_h_j(D x, L i){
if(x<= 1.0){
return 1.0- x;
}
else{
return 0;
}
}
inline D prox_of_g_j(D x1,D x2, L i){
if(i== this->m_1 - 1){
return x1;
}
else{
D new_x;
if(x1*x2> lambda1)
new_x=(x1*x2- lambda1)/(x2+lambda2);
else if(x1*x2< -lambda1)
new_x=(x1*x2+ lambda1)/(x2+ lambda2);
else
new_x=0;
return new_x;
}
}
// compute argmin_x h(x)+ x2/2*(x- x1)*(x- x1)
inline D prox_of_h_j(D x1, D x2, L j){
if (x1+ 1.0/x2< 1.0){
return x1+ 1.0/x2;
}
else if (x1> 1.0){
return x1;
}
else{
return 1.0;;
}
}
inline void set_matrix_M(){
this->data_M=my_M;
}
inline void set_matrix_A(){
this->data_A.nsamples=0;
this->data_A.nfeatures=this->data_M.nfeatures;
this->data_A.nnz=0;
this->data_A.ptr.resize(1,0);
this->data_A.ptr_t.resize(this->data_M.nfeatures+1,0);
}
void LADMM_solver(D beta_0, D rho,vector<D> & x0,vector<D> & y0, vector<D> & lambda0, L max_nb_outer, L p_N_1, string filename1, D time){
this->ADMM_solve_with_Linear(beta_0, rho,x0,y0, lambda0, max_nb_outer, p_N_1, filename1, time);
}
};
#endif
| {
"alphanum_fraction": 0.5856918239,
"avg_line_length": 17.306122449,
"ext": "h",
"hexsha": "3ea4d13f6cfaf3610ac68e9b352796baa84ab552",
"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_OPENMP/SMSVM_e.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_OPENMP/SMSVM_e.h",
"max_line_length": 140,
"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_OPENMP/SMSVM_e.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 908,
"size": 2544
} |
/* matrix/gsl_matrix_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_MATRIX_INT_H__
#define __GSL_MATRIX_INT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_int.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
int * data;
gsl_block_int * block;
int owner;
} gsl_matrix_int;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_view;
typedef _gsl_matrix_int_view gsl_matrix_int_view;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_const_view;
typedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;
/* Allocation */
gsl_matrix_int *
gsl_matrix_int_alloc (const size_t n1, const size_t n2);
gsl_matrix_int *
gsl_matrix_int_calloc (const size_t n1, const size_t n2);
gsl_matrix_int *
gsl_matrix_int_alloc_from_block (gsl_block_int * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
gsl_matrix_int *
gsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
gsl_vector_int *
gsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,
const size_t i);
gsl_vector_int *
gsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,
const size_t j);
void gsl_matrix_int_free (gsl_matrix_int * m);
/* Views */
_gsl_matrix_int_view
gsl_matrix_int_submatrix (gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_int_view
gsl_matrix_int_row (gsl_matrix_int * m, const size_t i);
_gsl_vector_int_view
gsl_matrix_int_column (gsl_matrix_int * m, const size_t j);
_gsl_vector_int_view
gsl_matrix_int_diagonal (gsl_matrix_int * m);
_gsl_vector_int_view
gsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);
_gsl_vector_int_view
gsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);
_gsl_vector_int_view
gsl_matrix_int_subrow (gsl_matrix_int * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_int_view
gsl_matrix_int_subcolumn (gsl_matrix_int * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_int_view
gsl_matrix_int_view_array (int * base,
const size_t n1,
const size_t n2);
_gsl_matrix_int_view
gsl_matrix_int_view_array_with_tda (int * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_int_view
gsl_matrix_int_view_vector (gsl_vector_int * v,
const size_t n1,
const size_t n2);
_gsl_matrix_int_view
gsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_int_const_view
gsl_matrix_int_const_submatrix (const gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_int_const_view
gsl_matrix_int_const_row (const gsl_matrix_int * m,
const size_t i);
_gsl_vector_int_const_view
gsl_matrix_int_const_column (const gsl_matrix_int * m,
const size_t j);
_gsl_vector_int_const_view
gsl_matrix_int_const_diagonal (const gsl_matrix_int * m);
_gsl_vector_int_const_view
gsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m,
const size_t k);
_gsl_vector_int_const_view
gsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m,
const size_t k);
_gsl_vector_int_const_view
gsl_matrix_int_const_subrow (const gsl_matrix_int * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_int_const_view
gsl_matrix_int_const_subcolumn (const gsl_matrix_int * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_array (const int * base,
const size_t n1,
const size_t n2);
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_array_with_tda (const int * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector (const gsl_vector_int * v,
const size_t n1,
const size_t n2);
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
void gsl_matrix_int_set_zero (gsl_matrix_int * m);
void gsl_matrix_int_set_identity (gsl_matrix_int * m);
void gsl_matrix_int_set_all (gsl_matrix_int * m, int x);
int gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;
int gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;
int gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);
int gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);
int gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);
int gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);
int gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);
int gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);
int gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);
int gsl_matrix_int_transpose (gsl_matrix_int * m);
int gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);
int gsl_matrix_int_max (const gsl_matrix_int * m);
int gsl_matrix_int_min (const gsl_matrix_int * m);
void gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);
void gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);
void gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);
void gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
int gsl_matrix_int_equal (const gsl_matrix_int * a, const gsl_matrix_int * b);
int gsl_matrix_int_isnull (const gsl_matrix_int * m);
int gsl_matrix_int_ispos (const gsl_matrix_int * m);
int gsl_matrix_int_isneg (const gsl_matrix_int * m);
int gsl_matrix_int_isnonneg (const gsl_matrix_int * m);
int gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);
int gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);
int gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
int gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
int gsl_matrix_int_scale (gsl_matrix_int * a, const double x);
int gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);
int gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);
int gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);
int gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);
int gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);
/***********************************************************************/
/* inline functions if you are using GCC */
INLINE_DECL int gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);
INLINE_DECL void gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);
INLINE_DECL int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);
INLINE_DECL const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
int
gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
int *
gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (int *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const int *
gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const int *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_INT_H__ */
| {
"alphanum_fraction": 0.6414520895,
"avg_line_length": 33.7464387464,
"ext": "h",
"hexsha": "a9b04c1b3e2df956b4b0f019b163f962b5384755",
"lang": "C",
"max_forks_count": 173,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z",
"max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "gsl-an/gsl/gsl_matrix_int.h",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/gsl/gsl_matrix_int.h",
"max_line_length": 120,
"max_stars_count": 460,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "gsl-an/gsl/gsl_matrix_int.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 2900,
"size": 11845
} |
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
* =====================================================================================
*
* Filename: Img_ss.c
*
* Description:
*
* Version: 1.0
* Created: 15/04/2013 16:44:51
* Revision: none
* Compiler: gcc
*
* Author: Giuseppe Argentieri (), argenti@ts.infn.it
* Organization:
*
* =====================================================================================
*/
#include "funcs.h"
/* #include <gsl/gsl_sf_expint.h> */
int im_gss ( void* params, double* val, double* error )
{
struct f_params* pars = (struct f_params*) params ;
double o_c, b, O, o_1, alpha ;
assign_p ( pars, &o_c, &b, &O, &o_1 ) ;
alpha = pars->alpha ;
double e1, e2, E1, E2 ;
double err1, err2, ERR1, ERR2 ;
double beta1 = O + o_1 ;
double beta2 = o_1 - O ;
double mu = 1/o_c ;
expi ( beta1*mu, &e1, &err1 ) ;
expi_plus ( beta1*mu, &E1, &ERR1 ) ;
expi_plus ( beta2*mu, &E2, &ERR2 ) ;
expi ( beta2*mu, &e2, &err2 ) ;
/* e1 = - gsl_sf_expint_E1 ( beta1*mu ) ;
* e2 = - gsl_sf_expint_E1 ( beta2*mu ) ;
* E1 = gsl_sf_expint_Ei ( beta1*mu ) ;
* E2 = gsl_sf_expint_Ei ( beta2*mu ) ;
*/
double imgss = (alpha/4)*(beta1*(e1*exp(beta1*mu)-E1*exp(-beta1*mu)) +
beta2*(E2*exp(-beta2*mu)-e2*exp(beta2*mu))) ;
*val = imgss ;
double err = (alpha/4)*(beta1*(err1*exp(beta1*mu))+ERR1*exp(-beta1*mu) +
beta2*(ERR2*exp(-beta2*mu)+err2*exp(beta2*mu))) ;
*error = err ;
return 0;
}
| {
"alphanum_fraction": 0.6311589174,
"avg_line_length": 32.75,
"ext": "c",
"hexsha": "f2597b41f268615c9c37c868d98d5c3c15399825",
"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": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "j-silver/quantum_dots",
"max_forks_repo_path": "Img_ss.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"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": "j-silver/quantum_dots",
"max_issues_repo_path": "Img_ss.c",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "j-silver/quantum_dots",
"max_stars_repo_path": "Img_ss.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 810,
"size": 2882
} |
/*
Copyright [2017-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 _API_KVSTORE_H_
#define _API_KVSTORE_H_
#include <api/components.h>
#include <api/registrar_memory_direct.h>
#include <common/byte.h>
#include <common/byte_span.h>
#include <common/errors.h> /* ERROR_BASE */
#include <common/string_view.h>
#include <common/time.h>
#include <gsl/span>
#include <sys/uio.h> /* iovec */
#include <cinttypes> /* PRIx64 */
#include <cstdlib>
#include <functional>
#include <map>
#include <list>
#include <mutex>
#include <vector>
namespace nupm
{
struct region_descriptor;
}
/* print format for the pool type */
#define PRIxIKVSTORE_POOL_T PRIx64
namespace component
{
#define DECLARE_OPAQUE_TYPE(NAME) \
struct Opaque_##NAME { \
virtual ~Opaque_##NAME() {} \
}
/**
* Key-value interface for pluggable backend (e.g. mapstore, hstore, hstore-cc)
*/
class KVStore : public Registrar_memory_direct {
protected:
~KVStore() {}
private:
DECLARE_OPAQUE_TYPE(lock_handle);
template <typename E, typename ... Args>
static E error_value(
E e, Args && ...
) { return e; }
public:
DECLARE_OPAQUE_TYPE(memory_region); /* Buffer_manager::buffer_t need this */
DECLARE_OPAQUE_TYPE(key);
DECLARE_OPAQUE_TYPE(pool_iterator);
public:
using pool_t = uint64_t;
// using memory_handle_t = Opaque_memory_region*;
using key_t = Opaque_key*;
using pool_lock_t = Opaque_lock_handle*;
using pool_iterator_t = Opaque_pool_iterator*;
using byte = common::byte;
template <typename C>
using basic_string_view = common::basic_string_view<C>;
using string_view = common::string_view;
using string_view_byte = basic_string_view<byte>;
using string_view_key = string_view_byte;
using string_view_value = string_view_byte;
static constexpr memory_handle_t HANDLE_NONE = nullptr; /* old name */
static constexpr memory_handle_t MEMORY_HANDLE_NONE = nullptr; /* better name */
static constexpr key_t KEY_NONE = nullptr;
struct Addr {
explicit Addr(addr_t addr_) : addr(addr_) {}
Addr() = delete;
addr_t addr;
};
enum {
THREAD_MODEL_UNSAFE,
THREAD_MODEL_SINGLE_PER_POOL,
THREAD_MODEL_RWLOCK_PER_POOL,
THREAD_MODEL_MULTI_PER_POOL,
};
using flags_t = std::uint32_t ;
static constexpr flags_t FLAGS_NONE = 0x0;
static constexpr flags_t FLAGS_READ_ONLY = 0x1; /* lock read-only */
static constexpr flags_t FLAGS_SET_SIZE = 0x2;
static constexpr flags_t FLAGS_CREATE_ONLY = 0x4; /* only succeed if no existing k-v pair exist */
static constexpr flags_t FLAGS_DONT_STOMP = 0x8; /* do not overwrite existing k-v pair */
static constexpr flags_t FLAGS_NO_RESIZE = 0x10; /* if size < existing size, do not resize */
static constexpr flags_t FLAGS_MAX_VALUE = 0x10;
using unlock_flags_t = std::uint32_t;
static constexpr unlock_flags_t UNLOCK_FLAGS_NONE = 0x0;
static constexpr unlock_flags_t UNLOCK_FLAGS_FLUSH = 0x1; /* indicates for PM backends to flush */
static constexpr pool_t POOL_ERROR = 0;
enum class Capability {
POOL_DELETE_CHECK, /*< checks if pool is open before allowing delete */
RWLOCK_PER_POOL, /*< pools are locked with RW-lock */
POOL_THREAD_SAFE, /*< pools can be shared across multiple client threads */
WRITE_TIMESTAMPS, /*< support for write timestamping */
};
enum class Op_type {
WRITE, /* copy bytes into memory region */
ZERO, /* zero the memory region */
INCREMENT_UINT64,
CAS_UINT64,
};
enum Attribute : std::uint32_t {
VALUE_LEN = 1, /* length of a value associated with key */
COUNT = 2, /* number of objects */
CRC32 = 3, /* get CRC32 of a value */
AUTO_HASHTABLE_EXPANSION = 4, /* set to true if the hash table should expand */
PERCENT_USED = 5, /* get percent used pool capacity at current size */
WRITE_EPOCH_TIME = 6, /* epoch time at which the key-value pair was last
written or locked with STORE_LOCK_WRITE */
MEMORY_TYPE = 7, /* type of memory */
MEMORY_SIZE = 8, /* size of pool or store in bytes */
NUMA_MASK = 9, /* mask of first 64 numa nodes eligible for mapstore allocation */
};
enum {
MEMORY_TYPE_DRAM = 0x1,
MEMORY_TYPE_PMEM_DEVDAX = 0x2,
MEMORY_TYPE_PMEM_FSDAX = 0x3,
MEMORY_TYPE_UNKNOWN = 0xFF,
};
enum lock_type_t {
STORE_LOCK_NONE = 0,
STORE_LOCK_READ = 1,
STORE_LOCK_WRITE = 2,
};
enum {
/* see common/errors.h */
S_MORE = 2,
E_KEY_EXISTS = E_ERROR_BASE - 1,
E_KEY_NOT_FOUND = E_ERROR_BASE - 2,
E_POOL_NOT_FOUND = E_ERROR_BASE - 3,
E_BAD_ALIGNMENT = E_ERROR_BASE - 4,
E_TOO_LARGE = E_ERROR_BASE - 5, /* -55 */
E_ALREADY_OPEN = E_ERROR_BASE - 6,
};
std::string strerro(int e)
{
static std::map<int, std::string> errs {
{ S_MORE, "MORE" }
, { E_KEY_EXISTS, "E_KEY_EXISTS" }
, { E_KEY_NOT_FOUND, "E_KEY_NOT_FOUND" }
, { E_POOL_NOT_FOUND, "E_POOL_NOT_FOUND" }
, { E_BAD_ALIGNMENT, "E_BAD_ALIGNMENT" }
, { E_TOO_LARGE, "E_TOO_LARGE" }
, { E_ALREADY_OPEN, "E_ALREADY_OPEN" }
};
auto it = errs.find(e);
return it == errs.end() ? ( "non-IKVStore error " + std::to_string(e) ) : it->second;
}
class Operation {
Op_type _type;
size_t _offset;
protected:
Operation(Op_type type, size_t offset) : _type(type), _offset(offset) {}
public:
Op_type type() const noexcept { return _type; }
size_t offset() const noexcept { return _offset; }
};
class Operation_sized : public Operation {
size_t _len;
protected:
Operation_sized(Op_type type, size_t offset_, size_t len) : Operation(type, offset_), _len(len) {}
public:
size_t size() const noexcept { return _len; }
};
class Operation_write : public Operation_sized {
const void* _data;
public:
Operation_write(size_t offset, size_t len, const void* data)
: Operation_sized(Op_type::WRITE, offset, len), _data(data)
{
}
const void* data() const noexcept { return _data; }
};
class Operation_zero : public Operation_sized {
public:
Operation_zero(size_t offset, size_t len)
: Operation_sized(Op_type::ZERO, offset, len)
{
}
};
/**
* Determine thread safety of the component
* Check capability of component
*
* @param cap Capability type
*
* @return THREAD_MODEL_XXXX
*/
virtual int thread_safety() const = 0;
/**
* Check capability of component
*
* @param cap Capability type
*
* @return THREAD_MODEL_XXXX
*/
virtual int get_capability(Capability cap) const { return error_value(-1, cap); }
/**
* Create an object pool. If the pool exists and the FLAGS_CREATE_ONLY
* is not provided, then the existing pool will be opened. If
* FLAGS_CREATE_ONLY is specified and the pool exists, POOL ERROR will be
* returned.
*
* @param pool_name Unique pool name
* @param size Size of pool in bytes (for keys,values and metadata)
* @param flags Creation flags
* @param expected_obj_count Expected maximum object count (optimization)
* @param base Optional base address
*
* @return Pool handle or POOL_ERROR
*/
virtual pool_t create_pool(const std::string& pool_name,
const size_t size,
flags_t flags = 0,
uint64_t expected_obj_count = 0,
const Addr base_addr = Addr{0})
{
PERR("create_pool not implemented");
return error_value(POOL_ERROR, pool_name, size, flags, expected_obj_count, base_addr);
}
virtual pool_t create_pool(const std::string& path,
const std::string& name,
const size_t size,
flags_t flags = 0,
uint64_t expected_obj_count = 0,
const Addr base_addr_unused = Addr{0}) __attribute__((deprecated))
{
return create_pool(path + name, size, flags, expected_obj_count, base_addr_unused);
}
/**
* Open an existing pool.
*
* @param name Name of object pool
* @param flags Optional flags e.g., FLAGS_READ_ONLY
* @param base Optional base address
*
* @return Pool handle or POOL_ERROR if pool cannot be opened, or flags
* unsupported
*/
virtual pool_t open_pool(const std::string& pool_name,
flags_t flags = 0,
const Addr base_addr_unused = Addr{0})
{
return error_value(POOL_ERROR, pool_name, flags, base_addr_unused);
}
virtual pool_t open_pool(const std::string& path,
const std::string& name,
flags_t flags = 0,
const Addr base_addr_unused = Addr{0}) __attribute__((deprecated))
{
return open_pool(path + name, flags, base_addr_unused);
}
/**
* Close pool handle
*
* @param pool Pool handle
*
* @return S_OK on success, E_POOL_NOT_FOUND, E_ALREADY_OPEN if pool cannot be
* closed due to open session.
*/
virtual status_t close_pool(pool_t pool) = 0;
/**
* Delete an existing pool
*
* @param name Name of object pool
*
* @return S_OK on success, E_POOL_NOT_FOUND, E_ALREADY_OPEN if pool cannot be
* deleted
*/
virtual status_t delete_pool(const std::string& name) = 0;
/**
* Get a list of pool names
*
* @param inout_pool_names [inout] List of pool names
*
* @return S_OK or E_NOT_IMPL;
*/
virtual status_t get_pool_names(std::list<std::string>& inout_pool_names) = 0;
/**
* Get mapped memory regions for pool. This is used for pre-registration with
* DMA engines.
*
* @param pool Pool handle
* @param out_regions Backing file name (if any), Mapped memory regions
*
* @return S_OK on success or E_POOL_NOT_FOUND. Components that do not
* support this return E_NOT_SUPPORTED.
*/
virtual status_t get_pool_regions(const pool_t pool, nupm::region_descriptor & out_regions)
{
return error_value(E_NOT_SUPPORTED, pool, out_regions); /* not supported in FileStore */
}
/**
* Dynamically expand a pool. Typically, this will add to the regions
* belonging to a pool.
*
* @param pool Pool handle
* @param increment_size Size in bytes to expand by
* @param reconfigured_size [out] new size of pool
*
* @return S_OK on success or E_POOL_NOT_FOUND. Components that do not support
* this return E_NOT_SUPPORTED (e.g. MCAS client)
*/
virtual status_t grow_pool(const pool_t pool,
const size_t increment_size,
size_t& reconfigured_size)
{
PERR("grow_pool: not supported");
return error_value(E_NOT_SUPPORTED, pool, increment_size, reconfigured_size);
}
/**
* Write or overwrite an object value. If there already exists an
* object with matching key, then it should be replaced
* (i.e. reallocated) or overwritten.
*
* @param pool Pool handle
* @param key Object key
* @param value Value data
* @param value_len Size of value in bytes
*
* @return S_OK or E_POOL_NOT_FOUND, E_KEY_EXISTS
*/
virtual status_t put(const pool_t pool,
const std::string& key,
const void* value,
const size_t value_len,
flags_t flags = FLAGS_NONE)
{
return error_value(E_NOT_SUPPORTED, pool, key, value, value_len, flags);
}
/**
* Zero-copy put operation. If there does not exist an object
* with matching key, then an error E_KEY_EXISTS should be returned.
*
* @param pool Pool handle
* @param key Object key
* @param value Value
* @param value_len Value length in bytes
* @param handle Memory registration handle
* @param flags Optional flags
*
* @return S_OK or E_POOL_NOT_FOUND, E_KEY_EXISTS
*/
virtual status_t put_direct(const pool_t pool,
const std::string& key,
gsl::span<const common::const_byte_span> values,
gsl::span<const memory_handle_t> handles = gsl::span<const memory_handle_t>(),
flags_t flags = FLAGS_NONE)
{
return error_value(E_NOT_SUPPORTED, pool, key, values, handles, flags);
}
/**
* Zero-copy put operation (see exceptions above).
*
* @param pool Pool handle
* @param key Object key
* @param value Value
* @param value_len Value length in bytes
* @param handle Memory registration handle
* @param flags Optional flags
*
* @return S_OK or error code
*/
virtual status_t put_direct(const pool_t pool,
const std::string& key,
const void* value,
const size_t value_len,
const memory_handle_t handle = MEMORY_HANDLE_NONE,
flags_t flags = FLAGS_NONE)
{
return put_direct(
pool
, key
, std::array<const common::const_byte_span,1>{common::make_const_byte_span(value, value_len)}
, std::array<memory_handle_t,1>{handle}
, flags
);
}
/**
* Resize memory for a value
*
* @param pool Pool handle
* @param key Object key (should be unlocked)
* @param new_size New size of value in bytes (can be more or less)
*
* @return S_OK on success, E_BAD_ALIGNMENT, E_POOL_NOT_FOUND,
* E_KEY_NOT_FOUND, E_TOO_LARGE, E_ALREADY(?)
*/
virtual status_t resize_value(const pool_t pool,
const std::string& key,
const size_t new_size,
const size_t alignment)
{
return error_value(E_NOT_SUPPORTED, pool, key, new_size, alignment);
}
/**
* Read an object value
*
* @param pool Pool handle
* @param key Object key
* @param out_value Value data (if null, component will allocate memory)
* @param out_value_len Size of value in bytes
*
* @return S_OK or E_POOL_NOT_FOUND, E_KEY_NOT_FOUND if key not found
*/
virtual status_t get(const pool_t pool,
const std::string& key,
void*& out_value, /* release with free_memory() API */
size_t& out_value_len) = 0;
/**
* Read an object value directly into client-provided memory.
*
* @param pool Pool handle
* @param key Object key
* @param out_value Client provided buffer for value
* @param out_value_len [in] size of value memory in bytes [out] size of value
* @param handle Memory registration handle
*
* @return S_OK, S_MORE if only a portion of value is read,
* E_BAD_ALIGNMENT on invalid alignment, E_POOL_NOT_FOUND, E_KEY_NOT_FOUND, or other
* error code
*
* Note: S_MORE is reduncant, it could have been inferred from S_OK and
* out_value_len [in] < out_value_len [out].
*/
virtual status_t get_direct(pool_t pool,
const std::string& key,
void* out_value,
size_t& out_value_len,
memory_handle_t handle = HANDLE_NONE)
{
return error_value(E_NOT_SUPPORTED, pool, key, out_value, out_value_len, handle);
}
/**
* Get attribute for key or pool (see enum Attribute)
*
* @param pool Pool handle
* @param attr Attribute to retrieve
* @param out_value Vector of attribute values
* @param key [optional] Key
*
* @return S_OK on success, E_POOL_NOT_FOUND, E_INVALID_ARG, E_KEY_NOT_FOUND
*/
virtual status_t get_attribute(pool_t pool,
Attribute attr,
std::vector<uint64_t>& out_value,
const std::string* key = nullptr) = 0;
/**
* Atomically (crash-consistent for pmem) swap keys (K,V)(K',V') -->
* (K,V')(K',V). Before calling this API, both KV-pairs must be
* unlocked.
*
* @param pool Pool handle
* @param key0 First key
* @param key1 Second key
*
* @return S_OK on success, E_POOL_NOT_FOUND, E_KEY_NOT_FOUND, E_LOCKED
* (unable to take both locks)
*/
virtual status_t swap_keys(const pool_t pool,
const std::string key0,
const std::string key1)
{
return error_value(E_NOT_SUPPORTED, pool, key0, key1);
}
/**
* Set attribute on a pool.
*
* @param pool Pool handle
* @param attr Attribute to set
* @param value Vector of values to set (for boolean 0=false, 1=true)
* @param key [optional] key
*
* @return S_OK, E_INVALID_ARG (e.g. key==nullptr), E_POOL_NOT_FOUND
*/
virtual status_t set_attribute(const pool_t pool,
const Attribute attr,
const std::vector<uint64_t>& value,
const std::string* key = nullptr)
{
return error_value(E_NOT_SUPPORTED, pool, attr, value, key);
}
/**
* Allocate memory for zero copy DMA
*
* @param vaddr [out] allocated memory buffer
* @param len [in] length of memory buffer in bytes
* @param handle memory handle
*
*/
virtual status_t allocate_direct_memory(void*& vaddr,
size_t len,
memory_handle_t& handle)
{
return error_value(E_NOT_SUPPORTED, vaddr, len, handle);
}
/**
* Free memory for zero copy DMA
*
* @param handle handle to memory region to free
*
* @return S_OK on success
*/
virtual status_t free_direct_memory(memory_handle_t handle)
{
return error_value(E_NOT_SUPPORTED, handle);
}
/**
* Register memory for zero copy DMA
*
* @param vaddr Appropriately aligned memory buffer
*
* @return Memory handle or NULL on not supported.
*/
memory_handle_t register_direct_memory(common::const_byte_span bytes) override
{
return error_value(nullptr, bytes);
}
using Registrar_memory_direct::register_direct_memory;
/**
* Direct memory regions should be unregistered before the memory is released
* on the client side.
*
* @param handle (as returned by register_direct_memory) of region to deregister.
*
* @return S_OK on success
*/
status_t unregister_direct_memory(memory_handle_t handle) override
{
return error_value(E_NOT_SUPPORTED, handle);
}
/**
* Take a lock on an object. If the object does not exist and inout_value_len
* is non-zero, create it with value space according to out_value_len (this
* is very important for mcas context). If the object does not exist and
* inout_value_len is zero, return E_KEY_NOT_FOUND.
*
* @param pool Pool handle
* @param key Key
* @param type STORE_LOCK_READ | STORE_LOCK_WRITE
* @param out_value [out] Pointer to data
* @param inout_value_len [in-out] Size of data in bytes
* @param alignment [in] Alignment of new value space in bytes.
* @param out_key [out] Handle to key for unlock
* @param out_key_ptr [out] Optional request for key-string pointer (set to
* nullptr if not required)
*
* @return S_OK, S_CREATED_OK (if created on demand), E_KEY_NOT_FOUND,
* E_LOCKED (already locked), E_INVAL (e.g., no key & no length),
* E_TOO_LARGE (cannot allocate space for lock), E_NOT_SUPPORTED
* if unable to take lock or other error
*/
virtual status_t lock(const pool_t pool,
const std::string& key,
const lock_type_t type,
void*& out_value,
size_t& inout_value_len,
size_t alignment,
key_t& out_key_handle,
const char** out_key_ptr = nullptr)
{
return error_value(E_NOT_SUPPORTED, pool, key, type, out_value, inout_value_len, alignment,
out_key_handle, out_key_ptr);
}
/**
* Unlock a key-value pair
*
* @param pool Pool handle
* @param key_handle Handle (opaque) for key used to unlock
* @param flags Optional unlock flags, UNLOCK_FLAGS_FLUSH
*
* @return S_OK, S_MORE (for async), E_INVAL or other error
*/
virtual status_t unlock(const pool_t pool,
const key_t key_handle,
const unlock_flags_t flags = UNLOCK_FLAGS_NONE)
{
return error_value(E_NOT_SUPPORTED, pool, key_handle, flags);
}
/**
* Update an existing value by applying a series of operations.
* Together the set of operations make up an atomic transaction.
* If the operation requires a result the operation type may provide
* a method to accept the result. No operation currently requires
* a result, but compare and swap probably would.
*
* @param pool Pool handle
* @param key Object key
* @param op_vector Operation vector
* @param take_lock Set to true for automatic locking of object
*
* @return S_OK or error code
*/
virtual status_t atomic_update(const pool_t pool,
const std::string& key,
const std::vector<Operation*>& op_vector,
bool take_lock = true)
{
return error_value(E_NOT_SUPPORTED, pool, key, op_vector, take_lock);
}
/**
* Erase an object
*
* @param pool Pool handle
* @param key Object key
*
* @return S_OK or error code (e.g. E_LOCKED)
*/
virtual status_t erase(pool_t pool, const std::string& key) = 0;
/**
* Return number of objects in the pool
*
* @param pool Pool handle
*
* @return Number of objects
*/
virtual size_t count(pool_t pool) = 0;
/**
* Apply functor to all objects in the pool
*
* @param pool Pool handle
* @param function Functor to apply
*
* @return S_OK, E_POOL_NOT_FOUND
*/
virtual status_t map(const pool_t pool,
std::function<int(const void* key,
const size_t key_len,
const void* value,
const size_t value_len)> function)
{
return error_value(E_NOT_SUPPORTED, pool, function);
}
/**
* Apply functor to all objects in the pool according
* to given time constraints
*
* @param pool Pool handle
* @param function Functor to apply (not in time order). If
* functor returns < 0, then map aborts
* @param t_begin Time must be after or equal. If set to zero, no constraint.
* @param t_end Time must be before or equal. If set to zero, no constraint.
*
* @return S_OK, E_POOL_NOT_FOUND
*/
virtual status_t map(const pool_t pool,
std::function<int(const void* key,
const size_t key_len,
const void* value,
const size_t value_len,
const common::tsc_time_t timestamp)> function,
const common::epoch_time_t t_begin,
const common::epoch_time_t t_end)
{
return error_value(E_NOT_SUPPORTED, pool, function, t_begin, t_end);
}
/**
* Apply functor to all keys only. Useful for file_store (now deprecated)
*
* @param pool Pool handle
* @param function Functor
*
* @return S_OK, E_POOL_NOT_FOUND
*/
virtual status_t map_keys(const pool_t pool, std::function<int(const std::string& key)> function)
{
return error_value(E_NOT_SUPPORTED, pool, function);
}
/*
auto iter = open_pool_iterator(pool);
while(deref_pool_iterator(iter, ref, true) == S_OK)
process_record(ref);
close_pool_iterator(iter);
*/
struct pool_reference_t {
public:
pool_reference_t()
: key(nullptr), key_len(0), value(nullptr), value_len(0), timestamp() {}
const void* key;
size_t key_len;
const void* value;
size_t value_len;
common::epoch_time_t timestamp; /* zero if not supported */
inline std::string get_key() const {
std::string k(static_cast<const char*>(key), key_len);
return k;
}
};
/**
* Open pool iterator to iterate over objects in pool.
*
* @param pool Pool handle
*
* @return Pool iterator or nullptr
*/
virtual pool_iterator_t open_pool_iterator(const pool_t pool)
{
return error_value(nullptr, pool);
}
/**
* Deference pool iterator position and optionally increment
*
* @param pool Pool handle
* @param iter Pool iterator
* @param t_begin Time must be after or equal. If set to zero, no constraint.
* @param t_end Time must be before or equal. If set to zero, no constraint.
* @param ref [out] Output reference record
* @param ref [out] Set to true if within time bounds
* @param increment Move iterator forward one position
*
* @return S_OK on success and valid reference, E_INVAL (bad iterator),
* E_OUT_OF_BOUNDS (when attempting to dereference out of bounds)
* E_ITERATOR_DISTURBED (when writes have been made since last iteration)
*/
virtual status_t deref_pool_iterator(const pool_t pool,
pool_iterator_t iter,
const common::epoch_time_t t_begin,
const common::epoch_time_t t_end,
pool_reference_t& ref,
bool& time_match,
bool increment = true)
{
/* Not sure of the difference between "not supported" and "not implemented",
* but they are separated codes.
*/
return error_value(E_NOT_IMPL, pool, iter, t_begin, t_end, ref, time_match, increment);
}
/**
* Unlock pool, release iterator and associated resources
*
* @param pool Pool handle
* @param iter Pool iterator
*
* @return S_OK on success, E_INVAL (bad iterator)
*/
virtual status_t close_pool_iterator(const pool_t pool,
pool_iterator_t iter)
{
return error_value(E_NOT_IMPL, pool, iter);
}
/**
* Free server-side allocated memory
*
* @param p Pointer to memory allocated through a get call
*
* @return S_OK on success
*/
virtual status_t free_memory(void* p)
{
::free(p);
return S_OK;
}
/**
* Allocate memory from pool
*
* @param pool Pool handle
* @param size Size in bytes
* @param alignment Alignment hint in bytes, 0 if no alignment is needed
* @param out_addr Pointer to allocated region
*
* @return S_OK on success, E_BAD_ALIGNMENT, E_POOL_NOT_FOUND, E_NOT_SUPPORTED
*/
virtual status_t allocate_pool_memory(const pool_t pool,
const size_t size,
const size_t alignment_hint,
void*& out_addr)
{
return error_value(E_NOT_SUPPORTED, pool, size, alignment_hint, out_addr);
}
/**
* Free memory from pool
*
* @param pool Pool handle
* @param addr Address of memory to free
* @param size Size in bytes of allocation; if provided this accelerates
* release
*
* @return S_OK on success, E_INVAL, E_POOL_NOT_FOUND, E_NOT_SUPPORTED
*/
virtual status_t free_pool_memory(pool_t pool, const void* addr, size_t size = 0)
{
return error_value(E_NOT_SUPPORTED, pool, addr, size);
}
/**
* Flush memory from pool
*
* @param pool Pool handle
* @param addr Address of memory to flush
* @param size Size in bytes to flush
*
* @return S_OK on success, E_INVAL, E_POOL_NOT_FOUND, E_NOT_SUPPORTED
*/
virtual status_t flush_pool_memory(pool_t pool, const void* addr, size_t size)
{
return error_value(E_NOT_SUPPORTED, pool, addr, size);
}
/**
* Perform control invocation on component
*
* @param command String representation of command (component-interpreted)
*
* @return S_OK on success or error otherwise
*/
virtual status_t ioctl(const std::string& command) { return error_value(E_NOT_SUPPORTED, command); }
/**
* Debug routine
*
* @param pool Pool handle
* @param cmd Debug command
* @param arg Parameter for debug operation
*/
virtual void debug(pool_t pool, unsigned cmd, uint64_t arg) = 0;
};
} // namespace component
#endif
| {
"alphanum_fraction": 0.61394461,
"avg_line_length": 32.670678337,
"ext": "h",
"hexsha": "aeb8946a39af9bc2a673d371470c2a226a1a4964",
"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": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "IBM/artemis",
"max_forks_repo_path": "src/components/api/kvstore.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"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": "IBM/artemis",
"max_issues_repo_path": "src/components/api/kvstore.h",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "IBM/artemis",
"max_stars_repo_path": "src/components/api/kvstore.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7075,
"size": 29861
} |
#ifndef CHEVALIER_H
#define CHEVALIER_H
#include <math.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_multiroots.h>
#define parsec_in_cm 3.085678e+18 //parsec in cm
#define parsec_in_km 3.085678e+13 //parsec in km
#define msun_in_g 1.988920e+33 //msun in g
#define year_in_sec 3.155760e+07 //year in s
typedef struct Chevalier
{
double M_dot; //mass input rate
double E_dot; //energy input rate
double R; //limit of mass and energy input
double gamma; //adiabatic index
double V; //Volume of input area
double q; //M_dot / V
double Q; //E_dot / V
gsl_root_fsolver *grsolve; //GSL root solver
} Chevalier;
// Function declarations for Chevalier struct
void SetChevalier(Chevalier *c, double M_dot, double E_dot, double gamma, double R);
double MachNumber(Chevalier *c, double r); //mach number vs. radius
double MomentumDensity(Chevalier *c, double r); //momentum density vs. radius in Msun/pc^3 * km/s
double Pressure(Chevalier *c, double r); //Pressure in dyn cm^-2
double Density(Chevalier *c, double r); //density in g cm^-3
double Density_Msunpc3(Chevalier *c, double r); //density in Msun/pc3
double WindVelocity(Chevalier *c, double r); //wind velocity in km/s
double EnergyIntegral(Chevalier *c, double r); //msun/yr (km/s)^2 / pc^3
double u_star(Chevalier *c, double r); //normalized wind velocity
double rho_star(Chevalier *c, double r); //normalized density
double P_star(Chevalier *c, double r); //normalized pressure
double mach_crossing_A(double M, void *fp); //functions for Mach number root finding
double mach_crossing_B(double M, void *fp);
// Function definitions
void SetChevalier(Chevalier *c, double M_dot, double E_dot, double gamma, double R) {
// M_dot = Mass input in Msun/yr
// E_dot = Energy input in erg / s
// gamma = Adiabatic index
// R = Radius of the wind region in parsec
//Set model parameters
c->M_dot = M_dot;
c->E_dot = E_dot;
c->gamma = gamma;
c->R = R;
c->V = (4.*M_PI/3. * R*R*R); //volume in pc^3
//compute input density rate (msun / yr / pc^3)
c->q = c->M_dot / c->V;
//compute input energy density rate (msun/yr (km/s)^2 / pc^3)
c->Q = (c->E_dot/msun_in_g*year_in_sec / 1.0e10) / c->V;
//define the GSL root solver to use
const gsl_root_fsolver_type *grsolve_T = gsl_root_fsolver_brent;
c->grsolve = gsl_root_fsolver_alloc(grsolve_T);
}
double u_star(Chevalier *c, double r) {
// Returns dimensionless wind velocity
double u = WindVelocity(c, r);
double u_prime = sqrt(c->E_dot)/sqrt(c->M_dot*msun_in_g/year_in_sec)/1.0e5;
return u/u_prime;
}
double rho_star(Chevalier *c, double r) {
// Returns dimensionless density
double rho = Density(c,r); //g cm^-3
double M_dot_prime = c->M_dot * msun_in_g/year_in_sec; // g/s
double R_prime = c->R * parsec_in_cm; //cm
double rho_prime = pow(M_dot_prime,1.5)/(sqrt(c->E_dot)*R_prime*R_prime);
return rho/rho_prime;
}
double P_star(Chevalier *c, double r) {
// Returns dimensionless pressure
double P = Pressure(c,r); //dyn cm^-2
double M_dot_prime = c->M_dot * msun_in_g/year_in_sec; // g/s
double R_prime = c->R * parsec_in_cm; //cm
double P_prime = sqrt(M_dot_prime)*sqrt(c->E_dot)/(R_prime*R_prime);
return P/P_prime;
}
double Pressure(Chevalier *c, double r) {
// Returns pressure in dyn cm^-2
double Mach = MachNumber(c,r); //mach number
double u = WindVelocity(c,r); //km/s
double cs = u/Mach * 1.0e5; //sound speed in cm/s
u *= year_in_sec / parsec_in_km; //to pc/yr
double rho = MomentumDensity(c,r)/u; //Msun / pc^3
rho *= msun_in_g; //g / pc^3
rho /= pow(parsec_in_cm, 3); //g / cm^3
double P = cs*cs*rho/c->gamma; //pressure in cgs
return P; //in dyn cm^-2
}
double Density(Chevalier *c, double r) {
// Returns density in g cm^-3
double rho = Density_Msunpc3(c, r); //Msun/pc^3
rho *= msun_in_g; //g / pc^3
rho /= pow(parsec_in_cm, 3); //g / cm^3
return rho; // in g/cm^3
}
double Density_Msunpc3(Chevalier *c, double r) {
// Returns density in g cm^-3
double u = WindVelocity(c, r); //km/s
u *= year_in_sec / parsec_in_km; //to pc/yr
return MomentumDensity(c,r)/u; //Msun/pc^3;
}
double WindVelocity(Chevalier *c, double r) {
// Returns wind velocity in km/s
//First, find integrated energy input density
double Qint = EnergyIntegral(c, r); //msun/yr (km/s)^2 / pc^3
//Second, find momentum density
double rhou = MomentumDensity(c, r); //msun/yr/pc^2
//find sq of velocity (modulo gamma + Mach correction)
double usq = Qint/rhou; //1/2 u^2 + (gamma/(gamma-1))*P/rho
//1/2 u^2 + c^2 / (gamma-1)
//1/2 u^2 + u^2 / (M^2 (gamma-1))
//u^2 * ( 1/2 + 1/(M^2 (gamma-1)) )
//get the mach number
double Mach = MachNumber(c,r);
//find the adjustment factor
double fac = (0.5 + 1./(Mach*Mach*(c->gamma-1.)));
return sqrt(usq/fac); //km/s
}
double EnergyIntegral(Chevalier *c, double r) {
double Qint = r<c->R ? 1./3.*c->Q*r : 1./3.*c->Q*c->R*c->R*c->R/(r*r);
return Qint; //msun/yr (km/s)^2 / pc^3
}
double MomentumDensity(Chevalier *c, double r) {
double rhou = r<c->R ? 1./3.*c->q*r : 1./3.*c->q*c->R*c->R*c->R/(r*r) ;
return rhou; // in Msun/yr/pc^2
}
double MachNumber(Chevalier *c, double r) {
int status, iter=0, max_iter=100;
double M_lo = 1.0e-5, M_hi = 5.;
double Mx, answer = 0;
double x = r/c->R;
gsl_function func;
double fp[2] = {c->gamma, x};
//choose which solution to use
if(x<=1.0) {
M_lo = 1.0e-5;
M_hi = 1.0;
func.function = &mach_crossing_A;
}
else {
M_lo = 1.0;
M_hi = 10000.0;
func.function = &mach_crossing_B;
}
func.params = &fp[0];
gsl_root_fsolver_set(c->grsolve, &func, M_lo, M_hi);
while(++iter<max_iter){
status = gsl_root_fsolver_iterate(c->grsolve);
Mx = gsl_root_fsolver_root(c->grsolve);
M_lo = gsl_root_fsolver_x_lower(c->grsolve);
M_hi = gsl_root_fsolver_x_upper(c->grsolve);
status = gsl_root_test_interval(M_lo,M_hi,0,1.0e-5);
if(status==GSL_SUCCESS) {answer = Mx; break;}
}
return answer;
}
double mach_crossing_A(double M, void *fp) {
double *g = (double *) fp;
double gamma = g[0];
double x = g[1];
double alpha = -1.*(3.*gamma+1.)/(5.*gamma+1.);
double beta = (gamma+1.)/(2.*(5.*gamma+1.));
double A = pow( (3.*gamma + 1./(M*M))/(1.+3.*gamma), alpha);
double B = pow( (gamma-1.+2./(M*M))/(1.+gamma), beta);
return A*B - x;
}
double mach_crossing_B(double M, void *fp) {
double *g = (double *) fp;
double gamma = g[0];
double x = g[1];
double alpha = 2./(gamma-1.);
double beta = (gamma+1.)/(2.*(gamma-1.));
double A = pow( M, alpha);
double B = pow( (gamma-1.+2./(M*M))/(1.+gamma), beta);
return A*B - x*x;
}
#endif //CHEVALIER_H | {
"alphanum_fraction": 0.5793735068,
"avg_line_length": 34.8796296296,
"ext": "h",
"hexsha": "0beb79112041ef564d4ac2a3b38a1393bd1d2208",
"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": "b550ea71473a4db8d110bf56c03889806358aea1",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "editeodoro/galpy",
"max_forks_repo_path": "galpy/potential/potential_c_ext/Chevalier.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b550ea71473a4db8d110bf56c03889806358aea1",
"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": "editeodoro/galpy",
"max_issues_repo_path": "galpy/potential/potential_c_ext/Chevalier.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b550ea71473a4db8d110bf56c03889806358aea1",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "editeodoro/galpy",
"max_stars_repo_path": "galpy/potential/potential_c_ext/Chevalier.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2406,
"size": 7534
} |
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* example_02-StructOfArrays-Naive-Omp.c :
* Example of SPH Density Calculation using a
* naive implementation of the main density loop,
* no neighbours earch, and Struct of Arrays (SoA)
* data layout and OpenMP parallelization.
*
* (C) Copyright 2021 José Hugo Elsas
* Author: José Hugo Elsas <jhelsas@gmail.com>
*
* Command Line Options:
* -runs <int> : Set the number of repetitions (runs) for
* calculating the density. The value of
* the density is based on the last
* iteration.
* Default value: 1
* -run_seed <int>: Flag to set an alternative seed use for
* for the PRNG. Instead of feeding seed
* to the PRNG directly, it feeds
* seed + iteration, as to generate different
* configurations for each iteration.
* Default value: 0 - (possible 0/1)
* -seed <int>: Set the seed to use for the SPH particles
* uniform position generation in the box
* Default value: 123123123
*
* -N <int>: Set the number of SPH particles to be used
* Default value: 1e5 = 100,000
* -h <float>: Set the value of the smoothing kernel
* parameter h, which corresponds to half
* of the support of the kernel.
* Default value: 0.05
*
* -Nx <int>: Set the number of Cells in the X direction
* Default value: 10
* -Ny <int>: Set the number of Cells in the Y direction
* Default value: 10
* -Nz <int>: Set the number of Cells in the Z direction
* Default value: 10
*
* -Xmin <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 0.0
*
* -Xmax <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 1.0
* -Ymax <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 1.0
* -Zmax <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 1.0
*/
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_utils.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define COMPUTE_BLOCKS 1
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times);
int compute_density_3d_naive_omp(int N,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rho);
double w_bspline_3d(double r,double h);
int main(int argc, char **argv){
bool run_seed = false; // By default the behavior is is to use the same seed
int runs = 1,err; // it only runs once
long int seed = 123123123; // The default seed is 123123123
int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000
double h=0.05; // The default kernel smoothing length is h = 0.05
linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method
SPHparticle *lsph; // Uninitialized array of SPH particles
box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box
// allow for command line customization of the run
arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command
// line arguments and override default values
err = SPHparticle_SoA_malloc(N,&lsph); // Create an array of N particles
if(err)
fprintf(stderr,"error in SPHparticle_SoA_malloc\n");
void *swap_arr = malloc(N*sizeof(double));
double times[runs*COMPUTE_BLOCKS];
for(int run=0;run<runs;run+=1)
main_loop(run,run_seed,N,h,seed,swap_arr,box,lsph,times);
bool is_cll = false;
const char *prefix = "ex02,naive,SoA,omp";
print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times);
print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box);
SPHparticleSOA_safe_free(N,&lsph);
safe_free_box(box);
free(swap_arr);
return 0;
}
/*
* Function main_loop:
* Runs the main loop of the program, including the particle array generation,
* density calculation and the timings annotations.
*
* Arguments:
* run <int> : index (or value) or the present iteration
* run_seed <bool> : boolean defining whether to use run index for seed or not
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* seed <long int> : seed for GSL PRNG generator to generate particle positions
* box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* times <double> : Array to store the computation timings to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
* times <double> : Times is updated by reference
*/
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times)
{
int err;
// Initialize the particles' positions and other values
if(run_seed)
err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);
else
err = gen_unif_rdn_pos_box(N,seed,box,lsph);
if(err)
fprintf(stderr,"error in gen_unif_rdn_pos\n");
// ------------------------------------------------------ //
double t0,t1;
t0 = omp_get_wtime();
compute_density_3d_naive_omp(N,h,lsph->x,lsph->y,lsph->z,
lsph->nu,lsph->rho); // Compute the density for all particles
t1 = omp_get_wtime();
// ------------------------------------------------------ //
times[COMPUTE_BLOCKS*run+0] = t1-t0; // Only one component to measure time
return 0;
}
/*
* Function compute_density_3d_naive_omp:
* Computes the SPH density from the particles naively (i.e. direct loop).
* The outer-most loop is parallelized using openMP.
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* x <double*> : Array of particles' X positions
* y <double*> : Array of particles' Y positions
* z <double*> : Array of particles' Z positions
* nu <double*> : Array of particles' density weights (i.e. masses)
* Returns:
* 0 : error code returned
* rho <double*> : Array of particles' densities
*/
int compute_density_3d_naive_omp(int N,double h,
double* restrict x, double* restrict y,
double* restrict z,double* restrict nu,
double* restrict rho){
memset(rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero
#pragma omp parallel for // Iterate in parallel
for(int64_t ii=0;ii<N;ii+=1){ // For every particle
for(int64_t jj=0;jj<N;jj+=1){ // Run over every other particle
double dist = 0.; // the contributions from each direction by
dist += (x[ii]-x[jj])*(x[ii]-x[jj]); // adding the contribution in the X direction
dist += (y[ii]-y[jj])*(y[ii]-y[jj]); // adding the contribution in the Y direction
dist += (z[ii]-z[jj])*(z[ii]-z[jj]); // adding the contribution in the Z direction
dist = sqrt(dist); // take the sqrt to have the distance
rho[ii] += nu[jj]*w_bspline_3d(dist,h); // and add the contribution to the density
}
}
return 0;
}
/*
* Function w_bspline_3d:
* Returns the normalized value of the cubic b-spline SPH smoothing kernel
*
* Arguments:
* q <double> : Distance between particles
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* Returns:
* wq <double> : Normalized value of the kernel
*/
double w_bspline_3d(double r,double h){
const double A_d = 3./(2.*M_PI*h*h*h); // The 3d normalization constant
double q=0.; // normalized distance, initialized to zero
if(r<0||h<=0.) // If either distance or smoothing length
exit(10); // are negative, declare an emergency
q = r/h; // Compute the normalized distance
if(q<=1) // If the distance is small
return A_d*(2./3.-q*q + q*q*q/2.0); // Compute this first polynomal
else if((1.<=q)&&(q<2.)) // If the distance is a bit larger
return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q); // Compute this other polynomial
else // Otherwise, if the distance is large
return 0.; // The value of the kernel is 0
} | {
"alphanum_fraction": 0.5669945564,
"avg_line_length": 41.3873517787,
"ext": "c",
"hexsha": "37bd96a1684f5e29d6bf6c3bd57f3d6f3498370f",
"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": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jhelsas/sphalerite",
"max_forks_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"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": "jhelsas/sphalerite",
"max_issues_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jhelsas/sphalerite",
"max_stars_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2614,
"size": 10471
} |
/**
*
* @file core_dgeqp3_tntpiv.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 d Tue Jan 7 11:44:50 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************
*
* @ingroup CORE_double
*
* CORE_dgeqp3_tntpiv computes a QR factorization with column pivoting of a
* matrix A: A*P = Q*R using Level 3 BLAS.
*
* The matrix Q is represented as a product of elementary reflectors
*
* Q = H(1) H(2) . . . H(k), where k = min(m,n).
*
* Each H(i) has the form
*
* H(i) = I - tau * v * v**T
*
* where tau is a complex scalar, and v is a real/complex vector
* with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in
* A(i+1:m,i), and tau in TAU(i).
*
*******************************************************************************
*
* Arguments:
* ==========
*
* @param[in] m
* The number of rows of the matrix A. M >= 0.
*
* @param[in] n
* The number of columns of the matrix A. N >= 0.
*
* @param[in,out] A
* A is COMPLEX*16 array, dimension (LDA,N)
* On entry, the M-by-N matrix A.
* On exit, the upper triangle of the array contains the
* min(M,N)-by-N upper trapezoidal matrix R; the elements below
* the diagonal, together with the array TAU, represent the
* unitary matrix Q as a product of min(M,N) elementary
* reflectors.
*
* @param[in] lda
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[out] IPIV
* IPIV is INTEGER array, dimension min(M,N)
* The pivot indices; for 1 <= j <= min(M,N), column j of the
* tile was interchanged with column IPIV(j).
*
* @param[out] TAU
* TAU is COMPLEX*16 array, dimension (min(M,N))
* The scalar factors of the elementary reflectors.
*
* @param[in,out] iwork
* iwork is INTEGER array, dimension (N)
* On entry, if iwork(J).ne.0, the J-th column of A is permuted
* to the front of A*P (a leading column); if iwork(J)=0,
* the J-th column of A is a free column.
* On exit, if iwork(J)=K, then the J-th column of A*P was the
* the K-th column of A.
*
* @param[out] INFO
* = 0: successful exit.
* < 0: if INFO = -i, the i-th argument had an illegal value.
*
*******************************************************************************
*
* @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_dgeqp3_tntpiv = PCORE_dgeqp3_tntpiv
#define CORE_dgeqp3_tntpiv PCORE_dgeqp3_tntpiv
#endif
int CORE_dgeqp3_tntpiv(int m, int n,
double *A, int lda,
int *IPIV, double *tau,
int *iwork)
{
int i, tmp, info;
memset(iwork, 0, n*sizeof(int));
info = LAPACKE_dgeqp3(LAPACK_COL_MAJOR, m, n, A, lda, iwork, tau );
/* Convert IPIV from permutation array, to pivot array
* WARNING: this is because this kernel is only used in
* tournament pivoting with rank revealing QR */
if (info == 0) {
for(i=0; i<min(m,n); i++) {
assert(iwork[i] != 0 );
tmp = iwork[i]-1;
while( tmp < i ) {
tmp = IPIV[ tmp ] - 1;
}
IPIV[i] = tmp+1;
}
}
return info;
}
| {
"alphanum_fraction": 0.5202666667,
"avg_line_length": 32.0512820513,
"ext": "c",
"hexsha": "12f4778016d8b1ea991b2e948ed0ba905d0c3ac6",
"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_dgeqp3_tntpiv.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_dgeqp3_tntpiv.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_dgeqp3_tntpiv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1055,
"size": 3750
} |
#include <cblas.h>
#include <stdio.h>
void main()
{
int i=0;
double A[6] = {1.0,2.0,1.0,-3.0,4.0,-1.0};
double B[6] = {1.0,2.0,1.0,-3.0,4.0,-1.0};
double C[9] = {.5,.5,.5,.5,.5,.5,.5,.5,.5};
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,3,3,2,1,A, 3, B, 3,2,C,3);
for(i=0; i<9; i++)
printf("%lf ", C[i]);
printf("\n");
}
| {
"alphanum_fraction": 0.5129682997,
"avg_line_length": 21.6875,
"ext": "c",
"hexsha": "1fb58a583311d26c935283e82c49e2fcf346ed5b",
"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": "eddd31268e213b2115374b61080ec0be621f5c60",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "chelini/openBlas",
"max_forks_repo_path": "benchmark/cblas_dgemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60",
"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": "chelini/openBlas",
"max_issues_repo_path": "benchmark/cblas_dgemm.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "chelini/openBlas",
"max_stars_repo_path": "benchmark/cblas_dgemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 179,
"size": 347
} |
//
// Created by Jarlene on 2017/7/21.
//
#ifndef MATRIX_MATH_H
#define MATRIX_MATH_H
#include <math.h>
#include <assert.h>
#include <functional>
#include <vector>
#include <random>
#include <sys/time.h>
#include "Logger.h"
#include "Eigen.h"
#ifdef USE_MP
#include <omp.h>
#endif
#ifdef USE_MKL
#ifndef BLAS
#define BLAS
#endif
#include <mkl.h>
#include <mkl_cblas.h>
#include <mkl_vsl.h>
#include <mkl_vsl_functions.h>
#elif defined(USE_BLAS)
#ifndef BLAS
#define BLAS
#endif
#include <cblas.h>
#endif
namespace matrix {
static inline bool isLess(int a, int b) {
return static_cast<unsigned>(a) < static_cast<unsigned>(b);
}
static struct timeval tv;
static std::mt19937 rnd_engine_;
enum BlasTranspose {
NoTrans,
Trans,
ConjTrans
};
/// C := alpha*op(A)*op(B) + beta*C
/// \tparam T the type of input data
/// \param TransA
/// \param TransB
/// \param M
/// \param N
/// \param K
/// \param alpha
/// \param A
/// \param B
/// \param beta
/// \param C
template <class T>
inline void CPUGemm(const BlasTranspose TransA,
const BlasTranspose TransB, const int M, const int N, const int K,
const T alpha, const T *A, const T *B, const T beta,
T *C);
template <>
inline void CPUGemm<float>(const BlasTranspose TransA,
const BlasTranspose TransB, const int M, const int N, const int K,
const float alpha, const float *A, const float *B, const float beta,
float *C) {
#ifdef BLAS
int lda = (TransA == NoTrans) ? K : M;
int ldb = (TransB == NoTrans) ? N : K;
CBLAS_TRANSPOSE Atrans, Btrans;
switch (TransA) {
case NoTrans:
Atrans = CblasNoTrans;
break;
case Trans:
Atrans = CblasTrans;
break;
case ConjTrans:
Atrans = CblasConjTrans;
break;
}
switch (TransB) {
case NoTrans:
Btrans = CblasNoTrans;
break;
case Trans:
Btrans = CblasTrans;
break;
case ConjTrans:
Btrans = CblasConjTrans;
break;
}
cblas_sgemm(CblasRowMajor, Atrans, Btrans, M, N, K, alpha, A, lda, B,
ldb, beta, C, N);
#elif defined(USE_EIGEN)
int lda = (TransA == NoTrans) ? M : K; // A 的行
int ldb = (TransB == NoTrans) ? N : K; // B 的列
int aCol = (TransA == NoTrans) ? K : M; // A的列
auto aMatrix = create<float>(A, lda, aCol);
auto bMatrix = create<float>(B, aCol, ldb);
auto cMatrix = create<float>(C, lda, ldb);
cMatrix = alpha * aMatrix * bMatrix + beta * cMatrix;
#endif
}
template <>
inline void CPUGemm<double>(const BlasTranspose TransA,
const BlasTranspose TransB, const int M, const int N, const int K,
const double alpha, const double *A, const double *B, const double beta,
double *C) {
#ifdef BLAS
int lda = (TransA == NoTrans) ? K : M;
int ldb = (TransB == NoTrans) ? N : K;
CBLAS_TRANSPOSE Atrans, Btrans;
switch (TransA) {
case NoTrans:
Atrans = CblasNoTrans;
break;
case Trans:
Atrans = CblasTrans;
break;
case ConjTrans:
Atrans = CblasConjTrans;
break;
}
switch (TransB) {
case NoTrans:
Btrans = CblasNoTrans;
break;
case Trans:
Btrans = CblasTrans;
break;
case ConjTrans:
Btrans = CblasConjTrans;
break;
}
cblas_dgemm(CblasRowMajor, Atrans, Btrans, M, N, K, alpha, A, lda, B,
ldb, beta, C, N);
#elif defined(USE_EIGEN)
int lda = (TransA == NoTrans) ? M : K; // A 的行
int ldb = (TransB == NoTrans) ? K : N; // B 的列
int aCol = (TransA == NoTrans) ? K : M; // A的列
auto aMatrix = create<double>(A, lda, aCol);
auto bMatrix = create<double>(B, aCol, ldb);
auto cMatrix = create<double>(C, lda, ldb);
cMatrix = alpha * aMatrix * bMatrix + beta * cMatrix;
#endif
}
template <>
inline void CPUGemm<int>(const BlasTranspose TransA,
const BlasTranspose TransB, const int M, const int N, const int K,
const int alpha, const int *A, const int *B, const int beta,
int *C) {
#ifdef USE_EIGEN
int lda = (TransA == NoTrans) ? M : K; // A 的行
int ldb = (TransB == NoTrans) ? N : K; // B 的列
int aCol = (TransA == NoTrans) ? K : M; // A的列
auto aMatrix = create<int>(A, lda, aCol);
auto bMatrix = create<int>(B, aCol, ldb);
auto cMatrix = create<int>(C, lda, ldb);
cMatrix = alpha * aMatrix * bMatrix + beta * cMatrix;
#endif
}
template <>
inline void CPUGemm<long>(const BlasTranspose TransA,
const BlasTranspose TransB, const int M, const int N, const int K,
const long alpha, const long *A, const long *B, const long beta,
long *C) {
}
/// y := alpha*A*x + beta*y, or y := alpha*A^T*x + beta*y,
/// \tparam T
/// \param TransA
/// \param M
/// \param N
/// \param alpha
/// \param A
/// \param x
/// \param beta
/// \param y
template <class T>
inline void CPUGemv(const BlasTranspose TransA, const int M, const int N,
const T alpha, const T *A, const T *x, const T beta,
T *y);
template <>
inline void CPUGemv<float>(const BlasTranspose TransA, const int M, const int N,
const float alpha, const float *A, const float *x, const float beta,
float *y) {
#ifdef BLAS
CBLAS_TRANSPOSE Atrans;
switch (TransA) {
case NoTrans:
Atrans = CblasNoTrans;
break;
case Trans:
Atrans = CblasTrans;
break;
case ConjTrans:
Atrans = CblasConjTrans;
break;
default:
break;
}
cblas_sgemv(CblasRowMajor, Atrans, M, N, alpha, A, N, x, 1, beta, y, 1);
#elif defined(USE_EIGEN)
int lda = (TransA == NoTrans)? M : N;
int cda = (TransA == NoTrans)? N : M;
auto aMatrix = create<>(A, lda, cda);
auto xVector = create<>(x, cda);
auto yVector = create<>(y, lda);
yVector = alpha * aMatrix * xVector + beta * yVector;
#endif
}
template <>
inline void CPUGemv<double>(const BlasTranspose TransA, const int M, const int N,
const double alpha, const double *A, const double *x, const double beta,
double *y) {
#ifdef BLAS
CBLAS_TRANSPOSE Atrans;
switch (TransA) {
case NoTrans:
Atrans = CblasNoTrans;
break;
case Trans:
Atrans = CblasTrans;
break;
case ConjTrans:
Atrans = CblasConjTrans;
break;
default:
break;
}
cblas_dgemv(CblasRowMajor, Atrans, M, N, alpha, A, N, x, 1, beta, y, 1);
#elif defined(USE_EIGEN)
int lda = (TransA == NoTrans)? M : N;
int cda = (TransA == NoTrans)? N : M;
auto aMatrix = create<double>(A, lda, cda);
auto xVector = create<double>(x, cda);
auto yVector = create<double>(y, lda);
yVector = alpha * aMatrix * xVector + beta * yVector;
#endif
}
template <>
inline void CPUGemv<int>(const BlasTranspose TransA, const int M, const int N,
const int alpha, const int *A, const int *x, const int beta,
int *y) {
#ifdef USE_EIGEN
int lda = (TransA == NoTrans)? M : N;
int cda = (TransA == NoTrans)? N : M;
auto aMatrix = create<int>(A, lda, cda);
auto xVector = create<int>(x, cda);
auto yVector = create<int>(y, lda);
yVector = alpha * aMatrix * xVector + beta * yVector;
#endif
}
template <>
inline void CPUGemv<long>(const BlasTranspose TransA, const int M, const int N,
const long alpha, const long *A, const long *x, const long beta,
long *y) {
}
/// Y = alpha * X + Y
/// \tparam T
/// \param N
/// \param alpha
/// \param X
/// \param incx
/// \param Y
/// \param incy
template <class T>
inline void CPUAxpy(const int N, const T alpha, const T *X, int incx,
T *Y, int incy);
template <>
inline void CPUAxpy<float>(const int N, const float alpha, const float *X, int incx,
float *Y, int incy) {
#ifdef BLAS
cblas_saxpy(N, alpha, X, incx, Y, incy);
#else
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i <N; ++i) {
Y[posy] += alpha * X[posx];
posx += incx;
posy += incy;
}
#endif
}
template <>
inline void CPUAxpy<double>(const int N, const double alpha, const double *X, int incx,
double *Y, int incy) {
#ifdef BLAS
cblas_daxpy(N, alpha, X, incx, Y, incy);
#else
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i <N; ++i) {
Y[posy] += alpha * X[posx];
posx += incx;
posy += incy;
}
#endif
}
template <>
inline void CPUAxpy<int>(const int N, const int alpha, const int *X, int incx,
int *Y, int incy) {
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i <N; ++i) {
Y[posy] += alpha * X[posx];
posx += incx;
posy += incy;
}
}
template <>
inline void CPUAxpy<long>(const int N, const long alpha, const long *X, int incx,
long *Y, int incy) {
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i <N; ++i) {
Y[posy] += alpha * X[posx];
posx += incx;
posy += incy;
}
}
/**
* Y = alpha * X + beta * Y
* @param T
* @param N
* @param alpha
* @param X
* @param beta
* @param Y
*/
template <class T>
inline void CPUAxpby(const int N, const T alpha, const T *X, int incx,
const T beta, T *Y, int incy);
template <>
inline void CPUAxpby<float>(const int N, const float alpha, const float *X, int incx,
const float beta, float *Y, int incy) {
#ifdef BLAS
cblas_saxpby(N, alpha, X, incx, beta, Y, incy);
#endif
}
template <>
inline void CPUAxpby<double>(const int N, const double alpha, const double *X, int incx,
const double beta, double *Y, int incy) {
#ifdef BLAS
cblas_daxpby(N, alpha, X, incx, beta, Y, incy);
#endif
}
template <>
inline void CPUAxpby<int>(const int N, const int alpha, const int *X, int incx,
const int beta, int *Y, int incy) {
}
template <>
inline void CPUAxpby<long>(const int N, const long alpha, const long *X, int incx,
const long beta, long *Y, int incy) {
}
/// Y=X
/// \tparam T
/// \param N
/// \param x
/// \param incx
/// \param y
/// \param incy
template <class T>
inline void CPUCopy(const int N, const T* x, int incx, T* y, int incy);
template <>
inline void CPUCopy<float>(const int N, const float* x, int incx, float* y, int incy) {
#ifdef BLAS
cblas_scopy(N, x, incx, y, incy);
#else
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
y[posy] = x[posx];
posy += incy;
posx += incx;
}
#endif
}
template <>
inline void CPUCopy<double>(const int N, const double* x, int incx, double* y, int incy) {
#ifdef BLAS
cblas_dcopy(N, x, incx, y, incy);
#else
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
y[posy] = x[posx];
posy += incy;
posx += incx;
}
#endif
}
template <>
inline void CPUCopy<int>(const int N, const int* x, int incx, int* y, int incy) {
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
y[posy] = x[posx];
posy += incy;
posx += incx;
}
}
template <>
inline void CPUCopy<long>(const int N, const long* x, int incx, long* y, int incy) {
int posx = 0;
int posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
y[posy] = x[posx];
posy += incy;
posx += incx;
}
}
///
/// \tparam T
/// \param N
/// \param x
/// \param incx
/// \param y
/// \param incy
template <class T>
inline void CPUSwap(const int N, T * x, int incx, T *y, int incy );
template <>
inline void CPUSwap<float>(const int N, float * x, int incx, float *y, int incy ) {
#ifdef BLAS
cblas_sswap(N, x, incx, y, incy);
#else
int posx = 0, posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
std::swap(x[posx], y[posy]);
posx += incx;
posy += incy;
}
#endif
}
template <>
inline void CPUSwap<double>(const int N, double * x, int incx, double *y, int incy ) {
#ifdef BLAS
cblas_dswap(N, x, incx, y, incy);
#else
int posx = 0, posy = 0;
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
std::swap(x[posx], y[posy]);
posx += incx;
posy += incy;
}
#endif
}
template <class T>
inline void CPUSwap(const int N, T * x) {
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N/2; ++i) {
std::swap(x[i], x[N-1-i]);
}
}
/// res = x'*y
/// \tparam T
/// \param N
/// \param x
/// \param y
/// \param res
template <class T>
inline void CPUDot(const int N, const T* x, const T* y, T& res);
template <>
inline void CPUDot<float>(const int N, const float* x, const float* y, float& res) {
#ifdef BLAS
res = cblas_sdot(N, x, 1, y, 1);
#else
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
res += x[i] * y[i];
}
#endif
}
template <>
inline void CPUDot<double>(const int N, const double* x, const double* y, double& res) {
#ifdef BLAS
res = cblas_ddot(N, x, 1, y, 1);
#else
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
res += x[i] * y[i];
}
#endif
}
template <>
inline void CPUDot<int>(const int N, const int* x, const int* y, int& res) {
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
res += x[i] * y[i];
}
}
template <>
inline void CPUDot<long>(const int N, const long* x, const long* y, long& res) {
#ifdef USE_MP
omp_set_num_threads(CPU_CORES);
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
res += x[i] * y[i];
}
}
template <class T>
inline void Value(const int N, T* out, T val) {
if (val == T(0)) {
memset(out, 0, sizeof(T) * N);
return;
}
#ifdef USE_EIGEN
Vec<T> vec = create<T>(out, N);
vec.fill(val);
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] = val;
}
#endif
}
template <class T>
inline void Scale(const int N, T* out, T val);
template <>
inline void Scale<float>(const int N, float* out, float val) {
#ifdef BLAS
cblas_sscal(N, val, out, 1);
#elif define(USE_EIGEN)
auto v = create<float>(out, N);
v = v * val;
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] *= val;
}
#endif
}
template <>
inline void Scale<double>(const int N, double* out, double val) {
#ifdef BLAS
cblas_dscal(N, val, out, 1);
#elif define(USE_EIGEN)
auto v = create<double>(out, N);
v = v*val;
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] *= val;
}
#endif
}
template <>
inline void Scale<int>(const int N, int* out, int val) {
#ifdef USE_EIGEN
auto v = create<int>(out, N);
v *= val;
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] *= val;
}
#endif
}
template <>
inline void Scale<long>(const int N, long* out, long val) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] *= val;
}
}
template <class T>
inline void Random(const int N, T *out, T mu, T sigma) {
gettimeofday(&tv,NULL);
std::normal_distribution<T> dist_normal(mu, sigma);
rnd_engine_.seed((unsigned int) (tv.tv_sec * 1000 * 1000 + tv.tv_usec));
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] = dist_normal(rnd_engine_);
}
}
template <class T>
inline void Add(const int N, const int M, const T *a, const T *b, T *y) {
#ifdef USE_EIGEN
auto av = create<T>(a, N, M);
auto bv = create<T>(b, N);
auto yv = create<T>(y, N, M);
yv = av.colwise() + bv;
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
y[i * M +j] = a[i * M +j] + b[i];
}
}
#endif
}
template <class T>
inline void Add(const int N, const T *a, const T *b, T *y) {
#ifdef USE_EIGEN
auto av = create<T>(a, N);
auto bv = create<T>(b, N);
auto yv = create<T>(y, N);
yv = (av + bv);
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = a[i] + b[i];
}
#endif
}
template <class T>
inline void Sub(const int N, const T *a, const T *b, T *y) {
#ifdef USE_EIGEN
auto av = create<T>(a, N);
auto bv = create<T>(b, N);
auto yv = create<T>(y, N);
yv = av - bv;
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = a[i] - b[i];
}
#endif
}
template <class T>
inline void Mul(const int N, const T *a, const T *b, T *y) {
#ifdef USE_EIGEN
auto av = create<T>(a, N);
auto bv = create<T>(b, N);
auto yv = create<T>(y, N);
yv = av.array() * bv.array();
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = a[i] * b[i];
}
#endif
}
template <class T>
inline void Div(const int N, const T *a, const T *b, T *y) {
#ifdef USE_EIGEN
auto av = create<T>(a, N);
auto bv = create<T>(b, N);
auto yv = create<T>(y, N);
yv = av.array() / bv.array();
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = a[i] / b[i];
}
#endif
}
template <class T>
inline void Reciprocal(const int N, T *x) {
#ifdef USE_EIGEN
auto xv = create<T>(x, N);
xv /= T(1.0);
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
x[i] = T(1.0) / x[i];
}
#endif
}
template <class T>
inline void Negative(const int N, T *x) {
#ifdef USE_EIGEN
auto xv = create<T>(x, N);
xv = (T(0) - xv);
#else
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
x[i] = -x[i];
}
#endif
}
/// tanh
/// \tparam T
/// \param N
/// \param x
/// \param y
template <class T>
inline void Tanh(const int N, const T *x, T *y) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = (exp(x[i])-exp(-x[i]))/(exp(x[i]) + exp(-x[i]));
}
}
/// tanh gradient
/// \tparam T
/// \param N
/// \param x
/// \param y
/// \param z
template <class T>
inline void TanhGrad(const int N, const T *x, const T *y, T *z) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
z[i] = y[i] * (T(1) - x[i]*x[i]);
}
}
/// sigmoid
/// \tparam T
/// \param N
/// \param x
/// \param y
template <class T>
inline void Sigmoid(const int N, const T*x, T *y) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = T(1)/(T(1) + exp(T(-1) * x[i]));
}
}
/// sigmoid gradient
/// \tparam T
/// \param N
/// \param x
/// \param y
/// \param z
template <class T>
inline void SigmoidGrad(const int N, const T *x, const T *y, T *z) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
z[i] = y[i]*x[i]*((T)1-x[i]);
}
}
/// relu
/// \tparam T
/// \param N
/// \param x
/// \param y
template <class T>
inline void Relu(const int N, const T *x, T *y) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
y[i] = (x[i] > T(0) ? x[i] : T(0));
}
}
/// relu gradient
/// \tparam T
/// \param N
/// \param dx
/// \param x
/// \param dy
template <class T>
inline void ReluGrad(const int N, const T *x, const T *dx, T* dy) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i < N; ++i) {
dy[i] = (x[i] > (T)0 ? dx[i] : 0);
}
}
/// softmax
/// \tparam T
/// \param N
/// \param x
/// \param y
template <class T>
inline void Softmax(const int N, const T* x, T* y) {
const T max = *std::max_element(x, x + N);
T sum = (T)0;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i<N; ++i) {
y[i] = std::exp(x[i] - max);
sum += y[i];
}
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i=0; i<N; ++i) {
y[i] /= sum;
}
}
template <class T>
inline void SoftmaxGrad(const int N, const int D, const T* x, const T* pre, T* y) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
T sum = T(0);
for (int j = 0; j < D; ++j) {
sum += x[i * D + j] * pre[i * D + j];
}
for (int k = 0; k < D; ++k) {
y[i * D + k] = x[i * D + k] * (pre[i * D + k] - sum);
}
}
}
/// cross-entropy
/// \tparam T
/// \param N prediction data length
/// \param in1 prediction value
/// \param M real data length
/// \param in2 real value
/// \param out
template <class T>
inline void CrossEntropy(const int N, const T *in1, const int M, const T *in2, T *out) {
int class_num = N / M;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
int label = (int)in2[i];
int index = i * class_num + label;
out[0] += T(-1) * log(in1[index]);
}
out[0] /= M;
}
/// cross-entropy gradient
/// \tparam T
/// \param N prediction data length
/// \param in1 prediction value
/// \param M real data length
/// \param in2 real value
/// \param out
template <class T>
inline void CrossEntropyGrad(const int N, const T *in1, const int M, const T *in2, T *out) {
int class_num = N / M;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
int label = (int)in2[i];
int index = i * class_num + label;
out[index] = T(-1.0) / in1[index];
}
}
/// rms loss
/// \tparam T
/// \param N prediction data length
/// \param in1 prediction value
/// \param M label data length
/// \param in2 label value
/// \param out
template <class T>
inline void RMSLoss(const int N, const T *in1, const int M, const T *in2, T *out) {
if (N == M) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[0] += T(0.5) * (in1[i] - in2[i]) * (in1[i] - in2[i]);
}
} else {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N / M; ++j) {
int idx = static_cast<int>(in2[i]);
if (j == idx) {
out[0] += T(0.5) * (in1[i] - 1) * (in1[i] - 1);
} else {
out[0] += T(0.5) * in1[i] * in1[i];
}
}
}
}
out[0] /= M;
}
/// rms loss grad
/// \tparam T
/// \param N prediction data length
/// \param in1 prediction value
/// \param M label data length
/// \param in2 label value
/// \param out
template <class T>
inline void RMSLossGrad(const int N, const T *in1, const int M, const T *in2, T *out) {
if (N == M) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
out[i] = (in1[i] - in2[i]);
}
} else {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N / M; ++j) {
int idx = static_cast<int>(in2[i]);
if (j == idx) {
out[i * M + j] = (in1[i * M + j] - 1);
} else {
out[i * M + j] = in1[i * M + j];
}
}
}
}
}
template <class T>
inline void SoftmaxCrossEntropy(const int N, const T *data, const int M, const T *label, T *out) {
int class_num = N/M;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
T sum = T(0.0);
for (int j = 0; j < class_num; ++j) {
sum += exp(data[i * class_num +j]);
}
out[0] += log(sum) - data[static_cast<int>(label[i])];
}
out[0] /= M;
}
template <class T>
inline void SoftmaxCrossEntropyGrad(const int N, const T *data, const int M, const T *label, T *out) {
int class_num = N / M;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
const T *d = data + i * class_num;
T *o = out + i * class_num;
Softmax<T>(class_num, d, o);
o[static_cast<int>(label[i])] -= 1;
}
}
template <class T>
inline void Reduce(const int N, std::function<void(int)> func) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < N; ++i) {
func(i);
}
}
template <class T>
inline void SumCopy(const int N, const T *in, const int M, T *out) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N / M; ++j) {
out[i] += in[i * N / M + j];
}
}
}
template <class T, int order>
inline void Img2Col(const T *input, const int channels, const int height, const int width,
const int kernel_h, const int kernel_w, const int dilation_h,
const int dilation_w, const int pad_t, const int pad_l,
const int pad_b, const int pad_r, const int stride_h, const int stride_w,
T *output) {
if (order == 0) {
const int output_h = (height + pad_b + pad_t - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
const int output_w = (width + pad_l + pad_r - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;
// padding = 0; dilation = 1;
if (dilation_h == 1 && dilation_w == 1 && pad_l == 0 && pad_r == 0 &&
pad_t == 0 && pad_b == 0) {
for (auto k = 0; k < channels * kernel_h * kernel_w; k++) {
const auto nip = k / (kernel_h * kernel_w);
const auto rest = k % (kernel_h * kernel_w);
const auto kh = rest / kernel_w;
const auto kw = rest % kernel_w;
auto* dst = output + nip * (kernel_h * kernel_w * output_h * output_w) +
kh * (kernel_w * output_h * output_w) + kw * (output_h * output_w);
const auto* src = input + nip * (height * width);
for (auto y = 0; y < output_h; y++) {
const auto iy = y * stride_h + kh;
const auto ix = kw;
if (stride_w == 1) {
memcpy(
dst + (y * output_w),
src + (iy * width + ix),
sizeof(T) * output_w);
} else {
for (auto x = 0; x < output_w; x++) {
memcpy(
dst + (y * output_w + x),
src + (iy * width + ix + x * stride_w),
sizeof(T));
}
}
}
}
return;
}
// equal padding
if (pad_l == pad_r && pad_t == pad_b) {
const int pad_h = pad_t;
const int pad_w = pad_l;
const int channel_size = height * width;
for (int channel = channels; channel--; input += channel_size) {
for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) {
for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) {
int input_row = -pad_h + kernel_row * dilation_h;
for (int output_rows = output_h; output_rows; output_rows--) {
if (!isLess(input_row, height)) {
for (int output_cols = output_w; output_cols; output_cols--) {
*(output++) = 0;
}
} else {
int input_col = -pad_w + kernel_col * dilation_w;
for (int output_col = output_w; output_col; output_col--) {
if (isLess(input_col, width)) {
*(output++) = input[input_row * width + input_col];
} else {
*(output++) = 0;
}
input_col += stride_w;
}
}
input_row += stride_h;
}
}
}
}
return;
}
// base
const int dkernel_h = dilation_h * (kernel_h - 1) + 1;
const int dkernel_w = dilation_w * (kernel_w - 1) + 1;
int height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;
int width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;
int channels_col = channels * kernel_h * kernel_w;
for (int c = 0; c < channels_col; ++c) {
int w_offset = c % kernel_w;
int h_offset = (c / kernel_w) % kernel_h;
int c_im = c / kernel_h / kernel_w;
for (int h = 0; h < height_col; ++h) {
for (int w = 0; w < width_col; ++w) {
int h_pad = h * stride_h - pad_t + h_offset * dilation_h;
int w_pad = w * stride_w - pad_l + w_offset * dilation_w;
if (h_pad >= 0 && h_pad < height && w_pad >= 0 && w_pad < width) {
output[(c * height_col + h) * width_col + w] = input[(c_im * height + h_pad) * width + w_pad];
} else {
output[(c * height_col + h) * width_col + w] = 0;
}
}
}
}
} else if (order == 1) {
const int dkernel_h = dilation_h * (kernel_h - 1) + 1;
const int dkernel_w = dilation_w * (kernel_w - 1) + 1;
int height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;
int width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;
int h_pad = -pad_t;
for (int h = 0; h < height_col; ++h) {
int w_pad = -pad_l;
for (int w = 0; w < width_col; ++w) {
for (int ih = h_pad; ih < h_pad + dkernel_h; ih += dilation_h) {
for (int iw = w_pad; iw < w_pad + dkernel_w; iw += dilation_w) {
if (ih >= 0 && ih < height && iw >= 0 && iw < width) {
memcpy(output, input + (ih * width + iw) * channels, sizeof(T) * channels);
} else {
memset(output, 0, sizeof(T) * channels);
}
output += channels;
}
}
w_pad += stride_w;
}
h_pad += stride_h;
}
} else {
Logger::Global()->Fatal("Img2Col do not support other image order except NCHW or NHWC \n");
}
};
template <class T, int order>
inline void Col2Img(const T *input, const int channels, const int height, const int width,
const int kernel_h, const int kernel_w, const int dilation_h,
const int dilation_w, const int pad_t, const int pad_l,
const int pad_b, const int pad_r, const int stride_h, const int stride_w,
T *output) {
memset(output, 0, height * width * channels* sizeof(T));
if (order == 0) {
const int output_h = (height + pad_b + pad_t - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
const int output_w = (width + pad_l + pad_r - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;
if (dilation_h == 1 && dilation_w == 1 && pad_l == 0 && pad_r == 0 &&
pad_t == 0 && pad_b == 0) {
for (auto k = 0; k < channels * kernel_h * kernel_w; k++) {
const auto nip = k / (kernel_h * kernel_w);
const auto rest = k % (kernel_h * kernel_w);
const auto kh = rest / kernel_w;
const auto kw = rest % kernel_w;
const auto* dst = input + nip * (kernel_h * kernel_w * output_h * output_w) +
kh * (kernel_w * output_h * output_w) + kw * (output_h * output_w);
auto* src = output + nip * (height * width);
for (auto y = 0; y < output_h; y++) {
const auto iy = y * stride_h + kh;
const auto ix = kw;
if (stride_w == 1) {
auto offsrc = src + (iy * width + ix);
const auto offdst = dst + (y * output_w);
for (auto i = 0; i < output_w; ++i) {
offsrc[i] += offdst[i];
}
} else {
for (auto x = 0; x < output_w; x++) {
auto offsrc = src + (iy * width + ix + x * stride_w);
const auto offdst = dst + (y * output_w + x);
*offsrc += *offdst;
}
}
}
}
return;
}
if (pad_l == pad_r && pad_t == pad_b) {
// From Intel, https://github.com/BVLC/caffe/pull/3536
const int pad_h = pad_t;
const int pad_w = pad_l;
const int channel_size = height * width;
for (int channel = channels; channel--; output += channel_size) {
for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) {
for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) {
int input_row = -pad_h + kernel_row * dilation_h;
for (int output_rows = output_h; output_rows; output_rows--) {
if (!isLess(input_row, height)) {
input += output_w;
} else {
int input_col = -pad_w + kernel_col * dilation_w;
for (int output_col = output_w; output_col; output_col--) {
if (isLess(input_col, width)) {
output[input_row * width + input_col] += *input;
}
input++;
input_col += stride_w;
}
}
input_row += stride_h;
}
}
}
}
return;
}
const int dkernel_h = dilation_h * (kernel_h - 1) + 1;
const int dkernel_w = dilation_w * (kernel_w - 1) + 1;
int height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;
int width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;
int channels_col = channels * kernel_h * kernel_w;
for (int c = 0; c < channels_col; ++c) {
int w_offset = c % kernel_w;
int h_offset = (c / kernel_w) % kernel_h;
int c_im = c / kernel_h / kernel_w;
for (int h = 0; h < height_col; ++h) {
for (int w = 0; w < width_col; ++w) {
int h_pad = h * stride_h - pad_t + h_offset * dilation_h;
int w_pad = w * stride_w - pad_l + w_offset * dilation_w;
if (h_pad >= 0 && h_pad < height && w_pad >= 0 && w_pad < width) {
output[(c_im * height + h_pad) * width + w_pad] += input[(c * height_col + h) * width_col + w];
}
}
}
}
} else if (order == 1) {
const int dkernel_h = dilation_h * (kernel_h - 1) + 1;
const int dkernel_w = dilation_w * (kernel_w - 1) + 1;
int height_col = (height + pad_t + pad_b - dkernel_h) / stride_h + 1;
int width_col = (width + pad_l + pad_r - dkernel_w) / stride_w + 1;
int h_pad = -pad_t;
for (int h = 0; h < height_col; ++h) {
int w_pad = -pad_l;
for (int w = 0; w < width_col; ++w) {
for (int ih = h_pad; ih < h_pad + dkernel_h; ih += dilation_h) {
for (int iw = w_pad; iw < w_pad + dkernel_w; iw += dilation_w) {
if (ih >= 0 && ih < height && iw >= 0 && iw < width) {
auto* data_im_patch = output + (ih * width + iw) * channels;
Add<T>(channels, data_im_patch, input, data_im_patch);
}
input += channels;
}
}
w_pad += stride_w;
}
h_pad += stride_h;
}
} else {
Logger::Global()->Fatal("Col2Img do not support other image order except NCHW or NHWC \n");
}
};
template <class T>
inline void Img2ColNd(const T *input, const int *imageShape, const int *dataShape,
const int * kernel, const int *stride, const int * dilation,
const int * padding, const int N, T *output, bool col2img = false) {
int kernel_size = 1;
for (int i = 0; i < N; ++i) {
kernel_size *= kernel[i];
}
const int channels_col = dataShape[0];
std::vector<int> d_offset(N, 0);
std::vector<int> d_iter(N, 0);
for (int c_col = 0; c_col < channels_col; ++c_col) {
int offset = c_col;
for (int d_i = N - 1; d_i >= 0; --d_i) {
if (d_i < N - 1) {
offset /= kernel[d_i + 1];
}
d_offset[d_i] = offset % kernel[d_i];
}
for (bool incremented = true; incremented;) {
int index_col = c_col;
int index_im = c_col / kernel_size;
bool is_padding = false;
for (int d_i = 0; d_i < N; ++d_i) {
const int d = d_iter[d_i];
const int d_im = d * stride[d_i] - padding[d_i] + d_offset[d_i] * dilation[d_i];
is_padding |= d_im < 0 || d_im >= imageShape[d_i + 1];
index_col *= dataShape[d_i + 1];
index_col += d;
index_im *= imageShape[d_i + 1];
index_im += d_im;
}
if (!col2img) {
if (is_padding) {
output[index_col] = 0;
} else {
output[index_col] = input[index_im];
}
} else if (!is_padding) { // col2im
output[index_im] += input[index_col];
}
incremented = false;
for (int d_i = N - 1; d_i >= 0; --d_i) {
const int d_max = dataShape[d_i + 1];
if (d_iter[d_i] < d_max) {
Logger::Global()->Fatal("Img2ColNd d_iter[%d] less then d_max\n", d_i);
}
if (d_iter[d_i] == d_max - 1) {
d_iter[d_i] = 0;
} else { // d_iter[d_i] < d_max - 1
++d_iter[d_i];
incremented = true;
break;
}
}
}
}
};
template <class T>
inline void Col2ImgNd(const T *input, const int *imageShape, const int *dataShape,
const int * kernel, const int *stride, const int * dilation,
const int * padding, const int N, T *output) {
int imageSize = 1;
for (int i = 0; i < N; ++i) {
imageSize *= imageShape[i];
}
memset(output, 0, sizeof(T) * imageSize);
Img2ColNd(input, imageShape, dataShape, kernel, stride, dilation, padding, N, output, true);
}
template<class T>
inline void img2col(const T *input, const int input_channels, const int input_width, const int input_height,
const int stride_width, const int stride_height, const int padding_width,
const int padding_height, const int filter_width, const int filter_height,
const int dilation_width, const int dilation_height, T *output) {
const int output_width =
(input_width + 2 * padding_width - (dilation_width * (filter_width - 1) + 1)) / stride_width + 1;
const int output_height =
(input_height + 2 * padding_height - (dilation_height * (filter_height - 1) + 1)) / stride_height + 1;
const int col_channels = input_channels * filter_width * filter_height;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int c = 0; c < col_channels; ++c) {
int w_offset = c % filter_width;
int h_offset = (c / filter_width) % filter_height;
int c_im = c / filter_width / filter_height;
for (int h = 0; h < output_height; ++h) {
for (int w = 0; w < output_width; ++w) {
int imRowIdx = h * stride_height + h_offset * dilation_height;
int imColIdx = w * stride_width + w_offset * dilation_width;
if ((imRowIdx - padding_height) < 0 ||
(imRowIdx - padding_height) >= input_height ||
(imColIdx - padding_width) < 0 ||
(imColIdx - padding_width) >= input_width) {
output[(c * output_height + h) * output_width + w] = T(0);
} else {
imRowIdx += c_im * input_height - padding_height;
imColIdx -= padding_width;
output[(c * output_height + h) * output_width + w] =
input[imRowIdx * input_width + imColIdx];
}
}
}
}
}
template<class T>
inline void col2img(T *input, const int input_channels, const int input_width, const int input_height,
const int stride_width, const int stride_height, const int padding_width,
const int padding_height, const int filter_width, const int filter_height,
const int dilation_width, const int dilation_height, const T *output) {
const int output_width =
(input_width + 2 * padding_width - (dilation_width * (filter_width - 1) + 1)) / stride_width + 1;
const int output_height =
(input_height + 2 * padding_height - (dilation_height * (filter_height - 1) + 1)) / stride_height + 1;
const int col_channels = input_channels * filter_width * filter_height;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int c = 0; c < col_channels; ++c) {
int w_offset = c % filter_width;
int h_offset = (c / filter_width) % filter_height;
int c_im = c / filter_width / filter_height;
for (int h = 0; h < output_height; ++h) {
for (int w = 0; w < output_width; ++w) {
int imRowIdx = h * stride_height + h_offset * dilation_height;
int imColIdx = w * stride_width + w_offset * dilation_width;
imRowIdx -= padding_height;
imColIdx -= padding_width;
if (imRowIdx >= 0 && imRowIdx < input_height &&
imColIdx >= 0 && imColIdx < input_width) {
int input_idx = (imRowIdx + c_im * input_height) * input_width + imColIdx;
int output_idx = (c * output_height + h) * output_width + w;
input[input_idx] += output[output_idx];
}
}
}
}
}
template<class T>
inline void NaiveConv(const T *input, const int batch_size, const int input_channels,
const int input_width, const int input_height,
const int stride_width, const int stride_height,
const int padding_width, const int padding_height,
const int filter_width, const int filter_height,
const int dilation_width, const int dilation_height,
const int output_channels, const T *filter, T *output) {
const int output_width =
(input_width + 2 * padding_width - (dilation_width * (filter_width - 1) + 1)) / stride_width + 1;
const int output_height =
(input_height + 2 * padding_height - (dilation_height * (filter_height - 1) + 1)) / stride_height + 1;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int batch = 0; batch < batch_size; ++batch) {
for (int out_channel = 0; out_channel <output_channels ; ++out_channel) {
for (int out_h = 0; out_h < output_height; ++out_h) {
for (int out_w = 0; out_w < output_width; ++out_w) {
const int inStartH = (out_h * stride_height) - padding_height;
const int inStartW = (out_w * stride_width) - padding_width;
T outValue = (T)0;
for (int in_channel = 0; in_channel < input_channels; ++in_channel) {
for (int filter_h = 0; filter_h < filter_height; ++filter_h) {
for (int filter_w = 0; filter_w < filter_width; ++filter_w) {
T inValue;
const int inH = inStartH + filter_h;
const int inW = inStartW + filter_w;
if ((inH >= 0 && inH < input_height) &&
(inW >= 0 && inW < input_width)) {
int offsetInput = batch * input_channels * input_height * input_width +
in_channel * input_height * input_width + inH * input_width + inW;
inValue = input[offsetInput];
} else {
inValue = (T)0;
}
int offsetFilter = out_channel * input_channels * filter_height * filter_width +
in_channel * filter_height * filter_width + filter_h * filter_width + filter_w;
T filterValue = filter[offsetFilter];
outValue += (inValue * filterValue);
}
}
}
int offset = batch * output_channels * output_height * output_width +
out_channel * output_height * output_width + out_h * output_width + out_w;
output[offset] = outValue;
}
}
}
}
}
template <class T>
inline void pooling2D(const T *input, const int batch_size, const int channel,
const int input_width, const int input_height,
const int output_width, const int output_height,
const int stride_width, const int stride_height,
const int padding_width, const int padding_height,
const int filter_width, const int filter_height,
const int dilation_width, const int dilation_height,
T *output, int type = 0, T *mask = nullptr) {
const int input_stride = input_height * input_width;
const int output_stride = output_height * output_width;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < batch_size; ++i) {
for (int c = 0; c < channel; ++c) {
for (int ph = 0; ph < output_height; ++ph) {
int hstart = ph * stride_height - padding_height;
int hend = std::min(hstart + filter_height, input_height);
hstart = std::max(hstart, 0);
for (int pw = 0; pw < output_width; ++pw) {
int wstart = pw * stride_width - padding_width;
int wend = std::min(wstart + filter_width, input_width);
wstart = std::max(wstart, 0);
T ele;
if (type == 0) {
ele = input[hstart * input_width + wstart];
int index = hstart * input_width + wstart;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
if (ele < input[h * input_width + w]) {
ele = input[h * input_width + w];
index = h * input_width + w;
}
}
}
output[ph * output_width + pw] = ele;
if (mask != nullptr) {
mask[ph * output_width + pw] = T(index);
}
} else if (type == 1) {
ele = T(0);
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
ele += input[h * input_width + w];
}
}
output[ph * output_width + pw] = ele / (hend * wend);
} else {
Logger::Global()->Fatal("not Implementation Pooling2D with other PoolType");
}
}
}
input += input_stride;
output += output_stride;
if (mask != nullptr) {
mask += output_stride;
}
}
}
}
template <class T>
inline void NHWC2NCHW(const T * input,
const int num,
const int inH,
const int inW,
const int inC,
T *output) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int n = 0; n < num; ++n) {
for (int h = 0; h < inH; ++h) {
for (int w = 0; w < inW; ++w) {
for (int c = 0; c < inC; ++c) {
output[((n * inC + c) * inH + h) * inW + w] = *(input++);
}
}
}
}
}
template <class T>
inline void NCHW2NHWC(const T * input,
const int num,
const int inC,
const int inH,
const int inW,
T *output) {
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int n = 0; n < num; ++n) {
for (int c = 0; c < inC; ++c) {
for (int h = 0; h < inH; ++h) {
for (int w = 0; w < inW; ++w) {
output[((n * inH + h) * inW + w) * inC + c] = *(input++);
}
}
}
}
}
template <class I, class R>
inline std::vector<R> Map(std::function<R(I)> fun, const std::vector<I>& vec) {
std::vector<R> res;
res.reserve(vec.size());
#ifdef USE_MP
#pragma omp parallel for
#endif
for (auto& i : vec) {
res.push_back(fun(i));
}
return res;
};
template <typename R, typename I>
inline std::vector<R> Map(std::function<R(I)> fun, std::vector<I>&& vec) {
return Map<R, I>(fun, vec);
}
template <typename I>
inline I Reduce(std::function<I(const I&, const I&)> func, I initVal, const std::vector<I>& vec) {
I res = initVal;
#ifdef USE_MP
#pragma omp parallel for
#endif
for (int i = 0; i < vec.size(); ++i) {
res = func(res, vec.at(i));
}
return res;
}
template <typename I>
inline I Reduce(std::function<I(const I&, const I&)> func, const std::vector<I>& vec) {
const std::vector<I> v(vec.begin() + 1, vec.end());
return Reduce(func, vec.at(0), v);
}
template <typename I>
inline I Reduce(std::function<I(I&&, I&&)> func, I&& initVal, std::vector<I>&& vec) {
#ifdef USE_MP
#pragma omp parallel for
#endif
I res = std::move(initVal);
for (int i = 0; i < vec.size(); ++i) {
res = func(std::move(res), std::move(vec.at(i)));
}
return res;
}
template <typename I>
I Reduce(std::function<I(I&&, I&&)> func, std::vector<I>&& vec) {
#ifdef USE_MP
#pragma omp parallel for
#endif
I res = std::move(vec.at(0));
for (int i = 1; i < vec.size(); ++i) {
res = func(std::move(res), std::move(vec.at(i)));
}
return res;
}
template <typename R, typename I>
inline R MapReduce(std::function<R(R, I, bool)> func, const std::vector<I>& vec) {
#ifdef USE_MP
#pragma omp parallel for
#endif
R res = func(R(), vec.at(0), true);
for (int i = 1; i < vec.size(); ++i) {
res = func(res, vec.at(i), false);
}
return res;
}
template< class T>
inline std::vector<T> Filter(std::function<bool(const T)> func, const std::vector<T> &input) {
std::vector<T> res;
res.reserve(input.size());
for (const auto &i : input) {
if (func(i)) {
res.push_back(i);
}
}
res.shrink_to_fit();
return res;
}
}
#endif //MATRIX_MATH_H
| {
"alphanum_fraction": 0.4576117752,
"avg_line_length": 32.9199779249,
"ext": "h",
"hexsha": "a82f38e2783791b0edde923794933b65b627af2a",
"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": "7b2e07a46f8d0477243d49c76db575280096e247",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Jarlene/Matrix",
"max_forks_repo_path": "matrix/include/utils/Math.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7b2e07a46f8d0477243d49c76db575280096e247",
"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": "Jarlene/Matrix",
"max_issues_repo_path": "matrix/include/utils/Math.h",
"max_line_length": 131,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "7b2e07a46f8d0477243d49c76db575280096e247",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Jarlene/Matrix",
"max_stars_repo_path": "matrix/include/utils/Math.h",
"max_stars_repo_stars_event_max_datetime": "2018-07-08T08:48:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-22T05:20:57.000Z",
"num_tokens": 15298,
"size": 59651
} |
#ifndef __CNN_ACTIV_H__
#define __CNN_ACTIV_H__
#include <cblas.h>
#include "cnn.h"
#include "cnn_builtin_math.h"
#include "cnn_macro.h"
#include "cnn_types.h"
#ifdef CNN_WITH_CUDA
#include <cublas_v2.h>
#include <cuda_runtime.h>
#include "cnn_builtin_math_cu.h"
#include "cnn_init.h"
#endif
static inline void cnn_forward_activ(union CNN_LAYER* layerRef,
struct CNN_CONFIG* cfgRef, int layerIndex)
{
// Cache
struct CNN_LAYER_ACTIV* layerPtr = &layerRef[layerIndex].activ;
struct CNN_MAT* outData = &layerPtr->outMat.data;
struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;
cnn_activ_t id = cfgRef->layerCfg[layerIndex].activ.id;
if (id > 0)
{
cnn_activ_list[id](outData->mat, preOutData->mat,
outData->rows * outData->cols, layerPtr->buf.mat);
}
else
{
#ifdef CNN_WITH_CUDA
float alpha = 1.0;
float beta = 0.0;
cnn_assert_cudnn(cudnnSoftmaxForward( //
cnnInit.cudnnHandle, //
CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_INSTANCE, //
&alpha, //
layerPtr->ten, preOutData->mat, //
&beta, //
layerPtr->ten, outData->mat));
#else
for (int j = 0; j < cfgRef->batch; j++)
{
int srcShift = j * preOutData->cols;
int dstShift = j * outData->cols;
float* srcPtr = preOutData->mat + srcShift;
float* dstPtr = outData->mat + dstShift;
float* bufPtr = layerPtr->buf.mat + dstShift;
cnn_activ_list[id](dstPtr, srcPtr, outData->cols, bufPtr);
}
#endif
}
}
static inline void cnn_backward_activ(union CNN_LAYER* layerRef,
struct CNN_CONFIG* cfgRef, int layerIndex)
{
// Cache
struct CNN_LAYER_ACTIV* layerPtr = &layerRef[layerIndex].activ;
struct CNN_MAT* outData = &layerPtr->outMat.data;
struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;
cnn_activ_t id = cfgRef->layerCfg[layerIndex].activ.id;
// Find layer gradient
if (layerIndex > 1)
{
if (id > 0)
{
cnn_activ_grad_list[id](
preOutData->grad, outData->grad, preOutData->mat,
outData->rows * outData->cols, outData->mat, layerPtr->buf.mat);
}
else
{
#ifdef CNN_WITH_CUDA
float alpha = 1.0;
float beta = 0.0;
cnn_assert_cudnn(cudnnSoftmaxBackward( //
cnnInit.cudnnHandle, //
CUDNN_SOFTMAX_ACCURATE, CUDNN_SOFTMAX_MODE_INSTANCE, //
&alpha, //
layerPtr->ten, outData->mat, //
layerPtr->ten, outData->grad, //
&beta, //
layerPtr->ten, preOutData->grad));
#else
for (int j = 0; j < cfgRef->batch; j++)
{
int shift = j * outData->cols;
// Gradient calculation
cnn_activ_grad_list[id](
preOutData->grad + shift, outData->grad + shift,
preOutData->mat + shift, outData->cols,
outData->mat + shift, layerPtr->buf.mat);
}
#endif
}
}
}
#endif
| {
"alphanum_fraction": 0.5038293217,
"avg_line_length": 31.5172413793,
"ext": "h",
"hexsha": "d701eb515bef0614367b5809f419fdfce1686932",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jamesljlster/cnn",
"max_forks_repo_path": "src/cnn_activ.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jamesljlster/cnn",
"max_issues_repo_path": "src/cnn_activ.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jamesljlster/cnn",
"max_stars_repo_path": "src/cnn_activ.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z",
"num_tokens": 864,
"size": 3656
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <mcbp/protocol/dcp_stream_end_status.h>
#include <mcbp/protocol/status.h>
#include <memcached/dcp_stream_id.h>
#include <memcached/engine_error.h>
#include <memcached/types.h>
#include <memcached/vbucket.h>
#include <memcached/visibility.h>
#include <gsl/gsl>
struct DocKey;
namespace cb::durability {
class Requirements;
enum class Level : uint8_t;
} // namespace cb::durability
namespace cb::mcbp {
class Response;
}
namespace mcbp::systemevent {
enum class id : uint32_t;
enum class version : uint8_t;
} // namespace mcbp::systemevent
class DcpConnHandlerIface {
public:
virtual ~DcpConnHandlerIface() = default;
};
/**
* The message producers are used by the engine's DCP producer
* to add messages into the DCP stream. Please look at the full
* DCP documentation to figure out the real meaning for all of the
* messages.
*/
struct DcpMessageProducersIface {
virtual ~DcpMessageProducersIface() = default;
virtual ENGINE_ERROR_CODE get_failover_log(uint32_t opaque,
Vbid vbucket) = 0;
virtual ENGINE_ERROR_CODE stream_req(uint32_t opaque,
Vbid vbucket,
uint32_t flags,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vbucket_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
const std::string& request_value) = 0;
virtual ENGINE_ERROR_CODE add_stream_rsp(uint32_t opaque,
uint32_t stream_opaque,
cb::mcbp::Status status) = 0;
virtual ENGINE_ERROR_CODE marker_rsp(uint32_t opaque,
cb::mcbp::Status status) = 0;
virtual ENGINE_ERROR_CODE set_vbucket_state_rsp(
uint32_t opaque, cb::mcbp::Status status) = 0;
/**
* Send a Stream End message
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param status the reason for the stream end.
* 0 = success
* 1+ = Something happened on the vbucket causing
* us to abort it.
* @param sid The stream-ID the end applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
* ENGINE_EWOULDBLOCK if no data is available
* ENGINE_* for errors
*/
virtual ENGINE_ERROR_CODE stream_end(uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a marker
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param start_seqno start of the snapshot range
* @param end_seqno end of the snapshot range
* @param flags snapshot marker flags (DISK/MEMORY/CHK/ACK).
* @param highCompletedSeqno the SyncRepl high completed seqno
* @param maxVisibleSeqno highest committed seqno (ignores prepare/abort)
* @param timestamp for the data in the snapshot marker (only valid for
* disk type and represents the disk commit time)
* @param sid The stream-ID the marker applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE marker(uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags,
std::optional<uint64_t> highCompletedSeqno,
std::optional<uint64_t> maxVisibleSeqno,
std::optional<uint64_t> timestamp,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a Mutation
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param vbucket the vbucket id the message belong to
* @param by_seqno
* @param rev_seqno
* @param lock_time
* @param nru the nru field used by ep-engine (may safely be ignored)
* @param sid The stream-ID the mutation applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE mutation(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
uint8_t nru,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a deletion
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param by_seqno
* @param rev_seqno
* @param sid The stream-ID the deletion applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE deletion(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a deletion with delete_time or collections (or both)
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param vbucket the vbucket id the message belong to
* @param by_seqno
* @param rev_seqno
* @param delete_time the time of the deletion (tombstone creation time)
* @param sid The stream-ID the deletion applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE deletion_v2(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send an expiration
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param itm the item to send.
* @param by_seqno
* @param rev_seqno
* @param delete_time the time of the deletion (tombstone creation time)
* @param sid The stream-ID the expiration applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE expiration(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Send a state transition for a vbucket
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param state the new state
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE set_vbucket_state(uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) = 0;
/**
* Send a noop
*
* @param opaque what to use as the opaque in the buffer
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE noop(uint32_t opaque) = 0;
/**
* Send a buffer acknowledgment
*
* @param opaque this is the opaque requested by the consumer
* in the Stream Request message
* @param vbucket the vbucket id the message belong to
* @param buffer_bytes the amount of bytes processed
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE buffer_acknowledgement(uint32_t opaque,
Vbid vbucket,
uint32_t buffer_bytes) = 0;
/**
* Send a control message to the other end
*
* @param opaque what to use as the opaque in the buffer
* @param key the identifier for the property to set
* @param value The value for the property (the layout of the
* value is defined for the key)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE control(uint32_t opaque,
std::string_view key,
std::string_view value) = 0;
/**
* Send a system event message to the other end
*
* @param cookie passed on the cookie provided by step
* @param opaque what to use as the opaque in the buffer
* @param vbucket the vbucket the event applies to
* @param bySeqno the sequence number of the event
* @param version A version value defining the eventData format
* @param key the system event's key data
* @param eventData the system event's specific data
* @param sid The stream-ID the event applies to (can be 0 for none)
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE system_event(uint32_t opaque,
Vbid vbucket,
mcbp::systemevent::id event,
uint64_t bySeqno,
mcbp::systemevent::version version,
cb::const_byte_buffer key,
cb::const_byte_buffer eventData,
cb::mcbp::DcpStreamId sid) = 0;
/*
* Send a GetErrorMap message to the other end
*
* @param opaque The opaque to send over
* @param version The version of the error map
*
* @return ENGINE_SUCCESS upon success
*/
virtual ENGINE_ERROR_CODE get_error_map(uint32_t opaque,
uint16_t version) = 0;
/**
* See mutation for a description of the parameters except for:
*
* @param deleted Are we storing a deletion operation?
* @param durability the durability specification for this item
*/
virtual ENGINE_ERROR_CODE prepare(uint32_t opaque,
cb::unique_item_ptr itm,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t lock_time,
uint8_t nru,
DocumentState document_state,
cb::durability::Level level) = 0;
/**
* Send a seqno ack message
*
* It serves to inform KV-Engine active nodes that the replica has
* successfully received and prepared to memory/disk all DCP_PREPARE
* messages up to the specified seqno.
*
* @param opaque identifying stream
* @param vbucket the vbucket the seqno ack is for
* @param prepared_seqno The seqno the replica has prepared up to.
*/
virtual ENGINE_ERROR_CODE seqno_acknowledged(uint32_t opaque,
Vbid vbucket,
uint64_t prepared_seqno) = 0;
/**
* Send a commit message:
*
* This is sent from the DCP Producer to the DCP Consumer.
* It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
* KV-Engine replicas of a committed Sync Write
*
* @param opaque
* @param vbucket the vbucket the event applies to
* @param key The key of the committed mutation.
* @param prepare_seqno The seqno of the prepare that we are committing.
* @param commit_seqno The sequence number to commit this mutation at.
* @return
*/
virtual ENGINE_ERROR_CODE commit(uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepare_seqno,
uint64_t commit_seqno) = 0;
/**
* Send an abort message:
*
* This is sent from the DCP Producer to the DCP Consumer.
*/
virtual ENGINE_ERROR_CODE abort(uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t abort_seqno) = 0;
/**
* Send an OSO snapshot marker to from server to client
*/
virtual ENGINE_ERROR_CODE oso_snapshot(uint32_t opaque,
Vbid vbucket,
uint32_t flags,
cb::mcbp::DcpStreamId sid) = 0;
virtual ENGINE_ERROR_CODE seqno_advanced(uint32_t opaque,
Vbid vbucket,
uint64_t seqno,
cb::mcbp::DcpStreamId sid) = 0;
};
using dcp_add_failover_log = std::function<ENGINE_ERROR_CODE(
const std::vector<vbucket_failover_t>&)>;
struct MEMCACHED_PUBLIC_CLASS DcpIface {
/**
* Called from the memcached core for a DCP connection to allow it to
* inject new messages on the stream.
*
* @param cookie a unique handle the engine should pass on to the
* message producers
* @param producers functions the client may use to add messages to
* the DCP stream
*
* @return The appropriate error code returned from the message
* producerif it failed, or:
* ENGINE_SUCCESS if the engine don't have more messages
* to send at this moment
*/
virtual ENGINE_ERROR_CODE step(gsl::not_null<const void*> cookie,
DcpMessageProducersIface& producers) = 0;
/**
* Called from the memcached core to open a new DCP connection.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param seqno Unused
* @param flags bitfield of flags to specify what to open. See DCP_OPEN_XXX
* @param name Identifier for this connection. Note that the name must be
* unique; attempting to (re)connect with a name already in use
* will disconnect the existing connection.
* @param value An optional JSON value specifying extra information about
* the connection to be opened.
* @return ENGINE_SUCCESS if the DCP connection was successfully opened,
* otherwise error code indicating reason for the failure.
*/
virtual ENGINE_ERROR_CODE open(gsl::not_null<const void*> cookie,
uint32_t opaque,
uint32_t seqno,
uint32_t flags,
std::string_view name,
std::string_view value = {}) = 0;
/**
* Called from the memcached core to add a vBucket stream to the set of
* connected streams.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param vbucket The vBucket to stream.
* @param flags bitfield of flags to specify what to open. See
* DCP_ADD_STREAM_FLAG_XXX
* @return ENGINE_SUCCESS if the DCP stream was successfully opened,
* otherwise error code indicating reason for the failure.
*/
virtual ENGINE_ERROR_CODE add_stream(gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
uint32_t flags) = 0;
/**
* Called from the memcached core to close a vBucket stream to the set of
* connected streams.
*
* @param cookie a unique handle the engine should pass on to the
* message producers (typically representing the memcached
* connection).
* @param opaque what to use as the opaque for this DCP connection.
* @param vbucket The vBucket to close.
* @param sid The id of the stream to close (can be 0/none)
* @return
*/
virtual ENGINE_ERROR_CODE close_stream(gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamId sid) = 0;
/**
* Callback to the engine that a Stream Request message was received
*/
virtual ENGINE_ERROR_CODE stream_req(
gsl::not_null<const void*> cookie,
uint32_t flags,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vbucket_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
uint64_t* rollback_seqno,
dcp_add_failover_log callback,
std::optional<std::string_view> json) = 0;
/**
* Callback to the engine that a get failover log message was received
*/
virtual ENGINE_ERROR_CODE get_failover_log(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
dcp_add_failover_log callback) = 0;
/**
* Callback to the engine that a stream end message was received
*/
virtual ENGINE_ERROR_CODE stream_end(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status) = 0;
/**
* Callback to the engine that a snapshot marker message was received
*/
virtual ENGINE_ERROR_CODE snapshot_marker(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags,
std::optional<uint64_t> high_completed_seqno,
std::optional<uint64_t> max_visible_seqno) = 0;
/**
* Callback to the engine that a mutation message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param flags The user specified flags
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param expiration When the document expire
* @param lock_time The lock time for the document
* @param meta The documents meta
* @param nru The engine's NRU value
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE mutation(gsl::not_null<const void*> cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
cb::const_byte_buffer meta,
uint8_t nru) = 0;
/**
* Callback to the engine that a deletion message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param meta The documents meta
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE deletion(gsl::not_null<const void*> cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
cb::const_byte_buffer meta) = 0;
/**
* Callback to the engine that a deletion_v2 message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param delete_time The time of the delete
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE deletion_v2(gsl::not_null<const void*> cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time) {
return ENGINE_ENOTSUP;
}
/**
* Callback to the engine that an expiration message was received
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The documents key
* @param value The value to store
* @param priv_bytes The number of bytes in the value which should be
* allocated from the privileged pool
* @param datatype The datatype for the incomming item
* @param cas The documents CAS value
* @param vbucket The vbucket identifier for the document
* @param by_seqno The sequence number in the vbucket
* @param rev_seqno The revision number for the item
* @param meta The documents meta
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE expiration(gsl::not_null<const void*> cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t deleteTime) = 0;
/**
* Callback to the engine that a set vbucket state message was received
*/
virtual ENGINE_ERROR_CODE set_vbucket_state(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) = 0;
/**
* Callback to the engine that a NOOP message was received
*/
virtual ENGINE_ERROR_CODE noop(gsl::not_null<const void*> cookie,
uint32_t opaque) = 0;
/**
* Callback to the engine that a buffer_ack message was received
*/
virtual ENGINE_ERROR_CODE buffer_acknowledgement(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
uint32_t buffer_bytes) = 0;
/**
* Callback to the engine that a Control message was received.
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param key The control message name
* @param value The control message value
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE control(gsl::not_null<const void*> cookie,
uint32_t opaque,
std::string_view key,
std::string_view value) = 0;
/**
* Callback to the engine that a response message has been received.
* @param cookie The cookie representing the connection
* @param response The response which the server received.
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE response_handler(
gsl::not_null<const void*> cookie,
const cb::mcbp::Response& response) = 0;
/**
* Callback to the engine that a system event message was received.
*
* @param cookie The cookie representing the connection
* @param opaque The opaque field in the message (identifying the stream)
* @param vbucket The vbucket identifier for this event.
* @param event The type of system event.
* @param bySeqno Sequence number of event.
* @param version The version of system event (defines the eventData format)
* @param key The event name .
* @param eventData The event value.
* @return Standard engine error code.
*/
virtual ENGINE_ERROR_CODE system_event(gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
mcbp::systemevent::id event,
uint64_t bySeqno,
mcbp::systemevent::version version,
cb::const_byte_buffer key,
cb::const_byte_buffer eventData) = 0;
/**
* Called by the core when it receives a DCP PREPARE message over the
* wire.
*
* See mutation for a description of the parameters except for:
*
* @param deleted Are we storing a deletion operation?
* @param durability the durability specification for this item
*/
virtual ENGINE_ERROR_CODE prepare(gsl::not_null<const void*> cookie,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
uint8_t nru,
DocumentState document_state,
cb::durability::Level level) = 0;
/**
* Called by the core when it receives a DCP SEQNO ACK message over the
* wire.
*
* It serves to inform KV-Engine active nodes that the replica has
* successfully received and prepared all DCP_PREPARE messages up to the
* specified seqno.
*
* @param cookie connection to send it over
* @param opaque identifying stream
* @param vbucket The vbucket which is being acknowledged.
* @param prepared_seqno The seqno the replica has prepared up to.
*/
virtual ENGINE_ERROR_CODE seqno_acknowledged(
gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t prepared_seqno) = 0;
/**
* Called by the core when it receives a DCP COMMIT message over the
* wire.
*
* This is sent from the DCP Producer to the DCP Consumer.
* It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
* KV-Engine replicas of a committed Sync Write
*/
virtual ENGINE_ERROR_CODE commit(gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t commit_seqno) = 0;
/**
* Called by the core when it receives a DCP ABORT message over the
* wire.
*
* This is sent from the DCP Producer to the DCP Consumer.
*/
virtual ENGINE_ERROR_CODE abort(gsl::not_null<const void*> cookie,
uint32_t opaque,
Vbid vbucket,
const DocKey& key,
uint64_t prepared_seqno,
uint64_t abort_seqno) = 0;
};
| {
"alphanum_fraction": 0.5338732988,
"avg_line_length": 43.0765239948,
"ext": "h",
"hexsha": "9cc4fe91e506c31b1981ceba4b06b414fb9e7e34",
"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": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rohansuri/kv_engine",
"max_forks_repo_path": "include/memcached/dcp.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"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": "rohansuri/kv_engine",
"max_issues_repo_path": "include/memcached/dcp.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rohansuri/kv_engine",
"max_stars_repo_path": "include/memcached/dcp.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6571,
"size": 33212
} |
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sum.h>
gsl_sum_levin_utrunc_workspace *
gsl_sum_levin_utrunc_alloc (size_t n)
{
gsl_sum_levin_utrunc_workspace * w;
if (n == 0)
{
GSL_ERROR_VAL ("length n must be positive integer", GSL_EDOM, 0);
}
w = (gsl_sum_levin_utrunc_workspace *) malloc(sizeof(gsl_sum_levin_utrunc_workspace));
if (w == NULL)
{
GSL_ERROR_VAL ("failed to allocate struct", GSL_ENOMEM, 0);
}
w->q_num = (double *) malloc (n * sizeof (double));
if (w->q_num == NULL)
{
free(w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for q_num", GSL_ENOMEM, 0);
}
w->q_den = (double *) malloc (n * sizeof (double));
if (w->q_den == NULL)
{
free (w->q_num);
free (w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for q_den", GSL_ENOMEM, 0);
}
w->dsum = (double *) malloc (n * sizeof (double));
if (w->dsum == NULL)
{
free (w->q_den);
free (w->q_num);
free (w) ; /* error in constructor, prevent memory leak */
GSL_ERROR_VAL ("failed to allocate space for dsum", GSL_ENOMEM, 0);
}
w->size = n;
w->terms_used = 0;
w->sum_plain = 0;
return w;
}
void
gsl_sum_levin_utrunc_free (gsl_sum_levin_utrunc_workspace * w)
{
RETURN_IF_NULL (w);
free (w->dsum);
free (w->q_den);
free (w->q_num);
free (w);
}
| {
"alphanum_fraction": 0.618729097,
"avg_line_length": 21.6666666667,
"ext": "c",
"hexsha": "81ddf67fecf0c6650801da7f68e2c9c3b91eae9f",
"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/sum/work_utrunc.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/sum/work_utrunc.c",
"max_line_length": 88,
"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/sum/work_utrunc.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 475,
"size": 1495
} |
/* blas/blas.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001 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.
*/
/* GSL implementation of BLAS operations for vectors and dense
* matrices. Note that GSL native storage is row-major. */
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/blas/gsl_blas_types.h>
#include <gsl/blas/gsl_blas.h>
#include <gsl/blas/cblas.h>
/* ========================================================================
* Level 1
* ========================================================================
*/
/* CBLAS defines vector sizes in terms of int. GSL defines sizes in
terms of size_t, so we need to convert these into integers. There
is the possibility of overflow here. FIXME: Maybe this could be
caught */
#define INT(X) ((int)(X))
int gsl_blas_ddot (const gsl_vector * X, const gsl_vector * Y, double *result){
if (X->size == Y->size){
*result = ddot (&INT (X->size), X->data, &INT (X->stride), Y->data, &INT (Y->stride));
return GSL_SUCCESS;
}
else {
GSL_ERROR ("invalid length", GSL_EBADLEN);
}
}
/**
* DNRM2 returns the euclidean norm of a vector via the function
* name, so that
*
* DNRM2 := sqrt( x'*x )
*/
double gsl_blas_dnrm2 (const gsl_vector * X){
return dnrm2 (&INT (X->size), X->data, &INT (X->stride));
}
/**
* interchanges two vectors.
*/
int gsl_blas_dswap (gsl_vector * X, gsl_vector * Y){
if (X->size == Y->size){
dswap (&INT (X->size), X->data, &INT (X->stride), Y->data, &INT (Y->stride));
return GSL_SUCCESS;
}
else{
GSL_ERROR ("invalid length", GSL_EBADLEN);
};
}
/**
* copies a vector, x, to a vector, y.
*/
int gsl_blas_dcopy (const gsl_vector * X, gsl_vector * Y){
if (X->size == Y->size){
dcopy (&INT (X->size), X->data, &INT (X->stride), Y->data, &INT (Y->stride));
return GSL_SUCCESS;
}
else {
GSL_ERROR ("invalid length", GSL_EBADLEN);
}
}
/* ===========================================================================
* Level 2
* ===========================================================================
*/
int
gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA, double alpha, const gsl_matrix * A,
const gsl_vector * X, double beta, gsl_vector * Y)
{
//here the matrix is by default transposed, so to get the right behaviour we will transpose it when the user didn't want it tranposed, and leave it the way it is when it should be transposed
//note that M and N are changed to show that the matrix is transposed by default.
const size_t M = A->size1;
const size_t N = A->size2;
char aTransp = (TransA == CblasNoTrans) ? 'T' : 'N';
if ((TransA == CblasNoTrans && N == X->size && M == Y->size)
|| (TransA == CblasTrans && M == X->size && N == Y->size))
{
dgemv (&aTransp, &INT (N), &INT (M), &alpha, A->data,
&INT (A->tda), X->data, &INT (X->stride), &beta, Y->data,
&INT (Y->stride));
return GSL_SUCCESS;
}
else
{
GSL_ERROR ("invalid length", GSL_EBADLEN);
}
}
/*
* ===========================================================================
* Prototypes for level 3 BLAS
* ===========================================================================
*/
int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB,
double alpha, const gsl_matrix * A, const gsl_matrix * B,
double beta, gsl_matrix * C)
{
/**
Since BLAS uses column major matrices, when asked to perform C = A*B we will
actually compute C = B*A, with the number of rows and cols switched up.
(C' = B' * A' if C = A * B, and we're working with transposes by default)
That's why we need to switch the order of the matrices as well as the order of M and N.
*/
const size_t M = C->size1;
const size_t N = C->size2;
const size_t MA = (TransA == CblasNoTrans) ? A->size1 : A->size2;
const size_t NA = (TransA == CblasNoTrans) ? A->size2 : A->size1;
const size_t MB = (TransB == CblasNoTrans) ? B->size1 : B->size2;
const size_t NB = (TransB == CblasNoTrans) ? B->size2 : B->size1;
char aTransp = (TransA == CblasNoTrans) ? 'N' : 'T';
char bTransp = (TransB == CblasNoTrans) ? 'N' : 'T';
if (M == MA && N == NB && NA == MB) /* [MxN] = [MAxNA][MBxNB] */
{
dgemm (&bTransp, &aTransp, &INT (N), &INT (M), &INT (NA),
&alpha, B->data, &INT (B->tda), A->data, &INT (A->tda), &beta,
C->data, &INT (C->tda));
return GSL_SUCCESS;
}
else
{
GSL_ERROR ("invalid length", GSL_EBADLEN);
}
}
| {
"alphanum_fraction": 0.5692827638,
"avg_line_length": 31.5147928994,
"ext": "c",
"hexsha": "1d9a57c6233901507687aef73794171978c6eec4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/blas.c",
"max_line_length": 191,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/blas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1504,
"size": 5326
} |
#include <algorithm>
#include <cstdio>
#include <random>
#include <gsl/gsl_multimin.h>
#include "dgp.h"
#include "vec.h"
#include "fobj_sph.h"
typedef struct
{
double tau;
double lambda;
double rho;
dgp_t *G;
} gsl_params_t;
void gsl_fdf(const gsl_vector *x, void *params, double *f, gsl_vector *g)
{
gsl_params_t *p = (gsl_params_t *)params;
*f = fobj_sph(p->lambda, p->tau, *(p->G), x->data, g->data);
}
void gsl_df(const gsl_vector *x, void *params, gsl_vector *g)
{
gsl_params_t *p = (gsl_params_t *)params;
fobj_sph(p->lambda, p->tau, *(p->G), x->data, g->data);
}
double gsl_f(const gsl_vector *x, void *params)
{
gsl_params_t *p = (gsl_params_t *)params;
return fobj_sph(p->lambda, p->tau, *(p->G), x->data, NULL);
}
double init_tau(dgp_t &G)
{
std::vector<double> tau_all(G.m_nedges);
for (int i = 0; i < G.m_nedges; i++)
{
tau_all[i] = (G.m_l[i] + G.m_u[i]) / 2.0;
}
std::sort(tau_all.begin(), tau_all.end());
return tau_all[(int)(0.75 * G.m_nedges)];;
}
double gsl_vector_norm(gsl_vector *v)
{
double v_nrm = 0.0;
for (size_t i = 0; i < v->size; i++)
{
v_nrm += v->data[i] * v->data[i];
}
return sqrt(v_nrm);
}
void init_sol(dgp_t &G, double *x)
{
double dij, lij, uij, *xi, *xj;
double y[3], y_nrm;
int *neighs, nneighs, j;
std::vector<int> s(G.m_nnodes);
std::vector<bool> b(G.m_nnodes, false);
// s = [0, 1, 2, ..., nnodes-1]
for (int k = 0; k < G.m_nnodes; k++)
{
s[k] = k;
}
std::random_shuffle(s.begin(), s.end());
// x = zeros(3 * nnodes)
for (int k = 0; k < (3 * G.m_nnodes); ++k)
{
x[k] = 0.0;
}
std::default_random_engine rndEngine;
std::normal_distribution<double> gaussian(0.0, 1.0);
for (int k = 0; k < G.m_nnodes; k++)
{
int i = s[k];
xi = &(x[3 * i]);
G.neighs(i, nneighs, &neighs);
for (int jj = 0; jj < nneighs; jj++)
{
j = neighs[jj];
if (b[j])
{
continue;
}
G.vals(i, j, NULL, &lij, &uij);
dij = (lij + uij) / 2.0;
xj = &(x[3 * j]);
// y is randomly distributed inside the sphere((0,0,0),1)
vec_set(y, gaussian(rndEngine), gaussian(rndEngine), gaussian(rndEngine));
y_nrm = vec_norm(y);
// xj = dij * (y / y_nrm) + xi (randomly distributed over sphere(xi, dij))
vec_axpby(dij / y_nrm, y, 1.0, xi, xj);
}
}
}
void sph_print_iter(int i, gsl_params_t &p, double f, double fs, gsl_vector *g, int k)
{
if ((i % 10) == 0)
{
printf(" iter | tau | f | fs | nrm(g) | #f_calls \n");
}
printf("%5d | %3.2e | %3.2e | %3.2e | %3.2e | %5d\n", i, p.tau, f, fs, gsl_vector_norm(g), k);
}
bool sph(dgp_t &G, double ftol, double &f, double *x, bool verbose)
{
gsl_params_t gsl_params;
gsl_params.lambda = 0.5;
gsl_params.rho = 0.99;
gsl_params.tau = init_tau(G);
gsl_params.G = &G;
gsl_vector *y = gsl_vector_alloc(3 * G.m_nnodes);
gsl_vector *g = gsl_vector_alloc(3 * G.m_nnodes);
init_sol(G, y->data);
const gsl_multimin_fdfminimizer_type *fdfmin_method = gsl_multimin_fdfminimizer_vector_bfgs2;
gsl_multimin_fdfminimizer *fdfmin;
gsl_multimin_function_fdf gsl_fobj;
gsl_fobj.n = 3 * G.m_nnodes;
gsl_fobj.f = gsl_f;
gsl_fobj.df = gsl_df;
gsl_fobj.fdf = gsl_fdf;
gsl_fobj.params = (void *)(&gsl_params);
double fs;
bool solved = false;
int maxit = 1000, k = 0, status;
for (int i = 0; i < maxit; i++)
{
fs = fobj_sph(gsl_params.lambda, gsl_params.tau, G, y->data, g->data);
f = fobj_sph(gsl_params.lambda, 1E-16, G, y->data, NULL);
if (verbose)
{
sph_print_iter(i, gsl_params, f, fs, g, k);
}
if (f < ftol)
{
solved = true;
break;
}
gsl_params.tau *= gsl_params.rho;
fdfmin = gsl_multimin_fdfminimizer_alloc(fdfmin_method, 3 * G.m_nnodes);
gsl_multimin_fdfminimizer_set(fdfmin, &gsl_fobj, y, 0.01, 1E-3);
// call local optimization
for (k = 0, status = GSL_CONTINUE; k < 1000 && status == GSL_CONTINUE; k++)
{
status = gsl_multimin_fdfminimizer_iterate(fdfmin);
if (status)
{
break;
}
status = gsl_multimin_test_gradient(fdfmin->gradient, 1E-8);
}
// copy from fdfmin to y
for (int j = 0; j < 3 * G.m_nnodes; j++)
{
y->data[j] = fdfmin->x->data[j];
}
gsl_multimin_fdfminimizer_free(fdfmin);
}
// copy solution from y to x
for (int i = 0; i < 3 * G.m_nnodes; i++)
{
x[i] = y->data[i];
}
gsl_vector_free(y);
return solved;
}
| {
"alphanum_fraction": 0.5383675962,
"avg_line_length": 25.4559585492,
"ext": "h",
"hexsha": "eebf1857c4fef701c9388cd39ec987f2bcb00c37",
"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": "f0b285ee936f27fe6d2dada457aec95618e7dbc7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "michaelsouza/sph",
"max_forks_repo_path": "sph.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0b285ee936f27fe6d2dada457aec95618e7dbc7",
"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": "michaelsouza/sph",
"max_issues_repo_path": "sph.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f0b285ee936f27fe6d2dada457aec95618e7dbc7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "michaelsouza/sph",
"max_stars_repo_path": "sph.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1647,
"size": 4913
} |
/* ---------------------------------------------------------------- *
* hod.h *
* Martin Kilbinger, Henry J. McCracken, Jean Coupon 2008-2013 *
* ---------------------------------------------------------------- */
#ifndef __HOD_H
#define __HOD_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "io.h"
#include "errorlist.h"
#include "config.h"
#include "maths.h"
#include "cosmo.h"
#include "nofz.h"
#include "halomodel.h"
/* errors */
#define HOD_BASE -50000
#define HOD_MSTAR_MAX HOD_BASE + 1
#define HOD_NGAL_FIT HOD_BASE + 2
#define GM_base -400000
#define GM_nz_type GM_base + 1
#define GM_pi_max GM_base + 2
#define GM_SHMR GM_base + 3
#define GM_SMF GM_base + 4
#define GM_GGL GM_base + 5
#define GM_MSTAR_MAX GM_base + 6
#define GM_ETA GM_base + 7
/* Limits for xi(r), 1- and 2-halo, in Mpc.h */
#define RMIN1 0.001
#define RMAX1 5.0
#define RMIN2 0.1
#define RMAX2 400.0
#define RMIN RMIN1
#define RMAX RMAX2
#define NR 50
#define MAXCHAR 1024
#define NLINES 100
#define NFIELD 100
#define NCHAR 20
/* GG: galaxy-galaxy stuff. GM: galaxy-dar matter stuff (lensing) */
#define GG 0
#define GM 1
#define getDoubleValue(array,col) atof(array+NCHAR*(col-1))
#define getIntValue(array,col) atoi(array+NCHAR*(col-1))
#define getCharValue(array,col) array+NCHAR*(col-1)
#define getLine(array,i) array+NFIELD*NCHAR*i
#define Nhalodata_t 4
typedef enum {w_of_theta, wp_rp, deltaSigma, smf} halodata_t;
#define shalodata_t(i) ( \
i==w_of_theta ? "w_of_theta" : \
i==wp_rp ? "wp_rp" : \
i==deltaSigma ? "deltaSigma" : \
i==smf ? "smf" : \
"")
#define Nhalomode_t 3
typedef enum {galcorr_var, galcorr_cov, galcorr_log} halomode_t;
#define shalomode_t(i) ( \
i==galcorr_var ? "galcorr_var" : \
i==galcorr_cov ? "galcorr_cov" : \
i==galcorr_log ? "galcorr_log" : \
"")
#define Nngal_fit_t 5
typedef enum {ngal_log_fit, ngal_lin_fit, ngal_no_fit, ngal_lin_fit_only} ngal_fit_t;
#define sngal_fit_t(i) ( \
i==ngal_log_fit ? "ngal_log_fit" : \
i==ngal_lin_fit ? "ngal_lin_fit" : \
i==ngal_no_fit ? "ngal_no_fit" : \
i==ngal_lin_fit_only ? "ngal_lin_fit_only" : \
"")
#define Nintconst_t 2
typedef enum {constant, random_file} intconst_t;
#define sintconst_t(i) ( \
i==constant ? "constant" : \
i==random_file ? "random_file" : \
"")
typedef struct {
char WTHETA[500];
char COVNAME[500];
char DNDZ[500];
char OUTFILE[500];
int nbins;
double ngal, ngalerr, area_deg, intconst, delta;
double alpha_min,alpha_max,dalpha;
double M1_min,M1_max,dM1;
double Mmin_min,Mmin_max,dMmin;
double Ngal_min,Ngal_max,dNgal;
ngal_fit_t ngal_fit_type;
} config_hm_info;
/* ---------------------------------------------------------------- *
* Global variables and functions *
* ---------------------------------------------------------------- */
#define ODD 0
#define EVEN 1
#define ABS(a) ((a) < 0 ? -(a) : (a))
#define PARITY(a) (a)%2 ? ODD : EVEN
#define FFTLog_SWAP(a,b) {FFTLog_TMP = (a); (a) = (b); (b) = FFTLog_TMP;}
#define CHANGE(fct) int change_##fct(cosmo_hm*, cosmo_hm*)
CHANGE(w_of_theta);
CHANGE(Pthg);
CHANGE(HOD);
CHANGE(ngd);
CHANGE(vc);
#undef CHANGE
/* ---------------------------------------------------------------- *
* New types *
* ---------------------------------------------------------------- */
/* This structure contains w_theta input data */
typedef struct {
int nbins, nbins_RR;
double *th;
double *w;
double *werr; /* Error bars */
double *wcov; /* Covariance matrix */
double *th_RR; /* theta for random pairs (can be larger than for the data [even recommended]) */
double *RR; /* Random pairs (for the integral constraint) */
double ngal; /* Galaxy number density*/
double ngal_err;
} wt_t;
typedef struct Nz_hist
{
int nbins;
double *z;
double *n;
double zmin;
double zmax;
double mean;
double dz;
double Norm;
double max;
} Nz_hist;
/* ---------------------------------------------------------------- *
* log-likelihood *
* ---------------------------------------------------------------- */
double chi2_hm(cosmo_hm *model, halodata_t halodata, halomode_t halomode, const wt_t* data, ngal_fit_t ngal_fit_type,
double ngal, double ngalerr, intconst_t intconst_type, error **err);
/* ---------------------------------------------------------------- *
* w(theta) and wp(rp) *
* ---------------------------------------------------------------- */
double *woftheta(cosmo_hm *model, pofk_t pofk, double *theta, int Ntheta, int i_bin, int j_bin, error **err);
double *woftheta_FFTLog_total(cosmo_hm *model, double ln_theta_min, double ln_delta_theta, int Ntheta,
double **theta, int i_bin, int j_bin, error **err);
double *wp(cosmo_hm *model, pofk_t pofk, const double *rp, int Nrp, double pi_max, int type, error **err);
double int_for_wp(double logr, void *params, error **err);
/* ---------------------------------------------------------------- *
* Lensing functions (only for leauthaud11 model) *
* ---------------------------------------------------------------- */
double *DeltaSigma(cosmo_hm *model, pofk_t pofk, const double *r, int N, error **err);
double int_for_Sigma(double logr, void *params, error **err);
/* ---------------------------------------------------------------- *
* Stellar mass function (only for leauthaud11 model) *
* ---------------------------------------------------------------- */
double *dNdlogM10stellar(cosmo_hm *model, double *log10Mstellar, int N, error **err);
double *dNdlogM10stellar_c(cosmo_hm *model, double *log10Mstellar, int N, error **err);
double *dNdlogM10stellar_s(cosmo_hm *model, double *log10Mstellar, int N, error **err);
/* ---------------------------------------------------------------- *
* HOD P(k) and xi(r) *
* ---------------------------------------------------------------- */
double *xiofr(cosmo_hm *model, pofk_t pofk, const double *r, int N, int type, error **err);
double *xi_1hcs(cosmo_hm *model,double a, const double *r, int N, int type, error **err);
double int_for_xi_1hcs(double logM, void *params, error **err);
double *xi_1hss(cosmo_hm *model,double a, const double *r, int N, int type, error **err);
double P1hss(double k, void *params);
double int_for_P1hss(double logM, void *params, error **err);
double concentration_sat(cosmo_hm *model, double Mh, double a, error **err);
double *xi_2h(cosmo_hm *model,double a, const double *r, int N, int type, error **err);
double *xi_P_NL(cosmo_hm *model, double a, const double *r, int N, error **err);
double FFTLog_P_NL(double k, void *params);
double P2h(double k, void *params);
double int_for_P2h(double logM, void *params, error **err);
double int_for_P2h_dm(double logM, void *params, error **err);
double bias_r(double M, void *params);
/* ---------------------------------------------------------------- *
* HOD model functions *
* ---------------------------------------------------------------- */
double log10_fSHMR(double log10Mh, cosmo_hm *model);
double log10_fSHMR_inv_minus_x(double log10Mstar, void *p);
double log10_fSHMR_inv(double log10Mstar, cosmo_hm *model);
double Ngal_c(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max);
double int_for_Ngal_c(double Mstellar, void *params, error **err);
double phi_c_Mstellar(cosmo_hm *model, double log10Mstellar, double Mh, error **err);
double sigma_log_M(cosmo_hm *model, double log10Mstellar, error **err);
double eta_cen(cosmo_hm *model, double Mh, error **err);
double Ngal_s(cosmo_hm *model, double M, double Mstellar_min, double Mstellar_max);
double Ngal(cosmo_hm *model, double M, double Mstellar_min, double Mstellar_max);
double av_Mh_given_Mstar(cosmo_hm *model, double Mstellar, double a, error **err);
double int_for_phi_c_Mh(double log10Mh, void *params, error **err);
double int_for_phi_c_Mh_norm(double log10Mh, void *params, error **err);
/* ---------------------------------------------------------------- *
* Deduced quantities *
* ---------------------------------------------------------------- */
double Mstar_tot_c(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max, error **err);
double int_for_Mstar_tot_c(double logMstar, void *params, error **err);
double Mstar_tot_s(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max, error **err);
double int_for_Mstar_tot_s(double logMstar, void *params, error **err);
double av_gal_bias(cosmo_hm *model, double a, error **err);
double int_for_av_gal_bias(double logM, void *intpar, error **err);
double av_halo_mass(cosmo_hm *model, double a, error **err);
double int_for_av_halo_mass(double logM, void *intpar, error **err);
double mass_weighted_av_stellar_mass(cosmo_hm *model, double a, error **err);
double int_for_mass_weighted_av_stellar_mass(double logM, void *params, error **err);
double int_for_mass_denum_weighted_av_stellar_mass(double logM, void *params, error **err);
double av_stellar_mass(cosmo_hm *model, double a, error **err);
double int_for_av_stellar_mass(double logM, void *params, error **err);
double av_frsat(cosmo_hm *model, double a, error **err);
double int_for_av_frsat(double logM, void *intpar, error **err);
double av_halo_bias(cosmo_hm *model, double a, error **err);
double int_for_av_halo_bias(double logM, void *intpar, error **err);
double dn_dlnM_integrand(double logM, void *intpar, error **err);
/* ---------------------------------------------------------------- *
* Physical quantities *
* ---------------------------------------------------------------- */
double vc(cosmo_hm *model,double zmin, double zmax, error **err);
double int_for_vc(double z, void *params, error **err);
double logM_lim(cosmo_hm *model, double a, double r, error **err);
double ngal_triax(cosmo_hm *model, double a, double r, error **err);
double ngal_den(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);
double int_for_ngal_den(double logM, void *params, error **err);
double ngal_den_c(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);
double int_for_ngal_den_c(double logM, void *params, error **err);
double ngal_den_s(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);
double int_for_ngal_den_s(double logM, void *params, error **err);
double ngal_den_vol(cosmo_hm *model, error **err);
double ngal_weighted(cosmo_hm *model, error **err);
/* ---------------------------------------------------------------- *
* FFTLog *
* ---------------------------------------------------------------- */
double xi_from_Pkr(gsl_function *ak, double r_prime, FFTLog_config *fc, error **err);
void FFTLog(FFTLog_config *fc, const gsl_function *ar_in,double *k, double *ak_out, int dir, error **err);
FFTLog_config *FFTLog_init(int N, double min, double max, double q, double mu);
void FFTLog_free(FFTLog_config *fc);
FFTLog_complex FFTLog_U_mu(double mu, FFTLog_complex z);
/* ---------------------------------------------------------------- *
* Utils *
* ---------------------------------------------------------------- */
void updateFrom_hm(cosmo_hm* avant, cosmo_hm* apres, error **err);
int change_vc(cosmo_hm *avant, cosmo_hm *apres);
int change_ngd(cosmo_hm *avant, cosmo_hm *apres);
int change_HOD(cosmo_hm *avant, cosmo_hm *apres);
int change_Pthg(cosmo_hm* avant, cosmo_hm* apres);
int change_w_of_theta(cosmo_hm *avant, cosmo_hm *apres);
wt_t *init_wt_t(double nlines, int wcov, error **err);
void free_wt_t(wt_t **model);
wt_t *read_wtheta(const char *data_file_name, intconst_t intconst_type, double delta, double intconst, const char *ran_file_name, error **err);
int getStrings(char *line, char *strings, char *delimit, size_t *N, error **err);
void read_config_hm_file(config_hm_info *config, char cname[], error **err);
Nz_hist *get_nz(redshift_t *nz_mk, int n_bin, error **err);
void free_nz( Nz_hist *nz);
double normalize(double *data, size_t Nbins, double binsize,error **err);
/* ---------------------------------------------------------------- *
* Obsolete stuff *
* ---------------------------------------------------------------- */
double *woftheta_total_OBSOLETE(cosmo_hm *model, double log_theta_min, double log_delta_theta, int Ntheta, error **err);
nz_t *read_dndz_OBSOLETE(char *infile,error **err);
double Ngal_mean(cosmo_hm *model, double a, error **err);
double xir_mwolk(cosmo_hm *model, double a, double r, error **err);
wt_t *read_wtheta_mwolk(const char *name, double delta, double intconst, error **err);
double chi2_mwolk(cosmo_hm *model, const wt_t* data, ngal_fit_t ngal_fit_type,
double ngal, double ngalerr, double area, error **err);
double wp_mwolk(cosmo_hm *model, double rp, error **err);
double compute_chisq_wp(cosmo_hm *model, const wt_t *wth, double ngd_obs, double ngd_err,
ngal_fit_t ngal_fit_type, double *ngd, int dologw, error **err);
#endif
| {
"alphanum_fraction": 0.5955845096,
"avg_line_length": 41.6114457831,
"ext": "h",
"hexsha": "0d997b51b9bea7d3f919f9d13e743db9b98155c3",
"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": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danielgruen/ccv",
"max_forks_repo_path": "src/nicaea_2.5/halomodel/include/hod.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"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": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/halomodel/include/hod.h",
"max_line_length": 143,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danielgruen/ccv",
"max_stars_repo_path": "src/nicaea_2.5/halomodel/include/hod.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 3650,
"size": 13815
} |
#include <iostream>
#include <vector>
#include <stdio.h>
#include <gsl\gsl_randist.h>
#include <gsl\gsl_rng.h>
#include <time.h>
#include <SFML\Graphics.hpp>
#ifndef _HEART_H
#define _HEART_H
class heart
{
private:
int L; //sytem size length for now square
std::vector<std::vector<int>> state; //value indicates whether in excited state refactory or resting
std::vector<std::vector<int>> new_state; //using new_state and state to distinguish newly excited cells from previously excited
std::vector<std::vector<int>> functional; //1 if functional 0 if disfunctional
std::vector<std::vector<int>> bond; //1 if bond to site above current cell, 0 if no bond above site
std::vector<std::vector<int>> unablated; // Defaults to zero initial value
int heart_time; //internal clock
//model parameters
int tau; //refactory period
int T; // pacemaker rate
double nu, epsilom, delta; //probability vertical connection exists, probability of misfire given faulty and probability cell faulty
//random number generator
const gsl_rng_type*Type;
gsl_rng*r;
int total_bonds;
int total_functional;
int total_excited;
public:
heart()
{
}
heart(const int _L, int _T, int _tau ,double _nu, double _epsilom, double _delta)
{
L=_L;
nu= _nu;
tau=_tau;
T=_T;
epsilom=_epsilom;
delta=_delta;
heart_time = T;
state.resize(L);
new_state.resize(L);
functional.resize(L);
bond.resize(L);
unablated.resize(L);
//pacemaker action
for(unsigned i=0; i<L; i++)
{
state[i].resize(L,0); // all cells eligible for excitation
new_state[i].resize(L,0);
functional[i].resize(L,0);// none disfunctional at the moment
bond[i].resize(L, 1); // all transverse bonds present at the moment
unablated[i].resize(L,1);
}
// total_functional = L*L;
// total_bonds = L*L;
total_excited =0;//could be useful avoiding calling size of some vector
//HAVE NOT USED gsl_rng in class before need to make sure is working correctly
// environment variable GSL_RNG_TYPE
gsl_rng_env_setup();
Type = gsl_rng_mt19937;//random number generator using the Mersenne Twister algorithm
r = gsl_rng_alloc (Type);
gsl_rng_set(r,time(NULL));//random number generator seeded with time
//gsl_rng_set(r,0);//random number generator seeded with time
//assigning cells as having a bond above them or not and functional or not functional
for(int i=0; i<L; i++)
{
for(int j=0; j<L; j++)
{
bond[i][j] = (gsl_rng_uniform(r)<nu);
functional[i][j] = (gsl_rng_uniform(r)>delta);// inequality reversed
//double x = gsl_rng_uniform(r);
// std::cout <<x<< '\t' << (x<nu) << std::endl;
}
}
}
void operate()//one time step
{
total_excited =0;
//Relax excited cells
for(int i=0; i<L ;i++)
{
for(int j=0; j<L; j++)
{
if(state[i][j]==1)//searching 4 neighbours of excited cell trying to excite if resting and if don't misfire and if there is a bond
{
new_state[((i+1)<L)*(i+1)][j]+=(state[((i+1)<L)*(i+1)][j]<1)*bond[i][j]*(1-(1-functional[((i+1)<L)*(i+1)][j])*(gsl_rng_uniform(r)<epsilom))*unablated[((i+1)<L)*(i+1)][j];
new_state[(i-1)*(i>0)+(L-1)*(i<1)][j]+=(state[(i-1)*(i>0)+(L-1)*(i<1)][j]<1)*bond[(i-1)*(i>0)+(L-1)*(i<1)][j]*(1-(1-functional[(i-1)*(i>0)+(L-1)*(i<1)][j])*(gsl_rng_uniform(r)<epsilom))*unablated[(i-1)*(i>0)+(L-1)*(i<1)][j];
new_state[i][(j+1)*(j<L-1)] += (j<L-1)*(state[i][(j+1)*(j<L-1)]<1)*(1-(1-functional[i][(j+1)*(j<L-1)])*(gsl_rng_uniform(r)<epsilom))*unablated[i][(j+1)*(j<L-1)];
new_state[i][(j-1)*(j>0)]+= (j>0)*(state[i][(j-1)*(j>0)]<1)*(1-(1-functional[i][(j-1)*(j>0)])*(gsl_rng_uniform(r)<epsilom))*unablated[i][(j-1)*(j>0)];
}
}
}
//end relaxing
//evolving cells that were not excited previously or now (some subtlty to those possibly excited now)
for(int i=0;i<L;i++)
{
for(int j=0; j<L; j++)
{
new_state[i][j] += (state[i][j]>0);
//if state was excited or refactory before +1 states that were resting may have been newly excited or not but this ignores them
new_state[i][j] *= (state[i][j]<tau);//promote to resting after end of refactory
total_excited += (new_state[i][j]<2)*new_state[i][j];
}
}
//SAN
for(int i=0; i<L; i++)
{
new_state[i][0] += (state[i][0]<1)*(heart_time>T-1)*(1-(1-functional[i][0])*(gsl_rng_uniform(r)<epsilom));
//will do something every T steps should also add in misfire
}
heart_time++;
heart_time *= (heart_time<T+1);
//end SAN
state=new_state;
}
int get_state(int i, int j)//perhaps have alternative for 2d array
{
return state[i][j];
}
void set_state(int i, int j, int val)
{
state[i][j]=val;
}
int get_function(int i, int j)
{
return functional[i][j];
}
void set_function(int i, int j, int val)
{
functional[i][j]=val;
}
int get_bond(int i, int j)
{
return bond[i][j];
}
void set_bond(int i, int j, int val)
{
bond[i][j]=val;
}
int get_tau()
{
return tau;
}
int get_T()
{
return T;
}
void age_nu()
{
}
void set_disfunction()
{
}
int get_excited()
{
return total_excited;
}
double colour(int i, int j)
{
return (1-state[i][j]/(1.0*tau))*(state[i][j]>1);
//return state[i][j]/(1.0*T);
}
void interact(sf::RenderWindow & renderWindow, int length)
{
sf::Event event;
float x;
float y;
float Mx = sf::Mouse::getPosition(renderWindow).x;
float My = sf::Mouse::getPosition(renderWindow).y;
//std::cout << Mx << " " << My << std::endl;
while (renderWindow.pollEvent(event))
{
switch(event.type)
{
case sf::Event::KeyPressed:
state[My/length][Mx/length] = 0;
new_state[My/length][Mx/length] = 0;
unablated[My/length][Mx/length] = 0;
}
}
}
};
#endif | {
"alphanum_fraction": 0.5906870726,
"avg_line_length": 26.9385964912,
"ext": "h",
"hexsha": "08bb4524deef8e7bb852774575bfb33c37bf33c5",
"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": "48ea3570c360aac7c3ff46354891998f4f364fab",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pm2111/Heart-Defibrillation-Project",
"max_forks_repo_path": "ablation 1/heart.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab",
"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": "pm2111/Heart-Defibrillation-Project",
"max_issues_repo_path": "ablation 1/heart.h",
"max_line_length": 231,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "48ea3570c360aac7c3ff46354891998f4f364fab",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pm2111/Heart-Defibrillation-Project",
"max_stars_repo_path": "ablation 1/heart.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1985,
"size": 6142
} |
#ifndef _H_INTERP2D
#define _H_INTERP2D
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp.h>
typedef struct Interpolator2D{
double *x1;
double *x2;
double *y;
int N1;
int N2;
double *y1;
gsl_spline *x1dir_spline;
gsl_interp_accel *x1dir_accel;
gsl_spline **x2dir_splines;
gsl_interp_accel **x2dir_accels;
} Interpolator2D;
typedef double (*interp2d_modifier_function)(double,double,double,void*);
Interpolator2D * init_interp_2d(double *x1, double *x2, double *y, int N1, int N2, const gsl_interp_type *T);
Interpolator2D * init_interp_2d_akima(double *x1, double *x2, double *y, int N1, int N2);
Interpolator2D * init_interp_2d_grid(double *x1, double *x2, double **y, int N1, int N2, const gsl_interp_type *T);
Interpolator2D * init_interp_2d_akima_grid(double *x1, double *x2, double **y, int N1, int N2);
Interpolator2D * init_interp_2d_function(double *x1, double *x2, double *y,
int N1, int N2, const gsl_interp_type *T, interp2d_modifier_function function, void * args);
Interpolator2D * init_interp_2d_akima_function(double *x1, double *x2, double *y,
int N1, int N2, interp2d_modifier_function function, void * args);
Interpolator2D * init_interp_2d_grid_function(double *x1, double *x2, double **y,
int N1, int N2, const gsl_interp_type *T, interp2d_modifier_function function, void * args);
Interpolator2D * init_interp_2d_akima_grid_function(double *x1, double *x2,
double **y, int N1, int N2, interp2d_modifier_function function, void * args);
void destroy_interp_2d(Interpolator2D * interp2d);
double interp_2d(double x1, double x2, Interpolator2D * interp2d);
Interpolator2D * load_interp_2d_file(const char * filename, int N1, int N2);
double interp_2d_xmin(Interpolator2D * interp2d);
double interp_2d_xmax(Interpolator2D * interp2d);
double interp_2d_ymin(Interpolator2D * interp2d);
double interp_2d_ymax(Interpolator2D * interp2d);
#endif | {
"alphanum_fraction": 0.7714135575,
"avg_line_length": 40.4893617021,
"ext": "h",
"hexsha": "c50bbd4ab6a19a2e1ee9207824e0c27d6cff0b92",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/interp2d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/interp2d.h",
"max_line_length": 115,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/interp2d.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z",
"num_tokens": 608,
"size": 1903
} |
/*
*/
#ifndef _aXe_GRISM_H
#define _aXe_GRISM_H
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "spc_trace_functions.h"
//#include "aXe_errors.h"
#define RELEASE "See github"
#define gsl_matrix gsl_matrix_float
#define gsl_matrix_get gsl_matrix_float_get
#define gsl_matrix_set gsl_matrix_float_set
#define gsl_matrix_set_all gsl_matrix_float_set_all
#define gsl_matrix_alloc gsl_matrix_float_alloc
#define gsl_matrix_free gsl_matrix_float_free
#define gsl_matrix_fprintf gsl_matrix_float_fprintf
#define gsl_matrix_add_constant gsl_matrix_float_add_constant
#define gsl_matrix_scale gsl_matrix_float_scale
#define gsl_matrix_min gsl_matrix_float_min
#define gsl_matrix_max gsl_matrix_float_max
/* WARNING: If you ever change PIXEL_T, make sure you also change
the FITS loader */
#define PIXEL_T float /* type of pixel data -- this should be in
sync with the GSL definitions */
#define MAX_BEAMS 27 /* Max. number of spectrum orders we handle */
// now equals the alphabet...
#define BEAM(x) (char)((int)x+65) /* Defines names for 3 different beams */
#define MAXCHAR 255 /* Number of characters in small strings and FITS keywords */
/**
A set of two relative (pixel) offsets.
*/
typedef struct
{
int dx0, dx1;
}
px_offset;
/**
A set of two relative double offsets.
*/
typedef struct
{
double dx0, dx1;
}
dx_offset;
/**
A point with integer (pixel) coordinates.
*/
typedef struct
{
int x, y;
}
px_point;
/**
A point with double coordinates.
*/
typedef struct
{
double x, y;
}
d_point;
/**
An aggregation of the grism exposure, its errors, the background,
and flatfields
*/
typedef struct
{
gsl_matrix *grism; /* The grism image */
gsl_matrix *pixerrs; /* (Absolute) errors associated with the grism image */
gsl_matrix *dq; /* Data quality associated with grism image */
}
observation;
/**
A beam, i.e., a description of the image of a spectrum of a given order,
including a reference point, the corners of a convex quadrangle
bounding the image, and the parametrization of the spectrum trace
*/
typedef struct
{
int ID; /* An integer ID for this beam
(see enum beamtype */
d_point refpoint; /* Pixel coordinates of the reference point */
px_point corners[4]; /* Bounding box of spectrum as an arbitrary
quadrangle */
px_point bbox[2]; /* Bounding box of corners, will be filled
in by spc_extract */
trace_func *spec_trace; /* Parametrization of the spectrum trace */
double width; /* largest axis of object in pixels */
double orient; /* orientation of largest axis in radian,
0==horizontal */
int modspec;
int modimage;
double awidth; /* the object width along the extraction direction */
double bwidth; /* the object width perpendicular to ewidth
(which is closer to the dispersion direction */
double aorient; /* orientation of awidth (CCW) =0 along the x-axis */
double slitgeom[4]; /* containst the values for the slit length, angle and
so on */
gsl_vector *flux; /* the flux of the object at various wavelengths */
int ignore; /* This beam should be ignored if this is not set to 0 */
}
beam;
/**
An object, describing the width and orientation of the object,
the beams in which the spectrum images lie, and the images
comprising an observation of the object.
*/
typedef struct
{
int ID; /* An integer ID number for this object */
beam beams[MAX_BEAMS]; /* table of beams (orders of spectrum) */
int nbeams; /* number of beams in beams member */
observation *grism_obs;
}
object;
/**
An aperture pixel, i.e., a pixel within a beam. The structure
contains the coordinates, the abscissa of the section point between
the object axis and the spectrum trace, the distance between
the pixel and the section point along the object axis, the path
length of the section point along the trace, and the photon count for
this pixel. A table of these is produced by the
make_spc_table function.
*/
typedef struct
{
int p_x, p_y; /* the absolute coordinates of the
source pixel. A -1 in p_x signifies
the end of a list of ap_pixels */
double x, y; /* the logical coordinates of this (logical)
pixel relative to the beam's reference
point */
double dist; /* distance between point and section */
double xs; /* abscissa of section point relative to reference point */
double ys; /* y coord of section point relative to reference point */
// traditionally (at least aXe-1.3-1.6 "dxs" was called "Projected size of pixel along the trace".
// however in the code (spc_extract.c, function "handle_one_pixel()" it becomes clear
// that this quantity indeed is the local trace angle
double dxs;
double xi; /* path length of the section along the
spectrum trace (computed from xs) */
double lambda; /* path length of the section along the
spectrum trace (computed from xi) */
double dlambda; /* dpath length of the section along the
spectrum trace */
double count; /* intensity for this pixel */
double weight; /* extraction weight for this pixel */
double error; /* absolute error of count */
double contam; /* flag whether this pixel is contaminated by another spectrum */
double model; /* the pixel flux computed for one of the emission models */
long dq; /* DQ bit information */
}
ap_pixel;
typedef struct
{
ap_pixel *ap; /* A pointer to an ap_pixel array */
object *obj; /* A pointer to the corresponding object
structure */
beam *b; /* A pointer to the beam in the object
that this group of pixel correspond to */
}
PET_entry;
/* See comment to spectrum structure */
typedef enum
{
SPC_W_CONTAM,
SPC_W_BORDER
}
spec_warning;
/**
A point within a spectrum, consisting of the minimum, maximum, and
(weighted) mean lambda of the points that contributed to the
bin, as well as an error estimate for the value (that's in there,
too, of course)
*/
typedef struct
{
double lambda_min, lambda_mean;
double lambda_max, dlambda;/* wavelength information */
double error; /* error in counts in this bin */
double count; /* number of counts in this bin */
double weight; /* weight of this bin */
double flux; /* flux in physical units in this bin */
double ferror; /* error in physical units in this bin */
double contam; /* spectral contamination flag */
// int contam; /* spectral contamination flag */
long dq; /* DQ information */
}
spc_entry;
/**
A spectrum, consisting of a gsl_array containing the data, a start
value (center wave length of lowest bin), a bin size, and warn flags,
which may be <ul><li>SPC_W_CONTAM -- Spectrum is contaminated</li>
<li>SPC_W_BORDER -- Spectrum lies partially beyond the image borders.
</li></ul>
*/
typedef struct
{
spc_entry *spec; /* the actual spectrum */
double lambdamin;
double lambdamax;
int spec_len; /* Number of items in spec */
spec_warning warning; /* problems with this spectrum */
}
spectrum;
#define DEBUG_FILE 0x01
#define DEBUG 0x0000
extern void
print_ap_pixel_table (const ap_pixel * ap_p);
extern ap_pixel *
make_spc_table (object * const ob,
const int beamorder, int *const flags);
extern ap_pixel *
make_gps_table (object * const ob,
const int beamorder, int *const flags,
int xval, int yval);
#endif /* !_aXe_GRISM_H */
| {
"alphanum_fraction": 0.6176056338,
"avg_line_length": 33.28125,
"ext": "h",
"hexsha": "f60dcafc1ce583ecfe6b067a7b3deac45e0ebca6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/aXe_grism.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/aXe_grism.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/aXe_grism.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1843,
"size": 8520
} |
/*
* ParticleFilter.h
*
* Created on: Mar 21, 2012
* Author: nair
*/
#ifndef PARTICLEFILTER_H_
#define PARTICLEFILTER_H_
#include <gsl/gsl_rng.h>
#include <opencv2/opencv.hpp>
#include <Eigen/Dense>
namespace tracking1
{
class ParticleFilterParams
{
public:
ParticleFilterParams();
~ParticleFilterParams();
void parse(std::string filename);
public:
int NUMBER_OF_PARTICLES;
/* standard deviations for gaussian sampling in transition model */
float TRANS_X_STD;
float TRANS_Y_STD;
float TRANS_SCALE_STD;
/* autoregressive dynamics parameters for transition model */
float DYNAMICS_A1;
float DYNAMICS_A2;
float DYNAMICS_B0;
double LAMBDA;
bool DYNAMIC_MODEL_CV;
};
struct Particle
{
float x; /**< current x coordinate */
float y; /**< current y coordinate */
float s; /**< current z coordinate */
float xp; /**< previous x coordinate */
float yp; /**< previous y coordinate */
float sp; /**< previous z coordinate */
float x0; /**< original x coordinate */
float y0; /**< original y coordinate */
float s0; /**< original z coordinate */
float x_velocity; /**< current x_velocity coordinate */
float y_velocity; /**< current y_velocity coordinate */
float s_velocity; /**< current z_velocity coordinate */
float w; /**< weight */
};
class ParticleFilter
{
public:
ParticleFilter();
~ParticleFilter();
void initialize(const cv::Vec3d& initPose);
void predict();
void predict_with_simple_model();
void predict_with_cv_model();
void correct();
void resizeParticleSet(int n);
void setParticleWeight(int id, float w);
double getMaxLikelihood()
{
double max=0.0;
for(int i=0;i<mParams.NUMBER_OF_PARTICLES;++i)
{
if(max<mParticles[i].w)
{
max=mParticles[i].w;
}
}
return max;
}
double getAvgLikelihood()
{
double avg=0.0;
for(int i=0;i<mParams.NUMBER_OF_PARTICLES;++i)
{
avg+=mParticles[i].w;
}
return avg/mParams.NUMBER_OF_PARTICLES;
}
int nOfParticles()
{
return mParams.NUMBER_OF_PARTICLES;
}
static int particle_cmp(const void* p1,const void* p2 )
{
Particle* _p1 = (Particle*)p1;
Particle* _p2 = (Particle*)p2;
if( _p1->w > _p2->w )
return -1;
if( _p1->w < _p2->w )
return 1;
return 0;
}
void getParticlePose(int id, cv::Vec3d& pose);
void getOutputPose(cv::Vec3d& pose);
void getOutputAvgPose(cv::Vec3d& pose);
void getOutputVelocity(cv::Vec3d& vel);
double getLambda()
{
return mParams.LAMBDA;
}
private:
void normalize();
void resample();
private:
ParticleFilterParams mParams;
Particle* mParticles;
cv::Vec3d mOutputPose;
Eigen::MatrixXd A_Matrix;
Eigen::MatrixXd G_Matrix;
Eigen::MatrixXd W_Matrix;
Eigen::MatrixXd State_Matrix;
Eigen::MatrixXd State_Prev_Matrix;
gsl_rng* rng;
};
}
#endif /* PARTICLEFILTER_H_ */
| {
"alphanum_fraction": 0.5990114303,
"avg_line_length": 19.5,
"ext": "h",
"hexsha": "8adcc57d84f0c7494340360d7573addf0b15389f",
"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": "5374193260e6385becfe8086a70d21d650314beb",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "cognitivesystems/smartcamera",
"max_forks_repo_path": "2d-object-tracking/client/src/tracker/ParticleFilter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5374193260e6385becfe8086a70d21d650314beb",
"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": "cognitivesystems/smartcamera",
"max_issues_repo_path": "2d-object-tracking/client/src/tracker/ParticleFilter.h",
"max_line_length": 71,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5374193260e6385becfe8086a70d21d650314beb",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "cognitivesystems/smartcamera",
"max_stars_repo_path": "2d-object-tracking/client/src/tracker/ParticleFilter.h",
"max_stars_repo_stars_event_max_datetime": "2017-03-27T16:14:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-27T16:14:59.000Z",
"num_tokens": 790,
"size": 3237
} |
#include "stdio.h"
#include "gsl/gsl_integration.h"
#include "gsl/gsl_errno.h"
#include "non_limber.h"
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_sf_bessel.h>
// This is a workspace size for the gsl integrator
#define LIMBER_FIXED_TABLE_SIZE 4096
// data that is passed into the integrator
// This is everything we need to compute the
// integrand
struct ClIntegrandData {
double ell;
double chimin;
double chimax;
gsl_spline * WbX;
gsl_spline * WbY;
gsl_spline * D_chi;
gsl_spline2d * P;
gsl_interp_accel * accelerator_wx;
gsl_interp_accel * accelerator_wy;
gsl_interp_accel * accelerator_px;
gsl_interp_accel * accelerator_py;
gsl_interp_accel * accelerator_growth;
};
double cl_integrand(double *x, size_t dim, void *data_void)
{
struct ClIntegrandData * data = (struct ClIntegrandData*) data_void;
double chi1 = x[0];
double log_delta = x[1];
double log_nu = x[2];
double nu = exp(log_nu);
double delta = exp(log_delta);
double chi2_p = chi1 * ( 1 + delta);
double chi2_m = chi1 * (1 - delta);
double logk = log_nu / chi1;
if(chi2_m < data->chimin || chi2_p > data->chimax) return 0.0;
double FX = gsl_spline_eval(data->WbX, chi1, data->accelerator_wx);
double FY_p = gsl_spline_eval(data->WbY, chi2_p, data->accelerator_wy);
double FY_m = gsl_spline_eval(data->WbY, chi2_m, data->accelerator_wy);
double growth_1 = gsl_spline_eval(data->D_chi, chi1, data->accelerator_growth);
double growth_2_p = gsl_spline_eval(data->D_chi, chi2_p, data->accelerator_growth);
double growth_2_m = gsl_spline_eval(data->D_chi, chi2_m, data->accelerator_growth);
// Get P(k,chi)
// Deactivate error handling
gsl_error_handler_t * old_handler = gsl_set_error_handler_off();
double p;
int status = gsl_spline2d_eval_e(data->P, chi1, logk, data->accelerator_px, data->accelerator_py, &p);
// Restore the old error handler
gsl_set_error_handler(old_handler);
if (status)
{
//printf(stderr,'spline failed, for now, assume this is because k was out of range and return 0...should probably be more careful here though.');
return 0.0;
}
double j1 = gsl_sf_bessel_jl(data->ell, nu);
double j2_p = gsl_sf_bessel_jl(data->ell, nu*(1+delta));
double j2_m = gsl_sf_bessel_jl(data->ell, nu*(1-delta));
double prefac = 2 * delta * 2 * nu * nu * nu * p / growth_1 / M_PI / chi1 / chi1 ;
return prefac * ( FY_p * growth_2_p * j2_p + FY_m * growth_2_m * j2_m );
}
static double inline gsl_spline_min_x(gsl_spline * s)
{
return s->x[0];
}
static double inline gsl_spline_max_x(gsl_spline * s)
{
return s->x[s->size-1];
}
int get_chi_mean_sigma(double chimin, double chimax, gsl_spline * WbX, gsl_spline * WbY,
gsl_interp_accel * accelerator_wx, gsl_interp_accel * accelerator_wy,
double *chi_mean, double *chi_sigma)
{
int nchi = 1000;
double dchi = (chimax-chimin)/nchi;
double chi = chimin;
double wxwy_sum = 0.;
double wxwy2_sum = 0.;
double wx,wy;
for (int i=0; i<nchi; i++){
wx = gsl_spline_eval(WbX, chi, accelerator_wx);
wy = gsl_spline_eval(WbY, chi, accelerator_wy);
wxwy_sum += wx*wy*chi;
wxwy2_sum += wx*wy*chi*chi;
chi += dchi;
}
*chi_mean = wxwy_sum*dchi;
*chi_sigma = sqrt(wxwy2_sum*dchi - *chi_mean * *chi_mean);
return 0;
}
int cl_integral(cl_config * config, gsl_spline * WbX,
gsl_spline * WbY, gsl_spline2d * P, gsl_spline * D_chi,
double * cl_out, double * cl_err_out)
{
config->status = LIMBER_STATUS_ERROR;
int any_parameter_error=0;
if (WbX==NULL){
fprintf(stderr, "NULL WX parameter in limber_integral\n");
any_parameter_error = 1;
}
if (WbY==NULL){
fprintf(stderr, "NULL WY parameter in limber_integral\n");
any_parameter_error = 1;
}
if (P==NULL){
fprintf(stderr, "NULL P parameter in limber_integral\n");
any_parameter_error = 1;
}
if (D_chi==NULL){
fprintf(stderr, "NULL D_chi parameter in limber_integral\n");
any_parameter_error = 1;
}
if (config->n_ell<0){
fprintf(stderr, "Negative n_ell parameter in limber_integral\n");
any_parameter_error = 1;
}
if (any_parameter_error){
return 1;
}
config->status = LIMBER_STATUS_OK;
static int n_ell_zero_warning = 0;
if (config->n_ell==0){
if (n_ell_zero_warning==0){
fprintf(stderr, "Warning: n_ell=0 in Limber. Will not be treated as an error. Warning once only per process.\n");
}
n_ell_zero_warning = 1;
return 1;
}
// Get the appropriate ranges over which to integrate
// It is assumed that (at least one of) the kernel
// splines should go to zero in some kind of reasonable
// place, so we just use the range they specify
struct ClIntegrandData data;
double chimin_x = gsl_spline_min_x(WbX);
double chimin_y = gsl_spline_min_x(WbY);
double chimax_x = gsl_spline_max_x(WbX);
double chimax_y = gsl_spline_max_x(WbY);
double c_ell, c_ell_error;
// Workspaces
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
size_t calls = 5000000;
double reltol = config->relative_tolerance;
double abstol = config->absolute_tolerance;
// Take the smallest range since we want both the
// splines to be valid there.
// This range as well as all the data needed to compute
// the integrand is put into a struct to be passed
// through the integrator to the function above.
double chimin = chimin_x>chimin_y ? chimin_x : chimin_y;
double chimax = chimax_x<chimax_y ? chimax_x : chimax_y;
data.chimin = chimin_y;
data.chimax = chimax_y;
data.WbX = WbX;
data.WbY = WbY;
data.P = P;
data.accelerator_wx = gsl_interp_accel_alloc();
data.accelerator_wy = gsl_interp_accel_alloc();
data.accelerator_px = gsl_interp_accel_alloc();
data.accelerator_py = gsl_interp_accel_alloc();
data.accelerator_growth = gsl_interp_accel_alloc();
data.D_chi = D_chi;
double chi_mean, chi_sigma;
get_chi_mean_sigma(chimin, chimax, WbX, WbY,
data.accelerator_wx, data.accelerator_wy,
&chi_mean, &chi_sigma);
// save ell values for return
double ell_vector[config->n_ell];
double nu_0;
gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (3);
// loop through ell values according to the input configuration
for (int i_ell = 0; i_ell<config->n_ell; i_ell++){
double ell = config->ell[i_ell];
double log_nu_0 = log(ell+0.5);
double log_nu_min = log_nu_0 - config->log_nu_range;
double log_nu_max = log_nu_0 + config->log_nu_range;
printf("delta_range_factor %f\n", config->delta_range_factor);
double delta_min = 1. / ell / config->delta_range_factor;
double delta_max = 1. * config->delta_range_factor / ell;
double log_delta_min = log(delta_min);
double log_delta_max = log(delta_max);
printf("log_delta_min,max %f %f\n", delta_min, delta_max);
double xl[3] = { chimin_x, log_delta_min, log_nu_min };
double xu[3] = { chimax_x, log_delta_max, log_nu_max };
data.ell=ell;
gsl_monte_function G = {&cl_integrand, 3, &data};
gsl_monte_vegas_integrate (&G, xl, xu, 3, 10000, r, s,
&c_ell, &c_ell_error);
gsl_monte_vegas_integrate (&G, xl, xu, 3, calls/5, r, s,
&c_ell, &c_ell_error);
gsl_monte_vegas_init (s);
//Include the prefactor scaling
c_ell *= config->prefactor;
// Record the results into arrays
cl_out[i_ell] = c_ell;
cl_err_out[i_ell] = c_ell_error;
ell_vector[i_ell] = ell;
}
gsl_monte_vegas_free (s);
// Tidy up
gsl_interp_accel_free(data.accelerator_wx);
gsl_interp_accel_free(data.accelerator_wy);
gsl_interp_accel_free(data.accelerator_px);
gsl_interp_accel_free(data.accelerator_py);
gsl_interp_accel_free(data.accelerator_growth);
// These two are not deallocated because they are static and only initialized once.
// gsl_integration_glfixed_table_free(table);
// gsl_integration_workspace_free(W);
// And that's it
return 0;
}
| {
"alphanum_fraction": 0.7008357915,
"avg_line_length": 32.2857142857,
"ext": "c",
"hexsha": "f79333cf5b4fe3bd94dcc14440d57a0a386fdd9d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c",
"max_line_length": 147,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z",
"num_tokens": 2450,
"size": 8136
} |
/**
*
* @file testing_ssyev.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
* @author Azzam Haidar
* @date 2010-11-15
* @generated s Tue Jan 7 11:45:18 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_smain.h"
#undef COMPLEX
#define REAL
static int check_orthogonality(int, int, float*, int, float);
static int check_reduction(int, int, int, float*, float*, int, float*, float);
static int check_solution(int, float*, float*, float);
int testing_ssyev(int argc, char **argv)
{
/* Check for number of arguments*/
if (argc != 2) {
USAGE("HEEV", "N LDA",
" - N : size of the matrix A\n"
" - LDA : leading dimension of the matrix A\n");
return -1;
}
int N = atoi(argv[0]);
int LDA = atoi(argv[1]);
int LDQ = LDA;
int mode = 4;
float eps = LAPACKE_slamch_work('e');
float dmax = 1.0;
float rcond = 1.0e6;
int INFO=-1;
PLASMA_enum uplo = PlasmaUpper;
PLASMA_enum vec = PlasmaVec;
int info_ortho = 0;
int info_solution = 0;
int info_reduction = 0;
int LDAxN = LDA*N;
int LDQxN = LDQ*N;
float *A1 = NULL;
float *A2 = (float *)malloc(LDAxN*sizeof(float));
float *Q = NULL;
float *W1 = (float *)malloc(N*sizeof(float));
float *W2 = (float *)malloc(N*sizeof(float));
float *work = (float *)malloc(3*N* sizeof(float));
PLASMA_desc *T;
/* Check if unable to allocate memory */
if ( (!A2) || (!W1) || (!W2) ){
printf("Out of Memory \n ");
return -2;
}
PLASMA_Disable(PLASMA_AUTOTUNING);
PLASMA_Set(PLASMA_TILE_SIZE, 120);
PLASMA_Set(PLASMA_INNER_BLOCK_SIZE, 20);
PLASMA_Enable(PLASMA_WARNINGS);
PLASMA_Enable(PLASMA_ERRORS);
PLASMA_Alloc_Workspace_ssyev(N, N, &T);
/*----------------------------------------------------------
* TESTING SSYEV
*/
/* Initialize A1 */
LAPACKE_slatms_work( LAPACK_COL_MAJOR, N, N,
lapack_const(PlasmaDistSymmetric), ISEED,
lapack_const(PlasmaHermGeev), W1, mode, rcond,
dmax, N, N,
lapack_const(PlasmaNoPacking), A2, LDA, work );
/*
* Sort the eigenvalue because when computing the tridiag
* and then the eigenvalue of the DSTQR are sorted.
* So to avoid testing fail when having good results W1 should be sorted
*/
LAPACKE_slasrt_work( 'I', N, W1 );
if ( vec == PlasmaVec ) {
Q = (float *)malloc(LDQxN*sizeof(float));
A1 = (float *)malloc(LDAxN*sizeof(float));
/* Copy A2 into A1 */
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, 'A', N, N, A2, LDA, A1, LDA);
}
/*
* PLASMA SSYEV
*/
INFO = PLASMA_ssyev(vec, uplo, N, A2, LDA, W2, T, Q, LDQ);
if(INFO!=0){
printf(" ERROR OCCURED INFO %d\n",INFO);
goto fin;
}
printf("\n");
printf("------ TESTS FOR PLASMA SSYEV ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", N, N);
printf("\n");
printf(" The matrix A is randomly generated for each test.\n");
printf("============\n");
printf(" The relative machine precision (eps) is to be %e \n",eps);
printf(" Computational tests pass if scaled residuals are less than 60.\n");
/* Check the orthogonality, reduction and the eigen solutions */
if (vec == PlasmaVec) {
info_ortho = check_orthogonality(N, N, Q, LDQ, eps);
info_reduction = check_reduction(uplo, N, 1, A1, W2, LDA, Q, eps);
}
info_solution = check_solution(N, W1, W2, eps);
if ( (info_solution == 0) & (info_ortho == 0) & (info_reduction == 0) ) {
printf("***************************************************\n");
printf(" ---- TESTING SSYEV ...................... PASSED !\n");
printf("***************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING SSYEV ... FAILED !\n");
printf("************************************************\n");
}
fin:
PLASMA_Dealloc_Handle_Tile(&T);
free(A2);
free(W1);
free(W2);
free(work);
if (Q != NULL) free(Q);
if (A1 != NULL) free(A1);
return 0;
}
/*-------------------------------------------------------------------
* Check the orthogonality of Q
*/
static int check_orthogonality(int M, int N, float *Q, int LDQ, float eps)
{
float done = 1.0;
float mdone = -1.0;
float normQ, result;
int info_ortho;
int minMN = min(M, N);
float *work = (float *)malloc(minMN*sizeof(float));
/* Build the idendity matrix */
float *Id = (float *) malloc(minMN*minMN*sizeof(float));
LAPACKE_slaset_work(LAPACK_COL_MAJOR, 'A', minMN, minMN, 0., 1., Id, minMN);
/* Perform Id - Q'Q */
if (M >= N)
cblas_ssyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, done, Q, LDQ, mdone, Id, N);
else
cblas_ssyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, done, Q, LDQ, mdone, Id, M);
normQ = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'U', minMN, Id, minMN, work);
result = normQ / (minMN * eps);
printf(" ======================================================\n");
printf(" ||Id-Q'*Q||_oo / (N*eps) : %15.3E \n", result );
printf(" ======================================================\n");
if ( isnan(result) || isinf(result) || (result > 60.0) ) {
printf("-- Orthogonality is suspicious ! \n");
info_ortho=1;
}
else {
printf("-- Orthogonality is CORRECT ! \n");
info_ortho=0;
}
free(work); free(Id);
return info_ortho;
}
/*------------------------------------------------------------
* Check the reduction
*/
static int check_reduction(int uplo, int N, int bw, float *A, float *D, int LDA, float *Q, float eps )
{
float zone = 1.0;
float mzone = -1.0;
float *TEMP = (float *)malloc(N*N*sizeof(float));
float *Residual = (float *)malloc(N*N*sizeof(float));
float *work = (float *)malloc(N*sizeof(float));
float Anorm, Rnorm, result;
int info_reduction;
int i;
/* Compute TEMP = Q * LAMBDA */
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, Q, LDA, TEMP, N);
for (i = 0; i < N; i++){
cblas_sscal(N, D[i], &(TEMP[i*N]),1);
}
/* Compute Residual = A - Q * LAMBDA * Q^H */
/* A is Hermetian but both upper and lower
* are assumed valable here for checking
* otherwise it need to be symetrized before
* checking.
*/
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, A, LDA, Residual, N);
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasTrans, N, N, N, (mzone), TEMP, N, Q, LDA, (zone), Residual, N);
Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), N, N, Residual, N, work);
Anorm = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), lapack_const(uplo), N, A, LDA, work);
result = Rnorm / ( Anorm * N * eps);
if ( uplo == PlasmaLower ){
printf(" ======================================================\n");
printf(" ||A-Q*LAMBDA*Q'||_oo/(||A||_oo.N.eps) : %15.3E \n", result );
printf(" ======================================================\n");
}else{
printf(" ======================================================\n");
printf(" ||A-Q'*LAMBDA*Q||_oo/(||A||_oo.N.eps) : %15.3E \n", result );
printf(" ======================================================\n");
}
if ( isnan(result) || isinf(result) || (result > 60.0) ) {
printf("-- Reduction is suspicious ! \n");
info_reduction = 1;
}
else {
printf("-- Reduction is CORRECT ! \n");
info_reduction = 0;
}
free(TEMP); free(Residual);
free(work);
return info_reduction;
}
/*------------------------------------------------------------
* Check the eigenvalues
*/
static int check_solution(int N, float *E1, float *E2, float eps)
{
int info_solution, i;
float resid;
float maxtmp;
float maxel = fabs( fabs(E1[0]) - fabs(E2[0]) );
float maxeig = max( fabs(E1[0]), fabs(E2[0]) );
for (i = 1; i < N; i++){
resid = fabs(fabs(E1[i])-fabs(E2[i]));
maxtmp = max(fabs(E1[i]), fabs(E2[i]));
/* Update */
maxeig = max(maxtmp, maxeig);
maxel = max(resid, maxel );
}
maxel = maxel / (maxeig * N * eps);
printf(" ======================================================\n");
printf(" | D - eigcomputed | / (|D| * N * eps) : %15.3E \n", maxel );
printf(" ======================================================\n");
if ( isnan(maxel) || isinf(maxel) || (maxel > 100) ) {
printf("-- The eigenvalues are suspicious ! \n");
info_solution = 1;
}
else{
printf("-- The eigenvalues are CORRECT ! \n");
info_solution = 0;
}
return info_solution;
}
| {
"alphanum_fraction": 0.5117709438,
"avg_line_length": 32.8571428571,
"ext": "c",
"hexsha": "2cf9cb9cdaf46e357d65b74c7a6965b7d46c8ac6",
"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_ssyev.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_ssyev.c",
"max_line_length": 122,
"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_ssyev.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2748,
"size": 9430
} |
/**
* @file bblas_zaccuracy.c
*
* @brief BBLAS accuracy tests for double_Complex precision.
*
* BBLAS is a software package provided by Univ. of Manchester,
* Univ. of Tennessee.
*
* @version 1.0.0
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-02-20
*
**/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* Code generation
* @precisions normal z -> c d s
**/
#endif
#include "bblas_common.h"
#include <lapacke.h>
#include <cblas.h>
#define COMPLEX
/**
* bblas_zgemm_tolerance computes the forward error
* @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_{\infty} +
* |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f]
*
**/
void bblas_zgemm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, An, Bm, Bn, M, K, N, ldc;
int max_work_size = max(test->maxK,max(test->maxM, test->maxN));
double Anorm, Bnorm, Rnorm, result;
double eps = LAPACKE_dlamch_work('e');
BBLAS_Complex64_t alpha =-1;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Temporary buffer to save (test-arrayC -C_final) */
BBLAS_Complex64_t **C_diff;
C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayC in C_diff */
bblas_zcopy_Cinit(test, C_diff);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
M = test->M[batch_iter];
K = test->K[batch_iter];
N = test->N[batch_iter];
ldc = test->ldc[batch_iter];
if (test->transA[batch_iter] == BblasNoTrans) {
Am = M; An = K;
} else {
Am = K; An = M;
}
if (test->transB[batch_iter] == BblasNoTrans) {
Bm = K; Bn = N;
} else {
Bm = N; Bn = K;
}
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED ) //fixed size
{
M = test->M[first_index];
K = test->K[first_index];
ldc = test->ldc[first_index];
N = test->N[first_index];
if (test->transA[first_index] == BblasNoTrans) {
Am = M; An = K;
} else {
Am = K; An = M;
}
if (test->transB[first_index] == BblasNoTrans) {
Bm = K; Bn = N;
} else {
Bm = N; Bn = K;
}
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
/*Compute the relative error */
result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal: Fixed, Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(C_diff[index]);
}
free(C_diff);
free(work);
}
/**
* bblas_zstarmm_tolerance computes the forward error
* @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_{\infty} +
* |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f]
*
**/
void bblas_zstarmm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, Bm, Bn, N, ldc;
int max_work_size = max(test->maxM, test->maxN);
double Anorm, Bnorm, Rnorm, result;
double eps = LAPACKE_dlamch_work('e');
BBLAS_Complex64_t alpha =-1;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Temporary buffer to save (test-arrayC -C_final) */
BBLAS_Complex64_t **C_diff;
C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayC in C_diff */
bblas_zcopy_Cinit(test, C_diff);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
N = test->N[batch_iter];
ldc = test->ldc[batch_iter];
if(test->side[batch_iter] == BblasLeft )
{
Am = test->M[batch_iter];
} else {
Am = test->N[batch_iter];
}
Bm = test->ldb[batch_iter];
Bn = test->N[batch_iter];
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
result = Rnorm / ((N*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED ) //fixed size
{
N = test->N[first_index];
ldc = test->ldc[first_index];
if(test->side[first_index] == BblasLeft )
{
Am = test->M[first_index];
} else {
Am = test->N[first_index];
}
Bm = test->ldb[first_index];
Bn = test->N[first_index];
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
/*Compute the relative error */
result = Rnorm / ((N*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal: Fixed, Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(C_diff[index]);
}
free(C_diff);
free(work);
}
/**
* bblas_zstark_tolerance computes the forward error
* @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|A\|_1 +
* |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f]
*
**/
void bblas_zstark_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, An, N, K, ldc;
char u;
int max_work_size = max(test->maxK, test->maxN);
double Anorm, ATnorm, Rnorm, result;
double eps = LAPACKE_dlamch_work('e');
double alpha_norm, beta_norm;
BBLAS_Complex64_t alpha =-1;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Temporary buffer to save (test-arrayC -C_final) */
BBLAS_Complex64_t **C_diff;
C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayC in C_diff */
bblas_zcopy_Cinit(test, C_diff);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
N = test->N[batch_iter];
K = test->K[batch_iter];
ldc = test->ldc[batch_iter];
if (test->trans[batch_iter] == BblasNoTrans) {
Am = N; An = K;
} else {
Am = K; An = N;
}
if(test->uplo[batch_iter] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the one norm of A */
ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);
if (test->routine == BBLAS_HERK)
{
beta_norm = cabs(test->beta_herk[batch_iter]);
alpha_norm = cabs(test->alpha_herk[batch_iter]);
}else{
beta_norm = cabs(test->beta[batch_iter]);
alpha_norm = cabs(test->alpha[batch_iter]);
}
result = Rnorm / ((K*alpha_norm*Anorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED ) //fixed size
{
N = test->N[first_index];
K = test->K[first_index];
ldc = test->ldc[first_index];
if (test->trans[first_index] == BblasNoTrans) {
Am = N; An = K;
} else {
Am = K; An = N;
}
if(test->uplo[first_index] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
Rnorm = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the one norm of A */
ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);
if (test->routine == BBLAS_HERK)
{
beta_norm = cabs(test->beta_herk[first_index]);
alpha_norm = cabs(test->alpha_herk[first_index]);
}else{
beta_norm = cabs(test->beta[first_index]);
alpha_norm = cabs(test->alpha[first_index]);
}
/*Compute the relative error */
result = Rnorm / ((K*alpha_norm*Anorm*ATnorm +
beta_norm*test->Cinitnorm[batch_iter])*eps);
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal: Fixed, Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(C_diff[index]);
}
free(C_diff);
free(work);
}
/**
* bblas_zstar2k_tolerance computes the forward error
* @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((K|\alpha|\|A\|_{\infty}\|B\|_1 +
* K|\alpha|\|B\|_{\infty}\|A\|_1 +
* |\beta|\|C_{\mathrm{init}}\|_{\infty})\epsilon).@f]
*
**/
void bblas_zstar2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, An, Bn, Bm, N, K, ldc;
int max_work_size = max(test->maxK, test->maxN);
double Anorm, Bnorm, ATnorm, BTnorm, Rnorm, result;
double beta_norm;
double eps = LAPACKE_dlamch_work('e');
BBLAS_Complex64_t alpha =-1;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Temporary buffer to save (test-arrayC -C_final) */
BBLAS_Complex64_t **C_diff;
C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayC in C_diff */
bblas_zcopy_Cinit(test, C_diff);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
N = test->N[batch_iter];
K = test->K[batch_iter];
ldc = test->ldc[batch_iter];
if (test->trans[batch_iter] == BblasNoTrans) {
Am = N; An = K;
Bn = K;
} else {
Am = K; An = N;
Bn = N;
}
Bm = test->ldb[batch_iter];
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the one norm of A */
ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
/*Compute the one norm of B */
BTnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);
if(test->routine == BBLAS_HER2K)
{
beta_norm = cabs(test->beta_herk[batch_iter]);
}else
{
beta_norm = cabs(test->beta[batch_iter]);
}
result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*BTnorm +
K*cabs(test->alpha[batch_iter])*Bnorm*ATnorm +
beta_norm*test->Cinitnorm[batch_iter])*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED ) //fixed size
{
N = test->N[first_index];
K = test->K[first_index];
ldc = test->ldc[first_index];
if (test->trans[first_index] == BblasNoTrans) {
Am = N; An = K;
Bn = K;
} else {
Am = K; An = N;
Bn = N;
}
Bm = test->ldb[first_index];
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute the error C - C_finial */
cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);
/*Compute the infinity norm of A */
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the one norm of A */
ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm of B */
Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);
/*Compute the one norm of B */
BTnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);
if(test->routine == BBLAS_HER2K)
{
beta_norm = cabs(test->beta_herk[first_index]);
}else
{
beta_norm = cabs(test->beta[first_index]);
}
/*Compute the relative error */
result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*BTnorm +
K*cabs(test->alpha[first_index])*Bnorm*ATnorm +
beta_norm*test->Cinitnorm[batch_iter])*eps);
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal: Fixed, Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(C_diff[index]);
}
free(C_diff);
free(work);
}
/**
* bblas_ztrmm_tolerance computes the forward error
* @f[\|C - C_{\mathrm{seq}}\|_{\infty}/((|\alpha|\|A\|_{\infty}\|B\|_{\infty}N\epsilon).@f]
*
**/
void bblas_ztrmm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **B_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, An, ldb, N, M;
int max_work_size = max(test->maxK, test->maxN);
char u, diag;
double Anorm, Rnorm, result;
double eps = LAPACKE_dlamch_work('e');
BBLAS_Complex64_t alpha =-1;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Temporary buffer to save (test-arrayB -B_final) */
BBLAS_Complex64_t **B_diff;
B_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayB in B_diff */
bblas_zcopy_Binit(test, B_diff);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
N = test->N[batch_iter];
M = test->M[batch_iter];
ldb = test->ldb[batch_iter];
Am = test->lda[batch_iter];
if(test->side[batch_iter] == BblasLeft )
{
An = M;
}else
{
An = N;
}
if(test->uplo[batch_iter] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
if(test->diag[batch_iter] == BblasUnit )
{
diag = 'U';
}else
{
diag = 'N';
}
/*Compute the error B - B_finial */
cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);
/*Infinity norm of the triangular matrix A */
Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,
An, test->arrayA[batch_iter], Am, work);
result = Rnorm/(N*cabs(test->alpha[batch_iter])*Anorm*test->Binitnorm[batch_iter]*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED )
{
N = test->N[first_index];
M = test->M[first_index];
ldb = test->ldb[first_index];
Am = test->lda[first_index];
if(test->side[first_index] == BblasLeft )
{
An = M;
}else
{
An = N;
}
if(test->uplo[first_index] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
if(test->diag[first_index] == BblasUnit )
{
diag = 'U';
}else
{
diag = 'N';
}
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute the error B - B_finial */
cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);
/*Compute the infinity norm associated with the error */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);
/*Infinity norm of the triangular matrix A */
Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,
An, test->arrayA[batch_iter], Am, work);
result = Rnorm/(N*cabs(test->alpha[first_index])*Anorm*test->Binitnorm[batch_iter]*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}
else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(B_diff[index]);
}
free(B_diff);
free(work);
}
/**
* bblas_ztrsm_tolerance computes the backward error
* @f[\|\alpha B - AX \|_{\infty}/((\|A\|_{\infty}\|X\| + |\alpha|\|B\|_{\infty})N\epsilon).@f]
*
**/
void bblas_ztrsm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **B_final)
{
/*Local variables */
int batch_count = test->batch_count;
int batch_iter, first_index = 0;
int Am, An, ldb, N, M;
int max_work_size = max(test->maxK, test->maxN);
char u, diag;
double Anorm, Rnorm, result, Xnorm;
double eps = LAPACKE_dlamch_work('e');
BBLAS_Complex64_t alpha;
double *work = (double *)malloc(max_work_size*sizeof(double));
/*Variable to save the residual alphaB -AX */
BBLAS_Complex64_t **residual;
residual = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));
/*Make a copy of test->arrayB (X) in residual */
bblas_zcopy_Binit(test, residual);
/*Variable size */
if( test->batch_opts == BBLAS_VARIABLE )
{
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
N = test->N[batch_iter];
M = test->M[batch_iter];
ldb = test->ldb[batch_iter];
Am = test->lda[batch_iter];
if(test->side[batch_iter] == BblasLeft )
{
An = M;
}else
{
An = N;
}
if(test->uplo[batch_iter] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
if(test->diag[batch_iter] == BblasUnit )
{
diag = 'U';
}else
{
diag = 'N';
}
/*Compute residual <- AX (ztrmm) */
alpha = 1;
cblas_ztrmm(BblasColMajor, test->side[batch_iter], test->uplo[batch_iter], test->transA[batch_iter],
test->diag[batch_iter], M, N, CBLAS_SADDR(alpha), test->arrayA[batch_iter],
test->lda[batch_iter], residual[batch_iter], ldb);
/*Compute Binit = alpha Binit */
for (int index=0; index < ldb*N; index++)
{
test->Binit[batch_iter][index] = test->alpha[batch_iter]*test->Binit[batch_iter][index];
}
/*Compute the residual <- alpha B - Ax */
alpha= -1;
cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);
/*Compute the infinity norm associated with the residual */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);
/*Infinity norm of the triangular matrix A */
Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,
An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm associated with X (B) */
Xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);
result = Rnorm/(Anorm*Xnorm*N*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}else if( test->batch_opts == BBLAS_FIXED )
{
N = test->N[first_index];
M = test->M[first_index];
ldb = test->ldb[first_index];
Am = test->lda[first_index];
if(test->side[first_index] == BblasLeft )
{
An = M;
}else
{
An = N;
}
if(test->uplo[first_index] == BblasLower )
{
u = 'L';
}else
{
u = 'U';
}
if(test->diag[first_index] == BblasUnit )
{
diag = 'U';
}else
{
diag = 'N';
}
for( batch_iter =0; batch_iter < batch_count ; batch_iter++)
{
/*Compute residual <- AX (ztrmm) */
alpha = 1;
cblas_ztrmm(BblasColMajor, test->side[first_index], test->uplo[first_index], test->transA[first_index],
test->diag[first_index], M, N, CBLAS_SADDR(alpha), (const BBLAS_Complex64_t*) test->arrayA[batch_iter],
test->lda[first_index], residual[batch_iter], ldb);
/*Compute Binit = alpha Binit */
for (int index=0; index < ldb*N; index++)
{
test->Binit[batch_iter][index] = test->alpha[first_index]*test->Binit[batch_iter][index];
}
/*Compute the residual <- alpha B - Ax */
alpha = -1;
cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);
/*Compute the infinity norm associated with the residual */
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);
/*Infinity norm of the triangular matrix A */
Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,
An, test->arrayA[batch_iter], Am, work);
/*Compute the infinity norm associated with X (B) */
Xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);
result = Rnorm/(Anorm*Xnorm*N*eps);
/*Compute the relative error */
switch(test->target)
{
case BBLAS_MKL:
test->mkl_error[batch_iter] = result;
break;
case BBLAS_CUBLAS:
case BBLAS_MAGMA:
test->device_error[batch_iter] = result;
break;
case BBLAS_OTHER:
test->other_error[batch_iter] = result;
break;
default:
printf("In bblas_zcheck_Cfinal, Variable: Target no defined\n");
exit(EXIT_FAILURE);
}
}
}
else
{
bblas_error("bblas_ztesting.c", "wrong batch_opts value");
}
/*Free allocated memory */
for(int index =0; index < batch_count; index++)
{
free(residual[index]);
}
free(residual);
free(work);
}
/**
* Calls bblas_zstar2k_tolerance.
**/
#ifdef COMPLEX
void bblas_zher2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstar2k_tolerance(test, C_final);
}
#endif
/**
* Calls bblas_zstar2k_tolerance.
**/
void bblas_zsyr2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstar2k_tolerance(test, C_final);
}
/**
* Calls bblas_zstark_tolerance.
**/
#ifdef COMPLEX
void bblas_zherk_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstark_tolerance(test, C_final);
}
#endif
/**
* Calls bblas_zstark_tolerance.
**/
void bblas_zsyrk_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstark_tolerance(test, C_final);
}
/**
* Calls bblas_zstarmm_tolerance.
**/
#ifdef COMPLEX
void bblas_zhemm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstarmm_tolerance(test, C_final);
}
#endif
/**
* Calls bblas_zstamm_tolerance.
**/
void bblas_zsymm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)
{
bblas_zstarmm_tolerance(test, C_final);
}
| {
"alphanum_fraction": 0.63273865,
"avg_line_length": 26.7295373665,
"ext": "c",
"hexsha": "524a5bdeee117d354c65151ee8bfdcc656a321c2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "NLAFET/BBLAS-ref",
"max_forks_repo_path": "testing/bblas_zaccuracy.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "NLAFET/BBLAS-ref",
"max_issues_repo_path": "testing/bblas_zaccuracy.c",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "NLAFET/BBLAS-ref",
"max_stars_repo_path": "testing/bblas_zaccuracy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9434,
"size": 30044
} |
#include <stdlib.h>
#include <cblas.h>
#include <lapacke.h>
#include "../../runtime/pcp.h"
#include "tasks.h"
#include "utils.h"
#define BLOCK_SIZE 32
#define MAX_MATRIX_SIZE 1024
#define MAX_NUM_ITER (MAX_MATRIX_SIZE / BLOCK_SIZE)
#define MAX_NUM_THREADS 16
// The matrix partitioning for TRSM and SYRK in each iteration.
//
// A partitioning x of a range 0, ..., n - 1 over p threads is
// represented as an array x[] of length p + 1 such that x[k] is the
// start of the block assigned to thread k and x[k + 1] - x[k] is the
// size of the block assigned to thread k, for k = 0, ..., p - 1.
struct partition
{
// The matrix size.
int matrix_size;
// The block size.
int block_size;
// The number of threads.
int num_threads;
// The number of iterations = ceil(matrix_size, block_size).
int num_iter;
// The partitionings for TRSM.
int trsm[MAX_NUM_ITER][MAX_NUM_THREADS + 1];
// The partitionings for SYRK.
int syrk[MAX_NUM_ITER][MAX_NUM_THREADS + 1];
};
// Barrier used to synchronize the workers between iterations.
static pcp_barrier_t *barrier = NULL;
static struct partition *partition_db[MAX_MATRIX_SIZE + 1][MAX_NUM_THREADS + 1] = {NULL};
static struct partition *partition = NULL;
static double *A;
static int ldA;
static int n;
#define A(i,j) A[(i) + (j) * ldA]
// Initializes the partitioning for TRSM for a given iteration.
//
// Uses uniform row blocks.
static void part_init_trsm(int iter)
{
const int last = partition->matrix_size;
const int first = min(last, (iter + 1) * partition->block_size);
const int size = last - first;
const int p = partition->num_threads;
const int chunk = iceil(size, p);
partition->trsm[iter][0] = first;
partition->trsm[iter][p] = last;
for (int th = 1; th < p; ++th) {
partition->trsm[iter][th] = min(last, partition->trsm[iter][th - 1] + chunk);
}
}
// Initializes the partitioning for SYRK for a given iteration.
static void part_init_syrk(int iter)
{
// Balance the load by flops.
const int last = partition->matrix_size;
const int first = min(last, (iter + 1) * partition->block_size);
const int size = last - first;
const int p = partition->num_threads;
const int total_work = size * (size + 1) / 2;
const int ideal_part_work = total_work / p;
partition->syrk[iter][0] = first;
partition->syrk[iter][p] = last;
for (int k = 1; k < p; ++k) {
partition->syrk[iter][k] = partition->syrk[iter][k - 1];
int work = 0;
while (work < ideal_part_work && partition->syrk[iter][k] < last) {
partition->syrk[iter][k] += 1;
work += partition->syrk[iter][k] - first;
}
if (k == 1) {
partition->syrk[iter][k] = max(partition->syrk[iter][k], partition->syrk[iter][k - 1] + partition->block_size);
partition->syrk[iter][k] = min(partition->syrk[iter][k], last);
}
}
}
// Returns the start of a TRSM block.
static int part_block_start_trsm(int iter, int me)
{
return partition->trsm[iter][me];
}
// Returns the size of a TRSM block.
static int part_block_size_trsm(int iter, int me)
{
return part_block_start_trsm(iter, me + 1) - part_block_start_trsm(iter, me);
}
// Returns the start of a SYRK block.
static int part_block_start_syrk(int iter, int me)
{
return partition->syrk[iter][me];
}
// Returns the size of a SYRK block.
static int part_block_size_syrk(int iter, int me)
{
return part_block_start_syrk(iter, me + 1) - part_block_start_syrk(iter, me);
}
// Initializes the partitioning for given parameters.
//
// Follows this protocol:
// 1) Re-use existing if it matches.
// 2) Load from file if it matches.
// 3) Create from scratch.
static void part_init(int matrix_size, int block_size, int num_threads)
{
// Check if the partitioning is available in the databse.
if (partition_db[matrix_size][num_threads] == NULL) {
// No, create from scratch and save in the database.
partition = malloc(sizeof(*partition));
partition->matrix_size = matrix_size;
partition->block_size = block_size;
partition->num_threads = num_threads;
partition->num_iter = iceil(matrix_size, block_size);
for (int iter = 0; iter < partition->num_iter; ++iter) {
part_init_trsm(iter);
part_init_syrk(iter);
}
partition_db[matrix_size][num_threads] = partition;
} else {
// Yes, reuse from database.
partition = partition_db[matrix_size][num_threads];
}
}
void chol_task_par_reconfigure(int nth)
{
// Choose current size of the worker pool for barrier.
if (barrier != NULL) {
pcp_barrier_destroy(barrier);
}
barrier = pcp_barrier_create(nth);
}
void chol_task_par_finalize(void)
{
if (barrier != NULL) {
pcp_barrier_destroy(barrier);
barrier = NULL;
}
}
static void krnl_chol(int iter)
{
int jp = iter * partition->block_size;
int n = min(partition->matrix_size - jp, partition->block_size);
double *A11 = &A(jp,jp);
LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, A11, ldA);
}
static void krnl_syrk(int iter, int me)
{
// j1 j2
// i g g g g g s
// g g g g g s s
// g g g g g s s s
// g g g g g s s s s
//
// g = gemm
// s = syrk
int jp = iter * partition->block_size;
int i = part_block_start_syrk(iter, me);
int m = part_block_size_syrk(iter, me);
int j1 = jp + partition->block_size;
int j2 = i;
int n1 = j2 - j1;
int k = partition->block_size;
double *A21;
double *A21a, *A21b;
double *A22;
/* SYRK */
if (m > 0) {
A22 = &A(i,j2);
A21 = &A(i,jp);
cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,
m, k,
-1.0, A21, ldA,
1.0, A22, ldA);
}
/* GEMM */
if (m > 0 && n1 > 0) {
A22 = &A(i,j1);
A21a = &A(i,jp);
A21b = &A(j1,jp);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m, n1, k,
-1.0, A21a, ldA,
A21b, ldA,
1.0, A22, ldA);
}
}
static void krnl_trsm(int iter, int me)
{
int jp = iter * partition->block_size;
int i = part_block_start_trsm(iter, me);
int m = part_block_size_trsm(iter, me);
int n = min(partition->matrix_size - jp, partition->block_size);
double *A11 = &A(jp,jp);
double *A21 = &A(i,jp);
if (m > 0) {
cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit,
m, n,
1.0, A11, ldA,
A21, ldA);
}
}
void chol_task_par(void *ptr, int nth, int me)
{
struct chol_task_arg *arg = (struct chol_task_arg*) ptr;
n = arg->n;
A = arg->A;
ldA = arg->ldA;
if (me == 0) {
part_init(n, BLOCK_SIZE, nth);
}
if (me == 0) {
// chol(0)
krnl_chol(0);
}
// Synchronize.
pcp_barrier_wait(barrier);
// Loop over iterations.
for (int iter = 0; iter < partition->num_iter; ++iter) {
const int final_iteration = (iter == partition->num_iter - 1);
// Synchronize
pcp_barrier_wait(barrier);
//
// Phase I: trsm(iter) in //
//
krnl_trsm(iter, me);
// Synchronize
pcp_barrier_wait(barrier);
//
// Phase II: syrk(iter) in // plus chol(iter + 1)
//
krnl_syrk(iter, me);
if (me == 0 && !final_iteration) {
krnl_chol(iter + 1);
}
}
// Synchronize
pcp_barrier_wait(barrier);
}
| {
"alphanum_fraction": 0.5897139926,
"avg_line_length": 25.903654485,
"ext": "c",
"hexsha": "47225be2e9eccc0f722dbab3dfe74901ad64a9ec",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/task-chol-par.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/task-chol-par.c",
"max_line_length": 123,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/task-chol-par.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2274,
"size": 7797
} |
/******************************************************************************
*
* INTEL CONFIDENTIAL
*
* Copyright 2015 Intel Corporation All Rights Reserved.
*
* The source code contained or described herein and all documents related
* to the source code (Material) are owned by Intel Corporation or its
* suppliers or licensors. Title to the Material remains with
* Intel Corporation or its suppliers and licensors. The Material contains
* trade secrets and proprietary and confidential information of Intel or
* its suppliers and licensors. The Material is protected by worldwide
* copyright and trade secret laws and treaty provisions. No part of the
* Material may be used, copied, reproduced, modified, published, uploaded,
* posted, transmitted, distributed, or disclosed in any way without Intel's
* prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or
* delivery of the Materials, either expressly, by implication, inducement,
* estoppel or otherwise. Any license under such intellectual property rights
* must be express and approved by Intel in writing.
*
*
* Workfile: FwUpdateDebug.c
*
* Abstract: macros to wrap dbglog for simple FwUpdate debugging
*
******************************************************************************/
#ifndef __FW_UPDATE_DEBUG_H__
#define __FW_UPDATE_DEBUG_H__
#include <gsl/span>
#include <iostream>
typedef enum
{
PRINT_NONE = 0,
PRINT_CRITICAL = 1,
PRINT_ERROR,
PRINT_WARNING,
PRINT_INFO,
PRINT_DEBUG,
PRINT_DEBUG2,
PRINT_ALL,
} dbg_level;
#define FWCRITICAL(MSG) PRINT(PRINT_CRITICAL, MSG)
#define FWERROR(MSG) PRINT(PRINT_ERROR, MSG)
#define FWWARN(MSG) PRINT(PRINT_WARNING, MSG)
#define FWINFO(MSG) PRINT(PRINT_INFO, MSG)
#define FWDEBUG(MSG) PRINT(PRINT_DEBUG, MSG)
#define FWDEBUG2(MSG) PRINT(PRINT_DEBUG2, MSG)
#define FWDUMP(D, L) DUMP(PRINT_DEBUG, D, L)
#define FW_UPDATE_DEBUG 1
#ifdef FW_UPDATE_DEBUG
extern dbg_level fw_update_get_dbg_level(void);
extern void fw_update_set_dbg_level(dbg_level l);
#define PRINT(LEVEL, MSG) \
do \
{ \
if ((LEVEL) <= fw_update_get_dbg_level()) \
{ \
std::stringstream ss; \
ss << '<' << LEVEL << '>' << __FUNCTION__ << ":" << __LINE__ \
<< ": " << MSG; \
std::cerr << ss.str() << std::endl; \
} \
} while (0)
void _dump(dbg_level lvl, const char* fn, int lineno, const char* bname,
const gsl::span<const uint8_t>& buf);
void _dump(dbg_level lvl, const char* fn, int lineno, const char* bname,
const void* buf, size_t len);
#define DUMP(LEVEL, BUF, ...) \
do \
{ \
if ((LEVEL) <= fw_update_get_dbg_level()) \
{ \
_dump(LEVEL, __FUNCTION__, __LINE__, #BUF, BUF, ##__VA_ARGS__); \
} \
} while (0)
#else /* !FW_UPDATE_DEBUG */
#define PRINT(...)
#define DUMP(...)
#endif /* FW_UPDATE_DEBUG */
#endif /* __FW_UPDATE_DEBUG_H__ */
| {
"alphanum_fraction": 0.5082341018,
"avg_line_length": 39.47,
"ext": "h",
"hexsha": "2344b10ebe062eefe4e03ca8d63e45ccef75c530",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-03-19T15:17:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-17T06:51:02.000Z",
"max_forks_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Intel-BMC/mtd-util",
"max_forks_repo_path": "debug.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4",
"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": "Intel-BMC/mtd-util",
"max_issues_repo_path": "debug.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "708072b62a3cecb520eeaacac88b4f2c2e101fe4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Intel-BMC/mtd-util",
"max_stars_repo_path": "debug.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 723,
"size": 3947
} |
/* -*- C -*- */
/**
* Author: Pierre Schnizer
* Date : January 2003
*/
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <pygsl/general_helpers.h>
#include <pygsl/utils.h>
#include <pygsl/profile.h>
PyGSL_API_EXTERN int
PyGSL_set_error_string_for_callback(PyGSL_error_info * info)
{
PyObject *name_o = NULL;
PyObject *callback;
const char * message = "";
const char * error_description = "";
const char * mmesg;
char * name, msg[1024];
char *formatstring = "For the callback %s evaluted for function %s, an error occured : %s";
FUNC_MESS_BEGIN();
callback = info->callback;
if(info->message){
message = info->message;
}
if(info->error_description){
error_description = info->error_description;
}
if (message == NULL){
mmesg = "Unknown";
}else{
mmesg = message;
}
assert(callback != NULL);
name_o = PyObject_GetAttrString(callback, "__name__");
if (name_o == NULL){
name_o = PyObject_GetAttrString(callback, "func_name");
}
if (name_o == NULL){
PyErr_SetString(PyExc_AttributeError,
"While I was treating an errornous callback object,"
" I found that it had no attribute '__name__'!");
PyGSL_ERROR("Could not get the name of the callback!", GSL_EBADFUNC);
goto fail;
}
if(!PyString_Check(name_o)){
PyErr_SetString(PyExc_TypeError,
" For an errornous callback object,"
" the attribute '__name__' was not a Python string!");
PyGSL_ERROR("Nameobject of the callback was not a string!", GSL_EBADFUNC);
goto fail;
}
name = PyString_AsString(name_o);
/* A non completly standard but safe function. */
FUNC_MESS("\tmakeing string");
snprintf(msg, 1024, formatstring, name, mmesg, error_description);
if(DEBUG > 2){
fprintf(stderr, "ERROR: \t%s", msg);
}
PyGSL_ERROR(msg, GSL_EBADFUNC);
FUNC_MESS_END();
return GSL_EBADFUNC;
/* Py_XDECREF(name_o); ??? */
fail:
return GSL_EBADFUNC;
/* Py_XDECREF(name_o); ??? */
}
PyGSL_API_EXTERN int
PyGSL_pyfloat_to_double(PyObject *object, double *result, PyGSL_error_info *info)
{
PyObject *object1;
char *msg="The object returned to the GSL Function could not be converted to float";
FUNC_MESS_BEGIN();
object1 = PyNumber_Float(object);
if(object1 == NULL){
*result = gsl_nan();
if(info){
info->error_description = msg;
return PyGSL_set_error_string_for_callback(info);
}
DEBUG_MESS(2, "Not from call back treatment, normal error. info = %p", info);
PyGSL_ERROR(msg, GSL_EBADFUNC);
}
*result = PyFloat_AsDouble(object1);
DEBUG_MESS(3, "found a double of %f\n", *result);
Py_DECREF(object1);
PyGSL_INCREASE_float_transform_counter();
FUNC_MESS_END();
return GSL_SUCCESS;
}
PyGSL_API_EXTERN int
PyGSL_pylong_to_uint(PyObject *object, unsigned int *result, PyGSL_error_info *info)
{
int flag;
unsigned long int tmp;
flag =PyGSL_pylong_to_ulong(object, &tmp, info);
*result = (unsigned int) tmp;
return flag;
}
PyGSL_API_EXTERN int
PyGSL_pylong_to_ulong(PyObject *object, unsigned long *result, PyGSL_error_info *info)
{
PyObject *object1;
char *msg="The object returned to the GSL Function could not be converted to unsigned long";
object1 = PyNumber_Long(object);
if(object1 == NULL){
*result = 0;
if(info){
info->error_description = msg;
return PyGSL_set_error_string_for_callback(info);
}
PyGSL_ERROR(msg, GSL_EINVAL);
}
*result = PyLong_AsUnsignedLong(object1);
if(DEBUG>2){
fprintf(stderr, "\t\t%s found a double of %ld\n", __FUNCTION__, *result);
}
Py_DECREF(object1);
PyGSL_INCREASE_float_transform_counter();
return GSL_SUCCESS;
}
PyGSL_API_EXTERN int
PyGSL_pyint_to_int(PyObject *object, int *result, PyGSL_error_info *info)
{
PyObject *object1;
char *msg="The object returned to the GSL Function could not be converted to int";
long tmp;
FUNC_MESS_BEGIN();
object1 = PyNumber_Int(object);
if(object1 == NULL){
*result = INT_MIN;
if(info){
info->error_description = msg;
return PyGSL_set_error_string_for_callback(info);
}
DEBUG_MESS(2, "Not from call back treatment, normal error. info = %p", info);
PyGSL_ERROR(msg, GSL_EINVAL);
}
tmp = PyInt_AsLong(object1);
if(tmp > INT_MAX)
PyGSL_ERROR("Number too big for int", GSL_EINVAL);
else if (tmp < INT_MIN)
PyGSL_ERROR("Number too small for int", GSL_EINVAL);
*result = (int) tmp;
DEBUG_MESS(3, "found a int of %d\n", *result);
Py_DECREF(object1);
FUNC_MESS_END();
return GSL_SUCCESS;
}
/*
* Checks following conditions:
* For No Arguments: Got Py_None and No Error
* For 1 Argument: Got an Object, No None and No Error
* (Is None a legal return for one object? I think so.) On the other hand its a
* callback and Conversions are waiting, so its good not to accept None.
* For 2 Arguments: Got a tuple of approbriate size
*/
#define PyGSL_CHECK_PYTHON_RETURN(object, nargs, info) \
( \
( ( (nargs) == 0 ) && ( object ) && ( Py_None == (object) ) && ( !PyErr_Occurred() ) ) \
|| ( ( (nargs) == 1 ) && ( object ) && ( Py_None != (object) ) && ( !PyErr_Occurred() ) ) \
|| ( ( (nargs) > 1 ) && ( object ) && ( PyTuple_Check((object)) ) && \
( (nargs) == PyTuple_GET_SIZE((object)) ) ) \
) \
? \
GSL_SUCCESS \
: \
PyGSL_check_python_return((object), (nargs), (info))
PyGSL_API_EXTERN int
PyGSL_check_python_return(PyObject *object, int nargs, PyGSL_error_info *info)
{
int tuple_size, flag=-1;
char *msg;
FUNC_MESS_BEGIN();
assert(info);
if(object == NULL && PyErr_Occurred()){
/*
* Error was apparently raised by the function, so lets just add a
* traceback frame ....
*/
info->error_description = "User function raised exception!";
PyGSL_add_traceback(NULL, "Unknown file", info->message, __LINE__);
return GSL_EBADFUNC;
}
if(PyErr_Occurred()){
info->error_description = "Function raised an exception.";
PyGSL_add_traceback(NULL, "Unknown file", info->message, __LINE__);
return GSL_EBADFUNC;
/* return PyGSL_set_error_string_for_callback(info); */
}
/* Expected No argumets */
if(nargs == 0){
if(object != Py_None){
info->error_description = "I expected 0 arguments, but I got an object different from None.";
return PyGSL_set_error_string_for_callback(info);
} else {
return GSL_SUCCESS;
}
}
if(nargs == 1){
if(object == Py_None){
info->error_description = "Expected 1 argument, but None was returned. This value is not acceptable for"
" the following arithmetic calculations.";
return PyGSL_set_error_string_for_callback(info);
} else {
return GSL_SUCCESS;
}
}
if(nargs > 1){
msg = (char *) malloc(256 * sizeof(char));
if(object == Py_None){
snprintf(msg, 256, "I expected %d arguments, but the function returned None!", nargs);
info->error_description = msg;
flag = PyGSL_set_error_string_for_callback(info);
} else if(!PyTuple_Check(object)){
snprintf(msg, 256, "Expected %d arguments, but I didn't get a tuple! "
"Did you just return one argument?.", nargs);
info->error_description = msg;
flag = PyGSL_set_error_string_for_callback(info);
} else {
tuple_size = PyTuple_GET_SIZE(object);
if(tuple_size != nargs){
snprintf(msg, 256, "I expected %d arguments, but the function returned %d arguments! ",
nargs, tuple_size);
info->error_description = msg;
flag = PyGSL_set_error_string_for_callback(info);
} else {
flag = GSL_SUCCESS;
}
}
free(msg);
}
FUNC_MESS_END();
return flag;
}
PyGSL_API_EXTERN void
PyGSL_clear_name(char *name, int size)
{
int j;
for(j = 0; j<size; j++){
if(name[j] == '-')
name[j] = '_';
}
}
| {
"alphanum_fraction": 0.5996779018,
"avg_line_length": 30.0795847751,
"ext": "c",
"hexsha": "3ef94b9faf9bd2f42227dff9b351f0657ec88d94",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/init/general_helpers.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2199,
"size": 8693
} |
#include <gsl/gsl_errno.h>
#include <gsl/block/gsl_block.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/block/block_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.7727272727,
"avg_line_length": 19.8,
"ext": "c",
"hexsha": "493c63d6ccfff66c9b1dd9369adb0ada32166fd9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c",
"max_line_length": 35,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/block.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 52,
"size": 198
} |
/*
* Copyright 2010, Weill Medical College of Cornell University
* All rights reserved.
*
* This software is distributed WITHOUT ANY WARRANTY
* under license "license.txt" included with distribution and
* at http://neurodatabase.org/src/license.
*/
#include <gsl/gsl_vector.h>
#include<gsl/gsl_matrix.h>
#include<gsl/gsl_permutation.h>
#include<gsl/gsl_linalg.h>
#include<gsl/gsl_sf.h>
#include "../shared/toolkit_c.h"
#define BUB_MAXWORDS_LIMIT 100000
struct bub_options{
double lambda_N;
int use_weighting;
double mesh_min;
double mesh_max;
double mesh_inc;
int opt_use_weighting;
double opt_mesh_min;
double opt_mesh_max;
double opt_mesh_inc;
int bag_threshold;
};
int bag1(int N,double m,double *a,double lambda_0,struct bub_options *bubopts);
int bub1(int N,double m,double *a,double lambda_0,int K,int compat,struct bub_options *bubopts);
void make_binom(int N,int meshsize,double *p,double **B_jN);
void make_weight(double *p,int meshsize,double m,int use_weighting,double *f,double *c);
double compute_error(double *a,int N,double m,int compat,struct bub_options *bubopts);
int entropy_bub(struct hist1d *in,struct options_entropy *opts,struct estimate *entropy)
{
double *a;
int *h;
double H;
struct bub_options *bubopts;
double eps,epsm;
int N,i,j,max_bin;
double m;
int status;
N = (*in).P;
if(opts->possible_words_flag==0)
{
if(opts->bub_possible_words_strategy==0)
m = (double)in->C;
else if(opts->bub_possible_words_strategy==1)
m = (double)in->N;
else if(opts->bub_possible_words_strategy==2)
m = MIN(max_possible_words(in,1),BUB_MAXWORDS_LIMIT);
else
m = (double)in->C;
}
else
if(opts->possible_words>0)
m = opts->possible_words;
else
switch((int)(opts->possible_words))
{
case 0: /* Inf */
entropy->value = NAN; /* this value based on piece-meal derivation when m=INFINITY */
return EXIT_SUCCESS;
case -1: /* recommended */
m = (double)in->C;
break;
case -2: /* unique */
m = (double)in->C;
break;
case -3: /* total */
m = (double)in->P;
break;
case -4: /* possible */
m = max_possible_words(in,0);
break;
case -5: /* min_tot_pos */
m = max_possible_words(in,1);
break;
case -6: /* min_lim_tot_pos */
m = MIN(BUB_MAXWORDS_LIMIT,max_possible_words(in,1));
break;
}
/* First find a vector */
a = (double *)malloc((N+1)*sizeof(double));
bubopts = (struct bub_options *)malloc(sizeof(struct bub_options));
(*bubopts).bag_threshold = 20;
if(N<(*bubopts).bag_threshold)
{
(*bubopts).lambda_N = 0;
(*bubopts).mesh_min = 0;
(*bubopts).mesh_max = 1;
(*bubopts).mesh_inc = 1/(5*(double)N);
(*bubopts).use_weighting = 0;
status = bag1(N,m,a,(*opts).bub_lambda_0,bubopts);
}
else
{
eps = (1/(double)N)*1e-10;
epsm = (1/m)*1e-10;
(*bubopts).lambda_N = 1;
(*bubopts).mesh_min = eps;
(*bubopts).mesh_max = MIN(1,3/(double)N)-eps;
(*bubopts).mesh_inc = MIN(1,3/(double)N)/100;
(*bubopts).lambda_N = 1;
(*bubopts).use_weighting = 0;
(*bubopts).opt_mesh_min = epsm;
(*bubopts).opt_mesh_max = MIN(1,3/m)-epsm;
(*bubopts).opt_mesh_inc = MIN(1,3/m)/100;
(*bubopts).opt_use_weighting = 0;
status = bub1(N,m,a,(*opts).bub_lambda_0,(*opts).bub_K,(*opts).bub_compat,bubopts);
}
/* Get counts of counts */
h = (int *)calloc(N+1,sizeof(int));
for(i=0; i<(*in).C; i++)
h[(int)(*in).wordcnt[i]]++;
/* Then compute entropy */
H = 0;
for(j=0; j<=N; j++)
H += a[j]*h[j];
entropy->value = NAT2BIT(H);
free(a);
free(h);
free(bubopts);
return EXIT_SUCCESS; /* TODO return status; reports errors with staverify.m - need to look into these errors and possibly pass them to message structure */
}
int bag1(int N,double m,double *a,double lambda_0,struct bub_options *bubopts)
{
int meshsize;
int i,j;
double *p,*Y,**X,**B_jN,*A_data,**D,*I0,*IN;
double *f,c;
gsl_vector *b,*x,*tau,*norm,*S,*work;
gsl_matrix *A,*V;
int *signum;
int d_status, s_status, status = EXIT_SUCCESS;
meshsize = floor(((*bubopts).mesh_max-(*bubopts).mesh_min)/(*bubopts).mesh_inc)+1;
A = gsl_matrix_calloc(meshsize+(N+1)+2,N+1);
A_data = (*A).data;
X = VectorToMatrixDouble(&A_data[0],meshsize,N+1);
D = VectorToMatrixDouble(&A_data[meshsize*(N+1)],N+1,N+1);
I0 = &A_data[(meshsize+(N+1))*(N+1)];
IN = &A_data[(meshsize+(N+1)+1)*(N+1)];
b = gsl_vector_calloc(meshsize+(N+1)+2);
Y = (*b).data;
/* Make mesh */
p = (double *)malloc(meshsize*sizeof(double));
for(i=0; i<meshsize; i++)
p[i] = (*bubopts).mesh_min + i*(*bubopts).mesh_inc;
/* Make weighting */
f = (double *)malloc(meshsize*sizeof(double));
make_weight(p,meshsize,m,(*bubopts).use_weighting,f,&c);
/* Make H */
for(i=0; i<meshsize; i++)
Y[i] = f[i]*XLOGX(p[i]);
/* Make binomial coefficents */
B_jN = MatrixDouble(meshsize,N+1);
make_binom(N,meshsize,p,B_jN);
for(i=0; i<meshsize; i++)
for(j=0; j<N+1; j++)
X[i][j] = f[i]*B_jN[i][j];
/* Make D */
for(j=0; j<N; j++)
{
D[j][j]=-1*sqrt((double)N)/c;
D[j][j+1]=1*sqrt((double)N)/c;
}
/* Make I0 and IN */
I0[0] = sqrt(((double)N)*lambda_0)/c;
IN[N] = sqrt(((double)N)*(*bubopts).lambda_N)/c;
/* Solve the least squares problem */
V = gsl_matrix_calloc(N+1,N+1);
S = gsl_vector_calloc(N+1);
work = gsl_vector_calloc(N+1);
d_status = gsl_linalg_SV_decomp(A,V,S,work);
if(d_status)
status = EXIT_FAILURE;
x = gsl_vector_calloc(N+1);
s_status = gsl_linalg_SV_solve(A,V,S,b,x);
if(s_status)
status = EXIT_FAILURE;
/* Read out the answer from x */
memcpy(a,(*x).data,(N+1)*sizeof(double));
/* Free memory */
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(x);
FreeMatrixDouble(B_jN);
free(X);
free(D);
free(f);
free(p);
gsl_matrix_free(A);
gsl_vector_free(b);
return status;
}
int bub1(int N,double m,double *a,double lambda_0,int K,int compat,struct bub_options *bubopts)
{
int meshsize;
int i,j,k;
double *p,*Y,**X,**B_jN,*A_data,*b_data,**D,*I0,*IN;
double *f,c;
gsl_vector *b,*x,*tau,*norm,*S,*work;
gsl_matrix *A,*V;
int d_status, s_status, status = EXIT_SUCCESS;
double best_error,max_error,h_MM;
double *a_MM,*a_temp;
int k1;
/* Compute the a coefficients using the Miller-Madow method */
a_MM = (double *)calloc(N+1,sizeof(double));
for(j=0; j<=N; j++)
a_MM[j] = XLOGX((double)j/(double)N) + (1-((double)j/(double)N))/(2*(double)N);
meshsize = floor(((*bubopts).mesh_max-(*bubopts).mesh_min)/(*bubopts).mesh_inc)+1;
/* Make mesh */
p = (double *)malloc(meshsize*sizeof(double));
for(i=0; i<meshsize; i++)
p[i] = (*bubopts).mesh_min + i*(*bubopts).mesh_inc;
/* Make weighting */
f = (double *)malloc(meshsize*sizeof(double));
make_weight(p,meshsize,m,(*bubopts).use_weighting,f,&c);
B_jN = MatrixDouble(meshsize,N+1);
make_binom(N,meshsize,p,B_jN);
best_error = HUGE_VAL;
for(k=0; k<MIN(K,N); k++)
{
k1 = k+1;
a_temp = (double *)calloc(N+1,sizeof(double));
memcpy(a_temp,a_MM,(N+1)*sizeof(double));
/*** MAKE A ***/
A = gsl_matrix_calloc(meshsize+k1+2,k1);
A_data = (*A).data;
X = VectorToMatrixDouble(&A_data[0],meshsize,k1);
D = VectorToMatrixDouble(&A_data[meshsize*k1],k1,k1);
I0 = &A_data[(meshsize+k1)*k1];
IN = &A_data[(meshsize+k1+1)*k1];
/*** MAKE B ***/
b = gsl_vector_calloc(meshsize+k1+2);
b_data = (*b).data;
Y = &b_data[0];
if(compat)
b_data[meshsize+k1+1] = (sqrt((double)N)/c)*a_MM[k];
else
b_data[meshsize+k1+1] = (sqrt((double)N)/c)*a_MM[k1];
for(i=0; i<meshsize; i++)
{
h_MM = 0;
for(j=k1; j<=N; j++)
h_MM += B_jN[i][j]*a_MM[j];
Y[i] = f[i]*(XLOGX(p[i]) - h_MM);
}
for(i=0; i<meshsize; i++)
for(j=0; j<k1; j++)
X[i][j] = f[i]*B_jN[i][j];
/* Make D */
for(j=0; j<k1-1; j++)
{
D[j][j]=-1*sqrt((double)N)/c;
D[j][j+1]=1*sqrt((double)N)/c;
}
/* Make I0 and IN */
I0[0] = sqrt(((double)N)*lambda_0)/c;
IN[k1-1] = sqrt(((double)N)*(*bubopts).lambda_N)/c;
/* Solve the least squares problem */
V = gsl_matrix_calloc(k1,k1);
S = gsl_vector_calloc(k1);
work = gsl_vector_calloc(k1);
d_status = gsl_linalg_SV_decomp(A,V,S,work);
if(d_status)
status = EXIT_FAILURE;
x = gsl_vector_calloc(k1);
s_status = gsl_linalg_SV_solve(A,V,S,b,x);
if(s_status)
status = EXIT_FAILURE;
/* Read out the answer from x */
memcpy(a_temp,(*x).data,k1*sizeof(double));
#ifdef DEBUG
printf("k1=%d\n",k1);
for(j=0; j<=k; j++)
printf("%f ",a_temp[j]);
printf("\n");
#endif
/* Find the error */
max_error = compute_error(a_temp,N,m,compat,bubopts);
if(max_error<best_error)
{
best_error = max_error;
memcpy(a,a_temp,(N+1)*sizeof(double));
}
free(a_temp);
/* Free memory */
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(x);
free(X);
free(D);
gsl_matrix_free(A);
gsl_vector_free(b);
}
free(f);
free(p);
FreeMatrixDouble(B_jN);
free(a_MM);
}
void make_binom(int N,int meshsize,double *p,double **B_jN)
{
int i,j;
double *NCj;
NCj = (double *)calloc(N+1,sizeof(double));
for(j=0; j<N+1; j++)
NCj[j] = gsl_sf_lngamma(N+1)-gsl_sf_lngamma(j+1)-gsl_sf_lngamma(N-j+1);
for(i=0; i<meshsize; i++)
if(p[i]==0)
{
B_jN[i][0]=1;
for(j=1; j<N+1; j++)
B_jN[i][j]=0;
}
else if(p[i]==1)
{
for(j=0; j<N; j++)
B_jN[i][j]=0;
B_jN[i][N]=1;
}
else
{
for(j=0; j<N+1; j++)
B_jN[i][j] = exp(NCj[j] + log(p[i])*j + log(1-p[i])*(N-j));
}
free(NCj);
}
void make_weight(double *p,int meshsize,double m,int use_weighting,double *f,double *c)
{
int i;
for(i=0; i<meshsize; i++)
if(use_weighting && p[i]>1/m)
f[i] = 1./p[i];
else
f[i] = m;
if(use_weighting)
*c = 2;
else
*c = 1;
}
double compute_error(double *a,int N,double m,int compat,struct bub_options *bubopts)
{
int i,j;
double max_bias,max_error,max_variance0,max_variance1;
double *p,*f,**B_jN;
double temp1,temp2,temp3,temp4,temp5;
int meshsize;
double c;
meshsize = floor(((*bubopts).opt_mesh_max-(*bubopts).opt_mesh_min)/(*bubopts).opt_mesh_inc)+1;
/* Make mesh */
p = (double *)malloc(meshsize*sizeof(double));
for(i=0; i<meshsize; i++)
p[i] = (*bubopts).opt_mesh_min + i*(*bubopts).opt_mesh_inc;
/* Make weighting */
f = (double *)malloc(meshsize*sizeof(double));
make_weight(p,meshsize,m,(*bubopts).opt_use_weighting,f,&c);
/* Make B_jN */
B_jN = MatrixDouble(meshsize,N+1);
make_binom(N,meshsize,p,B_jN);
/* Compute the worst-case bias */
max_bias = 0;
for(i=0; i<meshsize; i++)
{
temp1 = 0;
for(j=0; j<N+1; j++)
temp1+=B_jN[i][j]*a[j];
temp2 = f[i]*fabs(temp1 - XLOGX(p[i]));
if(temp2>max_bias)
max_bias = temp2;
}
/* Steele loose bound on variance */
max_variance1 = 0;
for(i=0; i<meshsize; i++)
{
temp3 = 0;
for(j=1; j<N+1; j++)
temp3 += B_jN[i][j]*((double)j/(double)N)*pow(a[j]-a[j-1],2);
temp4 = f[i]*temp3;
if(temp4>max_variance1)
max_variance1 = temp4;
}
if(compat)
max_variance1 *= 4*N*c;
else
max_variance1 *= 2*N*c;
/* McDiarmid bound on variance */
max_variance0 = 0;
for(j=1; j<N+1; j++)
{
temp5 = fabs(a[j]-a[j-1]);
if(temp5>max_variance0)
max_variance0=temp5;
}
max_variance0 = N*pow(max_variance0,2);
#ifdef DEBUG
printf("maxbias=%f maxvariance0=%f maxvariance1=%f\n",max_bias,max_variance0,max_variance1);
#endif
max_error = NAT2BIT(sqrt(pow(max_bias,2) + MIN(max_variance0,max_variance1)));
free(p);
free(f);
FreeMatrixDouble(B_jN);
return max_error;
}
| {
"alphanum_fraction": 0.6338935818,
"avg_line_length": 23.8731808732,
"ext": "c",
"hexsha": "63a45d2e08b08a5fe85180f07c66b3e0249c41fb",
"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": "8db8cbccab674c4b77efaed86086dc6a99e5b9a1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "joaodornas/random-code",
"max_forks_repo_path": "Master-Code/spike/entropy/entropy_bub_c.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8db8cbccab674c4b77efaed86086dc6a99e5b9a1",
"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": "joaodornas/random-code",
"max_issues_repo_path": "Master-Code/spike/entropy/entropy_bub_c.c",
"max_line_length": 156,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8db8cbccab674c4b77efaed86086dc6a99e5b9a1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "joaodornas/random-code",
"max_stars_repo_path": "Master-Code/spike/entropy/entropy_bub_c.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 4025,
"size": 11483
} |
/**
* This file is part of yasimSBML (http://www.labri.fr/perso/ghozlane/metaboflux/about/yasimSBML.php)
* Copyright (C) 2010 Amine Ghozlane from LaBRI and University of Bordeaux 1
*
* yasimSBML is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* yasimSBML 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 Lesser GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file yasimSBML.c
* \brief Main program
* \author {Amine Ghozlane}
* \version 1.0
* \date 27 octobre 2009
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <gsl/gsl_rng.h>
#include <sbml/SBMLTypes.h>
#include "especes.h"
#include "simulation.h"
/**
* \fn int main(int argc, char **argv)
* \author Amine Ghozlane
* \brief Enter in the program for simulated annealing
* \param argc Number of arguments
* \param argv List of arguments
* \return EXIT_SUCCESS Normal stop of the program
*/
int main(int argc, char **argv) {
SBMLDocument_t *file=NULL;
Model_t *mod=NULL;
unsigned int errors = 0;
/*unsigned int level;
unsigned int version;*/
/* File adress */
if (argc <= 2) {
fprintf(stderr, "Usage ./yasimSBML.exe sbml_file.xml number_of_simulation\n");
return 1;
}
/* Load File */
file = readSBML(argv[1]);
errors = SBMLDocument_getNumErrors(file);
/* Error File */
if (errors > 0) {
printf("Encountered the following SBML error(s):\n");
SBMLDocument_printErrors(file, stdout);
printf("Simulation skipped. Please correct the problems above first.\n");
return errors;
}
/*level = SBMLDocument_getLevel(file);
version = SBMLDocument_getVersion(file);
printf("SBML Level : %d, version : %d\n", level, version);*/
/* Testing mod file */
mod = SBMLDocument_getModel(file);
if (mod == NULL)
fprintf(stderr, "Error: file %s doesn't exist!\n", argv[1]);
/*compute_simulation(mod);*/
SBML_compute_simulation_mean(mod,atoi(argv[2]));
/* free memory */
Model_free(mod);
/*SBMLDocument_free(file);*/
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6926085256,
"avg_line_length": 29.0568181818,
"ext": "c",
"hexsha": "d94f83d1176a2a9adf6ad967243b997086b42093",
"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": "bd2067127afaaeccf3292b288797ce90ec9cddc0",
"max_forks_repo_licenses": [
"DOC"
],
"max_forks_repo_name": "aghozlane/yasimSBML",
"max_forks_repo_path": "src/yasimSBML.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"DOC"
],
"max_issues_repo_name": "aghozlane/yasimSBML",
"max_issues_repo_path": "src/yasimSBML.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bd2067127afaaeccf3292b288797ce90ec9cddc0",
"max_stars_repo_licenses": [
"DOC"
],
"max_stars_repo_name": "aghozlane/yasimSBML",
"max_stars_repo_path": "src/yasimSBML.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 693,
"size": 2557
} |
/*
This file is part of the Princeton FCMA Toolbox
Copyright (c) 2013 the authors (see AUTHORS file)
For license terms, please see the LICENSE file.
*/
#ifndef COMMON_H
#define COMMON_H
#include <vector>
#include <map>
#include <list>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <iomanip>
#include <stdlib.h>
// define NDEBUG here to disable assertions
// if/when "release" builds are supported
// #define NDEBUG
#include <cassert>
// nifti1_io.h is from nifticlib http://nifti.nimh.nih.gov
// see README in fcma-toolbox.git/deps/
#include <nifti1_io.h>
// SSE/AVX instrinsics
#if defined(_MSC_VER)
// Microsoft C/C++-compatible compiler */
#include <intrin.h>
#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
// GCC-compatible compiler (gcc,clang,icc) targeting x86/x86-64
#include <x86intrin.h>
#endif
// OpenMP : gcc >= 4.7 or clang-omp http://clang-omp.github.io
#include <omp.h>
// Aligned memory blocks
#ifdef __INTEL_COMPILER
#include <offload.h>
#else
#include <mm_malloc.h>
#endif
#if defined(__GNUC__)
// gcc supports this syntax
#define ALIGNED(x) __attribute__((aligned(x)))
#else
// visual c++, clang, icc
#define ALIGNED(x) __declspec(align(x))
#endif
// BLAS dependency
#ifdef USE_MKL
#include <mkl.h>
#else
typedef int MKL_INT;
#if defined __APPLE__
#include <Accelerate/Accelerate.h>
#else
extern "C" {
#include <cblas.h>
}
#endif
#endif
// Matrix multiplication parameters
#define TINYNUM 1e-4
#define LOGISTICTRHEHOLD 1e-6
#define MAXFILENAMELENGTH 300
#define MAXSUBJS 100
#define MAXTRIALPERSUBJ 100
#define MAXSVMITERATION 20000000
// MPI communication tags
#define COMPUTATIONTAG 1
#define LENGTHTAG 2
#define VOXELCLASSIFIERTAG 3
#define ELAPSETAG 4
#define POSITIONTAG 5
#define SECONDORDERTAG 6
enum Task {
Corr_Based_SVM = 0,
Corr_Based_Dis,
Acti_Based_SVM,
Corr_Sum,
Corr_Mask_Classification,
Corr_Mask_Cross_Validation,
Acti_Mask_Classification,
Acti_Mask_Cross_Validation,
Corr_Visualization,
Marginal_Screening,
Error_Type = -1
};
typedef unsigned long long uint64;
typedef unsigned short uint16;
typedef struct raw_matrix_t {
std::string sname; // subject name (file name without extension)
int sid; // subject id
int row;
int col;
int nx, ny, nz;
float* matrix;
} RawMatrix;
typedef struct trial_data_t {
int nTrials;
int nVoxels;
int nCols;
int* trialLengths; // keep all trials data, subject by subject
int* scs;
float* data; // normalized data for correlation
trial_data_t(int x, int y) : nTrials(x), nVoxels(y) {}
} TrialData;
typedef struct corr_matrix_t {
int sid; // subject id
int tlabel; // trial label
int sr; // starting row id
int step; // row of this matrix
int nVoxels; // col of this matrix
float* matrix;
} CorrMatrix;
// Trial: data structure for the start and end point of a trial
typedef struct trial_t {
int tid;
int sid;
int label;
int sc, ec;
// tid_withinsubj: block id within each subject,
// to be used in averaged matrix of searchlight
int tid_withinsubj;
} Trial;
typedef struct voxel_t {
int* vid; // contains global voxel ids
float* corr_vecs;
float* kernel_matrices; // contains precomputed kernel matrix
int nTrials; // row
int nVoxels; // col
// voxel_t(int x, int y, int z) : vid(x), nTrials(y), nVoxels(z) {}
} Voxel;
typedef struct voxel_Score_t {
int vid;
float score;
} VoxelScore;
// VoxelXYZ: voxel's 3-d coordinates in mm
typedef struct voxelxyz_t {
int x, y, z;
} VoxelXYZ;
typedef ALIGNED(64) struct WIDELOCK_T {
omp_lock_t lock;
} widelock_t;
extern unsigned long long total_count;
#endif
| {
"alphanum_fraction": 0.7217908903,
"avg_line_length": 22.08,
"ext": "h",
"hexsha": "8a3818d3a65b7014ad4fb7b2ea89ce51e74462f1",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-06-08T18:06:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-08-26T19:37:29.000Z",
"max_forks_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_forks_repo_path": "src/common.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_issues_repo_issues_event_max_datetime": "2017-07-27T08:11:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-17T01:05:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_issues_repo_path": "src/common.h",
"max_line_length": 69,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_stars_repo_path": "src/common.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-16T17:34:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-29T04:27:01.000Z",
"num_tokens": 1128,
"size": 3864
} |
/* tsqr.c
*
* Copyright (C) 2015 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module implements the sequential TSQR algorithm
* described in
*
* [1] Demmel, J., Grigori, L., Hoemmen, M. F., and Langou, J.
* "Communication-optimal parallel and sequential QR and LU factorizations",
* UCB Technical Report No. UCB/EECS-2008-89, 2008.
*
* The algorithm operates on a tall least squares system:
*
* [ A_1 ] x = [ b_1 ]
* [ A_2 ] [ b_2 ]
* [ ... ] [ ... ]
* [ A_k ] [ b_k ]
*
* as follows:
*
* 1. Initialize
* a. [Q_1,R_1] = qr(A_1)
* b. z_1 = Q_1^T b_1
* 2. Loop i = 2:k
* a. [Q_i,R_i] = qr( [ R_{i-1} ; A_i ] )
* b. z_i = Q_i^T [ z_{i-1} ; b_i ]
* 3. Output:
* a. R = R_k
* b. Q^T b = z_k
*
* Step 2(a) is optimized to take advantage
* of the sparse structure of the matrix
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multilarge.h>
#include <gsl/gsl_multifit.h>
typedef struct
{
size_t p; /* number of columns of LS matrix */
int init; /* QR system has been initialized */
int svd; /* SVD of R has been computed */
double normb; /* || b || for computing residual norm */
gsl_vector *tau; /* Householder scalars, p-by-1 */
gsl_matrix *R; /* [ R ; A_i ], size p-by-p */
gsl_vector *QTb; /* [ Q^T b ; b_i ], size p-by-1 */
gsl_multifit_linear_workspace *multifit_workspace_p;
} tsqr_state_t;
static void *tsqr_alloc(const size_t p);
static void tsqr_free(void *vstate);
static int tsqr_reset(void *vstate);
static int tsqr_accumulate(gsl_matrix * A, gsl_vector * b,
void * vstate);
static int tsqr_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate);
static int tsqr_rcond(double * rcond, void * vstate);
static int tsqr_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate);
static int tsqr_svd(tsqr_state_t * state);
static double tsqr_householder_transform (double *v0, gsl_vector * v);
static int tsqr_householder_hv (const double tau, const gsl_vector * v, double *w0,
gsl_vector * w);
static int tsqr_householder_hm (const double tau, const gsl_vector * v, gsl_matrix * R,
gsl_matrix * A);
static int tsqr_QR_decomp (gsl_matrix * R, gsl_matrix * A, gsl_vector * tau);
/*
tsqr_alloc()
Allocate workspace for solving large linear least squares
problems using the TSQR approach
Inputs: p - number of columns of LS matrix
Return: pointer to workspace
*/
static void *
tsqr_alloc(const size_t p)
{
tsqr_state_t *state;
if (p == 0)
{
GSL_ERROR_NULL("p must be a positive integer",
GSL_EINVAL);
}
state = calloc(1, sizeof(tsqr_state_t));
if (!state)
{
GSL_ERROR_NULL("failed to allocate tsqr state", GSL_ENOMEM);
}
state->p = p;
state->init = 0;
state->svd = 0;
state->normb = 0.0;
state->R = gsl_matrix_alloc(p, p);
if (state->R == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate R matrix", GSL_ENOMEM);
}
state->QTb = gsl_vector_alloc(p);
if (state->QTb == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate QTb vector", GSL_ENOMEM);
}
state->tau = gsl_vector_alloc(p);
if (state->tau == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate tau vector", GSL_ENOMEM);
}
state->multifit_workspace_p = gsl_multifit_linear_alloc(p, p);
if (state->multifit_workspace_p == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate multifit workspace", GSL_ENOMEM);
}
return state;
}
static void
tsqr_free(void *vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
if (state->R)
gsl_matrix_free(state->R);
if (state->QTb)
gsl_vector_free(state->QTb);
if (state->tau)
gsl_vector_free(state->tau);
if (state->multifit_workspace_p)
gsl_multifit_linear_free(state->multifit_workspace_p);
free(state);
}
static int
tsqr_reset(void *vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
gsl_matrix_set_zero(state->R);
gsl_vector_set_zero(state->QTb);
state->init = 0;
state->svd = 0;
state->normb = 0.0;
return GSL_SUCCESS;
}
/*
tsqr_accumulate()
Add a new block of rows to the QR system
Inputs: A - new block of rows, n-by-p
b - new rhs vector n-by-1
vstate - workspace
Return: success/error
Notes:
1) On output, the upper triangular portion of state->R(1:p,1:p)
contains current R matrix
2) state->QTb(1:p) contains current Q^T b vector
3) A and b are destroyed
*/
static int
tsqr_accumulate(gsl_matrix * A, gsl_vector * b, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
const size_t n = A->size1;
const size_t p = A->size2;
if (p != state->p)
{
GSL_ERROR("columns of A do not match workspace", GSL_EBADLEN);
}
else if (n != b->size)
{
GSL_ERROR("A and b have different numbers of rows", GSL_EBADLEN);
}
else if (state->init == 0)
{
int status;
const size_t npmin = GSL_MIN(n, p);
gsl_vector_view tau = gsl_vector_subvector(state->tau, 0, npmin);
gsl_matrix_view R = gsl_matrix_submatrix(state->R, 0, 0, npmin, p);
gsl_matrix_view Av = gsl_matrix_submatrix(A, 0, 0, npmin, p);
gsl_vector_view QTb = gsl_vector_subvector(state->QTb, 0, npmin);
gsl_vector_view bv = gsl_vector_subvector(b, 0, npmin);
/* this is the first matrix block A_1, compute its (dense) QR decomposition */
/* compute QR decomposition of A */
status = gsl_linalg_QR_decomp(A, &tau.vector);
if (status)
return status;
/* store upper triangular R factor in state->R */
gsl_matrix_tricpy('U', 1, &R.matrix, &Av.matrix);
/* compute ||b|| */
state->normb = gsl_blas_dnrm2(b);
/* compute Q^T b and keep the first p elements */
gsl_linalg_QR_QTvec(A, &tau.vector, b);
gsl_vector_memcpy(&QTb.vector, &bv.vector);
state->init = 1;
return GSL_SUCCESS;
}
else
{
int status;
/* compute QR decomposition of [ R_{i-1} ; A_i ], accounting for
* sparse structure */
status = tsqr_QR_decomp(state->R, A, state->tau);
if (status)
return status;
/* update ||b|| */
state->normb = gsl_hypot(state->normb, gsl_blas_dnrm2(b));
/*
* compute Q^T [ QTb_{i - 1}; b_i ], accounting for the sparse
* structure of the Householder reflectors
*/
{
size_t i;
for (i = 0; i < p; i++)
{
const double ti = gsl_vector_get (state->tau, i);
gsl_vector_const_view h = gsl_matrix_const_column (A, i);
double *wi = gsl_vector_ptr(state->QTb, i);
tsqr_householder_hv (ti, &(h.vector), wi, b);
}
}
return GSL_SUCCESS;
}
}
/*
tsqr_solve()
Solve the least squares system:
chi^2 = || QTb - R x ||^2 + lambda^2 || x ||^2
using the SVD of R
Inputs: lambda - regularization parameter
x - (output) solution vector p-by-1
rnorm - (output) residual norm ||b - A x||
snorm - (output) solution norm ||x||
vstate - workspace
Return: success/error
*/
static int
tsqr_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
const size_t p = x->size;
if (p != state->p)
{
GSL_ERROR("solution vector does not match workspace", GSL_EBADLEN);
}
else
{
int status;
/* compute SVD of R if not already computed */
if (state->svd == 0)
{
status = tsqr_svd(state);
if (status)
return status;
}
status = gsl_multifit_linear_solve(lambda, state->R, state->QTb, x, rnorm, snorm,
state->multifit_workspace_p);
if (status)
return status;
/*
* Since we're solving a reduced square system above, we need
* to account for the full residual vector:
*
* rnorm = || [ Q1^T b - R x ; Q2^T b ] ||
*
* where Q1 is the thin Q factor of X, and Q2
* are the remaining columns of Q. But:
*
* || Q2^T b ||^2 = ||b||^2 - ||Q1^T b||^2
*
* so add this into the rnorm calculation
*/
{
double norm_Q1Tb = gsl_blas_dnrm2(state->QTb);
double ratio = norm_Q1Tb / state->normb;
double diff = 1.0 - ratio*ratio;
if (diff > GSL_DBL_EPSILON)
{
double norm_Q2Tb = state->normb * sqrt(diff);
*rnorm = gsl_hypot(*rnorm, norm_Q2Tb);
}
}
return GSL_SUCCESS;
}
}
/*
tsqr_lcurve()
Compute L-curve of least squares system
Inputs: reg_param - (output) vector of regularization parameters
rho - (output) vector of residual norms
eta - (output) vector of solution norms
vstate - workspace
Return: success/error
*/
static int
tsqr_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
int status;
/* compute SVD of R if not already computed */
if (state->svd == 0)
{
status = tsqr_svd(state);
if (status)
return status;
}
status = gsl_multifit_linear_lcurve(state->QTb, reg_param, rho, eta,
state->multifit_workspace_p);
/* now add contribution to rnorm from Q2 factor */
{
double norm_Q1Tb = gsl_blas_dnrm2(state->QTb);
double ratio = norm_Q1Tb / state->normb;
double diff = 1.0 - ratio*ratio;
size_t i;
if (diff > GSL_DBL_EPSILON)
{
double norm_Q2Tb = state->normb * sqrt(diff);
for (i = 0; i < rho->size; ++i)
{
double *rhoi = gsl_vector_ptr(rho, i);
*rhoi = gsl_hypot(*rhoi, norm_Q2Tb);
}
}
}
return status;
}
static int
tsqr_rcond(double * rcond, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
/* compute SVD of R if not already computed */
if (state->svd == 0)
{
int status = tsqr_svd(state);
if (status)
return status;
}
*rcond = gsl_multifit_linear_rcond(state->multifit_workspace_p);
return GSL_SUCCESS;
}
/*
tsqr_svd()
Compute the SVD of the upper triangular
R factor. This allows us to compute the upper/lower
bounds on the regularization parameter and compute
the matrix reciprocal condition number.
Inputs: state - workspace
Return: success/error
*/
static int
tsqr_svd(tsqr_state_t * state)
{
int status;
status = gsl_multifit_linear_svd(state->R, state->multifit_workspace_p);
if (status)
{
GSL_ERROR("error computing SVD of R", status);
}
state->svd = 1;
return GSL_SUCCESS;
}
/*
tsqr_householder_transform()
This routine is an optimized version of
gsl_linalg_householder_transform(), designed for the QR
decomposition of M-by-N matrices of the form:
T = [ R ]
[ A ]
where R is N-by-N upper triangular, and A is (M-N)-by-N dense.
This routine computes a householder transformation (tau,v) of a
x so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will
be a subcolumn of the matrix T, and so its structure will be:
x = [ x0 ] <- 1 nonzero value for the diagonal element of R
[ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1]
[ x ] <- M-N nonzero values for the dense part A
Inputs: v0 - pointer to diagonal element of R
on input, v0 = x0;
v - on input, x vector
on output, householder vector v
*/
static double
tsqr_householder_transform (double *v0, gsl_vector * v)
{
/* replace v[0:M-1] with a householder vector (v[0:M-1]) and
coefficient tau that annihilate v[1:M-1] */
double alpha, beta, tau ;
/* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */
double xnorm = gsl_blas_dnrm2(v);
if (xnorm == 0)
{
return 0.0; /* tau = 0 */
}
alpha = *v0;
beta = - (alpha >= 0.0 ? +1.0 : -1.0) * hypot(alpha, xnorm) ;
tau = (beta - alpha) / beta ;
{
double s = (alpha - beta);
if (fabs(s) > GSL_DBL_MIN)
{
gsl_blas_dscal (1.0 / s, v);
*v0 = beta;
}
else
{
gsl_blas_dscal (GSL_DBL_EPSILON / s, v);
gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);
*v0 = beta;
}
}
return tau;
}
/*
tsqr_householder_hv()
Apply Householder reflector to a vector. The Householder
reflectors are for the QR decomposition of the matrix
[ R ]
[ A ]
where R is p-by-p upper triangular and A is n-by-p dense.
Therefore all relevant components of the Householder
vector are stored in the columns of A, while the components
in R are 0, except for diag(R) which are 1.
The vector w to be transformed is partitioned as
[ w1 ]
[ w2 ]
where w1 is p-by-1 and w2 is n-by-1. The w2 portion
of w is transformed by v, but most of w1 remains unchanged
except for the first element, w0
Inputs: tau - Householder scalar
v - Householder vector, n-by-1
w0 - (input/output)
on input, w1(0);
on output, transformed w1(0)
w - (input/output) n-by-1
on input, vector w2;
on output, P*w2
*/
static int
tsqr_householder_hv (const double tau, const gsl_vector * v, double *w0, gsl_vector * w)
{
/* applies a householder transformation v to vector w */
if (tau == 0)
return GSL_SUCCESS ;
{
double d1, d;
/* compute d1 = v(2:n)' w(2:n) */
gsl_blas_ddot (v, w, &d1);
/* compute d = v'w = w(1) + d1 since v(1) = 1 */
d = *w0 + d1;
/* compute w = w - tau (v) (v'w) */
*w0 -= tau * d;
gsl_blas_daxpy (-tau * d, v, w);
}
return GSL_SUCCESS;
}
/*
tsqr_householder_hm()
Apply Householder reflector to a submatrix of
[ R ]
[ A ]
where R is p-by-p upper triangular and A is n-by-p dense.
The diagonal terms of R are already transformed by
tsqr_householder_transform(), so we just need to operate
on the submatrix A(:,i:p) as well as the superdiagonal
elements of R
Inputs: tau - Householder scalar
v - Householder vector
R - upper triangular submatrix of R, (p-i)-by-(p-i-1)
A - dense submatrix of A, n-by-(p-i)
*/
static int
tsqr_householder_hm (const double tau, const gsl_vector * v, gsl_matrix * R,
gsl_matrix * A)
{
/* applies a householder transformation v,tau to matrix [ R ; A ] */
if (tau == 0.0)
{
return GSL_SUCCESS;
}
else
{
size_t j;
for (j = 0; j < A->size2; j++)
{
double R0j = gsl_matrix_get (R, 0, j);
double wj;
gsl_vector_view A1j = gsl_matrix_column(A, j);
gsl_blas_ddot (&A1j.vector, v, &wj);
wj += R0j;
gsl_matrix_set (R, 0, j, R0j - tau * wj);
gsl_blas_daxpy (-tau * wj, v, &A1j.vector);
}
return GSL_SUCCESS;
}
}
/*
tsqr_QR_decomp()
Compute the QR decomposition of the matrix
[ R ]
[ A ]
where R is p-by-p upper triangular and A is n-by-p dense.
Inputs: R - upper triangular p-by-p matrix
A - dense n-by-p matrix
tau - Householder scalars
*/
static int
tsqr_QR_decomp (gsl_matrix * R, gsl_matrix * A, gsl_vector * tau)
{
const size_t n = A->size1;
const size_t p = R->size2;
if (R->size2 != A->size2)
{
GSL_ERROR ("R and A have different number of columns", GSL_EBADLEN);
}
else if (tau->size != p)
{
GSL_ERROR ("size of tau must be p", GSL_EBADLEN);
}
else
{
size_t i;
for (i = 0; i < p; i++)
{
/* Compute the Householder transformation to reduce the j-th
column of the matrix [ R ; A ] to a multiple of the j-th unit vector,
taking into account the sparse structure of R */
gsl_vector_view c = gsl_matrix_column(A, i);
double *Rii = gsl_matrix_ptr(R, i, i);
double tau_i = tsqr_householder_transform(Rii, &c.vector);
gsl_vector_set (tau, i, tau_i);
/* Apply the transformation to the remaining columns and
update the norms */
if (i + 1 < p)
{
gsl_matrix_view Rv = gsl_matrix_submatrix(R, i, i + 1, p - i, p - (i + 1));
gsl_matrix_view Av = gsl_matrix_submatrix(A, 0, i + 1, n, p - (i + 1));
tsqr_householder_hm (tau_i, &(c.vector), &(Rv.matrix), &(Av.matrix));
}
}
return GSL_SUCCESS;
}
}
static const gsl_multilarge_linear_type tsqr_type =
{
"tsqr",
tsqr_alloc,
tsqr_reset,
tsqr_accumulate,
tsqr_solve,
tsqr_rcond,
tsqr_lcurve,
tsqr_free
};
const gsl_multilarge_linear_type * gsl_multilarge_linear_tsqr =
&tsqr_type;
| {
"alphanum_fraction": 0.6046966732,
"avg_line_length": 25.3328611898,
"ext": "c",
"hexsha": "68033ac5d28c9a08a92eff37cdbb12f45fd28524",
"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": "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/multilarge/tsqr.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge/tsqr.c",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/multilarge/tsqr.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-18T13:15:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-18T13:15:00.000Z",
"num_tokens": 5207,
"size": 17885
} |
#pragma once
#define NOMINMAX
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
#include <sstream>
#include <variant>
#include <codecvt>
#include <locale>
#include <filesystem>
#include <fstream>
#include <chrono>
#include <functional>
#include <numeric>
#include <wrl/client.h>
#include <wil/result.h>
#include <Windows.h>
#include <d3d12.h>
#include <dxcore.h>
#include <gsl/gsl>
#define DML_TARGET_VERSION_USE_LATEST
#include <DirectML.h>
#include <directx/d3dx12.h>
#include "DirectMLX.h"
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <fmt/format.h> | {
"alphanum_fraction": 0.7459807074,
"avg_line_length": 17.7714285714,
"ext": "h",
"hexsha": "0750632a6eb6504d47101405059fd770add3c92e",
"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": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jstoecker/dxdispatch",
"max_forks_repo_path": "src/dxdispatch/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda",
"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": "jstoecker/dxdispatch",
"max_issues_repo_path": "src/dxdispatch/pch.h",
"max_line_length": 37,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "24a73560ee14d4fe99ae859ef6f5df341e4fbbda",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jstoecker/dxdispatch",
"max_stars_repo_path": "src/dxdispatch/pch.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-21T08:11:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-21T08:11:12.000Z",
"num_tokens": 155,
"size": 622
} |
/* Copyright 2017 Peter Williams and collaborators
* Licensed under the MIT License.
*/
#include <Python.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_poly.h>
#define COUNT(arr) (sizeof(arr) / sizeof(arr[0]))
typedef enum result_t {
RESULT_OK = 0,
RESULT_LAMBDA_FAILED = 1,
RESULT_X_FAILED = 2,
RESULT_GSL_ERROR = 3,
RESULT_HIT_CRITICAL_POINT = 4,
} result_t;
typedef enum handedness_t {
R_MODE = 1,
L_MODE = -1,
} handedness_t;
typedef enum wave_filtering_t {
WF_ALL_WAVES = 0,
WF_NO_FORWARD_MODES = 1 << 0,
WF_NO_BACKWARD_MODES = 1 << 1,
} wave_filtering_t;
typedef enum integration_type_t {
ITYPE_BOUNCE_AVERAGED,
ITYPE_LOCAL,
} integration_type_t;
typedef struct parameters_t {
double E; /* dimensionless kinetic energy */
double sin_alpha; /* sine of the pitch angle */
double Omega_e; /* local electron gyrofrequency in rad/s */
handedness_t handedness; /* handedness of wave; `s` in Summers/Shprits notation */
double alpha_star; /* (cyclotron freq / plasma freq)**2 */
double R; /* magnetic wave energy perturbation: (delta B / B)**2 */
double x_m; /* center of wave frequency spectrum in units of cyclotron freq */
double delta_x; /* width of wave frequency spectrum in units of cyclotron freq */
double max_wave_latitude; /* maximum latitude at which waves are found, in radians */
wave_filtering_t wave_filtering; /* which kinds of waves to filter out */
} parameters_t;
typedef struct state_t {
parameters_t p;
integration_type_t itype;
result_t last_error;
double gamma; /* Lorentz factor */
double a; /* See Summers 2005, just after Eqn 24 */
double b; /* See Summers 2005, just after Eqn 25 */
double beta; /* velocity over speed of light */
double latitude; /* current magnetic latitude, radians */
double sin_alpha; /* current sin(alpha); varies since mu is conserved */
double mu; /* current cos(alpha) */
double Omega_e; /* current Omega_e; varies with latitude since it scales as B */
int n_xy; /* Number of resonances encountered */
double x[3]; /* x values of resonances */
double y[3]; /* y values of resonances */
double Q[3]; /* (1 - x cos alpha / y beta) */
double R[3]; /* complex expression in summand */
} state_t;
typedef struct coefficients_t {
double dimensionless_p; /* momentum over (m_0 * c) */
double Daa;
double err_Daa;
double Dap_on_p;
double err_Dpp_on_p2;
double Dpp_on_p2;
double err_Dap_on_p;
} coefficients_t;
static state_t *global_context = NULL;
static char global_err_msg[1024] = "";
static void
s05_error_handler(const char *reason, const char *file, int line, int gsl_errno)
{
/* Go ahead and segfault if global_context is NULL. */
int n;
n = snprintf(global_err_msg, COUNT(global_err_msg),
"%s (%s:%d; %d = %s)", reason, file, line, gsl_errno, gsl_strerror(gsl_errno));
if ((size_t) n > COUNT(global_err_msg))
n = COUNT(global_err_msg) - 1;
global_err_msg[n] = '\0';
global_context->last_error = RESULT_GSL_ERROR;
}
void
summers2005_debug_hook(void)
{
printf("Debug hook called.\n");
}
static gsl_integration_workspace *integ_workspace = NULL; /* We're lame and leak these */
static gsl_poly_complex_workspace *poly5_workspace = NULL;
static gsl_poly_complex_workspace *poly7_workspace = NULL;
const size_t INTEG_WS_SIZE = 512;
const double integ_abs_tol = 0.0;
const double integ_rel_tol = 1e-6;
const int lambda = -1; /* signifies that we're looking at electrons */
const double epsilon = 0.0005446; /* electron-to-proton mass ratio */
const double epsm1 = -0.9994554; /* epsilon - 1; C is lame and can't do the math with consts! */
const double sigma = 2.; /* range of `x` that we consider */
const double pi_on_2nu = 0.89039; /* pi/2nu, nu = sqrt(pi)erf(sigma); see after Shprits 06 Eqn 5 */
static inline result_t
apply_latitude(double latitude, state_t *state)
{
int i;
if (state->last_error != RESULT_OK)
return state->last_error;
state->latitude = latitude;
double scl = cos(latitude); /* sin of colatitude = cos of latitude */
double r = sqrt(4 - 3 * scl * scl) / pow(scl, 6); /* B(lam) / B_eq */
state->Omega_e = state->p.Omega_e * r;
state->sin_alpha = state->p.sin_alpha * sqrt(r);
state->mu = sqrt(1 - state->sin_alpha * state->sin_alpha); /* cos(alpha) */
if (state->mu == 0.) /* happens at the very top of our bounce trajectory */
state->mu = 1e-20;
/* Find the critical `x` and `y` values. We do this following Appendix A
* and Equation 24 of Summers 2005. */
state->n_xy = 0;
double c[5] = { 0 };
double z[8] = { 0 };
const int s = state->p.handedness;
const double a = state->a;
const double a2 = a * a;
const double bm2 = pow(state->beta * state->mu, 2);
c[0] = -a2 * epsilon;
c[1] = a2 * s * epsm1 - 2 * a * epsilon;
c[2] = a2 + 2 * a * s * epsm1 - epsilon + bm2 * (state->b + epsilon);
c[3] = 2 * a + s * epsm1 - bm2 * s * epsm1;
c[4] = 1 - bm2;
gsl_poly_complex_solve(c, 5, poly5_workspace, z);
if (state->last_error != RESULT_OK) {
strncat(global_err_msg, " (while finding x/y roots)", COUNT(global_err_msg) - 1);
return state->last_error;
}
for (i = 0; i < 4; i++) {
if (z[2*i + 1] != 0.) /* Imaginary root? */
continue;
double x = z[2*i];
if (x < 0) /* Non-physical root? */
continue;
if (x < state->p.x_m - sigma * state->p.delta_x || x > state->p.x_m + sigma * state->p.delta_x)
continue; /* Out of waveband? */
double y = (x + state->a) / (state->beta * state->mu);
if ((state->p.wave_filtering & WF_NO_FORWARD_MODES) && y > 0)
continue;
if ((state->p.wave_filtering & WF_NO_BACKWARD_MODES) && y < 0)
continue;
state->x[state->n_xy] = x;
state->y[state->n_xy] = y;
state->n_xy++;
}
if (state->n_xy > 3) {
snprintf(global_err_msg, COUNT(global_err_msg), "expect 0 to 3 X/Y solutions; got %d", state->n_xy);
return RESULT_X_FAILED;
}
/* Now we calculate F(x,y) = dx/dy, following Appendix C of Summers 2005,
* and related values that contribute to the sums in the integrands. `Q`
* is `1 - x cosa / y beta` and `R` is the factor that is in common
* between all three calculations. */
for (i = 0; i < state->n_xy; i++) {
double x = state->x[i];
double y = state->y[i];
c[0] = epsilon * (state->b + epsilon);
c[1] = -0.5 * s * epsm1 * (state->b + 4 * epsilon);
c[2] = 1 - 4 * epsilon + epsilon * epsilon;
c[3] = 2 * s * epsm1;
c[4] = 1.;
double g = gsl_poly_eval(c, 5, x);
double F = y * pow((x - s) * (x + s * epsilon), 2) / (x * g);
state->Q[i] = 1 - x * state->mu / (y * state->beta);
double k0 = pow((x - state->p.x_m) / state->p.delta_x, 2);
double k1 = fabs(state->beta * state->mu - F);
if (k1 < 1e-5) {
snprintf(global_err_msg, COUNT(global_err_msg), "hit a critical point (%f, %f, %f)",
state->sin_alpha, x, y);
return RESULT_HIT_CRITICAL_POINT;
}
state->R[i] = state->p.R * fabs(F) * exp(-k0) / (state->p.delta_x * k1);
}
return RESULT_OK;
}
typedef double (*gsl_signature)(double, void *);
static double
daa_integrand(double latitude, state_t *state)
{
result_t r;
if (state->last_error != RESULT_OK)
return 0;
if ((r = apply_latitude(latitude, state)) != RESULT_OK) {
state->last_error = r;
return 0;
}
int i;
double v = 0;
for (i = 0; i < state->n_xy; i++)
v += state->R[i] * pow(state->Q[i], 2);
if (state->itype == ITYPE_BOUNCE_AVERAGED)
v *= state->mu * pow(cos(state->latitude), 7);
return v * state->Omega_e;
}
static double
dap_on_p_integrand(double latitude, state_t *state)
{
result_t r;
if (state->last_error != RESULT_OK)
return 0;
if ((r = apply_latitude(latitude, state)) != RESULT_OK) {
state->last_error = r;
return 0;
}
int i;
double v = 0;
for (i = 0; i < state->n_xy; i++)
v += state->R[i] * state->Q[i] * state->x[i] / state->y[i];
/* Here we transform the sqrt(1 + 3 sin^2 lambda) term to use the cos
* instead */
double cos_lam = cos(state->latitude);
double sa = state->sin_alpha;
if (state->itype == ITYPE_BOUNCE_AVERAGED)
v *= state->mu * cos_lam * sqrt(4 - 3 * cos_lam * cos_lam) / sa;
return v * state->Omega_e * sa;
}
static double
dpp_on_p2_integrand(double latitude, state_t *state)
{
result_t r;
if (state->last_error != RESULT_OK)
return 0;
if ((r = apply_latitude(latitude, state)) != RESULT_OK) {
state->last_error = r;
return 0;
}
int i;
double v = 0;
for (i = 0; i < state->n_xy; i++)
v += state->R[i] * pow(state->x[i] / state->y[i], 2);
/* Same transform as in dap_on_p. */
double cos_lam = cos(state->latitude);
double sa = state->sin_alpha;
if (state->itype == ITYPE_BOUNCE_AVERAGED)
v *= cos_lam * sqrt(4 - 3 * cos_lam * cos_lam) / state->mu;
return v * state->Omega_e * sa * sa;
}
static result_t
calc_coefficients(parameters_t *params, coefficients_t *coeffs)
{
gsl_error_handler_t *prev_handler;
gsl_function integrand;
state_t state;
double c[7] = { 0 };
double z[12] = { 0 };
double lambda_m = -1;
double result, abserr, k;
int i;
if (params->sin_alpha > 0.99985) /* ~= 89 degrees */
params->sin_alpha = 0.99985;
global_context = &state;
prev_handler = gsl_set_error_handler(s05_error_handler);
if (integ_workspace == NULL) {
integ_workspace = gsl_integration_workspace_alloc(INTEG_WS_SIZE);
poly5_workspace = gsl_poly_complex_workspace_alloc(5);
poly7_workspace = gsl_poly_complex_workspace_alloc(7);
}
state.p = *params;
state.itype = ITYPE_BOUNCE_AVERAGED;
state.last_error = RESULT_OK;
/* Figure out the mirroring latitude; Shprits (2006) equation 10. */
double f0 = pow(state.p.sin_alpha, 4);
c[0] = -4 * f0;
c[1] = 3 * f0;
c[6] = 1.;
gsl_poly_complex_solve(c, 7, poly7_workspace, z);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while finding lambda_m)", COUNT(global_err_msg) - 1);
return state.last_error;
}
for (i = 0; i < 6; i++) {
if (z[2*i + 1] == 0. && z[2*i] > 0) {
lambda_m = acos(sqrt(z[2*i]));
break;
}
}
if (!(lambda_m >= 0 && lambda_m <= M_PI_2)) {
gsl_set_error_handler(prev_handler);
global_context = NULL;
snprintf(global_err_msg, COUNT(global_err_msg), "failed to compute lambda_m (%.16lf)", lambda_m);
return RESULT_LAMBDA_FAILED;
}
/* It can happen that lambda_m is just a tiiiiiny bit too large such that
* when we compute the sine of the pitch angle at lambda_m, we get
* something bigger than one. Witness our beautiful workaround.
*/
double cos_lat = cos(lambda_m);
if (sqrt(4 - 3 * cos_lat * cos_lat) / (pow(cos_lat, 6) * state.p.sin_alpha * state.p.sin_alpha) > 1.)
lambda_m -= 1e-7;
/* If a latitude limit on waves is imposed, truncate lambda_m further. */
if (lambda_m > state.p.max_wave_latitude)
lambda_m = state.p.max_wave_latitude;
/* Pre-compute quantities that do not depend on lambda. When lambda
* changes, B and alpha change. Consequently Omega_e changes too. In our
* model the other parameters stay fixed.
*/
state.gamma = state.p.E + 1;
state.a = ((int) state.p.handedness) * lambda / state.gamma;
state.b = (1 + epsilon) / state.p.alpha_star;
state.beta = sqrt(state.p.E * (state.p.E + 2)) / (state.p.E + 1);
coeffs->dimensionless_p = state.gamma * state.beta;
/* Shprits 2006 eqn 9, credited to Lencheck+ 1971 and Shultz & Lanzerotti 1974: */
double s0 = 1.38 - 0.32 * (params->sin_alpha + sqrt(params->sin_alpha));
double f1 = pi_on_2nu / (pow(state.p.E + 1, 2) * s0);
/* Let's integrate! First, D_aa. */
integrand.function = (gsl_signature) daa_integrand;
integrand.params = &state;
gsl_integration_qag(
&integrand,
0., /* lower limit */
lambda_m, /* upper limit */
integ_abs_tol,
integ_rel_tol,
INTEG_WS_SIZE, /* allocated workspace size */
GSL_INTEG_GAUSS51, /* integration rule */
integ_workspace, /* workspace */
&result, /* output: value of the integral */
&abserr /* estimated absolute error */
);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Daa)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
k = f1 / (1 - state.p.sin_alpha * state.p.sin_alpha);
coeffs->Daa = result * k;
coeffs->err_Daa = abserr * k;
/* D_ap/p. */
integrand.function = (gsl_signature) dap_on_p_integrand;
gsl_integration_qag(
&integrand,
0., /* lower limit */
lambda_m, /* upper limit */
integ_abs_tol,
integ_rel_tol,
INTEG_WS_SIZE, /* allocated workspace size */
GSL_INTEG_GAUSS51, /* integration rule */
integ_workspace, /* workspace */
&result, /* output: value of the integral */
&abserr /* estimated absolute error */
);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Dap)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
k = -f1 * state.p.sin_alpha / (state.beta * sqrt(1 - state.p.sin_alpha * state.p.sin_alpha));
coeffs->Dap_on_p = result * k;
coeffs->err_Dap_on_p = abserr * fabs(k);
/* D_pp/p^2. */
integrand.function = (gsl_signature) dpp_on_p2_integrand;
gsl_integration_qag(
&integrand,
0., /* lower limit */
lambda_m, /* upper limit */
integ_abs_tol,
integ_rel_tol,
INTEG_WS_SIZE, /* allocated workspace size */
GSL_INTEG_GAUSS51, /* integration rule */
integ_workspace, /* workspace */
&result, /* output: value of the integral */
&abserr /* estimated absolute error */
);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Dpp)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
k = f1 * pow(state.beta, -2);
coeffs->Dpp_on_p2 = result * k;
coeffs->err_Dpp_on_p2 = abserr * k;
/* Huzzah, all done. */
gsl_set_error_handler(prev_handler);
global_context = NULL;
return RESULT_OK;
}
static result_t
calc_unaveraged_coefficients(parameters_t *params, coefficients_t *coeffs)
{
gsl_error_handler_t *prev_handler;
state_t state;
global_context = &state;
prev_handler = gsl_set_error_handler(s05_error_handler);
if (integ_workspace == NULL) {
integ_workspace = gsl_integration_workspace_alloc(INTEG_WS_SIZE);
poly5_workspace = gsl_poly_complex_workspace_alloc(5);
poly7_workspace = gsl_poly_complex_workspace_alloc(7);
}
state.p = *params;
state.itype = ITYPE_LOCAL;
state.last_error = RESULT_OK;
/* The structure here is paralleling calc_coefficients for maintainability. */
state.gamma = state.p.E + 1;
state.a = ((int) state.p.handedness) * lambda / state.gamma;
state.b = (1 + epsilon) / state.p.alpha_star;
state.beta = sqrt(state.p.E * (state.p.E + 2)) / (state.p.E + 1);
coeffs->dimensionless_p = state.gamma * state.beta;
double f1 = pi_on_2nu / pow(state.p.E + 1, 2);
/* Compute! It all works if we pretend latitude = 0 and set `itype` to LOCAL. */
coeffs->Daa = daa_integrand(0., &state);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Daa)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
coeffs->Daa *= f1;
coeffs->err_Daa = 0;
/* D_ap/p. */
coeffs->Dap_on_p = dap_on_p_integrand(0., &state);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Dap)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
coeffs->Dap_on_p *= f1 / state.beta;
coeffs->err_Dap_on_p = 0;
/* D_pp/p^2. */
coeffs->Dpp_on_p2 = dpp_on_p2_integrand(0., &state);
if (state.last_error != RESULT_OK) {
strncat(global_err_msg, " (while computing Dpp)", COUNT(global_err_msg) - 1);
gsl_set_error_handler(prev_handler);
global_context = NULL;
return state.last_error;
}
coeffs->Dpp_on_p2 *= f1 * pow(state.beta, -2);
coeffs->err_Dpp_on_p2 = 0.;
/* Huzzah, all done. */
gsl_set_error_handler(prev_handler);
global_context = NULL;
return RESULT_OK;
}
static PyObject*
get_coeffs(PyObject *self, PyObject* args)
{
int modespec, handspec, wave_filtering;
parameters_t params;
coefficients_t coeffs = { 0 };
result_t r;
if (!PyArg_ParseTuple(args, "iiidddddddd", &modespec, &handspec, &wave_filtering,
¶ms.E,
¶ms.sin_alpha,
¶ms.Omega_e,
¶ms.alpha_star,
¶ms.R,
¶ms.x_m,
¶ms.delta_x,
¶ms.max_wave_latitude))
return NULL;
if (handspec == 0)
params.handedness = R_MODE;
else if (handspec == 1)
params.handedness = L_MODE;
else {
PyErr_SetString(PyExc_RuntimeError, "unexpected handedness magic constant");
return NULL;
}
params.wave_filtering = (wave_filtering_t) wave_filtering;
if (modespec == 0)
r = calc_coefficients(¶ms, &coeffs);
else if (modespec == 1)
r = calc_unaveraged_coefficients(¶ms, &coeffs);
else {
PyErr_SetString(PyExc_RuntimeError, "unexpected mode magic constant");
return NULL;
}
if (r != RESULT_OK) {
PyErr_SetString(PyExc_RuntimeError, global_err_msg);
return NULL;
}
return Py_BuildValue("ddddddd", coeffs.dimensionless_p,
coeffs.Daa, coeffs.err_Daa,
coeffs.Dap_on_p, coeffs.err_Dap_on_p,
coeffs.Dpp_on_p2, coeffs.err_Dpp_on_p2);
}
static PyMethodDef methods[] = {
{ "get_coeffs", get_coeffs, METH_VARARGS|METH_KEYWORDS,
"(mode, handedness, wfilt, E, sa, Oe, a*, R, xm, dx, mwl) -> "
"(dp, daa, udaa, dap/p, udap/p, dpp/p2, udpp/p2)" },
{ NULL, NULL, METH_NOARGS, NULL },
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"_summers2005",
NULL,
0,
methods,
NULL,
NULL,
NULL,
NULL
};
# define INIT_RET_TYPE PyObject *
#else
# define INIT_RET_TYPE void
#endif
INIT_RET_TYPE
PyInit__summers2005(void)
{
#if PY_MAJOR_VERSION >= 3
return PyModule_Create(&module_def);
#else
PyImport_AddModule("_summers2005");
Py_InitModule("_summers2005", methods);
#endif
}
| {
"alphanum_fraction": 0.6116519546,
"avg_line_length": 29.0263543192,
"ext": "c",
"hexsha": "33a149683ae98ed9c65c3181c891a085ef15d340",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-05T06:05:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-05T06:05:40.000Z",
"max_forks_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pkgw/vernon",
"max_forks_repo_path": "vernon/summers2005/impl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25",
"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": "pkgw/vernon",
"max_issues_repo_path": "vernon/summers2005/impl.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9dd52d813722d0932195723cf8c37a5dd2fd0d25",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pkgw/vernon",
"max_stars_repo_path": "vernon/summers2005/impl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5561,
"size": 19825
} |
// for license information, see the accompanying LICENSE file
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
// CBLAS, LAPACKE are f2c translated Netlib F77 reference routines.
// 'cblas.h' is widely supported, and is the f2c translated Netlib F77 refernce version.
// There are known issues with name mangling schemes regarding wrapped code and inter-language operability between Fortran and C.
//
// Netlib CBLAS / LAPACKE target
// #define LISE_LA_REF
// #include <lapacke.h>
// #include <cblas.h>
//
// IBM ESSL target
// #define LISE_LA_ESSL
// #include <essl.h>
//
// Intel MKL target
// #define LISE_LA_MKL
// #include <mkl.h>
#ifdef LISE_LA_MKL
#include <mkl.h>
double ddot(const int *, const double *, const int *, const double *, const int *);
void daxpy(const int *, const double *, const double *, const int *, double *, const int *);
void dgemv(const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
void dcopy(const int *, const double *, const int *, double *, const int *);
void dgemm(const char *, const char *, const int *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
void dgesdd(const char *, const int *, const int *, double *, const int *, double *, double *, const int *, double *, const int *, double *, const int *, int *, int *);
void dger(const int *, const int *, const double *, const double *, const int *, const double *, const int *, double *, const int *);
#endif
#ifdef LISE_LA_ESSL
#include <essl.h>
double ddot(int, const double *, int, const double *,int);
void daxpy(int, double, double *, int, double *, int);
void dgemv(const char *, int, int, double, const void *, int, const double *, int, double, double *, int);
void dcopy(int, double *, int, double *, int);
void dgemm(const char *, const char *, int, int, int, double, const void *, int, const void *, int, double, void *, int);
void dgesdd(const char *, int, int, void *, int, double *, void *, int, void *, int, double *, int, int *, int *);
void dger(int, int, double, const double *, int, const double *, int, void *, int);
// void dger1(int, int, double, const double *, int, const double *, int, void *, int);
#endif
#ifdef LISE_LA_REF
#include <lapacke.h>
#include <cblas.h>
double cblas_ddot(const int N, const double *X, const int incX, const double *Y, const int incY);
void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY);
void cblas_dgemv(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY);
void cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY);
void cblas_dgemm(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc);
void cblas_dger(CBLAS_LAYOUT layout, const int M, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A, const int lda);
lapack_int LAPACKE_dgesdd( int matrix_layout, char jobz, lapack_int m, lapack_int n, double* a, lapack_int lda, double* s, double* u, lapack_int ldu, double* vt, lapack_int ldvt );
#endif
double ddotII( int * , double * , int * , double * , int * ) ;
void daxpyII( int * , double * , double * , int * , double * , int * ) ;
int broyden_minB( double * v_in , double * v_in_old , double * f_old , double * b , double * v_out , const int n , int * it_out , const double alpha ) ;
int broyden_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha ) ;
int broydenMod_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha ) ;
void broyden_min_( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , int * n , int * it_out , double * alpha )
{
broydenMod_min( v_in , v_in_old , f_old , b_bra , b_ket , d , v_out , * n , it_out , * alpha ) ;
}
void broyden_minb_( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * v_out , int * n , int * it_out , double * alpha )
{
broyden_minB( v_in , v_in_old , f_old , b_bra , v_out , * n , it_out , * alpha ) ;
}
int broyden_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha )
{
double * f , * dv , * df ;
int i , ii , it1 ;
int ione = 1 ;
double norm , norm1 , norm2 ;
int n1 , ishift ;
int it ;
it = * it_out ;
n1 = n ;
if( it == 0 )
{
* it_out = 1 ;
for( i = 0 ; i < n ; ++i ) {
v_in_old[ i ] = v_in[ i ] ;
f_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
v_in[ i ] -= f_old[ i ] ;
v_out[ i ] = v_in[ i ] ;
}
return( 0 ) ;
}
assert( f = malloc( n * sizeof( double ) ) ) ;
assert( df = malloc( n * sizeof( double ) ) ) ;
assert( dv = malloc( n * sizeof( double ) ) ) ;
it1 = it - 1 ;
ishift = it1 * n ;
norm = 0. ; /* || F || */
norm1 = 0. ; /* || F_old || */
for( i = 0 ; i < n ; i++ )
{
f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
norm += f[ i ] * f[ i ] ;
norm1 += f_old[ i ] * f_old[ i ] ;
dv[ i ] = v_in[ i ] - v_in_old[ i ] ;
df[ i ] = f[ i ] - f_old[ i ] ;
b_ket[ ishift + i ] = df[ i ] ;
b_bra[ ishift + i ] = dv[ i ] ;
}
for( ii = 0 ; ii < it1 ; ++ii )
{
#ifdef LISE_LA_MKL
norm = d[ ii ] * ddot( &n1 , df , &ione , b_bra + ii * n , &ione ) ;
daxpy( &n1 , &norm , b_ket + ii * n , &ione , b_ket + ishift , &ione ) ;
norm = d[ ii ] * ddot( &n1 , dv , &ione , b_ket + ii * n , &ione ) ;
daxpy( &n1 , &norm , b_bra + ii * n , &ione , b_bra + ishift ,&ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = d[ ii ] * ddot( n1 , df , ione , b_bra + ii * n , ione ) ;
daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;
norm = d[ ii ] * ddot( n1 , dv , ione , b_ket + ii * n , ione ) ;
daxpy( n1 , norm , b_bra + ii * n , ione , b_bra + ishift ,ione ) ;
#endif
#ifdef LISE_LA_REF
//double cblas_ddot(const int N, const double *X, const int incX, const double *Y, const int incY);
//void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY);
norm = d[ ii ] * cblas_ddot( n1 , df , ione , b_bra + ii * n , ione ) ;
cblas_daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;
norm = d[ ii ] * cblas_ddot( n1 , dv , ione , b_ket + ii * n , ione ) ;
cblas_daxpy( n1 , norm , b_bra + ii * n , ione , b_bra + ishift ,ione ) ;
#endif
}
#ifdef LISE_LA_MKL
norm = ddot( &n1 , dv , &ione , b_ket + ishift , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = ddot( n1 , dv , ione , b_ket + ishift , ione ) ;
#endif
#ifdef LISE_LA_REF
norm = cblas_ddot( n1 , dv , ione , b_ket + ishift , ione ) ;
#endif
printf( "<dv|B|df> =%12.6e\n", norm ) ;
if( fabs( norm ) < 1.e-15 ) return( 0 ) ;
for( i = 0 ; i < n ; ++i )
b_ket[ ishift + i ] = ( dv[ i ] - b_ket[ ishift + i ] ) / norm ;
#ifdef LISE_LA_MKL
norm1 = sqrt( ddot( &n1 , b_ket + ishift , &ione , b_ket + ishift , &ione ) ) ;
norm2 = sqrt( ddot( &n1 , b_bra + ishift , &ione , b_bra + ishift , &ione ) ) ;
#endif
#ifdef LISE_LA_ESSL
norm1 = sqrt( ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;
norm2 = sqrt( ddot( n1 , b_bra + ishift , ione , b_bra + ishift , ione ) ) ;
#endif
#ifdef LISE_LA_REF
norm1 = sqrt( cblas_ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;
norm2 = sqrt( cblas_ddot( n1 , b_bra + ishift , ione , b_bra + ishift , ione ) ) ;
#endif
for( i = 0 ; i < n ; i++ )
{
b_ket[ ishift + i ] = b_ket[ ishift + i ] / norm1 ;
b_bra[ ishift + i ] = b_bra[ ishift + i ] / norm2 ;
}
d[ it1 ] = norm1 * norm2 ;
for( i = 0 ; i < n ; i++)
{
v_in_old[ i ] = v_in[ i ] ;
v_in[ i ] -= f[ i ] ;
}
for( ii = 0 ; ii < it ; ii++ )
{
#ifdef LISE_LA_MKL
norm = - d[ ii ] * ddot( &n1 , b_bra + ii * n , &ione , f , &ione ) ;
daxpy( &n1 , &norm , b_ket + ii * n , &ione , v_in , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = - d[ ii ] * ddot( n1 , b_bra + ii * n , ione , f , ione ) ;
daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;
#endif
#ifdef LISE_LA_REF
norm = - d[ ii ] * cblas_ddot( n1 , b_bra + ii * n , ione , f , ione ) ;
cblas_daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;
#endif
}
for( i = 0 ; i < n ; i++ )
{
f_old[ i ] = f[ i ] ;
v_out[ i ] = v_in[ i ] ;
}
( * it_out ) ++ ;
free( f ) ; free( dv ) ; free( df ) ;
return( 0 ) ;
}
int broyden_minB( double * v_in , double * v_in_old , double * f_old , double * b , double * v_out , const int n , int * it_out , const double alpha )
{
double * f , * dv , * df , * bdf , * bdv ;
int i , ii , it1 ;
int ione = 1 ;
double norm , norm1 , norm2 ;
int n1 , ishift ;
int it , j ;
double * u , * vt , * s , * work , wk_[ 2 ] ;
int lwork = -1 , info , * iwork ;
it = * it_out ;
printf( "Starting Broyden %d \n\n" , it ) ;
n1 = n ;
if( it == 0 )
{
* it_out = 1 ;
for( i = 0 ; i < n ; ++i ) {
v_in_old[ i ] = v_in[ i ] ;
f_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
v_in[ i ] -= f_old[ i ] ;
v_out[ i ] = v_in[ i ] ;
for( j = 0 ; j < n ; j++ )
b[ i + n * j ] = 0. ;
b[ i + n * i ] = 1. ;
}
return( 0 ) ;
}
assert( f = malloc( n * sizeof( double ) ) ) ;
assert( df = malloc( n * sizeof( double ) ) ) ;
assert( dv = malloc( n * sizeof( double ) ) ) ;
assert( bdv = malloc( n * sizeof( double ) ) ) ;
assert( bdf = malloc( n * sizeof( double ) ) ) ;
it1 = it - 1 ;
ishift = it1 * n ;
for( i = 0 ; i < n ; i++ )
{
f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
dv[ i ] = v_in[ i ] - v_in_old[ i ] ;
df[ i ] = f[ i ] - f_old[ i ] ;
}
norm = 0. ;
for( i = 0 ; i < n ; i ++ ) {
bdv[ i ] = 0. ;
bdf[ i ] = dv[ i ] ;
for( j = 0 ; j < n ; j++ ){
bdv[ i ] += b[ j + n * i ] * dv[ j ] ;
bdf[ i ] -= b[ i + n * j ] * df[ j ] ;
}
norm += df[ i ] * bdv[ i ] ;
}
printf( "<dv|B|df> =%12.6e\n", norm ) ;
norm = 1./norm ;
#ifdef LISE_LA_REF
cblas_dger( CBLASColMajor, n1 , n1 , norm , bdf , ione , bdv , ione , b , n1 ) ;
#endif
#ifdef LISE_LA_ESSL
dger( n1 , n1 , norm , bdf , ione , bdv , ione , b , n1 ) ;
#endif
#ifdef LISE_LA_MKL
// void dger(const int *, const int *, const double *, const double *, const int *, const double *, const int *, void *, const int *);
dger( &n1 , &n1 , &norm , bdf , &ione , bdv , &ione , b , &n1 ) ;
#endif
if( it > 5 ){
/* add a SVD decomposition of matrix B */
assert( s = malloc( n * sizeof( double ) ) ) ;
assert( u = malloc( n * n * sizeof( double ) ) ) ;
assert( vt = malloc( n * n * sizeof( double ) ) ) ;
assert( iwork = malloc( 8 * n * sizeof( double ) ) ) ;
#ifdef LISE_LA_MKL
dgesdd( "A", &n1 , &n1 , b , &n1 , s , u , &n1 , vt , &n1 , wk_ , &lwork , iwork , &info ) ;
#endif
#ifdef LISE_LA_ESSL
dgesdd( "A", n1 , n1 , b , n1 , s , u , n1 , vt , n1 , wk_ , lwork , iwork , &info ) ;
#endif
#ifdef LISE_LA_REF
info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n1 , n1 , b , n1 , s , u , n1 , vt , n1 ) ;
#endif
lwork = ( int ) wk_[ 0 ] ;
assert( work = malloc( lwork * sizeof( double ) ) ) ;
#ifdef LISE_LA_ESSL
dgesdd( "A" , n1 , n1 , b , n1 , s , u , n1 , vt , n1 , work , lwork , iwork , &info ) ;
#endif
#ifdef LISE_LA_REF
info = LAPACKE_dgesdd(LAPACK_COL_MAJOR, 'A', n1 , n1 , b , n1 , s , u , n1 , vt , n1 ) ;
#endif
#ifdef LISE_LA_MKL
dgesdd( "A", &n1 , &n1 , b , &n1 , s , u , &n1 , vt , &n1 , work , &lwork , iwork , &info ) ;
#endif
free( work ) ; free( iwork ) ;
for( i = 0 ; i < n ; i++ ){
if( s[ i ] < 1.e-6 ) {
printf( " s[ %d ] = %g \n" , i , s[ i ] ) ;
s[ i ] = 0. ;
}
for( j = 0 ; j < n ; j++ )
vt[ i + j * n ] *= s[ i ] ;
}
free( s ) ;
norm = 0. ;
norm1 = 1. ;
#ifdef LISE_LA_ESSL
dgemm( "N" , "N" , n1 , n1 , n1 , norm1 , u , n1 , vt , n1 , norm , b , n1 ) ;
#endif
#ifdef LISE_LA_MKL
// void dgemm(const char *, const char *, const int *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
dgemm( "N" , "N" , &n1 , &n1 , &n1 , &norm1 , u , &n1 , vt , &n1 , &norm , b , &n1 ) ;
#endif
#ifdef LISE_LA_REF
cblas_dgemm(CBLAS_COL_MAJOR,"N" , "N" , n1 , n1 , n1 , norm1 , u , n1 , vt , n1 , norm , b , n1);
#endif
free( u ) ; free( vt ) ;
}
#ifdef LISE_LA_ESSL
dcopy( n1 , v_in , ione , v_in_old , ione ) ;
#endif
#ifdef LISE_LA_MKL
//void dcopy(const int *, const double *, const int *, double *, const int *);
dcopy( &n1 , v_in , &ione , v_in_old , &ione ) ;
#endif
#ifdef LISE_LA_REF
cblas_dcopy( n1 , v_in , ione , v_in_old , ione ) ;
#endif
norm1 = -1. ;
norm = 1. ;
#ifdef LISE_LA_MKL
//void dgemv(const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
dgemv( "N" , &n1 , &n1 , &norm1 , b , &n1 , f , &ione , &norm , v_in , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
dgemv( "N" , n1 , n1 , norm1 , b , n1 , f , ione , norm , v_in , ione ) ;
#endif
#ifdef LISE_LA_REF
cblas_dgemv(CBLAS_COL_MAJOR, "N" , n1 , n1 , norm1 , b , n1 , f , ione , norm , v_in , ione ) ;
#endif
for( i = 0 ; i < n ; i++ )
{
f_old[ i ] = f[ i ] ;
v_out[ i ] = v_in[ i ] ;
}
( * it_out ) ++ ;
free( f ) ; free( dv ) ; free( df ) ; free( bdf ) ; free( bdv ) ;
printf( "Done with Broyden \n\n" ) ;
return( 0 ) ;
}
int broydenMod_min( double * v_in , double * v_in_old , double * f_old , double * b_bra , double * b_ket , double * d , double * v_out , const int n , int * it_out , const double alpha )
/*
Change in the formula. Use Eq. (10) in J.Chem.Phys. 134 (2011) 134109
*/
{
double * f , * dv , * df ;
int i , ii , it1 ;
int ione = 1 ;
double norm , norm1 , norm2 ;
int n1 , ishift ;
int it ;
it = * it_out ;
printf( "Starting Broyden %d \n\n" , it ) ;
n1 = n ;
if( it == 0 )
{
* it_out = 1 ;
for( i = 0 ; i < n ; ++i ) {
v_in_old[ i ] = v_in[ i ] ;
f_old[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
v_in[ i ] -= f_old[ i ] ;
v_out[ i ] = v_in[ i ] ;
}
return( 0 ) ;
}
assert( f = malloc( n * sizeof( double ) ) ) ;
assert( df = malloc( n * sizeof( double ) ) ) ;
assert( dv = malloc( n * sizeof( double ) ) ) ;
it1 = it - 1 ;
ishift = it1 * n ;
norm = 0. ; /* || F || */
norm1 = 0. ; /* || F_old || */
for( i = 0 ; i < n ; i++ )
{
f[ i ] = alpha * ( v_in[ i ] - v_out[ i ] ) ;
norm += f[ i ] * f[ i ] ;
norm1 += f_old[ i ] * f_old[ i ] ;
dv[ i ] = v_in[ i ] - v_in_old[ i ] ;
df[ i ] = f[ i ] - f_old[ i ] ;
b_ket[ ishift + i ] = df[ i ] ;
b_bra[ ishift + i ] = df[ i ] ;
}
for( ii = 0 ; ii < it1 ; ++ii )
{
#ifdef LISE_LA_MKL
norm = d[ ii ] * ddot( &n1 , df , &ione , b_bra + ii * n , &ione ) ;
daxpy( &n1 , &norm , b_ket + ii * n , &ione , b_ket + ishift , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = d[ ii ] * ddot( n1 , df , ione , b_bra + ii * n , ione ) ;
daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;
#endif
#ifdef LISE_LA_REF
norm = d[ ii ] * cblas_ddot( n1 , df , ione , b_bra + ii * n , ione ) ;
cblas_daxpy( n1 , norm , b_ket + ii * n , ione , b_ket + ishift , ione ) ;
#endif
}
#ifdef LISE_LA_MKL
norm = ddot( &n1 , df , &ione , df , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = ddot( n1 , df , ione , df , ione ) ;
#endif
#ifdef LISE_LA_REF
norm = cblas_ddot( n1 , df , ione , df , ione ) ;
#endif
printf( "<df|df> =%12.6e\n", norm ) ;
for( i = 0 ; i < n ; ++i )
b_ket[ ishift + i ] = ( dv[ i ] - b_ket[ ishift + i ] ) / norm ;
#ifdef LISE_LA_MKL
norm1 = sqrt( ddot( &n1 , b_ket + ishift , &ione , b_ket + ishift , &ione ) ) ;
norm2 = sqrt( ddot( &n1 , b_bra + ishift , &ione , b_bra + ishift ,&ione ) ) ;
#endif
#ifdef LISE_LA_ESSL
norm1 = sqrt( ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;
norm2 = sqrt( ddot( n1 , b_bra + ishift , ione , b_bra + ishift ,ione ) ) ;
#endif
#ifdef LISE_LA_REF
norm1 = sqrt( cblas_ddot( n1 , b_ket + ishift , ione , b_ket + ishift , ione ) ) ;
norm2 = sqrt( cblas_ddot( n1 , b_bra + ishift , ione , b_bra + ishift ,ione ) ) ;
#endif
for( i = 0 ; i < n ; i++ )
{
b_ket[ ishift + i ] = b_ket[ ishift + i ] / norm1 ;
b_bra[ ishift + i ] = b_bra[ ishift + i ] / norm2 ;
}
d[ it1 ] = norm1 * norm2 ;
for( i = 0 ; i < n ; i++)
{
v_in_old[ i ] = v_in[ i ] ;
v_in[ i ] -= f[ i ] ;
}
for( ii = 0 ; ii < it ; ii++ )
{
#ifdef LISE_LA_MKL
norm = - d[ ii ] * ddot( &n1 , b_bra + ii * n , &ione , f , &ione ) ;
daxpy( &n1 , &norm , b_ket + ii * n , &ione , v_in , &ione ) ;
#endif
#ifdef LISE_LA_ESSL
norm = - d[ ii ] * ddot( n1 , b_bra + ii * n , ione , f , ione ) ;
daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;
#endif
#ifdef LISE_LA_REF
norm = - d[ ii ] * cblas_ddot( n1 , b_bra + ii * n , ione , f , ione ) ;
cblas_daxpy( n1 , norm , b_ket + ii * n , ione , v_in , ione ) ;
#endif
}
for( i = 0 ; i < n ; i++ )
{
f_old[ i ] = f[ i ] ;
v_out[ i ] = v_in[ i ] ;
}
( * it_out ) ++ ;
free( f ) ; free( dv ) ; free( df ) ;
printf( "Done with Broyden \n\n" ) ;
return( 0 ) ;
}
double ddotII( int * n , double *v1 , int * i1 , double * v2 , int * i2 )
{
double sum = 0. ;
int i ;
for( i = 0 ; i < * n ; i++ )
sum += v1[ i ] * v2[ i ] ;
return( sum ) ;
}
void daxpyII( int * n , double * alpha , double * x , int * i1 , double * y , int * i2 )
{
int i ;
for( i = 0 ; i < * n ; i++ )
y[ i ] += *alpha * x[ i ] ;
}
| {
"alphanum_fraction": 0.5303652359,
"avg_line_length": 25.6917808219,
"ext": "c",
"hexsha": "76bcb0ad284fd7d66a31c80fbb71304aafba79ea",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-03-15T16:02:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-24T00:28:14.000Z",
"max_forks_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dmageeLANL/LISE",
"max_forks_repo_path": "LISE-SLDAsolver/broyden_min.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4",
"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": "dmageeLANL/LISE",
"max_issues_repo_path": "LISE-SLDAsolver/broyden_min.c",
"max_line_length": 254,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "89dfb2ab8456179ad6b97fb6669571799b2bd4f4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dmageeLANL/LISE",
"max_stars_repo_path": "LISE-SLDAsolver/broyden_min.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-03T19:14:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-21T14:58:09.000Z",
"num_tokens": 6950,
"size": 18755
} |
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include "../../include/timing.h"
double* default_vector;
double* default_matrix;
double** results;
int max(int a, int b){
if(a > b) return a;
return b;
}
void save_res_to_csv(double** results, size_t results_c, int stride, int trials, char* file_name){
FILE* csv = fopen(file_name, "w");
if(csv == NULL) perror("Error creating file!");
// header of the .csv
fprintf(csv, "size,trial,result\n" );
// measurement results
for(int i = 0; i < results_c; i++){
for (int j = 0; j < trials; j++) {
fprintf(csv, "%d,%d,%lf\n", i * stride, j, results[i][j]);
}
}
fclose(csv);
}
void init_vector(int max_size, int stride){
int actual_size = max_size * stride;
default_vector = (double*) malloc(actual_size * sizeof(double));
for (int i = 0; i < actual_size; i++) {
default_vector[i] = i;
}
}
void init_matrix(int max_size, int stride){
int actual_size = max_size * stride;
default_matrix = (double*) malloc(actual_size* actual_size * sizeof(double));
for (int i = 0; i < actual_size; i++) {
for (int j = 0; j < actual_size; j++) {
printf("%d,%d\n",i,j );
default_matrix[actual_size * i + j] = actual_size * i + j;
}
}
}
void init_results(int max_size, int trials){
results = (double**) malloc(max_size * sizeof(double*));
for (int i = 0; i < max_size; i++) {
results[i] = (double*) malloc(trials * sizeof(double));
}
}
void cleanup_vector(int max_size, int stride){
free(default_vector);
}
void cleanup_matrix(int max_size, int stride){
int actual_size = max_size * stride;
free(default_matrix);
}
void cleanup_results(int max_size){
for (int i = 0; i < max_size; i++) {
free(results[i]);
}
free(results);
}
double vector_multi_test(int size){
gsl_vector_view tmp = gsl_vector_view_array(default_vector, size);
double res;
double start = get_real_time();
gsl_blas_ddot(&tmp.vector, &tmp.vector, &res);
double end = get_real_time();
return end - start;
}
double matrix_multi_test(int size){
gsl_vector_view tmp_v = gsl_vector_view_array(default_vector, size);
gsl_matrix_view tmp_m = gsl_matrix_view_array(default_matrix, size, size);
double res;
double start = get_real_time();
gsl_blas_dgemv(CblasNoTrans, 1, &tmp_m.matrix, &tmp_v.vector, 0, &tmp_v.vector);
double end = get_real_time();
return end - start;
}
void vector_analysis(int max_size, int stride, int trials){
init_vector(max_size, stride);
for(int i = 1; i < max_size; i++){
for (int j = 0; j < trials; j++) {
double res = vector_multi_test(i * stride);
results[i][j] = res;
}
}
save_res_to_csv(results, max_size, stride, trials, "vector_multi.csv");
cleanup_vector(max_size, stride);
}
void matrix_analysis(int max_size, int stride, int trials){
printf("v\n");
init_vector(max_size, stride);
printf("m\n");
init_matrix(max_size, stride);
printf("a\n" );
for(int i = 1; i < max_size; i++){
for (int j = 0; j < trials; j++) {
printf("%d,%d\n",i,j );
double res = matrix_multi_test(i * stride);
results[i][j] = res;
}
}
printf("b\n" );
save_res_to_csv(results, max_size, stride, trials, "matrix_multi.csv");
printf("cleanup_matrix\n");
cleanup_matrix(max_size, stride);
printf("cleanup_vector\n");
cleanup_vector(max_size, stride);
printf("c\n");
}
int
main (void)
{
int vector_max_size = 1000;
int vector_stride = 1000;
int matrix_max_size = 100; //50
int matrix_stride = 100;
int trials = 10;
int results_size = max(vector_max_size, matrix_max_size);
init_results(results_size, trials);
printf("Analyzing vector*vector multiplication.\n" );
vector_analysis(vector_max_size, vector_stride, trials);
printf("Analyzing matrix*vector multiplication.\n" );
// matrix_analysis(matrix_max_size, matrix_stride, trials);
cleanup_results(results_size);
return 0;
}
| {
"alphanum_fraction": 0.6652185024,
"avg_line_length": 25.9139072848,
"ext": "c",
"hexsha": "94eb092f1f34768e4751a0ae9d9df6e2a6ec3b3f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-05-29T10:19:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-10T09:35:51.000Z",
"max_forks_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mprzewie/MOwNiT_2",
"max_forks_repo_path": "lab2/ex1/ex1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"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": "mprzewie/MOwNiT_2",
"max_issues_repo_path": "lab2/ex1/ex1.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d2a492d210d3acfa1246de82c4a9b818956b4271",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mprzewie/MOwNiT_2",
"max_stars_repo_path": "lab2/ex1/ex1.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1086,
"size": 3913
} |
#pragma once
#include "icode_generator.h"
#include <halley/data_structures/hash_map.h>
#include <gsl/gsl>
#include "halley/file/path.h"
namespace YAML
{
class Node;
}
namespace Halley
{
class ECSData;
class ComponentSchema;
class SystemSchema;
class MessageSchema;
class CustomTypeSchema;
class Codegen
{
struct Stats
{
int written = 0;
int skipped = 0;
std::vector<Path> files;
};
public:
using ProgressReporter = std::function<bool(float, String)>;
static void run(Path inDir, Path outDir);
static std::vector<Path> generateCode(const ECSData& data, Path directory);
private:
static bool writeFile(Path path, const char* data, size_t dataSize, bool stub);
static void writeFiles(Path directory, const CodeGenResult& files, Stats& stats);
};
} | {
"alphanum_fraction": 0.7262357414,
"avg_line_length": 19.725,
"ext": "h",
"hexsha": "d900fc143704a4de4acd82d6bb0d33a018785b52",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "code-disaster/halley",
"max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "code-disaster/halley",
"max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_line_length": 83,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "code-disaster/halley",
"max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 198,
"size": 789
} |
#include <cblas.h>
#include <lapacke.h>
#include "math.h"
#include "minimal_opencv.h"
#include "stdbool.h"
#include "stdio.h"
#include "string.h"
#include <limits.h>
#include <stdarg.h>
#include "linmath.h"
#ifdef _WIN32
#define SURVIVE_LOCAL_ONLY
#include <malloc.h>
#define alloca _alloca
#else
#define SURVIVE_LOCAL_ONLY __attribute__((visibility("hidden")))
#endif
SURVIVE_LOCAL_ONLY int cvRound(float f) { return roundf(f); }
#define CV_Error(code, msg) assert(0 && msg); // cv::error( code, msg, CV_Func, __FILE__, __LINE__ )
const int DECOMP_SVD = 1;
const int DECOMP_LU = 2;
void print_mat(const CvMat *M);
static size_t mat_size_bytes(const CvMat *mat) { return (size_t)CV_ELEM_SIZE(mat->type) * mat->cols * mat->rows; }
SURVIVE_LOCAL_ONLY void cvCopy(const CvMat *srcarr, CvMat *dstarr, const CvMat *mask) {
assert(mask == 0 && "This isn't implemented yet");
assert(srcarr->rows == dstarr->rows);
assert(srcarr->cols == dstarr->cols);
assert(dstarr->type == srcarr->type);
memcpy(dstarr->data.db, srcarr->data.db, mat_size_bytes(srcarr));
}
SURVIVE_LOCAL_ONLY void cvGEMM(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta,
CvMat *dst, int tABC) {
int rows1 = (tABC & CV_GEMM_A_T) ? src1->cols : src1->rows;
int cols1 = (tABC & CV_GEMM_A_T) ? src1->rows : src1->cols;
int rows2 = (tABC & CV_GEMM_B_T) ? src2->cols : src2->rows;
int cols2 = (tABC & CV_GEMM_B_T) ? src2->rows : src2->cols;
if (src3) {
int rows3 = (tABC & CV_GEMM_C_T) ? src3->cols : src3->rows;
int cols3 = (tABC & CV_GEMM_C_T) ? src3->rows : src3->cols;
assert(rows3 == dst->rows);
assert(cols3 == dst->cols);
}
// assert(src3 == 0 || beta != 0);
assert(cols1 == rows2);
assert(rows1 == dst->rows);
assert(cols2 == dst->cols);
lapack_int lda = src1->cols;
lapack_int ldb = src2->cols;
if (src3)
cvCopy(src3, dst, 0);
else
beta = 0;
assert(dst->data.db != src1->data.db);
assert(dst->data.db != src2->data.db);
cblas_dgemm(CblasRowMajor, (tABC & CV_GEMM_A_T) ? CblasTrans : CblasNoTrans,
(tABC & CV_GEMM_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha, src1->data.db,
lda, src2->data.db, ldb, beta, dst->data.db, dst->cols);
}
SURVIVE_LOCAL_ONLY void cvMulTransposed(const CvMat *src, CvMat *dst, int order, const CvMat *delta, double scale) {
lapack_int rows = src->rows;
lapack_int cols = src->cols;
lapack_int drows = dst->rows;
assert(drows == cols);
assert(order == 1 ? (dst->cols == src->cols) : (dst->cols == src->rows));
assert(delta == 0 && "This isn't implemented yet");
double beta = 0;
bool isAT = order == 1;
bool isBT = !isAT;
lapack_int dstCols = dst->cols;
cblas_dgemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, cols, dstCols, rows,
scale, src->data.db, cols, src->data.db, cols, beta, dst->data.db, dstCols);
}
SURVIVE_LOCAL_ONLY void *cvAlloc(size_t size) { return malloc(size); }
static void icvCheckHuge(CvMat *arr) {
if ((int64_t)arr->step * arr->rows > INT_MAX)
arr->type &= ~CV_MAT_CONT_FLAG;
}
SURVIVE_LOCAL_ONLY CvMat *cvCreateMatHeader(int rows, int cols, int type) {
type = CV_MAT_TYPE(type);
assert(!(rows < 0 || cols < 0));
int min_step = CV_ELEM_SIZE(type);
assert(!(min_step <= 0));
min_step *= cols;
CvMat *arr = (CvMat *)cvAlloc(sizeof(*arr));
arr->step = min_step;
arr->type = CV_MAT_MAGIC_VAL | type | CV_MAT_CONT_FLAG;
arr->rows = rows;
arr->cols = cols;
arr->data.ptr = 0;
arr->refcount = 0;
arr->hdr_refcount = 1;
icvCheckHuge(arr);
return arr;
}
/* the alignment of all the allocated buffers */
#define CV_MALLOC_ALIGN 16
/* IEEE754 constants and macros */
#define CV_TOGGLE_FLT(x) ((x) ^ ((int)(x) < 0 ? 0x7fffffff : 0))
#define CV_TOGGLE_DBL(x) ((x) ^ ((int64)(x) < 0 ? CV_BIG_INT(0x7fffffffffffffff) : 0))
#define CV_DbgAssert assert
static inline void *cvAlignPtr(const void *ptr, int align) {
CV_DbgAssert((align & (align - 1)) == 0);
return (void *)(((size_t)ptr + align - 1) & ~(size_t)(align - 1));
}
SURVIVE_LOCAL_ONLY void cvCreateData(CvMat *arr) {
if (CV_IS_MAT_HDR_Z(arr)) {
size_t step, total_size;
CvMat *mat = (CvMat *)arr;
step = mat->step;
if (mat->rows == 0 || mat->cols == 0)
return;
if (mat->data.ptr != 0)
CV_Error(CV_StsError, "Data is already allocated");
if (step == 0)
step = CV_ELEM_SIZE(mat->type) * mat->cols;
int64_t _total_size = (int64_t)step * mat->rows + sizeof(int) + CV_MALLOC_ALIGN;
total_size = (size_t)_total_size;
if (_total_size != (int64_t)total_size)
CV_Error(CV_StsNoMem, "Too big buffer is allocated");
mat->refcount = (int *)cvAlloc((size_t)total_size);
mat->data.ptr = (uchar *)cvAlignPtr(mat->refcount + 1, CV_MALLOC_ALIGN);
*mat->refcount = 1;
} else if (CV_IS_MATND_HDR(arr)) {
assert("There is no support for ND types");
} else
CV_Error(CV_StsBadArg, "unrecognized or unsupported array type");
}
SURVIVE_LOCAL_ONLY CvMat *cvCreateMat(int height, int width, int type) {
CvMat *arr = cvCreateMatHeader(height, width, type);
cvCreateData(arr);
return arr;
}
SURVIVE_LOCAL_ONLY double cvInvert(const CvMat *srcarr, CvMat *dstarr, int method) {
lapack_int inf;
lapack_int rows = srcarr->rows;
lapack_int cols = srcarr->cols;
lapack_int lda = srcarr->cols;
cvCopy(srcarr, dstarr, 0);
double *a = dstarr->data.db;
#ifdef DEBUG_PRINT
printf("a: \n");
print_mat(srcarr);
#endif
if (method == DECOMP_LU) {
lapack_int *ipiv = malloc(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols));
inf = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, rows, cols, a, lda, ipiv);
assert(inf == 0);
inf = LAPACKE_dgetri(LAPACK_ROW_MAJOR, rows, a, lda, ipiv);
assert(inf >= 0);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(srcarr);
}
free(ipiv);
} else if (method == DECOMP_SVD) {
// TODO: There is no way this needs this many allocations,
// but in my defense I was very tired when I wrote this code
CvMat *w = cvCreateMat(1, MIN(dstarr->rows, dstarr->cols), dstarr->type);
CvMat *u = cvCreateMat(dstarr->cols, dstarr->cols, dstarr->type);
CvMat *v = cvCreateMat(dstarr->rows, dstarr->rows, dstarr->type);
CvMat *um = cvCreateMat(w->cols, w->cols, w->type);
cvSVD(dstarr, w, u, v, 0);
cvSetZero(um);
for (int i = 0; i < w->cols; i++) {
cvmSet(um, i, i, 1. / w->data.db[i]);
}
CvMat *tmp = cvCreateMat(dstarr->cols, dstarr->rows, dstarr->type);
cvGEMM(v, um, 1, 0, 0, tmp, CV_GEMM_A_T);
cvGEMM(tmp, u, 1, 0, 0, dstarr, CV_GEMM_B_T);
cvReleaseMat(&tmp);
cvReleaseMat(&w);
cvReleaseMat(&u);
cvReleaseMat(&v);
cvReleaseMat(&um);
}
return 0;
}
SURVIVE_LOCAL_ONLY CvMat *cvCloneMat(const CvMat *mat) {
CvMat *rtn = cvCreateMat(mat->rows, mat->cols, mat->type);
cvCopy(mat, rtn, 0);
return rtn;
}
SURVIVE_LOCAL_ONLY int cvSolve(const CvMat *Aarr, const CvMat *xarr, CvMat *Barr, int method) {
lapack_int inf;
lapack_int arows = Aarr->rows;
lapack_int acols = Aarr->cols;
lapack_int xcols = xarr->cols;
lapack_int xrows = xarr->rows;
lapack_int lda = acols; // Aarr->step / sizeof(double);
lapack_int type = CV_MAT_TYPE(Aarr->type);
if (method == DECOMP_LU) {
assert(Aarr->cols == Barr->rows);
assert(xarr->rows == Aarr->rows);
assert(Barr->cols == xarr->cols);
assert(type == CV_MAT_TYPE(Barr->type) && (type == CV_32F || type == CV_64F));
cvCopy(xarr, Barr, 0);
CvMat *a_ws = cvCloneMat(Aarr);
lapack_int brows = Barr->rows;
lapack_int bcols = Barr->cols;
lapack_int ldb = bcols; // Barr->step / sizeof(double);
lapack_int *ipiv = malloc(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols));
inf = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, arows, acols, a_ws->data.db, lda, ipiv);
assert(inf >= 0);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(a_ws);
}
#ifdef DEBUG_PRINT
printf("Solve A * x = B:\n");
print_mat(a_ws);
print_mat(Barr);
#endif
inf =
LAPACKE_dgetrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, a_ws->data.db, lda, ipiv, Barr->data.db, ldb);
assert(inf == 0);
free(ipiv);
cvReleaseMat(&a_ws);
} else if (method == DECOMP_SVD) {
#ifdef DEBUG_PRINT
printf("Solve |b - A * x|:\n");
print_mat(Aarr);
print_mat(xarr);
#endif
bool xLargerThanB = xarr->rows > acols;
CvMat *xCpy = 0;
if (xLargerThanB) {
xCpy = cvCloneMat(xarr);
} else {
xCpy = Barr;
memcpy(Barr->data.db, xarr->data.db, mat_size_bytes(xarr));
}
CvMat *aCpy = cvCloneMat(Aarr);
double *S = malloc(sizeof(double) * MIN(arows, acols));
double rcond = -1;
lapack_int *rank = malloc(sizeof(lapack_int) * MIN(arows, acols));
lapack_int inf = LAPACKE_dgelss(LAPACK_ROW_MAJOR, arows, acols, xcols, aCpy->data.db, acols, xCpy->data.db,
xcols, S, rcond, rank);
free(rank);
free(S);
assert(Barr->rows == acols);
assert(Barr->cols == xCpy->cols);
if (xLargerThanB) {
xCpy->rows = acols;
cvCopy(xCpy, Barr, 0);
cvReleaseMat(&xCpy);
}
cvReleaseMat(&aCpy);
#ifdef DEBUG_PRINT
print_mat(Barr);
#endif
assert(inf == 0);
}
return 0;
}
SURVIVE_LOCAL_ONLY void cvTranspose(const CvMat *M, CvMat *dst) {
bool inPlace = M == dst || M->data.db == dst->data.db;
double *src = M->data.db;
CvMat *tmp = 0;
if (inPlace) {
tmp = cvCloneMat(dst);
src = tmp->data.db;
} else {
assert(M->rows == dst->cols);
assert(M->cols == dst->rows);
}
for (unsigned i = 0; i < M->rows; i++) {
for (unsigned j = 0; j < M->cols; j++) {
dst->data.db[j * M->rows + i] = src[i * M->cols + j];
}
}
if (inPlace) {
cvReleaseMat(&tmp);
}
}
SURVIVE_LOCAL_ONLY void cvSVD(CvMat *aarr, CvMat *warr, CvMat *uarr, CvMat *varr, int flags) {
char jobu = 'A';
char jobvt = 'A';
lapack_int inf;
if ((flags & CV_SVD_MODIFY_A) == 0) {
aarr = cvCloneMat(aarr);
}
if (uarr == 0)
jobu = 'N';
if (varr == 0)
jobvt = 'N';
double *pw, *pu, *pv;
lapack_int arows = aarr->rows, acols = aarr->cols;
pw = warr ? warr->data.db : (double *)alloca(sizeof(double) * arows * acols);
pu = uarr ? uarr->data.db : (double *)alloca(sizeof(double) * arows * arows);
pv = varr ? varr->data.db : (double *)alloca(sizeof(double) * acols * acols);
lapack_int ulda = uarr ? uarr->cols : acols;
lapack_int plda = varr ? varr->cols : acols;
double *superb = malloc(sizeof(double) * MIN(arows, acols));
inf = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, aarr->data.db, acols, pw, pu, ulda, pv, plda,
superb);
free(superb);
switch (inf) {
case -6:
assert(false && "matrix has NaNs");
break;
case 0:
break;
default:
assert(inf == 0);
}
if (uarr && (flags & CV_SVD_U_T)) {
cvTranspose(uarr, uarr);
}
if (varr && (flags & CV_SVD_V_T) == 0) {
cvTranspose(varr, varr);
}
if ((flags & CV_SVD_MODIFY_A) == 0) {
cvReleaseMat(&aarr);
}
}
SURVIVE_LOCAL_ONLY void cvSetZero(CvMat *arr) {
for (int i = 0; i < arr->rows; i++)
for (int j = 0; j < arr->cols; j++)
arr->data.db[i * arr->cols + j] = 0;
}
SURVIVE_LOCAL_ONLY void cvSetIdentity(CvMat *arr) {
for (int i = 0; i < arr->rows; i++)
for (int j = 0; j < arr->cols; j++)
arr->data.db[i * arr->cols + j] = i == j;
}
SURVIVE_LOCAL_ONLY void cvReleaseMat(CvMat **mat) {
assert(*(*mat)->refcount == 1);
free((*mat)->refcount);
free(*mat);
*mat = 0;
}
SURVIVE_LOCAL_ONLY double cvDet(const CvMat *M) {
assert(M->rows == M->cols);
assert(M->rows <= 3 && "cvDet unimplemented for matrices >3");
assert(CV_64F == CV_MAT_TYPE(M->type) && "cvDet unimplemented for float");
double *m = M->data.db;
switch (M->rows) {
case 1:
return m[0];
case 2: {
return m[0] * m[3] - m[1] * m[2];
}
case 3: {
double m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7],
m22 = m[8];
return m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20);
}
default:
abort();
}
}
| {
"alphanum_fraction": 0.6452020202,
"avg_line_length": 26.8778280543,
"ext": "c",
"hexsha": "6559be01d5c1afbfaa14547fd7ed1043d1f644da",
"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": "457a0a53c49a656424c51898b1150d0753c39673",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ChristophHaag/libsurvive",
"max_forks_repo_path": "redist/minimal_opencv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457a0a53c49a656424c51898b1150d0753c39673",
"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": "ChristophHaag/libsurvive",
"max_issues_repo_path": "redist/minimal_opencv.c",
"max_line_length": 116,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2e1c2576299035c38ca9b0ea51620530742ea208",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "a1batross/libsurvive",
"max_stars_repo_path": "redist/minimal_opencv.c",
"max_stars_repo_stars_event_max_datetime": "2021-02-06T05:34:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-06T05:34:37.000Z",
"num_tokens": 4185,
"size": 11880
} |
/* randist/erlang.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The sum of N samples from an exponential distribution gives an
Erlang distribution
p(x) dx = x^(n-1) exp (-x/a) / ((n-1)!a^n) dx
for x = 0 ... +infty */
double
gsl_ran_erlang (const gsl_rng * r, const double a, const double n)
{
return gsl_ran_gamma (r, n, a);
}
double
gsl_ran_erlang_pdf (const double x, const double a, const double n)
{
if (x <= 0)
{
return 0 ;
}
else
{
double p;
double lngamma = gsl_sf_lngamma (n);
p = exp ((n - 1) * log (x/a) - x/a - lngamma) / a;
return p;
}
}
| {
"alphanum_fraction": 0.673089701,
"avg_line_length": 27.3636363636,
"ext": "c",
"hexsha": "a990403dacb3dc7443eb534e6dd5b8684245ccb3",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/randist/erlang.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/randist/erlang.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/randist/erlang.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 438,
"size": 1505
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Erhan Kenar $
// $Authors: $
// --------------------------------------------------------------------------
#ifndef OPENMS_DATASTRUCTURES_MATRIX_H
#define OPENMS_DATASTRUCTURES_MATRIX_H
#include <OpenMS/CONCEPT/Macros.h>
#include <cmath> // pow()
#include <iomanip>
#include <vector>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
namespace OpenMS
{
/**
@brief A two-dimensional matrix. Similar to std::vector, but uses a binary
operator(,) for element access.
Think of it as a random access container. You can also generate gray
scale images. This data structure is not designed to be used for linear algebra,
but rather a simple two-dimensional array.
The following member functions of the base class std::vector<ValueType>
can also be used:
<ul>
<li>begin</li>
<li>end</li>
<li>rbegin</li>
<li>rend</li>
<li>front</li>
<li>back</li>
<li>assign</li>
<li>empty</li>
<li>size</li>
<li>capacity</li>
<li>max_size</li>
</ul>
@ingroup Datastructures
*/
template <typename Value>
class Matrix :
protected std::vector<Value>
{
protected:
typedef std::vector<Value> Base;
public:
///@name STL compliance type definitions
//@{
typedef Base container_type;
typedef typename Base::difference_type difference_type;
typedef typename Base::size_type size_type;
typedef typename Base::const_iterator const_iterator;
typedef typename Base::const_reverse_iterator const_reverse_iterator;
typedef typename Base::iterator iterator;
typedef typename Base::reverse_iterator reverse_iterator;
typedef typename Base::const_reference const_reference;
typedef typename Base::pointer pointer;
typedef typename Base::reference reference;
typedef typename Base::value_type value_type;
typedef typename Base::allocator_type allocator_type;
//@}
///@name OpenMS compliance type definitions
//@{
typedef Base ContainerType;
typedef difference_type DifferenceType;
typedef size_type SizeType;
typedef const_iterator ConstIterator;
typedef const_reverse_iterator ConstReverseIterator;
typedef iterator Iterator;
typedef reverse_iterator ReverseIterator;
typedef const_reference ConstReference;
typedef pointer Pointer;
typedef reference Reference;
typedef value_type ValueType;
typedef allocator_type AllocatorType;
//@}
///@name Constructors, assignment, and destructor
//@{
Matrix() :
Base(),
rows_(0),
cols_(0)
{}
Matrix(const SizeType rows, const SizeType cols, ValueType value = ValueType()) :
Base(rows * cols, value),
rows_(rows),
cols_(cols)
{}
Matrix(const Matrix& source) :
Base(source),
rows_(source.rows_),
cols_(source.cols_)
{}
Matrix& operator=(const Matrix& rhs)
{
Base::operator=(rhs);
rows_ = rhs.rows_;
cols_ = rhs.cols_;
return *this;
}
~Matrix() {}
//@}
///@name Accessors
//@{
const_reference operator()(size_type const i, size_type const j) const
{
return getValue(i, j);
}
reference operator()(size_type const i, size_type const j)
{
return getValue(i, j);
}
const_reference getValue(size_type const i, size_type const j) const
{
return Base::operator[](index(i, j));
}
reference getValue(size_type const i, size_type const j)
{
return Base::operator[](index(i, j));
}
void setValue(size_type const i, size_type const j, value_type value)
{
Base::operator[](index(i, j)) = value;
}
/// Return the i-th row of the matrix as a vector.
container_type row(size_type const i) const
{
#ifdef OPENMS_DEBUG
if (i >= rows_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, i, rows_);
#endif
container_type values(cols_);
for (size_type j = 0; j < cols_; j++)
{
values[j] = Base::operator[](index(i, j));
}
return values;
}
/// Return the i-th column of the matrix as a vector.
container_type col(size_type const i) const
{
#ifdef OPENMS_DEBUG
if (i >= cols_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, i, cols_);
#endif
container_type values(rows_);
for (size_type j = 0; j < rows_; j++)
{
values[j] = Base::operator[](index(j, i));
}
return values;
}
//@}
/**
@name Pure access declarations
These make begin(), end() etc. from container_type accessible.
*/
//@{
public:
using Base::begin;
using Base::end;
using Base::rbegin;
using Base::rend;
using Base::front;
using Base::back;
using Base::assign;
using Base::empty;
using Base::size;
using Base::capacity;
using Base::max_size;
//@}
void clear()
{
Base::clear();
rows_ = 0;
cols_ = 0;
}
void resize(size_type i, size_type j, value_type value = value_type())
{
rows_ = i;
cols_ = j;
Base::resize(rows_ * cols_, value);
}
void resize(std::pair<Size, Size> const& size_pair, value_type value = value_type())
{
rows_ = size_pair.first;
cols_ = size_pair.second;
Base::resize(rows_ * cols_, value);
}
/// Number of rows
SizeType rows() const
{
return rows_;
}
/// Number of columns
SizeType cols() const
{
return cols_;
}
std::pair<Size, Size> sizePair() const
{
return std::pair<Size, Size>(rows_, cols_);
}
/**
@brief Calculate the index into the underlying vector from row and column.
Note that Matrix uses the (row,column) lexicographic ordering for indexing.
*/
SizeType const index(SizeType row, SizeType col) const
{
#ifdef OPENMS_DEBUG
if (row >= rows_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, row, rows_);
if (col >= cols_) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, col, cols_);
#endif
return row * cols_ + col;
}
/**
@brief Calculate the row and column from an index into the underlying vector.
Note that Matrix uses the (row,column) lexicographic ordering for indexing.
*/
std::pair<Size, Size> const indexPair(Size index) const
{
#ifdef OPENMS_DEBUG
if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);
#endif
return std::pair<SizeType, SizeType>(index / cols_, index % cols_);
}
/**
@brief Calculate the column from an index into the underlying vector.
Note that Matrix uses the (row,column) lexicographic ordering for indexing.
*/
SizeType colIndex(SizeType index) const
{
#ifdef OPENMS_DEBUG
if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);
#endif
return index % cols_;
}
/**
@brief Calculate the row from an index into the underlying vector.
Note that Matrix uses the (row,column) lexicographic ordering for indexing.
*/
SizeType rowIndex(SizeType index) const
{
#ifdef OPENMS_DEBUG
if (index >= size()) throw Exception::IndexOverflow(__FILE__, __LINE__, __PRETTY_FUNCTION__, index, size() - 1);
#endif
return index / cols_;
}
/**
@brief Equality comparator.
If matrices have different row or column numbers, throws a precondition exception.
*/
bool operator==(Matrix const& rhs) const
{
OPENMS_PRECONDITION(cols_ == rhs.cols_,
"Matrices have different row sizes.");
OPENMS_PRECONDITION(rows_ == rhs.rows_,
"Matrices have different column sizes.");
return static_cast<typename Matrix<Value>::Base const&>(*this) == static_cast<typename Matrix<Value>::Base const&>(rhs);
}
/**
@brief Less-than comparator. Comparison is done lexicographically: first by row, then by column.
If matrices have different row or column numbers, throws a precondition exception.
*/
bool operator<(Matrix const& rhs) const
{
OPENMS_PRECONDITION(cols_ == rhs.cols_,
"Matrices have different row sizes.");
OPENMS_PRECONDITION(rows_ == rhs.rows_,
"Matrices have different column sizes.");
return static_cast<typename Matrix<Value>::Base const&>(*this) < static_cast<typename Matrix<Value>::Base const&>(rhs);
}
/// set matrix to 2D arrays values
template <int ROWS, int COLS>
void setMatrix(const ValueType matrix[ROWS][COLS])
{
resize(ROWS, COLS);
for (SizeType i = 0; i < this->rows_; ++i)
{
for (SizeType j = 0; j < this->cols_; ++j)
{
setValue(i, j, matrix[i][j]);
}
}
}
/**
@brief create gsl_matrix*
allocate and return an equivalent GSL matrix
@note Works only for Matrix<double> and Matrix<float>
@note Clean up the gsl_matrix using gsl_matrix_free (gsl_matrix * m)
*/
gsl_matrix* toGslMatrix()
{
gsl_matrix* m_ptr = gsl_matrix_alloc(rows_, cols_);
for (size_type i = 0; i < this->rows_; ++i)
{
for (size_type j = 0; j < this->cols_; ++j)
{
gsl_matrix_set(m_ptr, i, j, (double) (*this)(i, j));
}
}
return m_ptr;
}
protected:
///@name Data members
//@{
/// Number of rows (height of a column)
SizeType rows_;
/// Number of columns (width of a row)
SizeType cols_;
//@}
}; // class Matrix
// template<> OPENMS_DLLAPI gsl_matrix* Matrix<double>::toGslMatrix();
// template<> OPENMS_DLLAPI gsl_matrix* Matrix<float>::toGslMatrix();
/**
@brief Print the contents to a stream.
@relatesalso Matrix
*/
template <typename Value>
std::ostream& operator<<(std::ostream& os, const Matrix<Value>& matrix)
{
typedef typename Matrix<Value>::size_type size_type;
for (size_type i = 0; i < matrix.rows(); ++i)
{
for (size_type j = 0; j < matrix.cols(); ++j)
{
os << std::setprecision(6) << std::setw(6) << matrix(i, j) << ' ';
}
os << std::endl;
}
return os;
}
} // namespace OpenMS
#endif // OPENMS_DATASTRUCTURES_MATRIX_H
| {
"alphanum_fraction": 0.6261914297,
"avg_line_length": 29.0348837209,
"ext": "h",
"hexsha": "3c2b039149dcaec122bb3b54767536fb2f9de14f",
"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": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "open-ms/all-svn-branches",
"max_forks_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "open-ms/all-svn-branches",
"max_issues_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h",
"max_line_length": 126,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "open-ms/all-svn-branches",
"max_stars_repo_path": "include/OpenMS/DATASTRUCTURES/Matrix.h",
"max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z",
"num_tokens": 2878,
"size": 12485
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_statistics.h>
#include <assert.h>
#include <float.h>
extern "C" {
#include <quadmath.h>
}
#ifndef N
#define N 32
#endif
#define K N/2
#ifndef S
#define S K/2
#endif
#ifndef SEED
#define SEED 1
#endif
#ifndef FB
#define FB 64
#endif
#if(FB==64)
#define FT double
#elif(FB==80)
#define FT long double
#endif
int
main(int argc, char *argv[])
{
assert(argc == 4);
int i, j;
char *cinname = argv[1];
char *sinname = argv[2];
char *outname = argv[3];
FILE *cinfile = fopen(cinname, "r");
FILE *infile = fopen(sinname, "r");
FILE *outfile = fopen(outname, "w");
srand(SEED);
int index[K];
for (i=0; i<K; i++)
index[i]=i;
for (i=0; i<K-1; i++){
j = rand()%(K-1);
int tmp = index[i];
index[i] = index[j];
index[j] = tmp;
}
FT data[K], w[K];
FT wtss;
// read concrete input file
float cinput[N]; i=0;
while(i<N && fscanf(cinfile, "%f", &cinput[i])>0){
i++;
}
assert(i>=N);
fclose(cinfile);
for (i = 0; i < K-S; i++){
w[index[i]]=cinput[index[i]];
}
for (i = 0 ; i <K ; i++){
data[i] = cinput[i+K];
}
// read symbolic input data
float sinput[S];
for (i = 0 ; i < S ; i++) {
__float128 in_data;
fread(&in_data, sizeof(__float128), 1, infile);
sinput[i] = (float) in_data;
}
fclose(infile);
for (i = 0 ; i<S; i++){
w[index[K-1-i]] = sinput[i] / FLT_MAX * 100;
}
// library call
#if(FB==64)
wtss = gsl_stats_wtss(w, 1, data, 1, K);
#elif(FB==80)
wtss = gsl_stats_long_double_wtss(w, 1, data, 1, K);
#else
exit(-1);
#endif
__float128 out_data;
out_data = (__float128) wtss;
fwrite(&out_data, sizeof(__float128), 1, outfile);
fclose(outfile);
return 0;
}
| {
"alphanum_fraction": 0.563943662,
"avg_line_length": 16.2844036697,
"ext": "c",
"hexsha": "10761531516a9960d3baa4687bc7ed9bdb6d8ff2",
"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/wtss/wtss-INOUT-sample.c",
"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/wtss/wtss-INOUT-sample.c",
"max_line_length": 60,
"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/wtss/wtss-INOUT-sample.c",
"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": 630,
"size": 1775
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \addtogroup ioda_cxx_attribute
*
* @{
* \file Attribute_Creator.h
* \brief Flywheel creation of ioda::Attribute. Used by ioda::Has_Attributes and
* ioda::VariableCreationParameters.
*/
#include <gsl/gsl-lite.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "ioda/Attributes/Attribute.h"
#include "ioda/Attributes/Has_Attributes.h"
#include "ioda/Misc/Dimensions.h"
#include "ioda/Types/Type.h"
#include "ioda/defs.h"
namespace ioda {
namespace detail {
/// \brief Flywheel creation of ioda::Attribute.
/// \ingroup ioda_cxx_attribute
class IODA_DL Attribute_Creator_Base {
protected:
std::string name_;
public:
virtual ~Attribute_Creator_Base();
virtual void apply(Has_Attributes& obj) const = 0;
Attribute_Creator_Base(const std::string& name);
};
} // namespace detail
/// \brief Flywheel creation of ioda::Attribute.
/// \ingroup ioda_cxx_attribute
template <class DataType>
class Attribute_Creator : public detail::Attribute_Creator_Base {
private:
::std::vector<Dimensions_t> dimensions_;
::std::vector<DataType> data_;
public:
virtual ~Attribute_Creator() {}
void apply(Has_Attributes& obj) const override { obj.add<DataType>(name_, data_, dimensions_); }
/// \details Totally taking advantage of vector constructors.
template <class DataInput, class DimensionInput>
Attribute_Creator(const std::string& name, DataInput data, DimensionInput dimensions)
: Attribute_Creator_Base(name), data_(data.begin(), data.end()), dimensions_(dimensions) {}
template <class DimensionInput>
Attribute_Creator(const std::string& name, DimensionInput dimensions)
: Attribute_Creator_Base(name), dimensions_(dimensions) {}
template <class DataInput_junk_param = DataType>
void write(const ::gsl::span<const DataType>& data) {
data_ = ::std::vector<DataType>(data.begin(), data.end());
}
};
/// \brief Flywheel creation of ioda::Attribute objects.
/// \ingroup ioda_cxx_attribute
/// This is needed because you might want to make the same Attribute in multiple places.
class IODA_DL Attribute_Creator_Store : public detail::CanAddAttributes<Attribute_Creator_Store> {
std::vector<std::shared_ptr<detail::Attribute_Creator_Base>> atts_;
public:
Attribute_Creator_Store();
virtual ~Attribute_Creator_Store();
void apply(Has_Attributes& obj) const;
/// @name Convenience functions for adding attributes
/// @{
/// \see CanAddAttributes
/// \see CanAddAttributes::add
template <class DataType>
Attribute_Creator_Store& create(const std::string& attrname, ::gsl::span<const DataType> data,
::std::initializer_list<Dimensions_t> dimensions) {
atts_.push_back(std::make_shared<Attribute_Creator<DataType>>(attrname, data, dimensions));
return *this;
}
template <class DataType>
Attribute_Creator_Store& create(const std::string& attrname,
::std::initializer_list<DataType> data,
::std::initializer_list<Dimensions_t> dimensions) {
atts_.push_back(std::make_shared<Attribute_Creator<DataType>>(attrname, data, dimensions));
return *this;
}
template <class DataType2>
struct AttWrapper {
std::shared_ptr<Attribute_Creator<DataType2>> inner;
AttWrapper(std::shared_ptr<Attribute_Creator<DataType2>> d) : inner(d) {}
template <class DataInput_junk_param = DataType2>
void write(const ::gsl::span<const DataType2>& data) {
inner->write(data);
}
};
template <class DataType>
AttWrapper<DataType> create(const std::string& attrname, ::std::vector<Dimensions_t> dimensions) {
auto res = std::make_shared<Attribute_Creator<DataType>>(attrname, dimensions);
atts_.push_back(res);
return AttWrapper<DataType>{res};
}
/// @}
};
} // namespace ioda
/// @} // End Doxygen block
| {
"alphanum_fraction": 0.7182890855,
"avg_line_length": 32.544,
"ext": "h",
"hexsha": "55837f4e921183d96ac100248750581946b5a5e5",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z",
"max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NOAA-EMC/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "NOAA-EMC/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NOAA-EMC/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute_Creator.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z",
"num_tokens": 985,
"size": 4068
} |
/* rng/uni.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
This is a lagged Fibonacci generator which supposedly excellent
statistical properties (I do not concur)
I got it from the net and translated into C.
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module UNI from package CMLIB.
* Retrieved from CAMSUN on Tue Oct 8 14:04:10 1996.
* ======================================================================
C***BEGIN PROLOGUE UNI
C***DATE WRITTEN 810915
C***REVISION DATE 830805
C***CATEGORY NO. L6A21
C***KEYWORDS RANDOM NUMBERS, UNIFORM RANDOM NUMBERS
C***AUTHOR BLUE, JAMES, SCIENTIFIC COMPUTING DIVISION, NBS
C KAHANER, DAVID, SCIENTIFIC COMPUTING DIVISION, NBS
C MARSAGLIA, GEORGE, COMPUTER SCIENCE DEPT., WASH STATE UNIV
C
C***PURPOSE THIS ROUTINE GENERATES QUASI UNIFORM RANDOM NUMBERS ON [0,1
C AND CAN BE USED ON ANY COMPUTER WITH WHICH ALLOWS INTEGERS
C AT LEAST AS LARGE AS 32767.
C***DESCRIPTION
C
C THIS ROUTINE GENERATES QUASI UNIFORM RANDOM NUMBERS ON THE INTER
C [0,1). IT CAN BE USED WITH ANY COMPUTER WHICH ALLOWS
C INTEGERS AT LEAST AS LARGE AS 32767.
C
C
C USE
C FIRST TIME....
C Z = UNI(JD)
C HERE JD IS ANY N O N - Z E R O INTEGER.
C THIS CAUSES INITIALIZATION OF THE PROGRAM
C AND THE FIRST RANDOM NUMBER TO BE RETURNED AS Z.
C SUBSEQUENT TIMES...
C Z = UNI(0)
C CAUSES THE NEXT RANDOM NUMBER TO BE RETURNED AS Z.
C
C
C..................................................................
C NOTE: USERS WHO WISH TO TRANSPORT THIS PROGRAM FROM ONE COMPUTER
C TO ANOTHER SHOULD READ THE FOLLOWING INFORMATION.....
C
C MACHINE DEPENDENCIES...
C MDIG = A LOWER BOUND ON THE NUMBER OF BINARY DIGITS AVAILABLE
C FOR REPRESENTING INTEGERS, INCLUDING THE SIGN BIT.
C THIS VALUE MUST BE AT LEAST 16, BUT MAY BE INCREASED
C IN LINE WITH REMARK A BELOW.
C
C REMARKS...
C A. THIS PROGRAM CAN BE USED IN TWO WAYS:
C (1) TO OBTAIN REPEATABLE RESULTS ON DIFFERENT COMPUTERS,
C SET 'MDIG' TO THE SMALLEST OF ITS VALUES ON EACH, OR,
C (2) TO ALLOW THE LONGEST SEQUENCE OF RANDOM NUMBERS TO BE
C GENERATED WITHOUT CYCLING (REPEATING) SET 'MDIG' TO THE
C LARGEST POSSIBLE VALUE.
C B. THE SEQUENCE OF NUMBERS GENERATED DEPENDS ON THE INITIAL
C INPUT 'JD' AS WELL AS THE VALUE OF 'MDIG'.
C IF MDIG=16 ONE SHOULD FIND THAT
Editors Note: set the seed using 152 in order to get uni(305)
-jt
C THE FIRST EVALUATION
C Z=UNI(305) GIVES Z=.027832881...
C THE SECOND EVALUATION
C Z=UNI(0) GIVES Z=.56102176...
C THE THIRD EVALUATION
C Z=UNI(0) GIVES Z=.41456343...
C THE THOUSANDTH EVALUATION
C Z=UNI(0) GIVES Z=.19797357...
C
C***REFERENCES MARSAGLIA G., "COMMENTS ON THE PERFECT UNIFORM RANDOM
C NUMBER GENERATOR", UNPUBLISHED NOTES, WASH S. U.
C***ROUTINES CALLED I1MACH,XERROR
C***END PROLOGUE UNI
**/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
static inline unsigned long int uni_get (void *vstate);
static double uni_get_double (void *vstate);
static void uni_set (void *state, unsigned long int s);
static const unsigned int MDIG = 16; /* Machine digits in int */
static const unsigned int m1 = 32767; /* 2^(MDIG-1) - 1 */
static const unsigned int m2 = 256; /* 2^(MDIG/2) */
typedef struct
{
int i, j;
unsigned long m[17];
}
uni_state_t;
static inline unsigned long
uni_get (void *vstate)
{
uni_state_t *state = (uni_state_t *) vstate;
const int i = state->i;
const int j = state->j;
/* important k not be unsigned */
long k = state->m[i] - state->m[j];
if (k < 0)
k += m1;
state->m[j] = k;
if (i == 0)
{
state->i = 16;
}
else
{
(state->i)--;
}
if (j == 0)
{
state->j = 16;
}
else
{
(state->j)--;
}
return k;
}
static double
uni_get_double (void *vstate)
{
return uni_get (vstate) / 32767.0 ;
}
static void
uni_set (void *vstate, unsigned long int s)
{
unsigned int i, seed, k0, k1, j0, j1;
uni_state_t *state = (uni_state_t *) vstate;
/* For this routine, the seeding is very elaborate! */
/* A flaw in this approach is that seeds 1,2 give exactly the
same random number sequence! */
s = 2 * s + 1; /* enforce seed be odd */
seed = (s < m1 ? s : m1); /* seed should be less than m1 */
k0 = 9069 % m2;
k1 = 9069 / m2;
j0 = seed % m2;
j1 = seed / m2;
for (i = 0; i < 17; ++i)
{
seed = j0 * k0;
j1 = (seed / m2 + j0 * k1 + j1 * k0) % (m2 / 2);
j0 = seed % m2;
state->m[i] = j0 + m2 * j1;
}
state->i = 4;
state->j = 16;
return;
}
static const gsl_rng_type uni_type =
{"uni", /* name */
32766, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (uni_state_t),
&uni_set,
&uni_get,
&uni_get_double};
const gsl_rng_type *gsl_rng_uni = &uni_type;
| {
"alphanum_fraction": 0.5969017798,
"avg_line_length": 30.0396039604,
"ext": "c",
"hexsha": "c43cfa1654e87224693a5d95666ff59a53b04788",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/rng/uni.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/rng/uni.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/rng/uni.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 1771,
"size": 6068
} |
#pragma once
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "defines.h"
#include "matrix_vector_ops.h"
#define NUM_STATES 1
#define NUM_INPUTS 0
// A-stability test of RK method:
// y' = ky
int testDynamics(gsl_vector *dy, double t, const gsl_vector *y, const gsl_vector *u);
int setupTestDynamics();
int teardownTestDynamics();
gsl_vector *testFeedback(gsl_vector *yd, gsl_vector *y);
int setupTestFeedback();
int teardownTestFeedback();
| {
"alphanum_fraction": 0.7543103448,
"avg_line_length": 20.1739130435,
"ext": "h",
"hexsha": "e5ef7108bf9a31a7a46eb82d4d4a06281cdd58c8",
"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": "testDynamics.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": "testDynamics.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": "testDynamics.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 125,
"size": 464
} |
#if MKL_FOUND
#include <mkl.h>
#elif BLAS_FOUND
#if WASM_COMPATIBLE_BLAS
#include "3rd_party/onnxjs/src/wasm-ops/gemm.h"
#else
#include <cblas.h>
#endif // WASM_COMPATIBLE_BLAS
#endif
inline void sgemm(bool transA,
bool transB,
int rows_a,
int rows_b,
int width,
float alpha,
float* a,
int lda,
float* b,
int ldb,
float beta,
float* c,
int ldc) {
#if BLAS_FOUND
#if WASM_COMPATIBLE_BLAS
gemm_f32_imp(transA, transB, rows_a, rows_b, width, alpha, a, b, beta, c);
#else
cblas_sgemm(CblasRowMajor,
transA ? CblasTrans : CblasNoTrans,
transB ? CblasTrans : CblasNoTrans,
rows_a,
rows_b,
width,
alpha,
a,
lda,
b,
ldb,
beta,
c,
ldc);
#endif
#else
transA; transB; rows_a; rows_b; width; alpha; a; lda; b; ldb; beta; c; ldc; // make compiler happy
ABORT("Marian must be compiled with a BLAS library");
#endif
}
| {
"alphanum_fraction": 0.4428571429,
"avg_line_length": 27.7083333333,
"ext": "h",
"hexsha": "1d675792799c2732472b6b9a09374116eb5acec1",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-12-09T03:40:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-04T12:40:44.000Z",
"max_forks_repo_head_hexsha": "15adfcd816ea0f1d6d5acd26e91523a86267ed63",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "felipesantosk/marian-dev",
"max_forks_repo_path": "src/tensors/cpu/prod_blas.h",
"max_issues_count": 66,
"max_issues_repo_head_hexsha": "15adfcd816ea0f1d6d5acd26e91523a86267ed63",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T10:28:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-08-08T13:26:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "felipesantosk/marian-dev",
"max_issues_repo_path": "src/tensors/cpu/prod_blas.h",
"max_line_length": 102,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "15adfcd816ea0f1d6d5acd26e91523a86267ed63",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "felipesantosk/marian-dev",
"max_stars_repo_path": "src/tensors/cpu/prod_blas.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-13T02:39:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-23T14:28:53.000Z",
"num_tokens": 314,
"size": 1330
} |
//#include <gsl/gsl>
#include "../Problem15/ipv4Base.h"
class ipv4Extend : public ipv4Base
{
public:
ipv4Extend() : ipv4Base()
{
};
ipv4Extend( std::string aInput ) : ipv4Base( aInput )
{
};
~ipv4Extend()
{
};
ipv4Extend& operator= ( const ipv4Extend & aOther )
{
if ( this != & aOther )
{
mIPAddress = aOther.mIPAddress;
}
return *this;
}
//ipv4Extend& operator= ( ipv4Extend && aOther )
//{
// if ( this != &aOther )
// {
// }
// return *this;
//}
ipv4Extend& operator++()
{
increase();
return *this;
}
ipv4Extend operator++( int )
{
ipv4Extend sTemp( *this );
operator++();
return sTemp;
}
friend bool operator== ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
return (aLhs.mIPAddress == aRhs.mIPAddress);
}
friend bool operator!= ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
return !( aLhs == aRhs );
}
friend bool operator < ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
bool sIsRigthBigger = false;
for ( int i = 0; i < 4; i++ )
{
if ( aLhs.mIPAddress[i] < aRhs.mIPAddress[i] )
{
sIsRigthBigger = true;
break;
}
}
return sIsRigthBigger;
}
friend bool operator > ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
return aRhs < aLhs;
}
friend bool operator <= ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
return !( aLhs > aRhs );
}
friend bool operator >= ( const ipv4Extend & aLhs,
const ipv4Extend & aRhs )
{
return !( aLhs < aRhs );
}
private:
void increase()
{
bool sIsRoundUp = false;
mIPAddress[3]++;
for ( auto sIt = mIPAddress.rbegin();
sIt != mIPAddress.rend();
sIt++ )
{
//std::cout << *sIt << "\n";
if ( sIsRoundUp == true )
{
*sIt = *sIt + 1;
//*sIt++;
}
//std::cout << *sIt << "\n";
if ( (*sIt) > 255 )
{
sIsRoundUp = true;
*sIt = 0;
}
else
{
sIsRoundUp = false;
}
}
if ( sIsRoundUp == true )
{
mIPAddress[3]++;
}
}
void decrease()
{
bool sIsRoundDown = false;
}
};
| {
"alphanum_fraction": 0.4096683133,
"avg_line_length": 19.9577464789,
"ext": "h",
"hexsha": "1a6b157a33259693675e44a060c6198a376a6ea4",
"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": "1630f8cf5b3656171ee656738a908619cee6e718",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "akaseon/ModernCppChallengeStudy",
"max_forks_repo_path": "Language/Problem16/ipv4Extend.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1630f8cf5b3656171ee656738a908619cee6e718",
"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": "akaseon/ModernCppChallengeStudy",
"max_issues_repo_path": "Language/Problem16/ipv4Extend.h",
"max_line_length": 59,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1630f8cf5b3656171ee656738a908619cee6e718",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "akaseon/ModernCppChallengeStudy",
"max_stars_repo_path": "Language/Problem16/ipv4Extend.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 746,
"size": 2834
} |
#ifndef tabulate_H_INCLUDED
#define tabulate_H_INCLUDED
//#define DEBUG
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include "wf.h"
#include "glasma.h"
#include "jet.h"
#include "bfkl.h"
#include <gsl/gsl_errno.h>
#define END_MSG 0
#define PIPE_MSG 1
#define RET_MSG 2
int myid;
//number of processors
int np;
//each point in phi is done on an individual slave node
//the code is setup such that the number of points in phi is the number of processors - 1
MPI_Status Status;
int master_main(int, char**) ;
int slave_main(int, char**) ;
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.6781883194,
"avg_line_length": 17.1224489796,
"ext": "h",
"hexsha": "8df2ba192df7b2595a22e13516b73c6531ac4bd4",
"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/tabulate.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/tabulate.h",
"max_line_length": 90,
"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/tabulate.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 236,
"size": 839
} |
/**
*
* @file qwrapper_dsygst.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.8.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated d Fri Apr 1 11:02:42 2016
*
**/
#include <lapacke.h>
#include <al4san.h>
#include <runtime/al4san_quark.h>
#include <runtime/al4san_starpu.h>
//#include <runtime/al4san_parsec.h>
#undef COMPLEX
#define REAL
/***************************************************************************//**
*
**/
AL4SAN_TASK_CPU(dsygst, dsygst_cpu_func)
void EIG_AL4SAN_CORE_dsygst(AL4SAN_option_t *options,
int itype, int uplo, int n,
AL4SAN_desc_t *A, int Am, int An, int lda,
AL4SAN_desc_t *B, int Bm, int Bn, int ldb,
int iinfo)
{
AL4SAN_Insert_Task(AL4SAN_TASK(dsygst), (AL4SAN_option_t*)options,
AL4SAN_VALUE, &itype, sizeof(int),
AL4SAN_VALUE, &uplo, sizeof(int),
AL4SAN_VALUE, &n, sizeof(int),
AL4SAN_INOUT, AL4SAN_ADDR(A, double, Am, An), AL4SAN_DEP,
AL4SAN_VALUE, &lda, sizeof(int),
AL4SAN_INPUT, AL4SAN_ADDR(B, double, Bm, Bn), AL4SAN_DEP,
AL4SAN_VALUE, &ldb, sizeof(int),
AL4SAN_VALUE, &iinfo, sizeof(int),
ARG_END);
}
/***************************************************************************//**
*
**/
void dsygst_cpu_func(AL4SAN_arg_list *al4san_arg)
{
int itype;
int uplo;
int n;
double *A;
int lda;
double *B;
int ldb;
int iinfo;
int info;
AL4SAN_Unpack_Arg(al4san_arg, &itype, &uplo, &n, &A, &lda, &B, &ldb, &iinfo);
char u;
if(uplo==Al4sanUpper)
u='U';
else
u='L';
info = LAPACKE_dsygst_work(
LAPACK_COL_MAJOR,
itype,
u,
n, A, lda, B, ldb);
}
| {
"alphanum_fraction": 0.4528220595,
"avg_line_length": 30.1428571429,
"ext": "c",
"hexsha": "0cbc20800d5bcb3e97c0ac35212d9cd1234ab661",
"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": "93bc603d2b6262439a659ef98908839f678f1c95",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ecrc/al4san",
"max_forks_repo_path": "example/gesvp/codelets/al4san/codelet_dsygst.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95",
"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": "ecrc/al4san",
"max_issues_repo_path": "example/gesvp/codelets/al4san/codelet_dsygst.c",
"max_line_length": 90,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ecrc/al4san",
"max_stars_repo_path": "example/gesvp/codelets/al4san/codelet_dsygst.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-12T19:35:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-25T19:18:14.000Z",
"num_tokens": 592,
"size": 2321
} |
// 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: CEED BPs
//
// This example demonstrates a simple usage of libCEED with PETSc to solve the
// CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps.
//
// The code uses higher level communication protocols in DMPlex.
//
// Build with:
//
// make bps [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>]
//
// Sample runs:
//
// ./bps -problem bp1 -degree 3
// ./bps -problem bp2 -degree 3
// ./bps -problem bp3 -degree 3
// ./bps -problem bp4 -degree 3
// ./bps -problem bp5 -degree 3 -ceed /cpu/self
// ./bps -problem bp6 -degree 3 -ceed /gpu/cuda
//
//TESTARGS -ceed {ceed_resource} -test -problem bp5 -degree 3 -ksp_max_it_clip 15,15
/// @file
/// CEED BPs example using PETSc with DMPlex
/// See bpsraw.c for a "raw" implementation using a structured grid.
const char help[] = "Solve CEED BPs using PETSc with DMPlex\n";
#include <stdbool.h>
#include <string.h>
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscksp.h>
#include <petscsys.h>
#include "bps.h"
#include "include/bpsproblemdata.h"
#include "include/petscmacros.h"
#include "include/petscutils.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
// -----------------------------------------------------------------------------
// Utilities
// -----------------------------------------------------------------------------
// Utility function, compute three factors of an integer
static void Split3(PetscInt size, PetscInt m[3], bool reverse) {
for (PetscInt d=0, size_left=size; d<3; d++) {
PetscInt try = (PetscInt)PetscCeilReal(PetscPowReal(size_left, 1./(3 - d)));
while (try * (size_left / try) != size_left) try++;
m[reverse ? 2-d : d] = try;
size_left /= try;
}
}
static int Max3(const PetscInt a[3]) {
return PetscMax(a[0], PetscMax(a[1], a[2]));
}
static int Min3(const PetscInt a[3]) {
return PetscMin(a[0], PetscMin(a[1], a[2]));
}
// -----------------------------------------------------------------------------
// Parameter structure for running problems
// -----------------------------------------------------------------------------
typedef struct RunParams_ *RunParams;
struct RunParams_ {
MPI_Comm comm;
PetscBool test_mode, read_mesh, user_l_nodes, write_solution;
char *filename, *hostname;
PetscInt local_nodes, degree, q_extra, dim, num_comp_u, *mesh_elem;
PetscInt ksp_max_it_clip[2];
PetscMPIInt ranks_per_node;
BPType bp_choice;
PetscLogStage solve_stage;
};
// -----------------------------------------------------------------------------
// Main body of program, called in a loop for performance benchmarking purposes
// -----------------------------------------------------------------------------
static PetscErrorCode RunWithDM(RunParams rp, DM dm,
const char *ceed_resource) {
PetscErrorCode ierr;
double my_rt_start, my_rt, rt_min, rt_max;
PetscInt xl_size, l_size, g_size;
PetscScalar *r;
Vec X, X_loc, rhs, rhs_loc;
Mat mat_O;
KSP ksp;
UserO user_O;
Ceed ceed;
CeedData ceed_data;
CeedQFunction qf_error;
CeedOperator op_error;
CeedVector rhs_ceed, target;
VecType vec_type;
PetscMemType mem_type;
PetscFunctionBeginUser;
// 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);
}
// Create global and local solution vectors
ierr = DMCreateGlobalVector(dm, &X); CHKERRQ(ierr);
ierr = VecGetLocalSize(X, &l_size); CHKERRQ(ierr);
ierr = VecGetSize(X, &g_size); CHKERRQ(ierr);
ierr = DMCreateLocalVector(dm, &X_loc); CHKERRQ(ierr);
ierr = VecGetSize(X_loc, &xl_size); CHKERRQ(ierr);
ierr = VecDuplicate(X, &rhs); CHKERRQ(ierr);
// Operator
ierr = PetscMalloc1(1, &user_O); CHKERRQ(ierr);
ierr = MatCreateShell(rp->comm, l_size, l_size, g_size, g_size,
user_O, &mat_O); CHKERRQ(ierr);
ierr = MatShellSetOperation(mat_O, MATOP_MULT,
(void(*)(void))MatMult_Ceed); CHKERRQ(ierr);
ierr = MatShellSetOperation(mat_O, MATOP_GET_DIAGONAL,
(void(*)(void))MatGetDiag); CHKERRQ(ierr);
ierr = MatShellSetVecType(mat_O, vec_type); CHKERRQ(ierr);
// Print summary
if (!rp->test_mode) {
PetscInt P = rp->degree + 1, Q = P + rp->q_extra;
const char *used_resource;
CeedGetResource(ceed, &used_resource);
VecType vec_type;
ierr = VecGetType(X, &vec_type); CHKERRQ(ierr);
PetscInt c_start, c_end;
ierr = DMPlexGetHeightStratum(dm, 0, &c_start, &c_end); CHKERRQ(ierr);
PetscMPIInt comm_size;
ierr = MPI_Comm_size(rp->comm, &comm_size); CHKERRQ(ierr);
ierr = PetscPrintf(rp->comm,
"\n-- CEED Benchmark Problem %d -- libCEED + PETSc --\n"
" MPI:\n"
" Hostname : %s\n"
" Total ranks : %d\n"
" Ranks per compute node : %d\n"
" PETSc:\n"
" PETSc Vec Type : %s\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"
" Local Elements : %D\n"
" Owned nodes : %D\n"
" DoF per node : %D\n",
rp->bp_choice+1, rp->hostname, comm_size,
rp->ranks_per_node, vec_type, used_resource,
CeedMemTypes[mem_type_backend],
P, Q, g_size/rp->num_comp_u, c_end - c_start, l_size/rp->num_comp_u,
rp->num_comp_u);
CHKERRQ(ierr);
}
// Create RHS vector
ierr = VecDuplicate(X_loc, &rhs_loc); CHKERRQ(ierr);
ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr);
ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr);
CeedVectorCreate(ceed, xl_size, &rhs_ceed);
CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r);
ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);
ierr = SetupLibceedByDegree(dm, ceed, rp->degree, rp->dim, rp->q_extra,
rp->dim, rp->num_comp_u, g_size, xl_size, bp_options[rp->bp_choice],
ceed_data, true, rhs_ceed, &target); CHKERRQ(ierr);
// Gather RHS
CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL);
ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr);
ierr = VecZeroEntries(rhs); CHKERRQ(ierr);
ierr = DMLocalToGlobal(dm, rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr);
CeedVectorDestroy(&rhs_ceed);
// Create the error QFunction
CeedQFunctionCreateInterior(ceed, 1, bp_options[rp->bp_choice].error,
bp_options[rp->bp_choice].error_loc, &qf_error);
CeedQFunctionAddInput(qf_error, "u", rp->num_comp_u, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_error, "true_soln", rp->num_comp_u, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_error, "error", rp->num_comp_u, CEED_EVAL_NONE);
// Create the error operator
CeedOperatorCreate(ceed, qf_error, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE,
&op_error);
CeedOperatorSetField(op_error, "u", ceed_data->elem_restr_u,
ceed_data->basis_u, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_error, "true_soln", ceed_data->elem_restr_u_i,
CEED_BASIS_COLLOCATED, target);
CeedOperatorSetField(op_error, "error", ceed_data->elem_restr_u_i,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Set up Mat
user_O->comm = rp->comm;
user_O->dm = dm;
user_O->X_loc = X_loc;
ierr = VecDuplicate(X_loc, &user_O->Y_loc); CHKERRQ(ierr);
user_O->x_ceed = ceed_data->x_ceed;
user_O->y_ceed = ceed_data->y_ceed;
user_O->op = ceed_data->op_apply;
user_O->ceed = ceed;
ierr = KSPCreate(rp->comm, &ksp); CHKERRQ(ierr);
{
PC pc;
ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);
if (rp->bp_choice == CEED_BP1 || rp->bp_choice == CEED_BP2) {
ierr = PCSetType(pc, PCJACOBI); CHKERRQ(ierr);
ierr = PCJacobiSetType(pc, PC_JACOBI_ROWSUM); CHKERRQ(ierr);
} else {
ierr = PCSetType(pc, PCNONE); CHKERRQ(ierr);
}
ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);
ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr);
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,
PETSC_DEFAULT); CHKERRQ(ierr);
}
ierr = KSPSetOperators(ksp, mat_O, mat_O); CHKERRQ(ierr);
// First run's performance log is not considered for benchmarking purposes
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1);
CHKERRQ(ierr);
my_rt_start = MPI_Wtime();
ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);
my_rt = MPI_Wtime() - my_rt_start;
ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, rp->comm);
CHKERRQ(ierr);
// Set maxits based on first iteration timing
if (my_rt > 0.02) {
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,
rp->ksp_max_it_clip[0]);
CHKERRQ(ierr);
} else {
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,
rp->ksp_max_it_clip[1]);
CHKERRQ(ierr);
}
ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);
// Timed solve
ierr = VecZeroEntries(X); CHKERRQ(ierr);
ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr);
// -- Performance logging
ierr = PetscLogStagePush(rp->solve_stage); CHKERRQ(ierr);
// -- Solve
my_rt_start = MPI_Wtime();
ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);
my_rt = MPI_Wtime() - my_rt_start;
// -- Performance logging
ierr = PetscLogStagePop();
// Output results
{
KSPType ksp_type;
KSPConvergedReason reason;
PetscReal rnorm;
PetscInt its;
ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr);
ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);
ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);
ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr);
if (!rp->test_mode || reason < 0 || rnorm > 1e-8) {
ierr = PetscPrintf(rp->comm,
" KSP:\n"
" KSP Type : %s\n"
" KSP Convergence : %s\n"
" Total KSP Iterations : %D\n"
" Final rnorm : %e\n",
ksp_type, KSPConvergedReasons[reason], its,
(double)rnorm); CHKERRQ(ierr);
}
if (!rp->test_mode) {
ierr = PetscPrintf(rp->comm," Performance:\n"); CHKERRQ(ierr);
}
{
PetscReal max_error;
ierr = ComputeErrorMax(user_O, op_error, X, target, &max_error);
CHKERRQ(ierr);
PetscReal tol = 5e-2;
if (!rp->test_mode || max_error > tol) {
ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, rp->comm);
CHKERRQ(ierr);
ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, rp->comm);
CHKERRQ(ierr);
ierr = PetscPrintf(rp->comm,
" Pointwise Error (max) : %e\n"
" CG Solve Time : %g (%g) sec\n",
(double)max_error, rt_max, rt_min); CHKERRQ(ierr);
}
}
if (!rp->test_mode) {
ierr = PetscPrintf(rp->comm,
" DoFs/Sec in CG : %g (%g) million\n",
1e-6*g_size*its/rt_max,
1e-6*g_size*its/rt_min); CHKERRQ(ierr);
}
}
if (rp->write_solution) {
PetscViewer vtk_viewer_soln;
ierr = PetscViewerCreate(rp->comm, &vtk_viewer_soln); CHKERRQ(ierr);
ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr);
ierr = PetscViewerFileSetName(vtk_viewer_soln, "solution.vtu"); CHKERRQ(ierr);
ierr = VecView(X, vtk_viewer_soln); CHKERRQ(ierr);
ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr);
}
// Cleanup
ierr = VecDestroy(&X); CHKERRQ(ierr);
ierr = VecDestroy(&X_loc); CHKERRQ(ierr);
ierr = VecDestroy(&user_O->Y_loc); CHKERRQ(ierr);
ierr = MatDestroy(&mat_O); CHKERRQ(ierr);
ierr = PetscFree(user_O); CHKERRQ(ierr);
ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);
ierr = VecDestroy(&rhs); CHKERRQ(ierr);
ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr);
ierr = KSPDestroy(&ksp); CHKERRQ(ierr);
CeedVectorDestroy(&target);
CeedQFunctionDestroy(&qf_error);
CeedOperatorDestroy(&op_error);
CeedDestroy(&ceed);
PetscFunctionReturn(0);
}
static PetscErrorCode Run(RunParams rp, PetscInt num_resources,
char *const *ceed_resources, PetscInt num_bp_choices,
const BPType *bp_choices) {
PetscInt ierr;
DM dm;
PetscFunctionBeginUser;
// Setup DM
if (rp->read_mesh) {
ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, rp->filename, PETSC_TRUE, &dm);
CHKERRQ(ierr);
} else {
if (rp->user_l_nodes) {
// Find a nicely composite number of elements no less than global nodes
PetscMPIInt size;
ierr = MPI_Comm_size(rp->comm, &size); CHKERRQ(ierr);
for (PetscInt g_elem =
PetscMax(1, size * rp->local_nodes / PetscPowInt(rp->degree, rp->dim));
;
g_elem++) {
Split3(g_elem, rp->mesh_elem, true);
if (Max3(rp->mesh_elem) / Min3(rp->mesh_elem) <= 2) break;
}
}
ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, rp->dim, PETSC_FALSE,
rp->mesh_elem,
NULL, NULL, NULL, PETSC_TRUE, &dm); CHKERRQ(ierr);
}
{
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;
}
}
// Disable default VECSTANDARD *after* distribution (which creates a Vec)
ierr = DMSetVecType(dm, NULL); CHKERRQ(ierr);
for (PetscInt b = 0; b < num_bp_choices; b++) {
DM dm_deg;
VecType vec_type;
PetscInt q_extra = rp->q_extra;
rp->bp_choice = bp_choices[b];
rp->num_comp_u = bp_options[rp->bp_choice].num_comp_u;
rp->q_extra = q_extra < 0 ? bp_options[rp->bp_choice].q_extra : q_extra;
ierr = DMClone(dm, &dm_deg); CHKERRQ(ierr);
ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);
ierr = DMSetVecType(dm_deg, vec_type); CHKERRQ(ierr);
// Create DM
PetscInt dim;
ierr = DMGetDimension(dm_deg, &dim); CHKERRQ(ierr);
ierr = SetupDMByDegree(dm_deg, rp->degree, rp->num_comp_u, dim,
bp_options[rp->bp_choice].enforce_bc,
bp_options[rp->bp_choice].bc_func); CHKERRQ(ierr);
for (PetscInt r = 0; r < num_resources; r++) {
ierr = RunWithDM(rp, dm_deg, ceed_resources[r]); CHKERRQ(ierr);
}
ierr = DMDestroy(&dm_deg); CHKERRQ(ierr);
rp->q_extra = q_extra;
}
ierr = DMDestroy(&dm); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
int main(int argc, char **argv) {
PetscInt ierr, comm_size;
RunParams rp;
MPI_Comm comm;
char filename[PETSC_MAX_PATH_LEN];
char *ceed_resources[30];
PetscInt num_ceed_resources = 30;
char hostname[PETSC_MAX_PATH_LEN];
PetscInt dim = 3, mesh_elem[3] = {3, 3, 3};
PetscInt num_degrees = 30, degree[30] = {}, num_local_nodes = 2,
local_nodes[2] = {};
PetscMPIInt ranks_per_node;
PetscBool degree_set;
BPType bp_choices[10];
PetscInt num_bp_choices = 10;
// Initialize PETSc
ierr = PetscInitialize(&argc, &argv, NULL, help);
if (ierr) return ierr;
comm = PETSC_COMM_WORLD;
ierr = MPI_Comm_size(comm, &comm_size);
if (ierr != MPI_SUCCESS) return ierr;
#if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
{
MPI_Comm splitcomm;
ierr = MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL,
&splitcomm);
CHKERRQ(ierr);
ierr = MPI_Comm_size(splitcomm, &ranks_per_node); CHKERRQ(ierr);
ierr = MPI_Comm_free(&splitcomm); CHKERRQ(ierr);
}
#else
ranks_per_node = -1; // Unknown
#endif
// Setup all parameters needed in Run()
ierr = PetscMalloc1(1, &rp); CHKERRQ(ierr);
rp->comm = comm;
// Read command line options
ierr = PetscOptionsBegin(comm, NULL, "CEED BPs in PETSc", NULL);
CHKERRQ(ierr);
{
PetscBool set;
ierr = PetscOptionsEnumArray("-problem", "CEED benchmark problem to solve",
NULL,
bp_types, (PetscEnum *)bp_choices, &num_bp_choices, &set);
CHKERRQ(ierr);
if (!set) {
bp_choices[0] = CEED_BP1;
num_bp_choices = 1;
}
}
rp->test_mode = PETSC_FALSE;
ierr = PetscOptionsBool("-test",
"Testing mode (do not print unless error is large)",
NULL, rp->test_mode, &rp->test_mode, NULL); CHKERRQ(ierr);
rp->write_solution = PETSC_FALSE;
ierr = PetscOptionsBool("-write_solution", "Write solution for visualization",
NULL, rp->write_solution, &rp->write_solution, NULL);
CHKERRQ(ierr);
degree[0] = rp->test_mode ? 3 : 2;
ierr = PetscOptionsIntArray("-degree",
"Polynomial degree of tensor product basis", NULL,
degree, &num_degrees, °ree_set); CHKERRQ(ierr);
if (!degree_set)
num_degrees = 1;
rp->q_extra = PETSC_DECIDE;
ierr = PetscOptionsInt("-q_extra",
"Number of extra quadrature points (-1 for auto)", NULL,
rp->q_extra, &rp->q_extra, NULL); CHKERRQ(ierr);
{
PetscBool set;
ierr = PetscOptionsStringArray("-ceed",
"CEED resource specifier (comma-separated list)", NULL,
ceed_resources, &num_ceed_resources, &set); CHKERRQ(ierr);
if (!set) {
ierr = PetscStrallocpy( "/cpu/self", &ceed_resources[0]); CHKERRQ(ierr);
num_ceed_resources = 1;
}
}
ierr = PetscGetHostName(hostname, sizeof hostname); CHKERRQ(ierr);
ierr = PetscOptionsString("-hostname", "Hostname for output", NULL, hostname,
hostname, sizeof(hostname), NULL); CHKERRQ(ierr);
rp->read_mesh = PETSC_FALSE;
ierr = PetscOptionsString("-mesh", "Read mesh from file", NULL, filename,
filename, sizeof(filename), &rp->read_mesh);
CHKERRQ(ierr);
rp->filename = filename;
if (!rp->read_mesh) {
PetscInt tmp = dim;
ierr = PetscOptionsIntArray("-cells", "Number of cells per dimension", NULL,
mesh_elem, &tmp, NULL); CHKERRQ(ierr);
}
local_nodes[0] = 1000;
ierr = PetscOptionsIntArray("-local_nodes",
"Target number of locally owned nodes per "
"process (single value or min,max)",
NULL, local_nodes, &num_local_nodes, &rp->user_l_nodes);
CHKERRQ(ierr);
if (num_local_nodes < 2)
local_nodes[1] = 2 * local_nodes[0];
{
PetscInt two = 2;
rp->ksp_max_it_clip[0] = 5;
rp->ksp_max_it_clip[1] = 20;
ierr = PetscOptionsIntArray("-ksp_max_it_clip",
"Min and max number of iterations to use during benchmarking",
NULL, rp->ksp_max_it_clip, &two, NULL); CHKERRQ(ierr);
}
if (!degree_set) {
PetscInt max_degree = 8;
ierr = PetscOptionsInt("-max_degree",
"Range of degrees [1, max_degree] to run with",
NULL, max_degree, &max_degree, NULL);
CHKERRQ(ierr);
for (PetscInt i = 0; i < max_degree; i++)
degree[i] = i + 1;
num_degrees = max_degree;
}
{
PetscBool flg;
PetscInt p = ranks_per_node;
ierr = PetscOptionsInt("-p", "Number of MPI ranks per node", NULL,
p, &p, &flg);
CHKERRQ(ierr);
if (flg) ranks_per_node = p;
}
ierr = PetscOptionsEnd();
CHKERRQ(ierr);
// Register PETSc logging stage
ierr = PetscLogStageRegister("Solve Stage", &rp->solve_stage);
CHKERRQ(ierr);
rp->hostname = hostname;
rp->dim = dim;
rp->mesh_elem = mesh_elem;
rp->ranks_per_node = ranks_per_node;
for (PetscInt d = 0; d < num_degrees; d++) {
PetscInt deg = degree[d];
for (PetscInt n = local_nodes[0]; n < local_nodes[1]; n *= 2) {
rp->degree = deg;
rp->local_nodes = n;
ierr = Run(rp, num_ceed_resources, ceed_resources,
num_bp_choices, bp_choices); CHKERRQ(ierr);
}
}
// Clear memory
ierr = PetscFree(rp); CHKERRQ(ierr);
for (PetscInt i=0; i<num_ceed_resources; i++) {
ierr = PetscFree(ceed_resources[i]); CHKERRQ(ierr);
}
return PetscFinalize();
}
| {
"alphanum_fraction": 0.5986563396,
"avg_line_length": 38.3727422003,
"ext": "c",
"hexsha": "ed7ecd797d4ac1cf574915e74d4dbb4d25ce9748",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/petsc/bps.c",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/petsc/bps.c",
"max_line_length": 98,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/petsc/bps.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 6299,
"size": 23369
} |
/**
*
* @file core_sgeqp3_init.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 Mark Gates
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:49 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_sgeqp3_init initializes jpvt to [1, ..., n].
* Uses 1-based indexing for Fortran compatability.
*
*******************************************************************************
*
* @param[in] n
* Size of vector.
*
* @param[in,out] jpvt
* Vector of size n.
* On exit, jpvt[i] = i+1.
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgeqp3_init = PCORE_sgeqp3_init
#define CORE_sgeqp3_init PCORE_sgeqp3_init
#endif
void CORE_sgeqp3_init( int n, int *jpvt )
{
int j;
for( j = 0; j < n; ++j ) {
jpvt[j] = j+1;
}
}
| {
"alphanum_fraction": 0.5244956772,
"avg_line_length": 23.1333333333,
"ext": "c",
"hexsha": "3d08d15682ef93fc21af6026cb4ee0375a3b181d",
"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_sgeqp3_init.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_sgeqp3_init.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_sgeqp3_init.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 303,
"size": 1041
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <gsl/gsl-lite.hpp>
#include <nlohmann/json.hpp>
#include <platform/dirutils.h>
#include <vector>
class Event;
/**
* The Module class represents the configuration for a single module.
* See ../README.md for more information.
*/
class Module {
public:
Module() = delete;
Module(const nlohmann::json& json,
const std::string& srcRoot,
const std::string& objRoot);
void createHeaderFile();
/**
* The name of the module
*/
std::string name;
/**
* The lowest identifier for the audit events in this module. All
* audit descriptor defined for this module MUST be within the range
* [start, start + max_events_per_module]
*/
int64_t start;
/**
* The name of the file containing the audit descriptors for this
* module.
*/
std::string file;
/**
* The JSON data describing the audit descriptors for this module
*/
nlohmann::json json;
/**
* Is this module enterprise only?
*/
bool enterprise = false;
/**
* If present this is the name of a C headerfile to generate with
* #defines for all audit identifiers for the module.
*/
std::string header;
/**
* A list of all of the events defined for this module
*/
std::vector<std::unique_ptr<Event>> events;
protected:
/**
* Add the event to the list of events for the module
*
* @param event the event to add
* @throws std::invalid_argument if the event is outside the legal range
* for the module
*/
void addEvent(std::unique_ptr<Event> event);
/// Parse the event descriptor file and add all of the events into
/// the list of events
void parseEventDescriptorFile();
};
| {
"alphanum_fraction": 0.6405437825,
"avg_line_length": 28.4204545455,
"ext": "h",
"hexsha": "a0c93137cea69e2c8b1d706fa3fe7cbb462c286c",
"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": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rohansuri/kv_engine",
"max_forks_repo_path": "auditd/generator/generator_module.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"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": "rohansuri/kv_engine",
"max_issues_repo_path": "auditd/generator/generator_module.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rohansuri/kv_engine",
"max_stars_repo_path": "auditd/generator/generator_module.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 577,
"size": 2501
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define COMPEARTH_PRIVATE_UPDOWN_ARGSORT3 1
#define COMPEARTH_PRIVATE_UPDOWN_ABS_ARGSORT3 1
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_lapacke.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <lapacke.h>
#endif
/*
static int argsort3_upDown(const double *__restrict__ x,
const bool lascend,
int *__restrict__ iperm);
static int argsort3(const double *__restrict__ x, int *__restrict__ iperm);
*/
#define LWORK 102 //(NB+2)*N hence NB=32; must be atleast 3*N-1 which is 8
/*!
* @brief Decomposes a set of moment tensors into eigenvalues + basis.
*
* @param[in] nmt Number of moment tensors.
* @param[in] M 6 x n moment tensors with some unspecified basis
* (e.g., up-south-east) packed
* M = [M11 M22 M33 M12 M13 M23].
* @param[in] isort Sorting of eigenvalues. \n
* If 1 then the eigenvalues are sorted highest to lowest. \n
* If 2 then the eigenvalues are sorted lowest to highest. \n
* If 3 then the eigenvalues are sorted by absolute value
* from highest to lowest. \n
* If 4 then the eigenvalues are sorted by absolute value
* from lowest to highest.
*
* @param[out] lam 3 x n set of eigenvalues.
* @param[out] U 3 x 3 x n set of bases. The first 3 x 3 matrix is in
* column major order. This has the same basis as M.
*
* @author Carl Tape. Converted to C by Ben Baker.
*
* @copyright MIT
*
* @bug The
*/
int compearth_CMTdecom(const int nmt, const double *__restrict__ M,
const int isort,
double *__restrict__ lam,
double *__restrict__ U)
{
double Lams[3], Mx[9], Ut[9], work[LWORK];
int perm[3], c, i, ierr, info, r;
// Error checks
if (nmt < 1 || M == NULL || lam == NULL || U == NULL)
{
if (nmt < 1){fprintf(stderr, "%s: Error no mts\n", __func__);}
if (M == NULL){fprintf(stderr, "%s: Error M is NULL\n", __func__);}
if (lam == NULL){fprintf(stderr, "%s: Error lam is NULL\n", __func__);}
if (U == NULL){fprintf(stderr, "%s: Error U is NULL\n", __func__);}
return -1;
}
if (isort < 1 || isort > 4)
{
fprintf(stderr, "%s: Error isort=%d is invalid\n", __func__, isort);
return -1;
}
// Decompose the moment tensors
for (i=0; i<nmt; i++)
{
// Create the symmetric moment tensor matrix from the 6x1 vector
compearth_Mvec2Mmat(1, M, 1, Mx);
// Compute eigenvalues in ascending order
info = LAPACKE_dsyev_work(LAPACK_COL_MAJOR, 'V', 'U', 3, Mx, 3,
Lams, work, LWORK);
if (info != 0)
{
fprintf(stderr, "%s: Error computing eigenvalues\n", __func__);
return -1;
}
// Descending
if (isort == 1)
{
argsort3_upDown(Lams, false, perm);
}
else if (isort == 2)
{
argsort3_upDown(Lams, true, perm);
}
// Descending on absolute value
else if (isort == 3)
{
argsort3_absUpDown(Lams, false, perm);
}
else //if (isort == 4)
{
argsort3_absUpDown(Lams, true, perm);
}
// And permute and save
for (r=0; r<3; r++)
{
lam[3*i+r] = Lams[perm[r]];
}
// Permute columns
for (c=0; c<3; c++)
{
for (r=0; r<3; r++)
{
Ut[3*c+r] = Mx[3*perm[c]+r];
}
}
// Ensure the determinant is > 0
ierr = compearth_Udetcheck(1, Ut, &U[9*i]);
if (ierr != 0)
{
fprintf(stderr, "%s: Error checking determinant\n", __func__);
return -1;
}
}
return 0;
}
/*
static int argsort3_upDown(const double *__restrict__ x,
const bool lascend,
int *__restrict__ iperm)
{
int ipermt[3], ierr;
if (lascend)
{
ierr = argsort3(x, iperm);
}
else
{
ierr = argsort3(x, ipermt);
iperm[0] = ipermt[2];
iperm[1] = ipermt[1];
iperm[2] = ipermt[0];
}
return ierr;
}
static int argsort3(const double *__restrict__ x, int *__restrict__ iperm)
{
int i, temp;
const int a = 0;
const int b = 1;
const int c = 2;
// Copy
iperm[a] = a;
iperm[b] = b;
iperm[c] = c;
if (x[iperm[a]] > x[iperm[c]])
{
temp = iperm[c];
iperm[c] = iperm[a];
iperm[a] = temp;
}
if (x[iperm[a]] > x[iperm[b]])
{
temp = iperm[b];
iperm[b] = iperm[a];
iperm[a] = temp;
}
//Now the smallest element is the first one. Just check the 2-nd and 3-rd
if (x[iperm[b]] > x[iperm[c]])
{
temp = iperm[c];
iperm[c] = iperm[b];
iperm[b] = temp;
}
// Verify
for (i=1; i<3; i++)
{
if (x[iperm[i-1]] > x[iperm[i]])
{
fprintf(stderr, "%s: Failed to sort numbers in ascending order\n",
__func__);
return -1;
}
}
return 0;
}
*/
| {
"alphanum_fraction": 0.5186580553,
"avg_line_length": 28.8808290155,
"ext": "c",
"hexsha": "a482b409c82ac97ff02a4a960b2d7b78bef2c6f2",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/CMTdecom.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/CMTdecom.c",
"max_line_length": 79,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/CMTdecom.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 1595,
"size": 5574
} |
/* linalg/rqr.c
*
* Copyright (C) 2019 Patrick Alken, Julien Langou
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
/*
* this module contains routines for the QR factorization of a matrix
* using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with
* additional modifications courtesy of Julien Langou.
*/
static int unpack_Q1(gsl_matrix * Q);
static int unpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q);
static int aux_ULT(const gsl_matrix * L, gsl_matrix * U);
static int aux_mLU(gsl_matrix * A);
static int aux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A);
/*
gsl_linalg_QR_decomp_r()
QR decomposition using Level 3 BLAS recursive algorithm of:
Elmroth, E. and Gustavson, F.G., 2000. Applying recursion to serial and parallel
QR factorization leads to better performance. IBM Journal of Research and Development,
44(4), pp.605-624.
Inputs: A - matrix to be factored, M-by-N with M >= N
T - N-by-N upper triangular factor of block reflector
Return: success/error
Notes:
1) on output, upper triangle of A contains R; elements below the diagonal
are columns of V. The matrix Q is
Q = I - V T V^T
where T is upper triangular. Note that diag(T) = tau
2) implementation provided by Julien Langou
*/
int
gsl_linalg_QR_decomp_r (gsl_matrix * A, gsl_matrix * T)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M < N)
{
GSL_ERROR ("M must be >= N", GSL_EBADLEN);
}
else if (T->size1 != T->size2)
{
GSL_ERROR ("T matrix must be square", GSL_ENOTSQR);
}
else if (T->size1 != N)
{
GSL_ERROR ("T matrix does not match dimensions of A", GSL_EBADLEN);
}
else if (N == 1)
{
/* base case, compute householder transform for single column matrix */
double * T00 = gsl_matrix_ptr(T, 0, 0);
gsl_vector_view v = gsl_matrix_column(A, 0);
*T00 = gsl_linalg_householder_transform(&v.vector);
return GSL_SUCCESS;
}
else
{
/*
* partition matrices:
*
* N1 N2 N1 N2
* N1 [ A11 A12 ] and N1 [ T11 T12 ]
* M2 [ A21 A22 ] N2 [ 0 T22 ]
*/
int status;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
const size_t M2 = M - N1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);
gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, M2, N1);
gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, M2, N2);
gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);
gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);
gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);
gsl_matrix_view m;
/*
* Eq. 2: recursively factor
*
* [ A11 ] = Q1 [ R11 ]
* [ A21 ] [ 0 ]
* N1
* Note: Q1 = I - V1 T11 V1^T, where V1 = [ V11 ] N1
* [ V21 ] M2
*/
m = gsl_matrix_submatrix(A, 0, 0, M, N1);
status = gsl_linalg_QR_decomp_r(&m.matrix, &T11.matrix);
if (status)
return status;
/*
* Eq. 3:
*
* [ R12 ] := Q1^T [ A12 ] = [ A12 ] - [ V11 W ]
* [ A22 ] [ A22 ] [ A22 ] [ V21 W ]
*
* where W = T11^T (V11^T A12 + V21^T A22), and using T12 as temporary storage
*/
gsl_matrix_memcpy(&T12.matrix, &A12.matrix); /* W := A12 */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* W := V11^T * A12 */
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A21.matrix, &A22.matrix, 1.0, &T12.matrix); /* W := W + V21^T * A22 */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T * W */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &T12.matrix, 1.0, &A22.matrix); /* A22 = A22 - V21 * W */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* tmp = V11 * W */
gsl_matrix_sub(&A12.matrix, &T12.matrix); /* R12 := A12 - V11 * W */
/*
* Eq. 4: recursively factor
*
* A22 = Q2~ R22
*
* N1 M2
* Note: Q2 = [ I 0 ] N1
* [ 0 Q2~ ] M2
*/
status = gsl_linalg_QR_decomp_r(&A22.matrix, &T22.matrix);
if (status)
return status;
/*
* Eq. 13: update T12 := -T11 * V1^T * V2 * T22
*
* where:
*
* N1 N2
* V1 = [ V11 ] N1 V2 = [ 0 ] N1
* [ V21 ] N2 [ V22 ] N2
* [ V31 ] M-N [ V32 ] M-N
*
* Note: V1^T V2 = V21^T V22 + V31^T V32
* Also, V11, V22 are unit lower triangular
*/
m = gsl_matrix_submatrix(&A21.matrix, 0, 0, N2, N1); /* V21 */
gsl_matrix_transpose_memcpy(&T12.matrix, &m.matrix); /* T12 := V21^T */
m = gsl_matrix_submatrix(A, N1, N1, N2, N2); /* V22 */
gsl_blas_dtrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, 1.0, &m.matrix, &T12.matrix); /* T12 := V21^T * V22 */
if (M > N)
{
gsl_matrix_view V31 = gsl_matrix_submatrix(A, N, 0, M - N, N1);
gsl_matrix_view V32 = gsl_matrix_submatrix(A, N, N1, M - N, N2);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V31.matrix, &V32.matrix, 1.0, &T12.matrix); /* T12 := T12 + V31^T * V32 */
}
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */
gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */
return GSL_SUCCESS;
}
}
/* Solves the square system A x = b for x using the QR factorisation,
*
* R x = Q^T b
*
* where Q = I - V T V^T
*/
int
gsl_linalg_QR_solve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x)
{
const size_t N = QR->size2;
if (QR->size1 != N)
{
GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR);
}
else if (T->size1 != QR->size1 || T->size2 != QR->size2)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else if (N != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (N != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
size_t i;
/* compute Q^T b = [I - V T^T V^T] b */
/* x := V^T b */
gsl_vector_memcpy(x, b);
gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, QR, x);
/* x = T^T * x */
gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, x);
/* x = V * x */
gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, QR, x);
/* x = b - V * x */
for (i = 0; i < N; ++i)
{
double * xi = gsl_vector_ptr(x, i);
double bi = gsl_vector_get(b, i);
*xi = bi - (*xi);
}
/* Solve R x = Q^T b, storing x in-place */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);
return GSL_SUCCESS;
}
}
/* Find the least squares solution to the overdetermined system
*
* A x = b
*
* for M >= N using the QR factorization A = Q R.
*
* Inputs: QR - [R; V] matrix, M-by-N
* T - upper triangular block reflector, N-by-N
* b - right hand side, size M
* x - (output) solution, size M
* x(1:N) = least squares solution vector
* x(N+1:M) = vector whose norm equals ||b - Ax||
* work - workspace, size N
*/
int
gsl_linalg_QR_lssolve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x, gsl_vector * work)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (M < N)
{
GSL_ERROR ("QR matrix must have M >= N", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else if (M != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (M != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else if (N != work->size)
{
GSL_ERROR ("matrix size must match work size", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view R = gsl_matrix_const_submatrix (QR, 0, 0, N, N);
gsl_vector_view x1 = gsl_vector_subvector(x, 0, N);
/* compute x = Q^T b */
gsl_vector_memcpy(x, b);
gsl_linalg_QR_QTvec_r (QR, T, x, work);
/* Solve R x = Q^T b */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, &x1.vector);
return GSL_SUCCESS;
}
}
/*
gsl_linalg_QR_unpack_r()
Unpack matrices Q and R
Inputs: QR - packed QR format, M-by-N
T - block reflector matrix, N-by-N
Q - (output) Q matrix, M-by-M
R - (output) R matrix, N-by-N
Return: success/error
Notes:
1) Implementation provided by Julien Langou
*/
int
gsl_linalg_QR_unpack_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q, gsl_matrix * R)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (M < N)
{
GSL_ERROR ("M must be >= N", GSL_EBADLEN);
}
else if (Q->size1 != M || Q->size2 != M)
{
GSL_ERROR ("Q matrix must be M-by-M", GSL_EBADLEN);
}
else if (R->size1 != N || R->size2 != N)
{
GSL_ERROR ("R matrix must be N-by-N", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view RV = gsl_matrix_const_submatrix(QR, 0, 0, N, N);
gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, M, N);
gsl_matrix_view m;
/*
* set Q1 = [ T ]
* [ V ]
*/
m = gsl_matrix_submatrix(Q, 0, 0, N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &m.matrix, T);
gsl_matrix_tricpy(CblasLower, CblasUnit, &m.matrix, &RV.matrix);
if (M > N)
{
gsl_matrix_const_view tmp = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
m = gsl_matrix_submatrix(Q, N, 0, M - N, N);
gsl_matrix_memcpy(&m.matrix, &tmp.matrix);
}
unpack_Q1(&Q1.matrix);
if (M > N)
{
gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, 0, N, M, M - N);
unpack_Q2(QR, T, &Q2.matrix);
}
/* copy R */
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, &RV.matrix);
return GSL_SUCCESS;
}
}
/*
gsl_linalg_QR_QTvec_r()
Apply M-by-M Q^T to the M-by-1 vector b
Inputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r
T - block reflector matrix
b - M-by-1 vector replaced by Q^T b on output
work - workspace, length N
Notes:
1) Q^T b = (I - V T^T V^T) b
= b - V T^T [ V1^T V2^T ] [ b1 ]
[ b2 ]
= b - V T^T [ V1^T b1 + V2^T b2 ]
= [ b1 ] - [ V1 w ]
[ b2 ] [ V2 w ]
where w = T^T ( V1^T b1 + V2^T b2 )
*/
int
gsl_linalg_QR_QTvec_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_vector * b, gsl_vector * work)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (M < N)
{
GSL_ERROR ("M must be >= N", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else if (b->size != M)
{
GSL_ERROR ("b vector must have length M", GSL_EBADLEN);
}
else if (work->size != N)
{
GSL_ERROR ("workspace must be length N", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);
gsl_vector_view b1 = gsl_vector_subvector(b, 0, N);
gsl_vector_view b2;
/* work := V1^T b1 */
gsl_vector_memcpy(work, &b1.vector);
gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, &V1.matrix, work);
if (M > N)
{
gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
/* work = work + V2^T b2 */
b2 = gsl_vector_subvector(b, N, M - N);
gsl_blas_dgemv(CblasTrans, 1.0, &V2.matrix, &b2.vector, 1.0, work);
}
/* work = T^T * work */
gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, work);
if (M > N)
{
/* b2 = b2 - V2 * work */
gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
gsl_blas_dgemv(CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &b2.vector);
}
/* b1 = b1 - V1 * work */
gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, &V1.matrix, work);
gsl_vector_sub(&b1.vector, work);
return GSL_SUCCESS;
}
}
/*
gsl_linalg_QR_QTmat_r()
Apply M-by-M Q^T to the M-by-K matrix B
Inputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r
T - block reflector matrix
B - M-by-K matrix replaced by Q^T B on output
work - N-by-K workspace
Notes:
1) Provided by Julien Langou
*/
int
gsl_linalg_QR_QTmat_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * B, gsl_matrix * work)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
const size_t K = B->size2;
if (M < N)
{
GSL_ERROR ("M must be >= N", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else if (B->size1 != M)
{
GSL_ERROR ("B matrix must have M rows", GSL_EBADLEN);
}
else if (work->size1 != N || work->size2 != K)
{
GSL_ERROR ("workspace must be N-by-K", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);
gsl_matrix_view B1 = gsl_matrix_submatrix(B, 0, 0, N, K);
gsl_matrix_view B2;
/* work := V1^T B1 */
gsl_matrix_memcpy(work, &B1.matrix);
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &V1.matrix, work);
if (M > N)
{
gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
/* work = work + V2^T B2 */
B2 = gsl_matrix_submatrix(B, N, 0, M - N, K);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V2.matrix, &B2.matrix, 1.0, work);
}
/* work = T^T * work */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, T, work);
if (M > N)
{
/* B2 = B2 - V2 * work */
gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &B2.matrix);
}
/* B1 = B1 - V1 * work */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, work);
gsl_matrix_sub(&B1.matrix, work);
return GSL_SUCCESS;
}
}
/*
unpack_Q1()
Compute Q_1
Inputs: Q - on input, contains T in upper triangle and V in lower trapezoid
on output, contains Q_1
M-by-N
Return: success/error
Notes:
1) N
Q1 = [ Q1 Q2 ] [ I_n ] = (I - V T V^T) [ I; 0 ] = [ I - V1 T V1^T ] N
[ 0 ] [ - V2 T V1^T ] M - N
*/
static int
unpack_Q1(gsl_matrix * Q)
{
int status;
const size_t M = Q->size1;
const size_t N = Q->size2;
gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, N);
gsl_vector_view diag = gsl_matrix_diagonal(&Q1.matrix);
/* Q1 := T V1^T */
status = aux_ULT(&Q1.matrix, &Q1.matrix);
if (status)
return status;
if (M > N)
{
/* compute Q2 := - V2 T V1^T */
gsl_matrix_view V2 = gsl_matrix_submatrix(Q, N, 0, M - N, N);
gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Q1.matrix, &V2.matrix);
}
/* Q1 := - V1 T V1^T */
status = aux_mLU(&Q1.matrix);
if (status)
return status;
/* Q1 := I - V1 T V1^T */
gsl_vector_add_constant(&diag.vector, 1.0);
return GSL_SUCCESS;
}
/*
unpack_Q2()
Compute Q_2
Inputs: QR - [R; V] from QR_decomp_r, M-by-N
T - upper triangular T factor, N-by-N
Q - (output) Q_2 factor, M-by-(M-N)
Return: success/error
Notes: N M-N
1) Since Q = I - V T V^T = M [ Q1 Q2 ], we have
M-N
Q2 = Q [ 0 ] N
[ I_{M-N} ] M-N
So, Q2 = Q [ 0; I ] = (I - V T V^T) [ 0; I ] = [ - V1 T V2^T ]
[ I - V2 T V2^T ]
*/
static int
unpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (M <= N)
{
GSL_ERROR ("M must be > N", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix must be N-by-N", GSL_EBADLEN);
}
else if (Q->size1 != M || Q->size2 != (M - N))
{
GSL_ERROR ("Q matrix must be M-by-(M-N)", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);
gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);
gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, M - N);
gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, N, 0, M - N, M - N);
gsl_vector_view diag = gsl_matrix_diagonal(&Q2.matrix);
/* Q1 := V2^T */
gsl_matrix_transpose_memcpy(&Q1.matrix, &V2.matrix);
/* Q1 := - T V2^T */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, T, &Q1.matrix);
/* Q2 := - V2 T V2^T */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &V2.matrix, &Q1.matrix, 0.0, &Q2.matrix);
/* Q2 := I - V2 T V2^T */
gsl_vector_add_constant(&diag.vector, 1.0);
/* Q1 := - V1 T V2^T */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, &Q1.matrix);
return GSL_SUCCESS;
}
}
/* U := U L^T for triangular matrices L and U; L is unit lower triangular */
static int
aux_ULT(const gsl_matrix * L, gsl_matrix * U)
{
const size_t N = L->size1;
if (N != L->size2)
{
GSL_ERROR ("L matrix must be square", GSL_ENOTSQR);
}
else if (U->size1 != N || U->size2 != N)
{
GSL_ERROR ("U matrix must be same size as L", GSL_EBADLEN);
}
else if (N == 1)
{
/* nothing to do */
return GSL_SUCCESS;
}
else
{
int status;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
gsl_matrix_const_view L11 = gsl_matrix_const_submatrix(L, 0, 0, N1, N1);
gsl_matrix_const_view L21 = gsl_matrix_const_submatrix(L, N1, 0, N2, N1);
gsl_matrix_const_view L22 = gsl_matrix_const_submatrix(L, N1, N1, N2, N2);
gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1);
gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2);
gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2);
/* U12 = U12 * L22^T */
gsl_blas_dtrmm(CblasRight, CblasLower, CblasTrans, CblasUnit, 1.0, &L22.matrix, &U12.matrix);
/* U12 = U12 + U11 * L21^T */
status = aux_ApUBT(&U11.matrix, &L21.matrix, &U12.matrix);
if (status)
return status;
status = aux_ULT(&L11.matrix, &U11.matrix);
if (status)
return status;
status = aux_ULT(&L22.matrix, &U22.matrix);
if (status)
return status;
return GSL_SUCCESS;
}
}
/* store -L*U in A */
static int
aux_mLU(gsl_matrix * A)
{
const size_t N = A->size1;
if (N != A->size2)
{
GSL_ERROR ("matrix must be square", GSL_ENOTSQR);
}
else if (N == 1)
{
double *A00 = gsl_matrix_ptr(A, 0, 0);
*A00 = -(*A00);
return GSL_SUCCESS;
}
else
{
int status;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);
gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1);
gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2);
/* A22 = - L22 U22 */
status = aux_mLU(&A22.matrix);
if (status)
return status;
/* A22 = A22 - L21 U12 */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &A12.matrix, 1.0, &A22.matrix);
/* A12 - -L11 U12 */
gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, -1.0, &A11.matrix, &A12.matrix);
/* A21 = -L21 U11 */
gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &A11.matrix, &A21.matrix);
/* A11 = - L11 U11 */
status = aux_mLU(&A11.matrix);
if (status)
return status;
return GSL_SUCCESS;
}
}
/* A := A + U B^T where U is upper triangular */
static int
aux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (U->size1 != M || U->size2 != M)
{
GSL_ERROR ("U matrix has wrong dimensions", GSL_EBADLEN);
}
else if (B->size1 != N || B->size2 != M)
{
GSL_ERROR ("B matrix has wrong dimensions", GSL_EBADLEN);
}
else if (M == 1 && N == 1)
{
double *aptr = gsl_matrix_ptr(A, 0, 0);
const double *uptr = gsl_matrix_const_ptr(U, 0, 0);
const double *bptr = gsl_matrix_const_ptr(B, 0, 0);
*aptr += (*uptr) * (*bptr);
return GSL_SUCCESS;
}
else if (M == 1)
{
double U00 = gsl_matrix_get(U, 0, 0);
gsl_vector_view v = gsl_matrix_row(A, 0);
gsl_vector_const_view w = gsl_matrix_const_column(B, 0);
gsl_blas_daxpy(U00, &w.vector, &v.vector);
return GSL_SUCCESS;
}
else if (N == 1)
{
/*
* partition:
*
* M1 M2
* B = 1 [ B11 B12 ]
*
* 1 M1 M2 1
* M1 [ A11 ] + [ U11 U12 ] [ B11^T ] M1
* M2 [ A21 ] [ 0 U22 ] [ B12^T ] M2
*/
int status;
const size_t M1 = M / 2;
const size_t M2 = M - M1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, 1);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, 1);
gsl_vector_view a1 = gsl_matrix_subcolumn(A, 0, 0, M1);
gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1);
gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2);
gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2);
gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, 1, M1);
gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, 1, M2);
gsl_vector_const_view b2 = gsl_matrix_const_subrow(B, 0, M1, M2);
/* A(1:M1,1) += U12 * B12^T */
gsl_blas_dgemv(CblasNoTrans, 1.0, &U12.matrix, &b2.vector, 1.0, &a1.vector);
/* A11 := A11 + U11 B11^T */
status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix);
if (status)
return status;
/* A21 := A21 + U22 B12^T */
status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix);
if (status)
return status;
return GSL_SUCCESS;
}
else
{
int status;
const size_t M1 = M / 2;
const size_t M2 = M - M1;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, N1);
gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, M1, N2);
gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, N1);
gsl_matrix_view A22 = gsl_matrix_submatrix(A, M1, N1, M2, N2);
gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1);
gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2);
gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2);
gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, N1, M1);
gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, N1, M2);
gsl_matrix_const_view B21 = gsl_matrix_const_submatrix(B, N1, 0, N2, M1);
gsl_matrix_const_view B22 = gsl_matrix_const_submatrix(B, N1, M1, N2, M2);
/* A11 := A11 + U11 B11^T */
status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix);
if (status)
return status;
/* A11 := A11 + U12 B12^T */
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B12.matrix, 1.0, &A11.matrix);
/* A12 := A12 + U11 B21^T */
status = aux_ApUBT(&U11.matrix, &B21.matrix, &A12.matrix);
if (status)
return status;
/* A12 := A12 + U12 B22^T */
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B22.matrix, 1.0, &A12.matrix);
/* A21 := A21 + U22 B12^T */
status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix);
if (status)
return status;
/* A22 := A22 + U22 B22^T */
status = aux_ApUBT(&U22.matrix, &B22.matrix, &A22.matrix);
if (status)
return status;
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5673197165,
"avg_line_length": 30.0216154721,
"ext": "c",
"hexsha": "643f6f10c1d6fc698bd869825e4c0f3d4f65d8ae",
"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/rqr.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/rqr.c",
"max_line_length": 135,
"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/rqr.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": 8772,
"size": 26389
} |
#ifndef HIC_MPLD_POSTDOC_H
#define HIC_MPLD_POSTDOC_H
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <map>
#include <math.h>
//#include <mpi.h>
#include <omp.h>
#include <vector>
#include <gsl/gsl_cdf.h>
#include <../IRLS_glm/IRLS.h>
#include <regionDetail2D_pairSite.hpp>
#include <bothEndsMappedFragInfo_withCuttingSite.hpp>
#include <RInside.h>
#define INTTAG 0
#define BOOLTAG 1
#define DIETAG 2
#define NEIGHBDIS 5
#define MORANI 0.001
#define PCUTOFF 0.004
#define PRECISION 100000
//using namespace std;
using std::abs;
using std::basic_string;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::exception;
using std::flush;
using std::ifstream;
using std::istringstream;
using std::make_pair;
using std::map;
using std::ofstream;
using std::ostringstream;
using std::pair;
using std::sort;
using std::string;
using std::vector;
int postdoc(vector<double>, map<int, int>, const int, const string);
int receiveDomainMap(vector< pair<int, int> >&);
int write_domainFragInteractionMatrix(map< pair< pair< int, pair<int, int> >, pair< int, pair<int, int> > >, vector<fragInfo_bothEndsMapped_withCuttingSite> >&, map<int, int>&, vector< pair<int, int> >&, int, string&);
int getDomainCSinteractionMatrix(map< pair< pair<int, int>, pair<int, int> >, int >&, map< int, vector<int> >&, vector< pair<int, int> >&, int, vector< vector<int> >&, vector< vector< vector<int> > >&, map< int, map<int, int> >&);
inline int convtIndex(int, int, int);
int findIntraDomainInteraction(string, vector< vector<int> >&, vector< vector< vector<int> > >&, map<int, int>&, map< int, map< pair<int, int>, double > >&);
int outputDomainInfo(string, vector< vector<int> >&, vector< vector< vector<int> > >&, map<int, int>&, map< int, map< pair<int, int>, double > >&);
int findInteractingRegion(int, map< int, map< pair<int, int>, double> >&, vector< vector<int> >&, vector<regionDetail_pairSite_2D>&);
int searchNeighbSites(map< pair<int, int>, double >&, map<int, int>&, int, int, int, int, vector< pair< pair<int, int>, double > >&, int&, double&);
int writer_2Dregion(vector<regionDetail_pairSite_2D>&, const string&);
int glm_lasso_fit(vector<double>&, vector<double>&, vector< vector<double> >&);
#endif
| {
"alphanum_fraction": 0.6921425505,
"avg_line_length": 35.2878787879,
"ext": "h",
"hexsha": "3b3ade9f42937601022f198d197838ed3f96e3d7",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-05-07T02:16:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-15T09:15:46.000Z",
"max_forks_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Lan-lab/Chrom-Lasso-",
"max_forks_repo_path": "Code/2_Arrange_Domain/HiC_mixturePLD_postdoc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40",
"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": "Lan-lab/Chrom-Lasso-",
"max_issues_repo_path": "Code/2_Arrange_Domain/HiC_mixturePLD_postdoc.h",
"max_line_length": 231,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3b1c7797bfdf0f7d3330339ace0929e8e2225a40",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Lan-lab/Chrom-Lasso-",
"max_stars_repo_path": "Code/2_Arrange_Domain/HiC_mixturePLD_postdoc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 665,
"size": 2329
} |
/* BRAINS
* (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling
* Yan-Rong Li, liyanrong@ihep.ac.cn
* Thu, Aug 4, 2016
*/
/*!
* \file user_blr_model.c
* \brief allow users to define their own BLR models.
*
* User should provide: 1) number of parameters in 1D and 2D;
* 2) struct for BLR model;
* 3) function for setting parameter range
* 4) function for calculating clouds' lag and weight in 1D
* 5) function for calculating clouds' lag, velocity, and weight in 2D
* 6) function for setting the parameter values used in simulation (if flag_dim<0)
*
* The following is an example. The users can make modification with their own BLR models.
*
*/
#include <gsl/gsl_randist.h>
#include "brains.h"
const int num_params_MyBLRmodel1d = 8; /*!< number of parameters for 1D model */
const int num_params_MyBLRmodel2d = 17; /*!< number of parameters for 2D model */
/*!
* set parameter range
*/
void set_blr_range_mymodel()
{
int i;
i = 0;
//mu
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
blr_range_model[i][0] = 0.001;
blr_range_model[i++][1] = 2.0;
//F
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//inc
blr_range_model[i][0] = 0.0; //in cosine
blr_range_model[i++][1] = 1.0;
//opn
blr_range_model[i][0] = 0.0; // in rad
blr_range_model[i++][1] = 90.0;
//k
blr_range_model[i][0] = -0.5;
blr_range_model[i++][1] = 0.5;
//gamma
blr_range_model[i][0] = 1.0;
blr_range_model[i++][1] = 5.0;
//xi
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//mbh
blr_range_model[i][0] = log(0.1);
blr_range_model[i++][1] = log(1.0e3);
//fellip
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//fflow
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 1.0;
//sigr_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_circ
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//sigr_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(0.1);
//sigthe_rad
blr_range_model[i][0] = log(0.001);
blr_range_model[i++][1] = log(1.0);
//theta_rot
blr_range_model[i][0] = 0.0;
blr_range_model[i++][1] = 90.0;
//sig_turb
blr_range_model[i][0] = log(0.0001);
blr_range_model[i++][1] = log(0.1);
return;
}
/*
* This function caclulate 2d transfer function.
*
* The clouds' lag, velocity, and weight are stored in arrays "clouds_tau", "clouds_vel", "clouds_weight",
* which must be provided.
*/
void gen_cloud_sample_mymodel(const void *pm, int flag_type, int flag_save)
{
int i, j, nc;
double r, phi, cos_phi, sin_phi, dis, Lopn_cos;
double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb;
double V, rhoV, theV, Vr, Vph, Vkep, Rs, g;
double inc, F, beta, mu, k, gam, xi, a, s, sig, rin;
double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot, sig_turb;
double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp;
double weight, rnd, rnd_xi;
MyBLRmodel *model = (MyBLRmodel *)pm;
Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */
inc = acos(model->inc); /* inclination angle in rad */
beta = model->beta;
F = model->F;
mu = exp(model->mu); /* mean radius */
k = model->k;
gam = model-> gam;
xi = model->xi;
mbh = exp(model->mbh);
fellip = model->fellip;
fflow = model->fflow;
sigr_circ = exp(model->sigr_circ);
sigthe_circ = exp(model->sigthe_circ);
sigr_rad = exp(model->sigr_rad);
sigthe_rad = exp(model->sigthe_rad);
theta_rot = model->theta_rot*PI/180.0;
sig_turb = exp(model->sig_turb);
Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days
a = 1.0/beta/beta;
s = mu/a;
rin=mu*F + Rs; // include Scharzschild radius
sig=(1.0-F)*s;
sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc);
cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc);
for(i=0; i<parset.n_cloud_per_task; i++)
{
// generate a direction of the angular momentum of the orbit
Lphi = 2.0*PI * gsl_rng_uniform(gsl_r);
Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * pow(gsl_rng_uniform(gsl_r), gam));
sin_Lphi = sin(Lphi);
cos_Lphi = cos(Lphi);
sin_Lthe = sin(Lthe);
cos_Lthe = cos(Lthe);
nc = 0;
r = rcloud_max_set+1.0;
while(r>rcloud_max_set || r<rcloud_min_set)
{
if(nc > 1000)
{
printf("# Error, too many tries in generating ridial location of clouds.\n");
exit(0);
}
rnd = gsl_ran_gamma(gsl_r, a, 1.0);
// r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu);
r = rin + sig * rnd;
nc++;
}
phi = 2.0*PI * gsl_rng_uniform(gsl_r);
cos_phi = cos(phi);
sin_phi = sin(phi);
/* Polar coordinates to Cartesian coordinate */
x = r * cos_phi;
y = r * sin_phi;
z = 0.0;
/* right-handed framework
* first rotate around y axis by an angle of Lthe, then rotate around z axis
* by an angle of Lphi
*/
/*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z;
yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z;
zb = sin(Lthe) * x + cos(Lthe) * z; */
xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y;
yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y;
zb = sin_Lthe * x;
zb0 = zb;
rnd_xi = gsl_rng_uniform(gsl_r);
if( (rnd_xi < 1.0 - xi) && zb0 < 0.0)
zb = -zb;
// counter-rotate around y, LOS is x-axis
/* x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc);
y = yb;
z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); */
x = xb * cos_inc_cmp + zb * sin_inc_cmp;
y = yb;
z =-xb * sin_inc_cmp + zb * cos_inc_cmp;
weight = 0.5 + k*(x/r);
clouds_weight[i] = weight;
#ifndef SA
dis = r - x;
clouds_tau[i] = dis;
if(flag_type == 1)
{
if(flag_save && thistask==roottask)
{
if(i%(icr_cloud_save) == 0)
fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z);
}
continue;
}
#else
switch(flag_type)
{
case 1: /* 1D RM */
dis = r - x;
clouds_tau[i] = dis;
if(flag_save && thistask==roottask)
{
if(i%(icr_cloud_save) == 0)
fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z);
}
continue;
break;
case 2: /* 2D RM */
dis = r - x;
clouds_tau[i] = dis;
break;
case 3: /* SA */
clouds_alpha[i] = y;
clouds_beta[i] = z;
break;
case 4: /* 1D RM + SA */
dis = r - x;
clouds_tau[i] = dis;
clouds_alpha[i] = y;
clouds_beta[i] = z;
break;
case 5: /* 2D RM + SA */
dis = r - x;
clouds_tau[i] = dis;
clouds_alpha[i] = y;
clouds_beta[i] = z;
break;
}
#endif
Vkep = sqrt(mbh/r);
for(j=0; j<parset.n_vel_per_cloud; j++)
{
rnd = gsl_rng_uniform(gsl_r);
if(rnd < fellip)
{
rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_circ + 1.0) * Vkep;
theV = (gsl_ran_ugaussian(gsl_r) * sigthe_circ + 0.5)*PI;
}
else
{
if(fflow <= 0.5) /* inflow */
{
rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep;
theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad + 1.0) * PI + theta_rot;
}
else /* outflow */
{
rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep;
theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad) * PI + theta_rot;
}
}
Vr = sqrt(2.0) * rhoV * cos(theV);
Vph = rhoV * sin(theV);
vx = Vr * cos_phi - Vph * sin_phi;
vy = Vr * sin_phi + Vph * cos_phi;
vz = 0.0;
/*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz;
vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz;
vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/
vxb = cos_Lthe*cos_Lphi * vx + sin_Lphi * vy;
vyb =-cos_Lthe*sin_Lphi * vx + cos_Lphi * vy;
vzb = sin_Lthe * vx;
if((rnd_xi < 1.0-xi) && zb0 < 0.0)
vzb = -vzb;
/*vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc);
vy = vyb;
vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc);*/
vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp;
vy = vyb;
vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp;
V = -vx; //note the definition of the line-of-sight velocity. postive means a receding
// velocity relative to the observer.
V += gsl_ran_ugaussian(gsl_r) * sig_turb * Vkep; // add turbulence velocity
if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light
V = 0.9999*C_Unit * (V>0.0?1.0:-1.0);
g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects
V = (g-1.0)*C_Unit;
clouds_vel[i*parset.n_vel_per_cloud + j] = V;
if(flag_save && thistask==roottask)
{
if(i%(icr_cloud_save) == 0)
fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight);
}
}
}
return;
}
/*!
* set parameter values used in simulation (if flag_dim < 0).
*/
void set_par_value_mymodel_sim(double *pm)
{
int i;
i=0;
pm[i++] = log(4.0); // mu
pm[i++] = 1.0; // beta
pm[i++] = 0.25; // F
pm[i++] = cos(20.0/180.0*PI); // inc
pm[i++] = 40.0; // opn
pm[i++] = -0.4; // kappa
pm[i++] = 5.0; // gamma
pm[i++] = 0.5; // obscuration
pm[i++] = log(2.0); //mbh
pm[i++] = 0.5; //fellip
pm[i++] = 0.4; //fflow
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = 0.0; // theta_rot
pm[i++] = log(0.001); // sig_turb
pm[i++] = 0.0; // parameter for spectral broadening
}
#ifdef SA
/*!
* set parameter range
*/
void set_sa_blr_range_mymodel()
{
int i;
i = 0;
//mu
sa_blr_range_model[i][0] = log(0.1);
sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5);
//beta
sa_blr_range_model[i][0] = 0.001;
sa_blr_range_model[i++][1] = 2.0;
//F
sa_blr_range_model[i][0] = 0.0;
sa_blr_range_model[i++][1] = 1.0;
//inc
sa_blr_range_model[i][0] = 0.0; //in cosine
sa_blr_range_model[i++][1] = 1.0;
//opn
sa_blr_range_model[i][0] = 0.0; // in rad
sa_blr_range_model[i++][1] = 90.0;
//k
sa_blr_range_model[i][0] = -0.5;
sa_blr_range_model[i++][1] = 0.5;
//gamma
sa_blr_range_model[i][0] = 1.0;
sa_blr_range_model[i++][1] = 5.0;
//xi
sa_blr_range_model[i][0] = 0.0;
sa_blr_range_model[i++][1] = 1.0;
//mbh
sa_blr_range_model[i][0] = log(0.1);
sa_blr_range_model[i++][1] = log(1.0e3);
//fellip
sa_blr_range_model[i][0] = 0.0;
sa_blr_range_model[i++][1] = 1.0;
//fflow
sa_blr_range_model[i][0] = 0.0;
sa_blr_range_model[i++][1] = 1.0;
//sigr_circ
sa_blr_range_model[i][0] = log(0.001);
sa_blr_range_model[i++][1] = log(0.1);
//sigthe_circ
sa_blr_range_model[i][0] = log(0.001);
sa_blr_range_model[i++][1] = log(1.0);
//sigr_rad
sa_blr_range_model[i][0] = log(0.001);
sa_blr_range_model[i++][1] = log(0.1);
//sigthe_rad
sa_blr_range_model[i][0] = log(0.001);
sa_blr_range_model[i++][1] = log(1.0);
//theta_rot
sa_blr_range_model[i][0] = 0.0;
sa_blr_range_model[i++][1] = 90.0;
//sig_turb
sa_blr_range_model[i][0] = log(0.0001);
sa_blr_range_model[i++][1] = log(0.1);
return;
}
/*!
* set parameter values used in simulation (if flag_dim < 0).
*/
void set_sa_par_value_mymodel_sim(double *pm)
{
int i;
i=0;
pm[i++] = log(4.0); // mu
pm[i++] = 1.0; // beta
pm[i++] = 0.25; // F
pm[i++] = cos(20.0/180.0*PI); // inc
pm[i++] = 40.0; // opn
pm[i++] = -0.4; // kappa
pm[i++] = 5.0; // gamma
pm[i++] = 0.5; // obscuration
pm[i++] = log(2.0); //mbh
pm[i++] = 0.5; //fellip
pm[i++] = 0.4; //fflow
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = 0.0; // theta_rot
pm[i++] = log(0.001); // sig_turb
pm[i++] = 0.0; // parameter for spectral broadening
}
#endif
| {
"alphanum_fraction": 0.5519987131,
"avg_line_length": 27.4459161148,
"ext": "c",
"hexsha": "d2fba4a232de79a917e42263578ac23e60bcff9a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yzxamos/BRAINS",
"max_forks_repo_path": "src/user_blr_model.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yzxamos/BRAINS",
"max_issues_repo_path": "src/user_blr_model.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yzxamos/BRAINS",
"max_stars_repo_path": "src/user_blr_model.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4756,
"size": 12433
} |
#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 <fftw3.h> /* Note: when included AFTER complex.h, fftw_complex type defaults to native double complex */
#include "constants.h"
#include "struct.h"
/* Window functions */
double WindowFunction(double x, double xi, double xf, double deltaxi, double deltaxf)
{
double di = deltaxi/(20*log(10));
double df = deltaxf/(20*log(10));
if (x <= xi + di) return 0;
else if (xi +di < x && x < xi + deltaxi - di) {
return 1./(1 + exp(deltaxi/(x - xi) + deltaxi/(x - (xi + deltaxi))));
}
else if (xi + deltaxi - di <= x && x <= xf - deltaxf + df) return 1.;
else if (xf - deltaxf + df < x && x < xf - df) {
return 1./(1 + exp(-(deltaxf/(x - (xf - deltaxf))) - deltaxf/(x - xf)));
}
else return 0;
}
double WindowFunctionLeft(double x, double xf, double deltaxf)
{
double df = deltaxf/(20*log(10));
if (x <= xf - deltaxf + df) return 1;
else if (xf - deltaxf + df < x && x < xf - df) {
return 1./(1 + exp(-deltaxf/(x - (xf - deltaxf)) - deltaxf/(x - xf)));
}
else return 0;
}
double WindowFunctionRight(double x, double xi, double deltaxi)
{
double di = deltaxi/(20*log(10));
if (x <= xi + di) return 0;
else if (xi + di < x && x < xi + deltaxi - di) {
return 1./(1 + exp(deltaxi/(x - xi) + deltaxi/(x - (xi + deltaxi))));
}
else return 1;
}
/* FFT of real time series */
/* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
int FFTRealTimeSeries(ReImFrequencySeries** freqseries, RealTimeSeries* timeseries, double twindowbeg, double twindowend, int nzeropad)
{
/* deltat of time series */
/* Warning: assumes linear sampling in time */
double* times = timeseries->times->data;
double deltat = times[1] - times[0];
double tshift = times[0]; /* time shift to be re-applied later */
/* Initialize vector for windowed, 0-padded FFT input */
int n = (int) timeseries->times->size;
int nzeros = (int) pow(2, ((int) ceil(log(n)/log(2))) + nzeropad) - n; /* Here defined with ceil, but with floor in IFFT */
gsl_vector* hvalues = gsl_vector_alloc(n + nzeros);
gsl_vector_set_zero(hvalues);
/* Compute input TD values, with windowing */
int nbptswindowbeg = (int) ceil(twindowbeg/deltat) + 1;
int nbptswindowend = (int) ceil(twindowend/deltat) + 1;
double t1windowbeg = times[0];
double t2windowbeg = times[nbptswindowbeg-1];
double t1windowend = times[n-nbptswindowend];
double t2windowend = times[n-1];
double deltatwindowbeg = t2windowbeg - t1windowbeg;
double deltatwindowend = t2windowend - t1windowend;
double* h = timeseries->h->data;
double* hval = hvalues->data;
for (int i=0; i<nbptswindowbeg; i++) {
hval[i] = WindowFunctionRight(times[i], t1windowbeg, deltatwindowbeg) * h[i];
}
for (int i=nbptswindowbeg; i<n-nbptswindowend; i++) {
hval[i] = h[i];
}
for (int i=n-nbptswindowend; i<n; i++) {
hval[i] = WindowFunctionLeft(times[i], t2windowend, deltatwindowend) * h[i];
}
/* FFT - uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
int N = (int) hvalues->size;
fftw_plan p;
double* in = hvalues->data;
fftw_complex* out;
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); /* Note: N/2+1 elements */
p = fftw_plan_dft_r2c_1d(N, in, out, FFTW_ESTIMATE);
fftw_execute(p);
/* Initialize output structure */
ReImFrequencySeries_Init(freqseries, N/2); /* Note: N/2+1 elements as output of fftw, we drop the last one (at Nyquist frequency) */
/* Extracting and converting data from FFTW output */
double deltaf = 1./(N*deltat);
double* freq = (*freqseries)->freq->data;
double* hreal = (*freqseries)->h_real->data;
double* himag = (*freqseries)->h_imag->data;
double f;
double complex hcomplex;
double factorshift = 2*PI*tshift; /* Reminder: Flipped sign convention */
for(int i=0; i<N/2; i++) {
f = i*deltaf;
freq[i] = f;
hcomplex = deltat * conj(out[i]) * cexp(I*factorshift*f); /* Note that we convert here the FT sign convention */
hreal[i] = creal(hcomplex);
himag[i] = cimag(hcomplex);
}
/* Clean up */
gsl_vector_free(hvalues);
fftw_destroy_plan(p);
fftw_free(out);
return SUCCESS;
}
/* FFT of Re/Im time series */
/* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
/* NOTE: only keeps positive frequencies in the output */
int FFTTimeSeries(ReImFrequencySeries** freqseries, ReImTimeSeries* timeseries, double twindowbeg, double twindowend, int nzeropad)
{
/* deltat of time series */
/* Warning: assumes linear sampling in time */
double* times = timeseries->times->data;
double deltat = times[1] - times[0];
double tshift = times[0]; /* time shift to be re-applied later */
/* Initialize vector for windowed, 0-padded FFT input */
int n = (int) timeseries->times->size;
int nzeros = (int) pow(2, ((int) ceil(log(n)/log(2))) + nzeropad) - n; /* Here defined with ceil, but with floor in IFFT */
int N = n + nzeros;
/* Compute input TD values, with windowing */
int nbptswindowbeg = (int) ceil(twindowbeg/deltat) + 1;
int nbptswindowend = (int) ceil(twindowend/deltat) + 1;
double t1windowbeg = times[0];
double t2windowbeg = times[nbptswindowbeg-1];
double t1windowend = times[n-nbptswindowend];
double t2windowend = times[n-1];
double deltatwindowbeg = t2windowbeg - t1windowbeg;
double deltatwindowend = t2windowend - t1windowend;
double* htdreal = timeseries->h_real->data;
double* htdimag = timeseries->h_imag->data;
fftw_complex* in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
for (int i=0; i<nbptswindowbeg; i++) {
in[i] = WindowFunctionRight(times[i], t1windowbeg, deltatwindowbeg) * (htdreal[i] + I*htdimag[i]);
}
for (int i=nbptswindowbeg; i<n-nbptswindowend; i++) {
in[i] = (htdreal[i] + I*htdimag[i]);
}
for (int i=n-nbptswindowend; i<n; i++) {
in[i] = WindowFunctionLeft(times[i], t2windowend, deltatwindowend) * (htdreal[i] + I*htdimag[i]);
}
/* FFT - uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
/* Represented here by the use of FFTW_BACKWARD (plus sign in the exp) */
fftw_plan p;
fftw_complex* out;
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); /* Note: N/2+1 elements */
p = fftw_plan_dft_1d(N, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_execute(p);
/* Initialize output structure */
ReImFrequencySeries_Init(freqseries, N/2); /* NOTE: N/2 first elements of output of fftw are positive freqs, we eliminate negative frequency (the second half of the series) */
/* Extracting and converting data from FFTW output */
double deltaf = 1./(N*deltat);
double* freq = (*freqseries)->freq->data;
double* hreal = (*freqseries)->h_real->data;
double* himag = (*freqseries)->h_imag->data;
double f;
double complex hcomplex;
double factorshift = 2*PI*tshift; /* Reminder: Flipped sign convention */
for(int i=0; i<N/2; i++) {
f = i*deltaf;
freq[i] = f;
hcomplex = deltat * out[i] * cexp(I*factorshift*f); /* Note the FT sign convention */
hreal[i] = creal(hcomplex);
himag[i] = cimag(hcomplex);
}
/* Clean up */
fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);
return SUCCESS;
}
/* IFFT of frequency series */
/* Note: assumes frequency series is FT of real data - produces real time series */
/* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
int IFFTFrequencySeriesReal(RealTimeSeries** timeseries, ReImFrequencySeries* freqseries, double f1windowbeg, double f2windowbeg, double f1windowend, double f2windowend, int nzeropad)
{
/* Checking sanity of windowing frequencies */
if(!((f1windowbeg<f2windowbeg)&&(f1windowend<f2windowend)&&(f2windowbeg<f1windowend))) {
printf("Error in IFFTFrequencySeriesReal: inconsistent windowing frequencies.\n");
printf("(f1windowbeg, f2windowbeg, f1windowend, f2windowend) = (%g, %g, %g, %g)\n", f1windowbeg, f2windowbeg, f1windowend, f2windowend);
}
/* deltaf of frequency series */
/* Warning: assumes linear sampling in frequency */
double* freq = freqseries->freq->data;
double deltaf = freq[1] - freq[0];
/* Initialize vector for windowed, 0-padded FFT input */
int n = (int) freqseries->freq->size;
while(freq[n-1] > f2windowend) n--;
int nzeros = (int) pow(2, ((int) ceil(log(n)/log(2))) + nzeropad) - n; /* Here defined with floor, but with ceil in FFT */
gsl_vector* hrealvalues = gsl_vector_alloc(n + nzeros);
gsl_vector* himagvalues = gsl_vector_alloc(n + nzeros);
gsl_vector_set_zero(hrealvalues);
gsl_vector_set_zero(himagvalues);
/* Compute input FD values, with windowing */
double deltafwindowbeg = f2windowbeg - f1windowbeg;
double deltafwindowend = f2windowend - f1windowend;
double* hreal = freqseries->h_real->data;
double* himag = freqseries->h_imag->data;
double* hrealval = hrealvalues->data;
double* himagval = himagvalues->data;
for (int i=0; i<n; i++) {
double window = WindowFunction(freq[i], f1windowbeg, f2windowend, deltafwindowbeg, deltafwindowend);
hrealval[i] = window * hreal[i];
himagval[i] = window * himag[i];
}
/* Input as array of fftw_complex */
int N = (int) hrealvalues->size;
fftw_complex* in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
/* NOTE: Restoring the standard sign convention for the FT, used by FFTW - change in convention amounts to f->-f, equivalent to a conjugation only for FFT of a real series */
for(int i=0; i<n; i++) {
in[i] = hrealval[i] - I*himagval[i] ;
}
for(int i=n; i<N; i++) {
in[i] = 0;
}
/* FFT - uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
fftw_plan p;
double* out = fftw_malloc(sizeof(double) * N);
p = fftw_plan_dft_c2r_1d(N, in, out, FFTW_ESTIMATE);
fftw_execute(p);
/* Initialize output structure */
RealTimeSeries_Init(timeseries, N);
/* Extracting and converting data from FFTW output - moving negative times to the left */
double deltat = 1./(N*deltaf);
double fac = 1./(N*deltat); /* Additional 1/N to put the FFTW convention in agreement with numpy IFFT */
double* times = (*timeseries)->times->data;
double* h = (*timeseries)->h->data;
for(int i=0; i<N/2; i++) {
times[i] = (i-N/2)*deltat;
times[N/2+i] = i*deltat;
h[i] = fac * out[N/2+i];
h[N/2+i] = fac * out[i];
}
/* Clean up */
gsl_vector_free(hrealvalues);
gsl_vector_free(himagvalues);
fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);
return SUCCESS;
}
/* IFFT of frequency series */
/* Note: does not assume frequency series is FT of real data - produces complex time series */
/* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */
int IFFTFrequencySeries(ReImTimeSeries** timeseries, ReImFrequencySeries* freqseries, double f1windowbeg, double f2windowbeg, double f1windowend, double f2windowend, int nzeropad)
{
/* Checking sanity of windowing frequencies */
if(!((f1windowbeg<f2windowbeg)&&(f1windowend<f2windowend)&&(f2windowbeg<f1windowend))) {
printf("Error in IFFTFrequencySeries: inconsistent windowing frequencies.\n");
printf("(f1windowbeg, f2windowbeg, f1windowend, f2windowend) = (%g, %g, %g, %g)\n", f1windowbeg, f2windowbeg, f1windowend, f2windowend);
}
/* deltaf of frequency series */
/* Warning: assumes linear sampling in frequency */
double* freq = freqseries->freq->data;
double deltaf = freq[1] - freq[0];
/* Initialize vector for windowed, 0-padded FFT input */
int n = (int) freqseries->freq->size;
while(freq[n-1] > f2windowend) n--;
int nzeros = (int) pow(2, ((int) ceil(log(n)/log(2))) + nzeropad) - n; /* Here defined with floor, but with ceil in FFT */
gsl_vector* hrealvalues = gsl_vector_alloc(n + nzeros);
gsl_vector* himagvalues = gsl_vector_alloc(n + nzeros);
gsl_vector_set_zero(hrealvalues);
gsl_vector_set_zero(himagvalues);
/* Compute input FD values, with windowing */
double deltafwindowbeg = f2windowbeg - f1windowbeg;
double deltafwindowend = f2windowend - f1windowend;
double* hreal = freqseries->h_real->data;
double* himag = freqseries->h_imag->data;
double* hrealval = hrealvalues->data;
double* himagval = himagvalues->data;
for (int i=0; i<n; i++) {
double window = WindowFunction(freq[i], f1windowbeg, f2windowend, deltafwindowbeg, deltafwindowend);
hrealval[i] = window * hreal[i];
himagval[i] = window * himag[i];
}
/* Input as array of fftw_complex */
int N = (int) hrealvalues->size;
fftw_complex* in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
/* NOTE: the sign convention for the FT used by FFTW is different - change in convention amounts to f->-f, equivalent to a conjugation only for FFT of a real series - for a FFT of a complex series, we do not conjugate and we keep our convention */
for(int i=0; i<n; i++) {
in[i] = hrealval[i] + I*himagval[i] ;
}
for(int i=n; i<N; i++) {
in[i] = 0;
}
/* FFT - FFTW uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) - our convention is h(f) = int e^(-2ipift)h(t) */
/* NOTE: due to the difference in convention for the FT, we use the FFTW_FORWARD sign (sign - in the exponential) */
fftw_plan p;
double complex* out = fftw_malloc(sizeof(fftw_complex) * N);
p = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
/* Initialize output structure */
ReImTimeSeries_Init(timeseries, N);
/* Extracting and converting data from FFTW output - moving negative times to the left */
double deltat = 1./(N*deltaf);
double fac = 1./(N*deltat); /* Additional 1/N to put the FFTW convention in agreement with numpy IFFT */
double* times = (*timeseries)->times->data;
double* htdreal = (*timeseries)->h_real->data;
double* htdimag = (*timeseries)->h_imag->data;
for(int i=0; i<N/2; i++) {
times[i] = (i-N/2)*deltat;
times[N/2+i] = i*deltat;
htdreal[i] = fac * creal(out[N/2+i]);
htdimag[i] = fac * cimag(out[N/2+i]);
htdreal[N/2+i] = fac * creal(out[i]);
htdimag[N/2+i] = fac * cimag(out[i]);
}
/* Clean up */
gsl_vector_free(hrealvalues);
gsl_vector_free(himagvalues);
fftw_destroy_plan(p);
fftw_free(in);
fftw_free(out);
return SUCCESS;
}
| {
"alphanum_fraction": 0.67010452,
"avg_line_length": 39.0459459459,
"ext": "c",
"hexsha": "10eda939163597cf22337bf623393df08ee87263",
"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": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "tools/fft.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"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": "titodalcanton/flare",
"max_issues_repo_path": "tools/fft.c",
"max_line_length": 249,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "tools/fft.c",
"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": 4616,
"size": 14447
} |
#ifndef __GSLEXTRA_H__
#define __GSLEXTRA_H__
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#endif
void gsl_vector_complex_convert(gsl_vector * source, gsl_vector_complex * target, int length);
void gsl_matrix_complex_convert(gsl_matrix * source, gsl_matrix_complex * target, int rows, int columns);
void gsl_vector_complex_extract(gsl_vector_complex * source, gsl_vector * real, gsl_vector * imag, int length);
void gsl_matrix_complex_extract(gsl_vector_complex * source, gsl_matrix * real,gsl_matrix * imag, int rows, int columns);
void gsl_vector_complex_combine(gsl_vector * real, gsl_vector * imag, gsl_vector_complex * target);
void gsl_matrix_complex_combine(gsl_matrix * real,gsl_matrix * imag, gsl_matrix_complex * target);
void gsl_matrix_diag(gsl_matrix * target, gsl_vector * diag, int length);
void gsl_matrix_complex_diag(gsl_matrix_complex * target, gsl_vector_complex * diag, int length);
void gsl_matrix_mul(gsl_matrix * A, gsl_matrix *B, gsl_matrix * Result,int Acolumn,int Arow,int Bcolumn);
void gsl_matrix_complex_mul(gsl_matrix_complex * A, gsl_matrix_complex *B, gsl_matrix_complex * Result,int Acolumn,int Arow,int Bcolumn);
double gsl_vector_inner_product(gsl_vector * A, gsl_vector * B,int length);
gsl_complex gsl_vector_complex_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);
gsl_complex gsl_vector_complex_inner_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);
void gsl_vector_transform(gsl_vector * vec,gsl_matrix * trf,int length);
void gsl_vector_complex_transform(gsl_vector_complex * vec, gsl_matrix_complex * trf,int length);
void gsl_matrix_unitmatrix(gsl_matrix * m,int length);
void gsl_matrix_complex_unitmatrix(gsl_matrix_complex * m,int length);
void gsl_vector_complex_conjugate(gsl_vector_complex * v, int length);
void gsl_matrix_complex_conjugate(gsl_matrix_complex * m, int rows, int columns); | {
"alphanum_fraction": 0.8090869375,
"avg_line_length": 54.5,
"ext": "h",
"hexsha": "61c376dfb52ebeaaa69744fae1c69ac7dad8475d",
"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": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/HomebrewLib",
"max_forks_repo_path": "gslextra.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"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": "Walter-Feng/HomebrewLib",
"max_issues_repo_path": "gslextra.h",
"max_line_length": 137,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/HomebrewLib",
"max_stars_repo_path": "gslextra.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-27T12:45:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-27T12:45:50.000Z",
"num_tokens": 567,
"size": 2289
} |
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
#include "DirectionalLight.h"
namespace Library
{
class Texture2D;
class ProxyModel;
}
namespace Rendering
{
class DisplacementMappingMaterial;
class DisplacementMappingDemo final : public Library::DrawableGameComponent
{
public:
DisplacementMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
DisplacementMappingDemo(const DisplacementMappingDemo&) = delete;
DisplacementMappingDemo(DisplacementMappingDemo&&) = default;
DisplacementMappingDemo& operator=(const DisplacementMappingDemo&) = default;
DisplacementMappingDemo& operator=(DisplacementMappingDemo&&) = default;
~DisplacementMappingDemo();
bool RealDisplacementMapEnabled() const;
void SetRealDisplacementMapEnabled(bool enabled);
void ToggleRealDisplacementMap();
float AmbientLightIntensity() const;
void SetAmbientLightIntensity(float intensity);
float DirectionalLightIntensity() const;
void SetDirectionalLightIntensity(float intensity);
const DirectX::XMFLOAT3& LightDirection() const;
void RotateDirectionalLight(DirectX::XMFLOAT2 amount);
const float DisplacementScale() const;
void SetDisplacementScale(float displacementScale);
virtual void Initialize() override;
virtual void Update(const Library::GameTime& gameTime) override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
std::shared_ptr<DisplacementMappingMaterial> mMaterial;
DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity };
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mIndexBuffer;
std::uint32_t mIndexCount{ 0 };
Library::DirectionalLight mDirectionalLight;
std::unique_ptr<Library::ProxyModel> mProxyModel;
std::shared_ptr<Library::Texture2D> mRealDisplacementMap;
std::shared_ptr<Library::Texture2D> mDefaultDisplacementMap;
bool mUpdateMaterial{ true };
bool mRealDisplacementMapEnabled{ true };
};
} | {
"alphanum_fraction": 0.7970033833,
"avg_line_length": 32.8412698413,
"ext": "h",
"hexsha": "8b19fd573e8a1f1b18b371f251931d225ccd3dd4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/6.2_Displacement_Mapping/DisplacementMappingDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 505,
"size": 2069
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \defgroup ioda_cxx_types Type System
* \brief The data type system
* \ingroup ioda_cxx_api
*
* @{
* \file Type.h
* \brief Interfaces for ioda::Type and related classes. Implements the type system.
*/
#include <array>
#include <cstring>
#include <functional>
#include <gsl/gsl-lite.hpp>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <vector>
#include "ioda/Exception.h"
#include "ioda/Types/Type_Provider.h"
#include "ioda/defs.h"
namespace ioda {
class Group;
class Type;
/// Basic pre-defined types (Python convenience wrappers)
/// \see py_ioda.cpp
/// \note Names here do not match the Python equivalents. The
/// Python names match numpy's definitions.
enum class BasicTypes {
undefined_, ///< Internal use only
float_,
double_,
ldouble_,
char_,
short_,
ushort_,
int_,
uint_,
lint_,
ulint_,
llint_,
ullint_,
int32_,
uint32_,
int16_,
uint16_,
int64_,
uint64_,
bool_,
str_
};
/// \brief Data Types can be grouped into a few categories. These are the categories.
/// \note Not all backends implement all types.
enum class TypeClass {
Unknown, ///< Unsupported / unhandled type
Integer, ///< All integer types
Float, ///< All floating-point types
String, ///< All string types (fixed-length, variable, ASCII, UTF-8)
Bitfield, ///< All bit fields
Opaque, ///< All binary blobs
Compound, ///< All compound types (types with member elements)
Reference, ///< All object references
Enum, ///< All enumerated types
VlenArray, ///< All variable-length array types (not strings)
FixedArray ///< All fixed-length array types
};
namespace detail {
/// \brief Convenience function to safely copy a string.
IODA_DL size_t COMPAT_strncpy_s(char* dest, size_t destSz, const char* src, size_t srcSz);
class Type_Backend;
template <class Type_Implementation = Type>
class Type_Base {
friend class ::ioda::Type;
std::shared_ptr<Type_Backend> backend_;
protected:
::ioda::detail::Type_Provider* provider_;
/// @name General Functions
/// @{
Type_Base(std::shared_ptr<Type_Backend> b, ::ioda::detail::Type_Provider* p)
: backend_(b), provider_(p) {}
/// Get the type provider.
inline detail::Type_Provider* getTypeProvider() const { return provider_; }
public:
virtual ~Type_Base() {}
std::shared_ptr<Type_Backend> getBackend() const { return backend_; }
bool isValid() const { return (backend_.use_count() > 0); }
/// @}
/// @name General functions
/// @{
/// \brief Get the size of a type, in bytes.
/// \details This function is paired with the read and write functions to allow you to
/// read and write data in a type-agnostic manner.
/// This size report is a bit complicated when variable-length strings are encountered.
/// In these cases, the size of the string pointer is returned.
virtual size_t getSize() const;
/// \brief Does this type represent a string, an integer, a float, an array, an
/// enumeration, a bitset, or any other type?
virtual TypeClass getClass() const;
/// \brief Save (commit) the type to a backend
/// \details From the HDF5 docs:
/// Committed datatypes can be used to save space in a file where many
/// datasets or attributes use the same datatype or to avoid defining a complex
/// compound datatype more than once. Committed datatypes can also be used to ensure
/// that multiple instances of the same datatype are truly identical.
///
/// This is used extensively for enumerated types.
virtual void commitToBackend(Group& d, const std::string& name) const;
/// @}
/// @name Numeric type functions
/// @{
/// \brief Is this type signed or unsigned?
/// \returns true if signed, false if unsigned.
/// \throws if the type is not a numeric type (i.e. not a simple integer or float).
virtual bool isTypeSigned() const;
/// @}
/// @name String type functions
/// @{
/// \brief Is this a variable-length string type?
/// \returns true if a variable-length string type, false if not.
/// False can imply either that the type is a fixed-length string type (if getClass() == TypeClass::String),
/// or that the type is not a string type at all.
virtual bool isVariableLengthStringType() const;
/// \brief Get the character set of this string type.
/// \returns Ascii or Unicode.
/// \throws ioda::Exception on error, or if the type is not a string type.
/// \note Currently, there is no way to set the character set. Everything is
/// assumed to be a UTF-8 string in IODA.
virtual StringCSet getStringCSet() const;
/// @}
/// @name Array type functions
/// @{
/// \brief Get the "base" type of an object. For an array, this is the type of
/// the array's elements. I.e. an array of int32_t has a base type of int32_t.
/// For an enumerated type, this is the type used for the enumeration.
virtual Type_Implementation getBaseType() const;
/// \brief Get the dimensions of an array type.
/// \returns A vector of the dimensions. vector::size() is the rank (dimensionality).
virtual std::vector<Dimensions_t> getDimensions() const;
/// @}
};
} // namespace detail
/// \brief Represents the "type" (i.e. integer, string, float) of a piece of data.
/// \ingroup ioda_cxx_types
///
/// Generally, you do not have to use this class directly. Attributes and Variables have
/// templated functions that convert your type into the type used internally by ioda.
/// \see Types::GetType and Types::GetType_Wrapper for functions that produce these types.
class IODA_DL Type : public detail::Type_Base<> {
public:
Type();
Type(std::shared_ptr<detail::Type_Backend> b, std::type_index t);
Type(BasicTypes, gsl::not_null<::ioda::detail::Type_Provider*> t);
virtual ~Type();
/// @name Type-querying functions
/// @{
/// @deprecated This function is problematic since we cannot query a type properly
/// when loading from a file.
std::type_index getType() const { return as_type_index_; }
inline std::type_index operator()() const { return getType(); }
inline std::type_index get() const { return getType(); }
/// @}
private:
std::type_index as_type_index_;
};
namespace detail {
/// Backends inherit from this and they provide their own functions.
/// Lots of std::dynamic_cast, unfortunately.
class IODA_DL Type_Backend : public Type_Base<> {
public:
virtual ~Type_Backend();
StringCSet getStringCSet() const override;
protected:
Type_Backend();
};
} // namespace detail
/// \brief Defines the type system used for manipulating IODA objects.
namespace Types {
// using namespace ioda::Handles;
/// \brief Convenience struct to determine if a type can represent a string.
/// \ingroup ioda_cxx_types
/// \todo extend to UTF-8 strings, as HDF5 supports these. No support for UTF-16, but conversion
/// functions may be applied.
/// \todo Fix for "const std::string".
template <typename T>
struct is_string : public std::integral_constant<
bool, std::is_same<char*, typename std::decay<T>::type>::value
|| std::is_same<const char*, typename std::decay<T>::type>::value> {};
/// \brief Convenience struct to determine if a type can represent a string.
/// \ingroup ioda_cxx_types
template <>
struct is_string<std::string> : std::true_type {};
/// Useful compile-time definitions.
namespace constants {
/// \note Different than ObsSpace variable-length dimension. This is for a Type.
constexpr size_t _Variable_Length = 0;
// constexpr int _Not_An_Array_type = -3;
} // namespace constants
/// \brief For fundamental, non-string types.
/// \ingroup ioda_cxx_types
template <class DataType, int Array_Type_Dimensionality = 0>
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> Adims = {},
typename std::enable_if<!is_string<DataType>::value>::type* = 0) {
if (Array_Type_Dimensionality <= 0)
throw Exception(
"Bad assertion / unsupported type at the frontend side "
"of the ioda type system.",
ioda_Here());
else
return t->makeArrayType(Adims, typeid(DataType[]), typeid(DataType));
}
/// \brief For fundamental string types. These are either constant or variable length arrays.
/// Separate handling elsewhere.
/// \ingroup ioda_cxx_types
/// \todo Once C++20 support is added, make a distinction between std::string and std::u8string.
template <class DataType, int String_Type_Length = constants::_Variable_Length>
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> = {},
typename std::enable_if<is_string<DataType>::value>::type* = 0) {
return t->makeStringType(typeid(DataType), String_Type_Length);
}
// This macro just repeats a long definition
/// @def IODA_ADD_FUNDAMENTAL_TYPE
/// Macro that defines a "fundamental type" that needs to be supported
/// by the backend. These match C++11.
/// \ingroup ioda_cxx_types
/// \see https://en.cppreference.com/w/cpp/language/types
/// \since C++11: we use bool, short int, unsigned short int,
/// int, unsigned int, long int, unsigned long int,
/// long long int, unsigned long long int,
/// signed char, unsigned char, char,
/// wchar_t, char16_t, char32_t,
/// float, double, long double.
/// \since C++20: we also add char8_t.
#define IODA_ADD_FUNDAMENTAL_TYPE(x) \
template <> \
inline Type GetType<x, 0>(gsl::not_null<const ::ioda::detail::Type_Provider*> t, \
std::initializer_list<Dimensions_t>, void*) { \
return t->makeFundamentalType(typeid(x)); \
}
IODA_ADD_FUNDAMENTAL_TYPE(bool);
IODA_ADD_FUNDAMENTAL_TYPE(short int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned short int);
IODA_ADD_FUNDAMENTAL_TYPE(int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned int);
IODA_ADD_FUNDAMENTAL_TYPE(long int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned long int);
IODA_ADD_FUNDAMENTAL_TYPE(long long int);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned long long int);
IODA_ADD_FUNDAMENTAL_TYPE(signed char);
IODA_ADD_FUNDAMENTAL_TYPE(unsigned char);
IODA_ADD_FUNDAMENTAL_TYPE(char);
IODA_ADD_FUNDAMENTAL_TYPE(wchar_t);
IODA_ADD_FUNDAMENTAL_TYPE(char16_t);
IODA_ADD_FUNDAMENTAL_TYPE(char32_t);
// IODA_ADD_FUNDAMENTAL_TYPE(char8_t); // C++20
IODA_ADD_FUNDAMENTAL_TYPE(float);
IODA_ADD_FUNDAMENTAL_TYPE(double);
IODA_ADD_FUNDAMENTAL_TYPE(long double);
#undef IODA_ADD_FUNDAMENTAL_TYPE
/*
/// Used in an example. Incomplete.
/// \todo Pop off std::array as a 1-D object
template<> inline Type GetType<std::array<int,2>, 0>
(gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t>, void*) {
return t->makeArrayType({2}, typeid(std::array<int,2>), typeid(int)); }
*/
/*
template <class DataType, int Array_Type_Dimensionality = 0>
Type GetType(
gsl::not_null<const ::ioda::detail::Type_Provider*> t,
std::initializer_list<Dimensions_t> Adims = {},
typename std::enable_if<!is_string<DataType>::value>::type* = 0);
template <class DataType, int String_Type_Length = constants::_Variable_Length>
Type GetType(
gsl::not_null<const ::ioda::detail::Type_Provider*> t,
typename std::enable_if<is_string<DataType>::value>::type* = 0);
*/
/// \brief Wrapper struct to call GetType. Needed because of C++ template rules.
/// \ingroup ioda_cxx_types
/// \see ioda::Attribute, ioda::Has_Attributes, ioda::Variable, ioda::Has_Variables
template <class DataType,
int Length = 0> //, typename = std::enable_if_t<!is_string<DataType>::value>>
struct GetType_Wrapper {
static Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) {
/// \note Currently breaks array types, but these are not yet used.
return ::ioda::Types::GetType<DataType, Length>(t, {Length});
}
};
/// \ingroup ioda_cxx_types
typedef std::function<Type(gsl::not_null<const ::ioda::detail::Type_Provider*>)>
TypeWrapper_function;
/*
template <class DataType, int Length = 0, typename = std::enable_if_t<is_string<DataType>::value>>
struct GetType_Wrapper {
Type GetType(gsl::not_null<const ::ioda::detail::Type_Provider*> t) const {
// string split
return ::ioda::Types::GetType<DataType, Length>(t);
}
};
*/
// inline Encapsulated_Handle GetTypeFixedString(Dimensions_t sz);
} // namespace Types
} // namespace ioda
/// @}
| {
"alphanum_fraction": 0.6860456127,
"avg_line_length": 35.7320441989,
"ext": "h",
"hexsha": "4794c7d7bd6d70d03a3e5d2cfdea9f03b43955d4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NOAA-EMC/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "NOAA-EMC/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NOAA-EMC/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Types/Type.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3226,
"size": 12935
} |
/* block/gsl_block_long_double.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_BLOCK_LONG_DOUBLE_H__
#define __GSL_BLOCK_LONG_DOUBLE_H__
#include <stdlib.h>
#include <gsl/gsl_errno.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
struct gsl_block_long_double_struct
{
size_t size;
long double *data;
};
typedef struct gsl_block_long_double_struct gsl_block_long_double;
GSL_EXPORT gsl_block_long_double *gsl_block_long_double_alloc (const size_t n);
GSL_EXPORT gsl_block_long_double *gsl_block_long_double_calloc (const size_t n);
GSL_EXPORT void gsl_block_long_double_free (gsl_block_long_double * b);
GSL_EXPORT int gsl_block_long_double_fread (FILE * stream, gsl_block_long_double * b);
GSL_EXPORT int gsl_block_long_double_fwrite (FILE * stream, const gsl_block_long_double * b);
GSL_EXPORT int gsl_block_long_double_fscanf (FILE * stream, gsl_block_long_double * b);
GSL_EXPORT int gsl_block_long_double_fprintf (FILE * stream, const gsl_block_long_double * b, const char *format);
GSL_EXPORT int gsl_block_long_double_raw_fread (FILE * stream, long double * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_long_double_raw_fwrite (FILE * stream, const long double * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_long_double_raw_fscanf (FILE * stream, long double * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_long_double_raw_fprintf (FILE * stream, const long double * b, const size_t n, const size_t stride, const char *format);
GSL_EXPORT size_t gsl_block_long_double_size (const gsl_block_long_double * b);
GSL_EXPORT long double * gsl_block_long_double_data (const gsl_block_long_double * b);
__END_DECLS
#endif /* __GSL_BLOCK_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.7906632086,
"avg_line_length": 40.2835820896,
"ext": "h",
"hexsha": "ab4478bfc15b08b46982cff334904a042421e2c1",
"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_block_long_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_block_long_double.h",
"max_line_length": 145,
"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_block_long_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 676,
"size": 2699
} |
/*
KGSX: Biomolecular Kino-geometric Sampling and Fitting of Experimental Data
Yao et al, Proteins. 2012 Jan;80(1):25-43
e-mail: latombe@cs.stanford.edu, vdbedem@slac.stanford.edu, julie.bernauer@inria.fr
Copyright (C) 2011-2013 Stanford University
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:
This entire text, including 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef KGS_ATOMPAIRDISTANCEDIRECTION_H
#define KGS_ATOMPAIRDISTANCEDIRECTION_H
#include <gsl/gsl_vector.h>
#include <tuple>
#include <vector>
#include "core/graph/KinTree.h"
#include "directions/Direction.h"
#include "Selection.h"
/**
* A direction where the gradient seeks to drive configurations toward a desired distance between a particular pair of
* atoms. This class is conceptually similar to `RelativeMSDDirection` and to a lesser degree `LSNrelativeDirection`,
* but only takes a single pair of atoms and desired distance.
*/
class AtomPairDistanceDirection: public Direction {
public:
AtomPairDistanceDirection(const std::tuple<Atom*, Atom*, double> &relativeDistances);
protected:
void computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret);
private:
const std::tuple<Atom*, Atom*, double> &m_relativeDistance;
};
#endif //KGS_ATOMPAIRDISTANCEDIRECTION_H
| {
"alphanum_fraction": 0.7473639814,
"avg_line_length": 40.8793103448,
"ext": "h",
"hexsha": "d4074d3fef0a7032f21aa0e9dedf278d831dd1a8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/directions/AtomPairDistanceDirection.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/directions/AtomPairDistanceDirection.h",
"max_line_length": 118,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/directions/AtomPairDistanceDirection.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 522,
"size": 2371
} |
// MIT License Copyright (c) 2020 Jarrett Wendt
#pragma once
#define _SILENCE_CLANG_COROUTINE_MESSAGE
// Standard
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <initializer_list>
#include <iostream>
#include <new>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <utility>
#include <vector>
#ifdef _WIN32
#include <experimental/coroutine>
#else
#include <coroutine>
#endif
// External
#include <gsl/gsl>
| {
"alphanum_fraction": 0.7482014388,
"avg_line_length": 16.9512195122,
"ext": "h",
"hexsha": "68f6c451977ab0cf06d6b5c1517f62bc93f023d1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JarrettWendt/FIEAEngine",
"max_forks_repo_path": "source/Library/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "JarrettWendt/FIEAEngine",
"max_issues_repo_path": "source/Library/pch.h",
"max_line_length": 47,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "0bf7e89cd66fec29550f7d7a1a11f5cf398c27e5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JarrettWendt/FIEAEngine",
"max_stars_repo_path": "source/Library/pch.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T09:11:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-27T14:01:39.000Z",
"num_tokens": 162,
"size": 695
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#ifndef __BSSCR_MG_h__
#define __BSSCR_MG_h__
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include "Solvers/KSPSolvers/KSPSolvers.h"
#include "common-driver-utils.h"
#include "BSSCR.h" /* includes StokesBlockKSPInterface.h */
#define KSPBSSCR "bsscr"
typedef struct {
KSP ksp;
PC pc;
PetscTruth useAcceleratingSmoothingMG;
PetscTruth acceleratingSmoothingMGView;
/* mg_accelerating_smoothing options */
PetscInt smoothsMax;
PetscInt smoothsToStartWith;
PetscInt currentNumberOfSmooths;
PetscInt smoothingIncrement;
PetscInt targetCyclesForTenfoldReduction;
PetscInt smoothingCountThisSolve;
PetscInt totalSmoothingCount;
PetscInt totalMgCycleCount;
} MGContext;
PetscErrorCode KSPCycleEffectivenessMonitorAndAdjust(KSP ksp, PetscInt n, PetscReal rnorm, void *_mgctx );
//PetscErrorCode MG_inner_solver_mgContext_initialise(MGContext *mgCtx);
PetscErrorCode MG_inner_solver_pcmg_shutdown( PC pc_MG );
//PetscErrorCode BSSCR_mgPCApply( void *ctx, Vec x, Vec y );
//PetscErrorCode BSSCR_mgPCAccelerating( void *ctx, Vec x, Vec y );
double setupMG( KSP_BSSCR * bsscrp_self, KSP ksp_inner, PC pc_MG, Mat K, MGContext *mgCtx );
#endif
| {
"alphanum_fraction": 0.6057007126,
"avg_line_length": 36.9298245614,
"ext": "h",
"hexsha": "9e27c4915cf4b15fddd3e0ad66a5b0018e6ffda7",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h",
"max_line_length": 106,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/mg.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 644,
"size": 2105
} |
#include <stdlib.h>
#include <assert.h>
#include <cconfigspace.h>
#include <gsl/gsl_rng.h>
static void test_rng_create_with_type() {
const gsl_rng_type **t1, **t2, *t;
size_t type_count = 0;
int32_t selected, refcount;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
ccs_object_type_t otype;
t1 = t2 = gsl_rng_types_setup();
while (*t1++)
type_count++;
selected = rand() % type_count;
err = ccs_rng_create_with_type(t2[selected], NULL);
assert( err == -CCS_INVALID_VALUE );
err = ccs_rng_create_with_type(NULL, &rng);
assert( err == -CCS_INVALID_VALUE );
err = ccs_rng_create_with_type(t2[selected], &rng);
assert( err == CCS_SUCCESS );
assert( rng );
err = ccs_rng_get_type(rng, &t);
assert( err == CCS_SUCCESS );
assert( t == t2[selected] );
err = ccs_object_get_type(rng, &otype);
assert( err == CCS_SUCCESS );
assert( otype == CCS_RNG );
err = ccs_object_get_refcount(rng, &refcount);
assert( err == CCS_SUCCESS );
assert( refcount == 1 );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_rng_create() {
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const gsl_rng_type *t;
err = ccs_rng_create(NULL);
assert( err == -CCS_INVALID_VALUE );
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
assert( rng );
err = ccs_rng_get_type(rng, &t);
assert( err == CCS_SUCCESS );
assert( t == gsl_rng_default );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_rng_min_max() {
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
unsigned long int imin = 0;
unsigned long int imax = 0;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_rng_min(NULL, &imin);
assert( err == -CCS_INVALID_OBJECT );
err = ccs_rng_min(rng, NULL);
assert( err == -CCS_INVALID_VALUE );
err = ccs_rng_min(rng, &imin);
assert( err == CCS_SUCCESS );
err = ccs_rng_max(NULL, &imax);
assert( err == -CCS_INVALID_OBJECT );
err = ccs_rng_max(rng, NULL);
assert( err == -CCS_INVALID_VALUE );
err = ccs_rng_max(rng, &imax);
assert( err == CCS_SUCCESS );
assert( imin < imax );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_rng_get() {
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
unsigned long int i = 0;
unsigned long int imin = 0;
unsigned long int imax = 0;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_rng_min(rng, &imin);
assert( err == CCS_SUCCESS );
err = ccs_rng_max(rng, &imax);
assert( err == CCS_SUCCESS );
for (int j = 0; j < 100; j++) {
err = ccs_rng_get(rng, &i);
assert( err == CCS_SUCCESS );
assert( i >= imin );
assert( i <= imax );
}
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
static void test_rng_uniform() {
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
double d = -1.0;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
for (int j = 0; j < 100; j++) {
err = ccs_rng_uniform(rng, &d);
assert( err == CCS_SUCCESS );
assert( d >= 0.0 );
assert( d < 1.0 );
}
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
int main() {
ccs_init();
test_rng_create_with_type();
test_rng_create();
test_rng_min_max();
test_rng_get();
test_rng_uniform();
ccs_fini();
return 0;
}
| {
"alphanum_fraction": 0.6533451747,
"avg_line_length": 26.1860465116,
"ext": "c",
"hexsha": "938ef23242cd6848b1d224eec0cd77c4f62b785d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "tests/test_rng.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "tests/test_rng.c",
"max_line_length": 52,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "tests/test_rng.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 955,
"size": 3378
} |
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@file engalmod.c
@brief c-routines for function calls from Fortran in an enhanced
galmod environment
This module contains two functions that provide a very specialised
chisquare evaluation when comparing an observed cube with a cube
that is passed by galmod of the GIPSY environment. The c functions
are meant for a hack into galmod and therefore have as such no
use. There is one initialiser routine that initialises the
functionality, i.e., allocates memory, when needed and safes
variables that don't change if a lot of models are passed to the
second routine the chisquare evaluation routine. This does nothing
but give back a chisquare when comparing the original cube and the
model. Both are passed as float arrays only. The module will be
compiled as a library, so that only the library libengalmod.a will
be needed except this include file.
This is the first stable version.
@todo A lot of optimisation: As the array size doesn't change
calculate the fftw_plans ONCE excessively and safe them to global
variables. Make an array of the parts of the gaussian beam that are
redundant (in the hope that it makes things faster). It seems that
a division is a long process: think about it. Test whether
powf(x,2) is faster than x*x (should be...).
$Source: /Volumes/DATA_J_II/data/CVS/tirific/src/engalmod.c,v $
$Date: 2011/05/25 22:25:26 $
$Revision: 1.44 $
$Author: jozsa $
$Log: engalmod.c,v $
Revision 1.44 2011/05/25 22:25:26 jozsa
Left work
Revision 1.43 2011/05/11 13:37:12 jozsa
Left work
Revision 1.42 2011/05/10 00:30:15 jozsa
Left work
Revision 1.41 2009/05/26 07:56:40 jozsa
Left work
Revision 1.40 2007/08/22 15:58:40 gjozsa
Left work
Revision 1.39 2006/04/07 11:13:32 gjozsa
simple BUGFIX
Revision 1.38 2006/04/06 10:39:09 gjozsa
Included function engalmod_chflgs
Revision 1.37 2006/04/03 11:47:46 gjozsa
included masking, fixed a mask to be present if pixval < -1024
Revision 1.36 2005/04/20 13:26:24 gjozsa
Left work
Revision 1.35 2005/04/12 15:52:14 gjozsa
Left work
Revision 1.34 2005/04/07 12:45:47 gjozsa
Bugfix
Revision 1.33 2005/04/06 05:58:24 gjozsa
Bugfix: init now corrects the noiseweight to 1 in case of mode%2
Revision 1.32 2005/04/04 08:42:19 gjozsa
Left work
Revision 1.31 2005/04/01 12:37:11 gjozsa
Large improvements, repeated calls with same velocity dispersion are much faster
Revision 1.29 2005/03/11 17:45:54 gjozsa
Left work
Revision 1.28 2005/03/04 18:13:53 gjozsa
Left work
Revision 1.27 2005/03/02 17:56:09 gjozsa
Left work
Revision 1.26 2005/01/17 12:13:34 gjozsa
Left work
Revision 1.25 2005/01/06 10:44:10 gjozsa
Left work
Revision 1.24 2005/01/05 15:33:02 gjozsa
Left work
Revision 1.23 2004/12/30 13:36:05 gjozsa
Added probability evaluation and out-of-place fft
Revision 1.22 2004/12/27 12:54:40 gjozsa
Last updatde before commenting, no changes anymore allowed
Revision 1.21 2004/12/23 20:20:50 gjozsa
some minor changes, leaves the implementation of arbitrary arrays
Revision 1.18 2004/12/22 17:33:57 gjozsa
Left work
Revision 1.14 2004/12/21 18:42:12 gjozsa
Left work
Revision 1.10 2004/12/21 17:50:21 gjozsa
some changes
Revision 1.7 2004/12/20 14:55:58 gjozsa
Left work
Revision 1.5 2004/12/20 10:44:12 gjozsa
added
Revision 1.4 2004/12/17 14:13:40 gjozsa
First debugged running version
Revision 1.3 2004/12/16 13:19:51 gjozsa
Left work
Revision 1.1 2004/12/11 17:44:51 gjozsa
Added to CVS control
*/
/* ------------------------------------------------------------ */
/* void fftw_execute_dft_r2c(
const fftw_plan p,
double *in, fftw_complex *out);
void fftw_execute_dft_c2r(
const fftw_plan p,
fftw_complex *in, double *out);
check whether FFTW_UNALIGNED is necessary as a planner flag
or use fftw_malloc and fftw_free in this module for the arrays betweeen which the fft takes place.
*/
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* EXTERNAL INCLUDES */
/* ------------------------------------------------------------ */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fftw3.h>
#ifndef OPENMPTIR
#undef OPENMPFFT
#endif
#ifdef OPENMPFFT
#undef OPENMPTIR
#endif
#ifdef OPENMPTIR
#define OPENMPFFT
#include <omp.h>
#endif
/* #include <gsl/gsl_randist.h> */
/* #include <gsl/gsl_cdf.h> */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* INTERNAL INCLUDES */
/* ------------------------------------------------------------ */
#include <engalmod.h>
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@def _MEMORY_HERE_ON
@brief Controls the use of the memory_here module
If you don't want to use the memory_here facility comment this
define, otherways it will be included.
*/
/* ------------------------------------------------------------ */
/* #define _MEMORY_HERE_ON */
/* #include <memory_here.h> */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* (PRIVATE) SYMBOLIC CONSTANTS */
/* ------------------------------------------------------------ */
#define PI_HERE 3.141592653589793115997963468544185161590576171875
#define SQRTPI 1.772453850905516
#define SQRTOF2 0.70710678118655
/* This is -1024 */
#define HOT_VALUE -1024
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* STRUCTS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* (PRIVATE) GLOBAL VARIABLES */
/* ------------------------------------------------------------ */
static float *expofacsfft_;
static float *expofacsfft_noise_;
static float *veloarray_;
static float *veloarray_noise_;
static float sigma_maj_;
static float sigma_min_;
static float sigma_maj_noise_;
static float sigma_min_noise_;
static Cube original_;
static Cube model_;
static Cube noise_;
static Cube expcube_model_;
static Cube expcube_noise_;
static double *chisquare_;
static fftwf_complex *transformed_cube_model_;
static fftwf_complex *transformed_cube_noise_;
static fftwf_plan plan_noise_, plin_noise_;
static fftwf_plan plan_model_, plin_model_;
static int cubesizexhalf_;
static int cubesizeyhalf_;
static int newsize_;
static int dummy_;
static Cube *(*conmodel_)(void);
static Cube *(*connoise_)(void);
static double (*fetchchisquare_)(void);
static float noiseconstant_1_;
static float noiseconstant_2_;
static float modelconstant_1_;
static int realorigsizex_;
static int realorigsizey_;
static int realmodelsizex_;
static int realmodelsizey_;
static float oldsigma_;
#ifdef OPENMPTIR
#include <omp.h>
#endif
static int threads_;
static double *vector_;
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* PRIVATE FUNCTION DECLARATIONS */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double fetchchisquare_unflagged(void)
@brief Get the chisquare without taking care of flags
Returns the chisquare without taking care of flags. This function
will be assigned to the pointer of fetchchisquare if no blanked
pixels are found in the cube.
@return double fetchchisquare_unflagged the chisquared
*/
/* ------------------------------------------------------------ */
static double fetchchisquare_unflagged(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static double fetchchisquare_flagged(void)
@brief Get the chisquare taking care of flags
Returns the chisquare taking care of flags. This function
will be assigned to the pointer of fetchchisquare if any blanked
pixel is found in the cube.
@return double fetchchisquare_unflagged the chisquared
*/
/* ------------------------------------------------------------ */
static double fetchchisquare_flagged(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float fftgaussian (int nx, int ny, int nv, float *expofacs)
@brief Calculate a gaussian
Returns the value of a gaussian in dependence of expofacs.
gaussian = exp((expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*
ny*ny+expofacs[3]*nv*nv+expofacs[4])).
To be used by convolgaussfft. No modulation with respect of the
signum of the coordinates will be done. For a number in the exponent
lesser than MINEXPONENT the return value is 0.
@todo Implement the last thing in the description
@param nx (int) Relative pixelposition in x
@param ny (int) Relative pixelposition in x
@param nv (int) Relative pixelposition in x
@param expofacs (float *) Factors in the gaussian, calculated by
expofacsfft and normalised with respect to the sizes of the array
@return float fftgaussian The gaussian at the desired position
*/
/* ------------------------------------------------------------ */
static float fftgaussian (int nx, int ny, int nv, float *expofacs, float *veloarray);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float fftgaussian (int nx, int ny, int nv, float *expofacs, float *veloarray)
@brief Calculate a gaussian
Returns the value of a gaussian in dependence of expofacs.
gaussian = exp((expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*
ny*ny+expofacs[3]*nv*nv+expofacs[4])).
To be used by convolgaussfft. No modulation with respect of the
signum of the coordinates will be done. For a number in the exponent
lesser than MINEXPONENT the return value is 0.
@todo Implement the last thing in the description
@param nx (int) Relative pixelposition in x
@param ny (int) Relative pixelposition in x
@param nv (int) Relative pixelposition in x
@param expofacs (float *) Factors in the gaussian, calculated by
expofacsfft and normalised with respect to the sizes of the array
@return float fftgaussian The gaussian at the desired position
*/
/* ------------------------------------------------------------ */
static float fftgaussian (int nx, int ny, int nv, float *expofacs, float *veloarray);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float fftgaussian (int nx, int ny, int nv, float *expofacs)
@brief Calculate a gaussian
Returns the value of a gaussian in dependence of expofacs.
gaussian = exp((expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*
ny*ny+expofacs[3]*nv*nv+expofacs[4])).
To be used by convolgaussfft. No modulation with respect of the
signum of the coordinates will be done. For a number in the exponent
lesser than MINEXPONENT the return value is 0.
@todo Implement the last thing in the description
@param nx (int) Relative pixelposition in x
@param ny (int) Relative pixelposition in x
@param nv (int) Relative pixelposition in x
@param expofacs (float *) Factors in the gaussian, calculated by
expofacsfft and normalised with respect to the sizes of the array
@return float fftgaussian The gaussian at the desired position
*/
/* ------------------------------------------------------------ */
static float fftgaussian_array (int nx, int ny, int nv, float *expofacs, float *array, float *veloarray);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float fftgaussian2d (int nx, int ny, float *expofacs)
@brief Calculate a gaussian
Returns the value of a gaussian in dependence of expofacs with
nu_v = 0. gaussian = exp((expofacs[0]*nx*nx+expofacs[1]*nx*ny+
expofacs[2]*ny*ny+expofacs[4])).
To be used by convolgaussfft. No modulation with respect of the
signum of the coordinates will be done. For a number in the exponent
lesser than MINEXPONENT the return value is 0 (see fftgaussian).
@todo The last item in the description to be implemented
@param nx (int) Relative pixelposition in x
@param ny (int) Relative pixelposition in y
@param expofacs (float *) Factors in the gaussian, calculated by
expofacsfft and normalised with respect to the sizes of the array
@return float fftgaussian2d: The gaussian at the desired position,
no error handling.
*/
/* ------------------------------------------------------------ */
static float fftgaussian2d(int nx, int ny, float *expofacs);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float fftgaussian2d (int nx, int ny, float *expofacs)
@brief Calculate a gaussian
Returns the value of a gaussian in dependence of expofacs with
nu_v = 0. gaussian = exp((expofacs[0]*nx*nx+expofacs[1]*nx*ny+
expofacs[2]*ny*ny+expofacs[4])).
To be used by convolgaussfft. No modulation with respect of the
signum of the coordinates will be done. For a number in the exponent
lesser than MINEXPONENT the return value is 0 (see fftgaussian).
@todo The last item in the description to be implemented
@param nx (int) Relative pixelposition in x
@param ny (int) Relative pixelposition in y
@param expofacs (float *) Factors in the gaussian, calculated by
expofacsfft and normalised with respect to the sizes of the array
@return float fftgaussian2d: The gaussian at the desired position,
no error handling.
*/
/* ------------------------------------------------------------ */
static float fftgaussian2d_array(int nx, int ny, float *expofacs, float *array);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_here(void)
@brief Convolve a cube with a gaussian via fft
In-place convolution of a cube Cube with a gaussian via fft. The
convolution is not normalised in the xy-plane but in v. No
convolution takes place in v-direction in case of only one
plane. See function expofacsfft_here for definition of expofacsfft_
array.
@param cube (Cube *) The cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_here(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_here_single(void)
@brief Convolve a cube with a gaussian via fft
In-place convolution of a cube Cube with a gaussian via fft. The
convolution is not normalised in the xy-plane but in v. No
convolution takes place in v-direction in case of only one
plane. See function expofacsfft_here for definition of expofacsfft_
array.
@param cube (Cube *) The cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_here_single(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_noise(Cube *cube)
@brief Calculation of a weights map from the cube
cube is convolved with a beam of sqrt(1/2) times the sigma of the
convolving beam and normalized with a factor
2*sqrt(pi)*sigma_v*fluxpoint, where fluxpoint is the flux of one
pointsource in galmod. This is not an in-place convolution, but it
is safed to noise_.points. Then the noise of the original cube
squared is added to noise_.points (more accurately this is done in
Fourier-space before backtransformation.) The resulting map is used
as a weights map for calculation of the chisquare. See function
expofacsfft_noise for definition of expofacsfft_noise_ array.
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_noise(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_noise_single(Cube *cube)
@brief Calculation of a weights map from the cube
cube is convolved with a beam of sqrt(1/2) times the sigma of the
convolving beam and normalized with a factor
2*sqrt(pi)*sigma_v*fluxpoint, where fluxpoint is the flux of one
pointsource in galmod. This is not an in-place convolution, but it
is safed to noise_.points. Then the noise of the original cube
squared is added to noise_.points (more accurately this is done in
Fourier-space before backtransformation.) The resulting map is used
as a weights map for calculation of the chisquare. See function
expofacsfft_noise for definition of expofacsfft_noise_ array.
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_noise_single(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static void makemodelarray(float *array)
@brief Fill the allocated array *array with precalculated summands for exp evaluation of the model_ cube
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static void makemodelarray(float *array);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static void makenoisearray(float *array)
@brief Fill the allocated array *array with precalculated summands for exp evaluation of the model_ cube
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static void makenoisearray(float *array);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float findpixelrealrel(Cube cube, int x, int y, int v)
@brief Find relative pixel values in a padded Cube
The zero coordinate is array[0]. This function is not safe at all!
@param array (float *) The input cube
@param x (int) relative x coordinate
@param y (int) relative y coordinate
@param v (int) relative v coordinate
@return (success) float findpixelrel: Pixel value
*/
/* ------------------------------------------------------------ */
static float findpixelrealrel(Cube cube, int x, int y, int v);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float findpixelrealrel(Cube cube, int x, int y, int v)
@brief Find relative pixel values in a padded Cube
The zero coordinate is array[0]. This function is not safe at all!
@param array (float *) The input cube
@param x (int) relative x coordinate
@param y (int) relative y coordinate
@param v (int) relative v coordinate
@return (success) float findpixelrel: Pixel value
*/
/* ------------------------------------------------------------ */
static float findpixelrealrelmod(Cube cube, int x, int y, int v);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float *expofacsfft_here(float sigma_maj, float sigma_min, float *sincosofangle)
@brief Calculate static factors needed by convolgaussfft
Returns an allocated array containing factors needed by
convolgaussfft to convolve an array with a gaussian with sigma at
the major axis sigma_major, minor axis sigma_minor. These factors
are calculated from the measures of the convolution kernel and won't
change during the whole program. There are, however members of the
array that will change and will be added by calling the
changeexpofacsfft and changeexpofacsfft_noise routines.
@param sigma_maj (float) The sigma in direction of the major axis
@param sigma_min (float) The sigma in direction of the minor axis
@param sincosofangle (float *) An array containing the sin and the cos
of the position angle
@return (success) float *expofacsfft: The factors wanted\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static float *expofacsfft_here(float sigma_maj, float sigma_min, float *sincosofangle);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_here_array(void)
@brief Convolve a cube with a gaussian via fft using a predefined array
In-place convolution of a cube Cube with a gaussian via fft. The
convolution is not normalised in the xy-plane but in v. No
convolution takes place in v-direction in case of only one
plane. See function expofacsfft_here for definition of expofacsfft_
array.
@param cube (Cube *) The cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_here_array(void);
/* static void convolgaussfft_here_array_help1(void); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_here_single_array(void)
@brief Convolve a cube with a gaussian via fft using a predefined array
In-place convolution of a cube Cube with a gaussian via fft. The
convolution is not normalised in the xy-plane but in v. No
convolution takes place in v-direction in case of only one
plane. See function expofacsfft_here for definition of expofacsfft_
array.
@param cube (Cube *) The cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_here_single_array(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_noise_array(Cube *cube)
@brief Calculation of a weights map from the cube using a predefined array
cube is convolved with a beam of sqrt(1/2) times the sigma of the
convolving beam and normalized with a factor
2*sqrt(pi)*sigma_v*fluxpoint, where fluxpoint is the flux of one
pointsource in galmod. This is not an in-place convolution, but it
is safed to noise_.points. Then the noise of the original cube
squared is added to noise_.points (more accurately this is done in
Fourier-space before backtransformation.) The resulting map is used
as a weights map for calculation of the chisquare. See function
expofacsfft_noise for definition of expofacsfft_noise_ array.
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_noise_array(void);
/* static void convolgaussfft_noise_array_help1(void); */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static Cube *convolgaussfft_noise_single_array(Cube *cube)
@brief Calculation of a weights map from the cube using a predefined array
cube is convolved with a beam of sqrt(1/2) times the sigma of the
convolving beam and normalized with a factor
2*sqrt(pi)*sigma_v*fluxpoint, where fluxpoint is the flux of one
pointsource in galmod. This is not an in-place convolution, but it
is safed to noise_.points. Then the noise of the original cube
squared is added to noise_.points (more accurately this is done in
Fourier-space before backtransformation.) The resulting map is used
as a weights map for calculation of the chisquare. See function
expofacsfft_noise for definition of expofacsfft_noise_ array.
@param cube (Cube *) The (pointsource) cube
@return (success) Cube *convolgaussfft_here: The convolved cube\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static Cube *convolgaussfft_noise_single_array(void);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static void changeexpofacsfft(float sigma_v)
@brief Calculate factors needed by convolgaussfft
Changes the expofacsfft_ array containing factors needed by
convolgaussfft to convolve an array with a gaussian with sigma at
the major axis sigma_major, minor axis sigma_minor, and v-axis
sigma_v.
@param sigma_v (float) The (original) sigma in v-direction
@return (success) void
*/
/* ------------------------------------------------------------ */
static void changeexpofacsfft(float sigma_v);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static void changeexpofacsfft_noise(float sigma_v)
@brief Calculate factors needed by convolgaussfft_noise
Changes the expofacsfft_noise_ array containing factors needed by
convolgaussfft to convolve an array with a gaussian with sigma at
the major axis sigma_major, minor axis sigma_minor, and v-axis
sigma_v/sqrt(2). Also, a normalisation is applied, such that the
output is scaled by scale*2*sqrt(pi)*sigma_v*fluxpoint.
@param sigma_maj (float) The sigma in direction of the major axis
@param sigma_min (float) The sigma in direction of the minor axis
@param sigma_v (float) The sigma in v-direction
@param sincosofangle (float *) An array containing the sin and the cos
of the position angle
@return (success) float *expofacsfft: The factors wanted\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static void changeexpofacsfft_noise(float sigma_v);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float *sincosofangle(float angle)
@brief Returns the sin and the cosine of an angle in an
allocated array
Returns an allocated array containing the cos and the sin of an
angle in degrees. The array has to be freed.
@param angle (float) Angle in degrees
@return (success) float *sincosofangle: An array with the sin and
the cos of the angle\n
(error) NULL
*/
/* ------------------------------------------------------------ */
static float *sincosofangle(float angle);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static float degreetoradian(float degrees)
@brief Converts from degrees to radians
Changes a number from deg to rad
@param degrees (float) An angle in degrees
@return float degreetoradian: Input angle in radians
*/
/* ------------------------------------------------------------ */
static float degreetoradian(float degrees);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/**
@fn static int initchisquare((float *arrayorig, float *arraymodel, int
*x, int *y, int *v, float *hpbwmaj, float *hpbwmin, float *pa, float
*scale, float *flux, float *sigma, int *mode, int *arrayvsize,
double *chisquare, float *noiseweight, int *inimode, int *threads)
@brief Initializes the chisquare derivation control, internal function
This function will be called internally by initchisquare_, while as
many parameters as possible are made local copies to this module.
Initialising routine. Reads in the arrays corresponding to the
original cube and the model and links them into global tirific Cubes
that are private to the module. The user gives the logical size of
the cubes *x, *y, *v, where any pixel is adressed by
pixelvalue(x,y,v) = x+(physical_size_in_x)(y+physical_size_in_y*v),
where x,y,v is the integer pixelvalues starting with 0. The physical
size of the array in x has to be 2*(logical_size_x/2+1), where the
division is an integer division (rounds down to the next
integer). The physical size of the array in y has to be the same as
the logical, while there is no restriction of the physical size in v
else than it has to be larger than the logical size in v. Hence the
physical size is passed in arrayvsize.
hpbwmaj, hpbwmin are the major axis and minor axis HPBW of the
convolving gaussian beam, pa its position angle. These quantities
don't change during several calculations of the chisquare. Scale is
the scale the passed model has to be multiplied by to match the
units of the original (If the model is in W.U., the original in Jy,
this is 0.005). Flux is the flux of one pointsource in galmod. Sigma
is the rms noise in the original.
At initialisation the mode of the chisquare calculation can be
set. Bitwise the following adjustments are made, while the value to be passed with mode is bit0+2*bit1:
Bit 0: A uniform error that equals the noise in the original is used
to weight the chisquare if unset (bit0 = 0), if set (bit0 = 1), a
weightmap is calculated from the model, that is then used to weight
the chisquare.
Bit 1: If set (bit1 = 1), memory will be allocated for one or two
arrays within which precalculated factors are stored that otherways
at time of chisquare calculation will be repeatedly
recalculated. Saves some time. If unset (bit1 = 0) this optimisation
will not take place, saving memory.
Bit 2: If set (bit2 = 0), memory will be allocated for out-of-place
ffts instead of the in-place ffts used for the convolution. fftw can
calculate more efficient ways to perform the fft. This costs a lot
of memory (see list below), such that for computers with small
memory and big cubes, this option should be unset.
initchisquare will check upon the feasibility of the operation and
return 0 if the memory allocations cannot be made. The additionally
required memory (not counting the passed arrays) is a bit more than:
mode = 0: sizeof(float)* [ 0 ]
mode = 1: sizeof(float)* [ (*x/2)*2+2)**y**v ]
mode = 2: sizeof(float)* [ (*x/2+1)**y ]
mode = 3: sizeof(float)* [ (*x/2)*2+2)**y**v + 2 * (*x/2+1)**y ]
mode = 4: sizeof(float)* [ (*x/2)*2+2)**y**v ]
mode = 5: sizeof(float)* [ 3 * (*x/2)*2+2)**y**v ]
mode = 6: sizeof(float)* [ (*x/2)*2+2)**y**v + (*x/2+1)**y ]
mode = 7: sizeof(float)* [ 3 * (*x/2)*2+2)**y**v + 2 * (*x/2+1)**y ]
The chisquare evaluation goes as follows (logically, internal
calculation goes a slightly different path):
1) The pointsource model is convolved with a gaussian beam of HPBW
size hpbwmaj, hpbwmin, hpbwv (given when calling the getchisquare
function), The beam is rotated from N to E with the position angle
pa, but not in the third dimension. All values are pixel values,
except for the pa, which is in deg. The result of the convolution is
m.
2) The pointsource model is convolved with a gaussian beam of
1/sqrt(2) times the size of the original convolving beam and the
same position angle and then multiplied with the flux of one
pointsource pointflux resulting in the map r
3) An inverse weightmap w is computed with w(x,y,z) =
((sigma*noiseweight)^2+r(x,y,z))*noiseweight^(-2)
The noiseweight parameter serves two functions. It determines how
much weight is laid on the quantisation noise imposed by the
pointsource quantisation in comparison to the natural noise sigma of
the original datacube. It hence also serves as a downweighting
function of regions with high surface density. Bit 0 of model set to 0 is
equivalent with noiseweight = infity, while noiseweight towards 0 (0
is actually an error) will impose an additional weight on regions of
low surface density.
4) The chisquare is calculated from original o, convolved model m,
and inverse noisemap n by chisquare = sum_x_y_v
(o(x,y,v)-m(x,y,v))^2/n(x,y,v)
A value of mode of 2 or 3 means that the module needs a bit more
memory, but will be slightly faster, as some factors for the
evaluation of the chisquare are precalculated and stored in the
memory.
The chisquare parameter passes the pointer to the variable that
contains the chisquare.
As this module is meant for the use in interfacing fortran and c,
all parameters are pointers. It is recommended to use them only for
passing them into the initialisation routine, as some of them are
used internally. Mark that when calling the initchisquare_ routine,
the input arrays will be overwritten. They should be initialised
after calling initchisquare_.
The parameter inimode ranges from 0 to 3 and determines the time
that is given to the fft initialising routines to calculate the
shortest way to perform an fft. 0 means that almost no time is spent
on optimising the routines, which then will take longer, 3 means to
spend a long time optimising (once, for the whole process) to really
get the shortest fft, which maybe pays if a long time is spend
calculating again and again the chisquare.
@param arrayorig (*float) Array corresponding to the original cube
@param arraymodel (*float) Array corresponding to the model (pointsource) cube
@param x (int *) Size of logical array in x (that is regarded in calculation)
@param y (int *) Size fo logical array in y
@param v (int *) Size fo logical array in v
@param hpbwmaj (float *) HPBW of the gaussian beam, major axis
@param hpbwmin (float *) HPBW of the gaussian beam, minor axis
@param pa (float *) Position angle of the gaussian beam
@param scale (float *) Scale factor to scale model by to match original
@param flux (float *) The flux of one pointsource in galmod
@param sigma (float *) Sigma rms in the original
@param mode (int *) Calculation of the chisquare depends also on quantisation noise (1 or 3) or on the sigma rms in the original alone (0 or 2) If set to 2 or 3 a bit more memory is needed but the routine runs a bit faster.
@param arrayxsize (int *) Physical size of reserved arrays of model and original in x, a dummy, is always 2*((int) *x/2+1)
@param chisquare (double *) Pointer to the variable containing the chisquare used throughout the code
@param noiseweight (float *) Parameter used for weighting quantisation noise
@param inimode (int *) Mode for the determination of the best fft.
@param threads (int *) Number of threads.
@return (success) int initchisquare_: 1
(error) 0
*/
/* ------------------------------------------------------------ */
static int initchisquare(float *arrayorig, float *arraymodel, int *x, int *y, int *v, float *hpbwmaj, float *hpbwmin, float *pa, float *scale, float *flux, float *sigma, int *mode, int *arrayvsize, double *chisquare, float *noiseweight, int *inimode, int *threads);
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* FUNCTION CODE */
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Initialisation from external, the sense of this function is to make the module robust to changes from external, i.e., the function expects pointers, because that is what you get when you call c from fortran. Inernally these should be protected, i.e. local static variables are created that are pointed to */
int initchisquare_(float *arrayorig, float *arraymodel, int *x, int *y, int *v, float *hpbwmaj, float *hpbwmin, float *pa, float *scale, float *flux, float *sigma, int *mode, int *arrayvsize, double *chisquare, float *noiseweight, int *inimode, int *threads)
{
static int xm, ym, vm;
static float hpbwmajm, hpbwminm, pam, scalem, fluxm, sigmam;
static int modem, arrayvsizem;
static float noiseweightm;
static int inimodem;
static int threadsm;
xm = *x;
ym = *y;
vm = *v;
hpbwmajm = *hpbwmaj;
hpbwminm = *hpbwmin;
pam = *pa;
scalem = *scale;
fluxm = *flux;
sigmam = *sigma;
modem = *mode;
arrayvsizem = *arrayvsize;
noiseweightm = *noiseweight;
inimodem = *inimode;
threadsm = *threads;
return initchisquare(arrayorig, arraymodel, &xm, &ym, &vm, &hpbwmajm, &hpbwminm, &pam, &scalem, &fluxm, &sigmam, &modem, &arrayvsizem, chisquare, &noiseweightm, &inimodem, &threadsm);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Initialisation from external, the sense of this function is to make the module robust to changes from external, i.e., the function expects pointers, because that is what you get when you call c from fortran. Inernally these should be protected, i.e. local static variables are created that are pointed to */
int initchisquare_c(float *arrayorig, float *arraymodel, int x, int y, int v, float hpbwmaj, float hpbwmin, float pa, float scale, float flux, float sigma, int mode, int arrayvsize, double *chisquare, float noiseweight, int inimode, int threads)
{
static int xm, ym, vm;
static float hpbwmajm, hpbwminm, pam, scalem, fluxm, sigmam;
static int modem, arrayvsizem;
static float noiseweightm;
static int inimodem;
static int threadsm;
xm = x;
ym = y;
vm = v;
hpbwmajm = hpbwmaj;
hpbwminm = hpbwmin;
pam = pa;
scalem = scale;
fluxm = flux;
sigmam = sigma;
modem = mode;
arrayvsizem = arrayvsize;
noiseweightm = noiseweight;
inimodem = inimode;
threadsm = threads;
return initchisquare(arrayorig, arraymodel, &xm, &ym, &vm, &hpbwmajm, &hpbwminm, &pam, &scalem, &fluxm, &sigmam, &modem, &arrayvsizem, chisquare, &noiseweightm, &inimodem, &threadsm);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Initialisation */
int initchisquare(float *arrayorig, float *arraymodel, int *x, int *y, int *v, float *hpbwmaj, float *hpbwmin, float *pa, float *scale, float *flux, float *sigma, int *mode, int *arrayvsize, double *chisquare, float *noiseweight, int *inimode, int *threads)
{
float *sincosofangle_;
int physical[3];
int physical2[3];
int logical[3];
int physicaln[3];
int inimodel;
static char usedonce = 0;
/* hyper */
#ifdef OPENMPFFT
fftwf_init_threads();
#endif
if ((usedonce)) {
if ((noise_.points))
fftwf_free(noise_.points);
if ((transformed_cube_noise_))
fftwf_free(transformed_cube_noise_);
if ((transformed_cube_model_))
fftwf_free(transformed_cube_model_);
if ((expcube_model_.points))
fftwf_free(expcube_model_.points);
if ((expcube_noise_.points))
fftwf_free(expcube_noise_.points);
if ((expofacsfft_))
free(expofacsfft_);
if ((expofacsfft_noise_))
free(expofacsfft_noise_);
if ((veloarray_))
fftwf_free(veloarray_);
if ((veloarray_noise_))
fftwf_free(veloarray_noise_);
}
noise_.points = NULL;
transformed_cube_noise_ = NULL;
transformed_cube_model_ = NULL;
expcube_model_.points = NULL;
expcube_noise_.points = NULL;
expofacsfft_ = NULL;
expofacsfft_noise_ = NULL;
veloarray_ = NULL;
veloarray_noise_ = NULL;
oldsigma_ = -1;
threads_ = *threads;
vector_ = (double *) malloc(threads_*sizeof(double));
/* set number of threads */
#ifdef OPENMPTIR
omp_set_num_threads(threads_);
#endif
/* put the chisquare in its place */
chisquare_ = chisquare;
/* Get the array of the original */
original_.points = arrayorig;
/* Get the array of the model */
model_.points = arraymodel;
realorigsizex_ = 2*(*x/2+1);
/* 2*(*x/2+1); */
realorigsizey_ = *y;
realmodelsizex_ = 2*(*x/2+1);
realmodelsizey_ = *y;
/* Allocate memory for the noisecube if the noise per pixel is required in future */
if ((*mode & 1)) {
if (!((noise_.points) = (float *) fftwf_malloc(((*x/2)*2+2)**y**v*sizeof(float))))
goto error;
/* There might be a chance that things work faster with an out-of-place trafo on the expense of double the memory usage */
if (*mode & 4) {
if (!(transformed_cube_noise_ = (fftwf_complex *) fftwf_malloc((*x/2+1)**y**v*sizeof(fftwf_complex)))) {
fftwf_free(noise_.points);
goto error;
}
}
}
else
noise_.points = NULL;
/* There might be a chance that things work faster with an out-of-place trafo on the expense of double the memory usage */
if (*mode & 4) {
if (!(transformed_cube_model_ = (fftwf_complex *) fftwf_malloc((*x/2+1)**y**v*sizeof(fftwf_complex)))) {
if (*mode & 1) {
fftwf_free(noise_.points);
fftwf_free(transformed_cube_noise_);
goto error;
}
}
}
/* Allocate memory for the expcubes if they are required in future */
if ((*mode & 2)) {
if (!((expcube_model_.points) = (float *) fftwf_malloc((*x/2+1)**y*sizeof(float)))) {
if ((*mode & 1))
fftwf_free(noise_.points);
if ((*mode & 4)) {
if ((*mode & 1))
fftwf_free(transformed_cube_noise_);
fftwf_free(transformed_cube_model_);
}
goto error;
}
expcube_model_.size_x = *x/2+1;
expcube_model_.size_y = *y;
expcube_model_.size_v = 1;
expcube_model_.padding = 0;
if ((*mode & 1)) {
if (!((expcube_noise_.points) = (float *) fftwf_malloc((*x/2+1)**y*sizeof(float)))) {
if ((*mode & 1))
fftwf_free(noise_.points);
fftwf_free(expcube_model_.points);
if ((*mode & 4)) {
if ((*mode & 1))
fftwf_free(transformed_cube_noise_);
fftwf_free(transformed_cube_model_);
}
goto error;
}
}
else
expcube_noise_.points = NULL;
/* This info is warranted */
expcube_noise_.size_x = *x/2+1;
expcube_noise_.size_y = *y;
expcube_noise_.size_v = 1;
expcube_noise_.padding = 0;
expcube_noise_.refpix_x = expcube_noise_.refpix_y = expcube_noise_.refpix_v = expcube_model_.refpix_x = expcube_model_.refpix_y = expcube_model_.refpix_v = 0;
}
else
expcube_model_.points = expcube_noise_.points = NULL;
/* Now get the sizes right */
original_.size_x = model_.size_x = noise_.size_x = *x;
original_.size_y = model_.size_y = noise_.size_y = *y;
original_.size_v = model_.size_v = noise_.size_v = *v;
original_.refpix_x = model_.refpix_x = noise_.refpix_x = 0;
original_.refpix_y = model_.refpix_y = noise_.refpix_y = 0;
original_.refpix_v = model_.refpix_v = noise_.refpix_v = 0;
/* We don't need the reference pixel, but the padding */
original_.padding = model_.padding = noise_.padding = (*x/2)*2+2-*x;
/* The scale */
original_.scale = *scale;
model_.scale = *flux;
if (!(*mode & 1))
*noiseweight = 1;
noise_.scale = *sigma**sigma**noiseweight**noiseweight;
expcube_model_.scale = *noiseweight**noiseweight;
/* Now initialize the expofacsfft array */
/* We have only the HPBWs, so calculate the gaussian widths */
if (!(sincosofangle_ = sincosofangle(*pa))) {
if ((*mode & 1)) {
fftwf_free(noise_.points);
if ((*mode & 2))
fftwf_free(expcube_noise_.points);
}
if ((*mode & 2))
free(expcube_model_.points);
if ((*mode & 4)) {
if ((*mode & 1))
fftwf_free(transformed_cube_noise_);
fftwf_free(transformed_cube_model_);
}
goto error;
}
if (!(expofacsfft_ = expofacsfft_here(sigma_maj_ = 0.42466090014401**hpbwmaj, sigma_min_ = 0.42466090014401**hpbwmin, sincosofangle_))) {
if ((*mode & 1)) {
fftwf_free(noise_.points);
if ((*mode & 2))
fftwf_free(expcube_noise_.points);
}
if ((*mode & 2))
fftwf_free(expcube_model_.points);
free(sincosofangle_);
if ((*mode & 4)) {
if ((*mode & 1))
fftwf_free(transformed_cube_noise_);
fftwf_free(transformed_cube_model_);
}
goto error;
}
if (!(expofacsfft_noise_ = expofacsfft_here(sigma_maj_noise_ = sigma_maj_*SQRTOF2, sigma_min_noise_ = sigma_min_*SQRTOF2, sincosofangle_))) {
if ((*mode & 1)) {
fftwf_free(noise_.points);
if ((*mode & 2))
fftwf_free(expcube_noise_.points);
}
if ((*mode & 2))
fftwf_free(expcube_model_.points);
free(sincosofangle_);
free(expofacsfft_);
if ((*mode & 4)) {
if ((*mode & 1))
fftwf_free(transformed_cube_noise_);
fftwf_free(transformed_cube_model_);
}
goto error;
}
/* Now the veloarray */
if (!(veloarray_ = (float *) fftwf_malloc((model_.size_v/2+1)*sizeof(float)))) {
if ((*mode & 1)) {
fftwf_free(noise_.points);
noise_.points = NULL;
if ((*mode & 2)) {
fftwf_free(expcube_noise_.points);
expcube_noise_.points = NULL;
}
}
if ((*mode & 2)) {
fftwf_free(expcube_model_.points);
expcube_model_.points = NULL;
}
free(sincosofangle_);
sincosofangle_ = NULL;
free(expofacsfft_);
expofacsfft_ = NULL;
if ((*mode & 4)) {
if ((*mode & 1)) {
fftwf_free(transformed_cube_noise_);
transformed_cube_noise_ = NULL;
}
fftwf_free(transformed_cube_model_);
transformed_cube_model_ = NULL;
}
goto error;
}
/* Now the veloarray */
if (!(veloarray_noise_ = (float *) fftwf_malloc((model_.size_v/2+1)*sizeof(float)))) {
if ((*mode & 1)) {
fftwf_free(noise_.points);
noise_.points = NULL;
if ((*mode & 2)) {
fftwf_free(expcube_noise_.points);
expcube_noise_.points = NULL;
}
}
if ((*mode & 2)) {
fftwf_free(expcube_model_.points);
expcube_model_.points = NULL;
}
free(sincosofangle_);
sincosofangle_ = NULL;
free(expofacsfft_);
expofacsfft_ = NULL;
if ((*mode & 4)) {
if ((*mode & 1)) {
fftwf_free(transformed_cube_noise_);
transformed_cube_noise_ = NULL;
}
fftwf_free(transformed_cube_model_);
transformed_cube_model_ = NULL;
}
fftwf_free(veloarray_);
goto error;
}
/* Fill the arrays that describe the transformation */
if (model_.size_v != 1) {
logical[0] = model_.size_v;
logical[1] = model_.size_y;
logical[2] = model_.size_x;
physical[0] = *arrayvsize;
physical[1] = model_.size_y;
physical[2] = 2*(model_.size_x/2)+2;
physicaln[0] = model_.size_v;
physicaln[1] = model_.size_y;
physicaln[2] = 2*(model_.size_x/2)+2;
physical2[0] = model_.size_v;
physical2[1] = model_.size_y;
physical2[2] = (model_.size_x/2)+1;
if (*mode & 2) {
connoise_ = convolgaussfft_noise_array;
conmodel_ = convolgaussfft_here_array;
}
else {
connoise_ = convolgaussfft_noise;
conmodel_ = convolgaussfft_here;
}
}
else {
logical[0] = model_.size_y;
logical[1] = model_.size_x;
physical[0] = model_.size_y;
physical[1] = 2*(model_.size_x/2)+2;
physicaln[0] = model_.size_y;
physicaln[1] = 2*(model_.size_x/2)+2;
physical2[0] = model_.size_y;
physical2[1] = (model_.size_x/2)+1;
if (*mode & 2) {
connoise_ = convolgaussfft_noise_single;
conmodel_ = convolgaussfft_here_single;
}
else {
connoise_ = convolgaussfft_noise_single_array;
conmodel_ = convolgaussfft_here_single_array;
}
}
/* Take the input from inimodel to decide upon the way to
initialize fftw */
switch (*inimode) {
case 1:
inimodel = FFTW_MEASURE;
break;
case 2:
inimodel = FFTW_PATIENT;
break;
case 3:
inimodel = FFTW_EXHAUSTIVE;
break;
default:
inimodel = FFTW_ESTIMATE;
break;
}
/* Now make the plans for the fftw */
#ifdef OPENMPFFT
fftwf_plan_with_nthreads(threads_);
#endif
if (*mode & 1) {
/* point the trasnsformed cube to the cube itself for an in-place
transformation */
if (*mode & 4)
;
else
transformed_cube_noise_ = (fftwf_complex *) noise_.points;
/* fill plan_noise_ and plin_noise_ with the necessary information. Take care with the order of the axes, reversed for fftw */
if (model_.size_v != 1) {
plan_noise_ = fftwf_plan_many_dft_r2c(3, logical, 1, model_.points, physical, 1, 0, transformed_cube_noise_, physical2, 1, 0, inimodel | FFTW_PRESERVE_INPUT);
plin_noise_ = fftwf_plan_many_dft_c2r(3, logical, 1, transformed_cube_noise_, physical2, 1, 0, noise_.points, physicaln, 1, 0, inimodel);
/* (*x/2)*2+2)**y**v */
/* fftwf_plan_dft_c2r_3d(model_.size_v, model_.size_y, model_.size_x, transformed_cube_noise_, noise_.points, inimodel); */
}
else {
plan_noise_ = fftwf_plan_many_dft_r2c(2,logical , 1, model_.points, physical, 1, 0, transformed_cube_noise_, physical2, 1, 0, inimodel | FFTW_PRESERVE_INPUT);
plin_noise_ = fftwf_plan_dft_c2r_2d(model_.size_y, model_.size_x, transformed_cube_noise_, noise_.points, inimodel);
}
}
/* Fill the global variables that affect the noise estimation and
the convolution */
cubesizexhalf_ = model_.size_x/2;
cubesizeyhalf_ = model_.size_y/2;
newsize_ = cubesizexhalf_+1; /* The physical size of the cube in x */
dummy_ = model_.size_v/2;
/* point the trasnsformed cube to the cube itself for an in-place transformation */
if (*mode & 4)
;
else
transformed_cube_model_ = (fftwf_complex *) (model_).points;
if (model_.size_v != 1) {
logical[0] = model_.size_v;
logical[1] = model_.size_y;
logical[2] = model_.size_x;
physical[0] = *arrayvsize;
/* formerly: model_.size_v */
physical[1] = model_.size_y;
physical[2] = 2*(model_.size_x/2)+2;
physical2[0] = *arrayvsize;
/* formerly: model_.size_v */
physical2[1] = model_.size_y;
physical2[2] = (model_.size_x/2)+1;
}
else {
logical[0] = model_.size_y;
logical[1] = model_.size_x;
physical[0] = model_.size_y;
physical[1] = 2*(model_.size_x/2)+2;
physical2[0] = model_.size_y;
physical2[1] = (model_.size_x/2)+1;
}
/* fill plan and plin with the necessary information. Take care with the order of the axes, reversed for fftw */
if (model_.size_v != 1) {
plan_model_ = fftwf_plan_many_dft_r2c(3, logical, 1, model_.points, physical, 1, 0, transformed_cube_model_, physical2, 1, 0, inimodel);
plin_model_ = fftwf_plan_many_dft_c2r(3, logical, 1, transformed_cube_model_, physical2, 1, 0, model_.points, physical, 1, 0, inimodel);
}
else {
plan_model_ = fftwf_plan_dft_r2c_2d((model_).size_y, (model_).size_x, (model_).points, transformed_cube_model_, inimodel);
plin_model_ = fftwf_plan_dft_c2r_2d((model_).size_y, (model_).size_x, transformed_cube_model_, (model_).points, inimodel);
}
/* Now do some silly hacking */
if (*mode & 1) {
noiseconstant_1_ = (-2*SQRTOF2*PI_HERE*SQRTOF2*PI_HERE)/(original_.size_v*original_.size_v);
noiseconstant_2_ = original_.scale*model_.scale*2*PI_HERE*sigma_min_noise_*sigma_maj_noise_/(original_.size_v*original_.size_y*original_.size_x*2*SQRTPI);
}
modelconstant_1_ = -2*(PI_HERE*PI_HERE)/(original_.size_v*original_.size_v);
/* Fill the arrays for the exponential acceleration if required */
if (*mode & 2) {
/* In any case that is for the model */
makemodelarray(expcube_model_.points);
/* Could be that it is also the noisemap */
if (*mode & 1) {
makenoisearray(expcube_noise_.points);
}
}
/* Now check for the function that is needed to calculate the chisquare */
engalmod_chflgs();
/* nearly finished */
free(sincosofangle_);
return 1;
error:
noise_.points = NULL;
transformed_cube_noise_ = NULL;
transformed_cube_model_ = NULL;
expcube_model_.points = NULL;
expcube_noise_.points = NULL;
expofacsfft_ = NULL;
expofacsfft_noise_ = NULL;
veloarray_ = NULL;
veloarray_noise_ = NULL;
return 0;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* (Re-)Initialisation of the chisquare finding routine */
void engalmod_chflgs(void)
{
int i,j,k;
fetchchisquare_ = &fetchchisquare_unflagged;
for(k = 0; k < original_.size_v; ++k){
for(j = 0; j < original_.size_y; ++j) {
for(i = 0; i < original_.size_x; ++i) {
/* A nan compared with itself is false */
if (findpixelrealrel(original_, i, j, k) != findpixelrealrel(original_, i, j, k)) {
/* if ((double) ((findpixelrealrel(original_, i, j, k))) < HOT_VALUE) { */
fetchchisquare_ = &fetchchisquare_flagged;
break;
}
}
}
}
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static float findpixelrealrel(Cube cube, int x, int y, int v)
{
return (cube.points)[x+realorigsizex_*(y+realorigsizey_*v)];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static double fetchchisquare_flagged(void)
{
int i,j,k;
double chisquare = 0;
int nthreadz = 0;
for (i =0 ; i < threads_; ++i)
vector_[i] = 0.0;
/* Now calculate the chisquare */
if ((noise_.points)) {
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for(k = 0; k < original_.size_v; ++k){
#ifdef OPENMPTIR
if (nthreadz == 0) {
nthreadz = omp_get_num_threads();
}
#else
nthreadz = 1;
#endif
for(j = 0; j < original_.size_y; ++j) {
for(i = 0; i < original_.size_x; ++i) {
#ifdef OPENMPTIR
/* A nan compared with itself is false */
if (findpixelrealrel(original_, i, j, k) == findpixelrealrel(original_, i, j, k)) {
/* if (findpixelrealrel(original_, i, j, k) > HOT_VALUE) { */
vector_[omp_get_thread_num()] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))/findpixelrealrelmod(noise_, i, j, k));
}
#else
/* A nan compared with itself is false */
if (findpixelrealrel(original_, i, j, k) == findpixelrealrel(original_, i, j, k)) {
/* if (findpixelrealrel(original_, i, j, k) > HOT_VALUE) { */
vector_[0] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))/findpixelrealrelmod(noise_, i, j, k));
}
#endif
}
}
}
for (i = 0; i < nthreadz; ++i)
chisquare += vector_[i]*(double) expcube_model_.scale;
}
else {
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for(k = 0; k < original_.size_v; ++k){
#ifdef OPENMPTIR
if (nthreadz == 0) {
nthreadz = omp_get_num_threads();
}
#else
nthreadz = 1;
#endif
for(j = 0; j < original_.size_y; ++j) {
for(i = 0; i < original_.size_x; ++i) {
#ifdef OPENMPTIR
/* A nan compared with itself is false */
if (findpixelrealrel(original_, i, j, k) == findpixelrealrel(original_, i, j, k)) {
/* if (findpixelrealrel(original_, i, j, k) > HOT_VALUE) { */
vector_[omp_get_thread_num()] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k)));
}
#else
/* A nan compared with itself is false */
if (findpixelrealrel(original_, i, j, k) == findpixelrealrel(original_, i, j, k)) {
/* if (findpixelrealrel(original_, i, j, k) > HOT_VALUE) { */
vector_[0] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k)));
}
#endif
}
}
}
for (i = 0; i < nthreadz; ++i)
chisquare += vector_[i]/noise_.scale;
}
return chisquare;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static double fetchchisquare_unflagged(void)
{
int i,j,k;
double chisquare = 0;
int nthreadz = 0;
for (i =0 ; i < threads_; ++i)
vector_[i] = 0;
/* Now calculate the chisquare */
if ((noise_.points)) {
#ifdef OPENMPTIR
# pragma omp parallel for
#endif
for(k = 0; k < original_.size_v; ++k){
#ifdef OPENMPTIR
if (nthreadz == 0) {
nthreadz = omp_get_num_threads();
}
#else
nthreadz = 1;
#endif
for(j = 0; j < original_.size_y; ++j) {
for(i = 0; i < original_.size_x; ++i) {
#ifdef OPENMPTIR
vector_[omp_get_thread_num()] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))/findpixelrealrelmod(noise_, i, j, k));
#else
vector_[0] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))/findpixelrealrelmod(noise_, i, j, k));
#endif
}
}
}
for (i = 0; i < nthreadz; ++i)
chisquare += vector_[i]*(double) expcube_model_.scale;
}
else {
#ifdef OPENMPTIR
# pragma omp parallel for
#endif
for(k = 0; k < original_.size_v; ++k){
#ifdef OPENMPTIR
if (nthreadz == 0)
nthreadz = omp_get_num_threads();
#else
nthreadz = 1;
#endif
for(j = 0; j < original_.size_y; ++j) {
for(i = 0; i < original_.size_x; ++i) {
#ifdef OPENMPTIR
vector_[omp_get_thread_num()] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k)));
#else
vector_[0] += (double) ((findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k))*(findpixelrealrel(original_, i, j, k)-findpixelrealrelmod(model_, i, j, k)));
#endif
}
}
}
for (i = 0; i < nthreadz; ++i)
chisquare += vector_[i]/noise_.scale;
}
return chisquare;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static float findpixelrealrelmod(Cube cube, int x, int y, int v)
{
return (cube.points)[x+realmodelsizex_*(y+realmodelsizey_*v)];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
double getchisquare_(float *sigma_v)
{
/* formerly times 0.42466090014401, but now it's the real sigma */
return getchisquare_c(*sigma_v);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
double getchisquare_c (float sigma_v)
/* If ever the flux of one pointsource changes during one run, activate this */
/* static double getchisquare (float *array, float HPBW_v, float pointflux) */
{
/* Set the chisquare to 0 */
double chisquare = 0;
/* If a weight map should be calculated */
if ((noise_.points)) {
if (sigma_v != oldsigma_) {
changeexpofacsfft_noise(sigma_v);
}
/* If ever the flux of one pointsource changes during one run, activate this */
/* model_.scale = pointflux; */
(*connoise_)();
}
/* In any case we need the convolved cube */
if (sigma_v != oldsigma_) {
changeexpofacsfft(sigma_v);
}
(*conmodel_)();
oldsigma_ = sigma_v;
/* Now calculate the chisquare */
chisquare = (*fetchchisquare_)();
*chisquare_ = chisquare;
return chisquare;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve a cube with a gaussian via fft */
static Cube *convolgaussfft_here(void)
{
int i, j, k;
float expresult; /* A dummy */
/* Convolution in all dimensions or in xy only */
/* Now do the transform */
fftwf_execute(plan_model_);
/* multiply with the gaussian, first for nu_v = 0 */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian2d((i <= cubesizexhalf_) ? i : (i-(model_).size_x), (j <= cubesizeyhalf_) ? j : (j-(model_).size_y), expofacsfft_);
transformed_cube_model_[i+newsize_*j][0] = expresult*transformed_cube_model_[i+newsize_*j][0];
transformed_cube_model_[i+newsize_*j][1] = expresult*transformed_cube_model_[i+newsize_*j][1];
}
}
/* Check for an extra-axis in v, i.e. if the dimension in v is even, we have to calculate one v-plane separately */
if (!((model_).size_v % 2)) {
/* multiply with the gaussian, first for nu_v = N_v/2 */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j)
{
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian((i <= cubesizexhalf_) ? i : (i-(model_).size_x), (j <= cubesizeyhalf_) ? j : (j-(model_).size_y), dummy_, expofacsfft_, veloarray_);
transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][1];
}
}
}
/* Now the rest has to be done, v ranges from 1, ..., N_v-1/2, and using the symmetrics of the gaussian we fill the rest */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
for (k = 1; k <= ((model_).size_v-1)/2; ++k) {
expresult = fftgaussian((i <= cubesizexhalf_) ? i : (i-(model_).size_x), (j <= cubesizeyhalf_) ? j : (j-(model_).size_y), k, expofacsfft_, veloarray_);
transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][1];
/* Because of the symmetry, f(v) = f(-v), we can safe quite some calculations */
transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][1];
}
}
}
/* Now do the backtransformation */
fftwf_execute(plin_model_);
return &model_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve a cube with a gaussian via fft */
static Cube *convolgaussfft_here_single(void)
{
int i, j;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_model_);
/* multiply with the gaussian, first axis y, second x */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
expresult = fftgaussian2d((i <= cubesizexhalf_) ? i : (i-(model_).size_x), (j <= cubesizeyhalf_) ? j : (j-(model_).size_y), expofacsfft_);
transformed_cube_model_[i+newsize_*j][0] = expresult*transformed_cube_model_[i+newsize_*j][0];
transformed_cube_model_[i+newsize_*j][1] = expresult*transformed_cube_model_[i+newsize_*j][1];
}
}
/* Now do the backtransformation */
fftwf_execute(plin_model_);
return &model_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve the input cube with a gaussian via fft to the weightmap, adding a constant offset */
static Cube *convolgaussfft_noise(void)
{
int i, j, k;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_noise_);
/* fftwf_execute(plin_noise_); */
/* return NULL; */
/* multiply with the gaussian, first for nu_v = 0 */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian2d((i <= cubesizexhalf_) ? i : (i-model_.size_x), (j <= cubesizeyhalf_) ? j : (j-model_.size_y), expofacsfft_noise_);
transformed_cube_noise_[i+newsize_*j][0] = expresult*transformed_cube_noise_[i+newsize_*j][0];
transformed_cube_noise_[i+newsize_*j][1] = expresult*transformed_cube_noise_[i+newsize_*j][1];
}
}
/* Check for an extra-axis in v, i.e. if the dimension in v is even, we have to calculate one v-plane separately */
if (!(model_.size_v % 2)) {
/* multiply with the gaussian, first for nu_v = N_v/2 */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j)
{
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian((i <= cubesizexhalf_) ? i : (i-model_.size_x), (j <= cubesizeyhalf_) ? j : (j-model_.size_y), dummy_, expofacsfft_noise_, veloarray_noise_);
transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][1];
}
}
}
/* Now the rest has to be done, v ranges from 1, ..., N_v-1/2, and using the symmetrics of the gaussian we fill the rest */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
for (k = 1; k <= (model_.size_v-1)/2; ++k) {
expresult = fftgaussian((i <= cubesizexhalf_) ? i : (i-model_.size_x), (j <= cubesizeyhalf_) ? j : (j-model_.size_y), k, expofacsfft_noise_, veloarray_noise_);
transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][1];
/* Because of the symmetry, f(v) = f(-v), we can safe quite some calculations */
transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][1];
}
}
}
/* Now add the constant square of the noise */
transformed_cube_noise_[0][0] = transformed_cube_noise_[0][0] + noise_.scale;
/* Now do the backtransformation */
fftwf_execute(plin_noise_);
return &noise_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve the input cube with a gaussian via fft to the weightmap, adding a constant offset */
static Cube *convolgaussfft_noise_single(void)
{
int i, j;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_noise_);
/* multiply with the gaussian, first axis y, second x */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
expresult = fftgaussian2d((i <= cubesizexhalf_) ? i : (i-model_.size_x), (j <= cubesizeyhalf_) ? j : (j-model_.size_y), expofacsfft_noise_);
transformed_cube_noise_[i+newsize_*j][0] = expresult*transformed_cube_noise_[i+newsize_*j][0];
transformed_cube_noise_[i+newsize_*j][1] = expresult*transformed_cube_noise_[i+newsize_*j][1];
}
}
/* Now add the constant square of the noise */
transformed_cube_noise_[0][0] = transformed_cube_noise_[0][0] + noise_.scale;
/* Now do the backtransformation */
fftwf_execute(plin_noise_);
return &noise_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate factors needed by convolgaussfft */
static float *expofacsfft_here(float sigma_maj, float sigma_min, float *sincosofangle)
{
float *expofacs;
if ((sincosofangle && (expofacs = (float *) malloc(5*sizeof(float))))) {
/* First content is the factor to put before (n_x/N_x)^2 */
expofacs[0] = -2*PI_HERE*PI_HERE*(sigma_min*sigma_min*sincosofangle[1]*sincosofangle[1]+sigma_maj*sigma_maj*sincosofangle[0]*sincosofangle[0])/(original_.size_x*original_.size_x);
/* Second content is the factor to put before (n_x/N_x)(n_y/N_y) */
expofacs[1] = -4*PI_HERE*PI_HERE*sincosofangle[0]*sincosofangle[1]*(sigma_min*sigma_min-sigma_maj*sigma_maj)/(original_.size_x*original_.size_y);
/* Third content is the factor to put before (n_y/N_y)^2 */
expofacs[2] = -2*PI_HERE*PI_HERE*(sigma_min*sigma_min*sincosofangle[0]*sincosofangle[0]+sigma_maj*sigma_maj*sincosofangle[1]*sincosofangle[1])/(original_.size_y*original_.size_y);
/* Fifth component is the normalisation factor due to the width of the gaussians. This is not a factor to put in the exponent though. Here we have to care if only one direction conovolution is desired */
if (sigma_maj == 0)
sigma_maj = 1.0/sqrtf(2*PI_HERE);
if (sigma_min == 0)
sigma_min = 1.0/sqrtf(2*PI_HERE);
expofacs[4] = original_.scale*2*PI_HERE*sigma_min*sigma_maj/(original_.size_v*original_.size_y*original_.size_x);
}
else
expofacs = NULL;
return expofacs;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate factors needed by convolgaussfft */
static void changeexpofacsfft_noise(float sigma_v)
{
int i;
/* Fourth content is the factor to put before (n_v/N_v)^2 */
expofacsfft_noise_[3] = sigma_v*sigma_v*noiseconstant_1_;
if ((sigma_v)) {
expofacsfft_noise_[4] = noiseconstant_2_/sigma_v;
/* Now fill the veloarray */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < model_.size_v/2+1; ++i) {
veloarray_noise_[i] = expf(expofacsfft_noise_[3]*i*i)*expofacsfft_noise_[4];
}
}
else {
expofacsfft_noise_[4] = 2*SQRTPI*noiseconstant_2_;
/* Now fill the veloarray */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < model_.size_v/2+1; ++i) {
veloarray_noise_[i] = expf(expofacsfft_noise_[3]*i*i)*expofacsfft_noise_[4];
}
}
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate factors needed by convolgaussfft */
static void changeexpofacsfft(float sigma_v)
{
int i;
/* Fourth content is the factor to put before (n_v/N_v)^2 */
expofacsfft_[3] = modelconstant_1_*sigma_v*sigma_v;
/* Now fill the veloarray */
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < model_.size_v/2+1; ++i) {
veloarray_[i] = expf(expofacsfft_[3]*i*i)*expofacsfft_[4];
}
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate a gaussian */
static float fftgaussian (int nx, int ny, int nv, float *expofacs, float *veloarray)
{
/* As the trial to safe some time as seen below failed for some reason, we postpone it */
return expf(expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*ny*ny)*veloarray[nv];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate a gaussian */
static float fftgaussian_array (int nx, int ny, int nv, float *expofacs, float *array, float *veloarray)
{
/* As the trial to safe some time as seen below failed for some reason, we postpone it */
/* return array[nx+expcube_noise_.size_x*ny]*expf(expofacs[3]*nv*nv) * expofacs[4]; */
return array[nx+expcube_noise_.size_x*ny]*veloarray[nv];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate a gaussian */
static float fftgaussian2d (int nx, int ny, float *expofacs)
{
/* double number; */
/* If the floating point is low enough, we can simply return 0 */
/* if ((number = expf(expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*ny*ny+expofacs[4])) <= MINEXPONENT) */
/* return (float) exp(number); */
/* else */
return expf(expofacs[0]*nx*nx+expofacs[1]*nx*ny+expofacs[2]*ny*ny)*expofacs[4];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Calculate a gaussian */
static float fftgaussian2d_array (int nx, int ny, float *expofacs, float *array)
{
return array[nx+expcube_noise_.size_x*ny]*expofacs[4];
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Returns the sin and the cosine of an angle in an allocated array */
float *sincosofangle(float angle)
{
float *cossinofangle;
if ((cossinofangle = (float *) malloc(2*sizeof(float)))) {
*cossinofangle = sinf(degreetoradian(angle));
*(cossinofangle+1) = cosf(degreetoradian(angle));
}
return cossinofangle;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Translate from degree to radians */
static float degreetoradian(float degrees)
{
return PI_HERE*degrees/180.0;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Interface to get a cube out of engalmod */
Cube *getoriginal_galmod_(void)
{
return &original_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Interface to get a cube out of engalmod */
Cube *getmodel_galmod_(void)
{
return &model_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Interface to get a cube out of engalmod */
Cube *getnoise_galmod_(void)
{
return &noise_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static void makemodelarray(float *array)
{
int i,j;
int nx, ny;
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < expcube_model_.size_x; ++i) {
for (j = 0; j < expcube_model_.size_y; ++j) {
nx = (i <= cubesizexhalf_) ? i : (i-(model_).size_x);
ny = (j <= cubesizeyhalf_) ? j : (j-(model_).size_y);
expcube_model_.points[i+expcube_model_.size_x*j] = expofacsfft_[0]*nx*nx+expofacsfft_[1]*nx*ny+expofacsfft_[2]*ny*ny;
}
}
for (i = 0; i < expcube_model_.size_x; ++i) {
for (j = 0; j < expcube_model_.size_y; ++j) {
expcube_model_.points[i+expcube_model_.size_x*j] = expf(array[i+expcube_model_.size_x*j]);
}
}
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve a cube with a gaussian via fft */
static Cube *convolgaussfft_here_array(void)
{
int i, j, k;
float expresult; /* A dummy */
/* Convolution in all dimensions or in xy only */
/* Now do the transform */
fftwf_execute(plan_model_);
/* multiply with the gaussian, first for nu_v = 0 */
/* #ifdef OPENMPTIR */
/* #pragma omp parallel for */
/* #endif */
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian2d_array(i, j, expofacsfft_, expcube_model_.points);
transformed_cube_model_[i+newsize_*j][0] = expresult*transformed_cube_model_[i+newsize_*j][0];
transformed_cube_model_[i+newsize_*j][1] = expresult*transformed_cube_model_[i+newsize_*j][1];
}
}
/* convolgaussfft_here_array_help1(); */
/* Check for an extra-axis in v, i.e. if the dimension in v is even, we have to calculate one v-plane separately */
if (!((model_).size_v % 2)) {
/* multiply with the gaussian, first for nu_v = N_v/2 */
#ifdef OPENMPTIR
/* pragma omp parallel for */
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian_array(i, j, dummy_, expofacsfft_, expcube_model_.points, veloarray_);
transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*dummy_)][1];
}
}
}
/* Now the rest has to be done, v ranges from 1, ..., N_v-1/2, and using the symmetrics of the gaussian we fill the rest */
/* #ifdef OPENMPTIR */
/* !!! pragma omp parallel for */
/* #endif */
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
for (k = 1; k <= ((model_).size_v-1)/2; ++k) {
expresult = fftgaussian_array(i, j, k, expofacsfft_, expcube_model_.points, veloarray_);
transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*k)][1];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][0] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][0];
transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][1] = expresult*transformed_cube_model_[i+newsize_*(j+(model_).size_y*((model_).size_v-k))][1];
}
}
}
/* Now do the backtransformation */
fftwf_execute(plin_model_);
return &model_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve a cube with a gaussian via fft */
static Cube *convolgaussfft_here_single_array(void)
{
int i, j;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_model_);
/* multiply with the gaussian, first axis y, second x */
/* #ifdef OPENMPTIR */
/* !!! pragma omp parallel for */
/* #endif */
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < (model_).size_y; ++j) {
expresult = fftgaussian2d_array(i, j, expofacsfft_, expcube_model_.points);
transformed_cube_model_[i+newsize_*j][0] = expresult*transformed_cube_model_[i+newsize_*j][0];
transformed_cube_model_[i+newsize_*j][1] = expresult*transformed_cube_model_[i+newsize_*j][1];
}
}
/* Now do the backtransformation */
fftwf_execute(plin_model_);
return &model_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve the input cube with a gaussian via fft to the weightmap, adding a constant offset */
static Cube *convolgaussfft_noise_array(void)
{
int i, j, k;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_noise_);
/* fftwf_execute(plin_noise_); */
/* return NULL; */
/* multiply with the gaussian, first for nu_v = 0 */
#ifdef OPENMPTIR
/* pragma omp parallel for */
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian2d_array(i, j, expofacsfft_noise_, expcube_noise_.points);
transformed_cube_noise_[i+newsize_*j][0] = expresult*transformed_cube_noise_[i+newsize_*j][0];
transformed_cube_noise_[i+newsize_*j][1] = expresult*transformed_cube_noise_[i+newsize_*j][1];
}
}
if (!(model_.size_v % 2)) {
/* multiply with the gaussian, first for nu_v = N_v/2 */
#ifdef OPENMPTIR
/* pragma omp parallel for */
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j)
{
/* The exponential will be evaluated from 0, ... , N/2 and -1, ..., -N/2 or -N/2 - 1 */
expresult = fftgaussian_array(i,j, dummy_, expofacsfft_noise_, expcube_noise_.points, veloarray_noise_);
transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*dummy_)][1];
}
}
}
/* Now the rest has to be done, v ranges from 1, ..., N_v-1/2, and using the symmetrics of the gaussian we fill the rest */
/* #ifdef OPENMPTIR */
/* !!! pragma omp parallel for */
/* #endif */
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
for (k = 1; k <= (model_.size_v-1)/2; ++k) {
expresult = fftgaussian_array(i,j, k, expofacsfft_noise_,expcube_noise_.points, veloarray_noise_);
transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*k)][1];
/* Because of the symmetry, f(v) = f(-v), we can safe quite some calculations */
transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][0] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][0];
transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][1] = expresult*transformed_cube_noise_[i+newsize_*(j+model_.size_y*(model_.size_v-k))][1];
}
}
}
/* Now add the constant square of the noise */
transformed_cube_noise_[0][0] = transformed_cube_noise_[0][0] + noise_.scale;
/* Now do the backtransformation */
fftwf_execute(plin_noise_);
return &noise_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Convolve the input cube with a gaussian via fft to the weightmap, adding a constant offset */
static Cube *convolgaussfft_noise_single_array(void)
{
int i, j;
float expresult; /* A dummy */
/* Now do the transform */
fftwf_execute(plan_noise_);
/* multiply with the gaussian, first axis y, second x */
#ifdef OPENMPTIR
/* pragma omp parallel for */
#endif
for (i = 0; i < newsize_; ++i) {
for (j = 0; j < model_.size_y; ++j) {
expresult = fftgaussian2d_array(i,j, expofacsfft_noise_, expcube_noise_.points);
transformed_cube_noise_[i+newsize_*j][0] = expresult*transformed_cube_noise_[i+newsize_*j][0];
transformed_cube_noise_[i+newsize_*j][1] = expresult*transformed_cube_noise_[i+newsize_*j][1];
}
}
/* Now add the constant square of the noise */
transformed_cube_noise_[0][0] = transformed_cube_noise_[0][0] + noise_.scale;
/* Now do the backtransformation */
fftwf_execute(plin_noise_);
return &noise_;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
static void makenoisearray(float *array)
{
int i,j;
int nx, ny;
#ifdef OPENMPTIR
#pragma omp parallel for
#endif
for (i = 0; i < expcube_noise_.size_x; ++i) {
for (j = 0; j < expcube_noise_.size_y; ++j) {
nx = (i <= cubesizexhalf_) ? i : (i-(noise_).size_x);
ny = (j <= cubesizeyhalf_) ? j : (j-(noise_).size_y);
expcube_noise_.points[i+expcube_noise_.size_x*j] = expofacsfft_noise_[0]*nx*nx+expofacsfft_noise_[1]*nx*ny+expofacsfft_noise_[2]*ny*ny;
}
}
/* This is maybe not elegant but may be safe */
/* #ifdef OPENMPTIR */
/* !!! pragma omp parallel for */
/* #endif */
for (i = 0; i < expcube_noise_.size_x; ++i) {
for (j = 0; j < expcube_noise_.size_y; ++j) {
expcube_noise_.points[i+expcube_noise_.size_x*j] = expf(array[i+expcube_noise_.size_x*j]);
}
}
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Synonyme of fftwf_malloc */
void *malloc_engalmod(size_t size)
{
return fftwf_malloc(size);
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/* Synonyme of fftwf_free */
void free_engalmod(void *array)
{
fftwf_free(array);
return;
}
/* ------------------------------------------------------------ */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$Log: engalmod.c,v $
Revision 1.44 2011/05/25 22:25:26 jozsa
Left work
Revision 1.43 2011/05/11 13:37:12 jozsa
Left work
Revision 1.42 2011/05/10 00:30:15 jozsa
Left work
Revision 1.41 2009/05/26 07:56:40 jozsa
Left work
Revision 1.40 2007/08/22 15:58:40 gjozsa
Left work
Revision 1.39 2006/04/07 11:13:32 gjozsa
simple BUGFIX
Revision 1.38 2006/04/06 10:39:09 gjozsa
Included function engalmod_chflgs
Revision 1.37 2006/04/03 11:47:46 gjozsa
included masking, fixed a mask to be present if pixval < -1024
Revision 1.36 2005/04/20 13:26:24 gjozsa
Left work
Revision 1.35 2005/04/12 15:52:14 gjozsa
Left work
Revision 1.34 2005/04/07 12:45:47 gjozsa
Bugfix
Revision 1.33 2005/04/06 05:58:24 gjozsa
Bugfix: init now corrects the noiseweight to 1 in case of mode%2
Revision 1.32 2005/04/04 08:42:19 gjozsa
Left work
Revision 1.31 2005/04/01 12:37:11 gjozsa
Large improvements, repeated calls with same velocity dispersion are much faster
Revision 1.29 2005/03/11 17:45:54 gjozsa
Left work
Revision 1.28 2005/03/04 18:13:53 gjozsa
Left work
Revision 1.27 2005/03/02 17:56:09 gjozsa
Left work
Revision 1.26 2005/01/17 12:13:34 gjozsa
Left work
Revision 1.25 2005/01/06 10:44:10 gjozsa
Left work
Revision 1.24 2005/01/05 15:33:02 gjozsa
Left work
Revision 1.23 2004/12/30 13:36:05 gjozsa
Added probability evaluation and out-of-place fft
Revision 1.22 2004/12/27 12:54:40 gjozsa
Last updatde before commenting, no changes anymore allowed
Revision 1.21 2004/12/23 20:20:50 gjozsa
some minor changes, leaves the implementation of arbitrary arrays
Revision 1.18 2004/12/22 17:33:57 gjozsa
Left work
Revision 1.14 2004/12/21 18:42:12 gjozsa
Left work
Revision 1.10 2004/12/21 17:50:21 gjozsa
some changes
Revision 1.7 2004/12/20 14:55:58 gjozsa
Left work
Revision 1.5 2004/12/20 10:44:12 gjozsa
added
Revision 1.4 2004/12/17 14:13:40 gjozsa
First debugged running version
Revision 1.3 2004/12/16 13:19:51 gjozsa
Left work
Revision 1.1 2004/12/11 17:44:51 gjozsa
Added to CVS control
------------------------------------------------------------ */
| {
"alphanum_fraction": 0.6132852612,
"avg_line_length": 33.6711486746,
"ext": "c",
"hexsha": "6450d7be05653945200e12e89ed859d979baa7de",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-03T15:02:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-28T03:17:38.000Z",
"max_forks_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kernsuite-debian/tirific",
"max_forks_repo_path": "src/engalmod.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9",
"max_issues_repo_issues_event_max_datetime": "2019-10-31T15:08:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-03-14T14:01:18.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kernsuite-debian/tirific",
"max_issues_repo_path": "src/engalmod.c",
"max_line_length": 310,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kernsuite-debian/tirific",
"max_stars_repo_path": "src/engalmod.c",
"max_stars_repo_stars_event_max_datetime": "2018-01-04T08:22:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-07-01T12:07:09.000Z",
"num_tokens": 24976,
"size": 87646
} |
#ifndef AMICI_MISC_H
#define AMICI_MISC_H
#include "amici/defines.h"
#include "amici/exception.h"
#include "amici/vector.h"
#include <sunmatrix/sunmatrix_sparse.h> // SUNMatrixContent_Sparse
#include <algorithm>
#include <vector>
#include <memory>
#include <regex>
#include <gsl/gsl-lite.hpp>
namespace amici {
/**
* @brief creates a slice from existing data
*
* @param data to be sliced
* @param index slice index
* @param size slice size
* @return span of the slice
*/
template <class T>
gsl::span<T> slice(std::vector<T> &data, int index, unsigned size) {
if ((index + 1) * size > data.size())
throw std::out_of_range("requested slice is out of data range");
if (size > 0)
return gsl::make_span(&data.at(index*size), size);
return gsl::make_span(static_cast<T*>(nullptr), 0);
}
/**
* @brief creates a constant slice from existing constant data
*
* @param data to be sliced
* @param index slice index
* @param size slice size
* @return span of the slice
*/
template <class T>
const gsl::span<const T> slice(const std::vector<T> &data,
int index, unsigned size) {
if ((index + 1) * size > data.size())
throw std::out_of_range("requested slice is out of data range");
if (size > 0)
return gsl::make_span(&data.at(index*size), size);
return gsl::make_span(static_cast<T*>(nullptr), 0);
}
/**
* @brief local helper to check whether the provided buffer has the expected
* size
* @param buffer buffer to which values are to be written
* @param expected_size expected size of the buffer
*/
template <class T>
void checkBufferSize(gsl::span<T> buffer,
typename gsl::span<T>::index_type expected_size) {
if (buffer.size() != expected_size)
throw AmiException("Incorrect buffer size! Was %u, expected %u.",
buffer.size(), expected_size);
}
/* TODO: templating writeSlice breaks implicit conversion between vector & span
not sure whether this is fixable */
/**
* @brief local helper function to write computed slice to provided buffer (span)
* @param slice computed value
* @param buffer buffer to which values are to be written
*/
template <class T>
void writeSlice(const gsl::span<const T> slice, gsl::span<T> buffer) {
checkBufferSize(buffer, slice.size());
std::copy(slice.begin(), slice.end(), buffer.data());
};
/**
* @brief local helper function to write computed slice to provided buffer (vector)
* @param s computed value
* @param b buffer to which values are to be written
*/
template <class T>
void writeSlice(const std::vector<T> &s, std::vector<T> &b) {
writeSlice(gsl::make_span(s.data(), s.size()),
gsl::make_span(b.data(), b.size()));
};
/**
* @brief local helper function to write computed slice to provided buffer (vector/span)
* @param s computed value
* @param b buffer to which values are to be written
*/
template <class T>
void writeSlice(const std::vector<T> &s, gsl::span<T> b) {
writeSlice(gsl::make_span(s.data(), s.size()), b);
};
/**
* @brief local helper function to write computed slice to provided buffer (AmiVector/span)
* @param s computed value
* @param b buffer to which values are to be written
*/
void writeSlice(const AmiVector &s, gsl::span<realtype> b);
/**
* @brief Remove parameter scaling according to the parameter scaling in pscale
*
* All vectors must be of same length.
*
* @param bufferScaled scaled parameters
* @param pscale parameter scaling
* @param bufferUnscaled unscaled parameters are written to the array
*/
void unscaleParameters(gsl::span<const realtype> bufferScaled,
gsl::span<const ParameterScaling> pscale,
gsl::span<realtype> bufferUnscaled);
/**
* @brief Remove parameter scaling according to `scaling`
*
* @param scaledParameter scaled parameter
* @param scaling parameter scaling
*
* @return Unscaled parameter
*/
double getUnscaledParameter(double scaledParameter, ParameterScaling scaling);
/**
* @brief Apply parameter scaling according to `scaling`
* @param unscaledParameter
* @param scaling parameter scaling
* @return Scaled parameter
*/
double getScaledParameter(double unscaledParameter, ParameterScaling scaling);
/**
* @brief Apply parameter scaling according to `scaling`
* @param bufferUnscaled
* @param pscale parameter scaling
* @param bufferScaled destination
*/
void scaleParameters(gsl::span<const realtype> bufferUnscaled,
gsl::span<const ParameterScaling> pscale,
gsl::span<realtype> bufferScaled);
/**
* @brief Returns the current backtrace as std::string
* @param maxFrames Number of frames to include
* @return Backtrace
*/
std::string backtraceString(int maxFrames);
/**
* @brief Convert std::regex_constants::error_type to string
* @param err_type error type
* @return Error type as string
*/
std::string regexErrorToString(std::regex_constants::error_type err_type);
/**
* @brief Format printf-style arguments to std::string
* @param fmt Format string
* @param ap Argument list pointer
* @return Formatted String
*/
std::string printfToString(const char *fmt, va_list ap);
/**
* @brief Generic implementation for a context manager, explicitly deletes copy
* and move operators for derived classes
*/
class ContextManager{
public:
ContextManager() = default;
ContextManager(ContextManager &other) = delete;
ContextManager(ContextManager &&other) = delete;
};
} // namespace amici
#endif // AMICI_MISC_H
| {
"alphanum_fraction": 0.6916607015,
"avg_line_length": 28.9533678756,
"ext": "h",
"hexsha": "dd59b03fc9c759b97654f8ce6f3417920768bd71",
"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": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "PaulJonasJost/AMICI",
"max_forks_repo_path": "include/amici/misc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "PaulJonasJost/AMICI",
"max_issues_repo_path": "include/amici/misc.h",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a5c679b0cce90e192bacf9461d43825de8f675ce",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "PaulJonasJost/AMICI",
"max_stars_repo_path": "include/amici/misc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1305,
"size": 5588
} |
/* multifit/gsl_multifit.h
*
* Copyright (C) 2000, 2007, 2010 Brian Gough
* Copyright (C) 2013, Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MULTIFIT_H__
#define __GSL_MULTIFIT_H__
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.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
typedef struct
{
size_t nmax; /* maximum number of observations */
size_t pmax; /* maximum number of parameters */
size_t n; /* number of observations in current SVD decomposition */
size_t p; /* number of parameters in current SVD decomposition */
gsl_matrix * A; /* least squares matrix for SVD, n-by-p */
gsl_matrix * Q;
gsl_matrix * QSI;
gsl_vector * S;
gsl_vector * t;
gsl_vector * xt;
gsl_vector * D;
double rcond; /* reciprocal condition number */
}
gsl_multifit_linear_workspace;
gsl_multifit_linear_workspace *
gsl_multifit_linear_alloc (const size_t n, const size_t p);
void
gsl_multifit_linear_free (gsl_multifit_linear_workspace * w);
int
gsl_multifit_linear (const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_tsvd (const gsl_matrix * X,
const gsl_vector * y,
const double tol,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
size_t * rank,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_svd (const gsl_matrix * X,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_bsvd (const gsl_matrix * X,
gsl_multifit_linear_workspace * work);
size_t
gsl_multifit_linear_rank(const double tol, const gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_solve (const double lambda,
const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
double *rnorm,
double *snorm,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_applyW(const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * WX,
gsl_vector * Wy);
int
gsl_multifit_linear_stdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_wstdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * tau);
int
gsl_multifit_linear_stdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_wstdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_genform1 (const gsl_vector * L,
const gsl_vector * cs,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_genform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_wgenform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_lreg (const double smin, const double smax,
gsl_vector * reg_param);
int
gsl_multifit_linear_lcurve (const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * rho, gsl_vector * eta,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_lcorner(const gsl_vector *rho,
const gsl_vector *eta,
size_t *idx);
int
gsl_multifit_linear_lcorner2(const gsl_vector *reg_param,
const gsl_vector *eta,
size_t *idx);
int
gsl_multifit_linear_Lk(const size_t p, const size_t k, gsl_matrix *L);
int
gsl_multifit_linear_Lsobolev(const size_t p, const size_t kmax,
const gsl_vector *alpha, gsl_matrix *L,
gsl_multifit_linear_workspace *work);
int
gsl_multifit_wlinear (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_wlinear_tsvd (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
const double tol,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
size_t * rank,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_wlinear_svd (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,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_wlinear_usvd (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,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_est (const gsl_vector * x,
const gsl_vector * c,
const gsl_matrix * cov, double *y, double *y_err);
double
gsl_multifit_linear_rcond (const gsl_multifit_linear_workspace * w);
int
gsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y,
const gsl_vector *c, gsl_vector *r);
/* gcv.c */
int
gsl_multifit_linear_gcv_init(const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * UTy,
double * delta0,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_gcv_curve(const gsl_vector * reg_param,
const gsl_vector * UTy,
const double delta0,
gsl_vector * G,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_gcv_min(const gsl_vector * reg_param,
const gsl_vector * UTy,
const gsl_vector * G,
const double delta0,
double * lambda,
gsl_multifit_linear_workspace * work);
double
gsl_multifit_linear_gcv_calc(const double lambda,
const gsl_vector * UTy,
const double delta0,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_gcv(const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * G,
double * lambda,
double * G_lambda,
gsl_multifit_linear_workspace * work);
typedef struct
{
const char * name; /* method name */
int (*wfun)(const gsl_vector *r, gsl_vector *w);
int (*psi_deriv)(const gsl_vector *r, gsl_vector *dpsi);
double tuning_default; /* default tuning constant */
} gsl_multifit_robust_type;
typedef struct
{
double sigma_ols; /* OLS estimate of sigma */
double sigma_mad; /* MAD estimate of sigma */
double sigma_rob; /* robust estimate of sigma */
double sigma; /* final estimate of sigma */
double Rsq; /* R^2 coefficient of determination */
double adj_Rsq; /* degree of freedom adjusted R^2 */
double rmse; /* root mean squared error */
double sse; /* residual sum of squares */
size_t dof; /* degrees of freedom */
size_t numit; /* number of iterations */
gsl_vector *weights; /* final weights */
gsl_vector *r; /* final residuals y - X c */
} gsl_multifit_robust_stats;
typedef struct
{
size_t n; /* number of observations */
size_t p; /* number of parameters */
size_t numit; /* number of iterations */
size_t maxiter; /* maximum iterations */
const gsl_multifit_robust_type *type;
double tune; /* tuning parameter */
gsl_vector *r; /* residuals at current iteration */
gsl_vector *weights; /* weights at current iteration */
gsl_vector *c_prev; /* coefficients from previous iteration */
gsl_vector *resfac; /* multiplicative factors for residuals */
gsl_vector *psi; /* psi(r) */
gsl_vector *dpsi; /* psi'(r) */
gsl_matrix *QSI; /* Q S^{-1} of original matrix X */
gsl_vector *D; /* balancing parameters of original matrix X */
gsl_vector *workn; /* workspace of length n */
gsl_multifit_robust_stats stats; /* various statistics */
gsl_multifit_linear_workspace *multifit_p;
} gsl_multifit_robust_workspace;
/* available types */
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_default;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_bisquare;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_cauchy;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_fair;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_huber;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_ols;
GSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_welsch;
gsl_multifit_robust_workspace *gsl_multifit_robust_alloc(const gsl_multifit_robust_type *T,
const size_t n, const size_t p);
void gsl_multifit_robust_free(gsl_multifit_robust_workspace *w);
int gsl_multifit_robust_tune(const double tune,
gsl_multifit_robust_workspace *w);
int gsl_multifit_robust_maxiter(const size_t maxiter,
gsl_multifit_robust_workspace *w);
const char *gsl_multifit_robust_name(const gsl_multifit_robust_workspace *w);
gsl_multifit_robust_stats gsl_multifit_robust_statistics(const gsl_multifit_robust_workspace *w);
int gsl_multifit_robust_weights(const gsl_vector *r, gsl_vector *wts,
gsl_multifit_robust_workspace *w);
int gsl_multifit_robust(const gsl_matrix * X, const gsl_vector * y,
gsl_vector * c, gsl_matrix *cov,
gsl_multifit_robust_workspace *w);
int gsl_multifit_robust_est(const gsl_vector * x, const gsl_vector * c,
const gsl_matrix * cov, double *y, double *y_err);
int gsl_multifit_robust_residuals(const gsl_matrix * X,
const gsl_vector * y,
const gsl_vector * c, gsl_vector * r,
gsl_multifit_robust_workspace * w);
__END_DECLS
#endif /* __GSL_MULTIFIT_H__ */
| {
"alphanum_fraction": 0.5507595024,
"avg_line_length": 38.186351706,
"ext": "h",
"hexsha": "65feec5022b55a16db78592b8fb451b5d2d2ad88",
"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_multifit.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_multifit.h",
"max_line_length": 97,
"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_multifit.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": 3087,
"size": 14549
} |
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include "Watershed.h"
#include "math_functions.h"
#include "Globals.h"
#include "constitutive_equations.h"
#include "dgshed_numerical_flux.h"
#include "manufactured_solution.h"
/*****************************************************************************************//**
* @file computeL.c
*
* This file contains code to evaluate the right hand side of the following discrete ODE obtained
* from the DG discretization of the 2-D shallow water equations:
*
* \f$\frac{\partial \hat{\mathbf{w}}}{\partial t} = M^{-1}L(\hat{\mathbf{w}},t)\f$
*
* *******************************************************************************************/
/***************************************************************************/
/************ Compute the spatial discretization of the equation ***********/
/***************************************************************************/
extern void GetLGLWeights(int N, double *w);
extern double receive_floodwater(struct TwoDRegion *floodplain, int edg);
void computeChanL(struct channel* Chan, double time, double *dt, int channelNumber, int stage, double* RHSA, double* RHSQ)
{
int fluxType = 1;
int NumEdges = Chan->NumEdges;
int NumEl = Chan->NumEl;
int NumNodes = Chan->NumNodes;
int Np = Chan->Np;
int P = Chan->P;
#ifdef WDON
/**** Compute the mass over an element to use later for ensuring ********/
/**** positive mass with the flux in a wetting and drying treatment *************/
double* mass = xcalloc(NumEl, sizeof(double));
double LGLWeight[Np];
GetLGLWeights(P, LGLWeight);
for (int i = 0; i < NumEl; ++i)
{
double avgArea = 0;
int begNode = i*Np + 1;
for (int j =0; j < Np; j++)
{
avgArea += LGLWeight[j]*Chan->A[begNode+j];
}
mass[i] = avgArea;
}
#endif
/************** Compute the numerical flux at the faces *****************/
double* Fhat1L = xcalloc(NumEdges, sizeof(double));
double* Fhat2L = xcalloc(NumEdges, sizeof(double));
double* Fhat1R = xcalloc(NumEdges, sizeof(double));
double* Fhat2R = xcalloc(NumEdges, sizeof(double));
for (int i=0; i < NumEdges; ++i)
{
double A_L, Q_L, A_R, Q_R, m1val, m2val;
int leftNode = i*Np;
int rightNode = leftNode+1;
m1val = Chan->m1[i];
m2val = Chan->m2[i];
double bval = Chan->b[i];
double tmpF[2];
#ifdef WDON
// Check to see if the elements separated by this boundary are both dry
if (i > 0 && i < NumEdges-1)
{
if (Chan->WD[i-1] == 0 && Chan->WD[i] == 0)
{
// Reflection flux for the left element
A_L = Chan->A[leftNode];
A_R = A_L;
Q_L = Chan->Q[leftNode];
Q_R = -Q_L;
if (fluxType == 1)
RoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R,bval, m1val, m2val,0);
else if (fluxType == 2)
LFChan(tmpF, A_L, A_R, Q_L, Q_R,bval, m1val, m2val, 0);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
// Reflection flux for the right element
A_R = Chan->A[rightNode];
A_L = A_R;
Q_R = Chan->Q[rightNode];
Q_L = -Q_R;
if (fluxType == 1)
RoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);
else if (fluxType == 2)
LFChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("both elements dry flux not a number, edge %d \n",i);
exit(EXIT_FAILURE);
}
}
}
// if the elements are not both dry
if ((i == 0) || (i == NumEl) || Chan->WD[i-1] == 1 || Chan->WD[i] == 1)
{
A_L = Chan->A[leftNode];
A_R = Chan->A[rightNode];
Q_L = Chan->Q[leftNode];
Q_R = Chan->Q[rightNode];
if (fluxType == 1)
RoeFluxChan(tmpF, A_L, A_R, Q_L,Q_R,bval, m1val, m2val, g);
else if (fluxType == 2)
LFChan(tmpF, A_L, A_R, Q_L,Q_R,bval, m1val, m2val, g);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf\n", A_L, A_R, Q_L, Q_R);
printf(" both elements wet flux not a number, edge %d, channel %d , time = %lf\n",i, channelNumber, time);
exit(EXIT_FAILURE);
}
if (i==0 || Chan->WD[i-1] == 1)
{
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
}
else
{
double newtmpF[2];
if (fluxType == 1)
RoeFluxChan(newtmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);
else if (fluxType == 2)
LFChan(newtmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
Fhat1L[i] = newtmpF[0];
Fhat2L[i] = newtmpF[1];
if (isnan(newtmpF[0]) || isnan(newtmpF[1]))
{
printf("left element dry flux not a number, edge %d \n",i);
exit(EXIT_FAILURE);
}
}
if (i == NumEl || Chan->WD[i]==1)
{
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
}
else
{
if (fluxType == 1)
RoeFluxChan(tmpF, A_L,A_R,Q_L,Q_R,bval, m1val, m2val, 0);
else if (fluxType == 2)
LFChan(tmpF, A_L,A_R,Q_L,Q_R,bval, m1val, m2val, 0);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("right element dry flux not a number, edge %d \n",i);
printf("A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf bval = %lf m1val = %lf m2val = %lf\n", A_L, A_R, Q_L, Q_R, bval, m1val, m2val);
printf("F = %lf\n", tmpF[0]);
exit(EXIT_FAILURE);
}
}
}
#else
A_L = Chan->A[leftNode];
A_R = Chan->A[rightNode];
Q_L = Chan->Q[leftNode];
Q_R = Chan->Q[rightNode];
if (fluxType == 1)
RoeFluxChan(tmpF, A_L, A_R, Q_L,Q_R,bval,m1val,m2val,g);
else if (fluxType == 2)
LFChan(tmpF, A_L, A_R, Q_L,Q_R,bval,m1val,m2val,g);
else
{
printf("Unknown flux type. Exiting now \n");
exit(1);
}
if (isnan(tmpF[0]) || isnan(tmpF[1]))
{
printf("flux not a number, edge %d \n",i);
printf("A_L = %3.16f A_R = %3.16f Q_L = %3.16f Q_R = %31.6f, b = %lf, m1 = %lf, m2 = %lf \n", A_L, A_R, Q_L, Q_R, Chan->b[i], m1val, m2val);
printf("Fhat = %lf Ghat = %lf\n", tmpF[0], tmpF[1]);
exit(EXIT_FAILURE);
}
Fhat1L[i] = tmpF[0];
Fhat2L[i] = tmpF[1];
Fhat1R[i] = tmpF[0];
Fhat2R[i] = tmpF[1];
#endif
/**************************************************************************************************/
double u_L = Q_L/A_L;
double u_R = Q_R/A_R;
//approximate c_L (exact for rectangular channels, but not for trapezoidal
double c_L = sqrt(g*A_L/Chan->b[i]);
double c_R = sqrt(g*A_R/Chan->b[i]);
if (i==0)
Chan->max_lambda = fmax((fabs(u_L)+c_L), (fabs(u_R)+c_R));
// Compute maximum eigenvalue for the next time step
double current_max =fmax((fabs(u_L) + c_L), (fabs(u_R) + c_R));
Chan->max_lambda = max(Chan->max_lambda,current_max);
}
#ifdef WDON
for (int i =1; i < NumEdges-1; ++i)
{
int leftNode = i*Np;
int rightNode = leftNode+1;
double maxBetaOverAlpha = 2;
// Check to see if this flux might possibly result in negative mass
// If the mass will be negative on the left side
//int cont = 1;
//while(cont)
//{
if (Fhat1L[i]*maxBetaOverAlpha*(*dt) > mass[i-1] || -Fhat1R[i]*maxBetaOverAlpha*(*dt) > mass[i] )
{
Fhat1L[i] = 0.0;
Fhat2L[i] = 0.0;
Fhat1R[i] = 0.0;
Fhat2R[i] = 0.0;
//double A_L = Chan->A[leftNode];
//double A_R = A_L;
//double Q_L = Chan->Q[leftNode];
//double Q_R = -Q_L;
//double bval = Chan->NodalB[leftNode];
//double m1val = Chan->Nodalm1[leftNode];
//double m2val = Chan->Nodalm2[leftNode];
//double tmpF[2];
//double localG = g;
//if (Chan->WD[i] == 0)
// localG = 0;
//if (fluxType == 1)
// RoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);
//else if (fluxType == 2)
// LFChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);
//else
//{
// printf("Unknown flux type. Exiting now \n");
// exit(1);
//}
//Fhat1L[i] = tmpF[0];
//Fhat2L[i] = tmpF[1];
//printf("element %d of Channel %d will be dry. Reducing dt now.\n", i, channelNumber);
//(*dt) = 0.5*(*dt);
}
//else
// cont = 0;
//}
//cont = 1;
//while(cont)
//{
// // If the mass will be negative on the right side
// if (-Fhat1R[i]*maxBetaOverAlpha*(*dt) > mass[i])
// {
// double A_R = Chan->A[rightNode];
// double A_L = A_R;
// double Q_R = Chan->Q[rightNode];
// double Q_L = -Q_R;
// double bval = Chan->NodalB[rightNode];
// double m1val = Chan->Nodalm1[rightNode];
// double m2val = Chan->Nodalm2[rightNode];
// double tmpF[2];
// double localG = g;
// if (Chan->WD[i] == 0)
// localG = 0;
// if (fluxType == 1)
// RoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val,localG);
// else if (fluxType == 2)
// LFChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);
// else
// {
// printf("Unknown flux type. Exiting now \n");
// exit(1);
// }
// Fhat1R[i] = tmpF[0];
// Fhat2R[i] = tmpF[1];
// printf("element %d of channel %d will be dry. Decreasing dt now.\n",i, channelNumber);
// *dt = 0.5*(*dt);
// }
// else
// cont = 0;
//}
}
free(mass);
#endif
for (int k=0; k < NumEl; ++k)
{
double h = Chan->dh[k];
gsl_vector *F1 = gsl_vector_alloc(Np);
gsl_vector *F2 = gsl_vector_alloc(Np);
gsl_vector *ST21 = gsl_vector_alloc(Np);
gsl_vector *ST22 = gsl_vector_alloc(Np);
gsl_vector *ST23 = gsl_vector_alloc(Np);
//ST11 contains the qL term that comes from overland flow
gsl_vector *ST11 = gsl_vector_calloc(Np);
// ST12 contains term that takes flooding into account
gsl_vector *ST12 = gsl_vector_calloc(Np);
int begNode = k*Np;
for (int i = 0; i < Np; i++)
{
double Aval = Chan->A[begNode+i+1];
double Qval = Chan->Q[begNode+i+1];
double qL = Chan->qL[begNode+i];
double qM = Chan->qM[begNode+i];
double bval = Chan->NodalB[begNode+i];
double S0 = Chan->dz[begNode+i];
double m1val = Chan->Nodalm1[begNode+i];
double m2val = Chan->Nodalm2[begNode+i];
double dm1val = Chan->dm1[begNode+i];
double dm2val = Chan->dm2[begNode+i];
double dbval = Chan->db[begNode+i];
double nval = Chan->NodalnFriction[begNode+i];
double I1val = getI1(Aval, bval, m1val, m2val);
double I2val = getI2(Aval, bval, dbval, m1val, dm1val, m2val, dm2val);
double Sfval = getS_f(Aval, Qval, bval, m1val, m2val, nval);
double beta = Chan->beta[begNode+i];
double localG;
#ifdef WDON
if(Chan->WD[k]==1)
localG = g;
else
localG = 0;
#else
localG = g;
#endif
gsl_vector_set(F1, i, Qval);
gsl_vector_set(F2, i, beta*Qval*Qval/Aval + localG*I1val);
gsl_vector_set(ST21, i, localG*I2val);
gsl_vector_set(ST22, i, localG*Aval*S0);
gsl_vector_set(ST23, i, localG*Aval*Sfval);
gsl_vector_set(ST11, i, qL);
gsl_vector_set(ST12, i, qM);
}
//gsl_blas_dgemv(CblasNoTrans, 2.0/h, InvM, ST, 1.0, ST11);
gsl_vector *localFhat1 = gsl_vector_alloc(2);
gsl_vector_set(localFhat1, 0, Fhat1R[k]);
gsl_vector_set(localFhat1, 1, Fhat1L[k+1]);
gsl_vector *localFhat2 = gsl_vector_alloc(2);
gsl_vector_set(localFhat2, 0, Fhat2R[k]);
gsl_vector_set(localFhat2, 1, Fhat2L[k+1]);
// cacluate the volume integral of the flux
gsl_vector *localRHS1 = gsl_vector_calloc(Np);
gsl_vector *localRHS2 = gsl_vector_calloc(Np);
gsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F1, 1.0, localRHS1);
gsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F2, 1.0, localRHS2);
// calculate the surface integral of the flux
gsl_vector *SurfPart1 = gsl_vector_calloc(Np);
gsl_vector *SurfPart2 = gsl_vector_calloc(Np);
gsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat1, 1.0, SurfPart1);
gsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat2, 1.0, SurfPart2);
// calculate the RHS
gsl_vector_add(localRHS1, SurfPart1);
gsl_vector_add(localRHS1, ST11);
gsl_vector_add(localRHS1, ST12);
gsl_vector_add(localRHS2, SurfPart2);
gsl_vector_add(localRHS2, ST21);
gsl_vector_add(localRHS2, ST22);
gsl_vector_sub(localRHS2, ST23);
for(int i = 0; i < Np; i++)
{
RHSA[begNode+i+1] = gsl_vector_get(localRHS1, i);
RHSQ[begNode+i+1] = gsl_vector_get(localRHS2, i);
}
gsl_vector_free(F1);
gsl_vector_free(F2);
gsl_vector_free(localFhat1);
gsl_vector_free(localFhat2);
gsl_vector_free(SurfPart1);
gsl_vector_free(SurfPart2);
gsl_vector_free(ST11);
gsl_vector_free(ST12);
gsl_vector_free(ST21);
gsl_vector_free(ST22);
gsl_vector_free(ST23);
gsl_vector_free(localRHS1);
gsl_vector_free(localRHS2);
}
free(Fhat1L);
free(Fhat1R);
free(Fhat2L);
free(Fhat2R);
}
void computeLKinematicEls(double time, double* RHS, int fp)
{
int NumEl = FloodplainList[fp]->NumEl;
// calculate and store the flux (Q) at the downstream edge of each kinematic element
// these fluxes will be used to calculate the upwinded flux values
double *Fhat = xcalloc(NumEl, sizeof(double));
for (int i = 0; i < NumEl; ++i)
{
struct kinematicEl *kinEl = KinematicElList[i];
if (kinEl->isActive)
{
int Np = kinEl->Np;
double myA = kinEl->A[Np-1];
double myS0 = kinEl->dz[Np-1];
double myNf = kinEl->NodalnFriction[Np-1];
double myWeq = kinEl->weq;
double myH = myA/myWeq;
// using manning's N.
Fhat[i] = myWeq*sqrt(myS0)*pow(myH, 5.0/3)/myNf;
// using chezy's relationship. nf stands for C, chezy's coefficient
//Fhat[i] = myWeq*sqrt(myS0*myH)*myH*myNf;
}
}
// now calculate the right hand side
for (int i = 0; i < NumEl; ++i)
{
struct kinematicEl *kinEl = KinematicElList[i];
if (kinEl->isActive)
{
double h_el = kinEl->dh;
int Np = kinEl->Np;
gsl_vector *F = gsl_vector_calloc(Np);
gsl_vector *ST = gsl_vector_calloc(Np); // will eventually store R-I (Rainfall - Infiltration)
double weq = kinEl->weq;
for (int j = 0; j < Np; ++j)
{
double A = kinEl->A[j];
double nf = kinEl->NodalnFriction[j];
double S0 = kinEl->dz[j];
double H = A/weq;
// using manning's N
double myF = weq*sqrt(S0)*pow(H,5.0/3)/nf;
// using Chezy's relationship (nf stands for C)
//double myF = weq*sqrt(S0*H)*H*nf;
if (S0 < 0 )
printf("z1 = %lf z2 = %lf\n", kinEl->z1, kinEl->z2);
if (isnan(myF))
{
printf("myF is nan; A = %lf, nf = %lf, S0 = %lf, H = %lf weq = %lf, kinElNum = %d\n", A, nf, S0, H, weq, i);
exit(1);
}
gsl_vector_set(F, j, myF);
double rainfall;
if (time < 1800)
rainfall = 1.0/12/3600;
gsl_vector_set(ST, j, weq*rainfall);
// second parking lot case
//if (time <= 180)
// gsl_vector_set(ST, j, weq*2.0/12/3600);
//else if (time <= 360)
// gsl_vector_set(ST, j, weq*4.0/12/3600);
}
// Now calculate total upstream flux.
// If the element is at the boundary of the watershed, flux coming in will be 0.
int numUpstreamEls = kinEl->numUpstreamEls;
double Fhat1 = 0.0;
//if (numUpstreamEls > 1)
// printf(" i = %d UpEl1 = %d UpEl2 = %d\n", i, kinEl->upstreamEls[0], kinEl->upstreamEls[1]);
for (int j = 0; j < numUpstreamEls; ++j)
{
int upstreamEl = kinEl->upstreamEls[j];
//printf("upstream el = %d\t", upstreamEl);
Fhat1 += Fhat[upstreamEl];
}
//printf("downstream el = %d\n", kinEl->el2);
double Fhat2 = Fhat[i];
gsl_vector *localFhat = gsl_vector_alloc(2);
gsl_vector_set(localFhat, 0, Fhat1);
gsl_vector_set(localFhat, 1, Fhat2);
gsl_vector *localRHS = gsl_vector_calloc(Np);
// calculate the volume integral
gsl_blas_dgemv(CblasNoTrans, 2.0/h_el, VolMat, F, 1.0, localRHS);
// calculate the surface integral
gsl_vector *SurfPart = gsl_vector_calloc(Np);
gsl_blas_dgemv(CblasNoTrans, 2.0/h_el, LIFT, localFhat, 1.0, SurfPart);
// subtract the surface integral from the volume integral
gsl_vector_add(localRHS, SurfPart);
// add source term to the right hand side
gsl_vector_add(localRHS, ST);
for (int j = 0; j < Np; j++)
{
RHS[i*Np+j] = gsl_vector_get(localRHS, j);
if (isnan(RHS[i*Np+j]))
{
printf("SurfPart = %lf \n", gsl_vector_get(SurfPart,j));
}
}
gsl_vector_free(F);
gsl_vector_free(localFhat);
gsl_vector_free(SurfPart);
gsl_vector_free(localRHS);
gsl_vector_free(ST);
}
}
free(Fhat);
}
/***********************************************************************************************//**
* Function for evaluating the right hand side of the discrete ODE obtained from the DG discretization
* of the 2-D shallow water equations
* @param [in] currRegion a pointer to the junction structure corresponding to the junction that is
* currently being worked on
* @param [in] time a double representing the current time of the simulation
* @param [out] RHSZeta a pointer to an array of size NumEl x 3 in which the right hand side for
* the water surface elevation will be stored
* @param [out] RHSQx a pointer to an array of size NumEl x 3 in which the right hand side for the
* momentum in the x-direction is stored
* @param [out] RHSQy a pointer to an array of size NumEl x 3 in which the right hand side for the
* momentum in the y-direction is stored
*
***************************************************************************************************/
void compute2DL(struct TwoDRegion *currRegion, double time, double *RHSZeta, double *RHSQx, double *RHSQy, double dt)
{
int NumEdges = currRegion->TotalNumEdges;
int NumEl = currRegion->NumEl;
int Nfp = currRegion->P + 1;
int Np = currRegion->Np;
#ifdef WDON
/**** Compute the mass over an element to use later for ensuring ********/
/**** positive mass with the flux in a wetting and drying treatment *************/
double* mass = xcalloc(NumEl, sizeof(double));
gsl_vector *height = gsl_vector_calloc(Np);
gsl_vector *tmp = gsl_vector_alloc(Np);
gsl_vector *jac = gsl_vector_alloc(Np);
for (int i = 0; i < NumEl; ++i)
{
for (int j = 0; j < Np; j++)
{
gsl_vector_set(height, j, currRegion->zeta[i][j] + currRegion->NodalZ[i][j]);
gsl_vector_set(jac, j, currRegion->jac[i]);
}
gsl_blas_dgemv(CblasNoTrans, 1.0, MassMatrix2D, height, 0.0, tmp);
gsl_blas_ddot(jac, tmp, &mass[i]);
}
gsl_vector_free(height);
gsl_vector_free(tmp);
gsl_vector_free(jac);
#endif
/********************************* Compute Roe's flux at the face **********************************************/
double **Fhat1dotn, **Fhat2dotn, **Fhat3dotn;
Fhat1dotn = malloc(NumEl*sizeof(double*));
Fhat2dotn = malloc(NumEl*sizeof(double*));
Fhat3dotn = malloc(NumEl*sizeof(double*));
for (int i = 0; i < NumEl; i++)
{
Fhat1dotn[i] = xcalloc(3*Nfp, sizeof(double));
Fhat2dotn[i] = xcalloc(3*Nfp, sizeof(double));
Fhat3dotn[i] = xcalloc(3*Nfp, sizeof(double));
}
for (int i=0; i<NumEdges; ++i)
{
int el1 = currRegion->EdgtoEls[i*2];
int el2 = currRegion->EdgtoEls[i*2+1];
int ledg1 = currRegion->GlobaltoLocalEdg[i*2];
int ledg2 = currRegion->GlobaltoLocalEdg[i*2+1];
// take the normal from element 1 side
double nx = currRegion->nx[el1*3+ledg1];
double ny = currRegion->ny[el1*3+ledg1];
double tx = -ny;
double ty = nx;
for (int j = 0; j < Nfp; j++)
{
double zeta_in, Qx_in, Qy_in;
double zeta_ex, Qx_ex, Qy_ex;
double z_in, z_ex; // should be the same as z_ex
int lv1 = currRegion->GlobalEdgPosNegNodes[i][2*j];
int lv2 = currRegion->GlobalEdgPosNegNodes[i][2*j+1];
int pos1 = currRegion->PosInFVec[i][2*j];
int pos2 = currRegion->PosInFVec[i][2*j+1];
double Fn_in[3], Fn_ex[3];
zeta_in = currRegion->zeta[el1][lv1];
Qx_in = currRegion->Qx[el1][lv1];
Qy_in = currRegion->Qy[el1][lv1];
z_in = currRegion->NodalZ[el1][lv1];
double Q_T_in = Qx_in*tx + Qy_in*ty;
// need to change this later so that the boundary condition is given per node on the edge
// if the edge is an exterior edge connected to a channel
int bdrypres = currRegion->BdryPrescribed[i];
//if (el1 == 531 || el2 == 531)
//{
// printf("el1 = %d, el2 = %d\n", el1, el2);
// printf("WD1 = %d, WD2 = %d\n", currRegion->WD[el1], currRegion->WD[el2]);
// printf("bdrypres = %d\n", bdrypres);
//}
// manufactured solution
if (bdrypres == 555)
//if (bdrypres == 555 || (el1 == el2))
{
double xval = currRegion->NodalX[el1][lv1];
double yval = currRegion->NodalY[el1][lv1];
zeta_ex = getmanH(xval, yval, time);
Qx_ex = getQx(xval, yval, time);
Qy_ex = getQy(xval, yval, time);
}
// if inflow or outflow boundary, i.e. if bdrypres = 1 or 2
//for floodplains
else if (bdrypres == 111)
{
zeta_ex = currRegion->bzeta[i];
Qx_ex = Qx_in;
Qy_ex = Qy_in;
}
else if (bdrypres == 222)
{
zeta_ex = zeta_in;
double Q_N_ex = currRegion->bQn[i];
double Q_T_ex = Q_T_in;
double denom = 1./(nx*ty-ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
}
else if (bdrypres == 333)
{
zeta_ex = currRegion->bQn[i];
double Q_N_ex = currRegion->bQn[i];
double Q_T_ex = Q_T_in;
double denom = 1./(nx*ty-ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
}
// for junctions
else if (bdrypres == 1 || bdrypres == 2)
{
zeta_ex = currRegion->bzeta[i];
double Q_N_ex = currRegion->bQn[i];
// for the first iteration
if (zeta_ex == -10000.0 && Q_N_ex == -10000.0)
{
zeta_ex = zeta_in;
Qx_ex = Qx_in;
Qy_ex = Qy_in;
z_ex = z_in;
}
else
{
double Q_T_ex = Q_T_in;
double denom = 1./(nx*ty-ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
z_ex = z_in;
}
}
// for floodplains
else if (bdrypres == 3)
{
double Q_N_ex = receive_floodwater(currRegion, i);
// element 1
Qx_in = currRegion->Qx[el1][lv1];
Qy_in = currRegion->Qy[el1][lv1];
zeta_in = currRegion->zeta[el1][lv1];
z_in = currRegion->NodalZ[el1][lv1];
zeta_ex = zeta_in;
Q_T_in = Qx_in*tx + Qy_in*ty;
double Q_T_ex = Q_T_in;
double denom = 1./(nx*ty-ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
double localG = g;
#ifdef WDON
if (currRegion->WD[el1] == 0)
localG = 0;
else
localG = g;
#endif
double current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, localG,Fn_in);
//if (el1 == 170 && fabs(Q_N_ex) > 0)
//{
// printf("***************\n");
// printf("time = %lf\n", time);
// printf("j = %d el1 = %d, el2 = %d\n", j, el1, el2);
// printf("WD1 = %d, WD2 = %d\n", currRegion->WD[el1], currRegion->WD[el2]);
// printf("Q_N_ex = %lf, Qx_in = %lf, Qy_in = %lf, \n", Q_N_ex, Qx_in, Qy_in);
// printf("Fn_in = %lf, %lf, %lf\n", Fn_in[0], Fn_in[1], Fn_in[2]);
//}
// element 2
nx = -nx;
ny = -ny;
tx = -ny;
ty = nx;
denom = 1./(nx*ty-ny*tx);
zeta_in = currRegion->zeta[el2][lv2];
z_in = currRegion->NodalZ[el2][lv2];
zeta_ex = zeta_in;
Qx_in = currRegion->Qx[el2][lv2];
Qy_in = currRegion->Qy[el2][lv2];
Q_T_in = Qx_in*tx + Qy_in*ty;
Q_T_ex = Q_T_in;
denom = 1./(nx*ty-ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
z_ex = z_in;
#ifdef WDON
if (currRegion->WD[el2] == 0)
localG = 0;
else
localG = g;
#endif
current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, localG, Fn_ex);
if (el2 == 170 && fabs(Q_N_ex)>0)
{
printf("***************\n");
printf("el1 = %d, el2 = %d\n", el1, el2);
printf("Q_N_ex = %lf\n", Q_N_ex);
printf("Fn_in = %lf, %lf, %lf\n", Fn_in[0], Fn_in[1], Fn_ex[2]);
}
}
// if edge i is a boundary edge but not connected to a channel, implement no flux boundary condition
else if (el1 == el2)
{
zeta_ex = currRegion->zeta[el2][lv2];
// Compute the velocity in the normal direction
double Q_N_in = Qx_in*nx + Qy_in*ny;
double Q_T_in = Qx_in*tx + Qy_in*ty;
// Reflect the velocity in the normal direction
double Q_N_ex = -Q_N_in;
double Q_T_ex = Q_T_in;
// Compute the x and y components of the external state flow
double denom = 1./(nx*ty - ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
z_ex = z_in;
}
// if the edge is not a boundary edge
else
{
zeta_ex = currRegion->zeta[el2][lv2];
Qx_ex = currRegion->Qx[el2][lv2];
Qy_ex = currRegion->Qy[el2][lv2];
z_ex = currRegion->NodalZ[el2][lv2];
}
#ifdef WDON
// Check to see if both of the elements separated by this edge are dry
if (currRegion->WD[el1] == 0 && currRegion->WD[el2] == 0 && (bdrypres != 3) && (bdrypres != 222) && (bdrypres != 2) && (bdrypres !=1))
{
Fn_in[0] = 0.0;
Fn_in[1] = 0.0;
Fn_in[2] = 0.0;
Fn_ex[0] = 0.0;
Fn_ex[1] = 0.0;
Fn_ex[2] = 0.0;
//// Reflection flux for the interior element
//double zeta_ex_ref = zeta_in;
//double Q_N_in = Qx_in*nx + Qy_in*ny;
//double Q_T_in = Qx_in*tx + Qy_in*ty;
//double Q_N_ex = -Q_N_in;
//double Q_T_ex = Q_T_in;
//
//double denom = 1./(nx*ty - ny*tx);
//double Qx_ex_ref = (ty*Q_N_ex - ny*Q_T_ex)*denom;
//double Qy_ex_ref = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
//double max_lam_in = RoeFluxJunc(zeta_in, zeta_ex_ref, Qx_in,Qx_ex_ref,
// Qy_in, Qy_ex_ref, z_in, nx, ny, 0, Fn_in);
//// Reflection flux for the exterior element
//double zeta_in_ref = zeta_ex;
//Q_N_ex = Qx_ex*nx + Qy_ex*ny;
//Q_T_ex = Qx_ex*tx + Qy_ex*ty;
//Q_N_in = -Q_N_ex;
//Q_T_in = Q_T_ex;
//
//double Qx_in_ref = (ty*Q_N_in - ny*Q_T_in)*denom;
//double Qy_in_ref = (-tx*Q_N_in + nx*Q_T_ex)*denom;
//double max_lam_ex = RoeFluxJunc(zeta_in_ref, zeta_ex, Qx_in_ref, Qx_ex, Qy_in_ref, Qy_ex, z_in, nx, ny, 0, Fn_ex);
//if (i ==0)
// currRegion->max_lambda = max(max_lam_in, max_lam_ex);
//else
//{
// currRegion->max_lambda = fmax(currRegion->max_lambda, max_lam_in);
// currRegion->max_lambda = fmax(currRegion->max_lambda, max_lam_ex);
//}
}
else if (bdrypres != 3 && bdrypres != 222)// if the elements aren't both dry
{
double Fhatdotn[3];
double current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, g,Fhatdotn);
if (isnan(Fhatdotn[0]) || isnan(Fhatdotn[1]) || isnan(Fhatdotn[2]))
{
printf("2D both elements wet flux not a number, edge %d, time %e, for domain type %d \n",i,time, currRegion->type);
printf("ze_ex = %lf, ze_in = %lf, z_in = %lf, Qx_ex = %lf, Qx_in = %lf, Qy_ex = %lf, Qy_in = %lf, el_ex = %d, el_in = %d, bdrypres = %d\n", zeta_ex, zeta_in, z_in, Qx_ex, Qx_in, Qy_ex, Qy_in, el2, el1, bdrypres);
printf("wdfalg1 = %d , wdflag2 = %d\n", currRegion->WD[el1], currRegion->WD[el2]);
exit(EXIT_FAILURE);
}
// Check to see if the flux is large enough to dry up the elements
// Calculate the sum of the length of the three edges of the interior and exterior element
double edg_len_el1 = 0;
for (int v = 0; v < 3; v++)
{
int v1 = currRegion->EltoVert[el1*3 + v];
int v2 = currRegion->EltoVert[el1*3 + (v+1)%3];
edg_len_el1 += sqrt(pow(currRegion->Vx[v1] - currRegion->Vx[v2], 2) + pow(currRegion->Vy[v1] - currRegion->Vy[v2],2));
}
double edg_len_el2 = 0;
for (int v = 0; v < 3; v++)
{
int v1 = currRegion->EltoVert[el2*3 + v];
int v2 = currRegion->EltoVert[el2*3 + (v+1)%3];
edg_len_el2 += sqrt(pow(currRegion->Vx[v1] - currRegion->Vx[v2], 2) + pow(currRegion->Vy[v1] - currRegion->Vy[v2],2));
}
double maxBetaOverAlpha = 2;
if ((1.01*Fhatdotn[0]*edg_len_el1*maxBetaOverAlpha*dt >= mass[el1]) || (-1.01*Fhatdotn[0]*edg_len_el2*maxBetaOverAlpha*dt >= mass[el2]))
{
//printf("either el %d or el %d will be dry \n", el1, el2);
Fn_in[0] = 0.0;
Fn_in[1] = 0.0;
Fn_in[2] = 0.0;
Fn_ex[0] = 0.0;
Fn_ex[1] = 0.0;
Fn_ex[2] = 0.0;
}
else // check to make sure the flux is not coming from a dry element
{
if (currRegion->WD[el1] == 1 || (el1 == el2))
{
for (int j =0; j < 3; ++j)
{
Fn_in[j] = Fhatdotn[j];
}
}
else if (Fhatdotn[0] > 0)
{
//printf("initially, el1 = %d, j = %d, Fn_ex = %lf\n", el1, j, Fhatdotn[0]);
zeta_ex = currRegion->zeta[el2][lv2];
zeta_in = zeta_ex;
Qx_ex = currRegion->Qx[el2][lv2];
Qy_ex = currRegion->Qy[el2][lv2];
double Q_N_ex = Qx_ex*nx + Qy_ex*ny;
double Q_N_in = -Q_N_ex;
double Q_T_ex = Qx_ex*tx + Qy_ex*ty;
Q_T_in = Q_T_ex;
double denom = 1./(nx*ty-ny*tx);
Qx_in = (ty*Q_N_in - ny*Q_T_in)*denom;
Qy_in = (-tx*Q_N_in + nx*Q_T_in)*denom;
double max_lam_in = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex,
z_ex, nx, ny, g, Fn_in);
if (isnan(Fn_in[0]) || isnan(Fn_in[1]) || isnan(Fn_in[2]))
{
printf("2D interior element dry flux not a number, edge %d, el_in = %d, el_ex = %d, domain type = %d\n",i, el1, el2, currRegion->type);
printf("ze_ex = %lf, ze_in = %lf, z_in = %lf, z_ex = %lf, Qx_ex = %lf, Qx_in = %lf, Qy_ex = %lf, Qy_in = %lf, el_ex = %d, el_in = %d, bdrypres = %d\n", zeta_ex, zeta_in, z_in, z_ex, Qx_ex, Qx_in, Qy_ex, Qy_in, el2, el1, bdrypres);
printf("wdfalg1 = %d , wdflag2 = %d\n", currRegion->WD[el1], currRegion->WD[el2]);
exit(EXIT_FAILURE);
}
//printf("after reflection, el1 = %d, Fn_ex = %lf\n", el1, Fn_in[0]);
current_max_lam = max(current_max_lam, max_lam_in);
}
else
{
double max_lam_in = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex,
z_in, nx, ny, 0, Fn_in);
}
if (currRegion->WD[el2] == 1 && (el1 != el2))
{
for (int j = 0; j < 3; ++j)
{
Fn_ex[j] = Fhatdotn[j];
}
}
else if ((el1 != el2) && (Fhatdotn[0] < 0))
{
// printf("initially, el2 = %d, Fn_ex = %lf\n", el2, -Fhatdotn[0]);
Qx_in = currRegion->Qx[el1][lv1];
Qy_in = currRegion->Qy[el1][lv1];
zeta_in = currRegion->zeta[el1][lv1];
double Q_N_in = Qx_in*nx + Qy_in*ny;
double Q_T_in = Qx_in*tx + Qy_in*ty;
double Q_N_ex = -Q_N_in;
double Q_T_ex = Q_T_in;
double denom = 1.0/(nx*ty - ny*tx);
Qx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;
Qy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;
zeta_ex = zeta_in;
double max_lam_ex = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex,
Qy_in, Qy_ex, z_in, nx, ny, g, Fn_ex);
current_max_lam = max(current_max_lam, max_lam_ex);
if (isnan(Fn_ex[0]) || isnan(Fn_ex[1]) || isnan(Fn_ex[2]))
{
printf("2D exterior element dry flux not a number, edge %d \n",i);
exit(EXIT_FAILURE);
}
//printf("el2 = %d, Fn_ex = %lf\n", el2, -Fn_ex[0]);
// printf("after reflection, el2 = %d, Fn_ex = %lf\n", el2, -Fn_ex[0]);
}
else if (el1 != el2 )
{
double max_lam_ex = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex,
Qy_in, Qy_ex, z_in, nx, ny, 0, Fn_ex);
current_max_lam = max(current_max_lam, max_lam_ex);
}
if (i == 0)
currRegion->max_lambda = current_max_lam;
else
currRegion->max_lambda = fmax(currRegion->max_lambda, current_max_lam);
}
}
#else
double Fhatdotn[3];
double current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, g, Fhatdotn);
if (isnan(Fhatdotn[0]) || isnan(Fhatdotn[1]) || isnan(Fhatdotn[2]))
{
printf("2D numerical flux not a number, edge %d \n",i);
printf("zeta_in = %e, zeta_ex = %e, z_edge = %e, BdryPrescribed = %d \n", zeta_in, zeta_ex, z_in, bdrypres);
exit(EXIT_FAILURE);
}
for (int j = 0; j < 3; ++j)
{
Fn_in[j] = Fhatdotn[j];
Fn_ex[j] = Fhatdotn[j];
}
if (i == 0)
currRegion->max_lambda = current_max_lam;
else
currRegion->max_lambda = max(currRegion->max_lambda, current_max_lam);
#endif
// store Fhatdotn for the two elements connected by this edge
Fhat1dotn[el1][pos1] = Fn_in[0];
Fhat2dotn[el1][pos1] = Fn_in[1];
Fhat3dotn[el1][pos1] = Fn_in[2];
// store the value for the exterior element, only if the edge is not a boundary edge
if (el2 != el1 && (bdrypres != 3))
{
Fhat1dotn[el2][pos2] = -Fn_ex[0];
Fhat2dotn[el2][pos2] = -Fn_ex[1];
Fhat3dotn[el2][pos2] = -Fn_ex[2];
}
else if (el2 != el1) // for bdyrpes = 3, we have already taken sign of normals into account during flux calculation
{
Fhat1dotn[el2][pos2] = Fn_ex[0];
Fhat2dotn[el2][pos2] = Fn_ex[1];
Fhat3dotn[el2][pos2] = Fn_ex[2];
}
} // end node loop
} // end edge loop
for (int k=0; k<NumEl; ++k)
{
gsl_vector *F1x = gsl_vector_alloc(Np);
gsl_vector *F2x = gsl_vector_alloc(Np);
gsl_vector *F3x = gsl_vector_alloc(Np);
gsl_vector *F1y = gsl_vector_alloc(Np);
gsl_vector *F2y = gsl_vector_alloc(Np);
gsl_vector *F3y = gsl_vector_alloc(Np);
gsl_vector *ST21 = gsl_vector_calloc(Np);
gsl_vector *ST22 = gsl_vector_calloc(Np);
gsl_vector *ST31 = gsl_vector_calloc(Np);
gsl_vector *ST32 = gsl_vector_calloc(Np);
//gsl_vector *ST11 = gsl_vector_calloc(Np);
double localG = g;
#ifdef WDON
if(currRegion->WD[k] == 0)
localG = 0;
#endif
for (int i = 0; i < Np; i++)
{
double zeta = currRegion->zeta[k][i];
double Qx = currRegion->Qx[k][i];
double Qy = currRegion->Qy[k][i];
double z = currRegion->NodalZ[k][i];
double H = zeta + z;
double f2x = Qx*Qx/H + 0.5*localG*(H*H - z*z);
double f2y = Qx*Qy/H;
double f3x = f2y;
double f3y = Qy*Qy/H + 0.5*localG*(H*H - z*z);
gsl_vector_set(F1x, i, Qx);
gsl_vector_set(F1y, i, Qy);
gsl_vector_set(F2x, i, f2x);
gsl_vector_set(F2y, i, f2y);
gsl_vector_set(F3x, i, f3x);
gsl_vector_set(F3y, i, f3y);
double u = Qx/H;
double v = Qy/H;
double nfric = currRegion->NodalnFriction[k][i];
double tau = localG*nfric*nfric*sqrt(u*u + v*v)/pow(H,4.0/3);
double dzx = currRegion->Nodaldzx[k][i];
double dzy = currRegion->Nodaldzy[k][i];
gsl_vector_set(ST21, i, localG*zeta*dzx);
gsl_vector_set(ST22, i, -tau*Qx);
gsl_vector_set(ST31, i, localG*zeta*dzy);
gsl_vector_set(ST32, i, -tau*Qy);
// Source terms for manufactured solution
//double xval = currRegion->NodalX[k][i];
//double yval = currRegion->NodalY[k][i];
//double st2 = getS2(xval, yval, time);
//double st3 = getS3(xval, yval, time);
//gsl_vector_set(ST21, i, st2);
//gsl_vector_set(ST31, i, st3);
#ifdef WDON
if (currRegion->WD[k] == 0)
{
gsl_vector_set(F1x, i, 0);
gsl_vector_set(F1y, i, 0);
gsl_vector_set(F2x, i, 0);
gsl_vector_set(F2y, i, 0);
gsl_vector_set(F3x, i, 0);
gsl_vector_set(F3y, i, 0);
gsl_vector_set(ST21, i, 0);
gsl_vector_set(ST22, i, 0);
gsl_vector_set(ST31, i, 0);
gsl_vector_set(ST32, i, 0);
}
#endif
// rainfall
//if (currRegion->type == 2)
// gsl_vector_set(ST11, i, 0.5*12/3600);
}
// Calculate the volume integral of the flux
double rx = currRegion->rx[k];
double ry = currRegion->ry[k];
double sx = currRegion->sx[k];
double sy = currRegion->sy[k];
gsl_vector *localRHS1 = gsl_vector_calloc(Np);
gsl_vector *localRHS2 = gsl_vector_calloc(Np);
gsl_vector *localRHS3 = gsl_vector_calloc(Np);
gsl_vector *lR12 = gsl_vector_calloc(Np);
gsl_vector *lR13 = gsl_vector_calloc(Np);
gsl_vector *lR14 = gsl_vector_calloc(Np);
gsl_vector *lR22 = gsl_vector_calloc(Np);
gsl_vector *lR23 = gsl_vector_calloc(Np);
gsl_vector *lR24 = gsl_vector_calloc(Np);
gsl_vector *lR32 = gsl_vector_calloc(Np);
gsl_vector *lR33 = gsl_vector_calloc(Np);
gsl_vector *lR34 = gsl_vector_calloc(Np);
gsl_blas_dgemv(CblasNoTrans, rx, Drw, F1x, 0.0, localRHS1);
gsl_blas_dgemv(CblasNoTrans, sx, Dsw, F1x, 0.0, lR12);
gsl_blas_dgemv(CblasNoTrans, ry, Drw, F1y, 0.0, lR13);
gsl_blas_dgemv(CblasNoTrans, sy, Dsw, F1y, 0.0, lR14);
gsl_vector_add(localRHS1, lR12);
gsl_vector_add(localRHS1, lR13);
gsl_vector_add(localRHS1, lR14);
gsl_blas_dgemv(CblasNoTrans, rx, Drw, F2x, 0.0, localRHS2);
gsl_blas_dgemv(CblasNoTrans, sx, Dsw, F2x, 0.0, lR22);
gsl_blas_dgemv(CblasNoTrans, ry, Drw, F2y, 0.0, lR23);
gsl_blas_dgemv(CblasNoTrans, sy, Dsw, F2y, 0.0, lR24);
gsl_vector_add(localRHS2, lR22);
gsl_vector_add(localRHS2, lR23);
gsl_vector_add(localRHS2, lR24);
gsl_blas_dgemv(CblasNoTrans, rx, Drw, F3x, 0.0, localRHS3);
gsl_blas_dgemv(CblasNoTrans, sx, Dsw, F3x, 0.0, lR32);
gsl_blas_dgemv(CblasNoTrans, ry, Drw, F3y, 0.0, lR33);
gsl_blas_dgemv(CblasNoTrans, sy, Dsw, F3y, 0.0, lR34);
gsl_vector_add(localRHS3, lR32);
gsl_vector_add(localRHS3, lR33);
gsl_vector_add(localRHS3, lR34);
// calculate the surface integral of the flux
gsl_vector *localFhat1dotn = gsl_vector_alloc(3*Nfp);
gsl_vector *localFhat2dotn = gsl_vector_alloc(3*Nfp);
gsl_vector *localFhat3dotn = gsl_vector_alloc(3*Nfp);
for (int i = 0; i < 3; i++)
{
double edgJac = currRegion->edgJac[k*3+i];
for (int j = 0; j < Nfp; j++)
{
int index = i*Nfp+j;
gsl_vector_set(localFhat1dotn, index, edgJac*Fhat1dotn[k][index]);
gsl_vector_set(localFhat2dotn, index, edgJac*Fhat2dotn[k][index]);
//printf("edgJac = %lf Fhat = %lf\n", edgJac, Fhat2dotn[k][index]);
gsl_vector_set(localFhat3dotn, index, edgJac*Fhat3dotn[k][index]);
}
}
double jac = currRegion->jac[k];
gsl_vector *SurfPart1 = gsl_vector_calloc(Np);
gsl_vector *SurfPart2 = gsl_vector_calloc(Np);
gsl_vector *SurfPart3 = gsl_vector_calloc(Np);
double fac = 1.0/jac;
gsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat1dotn, 0.0, SurfPart1);
gsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat2dotn, 0.0, SurfPart2);
gsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat3dotn, 0.0, SurfPart3);
// subtract this from the RHS
gsl_vector_sub(localRHS1, SurfPart1);
gsl_vector_sub(localRHS2, SurfPart2);
gsl_vector_sub(localRHS3, SurfPart3);
// add source and sink terms
//gsl_vector_add(localRHS1, ST11);
//
//gsl_vector_add(localRHS1, ST11);
gsl_vector_add(localRHS2, ST21);
gsl_vector_add(localRHS2, ST22);
gsl_vector_add(localRHS3, ST31);
gsl_vector_add(localRHS3, ST32);
int begNode = k*Np;
for(int i = 0; i < Np; i++)
{
RHSZeta[begNode+i] = gsl_vector_get(localRHS1,i);
RHSQx[begNode+i] = gsl_vector_get(localRHS2,i);
RHSQy[begNode+i] = gsl_vector_get(localRHS3, i);
}
// free all gsl vectors
gsl_vector_free(localRHS1);
gsl_vector_free(localRHS2);
gsl_vector_free(localRHS3);
gsl_vector_free(localFhat1dotn);
gsl_vector_free(localFhat2dotn);
gsl_vector_free(localFhat3dotn);
gsl_vector_free(SurfPart1);
gsl_vector_free(SurfPart2);
gsl_vector_free(SurfPart3);
gsl_vector_free(lR12);
gsl_vector_free(lR13);
gsl_vector_free(lR14);
gsl_vector_free(lR22);
gsl_vector_free(lR23);
gsl_vector_free(lR24);
gsl_vector_free(lR32);
gsl_vector_free(lR33);
gsl_vector_free(lR34);
gsl_vector_free(F1x);
gsl_vector_free(F2x);
gsl_vector_free(F3x);
gsl_vector_free(F1y);
gsl_vector_free(F2y);
gsl_vector_free(F3y);
//gsl_vector_free(ST11);
gsl_vector_free(ST21);
gsl_vector_free(ST22);
gsl_vector_free(ST31);
gsl_vector_free(ST32);
}
// free allocated space
for (int i = 0; i < NumEl; i++)
{
free(Fhat1dotn[i]);
free(Fhat2dotn[i]);
free(Fhat3dotn[i]);
}
free(Fhat1dotn);
free(Fhat2dotn);
free(Fhat3dotn);
#ifdef WDON
free(mass);
#endif
}
| {
"alphanum_fraction": 0.6081878658,
"avg_line_length": 29.2723279649,
"ext": "c",
"hexsha": "4787760dbfb621d15b3385f08b7bc4b30ad9716e",
"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": "DGSHED/computeL.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": "DGSHED/computeL.c",
"max_line_length": 238,
"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": "DGSHED/computeL.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": 15278,
"size": 39986
} |
/**
* author: Jochen K"upper
* created: Jan 2002
* file: pygsl/src/statistics/longmodule.c
* $Id: ucharmodule.c,v 1.5 2004/03/24 08:40:45 schnizer Exp $
*
*"
*/
#include <Python.h>
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
#include <gsl/gsl_statistics.h>
/* include real functions for different data-types */
#define STATMOD_APPEND_PY_TYPE(X) X ## Int
#define STATMOD_APPEND_PYC_TYPE(X) X ## UBYTE
#define STATMOD_FUNC_EXT(X, Y) X ## _uchar ## Y
#define STATMOD_PY_AS_C PyInt_AsLong
#define STATMOD_C_TYPE unsigned char
#include "functions.c"
PyGSL_STATISTICS_INIT(uchar, "uchar")
/*
* Local Variables:
* mode: c
* c-file-style: "Stroustrup"
* End:
*/
| {
"alphanum_fraction": 0.7061340942,
"avg_line_length": 17.525,
"ext": "c",
"hexsha": "4cd6b7d0901dc5e46270ccb57402d67d63613adc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c",
"max_line_length": 62,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/ucharmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 209,
"size": 701
} |
/*
* Copyright (c) 2014, Newcastle University, UK.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Linear Regression
// Dan Jackson, 2014 (but see below)
#include <stdlib.h>
//#include <math.h>
#include "linearregression.h"
// Linear regression with one independent variable
double *LinearModelFitOneIndependent(int n, double *y, double *x)
{
static double coef[3]; // offset(intersect), scale(gradient), spare(to be compatible with two-variable version)
int i;
// sum(Xi * Yi)
// sum(Xi^2)
double sumx = 0, sumy = 0;
double sumxy = 0, sumxsq = 0;
for (i = 0; i < n; i++)
{
sumx += x[i];
sumy += y[i];
sumxy += x[i] * y[i];
sumxsq += x[i] * x[i];
}
// Calculate mean of x and y
double xmean = n > 0 ? sumx / n : 0;
double ymean = n > 0 ? sumy / n : 0;
// sum(x*y) - (n * xm * ym)
// Slope (b): b = ------------------------
// sum(x^2) - (n * xm^2)
double bNumerator = sumxy - (n * xmean * ymean);
double bDenominator = sumxsq - (n * xmean * xmean);
double b = bDenominator != 0.0 ? bNumerator / bDenominator : 0.0;
// Intercept (a): a = ym - b * xm
double a = ymean - (b * xmean);
// Line of best fit: y = a + b * X
coef[0] = a;
coef[1] = b;
coef[2] = 0.0; // just to be compatible with two-variable version
return &coef[0];
}
// Linear regression with two independent variables
double *LinearModelFitTwoIndependent(int n, double *y, double *x1, double *x2)
{
// Implemented from information from: http://faculty.cas.usf.edu/mbrannick/regression/Reg2IV.html
static double coef[3]; // offset (intersect), scale 1 (gradient 1), scale 2 (gradient 2)
int i;
double sumx1 = 0, sumx2 = 0, sumy = 0;
double sumx1y = 0, sumx2y = 0;
double sumx1x2 = 0;
double sumx1sq = 0, sumx2sq = 0;
for (i = 0; i < n; i++)
{
sumx1 += x1[i];
sumx2 += x2[i];
sumy += y[i];
sumx1y += x1[i] * y[i];
sumx2y += x2[i] * y[i];
sumx1x2 += x1[i] * x2[i];
sumx1sq += x1[i] * x1[i];
sumx2sq += x2[i] * x2[i];
}
// Calculate mean of x1, x2, and y
double x1mean = n > 0 ? sumx1 / n : 0;
double x2mean = n > 0 ? sumx2 / n : 0;
double ymean = n > 0 ? sumy / n : 0;
// sum(x2^2).sum(x1*y) - sum(x1*x2).sum(x2*y)
// Slope (b1): b1 = ------------------------------------------
// sum(x1^2).sum(x2^2) - sum(x1*x2)^2
double b1Numerator = (sumx2sq * sumx1y) - (sumx1x2 * sumx2y);
double b1Denominator = (sumx1sq * sumx2sq) - (sumx1x2 * sumx1x2);
double b1 = b1Numerator != 0.0 ? b1Numerator / b1Denominator : 0.0;
// sum(x1^2).sum(x2*y) - sum(x1*x2).sum(x1*y)
// Slope (b2): b2 = ------------------------------------------
// sum(x1^2).sum(x2^2) - sum(x1*x2)^2
double b2Numerator = (sumx1sq * sumx2y) - (sumx1x2 * sumx1y);
double b2Denominator = b1Denominator; // Same as denominator of b1
double b2 = b2Denominator != 0.0 ? b2Numerator / b2Denominator : 0.0;
// Intercept (a): a = ym - b1 * x1m - b2 * x2m
double a = ymean - (b1 * x1mean) - (b2 * x2mean);
// Line of best fit: y = a + b1 * x1 + b2 * x2
coef[0] = a;
coef[1] = b1;
coef[2] = b2;
return &coef[0];
}
#ifdef ENABLE_APPROXIMATE
// Linear regression with two independent variables, weighted
// NOTE: This is not really correct...
double *LinearModelFitTwoIndependentWeightedApproximately(int n, double *y, double *x1, double *x2, double *weights)
{
double *weightedY = (double *)malloc(sizeof(double) * n);
double *weightedX1 = (double *)malloc(sizeof(double) * n);
double *weightedX2 = (double *)malloc(sizeof(double) * n);
int i;
// HACK: To reduce influence on intercept
double influenceSum = 0;
for (i = 0; i < n; i++)
{
double sw = sqrt(weights[i]);
weightedY[i] = y[i] * sw;
weightedX1[i] = x1[i] * sw;
weightedX2[i] = x2[i] * sw;
influenceSum += sw;
}
double *coef = LinearModelFitTwoIndependent(n, weightedY, weightedX1, weightedX2);
double influence = n != 0 ? influenceSum / n : 0;
if (influence != 0.0) { coef[0] /= influence; }
free(weightedY);
free(weightedX1);
free(weightedX2);
return coef;
}
#endif
#ifdef ENABLE_GSL
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multifit.h>
//#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
/* General weighted case in gsl/multifit/multilinear.c */
double *LinearModelFitTwoIndependentWeighted(int n, double *y, double *x1, double *x2, double *weights)
{
#define NPARAMS 2
// Allocate
gsl_matrix *matrixX = gsl_matrix_alloc(n, NPARAMS);
gsl_vector *vectorW = gsl_vector_alloc(n);
gsl_vector *vectorY = gsl_vector_alloc(n);
gsl_vector *vectorC = gsl_vector_alloc(1 + NPARAMS);
// Copy data
int i;
for (i = 0; i < n; i++)
{
// NPARAMS
gsl_matrix_set(matrixX, i, 0, x1[i]);
gsl_matrix_set(matrixX, i, 1, x2[i]);
gsl_vector_set(vectorW, i, weights[i]);
gsl_vector_set(vectorY, i, y[i]);
}
// Compute
gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(n, NPARAMS);
int ret = gsl_multifit_wlinear(matrixX, vectorW, vectorY, vectorC, /*gsl_matrix * cov*/ NULL, /*double * chisq*/ NULL, work);
gsl_multifit_linear_free(work);
static double coef[NPARAMS + 1];
// NPARAMS+1
coef[0] = gsl_vector_get(vectorC, 0);
coef[1] = gsl_vector_get(vectorC, 1);
coef[2] = gsl_vector_get(vectorC, 2);
// Free
gsl_matrix_free(matrixX);
gsl_vector_free(vectorW);
gsl_vector_free(vectorY);
gsl_vector_free(vectorC);
return coef;
}
#endif
| {
"alphanum_fraction": 0.6488776572,
"avg_line_length": 30.1659192825,
"ext": "c",
"hexsha": "b0e232c2fbce9e644d0739615a5850a04fdc63b0",
"lang": "C",
"max_forks_count": 80,
"max_forks_repo_forks_event_max_datetime": "2021-11-21T06:53:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-17T23:01:13.000Z",
"max_forks_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500",
"max_forks_repo_licenses": [
"CC-BY-3.0"
],
"max_forks_repo_name": "digitalinteraction/openmovement",
"max_forks_repo_path": "Software/AX3/omconvert/linearregression.c",
"max_issues_count": 46,
"max_issues_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500",
"max_issues_repo_issues_event_max_datetime": "2022-01-19T11:52:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-06T16:26:25.000Z",
"max_issues_repo_licenses": [
"CC-BY-3.0"
],
"max_issues_repo_name": "digitalinteraction/openmovement",
"max_issues_repo_path": "Software/AX3/omconvert/linearregression.c",
"max_line_length": 126,
"max_stars_count": 113,
"max_stars_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500",
"max_stars_repo_licenses": [
"CC-BY-3.0"
],
"max_stars_repo_name": "digitalinteraction/openmovement",
"max_stars_repo_path": "Software/AX3/omconvert/linearregression.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-08T14:51:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-28T16:27:41.000Z",
"num_tokens": 2174,
"size": 6727
} |
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "nrsrc/nrutil.h"
#include "prototypes.h"
#include "globvars.h"
double comp_DF_halo_exact(double E, double L);
double comp_DF_bulge_exact(double E, double L);
double comp_DF_H_iso(double E);
double comp_DF_H_ani(double Q);
double comp_DF_halo_Eddington(double Q);
double comp_DF_bulge_Eddington(double Q);
void comp_DF_init(void);
void compute_d2rhodpsi2_halo(void);
void compute_d2rhodpsi2_bulge(void);
double eddington_integrand(double t, void *params);
#define WORKSIZE 100000
gsl_integration_workspace *Workspace;
double *xi, *yi, *eddint;
double *list_radius;
double *list_E; /* tabulated energies */
double *DistFunc_halo, *DistFunc_bulge; /* distribution function(s) */
double *psi_R;
double *rho_R_halo,*rho_R_bulge;
double *drhodpsi_halo,*d2rhodpsi2_halo;
double *drhodpsi_bulge,*d2rhodpsi2_bulge;
/* size of DF look-up table */
int DFSIZE= RSIZE * 2;
void compute_DF_lookuptable(void)
{
FILE *fd;
char dffile[100]="";
int i;
printf("Start computing distribution function.\n"); fflush(stdout);
#ifdef MAXWELLIAN
AnisotropyRadius= -1;
printf("MAXWELLIAN is turned on\n");
#else
printf("MAXWELLIAN is turned off\n");
#endif
#ifdef DF_H_MODEL
printf("DF_H_MODEL is turned on\n");
#else
printf("DF_H_MODEL is turned off\n");
#endif
#ifdef DF_EDDINGTON
printf("DF_EDDINGTON is turned on\n");
#else
printf("DF_EDDINGTON is turned off\n");
#endif
printf("AnisotropyRadius= %g\n", AnisotropyRadius);
printf("ra= %g\n", AnisotropyRadius * RH);
comp_DF_init();
for(i = 0; i <= DFSIZE; i++)
{
printf("Computing DF table bin %d/%d (e= %g)\n", i, DFSIZE, -1.0*psi_R[i]); fflush(stdout);
list_E[i]= -1.0 * psi_R[i];
DistFunc_halo[i] = comp_DF_halo_exact(list_E[i], 0.0);
DistFunc_bulge[i] = comp_DF_bulge_exact(list_E[i], 0.0);
}
printf("\n");
/* write this to a file so we have a record of it */
if(strstr(OutputFile,".hdf5"))
strncpy(dffile, OutputFile, strlen(OutputFile)-5);
if(strstr(OutputFile,".dat"))
strncpy(dffile, OutputFile, strlen(OutputFile)-4);
strcat(dffile, ".df");
printf("DF look-up table saved in file: %s\n",dffile);
if((fd = fopen(dffile,"w")))
{
fprintf(fd," Energy f_halo(E) f_bulge(E)\n");
for(i= 0; i<= DFSIZE; i++)
fprintf(fd," %10.5e %10.5e %10.5e\n",list_E[i],DistFunc_halo[i],DistFunc_bulge[i]);
fclose(fd);
}
}
double comp_DF_halo_exact(double E, double L)
{
double Q, f_e= 0.0;
if((N_HALO == 0) || (M_HALO == 0))
return 0;
if (AnisotropyRadius > 0.0)
Q= - E - (L*L/2./(AnisotropyRadius * RH)/(AnisotropyRadius * RH));
else
Q= - E;
#ifdef DF_H_MODEL
/* calculate f_e exactly from the H90 analytic formula */
if (AnisotropyRadius > 0.0)
f_e= comp_DF_H_ani(Q);
else
f_e= comp_DF_H_iso(E);
#endif
#ifdef DF_EDDINGTON
/* calculate f_e using Eddington's formula */
f_e= comp_DF_halo_Eddington(Q);
printf("f_e_edd(Q)/f_H_iso(E)= %g\n",f_e/comp_DF_H_iso(E));
printf("f_e_edd(Q)/f_H_ani(Q)= %g\n",f_e/comp_DF_H_ani(Q)); fflush(stdout);
printf("------\n");
#endif
return f_e;
}
double comp_DF_bulge_exact(double E, double L)
{
double Q, f_e= 0.0;
if((N_BULGE == 0) || (M_BULGE == 0))
return 0;
/* for the moment, we only assume isotropic DF and use Eddington's formula */
/*
if (AnisotropyRadius > 0.0)
Q= - E - (L*L/2./(AnisotropyRadius * RH)/(AnisotropyRadius * RH));
else
*/
Q= - E;
f_e= comp_DF_bulge_Eddington(Q);
return f_e;
}
/*
interpolate the halo f_e from the pre-computed table
*/
double comp_DF_halo(double E, double L)
{
double f_e= 0.0, Q, ee, ue;
int ie;
ee= E;
if(AnisotropyRadius > 0.0)
{
Q= - E - (L*L/2./(AnisotropyRadius * RH)/(AnisotropyRadius * RH));
/* in this case, table is stored in terms of -Q */
ee= -1.0 * Q;
}
/* if e>0 or q<0 then dist. func. is zero */
if(ee>0.0)
return 0.0;
ie= find_idx(ee, list_E, DFSIZE);
/*
printf("\nE= %g Q= %g ee= %g\n",E, Q, ee);
printf("ie= %d list_E[0]= %g list_E[DFSIZE]= %g \n",ie, list_E[0], list_E[DFSIZE]);
printf("list_E[%d]= %g\n", ie-1, list_E[ie-1]);
printf("list_E[%d]= %g\n", ie, list_E[ie]);
printf("list_E[%d]= %g\n", ie+1, list_E[ie+1]);
fflush(stdout);
*/
if(ie < 0 || ie > DFSIZE)
ie= 0;
ue = (ee - list_E[ie]) / (list_E[ie + 1] - list_E[ie]);
if(ee>list_E[0])
{
/*
printf("\nparticle has energy very close to zero\n");
printf("ee= %g, table min list_E[0]= %g\n",ee,list_E[0]);
printf("return 0.\n");
*/
ue= 0.0;
}
if(ie < 0 || ie >= DFSIZE || ue < 0 || ue > 1)
{
printf("\nee= %g (in bounds? list_E[0]= %g list_E[DFSIZE]= %g\n",ee, list_E[0], list_E[DFSIZE]);
printf("in: comp_DF_fromtable\nerror: ie=%d out of range ue=%g\nstopping\n", ie, ue);
exit(0);
}
f_e= DistFunc_halo[ie] * (1-ue) + DistFunc_halo[ie+1] * ue;
return f_e;
}
/*
interpolate the bulge f_e from the pre-computed table
*/
double comp_DF_bulge(double E, double L)
{
double f_e= 0.0, Q, ee, ue;
int ie;
ee= E;
/* for the moment, we'll assume the bulge is isotropic */
/*
if(AnisotropyRadius > 0.0)
{
Q= - E - (L*L/2./(AnisotropyRadius * RH)/(AnisotropyRadius * RH));
ee= -1.0 * Q;
}
*/
/* if e>0 or q<0 then dist. func. is zero */
if(ee>0.0)
return 0.0;
ie= find_idx(ee, list_E, DFSIZE);
if(ie < 0 || ie > DFSIZE)
ie= 0;
ue = (ee - list_E[ie]) / (list_E[ie + 1] - list_E[ie]);
if(ee>list_E[0])
{
/*
printf("\nparticle has energy very close to zero\n");
printf("ee= %g, table min list_E[0]= %g\n",ee,list_E[0]);
printf("return 0.\n");
*/
ue= 0.0;
}
if(ie < 0 || ie >= DFSIZE || ue < 0 || ue > 1)
{
printf("\nee= %g (in bounds? list_E[0]= %g list_E[DFSIZE]= %g\n",ee, list_E[0], list_E[DFSIZE]);
printf("in: comp_DF_fromtable\nerror: ie=%d out of range ue=%g\nstopping\n", ie, ue);
exit(0);
}
f_e= DistFunc_bulge[ie] * (1-ue) + DistFunc_bulge[ie+1] * ue;
return f_e;
}
/* ----------------------------------------------------------------- */
/* the following are analytic forms of the distribution
function, currently, it's only Hernquist 1990 */
/* Isotropic Hernquist Model */
double comp_DF_H_iso(double E)
{
double vg, q, prefac, f_e;
if (E >= 0.0)
return 0.0;
vg= sqrt(G * M_HALO / RH);
q= sqrt(-1.0 * E * RH / G / M_HALO);
if (q >= 1.0)
return (1.0e+30);
prefac= M_HALO / (8.0 * sqrt(2.0) * PI * PI * PI * RH * RH * RH * vg * vg * vg);
f_e= pow((1-q*q), -5./2.) * ( 3.*asin(q) + q*pow((1.-q*q),0.5)*(1.-2.*q*q) * (8.*q*q*q*q - 8.*q*q - 3.));
/*
printf(" E= %g vg= %g q= %g prefac= %g f_e %g\n", E, vg, q, prefac, f_e); fflush(stdout);
*/
return prefac * f_e;
}
/* Anisotropic Hernquist Model */
double comp_DF_H_ani(double Q)
{
if (AnisotropyRadius <= 0.0)
return 0;
double vg, qbar, prefac, f_e, f_iso;
double ra;
ra= AnisotropyRadius * RH;
if (Q <= 0.0)
return 0;
vg= sqrt(G * M_HALO / RH);
qbar= sqrt(RH * Q / G / M_HALO);
if (qbar >= 1.0)
return 1.0e+30;
prefac= M_HALO / (sqrt(2.0) * PI * PI * PI * RH * RH * RH * vg * vg * vg);
f_e= (RH * RH / ra / ra) * qbar * (1. - 2.*qbar*qbar);
f_iso= comp_DF_H_iso(-1.0*Q);
/*
printf("DF_ani Q= %g qbar= %g f_iso= %g prefac= %g f_e= %g\n",Q,qbar,f_iso,prefac,f_e); fflush(stdout);
*/
return f_iso + prefac * f_e;
}
/* -----------------------------------------------------------------
Now, calculate DF using the Eddington formula.
----------------------------------------------------------------- */
gsl_spline * d2rhodpsi2_spline_halo;
gsl_interp_accel * d2rhodpsi2_spline_acc_halo;
gsl_spline * d2rhodpsi2_spline_bulge;
gsl_interp_accel * d2rhodpsi2_spline_acc_bulge;
// Parameter struct for the Eddington integration function.
typedef struct {
const gsl_spline* s;
gsl_interp_accel* a;
double Q;
} spline_params;
/* The integrand for the Eddington integration. Now uses
the GSL spline functionality rather than the NR, which is evil. */
double eddington_integrand(double t, void *params)
{
spline_params* p = params;
//printf("t= %g\t", t);
//printf("Q= %g\t",p->Q);
//printf("sqrt(p->Q-t)= %g \t", sqrt(p->Q-t));
//printf("d2rhodpsi2= %g \t", gsl_spline_eval(p->s, t, p->a));
double v2 = gsl_spline_eval(p->s, t, p->a) / sqrt(p->Q - t);
//printf("v2= %g \n",v2); fflush(stdout);
return v2;
}
double comp_DF_halo_Eddington(double Q)
{
double f_e;
int i;
double result, abserr;
/* first, we'll generate the spline for d2rho/dpsi2 term in integrand */
if(Q<=0)
return 0.0;
/* load spline for d2rho/dpsi2 term into function parameters */
spline_params p;
p.s = d2rhodpsi2_spline_halo;
p.a = d2rhodpsi2_spline_acc_halo;
p.Q = Q;
/* error checking: write entire DF integrand and the spline */
/*
FILE *fd;
char tempfile[100]="";
sprintf(tempfile, "df_integrands/%g.txt", Q);
if((fd = fopen(tempfile,"w")))
{
fprintf(fd,"Q= %g \n",Q);
fprintf(fd," xi yi d2rho_dpsi2 Q Q-psiR sqrt(Q-psiR) \n");
for(i = 0; i <= DFSIZE; i++)
fprintf(fd," %8.5e %8.5e %8.5e %8.5e %8.5e %8.5e \n",xi[i],yi[i],d2rho_dpsi2[i], Q, Q-psi_R[i], sqrt(Q-psi_R[i]));
fclose(fd);
}
*/
gsl_function F;
F.function = &eddington_integrand;
F.params = &p;
double epsabs=0;
double epsrel=1e-4;
int intstatus;
/* do our own error handling, so that we can adjust the accuracy if needed (i.e., at small r) */
gsl_error_handler_t * old_handler = gsl_set_error_handler_off(); /* turn off the error-handler */
do
{
intstatus= gsl_integration_qags(&F, 0.0, Q, epsabs, epsrel, WORKSIZE, Workspace, &result, &abserr);
printf("epsrel = %g result = %g +/- %g (%g %)\n", epsrel, result, abserr, 100.0*abserr/result);
epsrel *= 2.0;
} while(intstatus == GSL_EROUND);
//printf("Workspace.intervals = %d\n", Workspace->size);
//printf("Workspace.maximum_level = %d\n", Workspace->maximum_level);
gsl_set_error_handler(old_handler); /* turn it on again */
f_e = result / sqrt(8.0) / PI / PI;
if(f_e<0)
f_e= 0.0;
return f_e;
}
double comp_DF_bulge_Eddington(double Q)
{
double f_e;
int i;
double result, abserr;
if(Q<=0)
return 0.0;
spline_params p;
p.s = d2rhodpsi2_spline_bulge;
p.a = d2rhodpsi2_spline_acc_bulge;
p.Q = Q;
gsl_function F;
F.function = &eddington_integrand;
F.params = &p;
double epsabs=0;
double epsrel=1e-4;
int intstatus;
gsl_error_handler_t * old_handler = gsl_set_error_handler_off(); /* turn off the error-handler */
do
{
intstatus= gsl_integration_qags(&F, 0.0, Q, epsabs, epsrel, WORKSIZE, Workspace, &result, &abserr);
//printf("epsrel = %g result = %g +/- %g (%g %)\n", epsrel, result, abserr, 100.0*abserr/result);
//printf("error = %g\n", abserr);
epsrel *= 2.0;
} while(intstatus == GSL_EROUND);
gsl_set_error_handler(old_handler); /* turn it on again */
f_e = result / sqrt(8.0) / PI / PI;
if(f_e<0)
f_e= 0.0;
return f_e;
}
/*
Computes d2_rho / dpsi2, which is the primary term
in the integral when using the Eddington formulation
to calculate the distribution function.
We do this for the halo and bulge components separately.
*/
void compute_d2rhodpsi2_halo()
{
FILE *fd;
char drhodpsifile[100]="";
int i;
double R, RplusdR, RminusdR, dR;
double rho_RplusdR, rho_RminusdR;
double psi_RplusdR, psi_RminusdR;
double slope1, slope2, ra;
// normalize just in case we get really small densities
double rho_norm, psi_norm;
for(i = 0; i <= DFSIZE; i++)
{
if(i < RSIZE)
/* continues same scaling as list_R
R= list_R[RSIZE] * exp((RSIZE-i) * (log(LL) - log(Baselen)) / (RSIZE - 1)); */
/* more modest scaling to zero energy (ie larger radii) */
R= list_R[RSIZE] * pow(10., 5.0 * (RSIZE-i) / RSIZE);
//R= list_R[RSIZE] * pow(10., 7.0 * (RSIZE-i) / RSIZE);
else
R= list_R[DFSIZE-i];
if(i == DFSIZE)
R= list_R[1] * 0.5;
/* interval of integration */
dR= R * exp(1.0e-2 * (log(LL) - log(Baselen)) / (RSIZE - 1)) - R;
if(dR>1.5)
dR= 1.5;
if((dR/R)<1.0e-4)
dR=1.0e-4*R;
RplusdR= R + dR;
RminusdR= R - dR;
list_radius[i]= R;
/* compute psi (=-phi, i.e., negative the potential) along the z axis, although
the full DF assumes spherical symmetry */
psi_R[i]= -1.0 * comp_phi(0, R);;
psi_RplusdR= -1.0 * comp_phi(0, RplusdR);
psi_RminusdR= -1.0 * comp_phi(0, RminusdR);
/* -------------------------------
DF for halo component */
rho_R_halo[i]= comp_rho_halo(R,0);
rho_RplusdR= comp_rho_halo(RplusdR,0);
rho_RminusdR= comp_rho_halo(RminusdR,0);
if(AnisotropyRadius>0)
{
ra= AnisotropyRadius * RH;
rho_R_halo[i] *= (1.0 + (R * R / ra / ra ));
rho_RplusdR *= (1.0 + (RplusdR * RplusdR / ra / ra));
rho_RminusdR *= (1.0 + (RminusdR * RminusdR / ra / ra));
}
// normalize
rho_norm= rho_R_halo[i];
rho_R_halo[i] /= rho_norm;
rho_RplusdR /= rho_norm;
rho_RminusdR /= rho_norm;
psi_norm= psi_R[i];
psi_R[i] /= psi_norm;
psi_RplusdR /= psi_norm;
psi_RminusdR /= psi_norm;
slope1= (rho_RplusdR - rho_R_halo[i]) / (psi_RplusdR - psi_R[i]);
slope2= (rho_R_halo[i] - rho_RminusdR) / (psi_R[i] - psi_RminusdR);
drhodpsi_halo[i]= 0.5*(slope1+slope2);
d2rhodpsi2_halo[i]= (rho_RplusdR+rho_RminusdR-2.*rho_R_halo[i])/(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR);
// now put units back in
psi_R[i] *= psi_norm;
rho_R_halo[i] *= rho_norm;
drhodpsi_halo[i] *= rho_norm / psi_norm;
d2rhodpsi2_halo[i] *= rho_norm / psi_norm / psi_norm;
//printf("i= %d, R= %g, second derivative denominators: %g, %g diff= %g\n",i,R,(psi_RplusdR-psi_R[i]),(psi_R[i]-psi_RminusdR),(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR));
//printf("i= %d, R= %g, rho= %g drhodpsi_halo= %g d2rhodpsi2_halo= %g second derivative denominators: %g, %g diff= %g\n",i,R,rho_R_halo[i],drhodpsi_halo[i],d2rhodpsi2_halo[i],(psi_RplusdR-psi_R[i]),(psi_R[i]-psi_RminusdR),(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR));
//printf("i= %d, R= %g, rho_0= %g ani_factor= %g rho_R_halo= %g\n",i,R,comp_rho_halo(R,0),(1.0 + (R * R / ra / ra )),rho_R_halo[i]);
}
xi[0] = 0;
yi[0] = 0;
/* generate spline for the d2rho / dpsi2 term */
for(i = 0; i <= DFSIZE; i++)
{
xi[i + 1] = psi_R[i];
yi[i + 1] = d2rhodpsi2_halo[i];
if( (xi[i+1] - xi[i]) < 0) xi[i+1] = xi[i] + 1e-5;
printf("xi[i] = %f yi[i] = %f delta_x = %f\n",xi[i + 1], yi[i + 1], xi[i+1] - xi[i]);
}
printf("check_abcdefg\n");
gsl_spline_init(d2rhodpsi2_spline_halo, xi, yi, DFSIZE+1);
printf("check_abcdefg done\n");
/* write this to a file so we have a record of it */
strcpy(drhodpsifile,"");
if(strstr(OutputFile,".hdf5"))
strncpy(drhodpsifile, OutputFile, strlen(OutputFile)-5);
if(strstr(OutputFile,".dat"))
strncpy(drhodpsifile, OutputFile, strlen(OutputFile)-4);
strcat(drhodpsifile, ".drhodpsi_halo");
if((fd = fopen(drhodpsifile,"w")))
{
fprintf(fd,"# drhodpsi file, halo component\n");
fprintf(fd,"# n= %d \n",DFSIZE);
fprintf(fd,"# \n");
fprintf(fd,"# R (kpc) psi rho drho/dpsi d2rho/dpsi2 spline(psi) \n");
fprintf(fd,"# \n");
for(i = 0; i <= DFSIZE; i++)
fprintf(fd," %8.5e %8.5e %8.5e %8.5e %8.5e %8.5e \n",list_radius[i],psi_R[i],rho_R_halo[i],drhodpsi_halo[i],d2rhodpsi2_halo[i],gsl_spline_eval(d2rhodpsi2_spline_halo, 0.999*psi_R[i], d2rhodpsi2_spline_acc_halo));
fclose(fd);
}
}
void compute_d2rhodpsi2_bulge()
{
FILE *fd;
char drhodpsifile[100]="";
int i;
double R, RplusdR, RminusdR, dR;
double rho_RplusdR, rho_RminusdR;
double psi_RplusdR, psi_RminusdR;
double slope1, slope2, ra;
// normalize just in case we get really small densities
double rho_norm, psi_norm;
if(M_BULGE == 0)
return;
for(i = 0; i <= DFSIZE; i++)
{
if(i < RSIZE)
/* continues same scaling as list_R
R= list_R[RSIZE] * exp((RSIZE-i) * (log(LL) - log(Baselen)) / (RSIZE - 1)); */
/* more modest scaling to zero energy (ie larger radii) */
R= list_R[RSIZE] * pow(10., 5.0 * (RSIZE-i) / RSIZE);
//R= list_R[RSIZE] * pow(10., 7.0 * (RSIZE-i) / RSIZE);
else
R= list_R[DFSIZE-i];
if(i == DFSIZE)
R= list_R[1] * 0.5;
/* interval of integration */
dR= R * exp(1.0e-2 * (log(LL) - log(Baselen)) / (RSIZE - 1)) - R;
if(dR>1.5)
dR= 1.5;
if((dR/R)<1.0e-4)
dR=1.0e-4*R;
RplusdR= R + dR;
RminusdR= R - dR;
list_radius[i]= R;
/* compute psi (=-phi, i.e., negative the potential) along the z axis, although
the full DF assumes spherical symmetry */
psi_R[i]= -1.0 * comp_phi(0, R);;
psi_RplusdR= -1.0 * comp_phi(0, RplusdR);
psi_RminusdR= -1.0 * comp_phi(0, RminusdR);
/* -------------------------------
DF for bulge component */
rho_R_bulge[i]= comp_rho_bulge(R,0);
rho_RplusdR= comp_rho_bulge(RplusdR,0);
rho_RminusdR= comp_rho_bulge(RminusdR,0);
if(AnisotropyRadius>0)
{
ra= AnisotropyRadius * RH;
rho_R_bulge[i] *= (1.0 + (R * R / ra / ra ));
rho_RplusdR *= (1.0 + (RplusdR * RplusdR / ra / ra));
rho_RminusdR *= (1.0 + (RminusdR * RminusdR / ra / ra));
}
// normalize
rho_norm= rho_R_bulge[i];
rho_R_bulge[i] /= rho_norm;
rho_RplusdR /= rho_norm;
rho_RminusdR /= rho_norm;
psi_norm= psi_R[i];
psi_R[i] /= psi_norm;
psi_RplusdR /= psi_norm;
psi_RminusdR /= psi_norm;
slope1= (rho_RplusdR - rho_R_bulge[i]) / (psi_RplusdR - psi_R[i]);
slope2= (rho_R_bulge[i] - rho_RminusdR) / (psi_R[i] - psi_RminusdR);
drhodpsi_bulge[i]= 0.5*(slope1+slope2);
d2rhodpsi2_bulge[i]= (rho_RplusdR+rho_RminusdR-2.*rho_R_bulge[i])/(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR);
// now put units back in
psi_R[i] *= psi_norm;
rho_R_bulge[i] *= rho_norm;
drhodpsi_bulge[i] *= rho_norm / psi_norm;
d2rhodpsi2_bulge[i] *= rho_norm / psi_norm / psi_norm;
//printf("i= %d, R= %g, second derivative denominators: %g, %g diff= %g\n",i,R,(psi_RplusdR-psi_R[i]),(psi_R[i]-psi_RminusdR),(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR));
//printf("i= %d, R= %g, rho= %g drhodpsi_bulge= %g d2rhodpsi2_bulge= %g second derivative denominators: %g, %g diff= %g\n",i,R,rho_R_bulge[i],drhodpsi_bulge[i],d2rhodpsi2_bulge[i],(psi_RplusdR-psi_R[i]),(psi_R[i]-psi_RminusdR),(psi_RplusdR-psi_R[i])/(psi_R[i]-psi_RminusdR));
//printf("i= %d, R= %g, rho_0= %g ani_factor= %g rho_R_bulge= %g\n",i,R,comp_rho_bulge(R,0),(1.0 + (R * R / ra / ra )),rho_R_bulge[i]);
}
/* generate spline for the d2rho / dpsi2 term */
for(i = 0; i <= DFSIZE; i++)
{
xi[i + 1] = psi_R[i];
yi[i + 1] = d2rhodpsi2_bulge[i];
if( (xi[i+1] - xi[i]) < 0) xi[i+1] = xi[i] + 1e-5;
}
gsl_spline_init(d2rhodpsi2_spline_bulge, xi, yi, DFSIZE+1);
/* write this to a file so we have a record of it */
strcpy(drhodpsifile,"");
if(strstr(OutputFile,".hdf5"))
strncpy(drhodpsifile, OutputFile, strlen(OutputFile)-5);
if(strstr(OutputFile,".dat"))
strncpy(drhodpsifile, OutputFile, strlen(OutputFile)-4);
strcat(drhodpsifile, ".drhodpsi_bulge");
if((fd = fopen(drhodpsifile,"w")))
{
fprintf(fd,"# drhodpsi file, bulge component\n");
fprintf(fd,"# n= %d \n",DFSIZE);
fprintf(fd,"# \n");
fprintf(fd,"# R (kpc) psi rho drho/dpsi d2rho/dpsi2 spline(psi) \n");
fprintf(fd,"# \n");
for(i = 0; i <= DFSIZE; i++)
fprintf(fd," %8.5e %8.5e %8.5e %8.5e %8.5e %8.5e \n",list_radius[i],psi_R[i],rho_R_bulge[i],drhodpsi_bulge[i],d2rhodpsi2_bulge[i],gsl_spline_eval(d2rhodpsi2_spline_bulge, 0.999*psi_R[i], d2rhodpsi2_spline_acc_bulge));
fclose(fd);
}
}
void comp_DF_init(void)
{
/* stores spline on the Eddington integrand */
xi= vector(1, DFSIZE+1);
yi= vector(1, DFSIZE+1);
eddint= vector(1, DFSIZE+1);
/* arrays for energies, radii, d2rho/dpsi2 term in Eddington integrand, and pre-computed DF */
list_radius= vector(0, DFSIZE);
list_E= vector(0, DFSIZE);
psi_R= vector(0, DFSIZE);
/* halo specific */
rho_R_halo= vector(0, DFSIZE);
drhodpsi_halo= vector(0, DFSIZE);
d2rhodpsi2_halo= vector(0, DFSIZE);
DistFunc_halo= vector(0, DFSIZE);
/* bulge specific */
rho_R_bulge= vector(0, DFSIZE);
drhodpsi_bulge= vector(0, DFSIZE);
d2rhodpsi2_bulge= vector(0, DFSIZE);
DistFunc_bulge= vector(0, DFSIZE);
/* setup the d2rho_dpsi2 array */
/* for the halo */
printf("allocating for halo\n");
d2rhodpsi2_spline_halo = gsl_spline_alloc(gsl_interp_cspline, DFSIZE+1);
d2rhodpsi2_spline_acc_halo = gsl_interp_accel_alloc();
printf("evaluating for halo\n");
compute_d2rhodpsi2_halo();
/* for the bulge */
printf("allocating for bulge\n");
d2rhodpsi2_spline_bulge = gsl_spline_alloc(gsl_interp_cspline, DFSIZE+1);
d2rhodpsi2_spline_acc_bulge = gsl_interp_accel_alloc();
compute_d2rhodpsi2_bulge();
printf("some workplace alloc\n");
Workspace = gsl_integration_workspace_alloc(WORKSIZE);
}
void comp_DF_Eddington_close(void)
{
free_vector(xi, 1, DFSIZE+1);
free_vector(yi, 1, DFSIZE+1);
free_vector(eddint, 1, DFSIZE+1);
free_vector(psi_R, 1, DFSIZE);
free_vector(list_radius, 1, DFSIZE);
free_vector(list_E, 1, DFSIZE);
free_vector(rho_R_halo, 1, DFSIZE);
free_vector(rho_R_bulge, 1, DFSIZE);
free_vector(drhodpsi_halo, 1, DFSIZE);
free_vector(drhodpsi_bulge, 1, DFSIZE);
free_vector(d2rhodpsi2_halo, 1, DFSIZE);
free_vector(d2rhodpsi2_bulge, 1, DFSIZE);
free_vector(DistFunc_halo, 1, DFSIZE);
free_vector(DistFunc_bulge, 1, DFSIZE);
gsl_integration_workspace_free(Workspace);
gsl_spline_free(d2rhodpsi2_spline_halo);
printf("check_1234\n");
gsl_interp_accel_free(d2rhodpsi2_spline_acc_halo);
gsl_spline_free(d2rhodpsi2_spline_bulge);
printf("check_abcd\n");
gsl_interp_accel_free(d2rhodpsi2_spline_acc_bulge);
}
/* ----------------------------------------------------------------- */
double compute_ani_beta(double r)
{
double beta;
/* isotropic model */
beta = 0.0;
if (AnisotropyRadius > 0)
{
double ra;
ra= AnisotropyRadius * RH;
/* Osipkov & Merritt anisotropy dependency */
beta = r * r / (r * r + ra * ra);
}
return beta;
}
| {
"alphanum_fraction": 0.6010663456,
"avg_line_length": 24.1505711319,
"ext": "c",
"hexsha": "0a9c255ac36476eb3963e07fb4a5ca9eaf630bce",
"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": "f14519552cedd39a040b53e6d7cc538b5b8f38a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lzkelley/arepo-mbh-sims_analysis",
"max_forks_repo_path": "paul_analysis/C/ICs/MakeGalaxy/distfunc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3",
"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": "lzkelley/arepo-mbh-sims_analysis",
"max_issues_repo_path": "paul_analysis/C/ICs/MakeGalaxy/distfunc.c",
"max_line_length": 288,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f14519552cedd39a040b53e6d7cc538b5b8f38a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lzkelley/arepo-mbh-sims_analysis",
"max_stars_repo_path": "paul_analysis/C/ICs/MakeGalaxy/distfunc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8356,
"size": 23257
} |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
int
func (double t, const double y[], double f[],
void *params)
{
double mu = *(double *)params;
f[0] = y[1];
f[1] = -y[0] - mu*y[1]*(y[0]*y[0] - 1);
return GSL_SUCCESS;
}
int
jac (double t, const double y[], double *dfdy,
double dfdt[], void *params)
{
double mu = *(double *)params;
gsl_matrix_view dfdy_mat
= gsl_matrix_view_array (dfdy, 2, 2);
gsl_matrix * m = &dfdy_mat.matrix;
gsl_matrix_set (m, 0, 0, 0.0);
gsl_matrix_set (m, 0, 1, 1.0);
gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0);
gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0));
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
int
main (void)
{
const gsl_odeiv_step_type * T
= gsl_odeiv_step_rk8pd;
gsl_odeiv_step * s
= gsl_odeiv_step_alloc (T, 2);
gsl_odeiv_control * c
= gsl_odeiv_control_y_new (1e-6, 0.0);
gsl_odeiv_evolve * e
= gsl_odeiv_evolve_alloc (2);
double mu = 10;
gsl_odeiv_system sys = {func, jac, 2, &mu};
double t = 0.0, t1 = 100.0;
double h = 1e-6;
double y[2] = { 1.0, 0.0 };
while (t < t1)
{
int status = gsl_odeiv_evolve_apply (e, c, s,
&sys,
&t, t1,
&h, y);
if (status != GSL_SUCCESS)
break;
printf ("%.5e %.5e %.5e\n", t, y[0], y[1]);
}
gsl_odeiv_evolve_free (e);
gsl_odeiv_control_free (c);
gsl_odeiv_step_free (s);
return 0;
}
| {
"alphanum_fraction": 0.5408291457,
"avg_line_length": 22.4225352113,
"ext": "c",
"hexsha": "8a8f79493e85d3a9ddd931896ea1f055df8e4975",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c",
"max_line_length": 52,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ode-initval.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 605,
"size": 1592
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.