Search is not available for this dataset
text string | meta dict |
|---|---|
/* multimin/steepest_descent.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* 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.
*/
/* steepest_descent.c -- the steepest descent algorithm */
#include <config.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_blas_types.h>
#include <gsl/gsl_blas.h>
typedef struct
{
double step;
double max_step;
gsl_vector *x1;
gsl_vector *g1;
}
steepest_descent_state_t;
static int
steepest_descent_alloc (void *vstate, size_t n)
{
steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;
state->x1 = gsl_vector_alloc (n);
if (state->x1 == NULL)
{
GSL_ERROR ("failed to allocate space for x1", GSL_ENOMEM);
}
state->g1 = gsl_vector_alloc (n);
if (state->g1 == NULL)
{
gsl_vector_free (state->x1);
GSL_ERROR ("failed to allocate space for g1", GSL_ENOMEM);
}
return GSL_SUCCESS;
}
static int
steepest_descent_set (void *vstate, gsl_multimin_function_fdf * fdf,
const gsl_vector * x, double *f,
gsl_vector * gradient, double step_size)
{
steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;
GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x, f, gradient);
state->step = step_size;
state->max_step = step_size;
return GSL_SUCCESS;
}
static void
steepest_descent_free (void *vstate)
{
steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;
gsl_vector_free (state->x1);
gsl_vector_free (state->g1);
}
static int
steepest_descent_restart (void *vstate)
{
steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;
state->step = state->max_step;
return GSL_SUCCESS;
}
static int
steepest_descent_iterate (void *vstate, gsl_multimin_function_fdf * fdf,
gsl_vector * x, double *f,
gsl_vector * gradient, gsl_vector * dx)
{
steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;
gsl_vector *x1 = state->x1;
gsl_vector *g1 = state->g1;
double f0 = *f;
double f1, fm, f_trial;
double step0 = 0.0, step1, stepm, step_trial, step = state->step;
size_t iter = 0;
/* compute new trial point at x1= x - step * dir, where dir is the
normalized gradient */
double gnorm = gsl_blas_dnrm2 (gradient);
gsl_vector_set_zero (dx);
gsl_blas_daxpy (-step / gnorm, gradient, dx);
gsl_vector_memcpy (x1, x);
gsl_blas_daxpy (1.0, dx, x1);
/* evaluate function and gradient at new point x1 */
GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x1, &f1, g1);
if (f1 < f0)
{
state->step = 2.0 * step;
gsl_vector_memcpy (x, x1);
gsl_vector_memcpy (gradient, g1);
*f = f1;
return GSL_SUCCESS;
}
step1 = step;
trial:
stepm = 0.5 * step1;
gsl_vector_set_zero (dx);
gsl_blas_daxpy (-stepm / gnorm, gradient, dx);
gsl_vector_memcpy (x1, x);
gsl_blas_daxpy (1.0, dx, x1);
fm = GSL_MULTIMIN_FN_EVAL_F (fdf, x1);
printf("trying stepm = %.18e fm=%g\n", stepm, fm);
if (fm >= f0)
{
/* downhill step failed, reduce step-size and try again */
f1 = fm;
step1 = stepm;
goto trial;
}
/* We now have a triplet (0,f0) (stepm, fm) (step1, f1) */
minimize:
iter++;
if ((stepm - step0) > (step1 - stepm))
{
step_trial = stepm - 0.38 * (stepm - step0);
}
else
{
step_trial = stepm + 0.38 * (step1 - stepm);
}
gsl_vector_set_zero (dx);
gsl_blas_daxpy (-step_trial / gnorm, gradient, dx);
gsl_vector_memcpy (x1, x);
gsl_blas_daxpy (1.0, dx, x1);
f_trial = GSL_MULTIMIN_FN_EVAL_F (fdf, x1);
if (f_trial > fm)
{
if (step_trial < stepm)
{
step0 = step_trial;
f0 = f_trial;
}
else
{
step1 = step_trial;
f1 = f_trial;
}
}
else
{
if (step_trial < stepm)
{
step1 = stepm;
f1 = fm;
}
else
{
step0 = stepm;
f0 = fm;
}
stepm = step_trial;
fm = f_trial;
}
printf("f = %.18e\n", fm);
if (iter > 100)
{
gsl_vector_set_zero (dx);
gsl_blas_daxpy (-stepm / gnorm, gradient, dx);
gsl_blas_daxpy (1.0, dx, x);
GSL_MULTIMIN_FN_EVAL_DF (fdf, x, gradient);
*f = fm;
state->step = stepm;
return GSL_SUCCESS;
}
goto minimize;
}
static const gsl_multimin_fdfminimizer_type steepest_descent_type =
{ "steepest_descent", /* name */
sizeof (steepest_descent_state_t),
&steepest_descent_alloc,
&steepest_descent_set,
&steepest_descent_iterate,
&steepest_descent_restart,
&steepest_descent_free
};
const gsl_multimin_fdfminimizer_type
*gsl_multimin_fdfminimizer_steepest_descent = &steepest_descent_type;
| {
"alphanum_fraction": 0.6407589856,
"avg_line_length": 22.8375,
"ext": "c",
"hexsha": "e7727bdd9e18f734ea588a9816cce8eb2a5c4fa3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/sd2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/sd2.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/sd2.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": 1671,
"size": 5481
} |
/* 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: Expi.c
*
* Description: Calculation of the exponential integrals (w/o the GSL special
* functions).
*
* Version: 1.0
* Created: 15/04/2013 11:54:19
* Revision: none
* Compiler: gcc
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization:
*
* =====================================================================================
*/
#include "funcs.h"
#include <gsl/gsl_integration.h>
/* #include <gsl/gsl_sf_expint.h> */
double fu ( double t, void* params )
{
double f = -exp(-t)/t ;
return f ;
}
double ex ( double t, void* params )
{
double e = exp(-t) ;
return e ;
}
int expi ( double x, double* result, double* abserr )
{
double r, err ;
gsl_integration_workspace* expi_ws =
gsl_integration_workspace_alloc (WS_SZ) ;
gsl_function F ;
F.function = &fu ;
int status ;
status = gsl_integration_qagiu ( &F, x, 10e-9, .001 , WS_SZ, expi_ws, &r,
&err) ;
*result = r ; *abserr = err ;
/* Using the GSL special functions, it is simply:
*
* *result = - gsl_sf_expint_E1(x) ;
*/
gsl_integration_workspace_free (expi_ws) ;
return status;
}
int expi_plus ( double x, double* result, double* abserr )
{
double r, err ;
gsl_integration_workspace *expi_ws =
gsl_integration_workspace_alloc (WS_SZ) ;
gsl_function F ;
F.function = &ex ;
int status ;
status = gsl_integration_qawc ( &F, -x, x, 0, 1e-9, .001, WS_SZ,
expi_ws, &r, &err ) ;
double R , EXPI , ERREXPI ;
int s = expi ( x , &EXPI, &ERREXPI ) ;
R = - (r - EXPI) ; /* The minus (-) sign because of the def.
of ex */
double ERR ;
ERR = err + ERREXPI ;
*result = R ;
*abserr = ERR ;
/* Using the GSL exponential integral, it is simply:
*
* R = gsl_sf_expint_Ei(x) ;
*
*/
gsl_integration_workspace_free (expi_ws) ;
return status + s ;
}
| {
"alphanum_fraction": 0.6385893326,
"avg_line_length": 27.448,
"ext": "c",
"hexsha": "1734c7a62d3da2552c818291065651c2705fc013",
"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": "Expi.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": "Expi.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": "Expi.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 870,
"size": 3431
} |
#ifndef __mcas_SERVER_TASK_KEY_FIND_H__
#define __mcas_SERVER_TASK_KEY_FIND_H__
#include <common/logging.h>
#include <gsl/pointers>
#include <unistd.h>
#include <string>
#include "task.h"
namespace mcas
{
/**
* Key search task. We limit the number of hops we search so as to bound
* the worst case execution time.
*
*/
class Key_find_task : public Shard_task,
private common::log_source
{
static constexpr unsigned MAX_COMPARES_PER_WORK = 5;
public:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++" // uninitialized _expr, _out_key, _type
Key_find_task(const std::string& expression,
const offset_t offset,
Connection_handler* handler,
gsl::not_null<component::IKVIndex*> index,
const unsigned debug_level)
: Shard_task(handler),
log_source(debug_level),
_offset(offset),
_index(index)
{
using namespace component;
_index->add_ref();
CPLOG(1, "offset=%lu", offset);
CPLOG(1,"expr: (%s)", expression.c_str());
if (expression == "next:") {
_type = IKVIndex::FIND_TYPE_NEXT;
_expr = expression.substr(5);
}
else if (expression.substr(0, 6) == "regex:") {
_type = IKVIndex::FIND_TYPE_REGEX;
_expr = expression.substr(6);
}
else if (expression.substr(0, 6) == "exact:") {
_type = IKVIndex::FIND_TYPE_EXACT;
_expr = expression.substr(6);
}
else if (expression.substr(0, 7) == "prefix:") {
_type = IKVIndex::FIND_TYPE_PREFIX;
_expr = expression.substr(7);
}
else
throw Logic_exception("unhandled expression");
}
#pragma GCC diagnostic pop
Key_find_task(const Key_find_task&) = delete;
Key_find_task& operator=(const Key_find_task&) = delete;
status_t do_work() override
{
using namespace component;
status_t hr;
try {
hr = _index->find(_expr, _offset, _type, _offset, _out_key, MAX_COMPARES_PER_WORK);
if (hr == E_MAX_REACHED) {
_offset++;
return component::IKVStore::S_MORE;
}
else if (hr == S_OK) {
CPLOG(2, "matched: (%s)", _out_key.c_str());
return S_OK;
}
else {
_out_key.clear();
return hr;
}
}
catch (...) {
return E_FAIL;
}
throw Logic_exception("unexpected code path (hr=%d)", hr);
}
const void* get_result() const override { return _out_key.data(); }
size_t get_result_length() const override { return _out_key.length(); }
offset_t matched_position() const override { return _offset; }
private:
std::string _expr;
std::string _out_key;
component::IKVIndex::find_t _type;
offset_t _offset;
component::Itf_ref<component::IKVIndex> _index;
};
} // namespace mcas
#endif // __mcas_SERVER_TASK_KEY_FIND_H__
| {
"alphanum_fraction": 0.6159618008,
"avg_line_length": 26.4144144144,
"ext": "h",
"hexsha": "55ef29321f1fdbcc1db6b7da7929452fea8fa368",
"lang": "C",
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z",
"max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "moshik1/mcas",
"max_forks_repo_path": "src/server/mcas/src/task_key_find.h",
"max_issues_count": 66,
"max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "moshik1/mcas",
"max_issues_repo_path": "src/server/mcas/src/task_key_find.h",
"max_line_length": 89,
"max_stars_count": 60,
"max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "moshik1/mcas",
"max_stars_repo_path": "src/server/mcas/src/task_key_find.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z",
"num_tokens": 734,
"size": 2932
} |
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
void *xcalloc(int items, int size)
{
void *ptr = calloc(items, size);
if (ptr == NULL)
{
printf("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
return ptr;
}
void GetLGLPoints(int N, double *x)
{
if (N == 0)
{
printf("Support for constants doesn't exist\n");
exit(1);
}
else if (N == 1)
{
x[0] = -1.0;
x[1] = 1.0;
}
else if (N==2)
{
x[0] = -1.0;
x[1] = 0.0;
x[2] = 1.0;
}
else if (N==3)
{
x[0] = -1.0;
x[1] = -0.4472;
x[2] = 0.4472;
x[3] = 1.0;
}
else if (N==4)
{
x[0] = -1.0;
x[1] = -0.6547;
x[2] = 0;
x[3] = 0.6547;
x[4] = 1.0;
}
else
{
printf("Currently only have up to fourth order polynomial encoded for LGL points\n");
exit(1);
}
}
void GetLGLWeights(int N, double *w)
{
if (N == 0)
{
printf("Support for constants doesn't exist\n");
exit(1);
}
else if (N == 1)
{
w[0] = 1.0;
w[1] = 1.0;
}
else if (N==2)
{
w[0] = 0.3333333333333;
w[1] = 1.3333333333333;
w[2] = 0.3333333333333;
}
else if (N==3)
{
w[0] = 0.16666666666667;
w[1] = 0.83333333333333;
w[2] = 0.83333333333333;
w[3] = 0.16666666666667;
}
else if (N==4)
{
w[0] = 0.1;
w[1] = 0.5444444;
w[2] = 0.7111111;
w[3] = 0.5444444;
w[4] = 0.1;
}
else
{
printf("Currently only have up to fourth order polynomial encoded for LGL points\n");
exit(1);
}
}
void calculateNodalCoordinates(int N, int NumEl, double* X, double* Xnodes)
{
double r[N+1];
GetLGLPoints(N, r);
for(int i = 0; i < NumEl; i++)
{
for (int j = 0; j < N+1; j++)
{
Xnodes[i*(N+1)+j] = X[i] + 0.5*(r[j]+1)*(X[i+1]-X[i]);
}
}
}
void LegendrePoly(double *x, int Np, int N, double* P)
{
// Purpose: Evaluates the normalized Legendre polynomials
// at points x for order N and returns the values in the
// array P that is Np long
double aold = 0.0, anew=0.0;
double **PL = xcalloc(N+1, sizeof(double*));
for (int i =0; i < N+1; i++)
{
PL[i] = xcalloc(Np, sizeof(double));
}
// Initial values P_0(x) and P_1(x)
if (N==0)
{
double constVal = 1.0/sqrt(2);
for (int j = 0; j < Np; j++)
{
P[j] = constVal;
}
free(PL[0]);
free(PL);
return;
}
else
{
for (int j = 0; j < Np; j++)
{
PL[0][j] = 1.0/sqrt(2);
}
}
double *prow = xcalloc(Np, sizeof(double));
double coeff = sqrt(1.5);
for (int i = 0; i < Np; i++)
{
prow[i] = coeff*x[i];
}
if(N==1)
{
for (int i = 0; i < Np; i++)
{
P[i] = prow[i];
}
free(prow);
free(PL[0]);
free(PL[1]);
free(PL);
return;
}
else
{
for (int j =0; j < Np; j++)
{
PL[1][j] = coeff*x[j];
}
}
// Repeat value in recurrence
aold = sqrt(1.0/3);
// Forward recurrence
for (int i = 2; i <= N; i++)
{
anew = sqrt(i*i/((2.0*i+1)*(2*i-1)));
for (int j = 0; j < Np; j++)
{
PL[i][j] = (x[j]*PL[i-1][j]-aold*PL[i-2][j])/anew;
}
aold = anew;
}
for (int j = 0; j < Np; j++)
{
P[j] = PL[N][j];
}
for (int i =0; i < N; i++)
{
free(PL[i]);
}
free(PL);
return;
}
void Vandermonde1D(double *x, int Np, int N, gsl_matrix** V1D)
{
// Purpose: Evaluates the Vandermonde matrix V_{ij} = phi_i(r_j);
*V1D = gsl_matrix_alloc(Np, N+1);
double V1DT[Np];
for(int i = 0; i < N+1; i++)
{
LegendrePoly(x, Np, i, V1DT);
for (int j = 0; j < Np; j++)
{
gsl_matrix_set(*V1D, i, j, V1DT[j]);
//gsl_matrix_set(*V1D, j, i, V1DT[j]);
}
}
}
void GradLegendrePoly(double *x, int Np, int N, double* DP)
{
// Purpose: Evaluates the derivatives of normalized Legendre polynomial
// at points x for order N and returns the values in the
// array P that is Np long
//
double aold, anew;
double **DPL = xcalloc(N+1, sizeof(double*));
for (int i =0; i < N+1; i++)
{
DPL[i] = xcalloc(Np, sizeof(double));
}
// Initial values P_0(x) and P_1(x)
if (N==0)
{
for (int j = 0; j < Np; j++)
{
DP[0] = 0;
}
free(DPL[0]);
free(DPL);
return;
}
else
{
for (int j = 0; j < Np; j++)
{
DPL[0][j] = 0;
}
}
double *dprow = xcalloc(Np, sizeof(double));
double deriv = sqrt(1.5);
for (int i = 0; i < Np; i++)
{
dprow[i] = deriv;
}
if(N==1)
{
for (int i = 0; i < Np; i++)
{
DP[i] = deriv;
}
free(dprow);
free(DPL[0]);
free(DPL[1]);
free(DPL);
return;
}
else
{
for (int j =0; j < Np; j++)
{
DPL[1][j] = deriv;
}
}
// Repeat value in recurrence
aold = sqrt(1.0/3);
// Forward recurrence
for (int i = 2; i <= N; i++)
{
anew = sqrt(i*i/((2.0*i+1)*(2*i-1)));
double P[Np];
LegendrePoly(x, Np, i-1, P);
for (int j = 0; j < Np; j++)
{
DPL[i][j] = 1.0/(anew)*(P[j] + x[j]*DPL[i-1][j] - aold*DPL[i-2][j]);
}
aold = anew;
}
for (int j = 0; j < Np; j++)
{
DP[j] = DPL[N][j];
}
for (int i =0; i < N; i++)
{
free(DPL[i]);
}
free(DPL);
return;
}
void GradVandermonde1D(double *r, int Np, int N, gsl_matrix** GV)
{
// Purpose: Evaluates the gradient of modal basis (i) at (r)
// at order N and return them in GV whose size is
// ixNp
//
*GV = gsl_matrix_alloc(Np, N+1);
double GVT[Np];
for (int i =0; i < N+1; i++)
{
GradLegendrePoly(r, Np, i, GVT);
for (int j = 0; j < Np; j++)
gsl_matrix_set(*GV,i,j, GVT[j]);
//gsl_matrix_set(*GV,j,i,GVT[j]);
}
}
void VolIntMat1D(double *x, int N, gsl_matrix* V, gsl_matrix *Vr, gsl_matrix** VolMat)
{
gsl_permutation *p = gsl_permutation_alloc(N+1);
gsl_matrix *Vcopy = gsl_matrix_alloc(N+1, N+1);
gsl_matrix_memcpy(Vcopy, V);
gsl_matrix *Vinv = gsl_matrix_alloc(N+1, N+1);
int s;
gsl_linalg_LU_decomp(Vcopy, p, &s);
gsl_linalg_LU_invert(Vcopy, p, Vinv);
gsl_matrix *tmp1 = gsl_matrix_alloc(N+1, N+1);
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, Vinv, Vinv, 0.0, tmp1);
gsl_matrix *tmp2 = gsl_matrix_alloc(N+1, N+1);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Vr, tmp1, 0.0, tmp2);
*VolMat = gsl_matrix_alloc(N+1, N+1);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, tmp2, 0.0, *
VolMat);
//gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Vr, Vinv, 0.0, *Dr);
gsl_permutation_free(p);
gsl_matrix_free(Vcopy);
gsl_matrix_free(Vinv);
gsl_matrix_free(tmp1);
gsl_matrix_free(tmp2);
}
void Lift1D(int Np, gsl_matrix *V, gsl_matrix **LIFT)
{
*LIFT = gsl_matrix_alloc(Np,2);
gsl_matrix *EMAT = gsl_matrix_calloc(Np, 2);
gsl_matrix_set(EMAT, 0, 0, 1.0);
gsl_matrix_set(EMAT, Np-1, 1, -1.0);
gsl_matrix *tmp = gsl_matrix_alloc(Np,2);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, V, EMAT, 0.0, tmp);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, tmp, 0.0, *LIFT);
gsl_matrix_free(EMAT);
gsl_matrix_free(tmp);
}
void calculateMassMatrix(int Np, gsl_matrix* V, gsl_matrix** MassMatrix)
{
*MassMatrix = gsl_matrix_alloc(Np,Np);
gsl_matrix *MassMatrixInv = gsl_matrix_alloc(Np,Np);
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, V, 0.0, MassMatrixInv);
int s = 0;
gsl_permutation *p = gsl_permutation_alloc(Np);
gsl_linalg_LU_decomp(MassMatrixInv, p, &s);
gsl_linalg_LU_invert(MassMatrixInv, p, *MassMatrix);
gsl_matrix_free(MassMatrixInv);
gsl_permutation_free(p);
}
void calculateLIFTVolMat(int N, int Np, gsl_matrix **LIFT, gsl_matrix **VolMat,gsl_matrix **MassMatrix)
{
double r[Np];
GetLGLPoints(N,r);
gsl_matrix *V;
gsl_matrix *GV;
Vandermonde1D(r,Np,N,&V);
GradVandermonde1D(r, Np, N, &GV);
VolIntMat1D(r, N, V, GV, VolMat);
Lift1D(Np, V, LIFT);
calculateMassMatrix(Np, V,MassMatrix);
gsl_matrix_free(V);
gsl_matrix_free(GV);
}
| {
"alphanum_fraction": 0.5805724887,
"avg_line_length": 17.9239904988,
"ext": "c",
"hexsha": "8c64a3908598db0dda55e6e1c8d1fa35b6e1811c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z",
"max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "evalseth/DG-RAIN",
"max_forks_repo_path": "1DCode/BasisFunctionRoutines.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "evalseth/DG-RAIN",
"max_issues_repo_path": "1DCode/BasisFunctionRoutines.c",
"max_line_length": 103,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "evalseth/DG-RAIN",
"max_stars_repo_path": "1DCode/BasisFunctionRoutines.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": 3162,
"size": 7546
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for functions computing coeffcients of Not-A-Knot and Quadratic splines in matrix form.
*
*/
#ifndef _SPLINECOEFFS_H
#define _SPLINECOEFFS_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#if defined(__cplusplus)
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
void BuildNotAKnotSpline(
gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */
gsl_vector* vectx, /* Input: vector x*/
gsl_vector* vecty, /* Input: vector y */
int n); /* Size of x, y, and of output matrix */
void BuildQuadSpline(
gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */
gsl_vector* vectx, /* Input: vector x*/
gsl_vector* vecty, /* Input: vector y */
int n); /* Size of x, y, and of output matrix */
void BuildSplineCoeffs(
CAmpPhaseSpline** splines, /* */
CAmpPhaseFrequencySeries* freqseries); /* */
void BuildListmodesCAmpPhaseSpline(
ListmodesCAmpPhaseSpline** listspline, /* Output: list of modes of splines in matrix form */
ListmodesCAmpPhaseFrequencySeries* listh); /* Input: list of modes in amplitude/phase form */
/* Functions for spline evaluation */
/* Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 */
double EvalCubic(
gsl_vector* coeffs, /**/
double eps, /**/
double eps2, /**/
double eps3); /**/
double EvalQuad(
gsl_vector* coeffs, /**/
double eps, /**/
double eps2); /**/
void EvalCAmpPhaseSpline(
CAmpPhaseSpline* splines, //input
CAmpPhaseFrequencySeries* freqseries); //in/out defines CAmpPhase from defined freqs
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _SPLINECOEFFS_H */
| {
"alphanum_fraction": 0.6600159617,
"avg_line_length": 27.5384615385,
"ext": "h",
"hexsha": "2c0f659d347ea43e40d4b7a2d407bb3788d66fba",
"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/splinecoeffs.h",
"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/splinecoeffs.h",
"max_line_length": 107,
"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/splinecoeffs.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 653,
"size": 2506
} |
#pragma once
#include <Windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <cassert>
#include <cstdarg>
#include <climits>
#include <cinttypes>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <any>
#include <array>
#include <chrono>
#include <complex>
#include <deque>
#include <exception>
#include <filesystem>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <locale>
#include <memory>
#include <mutex>
#include <new>
#include <numeric>
#include <optional>
#include <random>
#include <ratio>
#include <sstream>
#include <stack>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unordered_set>
#include <utility>
#include <valarray>
#include <vector>
#include <gsl/gsl>
| {
"alphanum_fraction": 0.7318435754,
"avg_line_length": 16.8867924528,
"ext": "h",
"hexsha": "51932140d4e3e018bb648ef7c5ffe42073128e3d",
"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": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lopezfjose/Digger",
"max_forks_repo_path": "digger/Digger.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c",
"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": "lopezfjose/Digger",
"max_issues_repo_path": "digger/Digger.h",
"max_line_length": 24,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "434aeb02fad1ba00ba05ca52ebcf7694b2397a3c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lopezfjose/Digger",
"max_stars_repo_path": "digger/Digger.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 203,
"size": 895
} |
#include "common/c_math/gsl_linalg_extra.h"
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_blas_types.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_vector.h>
// TODO(kennyjensen): Remove these and allocate arrays in calling
// library.
#define MAX_VECTOR_SIZE (32U)
#define MAX_MATRIX_SIZE (16U * 16U)
// Solves triangular matrix equations of the form:
//
// op(T) * X = B or X * op(T) = B
//
// using forward or back substitution. For rectangular T
// (i.e. underdetermined or overdetermined systems), this only solves
// the square submatrix of T. For underdetermined systems, the
// remaining elements of X are set to zeros. If the triangular matrix
// T is singular, then this will only solve the part of the matrix up
// to the first zero diagonal element.
//
// Args:
// side: Which side of the multiplication op(T) appears.
// uplo: Whether T is upper or lower triangular.
// transpose: Whether op(.) is a transpose or not.
// T: Triangular matrix (m x n).
// B: Right hand side matrix (m x k).
// X: Solution matrix (n x k).
//
// Returns:
// GSL_ESING if T is singular and GSL_SUCCESS otherwise.
int32_t GslTriangularSolve(CBLAS_SIDE_t side, CBLAS_UPLO_t uplo,
CBLAS_TRANSPOSE_t transpose, const gsl_matrix *T,
const gsl_matrix *B, gsl_matrix *X) {
assert(T != NULL && B != NULL && X != NULL);
assert(T != X && B != X);
assert(side != CblasLeft ||
(X->size2 == B->size2 &&
(transpose == CblasNoTrans ? T->size1 : T->size2) == B->size1 &&
(transpose == CblasNoTrans ? T->size2 : T->size1) == X->size1));
assert(side != CblasRight ||
(X->size1 == B->size1 &&
(transpose == CblasNoTrans ? T->size1 : T->size2) == X->size2 &&
(transpose == CblasNoTrans ? T->size2 : T->size1) == B->size2));
int32_t err = GSL_SUCCESS;
size_t small_dim = (T->size1 < T->size2) ? T->size1 : T->size2;
gsl_matrix_set_zero(X);
// Calling this "rank" here is assuming that the diagonal elements
// of T are in descending order.
size_t rank = small_dim;
for (size_t i = 0U; i < small_dim; ++i) {
if (fabs(gsl_matrix_get(T, i, i)) <= DBL_EPSILON) {
rank = i;
err = GSL_ESING;
break;
}
gsl_vector_const_view row = gsl_matrix_const_row(B, i);
gsl_matrix_set_row(X, i, &row.vector);
}
if (rank == 0U) return err;
// Make a square sub-matrix of T that has all non-zero elements
// along the diagonal and a reduced B matrix with the same number of
// rows.
gsl_matrix_const_view T_rank =
gsl_matrix_const_submatrix(T, 0U, 0U, rank, rank);
gsl_matrix_view X_rank = gsl_matrix_submatrix(X, 0U, 0U, rank, X->size2);
// Solve the triangular system op(T) * X = B or X * op(T) = B.
gsl_blas_dtrsm(side, uplo, transpose, CblasNonUnit, 1.0, &T_rank.matrix,
&X_rank.matrix);
return err;
}
// Converts a trapezoidal matrix R with m < n to a pure upper
// triangular matrix with zeros outside of the square portion of the
// matrix using orthogonal transformations from the right:
//
// R = [T, 0] * Z
//
// Here Z = Z_1 * Z_2 * ... * Z_m with Z_k = I - tau_k * v_k * v_k'
// where v_k is the Householder vector which cancels the
// non-triangular elements of the kth row of T. This is similar to
// the DTZRZF function from LAPACK.
//
// Args:
// R: Right trapezoidal matrix with m < n. This function will
// happily ignore non-zero components in the lower portion of
// the R matrix; however these will also appear in the T matrix.
// T: Upper triangular matrix output (m x n). The "zero" portion of
// the T matrix is used to store the Householder vectors that,
// with tau, form Z.
// tau: Vector of length m of Householder coefficients.
void GslTrapezoidalToTriangular(const gsl_matrix *R, gsl_matrix *T,
gsl_vector *tau) {
assert(R != NULL && T != NULL && tau != NULL);
assert(R->size1 == T->size1 && R->size2 == T->size2);
assert(tau->size == T->size1);
assert(R->size1 > 0U && R->size1 < R->size2);
if (T != R) gsl_matrix_memcpy(T, R);
size_t i_max = R->size1 - 1U;
for (size_t k = 0U; k < R->size1; ++k) {
size_t i = i_max - k;
// hh is used to calculate the Householder vector; however, the
// Household vector itself is only stored in hh1.
gsl_vector_view hh = gsl_matrix_subrow(T, i, i_max, R->size2 - i_max);
gsl_vector_view hh1 =
gsl_matrix_subrow(T, i, R->size1, R->size2 - R->size1);
// GSL assumes that the elements you want to cancel are adjacent
// to the diagonal element, which isn't the case here, so we have
// to swap elements around.
gsl_vector_view row = gsl_matrix_row(T, i);
gsl_vector_swap_elements(&row.vector, i, i_max);
double tau_k = gsl_linalg_householder_transform(&hh.vector);
gsl_vector_set(tau, k, tau_k);
gsl_vector_swap_elements(&row.vector, i, i_max);
// Apply Householder reflections to the right hand side of the
// triangular matrix. We don't apply the reflection to the ith
// row itself because GSL's Householder transform sets the
// diagonal element for us. (Doing this with the
// gsl_linalg_householder_mh function would require swapping
// columns because of assumptions GSL makes about the diagonal
// element being adjacent to the elements that the Householder
// vector cancels.)
for (size_t j = 0U; j < i; ++j) {
gsl_vector_view T_jm =
gsl_matrix_subrow(T, j, R->size1, R->size2 - R->size1);
double alpha, T_ji = gsl_matrix_get(T, j, i);
gsl_blas_ddot(&hh1.vector, &T_jm.vector, &alpha);
alpha += T_ji;
gsl_blas_daxpy(-tau_k * alpha, &hh1.vector, &T_jm.vector);
gsl_matrix_set(T, j, i, -tau_k * alpha + T_ji);
}
}
}
// Applies the inverse of the Householder transformations output by
// GslTrapezoidalToTriangular to the matrix X. More specifically, for
// the matrix Z defined by:
//
// R = [T, 0] * Z
//
// this function applies Z' to the input matrix X.
//
// Args:
// T: The R matrix of a QR decomposition after complete
// orthogonalization. The elements that should be zero from the
// QR decomposition are ignored. The elements that should be
// zero from the complete orthogonalization must contain the
// Householder vectors used in the orthogonalization.
// tau: The factors to multiply the Householder vectors by which is
// output by the GslTrapezoidalToTriangular function.
// X: The input matrix to which we apply Z'.
// Zt_X: Output matrix with Householder transformations applied Z' * X.
void GslTrapezoidalToTriangularZTMat(const gsl_matrix *T, const gsl_vector *tau,
const gsl_matrix *X, gsl_matrix *Zt_X) {
assert(X != NULL && tau != NULL && Zt_X != NULL && T != NULL);
assert(T != X && T != Zt_X);
assert(T->size1 == tau->size && T->size2 == X->size1);
assert(X->size1 == Zt_X->size1 && X->size2 == Zt_X->size2);
assert(T->size1 <= T->size2);
if (X != Zt_X) gsl_matrix_memcpy(Zt_X, X);
for (size_t i = 0U; i < T->size1; ++i) {
// Grab the Householder vector from the columns past the square
// section of the T matrix.
gsl_vector_const_view hh1 =
gsl_matrix_const_subrow(T, i, T->size1, T->size2 - T->size1);
// Apply Householder reflections to the left hand side of X.
// (Doing this with the gsl_linalg_householder_hm function would
// require swapping rows because of assumptions GSL makes about
// the diagonal element being adjacent to the elements that the
// Householder vector cancels.)
//
// TODO(kennyjensen): If we need this non-standard
// gsl_linalg_householder_hm in other places, we should make a
// helper function.
double tau_k = gsl_vector_get(tau, T->size1 - i - 1U);
for (size_t j = 0U; j < Zt_X->size2; ++j) {
gsl_vector_view Zt_X_mj =
gsl_matrix_subcolumn(Zt_X, j, T->size1, T->size2 - T->size1);
double alpha, Zt_X_ij = gsl_matrix_get(Zt_X, i, j);
gsl_blas_ddot(&hh1.vector, &Zt_X_mj.vector, &alpha);
alpha += Zt_X_ij;
gsl_blas_daxpy(-tau_k * alpha, &hh1.vector, &Zt_X_mj.vector);
gsl_matrix_set(Zt_X, i, j, -tau_k * alpha + Zt_X_ij);
}
}
}
// Left or right matrix divide. Finds a solution, X, to the equations
// A*X = B or X*A = B for left and right divide respectively. If the
// system is overdetermined or underdetermined, then this returns a
// least-squares solution that minimizes |A*X - B| or |X*A - B|,
// similar to MATLAB's "\" or "/" operators. The solution is found
// using QR decomposition with column pivoting followed by back
// substitution. For matrix left divide, the solution proceeds as:
//
// A*X = B
// Q*R*P' * X = B
// R * P'*X = Q'*B
//
// For matrix right divide, the solution proceeds as:
//
// X*A = B
// A'*X' = B'
// Q*R*P' * X' = B'
// R * (X*P)' = Q'*B'
//
// Args:
// side: CblasLeft or CblasRight for left or right divide.
// A: Left hand side matrix.
// B: Right hand side matrix.
// X: Solution matrix.
//
// Returns:
// GSL_ESING A is rank deficient and thus the R matrix is singular and
// GSL_SUCCESS otherwise.
int32_t GslMatrixDivide(CBLAS_SIDE_t side, const gsl_matrix *A,
const gsl_matrix *B, gsl_matrix *X) {
assert(A != NULL && B != NULL && X != NULL);
assert(A != X && B != X);
assert(side != CblasLeft || (A->size1 == B->size1 && A->size2 == X->size1 &&
X->size2 == B->size2));
assert(side != CblasRight || (A->size2 == B->size2 && A->size1 == X->size2 &&
X->size1 == B->size1));
assert(A->size1 <= MAX_VECTOR_SIZE && A->size2 <= MAX_VECTOR_SIZE);
assert(A->size1 * A->size2 <= MAX_MATRIX_SIZE);
assert(B->size1 * B->size2 <= MAX_MATRIX_SIZE);
assert(X->size1 * X->size2 <= MAX_MATRIX_SIZE);
int32_t err = GSL_SUCCESS;
size_t m = (side == CblasLeft) ? A->size1 : A->size2;
size_t n = (side == CblasLeft) ? A->size2 : A->size1;
size_t k = (side == CblasLeft) ? B->size2 : B->size1;
// Allocate workspace variables.
double workspace[MAX_MATRIX_SIZE];
double qr_data[MAX_MATRIX_SIZE];
double tau_data[MAX_VECTOR_SIZE];
size_t perm_data[MAX_VECTOR_SIZE];
int signum;
// Decompose op(A) into Q*R*P'.
gsl_matrix_view QR = gsl_matrix_view_array(qr_data, m, n);
gsl_vector_view tau = gsl_vector_view_array(tau_data, m < n ? m : n);
gsl_permutation p = {n, perm_data};
gsl_vector_view norm = gsl_vector_view_array(workspace, n);
if (side == CblasLeft) {
gsl_matrix_memcpy(&QR.matrix, A);
} else {
gsl_matrix_transpose_memcpy(&QR.matrix, A);
}
gsl_linalg_QRPT_decomp(&QR.matrix, &tau.vector, &p, &signum, &norm.vector);
// Calculate Q'*op(B) matrix.
gsl_matrix_view Qt_opB = gsl_matrix_view_array(workspace, m, k);
if (side == CblasLeft) {
gsl_matrix_memcpy(&Qt_opB.matrix, B);
} else {
gsl_matrix_transpose_memcpy(&Qt_opB.matrix, B);
}
gsl_linalg_QR_QTmat(&QR.matrix, &tau.vector, &Qt_opB.matrix);
// Determine the rank of the R matrix.
//
// TODO(tobenkin): DGELSY uses a different iterative condition
// number estimation technique to determine the rank of the
// submatrix R(1:rank, 1:rank). See http://www.netlib.org/lapack/
// lapack-3.1.1/html/dgelsy.f.html#DGEQP3.269.
double R_00 = fabs(gsl_matrix_get(&QR.matrix, 0U, 0U));
uint32_t rank = 0U;
if (R_00 > DBL_EPSILON) {
for (rank = 1U; rank < m && rank < n; ++rank) {
if (fabs(gsl_matrix_get(&QR.matrix, rank, rank)) < 1e-9 * R_00) {
err = GSL_ESING;
break;
}
}
} else {
gsl_matrix_set_zero(X);
return GSL_ESING;
}
// Solve the triangular system R * Z * P' * op(X) = Q' * op(B) and
// multiply the solution by Z' to get P' * op(X).
gsl_matrix_view Z_Pt_opX = gsl_matrix_view_array(X->data, n, k);
gsl_matrix_set_zero(&Z_Pt_opX.matrix);
// For underdetermined or rank deficient matrices, use complete
// orthogonalization to provide the minimal 2-norm solution.
gsl_vector_view tau_trap = gsl_vector_view_array(tau_data, rank);
gsl_matrix_view QR_trap = gsl_matrix_submatrix(&QR.matrix, 0U, 0U, rank, n);
if (rank < n) {
GslTrapezoidalToTriangular(&QR_trap.matrix, &QR_trap.matrix,
&tau_trap.vector);
}
// Solve the non-singular square triangular system.
gsl_matrix_const_view QR_rank =
gsl_matrix_const_submatrix(&QR.matrix, 0U, 0U, rank, rank);
gsl_matrix_const_view Qt_opB_rank =
gsl_matrix_const_submatrix(&Qt_opB.matrix, 0U, 0U, rank, k);
gsl_matrix_view Z_Pt_opX_rank =
gsl_matrix_submatrix(&Z_Pt_opX.matrix, 0U, 0U, rank, k);
gsl_matrix_memcpy(&Z_Pt_opX_rank.matrix, &Qt_opB_rank.matrix);
gsl_blas_dtrsm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0,
&QR_rank.matrix, &Z_Pt_opX_rank.matrix);
// For full-rank square and overdetermined matrices, Z = I.
if (rank < n) {
GslTrapezoidalToTriangularZTMat(&QR_trap.matrix, &tau_trap.vector,
&Z_Pt_opX.matrix, &Z_Pt_opX.matrix);
}
// Apply the permutation matrix to get op(X).
for (uint32_t i = 0U; i < k; ++i) {
gsl_vector_view col = gsl_matrix_column(&Z_Pt_opX.matrix, i);
gsl_permute_vector_inverse(&p, &col.vector);
}
if (side == CblasRight) {
// We can't transpose within the same memory, hence the
// unfortunate extra memcpy.
gsl_matrix_view X_copy = gsl_matrix_view_array(qr_data, k, n);
gsl_matrix_transpose_memcpy(&X_copy.matrix, &Z_Pt_opX.matrix);
gsl_matrix_memcpy(X, &X_copy.matrix);
}
return err;
}
| {
"alphanum_fraction": 0.6534667723,
"avg_line_length": 39.4573863636,
"ext": "c",
"hexsha": "f7a64ccc627d6129cd8f8535b38cdeb58cd705c0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-20T21:04:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-13T11:39:01.000Z",
"max_forks_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "OpenFAST/KiteFAST",
"max_forks_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"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": "OpenFAST/KiteFAST",
"max_issues_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c",
"max_line_length": 80,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "OpenFAST/KiteFAST",
"max_stars_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-16T10:13:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-22T18:21:36.000Z",
"num_tokens": 4108,
"size": 13889
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_randist.h>
#include "allvars.h"
#include "proto.h"
void mcmc_conline_run()
{
double aicc, chi2, aicc_best;
double *theta_best_this, *theta_best_var_this;
char fname_mcmc[100];
aicc_best = DBL_MAX;
theta_best_this = malloc(ntheta_max*sizeof(double));
theta_best_var_this = malloc(ntheta_max*2*sizeof(double));
printf("*******con-line mcmc\n");
if(flag_mcmc==1)
{
fprintf(fp_results, "************AICC************\n");
for(nc = nc_lim_low; nc<=nc_lim_up; nc++)
{
printf("nc = %d\n", nc);
sprintf(fname_mcmc, "data/mcmc_%02d.txt", nc);
mcmc_conline_init();
mcmc_sampling(fname_mcmc, &probability_conline);
mcmc_stats(fname_mcmc);
aicc = cal_aicc();
if(aicc < aicc_best)
{
aicc_best = aicc;
nc_best = nc;
memcpy(theta_best_this, theta_best, ntheta * sizeof(double));
memcpy(theta_best_var_this, theta_best_var, ntheta * 2 * sizeof(double));
}
printf("aicc: %d %f\n", nc, aicc);
fprintf(fp_results, "aicc: %d %f\n", nc, aicc);
}
}
else
{
printf("reading par.txt\n");
nc = nc_best = nc_lim_low;
sprintf(fname_mcmc, "data/mcmc_%02d.txt", nc);
mcmc_conline_init();
read_input();
memcpy(theta_best_this, theta_best, ntheta * sizeof(double));
memcpy(theta_best_var_this, theta_best_var, ntheta * 2 * sizeof(double));
}
printf("*******finish mcmc\n");
fprintf(fp_results, "************Best Estimate************\n");
fprintf(fp_results, "best nc: %d\n", nc_best);
printf("best nc: %d\n", nc_best);
nc = nc_best;
memcpy(theta_best, theta_best_this, ntheta * sizeof(double));
memcpy(theta_best_var, theta_best_var_this, ntheta * 2 * sizeof(double));
mcmc_conline_init(); // reset the grid of tau
reconstruct_conline();
transfer_function(theta_best);
aicc = cal_aicc();
chi2 = chi_square();
line_convolution();
fprintf(fp_results, "aicc: %f\n", aicc);
fprintf(fp_results, "chi2: %f\n", chi2);
free(theta_best_this);
free(theta_best_var_this);
}
void mcmc_conline_init()
{
int i, j;
#ifdef JAVELIN // only one-tophat is used in JAVELIN
ntheta = 2 + 3 + 1;
theta_range[0][0] = log(1.0e-6); // sigma in DRW
theta_range[0][1] = log(10.0); //
theta_range[1][0] = log(1.0e-2); // tau in DRW
theta_range[1][1] = log(1.0e5);
theta_range[2][0] = (tau_lim_up - tau_lim_low)/1000.0; // width of tophat
theta_range[2][1] = (tau_lim_up - tau_lim_low)*10.0;
theta_range[3][0] = 0.0; // height of tophat
theta_range[3][1] = 1.0e3;
theta_range[4][0] = tau_lim_low; //central value of tophat
theta_range[4][1] = tau_lim_up;
theta_range[5][0] = log(1.0e-5); // systematic error
theta_range[5][1] = log(1.0e6);
i = 0;
sigma_input[i++] = 0.01; // sigma
sigma_input[i++] = 0.01; // taud
sigma_input[i++] = 0.01; // width
sigma_input[i++] = 0.1; // fk
sigma_input[i++] = 0.1; // tauc
sigma_input[i++] = 0.1;
theta_input[0] = theta_best[0];
theta_input[1] = theta_best[1];
theta_input[2] = (tau_lim_up-tau_lim_low)/5.0;
theta_input[3] = 1.0;
theta_input[4] = (tau_lim_up-tau_lim_low)/2.0;
theta_input[5] = log(10.0);
#else
ntheta = nc + 3 + 1;
// grid of time lag
for(i=0; i<nc; i++)
{
grid_tau[i] = (tau_lim_up-tau_lim_low)/(nc-1.0) * i + tau_lim_low;
}
// limit range for parameters
i=0;
theta_range[i][0] = log(1.0e-6);
theta_range[i++][1] = log(10.0);
theta_range[i][0] = log(1.0);
theta_range[i++][1] = log(1.0e4);
theta_range[i][0] = (tau_lim_up - tau_lim_low)/(nc-1.0)/2.0;
theta_range[i++][1] = (tau_lim_up - tau_lim_low)/(nc-1.0);
for(j=0; j<nc; j++)
{
theta_range[i][0] = log(1.0e-10);
theta_range[i++][1] = log(100.0);
}
theta_range[i][0] = log(1.0e-5);
theta_range[i++][1] = log(1.0e6);
/* input step sizes for mcmc sampling */
i = 0;
sigma_input[i++] = 0.01; // sigma
sigma_input[i++] = 0.01; // taud
sigma_input[i++] = 0.01; // width
for(j=0; j<nc; j++)
{
sigma_input[i++] = 0.1; // fk
}
sigma_input[i++] = 0.1; // systematic error
/* input values for parameters */
theta_input[0] = theta_best[0];
theta_input[1] = theta_best[1];
theta_input[2] = (tau_lim_up-tau_lim_low)/(nc-1.0)/2.0;
for(i=0; i<nc; i++)
{
theta_input[3+i] = log(1.0/nc);
}
theta_input[3 + nc] = log(10.0);
#endif
/* set if the parameters are fixed */
for(i=0; i<ntheta; i++)
{
theta_fixed[i] = 0;
}
/* for TOPHAT case, the width is fixed */
#ifdef TOPHAT
theta_fixed[2] = 1;
#endif
}
/* theta represets sigma, tuad, and the parameters for transfer function */
double probability_conline(double *theta)
{
double prob, prior, lndet_C, lndet_ICq, sigma, taud;
double *Larr, *ybuf, *Cq, *ICq, *ave, *ysub, *yrec, *yrec_err, *yave;
int i, nq, info, sign_C, sign_Cq;
taud = exp(theta[1]);
sigma = exp(theta[0]) * sqrt(taud/2.0);
nq = (flag_detrend + 1)*2;
Larr = workspace;
ybuf = Larr + nq*nall_data;
Cq = ybuf + nall_data;
ICq = Cq + nq*nq;
ave = ICq + nq*nq;
ysub = ave + nq;
yrec = ysub + nall_data;
yrec_err = yrec + nall_data;
yave = yrec_err + nall_data;
set_covar_mat(theta);
for(i=0; i<nall_data*nall_data; i++)
{
Cmat[i] = Smat[i] + Nmat[i];
}
for(i=0; i<ncon_data; i++)
{
if(flag_detrend==0)
{
Larr[i*nq+0] = 1.0;
Larr[i*nq+1] = 0.0;
}
else
{
Larr[i*nq + 0] = 1.0;
Larr[i*nq + 1] = Tcon_data[i];
Larr[i*nq + 2] = 0.0;
Larr[i*nq + 3] = 0.0;
}
}
for(i=0; i<nline_data; i++)
{
if(flag_detrend==0)
{
Larr[(i+ncon_data)*nq+0] = 0.0;
Larr[(i+ncon_data)*nq+1] = 1.0;
}
else
{
Larr[(i+ncon_data)*nq + 0] = 0.0;
Larr[(i+ncon_data)*nq + 1] = 0.0;
Larr[(i+ncon_data)*nq + 2] = 1.0;
Larr[(i+ncon_data)*nq + 3] = Tline_data[i];
}
}
// cal q
memcpy(Tmat1, Cmat, nall_data*nall_data*sizeof(double));
memcpy(Tmat2, Larr, nall_data*nq*sizeof(double));
//printf("FFFF\n");
//display_mat(Tmat1, 1, nall_data);
multiply_mat_MN_inverseA(Tmat1, Tmat2, nall_data, nq); // Tmat2 = C^-1 * L
multiply_mat_MN_transposeA(Larr, Tmat2, ICq, nq, nq, nall_data); // ICq = L^T*C^-1*L
multiply_mat_MN_transposeA(Tmat2, Fall_data, ave, nq, 1, nall_data); // ave = L^T*C^-1*y
memcpy(Tmat1, ICq, nq*nq*sizeof(double));
multiply_mat_MN_inverseA(Tmat1, ave, nq, 1); // (L^T*C^-1*L)^-1 * L^T*C^-1*y
multiply_mat_MN(Larr, ave, yave, nall_data, 1, nq);
for(i=0; i<nall_data; i++)ysub[i] = Fall_data[i] - yave[i];
memcpy(Tmat1, Cmat, nall_data*nall_data*sizeof(double));
memcpy(ybuf, ysub, nall_data*sizeof(double));
multiply_mat_MN_inverseA(Tmat1, ybuf, nall_data, 1);
prob = -0.5*cblas_ddot(nall_data, ysub, 1, ybuf, 1) / (sigma*sigma);
//printf("%f\n", prob);
if(prob > 0.0 ) // check if prob is positive
{
prob = -1.0e10;
printf("prob >0!\n");
return prob;
}
//memcpy(Tmat1, Cmat, n_data*nall_data*sizeof(double));
lndet_C = lndet_mat3(Cmat, nall_data, &info, &sign_C) + 2.0*nall_data * log(sigma);
if(info!=0|| sign_C==-1)
{
prob = -1.0e10;
printf("lndet_C %f %d!\n", lndet_C, sign_C);
return prob;
}
//memcpy(Tmat1, ICq, nq*nq*sizeof(double));
lndet_ICq = lndet_mat3(ICq, nq, &info, &sign_Cq) - 2.0*nq*log(sigma);
if(info!=0 || sign_Cq==-1 )
{
prob = -1.0e10;
printf("lndet_ICq!\n");
return prob;
}
prob -= 0.5*(lndet_C + lndet_ICq);
prior = 0.0;
// for sigmad
if( theta[0] < theta_best_con[0])
{
prior += -0.5*pow(theta[0] - theta_best_con[0], 2.0)/pow(theta_best_var_con[0*2], 2.0);
}
else
{
prior += -0.5*pow(theta[0] - theta_best_con[0], 2.0)/pow(theta_best_var_con[0*2+1], 2.0);
}
// for taud
if( theta[1] < theta_best_con[1])
{
prior += -0.5*pow(theta[1] - theta_best_con[1], 2.0)/pow(theta_best_var_con[1*2], 2.0);
}
else
{
prior += -0.5*pow(theta[1] - theta_best_con[1], 2.0)/pow(theta_best_var_con[1*2+1], 2.0);
}
//penalize very large tau or very small tau
/* if(theta[1] > log(len_con) )
{
prior += (log(len_con) - theta[1])/fabs(log(cad_con));
}
if(theta[1] < log(cad_con))
{
prior += (theta[1] - log(cad_con) ) / fabs(log(cad_con));
}*/
prob += prior;
return prob;
}
double cal_aicc()
{
double prob, aic, aicc;
int k, n;
k = nc + 4;
n = nall_data;
prob = probability_conline_aicc(theta_best);
aic = 2.0*k - 2.0*prob;
aicc = aic + 2.0*k*(k+1.0)/(n - k - 1.0);
//printf("aicc: %d %f %f\n", nc, aicc, prob);
return aicc;
}
double probability_conline_aicc(double *theta)
{
double prob, lndet_C, lndet_ICq, sigma, taud;
double *Larr, *ybuf, *Cq, *ICq, *ave, *ysub, *yrec, *yrec_err, *yave;
int i, nq, info, sign_C, sign_Cq;
taud = exp(theta[1]);
sigma = exp(theta[0]) * sqrt(taud/2.0);
nq = (flag_detrend + 1)*2;
Larr = workspace;
ybuf = Larr + nq*nall_data;
Cq = ybuf + nall_data;
ICq = Cq + nq*nq;
ave = ICq + nq*nq;
ysub = ave + nq;
yrec = ysub + nall_data;
yrec_err = yrec + nall_data;
yave = yrec_err + nall_data;
set_covar_mat(theta);
for(i=0; i<nall_data*nall_data; i++)
{
Cmat[i] = Smat[i] + Nmat[i];
}
for(i=0; i<ncon_data; i++)
{
if(flag_detrend==0)
{
Larr[i*nq+0] = 1.0;
Larr[i*nq+1] = 0.0;
}
else
{
Larr[i*nq + 0] = 1.0;
Larr[i*nq + 1] = Tcon_data[i];
Larr[i*nq + 2] = 0.0;
Larr[i*nq + 3] = 0.0;
}
}
for(i=0; i<nline_data; i++)
{
if(flag_detrend==0)
{
Larr[(i+ncon_data)*nq+0] = 0.0;
Larr[(i+ncon_data)*nq+1] = 1.0;
}
else
{
Larr[(i+ncon_data)*nq + 0] = 0.0;
Larr[(i+ncon_data)*nq + 1] = 0.0;
Larr[(i+ncon_data)*nq + 2] = 1.0;
Larr[(i+ncon_data)*nq + 3] = Tline_data[i];
}
}
// cal q
memcpy(Tmat1, Cmat, nall_data*nall_data*sizeof(double));
memcpy(Tmat2, Larr, nall_data*nq*sizeof(double));
//printf("FFFF\n");
//display_mat(Tmat1, 1, nall_data);
multiply_mat_MN_inverseA(Tmat1, Tmat2, nall_data, nq); // Tmat2 = C^-1 * L
multiply_mat_MN_transposeA(Larr, Tmat2, ICq, nq, nq, nall_data); // ICq = L^T*C^-1*L
multiply_mat_MN_transposeA(Tmat2, Fall_data, ave, nq, 1, nall_data); // ave = L^T*C^-1*y
memcpy(Tmat1, ICq, nq*nq*sizeof(double));
multiply_mat_MN_inverseA(Tmat1, ave, nq, 1); // (L^T*C^-1*L)^-1 * L^T*C^-1*y
multiply_mat_MN(Larr, ave, yave, nall_data, 1, nq);
for(i=0; i<nall_data; i++)ysub[i] = Fall_data[i] - yave[i];
memcpy(Tmat1, Cmat, nall_data*nall_data*sizeof(double));
memcpy(ybuf, ysub, nall_data*sizeof(double));
multiply_mat_MN_inverseA(Tmat1, ybuf, nall_data, 1);
prob = -0.5*cblas_ddot(nall_data, ysub, 1, ybuf, 1) / (sigma*sigma);
//printf("%f\n", prob);
if(prob > 0.0 ) // check if prob is positive
{
prob = -1.0e10;
printf("prob >0!\n");
return prob;
}
//memcpy(Tmat1, Cmat, n_data*nall_data*sizeof(double));
lndet_C = lndet_mat3(Cmat, nall_data, &info, &sign_C) + 2.0*nall_data * log(sigma);
if(info!=0|| sign_C==-1)
{
prob = -1.0e10;
printf("lndet_C %f %d!\n", lndet_C, sign_C);
return prob;
}
//memcpy(Tmat1, ICq, nq*nq*sizeof(double));
lndet_ICq = lndet_mat3(ICq, nq, &info, &sign_Cq) - 2.0*nq*log(sigma);
if(info!=0 || sign_Cq==-1 )
{
prob = -1.0e10;
printf("lndet_ICq!\n");
return prob;
}
prob -= 0.5*(lndet_C + lndet_ICq);
return prob;
}
double chi_square()
{
double chi2, sigma, taud;
double *Larr, *ybuf, *Cq, *ICq, *ave, *ysub, *yrec, *yrec_err, *yave;
int i, nq, info;
taud = exp(theta_best[1]);
sigma = exp(theta_best[0]) * sqrt(taud/2.0);
nq = 2*(flag_detrend + 1);
Larr = workspace;
ybuf = Larr + nq*nall_data;
Cq = ybuf + nall_data;
ICq = Cq + nq*nq;
ave = ICq + nq*nq;
ysub = ave + nq;
yrec = ysub + nall_data;
yrec_err = yrec + nall_data;
yave = yrec_err + nall_data;
set_covar_mat(theta_best);
for(i=0; i<nall_data*nall_data; i++)
{
Cmat[i] = Smat[i] + Nmat[i];
}
for(i=0; i<ncon_data; i++)
{
if(flag_detrend==0)
{
Larr[i*nq+0] = 1.0;
Larr[i*nq+1] = 0.0;
}
else
{
Larr[i*nq + 0] = 1.0;
Larr[i*nq + 1] = Tcon_data[i];
Larr[i*nq + 2] = 0.0;
Larr[i*nq + 3] = 0.0;
}
}
for(i=0; i<nline_data; i++)
{
if(flag_detrend==0)
{
Larr[(i+ncon_data)*nq+0] = 0.0;
Larr[(i+ncon_data)*nq+1] = 1.0;
}
else
{
Larr[(i+ncon_data)*nq + 0] = 0.0;
Larr[(i+ncon_data)*nq + 1] = 0.0;
Larr[(i+ncon_data)*nq + 2] = 1.0;
Larr[(i+ncon_data)*nq + 3] = Tline_data[i];
}
}
memcpy(ICmat, Cmat, nall_data*nall_data*sizeof(double));
inverse_mat(ICmat, nall_data, &info);
multiply_mat_MN(ICmat, Larr, Tmat1, nall_data, nq, nall_data);
multiply_mat_MN_transposeA(Larr, Tmat1, ICq, nq, nq, nall_data);
memcpy(Cq, ICq, nq*nq*sizeof(double));
inverse_mat(Cq, nq, &info);
multiply_mat_MN_transposeA(Larr, ICmat, Tmat1, nq, nall_data, nall_data);
multiply_mat_MN(Cq, Tmat1, Tmat2, nq, nall_data, nq);
multiply_mat_MN(Tmat2, Fall_data, ave, nq, 1, nall_data);
multiply_mat_MN(Larr, ave, yave, nall_data, 1, nq);
for(i=0; i<nall_data; i++)ysub[i] = Fall_data[i] - yave[i];
multiply_matvec(ICmat, ysub, nall_data, ybuf);
multiply_matvec_MN(Smat, nall_data, nall_data, ybuf, yrec);
for(i=0; i<nall_data; i++)yrec[i] += yave[i];
multiply_mat_MN(Smat, ICmat, Tmat1, nall_data, nall_data, nall_data);
multiply_mat_MN_transposeB(Tmat1, Smat, Tmat2, nall_data, nall_data, nall_data);
multiply_mat_MN(Tmat1, Larr, Tmat3, nall_data, nq, nall_data);
for(i=0; i<nall_data*nq; i++)Tmat3[i] -= Larr[i];
multiply_mat_MN(Tmat3, Cq, Tmat1, nall_data, nq, nq);
multiply_mat_MN_transposeB(Tmat1, Tmat3, Tmat4, nall_data, nall_data, nq);
for(i=0; i<nall_data; i++)
{
yrec_err[i] = sigma*sqrt((Smat[i*nall_data+i] - Tmat2[i*nall_data+i] + Tmat4[i*nall_data+i]));
}
FILE *fp;
fp = fopen("data/tmp.txt", "w");
for(i=0; i<ncon_data; i++)
{
fprintf(fp, "%f %f %f\n", Tcon_data[i], yrec[i]*scale_con, yrec_err[i]*scale_con);
}
fprintf(fp, "\n");
for(i=ncon_data; i<nall_data; i++)
{
fprintf(fp, "%f %f %f\n", Tline_data[i-ncon_data], yrec[i]*scale_line, yrec_err[i]*scale_line);
}
fclose(fp);
chi2 = 0.0;
for(i=0; i<ncon_data; i++)chi2 += pow(Fcon_data[i] - yrec[i], 2)
/( pow(Fcerrs_data[i], 2) );
for(i=ncon_data; i<nall_data; i++) chi2 += pow(Fline_data[i-ncon_data] - yrec[i], 2)
/( pow(Flerrs_data[i-ncon_data], 2) );
printf("chi2: %f\n", chi2/(nall_data-ntheta));
return chi2/(nall_data - ntheta);
}
void set_covar_mat(double *theta)
{
double t1, t2, nerr, syserr;
double taud, sigma;
int i, j;
//alpha = 1.0;
taud = exp(theta[1]);
sigma = exp(theta[0]) * sqrt(taud/2.0);
syserr = exp(theta[ntheta-1]);
// first con-con
for(i=0; i<ncon_data; i++)
{
t1 = Tcon_data[i];
for(j=0; j<i; j++)
{
t2 = Tcon_data[j];
Smat[i*nall_data+j] = Smat[j*nall_data+i] = exp( - fabs(t2-t1)/taud );
Nmat[i*nall_data+j] = Nmat[j*nall_data+i] = 0.0;
}
nerr = Fcerrs_data[i];
Nmat[i*nall_data+i] = (nerr*nerr + syserr*syserr)/(sigma*sigma);
Smat[i*nall_data+i] = 1.0;
}
// then con-line and line-con
for(i=0; i<ncon_data; i++)
{
t1 = Tcon_data[i];
for(j=0; j<nline_data; j++)
{
t2 = Tline_data[j];
Smat[ i*nall_data + (ncon_data+j)] = Smat[(j+ncon_data)*nall_data + i] = Slc(t1, t2, theta);
Nmat[ i*nall_data + (ncon_data+j)] = Nmat[(j+ncon_data)*nall_data + i] = 0.0;
}
}
/*// then line-con
for(i=0; i<nline_data; i++)
{
t1 = Tline_data[i];
for(j=0; j<ncon_data; j++)
{
t2 = Tcon_data[j];
Smat[ (i+ncon_data)*n_data + j] = Slc(t2, t1, theta);
Nmat[ (i+ncon_data)*n_data + j] = 0.0;
}
} */
// then line-line
for(i=0; i<nline_data; i++)
{
t1 = Tline_data[i];
for(j=0; j<i; j++)
{
t2 = Tline_data[j];
Smat[ (i+ncon_data)*nall_data + (ncon_data+j)] = Smat[ (j+ncon_data)*nall_data + (ncon_data+i)] = Sll(t1, t2, theta);
Nmat[ (i+ncon_data)*nall_data + (ncon_data+j)] = Nmat[ (j+ncon_data)*nall_data + (ncon_data+i)] = 0.0;
}
nerr = Flerrs_data[i];
Nmat[ (i+ncon_data)*nall_data + (ncon_data+i) ] = (nerr * nerr + syserr*syserr)/(sigma*sigma);
Smat[ (i+ncon_data)*nall_data + (ncon_data+i) ] = Sll(t1, t1, theta);
}
}
void set_covar_Umat(double *theta)
{
double t1, t2, taud;
int i, j;
taud = exp(theta[1]);
//sigma = exp(theta[0]) * sqrt(taud/2.0);
for(i=0; i<ncon; i++)
{
t1 = Tcon[i];
for(j=0; j<ncon_data; j++)
{
t2 = Tcon_data[j];
USmat[i*nall_data+j] = exp (- fabs(t1-t2) / taud );
}
for(j=0; j<nline_data; j++)
{
t2 = Tline_data[j];
USmat[i*nall_data + (ncon_data+j)] = Slc(t1, t2, theta);
}
}
for(i=0; i<nline; i++)
{
t1 = Tline[i];
for(j=0; j<ncon_data; j++)
{
t2 = Tcon_data[j];
USmat[ (i+ncon)*nall_data + j] = Slc(t2, t1, theta);
}
for(j=0; j<nline_data; j++)
{
t2 = Tline_data[j];
USmat[ (i+ncon)*nall_data + (ncon_data+j)] = Sll(t1, t2, theta);
}
}
return;
}
void set_covar_Amat(double *theta)
{
double t1, t2, taud;
int i, j;
taud = exp(theta[1]);
//sigma = exp(theta[0]) * sqrt(taud/2.0);
for(i=0; i<ncon; i++)
{
t1 = Tcon[i];
for(j=0; j<ncon; j++)
{
t2 = Tcon[j];
ASmat[i*nall+j] = exp (- fabs(t1-t2) / taud );
}
for(j=0; j<nline; j++)
{
t2 = Tline[j];
ASmat[i*nall + (ncon+j)] = Slc(t1, t2, theta);
}
}
for(i=0; i<nline; i++)
{
t1 = Tline[i];
for(j=0; j<ncon; j++)
{
t2 = Tcon[j];
ASmat[ (i+ncon)*nall + j] = Slc(t2, t1, theta);
}
for(j=0; j<nline; j++)
{
t2 = Tline[j];
ASmat[ (i+ncon)*nall + (ncon+j)] = Sll(t1, t2, theta);
}
}
return;
}
double Slc(double tcon, double tline, double *theta)
{
double Dt, DT, w, tauk, fk, Sk, Stot, taud;
int i;
Dt = tline - tcon;
taud = exp(theta[1]);
w = theta[2];
Stot = 0.0;
#ifdef TOPHAT
for(i=0; i<nc; i++)
{
tauk = grid_tau[i]; //theta[3+nc+i];
fk = exp(theta[3+i]);
DT = Dt - tauk;
if(DT < -w)
{
Sk = exp( (DT + w) / taud ) - exp( (DT - w)/taud);
}
else if(DT < w)
{
Sk = 2.0 - exp(- (DT + w) / taud) - exp( (DT - w)/taud);
}
else
{
Sk = exp( - (DT - w)/taud) - exp ( - (DT + w)/taud);
}
Stot += fk * Sk;
}
Stot *= (taud/2.0/w);
#elif defined JAVELIN
tauk = theta[4]; //theta[3+nc+i];
fk = theta[3];
DT = Dt - tauk;
if(DT < -w)
{
Sk = exp( (DT + w) / taud ) - exp( (DT - w)/taud);
}
else if(DT < w)
{
Sk = 2.0 - exp(- (DT + w) / taud) - exp( (DT - w)/taud);
}
else
{
Sk = exp( - (DT - w)/taud) - exp ( - (DT + w)/taud);
}
Stot = fk * Sk;
Stot *= (taud/2.0/w);
#else
for(i=0; i<nc; i++)
{
tauk = grid_tau[i]; //theta[3+nc+i];
fk = exp(theta[3+i]);
DT = Dt - tauk;
Sk = exp(-DT/taud) * erfc( -(DT/w - w/taud)/sqrt(2.0) )
+exp( DT/taud) * erfc( (DT/w + w/taud)/sqrt(2.0) );
Stot += Sk * fk;
}
Stot *= 1.0/2.0 * exp(w*w/2.0/taud/taud);
#endif
return Stot;
}
double Sll(double ti, double tj, double *theta)
{
double Dt, DT, w, tauk, fk, taum, fm, Skm, Stot, taud;
int k, m;
Dt = ti - tj;
taud = exp(theta[1]);
w = theta[2];
Stot = 0.0;
#ifdef TOPHAT
for(k=0; k<nc; k++)
{
tauk = grid_tau[k]; //theta[3+nc+k];
fk = exp(theta[3+k]);
for(m=0; m<nc; m++)
{
taum = grid_tau[m]; //theta[3+nc+m];
fm = exp(theta[3+m]);
DT = Dt - (tauk-taum);
if(DT < -2.0*w)
{
Skm = exp((DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(DT/taud);
}
else if(DT < 0.0)
{
Skm = exp(-(DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(DT/taud) + 2.0*(DT+2.0*w)/taud;
}
else if(DT < 2.0*w)
{
Skm = exp(-(DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(-DT/taud) - 2.0*(DT-2.0*w)/taud;
}
else
{
Skm = exp( -(DT + 2.0*w)/taud) + exp(-(DT - 2.0*w)/taud) - 2.0*exp(-DT/taud);
}
Stot += fk*fm*Skm;
}
}
Stot *= (taud*taud/4.0/w/w);
#elif defined JAVELIN
for(k=0; k<1; k++)
{
tauk = theta[3+k+1]; //theta[3+nc+k];
fk = theta[3+k];
for(m=0; m<1; m++)
{
taum = theta[3+m+1]; //theta[3+nc+m];
fm = theta[3+m];
DT = Dt - (tauk-taum);
if(DT < -2.0*w)
{
Skm = exp((DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(DT/taud);
}
else if(DT < 0.0)
{
Skm = exp(-(DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(DT/taud) + 2.0*(DT+2.0*w)/taud;
}
else if(DT < 2.0*w)
{
Skm = exp(-(DT + 2.0*w)/taud) + exp((DT - 2.0*w)/taud) - 2.0*exp(-DT/taud) - 2.0*(DT-2.0*w)/taud;
}
else
{
Skm = exp( -(DT + 2.0*w)/taud) + exp(-(DT - 2.0*w)/taud) - 2.0*exp(-DT/taud);
}
Stot += fk*fm*Skm;
}
}
Stot *= (taud*taud/4.0/w/w);
#else
for(k=0; k<nc; k++)
{
tauk = grid_tau[k]; //theta[3+nc+k];
fk = exp(theta[3+k]);
for(m=0; m<nc; m++)
{
taum = grid_tau[m]; //theta[3+nc+m];
fm = exp(theta[3+m]);
DT = Dt - (tauk-taum);
Skm = ( exp(-DT/taud) * erfc( -DT/2.0/w + w/taud )
+ exp( DT/taud) * erfc( DT/2.0/w + w/taud ) );
Stot += Skm * fm*fk;
}
}
Stot *= 1.0/2.0 * exp( w*w/taud/taud);
#endif
return Stot;
}
int reconstruct_conline()
{
FILE *frec;
double *Larr, *Larr_rec, *ave, *yave, *yave_rec, *ysub, *ybuf, *yrec, *yrec_err, *Cq, *ICq;
double *Tmp1, *Tmp2, *Tmp3, *Tmp4;
double sigma, taud;
int i, nq, info;
nq = 2*(flag_detrend + 1);
Larr = array_malloc(nall_data * nq);
Larr_rec = array_malloc(nall * nq);
ybuf = array_malloc(nall_data);
ysub = array_malloc(nall_data);
yave = array_malloc(nall_data);
yave_rec = array_malloc(nall);
yrec = array_malloc(nall);
yrec_err = array_malloc(nall);
ave = array_malloc(nq);
Cq = array_malloc(nq*nq);
ICq = array_malloc(nq*nq);
Tmp1 = array_malloc(max(nall,nall_data)*max(nall,nall_data));
Tmp2 = array_malloc(max(nall,nall_data)*max(nall,nall_data));
Tmp3 = array_malloc(max(nall,nall_data)*max(nall,nall_data));
Tmp4 = array_malloc(max(nall,nall_data)*max(nall,nall_data));
taud = exp(theta_best[1]);
sigma = exp(theta_best[0]) * sqrt(taud/2.0);
set_covar_mat(theta_best);
set_covar_Umat(theta_best);
set_covar_Amat(theta_best);
for(i=0;i<nall_data*nall_data; i++)
{
Cmat[i] = Smat[i] + Nmat[i];
}
memcpy(ICmat, Cmat, nall_data*nall_data*sizeof(double));
inverse_mat(ICmat, nall_data, &info);
for(i=0; i<ncon_data; i++)
{
if(flag_detrend==0)
{
Larr[i*nq+0] = 1.0;
Larr[i*nq+1] = 0.0;
}
else
{
Larr[i*nq + 0] = 1.0;
Larr[i*nq + 1] = Tcon_data[i];
Larr[i*nq + 2] = 0.0;
Larr[i*nq + 3] = 0.0;
}
}
for(i=0; i<nline_data; i++)
{
if(flag_detrend==0)
{
Larr[(i+ncon_data)*nq+0] = 0.0;
Larr[(i+ncon_data)*nq+1] = 1.0;
}
else
{
Larr[(i+ncon_data)*nq + 0] = 0.0;
Larr[(i+ncon_data)*nq + 1] = 0.0;
Larr[(i+ncon_data)*nq + 2] = 1.0;
Larr[(i+ncon_data)*nq + 3] = Tline_data[i];
}
}
for(i=0; i<ncon; i++)
{
if(flag_detrend==0)
{
Larr_rec[i*nq+0] = 1.0;
Larr_rec[i*nq+1] = 0.0;
}
else
{
Larr_rec[i*nq + 0] = 1.0;
Larr_rec[i*nq + 1] = Tcon[i];
Larr_rec[i*nq + 2] = 0.0;
Larr_rec[i*nq + 3] = 0.0;
}
}
for(i=0; i<nline; i++)
{
if(flag_detrend==0)
{
Larr_rec[(i+ncon)*nq+0] = 0.0;
Larr_rec[(i+ncon)*nq+1] = 1.0;
}
else
{
Larr_rec[(i+ncon)*nq + 0] = 0.0;
Larr_rec[(i+ncon)*nq + 1] = 0.0;
Larr_rec[(i+ncon)*nq + 2] = 1.0;
Larr_rec[(i+ncon)*nq + 3] = Tline[i];
}
}
multiply_mat_MN(ICmat, Larr, Tmat1, nall_data, nq, nall_data);
multiply_mat_MN_transposeA(Larr, Tmat1, ICq, nq, nq, nall_data);
memcpy(Cq, ICq, nq*nq*sizeof(double));
inverse_mat(Cq, nq, &info);
multiply_mat_MN_transposeA(Larr, ICmat, Tmat1, nq, nall_data, nall_data);
multiply_mat_MN(Cq, Tmat1, Tmat2, nq, nall_data, nq);
multiply_mat_MN(Tmat2, Fall_data, ave, nq, 1, nall_data);
if(flag_detrend==0)
{
printf("ave: %e %e\n", ave[0]*scale_con, ave[1]*scale_line);
fprintf(fp_results, "ave: %e %e\n", ave[0]*scale_con, ave[1]*scale_line);
}
else
{
printf("ave_line: %e %e\n", ave[2]*scale_line, ave[3]*scale_line);
printf("ave_con: %e %e\n", ave[0]*scale_con, ave[1]*scale_con);
fprintf(fp_results, "ave_con: %e %e\n", ave[0]*scale_con, ave[1]*scale_con);
fprintf(fp_results, "ave_line: %e %e\n", ave[2]*scale_line, ave[3]*scale_line);
}
multiply_mat_MN(Larr, ave, yave, nall_data, 1, nq);
for(i=0; i<nall_data; i++)ysub[i] = Fall_data[i] - yave[i];
multiply_matvec(ICmat, ysub, nall_data, ybuf);
multiply_matvec_MN(USmat, nall, nall_data, ybuf, yrec);
multiply_mat_MN(Larr_rec, ave, yave_rec, nall, 1, nq);
/* store the reconstructed, mean-substracted contionum */
memcpy(Fcon, yrec, ncon*sizeof(double));
for(i=0; i<nall; i++)yrec[i] += yave_rec[i];
// get errors
multiply_mat_MN(USmat, ICmat, Tmp1, nall, nall_data, nall_data);
multiply_mat_MN_transposeB(Tmp1, USmat, Tmp2, nall, nall, nall_data);
multiply_mat_MN(Tmp1, Larr, Tmp3, nall, nq, nall_data);
for(i=0; i<nall*nq; i++)Tmp3[i] -= Larr_rec[i];
multiply_mat_MN(Tmp3, Cq, Tmp1, nall, nq, nq);
multiply_mat_MN_transposeB(Tmp1, Tmp3, Tmp4, nall, nall, nq);
for(i=0; i<nall; i++)
{
yrec_err[i] = sigma * sqrt(ASmat[i*nall+i] - Tmp2[i*nall+i] + Tmp4[i*nall+i]);
}
/* store the error */
for(i=0; i<ncon; i++)
{
Fcerrs[i] = sigma * sqrt(ASmat[i*nall+i] - Tmp2[i*nall+i]);
}
frec = fopen("data/sall_con.txt", "w");
for(i=0; i<ncon; i++)
{
fprintf(frec, "%f %e %e\n", Tcon[i], yrec[i]*scale_con, yrec_err[i]*scale_con);
}
fclose(frec);
frec = fopen("data/sall_line.txt", "w");
for(i=ncon; i<nall; i++)
{
fprintf(frec, "%f %e %e\n", Tline[i-ncon], yrec[i]*scale_line, yrec_err[i]*scale_line);
}
fclose(frec);
free(Tmp1);
free(Tmp2);
free(Tmp3);
free(Tmp4);
return 0;
}
| {
"alphanum_fraction": 0.5609252375,
"avg_line_length": 25.0999057493,
"ext": "c",
"hexsha": "3bcf0bee1141f1b6256b6b62fdb2904abad30cff",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/mcmc_conline.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/mcmc_conline.c",
"max_line_length": 123,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/mcmc_conline.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 10790,
"size": 26631
} |
//
// Created by jonathan on 1/5/18.
//
#ifndef CIMPLE_CIMPLE_MPC_COMPUTATION_H
#define CIMPLE_CIMPLE_MPC_COMPUTATION_H
#include <stddef.h>
#include <math.h>
#include "cimple_system.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include "cimple_polytope_library.h"
/**
* @brief Set up weight matrices for the quadratic problem
* @param P
* @param q
* @param L
* @param M
* @param now
* @param s_dyn
* @param f_cost
* @param time_horizon
* @return
*/
polytope *set_cost_function(gsl_matrix *P,
gsl_vector *q,
gsl_matrix *L,
gsl_vector *M,
current_state *now,
system_dynamics *s_dyn,
cost_function *f_cost,
size_t time_horizon);
/**
* @brief Set up GUROBI environment and solve qp
* @param low_u
* @param low_cost
* @param P
* @param q
* @param opt_constraints
* @param time_horizon
* @param n
*/
void compute_optimal_control_qp(gsl_matrix *low_u,
double *low_cost,
gsl_matrix *P,
gsl_vector* q,
polytope *opt_constraints,
size_t time_horizon,
size_t n);
/**
* @brief Calculate (optimal) input that will be applied to take plant from current state (now) to target_abs_state.
*
* Global function to compute continuous control input for discrete transition.
*
* Computes continuous control input sequence which takes the plant:
*
* - from now
* - to (chebyshev center of) target_abs_state
* => partitions given by discrete dynamics (d_dyn)
*
* Control input is calculated such that it minimizes:
*
* f(x, u) = |Rx|_{ord} + |Qu|_{ord} + r'x + distance_error_weight * |xc - x(N)|_{ord}
* with xc == chebyshev center of target_abs_state
*
* Notes
* =====
* 1. The same horizon length as in reachability analysis
* should be used in order to guarantee feasibility.
*
* 2. If the closed loop algorithm has been used
* to compute reachability the input needs to be
* recalculated for each time step
* (with decreasing horizon length).
*
* In this case only u(0) should be used as
* a control signal and u(1) ... u(N-1) discarded.
*
* 3. The "conservative" calculation makes sure that
* the plant remains inside the convex hull of the
* starting region during execution, i.e.::
*
* x(1), x(2) ... x(N-1) are in starting region.
*
* If the original proposition preserving partition
* is not convex, then safety cannot be guaranteed.
*
* @param low_u row k contains the control input: u(k) dim[N x m]
* @param now initial continuous state
* @param d_dyn discrete abstraction of system
* @param s_dyn system dynamics (including auxiliary matrices)
* @param target_abs_state index of target region in discrete dynamics (d_dyn)
* @param f_cost cost func matrices: f(x, u) = |Rx|_{ord} + |Qu|_{ord} + r'x + distance_error_weight *|xc - x(N)|_{ord}
*/
void get_input (gsl_matrix *u,
current_state * now,
discrete_dynamics *d_dyn,
system_dynamics *s_dyn,
int target_abs_state,
cost_function * f_cost,
size_t current_time_horizon,
polytope **polytope_list_backup);
/**
* @brief Calculates (optimal) input to reach desired state (P3) from current state (now) through convex optimization
*
* Calculate the sequence low_u such that:
*
* - x(t+1) = A x(t) + B u(t) + K
* - x(k) in P1 for k = 0,...,N-1 (if closed loop == 'true')
* - x(N) in P3
* - [u(k); x(k)] always obey s_dyn.Uset
*
* Actual optimality is compared in get_input()
*
*
* @param low_u currently optimal calculated input to target region (input to beat)
* @param now current state
* @param s_dyn system dynamics (including auxiliary matrices)
* @param P1 current polytope (or hull of region) the system is in
* @param P3 a polytope from the target region
* @param ord ordinance of the norm that should be minimized ord in {1, 2, INFINITY} (currently only '2' is possible)
* @param time_horizon
* @param f_cost predefined cost functions |Rx|_{ord} + |Qu|_{ord} + r'x + mid_weight * |xc - x(N)|_{ord}
* @param low_cost cost associate to low_u
*/
void search_better_path(gsl_matrix *low_u,
current_state *now,
system_dynamics *s_dyn,
polytope *P1,
polytope *P3,
int ord,
size_t time_horizon,
cost_function * f_cost,
double* low_cost,
polytope **polytope_list_backup,
size_t total_time);
/**
* @brief Compute a polytope that constraints the system over the next N time steps to fullfill the GR(1) specifications
*
* @param L_full empty matrix when passed in, left side of constraint polytope at the end
* @param M_full empty vector when passed in, right side of constraint polytope at the end
* @param s_dyn system dynamics (including auxiliary matrices)
* @param list_polytopes list of N+1 polytopes in which the systems needs to be in to reach new desired state at time N
* @param N time horizon
*
* Compute the components of the polytope:
*
* L [x(0)' u(0)' ... u(N-1)']' <= M
*
* which stacks the following constraints:
*
* - x(t+1) = A x(t) + B u(t) + E d(t)
* - [u(k); x(k)] in s_dyn.Uset for all k => system obeys predefined constraints on how inputs may behave
*
* [L_full; M_full] polytope intersection of required and allowed polytopes
*
*/
polytope * set_path_constraints(current_state * now,
system_dynamics * s_dyn,
polytope **list_polytopes,
size_t N);
#endif //CIMPLE_CIMPLE_MPC_COMPUTATION_H
| {
"alphanum_fraction": 0.6062438705,
"avg_line_length": 35.5697674419,
"ext": "h",
"hexsha": "03c3e80a68c6e742afe901566e58cb6e3d70e511",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "shaesaert/TuLiPXML",
"max_forks_repo_path": "Interface/Cimple/cimple_mpc_computation.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "shaesaert/TuLiPXML",
"max_issues_repo_path": "Interface/Cimple/cimple_mpc_computation.h",
"max_line_length": 120,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "shaesaert/TuLiPXML",
"max_stars_repo_path": "Interface/Cimple/cimple_mpc_computation.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z",
"num_tokens": 1509,
"size": 6118
} |
#include "poisson.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
static gsl_rng* poisson_rng_g = NULL;
void poisson_init(void)
{
const gsl_rng_type * T;
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
T = gsl_rng_default;
poisson_rng_g = gsl_rng_alloc (T);
}
void poisson_fini(void)
{
gsl_rng_free (poisson_rng_g);
}
unsigned int poisson(double mu)
{
return gsl_ran_poisson (poisson_rng_g, mu);
}
| {
"alphanum_fraction": 0.7435897436,
"avg_line_length": 16.1379310345,
"ext": "c",
"hexsha": "b0138d1da6a635798ce630f05a259529c66ccee9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-19T22:01:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-19T22:01:04.000Z",
"max_forks_repo_head_hexsha": "38002e4b306885ece995a5ae1fad46ba3d253a12",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Michael137/nfv-benchmark",
"max_forks_repo_path": "lib/poisson.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "38002e4b306885ece995a5ae1fad46ba3d253a12",
"max_issues_repo_issues_event_max_datetime": "2019-09-21T06:24:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-19T22:03:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Michael137/nfv-benchmark",
"max_issues_repo_path": "lib/poisson.c",
"max_line_length": 44,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "38002e4b306885ece995a5ae1fad46ba3d253a12",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Michael137/nfv-benchmark",
"max_stars_repo_path": "lib/poisson.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 135,
"size": 468
} |
//This does CELL (~soma) stage of peephole LSTM (long short-term memory) model.
//This requires each neuron to have 4 input time series, Xc, Xi, Xf, Xo,
//where Xc is the usual (or "cellular") input and Xi, Xf, Xo the inputs for the input, forget, output gates.
//Xc, Xi, Xf, Xo are the output of separate linear IN stages (weights and baises).
//In this version, these are stacked into one matrix
//For dim=0: X = [Xc; Xi; Xf; Xo]; for dim=1: X = [Xc Xi Xf Xo].
//For dim=0, I[:,t] = sig{Xi[:,t] + Ui*C[:,t-1]}
// F[:,t] = sig{Xf[:,t] + Uf*C[:,t-1]}
// O[:,t] = sig{Xo[:,t] + Uo*C[:,t-1]}
// C[:,t] = F[:,t].*C[:,t-1] + I[:,t].*sig{Xc[t,:]}
// Y[:,t] = tanh{O[:,t].*C[:,t]}
//with sizes Xc, Xi, Xf, Xo: N x T
// Ui, Uf, Uo: N x N
// Y: N x T
//
//For dim=1, I[t,:] = sig{Xi[t,:] + C[t-1,:]*Ui}
// F[t,:] = sig{Xf[t,:] + C[t-1,:]*Uf}
// O[t,:] = sig{Xo[t,:] + C[t-1,:]*Uo}
// C[t,:] = F[t,:].*C[t-1,:] + I[t,:].*sig{Xc[t,:]}
// Y[t,:] = tanh{O[t,:].*C[t,:]}
//with sizes Xc, Xi, Xf, Xo: T x N
// Ui, Uf, Uo: N x N
// Y: T x N
//
//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),
//I is the input gate, F is the forget gate, O is the output gate,
//C is the "cell input activation vector",
//H is an intermediate (hidden) vector (sometimes called the "cell state vector"),
//Uc, Ui, Uf, Uo are NxN matrices, and Y is the final output (sometimes called the "hidden state vector").
//The tanh is omitted here!! (To allow trying other nonlinearities.)
//Note that, the neurons of a layer are independent only if Uc, Ui, Uf, Uo are diagonal matrices.
//This is only really a CELL (~soma) stage in that case.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#ifdef I
#undef I
#endif
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int lstm_peephole_s (float *Y, const float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm_peephole_d (double *Y, const double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm_peephole_inplace_s (float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm_peephole_inplace_d (double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int lstm_peephole_s (float *Y, const float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T;
size_t nT, tN, tN4;
float *C, *I, *F, *O;
if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_s: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-X[N+n]));
C[n] = I[n] / (1.0f+expf(-X[n]));
Y[n] = C[n] / (1.0f+expf(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[tN4+n]));
Y[tN+n] = C[n] / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0f / (1.0f+expf(-X[NT+nT]));
C[n] = I[n] / (1.0f+expf(-X[nT]));
Y[nT] = C[n] / (1.0f+expf(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[t+n*T]));
Y[t+n*T] = C[n] / (1.0f+expf(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0f / (1.0f+expf(-X[NT+nT]));
C[n] = I[n] / (1.0f+expf(-X[nT]));
Y[nT] = C[n] / (1.0f+expf(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[t+n*T]));
Y[t+n*T] = C[n] / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-X[N+n]));
C[n] = I[n] / (1.0f+expf(-X[n]));
Y[n] = C[n] / (1.0f+expf(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[tN4+n]));
Y[tN+n] = C[n] / (1.0f+expf(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm_peephole_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm_peephole_d (double *Y, const double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T;
size_t nT, tN, tN4;
double *C, *I, *F, *O;
if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_d: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-X[N+n]));
C[n] = I[n] / (1.0+exp(-X[n]));
Y[n] = C[n] / (1.0+exp(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[tN4+n]));
Y[tN+n] = C[n] / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0 / (1.0+exp(-X[NT+nT]));
C[n] = I[n] / (1.0+exp(-X[nT]));
Y[nT] = C[n] / (1.0+exp(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[t+n*T]));
Y[t+n*T] = C[n] / (1.0+exp(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0 / (1.0+exp(-X[NT+nT]));
C[n] = I[n] / (1.0+exp(-X[nT]));
Y[nT] = C[n] / (1.0+exp(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[t+n*T]));
Y[t+n*T] = C[n] / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-X[N+n]));
C[n] = I[n] / (1.0+exp(-X[n]));
Y[n] = C[n] / (1.0+exp(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[tN4+n]));
Y[tN+n] = C[n] / (1.0+exp(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm_peephole_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm_peephole_inplace_s (float *X, const float *Ui, const float *Uf, const float *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T;
size_t nT, tN, tN4;
float *C, *I, *F, *O;
if (!(C=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in lstm_peephole_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-X[N+n]));
C[n] = I[n] / (1.0f+expf(-X[n]));
X[n] = C[n] / (1.0f+expf(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[tN4+n]));
X[tN4+n] = C[n] / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0f / (1.0f+expf(-X[NT+nT]));
C[n] = I[n] / (1.0f+expf(-X[nT]));
X[nT] = C[n] / (1.0f+expf(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[t+n*T]));
X[t+n*T] = C[n] / (1.0f+expf(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0f / (1.0f+expf(-X[NT+nT]));
C[n] = I[n] / (1.0f+expf(-X[nT]));
X[nT] = C[n] / (1.0f+expf(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&X[NT+t],(int)T,I,1); cblas_scopy((int)N,&X[NT2+t],(int)T,F,1); cblas_scopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[t+n*T]));
X[t+n*T] = C[n] / (1.0f+expf(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-X[N+n]));
C[n] = I[n] / (1.0f+expf(-X[n]));
X[n] = C[n] / (1.0f+expf(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_scopy((int)N,&X[tN4+N],1,I,1); cblas_scopy((int)N,&X[tN4+N2],1,F,1); cblas_scopy((int)N,&X[tN4+N3],1,O,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0f / (1.0f+expf(-I[n]));
C[n] = C[n]/(1.0f+expf(-F[n])) + I[n]/(1.0f+expf(-X[tN4+n]));
X[tN4+n] = C[n] / (1.0f+expf(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm_peephole_inplace_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int lstm_peephole_inplace_d (double *X, const double *Ui, const double *Uf, const double *Uo, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
const size_t N2 = 2*N, N3 = 3*N, NT = N*T, NT2 = 2*N*T, NT3 = 3*N*T;
size_t nT, tN, tN4;
double *C, *I, *F, *O;
if (!(C=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(I=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(O=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in lstm_peephole_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-X[N+n]));
C[n] = I[n] / (1.0+exp(-X[n]));
X[n] = C[n] / (1.0+exp(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[tN4+n]));
X[tN4+n] = C[n] / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0 / (1.0+exp(-X[NT+nT]));
C[n] = I[n] / (1.0+exp(-X[nT]));
X[nT] = C[n] / (1.0+exp(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[t+n*T]));
X[t+n*T] = C[n] / (1.0+exp(-O[n]));
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
I[n] = 1.0 / (1.0+exp(-X[NT+nT]));
C[n] = I[n] / (1.0+exp(-X[nT]));
X[nT] = C[n] / (1.0+exp(-X[NT3+nT]));
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&X[NT+t],(int)T,I,1); cblas_dcopy((int)N,&X[NT2+t],(int)T,F,1); cblas_dcopy((int)N,&X[NT3+t],(int)T,O,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[t+n*T]));
X[t+n*T] = C[n] / (1.0+exp(-O[n]));
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-X[N+n]));
C[n] = I[n] / (1.0+exp(-X[n]));
X[n] = C[n] / (1.0+exp(-X[N3+n]));
}
for (size_t t=1; t<T; ++t)
{
tN = t*N; tN4 = 4*tN;
cblas_dcopy((int)N,&X[tN4+N],1,I,1); cblas_dcopy((int)N,&X[tN4+N2],1,F,1); cblas_dcopy((int)N,&X[tN4+N3],1,O,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Ui,(int)N,C,1,o,I,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,C,1,o,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uo,(int)N,C,1,o,O,1);
for (size_t n=0u; n<N; ++n)
{
I[n] = 1.0 / (1.0+exp(-I[n]));
C[n] = C[n]/(1.0+exp(-F[n])) + I[n]/(1.0+exp(-X[tN4+n]));
X[tN4+n] = C[n] / (1.0+exp(-O[n]));
}
}
}
}
else
{
fprintf(stderr,"error in lstm_peephole_inplace_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4483599664,
"avg_line_length": 44.1187384045,
"ext": "c",
"hexsha": "6c27fabca66b9c1b560f908c1df02465bd6df006",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/lstm_peephole.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/lstm_peephole.c",
"max_line_length": 176,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/lstm_peephole.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 8747,
"size": 23780
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_sswap (const int N, float *X, const int incX, float *Y, const int incY)
{
#define BASE float
#include "source_swap_r.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7196261682,
"avg_line_length": 17.8333333333,
"ext": "c",
"hexsha": "ecb0020d808c8db772644c9c821b6934d6d29686",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.c",
"max_line_length": 77,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/sswap.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": 68,
"size": 214
} |
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
#include <getopt.h>
#include <pthread.h>
#include <cblas.h>
#include <omp.h>
#define WALLTIME(t) ((double)(t).tv_sec + 1e-6 * (double)(t).tv_usec)
#define min(x,y) (((x) < (y)) ? (x) : (y))
void options ( int argc, char **argv );
const char *usage =
"\t-k <int>\n"
"\t-m <int>\n"
"\t-n <int>\n"
"\t-t <int>\n";
//Global variables and definitions
int num_threads = 4;
double
*A, *B,
*C_serial, *C_openmp, *C_pthreads, *C_blas,
alpha = 1.0, beta = 0.0;
int
m = 1024, n = 1024, k = 1024;
void print_matrices()
{
size_t i, j;
printf (" Top left corner of matrix A: \n");
for (i=0; i<min(m,6); i++) {
for (j=0; j<min(k,6); j++) {
printf ("%12.0f", A[j+i*k]);
}
printf ("\n");
}
printf ("\n Top left corner of matrix B: \n");
for (i=0; i<min(k,6); i++) {
for (j=0; j<min(n,6); j++) {
printf ("%12.0f", B[j+i*n]);
}
printf ("\n");
}
printf ("\n Top left corner of matrix C: \n");
for (i=0; i<min(m,6); i++) {
for (j=0; j<min(n,6); j++) {
printf ("%12.5G", C_serial[j+i*n]);
}
printf ("\n");
}
}
//TODO: Pthreads - function
//TODO end
int
main ( int argc, char **argv )
{
options ( argc, argv );
A = (double *)malloc( m*k*sizeof( double ) );
B = (double *)malloc( k*n*sizeof( double ) );
C_serial = (double *)malloc( m*n*sizeof( double ) );
C_openmp = (double *)malloc( m*n*sizeof( double ) );
C_pthreads = (double *)malloc( m*n*sizeof( double ) );
C_blas = (double *)malloc( m*n*sizeof( double ) );
int i, j;
/* Initialize with dummy data */
for ( i = 0; i < (m*k); i++ )
A[i] = (double)(i+1);
for ( i = 0; i < (k*n); i++ )
B[i] = (double)(-i-1);
for ( i = 0; i < (m*n); i++ ){
C_serial[i] = 0.0;
C_openmp [i] = 0.0;
C_pthreads[i] = 0.0;
C_blas[i] = 0.0;
}
struct timeval start, end;
double total_time_serial = 0;
double total_time_openmp = 0;
double total_time_pthreads = 0;
double total_time_blas = 0;
/*
* DGEMM (Double-precision GEneral Matrix Multiply)
* Example: A general multiplication between two matricies A and B, accumulating in C.
*/
// A has m rows and k columns
// B has k rows and n columns
// C has m rows and n columns
double sum = 0;
int p;
gettimeofday( &start, NULL );
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
sum = 0;
for (p = 0; p < k; p++) {
sum = sum + A[i * k + p] * B[p * n + j];
}
C_serial[i * n + j] = sum;
}
}
gettimeofday ( &end, NULL );
total_time_serial = (WALLTIME(end)-WALLTIME(start));
//print_matrices();
//TODO: OpenMP
gettimeofday( &start, NULL );
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
sum = 0;
for (p = 0; p < k; p++) {
sum = sum + A[i * k + p] * B[p * n + j];
}
C_openmp[i * n + j] = sum;
}
}
gettimeofday ( &end, NULL );
total_time_openmp = (WALLTIME(end)-WALLTIME(start));
//TODO end
//TODO: Pthreads - spawn threads
gettimeofday( &start, NULL );
gettimeofday ( &end, NULL );
total_time_pthreads = (WALLTIME(end)-WALLTIME(start));
//TODO end
gettimeofday( &start, NULL );
// Documentation for GEMM:
// https://software.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-c/top/blas-and-sparse-blas-routines/blas-routines/blas-level-3-routines/cblas-gemm.html
cblas_dgemm(
CblasRowMajor, // Formating of the matrix, RowMajor or ColMajor
CblasNoTrans, // The form of Matrix A
CblasNoTrans, // The form of Matrix B
m, // Number of rows in A and in C
n, // Number of columns in B and C
k, // Number of columns in A and rows of B
alpha, // Scalar alpha of multiplication with A
A, // The A matrix
k, // Leading dimension of A, k if CblasRowMajor and NoTrans
B, // The B matrix
n, // Leading dimension of B, n if CblasRowMajor and NoTrans
beta, // Scalar beta of multiplication with C
C_blas, // The C matrix, this is also the output matrix
n // Leading dimension of C, n if CblasRowMajor
);
gettimeofday ( &end, NULL );
//print_matrices();
total_time_blas = (WALLTIME(end)-WALLTIME(start));
bool openmp_correct = true;
bool pthreads_correct = true;
bool blas_correct = true;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
if(C_openmp[i*n+j] != C_serial[i*n+j])
openmp_correct = false;
if(C_pthreads[i*n+j] != C_serial[i*n+j])
pthreads_correct = false;
if(C_blas[i*n+j] != C_serial[i*n+j])
blas_correct = false;
}
}
printf ( "Manual\t\t\tTime:\t%es\n", total_time_serial );
printf("OpenMP:\t %s\t", openmp_correct ? "CORRECT" : "INCORRECT");
printf ( "Time:\t%es\t", total_time_openmp );
printf ( "Speedup: %.2lfx\n", total_time_serial/total_time_openmp );
printf("Pthreads: %s\t", pthreads_correct ? "CORRECT" : "INCORRECT");
printf ( "Time:\t%es\t", total_time_pthreads );
printf ( "Speedup: %.2lfx\n", total_time_serial/total_time_pthreads );
printf("BLAS:\t %s\t", blas_correct ? "CORRECT" : "INCORRECT");
printf ( "Time:\t%es\t", total_time_blas );
printf ( "Speedup: %.2lfx\n", total_time_serial/total_time_blas );
free ( A );
free ( B );
free ( C_serial );
free ( C_openmp );
free ( C_pthreads );
free ( C_blas );
exit ( EXIT_SUCCESS );
}
void
options ( int argc, char **argv )
{
int o;
while ( (o = getopt(argc,argv,"k:m:n:t:h")) != -1 )
switch ( o )
{
case 'k': k = strtol ( optarg, NULL, 10 ); break;
case 'm': m = strtol ( optarg, NULL, 10 ); break;
case 'n': n = strtol ( optarg, NULL, 10 ); break;
case 't': num_threads = strtol ( optarg, NULL, 10 ); break;
case 'h':
fprintf ( stderr, "%s", usage );
exit ( EXIT_FAILURE );
break;
}
}
| {
"alphanum_fraction": 0.546291808,
"avg_line_length": 27.1447368421,
"ext": "c",
"hexsha": "749b0b1f68b5d48a6b10772bb0b3648d4e612229",
"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": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jorgstei/Datateknologi",
"max_forks_repo_path": "TDT4200/A4/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"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": "jorgstei/Datateknologi",
"max_issues_repo_path": "TDT4200/A4/main.c",
"max_line_length": 188,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jorgstei/Datateknologi",
"max_stars_repo_path": "TDT4200/A4/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1984,
"size": 6189
} |
#include <gsl/gsl_matrix.h>
#include "cimple_safe_mode.h"
/**
* Adds a node to the beginning of the list
*/
void push_burn_node(burn_graph_node ** head,
abstract_state *state)
{
burn_graph_node * new_node;
new_node = malloc(sizeof(burn_graph_node));
new_node->state = state;
new_node->next = *head;
*head = new_node;
};
/**
* Remove a node from the beginning of the list
*/
void pop_burn_node(burn_graph_node ** head)
{
burn_graph_node * next_node = NULL;
next_node = (*head)->next;
free(*head);
*head = next_node;
};
/**
* Delete and free memory of all nodes of a list
*/
void clear_burn_list(burn_graph_node **head)
{
while (head !=NULL){
pop_burn_node(head);
}
};
/**
* Given a set of abstract states (associated with the transitions going out from a state, where the function was called)
* it finds the shortest distance to a state with an invariant set.
*/
abstract_state* fastest_burn(abstract_state **transitions,
int transitions_count)
{
//Initialize
abstract_state* fastest = transitions[0];
int distance = transitions[0]->distance_invariant_set;
//Check that there are more than 1 transition to evaluate, else trivial
if(transitions_count >1){
//Compare transitions
for(int i = 1; i<transitions_count; i++){
if(transitions[i]->distance_invariant_set<distance){
distance = transitions[i]->distance_invariant_set;
fastest = transitions[i];
}
}
}
return fastest;
}
/**
* Given two polytopes, computes one step backwards from second polytope towards first polytope.
*/
polytope* previous_polytope(polytope *P1,
polytope *P2,
system_dynamics *s_dyn)
{
size_t n = s_dyn->A->size2; // State space dimension;
size_t m = s_dyn->B->size2; // Input space dimension;
polytope *scaled_W_set = polytope_linear_transform(s_dyn->W_set, s_dyn->E); // multiplication: EW
polytope * robust_P1 = polytope_pontryagin(P1, scaled_W_set);
polytope * robust_P2 = polytope_pontryagin(P2, scaled_W_set);
size_t sum_dim = robust_P1->H->size1+robust_P2->H->size1;
polytope *precedent_polytope = polytope_alloc(sum_dim+s_dyn->U_set->H->size1, n+m);
// FOR precedent_polytope G
/*
* |P1_G|
* G = |P2_G|
* | 0 |
*/
gsl_vector_set_zero(precedent_polytope->G);
gsl_vector_view G_P1 = gsl_vector_subvector(precedent_polytope->G, 0, robust_P1->G->size);
gsl_vector_memcpy(&G_P1.vector, robust_P1->G);
gsl_vector_view G_P2 = gsl_vector_subvector(precedent_polytope->G, robust_P1->G->size,robust_P2->G->size);
gsl_vector_memcpy(&G_P2.vector, robust_P2->G);
// gsl_vector * P2_HdotK = gsl_vector_alloc(robust_P2->G->size);
// gsl_blas_dgemv(CblasNoTrans,1.0, robust_P2->H, s_dyn->K, 0.0, P2_HdotK);
// gsl_vector_sub(&G_P2.vector, P2_HdotK);
// //Clean up!
// gsl_vector_free(P2_HdotK);
// FOR Dist
/*
* | 0 |
* Dist = |P2_H.E|
* | 0 |
*/
// gsl_matrix *Dist = gsl_matrix_alloc(sum_dim+s_dyn->U_set->H->size1, p);
// gsl_matrix_set_zero(Dist);
// gsl_matrix_view Dist_P2 = gsl_matrix_submatrix(Dist, P1->H->size1, 0, P2->H->size1, Dist->size2);
// gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, P2->H, s_dyn->E, 0.0, &Dist_P2.matrix);
// FOR precedent_polytope H
/*
* H = |H1 0 | OR H = |H1 0 |
* |H2A H2B| |H2A H2B|
* | 0 HU | | HU |
*/
gsl_matrix_set_zero(precedent_polytope->H);
gsl_matrix_view H_P1 = gsl_matrix_submatrix(precedent_polytope->H, 0, 0, robust_P1->H->size1, n);
gsl_matrix_memcpy(&H_P1.matrix, robust_P1->H);
gsl_matrix_view H_P2_1 = gsl_matrix_submatrix(precedent_polytope->H, robust_P1->H->size1, 0, robust_P2->H->size1, n);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, robust_P2->H, s_dyn->A, 0.0, &H_P2_1.matrix);
gsl_matrix_view H_P2_2 = gsl_matrix_submatrix(precedent_polytope->H, robust_P1->H->size1, n, robust_P2->H->size1, m);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, robust_P2->H, s_dyn->B, 0.0, &H_P2_2.matrix);
if (s_dyn->U_set->H->size2 == m){
gsl_matrix_view HU = gsl_matrix_submatrix(precedent_polytope->H,sum_dim, n, s_dyn->U_set->H->size1,m);
gsl_matrix_memcpy(&HU.matrix,s_dyn->U_set->H);
} else if (s_dyn->U_set->H->size2 == m+n){
// transforms U_set.H from |constraints_ input constraints_state| to |constraints_state constraints_input|
/*
* |m m m m n n n| |n n n m m m m|
* |m m m m n n n| => |n n n m m m m|
* |m m m m n n n| |n n n m m m m|
*/
gsl_matrix_view HU = gsl_matrix_submatrix(precedent_polytope->H,sum_dim, 0, s_dyn->U_set->H->size1,m+n);
gsl_matrix * exchange_matrix = gsl_matrix_alloc(n+m,n+m);
gsl_matrix_set_zero(exchange_matrix);
gsl_matrix_view eye_m = gsl_matrix_submatrix(exchange_matrix, 0, n, m, m);
gsl_matrix_set_identity(&eye_m.matrix);
gsl_matrix_view eye_n = gsl_matrix_submatrix(exchange_matrix, m, 0, n, n);
gsl_matrix_set_identity(&eye_n.matrix);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, s_dyn->U_set->H,exchange_matrix, 0.0, &HU.matrix);
}
polytope *return_polytope = polytope_projection(precedent_polytope, n);
//Clean up!
// gsl_matrix_free(Dist);
// gsl_vector_free(D_hat);
polytope_free(precedent_polytope);
return return_polytope;
};
/**
* Computes N-1 polytopes the system has to transition to go from origin to target in N time steps
*/
polytope ** compute_path(polytope *origin,
polytope *target,
system_dynamics *s_dyn,
int N)
{
//Initialize
polytope **path = malloc(sizeof(polytope) * N);
//Instead of just pointing path[N] = target, the memory is copied,
// thus when the target polytope is freed somewhere the path stays complete
path[N] = polytope_alloc(target->H->size1,target->H->size2);
gsl_matrix_memcpy(path[N]->H,target->H);
path[0] = polytope_alloc(origin->H->size1,origin->H->size2);
gsl_matrix_memcpy(path[0]->H,origin->H);
//Compute intermediate steps
for(int j = N-1; j>0;j--){
path[j]=previous_polytope(path[0], path[j+1], s_dyn);
}
return path;
};
polytope *pre_alpha(polytope *R_i,
gsl_matrix *A,
gsl_matrix *B,
polytope *W_set,
polytope *U_set,
polytope *scaled_unit_cube)
{
size_t n = A->size2;
size_t m = B->size2;
polytope *W_set_scaled = polytope_minkowski(W_set, scaled_unit_cube);
polytope *R_i_scaled = polytope_pontryagin(R_i, W_set_scaled);
polytope *P0 = polytope_alloc(R_i_scaled->H->size1+U_set->H->size1, n+m);
gsl_matrix_set_zero(P0->H);
gsl_matrix_view H_P2_1 = gsl_matrix_submatrix(P0->H, 0, 0, R_i_scaled->H->size1, n);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, R_i_scaled->H, A, 0.0, &H_P2_1.matrix);
gsl_matrix_view H_P2_2 = gsl_matrix_submatrix(P0->H, 0, n, R_i_scaled->H->size1, m);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans, 1.0, R_i_scaled->H, B, 0.0, &H_P2_2.matrix);
if (U_set->H->size2 == m){
gsl_matrix_view HU = gsl_matrix_submatrix(P0->H,R_i_scaled->H->size1, n, U_set->H->size1,m);
gsl_matrix_memcpy(&HU.matrix,U_set->H);
} else if (U_set->H->size2 == m+n){
// transforms U_set.H from |constraints_ input constraints_state| to |constraints_state constraints_input|
/*
* |m m m m n n n| |n n n m m m m|
* |m m m m n n n| => |n n n m m m m|
* |m m m m n n n| |n n n m m m m|
*/
gsl_matrix_view HU = gsl_matrix_submatrix(P0->H,R_i_scaled->H->size1, 0, U_set->H->size1,m+n);
gsl_matrix * exchange_matrix = gsl_matrix_alloc(n+m,n+m);
gsl_matrix_set_zero(exchange_matrix);
gsl_matrix_view eye_m = gsl_matrix_submatrix(exchange_matrix, 0, n, m, m);
gsl_matrix_set_identity(&eye_m.matrix);
gsl_matrix_view eye_n = gsl_matrix_submatrix(exchange_matrix, m, 0, n, n);
gsl_matrix_set_identity(&eye_n.matrix);
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0, U_set->H,exchange_matrix, 0.0, &HU.matrix);
}
gsl_vector_set_zero(P0->G);
gsl_vector_view G_P1 = gsl_vector_subvector(P0->G, 0, R_i_scaled->G->size);
gsl_vector_memcpy(&G_P1.vector, R_i_scaled->G);
gsl_vector_view G_P2 = gsl_vector_subvector(P0->G, R_i_scaled->G->size,U_set->G->size);
gsl_vector_memcpy(&G_P2.vector, U_set->G);
polytope *pre_R_1 = polytope_projection(P0, n);
polytope_free(P0);
return pre_R_1;
}
polytope * compute_invariant_set(polytope* X,
gsl_matrix *A,
gsl_matrix *B,
polytope *W_set,
polytope *U_set,
double alpha)
{
polytope * scaled_unit_cube = polytope_scaled_unit_cube(alpha, (int)X->H->size2);
polytope *R_i = polytope_alloc(X->H->size1,X->H->size2);
gsl_matrix_memcpy(R_i->H,X->H);
gsl_vector_memcpy(R_i->G,X->G);
polytope *pre_R_i = pre_alpha(R_i,A,B,W_set,U_set,scaled_unit_cube);
polytope *R_i_plus = polytope_unite_inequalities(pre_R_i, X);
dd_ErrorType err = dd_NoError;
dd_WriteMatrix(stdout,dd_CopyGenerators(polytope_to_cdd(R_i_plus,&err)));
polytope *R_scaled = polytope_minkowski(R_i_plus, scaled_unit_cube);
while(!(polytope_is_subset(R_i, R_scaled))){
polytope_free(pre_R_i);
polytope_free(R_scaled);
polytope_free(R_i);
R_i = R_i_plus;
pre_R_i = pre_alpha(R_i,A,B,W_set,U_set,scaled_unit_cube);
R_i_plus = polytope_unite_inequalities(pre_R_i, X);
R_scaled = polytope_minkowski(R_i_plus, scaled_unit_cube);
}
polytope_free(pre_R_i);
polytope_free(R_i_plus);
polytope_free(R_scaled);
return R_i;
};
bool has_transition(abstract_state *state,
abstract_state *transition)
{
bool transition_found = false;
for(int i = 0; i<state->transitions_in_count; i++){
if(state->transitions_in[i] == transition){
transition_found = true;
}
}
return transition_found;
};
/**
* 1) Runs through all abstract states,
* 2) checks if invariant set is contained
* 3) sets path for all cells in those states containing an invariant set if possible
*/
burn_graph_node *set_invariant_sets(discrete_dynamics *d_dyn,
system_dynamics *s_dyn)
{
//Initialize graph
burn_graph_node * head_node = NULL;
head_node = malloc(sizeof(burn_graph_node));
head_node->state = NULL;
head_node->next = NULL;
int N = (int)d_dyn->time_horizon;
double unit_cube_scale = 1;
//Create graph by
// 1) running through all abstract_states and
// 2) check whether it contains an invariant set
for(int i = 0; i< d_dyn->abstract_states_count; i++){
bool found_set = false;
for(int j=0; j<d_dyn->abstract_states_set[i]->cells_count; j++){
//Try to compute invariant set
polytope *invariant_set = compute_invariant_set(d_dyn->abstract_states_set[i]->cells[j]->polytope_description,
s_dyn->A,
s_dyn->B,
s_dyn->W_set,
s_dyn->U_set,
unit_cube_scale);
//if invariant set is found
if(invariant_set != NULL){
found_set = true;
//Set invariant_set cell to A cell containing an invariant set
//(may be more than one invariant set!!)
d_dyn->abstract_states_set[i]->invariant_set = d_dyn->abstract_states_set[i]->cells[j];
//Compute path for rest of cell to invariant set (may be just a subset of that polytope)
d_dyn->abstract_states_set[i]->cells[j]->safe_mode = compute_path(d_dyn->abstract_states_set[i]->cells[j]->polytope_description,
invariant_set,
s_dyn,
N);
}else{
//Set NULL because later safe_mode==NULL cells will be picked out
d_dyn->abstract_states_set[i]->cells[j]->safe_mode = NULL;
}
}
//If abstract state contains at least one invariant set it is appended to the graph
if(found_set){
//Check whether state has a transition to itself
if(has_transition(d_dyn->abstract_states_set[i], d_dyn->abstract_states_set[i])){
//if yes compute the safe_mode path for the cells that do not contain an invariant set
for(int j = 0; j < d_dyn->abstract_states_set[i]->cells_count; j++){
if(d_dyn->abstract_states_set[i]->cells[j]->safe_mode == NULL){
d_dyn->abstract_states_set[i]->cells[j]->safe_mode = compute_path(d_dyn->abstract_states_set[i]->cells[j]->polytope_description,
d_dyn->abstract_states_set[i]->invariant_set->polytope_description,
s_dyn,
N);
}
}
}
//Append state to graph
if (head_node->state == NULL) {
head_node->state = d_dyn->abstract_states_set[i];
}else{
push_burn_node(&head_node,d_dyn->abstract_states_set[i]);
}
}
}
return head_node;
};
/**
* Gets list of states containing invariant sets.
* Burns through transition system, setting all other safe mode paths.
*/
//void burning_method(burn_graph_node *seeds,
// discrete_dynamics *d_dyn,
// system_dynamics *s_dyn)
//{
//
// //Initialize needed variables
// bool graph_burnt = false;
// int N = (int)d_dyn->time_horizon;
// burn_graph_node *current_burning = seeds;
// int burning_round = 0;
//
//
// while(!graph_burnt){
// burning_round +=1;
// burn_graph_node *next_burning = current_burning;
// while (current_burning != NULL) {
// if(current_burning->state->distance_invariant_set == INFINITY){
// for(int i = 0; i<current_burning->state->cells_count;i++){
// if(current_burning->state->cells[i]->safe_mode == NULL){
// current_burning->state->cells[i]->safe_mode = compute_path(current_burning->state->cells[i]->polytope_description,
// current_burning->state->next_state->convex_hull,
// s_dyn,
// N);
// }
//
// }
// current_burning->state->distance_invariant_set = burning_round;
// }
// current_burning = current_burning->next;
// }
// while(next_burning != NULL){
// for(int i = 0;i<next_burning->state->transitions_in_count;i++){
// if(next_burning->state->transitions_in[i]->distance_invariant_set == NULL){
// push_burn_node(¤t_burning,next_burning->state->transitions_in[i]);
// }
// }
// next_burning = next_burning->next;
// }
// if(current_burning == NULL){
// graph_burnt = true;
// }
// }
// while (seeds !=NULL){
// if(seeds->state->next_state != seeds->state){
// abstract_state* fastest = fastest_burn(seeds->state->transitions_out,seeds->state->transitions_out_count);
// for(int i = 0; i< seeds->state->cells_count; i++){
// if(seeds->state->cells[i]->safe_mode == NULL){
// seeds->state->cells[i]->safe_mode = compute_path(seeds->state->cells[i]->polytope_description, fastest->convex_hull,s_dyn,N);
// }
// }
// }
// seeds = seeds->next;
// }
//};
/**
* Set the safe_mode path for every cell in every abstract_state:
* 1) Compute invariant sets
* 2) Find path towards invariant sets for other abstract_states
*/
//void compute_safe_mode(discrete_dynamics *d_dyn,
// system_dynamics *s_dyn)
//{
//
// burn_graph_node * invariant_sets = set_invariant_sets(d_dyn, s_dyn);
// burning_method(invariant_sets, d_dyn, s_dyn);
// free(invariant_sets);
//};
//gsl_vector *one_step_input(polytope *A, polytope *B)
//{
// gsl_vector *u;
// return u;
//};
//abstract_state *find_current_state(gsl_vector *x,
// discrete_dynamics *d_dyn)
//{
// abstract_state *now;
// return now;
//};
//
//void *apply_safe_mode(current_state *now,
// discrete_dynamics *d_dyn,
// system_dynamics *s_dyn,
// void *arg)
//{
//
// //find correct cell
// cell * current_cell = NULL;
// int N = (int)d_dyn->time_horizon;
// int found = 0;
// int i;
// for(i = 0; i < d_dyn->abstract_states_set[now->current_abs_state]->cells_count; i++){
// found = polytope_check_state(d_dyn->abstract_states_set[now->current_abs_state]->cells[i]->polytope_description, now->x);
// if(found){
// current_cell = d_dyn->abstract_states_set[now->current_abs_state]->cells[i];
// break;
// }
// }
//
// //if not found check all other abstract_states_set all other cells
// if(current_cell ==NULL){
// for(i = 0; i<d_dyn->abstract_states_count; i++){
// for(int j = 0; j < d_dyn->abstract_states_set[i]->cells_count; j++){
// found = polytope_check_state(d_dyn->abstract_states_set[i]->cells[j]->polytope_description, now->x);
// if(found){
// now->current_abs_state = i;
// current_cell = d_dyn->abstract_states_set[i]->cells[j];
// }
// }
// }
// }
// int safe_mode_state = 0;
// found = 0;
// for(i = N; i>0; i--){
// found = polytope_check_state(current_cell->safe_mode[i], now->x);
// if(found){
// safe_mode_state = i;
// break;
// }
// }
// pthread_mutex_t *mx = arg;
//
// //while ! in invariant set
// while(d_dyn->abstract_states_set[now->current_abs_state]->invariant_set == NULL && !needQuit(mx)){
// //find polytope of safe_mode
// int check = polytope_check_state(current_cell->safe_mode[safe_mode_state], now->x);
// if(!check){
// safe_mode_state = 0;
// found = 0;
// for(i = N; i>0; i--){
// found = polytope_check_state(current_cell->safe_mode[i], now->x);
// if(found){
// safe_mode_state = i;
// break;
// }
// }
// }
//
// //linear combination to next polytope in line
// gsl_vector *u = one_step_input(current_cell->safe_mode[safe_mode_state],
// current_cell->safe_mode[safe_mode_state+1]);
// gsl_vector *w = gsl_vector_alloc(s_dyn->E->size2);
// simulate_disturbance(w, 0, 0.01);
// apply_control(now->x, u, s_dyn->A, s_dyn->B, s_dyn->E, w, (size_t)safe_mode_state);
//
// }
//
// //while not interrupted stay in invariant set
//
// while( !needQuit(mx) ) {
// int check = polytope_check_state(d_dyn->abstract_states_set[now->current_abs_state]->invariant_set->polytope_description, now->x);
// if(!check){
// safe_mode_state = 0;
// found = 0;
// for(i = N; i>0; i--){
// found = polytope_check_state(current_cell->safe_mode[i], now->x);
// if(found){
// safe_mode_state = i;
// break;
// }
// }
// }
// one_step_input(d_dyn->abstract_states_set[now->current_abs_state]->invariant_set->polytope_description, d_dyn->abstract_states_set[now->current_abs_state]->invariant_set->polytope_description);
// }
// return NULL;
//};
| {
"alphanum_fraction": 0.577175152,
"avg_line_length": 39.6534839925,
"ext": "c",
"hexsha": "95cbda7bd3bb9f74f48cc3c2dfb05858296ed798",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z",
"max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "shaesaert/TuLiPXML",
"max_forks_repo_path": "Interface/Cimple/cimple_safe_mode.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "shaesaert/TuLiPXML",
"max_issues_repo_path": "Interface/Cimple/cimple_safe_mode.c",
"max_line_length": 203,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "shaesaert/TuLiPXML",
"max_stars_repo_path": "Interface/Cimple/cimple_safe_mode.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z",
"num_tokens": 5493,
"size": 21056
} |
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"gsl")
int main(int argc, char** argv)
{
gsl_complex a,b;
GSL_SET_COMPLEX(&a,3,4);//a=3+4i
GSL_SET_COMPLEX(&b,6,8);//b=6+8i
gsl_complex c = gsl_complex_add(a,b);
printf("a+b\treal : %f image : %f\n",c.dat[0],c.dat[1]);
c = gsl_complex_sub(a,b);
printf("a-b\treal : %f image : %f\n",c.dat[0],c.dat[1]);
c = gsl_complex_mul(a,b);
printf("a*b\treal : %f image : %f\n",c.dat[0],c.dat[1]);
c = gsl_complex_div(a,b);
printf("a/b\treal : %f image : %f\n",c.dat[0],c.dat[1]);
// system("PAUSE");
return 0;
} | {
"alphanum_fraction": 0.5911111111,
"avg_line_length": 29.347826087,
"ext": "c",
"hexsha": "ebe8710f9613cca702bb7b3fec438e7310961d35",
"lang": "C",
"max_forks_count": 29,
"max_forks_repo_forks_event_max_datetime": "2021-12-24T01:51:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-10T13:25:54.000Z",
"max_forks_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wurui1994/test",
"max_forks_repo_path": "Sources/CLibrary/GSL/gsl_complex.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"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": "wurui1994/test",
"max_issues_repo_path": "Sources/CLibrary/GSL/gsl_complex.c",
"max_line_length": 60,
"max_stars_count": 27,
"max_stars_repo_head_hexsha": "027cef75f98dbb252b322113dacd4a9a6997d84f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wurui1994/test",
"max_stars_repo_path": "Sources/CLibrary/GSL/gsl_complex.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-30T13:02:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-19T09:15:36.000Z",
"num_tokens": 243,
"size": 675
} |
#ifndef FEODOROV_SQC_LAB1_GAUSS_H
#define FEODOROV_SQC_LAB1_GAUSS_H
#include <gsl/gsl_matrix.h>
#define EPSILON .0000001
#ifdef __cplusplus
extern "C" {
#endif
void gauss_init(size_t size, const double *d_matrix, const double *d_vector, gsl_matrix **matrix, gsl_vector **vector, gsl_vector **result);
int gauss(size_t size, gsl_matrix *matrix, gsl_vector *vector, gsl_vector *result, double *det);
void gauss_print(size_t size, gsl_vector *result);
int gauss_check(size_t size, const double *d_matrix, const double *d_vector, gsl_vector *result);
#ifdef __cplusplus
}
#endif
#endif //FEODOROV_SQC_LAB1_GAUSS_H
| {
"alphanum_fraction": 0.788961039,
"avg_line_length": 28,
"ext": "h",
"hexsha": "892e49d2302da6a167857c6b4e90b13b6d6ac594",
"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": "51c57f411ea1155d22e543f0ab62107a273cb7b2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "z8432k/feodorov-sqc-lab1",
"max_forks_repo_path": "include/gauss.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "51c57f411ea1155d22e543f0ab62107a273cb7b2",
"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": "z8432k/feodorov-sqc-lab1",
"max_issues_repo_path": "include/gauss.h",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "51c57f411ea1155d22e543f0ab62107a273cb7b2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "z8432k/feodorov-sqc-lab1",
"max_stars_repo_path": "include/gauss.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 176,
"size": 616
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef rasm_150d55c1_d63d_40ea_8fd2_9bc280975fe0_h
#define rasm_150d55c1_d63d_40ea_8fd2_9bc280975fe0_h
#include <gslib\pool.h>
#include <gslib\string.h>
#include <gslib\std.h>
#include <rathen\config.h>
/*
* @ 2013.02.26
* New assemble tool for rathen. This version we gonna solve the problem that last version of rasm could not support labeled jump.
* In this version, every chuck of assembly code would be a separate and independent node, linked to a whole code segment, and the
* label would be a particular node in the tree. In this version, we would not need vslen to do the linkage stuff any more.
* And the short jump would be available.
* Plus, in this way, we could see the machine code correspond to every single assemble instruction, and yet we've been very close
* to a disassemble toolkit, but there were still some problems. The rathen didn't use all the x86 machine code. This assemble tool
* just concerned about a subset of all the x86 machine codes. I didn't intend to provide such a tool to decode all the machine codes
* into assemble, or rathen source code, either. As the optimize work we might probably did in the future, this decode works would
* be a hard problem, which was considered unnecessary.
*/
__rathen_begin__
enum reg
{
_regzr = 0,
_eax = 1,
_ecx = 2,
_edx,
_ebx,
_esp,
_ebp,
_esi,
_edi,
/* more to come... */
};
#ifdef _GS_X86
inline byte get_register_index(reg r)
{
switch(r)
{
case _eax: return 0;
case _ecx: return 1;
case _edx: return 2;
case _ebx: return 3;
case _esp: return 4; /* why "no index" */
case _ebp: return 5;
case _esi: return 6;
case _edi: return 7;
default: assert(0);
}
return -1;
}
typedef const gchar* lab;
#define __rasm_make_type(tname, dname) \
struct tname \
{ \
dname _data; \
\
explicit tname(dname d = (dname)0) { _data = d; } \
bool operator == (const tname& d) const { return _data == d._data; } \
dname inner_data() const { return _data; } \
}
__rasm_make_type(_bias_, int);
__rasm_make_type(_bias8_, int8);
__rasm_make_type(_bias16_, int16);
__rasm_make_type(_mem_, int);
__rasm_make_type(_reg_, reg);
enum cccc
{
cccc_o = 0,
cccc_no,
cccc_c,
cccc_nc,
cccc_e,
cccc_ne,
cccc_be,
cccc_a,
cccc_s,
cccc_ns,
cccc_p,
cccc_np,
cccc_l,
cccc_ge,
cccc_le,
cccc_g,
};
struct __gs_novtable rasm_instr abstract
{
virtual ~rasm_instr() {}
virtual const gchar* get_name() const = 0;
virtual bool finalize(vessel& vsl) = 0;
virtual void to_string(string& str) const = 0;
virtual bool compare(const rasm_instr* that) const = 0;
};
inline const gchar* nameofreg(reg r)
{
switch(r)
{
case _eax: return _t("eax");
case _ecx: return _t("ecx");
case _edx: return _t("edx");
case _ebx: return _t("ebx");
case _esp: return _t("esp");
case _ebp: return _t("ebp");
case _esi: return _t("esi");
case _edi: return _t("edi");
}
return 0;
}
template<class _in>
struct rasm_instr0:
public _in
{
virtual void to_string(string& str) const override { print(str, get_name(), _t(";")); }
virtual bool compare(const rasm_instr* that) const override { return strtool::compare(get_name(), that->get_name()) == 0; }
inline void print(string& str, const gchar* p, const gchar* a) const
{
if(p) { str += p; }
if(a) { str += a; }
}
inline void print(string& str, int n, const gchar* a) const
{
string s;
s.format(_t("%08x"), n);
str += s;
if(a) { str += a; }
}
inline void print(string& str, reg n, const gchar* a) const
{
string s;
s.format(_t("[%s]"), nameofreg(n));
str += s;
if(a) { str += a; }
}
inline void print(string& str, _bias8_ n, const gchar* a) const
{
string s;
s.format(_t("[s8:%02x]"), (int)n.inner_data());
str += s;
if(a) { str += a; }
}
inline void print(string& str, _bias16_ n, const gchar* a) const
{
string s;
s.format(_t("[s16:%04x]"), (int)n.inner_data());
str += s;
if(a) { str += a; }
}
inline void print(string& str, _bias_ n, const gchar* a) const
{
string s;
s.format(_t("[s:%08x]"), (int)n.inner_data());
str += s;
if(a) { str += a; }
}
inline void print(string& str, _mem_ n, const gchar* a) const
{
string s;
s.format(_t("[m:%08x]"), (int)n.inner_data());
str += s;
if(a) { str += a; }
}
inline void print(string& str, _reg_ n, const gchar* a) const
{
string s;
s.format(_t("[%s]"), nameofreg(n.inner_data()));
str += s;
if(a) { str += a; }
}
};
template<class c1>
struct rasm_instr1:
public rasm_instr0<rasm_instr>
{
typedef c1 type1;
typedef rasm_instr1<c1> myref;
c1 _data1;
rasm_instr1(c1 a) { _data1 = a; }
virtual void to_string(string& str) const override
{
print(str, get_name(), _t(" "));
print(str, _data1, _t(";"));
}
virtual bool compare(const rasm_instr* that) const override
{
if(strtool::compare(get_name(), that->get_name()) != 0)
return false;
const myref* ptr = static_cast<const myref*>(that);
return _data1 == ptr->_data1;
}
};
struct __gs_novtable rasm_link abstract:
public rasm_instr
{
virtual bool is_linker() const = 0;
virtual const string& get_label() const = 0;
};
struct rasm_linker;
struct rasm_label:
public rasm_instr0<rasm_link>
{
typedef rasm_linker linker;
typedef gs::vector<linker*> linker_list;
string _label;
linker_list _linkers;
public:
rasm_label(lab l) { _label.assign(l); }
virtual const gchar* get_name() const override { return _t("label"); }
virtual bool finalize(vessel& vsl) override { return true; }
virtual void to_string(string& str) const override;
virtual bool compare(const rasm_instr* that) const override;
virtual bool is_linker() const override { return false; }
virtual const string& get_label() const override { return _label; }
public:
int get_linker_ctr() const { return (int)_linkers.size(); }
rasm_linker* get_linker(int i) { return _linkers.at(i); }
void add_linker(linker* p) { _linkers.push_back(p); }
};
struct rasm_linker:
public rasm_instr0<rasm_link>
{
typedef lab type1;
typedef rasm_linker linker;
typedef gs::vector<linker*> linker_list;
string _label;
int _linkeeid;
linker_list _affects;
public:
rasm_linker(lab l): _linkeeid(0) { _label.assign(l); }
virtual void to_string(string& str) const override;
virtual bool compare(const rasm_instr* that) const override;
virtual bool is_linker() const override { return true; }
virtual const string& get_label() const override { return _label; }
public:
void set_linkee_index(int i) { _linkeeid = i; }
int get_linkee_index() const { return _linkeeid; }
void add_affects(linker* p) { _affects.push_back(p); }
};
template<class c1, class c2>
struct rasm_instr2:
public rasm_instr1<c1>
{
typedef c2 type2;
typedef rasm_instr2<c1, c2> myref;
c2 _data2;
rasm_instr2(c1 a, c2 b): rasm_instr1(a) { _data2 = b; }
virtual void to_string(string& str) const override
{
print(str, get_name(), _t(" "));
print(str, _data1, _t(","));
print(str, _data2, _t(";"));
}
virtual bool compare(const rasm_instr* that) const override
{
if(strtool::compare(get_name(), that->get_name()) != 0)
return false;
const myref* ptr = static_cast<const myref*>(that);
return _data1 == ptr->_data1 && _data2 == ptr->_data2;
}
};
template<class c1, class c2, class c3>
struct rasm_instr3:
public rasm_instr2<c1, c2>
{
typedef c3 type3;
typedef rasm_instr3<c1, c2, c3> myref;
c3 _data3;
rasm_instr3(c1 a, c2 b, c3 c): rasm_instr2(a, b) { _data3 = c; }
virtual void to_string(string& str) const override
{
print(str, get_name(), _t(" "));
print(str, _data1, _t(","));
print(str, _data2, _t(","));
print(str, _data3, _t(";"));
}
virtual bool compare(const rasm_instr* that) const override
{
if(strtool::compare(get_name(), that->get_name()) != 0)
return false;
const myref* ptr = static_cast<const myref*>(that);
return _data1 == ptr->_data1 && _data2 == ptr->_data2 && _data3 == ptr->_data3;
}
};
#define rasm_reginstr(in) \
static rasm_instr* make_##in(); \
void in() { _list.push_back(make_##in()); }
#define rasm_reginstr_i_begin(in, c1) \
static rasm_instr* make_##in(c1); \
void in(c1 a) {
#define rasm_reginstr_i_end(in) \
_list.push_back(make_##in(a)); }
#define rasm_reginstr_i(in, c1) \
rasm_reginstr_i_begin(in, c1) \
rasm_reginstr_i_end(in)
#define rasm_reginstr_ii_begin(in, c1, c2) \
static rasm_instr* make_##in(c1, c2); \
void in(c1 a, c2 b) {
#define rasm_reginstr_ii_end(in) \
_list.push_back(make_##in(a, b)); }
#define rasm_reginstr_ii(in, c1, c2) \
rasm_reginstr_ii_begin(in, c1, c2) \
rasm_reginstr_ii_end(in)
#define rasm_reginstr_iii_begin(in, c1, c2, c3) \
static rasm_instr* make_##in(c1, c2, c3); \
void in(c1 a, c2 b, c3 c) {
#define rasm_reginstr_iii_end(in) \
_list.push_back(make_##in(a, b, c)); }
#define rasm_reginstr_iii(in, c1, c2, c3) \
rasm_reginstr_iii_begin(in, c1, c2, c3) \
rasm_reginstr_iii_end(in)
#define rasm_reginstr_lab(in, c1) \
static rasm_instr* make_##in(c1); \
void in(c1 a) \
{ \
rasm_label* ptr = static_cast<rasm_label*>(make_##in(a)); \
assert(ptr && "alloc failed."); \
_list.push_back(ptr); \
verify(_label.insert(std::make_pair(ptr->get_label(), get_last_instruction_index())).second && "insert failed."); \
}
#define rasm_reginstr_lnk(in, c1) \
static rasm_instr* make_##in(c1); \
void in(c1 a) \
{ \
rasm_linker* ptr = static_cast<rasm_linker*>(make_##in(a)); \
assert(ptr && "alloc failed."); \
_list.push_back(ptr); \
_link.push_back(ptr); \
}
/*
* Only the 8 - bit offsets need this optimization, but DONOT apply such kind of optimizations to immediate operands,
* that might cause problems like "mov eax, 1" become "mov ah, 1", which was incorrect
*/
#define rasm_optimize_b8(calling, bparam) \
if((int)bparam.inner_data() > (int)-0x80 && (int)bparam.inner_data() < (int)0x80) \
return calling;
#define rasm_optimize_b16(calling, bparam) \
if((int)bparam.inner_data() > (int)-0x8000 && (int)bparam.inner_data() < (int)0x8000) \
return calling;
/*
* If a instruction was operated on the eax register, it could be optimized like:
*/
#define rasm_optimize_acc(calling, rparam) \
if(rparam == _eax) \
return calling;
/*
* Optimize for inc or dec
*/
#define rasm_optimize_i1(calling, iparam) \
if(iparam == 1) \
return calling;
/*
* Optimize for immediate operants less than 1 byte. Instructions like loop need this optimization
*/
#define rasm_optimize_i8(calling, iparam) \
if((int)iparam > (int)-0x80 && (int)iparam < (int)0x80) \
return calling;
class rasm
{
public:
typedef gs::vector<rasm_instr*> instr_list;
typedef gs::vector<rasm_link*> link_list;
typedef gs::unordered_map<gs::string, int> label_map; /* label name => index in instruction list */
public:
rasm() {}
~rasm();
void print(string& str) const;
int finalize(vessel& vsl);
int get_last_instruction_index() const;
//link get_label(lab l) { return _label.find(l); }
//link no_label() { return _label.end(); }
//const_link get_label(lab l) const { return _label.find(l); }
//const_link no_label() const { return _label.end(); }
//iterator get_current() { return _list.end(); }
//const_iterator get_current() const { return _list.end(); }
//iterator get_head() { return _list.begin(); }
//const_iterator get_head() const { return _list.begin(); }
//void attach(const_iterator pos, rasm& other);
//iterator tick() { return _list.size() ? -- _list.end() : _list.end(); }
//void tick(iterator& i) { i = tick(); }
protected:
instr_list _list;
label_map _label;
link_list _link;
public:
rasm_reginstr_ii(mov, reg, int8);
rasm_reginstr_ii(mov, reg, int);
rasm_reginstr_ii(mov, reg, reg);
rasm_reginstr_ii(mov, reg, _mem_);
rasm_reginstr_ii(mov, reg, _bias8_);
rasm_reginstr_ii_begin(mov, reg, _bias_)
rasm_optimize_b8(mov(a, (_bias8_)b.inner_data()), b)
rasm_reginstr_ii_end(mov);
rasm_reginstr_ii(mov, _mem_, reg);
rasm_reginstr_ii(mov, _bias8_, reg);
rasm_reginstr_ii_begin(mov, _bias_, reg)
rasm_optimize_b8(mov((_bias8_)a.inner_data(), b), a)
rasm_reginstr_ii_end(mov);
rasm_reginstr_ii(mov, _mem_, int);
rasm_reginstr_ii(mov, _bias8_, int);
rasm_reginstr_ii_begin(mov, _bias_, int)
rasm_optimize_b8(mov((_bias8_)a.inner_data(), b), a)
rasm_reginstr_ii_end(mov);
rasm_reginstr_ii(mov, reg, _reg_);
rasm_reginstr_ii(mov, _reg_, reg);
rasm_reginstr_ii(lea, reg, _bias8_);
rasm_reginstr_ii_begin(lea, reg, _bias_)
rasm_optimize_b8(lea(a, (_bias8_)b.inner_data()), b)
rasm_reginstr_ii_end(lea);
rasm_reginstr(nop);
rasm_reginstr(hlt);
rasm_reginstr_i(call, int);
rasm_reginstr_i(call, reg);
rasm_reginstr_i(call, _bias_);
rasm_reginstr_lnk(call, lab);
rasm_reginstr(ret);
rasm_reginstr_i(ret, int);
rasm_reginstr_i(push, reg);
rasm_reginstr_i(push, int8);
rasm_reginstr_i(push, int);
rasm_reginstr_i(push, _mem_);
rasm_reginstr_i(push, _bias8_);
rasm_reginstr_i_begin(push, _bias_)
rasm_optimize_b8(push((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(push);
rasm_reginstr_i(push, _reg_);
rasm_reginstr_i(pushw, _bias8_);
rasm_reginstr_i_begin(pushw, _bias_)
rasm_optimize_b8(pushw((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(pushw);
rasm_reginstr(pushad);
rasm_reginstr_i(pop, reg);
rasm_reginstr_i(pop, _mem_);
rasm_reginstr_i(pop, _bias8_);
rasm_reginstr_i_begin(pop, _bias_)
rasm_optimize_b8(pop((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(pop);
rasm_reginstr(popad);
rasm_reginstr_lab(label, lab);
rasm_reginstr_i(jmp, _mem_);
rasm_reginstr_i(jmp, _bias8_);
rasm_reginstr_i_begin(jmp, _bias_)
rasm_optimize_b8(jmp((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(jmp);
rasm_reginstr_i(jmp, reg);
rasm_reginstr_i(jmps, _bias8_); /* jmp bias from ss */
rasm_reginstr_i_begin(jmps, _bias_)
rasm_optimize_b8(jmps((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(jmps);
//rasm_reginstr_i(jmp, lab);
rasm_reginstr_lnk(jmp, lab);
rasm_reginstr_i(jes, _bias8_);
rasm_reginstr_i_begin(jes, _bias_)
rasm_optimize_b8(jes((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(jes);
rasm_reginstr_i(jnes, _bias8_);
rasm_reginstr_i_begin(jnes, _bias_)
rasm_optimize_b8(jnes((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(jnes);
rasm_reginstr_i(loop, int8);
rasm_reginstr_i_begin(loop, int) /* I'm not sure about this, can the loop instruction operate on a short? */
rasm_optimize_i8(loop((int8)a), (a - 2))
rasm_reginstr_i_end(loop);
rasm_reginstr_lnk(loop, lab);
rasm_reginstr(cld);
rasm_reginstr(std);
rasm_reginstr(movsb);
rasm_reginstr(movsw);
rasm_reginstr(movs);
rasm_reginstr(rep);
rasm_reginstr_ii(cmp, _bias_, int);
rasm_reginstr_ii(cmp, reg, int8);
rasm_reginstr_ii(cmp, reg, int);
rasm_reginstr_ii(cmp, reg, _bias8_);
rasm_reginstr_ii_begin(cmp, reg, _bias_)
rasm_optimize_b8(cmp(a, (_bias8_)b.inner_data()), b)
rasm_reginstr_ii_end(cmp);
rasm_reginstr_ii(cmp, _reg_, int8);
rasm_reginstr_ii(cmp, _reg_, int);
rasm_reginstr_ii(cmp, reg, _reg_);
rasm_reginstr_i(inc, reg);
rasm_reginstr_i(inc, _mem_);
rasm_reginstr_i(inc, _bias8_);
rasm_reginstr_i_begin(inc, _bias_)
rasm_optimize_b8(inc((_bias8_)a.inner_data()), a)
rasm_reginstr_i_end(inc);
rasm_reginstr_ii(add, reg, reg);
rasm_reginstr_ii(add, reg, int8);
rasm_reginstr_ii(add, reg, int);
rasm_reginstr_i(add, int);
rasm_reginstr_ii(add, reg, _mem_);
rasm_reginstr_ii(add, reg, _bias8_);
rasm_reginstr_ii(add, reg, _bias_);
rasm_reginstr_ii(add, _mem_, int8);
rasm_reginstr_ii(add, _mem_, int);
rasm_reginstr_ii(add, _bias8_, int8);
rasm_reginstr_ii(add, _bias_, int8);
rasm_reginstr_ii(add, _bias8_, int);
rasm_reginstr_ii(add, _bias_, int);
rasm_reginstr_ii(add, _mem_, reg);
rasm_reginstr_ii(add, _bias8_, reg);
rasm_reginstr_ii(add, _bias_, reg);
rasm_reginstr_ii(add, reg, _reg_);
rasm_reginstr_ii(add, _reg_, reg);
rasm_reginstr_i(dec, reg);
rasm_reginstr_i(dec, _mem_);
rasm_reginstr_i(dec, _bias_);
rasm_reginstr_ii(sub, reg, reg);
rasm_reginstr_ii(sub, reg, int);
rasm_reginstr_i(sub, int);
rasm_reginstr_ii(sub, reg, _mem_);
rasm_reginstr_ii(sub, reg, _bias_);
rasm_reginstr_ii(sub, _mem_, int);
rasm_reginstr_ii(sub, _bias_, int);
rasm_reginstr_ii(sub, _mem_, reg);
rasm_reginstr_ii(sub, _bias_, reg);
rasm_reginstr_ii(sub, reg, _reg_);
rasm_reginstr_ii(sub, _reg_, reg);
rasm_reginstr_iii(imul, reg, reg, int);
rasm_reginstr_ii(imul, reg, int);
rasm_reginstr_i(imul, reg);
rasm_reginstr_ii(imul, reg, _mem_);
rasm_reginstr_ii(imul, reg, _bias_);
rasm_reginstr_iii(imul, reg, _mem_, int);
rasm_reginstr_iii(imul, reg, _bias_, int);
rasm_reginstr_ii(imul, reg, reg);
rasm_reginstr_i(imul, _mem_);
rasm_reginstr_i(imul, _bias_);
rasm_reginstr_ii(imul, reg, _reg_);
rasm_reginstr_i(idiv, reg);
rasm_reginstr_i(idiv, _mem_);
rasm_reginstr_i(idiv, _bias_);
rasm_reginstr_i(idiv, _reg_);
rasm_reginstr(cdq);
rasm_reginstr_i(neg, reg);
rasm_reginstr_i(not, reg);
rasm_reginstr_ii(xor, reg, reg);
rasm_reginstr_ii(xor, reg, int);
rasm_reginstr_ii(xor, reg, _bias_);
rasm_reginstr_ii(xor, reg, _reg_);
rasm_reginstr_i(shl, reg);
rasm_reginstr_ii(shl, reg, int);
rasm_reginstr_i(shr, reg);
rasm_reginstr_ii(shr, reg, int);
//rasm_reginstr
//setcc
rasm_reginstr_ii(and, reg, int);
rasm_reginstr_ii(and, reg, _bias_);
rasm_reginstr_ii(and, reg, _reg_);
rasm_reginstr_ii(or , reg, int);
rasm_reginstr_ii(or , reg, _bias_);
rasm_reginstr_ii(or , reg, _reg_);
};
#endif
__rathen_end__
#endif | {
"alphanum_fraction": 0.6489988221,
"avg_line_length": 32.1895734597,
"ext": "h",
"hexsha": "bd1b78e0c9d22fbed36ebc250e13c40af14f5af6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/rathen/rasm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/rathen/rasm.h",
"max_line_length": 133,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/rathen/rasm.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 6207,
"size": 20376
} |
/*
* Copyright 2016 Maikel Nadolski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HMM_ALGORITHM_FORWARD_H_
#define HMM_ALGORITHM_FORWARD_H_
#include <utility>
#include <boost/iterator/iterator_facade.hpp>
#include <gsl_assert.h>
#include "maikel/hmm/hidden_markov_model.h"
namespace maikel { namespace hmm {
template <class InputIter, class T>
class forward_range_fn {
public:
using model = hidden_markov_model<T>;
using row_vector = typename model::row_vector;
using matrix = typename model::matrix;
using symbol_type = typename std::iterator_traits<InputIter>::value_type;
forward_range_fn() = delete;
forward_range_fn(InputIter seq_it, InputIter seq_end, model const& hmm)
: hmm_{&hmm}, seq_it_{seq_it}, seq_end_{seq_end},
alpha_{0,row_vector(hmm.states())}, prev_alpha_(hmm.states())
{
if (seq_it != seq_end)
initial_coefficients(*seq_it);
}
class iterator
: public boost::iterator_facade<
iterator, std::pair<T, row_vector>, std::input_iterator_tag,
std::pair<T, row_vector> const&
> {
public:
iterator() = default;
private:
friend class forward_range_fn;
friend class boost::iterator_core_access;
iterator(forward_range_fn& parent)
: parent_{parent ? &parent : nullptr} {}
forward_range_fn* parent_ = nullptr;
std::pair<T, row_vector> const& dereference() const
{
Expects(parent_ && *parent_);
return parent_->alpha_;
}
void increment()
{
Expects(parent_ && *parent_);
if (!parent_->next())
parent_ = nullptr;
}
bool equal(iterator other) const noexcept
{
return parent_ == other.parent_;
}
};
operator bool() const noexcept
{
return seq_it_ != seq_end_;
}
iterator begin() noexcept
{
return {*this};
}
iterator end() noexcept
{
return {};
}
private:
model const* hmm_; // not owning
InputIter seq_it_, seq_end_;
std::pair<T, row_vector> alpha_;
row_vector prev_alpha_;
void initial_coefficients(symbol_type s)
{
using size_type = typename hidden_markov_model<T>::size_type;
matrix const& B = hmm_->symbol_probabilities();
row_vector const& pi = hmm_->initial_distribution();
// check pre conditions
size_type states = pi.size();
size_type ob = gsl::narrow<size_type>(s);
Expects(B.rows() == states);
Expects(0 <= ob && ob < B.cols());
Expects(alpha_.second.size() == states);
// initial formula
T& scaling = alpha_.first;
row_vector& alpha = alpha_.second;
scaling = 0.0;
for (size_type i = 0; i < states; ++i) {
alpha(i) = pi(i)*B(i,ob);
scaling += alpha(i);
}
scaling = scaling ? 1/scaling : 0;
alpha *= scaling;
// check post conditions
Ensures((!scaling && almost_equal<T>(alpha.sum(), 0.0)) ||
( scaling && almost_equal<T>(alpha.sum(), 1.0)) );
}
void recursion_advance(symbol_type s)
{
using size_type = typename hidden_markov_model<T>::size_type;
matrix const& A = hmm_->transition_matrix();
matrix const& B = hmm_->symbol_probabilities();
prev_alpha_.swap(alpha_.second);
// check pre conditions
size_type states = A.rows();
Expects(A.cols() == states);
Expects(B.rows() == states);
Expects(prev_alpha_.size() == states);
size_type ob = gsl::narrow<size_type>(s);
Expects(0 <= ob && ob < B.cols());
// recursion formula
T& scaling = alpha_.first;
row_vector& alpha = alpha_.second;
scaling = 0.0;
for (size_type j = 0; j < states; ++j) {
alpha(j) = 0.0;
for (size_type i = 0; i < states; ++i)
alpha(j) += prev_alpha_(i)*A(i,j);
alpha(j) *= B(j, ob);
scaling += alpha(j);
}
scaling = scaling ? 1/scaling : 0;
alpha *= scaling;
// post conditions
Ensures((!scaling && almost_equal<T>(alpha.sum(), 0.0)) ||
( scaling && almost_equal<T>(alpha.sum(), 1.0)) );
}
bool next()
{
Expects(*this);
++seq_it_;
if (seq_it_ == seq_end_)
return false;
recursion_advance(*seq_it_);
return true;
}
};
template <class InputIter, class T>
forward_range_fn<InputIter, T>
forward(InputIter begin, InputIter end, hidden_markov_model<T> const& hmm)
{
return {begin, end, hmm};
}
} // namespace hmm
} // namespace maikel
#endif /* HMM_ALGORITHM_FORWARD_H_ */
| {
"alphanum_fraction": 0.5549903526,
"avg_line_length": 30.486631016,
"ext": "h",
"hexsha": "11ffdd54e5ea3ec1c370de0b20384d6b2eaccd71",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "maikel/Hidden-Markov-Model",
"max_forks_repo_path": "include/maikel/hmm/algorithm/forward.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "maikel/Hidden-Markov-Model",
"max_issues_repo_path": "include/maikel/hmm/algorithm/forward.h",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "maikel/hidden-markov-model",
"max_stars_repo_path": "include/maikel/hmm/algorithm/forward.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z",
"num_tokens": 1288,
"size": 5701
} |
#pragma once
#include "common.h"
#include "multibase.h"
#include "uvarint.h"
#include <gsl/gsl>
#include <map>
namespace multiformats {
enum hash_t {
dynamic_hash = -1,
sha1,
sha2_256
};
namespace details {
struct hashimpl {
hash_t key;
const char* name;
uint32_t code;
int32_t len;
};
constexpr hashimpl _HashTable[] = {
{ dynamic_hash, "dynamic_hash", 0x00, 0 },
{ sha1, "sha1", 0x11, 20 },
{ sha2_256, "sha2_256", 0x12, 32 },
};
constexpr int find_hashimpl_by_key(hash_t code) {
for (auto i = 0; i < _countof(_HashTable); i++)
if (_HashTable[i].key == code) return i;
return 0;
}
constexpr int find_hashimpl_by_code(uint32_t code) {
for (auto i = 0; i < _countof(_HashTable); i++)
if (_HashTable[i].code == code) return i;
return 0;
}
template <hash_t _Hash = dynamic_hash, int _Index = find_hashimpl_by_key(_Hash)>
class hashcode_type
{
public:
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
static_assert(_Index > 0, "The hash_t is not implemented");
constexpr hashcode_type(hash_t hash) { Expects(hash == _Hash); }
constexpr hash_t hash() const { return _HashTable[_Index].key; }
constexpr const char* name() const { return _HashTable[_Index].name; }
constexpr uint32_t code() const { return _HashTable[_Index].code; }
constexpr int32_t len() const { return _HashTable[_Index].len; }
constexpr int index() const { return _Index; }
};
template <>
class hashcode_type<dynamic_hash>
{
public:
explicit constexpr hashcode_type(hash_t hash) : _index(find_hashimpl_by_key(hash)) { Expects(_index > 0); }
const hash_t hash() const { return _HashTable[_index].key; }
const char* name() const { return _HashTable[_index].name; }
const uint32_t code() const { return _HashTable[_index].code; }
const int32_t len() const { return _HashTable[_index].len; }
const int index() const { return _index; }
private:
const int _index;
};
}
// A strongly typed byte buffer that contains an immutable representation of the output digest for a specific hash algorithm
// known at compile-time.
// The specialization with dynamic_hash is used when the hash function is not known at compile-time.
template <hash_t _Hash = dynamic_hash>
class digest_buffer
{
public:
// Construct empty
digest_buffer() : _hash(_Hash) {}
digest_buffer(hash_t hash) : _hash(hash) {}
// Construct by copying _Right
// - from bufferview_t
digest_buffer(bufferview_t _Right) : _buffer(std::begin(_Right), std::end(_Right)), _hash(_Hash)
{
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || _Right.size() == _hash.len());
}
digest_buffer(hash_t hash, bufferview_t _Right) : _buffer(std::begin(_Right), std::end(_Right)), _hash(hash)
{
Expects(!_Right.empty());
Expects(_hash.len() < 0 || _Right.size() == _hash.len());
}
// - from digest_buffer<>
digest_buffer(const digest_buffer<_Hash>& _Right) : _buffer(_Right._buffer), _hash(_Right.hash())
{
Expects(!_Right.empty());
}
template <hash_t _RightHash>
digest_buffer(const digest_buffer<_RightHash>& _Right) : _buffer(_Right._buffer), _hash(_Right.hash())
{
Expects(!_Right.empty());
}
// Construct by moving _Right
digest_buffer(buffer_t&& _Right) : _buffer(std::move(_Right)), _hash(_Hash)
{
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
}
digest_buffer(hash_t hash, buffer_t&& _Right) : _buffer(std::move(_Right)), _hash(hash) {}
digest_buffer(digest_buffer<_Hash>&& _Right) : _buffer(std::move(_Right._buffer)), _hash(_Right.hash()) {}
template <hash_t _RightHash>
digest_buffer(digest_buffer<_RightHash>&& _Right) : _string(std::move(_Right._buffer)), _hash(_Right.hash()) {}
// Assign by copying _Right
// Note: an digest_buffer<> is immutable once initialized
digest_buffer<_Hash>& operator =(bufferview_t _Right)
{
Expects(_buffer.empty() && !_Right.empty());
_buffer = _Right;
return *this;
}
digest_buffer<_Hash>& operator =(const digest_buffer<_Hash>& _Right)
{
Expects(_Right.hash() == hash());
Expects(_buffer.empty() && !_Right.empty());
_buffer = _Right._buffer;
return *this;
}
template <hash_t _RightHash>
digest_buffer<_Hash>& operator =(const digest_buffer<_RightHash>& _Right)
{
static_assert(_RightHash == _Hash || _RightHash == dynamic_hash || _Hash == dynamic_hash, "Mismatch between codes.");
Expects(_Right.hash() == hash());
Expects(_buffer.empty() && !_Right.empty());
_buffer = _Right._buffer;
return *this;
}
// Assign by moving _Right
// Note: an digest_buffer<> is immutable once initialized and cannot be emptied
digest_buffer<_Hash>& operator =(bufferview_t&& _Right)
{
Expects(_buffer.empty() && !_Right.empty());
_buffer = std::move(_Right);
return *this;
}
digest_buffer<_Hash>& operator =(digest_buffer<_Hash>&& _Right)
{
Expects(_Right.hash() == hash());
Expects(_buffer.empty() && !_Right.empty());
_buffer = std::move(_Right._buffer);
return *this;
}
template <hash_t _RightHash>
digest_buffer<_Hash>& operator =(digest_buffer<_RightHash>&& _Right)
{
static_assert(_RightHash == _Hash || _RightHash == dynamic_hash || _Hash == dynamic_hash, "Mismatch between codes.");
Expects(_Right.hash() == hash());
Expects(_buffer.empty() && !_Right.empty());
_buffer = std::move(_Right._buffer);
return *this;
}
auto hash() const { return _hash.hash(); }
auto data() const { return _buffer; }
auto code() const { return _hash.code(); }
auto empty() const { return _buffer.empty(); }
auto size() const { return _buffer.size(); }
auto begin() const { return _buffer.begin(); }
auto end() const { return _buffer.end(); }
private:
const details::hashcode_type<_Hash> _hash;
buffer_t _buffer;
template <hash_t _FriendHash> friend class digest_buffer;
};
// operator==
template <hash_t _HashLeft, hash_t _HashRight>
bool operator==(const digest_buffer<_HashLeft>& _Left, const digest_buffer<_HashRight>& _Right)
{
return (_Left.hash() == _Right.hash()) && (_Left.data() == _Right.data());
}
// A string that contains an encoded string in base _Base of a digest with algo _Hash
template <hash_t _Hash = dynamic_hash, base_t _Base = dynamic_base>
class digest_string : public encoded_string<_Base>
{
using string_t = encoded_string<_Base>;
public:
// Construct empty
digest_string() : string_t(), _hash(_Hash) {}
digest_string(hash_t hash) : string_t(), _hash(hash) {}
digest_string(base_t base) : string_t(base), _hash(_Hash) {}
digest_string(hash_t hash, base_t base) : string_t(base), _hash(hash) {}
// Construct by copying _Right
// - from string
digest_string(stringview_t _Right) : string_t(_Right), _hash(_Hash)
{
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(this->base(), _Right).size() == _hash.len());
}
digest_string(hash_t hash, stringview_t _Right) : string_t(_Right), _hash(hash)
{
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(this->base(), _Right).size() == _hash.len());
}
digest_string(base_t base, stringview_t _Right) : string_t(base, _Right), _hash(_Hash)
{
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(this->base(), _Right).size() == _hash.len());
}
digest_string(hash_t hash, base_t base, stringview_t _Right) : string_t(base, _Right), _hash(hash)
{
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(this->base(), _Right).size() == _hash.len());
}
digest_string(const char* _Right) : digest_string(gsl::ensure_z(_Right)) {}
digest_string(hash_t hash, const char* _Right) : digest_string(hash, gsl::ensure_z(_Right)) {}
digest_string(base_t base, const char* _Right) : digest_string(base, gsl::ensure_z(_Right)) {}
digest_string(hash_t hash, base_t base, const char* _Right) : digest_string(hash, base, gsl::ensure_z(_Right)) {}
// - from encoded_string<>
digest_string(const encoded_string<_Base>& _Right) : string_t(_Right), _hash(_Hash)
{
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
}
digest_string(hash_t hash, const encoded_string<_Base>& _Right) : string_t(_Right), _hash(hash)
{
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
}
template <base_t _RightBase>
digest_string(const encoded_string<_RightBase>& _Right) : string_t(_Right), _hash(_Hash)
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
static_assert(_Hash != dynamic_hash, "dynamic_hash is not allowed here");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
}
template <base_t _RightBase>
digest_string(hash_t hash, const encoded_string<_RightBase>& _Right) : string_t(_Right), _hash(hash)
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(!_Right.empty());
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
}
// - from digest_string<>
digest_string(const digest_string<_Hash, _Base>& _Right) : string_t(_Right), _hash(_Right.hash())
{
Expects(!_Right.empty());
}
template <hash_t _RightHash>
digest_string(const digest_string<_RightHash, _Base>& _Right) : string_t(_Right), _hash(_Right.hash())
{
static_assert(_RightHash == _Hash || _RightHash == dynamic_hash || _Hash == dynamic_hash, "Mismatch between codes.");
Expects(!_Right.empty());
}
template <base_t _RightBase>
digest_string(const digest_string<_Hash, _RightBase>& _Right) : string_t(_Right), _hash(_Right.hash())
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(!_Right.empty());
}
template <hash_t _RightHash, base_t _RightBase>
digest_string(const digest_string<_RightHash, _RightBase>& _Right) : string_t(_Right), _hash(_Right.hash())
{
static_assert(_RightHash == _Hash || _RightHash == dynamic_hash || _Hash == dynamic_hash, "Mismatch between codes.");
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(!_Right.empty());
}
// Assign by copying _Right
// Note: an digest_string<> is immutable once initialized
digest_string<_Hash, _Base>& operator =(stringview_t _Right)
{
Expects(_hash.len() < 0 || decode(this->base(), _Right).size() == _hash.len());
*((string_t*)this) = _Right;
return *this;
}
digest_string<_Hash, _Base>& operator =(const char* _Right)
{
return operator=(gsl::ensure_z(_Right));
}
digest_string<_Hash, _Base>& operator =(const encoded_string<_Base>& _Right)
{
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
*((string_t*)this) = _Right;
return *this;
}
template <base_t _RightBase>
digest_string<_Hash, _Base>& operator =(const encoded_string<_RightBase>& _Right)
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(_hash.len() < 0 || decode(_Right).size() == _hash.len());
*((string_t*)this) = _Right;
return *this;
}
digest_string<_Hash, _Base>& operator =(const digest_string<_Hash, _Base>& _Right)
{
Expects(_Right.hash() == hash());
*this = _Right.str();
return *this;
}
template <hash_t _RightHash, base_t _RightBase>
digest_string<_Hash, _Base>& operator =(const digest_string<_RightHash, _RightBase>& _Right)
{
static_assert(_RightHash == _Hash || _RightHash == dynamic_hash || _Hash == dynamic_hash, "Mismatch between codes.");
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(_Right.hash() == hash());
*this = _Right.str();
return *this;
}
hash_t hash() const { return _hash.hash(); }
private:
const details::hashcode_type<_Hash> _hash;
};
//
// Encode a digest into a _Base encoded_string
//
template <hash_t _Hash, base_t _Base>
digest_string<_Hash, _Base> encode(const digest_buffer<_Hash>& digest)
{
Expects(!digest.empty());
return encode<_Base>(digest);
}
template <hash_t _Hash>
digest_string<_Hash> encode(base_t base, const digest_buffer<_Hash>& digest)
{
Expects(!digest.empty());
return encode(base, digest);
}
inline digest_string<> encode(hash_t hash, base_t base, bufferview_t digest)
{
Expects(!digest.empty());
return { hash, encode(base, digest) };
}
template <hash_t _Hash, base_t _Base>
digest_buffer<_Hash> decode(digest_string<_Hash, _Base> digest)
{
return decode(static_cast<encoded_string<_Base>>(digest));
}
class multihash
{
public:
multihash(bufferview_t mhview)
{
auto posIt = mhview.begin();
// parse and check hash code
auto code = uint32_t{};
posIt = uvarint::decode(posIt, mhview.end(), &code);
auto index = details::find_hashimpl_by_code(code);
if (index == 0) throw std::invalid_argument("Failed to parse multihash buffer: wrong hash code");
_hash = details::_HashTable[index].key;
// parse and check size
posIt = uvarint::decode(posIt, mhview.end(), &_size);
if (static_cast<ptrdiff_t>(_size) != mhview.end() - posIt) throw std::invalid_argument("Failed to parse multihash buffer: wrong size");
if (details::_HashTable[index].len > 0 && _size != details::_HashTable[index].len) throw std::invalid_argument("Failed to parse multihash buffer: wrong size");
// Seems legit
_data.assign(mhview.begin(), mhview.end());
}
hash_t hash() const { return _hash; }
size_t size() const { return _size; }
bufferview_t digest() const { return bufferview_t{ _data }.last(_size); }
bufferview_t data() const { return _data; }
private:
hash_t _hash;
size_t _size;
buffer_t _data;
};
// Create a multihash from a digest_buffer
template <hash_t _Hash>
multihash to_multihash(digest_buffer<_Hash> digest) {
auto mh = buffer_t{};
uvarint::encode(digest.code(), std::back_inserter(mh));
uvarint::encode(digest.size(), std::back_inserter(mh));
mh.insert(mh.end(), digest.begin(), digest.end());
return { mh };
}
// Create a multihash from a digest_string
template <hash_t _Hash, base_t _Base>
multihash to_multihash(digest_string<_Hash, _Base> digest) { return to_multihash(decode(digest)); }
// Create a multihash from a raw digest_string
template <hash_t _Hash>
multihash to_multihash(bufferview_t digest) { return to_multihash(digest_buffer<_Hash>{ digest }); }
inline multihash to_multihash(hash_t hash, bufferview_t digest) { return to_multihash(digest_buffer<>{ hash, digest }); }
}
| {
"alphanum_fraction": 0.5767657787,
"avg_line_length": 40.3883928571,
"ext": "h",
"hexsha": "59a7207a1e4d74156ef83ce1374044f59a0880c9",
"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": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cedrou/multiformats",
"max_forks_repo_path": "include/multiformats/multihash.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"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": "cedrou/multiformats",
"max_issues_repo_path": "include/multiformats/multihash.h",
"max_line_length": 172,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cedrou/cpp-multiformats",
"max_stars_repo_path": "include/multiformats/multihash.h",
"max_stars_repo_stars_event_max_datetime": "2019-07-29T20:33:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-29T20:33:02.000Z",
"num_tokens": 4199,
"size": 18094
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
#include <cairo.h>
#include <gtk/gtk.h>
double globx;
double analytic(double w0, double t);
double spring_euler(double w0, double x);
void test_euler(GtkWidget *darea);
int func(double t, const double x[], double f[], void *params);
int jac(double t, const double x[], double *dfdy, double dfdt[], void *params);
int test_gsl(GtkWidget *darea);
void do_drawing(cairo_t *cr);
gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data);
gboolean terminate(GThread *thread);
void *thread_func(GtkWidget *entry) {
//test_euler(entry);
test_gsl(entry);
gdk_threads_add_idle((GSourceFunc)terminate, g_thread_self());
return NULL;
}
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *darea;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
darea = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), darea);
g_signal_connect(G_OBJECT(darea), "draw", G_CALLBACK(on_draw_event), NULL);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
gtk_window_set_title(GTK_WINDOW(window), "Spring simulation");
gtk_widget_show_all(window);
g_thread_new("eval", (GThreadFunc)thread_func, darea);
gtk_main();
return 0;
}
double analytic(double w0, double t) {
return cos(w0 * t);
}
// euler
double spring_euler(double w0, double x) {
return -w0 * w0 * x;
}
void test_euler(GtkWidget *darea) {
const int n = 1000;
// x - position
// v - speed
// t - time
// dt - step
// w0 = sqrt(k/m)
double x[n], v[n], t[n], dt;
const double w0 = 1.0;
x[0] = 1.0; v[0] = 0.0; t[0] = 0.0;
dt = 0.05;
int i;
for (i = 0; i < n - 1 ; i++) {
x[i+1] = x[i] + v[i] * dt;
v[i+1] = v[i] + spring_euler(w0, x[i]) * dt;
t[i+1] = t[i] + dt;
}
for (i = 0; i < n; i++) {
// draw
globx = x[i];
gtk_widget_queue_draw(darea);
printf("t: %f\tx: %f\tanalytic: \t%f\n", t[i], x[i], analytic(w0, t[i]));
g_usleep(10000);
}
}
// gsl
int func(double t, const double x[], double f[], void *params) {
// x' = v
// v' = -w0^2 * x
double w0 = *(double *) params;
f[0] = x[1];
f[1] = -w0 * w0 * x[0];
return GSL_SUCCESS;
}
int jac(double t, const double x[], double *dfdy, double dfdt[], void *params) {
double w0 = *(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, -w0 * w0);
gsl_matrix_set(m, 1, 1, 0.0);
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
int test_gsl(GtkWidget *darea) {
double w0 = 1.0;
gsl_odeiv2_system sys = { func, jac, 2, &w0 };
gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&sys, gsl_odeiv2_step_rk4, 0.05, 1e-6, 1e-6);
double t = 0.0;
double x[2] = { 1.0, 0.0 };
int i, s;
for (i = 0; i < 1000; i++) {
s = gsl_odeiv2_driver_apply_fixed_step(d, &t, 0.05, 1, x);
if (s != GSL_SUCCESS) {
printf ("error: driver returned %d\n", s);
break;
}
// draw
globx = x[0];
gtk_widget_queue_draw(darea);
printf("t: %.4f\tanalytic: %.8f\tx:%.8f\n", t, analytic(w0, t), x[0]);
g_usleep(10000);
}
gsl_odeiv2_driver_free(d);
return s;
}
// drawing
gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data) {
do_drawing(cr);
return FALSE;
}
void do_drawing(cairo_t *cr) {
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 1);
int k;
int prevy = 0;
cairo_move_to(cr, 200, 0);
for (k = 0; k < 20; k++) {
int j = k % 2 == 0 ? -1 : 1;
cairo_line_to(cr, 200 + j * 20, k*5*(globx + 1) + prevy);
prevy = k*2;
}
cairo_line_to(cr, 200, 100*(globx + 1) + prevy);
//cairo_stroke(cr);
cairo_rectangle(cr, 180, 100*(globx + 1) + prevy, 40, 40);
//cairo_stroke_preserve(cr);
//cairo_fill(cr);
cairo_stroke(cr);
}
// threads
gboolean terminate(GThread *thread) {
g_thread_join(thread);
//g_thread_unref(thread);
return FALSE;
} | {
"alphanum_fraction": 0.6368595825,
"avg_line_length": 22.3068783069,
"ext": "c",
"hexsha": "faa73b5080b7221e4403bbf31895fb2feea373e1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-15T09:06:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-15T09:06:12.000Z",
"max_forks_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Hoobie/spring-simulation",
"max_forks_repo_path": "spring_ode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93",
"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": "Hoobie/spring-simulation",
"max_issues_repo_path": "spring_ode.c",
"max_line_length": 99,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f21cd62d512bb55f1c29fe3e310f4a9352284d93",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Hoobie/spring-simulation",
"max_stars_repo_path": "spring_ode.c",
"max_stars_repo_stars_event_max_datetime": "2021-03-17T06:58:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-17T06:58:39.000Z",
"num_tokens": 1494,
"size": 4216
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_spmv (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1134)");
}
};
};
{
int order = 101;
int uplo = 121;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1135)");
}
};
};
{
int order = 101;
int uplo = 122;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1136)");
}
};
};
{
int order = 101;
int uplo = 122;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1137)");
}
};
};
{
int order = 102;
int uplo = 121;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1138)");
}
};
};
{
int order = 102;
int uplo = 121;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1139)");
}
};
};
{
int order = 102;
int uplo = 122;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1140)");
}
};
};
{
int order = 102;
int uplo = 122;
float alpha = 0.1f;
float beta = -0.3f;
int N = 2;
float A[] = { -0.174f, 0.878f, 0.478f };
float X[] = { 0.503f, 0.313f };
int incX = -1;
float Y[] = { -0.565f, -0.109f };
int incY = -1;
float y_expected[] = { 0.221025f, 0.0714172f };
cblas_sspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "sspmv(case 1141)");
}
};
};
{
int order = 101;
int uplo = 121;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1142)");
}
};
};
{
int order = 101;
int uplo = 121;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1143)");
}
};
};
{
int order = 101;
int uplo = 122;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1144)");
}
};
};
{
int order = 101;
int uplo = 122;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1145)");
}
};
};
{
int order = 102;
int uplo = 121;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1146)");
}
};
};
{
int order = 102;
int uplo = 121;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1147)");
}
};
};
{
int order = 102;
int uplo = 122;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1148)");
}
};
};
{
int order = 102;
int uplo = 122;
double alpha = -1;
double beta = 0.1;
int N = 2;
double A[] = { -0.181, -0.071, -0.038 };
double X[] = { -0.015, 0.132 };
int incX = -1;
double Y[] = { -0.449, -0.219 };
int incY = -1;
double y_expected[] = { -0.036098, 9.27e-04 };
cblas_dspmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dspmv(case 1149)");
}
};
};
}
| {
"alphanum_fraction": 0.4876936007,
"avg_line_length": 22.8818681319,
"ext": "c",
"hexsha": "d49b48b28991cae48e79845af7c930f550950948",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_spmv.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_spmv.c",
"max_line_length": 69,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_spmv.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 3541,
"size": 8329
} |
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <cblas.h>
#include <string.h> // memcpy
#include <math.h>
#include "cgraph.h"
#include "cg_operation.h"
#include "cg_types.h"
#include "cg_variables.h"
#include "cg_errors.h"
#include "cg_constants.h"
#include "cg_enums.h"
#include "cg_factory.h"
#include "cg_math.h"
void freeDoubleValue(CGDouble* v){
}
void freeVectorValue(CGVector* data){
free(data->data);
}
void freeMatrixValue(CGMatrix* data){
free(data->data);
}
void freeNode(CGraph* graph, CGNode* node){
//printf("freeing node %d\n", node->type);
if(node->result != NULL){
freeResultNode(node->result);
free(node->result);
node->result = NULL;
}
if(node->diff != NULL){
freeNode(graph, node->diff);
free(node->diff);
}
switch(node->type){
case CGNT_CONSTANT:{
switch(node->constant->type){
case CGVT_DOUBLE:
{
free(node->constant->value);
free(node->constant);
break;
}
case CGVT_VECTOR:{
CGVector* vec = (CGVector*)node->constant->value;
freeVectorValue(vec);
free(node->constant->value);
free(node->constant);
break;
}
case CGVT_MATRIX:{
CGMatrix* mat = (CGMatrix*)node->constant->value;
freeMatrixValue(mat);
free(node->constant->value);
free(node->constant);
break;
}
}
break;
}
case CGNT_VARIABLE:{
free(node->var);
break;
}
case CGNT_BINARY_OPERATION:
free(node->bop);
break;
case CGNT_UNARY_OPERATION:
free(node->uop);
break;
case CGNT_AXIS_BOUND_OPERATION:
free(node->axop);
break;
case CGNT_GRAPH:
free(node->graph);
break;
case CGNT_CROSS_ENTROPY_LOSS_FUNC:
free(node->crossEntropyLoss);
break;
}
}
void freeResultNode(CGResultNode* node){
if(node->error){
free(node->error);
free(node);
return;
}
switch(node->type){
case CGVT_DOUBLE:
freeDoubleValue(node->value);
break;
case CGVT_VECTOR:
freeVectorValue(node->value);
break;
case CGVT_MATRIX:
freeMatrixValue(node->value);
break;
}
free(node->value);
}
void freeGraph(CGraph* graph){
if(graph == NULL)
return;
const char *key;
map_iter_t iter = map_iter(&graph->vars);
while ((key = map_next(&graph->vars, &iter))) {
CGNode* node = *map_get(&graph->vars, key);
if(node != NULL){
freeNode(graph, node);
free(node);
}
}
map_deinit(&graph->vars);
int i = 0;
CGNode* node;
vec_foreach(&graph->nodes, node, i) {
freeNode(graph, node);
free(node);
}
vec_deinit(&graph->nodes);
// graph pointer must be freed elsewhere. in lua API we create a copy so we cannot free the parameter of this function.
}
/*
* Lua lightuser data are automatically freed within the lua VM,
* this version is lua friendly.
*/
void freeGraph_lua(CGraph* graph){
if(graph == NULL)
return;
const char *key;
map_deinit(&graph->vars);
int i = 0;
CGNode* node;
vec_deinit(&graph->nodes);
// graph pointer must be freed elsewhere. in lua API we create a copy so we cannot free the parameter of this function.
}
void freeNode_lua(CGraph* graph, CGNode* node){
//printf("freeing node %d\n", node->type);
if(node->result != NULL){
freeResultNode(node->result);
free(node->result);
node->result = NULL;
}
if(node->diff != NULL){
freeNode(graph, node->diff);
free(node->diff);
}
switch(node->type){
case CGNT_CONSTANT:{
switch(node->constant->type){
case CGVT_DOUBLE:
{
free(node->constant->value);
free(node->constant);
break;
}
case CGVT_VECTOR:{
CGVector* vec = (CGVector*)node->constant->value;
freeVectorValue(vec);
free(node->constant->value);
free(node->constant);
break;
}
case CGVT_MATRIX:{
CGMatrix* mat = (CGMatrix*)node->constant->value;
freeMatrixValue(mat);
free(node->constant->value);
free(node->constant);
break;
}
}
break;
}
case CGNT_VARIABLE:{
free(node->var);
break;
}
case CGNT_BINARY_OPERATION:
free(node->bop);
break;
case CGNT_UNARY_OPERATION:
free(node->uop);
break;
case CGNT_AXIS_BOUND_OPERATION:
free(node->axop);
break;
case CGNT_GRAPH:
free(node->graph);
break;
case CGNT_CROSS_ENTROPY_LOSS_FUNC:
free(node->crossEntropyLoss);
break;
}
}
| {
"alphanum_fraction": 0.6398441082,
"avg_line_length": 18.175,
"ext": "c",
"hexsha": "ae1bf6efff5838ecbd351a663927f011f1be08f2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z",
"max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "praisethemoon/ccgraph",
"max_forks_repo_path": "source/libcgraph/source/cg_free.c",
"max_issues_count": 27,
"max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af",
"max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Enehcruon/cgraph",
"max_issues_repo_path": "source/libcgraph/source/cg_free.c",
"max_line_length": 120,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Enehcruon/cgraph",
"max_stars_repo_path": "source/libcgraph/source/cg_free.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z",
"num_tokens": 1213,
"size": 4362
} |
#pragma once
#include "PropertyType.h"
#include <CesiumUtility/SpanHelper.h>
#include <gsl/span>
#include <cassert>
#include <cstddef>
namespace CesiumGltf {
template <typename ElementType> class MetadataArrayView {
public:
MetadataArrayView() : _valueBuffer{} {}
MetadataArrayView(const gsl::span<const std::byte>& buffer) noexcept
: _valueBuffer{
CesiumUtility::reintepretCastSpan<const ElementType>(buffer)} {}
const ElementType& operator[](int64_t index) const noexcept {
return _valueBuffer[index];
}
int64_t size() const noexcept {
return static_cast<int64_t>(_valueBuffer.size());
}
private:
gsl::span<const ElementType> _valueBuffer;
};
template <> class MetadataArrayView<bool> {
public:
MetadataArrayView() : _valueBuffer{}, _bitOffset{0}, _instanceCount{0} {}
MetadataArrayView(
const gsl::span<const std::byte>& buffer,
int64_t bitOffset,
int64_t instanceCount) noexcept
: _valueBuffer{buffer},
_bitOffset{bitOffset},
_instanceCount{instanceCount} {}
bool operator[](int64_t index) const noexcept {
index += _bitOffset;
const int64_t byteIndex = index / 8;
const int64_t bitIndex = index % 8;
const int bitValue =
static_cast<int>(_valueBuffer[byteIndex] >> bitIndex) & 1;
return bitValue == 1;
}
int64_t size() const noexcept { return _instanceCount; }
private:
gsl::span<const std::byte> _valueBuffer;
int64_t _bitOffset;
int64_t _instanceCount;
};
template <> class MetadataArrayView<std::string_view> {
public:
MetadataArrayView()
: _valueBuffer{}, _offsetBuffer{}, _offsetType{}, _size{0} {}
MetadataArrayView(
const gsl::span<const std::byte>& buffer,
const gsl::span<const std::byte>& offsetBuffer,
PropertyType offsetType,
int64_t size) noexcept
: _valueBuffer{buffer},
_offsetBuffer{offsetBuffer},
_offsetType{offsetType},
_size{size} {}
std::string_view operator[](int64_t index) const noexcept {
const size_t currentOffset =
getOffsetFromOffsetBuffer(index, _offsetBuffer, _offsetType);
const size_t nextOffset =
getOffsetFromOffsetBuffer(index + 1, _offsetBuffer, _offsetType);
return std::string_view(
reinterpret_cast<const char*>(_valueBuffer.data() + currentOffset),
(nextOffset - currentOffset));
}
int64_t size() const noexcept { return _size; }
private:
static size_t getOffsetFromOffsetBuffer(
size_t instance,
const gsl::span<const std::byte>& offsetBuffer,
PropertyType offsetType) noexcept {
switch (offsetType) {
case PropertyType::Uint8: {
assert(instance < offsetBuffer.size() / sizeof(uint8_t));
const uint8_t offset = *reinterpret_cast<const uint8_t*>(
offsetBuffer.data() + instance * sizeof(uint8_t));
return static_cast<size_t>(offset);
}
case PropertyType::Uint16: {
assert(instance < offsetBuffer.size() / sizeof(uint16_t));
const uint16_t offset = *reinterpret_cast<const uint16_t*>(
offsetBuffer.data() + instance * sizeof(uint16_t));
return static_cast<size_t>(offset);
}
case PropertyType::Uint32: {
assert(instance < offsetBuffer.size() / sizeof(uint32_t));
const uint32_t offset = *reinterpret_cast<const uint32_t*>(
offsetBuffer.data() + instance * sizeof(uint32_t));
return static_cast<size_t>(offset);
}
case PropertyType::Uint64: {
assert(instance < offsetBuffer.size() / sizeof(uint64_t));
const uint64_t offset = *reinterpret_cast<const uint64_t*>(
offsetBuffer.data() + instance * sizeof(uint64_t));
return static_cast<size_t>(offset);
}
default:
assert(false && "Offset type has unknown type");
return 0;
}
}
gsl::span<const std::byte> _valueBuffer;
gsl::span<const std::byte> _offsetBuffer;
PropertyType _offsetType;
int64_t _size;
};
} // namespace CesiumGltf
| {
"alphanum_fraction": 0.6836016097,
"avg_line_length": 30.5846153846,
"ext": "h",
"hexsha": "153f9d1fd44c935734786ee4e1a678e725da8c79",
"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": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JiangMuWen/cesium-native",
"max_forks_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"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": "JiangMuWen/cesium-native",
"max_issues_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1d9912307336c833b74b7e9b7bc715d0a4e6c7ec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JiangMuWen/cesium-native",
"max_stars_repo_path": "CesiumGltf/include/CesiumGltf/MetadataArrayView.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 977,
"size": 3976
} |
/*
* iaf_chxk_2008.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef IAF_CHXK_2008_H
#define IAF_CHXK_2008_H
// Generated includes:
#include "config.h"
#ifdef HAVE_GSL
// C includes:
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
// Includes from nestkernel:
#include "archiving_node.h"
#include "connection.h"
#include "event.h"
#include "nest_types.h"
#include "recordables_map.h"
#include "ring_buffer.h"
#include "universal_data_logger.h"
/* BeginDocumentation
Name: iaf_chxk_2008 - Conductance based leaky integrate-and-fire neuron model
used in Casti et al 2008.
Description:
iaf_chxk_2008 is an implementation of a spiking neuron using IAF dynamics with
conductance-based synapses [1]. It is modeled after iaf_cond_alpha with the
addition of after hyper-polarization current instead of a membrane potential
reset. Incoming spike events induce a post-synaptic change of conductance
modeled by an alpha function. The alpha function is normalized such that an
event of weight 1.0 results in a peak current of 1 nS at t = tau_syn.
Parameters:
The following parameters can be set in the status dictionary.
V_m double - Membrane potential in mV
E_L double - Leak reversal potential in mV.
C_m double - Capacity of the membrane in pF
V_th double - Spike threshold in mV.
E_ex double - Excitatory reversal potential in mV.
E_in double - Inhibitory reversal potential in mV.
g_L double - Leak conductance in nS.
tau_ex double - Rise time of the excitatory synaptic alpha function in ms.
tau_in double - Rise time of the inhibitory synaptic alpha function in ms.
I_e double - Constant input current in pA.
tau_ahp double - Afterhyperpolarization (AHP) time constant in ms.
E_ahp double - AHP potential in mV.
g_ahp double - AHP conductance in nS.
ahp_bug bool - Defaults to false. If true, behaves like original
model implementation.
References:
[1] Casti A, Hayot F, Xiao Y, and Kaplan E (2008) A simple model of retina-LGN
transmission. J Comput Neurosci 24:235-252.
Sends: SpikeEvent
Receives: SpikeEvent, CurrentEvent
Author: Heiberg
SeeAlso: iaf_cond_alpha
*/
namespace nest
{
/**
* Function computing right-hand side of ODE for GSL solver.
* @note Must be declared here so we can befriend it in class.
* @note Must have C-linkage for passing to GSL. Internally, it is
* a first-class C++ function, but cannot be a member function
* because of the C-linkage.
* @note No point in declaring it inline, since it is called
* through a function pointer.
* @param void* Pointer to model neuron instance.
*/
extern "C" int iaf_chxk_2008_dynamics( double, const double*, double*, void* );
/**
* Integrate-and-fire neuron model with two conductance-based synapses.
*/
class iaf_chxk_2008 : public Archiving_Node
{
// Boilerplate function declarations --------------------------------
public:
iaf_chxk_2008();
iaf_chxk_2008( const iaf_chxk_2008& );
~iaf_chxk_2008();
/**
* Import sets of overloaded virtual functions.
* @see Technical Issues / Virtual Functions: Overriding, Overloading, and
* Hiding
*/
using Node::handle;
using Node::handles_test_event;
port send_test_event( Node&, rport, synindex, bool );
bool
is_off_grid() const
{
return true;
} // uses off_grid events
port handles_test_event( SpikeEvent&, rport );
port handles_test_event( CurrentEvent&, rport );
port handles_test_event( DataLoggingRequest&, rport );
void handle( SpikeEvent& );
void handle( CurrentEvent& );
void handle( DataLoggingRequest& );
void get_status( DictionaryDatum& ) const;
void set_status( const DictionaryDatum& );
private:
void init_state_( const Node& proto );
void init_buffers_();
void calibrate();
void update( Time const&, const long, const long );
// END Boilerplate function declarations ----------------------------
// Friends --------------------------------------------------------
// make dynamics function quasi-member
friend int iaf_chxk_2008_dynamics( double, const double*, double*, void* );
// The next two classes need to be friends to access the State_ class/member
friend class RecordablesMap< iaf_chxk_2008 >;
friend class UniversalDataLogger< iaf_chxk_2008 >;
private:
// Parameters class -------------------------------------------------
//! Model parameters
struct Parameters_
{
double V_th; //!< Threshold Potential in mV
double g_L; //!< Leak Conductance in nS
double C_m; //!< Membrane Capacitance in pF
double E_ex; //!< Excitatory reversal Potential in mV
double E_in; //!< Inhibitory reversal Potential in mV
double E_L; //!< Leak reversal Potential (a.k.a. resting potential) in mV
double tau_synE; //!< Synaptic Time Constant Excitatory Synapse in ms
double tau_synI; //!< Synaptic Time Constant for Inhibitory Synapse in ms
double I_e; //!< Constant Current in pA
double tau_ahp; //!< Afterhyperpolarization (AHP) time constant
double g_ahp; //!< AHP conductance
double E_ahp; //!< AHP potential
bool ahp_bug; //!< If true, discard AHP conductance value from previous
//!< spikes
Parameters_(); //!< Set default parameter values
void get( DictionaryDatum& ) const; //!< Store current values in dictionary
void set( const DictionaryDatum& ); //!< Set values from dictionary
};
// State variables class --------------------------------------------
/**
* State variables of the model.
*
* State variables consist of the state vector for the subthreshold
* dynamics and the refractory count. The state vector must be a
* C-style array to be compatible with GSL ODE solvers.
*
* @note Copy constructor and assignment operator are required because
* of the C-style array.
*/
public:
struct State_
{
//! Symbolic indices to the elements of the state vector y
enum StateVecElems
{
V_M = 0,
DG_EXC,
G_EXC,
DG_INH,
G_INH,
DG_AHP,
G_AHP,
STATE_VEC_SIZE
};
//! state vector, must be C-array for GSL solver
double y[ STATE_VEC_SIZE ];
//!< number of refractory steps remaining
int r;
State_( const Parameters_& ); //!< Default initialization
State_( const State_& );
State_& operator=( const State_& );
void get( DictionaryDatum& ) const; //!< Store current values in dictionary
/**
* Set state from values in dictionary.
* Requires Parameters_ as argument to, e.g., check bounds.'
*/
void set( const DictionaryDatum&, const Parameters_& );
};
private:
// Buffers class --------------------------------------------------------
/**
* Buffers of the model.
* Buffers are on par with state variables in terms of persistence,
* i.e., initialized only upon first Simulate call after ResetKernel
* or ResetNetwork, but are implementation details hidden from the user.
*/
struct Buffers_
{
Buffers_( iaf_chxk_2008& ); //!<Sets buffer pointers to 0
Buffers_( const Buffers_&, iaf_chxk_2008& ); //!<Sets buffer pointers to 0
//! Logger for all analog data
UniversalDataLogger< iaf_chxk_2008 > logger_;
/** buffers and sums up incoming spikes/currents */
RingBuffer spike_exc_;
RingBuffer spike_inh_;
RingBuffer currents_;
/* GSL ODE stuff */
gsl_odeiv_step* s_; //!< stepping function
gsl_odeiv_control* c_; //!< adaptive step size control function
gsl_odeiv_evolve* e_; //!< evolution function
gsl_odeiv_system sys_; //!< struct describing system
// IntergrationStep_ should be reset with the neuron on ResetNetwork,
// but remain unchanged during calibration. Since it is initialized with
// step_, and the resolution cannot change after nodes have been created,
// it is safe to place both here.
double step_; //!< step size in ms
double IntegrationStep_; //!< current integration time step, updated by GSL
/**
* Input current injected by CurrentEvent.
* This variable is used to transport the current applied into the
* _dynamics function computing the derivative of the state vector.
* It must be a part of Buffers_, since it is initialized once before
* the first simulation, but not modified before later Simulate calls.
*/
double I_stim_;
};
// Variables class -------------------------------------------------------
/**
* Internal variables of the model.
* Variables are re-initialized upon each call to Simulate.
*/
struct Variables_
{
/**
* Impulse to add to DG_EXC on spike arrival to evoke unit-amplitude
* conductance excursion.
*/
double PSConInit_E;
/**
* Impulse to add to DG_INH on spike arrival to evoke unit-amplitude
* conductance excursion.
*/
double PSConInit_I;
/**
* Impulse to add to DG_AHP on spike generation to evoke unit-amplitude
* conductance excursion.
*/
double PSConInit_AHP;
};
// Access functions for UniversalDataLogger -------------------------------
//! Read out state vector elements, used by UniversalDataLogger
template < State_::StateVecElems elem >
double
get_y_elem_() const
{
return S_.y[ elem ];
}
//! Read out remaining refractory time, used by UniversalDataLogger
double
get_r_() const
{
return Time::get_resolution().get_ms() * S_.r;
}
double
get_I_syn_exc_() const
{
return S_.y[ State_::G_EXC ] * ( S_.y[ State_::V_M ] - P_.E_ex );
}
double
get_I_syn_inh_() const
{
return S_.y[ State_::G_INH ] * ( S_.y[ State_::V_M ] - P_.E_in );
}
double
get_I_ahp_() const
{
return S_.y[ State_::G_AHP ] * ( S_.y[ State_::V_M ] - P_.E_ahp );
}
// Data members -----------------------------------------------------------
// keep the order of these lines, seems to give best performance
Parameters_ P_;
State_ S_;
Variables_ V_;
Buffers_ B_;
//! Mapping of recordables names to access functions
static RecordablesMap< iaf_chxk_2008 > recordablesMap_;
};
// Boilerplate inline function definitions ----------------------------------
inline port
iaf_chxk_2008::send_test_event( Node& target,
rport receptor_type,
synindex,
bool )
{
SpikeEvent e;
e.set_sender( *this );
return target.handles_test_event( e, receptor_type );
}
inline port
iaf_chxk_2008::handles_test_event( SpikeEvent&, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
iaf_chxk_2008::handles_test_event( CurrentEvent&, rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
iaf_chxk_2008::handles_test_event( DataLoggingRequest& dlr,
rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return B_.logger_.connect_logging_device( dlr, recordablesMap_ );
}
inline void
iaf_chxk_2008::get_status( DictionaryDatum& d ) const
{
P_.get( d );
S_.get( d );
Archiving_Node::get_status( d );
( *d )[ names::recordables ] = recordablesMap_.get_list();
}
inline void
iaf_chxk_2008::set_status( const DictionaryDatum& d )
{
Parameters_ ptmp = P_; // temporary copy in case of errors
ptmp.set( d ); // throws if BadProperty
State_ stmp = S_; // temporary copy in case of errors
stmp.set( d, ptmp ); // throws if BadProperty
// We now know that (ptmp, stmp) are consistent. We do not
// write them back to (P_, S_) before we are also sure that
// the properties to be set in the parent class are internally
// consistent.
Archiving_Node::set_status( d );
// if we get here, temporaries contain consistent set of properties
P_ = ptmp;
S_ = stmp;
}
} // namespace
#endif // HAVE_GSL
#endif // IAF_CHXK_2008_H
| {
"alphanum_fraction": 0.667921864,
"avg_line_length": 29.5069444444,
"ext": "h",
"hexsha": "e6153e22014ce51ebb825060c7c8c982513019bb",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z",
"max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_forks_repo_path": "NEST-14.0-FPGA/models/iaf_chxk_2008.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster",
"max_issues_repo_path": "NEST-14.0-FPGA/models/iaf_chxk_2008.h",
"max_line_length": 79,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_stars_repo_path": "NEST-14.0-FPGA/models/iaf_chxk_2008.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z",
"num_tokens": 3265,
"size": 12747
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "tests.h"
void
test_syr2 (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
int N = 1;
int lda = 1;
float alpha = 0.0f;
float A[] = { 0.862f };
float X[] = { 0.823f };
int incX = -1;
float Y[] = { 0.699f };
int incY = -1;
float A_expected[] = { 0.862f };
cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "ssyr2(case 1434)");
}
};
};
{
int order = 101;
int uplo = 122;
int N = 1;
int lda = 1;
float alpha = 0.0f;
float A[] = { 0.862f };
float X[] = { 0.823f };
int incX = -1;
float Y[] = { 0.699f };
int incY = -1;
float A_expected[] = { 0.862f };
cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "ssyr2(case 1435)");
}
};
};
{
int order = 102;
int uplo = 121;
int N = 1;
int lda = 1;
float alpha = 0.0f;
float A[] = { 0.862f };
float X[] = { 0.823f };
int incX = -1;
float Y[] = { 0.699f };
int incY = -1;
float A_expected[] = { 0.862f };
cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "ssyr2(case 1436)");
}
};
};
{
int order = 102;
int uplo = 122;
int N = 1;
int lda = 1;
float alpha = 0.0f;
float A[] = { 0.862f };
float X[] = { 0.823f };
int incX = -1;
float Y[] = { 0.699f };
int incY = -1;
float A_expected[] = { 0.862f };
cblas_ssyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "ssyr2(case 1437)");
}
};
};
{
int order = 101;
int uplo = 121;
int N = 1;
int lda = 1;
double alpha = 0;
double A[] = { -0.824 };
double X[] = { 0.684 };
int incX = -1;
double Y[] = { 0.965 };
int incY = -1;
double A_expected[] = { -0.824 };
cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr2(case 1438)");
}
};
};
{
int order = 101;
int uplo = 122;
int N = 1;
int lda = 1;
double alpha = 0;
double A[] = { -0.824 };
double X[] = { 0.684 };
int incX = -1;
double Y[] = { 0.965 };
int incY = -1;
double A_expected[] = { -0.824 };
cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr2(case 1439)");
}
};
};
{
int order = 102;
int uplo = 121;
int N = 1;
int lda = 1;
double alpha = 0;
double A[] = { -0.824 };
double X[] = { 0.684 };
int incX = -1;
double Y[] = { 0.965 };
int incY = -1;
double A_expected[] = { -0.824 };
cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr2(case 1440)");
}
};
};
{
int order = 102;
int uplo = 122;
int N = 1;
int lda = 1;
double alpha = 0;
double A[] = { -0.824 };
double X[] = { 0.684 };
int incX = -1;
double Y[] = { 0.965 };
int incY = -1;
double A_expected[] = { -0.824 };
cblas_dsyr2(order, uplo, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr2(case 1441)");
}
};
};
}
| {
"alphanum_fraction": 0.4781012326,
"avg_line_length": 20.2819148936,
"ext": "c",
"hexsha": "9ba29598998dbabad91c432a16548433cac4b7d9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.c",
"max_line_length": 69,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_syr2.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": 1543,
"size": 3813
} |
#include <math.h>
#include <string.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_sf_erf.h>
#include "prob_functions.h"
#include "data.h"
static const double ALPHA_PRIOR_MEAN = 1, BETA_PRIOR_MEAN = 1;
double my_f (const gsl_vector *x, void *params)
{
Dataset *data = (Dataset *) params;
unpackX(x, data);
return - computeQ(data);
}
void my_df (const gsl_vector *x, void *params, gsl_vector *g)
{
int i, j;
Dataset *data = (Dataset *) params;
double *dQdAlpha = (double *) malloc(sizeof(double) * data->numLabelers * data->numWorkflows);
double *dQdBeta = (double *) malloc(sizeof(double) * data->numImages * data->numWorkflows);
unpackX(x, data);
gradientQ(data, dQdAlpha, dQdBeta);
/* Pack dQdAlpha and dQdBeta into gsl_vector */
for (i = 0; i < data->numLabelers * data->numWorkflows; i++) {
gsl_vector_set(g, i, - dQdAlpha[i]); /* Flip the sign since we want to minimize */
}
for (j = 0; j < data->numImages * data->numWorkflows; j++) {
gsl_vector_set(g, (data->numLabelers * data->numWorkflows) + j, - dQdBeta[j]); /* Flip the sign since we want to minimize */
}
free(dQdAlpha);
free(dQdBeta);
}
void my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g)
{
*f = my_f(x, params);
my_df(x, params, g);
}
void gradientQ (Dataset *data, double *dQdAlpha, double *dQdBeta)
{
int i, j;
int idx;
/* This comes from the priors */
/*RandoPriors*/
/*
for (i = 0; i < data->numLabelers; i++) {
dQdAlpha[i] = - 1 * (data->alpha[i] - data->priorAlpha[i]);
}
for (j = 0; j < data->numImages; j++) {
dQdBeta[j] = - 5 * (data->beta[j] - data->priorBeta[j]);
}
*/
/*Here's where the real shit starts*/
for (idx = 0; idx < data->numLabels; idx++) {
int i = data->labels[idx].labelerId;
int j = data->labels[idx].imageIdx;
int k = data->labels[idx].workflowId;
int alphaidx = k * data->numLabelers + i;
int betaidx = k * data->numImages + j;
int lij = data->labels[idx].label;
double sigma = prob(data->alpha[alphaidx], data->beta[betaidx]);
double increa, increb;
double weight = data->probZ1[j] * (lij - sigma) + data->probZ0[j] * (1 - lij - sigma);
//double weight = data->probZ1[j] * (2 * lij - 1) + data->probZ0[j] * (-2 * lij + 1);
increa = .5 * weight * log(1-data->beta[betaidx]) * pow( 1-data->beta[betaidx],
data->alpha[alphaidx] );
increb = -.5 * weight * data->alpha[alphaidx] * pow( 1-data->beta[betaidx],
data->alpha[alphaidx]-1 );
dQdAlpha[alphaidx] += increa;
dQdBeta[betaidx] += increb;
//printf("Alpha: %f Beta: %f", data->alpha[alphaidx], data->beta[betaidx]);
//printf("Blah%f %f %f\n", log(1-data->beta[j]), 1-data->beta[j], data->alpha[i]);
//printf("%d %d %d %f %f %f %f\n", i, j, lij, sigma, increa, increb, weight);
//printf("%f %f\n", data->probZ1[j], data->probZ0[j]);
/*
if ( isnan(prob(data->alpha[i], data->beta[j])) )
{
printf("%d %d\n", i, j);
printf("%f %f\n", data->probZ1[j], data->probZ0[j]);
printf("alpha %f beta %f\n", data->alpha[i], data->beta[j]);
printf("sigma %f\n", sigma);
printf("label %d\n", lij);
printf("prob: %f\n", prob);
printf("%f\n", pow( 1-data->beta[j], data->alpha[i]-1 ));
printf("%f\n", data->alpha[i]);
printf("%f %f\n", increa, increb);
}
fflush(0);
for (i = 0; i < data->numLabelers; i++) {
printf("i %d %f %f\n", i, data->alpha[i], dQdAlpha[i]);
}
for (j = 0; j < data->numImages; j++) {
printf("j %d %f %f\n", j, data->beta[j], dQdBeta[j]);
}
*/
}
}
/*
double computeLikelihood (Dataset *data)
{
int i, j;
int idx;
double L = 0;
double *alpha = data->alpha, *beta = data->beta;
for (j = 0; j < data->numImages; j++) {
double P1 = data->priorZ1[j];
double P0 = 1 - data->priorZ1[j];
for (idx = 0; idx < data->numLabels; idx++) {
if (data->labels[idx].imageIdx == j) {
int i = data->labels[idx].labelerId;
int lij = data->labels[idx].label;
double sigma = prob(alpha[i], beta[j]);
P1 *= pow(sigma, lij) * pow(1 - sigma, 1 - lij);
P0 *= pow(sigma, 1 - lij) * pow(1 - sigma, lij);
}
}
L += log(P1 + P0);
}
/// Add Gaussian (standard normal) prior for alpha
for (i = 0; i < data->numLabelers; i++) {
L += log(gsl_sf_erf_Z(alpha[i] - data->priorAlpha[i]));
}
/// Add Gaussian (standard normal) prior for beta
for (j = 0; j < data->numImages; j++) {
L += log(gsl_sf_erf_Z(beta[j] - data->priorBeta[j]));
}
return L;
}*/
double computeQ (Dataset *data)
{
int i, j;
int idx;
double Q = 0;
double *alpha = data->alpha, *beta = data->beta;
/* Start with the expectation of the sum of priors over all images */
for (j = 0; j < data->numImages; j++) {
Q += data->probZ1[j] * log(data->priorZ1[j]);
Q += data->probZ0[j] * log(1 - data->priorZ1[j]);
}
for (idx = 0; idx < data->numLabels; idx++) {
int i = data->labels[idx].labelerId;
int j = data->labels[idx].imageIdx;
int k = data->labels[idx].workflowId;
int alphaidx = k * data->numLabelers + i;
int betaidx = k * data->numImages + j;
int lij = data->labels[idx].label;
/* Do some analytic manipulation first for numerical stability! */
double logSigma = log( prob(alpha[alphaidx], beta[betaidx]) );
double logOneMinusSigma = log( 1-prob(alpha[alphaidx], beta[betaidx]) );
if (beta[betaidx] > 1 || beta[betaidx] < 0 || alpha[alphaidx] < 0) {
Q += -100000000000000000;
} else {
Q += data->probZ1[j] * (lij * logSigma + (1 - lij) * logOneMinusSigma) +
data->probZ0[j] * ((1 - lij) * logSigma + lij * logOneMinusSigma);
}
if (isnan(Q)) {
printf("%d %d %d %f %f %f %f %f %f %f %f\n", i, j, lij, logSigma,
logOneMinusSigma,
prob(alpha[i], beta[j]),
data->probZ1[j],
data->probZ0[j],
alpha[alphaidx],
beta[betaidx],
Q);
abort();
}
}
/* Add Gaussian (standard normal) prior for alpha */
for (i = 0; i < data->numLabelers * data->numWorkflows; i++) {
//Q += log(gsl_sf_erf_Z(alpha[i] - data->priorAlpha[i]));
}
/* Add Gaussian (standard normal) prior for beta */
for (j = 0; j < data->numImages * data->numWorkflows; j++) {
//Q += log(gsl_sf_erf_Z(beta[j] - data->priorBeta[j]));
}
// add penalty of beta not between 0 and 1
for (j = 0; j < data->numImages * data->numWorkflows; j++) {
if ( data->beta[j] > 1 || data->beta[j] < 0 ) {
Q -= 100;
}
}
return Q;
}
double logProbL (int l, int z, double alphaI, double betaJ)
{
double p;
if (z == l) {
p = log(prob(alphaI, betaJ));
} else {
p = log(1-prob(alphaI, betaJ));
}
/*
printf("p: %f\n", prob(alphaI, betaJ) );
printf("1-p: %f\n", 1-prob(alphaI, betaJ) );
printf("log: %f\n", p);
*/
return p;
}
double prob(double alpha, double beta)
{
return .5 + .5 * pow(1-beta, alpha);
}
void EStep (Dataset *data)
{
int j;
int idx;
/*
printf("begin Estep\n");
fflush(0);
*/
for (j = 0; j < data->numImages; j++) {
data->probZ1[j] = log(data->priorZ1[j]);
data->probZ0[j] = log(1 - data->priorZ1[j]);
//printf("%d %f %f\n", j, data->probZ1[j], data->probZ0[j]);
}
for (idx = 0; idx < data->numLabels; idx++) {
int i = data->labels[idx].labelerId;
int j = data->labels[idx].imageIdx;
int k = data->labels[idx].workflowId;
int alphaidx = k * data->numLabelers + i;
int betaidx = k * data->numImages + j;
int lij = data->labels[idx].label;
//printf("JOE%d %d %d %f %f\n", k, alphaidx, betaidx, data->alpha[alphaidx], data->beta[betaidx]);
data->probZ1[j] += logProbL(lij, 1, data->alpha[alphaidx],
data->beta[betaidx]);
data->probZ0[j] += logProbL(lij, 0, data->alpha[alphaidx],
data->beta[betaidx]);
//printf("%d %d %f %f\n", j, lij, data->probZ1[j], data->probZ0[j]);
}
/* Exponentiate and renormalize */
for (j = 0; j < data->numImages; j++) {
//printf("Before: %f %f\n", data->probZ1[j], data->probZ0[j]);
/*Chris adding code here to do this better */
double normalizingDenominator = data->probZ1[j] +
log(1 + exp(data->probZ0[j] -
data->probZ1[j]));
data->probZ1[j] = data->probZ1[j] - normalizingDenominator;
data->probZ0[j] = data->probZ0[j] - normalizingDenominator;
//printf("Hmm: %f %f %f\n", normalizingDenominator, data->probZ1[j], data->probZ0[j]);
data->probZ1[j] = exp(data->probZ1[j]);
data->probZ0[j] = exp(data->probZ0[j]);
/*
data->probZ1[j] = exp(data->probZ1[j]);
data->probZ0[j] = exp(data->probZ0[j]);
printf("%f %f\n", data->probZ1[j], data->probZ0[j]);
data->probZ1[j] = data->probZ1[j] / (data->probZ1[j] + data->probZ0[j]);
data->probZ0[j] = 1 - data->probZ1[j];
*/
//printf("%d %f %f\n", j, data->probZ1[j], data->probZ0[j]);
if (isnan(data->probZ1[j])) {
printf("ABORTING?");
abort();
}
}
/*
printf("end Estep\n");
fflush(0);
*/
}
void MStep (Dataset *data)
{
double lastF;
int iter, status;
int i, j;
int numLabelers = data->numLabelers;
int numImages = data->numImages;
int numWorkflows = data->numWorkflows;
gsl_vector *x;
gsl_multimin_fdfminimizer *s;
const gsl_multimin_fdfminimizer_type *T;
gsl_multimin_function_fdf my_func;
x = gsl_vector_alloc((numLabelers * numWorkflows) + (numImages * numWorkflows));
/* Pack alpha and beta into a gsl_vector */
packX(x, data);
/* Initialize objective function */
my_func.n = (numLabelers * numWorkflows) + (numImages * numWorkflows);
my_func.f = &my_f;
my_func.df = &my_df;
my_func.fdf = &my_fdf;
my_func.params = data;
/* Initialize minimizer */
T = gsl_multimin_fdfminimizer_conjugate_pr;
s = gsl_multimin_fdfminimizer_alloc(T, (numLabelers * numWorkflows) + (numImages * numWorkflows));
gsl_multimin_fdfminimizer_set(s, &my_func, x, 0.01, 0.01);
iter = 0;
do {
lastF = s->f;
iter++;
/*printf("iter=%d f=%f\n", iter, s->f);*/
status = gsl_multimin_fdfminimizer_iterate(s);
if (status) {
break;
}
status = gsl_multimin_test_gradient(s->gradient, 1e-3);
// } while (lastF - s->f > 0.01 && status == GSL_CONTINUE && iter < 25);
} while (iter < 5);
/* Unpack alpha and beta from gsl_vector */
unpackX(s->x, data);
gsl_multimin_fdfminimizer_free(s);
gsl_vector_free(x);
}
| {
"alphanum_fraction": 0.6066746126,
"avg_line_length": 28.7657142857,
"ext": "c",
"hexsha": "5dcc4ecf5cdd115bc888aca5c20726742bb8491b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ShreyaR/WorkerPoolSelection",
"max_forks_repo_path": "EM/prob_functions.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"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": "ShreyaR/WorkerPoolSelection",
"max_issues_repo_path": "EM/prob_functions.c",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ShreyaR/WorkerPoolSelection",
"max_stars_repo_path": "EM/prob_functions.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3549,
"size": 10068
} |
#include <stdio.h>
#include <stdlib.h>
// include files for optimized libraries
#if defined USE_ESSL
#include <essl.h>
#elif defined USE_MKL
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
#elif defined USE_LAPACK
#include <cblas.h>
#include <lapacke.h>
#endif
// interface to f2c code
#include "f2c.h"
#include "mrrr.h"
static inline int PCA_ssytd2(char uplo, int n, real *a, int lda, real *d, real *e, real *tau)
{
int info;
ssytd2_(&uplo, &n, a, &lda, d, e, tau, &info, 1);
return info;
}
static inline int PCA_sstemr(char jobz, char range, int n, real *d, real *e, real vl, real vu,
int il, int iu, int *m, real *w, real *z, int ldz, int nzc, int *isuppz, int *tryrac,
real *work, int lwork, int *iwork, int liwork)
{
int info;
pca_sstemr__(&jobz, &range, &n, d, e, &vl, &vu, &il, &iu, m, w, z, &ldz, &nzc, isuppz,
tryrac, work, &lwork, iwork, &liwork, &info, 1, 1);
return info;
}
static inline int PCA_sorm2l(char side, char trans, int m, int n, int k, real *a, int lda, real *tau, real *c, int ldc, real *work)
{
int info;
sorm2l_(&side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, work, &info, 1, 1);
return info;
}
#ifndef NO_PULP
#include "utils.h"
#include "hwTrace.h"
#endif
#if 1
#define ALLOC(t, v, s) t v[s];
#define FREE(v)
#else
#define ALLOC(t, v, s) t *v = malloc(sizeof(t) * (s));
#define FREE(v) free(v);
#endif
// PCA main routine
// input is a column-major matrix with a row for each sample and a column for each variable
// output is a column-major matrix with a row for each sample and a column for each component
void PCA_mrrr(int samples, int variables, float *input, int components, float *output)
{
int lwork = 18 * variables;
int liwork = 10 * variables;
ALLOC(real, A, variables * variables);
ALLOC(real, T, samples * variables);
ALLOC(real, d, variables);
ALLOC(real, e, variables);
ALLOC(real, tau, variables);
ALLOC(int, isuppz, variables * 2);
ALLOC(real, w, variables);
ALLOC(real, Z, variables * variables);
ALLOC(real, work, lwork);
ALLOC(int, iwork, liwork);
// pulp_trace_kernel_declare(0, "kernel 0");
// pulp_trace_kernel_start(0, 1);
// compute and subtract mean
for (int j = 0; j < variables; j++) {
real mean = 0.0;
#pragma omp parallel for reduction(+:mean)
for (int i = 0; i < samples; i++)
mean += input[j * samples + i];
mean /= samples;
#pragma omp parallel for
for (int i = 0; i < samples; i++)
T[j * samples + i] = input[j * samples + i] - mean;
}
// compute A=T^T*T
for (int j = 0; j < variables; j++)
for (int i = 0; i <= j; i++) {
real dot = 0;
#pragma omp parallel for reduction(+:dot)
for (int k = 0; k < samples; k++)
dot += T[j * samples + k] * T[i * samples + k];
A[i + j * variables] = dot;
}
// tridiagonalization
#if defined USE_MKL || USE_LAPACK
int info = LAPACKE_ssytrd(LAPACK_COL_MAJOR, 'U', variables, A, variables, d, e, tau);
#else
int info = PCA_ssytd2('U', variables, A, variables, d, e, tau);
#endif
if (info != 0) {
printf("Error in SSYTRD/SSYTD2: %i\n", info);
abort();
}
// compute eigenvalues
int il = variables - components + 1, iu = variables, m, tryrac = 1;
real vl = 0.0, vu = 0.0;
info = PCA_sstemr('V', 'I', variables, d, e, vl, vu, il, iu, &m, w, Z, variables, variables,
isuppz, &tryrac, work, lwork, iwork, liwork);
if (info != 0) {
printf("Error in SSTEMR: %i\n", info);
abort();
}
printf("%d: ", m);
for (int i = 0; i < m; i++) printf("%d ", (int)w[i]); printf("\n");
// compute eigenvectors
#if defined USE_MKL || USE_LAPACK
info = LAPACKE_sormtr(LAPACK_COL_MAJOR, 'L', 'U', 'N', variables, m, A, variables, tau,
Z, variables);
#else
info = PCA_sorm2l('L', 'N', variables - 1, m, variables - 1, A + variables, variables, tau,
Z, variables, work);
#endif
if (info != 0) {
printf("Error in SORMTR/SORM2L: %i\n", info);
abort();
}
#if defined USE_ESSL || USE_MKL || USE_LAPACK
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, samples, components, variables,
1.0, T, samples, Z, variables, 0.0, output, samples);
#else
#pragma omp parallel for
for (int i = 0; i < samples; i++)
for (int j = 0; j < components; j++) {
real t = 0;
for (int k = 0; k < variables; k++)
t += T[i + k * samples] * Z[j * variables + k];
output[i + j * samples] = t;
}
#endif
FREE(T);
FREE(A);
FREE(e);
FREE(d);
FREE(tau);
FREE(w);
FREE(Z);
FREE(isuppz);
FREE(work);
FREE(iwork);
// pulp_trace_kernel_stop(0, 1);
}
| {
"alphanum_fraction": 0.5743104158,
"avg_line_length": 29.0898203593,
"ext": "c",
"hexsha": "31e2a8d86896dd2d4128d9dca91139466f4b54bb",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-03T14:21:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-15T12:11:04.000Z",
"max_forks_repo_head_hexsha": "784280fea7f87be97bcde7a23a46b00f90351da6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "stmach/micro-benchmarks",
"max_forks_repo_path": "mb/pca/pca_mrrr.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "784280fea7f87be97bcde7a23a46b00f90351da6",
"max_issues_repo_issues_event_max_datetime": "2021-08-08T15:11:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-08T15:11:12.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "stmach/micro-benchmarks",
"max_issues_repo_path": "mb/pca/pca_mrrr.c",
"max_line_length": 131,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "784280fea7f87be97bcde7a23a46b00f90351da6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "stmach/micro-benchmarks",
"max_stars_repo_path": "mb/pca/pca_mrrr.c",
"max_stars_repo_stars_event_max_datetime": "2020-02-20T23:43:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-15T12:10:51.000Z",
"num_tokens": 1592,
"size": 4858
} |
#ifndef SmtkMatcher_h
#define SmtkMatcher_h
/** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <memory>
#include <QSharedPointer>
#include "SmtkStack.h"
#include "Gruen.h"
#include "SmtkPoint.h"
#include "GSLUtility.h"
#include <gsl/gsl_rng.h>
namespace Isis {
/**
* @brief Workhorse of stereo matcher
*
* This class provides stereo matching functionality to the SMTK toolkit. It
* registers points, clones them by adjusting parameters to nearby point
* locations and manages point selection processes.
*
* The Gruen algorithm is initialized here and maintained for use in the
* stereo matching process.
*
* @author 2011-05-28 Kris Becker
*
* @internal
* @history 2012-12-20 Debbie A. Cook - Removed unused Projection.h
* References #775.
* @history 2017-08-18 Summer Stapleton, Ian Humphrey, Tyler Wilson -
* Changed auto_ptr reference to QSharedPointer
* so this class compiles under C++14.
* References #4809.
*/
class SmtkMatcher {
public:
SmtkMatcher();
SmtkMatcher(const QString ®def);
SmtkMatcher(const QString ®def, Cube *lhImage, Cube *rhImage);
SmtkMatcher(Cube *lhImage, Cube *rhImage);
~SmtkMatcher();
void setImages(Cube *lhImage, Cube *rhImage);
void setGruenDef(const QString ®def);
bool isValid(const Coordinate &pnt);
bool isValid(const SmtkPoint &spnt);
/** Return pattern chip */
Chip *PatternChip() const {
validate();
return (m_gruen->PatternChip());
}
/** Return search chip */
Chip *SearchChip() const {
validate();
return (m_gruen->SearchChip());
}
/** Returns the fit chip */
Chip *FitChip() const {
validate();
return (m_gruen->FitChip());
}
void setWriteSubsearchChipPattern(const QString &fileptrn = "SmtkMatcher");
SmtkQStackIter FindSmallestEV(SmtkQStack &stack);
SmtkQStackIter FindExpDistEV(SmtkQStack &stack, const double &seedsample,
const double &minEV, const double &maxEV);
SmtkPoint Register(const Coordinate &lpnt,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const PointPair &pnts,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const SmtkPoint &spnt,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const PointGeometry &lpg, const PointGeometry &rpg,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Create(const Coordinate &left, const Coordinate &right);
SmtkPoint Clone(const SmtkPoint &point, const Coordinate &left);
inline BigInt OffImageErrorCount() const { return (m_offImage); }
inline BigInt SpiceErrorCount() const { return (m_spiceErr); }
/** Return Gruen template parameters */
PvlGroup RegTemplate() { return (m_gruen->RegTemplate()); }
/** Return Gruen registration statistics */
Pvl RegistrationStatistics() { return (m_gruen->RegistrationStatistics()); }
private:
SmtkMatcher &operator=(const SmtkMatcher &matcher); // Assignment disabled
SmtkMatcher(const SmtkMatcher &matcher); // Copy const disabled
Cube *m_lhCube; // Left image cube (not owned)
Cube *m_rhCube; // Right image cube (not owned)
QSharedPointer<Gruen> m_gruen; // Gruen matcher
BigInt m_offImage; // Offimage counter
BigInt m_spiceErr; // SPICE distance error
bool m_useAutoReg; // Select AutoReg features
const gsl_rng_type * T; // GSL random number type
gsl_rng * r; // GSL random number generator
void randomNumberSetup();
bool validate(const bool &throwError = true) const;
inline Camera &lhCamera() { return (*m_lhCube->camera()); }
inline Camera &rhCamera() { return (*m_rhCube->camera()); }
Coordinate getLineSample(Camera &camera, const Coordinate &geom);
Coordinate getLatLon(Camera &camera, const Coordinate &pnt);
bool inCube(const Camera &camera, const Coordinate &point) const;
SmtkPoint makeRegisteredPoint(const PointGeometry &left,
const PointGeometry &right, Gruen *gruen);
};
} // namespace Isis
#endif
| {
"alphanum_fraction": 0.650404772,
"avg_line_length": 35.2932330827,
"ext": "h",
"hexsha": "80c78332ab7b072489b31dd36bf7eb25b07f01b1",
"lang": "C",
"max_forks_count": 164,
"max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z",
"max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "jlaura/isis3",
"max_forks_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_issues_count": 3825,
"max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "kdl222/ISIS3",
"max_issues_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_line_length": 80,
"max_stars_count": 134,
"max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "kdl222/ISIS3",
"max_stars_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z",
"num_tokens": 1135,
"size": 4694
} |
//This does CELL (~soma) stage of minimal GRU (gated recurrent unit) model.
//This requires each neuron to have 2 input time series, X and Xf,
//where X is the usual input and Xf the input for the forget-gate.
//Both X and Xf are the output of a linear IN stage (weights and baises).
//For dim=0: F[:,t] = sig(Xf[:,t] + Uf*Y[:,t-1])
// H[:,t] = F[:,t].*Y[:,t-1]
// Y[:,t] = H[:,t] + (1-F[:,t]).*tanh(X[:,t] + U*H[:,t])
//
//For dim=1: F[t,:] = sig(Xf[t,:] + Y[t-1,:]*Uf)
// H[t,:] = F[t,:].*Y[t-1,:]
// Y[t,:] = H[t,:] + (1-F[t,:]).*tanh(X[t,:] + H[t,:]*U)
//
//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),
//F is the forget gate signal, H is an intermediate vector,
//U and Uf are NxN update matrices, and Y is the output.
//Note that, the neurons of a layer are independent only if U and Uf are diagonal matrices.
//This is only really a CELL (~soma) stage in that case.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int gru_min2_s (float *Y, const float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru_min2_d (double *Y, const double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru_min2_inplace_s (float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru_min2_inplace_d (double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);
int gru_min2_s (float *Y, const float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *F, *H;
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_min2_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_min2_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
F[0] = 1.0f / (1.0f+expf(-Xf[0]));
Y[0] = (1.0f-F[0]) * tanhf(X[0]);
for (size_t t=1; t<T; ++t)
{
F[0] = 1.0f / (1.0f+expf(-Xf[t]-Uf[0]*Y[t-1]));
H[0] = F[0] * Y[t-1];
Y[t] = H[0] + (1.0f-F[0])*tanhf(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-Xf[n]));
Y[n] = (1.0f-F[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xf[tN],1,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * Y[tN-N+n];
}
cblas_scopy((int)N,&X[tN],1,&Y[tN],1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = H[n] + (1.0f-F[n])*tanhf(Y[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0f / (1.0f+expf(-Xf[nT]));
Y[nT] = (1.0f-F[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xf[t],(int)T,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * Y[t-1+n*T];
}
cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = H[n] + (1.0f-F[n])*tanhf(Y[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0f / (1.0f+expf(-Xf[nT]));
Y[nT] = (1.0f-F[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xf[t],(int)T,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * Y[t-1+n*T];
}
cblas_scopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = H[n] + (1.0f-F[n])*tanhf(Y[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-Xf[n]));
Y[n] = (1.0f-F[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xf[tN],1,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * Y[tN-N+n];
}
cblas_scopy((int)N,&X[tN],1,&Y[tN],1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = H[n] + (1.0f-F[n])*tanhf(Y[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru_min2_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru_min2_d (double *Y, const double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *F, *H;
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_min2_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_min2_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
F[0] = 1.0 / (1.0+exp(-X[0]));
Y[0] = (1.0-F[0]) * tanh(X[0]);
for (size_t t=1; t<T; ++t)
{
F[0] = 1.0 / (1.0+exp(-X[t]-Uf[0]*Y[t-1]));
H[0] = F[0] * Y[t-1];
Y[t] = H[0] + (1.0-F[0])*tanh(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-Xf[n]));
Y[n] = (1.0-F[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xf[tN],1,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * Y[tN-N+n];
}
cblas_dcopy((int)N,&X[tN],1,&Y[tN],1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = H[n] + (1.0-F[n])*tanh(Y[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0 / (1.0+exp(-Xf[nT]));
Y[nT] = (1.0-F[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xf[t],(int)T,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * Y[t-1+n*T];
}
cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = H[n] + (1.0-F[n])*tanh(Y[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0 / (1.0+exp(-Xf[nT]));
Y[nT] = (1.0-F[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xf[t],(int)T,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * Y[t-1+n*T];
}
cblas_dcopy((int)N,&X[t],(int)T,&Y[t],(int)T);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
Y[t+nT] = H[n] + (1.0-F[n])*tanh(Y[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-Xf[n]));
Y[n] = (1.0-F[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xf[tN],1,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&Y[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * Y[tN-N+n];
}
cblas_dcopy((int)N,&X[tN],1,&Y[tN],1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&Y[tN],1);
for (size_t n=0u; n<N; ++n)
{
Y[tN+n] = H[n] + (1.0-F[n])*tanh(Y[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru_min2_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru_min2_inplace_s (float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const float o = 1.0f;
size_t nT, tN;
float *F, *H;
if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_min2_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in gru_min2_inplace_s: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
F[0] = 1.0f / (1.0f+expf(-X[0]));
X[0] = (1.0f-F[0]) * tanhf(X[0]);
for (size_t t=1; t<T; ++t)
{
F[0] = 1.0f / (1.0f+expf(-X[t]-Uf[0]*X[t-1]));
H[0] = F[0]*X[t-1];
X[t] = H[0] + (1.0f-F[0])*tanhf(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-Xf[n]));
X[n] = (1.0f-F[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xf[tN],1,F,1);
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * X[tN-N+n];
}
cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = H[n] + (1.0f-F[n])*tanhf(X[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0f / (1.0f+expf(-Xf[nT]));
X[nT] = (1.0f-F[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xf[t],(int)T,F,1);
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * X[t-1+n*T];
}
cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = H[n] + (1.0f-F[n])*tanhf(X[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0f / (1.0f+expf(-Xf[nT]));
X[nT] = (1.0f-F[n]) * tanhf(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_scopy((int)N,&Xf[t],(int)T,F,1);
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * X[t-1+n*T];
}
cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = H[n] + (1.0f-F[n])*tanhf(X[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-Xf[n]));
X[n] = (1.0f-F[n]) * tanhf(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_scopy((int)N,&Xf[tN],1,F,1);
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0f / (1.0f+expf(-F[n]));
H[n] = F[n] * X[tN-N+n];
}
cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = H[n] + (1.0f-F[n])*tanhf(X[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru_min2_inplace_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int gru_min2_inplace_d (double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim)
{
const double o = 1.0;
size_t nT, tN;
double *F, *H;
if (!(F=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_min2_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(H=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in gru_min2_inplace_d: problem with malloc. "); perror("malloc"); return 1; }
if (N==1u)
{
F[0] = 1.0 / (1.0+exp(-X[0]));
X[0] = (1.0-F[0]) * tanh(X[0]);
for (size_t t=1; t<T; ++t)
{
F[0] = 1.0 / (1.0+exp(-X[t]-Uf[0]*X[t-1]));
H[0] = F[0]*X[t-1];
X[t] = H[0] + (1.0-F[0])*tanh(X[t]+U[0]*H[0]);
}
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-Xf[n]));
X[n] = (1.0-F[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xf[tN],1,F,1);
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * X[tN-N+n];
}
cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = H[n] + (1.0-F[n])*tanh(X[tN+n]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0 / (1.0+exp(-Xf[nT]));
X[nT] = (1.0-F[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xf[t],(int)T,F,1);
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * X[t-1+n*T];
}
cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = H[n] + (1.0-F[n])*tanh(X[t+nT]);
}
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
F[n] = 1.0 / (1.0+exp(-Xf[nT]));
X[nT] = (1.0-F[n]) * tanh(X[nT]);
}
for (size_t t=1; t<T; ++t)
{
cblas_dcopy((int)N,&Xf[t],(int)T,F,1);
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[t-1],(int)T,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * X[t-1+n*T];
}
cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t],(int)T);
for (size_t n=0u; n<N; ++n)
{
nT = n*T;
X[t+nT] = H[n] + (1.0-F[n])*tanh(X[t+nT]);
}
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-Xf[n]));
X[n] = (1.0-F[n]) * tanh(X[n]);
}
for (size_t t=1; t<T; ++t)
{
tN = t*N;
cblas_dcopy((int)N,&Xf[tN],1,F,1);
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,Uf,(int)N,&X[tN-N],1,o,F,1);
for (size_t n=0u; n<N; ++n)
{
F[n] = 1.0 / (1.0+exp(-F[n]));
H[n] = F[n] * X[tN-N+n];
}
cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[tN],1);
for (size_t n=0u; n<N; ++n)
{
X[tN+n] = H[n] + (1.0-F[n])*tanh(X[tN+n]);
}
}
}
}
else
{
fprintf(stderr,"error in gru_min2_inplace_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.385767062,
"avg_line_length": 35.2864493997,
"ext": "c",
"hexsha": "6a4b032f0527a6fd42ae662dcd5b6a8aeed476af",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/gru_min2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/gru_min2.c",
"max_line_length": 170,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/gru_min2.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 7198,
"size": 20572
} |
// align.h
//
// prototypes for align.cc
//
// dw, 12/12/3
#ifndef _PTALIGN_H_
#define _PTALIGN_H_
#include <gsl/gsl_matrix.h>
#include <vector>
#include <cmath>
#include <map>
#include "pdb.h"
typedef double T3Matrix[3][3];
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
bool ptalign(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *);
bool ptalign(vector<vector<double> >&, vector<vector<double> >&, double*);
#endif
| {
"alphanum_fraction": 0.7085828343,
"avg_line_length": 18.5555555556,
"ext": "h",
"hexsha": "bc98dd08b4db826c7d49a7ea0f2b0b6fc0ef26a7",
"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": "a30e907e83fa5bbfb934d951b7c663b622104fcc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "tecdatalab/biostructure",
"max_forks_repo_path": "db/Updater/generators/LZerD/ptalign.h",
"max_issues_count": 15,
"max_issues_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5",
"max_issues_repo_issues_event_max_datetime": "2022-02-27T05:23:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-06-17T16:13:39.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "tecdatalab/legacy",
"max_issues_repo_path": "core/LZerD/ptalign.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "tecdatalab/legacy",
"max_stars_repo_path": "core/LZerD/ptalign.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 134,
"size": 501
} |
#pragma once
#include <boost/operators.hpp>
#include <cmath>
#include <gsl/gsl>
#include <iostream>
#include <nlohmann/json.hpp>
#include <numeric>
namespace Simulator {
template <class T, class Category> class UnitBase : public boost::multiplicative<T, double> {
public:
UnitBase() = default;
explicit constexpr UnitBase(double val) : _val(val) {}
explicit constexpr UnitBase(long double val) : _val(gsl::narrow_cast<double>(val)) {}
explicit constexpr UnitBase(int val) : _val(gsl::narrow<double>(val)) {}
explicit constexpr UnitBase(std::int64_t val) : _val(gsl::narrow<double>(val)) {}
explicit constexpr operator double() const noexcept { return _val; }
explicit constexpr operator int() const noexcept { return gsl::narrow_cast<int>(_val); }
explicit constexpr operator std::int64_t() const noexcept { return gsl::narrow_cast<std::int64_t>(_val); }
explicit constexpr operator float() const noexcept { return gsl::narrow_cast<float>(_val); }
constexpr bool operator<(const T &rhs) const noexcept { return _val < rhs._val; }
constexpr bool operator<=(const T &rhs) const noexcept { return _val <= rhs._val; }
constexpr bool operator>(const T &rhs) const noexcept { return _val > rhs._val; }
constexpr bool operator>=(const T &rhs) const noexcept { return _val >= rhs._val; }
constexpr bool operator==(const T &rhs) const noexcept { return _val == rhs._val; }
constexpr bool operator!=(const T &rhs) const noexcept { return !(*this == rhs); }
constexpr T &operator+=(const T &rhs) noexcept {
_val += rhs._val;
return static_cast<T &>(*this);
}
template <class U> constexpr T operator+(const UnitBase<U, Category> &rhs) const noexcept {
auto ret = *this;
return ret += rhs;
}
constexpr T &operator-=(const T &rhs) noexcept {
_val -= rhs._val;
return static_cast<T &>(*this);
}
template <class U> constexpr T operator-(const UnitBase<U, Category> &rhs) const noexcept {
auto ret = *this;
return ret -= rhs;
}
constexpr T &operator*=(double rhs) noexcept {
_val *= rhs;
return static_cast<T &>(*this);
}
constexpr T &operator/=(double rhs) noexcept {
_val /= rhs;
return static_cast<T &>(*this);
}
constexpr T operator-() const noexcept { return T(-_val); }
constexpr double operator/(const T &rhs) const noexcept { return _val / rhs._val; }
friend constexpr T abs(const T &x) noexcept { return T(std::abs(x._val)); }
friend constexpr T round(const T &x) noexcept { return T(std::round(x._val)); }
friend constexpr T floor(const T &x) noexcept { return T(std::floor(x._val)); }
friend constexpr T ceil(const T &x) noexcept { return T(std::ceil(x._val)); }
friend constexpr T fmod(const T &x, const T &y) { return T(std::fmod(x._val, y._val)); }
friend std::string to_string(const T &x) { return std::to_string(x._val); }
friend std::ostream &operator<<(std::ostream &os, const T &rhs) { return os << to_string(rhs); }
friend std::istream &operator>>(std::istream &is, T &rhs) {
is >> rhs._val;
return is;
}
[[nodiscard]] constexpr double getValue() const noexcept { return _val; }
protected:
double _val = 0;
};
// NOLINTNEXTLINE
#define DEFINE_UNIT(name, cat, s) \
class name : public UnitBase<name, cat> { \
public: \
static constexpr name infinity() { return name(std::numeric_limits<double>::infinity()); } \
using category = cat; \
static constexpr double scale = (s); \
using UnitBase<name, cat>::UnitBase; \
constexpr name(const UnitBase<name, cat> &other) : UnitBase<name, cat>(other) {} \
template <class U> \
constexpr name(const UnitBase<U, cat> &other) : UnitBase<name, cat>(other.getValue() * (U::scale / scale)) { \
static_assert(U::scale == U::scale && scale == scale); \
} \
}; \
inline void from_json(const nlohmann::json &j, name &v) { v = name(j.get<double>()); } \
inline void to_json(nlohmann::json &j, const name &v) { j = v.getValue(); }
struct MasteryCategory {};
DEFINE_UNIT(Mastery, MasteryCategory, 1.0);
struct CriticalRatingCategory {};
DEFINE_UNIT(CriticalRating, CriticalRatingCategory, 1.0);
struct AlacrityRatingCategory {};
DEFINE_UNIT(AlacrityRating, AlacrityRatingCategory, 1.0);
struct PowerCategory {};
DEFINE_UNIT(Power, PowerCategory, 1.0);
struct ForceTechDamageCategory {};
DEFINE_UNIT(FTPower, ForceTechDamageCategory, 1.0);
struct AccuracyRatingCategory {};
DEFINE_UNIT(AccuracyRating, AccuracyRatingCategory, 1.0);
struct TimeCategory {};
DEFINE_UNIT(Second, TimeCategory, 1.0);
DEFINE_UNIT(Minute, TimeCategory, 60.0);
constexpr Second _tinyTime{1e-7};
struct HealthCategory {};
DEFINE_UNIT(HealthPoints, HealthCategory, 1.0);
struct ArmorCatergory {};
DEFINE_UNIT(Armor, ArmorCatergory, 1.0);
struct EnergyCategory {};
DEFINE_UNIT(EnergyCost, EnergyCategory, 1.0);
} // namespace Simulator
| {
"alphanum_fraction": 0.5621965511,
"avg_line_length": 48.9590163934,
"ext": "h",
"hexsha": "5e37ef31da979a9d3cbe4c055e449b472ed52091",
"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": "4d2866f997fc3f75b69a97dd5fc474227185de81",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tomcool420/SimulatorSWTOR",
"max_forks_repo_path": "Simulator/SimulatorBase/detail/units.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4d2866f997fc3f75b69a97dd5fc474227185de81",
"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": "tomcool420/SimulatorSWTOR",
"max_issues_repo_path": "Simulator/SimulatorBase/detail/units.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4d2866f997fc3f75b69a97dd5fc474227185de81",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tomcool420/SimulatorSWTOR",
"max_stars_repo_path": "Simulator/SimulatorBase/detail/units.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1313,
"size": 5973
} |
//
// hemm.h
// Linear Algebra Template Library
//
// Created by Rodney James on 1/6/12.
// Copyright (c) 2012 University of Colorado Denver. All rights reserved.
//
#ifndef _hemm_h
#define _hemm_h
/// @file hemm.h Performs general Hermitian complex matrix-matrix multiplication.
#include <cctype>
#include "latl.h"
namespace LATL
{
/// @brief Performs general Hermitian complex matrix-matrix multiplication.
///
/// For complex matrices B and C, Hermitian matrix A, and complex scalars alpha and beta,
///
/// C := alpha*A*B + beta*C or C := 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 side Specifies whether the matrix A appears on the left or right side as follows:
///
/// if side = 'L' or 'l' then C := alpha*A*B + beta*C,
/// if side = 'R' or 'r' then C := alpha*B*A + beta*C.
/// @param uplo Specifies whether the upper or lower triangular part of the Hermitian matrix A
/// is to be referenced:
///
/// if uplo = 'U' or 'u' then A is upper triangular,
/// if uplo = 'L' or 'l' then A is lower triangular.
/// @param m Specifies the number of rows of the matrices B and C. m>=0
/// @param n Specifies the number of columns of the matrices B and C. n>=0
/// @param alpha Complex scalar.
/// @param A Pointer to complex Hermitian matrix A. If side = 'L' or 'l', then A is m-by-m;
/// if side = 'R' or 'r', then A is n-by-n.
/// @param ldA Column length of the matrix A. If side = 'L' or 'l', ldA>=m. If side = 'R' or 'r', ldA>=n.
/// @param B Pointer to complex m-by-n matrix B.
/// @param ldB Column length of the matrix B. ldB>=m.
/// @param beta Complex scalar.
/// @param C Pointer to complex m-by-n matrix C.
/// @param ldC Column length of the matrix C. ldC>=m.
/// @ingroup BLAS
template <typename real_t>
int HEMM(char side, char uplo, int_t m, int_t n, 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::conj;
using std::real;
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,k;
complex<real_t> *a,*b,*c,*at,*bt;
complex<real_t> s,t;
side=toupper(side);
uplo=toupper(uplo);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(ldA<((side=='L')?m:n))
return -7;
else if(ldB<m)
return -9;
else if(ldC<m)
return -12;
else if((m==0)||(n==0)||((alpha==zero)&&(beta==one)))
return 0;
if(alpha==zero)
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
c+=ldC;
}
}
else if(side=='L')
{
if(uplo=='U')
{
b=B;
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
t=alpha*b[i];
s=zero;
for(k=0;k<i;k++)
{
c[k]+=t*a[k];
s+=b[k]*conj(a[k]);
}
c[i]=beta*c[i]+t*real(a[i])+alpha*s;
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else
{
b=B;
c=C;
for(j=0;j<n;j++)
{
a=A+m*ldA;
for(i=m-1;i>=0;i--)
{
a-=ldA;
t=alpha*b[i];
s=zero;
for(k=i+1;k<m;k++)
{
c[k]+=t*a[k];
s+=b[k]*conj(a[k]);
}
c[i]=beta*c[i]+t*real(a[i])+alpha*s;
}
b+=ldB;
c+=ldC;
}
}
}
else
{
if(uplo=='U')
{
a=A;
c=C;
b=B;
for(j=0;j<n;j++)
{
t=alpha*real(a[j]);
for(i=0;i<m;i++)
c[i]=c[i]*beta+t*b[i];
bt=B;
for(k=0;k<j;k++)
{
t=alpha*a[k];
for(i=0;i<m;i++)
c[i]+=bt[i]*t;
bt+=ldB;
}
at=A+(j+1)*ldA;
bt=B+(j+1)*ldB;
for(k=j+1;k<n;k++)
{
t=alpha*conj(at[j]);
for(i=0;i<m;i++)
c[i]+=t*bt[i];
at+=ldA;
bt+=ldB;
}
a+=ldA;
b+=ldB;
c+=ldC;
}
}
else
{
a=A;
c=C;
b=B;
for(j=0;j<n;j++)
{
t=alpha*real(a[j]);
for(i=0;i<m;i++)
c[i]=c[i]*beta+t*b[i];
bt=B;
at=A;
for(k=0;k<j;k++)
{
t=alpha*conj(at[j]);
for(i=0;i<m;i++)
c[i]+=bt[i]*t;
at+=ldA;
bt+=ldB;
}
bt=B+(j+1)*ldB;
for(k=j+1;k<n;k++)
{
t=alpha*at[k];
for(i=0;i<m;i++)
c[i]+=t*bt[i];
bt+=ldB;
}
a+=ldA;
b+=ldB;
c+=ldC;
}
}
}
return 0;
}
#ifdef __latl_cblas
#include <cblas.h>
template <> int HEMM<float>(char side, char uplo, int_t m, int_t n, 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;
side=toupper(side);
uplo=toupper(uplo);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(ldA<((side=='L')?m:n))
return -7;
else if(ldB<m)
return -9;
else if(ldC<m)
return -12;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
cblas_chemm(CblasColMajor,Side,Uplo,m,n,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
template <> int HEMM<double>(char side, char uplo, int_t m, int_t n, 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;
side=toupper(side);
uplo=toupper(uplo);
if((side!='L')&&(side!='R'))
return -1;
else if((uplo!='U')&&(uplo!='L'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(ldA<((side=='L')?m:n))
return -7;
else if(ldB<m)
return -9;
else if(ldC<m)
return -12;
const CBLAS_SIDE Side=(side=='L')?CblasLeft:CblasRight;
const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower;
cblas_zhemm(CblasColMajor,Side,Uplo,m,n,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
#endif
}
#endif
| {
"alphanum_fraction": 0.421810166,
"avg_line_length": 28.0436363636,
"ext": "h",
"hexsha": "ed33b2880d40879a5be0b62ff849e9a33f4f4a00",
"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/hemm.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/hemm.h",
"max_line_length": 209,
"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/hemm.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": 2188,
"size": 7712
} |
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <stdbool.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/pt.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/covariances_3D.c"
#include "../cosmolike_core/theory/covariances_fourier.c"
#include "../cosmolike_core/theory/CMBxLSS_fourier.c"
#include "../cosmolike_core/theory/covariances_CMBxLSS_fourier.c"
#include "../cosmolike_core/theory/covariances_binned_simple.c"
#include "../cosmolike_core/theory/run_covariances_fourier_binned_6x2pt.c"
#include "init_LSSxCMB.c"
int main(int argc, char** argv)
{
int i,l,m,n,o,s,p,nl1,t,k;
char OUTFILE[400],filename[400],arg1[400],arg2[400];
int N_scenarios=2;
double area_table[2]={12300.0,16500.0}; // Y1 corresponds to DESC SRD Y1, Y6 corresponds to assuming that we cover the full SO area=0.4*fsky and at a depth of 26.1 which is in a range of reasonable scenarios (see https://github.com/LSSTDESC/ObsStrat/tree/static/static )
double nsource_table[2]={11.0,23.0};
double nlens_table[2]={18.0,41.0};
char survey_designation[2][200]={"LSSTxSO_Y1","LSSTxSO_Y6"};
char source_zfile[2][400]={"src_LSSTY1","src_LSSTY6"};
#ifdef ONESAMPLE
char lens_zfile[2][400]={"src_LSSTY1","src_LSSTY6"};
nlens_table[0] = nsource_table[0];
nlens_table[1] = nsource_table[1];
#else
char lens_zfile[2][400]={"lens_LSSTY1","lens_LSSTY6"};
#endif
int hit=atoi(argv[1]);
Ntable.N_a=100;
k=1;
t = atoi(argv[2]);
//RUN MODE setup
init_cosmo_runmode("emu");
// init_binning_fourier(20,30.0,3000.0,3000.0,21.0,10,10);
init_binning_fourier(15,20.0,3000.0,3000.0,0.0,10,10);
init_survey(survey_designation[t],nsource_table[t],nlens_table[t],area_table[t]);
sprintf(arg1,"zdistris/%s",source_zfile[t]);
sprintf(arg2,"zdistris/%s",lens_zfile[t]);
init_galaxies(arg1,arg2,"none","none","source_std","LSST_gold");
init_IA("none","GAMA");
init_probes("6x2pt");
if(t==0) init_cmb("so_Y1");
if(t==1) init_cmb("so_Y5");
cmb.fsky = survey.area*survey.area_conversion_factor/(4.*M_PI);
//set l-bins for shear, ggl, clustering, clusterWL
double lmin=like.lmin;
double lmax=like.lmax;
int Nell=like.Ncl;
int Ncl = Nell;
double logdl=(log(lmax)-log(lmin))/Nell;
double *ellmin, *dell;
ellmin=create_double_vector(0,Nell);
dell=create_double_vector(0,Nell-1);
double ellmax;
for(i=0; i<Nell ; i++){
ellmin[i]=exp(log(lmin)+(i+0.0)*logdl);
ellmax = exp(log(lmin)+(i+1.0)*logdl);
dell[i]=ellmax-ellmin[i];
}
ellmin[Nell] = ellmax;
like.ell = ellmin;
covparams.ng = 1;
covparams.cng= 0;
printf("----------------------------------\n");
sprintf(survey.name,"%s_area%le_ng%le_nl%le",survey_designation[t],survey.area,survey.n_gal,survey.n_lens);
printf("area: %le n_source: %le n_lens: %le\n",survey.area,survey.n_gal,survey.n_lens);
// sprintf(covparams.outdir,"/home/u17/timeifler/covparallel/");
#ifdef ONESAMPLE
sprintf(covparams.outdir,"out_cov_lsstxso_1sample/");
#else
sprintf(covparams.outdir,"out_cov_lsstxso/");
//sprintf(covparams.outdir,"/halo_nobackup/cosmos/teifler/covparallel/");
#endif
printf("----------------------------------\n");
if (like.shear_shear)
{
sprintf(OUTFILE,"%s_ssss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Npowerspectra; l++){
for (m=l;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_shear_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.pos_pos)
{
sprintf(OUTFILE,"%s_llll_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=l;m<tomo.clustering_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.shear_pos)
{
sprintf(OUTFILE,"%s_lsls_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=l;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.shear_pos && like.shear_shear)
{
sprintf(OUTFILE,"%s_lsss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ggl_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.pos_pos && like.shear_shear)
{
sprintf(OUTFILE,"%s_llss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_clustering_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.pos_pos && like.shear_pos)
{
sprintf(OUTFILE,"%s_llls_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_clustering_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.gk && like.shear_shear)
{
sprintf(OUTFILE,"%s_lkss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Nbin; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_gk_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.ks && like.shear_shear)
{
sprintf(OUTFILE,"%s_ksss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Nbin; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ks_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.gk && like.shear_pos)
{
sprintf(OUTFILE,"%s_lkls_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Nbin; l++){
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_gk_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.ks && like.shear_pos)
{
sprintf(OUTFILE,"%s_ksls_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Nbin; l++){
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ks_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.gk && like.pos_pos)
{
sprintf(OUTFILE,"%s_lkll_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Nbin; l++){
for (m=0;m<tomo.clustering_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_gk_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.ks && like.pos_pos)
{
sprintf(OUTFILE,"%s_ksll_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Nbin; l++){
for (m=0;m<tomo.clustering_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ks_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.gk)
{
sprintf(OUTFILE,"%s_lklk_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Nbin; l++){
for (m=l;m<tomo.clustering_Nbin; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_gk_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.ks && like.gk)
{
sprintf(OUTFILE,"%s_kslk_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Nbin; l++){
for (m=0;m<tomo.clustering_Nbin; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ks_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
if (like.ks)
{
sprintf(OUTFILE,"%s_ksks_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Nbin; l++){
for (m=l;m<tomo.shear_Nbin; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_ks_ks_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,l,m,k);
}
k=k+1;
}
}
}
////////
if (like.kk && like.shear_shear)
{
sprintf(OUTFILE,"%s_kkss_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_shear_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);
}
k=k+1;
}
}
if (like.kk && like.shear_pos)
{
sprintf(OUTFILE,"%s_kkls_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_ggl_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);
}
k=k+1;
}
}
if (like.kk && like.pos_pos)
{
sprintf(OUTFILE,"%s_kkll_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (m=0;m<tomo.clustering_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_clustering_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);
}
k=k+1;
}
}
if (like.kk && like.gk)
{
sprintf(OUTFILE,"%s_kklk_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (m=0;m<tomo.clustering_Nbin; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_gk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);
}
k=k+1;
}
}
if (like.kk && like.ks)
{
sprintf(OUTFILE,"%s_kkks_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
for (m=0;m<tomo.shear_Nbin; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_ks_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,m,k);
}
k=k+1;
}
}
if (like.kk)
{
sprintf(OUTFILE,"%s_kkkk_cov_Ncl%d_Ntomo%d",survey.name,Ncl,tomo.shear_Nbin);
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
// if (fopen(filename, "r") != NULL){exit(1);}
run_cov_kk_kk_fourier_bin(OUTFILE,covparams.outdir,ellmin,Ncl,k);
}
k=k+1;
}
printf("number of cov blocks for parallelization: %d\n",k-1);
printf("-----------------\n");
printf("PROGRAM EXECUTED\n");
printf("-----------------\n");
return 0;
}
| {
"alphanum_fraction": 0.6179496275,
"avg_line_length": 33.1647058824,
"ext": "c",
"hexsha": "11d9fb27cc98578126998edf86ed60a9ccc44b2d",
"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": "43dfce33112480e17878b2de3421775ec9df296c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/LSSTxSO",
"max_forks_repo_path": "compute_covariances_fourier_binned.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c",
"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": "CosmoLike/LSSTxSO",
"max_issues_repo_path": "compute_covariances_fourier_binned.c",
"max_line_length": 272,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/LSSTxSO",
"max_stars_repo_path": "compute_covariances_fourier_binned.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4740,
"size": 14095
} |
/* poly/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_heapsort.h>
static int
cmp_cplx(const double *a, const double *b)
{
double t = (a[0] * a[0] + a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1]);
return t < 0.0 ? -1 : t > 0.0 ? 1 : 0;
}
int
main (void)
{
const double eps = 100.0 * GSL_DBL_EPSILON;
gsl_ieee_env_setup ();
/* Polynomial evaluation */
{
double x, y;
double c[3] = { 1.0, 0.5, 0.3 };
x = 0.5;
y = gsl_poly_eval (c, 3, x);
gsl_test_rel (y, 1 + 0.5 * x + 0.3 * x * x, eps,
"gsl_poly_eval({1, 0.5, 0.3}, 0.5)");
}
{
double x, y;
double d[11] = { 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1 };
x = 1.0;
y = gsl_poly_eval (d, 11, x);
gsl_test_rel (y, 1.0, eps,
"gsl_poly_eval({1,-1, 1, -1, 1, -1, 1, -1, 1, -1, 1}, 1.0)");
}
{
gsl_complex x, y;
double c[1] = {0.3};
GSL_SET_REAL (&x, 0.75);
GSL_SET_IMAG (&x, 1.2);
y = gsl_poly_complex_eval (c, 1, x);
gsl_test_rel (GSL_REAL (y), 0.3, eps, "y.real, gsl_poly_complex_eval ({0.3}, 0.75 + 1.2i)");
gsl_test_rel (GSL_IMAG (y), 0.0, eps, "y.imag, gsl_poly_complex_eval ({0.3}, 0.75 + 1.2i)");
}
{
gsl_complex x, y;
double c[4] = {2.1, -1.34, 0.76, 0.45};
GSL_SET_REAL (&x, 0.49);
GSL_SET_IMAG (&x, 0.95);
y = gsl_poly_complex_eval (c, 4, x);
gsl_test_rel (GSL_REAL (y), 0.3959143, eps, "y.real, gsl_poly_complex_eval ({2.1, -1.34, 0.76, 0.45}, 0.49 + 0.95i)");
gsl_test_rel (GSL_IMAG (y), -0.6433305, eps, "y.imag, gsl_poly_complex_eval ({2.1, -1.34, 0.76, 0.45}, 0.49 + 0.95i)");
}
{
gsl_complex x, y;
gsl_complex c[1];
GSL_SET_REAL (&c[0], 0.674);
GSL_SET_IMAG (&c[0], -1.423);
GSL_SET_REAL (&x, -1.44);
GSL_SET_IMAG (&x, 9.55);
y = gsl_complex_poly_complex_eval (c, 1, x);
gsl_test_rel (GSL_REAL (y), 0.674, eps, "y.real, gsl_complex_poly_complex_eval ({0.674 - 1.423i}, -1.44 + 9.55i)");
gsl_test_rel (GSL_IMAG (y), -1.423, eps, "y.imag, gsl_complex_poly_complex_eval ({0.674 - 1.423i}, -1.44 + 9.55i)");
}
{
gsl_complex x, y;
gsl_complex c[4];
GSL_SET_REAL (&c[0], -2.31);
GSL_SET_IMAG (&c[0], 0.44);
GSL_SET_REAL (&c[1], 4.21);
GSL_SET_IMAG (&c[1], -3.19);
GSL_SET_REAL (&c[2], 0.93);
GSL_SET_IMAG (&c[2], 1.04);
GSL_SET_REAL (&c[3], -0.42);
GSL_SET_IMAG (&c[3], 0.68);
GSL_SET_REAL (&x, 0.49);
GSL_SET_IMAG (&x, 0.95);
y = gsl_complex_poly_complex_eval (c, 4, x);
gsl_test_rel (GSL_REAL (y), 1.82462012, eps, "y.real, gsl_complex_poly_complex_eval ({-2.31 + 0.44i, 4.21 - 3.19i, 0.93 + 1.04i, -0.42 + 0.68i}, 0.49 + 0.95i)");
gsl_test_rel (GSL_IMAG (y), 2.30389412, eps, "y.imag, gsl_complex_poly_complex_eval ({-2.31 + 0.44i, 4.21 - 3.19i, 0.93 + 1.04i, -0.42 + 0.68i}, 0.49 + 0.95i)");
}
/* Quadratic */
{
double x0, x1;
int n = gsl_poly_solve_quadratic (4.0, -20.0, 26.0, &x0, &x1);
gsl_test (n != 0, "gsl_poly_solve_quadratic, no roots, (2x - 5)^2 = -1");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (4.0, -20.0, 25.0, &x0, &x1);
gsl_test (n != 2, "gsl_poly_solve_quadratic, one root, (2x - 5)^2 = 0");
gsl_test_rel (x0, 2.5, 1e-9, "x0, (2x - 5)^2 = 0");
gsl_test_rel (x1, 2.5, 1e-9, "x1, (2x - 5)^2 = 0");
gsl_test (x0 != x1, "x0 == x1, (2x - 5)^2 = 0");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (4.0, -20.0, 21.0, &x0, &x1);
gsl_test (n != 2, "gsl_poly_solve_quadratic, two roots, (2x - 5)^2 = 4");
gsl_test_rel (x0, 1.5, 1e-9, "x0, (2x - 5)^2 = 4");
gsl_test_rel (x1, 3.5, 1e-9, "x1, (2x - 5)^2 = 4");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (4.0, 7.0, 0.0, &x0, &x1);
gsl_test (n != 2, "gsl_poly_solve_quadratic, two roots, x(4x + 7) = 0");
gsl_test_rel (x0, -1.75, 1e-9, "x0, x(4x + 7) = 0");
gsl_test_rel (x1, 0.0, 1e-9, "x1, x(4x + 7) = 0");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (5.0, 0.0, -20.0, &x0, &x1);
gsl_test (n != 2,
"gsl_poly_solve_quadratic, two roots b = 0, 5 x^2 = 20");
gsl_test_rel (x0, -2.0, 1e-9, "x0, 5 x^2 = 20");
gsl_test_rel (x1, 2.0, 1e-9, "x1, 5 x^2 = 20");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (0.0, 3.0, -21.0, &x0, &x1);
gsl_test (n != 1,
"gsl_poly_solve_quadratic, one root (linear) 3 x - 21 = 0");
gsl_test_rel (x0, 7.0, 1e-9, "x0, 3x - 21 = 0");
}
{
double x0, x1;
int n = gsl_poly_solve_quadratic (0.0, 0.0, 1.0, &x0, &x1);
gsl_test (n != 0,
"gsl_poly_solve_quadratic, no roots 1 = 0");
}
/* Cubic */
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (0.0, 0.0, -27.0, &x0, &x1, &x2);
gsl_test (n != 1, "gsl_poly_solve_cubic, one root, x^3 = 27");
gsl_test_rel (x0, 3.0, 1e-9, "x0, x^3 = 27");
}
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (-51.0, 867.0, -4913.0, &x0, &x1, &x2);
gsl_test (n != 3, "gsl_poly_solve_cubic, three roots, (x-17)^3=0");
gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)^3=0");
gsl_test_rel (x1, 17.0, 1e-9, "x1, (x-17)^3=0");
gsl_test_rel (x2, 17.0, 1e-9, "x2, (x-17)^3=0");
}
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (-57.0, 1071.0, -6647.0, &x0, &x1, &x2);
gsl_test (n != 3,
"gsl_poly_solve_cubic, three roots, (x-17)(x-17)(x-23)=0");
gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)(x-17)(x-23)=0");
gsl_test_rel (x1, 17.0, 1e-9, "x1, (x-17)(x-17)(x-23)=0");
gsl_test_rel (x2, 23.0, 1e-9, "x2, (x-17)(x-17)(x-23)=0");
}
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (-11.0, -493.0, +6647.0, &x0, &x1, &x2);
gsl_test (n != 3,
"gsl_poly_solve_cubic, three roots, (x+23)(x-17)(x-17)=0");
gsl_test_rel (x0, -23.0, 1e-9, "x0, (x+23)(x-17)(x-17)=0");
gsl_test_rel (x1, 17.0, 1e-9, "x1, (x+23)(x-17)(x-17)=0");
gsl_test_rel (x2, 17.0, 1e-9, "x2, (x+23)(x-17)(x-17)=0");
}
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (-143.0, 5087.0, -50065.0, &x0, &x1, &x2);
gsl_test (n != 3,
"gsl_poly_solve_cubic, three roots, (x-17)(x-31)(x-95)=0");
gsl_test_rel (x0, 17.0, 1e-9, "x0, (x-17)(x-31)(x-95)=0");
gsl_test_rel (x1, 31.0, 1e-9, "x1, (x-17)(x-31)(x-95)=0");
gsl_test_rel (x2, 95.0, 1e-9, "x2, (x-17)(x-31)(x-95)=0");
}
{
double x0, x1, x2;
int n = gsl_poly_solve_cubic (-109.0, 803.0, 50065.0, &x0, &x1, &x2);
gsl_test (n != 3,
"gsl_poly_solve_cubic, three roots, (x+17)(x-31)(x-95)=0");
gsl_test_rel (x0, -17.0, 1e-9, "x0, (x+17)(x-31)(x-95)=0");
gsl_test_rel (x1, 31.0, 1e-9, "x1, (x+17)(x-31)(x-95)=0");
gsl_test_rel (x2, 95.0, 1e-9, "x2, (x+17)(x-31)(x-95)=0");
}
/* Quadratic with complex roots */
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 26.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, 2 roots (2x - 5)^2 = -1");
gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, "z0.real, (2x - 5)^2 = -1");
gsl_test_rel (GSL_IMAG (z0), -0.5, 1e-9, "z0.imag, (2x - 5)^2 = -1");
gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, "z1.real, (2x - 5)^2 = -1");
gsl_test_rel (GSL_IMAG (z1), 0.5, 1e-9, "z1.imag, (2x - 5)^2 = -1");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 25.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, one root, (2x - 5)^2 = 0");
gsl_test_rel (GSL_REAL (z0), 2.5, 1e-9, "z0.real, (2x - 5)^2 = 0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag (2x - 5)^2 = 0");
gsl_test_rel (GSL_REAL (z1), 2.5, 1e-9, "z1.real, (2x - 5)^2 = 0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag (2x - 5)^2 = 0");
gsl_test (GSL_REAL (z0) != GSL_REAL (z1),
"z0.real == z1.real, (2x - 5)^2 = 0");
gsl_test (GSL_IMAG (z0) != GSL_IMAG (z1),
"z0.imag == z1.imag, (2x - 5)^2 = 0");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (4.0, -20.0, 21.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, two roots, (2x - 5)^2 = 4");
gsl_test_rel (GSL_REAL (z0), 1.5, 1e-9, "z0.real, (2x - 5)^2 = 4");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (2x - 5)^2 = 4");
gsl_test_rel (GSL_REAL (z1), 3.5, 1e-9, "z1.real, (2x - 5)^2 = 4");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (2x - 5)^2 = 4");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (4.0, 7.0, 0.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, two roots, x(4x + 7) = 0");
gsl_test_rel (GSL_REAL (z0), -1.75, 1e-9, "z0.real, x(4x + 7) = 0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, x(4x + 7) = 0");
gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, "z1.real, x(4x + 7) = 0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, x(4x + 7) = 0");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, -20.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = 20");
gsl_test_rel (GSL_REAL (z0), -2.0, 1e-9, "z0.real, 5 x^2 = 20");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, 5 x^2 = 20");
gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, "z1.real, 5 x^2 = 20");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, 5 x^2 = 20");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (5.0, 0.0, 20.0, &z0, &z1);
gsl_test (n != 2,
"gsl_poly_complex_solve_quadratic, two roots b = 0, 5 x^2 = -20");
gsl_test_rel (GSL_REAL (z0), 0.0, 1e-9, "z0.real, 5 x^2 = -20");
gsl_test_rel (GSL_IMAG (z0), -2.0, 1e-9, "z0.imag, 5 x^2 = -20");
gsl_test_rel (GSL_REAL (z1), 0.0, 1e-9, "z1.real, 5 x^2 = -20");
gsl_test_rel (GSL_IMAG (z1), 2.0, 1e-9, "z1.imag, 5 x^2 = -20");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (0.0, 3.0, -21.0, &z0, &z1);
gsl_test (n != 1,
"gsl_poly_complex_solve_quadratic, one root (linear) 3 x - 21 = 0");
gsl_test_rel (GSL_REAL (z0), 7.0, 1e-9, "z0.real, 3x - 21 = 0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, 3x - 21 = 0");
}
{
gsl_complex z0, z1;
int n = gsl_poly_complex_solve_quadratic (0.0, 0.0, 1.0, &z0, &z1);
gsl_test (n != 0,
"gsl_poly_complex_solve_quadratic, no roots 1 = 0");
}
/* Cubic with complex roots */
{
gsl_complex z0, z1, z2;
int n = gsl_poly_complex_solve_cubic (0.0, 0.0, -27.0, &z0, &z1, &z2);
gsl_test (n != 3, "gsl_poly_complex_solve_cubic, three root, x^3 = 27");
gsl_test_rel (GSL_REAL (z0), -1.5, 1e-9, "z0.real, x^3 = 27");
gsl_test_rel (GSL_IMAG (z0), -1.5 * sqrt (3.0), 1e-9,
"z0.imag, x^3 = 27");
gsl_test_rel (GSL_REAL (z1), -1.5, 1e-9, "z1.real, x^3 = 27");
gsl_test_rel (GSL_IMAG (z1), 1.5 * sqrt (3.0), 1e-9, "z1.imag, x^3 = 27");
gsl_test_rel (GSL_REAL (z2), 3.0, 1e-9, "z2.real, x^3 = 27");
gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, x^3 = 27");
}
{
gsl_complex z0, z1, z2;
int n = gsl_poly_complex_solve_cubic (-1.0, 1.0, 39.0, &z0, &z1, &z2);
gsl_test (n != 3,
"gsl_poly_complex_solve_cubic, three root, (x+3)(x^2-4x+13) = 0");
gsl_test_rel (GSL_REAL (z0), -3.0, 1e-9, "z0.real, (x+3)(x^2+1) = 0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x+3)(x^2+1) = 0");
gsl_test_rel (GSL_REAL (z1), 2.0, 1e-9, "z1.real, (x+3)(x^2+1) = 0");
gsl_test_rel (GSL_IMAG (z1), -3.0, 1e-9, "z1.imag, (x+3)(x^2+1) = 0");
gsl_test_rel (GSL_REAL (z2), 2.0, 1e-9, "z2.real, (x+3)(x^2+1) = 0");
gsl_test_rel (GSL_IMAG (z2), 3.0, 1e-9, "z2.imag, (x+3)(x^2+1) = 0");
}
{
gsl_complex z0, z1, z2;
int n =
gsl_poly_complex_solve_cubic (-51.0, 867.0, -4913.0, &z0, &z1, &z2);
gsl_test (n != 3,
"gsl_poly_complex_solve_cubic, three roots, (x-17)^3=0");
gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)^3=0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)^3=0");
gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x-17)^3=0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)^3=0");
gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, "z2.real, (x-17)^3=0");
gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)^3=0");
}
{
gsl_complex z0, z1, z2;
int n =
gsl_poly_complex_solve_cubic (-57.0, 1071.0, -6647.0, &z0, &z1, &z2);
gsl_test (n != 3,
"gsl_poly_complex_solve_cubic, three roots, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_REAL (z2), 23.0, 1e-9, "z2.real, (x-17)(x-17)(x-23)=0");
gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)(x-17)(x-23)=0");
}
{
gsl_complex z0, z1, z2;
int n =
gsl_poly_complex_solve_cubic (-11.0, -493.0, +6647.0, &z0, &z1, &z2);
gsl_test (n != 3,
"gsl_poly_complex_solve_cubic, three roots, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_REAL (z0), -23.0, 1e-9,
"z0.real, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_REAL (z1), 17.0, 1e-9, "z1.real, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_REAL (z2), 17.0, 1e-9, "z2.real, (x+23)(x-17)(x-17)=0");
gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x+23)(x-17)(x-17)=0");
}
{
gsl_complex z0, z1, z2;
int n =
gsl_poly_complex_solve_cubic (-143.0, 5087.0, -50065.0, &z0, &z1, &z2);
gsl_test (n != 3,
"gsl_poly_complex_solve_cubic, three roots, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_REAL (z0), 17.0, 1e-9, "z0.real, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_IMAG (z0), 0.0, 1e-9, "z0.imag, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_REAL (z1), 31.0, 1e-9, "z1.real, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_IMAG (z1), 0.0, 1e-9, "z1.imag, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_REAL (z2), 95.0, 1e-9, "z2.real, (x-17)(x-31)(x-95)=0");
gsl_test_rel (GSL_IMAG (z2), 0.0, 1e-9, "z2.imag, (x-17)(x-31)(x-95)=0");
}
{
/* Wilkinson polynomial: y = (x-1)(x-2)(x-3)(x-4)(x-5) */
double a[6] = { -120, 274, -225, 85, -15, 1 };
double z[6*2];
gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (6);
int status = gsl_poly_complex_solve (a, 6, w, z);
gsl_poly_complex_workspace_free (w);
gsl_test (status,
"gsl_poly_complex_solve, 5th-order Wilkinson polynomial");
gsl_test_rel (z[0], 1.0, 1e-9, "z0.real, 5th-order polynomial");
gsl_test_rel (z[1], 0.0, 1e-9, "z0.imag, 5th-order polynomial");
gsl_test_rel (z[2], 2.0, 1e-9, "z1.real, 5th-order polynomial");
gsl_test_rel (z[3], 0.0, 1e-9, "z1.imag, 5th-order polynomial");
gsl_test_rel (z[4], 3.0, 1e-9, "z2.real, 5th-order polynomial");
gsl_test_rel (z[5], 0.0, 1e-9, "z2.imag, 5th-order polynomial");
gsl_test_rel (z[6], 4.0, 1e-9, "z3.real, 5th-order polynomial");
gsl_test_rel (z[7], 0.0, 1e-9, "z3.imag, 5th-order polynomial");
gsl_test_rel (z[8], 5.0, 1e-9, "z4.real, 5th-order polynomial");
gsl_test_rel (z[9], 0.0, 1e-9, "z4.imag, 5th-order polynomial");
}
{
/* : 8-th order polynomial y = x^8 + x^4 + 1 */
double a[9] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
double z[8*2];
double C = 0.5;
double S = sqrt (3.0) / 2.0;
gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (9);
int status = gsl_poly_complex_solve (a, 9, w, z);
gsl_poly_complex_workspace_free (w);
gsl_test (status, "gsl_poly_complex_solve, 8th-order polynomial");
gsl_test_rel (z[0], -S, 1e-9, "z0.real, 8th-order polynomial");
gsl_test_rel (z[1], C, 1e-9, "z0.imag, 8th-order polynomial");
gsl_test_rel (z[2], -S, 1e-9, "z1.real, 8th-order polynomial");
gsl_test_rel (z[3], -C, 1e-9, "z1.imag, 8th-order polynomial");
gsl_test_rel (z[4], -C, 1e-9, "z2.real, 8th-order polynomial");
gsl_test_rel (z[5], S, 1e-9, "z2.imag, 8th-order polynomial");
gsl_test_rel (z[6], -C, 1e-9, "z3.real, 8th-order polynomial");
gsl_test_rel (z[7], -S, 1e-9, "z3.imag, 8th-order polynomial");
gsl_test_rel (z[8], C, 1e-9, "z4.real, 8th-order polynomial");
gsl_test_rel (z[9], S, 1e-9, "z4.imag, 8th-order polynomial");
gsl_test_rel (z[10], C, 1e-9, "z5.real, 8th-order polynomial");
gsl_test_rel (z[11], -S, 1e-9, "z5.imag, 8th-order polynomial");
gsl_test_rel (z[12], S, 1e-9, "z6.real, 8th-order polynomial");
gsl_test_rel (z[13], C, 1e-9, "z6.imag, 8th-order polynomial");
gsl_test_rel (z[14], S, 1e-9, "z7.real, 8th-order polynomial");
gsl_test_rel (z[15], -C, 1e-9, "z7.imag, 8th-order polynomial");
}
{
/* 15-th order polynomial y = (x + 1) * (x^10 + x^9 + 2 * x^7 + 4 * x^2 +
4 * x + 8) * (x - 1)^2 * (x - 2)^2
Problem reported by Munagala Ramanath (bug #39055)
*/
double a[16] = { 32, -48, -8, 28, -8, 16, -16, 12, -16, 6, 10, -17, 10, 2, -4, 1 };
double z[16*2];
double expected[16*20] = {
1.0000000000000000, 0.00000000000000000,
1.0000000000000000, 0.00000000000000000,
-1.0000000000000000, 0.00000000000000000,
-0.65893856175240950, 0.83459757287426684,
-0.65893856175240950, -0.83459757287426684,
-0.070891117403341281, -1.1359249087587791,
-0.070891117403341281, 1.1359249087587791,
1.1142366961812986, -0.48083981203389980,
1.1142366961812986, 0.48083981203389980,
-1.3066982484920768, 0.00000000000000000,
0.57284747839410854, 1.1987808988289705,
0.57284747839410854, -1.1987808988289705,
-1.6078107423472359, 0.00000000000000000,
2.0000000000000000, 0.00000000000000000,
2.0000000000000000, 0.00000000000000000 };
int i;
gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc (16);
int status = gsl_poly_complex_solve (a, 16, w, z);
gsl_poly_complex_workspace_free (w);
gsl_test (status, "gsl_poly_complex_solve, 15th-order polynomial");
gsl_heapsort(z, 15, 2 * sizeof(double), (gsl_comparison_fn_t) &cmp_cplx);
for (i = 0; i<15; i++)
{
gsl_test_abs (z[2*i], expected[2*i], 1e-7, "z%d.real, 15th-order polynomial", i);
gsl_test_abs (z[2*i+1], expected[2*i+1], 1e-7, "z%d.imag, 15th-order polynomial", i);
}
}
{
int i;
double xa[7] = {0.16, 0.97, 1.94, 2.74, 3.58, 3.73, 4.70 };
double ya[7] = {0.73, 1.11, 1.49, 1.84, 2.30, 2.41, 3.07 };
double dd_expected[7] = { 7.30000000000000e-01,
4.69135802469136e-01,
-4.34737219941284e-02,
2.68681098870099e-02,
-3.22937056934996e-03,
6.12763259971375e-03,
-6.45402453527083e-03 };
double dd[7], coeff[7], work[7];
gsl_poly_dd_init (dd, xa, ya, 7);
for (i = 0; i < 7; i++)
{
gsl_test_rel (dd[i], dd_expected[i], 1e-10, "divided difference dd[%d]", i);
}
for (i = 0; i < 7; i++)
{
double y = gsl_poly_dd_eval(dd, xa, 7, xa[i]);
gsl_test_rel (y, ya[i], 1e-10, "divided difference y[%d]", i);
}
gsl_poly_dd_taylor (coeff, 1.5, dd, xa, 7, work);
for (i = 0; i < 7; i++)
{
double y = gsl_poly_eval(coeff, 7, xa[i] - 1.5);
gsl_test_rel (y, ya[i], 1e-10, "taylor expansion about 1.5 y[%d]", i);
}
}
{
size_t i;
double xa[3] = { 1.3, 1.6, 1.9 };
double ya[3] = { 0.6200860, 0.4554022, 0.2818186 };
double dya[3] = { -0.5220232, -0.5698959, -0.5811571 };
double dd_expected[6] = { 6.200860000000e-01,
-5.220232000000e-01,
-8.974266666667e-02,
6.636555555556e-02,
2.666666666662e-03,
-2.774691357989e-03 };
double dd[6], za[6], coeff[6], work[6];
gsl_poly_dd_hermite_init(dd, za, xa, ya, dya, 3);
for (i = 0; i < 6; i++)
{
gsl_test_rel (dd[i], dd_expected[i], 1e-10, "hermite divided difference dd[%d]", i);
}
for (i = 0; i < 3; i++)
{
double y = gsl_poly_dd_eval(dd, za, 6, xa[i]);
gsl_test_rel (y, ya[i], 1e-10, "hermite divided difference y[%d]", i);
}
for (i = 0; i < 3; i++)
{
gsl_poly_dd_taylor(coeff, xa[i], dd, za, 6, work);
gsl_test_rel (coeff[1], dya[i], 1e-10, "hermite divided difference dy/dx[%d]", i);
}
}
{
double c[6] = { +1.0, -2.0, +3.0, -4.0, +5.0, -6.0 };
double dc[6];
double x;
x = -0.5;
gsl_poly_eval_derivs(c, 6, x, dc, 6);
gsl_test_rel (dc[0], c[0] + c[1]*x + c[2]*x*x + c[3]*x*x*x + c[4]*x*x*x*x + c[5]*x*x*x*x*x , eps, "gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6}, 3.75)");
gsl_test_rel (dc[1], c[1] + 2.0*c[2]*x + 3.0*c[3]*x*x + 4.0*c[4]*x*x*x + 5.0*c[5]*x*x*x*x , eps, "gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6} deriv 1, -12.375)");
gsl_test_rel (dc[2], 2.0*c[2] + 3.0*2.0*c[3]*x + 4.0*3.0*c[4]*x*x + 5.0*4.0*c[5]*x*x*x , eps, "gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6} deriv 2, +48.0)");
gsl_test_rel (dc[3], 3.0*2.0*c[3] + 4.0*3.0*2.0*c[4]*x + 5.0*4.0*3.0*c[5]*x*x , eps,"gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6} deriv 3, -174.0)");
gsl_test_rel (dc[4], 4.0*3.0*2.0*c[4] + 5.0*4.0*3.0*2.0*c[5]*x, eps, "gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6} deriv 4, +480.0)");
gsl_test_rel (dc[5], 5.0*4.0*3.0*2.0*c[5] , eps, "gsl_poly_eval_dp({+1, -2, +3, -4, +5, -6} deriv 5, -720.0)");
}
/* now summarize the results */
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.5517867959,
"avg_line_length": 34.4985074627,
"ext": "c",
"hexsha": "39ff417164ebaae0da1080c694ffc272180fc23f",
"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": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/poly/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"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": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/poly/test.c",
"max_line_length": 165,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/poly/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 10429,
"size": 23114
} |
/*
* vbHmmPcFret.c
* Model-specific core functions for VB-HMM-PC-FRET.
*
* 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 2015.09.17
*/
#include "vbHmmPcFret.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 DEBUG
//// Uncomment one/both of the following defenitions to activate constraint on I and K.
//#define INTENSITY_CAP
#ifdef INTENSITY_CAP
#define maxIntensityRatio 10.0
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
//static int isGlobalAnalysis = 0;
void setFunctions_pcFret(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_pcFret;
funcs.freeModelParameters = freeModelParameters_pcFret;
funcs.newModelStats = newModelStats_pcFret;
funcs.freeModelStats = freeModelStats_pcFret;
funcs.initializeVbHmm = initializeVbHmm_pcFret;
funcs.pTilde_z1 = pTilde_z1_pcFret;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;
funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;
funcs.calcStatsVars = calcStatsVars_pcFret;
funcs.maximization = maximization_pcFret;
funcs.varLowerBound = varLowerBound_pcFret;
funcs.reorderParameters = reorderParameters_pcFret;
funcs.outputResults = outputResults_pcFret;
setFunctions( funcs );
}
//void setGFunctions_pcFret(){
// gCommonFunctions funcs;
// funcs.newModelParameters = newModelParameters_pcFret;
// funcs.freeModelParameters = freeModelParameters_pcFret;
// funcs.newModelStats = newModelStats_pcFret;
// funcs.freeModelStats = freeModelStats_pcFret;
// funcs.newModelStatsG = newModelStatsG_pcFret;
// funcs.freeModelStatsG = freeModelStatsG_pcFret;
// funcs.initializeVbHmmG = initializeVbHmmG_pcFret;
// funcs.pTilde_z1 = pTilde_z1_pcFret;
// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;
// funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;
// funcs.calcStatsVarsG = calcStatsVarsG_pcFret;
// funcs.maximizationG = maximizationG_pcFret;
// funcs.varLowerBoundG = varLowerBoundG_pcFret;
// funcs.reorderParametersG = reorderParametersG_pcFret;
// funcs.outputResultsG = outputResultsG_pcFret;
// setGFunctions( funcs );
// isGlobalAnalysis = 1;
//}
void outputResults_pcFret( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputPcFretResults( xn, gv, iv, logFP );
}
//void outputResultsG_pcFret( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
// outputPcFretResultsG( xns, gv, ivs, logFP );
//}
void *newModelParameters_pcFret( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
pcFretParameters *p = (void*)malloc( sizeof(pcFretParameters) );
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->aIArr = (double*)malloc( sNo * sizeof(double) );
p->bIArr = (double*)malloc( sNo * sizeof(double) );
p->uEArr = (double*)malloc( sNo * sizeof(double) );
p->vEArr = (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->avgI = (double *)malloc( sNo * sizeof(double) );
p->avgLnI = (double *)malloc( sNo * sizeof(double) );
p->avgE = (double *)malloc( sNo * sizeof(double) );
p->avgLnE = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ p->avgLnE[i] = (double *)malloc( 2 * sizeof(double) ); }
return p;
}
void freeModelParameters_pcFret( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
pcFretParameters *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->aIArr );
free( gp->bIArr );
free( gp->uEArr );
free( gp->vEArr );
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->avgI );
free( gp->avgLnI );
free( gp->avgE );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgLnE[i] );
}
free( gp->avgLnE );
free( *p );
*p = NULL;
}
void *newModelStats_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcFretStats *s = (pcFretStats*)malloc( sizeof(pcFretStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Ci = (double *)malloc( sNo * sizeof(double) );
s->Di = (double *)malloc( sNo * sizeof(double) );
s->Ai = (double *)malloc( sNo * sizeof(double) );
s->Mi = (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) ); }
return s;
// } else {
//
// return NULL;
//
// }
}
void freeModelStats_pcFret( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcFretStats *gs = *s;
int i;
free( gs->Ni );
free( gs->Ci );
free( gs->Di );
free( gs->Ai );
free( gs->Mi );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs );
*s = NULL;
// }
}
//void *newModelStatsG_pcFret( xns, gv, ivs)
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcFretGlobalStats *gs = (pcFretGlobalStats*)malloc( sizeof(pcFretGlobalStats) );
//
// return gs;
//}
//void freeModelStatsG_pcFret( gs, xns, gv, ivs )
//void **gs;
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcFretGlobalStats *ggs = *gs;
//
// free( *gs );
// *gs = NULL;
//}
void initializeVbHmm_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretData *d = xn->data;
size_t dLen = xn->N;
int sNo = gv->sNo;
pcFretParameters *p = gv->params;
int i, j;
size_t totalC = 0;
for( i = 0 ; i < dLen ; i++ ){
totalC += d->dCounts[i] + d->aCounts[i];
}
double meanI = (double)totalC / (double)dLen;
// 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] = 100.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyper parameter for p( I(k) )
for( i = 0 ; i < sNo ; i++ ){
p->aIArr[i] = 1.0;
p->bIArr[i] = 1.0 / meanI;
}
// hyper parameter for p( E(i) )
for( i = 0 ; i < sNo ; i++ ){
p->uEArr[i] = 1.0;
p->vEArr[i] = 1.0;
}
initialize_indVars_pcFret( xn, gv, iv );
calcStatsVars_pcFret( xn, gv, iv );
maximization_pcFret( xn, gv, iv );
}
//void initializeVbHmmG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void initialize_indVars_pcFret( 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_pcFret( 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 = (pcFretData*)malloc( sizeof(pcFretData) );
pcFretData *d = (pcFretData*)xn->data;
d->binSize = 0.0;
d->dCounts = NULL;
d->aCounts = NULL;
return xn;
}
void freeXnDataSet_pcFret( xn )
xnDataSet **xn;
{
pcFretData *d = (pcFretData*)(*xn)->data;
free( d->dCounts );
free( d->aCounts );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_pcFret( i, params )
int i;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_pcFret( i, j, params )
int i, j;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn_pcFret( xn, n, i, params )
xnDataSet *xn;
size_t n;
int i;
void *params;
{
pcFretParameters *p = (pcFretParameters*)params;
pcFretData *d = (pcFretData*)xn->data;
return exp( d->dCounts[n]*p->avgLnE[i][0] + d->aCounts[n]*p->avgLnE[i][1] + (d->dCounts[n]+d->aCounts[n])*p->avgLnI[i] - p->avgI[i] ) / gsl_sf_fact( d->dCounts[n] ) / gsl_sf_fact( d->aCounts[n] );
}
void calcStatsVars_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretData *d = (pcFretData*)xn->data;
pcFretStats *s = (pcFretStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ci[i] = 1e-10;
Di[i] = 1e-10;
Ai[i] = 1e-10;
Mi[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];
Di[i] += gmMat[n][i] * (double)d->dCounts[n];
Ai[i] += gmMat[n][i] * (double)d->aCounts[n];
for( j = 0 ; j < sNo ; j++ ){
Mi[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
Ci[i] = Di[i] + Ai[i];
}
//#ifdef DEBUG
//#pragma omp critical
//{
// for( n = 0 ; n < 20 ; n++ ){
// for( i = 0 ; i < sNo ; i++ ){
// fprintf(logFP, "%g,", gmMat[n][i]);
// }
// fprintf(logFP, "; ");
// }
// fprintf(logFP, "\n");
// for( i = 0 ; i < sNo ; i++ ){
// fprintf(logFP, "Ni(%d)=%g, ", i, Ni[i]);
// fprintf(logFP, "Ti(%d)=%g, ", i, Ti[i]);
// fprintf(logFP, "Mi(%d)=%g, ", i, Mi[i]);
// for( j = 0 ; j < sNo ; j++ ){
// if( j != i )
// fprintf(logFP, "Nij(%d,%d)=%g, ", i, j, Nij[i][j]);
// }
// fprintf(logFP, "\n");
// }
//}
//#endif
}
//void calcStatsVarsG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void maximization_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgE = p->avgE, **avgLnE = p->avgLnE;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
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] + Mi[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Mi[i] );
}
avgI[i] = (Ci[i] + aIArr[i]) / (Ni[i] + bIArr[i]);
avgLnI[i] = gsl_sf_psi( Ci[i] + aIArr[i] ) - log( Ni[i] + bIArr[i] );
#ifdef INTENSITY_CAP
size_t n, totalC = 0;
pcFretData *pc = xnWv->data;
for( n = 0 ; n < xnWv->N ; n++ ){
totalC += pc->dCounts[n] + pc->aCounts[n];
}
double meanI = (double)totalC / (double)xnWv->N;
avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );
avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );
#endif
avgE[i] = ( uEArr[i] + Ai[i] ) / ( uEArr[i] + vEArr[i] + Ci[i] );
// ln(1-E) for donor
avgLnE[i][0] = gsl_sf_psi( vEArr[i] + Di[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );
// ln(E) for acceptor
avgLnE[i][1] = gsl_sf_psi( uEArr[i] + Ai[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );
}
}
//void maximizationG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
double varLowerBound_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)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, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *uEArr = p->uEArr, *vEArr = p->vEArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI, **avgLnE = p->avgLnE;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
double *Mi = s->Mi, **Nij = s->Nij;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpI = 0.0;
double lnpE = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqI = 0.0;
double lnqE = 0.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);
lnpI += (aIArr[i] - 1.0) * avgLnI[i] - bIArr[i] * avgI[i];
lnpE += gsl_sf_lngamma(uEArr[i]+vEArr[i]) - gsl_sf_lngamma(uEArr[i]);
lnpE += -gsl_sf_lngamma(vEArr[i]);
lnpE += (uEArr[i]-1.0)*avgLnE[i][1] + (vEArr[i]-1.0)*avgLnE[i][0];
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]);
lnqI += (Ci[i] + aIArr[i]) * log(Ni[i] + bIArr[i]) - gsl_sf_lngamma(Ci[i] + aIArr[i]);
lnqI += (Ci[i] + aIArr[i] - 1.0) * avgLnI[i] - (Ni[i] + bIArr[i]) * avgI[i];
lnqE += gsl_sf_lngamma(uEArr[i] + vEArr[i] + Ci[i]);
lnqE -= gsl_sf_lngamma(uEArr[i] + Ai[i]);
lnqE -= gsl_sf_lngamma(vEArr[i] + Di[i]);
lnqE += (uEArr[i] + Ai[i] - 1.0) * avgLnE[i][1];
lnqE += (vEArr[i] + Di[i] - 1.0) * avgLnE[i][0];
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Mi[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]+Mi[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpI + lnpE;
val -= lnqPi + lnqA + lnqI + lnqE;
val += lnpX;
val += log(gsl_sf_fact(sNo));
//#ifdef DEBUG
//#pragma omp critical
//{
// FILE *logFP = stderr;
// if( val > 100000 ){
// fprintf(logFP, " > %g; %g; %g; %g;", lnpPi, lnpA, lnpI, lnpE);
// fprintf(logFP, " %g; %g; %g; %g; %g\n", lnqPi, lnqA, lnqI, lnqE, lnpX);
// }
//}
//#endif
return val;
}
//double varLowerBoundG_pcFret( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void reorderParameters_pcFret( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
pcFretStats *s = (pcFretStats*)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;
double **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI, *avgE = p->avgE, **avgLnE = p->avgLnE;
double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;
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 avgE values (0=biggest avgE -- sNo=smallest avgE).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgE[i] < avgE[j] ){
index[i]--;
} else if( avgE[i] == avgE[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]] = avgI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnI[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]] = avgE[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgE[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ )
{ s2D[index[i]][0] = avgLnE[i][0];
s2D[index[i]][1] = avgLnE[i][1]; }
for( i = 0 ; i < sNo ; i++ )
{ avgLnE[i][0] = s2D[i][0];
avgLnE[i][1] = s2D[i][1]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ci[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ci[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Di[i]; }
for( i = 0 ; i < sNo ; i++ ){ Di[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ai[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ai[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_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void outputPcFretResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
pcFretParameters *p = (pcFretParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " intensities: ( %g", p->avgI[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgI[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " FRET efficiencies: ( %g", p->avgE[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgE[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, "I, E, 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", p->avgI[i], p->avgE[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);
}
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 outputPcFretResultsG( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
//}
//
| {
"alphanum_fraction": 0.5020260367,
"avg_line_length": 28.463803681,
"ext": "c",
"hexsha": "cb35305656d9e37bfb3830105b33767a0c0d7006",
"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/vbHmmPcFret.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/vbHmmPcFret.c",
"max_line_length": 200,
"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/vbHmmPcFret.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": 8720,
"size": 23198
} |
// The GSL extra library provides linear algebra functions using a
// similar interface to the rest of the GSL library.
#ifndef COMMON_C_MATH_GSL_LINALG_EXTRA_H_
#define COMMON_C_MATH_GSL_LINALG_EXTRA_H_
#include <stdint.h>
#include <gsl/gsl_blas_types.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t GslTriangularSolve(CBLAS_SIDE_t side, CBLAS_UPLO_t uplo,
CBLAS_TRANSPOSE_t transpose, const gsl_matrix *T,
const gsl_matrix *B, gsl_matrix *X);
void GslTrapezoidalToTriangular(const gsl_matrix *R, gsl_matrix *T,
gsl_vector *tau);
void GslTrapezoidalToTriangularZTMat(const gsl_matrix *T, const gsl_vector *tau,
const gsl_matrix *X, gsl_matrix *Zt_X);
int32_t GslMatrixDivide(CBLAS_SIDE_t side, const gsl_matrix *A,
const gsl_matrix *B, gsl_matrix *X);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // COMMON_C_MATH_GSL_LINALG_EXTRA_H_
| {
"alphanum_fraction": 0.6866096866,
"avg_line_length": 32.90625,
"ext": "h",
"hexsha": "61499eacee58ea52ddc5f5942f4c94a0d832852a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-20T21:04:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-13T11:39:01.000Z",
"max_forks_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "OpenFAST/KiteFAST",
"max_forks_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"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": "OpenFAST/KiteFAST",
"max_issues_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.h",
"max_line_length": 80,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "OpenFAST/KiteFAST",
"max_stars_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-16T10:13:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-22T18:21:36.000Z",
"num_tokens": 270,
"size": 1053
} |
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_statistics.h>
#include "tz_error.h"
#include "tz_constant.h"
#include "tz_image_lib.h"
#include "tz_stack_lib.h"
#include "tz_objdetect.h"
#include "tz_imatrix.h"
#include "tz_stack_math.h"
#include "tz_stack_bwdist.h"
#include "tz_stack_bwmorph.h"
#include "tz_voxel_linked_list.h"
#include "tz_stack_sampling.h"
#include "tz_stack_attribute.h"
#include "tz_dimage_lib.h"
#include "tz_arrayview.h"
#include "tz_dmatrix.h"
INIT_EXCEPTION_MAIN(e)
int main(int argc, char* argv[]) {
char neuron_name[100];
if (argc == 1) {
strcpy(neuron_name, "fly_neuron");
} else {
strcpy(neuron_name, argv[1]);
}
char file_path[100];
#if 0 /* local maxima */
sprintf(file_path, "../data/%s/mask.tif", neuron_name);
Stack *stack1 = Read_Stack(file_path);
sprintf(file_path, "../data/%s/highpass_locmin.tif", neuron_name);
Stack *stack2 = Read_Stack(file_path);
Stack_Add(stack1, stack2, stack1);
sprintf(file_path, "../data/%s/cell_mark.tif", neuron_name);
Write_Stack(file_path, stack1);
#endif
#if 0
sprintf(file_path, "../data/%s.tif", neuron_name);
Stack *stack1 = Read_Stack(file_path);
DMatrix *filter = Mexihat_2D_D(2.0, NULL);
filter->ndim = 3;
filter->dim[2] = 1;
DMatrix *out = Filter_Stack_Fast_D(stack1, filter, NULL, 0);
# if 1
int nvoxel = Stack_Voxel_Number(stack1);
int i;
for (i = 0; i < nvoxel; i++) {
out->array[i] = fabs(out->array[i]);
}
# endif
Stack *stack2 = Scale_Double_Stack(out->array, out->dim[0], out->dim[1],
out->dim[2], GREY);
sprintf(file_path, "../data/%s/edge.tif", neuron_name);
Write_Stack(file_path, stack2);
Kill_Stack(stack1);
Kill_Stack(stack2);
#endif
#if 1
sprintf(file_path, "../data/%s/mask.tif", neuron_name);
Stack *stack2 = Read_Stack(file_path);
sprintf(file_path, "../data/%s/seeds.pa", neuron_name);
Pixel_Array *pa = Pixel_Array_Read(file_path);
double *pa_array = (double *) pa->array;
double max_dist = gsl_stats_max(pa_array, 1, pa->size);
double mean_dist = gsl_stats_mean(pa_array, 1, pa->size);
double std_dist = sqrt(gsl_stats_variance(pa_array, 1, pa->size));
int erode_size = (int) (mean_dist + std_dist * 2 + 0.5);
Struct_Element *se = Make_Ball_Se(erode_size);
Stack *stack3 = Stack_Erode_Fast(stack2, NULL, se);
int dilate_size = (int) (max_dist + 0.5);
se = Make_Ball_Se(dilate_size);
Stack *stack4 = Stack_Dilate(stack3, NULL, se);
Stack_Sub(stack2, stack4, stack2);
Write_Stack("../data/test.tif", stack2);
Kill_Stack(stack2);
Kill_Stack(stack3);
Kill_Stack(stack4);
Kill_Pixel_Array(pa);
#endif
return 0;
}
| {
"alphanum_fraction": 0.6878525762,
"avg_line_length": 25.8155339806,
"ext": "c",
"hexsha": "1b8eeb562d9249982eae09a7aa6c31c46a5deae3",
"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": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzhmark/vaa3d_tools",
"max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzhmark/vaa3d_tools",
"max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c",
"max_line_length": 74,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzhmark/vaa3d_tools",
"max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_test.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z",
"num_tokens": 822,
"size": 2659
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <float.h>
#define COMPEARTH_PRIVATE_CROSS3 1
#define COMPEARTH_PRIVATE_NORM3 1
#define COMPEARTH_PRIVATE_DOT3 1
#define COMPEARTH_PRIVATE_WRAP360 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_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <cblas.h>
#endif
//#define MAXMT 64
static void setZero(const int nmt, const double tol, double *__restrict__ X);
static void faultVec2Ang(const double *__restrict__ S,
const double *__restrict__ N,
double *theta, double *sigma,
double *kappa, double *__restrict__ K, int *ierr);
static int pickP1(const double thetaA, const double sigmaA, const double kappaA,
const double thetaB, const double sigmaB, const double kappaB,
const double tol, const int p1, const int p2);
/*!
* @brief Converts a moment tensor to six parameters of Tape and Tape 2012.
* The reverse program is TT2CMT.c
*
* @param[in] nmt Number of moment tensors.
* @param[in] Min [6 x nmt] array of moment tensors in CMT
* convention (i.e. UP-SOUTH-EAST). M is packed:
* \f$
* M = \{ M_{rr}, M_{\theta \theta}, M_{\phi \phi}
* M_{r \theta}, M_{r \phi}, M_{\theta \phi} \}
* \f$.
* The leading dimension is 6.
* @param[in] ldisplay If true then display the results. \n
* Otherwise, this routine will be quiet unless
* an error is encountered.
*
* @param[out] gamma Angle from DC meridian to MT point.
* Note that \f$ \gamma \in [-30, 30] \f$.
* This is an array of dimension [nmt].
* @param[out] delta Angle from deviatoric plane to MT point.
* Note that \f$ \delta \in [-90, 90] \f$.
* This is an array of dimension [nmt].
* @param[out] M0 Seismic moment in N-m. This is an array of
* dimension [nmt].
* @param[out] kappa Strike angle \f$ \kappa \in [0,360] \f$.
* This is an array of dimension [nmt].
* @param[out] theta Dip angle \f$ \theta \in [0,90] \f$.
* This is an array of dimension [nmt].
* @param[out] sigma Slip (or rake) angle \f$ \sigma \in [-90,90] \f$.
* This is an array of dimension [nmt].
* @param[out] K If K is not NULL then it is the strike vector
* (SOUTH-EAST-UP). In this case K is an array
* of dimension [3 x nmt] with leading dimension 3.
* @param[out] N If N is not NULL then it is the normal vector
* (SOUTH-EAST-UP). In this case N is an array
* of dimension [3 x nmt] with leading dimension 3.
* @param[out] S If S Is not NULL then it is the slip vector
* (SOUTH-EAST-UP). In this case S is an array
* of dimension [3 x nmt] with leading dimension 3.
* @param[out] thetadc If thetadc is not NULL then it is angle between
* the moment tensor and the double couple where
* \f$ \theta_{DC} \in [0,90] \f$.
* In this case thetadc is an array of dimension [nmt].
* @param[out] lam If lam is not NULL then these are the eigenvalues
* corresponding to the moment tensor. In this
* case lam is an array of dimension [3 x nmt]
* with leading dimension 3.
* @param[out] U If U is not NULL then this is the basis in
* SOUTH-EAST-UP for the moment tensor. In this
* case U an array of dimension [3 x 3 x nmt] with
* leading dimension 9 and the understanding that
* each 3 x 3 matrix is in column major format.
*
* @result 0 indicates success.
*
* @author Carl Tape and translated to C by Ben Baker
*
* @date July 2017
*
* @copyright MIT
*
*/
int compearth_CMT2TT(const int nmt, const double *__restrict__ Min,
const bool ldisplay,
double *__restrict__ gamma,
double *__restrict__ delta,
double *__restrict__ M0,
double *__restrict__ kappa,
double *__restrict__ theta,
double *__restrict__ sigma,
double *__restrict__ K, double *__restrict__ N,
double *__restrict__ S, double *__restrict__ thetadc,
double *__restrict__ lam, double *__restrict__ U)
{
double *lamdev, *lamiso, Vwork[9], Yrot[9], M[6],
Sloc[12], Kloc[12], Nloc[12], kappaL[4], sigmaL[4], thetaL[4];
double *thetadcWork;
double Uwork[9*CE_CHUNKSIZE] __attribute__((aligned(64)));
double lamWork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));
double Nwork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));
double Swork[3*CE_CHUNKSIZE] __attribute__((aligned(64)));
//double lamSpace[3*MAXMT];
//double uSpace[9*MAXMT];
bool lwantLam, lwantK, lwantN, lwantS, lwantU;
int itemp[4], ierr, ierrAll, match, imt, j, jmt, nmtLoc, nMatch;
const int isort = 1;
const double rotAngle = 45.0;
const double tol = 1.e-6;
ierr = 0;
if (nmt < 1 || Min == NULL || gamma == NULL || delta == NULL ||
M0 == NULL || kappa == NULL || theta == NULL || sigma == NULL)
{
if (nmt < 1){fprintf(stderr, "%s: No moment tensors\n", __func__);}
if (Min == NULL){fprintf(stderr, "%s: Min is NULL\n", __func__);}
if (gamma == NULL){fprintf(stderr, "%s: gamma is NULL\n", __func__);}
if (delta == NULL){fprintf(stderr, "%s: delta is NULL\n", __func__);}
if (M0 == NULL){fprintf(stderr, "%s: M0 is NULL\n", __func__);}
if (kappa == NULL){fprintf(stderr, "%s: kappa is NULL\n", __func__);}
if (theta == NULL){fprintf(stderr, "%s: theta is NULL\n", __func__);}
if (sigma == NULL){fprintf(stderr, "%s: sigma is NULL\n", __func__);}
return -1;
}
// Determine if eigenvalue/eigenvector decomposition is requested
lwantLam = false;
if (lam != NULL){lwantLam = true;}
lwantU = false;
if (U != NULL){lwantU = true;}
// Determine the desired fault vectors
lwantK = false;
lwantN = false;
lwantS = false;
if (K != NULL){lwantK = true;}
if (N != NULL){lwantN = true;}
if (S != NULL){lwantS = true;}
// Loop on moment tensor chunks
for (jmt=0; jmt<nmt; jmt=jmt+CE_CHUNKSIZE)
{
nmtLoc = MIN(CE_CHUNKSIZE, nmt - jmt);
// This is the numerically expensive part b/c of eigendecomposition
ierrAll = 0;
for (imt=0; imt<nmtLoc; imt++)
{
// KEY: Convert M into another basis.
// YOU MUST ALSO CHANGE north AND zenith IN fault2vecang BELOW
// --> U will be with respect to this basis (from CMTdecom.m)
// ierr = compearth_convertMT(1, CE_USE, CE_NWU, &Min[6*imt], M);
ierr = compearth_convertMT(1, CE_USE, CE_SEU,
&Min[6*(jmt+imt)], M);
if (ierr != 0)
{
fprintf(stderr, "%s: Error switching basis\n", __func__);
ierrAll = ierrAll + 1; //break;
}
// PART 1: moment tensor source type (or pattern)
// Decompose moment tensor into eigenvalues + basis (M = U*lam*U')
// NOTE: ordering of eigenvalues is important.
ierr = compearth_CMTdecom(1, M, isort, &lamWork[3*imt],
&Uwork[9*imt]);
if (ierr != 0)
{
fprintf(stderr, "%s: Error decomposing CMT\n", __func__);
ierrAll = ierrAll + 1; //break;
}
}
if (ierrAll != 0)
{
fprintf(stderr, "%s: Error during eigendecomposition\n", __func__);
ierr = 1;
goto ERROR;
}
// Compute the lune coordinates and magnitude from eigenvalues
lamdev = NULL;
lamiso = NULL;
thetadcWork = NULL;
if (thetadc != NULL){thetadcWork = &thetadc[jmt];}
ierr = compearth_lam2lune(nmtLoc, lamWork, &gamma[jmt], &delta[jmt],
&M0[jmt], thetadcWork,
lamdev, lamiso);
// Part 2: moment tensor orientation; TT2012, Section 6.3
ierr = compearth_eulerUtil_rotmat(1, &rotAngle, 2, Yrot);
if (ierr != 0)
{
fprintf(stderr, "%s: Error computing rotation matrix\n", __func__);
return -1;
}
// Compute candidate fault vectors
for (imt=0; imt<nmtLoc; imt++)
{
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
3, 3, 3, 1.0, &Uwork[9*imt], 3, Yrot, 3,
0.0, Vwork, 3); // V = U*Yrot (TT2012, p. 487)
Swork[3*imt+0] = Vwork[0];
Swork[3*imt+1] = Vwork[1];
Swork[3*imt+2] = Vwork[2];
Nwork[3*imt+0] = Vwork[6];
Nwork[3*imt+1] = Vwork[7];
Nwork[3*imt+2] = Vwork[8];
}
// Save lambda and U
if (lwantLam){cblas_dcopy(3*nmtLoc, lamWork, 1, &lam[3*jmt], 1);}
if (lwantU){cblas_dcopy(9*nmtLoc, Uwork, 1, &U[9*jmt], 1);}
// Reassign ~0 elements to 0; ~1 elements to 1, and ~-1 elements to -1.
setZero(nmtLoc, tol, Swork);
setZero(nmtLoc, tol, Nwork);
// Compute fault angles for four possible combinations (TT2012 Fig 15)
for (imt=0; imt<nmtLoc; imt++)
{
for (j=0; j<3; j++)
{
Sloc[3*0+j] = Swork[3*imt+j]; Nloc[3*0+j] = Nwork[3*imt+j];
Sloc[3*1+j] =-Swork[3*imt+j]; Nloc[3*1+j] =-Nwork[3*imt+j];
Sloc[3*2+j] = Nwork[3*imt+j]; Nloc[3*2+j] = Swork[3*imt+j];
Sloc[3*3+j] =-Nwork[3*imt+j]; Nloc[3*3+j] =-Swork[3*imt+j];
}
faultVec2Ang(&Sloc[0], &Nloc[0], &thetaL[0], &sigmaL[0],
&kappaL[0], &Kloc[0], &ierr);
faultVec2Ang(&Sloc[3], &Nloc[3], &thetaL[1], &sigmaL[1],
&kappaL[1], &Kloc[3], &ierr);
faultVec2Ang(&Sloc[6], &Nloc[6], &thetaL[2], &sigmaL[2],
&kappaL[2], &Kloc[6], &ierr);
faultVec2Ang(&Sloc[9], &Nloc[9], &thetaL[3], &sigmaL[3],
&kappaL[3], &Kloc[9], &ierr);
// There are four combinations of N and S that represent a double
// copule moment tensor, as shown in Figure 15 of TT2012.
// From these four combinations, there are two possible fault
// planes. We want to isoate the combination that is within the
// boundingregion shown in Figures 16 and B1.
memset(itemp, 0, 4*sizeof(int));
nMatch = 0;
for (j=0; j<4; j++)
{
if (thetaL[j] <= 90.0 + tol && fabs(sigmaL[j]) <= 90.0 + tol)
{
itemp[nMatch] = j; //bmatch[j] = true;
nMatch = nMatch + 1;
}
}
if (nMatch == 1)
{
match = itemp[0];
}
else if (nMatch == 2)
{
match = pickP1(thetaL[itemp[0]], sigmaL[itemp[0]], kappaL[itemp[0]],
thetaL[itemp[1]], sigmaL[itemp[1]], kappaL[itemp[1]],
tol, itemp[0], itemp[1]);
if (match < 0)
{
fprintf(stderr, "%s: Failed to pick a fault plane\n",
__func__);
ierr = 1;
goto ERROR;
}
}
else if (nMatch == 3)
{
fprintf(stdout,
"%s: Warning mt on bdry of orientation domain 3 candidates\n",
__func__);
fprintf(stdout, "%s: thetas: %e %e %e\n", __func__,
thetaL[0], thetaL[1], thetaL[2]);
fprintf(stdout, "%s: sigmas: %e %e %e\n", __func__,
sigmaL[0], sigmaL[1], sigmaL[2]);
fprintf(stdout, "%s: kappas: %e %e %e\n", __func__,
kappaL[0], kappaL[1], kappaL[2]);
// Just take the first one
match = itemp[0];
}
else if (nMatch == 4)
{
fprintf(stderr, "%s: Error not yet programmed\n", __func__);
ierr = 1;
goto ERROR;
}
else
{
fprintf(stderr, "%s: Error no match\n", __func__);
ierr = 1;
goto ERROR;
}
// Select the angle
kappa[jmt+imt] = kappaL[match];
sigma[jmt+imt] = sigmaL[match];
theta[jmt+imt] = thetaL[match];
// Fault vectors
if (lwantK)
{
for (j=0; j<3; j++){K[3*(jmt+imt)+j] = Kloc[3*match+j];}
}
if (lwantN)
{
for (j=0; j<3; j++){N[3*(jmt+imt)+j] = Nloc[3*match+j];}
}
if (lwantS)
{
for (j=0; j<3; j++){S[3*(jmt+imt)+j] = Sloc[3*match+j];}
}
}
} // Loop on moment tensor chunks
if (ldisplay)
{
fprintf(stderr, "%s: ldisply not yet supported\n", __func__);
}
ERROR:;
/*
Uwork = NULL;
lamWork = NULL;
*/
return ierr;
}
/*!
* @brief Returns fault angles in degrees. Assumes input vectors are in
* the South-East-Up basis.
*
* @author Carl Tape and converted to C by Ben Baker
*
* @copyright MIT
*
*/
static void faultVec2Ang(const double *__restrict__ S,
const double *__restrict__ N,
double *theta, double *sigma,
double *kappa, double *__restrict__ K, int *ierr)
{
double v[3], costh, vnorm;
int ierr1;
const double deg = 180.0/M_PI;
// South-East-Up (as In TT2012)
const double zenith[3] = {0, 0, 1};
const double negZenith[3] = {0, 0, -1};
const double north[3] = {-1, 0, 0};
*ierr = 0;
*kappa = (double) NAN;
*theta = (double) NAN;
*sigma = (double) NAN;
// Strike vector from TT2012, Eqn 29
cross3(zenith, N, v);
vnorm = norm3(v);
if (vnorm < DBL_EPSILON) //== 0.0)
{
fprintf(stderr,
"%s: Horizontal fault -- strike vector is same as slip vector\n",
__func__);
K[0] = S[0];
K[1] = S[1];
K[2] = S[2];
}
else
{
K[0] = v[0]/vnorm;
K[1] = v[1]/vnorm;
K[2] = v[2]/vnorm;
}
// Figure 14
*kappa = compearth_eulerUtil_fangleSigned(3, north, K, negZenith, &ierr1);
if (ierr1 != 0){*ierr = *ierr + 1;}
*kappa = wrap360(*kappa);
// Figure 14
costh = dot3(N, zenith);
*theta = acos(costh)*deg;
// Figure 14
*sigma = compearth_eulerUtil_fangleSigned(3, K, S, N, &ierr1);
if (ierr1 != 0){*ierr = *ierr + 1;}
return;
}
static void setZero(const int nmt, const double tol, double *__restrict__ X)
{
double dmax;
int i, idmax;
// Compute the largest element of abs(X)
idmax = (int) cblas_idamax(3*nmt, X, 1);
dmax = X[idmax];
// Elements near zero whilst trying to eliminate round-off errors
#pragma omp simd
for (i=0; i<3*nmt; i++)
{
if (fabs(X[i]/dmax) < tol){X[i] = 0.0;}
}
#pragma omp simd
for (i=0; i<3*nmt; i++)
{
if (fabs(X[i] - 1.0) < tol){X[i] =-1.0;}
}
#pragma omp simd
for (i=0; i<3*nmt; i++)
{
if (fabs(X[i] + 1.0) < tol){X[i] = 1.0;}
}
return;
}
static int pickP1(const double thetaA, const double sigmaA, const double kappaA,
const double thetaB, const double sigmaB, const double kappaB,
const double tol, const int p1, const int p2)
{
int ipick;
ipick =-1;
if (fabs(thetaA - 90.0) < tol)
{
if (kappaA < 180.0){ipick = p1;}
if (kappaB < 180.0){ipick = p2;}
return ipick;
}
if (fabs(sigmaA - 90.0) < tol)
{
if (kappaA < 180.0){ipick = p1;}
if (kappaB < 180.0){ipick = p2;}
return ipick;
}
if (fabs(sigmaA + 90.0) < tol)
{
if (kappaA < 180.0){ipick = p1;}
if (kappaB < 180.0){ipick = p2;}
return ipick;
}
fprintf(stderr, "%s: Error no selection criterion was met\n", __func__);
fprintf(stderr, "thetaA,sigmaA,kappaA=%f,%f,%f\n", thetaA, sigmaA, kappaA);
fprintf(stderr, "thetaB,sigmaB,kappaB=%f,%f,%f\n", thetaB, sigmaB, kappaB);
return ipick;
}
| {
"alphanum_fraction": 0.5045824264,
"avg_line_length": 39.8584474886,
"ext": "c",
"hexsha": "e9305f80b03d1a0fcde24f92c02906b69e008d2f",
"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/CMT2TT.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/CMT2TT.c",
"max_line_length": 84,
"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/CMT2TT.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": 5044,
"size": 17458
} |
#pragma once
#include <gsl.h>
#include <QString>
namespace gsl {
inline QString to_QString(gsl::cstring_span<> view) { return QString::fromLatin1(view.data(), view.size()); }
} | {
"alphanum_fraction": 0.6994535519,
"avg_line_length": 20.3333333333,
"ext": "h",
"hexsha": "44b191616ab2993e52c7a860aea6382461349717",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z",
"max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carthurs/CRIMSONGUI",
"max_forks_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"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": "carthurs/CRIMSONGUI",
"max_issues_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h",
"max_line_length": 113,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carthurs/CRIMSONGUI",
"max_stars_repo_path": "Modules/SolverSetupService/include/SolverSetupUtils.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z",
"num_tokens": 45,
"size": 183
} |
#include "jobqueue.h"
#include "ance_degnome.h"
#include "fitfunc.h"
#include "flagparse.c"
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <limits.h>
typedef struct JobData JobData;
struct JobData {
Degnome* child;
Degnome* p1;
Degnome* p2;
};
void usage(void);
void help_menu(void);
int jobfunc(void* p, void* tdat);
void calculate_diversity(Degnome* generation, double** percent_decent, double* diversity);
const char* usageMsg =
"Usage: devosim [-bhrv] [-s | -u] [-c chromosome_length]\n"
"\t\t [-e mutation_effect] [-g num_generations]\n"
"\t\t [-m mutation_rate] [-o crossover_rate]\n"
"\t\t [-p population_size] [-t num_threads]\n"
"\t\t [--seed rngseed] [--target hat_height target]\n"
"\t\t [--sqrt | --linear | --close | --ceiling | --log]\n";
const char* helpMsg =
"OPTIONS\n"
"\t -b\t Simulation will stop when all degnomes are identical.\n\n"
"\t -c chromosome_length\n"
"\t\t Set chromosome length for the current simulation.\n"
"\t\t Default chromosome length is 10.\n\n"
"\t -e mutation_effect\n"
"\t\t Set how much a mutation will effect a gene on average.\n"
"\t\t Default mutation effect is 2.\n\n"
"\t -g num_generations\n"
"\t\t Set how many generations this simulation will run for.\n"
"\t\t Default number of generations is 1000.\n\n"
"\t -h\t Display this help menu.\n\n"
"\t -m mutation_rate\n"
"\t\t Set the mutation rate for the current simulation.\n"
"\t\t Default mutation rate is 1.\n\n"
"\t -o crossover_rate\n"
"\t\t Set the crossover rate for the current simulation.\n"
"\t\t Default crossover rate is 2.\n\n"
"\t -p population_size\n"
"\t\t Set the population size for the current simulation.\n"
"\t\t Default population size is 10.\n\n"
"\t -r\t Only show percentages of descent from the original genomes.\n\n"
"\t -s\t Degnome selection will occur.\n\n"
"\t -u\t All degnomes contribute to two offspring.\n\n"
"\t -v\t Output will be given for every generation.\n\n"
"\t -t num_threads\n"
"\t\t Select the number of threads to be used in the current run.\n"
"\t\t Default is 0 (which will result in 3/4 of cores being used).\n"
"\t\t Must be 1 if a seed is used in order to prevent race conditions.\n\n"
"\t --seed rngseed\n"
"\t\t Select the seed used by the RNG in the current run.\n"
"\t\t Default seed is 0 (which will result in a random seed).\n\n"
"\t --target hat_height target\n"
"\t\t Sets the ideal hat height for the current simulation\n"
"\t\t Used for fitness functions that have an \"ideal\" value.\n\n"
"\t --sqrt\t\t fitness will be sqrt(hat_height)\n\n"
"\t --linear\t fitness will be hat_height\n\n"
"\t --close\t fitness will be (target - abs(target - hat_height))\n\n"
"\t --ceiling\t fitness will quickly level off after passing target\n\n";
pthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER;
unsigned long rngseed=0;
// there is no need for the line 'int chrom_size' as it is declared as a global variable in degnome.h
int pop_size;
int num_gens;
int mutation_rate;
int mutation_effect;
int crossover_rate;
int selective;
int uniform;
int verbose;
int reduced;
int break_at_zero_diversity;
void usage(void) {
fputs(usageMsg, stderr);
exit(EXIT_FAILURE);
}
void help_menu(void) {
fputs(helpMsg, stderr);
exit(EXIT_FAILURE);
}
int num_threads = 0;
JobQueue* jq;
void *ThreadState_new(void *notused);
void ThreadState_free(void *rng);
void *ThreadState_new(void *notused) {
// Lock seed, initialize random number generator, increment seed,
// and unlock.
gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus);
pthread_mutex_lock(&seedLock);
gsl_rng_set(rng, rngseed);
rngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);
pthread_mutex_unlock(&seedLock);
return rng;
}
void ThreadState_free(void *rng) {
gsl_rng_free((gsl_rng *) rng);
}
int jobfunc(void* p, void* tdat) {
gsl_rng* rng = (gsl_rng*) tdat;
JobData* data = (JobData*) p; //get data out
Degnome_mate(data->child, data->p1, data->p2, rng, mutation_rate, mutation_effect, crossover_rate); //mate
return 0; //exited without error
}
void calculate_diversity(Degnome* generation, double** percent_decent, double* diversity) {
*diversity = 0;
for (int i = 0; i < pop_size; i++) { //calculate percent decent for each degnome
for (int j = 0; j < pop_size; j++) {
percent_decent[i][j] = 0;
for (int k = 0; k < chrom_size; k++) {
if (generation[i].GOI_array[k] == j) {
percent_decent[i][j]++;
}
}
percent_decent[i][j] /= chrom_size;
}
}
for (int j = 0; j < pop_size; j++) { //sum and average
percent_decent[pop_size][j] = 0;
for (int k = 0; k < pop_size; k++) {
percent_decent[pop_size][j] += percent_decent[k][j];
}
percent_decent[pop_size][j] /= pop_size;
}
for (int i = 0; i < pop_size; i++) { //calculate percent diversity for the entire generation
for (int j = 0; j < pop_size; j++) {
if (i == j) {
continue;
}
for (int k = 0; k < chrom_size; k++) {
if (generation[i].GOI_array[k] != generation[j].GOI_array[k]) {
(*diversity)++;
}
}
}
}
*diversity /= ((pop_size-1) * pop_size * chrom_size);
}
int main(int argc, char **argv) {
int * flags = NULL;
if (parse_flags(argc, argv, 3, &flags) == -1) {
free(flags);
usage();
}
if (flags[2] == 1) {
free(flags);
help_menu();
}
break_at_zero_diversity = flags[1];
reduced = flags[3];
verbose = flags[4];
if (flags[5] == 1) {
selective = 1;
}
else if (flags[5] == 2) {
uniform = 1;
}
chrom_size = flags[6];
mutation_effect = flags[7];
num_gens = flags[8];
mutation_rate = flags[9];
crossover_rate = flags[10];
pop_size = flags[11];
num_threads = flags[12];
if(flags[13] == 0){
set_function("linear");
}
else if(flags[13] == 1){
set_function("sqrt");
}
else if(flags[13] == 2){
set_function("close");
}
else if(flags[13] == 3){
set_function("ceiling");
}
else if(flags[13] == 4){
set_function("log");
}
target_num = flags[14];
if(flags[15] <= 0) {
time_t currtime = time(NULL); // time
unsigned long pid = (unsigned long) getpid(); // process id
rngseed = currtime ^ pid; // random seed
}
else{
rngseed = flags[15];
}
gsl_rng* rng = gsl_rng_alloc(gsl_rng_taus); // rand generator
gsl_rng_set(rng, rngseed);
free(flags);
if (num_threads <= 0) {
if (num_threads < 0) {
#ifdef DEBUG_MODE
fprintf(stderr, "Error invalid number of threads: %u\n", num_threads);
#endif
}
num_threads = (3*getNumCores()/4);
}
#ifdef DEBUG_MODE
fprintf(stderr, "Final number of threads: %u\n", num_threads);
#endif
Degnome* parents;
Degnome* children;
Degnome* temp;
printf("%u, %u, %u\n", chrom_size, pop_size, num_gens);
parents = malloc(pop_size*sizeof(Degnome));
children = malloc(pop_size*sizeof(Degnome));
for (int i = 0; i < pop_size; i++) {
parents[i].dna_array = malloc(chrom_size*sizeof(double));
parents[i].GOI_array = malloc(chrom_size*sizeof(int));
children[i].dna_array = malloc(chrom_size*sizeof(double));
children[i].GOI_array = malloc(chrom_size*sizeof(int));
parents[i].hat_size = 0;
for (int j = 0; j < chrom_size; j++) {
parents[i].dna_array[j] = 10; //children aren't initialized
parents[i].hat_size += 10;
parents[i].GOI_array[j] = (i); //track ancestries
}
}
double* diversity;
double** percent_decent;
diversity = malloc(sizeof(double));
*diversity = 1;
percent_decent = malloc((pop_size+1)*sizeof(double*));
for (int i = 0; i < pop_size+1; i++) {
percent_decent[i] = malloc(pop_size*sizeof(double));
if (i == pop_size) {
continue;
}
for (int j = 0; j < pop_size; j++) {
if (i == j) {
percent_decent[i][j] = 1;
}
else {
percent_decent[i][j] = 0;
}
}
}
if (!reduced && !verbose) {
printf("\nGeneration 0:\n\n");
for (int i = 0; i < pop_size; i++) {
printf("Degnome %u allele values:\n", i);
if (!reduced) {
for (int j = 0; j < chrom_size; j++) {
printf("%lf\t", parents[i].dna_array[j]);
}
printf("\n");
}
else {
printf("%lf\n", parents[i].dna_array[0]);
}
printf("Degnome %u ancestries:\n", i);
if (!reduced) {
for (int j = 0; j < chrom_size; j++) {
printf("%u\t", parents[i].GOI_array[j]);
}
printf("\n");
}
else {
printf("%u\n", parents[i].GOI_array[0]);
}
}
}
printf("\n\n");
int final_gen;
int broke_early = 0;
jq = JobQueue_new(num_threads, NULL, ThreadState_new, ThreadState_free);
JobData* dat = malloc(pop_size*sizeof(JobData));
for (int i = 0; i < num_gens; i++) {
if (break_at_zero_diversity) {
calculate_diversity(parents, percent_decent, diversity);
if ((*diversity) <= 0) {
final_gen = i;
broke_early = 1;
break;
}
}
if (!uniform) {
double fit;
if (selective) {
fit = get_fitness(parents[0].hat_size);
}
else {
fit = 100; //in runs withoutslection, everybody is equally fit
}
double total_hat_size = fit;
double cum_hat_size[pop_size];
cum_hat_size[0] = fit;
for (int j = 1; j < pop_size; j++) {
if (selective) {
fit = get_fitness(parents[j].hat_size);
}
else {
fit = 100;
}
total_hat_size += fit;
cum_hat_size[j] = (cum_hat_size[j-1] + fit);
}
for (int j = 0; j < pop_size; j++) {
pthread_mutex_lock(&seedLock);
gsl_rng_set(rng, rngseed);
rngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);
pthread_mutex_unlock(&seedLock);
int m, d;
double win_m = gsl_rng_uniform(rng);
win_m *= total_hat_size;
double win_d = gsl_rng_uniform(rng);
win_d *= total_hat_size;
// printf("win_m:%lf, wind:%lf, max: %lf\n", win_m,win_d,total_hat_size);
for (m = 0; cum_hat_size[m] < win_m; m++) {
continue;
}
for (d = 0; cum_hat_size[d] < win_d; d++) {
continue;
}
// printf("m:%u, d:%u\n", m,d);
dat[j].child = (children + j);
dat[j].p1 = (parents + m);
dat[j].p2 = (parents + d);
JobQueue_addJob(jq, jobfunc, dat + j); }
}
else {
// printf("uniform!!!\n");
int moms[pop_size];
int dads[pop_size];
int mom_max = pop_size;
int dad_max = pop_size;
int m, d;
for (int j = 0; j < pop_size; j++) {
moms[j] = j;
dads[j] = j;
}
for (int j = 0; j < pop_size; j++) {
pthread_mutex_lock(&seedLock);
gsl_rng_set(rng, rngseed);
rngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1);
pthread_mutex_unlock(&seedLock);
int index_m = (int) gsl_rng_uniform_int (rng, mom_max);
int index_d = (int) gsl_rng_uniform_int (rng, dad_max);
m = moms[index_m];
d = dads[index_d];
// printf("m:\t%u\nd:\t%u\n", m, d);
//reduce the pool of available degnomes
//in order to make sure everybody get's two chances to mate
//one as a dad and one as a mom
int temp_m = moms[index_m];
int temp_d = dads[index_d];
moms[index_m] = moms[mom_max-1];
dads[index_d] = dads[dad_max-1];
moms[mom_max-1] = temp_m;
dads[dad_max-1] = temp_d;
mom_max--;
dad_max--;
dat[j].child = (children + j);
dat[j].p1 = (parents + m);
dat[j].p2 = (parents + d);
JobQueue_addJob(jq, jobfunc, dat + j);
}
}
JobQueue_waitOnJobs(jq);
temp = children;
children = parents;
parents = temp;
if (verbose) {
calculate_diversity(parents, percent_decent, diversity);
printf("\nGeneration %u:\n", i);
if (!reduced) {
for (int k = 0; k < pop_size; k++) {
printf("\n\nDegnome %u allele values:\n", k);
for (int j = 0; j < chrom_size; j++) {
printf("%lf\t", parents[k].dna_array[j]);
}
if (selective) {
printf("\nTOTAL HAT SIZE: %lg\n\n", parents[k].hat_size);
}
else {
printf("\n");
}
printf("\n\nDegnome %u ancestries:\n", k);
for (int j = 0; j < chrom_size; j++) {
printf("%u\t", parents[k].GOI_array[j]);
}
printf("\n");
for (int j = 0; j < pop_size; j++) {
if (percent_decent[k][j] > 0) {
printf("%lf%% Degnome %u\t", (100*percent_decent[k][j]), j);
}
}
}
}
printf("\nAverage population descent percentages:\n");
for (int j = 0; j < pop_size; j++) {
if (percent_decent[pop_size][j] > 0) {
printf("%lf%% Degnome %u\t", (100*percent_decent[pop_size][j]), j);
}
}
printf("\nPercent diversity: %lf\n", (100* (*diversity)));
printf("\n\n");
}
}
JobQueue_noMoreJobs(jq);
if (verbose) {
printf("\n");
}
calculate_diversity(parents, percent_decent, diversity);
// printf("\n\n DIVERSITY%lf\n\n\n", *diversity);
if (broke_early) {
printf("Generation %u:\n", final_gen);
}
else {
printf("Generation %u:\n", num_gens);
}
if (!reduced) {
for (int i = 0; i < pop_size; i++) {
printf("\n\nDegnome %u allele values:\n", i);
if (!reduced) {
for (int j = 0; j < chrom_size; j++) {
printf("%lf\t", parents[i].dna_array[j]);
}
}
printf("\n\nDegnome %u ancestries:\n", i);
if (!reduced) {
for (int j = 0; j < chrom_size; j++) {
printf("%u\t", parents[i].GOI_array[j]);
}
printf("\n");
}
for (int j = 0; j < pop_size; j++) {
if (percent_decent[i][j] > 0) {
printf("%lf%% Degnome %u\t", (100*percent_decent[i][j]), j);
}
}
printf("\n");
if (selective) {
printf("\nTOTAL HAT SIZE: %lg\n\n", parents[i].hat_size);
}
else {
printf("\n\n");
}
}
}
printf("Average population decent percentages:\n");
for (int j = 0; j < pop_size; j++) {
if (percent_decent[pop_size][j] > 0) {
printf("%lf%% Degnome %u\t", (100*percent_decent[pop_size][j]), j);
}
}
printf("\nPercent diversity: %lf\n", (100* (*diversity)));
printf("\n\n\n");
//free everything
JobQueue_free(jq);
free(dat);
for (int i = 0; i < pop_size; i++) {
free(parents[i].dna_array);
free(children[i].dna_array);
free(parents[i].GOI_array);
free(children[i].GOI_array);
parents[i].hat_size = 0;
free(percent_decent[i]);
}
free(percent_decent[pop_size]);
free(parents);
free(children);
free(percent_decent);
free(diversity);
gsl_rng_free (rng);
}
| {
"alphanum_fraction": 0.5907917968,
"avg_line_length": 26.0637168142,
"ext": "c",
"hexsha": "1866aa5e3a62c2d5f31f31d27da219d15160048e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z",
"max_forks_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "masalemi/PopGenSim",
"max_forks_repo_path": "src/devosim.c",
"max_issues_count": 27,
"max_issues_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f",
"max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "masalemi/PopGenSim",
"max_issues_repo_path": "src/devosim.c",
"max_line_length": 110,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "masalemi/PopGenSim",
"max_stars_repo_path": "src/devosim.c",
"max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z",
"num_tokens": 4597,
"size": 14726
} |
/* multifit/lmpar.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_permute_vector_double.h>
#include "qrsolv.c"
static size_t
count_nsing (const gsl_matrix * r)
{
/* Count the number of nonsingular entries. Returns the index of the
first entry which is singular. */
size_t n = r->size2;
size_t i;
for (i = 0; i < n; i++)
{
double rii = gsl_matrix_get (r, i, i);
if (rii == 0)
{
break;
}
}
return i;
}
static void
compute_newton_direction (const gsl_matrix * r, const gsl_permutation * perm,
const gsl_vector * qtf, gsl_vector * x)
{
/* Compute and store in x the Gauss-Newton direction. If the
Jacobian is rank-deficient then obtain a least squares
solution. */
const size_t n = r->size2;
size_t i, j, nsing;
for (i = 0 ; i < n ; i++)
{
double qtfi = gsl_vector_get (qtf, i);
gsl_vector_set (x, i, qtfi);
}
nsing = count_nsing (r);
#ifdef DEBUG
printf("nsing = %d\n", nsing);
printf("r = "); gsl_matrix_fprintf(stdout, r, "%g"); printf("\n");
printf("qtf = "); gsl_vector_fprintf(stdout, x, "%g"); printf("\n");
#endif
for (i = nsing; i < n; i++)
{
gsl_vector_set (x, i, 0.0);
}
if (nsing > 0)
{
for (j = nsing; j > 0 && j--;)
{
double rjj = gsl_matrix_get (r, j, j);
double temp = gsl_vector_get (x, j) / rjj;
gsl_vector_set (x, j, temp);
for (i = 0; i < j; i++)
{
double rij = gsl_matrix_get (r, i, j);
double xi = gsl_vector_get (x, i);
gsl_vector_set (x, i, xi - rij * temp);
}
}
}
gsl_permute_vector_inverse (perm, x);
}
static void
compute_newton_correction (const gsl_matrix * r, const gsl_vector * sdiag,
const gsl_permutation * p, gsl_vector * x,
double dxnorm,
const gsl_vector * diag, gsl_vector * w)
{
size_t n = r->size2;
size_t i, j;
for (i = 0; i < n; i++)
{
size_t pi = gsl_permutation_get (p, i);
double dpi = gsl_vector_get (diag, pi);
double xpi = gsl_vector_get (x, pi);
gsl_vector_set (w, i, dpi * (dpi * xpi) / dxnorm);
}
for (j = 0; j < n; j++)
{
double sj = gsl_vector_get (sdiag, j);
double wj = gsl_vector_get (w, j);
double tj = wj / sj;
gsl_vector_set (w, j, tj);
for (i = j + 1; i < n; i++)
{
double rij = gsl_matrix_get (r, i, j);
double wi = gsl_vector_get (w, i);
gsl_vector_set (w, i, wi - rij * tj);
}
}
}
static void
compute_newton_bound (const gsl_matrix * r, const gsl_vector * x,
double dxnorm, const gsl_permutation * perm,
const gsl_vector * diag, gsl_vector * w)
{
/* If the jacobian is not rank-deficient then the Newton step
provides a lower bound for the zero of the function. Otherwise
set this bound to zero. */
size_t n = r->size2;
size_t i, j;
size_t nsing = count_nsing (r);
if (nsing < n)
{
gsl_vector_set_zero (w);
return;
}
for (i = 0; i < n; i++)
{
size_t pi = gsl_permutation_get (perm, i);
double dpi = gsl_vector_get (diag, pi);
double xpi = gsl_vector_get (x, pi);
gsl_vector_set (w, i, dpi * (dpi * xpi / dxnorm));
}
for (j = 0; j < n; j++)
{
double sum = 0;
for (i = 0; i < j; i++)
{
sum += gsl_matrix_get (r, i, j) * gsl_vector_get (w, i);
}
{
double rjj = gsl_matrix_get (r, j, j);
double wj = gsl_vector_get (w, j);
gsl_vector_set (w, j, (wj - sum) / rjj);
}
}
}
/* compute scaled gradient g = D^{-1} J^T f (see More' eq 7.2) */
static void
compute_gradient_direction (const gsl_matrix * r, const gsl_permutation * p,
const gsl_vector * qtf, const gsl_vector * diag,
gsl_vector * g)
{
const size_t n = r->size2;
size_t i, j;
for (j = 0; j < n; j++)
{
double sum = 0;
for (i = 0; i <= j; i++)
{
sum += gsl_matrix_get (r, i, j) * gsl_vector_get (qtf, i);
}
{
size_t pj = gsl_permutation_get (p, j);
double dpj = gsl_vector_get (diag, pj);
gsl_vector_set (g, j, sum / dpj);
}
}
}
/* compute gradient g = J^T f */
static void
compute_gradient (const gsl_matrix * r, const gsl_vector * qtf,
gsl_vector * g)
{
const size_t n = r->size2;
size_t i, j;
for (j = 0; j < n; j++)
{
double sum = 0;
for (i = 0; i <= j; i++)
{
sum += gsl_matrix_get (r, i, j) * gsl_vector_get (qtf, i);
}
gsl_vector_set (g, j, sum);
}
}
static int
lmpar (gsl_matrix * r, const gsl_permutation * perm, const gsl_vector * qtf,
const gsl_vector * diag, double delta, double * par_inout,
gsl_vector * newton, gsl_vector * gradient, gsl_vector * sdiag,
gsl_vector * x, gsl_vector * w)
{
double dxnorm, gnorm, fp, fp_old, par_lower, par_upper, par_c;
double par = *par_inout;
size_t iter = 0;
#ifdef DEBUG
printf("ENTERING lmpar\n");
#endif
compute_newton_direction (r, perm, qtf, newton);
#ifdef DEBUG
printf ("newton = ");
gsl_vector_fprintf (stdout, newton, "%g");
printf ("\n");
printf ("diag = ");
gsl_vector_fprintf (stdout, diag, "%g");
printf ("\n");
#endif
/* Evaluate the function at the origin and test for acceptance of
the Gauss-Newton direction. */
dxnorm = scaled_enorm (diag, newton);
fp = dxnorm - delta;
#ifdef DEBUG
printf ("dxnorm = %g, delta = %g, fp = %g\n", dxnorm, delta, fp);
#endif
if (fp <= 0.1 * delta)
{
gsl_vector_memcpy (x, newton);
#ifdef DEBUG
printf ("took newton (fp = %g, delta = %g)\n", fp, delta);
#endif
*par_inout = 0;
return GSL_SUCCESS;
}
#ifdef DEBUG
printf ("r = ");
gsl_matrix_fprintf (stdout, r, "%g");
printf ("\n");
printf ("newton = ");
gsl_vector_fprintf (stdout, newton, "%g");
printf ("\n");
printf ("dxnorm = %g\n", dxnorm);
#endif
compute_newton_bound (r, newton, dxnorm, perm, diag, w);
#ifdef DEBUG
printf("perm = "); gsl_permutation_fprintf(stdout, perm, "%d");
printf ("diag = ");
gsl_vector_fprintf (stdout, diag, "%g");
printf ("\n");
printf ("w = ");
gsl_vector_fprintf (stdout, w, "%g");
printf ("\n");
#endif
{
double wnorm = enorm (w);
double phider = wnorm * wnorm;
/* w == zero if r rank-deficient,
then set lower bound to zero form MINPACK, lmder.f
Hans E. Plesser 2002-02-25 (hans.plesser@itf.nlh.no) */
if ( wnorm > 0 )
par_lower = fp / (delta * phider);
else
par_lower = 0.0;
}
#ifdef DEBUG
printf("par = %g\n", par );
printf("par_lower = %g\n", par_lower);
#endif
compute_gradient_direction (r, perm, qtf, diag, gradient);
gnorm = enorm (gradient);
#ifdef DEBUG
printf("gradient = "); gsl_vector_fprintf(stdout, gradient, "%g"); printf("\n");
printf("gnorm = %g\n", gnorm);
#endif
par_upper = gnorm / delta;
if (par_upper == 0)
{
par_upper = GSL_DBL_MIN / GSL_MIN_DBL(delta, 0.1);
}
#ifdef DEBUG
printf("par_upper = %g\n", par_upper);
#endif
if (par > par_upper)
{
#ifdef DEBUG
printf("set par to par_upper\n");
#endif
par = par_upper;
}
else if (par < par_lower)
{
#ifdef DEBUG
printf("set par to par_lower\n");
#endif
par = par_lower;
}
if (par == 0)
{
par = gnorm / dxnorm;
#ifdef DEBUG
printf("set par to gnorm/dxnorm = %g\n", par);
#endif
}
/* Beginning of iteration */
iteration:
iter++;
#ifdef DEBUG
printf("lmpar iteration = %d\n", iter);
#endif
#ifdef BRIANSFIX
/* Seems like this is described in the paper but not in the MINPACK code */
if (par < par_lower || par > par_upper)
{
par = GSL_MAX_DBL (0.001 * par_upper, sqrt(par_lower * par_upper));
}
#endif
/* Evaluate the function at the current value of par */
if (par == 0)
{
par = GSL_MAX_DBL (0.001 * par_upper, GSL_DBL_MIN);
#ifdef DEBUG
printf("par = 0, set par to = %g\n", par);
#endif
}
/* Compute the least squares solution of [ R P x - Q^T f, sqrt(par) D x]
for A = Q R P^T */
#ifdef DEBUG
printf ("calling qrsolv with par = %g\n", par);
#endif
{
double sqrt_par = sqrt(par);
qrsolv (r, perm, sqrt_par, diag, qtf, x, sdiag, w);
}
dxnorm = scaled_enorm (diag, x);
fp_old = fp;
fp = dxnorm - delta;
#ifdef DEBUG
printf ("After qrsolv dxnorm = %g, delta = %g, fp = %g\n", dxnorm, delta, fp);
printf ("sdiag = ") ; gsl_vector_fprintf(stdout, sdiag, "%g"); printf("\n");
printf ("x = ") ; gsl_vector_fprintf(stdout, x, "%g"); printf("\n");
printf ("r = ") ; gsl_matrix_fprintf(stdout, r, "%g"); printf("\nXXX\n");
#endif
/* If the function is small enough, accept the current value of par */
if (fabs (fp) <= 0.1 * delta)
goto line220;
if (par_lower == 0 && fp <= fp_old && fp_old < 0)
goto line220;
/* Check for maximum number of iterations */
if (iter == 10)
goto line220;
/* Compute the Newton correction */
compute_newton_correction (r, sdiag, perm, x, dxnorm, diag, w);
#ifdef DEBUG
printf ("newton_correction = ");
gsl_vector_fprintf(stdout, w, "%g"); printf("\n");
#endif
{
double wnorm = enorm (w);
par_c = fp / (delta * wnorm * wnorm);
}
#ifdef DEBUG
printf("fp = %g\n", fp);
printf("par_lower = %g\n", par_lower);
printf("par_upper = %g\n", par_upper);
printf("par_c = %g\n", par_c);
#endif
/* Depending on the sign of the function, update par_lower or par_upper */
if (fp > 0)
{
if (par > par_lower)
{
par_lower = par;
#ifdef DEBUG
printf("fp > 0: set par_lower = par = %g\n", par);
#endif
}
}
else if (fp < 0)
{
if (par < par_upper)
{
#ifdef DEBUG
printf("fp < 0: set par_upper = par = %g\n", par);
#endif
par_upper = par;
}
}
/* Compute an improved estimate for par */
#ifdef DEBUG
printf("improved estimate par = MAX(%g, %g) \n", par_lower, par+par_c);
#endif
par = GSL_MAX_DBL (par_lower, par + par_c);
#ifdef DEBUG
printf("improved estimate par = %g \n", par);
#endif
goto iteration;
line220:
#ifdef DEBUG
printf("LEAVING lmpar, par = %g\n", par);
#endif
*par_inout = par;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5700811001,
"avg_line_length": 21.690248566,
"ext": "c",
"hexsha": "1e7a3d1286261b4e534d5f8d9b03fde204be4933",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmpar.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmpar.c",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit/lmpar.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": 3392,
"size": 11344
} |
/* this manages and calls function to execute function
* from beginning to end
*/
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_statistics.h>
#include "fileio.h"
#include "data_process.h"
#include "sensor_history.h"
#include "sensor_validation.h"
#include "externs.h"
void handle_files(char *, double*, double*);
void sensor_validation(double*);
double data_processing(double*);
int sensor_number;
int temperature_min = 30;
int temperature_max = 60;
int data_number;
int group_number;
float q_percent;
/* path and names of the files used in the program
* which include input file, output file and sensor history file */
char input_file_name[255] = "../data/input_data/sample_input.csv";
char history_file_name[255] = "../data/sensor_history/sensor_history.csv";
char output_file_name[255] = "../data/output_data/output.csv";
int main() {
printf("\nApplication is running....\n");
/* user input for the number of sensors to process */
printf("Insert number of sensors:");
scanf("%d", &sensor_number);
/* determining the time intervals for the sensors */
int time_interval;
printf("Insert collected time intervals:");
scanf("%d", &time_interval);
printf("Insert q percent(Should be 0~1):");
scanf("%f", &q_percent);
if ((q_percent<0) || (q_percent>1)) {
printf("Invalid q_percent! It will be regarded as 0.7 of default value.\n");
q_percent = 0.7;
}
double values[256];
double time_value[256];
double group_values[sensor_number];
/* function performs reading of sensor data
* @input : file name
* @output : sensor time and associated values
*/
handle_files(input_file_name, &time_value[0], &values[0]);
/* number of calculations to be performed based on the user input */
group_number = data_number / sensor_number;
for (int i = 0; i < group_number; i++) {
time_value[i] = time_value[i * sensor_number];
}
/* check whether the user input and actual file data matches */
if (group_number != time_interval) {
printf("ERROR: Time interval numbers, sensor numbers do not match with your input file!\n");
exit(0);
}
sensor_validation(&values[0]);
/* seperating multiple data computations in the output file*/
FILE *fpout = fopen(output_file_name, "a");
fprintf(fpout, "--------------\n");
fclose(fpout);
FILE *fphis = fopen(history_file_name, "a");
fprintf(fphis, "--------------\n");
fclose(fphis);
for (int i = 0 ; i < group_number; i++) {
for (int j = 0; j < sensor_number; j++) {
group_values[j] = values[i*sensor_number + j];
}
printf("\n---------------------Time interval %d---------------------\n\n", i);
double fused = data_processing(&group_values[0]);
float time_val_file = (float)time_value[i];
write_data(time_val_file, fused, output_file_name);
}
return 1;
}
/* function checks whether an attempt made to open a file is succuessful or not */
void handle_files(char* input_file_name, double* time_value, double* values) {
printf("\n");
if (input_file_name != NULL) {
data_number = read_data(&time_value[0], &values[0], input_file_name);
if ( data_number == -1 ) {
printf("ERROR: File open failed!\n");
exit(0);
} else if ( data_number == 0 ) {
printf("ERROR: Sensor numbers inserted and file are different!\n");
exit(0);
} else if ( data_number > 0) {
printf("Read data successfully!\n");
}
} else {
printf("ERROR: Input file does not exist!\n");
exit(0);
}
}
/* function performs sensor validation for group values
* @input : group Values
*/
void sensor_validation(double* group_values) {
int res = reading_validation(&group_values[0]);
if (res == 1) {
frozen_value_check(&group_values[0]);
}
if (res == 0) {
printf("ERROR: Temperature values are out of range! Check history file.\n");
frozen_value_check(&group_values[0]);
}
}
/* function performs sensor fusion algo using group Values
* @input : group Values
* @output : fused result
*/
double data_processing(double* group_values) {
printf("Sensor Values:\n");
for (int i = 0; i < sensor_number; i++) {
printf("x%d=%f, ", i, group_values[i]);
}
/* Step 1: Calc the Support Degree Matrix */
gsl_matrix* D = gsl_matrix_alloc(sensor_number,sensor_number);
support_degree_generator(D, &group_values[0]); //function in data_process.c to get D - Support Degree Matrix
/* Step 2: Calc eigenval & eigenvec */
gsl_matrix* T = gsl_matrix_alloc(sensor_number,sensor_number);
gsl_vector* evec = gsl_vector_alloc(sensor_number);
gsl_matrix* Temp = gsl_matrix_alloc(sensor_number,sensor_number);
gsl_matrix_memcpy(Temp, D);
eigenvec_calc(evec, T, Temp); //function in data_process.c to get evec - eigen group_values & T - vectors
/* Step 3: Principal Comp Calc */
gsl_matrix* y = gsl_matrix_alloc(sensor_number,sensor_number);
principal_comp_calc(T, D, y); //function in data_process.c to get T - Principal Components
/* Step 4: Calc the contri rate of the kth principal comp */
double alpha[sensor_number];
contri_rate_calc_kth(evec, &alpha[0]); //function in data_process.c to get alpha
/* Step 5: Calc the contri rate of the m principal comp */
double phi[sensor_number];
major_contri_calc(&alpha[0], &phi[0]); //function in data_process.c to get phi
/* Step 6: Compute the integrated support degree score */
gsl_vector* Z = gsl_vector_alloc(sensor_number);
integ_supp_score_calc(&alpha[0], y, Z); //function in data_process.c to get z_i
/* Step 7-1: Eliminate incorrect data */
int sensor_correction[sensor_number];
elliminate_incorrect_data(Z, &sensor_correction[0]); //function in data_process.c to elliminate incorrect datas
/* Step 7-2: Compute the weight coefficient for each sensor */
double omega[sensor_number];
weight_coeff_calc(Z, &sensor_correction[0], &omega[0]); //function in data_process.c to get omega
/* Step 7-3: Compute the fused output */
double fused;
fused = fused_output(&omega[0], &group_values[0]); //function in data_process.c to get fused output
printf("FINAL STEP: \nThe fused output is %f\n", fused);
/* Free memory */
gsl_matrix_free(D);
gsl_matrix_free(Temp);
gsl_matrix_free(T);
gsl_vector_free(evec);
gsl_matrix_free(y);
gsl_vector_free(Z);
return fused;
}
| {
"alphanum_fraction": 0.6481781974,
"avg_line_length": 29.4739130435,
"ext": "c",
"hexsha": "998861dcf45a18103bf8f05d19e68a57933d34fb",
"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": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "src/main.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"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": "karanbirsandhu/nu-sense",
"max_issues_repo_path": "src/main.c",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "karanbirsandhu/nu-sense",
"max_stars_repo_path": "src/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1661,
"size": 6779
} |
// directdebye.c
// Computes the Debye sum from raytracing data.
// See man page for usage information.
#include <assert.h>
#include <complex.h>
#include <errno.h>
#include <error.h>
#include <gsl/gsl_const_mksa.h>
#include <malloc.h>
#include <math.h>
#include <matheval.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "hdfio.h"
#include "miscprint.h"
#include "parseargs.h"
#include "rays.h"
int main(int argc, char **argv) {
/* MPI initialization */
int rank, nprocs;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* parse command line arguments */
args_t *a = malloc(sizeof(args_t));
parse_args(argc, argv, a);
/* read the rays */
unsigned int nrays; /* number of rays */
ray_t *ray = NULL;
ray = readrays(a->filename_in, &nrays);
if (ray == NULL) {
error_at_line(-1, errno, __FILE__, __LINE__, "Problem reading ray file.\n");
}
/* pulse function */
void *pfcn_intensity = NULL;
pfcn_intensity = evaluator_create(a->pfcn_intensity_buffer);
if (pfcn_intensity == NULL) {
error_at_line(-1, EINVAL, __FILE__, __LINE__,
"Problem creating pulse evaluator function.");
}
/* apodization function */
void *pfcn_g = NULL;
pfcn_g = evaluator_create(a->pfcn_g_buffer);
if (pfcn_g == NULL) {
error_at_line(-1, EINVAL, __FILE__, __LINE__,
"Problem creating apodization evaluator function.");
}
/* root node prints some useful information */
if (rank == 0) {
print_args(a, nrays);
}
/* Before allocating what could potentially be a lot of memory, check to
* see if it's even possible. */
unsigned int i;
a->efield_ss_out = 1;
for (i = 0; i < 4; ++i) {
a->efield_ss_out *= a->dim_efield_out[i];
}
long page_size = sysconf(_SC_PAGE_SIZE);
// long pages_avail = sysconf(_SC_AVPHYS_PAGES);
long pages_tot = sysconf(_SC_PHYS_PAGES);
if (pages_tot * page_size < 8 * a->efield_ss_out * sizeof(complex double)) {
error_at_line(-1, ENOMEM, __FILE__, __LINE__,
"Size of output arrays exceed avaliable memory.\n");
}
/* Allocate memory for the fields. The _rcv is memory for nodes. */
complex double *efield_x = NULL;
complex double *efield_x_rcv = NULL;
complex double *efield_y = NULL;
complex double *efield_y_rcv = NULL;
complex double *efield_z = NULL;
complex double *efield_z_rcv = NULL;
double *efield_r = NULL;
double *efield_r_rcv = NULL;
/* The root node will be receiving all of the data, so it gets the whole
* thing. Calloc here to pre-zero out everything. */
if (rank == 0) {
efield_x =
(complex double *)calloc(a->efield_ss_out, sizeof(complex double));
efield_y =
(complex double *)calloc(a->efield_ss_out, sizeof(complex double));
efield_z =
(complex double *)calloc(a->efield_ss_out, sizeof(complex double));
efield_r = (double *)calloc(4 * (a->efield_ss_out), sizeof(double));
}
/* The root node and all the other nodes also get this little chunk to
* work on. The root node really has nothing better to do while waiting
* for information so there's no real waste. */
efield_x_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,
sizeof(complex double));
efield_y_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,
sizeof(complex double));
efield_z_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,
sizeof(complex double));
efield_r_rcv =
(double *)calloc(4 * (a->efield_ss_out / nprocs), sizeof(double));
/* Catch some possible malloc errors*/
if (errno) {
fprintf(stderr, "Node %d\n", rank);
error_at_line(-1, errno, __FILE__, __LINE__, "Error allocating memory.");
}
unsigned int n;
double w;
/* precompute some ray information */
for (n = 0; n < nrays; ++n, ++ray) {
w = 2 * M_PI * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000 / ray->lambda;
/* ray intensity for gaussian pulse */
ray->intensity *= evaluator_evaluate_x(pfcn_intensity, w);
if (isnan(ray->intensity)) {
error_at_line(-1, errno, __FILE__, __LINE__,
"Error with intensity function: got nan.");
}
/* analytic apodization factor for parabola */
ray->g *= evaluator_evaluate_x(pfcn_g, acos(ray->p0[2] / a->fs_radius));
if (isnan(ray->g)) {
error_at_line(-1, errno, __FILE__, __LINE__,
"Error with apodization function: got nan.");
}
/* all of the intensity information is stored in ray->g in order to
* save a few multiplications in the inner loop */
ray->g =
(1.0 / (a->fs_radius * ray->lambda * 0.001)) * ray->g * ray->intensity;
ray->e0[0] /= ray->lambda;
ray->e0[1] /= ray->lambda;
ray->e0[2] /= ray->lambda;
}
ray -= nrays;
/* precompute the position vectors in the efield we'll be dealing with */
if (rank == 0) {
double dr[4];
/* get the spacings of the electric field */
for (i = 0; i < 4; ++i) {
if (a->dim_efield_out[i] == 1) {
dr[i] = (a->dim_efield_ub[i] - a->dim_efield_lb[i]) /
((double)a->dim_efield_out[i]);
} else {
dr[i] = (a->dim_efield_ub[i] - a->dim_efield_lb[i]) /
((double)a->dim_efield_out[i] - 1);
}
}
/* set them */
unsigned int r_i[4] = {};
for (r_i[0] = 0; r_i[0] < a->dim_efield_out[0]; r_i[0]++) {
for (r_i[1] = 0; r_i[1] < a->dim_efield_out[1]; r_i[1]++) {
for (r_i[2] = 0; r_i[2] < a->dim_efield_out[2]; r_i[2]++) {
for (r_i[3] = 0; r_i[3] < a->dim_efield_out[3]; r_i[3]++) {
*efield_r++ = a->dim_efield_lb[0] + dr[0] * (double)r_i[0];
*efield_r++ = a->dim_efield_lb[1] + dr[1] * (double)r_i[1];
*efield_r++ = a->dim_efield_lb[2] + dr[2] * (double)r_i[2];
*efield_r++ = a->dim_efield_lb[3] + dr[3] * (double)r_i[3];
}
}
}
}
efield_r -= 4 * a->efield_ss_out;
}
/* send this spacing information out to everyone */
MPI_Scatter(efield_r, 4 * (a->efield_ss_out / nprocs), MPI_DOUBLE,
efield_r_rcv, 4 * (a->efield_ss_out / nprocs), MPI_DOUBLE, 0,
MPI_COMM_WORLD);
/* Main loop over ray data. This should be fast as possible. */
/* pre-computing the three efield_r_rcv lines doesn't appear to have a *
* significant effect on performance */
complex double tmp;
for (i = 0; i < a->efield_ss_out / nprocs; ++i) {
for (n = 0; n < nrays; ++n, ++ray) {
tmp = -1.0i * ray->g *
cexp(2.0i * M_PI *
((*(efield_r_rcv + 0) - ray->p0[0]) * ray->e0[0] +
(*(efield_r_rcv + 1) - ray->p0[1]) * ray->e0[1] +
(*(efield_r_rcv + 2) - ray->p0[2]) * ray->e0[2] - ray->OPL -
*(efield_r_rcv + 3) * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000.0 /
ray->lambda +
a->temporal_offset * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000.0 /
ray->lambda));
/* three polarization components */
efield_x_rcv[i] += ray->pol[0] * tmp;
efield_y_rcv[i] += ray->pol[1] * tmp;
efield_z_rcv[i] += ray->pol[2] * tmp;
}
ray -= nrays;
efield_r_rcv += 4;
}
efield_r_rcv -= 4 * i;
/* gather all data from nodes */
MPI_Gather(efield_x_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,
efield_x, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,
MPI_COMM_WORLD);
MPI_Gather(efield_y_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,
efield_y, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,
MPI_COMM_WORLD);
MPI_Gather(efield_z_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,
efield_z, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,
MPI_COMM_WORLD);
/* write electric field information to HDF file */
if (rank == 0) {
write_efield(a, efield_x, efield_y, efield_z);
}
/* clean up bit */
free(efield_x);
free(efield_y);
free(efield_z);
free(a);
free(efield_x_rcv);
free(efield_y_rcv);
free(efield_z_rcv);
free(efield_r_rcv);
if (rank == 0) free(efield_r);
free(ray);
evaluator_destroy(pfcn_intensity);
evaluator_destroy(pfcn_g);
MPI_Finalize();
return 0;
}
| {
"alphanum_fraction": 0.6042679312,
"avg_line_length": 34.4285714286,
"ext": "c",
"hexsha": "2fe5d28d1bae9678945a0732e27f7498e6ad3cd9",
"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": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "AaronWebster/directdebye",
"max_forks_repo_path": "directdebye.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"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": "AaronWebster/directdebye",
"max_issues_repo_path": "directdebye.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "AaronWebster/directdebye",
"max_stars_repo_path": "directdebye.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2563,
"size": 8435
} |
#ifndef __GSL_HELPER_H__
#define __GSL_HELPER_H__
#if defined _WIN32 || defined _WIN64
#include <crtdbg.h>
#define _gsl_asserte(expr,msg) _ASSERT_EXPR(expr,_CRT_WIDE(msg))
#else
#include <assert.h>
#define _gsl_asserte(expr,msg) assert(expr)
#endif
#define _gsl_assert(expr) _gsl_asserte(expr, #expr)
extern "C"
{
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix_double.h>
}
#include <limits>
#include <memory>
#include <functional>
#include <iostream>
namespace gsl
{
struct Precondition
{
template<typename E, typename Condition>
void check(Condition cond) {
if (!cond) throw E();
}
template<typename E, typename Condition, typename... ConditionList>
void check(Condition cond, ConditionList... conds) {
if (!cond) throw E();
else check<E>(conds...);
}
template<typename E, typename Condition, typename... ConditionList>
void operator () (Condition cond, ConditionList... conds) {
return check<E>(cond, conds...);
}
const char* file;
int line;
Precondition(const char* file, int line)
: file(file), line(line) {}
};
#define precondition Precondition(__FILE__, __LINE__).operator()
struct out_of_range: public std::exception {};
struct bad_pointer: public std::exception {};
struct bad_size: public std::exception {};
struct zero_devide: public std::exception {};
/**
* base_vector
* объектно-ориентированная оболочка для gsl_vector*
*/
class base_const_vector
{
protected:
base_const_vector() = default;
base_const_vector(base_const_vector&&) = default;
base_const_vector(const base_const_vector&) = default;
public:
double at(size_t i) const throw(std::exception) {
precondition<out_of_range>(i >= 0);
precondition<out_of_range>(i < ptr()->size);
return gsl_vector_get(ptr(), i);
}
double operator [] (size_t i) const throw (std::exception) {
return at(i);
}
const double* data() const {
return ptr()->data;
}
size_t size() const {
return ptr()->size;
}
virtual ~base_const_vector() {}
virtual const gsl_vector* ptr() const = 0;
};
class base_vector: public base_const_vector
{
protected:
base_vector() = default;
base_vector(base_vector&&) = default;
base_vector(const base_vector&) = default;
public:
double& at(size_t i) throw(std::exception) {
precondition<out_of_range>(i >= 0);
precondition<out_of_range>(i < ptr()->size);
return *gsl_vector_ptr(ptr(), i);
}
double& operator [] (size_t i) throw (std::exception) {
return at(i);
}
double* data() {
return ptr()->data;
}
void set_zero() {
gsl_vector_set_zero(ptr());
}
void set_all(double value) {
gsl_vector_set_all(ptr(), value);
}
virtual ~base_vector() {}
virtual gsl_vector* ptr() = 0;
};
class vector: public base_vector
{
public:
vector(vector&&) = default;
explicit vector(size_t n)
{
precondition<bad_size>(n > 0);
myvec = gsl_vector_calloc(n);
precondition<bad_pointer>(myvec);
}
vector(size_t n, double value)
{
precondition<bad_size>(n > 0);
myvec = gsl_vector_alloc(n);
gsl_vector_set_all(myvec, value);
precondition<bad_pointer>(myvec);
}
vector(const double* array, size_t n)
{
precondition<bad_pointer>(array);
precondition<bad_size>(n > 0);
gsl_vector_const_view view = gsl_vector_const_view_array(array, n);
myvec = gsl_vector_alloc(n);
gsl_vector_memcpy(myvec, &view.vector);
precondition<bad_pointer>(myvec);
}
explicit vector(const gsl_vector* vec)
{
precondition<bad_pointer>(vec);
myvec = gsl_vector_alloc(vec->size);
gsl_vector_memcpy(myvec, vec);
precondition<bad_pointer>(myvec);
}
explicit vector(const gsl_vector_view& view)
{
myvec = gsl_vector_alloc(view.vector.size);
gsl_vector_memcpy(myvec, &view.vector);
precondition<bad_pointer>(myvec);
}
explicit vector(const gsl_vector_const_view& view)
{
myvec = gsl_vector_alloc(view.vector.size);
gsl_vector_memcpy(myvec, &view.vector);
precondition<bad_pointer>(myvec);
}
vector(const base_const_vector& other)
: vector(other.ptr()) {}
vector(const vector& other)
: vector(other.myvec) {}
~vector() {
gsl_vector_free(myvec);
}
vector& operator = (const vector& other) {
if( this != &other ) {
precondition<bad_pointer>(other.myvec);
precondition<bad_size>(myvec->size == other.myvec->size);
gsl_vector_memcpy(myvec, other.myvec);
}
return *this;
}
gsl_vector* ptr() override {
return myvec;
}
const gsl_vector* ptr() const override {
return myvec;
}
private:
gsl_vector* myvec;
};
template<class V>
struct view_traits;
template<>
struct view_traits<gsl_vector_view> {
using value_t = double;
using vector_t = gsl_vector;
using view_t = gsl_vector_view;
inline static view_t view_array(value_t* arr, size_t n) {
return gsl_vector_view_array(arr, n);
}
inline static view_t view_array_with_stride(value_t* arr, size_t n, size_t stride) {
return gsl_vector_view_array_with_stride(arr, n, stride);
}
inline static view_t subvector(vector_t* v, size_t i, size_t n) {
return gsl_vector_subvector(v, i, n);
}
inline static view_t subvector_with_stride(vector_t* v, size_t i, size_t stride, size_t n) {
return gsl_vector_subvector_with_stride(v, i, stride, n);
}
};
template<>
struct view_traits<gsl_vector_const_view> {
using value_t = const double;
using vector_t = const gsl_vector;
using view_t = gsl_vector_const_view;
inline static view_t view_array(value_t* arr, size_t n) {
return gsl_vector_const_view_array(arr, n);
}
inline static view_t view_array_with_stride(value_t* arr, size_t n, size_t stride) {
return gsl_vector_const_view_array_with_stride(arr, n, stride);
}
inline static view_t subvector(vector_t* v, size_t i, size_t n) {
return gsl_vector_const_subvector(v, i, n);
}
inline static view_t subvector_with_stride(vector_t* v, size_t i, size_t stride, size_t n) {
return gsl_vector_const_subvector_with_stride(v, i, stride, n);
}
};
template<class View>
class base_view_t
{
protected:
typedef view_traits<View> traits;
typedef typename traits::value_t value_t;
typedef typename traits::vector_t vector_t;
typedef typename traits::view_t view_t;
view_t make_view(vector_t* v, size_t i, size_t stride, size_t n) {
precondition<bad_pointer>(v);
precondition<out_of_range>(i >= 0 && i < v->size);
precondition<out_of_range>(i + stride * (n - 1) < v->size);
precondition<bad_size>(n > 0 && n <= v->size - i);
return traits::subvector_with_stride(v, i, stride, n);
}
public:
base_view_t(const base_view_t& other)
: view(other.view) {}
base_view_t(const view_t& _view)
: view(_view) {}
base_view_t(vector_t* v)
: view( make_view(v, 0, 1, v->size) ) {}
base_view_t(vector_t* vector, size_t i, size_t n)
: view( make_view(vector, i, 1, n) ) {}
base_view_t(vector_t* vector, size_t i, size_t stride, size_t n)
: view( make_view(vector, i, stride, n) ) {}
protected:
view_t view;
};
class vector_const_view: public base_const_vector, public base_view_t<gsl_vector_const_view>
{
public:
using base_view_t<gsl_vector_const_view>::base_view_t;
vector_const_view(const base_const_vector& v)
: base_view_t(v.ptr()) {}
vector_const_view(const base_const_vector& v, size_t i, size_t n)
: base_view_t(v.ptr(), i, n) {}
vector_const_view(const base_const_vector& v, size_t i, size_t stride, size_t n)
: base_view_t(v.ptr(), i, stride, n) {}
const gsl_vector* ptr() const override {
return &view.vector;
}
};
class vector_view: public base_vector, public base_view_t<gsl_vector_view>
{
public:
using base_view_t<gsl_vector_view>::base_view_t;
vector_view(base_vector& v)
: base_view_t(v.ptr()) {}
vector_view(base_vector& v, size_t i, size_t n)
: base_view_t(v.ptr(), i, n) {}
vector_view(base_vector& v, size_t i, size_t stride, size_t n)
: base_view_t(v.ptr(), i, stride, n) {}
vector_view& operator = (const vector_view& other) {
if (this != &other)
view = other.view;
return *this;
}
const gsl_vector* ptr() const override {
return &view.vector;
}
gsl_vector* ptr() override {
return &view.vector;
}
};
inline std::ostream& operator << (std::ostream& output, const base_const_vector& v) {
output << '{';
for( size_t i=0; i<v.size(); ++i ) {
if( i > 0 ) output << ", ";
output << v[i];
}
output << '}';
return output;
}
}//namespace gsl
#endif //__GSL_HELPER_H__
| {
"alphanum_fraction": 0.6797197979,
"avg_line_length": 23.0981432361,
"ext": "h",
"hexsha": "149025d0d753c435afa815b1a469dbc4a3ac9394",
"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": "cdfbc878b24e436bc333e94eb9aade801a355ff1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sambritton/Fibrin_Network",
"max_forks_repo_path": "src/VectorMath.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cdfbc878b24e436bc333e94eb9aade801a355ff1",
"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": "sambritton/Fibrin_Network",
"max_issues_repo_path": "src/VectorMath.h",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cdfbc878b24e436bc333e94eb9aade801a355ff1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sambritton/Fibrin_Network",
"max_stars_repo_path": "src/VectorMath.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2291,
"size": 8708
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "arcana/finally_scope.h"
#include "arcana/functional/inplace_function.h"
#include "arcana/utils/algorithm.h"
#include "sorted_vector.h"
#include <gsl/gsl>
#include <iterator>
#include <map>
#include <mutex>
#include <stdint.h>
namespace mira
{
/*
A collection that mimics a coat check. You insert something into it and it gives you a ticket.
Once you're done with the ticket, your item gets removed from the collection.
*/
template<typename T, typename MutexT = std::mutex>
class ticketed_collection
{
using seed_t = int64_t;
struct compare
{
bool operator()(const std::pair<seed_t, T>& left, const std::pair<seed_t, T>& right) const
{
return left.first < right.first;
}
bool operator()(const std::pair<seed_t, T>& left, const seed_t& right) const
{
return left.first < right;
}
};
using storage_t = sorted_vector<std::pair<seed_t, T>, compare>;
struct ticket_functor
{
ticket_functor(seed_t id, MutexT& mutex, storage_t& items)
: m_id{ id }
, m_mutex{ mutex }
, m_items{ items }
{}
void operator()()
{
std::lock_guard<MutexT> guard{ m_mutex };
auto found = m_items.find(
m_id, [](const std::pair<seed_t, T>& left, const seed_t& right) { return left.first == right; });
assert(found != m_items.end() && "ticketed item wasn't found in the collection");
m_items.erase(found);
}
seed_t m_id;
MutexT& m_mutex;
storage_t& m_items;
};
public:
struct iterator
{
using iter_t = typename storage_t::const_iterator;
using difference_type = typename std::iterator_traits<iter_t>::difference_type;
using value_type = T;
using pointer = const value_type*;
using reference = const value_type&;
using iterator_category = std::input_iterator_tag;
explicit iterator(const iter_t& itr)
: m_iter{ itr }
{}
bool operator==(const iterator& other) const
{
return m_iter == other.m_iter;
}
bool operator!=(const iterator& other) const
{
return !(*this == other);
}
iterator& operator++()
{
++m_iter;
return *this;
}
iterator operator++(int)
{
iterator pre{ *this };
++m_iter;
return pre;
}
const T* operator->() const
{
return &m_iter->second;
}
const T& operator*() const
{
return m_iter->second;
}
private:
typename storage_t::const_iterator m_iter;
};
using ticket = gsl::final_action<
stdext::inplace_function<void(), sizeof(ticket_functor), alignof(ticket_functor)>>;
using ticket_scope = finally_scope<ticket>;
ticketed_collection() = default;
ticketed_collection(const ticketed_collection&) = delete;
ticketed_collection& operator=(const ticketed_collection&) = delete;
iterator begin() const
{
return iterator{ m_items.cbegin() };
}
iterator end() const
{
return iterator{ m_items.cend() };
}
auto size() const
{
return m_items.size();
}
auto empty() const
{
return m_items.empty();
}
//
// Inserts an element into the collection and returns a ticket
// that will remove the item on its destruction. The mutex passed
// in should be already locked when calling this method. That same
// mutex will get locked when removing the item from the collection.
//
template<typename ElementT>
ticket insert(ElementT&& element, MutexT& mutex)
{
seed_t id = m_seed++;
m_items.insert(std::pair<seed_t, T>{ id, std::forward<ElementT>(element) });
return ticket{ ticket_functor(id, mutex, m_items) };
}
private:
seed_t m_seed = 0;
storage_t m_items;
};
}
| {
"alphanum_fraction": 0.5279931094,
"avg_line_length": 27.4792899408,
"ext": "h",
"hexsha": "6c073dce783132295ee2d8a77e1a060068bb0e52",
"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": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.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": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.h",
"max_line_length": 117,
"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": "Dependencies/Arcana/Shared/arcana/containers/ticketed_collection.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": 958,
"size": 4644
} |
#pragma once
#include "Library.h"
#include <gsl/span>
#include <cstdint>
#include <memory>
#include <optional>
#include <utility>
#include <variant>
#include <vector>
namespace CesiumGeometry {
namespace AvailabilityUtilities {
uint8_t countOnesInByte(uint8_t _byte);
uint32_t countOnesInBuffer(gsl::span<const std::byte> buffer);
} // namespace AvailabilityUtilities
struct CESIUMGEOMETRY_API ConstantAvailability {
bool constant;
};
struct CESIUMGEOMETRY_API SubtreeBufferView {
uint32_t byteOffset;
uint32_t byteLength;
uint8_t buffer;
};
typedef std::variant<ConstantAvailability, SubtreeBufferView> AvailabilityView;
struct CESIUMGEOMETRY_API AvailabilitySubtree {
AvailabilityView tileAvailability;
AvailabilityView contentAvailability;
AvailabilityView subtreeAvailability;
std::vector<std::vector<std::byte>> buffers;
};
/**
* @brief Availability nodes wrap subtree objects and link them together to
* form a downwardly traversable availability tree.
*/
struct CESIUMGEOMETRY_API AvailabilityNode {
/**
* @brief The subtree data for this node.
*
* If a node exists but its subtree does not exist, it indicates that the
* subtree is known to be available and is actively in the process of loading.
*/
std::optional<AvailabilitySubtree> subtree;
/**
* @brief The child nodes for this subtree node.
*/
std::vector<std::unique_ptr<AvailabilityNode>> childNodes;
/**
* @brief Creates an empty instance;
*/
AvailabilityNode() noexcept;
/**
* @brief Sets the loaded subtree for this availability node.
*
* @param subtree_ The loaded subtree to set for this node.
* @param maxChildrenSubtrees The maximum number of children this subtree
* could possible have if all of them happen to be available.
*/
void setLoadedSubtree(
AvailabilitySubtree&& subtree_,
uint32_t maxChildrenSubtrees) noexcept;
};
struct CESIUMGEOMETRY_API AvailabilityTree {
std::unique_ptr<AvailabilityNode> pRoot;
};
class CESIUMGEOMETRY_API AvailabilityAccessor {
public:
AvailabilityAccessor(
const AvailabilityView& view,
const AvailabilitySubtree& subtree) noexcept;
bool isBufferView() const noexcept {
return pBufferView != nullptr && bufferAccessor;
}
bool isConstant() const noexcept { return pConstant != nullptr; }
/**
* @brief Unsafe if isConstant is false.
*/
bool getConstant() const { return pConstant->constant; }
/**
* @brief Unsafe is isBufferView is false.
*/
const gsl::span<const std::byte>& getBufferAccessor() const {
return *bufferAccessor;
}
/**
* @brief Unsafe if isBufferView is false.
*/
const std::byte& operator[](size_t i) const {
return bufferAccessor.value()[i];
}
/**
* @brief Unsafe if isBufferView is false;
*/
size_t size() const { return pBufferView->byteLength; }
private:
const SubtreeBufferView* pBufferView;
const ConstantAvailability* pConstant;
std::optional<gsl::span<const std::byte>> bufferAccessor;
};
} // namespace CesiumGeometry
| {
"alphanum_fraction": 0.7303149606,
"avg_line_length": 25.1900826446,
"ext": "h",
"hexsha": "6c50591f99da15f876e886cf559141f9a60e1a2f",
"lang": "C",
"max_forks_count": 66,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T13:38:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-30T15:14:32.000Z",
"max_forks_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "yieryi/cesium-native",
"max_forks_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h",
"max_issues_count": 256,
"max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T23:44:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-30T18:12:28.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "yieryi/cesium-native",
"max_issues_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h",
"max_line_length": 80,
"max_stars_count": 154,
"max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "yieryi/cesium-native",
"max_stars_repo_path": "CesiumGeometry/include/CesiumGeometry/Availability.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T00:01:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-30T14:08:39.000Z",
"num_tokens": 708,
"size": 3048
} |
/*
** LISA single subject statistical inference using 1st level GLM (general linear modeling).
** The prewhitening approach is adapted from Worsley et al (2002), Neuroimage 15(1).
**
** G.Lohmann, MPI-KYB, 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
extern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);
extern void printmat(gsl_matrix *R,char *str);
extern void printvec(gsl_vector *x,char *str);
extern void prewhite(gsl_matrix_float** pinvX,gsl_matrix_float** invM,gsl_matrix_float* X,int);
extern void dfs(VFloat** Dfs,gsl_matrix_float* pinvX,gsl_matrix_float* X,gsl_matrix_float* con,int);
extern void whitecov(VImage rho_vol,gsl_matrix_float* Y,gsl_matrix_float* invM,
gsl_matrix_float* pinvX,gsl_matrix_float* X,int,int);
extern void whitecov2(VImage effect_image, VImage rho_vol,
gsl_matrix_float* Y, gsl_matrix_float* X, gsl_matrix_float* con,
VFloat* Dfs, int, int slice);
void CopySlice(gsl_matrix *Data,gsl_matrix_float *Y,VImage map,int slice)
{
size_t nvox;
size_t i=0,j=0;
double u=0;
int ncols = VPixel(map,0,3,2,VShort);
gsl_matrix_float_set_zero(Y);
for (nvox=0; nvox < Data->size1; nvox++) {
int b = VPixel(map,0,0,nvox,VShort);
if (b != slice) continue;
int r = VPixel(map,0,1,nvox,VShort);
int c = VPixel(map,0,2,nvox,VShort);
i = c + ncols*r;
if (i >= Y->size2) continue;
for (j=0; j<Data->size2; j++) {
u = gsl_matrix_get(Data,nvox,j);
gsl_matrix_float_set(Y,j,i,(float)u);
}
}
}
gsl_matrix_float *GslFloatCpy(gsl_matrix *X)
{
int i,j;
double u;
gsl_matrix_float *Z = gsl_matrix_float_calloc(X->size2,X->size1);
for (i=0; i<X->size1; i++) {
for (j=0; j<X->size2; j++) {
u = gsl_matrix_get(X,i,j);
gsl_matrix_float_set(Z,j,i,(float)u);
}
}
return Z;
}
/*
** general linear model (GLM) using whitening
*/
void VWhiteGLM(gsl_matrix *Data,VImage map,gsl_matrix *X0,gsl_vector *con,int numlags,VImage zmap)
{
int i,slice;
int numcon=1;
int nslices = VPixel(map,0,3,0,VShort);
int nrows = VPixel(map,0,3,1,VShort);
int ncols = VPixel(map,0,3,2,VShort);
int npix = (nrows*ncols);
int ntimesteps = Data->size2;
gsl_set_error_handler_off();
VFillImage(zmap,VAllBands,0);
/* contrast vector */
gsl_matrix_float *contrast = gsl_matrix_float_alloc(1,con->size);
for (i=0; i<con->size; i++) gsl_matrix_float_set(contrast,0,i,(float)con->data[i]);
/* copy design matrix */
gsl_matrix_float *X = GslFloatCpy(X0);
/* initialize rho_vol */
VImage rho_vol = VCreateImage(npix,nslices,numlags,VFloatRepn);
VFillImage(rho_vol,VAllBands,0);
/* prewhitening */
gsl_matrix_float *pinvX=NULL,*invM=NULL;
prewhite(&pinvX,&invM,X,numlags);
/* degrees of freedom */
VFloat *dfs_gsl = (VFloat *)VMalloc(sizeof(VFloat)* (numcon+1));
dfs(&dfs_gsl,pinvX,X,contrast,numlags);
/* first pass */
gsl_matrix_float *Y = gsl_matrix_float_calloc(ntimesteps,npix);
for (slice=0; slice<nslices; slice++) {
CopySlice(Data,Y,map,(int)slice);
whitecov(rho_vol,Y,invM,pinvX,X,numlags,slice);
}
/* second pass */
VImage dest = VCreateImage(nslices,nrows,ncols,VFloatRepn);
VFillImage(dest,VAllBands,0);
for (slice=0; slice<nslices; slice++) {
CopySlice(Data,Y,map,(int)slice);
whitecov2(dest,rho_vol,Y,X,contrast,dfs_gsl,numlags,slice);
}
/* output */
zmap = VCopyImagePixels(dest,zmap,VAllBands);
/* cleanup */
gsl_matrix_float_free(contrast);
gsl_matrix_float_free(X);
gsl_matrix_float_free(Y);
gsl_matrix_float_free(pinvX);
gsl_matrix_float_free(invM);
VFree(dfs_gsl);
VDestroyImage(rho_vol);
VDestroyImage(dest);
}
| {
"alphanum_fraction": 0.6911803193,
"avg_line_length": 26.1712328767,
"ext": "c",
"hexsha": "42b9b69df7addbda30925cc29f6f95401d750563",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_prewhitening/WhiteGLM.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_prewhitening/WhiteGLM.c",
"max_line_length": 100,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_prewhitening/WhiteGLM.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1223,
"size": 3821
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <math.h>
// #include <stdlib.h>
// #include <time.h>
double boxcar_overlap(double rA, double radiiA, double rB, double radiiB)
{
double F;
F = pow(rB - rA, 2) / pow(radiiA + radiiB, 2);
return F;
}
size_t gen_pts_rsa_1d(double *x,
size_t npoints, double radius, int step_limit,
unsigned long randSeed)
{
// Setup GSL random number generator
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
// Set the seed
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
// Set the initial position
double xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
x[0] = xn;
size_t valid_pts;
double F;
int k, flag, step;
step = 0;
valid_pts = 1;
while ((valid_pts < npoints) & (step < step_limit))
{
xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
flag = 1;
for (k = 0; k < valid_pts; k++)
{
F = boxcar_overlap(xn, radius, x[k], radius);
if (F < 1.0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[valid_pts] = xn;
valid_pts += 1;
}
step += 1;
}
gsl_rng_free (r);
return valid_pts;
}
unsigned int metro_md_1d(double *x,
double radius, size_t npoints, unsigned int step_limit,
unsigned long randSeed)
{
/* Setup GSL random number generator */
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* Set the seed */
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double diameter = 2 * radius;
double dx, xn, F;
unsigned int step, i, k, flag, success_steps;
step = 0;
success_steps = 0;
while (step < step_limit)
{
i = step % npoints;
/* Generate new position */
while (1)
{
dx = diameter * (gsl_rng_uniform (r) - 0.5);
xn = x[i] + dx;
if (((xn > radius) & (xn < 1 - radius)))
{
break;
}
}
/* Determine if new position overlaps with other positions */
flag = 1;
for (k = 0; k < npoints; k++)
{
F = boxcar_overlap(xn, radius, x[k], radius);
if ((F < 1.0) & (i != k))
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[i] = xn;
success_steps = success_steps + 1;
}
step = step + 1;
}
gsl_rng_free (r);
return success_steps;
}
unsigned int metro_pd_1d(double *x,
double *radius, size_t npoints, int step_limit,
unsigned long randSeed)
{
/* Setup GSL random number generator */
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* Set the seed */
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double dx, xn, diameter, F;
unsigned int step, i, k, flag, success_steps;
step = 0;
success_steps = 0;
while (step < step_limit)
{
i = step % npoints;
/* Generate new position */
while (1)
{
diameter = 2 * radius[i];
dx = diameter * (gsl_rng_uniform (r) - 0.5);
xn = x[i] + dx;
if (((xn > radius[i]) & (xn < 1 - radius[i])) )
{
break;
}
}
/* Determine if new position overlaps with other positions */
flag = 1;
for (k = 0; k < npoints; k++)
{
F = boxcar_overlap(xn, radius[i], x[k], radius[k]);
if ((F < 1.0) & (i != k))
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[i] = xn;
success_steps += 1;
}
step = step + 1;
}
gsl_rng_free (r);
return success_steps;
} | {
"alphanum_fraction": 0.4673426079,
"avg_line_length": 15.5919117647,
"ext": "c",
"hexsha": "d278d235120c7cb846d8124aaec3e3bfb2efe722",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aluchies/particle_packing",
"max_forks_repo_path": "particle_packing/cython/c/boxcar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "aluchies/particle_packing",
"max_issues_repo_path": "particle_packing/cython/c/boxcar.c",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "aluchies/particle_packing",
"max_stars_repo_path": "particle_packing/cython/c/boxcar.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1149,
"size": 4241
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_chebyshev.h>
double f(double x, void *p) {
(void) (p); /* avoid unused parameter warning */
return pow(0.5, pow(x, 2) + 2 * x);
}
int main(void) {
int i, j, n = 10000;
gsl_function F;
F.function = f;
F.params = 0;
gsl_cheb_series *cs = gsl_cheb_alloc(40);
FILE *file;
double *x = malloc(2 * n * sizeof(double));
double *w = malloc(2 * n * sizeof(double));
double *y = malloc(2 * n * sizeof(double));
for (i = -n, j = 0; i < n; i++, j++) {
double xf = i / (double) n;
x[j] = xf;
w[j] = 1;
y[j] = GSL_FN_EVAL (&F, xf);
}
double c0, c1, cov00, cov01, cov11, chisq;
gsl_fit_wlinear(x, 1, w, 1, y, 1, n,
&c0, &c1, &cov00, &cov01, &cov11,
&chisq);
gsl_cheb_init(cs, &F, -1.0, 1.0);
file = fopen("dalsze.dat", "w");
for (i = -n; i < n; i++) {
double xf = i / (double) n;
double yf, yf_err;
gsl_fit_linear_est(xf,
c0, c1,
cov00, cov01, cov11,
&yf, &yf_err);
double r10 = gsl_cheb_eval_n(cs, 10, xf);
double r40 = gsl_cheb_eval(cs, xf);
fprintf(file, "%g %g %g %g %g\n",
xf, GSL_FN_EVAL (&F, xf), yf, r10, r40);
}
free(x);
free(y);
free(w);
gsl_cheb_free(cs);
fclose(file);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.4864686469,
"avg_line_length": 28.5849056604,
"ext": "c",
"hexsha": "0f1af8ec2fbf222a60707e54d32d050d75da14c5",
"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": "d88c21308b863942497c111d044e359ce220d421",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mistyfiky/agh-mownit",
"max_forks_repo_path": "lab3/dalsze.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421",
"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": "mistyfiky/agh-mownit",
"max_issues_repo_path": "lab3/dalsze.c",
"max_line_length": 56,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mistyfiky/agh-mownit",
"max_stars_repo_path": "lab3/dalsze.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 514,
"size": 1515
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#ifdef SUBFIND
#include "subfind.h"
/*! Structure for communication during the density computation. Holds data that is sent to other processors.
*/
static struct nearestdata_in
{
MyDouble Pos[3];
MyIDType ID;
MyFloat Hsml;
MyFloat Density;
MyFloat Dist[2];
int Count;
long long Index[2];
int NodeList[NODELISTLENGTH];
}
*NearestDataIn, *NearestDataGet;
static struct nearestdata_out
{
MyFloat Dist[2];
long long Index[2];
int Count;
}
*NearestDataResult, *NearestDataOut;
void subfind_find_nearesttwo(void)
{
int i, j, k, l, ndone, ndone_flag, dummy;
int ngrp, sendTask, recvTask, place, nexport, nimport, maxexport;
if(ThisTask == 0)
printf("Start finding nearest two (%d particles on task=%d)\n", NumPartGroup, ThisTask);
/* allocate buffers to arrange communication */
Ngblist = (int *) mymalloc(NumPartGroup * sizeof(int));
Dist2list = (double *) mymalloc(NumPartGroup * sizeof(double));
All.BunchSize =
(int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +
sizeof(struct nearestdata_in) + sizeof(struct nearestdata_out) +
sizemax(sizeof(struct nearestdata_in),
sizeof(struct nearestdata_out))));
DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));
DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));
maxexport = All.BunchSize - 2 * NTopleaves / NODELISTLENGTH;
for(i = 0; i < NumPartGroup; i++)
NgbLoc[i].count = 0;
/* we will repeat the whole thing for those particles where we didn't find enough neighbours */
i = 0; /* begin with this index */
do
{
for(j = 0; j < NTask; j++)
{
Send_count[j] = 0;
Exportflag[j] = -1;
}
/* do local particles and prepare export list */
for(nexport = 0; i < NumPartGroup; i++)
{
if(subfind_nearesttwo_evaluate(i, 0, &nexport, Send_count) < 0)
break;
}
qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);
MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);
for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)
{
Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];
nimport += Recv_count[j];
if(j > 0)
{
Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];
Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];
}
}
NearestDataGet = (struct nearestdata_in *) mymalloc(nimport * sizeof(struct nearestdata_in));
NearestDataIn = (struct nearestdata_in *) mymalloc(nexport * sizeof(struct nearestdata_in));
/* prepare particle data for export */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
NearestDataIn[j].Pos[0] = P[place].Pos[0];
NearestDataIn[j].Pos[1] = P[place].Pos[1];
NearestDataIn[j].Pos[2] = P[place].Pos[2];
NearestDataIn[j].Hsml = P[place].DM_Hsml;
NearestDataIn[j].ID = P[place].ID;
NearestDataIn[j].Density = P[place].u.DM_Density;
NearestDataIn[j].Count = NgbLoc[place].count;
for(k = 0; k < NgbLoc[place].count; k++)
{
NearestDataIn[j].Dist[k] = R2Loc[place].dist[k];
NearestDataIn[j].Index[k] = NgbLoc[place].index[k];
}
memcpy(NearestDataIn[j].NodeList,
DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));
}
/* exchange particle data */
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&NearestDataIn[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct nearestdata_in), MPI_BYTE,
recvTask, TAG_DENS_A,
&NearestDataGet[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct nearestdata_in), MPI_BYTE,
recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
myfree(NearestDataIn);
NearestDataResult = (struct nearestdata_out *) mymalloc(nimport * sizeof(struct nearestdata_out));
NearestDataOut = (struct nearestdata_out *) mymalloc(nexport * sizeof(struct nearestdata_out));
/* now do the particles that were sent to us */
for(j = 0; j < nimport; j++)
subfind_nearesttwo_evaluate(j, 1, &dummy, &dummy);
if(i >= NumPartGroup)
ndone_flag = 1;
else
ndone_flag = 0;
MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
/* get the result */
for(ngrp = 1; ngrp < (1 << PTask); ngrp++)
{
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)
{
/* send the results */
MPI_Sendrecv(&NearestDataResult[Recv_offset[recvTask]],
Recv_count[recvTask] * sizeof(struct nearestdata_out),
MPI_BYTE, recvTask, TAG_DENS_B,
&NearestDataOut[Send_offset[recvTask]],
Send_count[recvTask] * sizeof(struct nearestdata_out),
MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
}
}
/* add the result to the local particles */
for(j = 0; j < nexport; j++)
{
place = DataIndexTable[j].Index;
for(k = 0; k < NearestDataOut[j].Count; k++)
{
if(NgbLoc[place].count >= 1)
if(NgbLoc[place].index[0] == NearestDataOut[j].Index[k])
continue;
if(NgbLoc[place].count == 2)
if(NgbLoc[place].index[1] == NearestDataOut[j].Index[k])
continue;
if(NgbLoc[place].count < 2)
{
l = NgbLoc[place].count;
NgbLoc[place].count++;
}
else
{
if(R2Loc[place].dist[0] > R2Loc[place].dist[1])
l = 0;
else
l = 1;
if(NearestDataOut[j].Dist[k] >= R2Loc[place].dist[l])
continue;
}
R2Loc[place].dist[l] = NearestDataOut[j].Dist[k];
NgbLoc[place].index[l] = NearestDataOut[j].Index[k];
if(NgbLoc[place].count == 2)
if(NgbLoc[place].index[0] == NgbLoc[place].index[1])
{
/*
printf("taaa=%d i=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, place,
NgbLoc[place].task[0], NgbLoc[place].index[0],
NgbLoc[place].task[1], NgbLoc[place].index[1]);
printf
("NearestDataOut[j].Count=%d l=%d k=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
NearestDataOut[j].Count, l, k, NearestDataOut[j].Task[0], NearestDataOut[j].Index[0],
NearestDataOut[j].Task[1], NearestDataOut[j].Index[1]);
*/
endrun(112);
}
}
}
myfree(NearestDataOut);
myfree(NearestDataResult);
myfree(NearestDataGet);
}
while(ndone < NTask);
myfree(DataNodeList);
myfree(DataIndexTable);
myfree(Dist2list);
myfree(Ngblist);
}
/*! This function represents the core of the SPH density computation. The
* target particle may either be local, or reside in the communication
* buffer.
*/
int subfind_nearesttwo_evaluate(int target, int mode, int *nexport, int *nsend_local)
{
int j, k, n, count;
MyIDType ID;
long long index[2];
double dist[2];
int startnode, numngb, numngb_inbox, listindex = 0;
double hmax;
double h, h2, hinv, hinv3;
double r2, density;
MyDouble *pos;
numngb = 0;
if(mode == 0)
{
ID = P[target].ID;
density = P[target].u.DM_Density;
pos = P[target].Pos;
h = P[target].DM_Hsml;
count = NgbLoc[target].count;
for(k = 0; k < count; k++)
{
dist[k] = R2Loc[target].dist[k];
index[k] = NgbLoc[target].index[k];
}
}
else
{
ID = NearestDataGet[target].ID;
density = NearestDataGet[target].Density;
pos = NearestDataGet[target].Pos;
h = NearestDataGet[target].Hsml;
count = NearestDataGet[target].Count;
for(k = 0; k < count; k++)
{
dist[k] = NearestDataGet[target].Dist[k];
index[k] = NearestDataGet[target].Index[k];
}
}
h2 = h * h;
hinv = 1.0 / h;
hinv3 = hinv * hinv * hinv;
if(mode == 0)
{
startnode = All.MaxPart; /* root node */
}
else
{
startnode = NearestDataGet[target].NodeList[0];
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
numngb = 0;
if(count == 2)
if(index[0] == index[1])
{
/* printf("T-A-S-K=%d target=%d mode=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target, mode, task[0], index[0], task[1], index[1]);
*/
endrun(1232);
}
while(startnode >= 0)
{
while(startnode >= 0)
{
numngb_inbox =
subfind_ngb_treefind_nearesttwo(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);
if(numngb_inbox < 0)
return -1;
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
r2 = Dist2list[n];
if(P[j].ID != ID) /* exclude the self-particle */
{
if(P[j].u.DM_Density > density) /* we only look at neighbours that are denser */
{
if(count < 2)
{
dist[count] = r2;
index[count] = (((long long) ThisTask) << 32) + j;
count++;
}
else
{
if(dist[0] > dist[1])
k = 0;
else
k = 1;
if(r2 < dist[k])
{
dist[k] = r2;
index[k] = (((long long) ThisTask) << 32) + j;
}
}
}
numngb++;
}
}
}
if(mode == 1)
{
listindex++;
if(listindex < NODELISTLENGTH)
{
startnode = NearestDataGet[target].NodeList[listindex];
if(startnode >= 0)
startnode = Nodes[startnode].u.d.nextnode; /* open it */
}
}
}
if(mode == 0)
{
NgbLoc[target].count = count;
for(k = 0; k < count; k++)
{
R2Loc[target].dist[k] = dist[k];
NgbLoc[target].index[k] = index[k];
}
if(count == 2)
if(NgbLoc[target].index[0] == NgbLoc[target].index[1])
{
/*
printf("TASK=%d target=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target,
NgbLoc[target].task[0], NgbLoc[target].index[0],
NgbLoc[target].task[1], NgbLoc[target].index[1]);
*/
endrun(2);
}
}
else
{
NearestDataResult[target].Count = count;
for(k = 0; k < count; k++)
{
NearestDataResult[target].Dist[k] = dist[k];
NearestDataResult[target].Index[k] = index[k];
}
if(count == 2)
if(NearestDataResult[target].Index[0] == NearestDataResult[target].Index[1])
{
/*
printf("TASK!!=%d target=%d task_0=%d index_0=%d task_1=%d index_1=%d\n",
ThisTask, target,
NearestDataResult[target].Task[0], NearestDataResult[target].Index[0],
NearestDataResult[target].Task[1], NearestDataResult[target].Index[1]);
*/
endrun(22);
}
}
return 0;
}
int subfind_ngb_treefind_nearesttwo(MyDouble searchcenter[3], double hsml, int target, int *startnode,
int mode, double *hmax, int *nexport, int *nsend_local)
{
int numngb, no, p, task, nexport_save, exported = 0;
struct NODE *current;
double dx, dy, dz, dist, r2;
#ifdef PERIODIC
double xtmp;
#endif
nexport_save = *nexport;
*hmax = 0;
numngb = 0;
no = *startnode;
while(no >= 0)
{
if(no < All.MaxPart) /* single particle */
{
p = no;
no = Nextnode[no];
#ifdef DENSITY_SPLIT_BY_TYPE
if(!((1 << P[p].Type) & (DENSITY_SPLIT_BY_TYPE)))
continue;
#else
if(!((1 << P[p].Type) & (FOF_PRIMARY_LINK_TYPES)))
continue;
#endif
dist = hsml;
dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);
if(dx > dist)
continue;
dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);
if(dy > dist)
continue;
dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);
if(dz > dist)
continue;
if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)
continue;
Dist2list[numngb] = r2;
Ngblist[numngb++] = p;
}
else
{
if(no >= All.MaxPart + MaxNodes) /* pseudo particle */
{
if(mode == 1)
endrun(12312);
if(target >= 0) /* if no target is given, export will not occur */
{
exported = 1;
if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)
{
Exportflag[task] = target;
Exportnodecount[task] = NODELISTLENGTH;
}
if(Exportnodecount[task] == NODELISTLENGTH)
{
if(*nexport >= All.BunchSize)
{
*nexport = nexport_save;
if(nexport_save == 0)
endrun(13004); /* in this case, the buffer is too small to process even a single particle */
for(task = 0; task < NTask; task++)
nsend_local[task] = 0;
for(no = 0; no < nexport_save; no++)
nsend_local[DataIndexTable[no].Task]++;
return -1;
}
Exportnodecount[task] = 0;
Exportindex[task] = *nexport;
DataIndexTable[*nexport].Task = task;
DataIndexTable[*nexport].Index = target;
DataIndexTable[*nexport].IndexGet = *nexport;
*nexport = *nexport + 1;
nsend_local[task]++;
}
DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =
DomainNodeIndex[no - (All.MaxPart + MaxNodes)];
if(Exportnodecount[task] < NODELISTLENGTH)
DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;
}
no = Nextnode[no - MaxNodes];
continue;
}
current = &Nodes[no];
if(mode == 1)
{
if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */
{
*startnode = -1;
return numngb;
}
}
no = current->u.d.sibling; /* in case the node can be discarded */
dist = hsml + 0.5 * current->len;;
dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);
if(dx > dist)
continue;
dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);
if(dy > dist)
continue;
dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);
if(dz > dist)
continue;
/* now test against the minimal sphere enclosing everything */
dist += FACT1 * current->len;
if(dx * dx + dy * dy + dz * dz > dist * dist)
continue;
no = current->u.d.nextnode; /* ok, we need to open the node */
}
}
*startnode = -1;
return numngb;
}
#endif
| {
"alphanum_fraction": 0.6023048789,
"avg_line_length": 25.2456445993,
"ext": "c",
"hexsha": "30e3d93a249411336e36abc4910591d4023e5ab7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_nearesttwo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_nearesttwo.c",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_nearesttwo.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4563,
"size": 14491
} |
/* specfunc/beta_inc.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_gamma.h>
#include "error.h"
#include "check.h"
static
int
beta_cont_frac(
const double a,
const double b,
const double x,
gsl_sf_result * result
)
{
const unsigned int max_iter = 512; /* control iterations */
const double cutoff = 2.0 * GSL_DBL_MIN; /* control the zero cutoff */
unsigned int iter_count = 0;
double cf;
/* standard initialization for continued fraction */
double num_term = 1.0;
double den_term = 1.0 - (a+b)*x/(a+1.0);
if (fabs(den_term) < cutoff) den_term = cutoff;
den_term = 1.0/den_term;
cf = den_term;
while(iter_count < max_iter) {
const int k = iter_count + 1;
double coeff = k*(b-k)*x/(((a-1.0)+2*k)*(a+2*k));
double delta_frac;
/* first step */
den_term = 1.0 + coeff*den_term;
num_term = 1.0 + coeff/num_term;
if(fabs(den_term) < cutoff) den_term = cutoff;
if(fabs(num_term) < cutoff) num_term = cutoff;
den_term = 1.0/den_term;
delta_frac = den_term * num_term;
cf *= delta_frac;
coeff = -(a+k)*(a+b+k)*x/((a+2*k)*(a+2*k+1.0));
/* second step */
den_term = 1.0 + coeff*den_term;
num_term = 1.0 + coeff/num_term;
if(fabs(den_term) < cutoff) den_term = cutoff;
if(fabs(num_term) < cutoff) num_term = cutoff;
den_term = 1.0/den_term;
delta_frac = den_term*num_term;
cf *= delta_frac;
if(fabs(delta_frac-1.0) < 2.0*GSL_DBL_EPSILON) break;
++iter_count;
}
result->val = cf;
result->err = iter_count * 4.0 * GSL_DBL_EPSILON * fabs(cf);
if(iter_count >= max_iter)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_beta_inc_e(
const double a,
const double b,
const double x,
gsl_sf_result * result
)
{
if(a <= 0.0 || b <= 0.0 || x < 0.0 || x > 1.0) {
DOMAIN_ERROR(result);
}
else if(x == 0.0) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(x == 1.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
gsl_sf_result ln_beta;
gsl_sf_result ln_x;
gsl_sf_result ln_1mx;
gsl_sf_result prefactor;
const int stat_ln_beta = gsl_sf_lnbeta_e(a, b, &ln_beta);
const int stat_ln_1mx = gsl_sf_log_1plusx_e(-x, &ln_1mx);
const int stat_ln_x = gsl_sf_log_e(x, &ln_x);
const int stat_ln = GSL_ERROR_SELECT_3(stat_ln_beta, stat_ln_1mx, stat_ln_x);
const double ln_pre_val = -ln_beta.val + a * ln_x.val + b * ln_1mx.val;
const double ln_pre_err = ln_beta.err + fabs(a*ln_x.err) + fabs(b*ln_1mx.err);
const int stat_exp = gsl_sf_exp_err_e(ln_pre_val, ln_pre_err, &prefactor);
if(stat_ln != GSL_SUCCESS) {
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_ESANITY);
}
if(x < (a + 1.0)/(a+b+2.0)) {
/* Apply continued fraction directly. */
gsl_sf_result cf;
const int stat_cf = beta_cont_frac(a, b, x, &cf);
int stat;
result->val = prefactor.val * cf.val / a;
result->err = (fabs(prefactor.err * cf.val) + fabs(prefactor.val * cf.err))/a;
stat = GSL_ERROR_SELECT_2(stat_exp, stat_cf);
if(stat == GSL_SUCCESS) {
CHECK_UNDERFLOW(result);
}
return stat;
}
else {
/* Apply continued fraction after hypergeometric transformation. */
gsl_sf_result cf;
const int stat_cf = beta_cont_frac(b, a, 1.0-x, &cf);
int stat;
const double term = prefactor.val * cf.val / b;
result->val = 1.0 - term;
result->err = fabs(prefactor.err * cf.val)/b;
result->err += fabs(prefactor.val * cf.err)/b;
result->err += 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(term));
stat = GSL_ERROR_SELECT_2(stat_exp, stat_cf);
if(stat == GSL_SUCCESS) {
CHECK_UNDERFLOW(result);
}
return stat;
}
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_beta_inc(const double a, const double b, const double x)
{
EVAL_RESULT(gsl_sf_beta_inc_e(a, b, x, &result));
}
| {
"alphanum_fraction": 0.6289974495,
"avg_line_length": 28.1602209945,
"ext": "c",
"hexsha": "bd840b61083fdc533e6f12e75ac645d7086751dc",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/beta_inc.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/beta_inc.c",
"max_line_length": 84,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/beta_inc.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": 1570,
"size": 5097
} |
-----------natrix mul---
/*
* standard includes
*/
#include <stdio.h>
#include <stdlib.h>
/*
* includes for GSL components
* - use double precision
*/
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/*
* FUNCTIONS
*/
/*
* simple Fibonacci sequence generator function, using recursion
*/
size_t fib(size_t k)
{
if (k==0)
{
return 0;
}
else if (k==1)
{
return 1;
}
else /* k >= 2 */
{
return fib(k-1) + fib(k-2);
}
}
gsl_matrix *embt_mm(const gsl_matrix *U,const gsl_matrix *V, size_t N)
{
gsl_matrix *W=gsl_matrix_calloc(N,N);
double sum=0;
for (size_t i=0;i!=N;i++)
{
for(size_t j=0;j!=N;j++)
{
for (size_t k=0;k!=N;k++)
{
sum=sum+gsl_matrix_get(U,i,k)*gsl_matrix_get(V,k,j);
}
gsl_matrix_set(W,i,j,(double)sum);
sum=0;
}
}
return W;
}
gsl_matrix *embt_apb(gsl_vector *u, gsl_vector *v,size_t N)
{
gsl_vector *w=gsl_vector_calloc(N);
gsl_vector_add(w,u);
gsl_vector_add(w,v);
return w;
}
gsl_matrix *embt_m_print(const gsl_matrix *U, size_t N)
{
for (size_t i = 0; i != N; ++i)
{
for (size_t j=0;j!=N;j++)
{
printf("%0.2f\t",gsl_matrix_get(U, i, j));
}
printf("\n");
}
}
gsl_matrix *embt_v_print(const gsl_vector *u, size_t N)
{
for (int i = 0; i != N; ++i)
{
printf("%0.2f\n",gsl_vector_get(u, i));
}
}
int main()
{
/*
* INITIALIZE PARAMETERS
*/
/* vectors parameters */
size_t N=3; /* index type, vector sizes */
gsl_vector *a = gsl_vector_alloc(N); /* allocate vector from heap of size N */
gsl_vector *b = gsl_vector_alloc(N); /* allocate vector from heap of size N */
gsl_vector *c = gsl_vector_calloc(N); /* allocate vector of size N but initialize entries to zero */
/* random number generator parameters */
const gsl_rng_type *T;
gsl_rng *r; /* handle for our random number generator */
/* matrix parameters */
gsl_matrix *A = gsl_matrix_alloc(N,N);
gsl_matrix *B = gsl_matrix_alloc(N,N);
gsl_matrix *C = gsl_matrix_calloc(N,N);
/*
* SET UP RANDOM NUMBER GENERATION
*/
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
/*
* VECTOR OPERATIONS
*/
/* set the vector elements */
for (size_t i = 0; i != N; ++i)
{
gsl_vector_set(a, i, fib(i)); /* set element i of vector a to Fibonacci number i */
gsl_vector_set(b, i, gsl_ran_flat(r,-1.0,+1.0)); /* set element of vector b to random number */
}
/* c = a + b */
c=embt_apb(a,b,N); /* c += a */
//gsl_vector_add(c, b); /* c += b */
/* print results */
int sum=0;
/* MATRIX OPERATIONS */
for (size_t i=0;i!=N;i++)
for (size_t j=0;j!=N;j++)
{
//size_t x=j+(i*N);
gsl_matrix_set(A,i,j,(double)fib(j+i*N));
gsl_matrix_set(B,i,j,gsl_ran_flat(r,-100,+100));
}
//gsl_matrix_mul_elements(C, A); /* c += a */
//gsl_matrix_mul_elements(C, B); /* c += b */
C=embt_mm(A,B,N);
printf("a= \n");embt_v_print(a,N);
printf("b= \n");embt_v_print(b,N);
printf("c= \n");embt_v_print(c,N);
printf("A= \n");embt_m_print(A,N);
printf("B= \n");embt_m_print(B,N);
printf("C= \n");embt_m_print(C,N);
/* de-allocate memory */
gsl_vector_free(a);
gsl_vector_free(b);
gsl_vector_free(c);
gsl_matrix_free(A);
gsl_matrix_free(B);
gsl_matrix_free(C);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6175491679,
"avg_line_length": 21.3225806452,
"ext": "c",
"hexsha": "741a56ec446d6cd9e08a27c5db67143ae09a5204",
"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": "febf81fbda55d38a587335057dd561fc486f5103",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gov466/Embedded-C",
"max_forks_repo_path": "C program/matric_mul_gsl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103",
"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": "gov466/Embedded-C",
"max_issues_repo_path": "C program/matric_mul_gsl.c",
"max_line_length": 102,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gov466/Embedded-C",
"max_stars_repo_path": "C program/matric_mul_gsl.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-02T15:42:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-02T15:42:58.000Z",
"num_tokens": 1125,
"size": 3305
} |
/* Calling DGELS using row-major order */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include <string.h>
#include "magneticTrap.h"
//#include <sys/stat.h>
#define SIZE 3
//Function to calculate beta. The speed is then v=beta*c
double calculateBeta(double T) {
double eMass = 9.10938356e-31;
double c = 299792458.0;
double factor = pow(T,2.0)/(pow(eMass,2.0)*pow(c,4.0)) + (2.0*T)/(eMass*pow(c,2.0)) + 1;
double beta = sqrt(1.0 - 1.0/factor);
return beta;
}
int main (int argc, const char * argv[]) {
int i, j;
//FILE *inputFile = fopen("simParms.dat","r");
//for(int kk=0; kk<10; kk++){
//}
//
double lambda,lambda0,Bx,By,Bz,q,dt,posX,posY,posZ;
double kinE, mass,gamma,c,Ux,Uy,Uz,magV,magVComputed;
double dirCosX, dirCosY, dirCosZ, rotationR, solenoidWidth;
double coilRadius, current, mu, coilPosZMin1, coilPosZMax1, coilPosZMin2, coilPosZMax2;
double Z_coil1_, Z_coil2_ ;
int nTsteps, nCoils;
//double vecRHS[SIZE] = {0.0, 0.0, 0.0};
//double Bfield[SIZE] = {0.0, 0.0, 0.0 };
//double Bcgrnd[SIZE] = {0.0, 0.0, 1.0 };
double *vecRHS, *Bfield, *background;
vecRHS = (double*)malloc(SIZE*sizeof(double));
Bfield = (double*)malloc(SIZE*sizeof(double));
background = (double*)malloc(SIZE*sizeof(double));
background[0] = 0.0; background[1] = 0.0; background[2] = 1.0;
lapack_int info,nRowsA,nColsB,nColsARowsB,ldA,ldB,ipvt[SIZE*SIZE];
dt= 5.0e-12;
nTsteps = 2.5e6;
q = 1.602176634e-19;
c = 299792458.0;
mass = 9.10938356e-31;
kinE = 18575.0*q;
rotationR = 4.6375e-4;
solenoidWidth = 0.2;
coilRadius = 0.05;
current = 20.0;
nCoils = 11;
mu = 1.25663706e-6;
Z_coil1_ = -0.5;
Z_coil2_ = 0.5;
coilPosZMin1 = Z_coil1_ - solenoidWidth/2.0;
coilPosZMax1 = Z_coil1_ + solenoidWidth/2.0;
coilPosZMin2 = Z_coil2_ - solenoidWidth/2.0;
coilPosZMax2 = Z_coil2_ + solenoidWidth/2.0;
posX=rotationR;posY=0.0;posZ=0.0;
bathTubFieldSolenoids(coilRadius, current, coilPosZMin1, coilPosZMax1, coilPosZMin2, coilPosZMax2, nCoils,
mu, posX, posY, posZ, background, Bfield);
Bx = Bfield[0]; By = Bfield[1]; Bz = Bfield[2];
//-----------
magV = calculateBeta(kinE)*c;
double pitchAngle = 85.0 * M_PI/180.0;
dirCosX = 0.0; dirCosZ=cos(pitchAngle); dirCosY=1.0-dirCosZ;
Ux = magV*dirCosX; Uy=magV*dirCosY; Uz=magV*dirCosZ;
//double ufuture[SIZE] = {0.0, 0.0, 0.0};
//double upast[SIZE] = {Ux, Uy, Uz};
double *ufuture, *upast;
ufuture = (double*)malloc(SIZE*sizeof(double));
upast = (double*)malloc(SIZE*sizeof(double));
upast[0] = Ux; upast[1] = Uy; upast[2] = Uz;
printf("# Starting simulation with U(x), U(y), U(z) = %8.5e , %8.5e , %8.5e \n", Ux, Uy, Uz);
gamma = 1.0/(sqrt(1.0-(pow(magV,2.0))/(pow(c,2.0))));
lambda0= (0.5*q*dt)/(2.0*mass*gamma); // Careful: this definition is only for the first time step
lambda = (1.0*q*dt)/(2.0*mass*gamma); // Careful: this definition is only for the first time step
//writing a and b as vectors, but they are in concept the matrices of the system of linear equations
//double a[SIZE*SIZE] = { 1.0, lambda0*Bz,-lambda0*By , -lambda0*Bz,1.0, lambda0*Bx , lambda0*By,-lambda0*Bx,1.0 };
//double b[SIZE*SIZE] = { 1.0,-lambda0*Bz, lambda0*By , lambda0*Bz,1.0,-lambda0*Bx , -lambda0*By, lambda0*Bx,1.0 };
double *a, *b;
a = (double*)malloc(SIZE*SIZE*sizeof(double));
b = (double*)malloc(SIZE*SIZE*sizeof(double));
a[0] = 1.0; a[1] = lambda0*Bz; a[2] = -lambda0*By;
a[3] = -lambda0*Bz; a[4] = 1.0; a[5] = lambda0*Bx;
a[6] = lambda0*By; a[7] = -lambda0*Bx; a[8] = 1.0;
b[0] = 1.0; b[1] = -lambda0*Bz; b[2] = lambda0*By;
b[3] = lambda0*Bz; b[4] = 1.0; b[5] = -lambda0*Bx;
b[6] = -lambda0*By; b[7] = lambda0*Bx; b[8] = 1.0;
nRowsA = SIZE;
nColsB = 1;
nColsARowsB = SIZE;
ldA = nRowsA;
ldB = nColsARowsB;
// Printing LHS matrix
/*printf("#LHS Matrix (Traspose -> Column major order -----------\t | \n");
for(i=0;i<SIZE;i++)
{
printf("#| \t");
for(j=0;j<SIZE;j++)
{
printf("%.5e \t",a[i*SIZE + j]);
}
printf("\t | \n");
}
printf("#------------------------------------------------------\n");
printf("#RHS Matrix (Traspose -> Column major order -----------\t | \n");
for(i=0;i<SIZE;i++)
{
printf("#| \t");
for(j=0;j<SIZE;j++)
{
printf("%.5e \t",b[i*SIZE + j]);
}
printf("\t | \n");
}
printf("#----------------------------------------------------------\n");
printf("# Time | Ux \t | Uy \t | Uz \t | magV \t | PosX \t | PosY \t | PosZ \t |\n");
*/
double timeVal = 0.0;
for (int tt = 0; tt < nTsteps; tt++) {
timeVal = (double)tt * dt;
//using header variables from LAPACK and openblas
cblas_dgemm(CblasColMajor,CblasNoTrans,CblasNoTrans,
nRowsA,nColsB,nColsARowsB,1.0,b,ldA,upast,ldB,0.0,vecRHS,nRowsA);
for (i=0; i<SIZE; i++){ufuture[i] = vecRHS[i];}; // This is because dgesv rewrites ufuture
info = LAPACKE_dgesv(LAPACK_COL_MAJOR, SIZE, 1, a, ldA, ipvt, ufuture, ldA);
for (i=0; i<SIZE; i++){upast[i] = ufuture[i];};
Ux = ufuture[0];
Uy = ufuture[1];
Uz = ufuture[2];
magVComputed = sqrt(pow(Ux,2.0)+pow(Uy,2.0)+pow(Uz,2.0));
magV = magVComputed;
gamma = 1.0/(sqrt(1.0-(pow(magV,2.0))/(pow(c,2.0))));
lambda = (q*dt)/(2.0*mass*gamma);
bathTubFieldSolenoids(coilRadius, current, coilPosZMin1, coilPosZMax1,
coilPosZMin2, coilPosZMax2, nCoils, mu, posX, posY, posZ, background, Bfield);
Bx = Bfield[0]; By = Bfield[1]; Bz = Bfield[2];
a[0] = 1.0; a[1] = lambda*Bz; a[2] = -lambda*By;
a[3] = -lambda*Bz; a[4] = 1.0; a[5] = lambda*Bx;
a[6] = lambda*By; a[7] = -lambda*Bx; a[8] = 1.0;
b[0] = 1.0; b[1] = -lambda*Bz; b[2] = lambda*By;
b[3] = lambda*Bz; b[4] = 1.0; b[5] = -lambda*Bx;
b[6] = -lambda*By; b[7] = lambda*Bx; b[8] = 1.0;
// -----------
posX = posX + dt*Ux;
posY = posY + dt*Uy;
posZ = posZ + dt*Uz;
if ( tt%1 == 0 ) { //This alters the number of points written to the text file
printf(" %7.4e \t %8.5e \t %8.5e \t %8.5e \t %8.5e \t %8.5e \t %8.5e \n ",
timeVal, posX, posY, posZ, ufuture[0], ufuture[1], ufuture[2]);
}
}
//free(a); free(b);
free(ufuture); free(upast);
free(vecRHS); free(Bfield); free(background);
info = 0;
return(info);
}
| {
"alphanum_fraction": 0.5394775036,
"avg_line_length": 39.3714285714,
"ext": "c",
"hexsha": "3b25bc3322d54b2fe8f91f525220a6ca799ff625",
"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": "2560861d1a978b1feb743729fa2b4fa8a67b2c77",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "josephDuque/FinalYearProjectQTNM_u1803982",
"max_forks_repo_path": "2_Trajectories/motionWLorentzForce/motionWLorentzForce.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2560861d1a978b1feb743729fa2b4fa8a67b2c77",
"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": "josephDuque/FinalYearProjectQTNM_u1803982",
"max_issues_repo_path": "2_Trajectories/motionWLorentzForce/motionWLorentzForce.c",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2560861d1a978b1feb743729fa2b4fa8a67b2c77",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "josephDuque/FinalYearProjectQTNM_u1803982",
"max_stars_repo_path": "2_Trajectories/motionWLorentzForce/motionWLorentzForce.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2660,
"size": 6890
} |
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include "allvars.h"
#include "proto.h"
#define WORKSIZE 100000
static double R8;
static double r_tophat;
static double AA, BB, CC;
static double nu;
static double Norm;
static int NPowerTable;
static struct pow_table
{
double logk, logD;
}
*PowerTable;
double PowerSpec(double k)
{
double power = 0;
switch (WhichSpectrum)
{
case 1:
power = PowerSpec_EH(k);
break;
case 2:
power = PowerSpec_Tabulated(k);
break;
default:
power = PowerSpec_Efstathiou(k);
break;
}
power *= pow(k, PrimordialIndex - 1.0);
return power;
}
void read_power_table(void)
{
FILE *fd;
char buf[500];
double k, p;
sprintf(buf, FileWithInputSpectrum);
if(!(fd = fopen(buf, "r")))
{
printf("can't read input spectrum in file '%s' on task %d\n", buf, ThisTask);
FatalError(17);
}
NPowerTable = 0;
do
{
if(fscanf(fd, " %lg %lg ", &k, &p) == 2)
NPowerTable++;
else
break;
}
while(1);
fclose(fd);
if(ThisTask == 0)
{
printf("found %d rows in input spectrum table\n", NPowerTable);
fflush(stdout);
}
PowerTable = malloc(NPowerTable * sizeof(struct pow_table));
sprintf(buf, FileWithInputSpectrum);
if(!(fd = fopen(buf, "r")))
{
printf("can't read input spectrum in file '%s' on task %d\n", buf, ThisTask);
FatalError(18);
}
NPowerTable = 0;
do
{
double p;
if(fscanf(fd, " %lg %lg ", &k, &p) == 2)
{
PowerTable[NPowerTable].logk = k;
PowerTable[NPowerTable].logD = p;
NPowerTable++;
}
else
break;
}
while(1);
fclose(fd);
qsort(PowerTable, NPowerTable, sizeof(struct pow_table), compare_logk);
}
int compare_logk(const void *a, const void *b)
{
if(((struct pow_table *) a)->logk < (((struct pow_table *) b)->logk))
return -1;
if(((struct pow_table *) a)->logk > (((struct pow_table *) b)->logk))
return +1;
return 0;
}
void initialize_powerspectrum(void)
{
double res;
InitTime = 1 / (1 + Redshift);
AA = 6.4 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);
BB = 3.0 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);
CC = 1.7 / ShapeGamma * (3.085678e24 / UnitLength_in_cm);
nu = 1.13;
R8 = 8 * (3.085678e24 / UnitLength_in_cm); /* 8 Mpc/h */
if(WhichSpectrum == 2)
read_power_table();
if(ReNormalizeInputSpectrum == 0 && WhichSpectrum == 2)
{
Norm = 1.0;
/* tabulated file is already at the initial redshift */
Dplus = 1.0;
}
else
{
Norm = 1.0;
res = TopHatSigma2(R8);
if(ThisTask == 0 && WhichSpectrum == 2)
printf("\nNormalization of spectrum in file: Sigma8 = %g\n", sqrt(res));
Norm = Sigma8 * Sigma8 / res;
if(ThisTask == 0 && WhichSpectrum == 2)
printf("Normalization adjusted to Sigma8=%g (Normfac=%g)\n\n", Sigma8, Norm);
Dplus = GrowthFactor(InitTime, 1.0);
}
}
double PowerSpec_Tabulated(double k)
{
double logk, logD, P, kold, u, dlogk, Delta2;
int binlow, binhigh, binmid;
kold = k;
k *= (InputSpectrum_UnitLength_in_cm / UnitLength_in_cm); /* convert to h/Mpc */
logk = log10(k);
if(logk < PowerTable[0].logk || logk > PowerTable[NPowerTable - 1].logk)
return 0;
binlow = 0;
binhigh = NPowerTable - 1;
while(binhigh - binlow > 1)
{
binmid = (binhigh + binlow) / 2;
if(logk < PowerTable[binmid].logk)
binhigh = binmid;
else
binlow = binmid;
}
dlogk = PowerTable[binhigh].logk - PowerTable[binlow].logk;
if(dlogk == 0)
FatalError(777);
u = (logk - PowerTable[binlow].logk) / dlogk;
logD = (1 - u) * PowerTable[binlow].logD + u * PowerTable[binhigh].logD;
Delta2 = pow(10.0, logD);
P = Norm * Delta2 / (4 * M_PI * kold * kold * kold);
return P;
}
double PowerSpec_Efstathiou(double k)
{
return Norm * k / pow(1 + pow(AA * k + pow(BB * k, 1.5) + CC * CC * k * k, nu), 2 / nu);
}
double PowerSpec_EH(double k) /* Eisenstein & Hu */
{
return Norm * k * pow(tk_eh(k), 2);
}
double tk_eh(double k) /* from Martin White */
{
double q, theta, ommh2, a, s, gamma, L0, C0;
double tmp;
double omegam, ombh2, hubble;
/* other input parameters */
hubble = HubbleParam;
omegam = Omega;
ombh2 = OmegaBaryon * HubbleParam * HubbleParam;
if(OmegaBaryon == 0)
ombh2 = 0.04 * HubbleParam * HubbleParam;
k *= (3.085678e24 / UnitLength_in_cm); /* convert to h/Mpc */
theta = 2.728 / 2.7;
ommh2 = omegam * hubble * hubble;
s = 44.5 * log(9.83 / ommh2) / sqrt(1. + 10. * exp(0.75 * log(ombh2))) * hubble;
a = 1. - 0.328 * log(431. * ommh2) * ombh2 / ommh2
+ 0.380 * log(22.3 * ommh2) * (ombh2 / ommh2) * (ombh2 / ommh2);
gamma = a + (1. - a) / (1. + exp(4 * log(0.43 * k * s)));
gamma *= omegam * hubble;
q = k * theta * theta / gamma;
L0 = log(2. * exp(1.) + 1.8 * q);
C0 = 14.2 + 731. / (1. + 62.5 * q);
tmp = L0 / (L0 + C0 * q * q);
return (tmp);
}
double TopHatSigma2(double R)
{
double result, abserr;
gsl_integration_workspace *workspace;
gsl_function F;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &sigma2_int;
r_tophat = R;
gsl_integration_qag(&F, 0, 500.0 * 1 / R,
0, 1.0e-4, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);
gsl_integration_workspace_free(workspace);
return result;
/* note: 500/R is here chosen as (effectively) infinity integration boundary */
}
double sigma2_int(double k, void *param)
{
double kr, kr3, kr2, w, x;
kr = r_tophat * k;
kr2 = kr * kr;
kr3 = kr2 * kr;
if(kr < 1e-8)
return 0;
w = 3 * (sin(kr) / kr3 - cos(kr) / kr2);
x = 4 * PI * k * k * w * w * PowerSpec(k);
return x;
}
double GrowthFactor(double astart, double aend)
{
return growth(aend) / growth(astart);
}
double growth(double a)
{
double hubble_a;
hubble_a = sqrt(Omega / (a * a * a) + (1 - Omega - OmegaLambda) / (a * a) + OmegaLambda);
double result, abserr;
gsl_integration_workspace *workspace;
gsl_function F;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &growth_int;
gsl_integration_qag(&F, 0, a, 0, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);
gsl_integration_workspace_free(workspace);
return hubble_a * result;
}
double growth_int(double a, void *param)
{
return pow(a / (Omega + (1 - Omega - OmegaLambda) * a + OmegaLambda * a * a * a), 1.5);
}
double F_Omega(double a)
{
double omega_a;
omega_a = Omega / (Omega + a * (1 - Omega - OmegaLambda) + a * a * a * OmegaLambda);
return pow(omega_a, 0.6);
}
| {
"alphanum_fraction": 0.6070301938,
"avg_line_length": 19.6371681416,
"ext": "c",
"hexsha": "7311d9d153167c269c463c9705b6cb8e64362e1a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/N-GenIC/power_debug.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2292,
"size": 6657
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_deriv.h>
double f (double x, void * params)
{
return pow (x, 1.5);
}
int
main (void)
{
gsl_function F;
double result, abserr;
F.function = &f;
F.params = 0;
printf ("f(x) = x^(3/2)\n");
gsl_deriv_central (&F, 2.0, 1e-8, &result, &abserr);
printf ("x = 2.0\n");
printf ("f'(x) = %.10f +/- %.10f\n", result, abserr);
printf ("exact = %.10f\n\n", 1.5 * sqrt(2.0));
gsl_deriv_forward (&F, 0.0, 1e-8, &result, &abserr);
printf ("x = 0.0\n");
printf ("f'(x) = %.10f +/- %.10f\n", result, abserr);
printf ("exact = %.10f\n", 0.0);
return 0;
}
| {
"alphanum_fraction": 0.5534591195,
"avg_line_length": 19.2727272727,
"ext": "c",
"hexsha": "b32e1934f547a84e0ed90e49766ee747884ab1be",
"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/diff.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/diff.c",
"max_line_length": 55,
"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/diff.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": 254,
"size": 636
} |
/*
* Test uni_qdblflt() in reprand.cc has a uniform distribution. From:
* http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
*
* Compile with :
* gcc -std=c99 -Wall -o reprand_test reprand_test.c -lgsl
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#define REPRAND_TEST
#include "reprand.cc"
double chi2UniformDistance( const double const *ds, int dslen)
{
double expected = 0.0;
double sum = 0.0;
int k;
for (k=0; k<dslen; k++)
{
expected += ds[k];
}
expected /= k;
for (k=0; k<dslen; k++)
{
double x = ds[k] - expected;
sum += x*x;
}
return sum/expected;
}
double chi2Probability(double dof, double distance)
{
return gsl_sf_gamma_inc_Q( 0.5*dof, 0.5*distance);
}
int chiIsUniform
( const double * const dset, const int dslen, const double significance)
{
int dof = dslen -1;
double dist = chi2UniformDistance( dset, dslen);
return chi2Probability( dof, dist ) > significance;
}
int main(int argc, char **argv)
{
/* Example sets */
const double const dset1[] = { 199809., 200665., 199607., 200270., 199649. };
const double const dset2[] = { 522573., 244456., 139979., 71531., 21461. };
/* Data set for getRan() */
const uint32_t N=0x10000;
double dset_getRan[N];
/* Initialise with getRan() */
init_JKISS();
for(uint32_t k=0;k<N;k++)
{
dset_getRan[k]=uni_qdblflt();
}
/* Run chi^2 tests. Start with the example sets */
const double * const dsets[] = { dset1, dset2, dset_getRan };
const uint32_t const dslens[] = { 5, 5, N };
for (uint32_t k=0; k<sizeof(dslens)/sizeof(uint32_t); k++)
{
double dist = chi2UniformDistance(dsets[k], dslens[k]);
uint32_t dof = dslens[k]-1;
double prob = chi2Probability( dof, dist );
const double significance = 0.001;
char * const uniform =
chiIsUniform(dsets[k], dslens[k], significance) ? "Yes":"No";
printf("dof: %d, dist.: %.4f, prob.: %.6f, uniform? %s, sig. %.3f\n",
dof, dist, prob, uniform, significance);
}
return 0;
}
| {
"alphanum_fraction": 0.6170407696,
"avg_line_length": 25.3837209302,
"ext": "c",
"hexsha": "8519769b2aa5de5cb5c49d6690c0d73a35ae80f3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-28T06:26:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-28T06:26:39.000Z",
"max_forks_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robertgj/DesignOfIIRFilters",
"max_forks_repo_path": "src/reprand_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9",
"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": "robertgj/DesignOfIIRFilters",
"max_issues_repo_path": "src/reprand_test.c",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robertgj/DesignOfIIRFilters",
"max_stars_repo_path": "src/reprand_test.c",
"max_stars_repo_stars_event_max_datetime": "2020-04-27T03:13:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-11T11:44:10.000Z",
"num_tokens": 694,
"size": 2183
} |
/*
* Copyright (c) 2018, Aleksi Kurkela, Aleksas Mazeliauskas, Jean-Francois
* Paquet, Soeren Schlichting and Derek Teaney
* All rights reserved.
*
* KoMPoST is distributed under MIT license;
* see the LICENSE file that should be present in the root
* of the source distribution, or alternately available at:
* https://github.com/KMPST/KoMPoST/
*/
#include <gsl/gsl_math.h>
#include <iostream>
#ifndef M_HBARC
#define M_HBARC 0.197326979
#endif
namespace GreensFunctions {
class LowKArguments;
//////////////////////////////////////////////////
namespace EnergyPerturbations {
namespace FreeStreaming {
namespace CoordinateSpace {
double Gs(double dX, double dT);
double Gv(double dX, double dT);
double Gd(double dX, double dT);
double Gr(double dX, double dT);
}
} // FreeStreaming
namespace KineticTheory {
namespace CoordinateSpace {
double Gs(double dX, double dT, double ScalingVarOut);
double Gv(double dX, double dT, double ScalingVarOut);
double Gd(double dX, double dT, double ScalingVarOut);
double Gr(double dX, double dT, double ScalingVarOut);
}
} // KineticTheory
namespace LowKLimit {
namespace CoordinateSpace {
double Gs(double dX, double dT, const LowKArguments &in);
double Gv(double dX, double dT, const LowKArguments &in);
double Gd(double dX, double dT, const LowKArguments &in);
double Gr(double dX, double dT, const LowKArguments &in);
}
} // LowKLimit
} // EnergyPerturbations
//////////////////////////////////////////////////
namespace MomentumPerturbations {
namespace FreeStreaming {
namespace CoordinateSpace {
double Hv(double dX, double dT);
double Hd(double dX, double dT);
double Hr(double dX, double dT);
double Htd(double dX, double dT);
double Htm(double dX, double dT);
double Htr(double dX, double dT);
}
} // FreeStreaming
namespace KineticTheory {
namespace CoordinateSpace {
double Hv(double dX, double dT, double ScalingVarOut);
double Hd(double dX, double dT, double ScalingVarOut);
double Hr(double dX, double dT, double ScalingVarOut);
double Htd(double dX, double dT, double ScalingVarOut);
double Htm(double dX, double dT, double ScalingVarOut);
double Htr(double dX, double dT, double ScalingVarOut);
}
} // Kinetic Theory
} // MomentumPerturbations
//////////////////////////////////////////////////
void Setup(double Sigma, int NumberOfPoints, int ENERGY_PERTURBATIONS,
int MOMENTUM_PERTURBATIONS);
void Output(int ENERGY_PERTURBATIONS, int MOMENTUM_PERTURBATIONS);
class LowKArguments {
// private:
public:
// Number of DOF
const int NuG = 16;
double tauF; // Final time in fm
double tauIn; // Initial time in fm
double E0;
double EF;
double TXX0;
double TXXF;
double EtaByS;
double SigmaBG; // Sigma in fm
public:
LowKArguments(double tf, double tin, double e0, double ef, double txx0,
double txxf, double etabys, double sigmabg)
: tauF(tf), tauIn(tin), E0(e0), EF(ef), TXX0(txx0), TXXF(txxf),
EtaByS(etabys), SigmaBG(sigmabg) {}
double S(double dX, double dT) const {
const double &s = SigmaBG;
double rs = dX / s;
return 1. / (M_PI * s * s) * exp(-rs * rs);
}
double DS(double dX, double dT) const {
const double &s = SigmaBG;
double rs = dX / s;
return dT / (M_PI * s * s * s) * exp(-rs * rs) * (-2. * rs);
}
double DSOverR(double dX, double dT) const {
const double &s = SigmaBG;
double rs = dX / s;
return dT * dT / (M_PI * s * s * s * s) * exp(-rs * rs) * (-2.);
}
double DDS(double dX, double dT) const {
const double &s = SigmaBG;
double rs = dX / s;
return dT * dT / (M_PI * s * s * s * s) * exp(-rs * rs) *
(4 * rs * rs - 2.);
}
double Ass() const {
double dT = tauF - tauIn;
double s2 = SigmaBG * SigmaBG / (dT * dT);
return (-0.5 + s2 / 2.) * E0 / EF * (EF + TXXF) / (E0 + TXX0);
}
double Asv() const { return 0.5 * E0 / EF * (EF + TXXF) / (E0 + TXX0); }
double ScalingVariableInverse() const {
return 3. / 4. * EtaByS * Entropy(EF) * M_HBARC / (EF * tauF);
}
double Entropy(double e) const {
double T = pow(30. / (M_PI * M_PI * NuG) * e, 0.25);
return 4. / 3. * e / T;
}
};
} // GreensFunctions
| {
"alphanum_fraction": 0.6473822615,
"avg_line_length": 26.3081761006,
"ext": "h",
"hexsha": "c1207d210c7314d56bb2ec8bca27618fac21736a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-08-02T09:49:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-08-02T09:49:07.000Z",
"max_forks_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "j-f-paquet/kompost",
"max_forks_repo_path": "src/GreensFunctions.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd",
"max_issues_repo_issues_event_max_datetime": "2021-08-23T13:24:54.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-10T19:10:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "j-f-paquet/kompost",
"max_issues_repo_path": "src/GreensFunctions.h",
"max_line_length": 74,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "13113cb05bc673f8e54d52f49adf15ff8d2cd3bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "j-f-paquet/kompost",
"max_stars_repo_path": "src/GreensFunctions.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-02T09:49:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-02T17:14:11.000Z",
"num_tokens": 1277,
"size": 4183
} |
#pragma once
#include "concepts/MemoryIntrospection.h"
#include "math/Vector3.h"
#include "pointcloud/PointAttributes.h"
#include <gsl/gsl>
#include <optional>
#include <vector>
// TECH_DEBT Make attributes more dynamic (map<AttributeType, GenericAttribute*>
// or something like that)
/// <summary>
/// Buffer structure that stores point attributes (position, color etc.) for
/// multiple points at once in a structure-of-array fashion. Compared to storing
/// all points as Point structures, this has better performance for data access
/// </summary>
struct PointBuffer
{
struct PointConstReference;
/// <summary>
/// Mutable indirect reference to a single point inside the PointBuffer
/// </summary>
struct PointReference
{
friend struct PointBuffer;
friend struct PointConstReference;
PointReference();
PointReference(const PointReference&) = default;
PointReference& operator=(const PointReference&) = default;
Vector3<double>& position() const;
Vector3<uint8_t>* rgbColor() const;
Vector3<float>* normal() const;
uint16_t* intensity() const;
uint8_t* classification() const;
uint8_t* edge_of_flight_line() const;
double* gps_time() const;
uint8_t* number_of_returns() const;
uint8_t* return_number() const;
uint16_t* point_source_id() const;
uint8_t* scan_direction_flag() const;
int8_t* scan_angle_rank() const;
uint8_t* user_data() const;
private:
PointReference(PointBuffer* pointBuffer, size_t index);
PointBuffer* _pointBuffer;
size_t _index;
};
/// <summary>
/// Constant indirect reference to a single point inside the PointBuffer
/// </summary>
struct PointConstReference
{
friend struct PointBuffer;
PointConstReference();
PointConstReference(const PointReference& point_reference);
PointConstReference(const PointConstReference&) = default;
PointConstReference& operator=(const PointConstReference&) = default;
const Vector3<double>& position() const;
const Vector3<uint8_t>* rgbColor() const;
const Vector3<float>* normal() const;
const uint16_t* intensity() const;
const uint8_t* classification() const;
const uint8_t* edge_of_flight_line() const;
const double* gps_time() const;
const uint8_t* number_of_returns() const;
const uint8_t* return_number() const;
const uint16_t* point_source_id() const;
const uint8_t* scan_direction_flag() const;
const int8_t* scan_angle_rank() const;
const uint8_t* user_data() const;
private:
PointConstReference(PointBuffer const* pointBuffer, size_t index);
PointBuffer const* _pointBuffer;
size_t _index;
};
/// <summary>
/// Creates an empty point buffer
/// </summary>
PointBuffer();
/// <summary>
/// Creates a PointBuffer from the given range of PointReferences
/// </summary>
explicit PointBuffer(gsl::span<PointReference> points);
/// <summary>
/// Creates a PointBuffer from the given range of PointConstReferences
/// </summary>
explicit PointBuffer(gsl::span<PointConstReference> points);
/// <summary>
/// Creates a new PointBuffer storing count points. For all passed attribute
/// vectors, their count has to be equal to the specified count, otherwise a
/// invalid_argument error is thrown
/// </summary>
PointBuffer(size_t count,
std::vector<Vector3<double>> positions,
std::vector<Vector3<uint8_t>> rgbColors = {},
std::vector<Vector3<float>> normals = {},
std::vector<uint16_t> intensities = {},
std::vector<uint8_t> classifications = {},
std::vector<uint8_t> edge_of_flight_lines = {},
std::vector<double> gps_times = {},
std::vector<uint8_t> number_of_returns = {},
std::vector<uint8_t> return_numbers = {},
std::vector<uint16_t> point_source_ids = {},
std::vector<uint8_t> scan_direction_flags = {},
std::vector<int8_t> scan_angle_ranks = {},
std::vector<uint8_t> user_data = {});
/**
* Creates a new PointBuffer storing 'count' default-constructed points with the
* attributes given by 'attributes'
*/
PointBuffer(size_t count, const PointAttributes& attributes);
PointBuffer(const PointBuffer&) = default;
PointBuffer(PointBuffer&&) = default;
PointBuffer& operator=(const PointBuffer&) = default;
PointBuffer& operator=(PointBuffer&&) = default;
/// <summary>
/// Push a single point into this PointBuffer. If the point has attributes
/// that are not defined in this PointBuffer they are ignored. Attributes from
/// this PointBuffer that are not defined in the given point are filled with
/// default values
/// </summary>
void push_point(PointConstReference point);
/// <summary>
/// Returns a constant indirect reference to the point with the given index
/// </summary>
PointConstReference get_point(size_t point_index) const;
/// <summary>
/// Returns a mutable indirect reference to the point with the given index
/// </summary>
PointReference get_point(size_t point_index);
/// <summary>
/// Appends the contents of the given PointBuffer to this PointBuffer. This
/// will copy all attributes that exist from the given buffer into this
/// buffer. Attributes that exist in this buffer but not in the other buffer
/// are filled with default values
/// </summary>
void append_buffer(const PointBuffer& other);
/**
* Applies a new attribute schema to this PointBuffer. Clears all attributes that are not in the
* new schema and fills all attributes that are in the new schema but weren't in the PointBuffers
* old schema (i.e. the state of the PointBuffer prior to calling 'apply_schema') with default
* values
*/
void apply_schema(const PointAttributes& schema);
size_t count() const { return _count; }
bool empty() const { return _count == 0; }
void clear();
void shrink_to_fit();
void resize(size_t new_size);
std::vector<Vector3<double>>& positions() { return _positions; }
std::vector<Vector3<uint8_t>>& rgbColors() { return _rgbColors; }
std::vector<Vector3<float>>& normals() { return _normals; }
std::vector<uint16_t>& intensities() { return _intensities; }
std::vector<uint8_t>& classifications() { return _classifications; }
auto& edge_of_flight_lines() { return _edge_of_flight_lines; }
auto& gps_times() { return _gps_times; }
auto& number_of_returns() { return _number_of_returns; }
auto& return_numbers() { return _return_numbers; }
auto& point_source_ids() { return _point_source_ids; }
auto& scan_direction_flags() { return _scan_direction_flags; }
auto& scan_angle_ranks() { return _scan_angle_ranks; }
auto& user_data() { return _user_data; }
const std::vector<Vector3<double>>& positions() const { return _positions; }
const std::vector<Vector3<uint8_t>>& rgbColors() const { return _rgbColors; }
const std::vector<Vector3<float>>& normals() const { return _normals; }
const std::vector<uint16_t>& intensities() const { return _intensities; }
const std::vector<uint8_t>& classifications() const { return _classifications; }
const auto& edge_of_flight_lines() const { return _edge_of_flight_lines; }
const auto& gps_times() const { return _gps_times; }
const auto& number_of_returns() const { return _number_of_returns; }
const auto& return_numbers() const { return _return_numbers; }
const auto& point_source_ids() const { return _point_source_ids; }
const auto& scan_direction_flags() const { return _scan_direction_flags; }
const auto& scan_angle_ranks() const { return _scan_angle_ranks; }
const auto& user_data() const { return _user_data; }
bool hasColors() const;
bool hasNormals() const;
bool hasIntensities() const;
bool hasClassifications() const;
bool has_edge_of_flight_lines() const;
bool has_gps_times() const;
bool has_number_of_returns() const;
bool has_return_numbers() const;
bool has_point_source_ids() const;
bool has_scan_direction_flags() const;
bool has_scan_angle_ranks() const;
bool has_user_data() const;
void verify() const;
/// <summary>
/// Returns the raw size in bytes of the contents (positions, normals etc.) of
/// this PointBuffer. This does NOT include the in-memory size of a
/// PointBuffer structure itself, but rather the allocated memory of all the
/// vectors of the PointBuffer
/// </summary>
size_t content_byte_size() const;
struct PointIterator
{
PointIterator(PointBuffer& pointBuffer, size_t idx);
PointReference operator*() const;
PointIterator& operator++();
PointIterator operator++(int);
PointIterator& operator--();
PointIterator operator--(int);
PointIterator operator+(std::ptrdiff_t count) const;
PointIterator operator-(std::ptrdiff_t count) const;
PointIterator& operator+=(std::ptrdiff_t count);
PointIterator& operator-=(std::ptrdiff_t count);
friend std::ptrdiff_t operator-(const PointIterator& l, const PointIterator& r);
PointReference operator[](std::ptrdiff_t idx) const;
bool operator==(const PointIterator& other) const;
bool operator!=(const PointIterator& other) const;
friend bool operator<(const PointIterator& l, const PointIterator& r);
friend bool operator<=(const PointIterator& l, const PointIterator& r);
friend bool operator>(const PointIterator& l, const PointIterator& r);
friend bool operator>=(const PointIterator& l, const PointIterator& r);
private:
PointBuffer* _pointBuffer;
size_t _index;
};
struct PointConstIterator
{
PointConstIterator(PointBuffer const& pointBuffer, size_t idx);
PointConstReference operator*() const;
PointConstIterator& operator++();
PointConstIterator operator++(int);
PointConstIterator& operator--();
PointConstIterator operator--(int);
PointConstIterator operator+(std::ptrdiff_t count) const;
PointConstIterator operator-(std::ptrdiff_t count) const;
PointConstIterator& operator+=(std::ptrdiff_t count);
PointConstIterator& operator-=(std::ptrdiff_t count);
friend std::ptrdiff_t operator-(const PointConstIterator& l, const PointConstIterator& r);
PointConstReference operator[](std::ptrdiff_t idx) const;
bool operator==(const PointConstIterator& other) const;
bool operator!=(const PointConstIterator& other) const;
friend bool operator<(const PointConstIterator& l, const PointConstIterator& r);
friend bool operator<=(const PointConstIterator& l, const PointConstIterator& r);
friend bool operator>(const PointConstIterator& l, const PointConstIterator& r);
friend bool operator>=(const PointConstIterator& l, const PointConstIterator& r);
private:
PointBuffer const* _pointBuffer;
size_t _index;
};
PointIterator begin();
PointIterator end();
PointConstIterator begin() const;
PointConstIterator end() const;
private:
size_t _count;
std::vector<Vector3<double>> _positions;
std::vector<Vector3<uint8_t>> _rgbColors;
std::vector<Vector3<float>> _normals;
std::vector<uint16_t> _intensities;
std::vector<uint8_t> _classifications;
std::vector<uint8_t> _edge_of_flight_lines;
std::vector<double> _gps_times;
std::vector<uint8_t> _number_of_returns;
std::vector<uint8_t> _return_numbers;
std::vector<uint16_t> _point_source_ids;
std::vector<uint8_t> _scan_direction_flags;
std::vector<int8_t> _scan_angle_ranks;
std::vector<uint8_t> _user_data;
};
namespace std {
template<>
struct iterator_traits<::PointBuffer::PointIterator>
{
using difference_type = std::ptrdiff_t;
using value_type = ::PointBuffer::PointReference;
using iterator_category = std::random_access_iterator_tag;
};
template<>
struct iterator_traits<::PointBuffer::PointConstIterator>
{
using difference_type = std::ptrdiff_t;
using value_type = ::PointBuffer::PointConstReference;
using iterator_category = std::random_access_iterator_tag;
};
} // namespace std
namespace concepts {
namespace detail {
template<>
constexpr bool has_constant_size_impl<::PointBuffer> = false;
}
template<>
inline unit::byte
size_in_memory(PointBuffer const& point_buffer)
{
return (sizeof(size_t) * boost::units::information::byte) +
size_in_memory(point_buffer.positions()) + size_in_memory(point_buffer.rgbColors()) +
size_in_memory(point_buffer.normals()) + size_in_memory(point_buffer.intensities()) +
size_in_memory(point_buffer.classifications());
}
} // namespace concepts | {
"alphanum_fraction": 0.7209784081,
"avg_line_length": 36.8064516129,
"ext": "h",
"hexsha": "c4b511ee0d7fbb5e25b3784b216ddbea49857f49",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z",
"max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "igd-geo/schwarzwald",
"max_forks_repo_path": "schwarzwald/core/datastructures/PointBuffer.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "igd-geo/schwarzwald",
"max_issues_repo_path": "schwarzwald/core/datastructures/PointBuffer.h",
"max_line_length": 99,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "igd-geo/schwarzwald",
"max_stars_repo_path": "schwarzwald/core/datastructures/PointBuffer.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z",
"num_tokens": 2965,
"size": 12551
} |
/* ode-initval/odeiv.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include "gsl_odeiv.h"
gsl_odeiv_step *
gsl_odeiv_step_alloc(const gsl_odeiv_step_type * T, size_t dim)
{
gsl_odeiv_step *s = (gsl_odeiv_step *) malloc (sizeof (gsl_odeiv_step));
if (s == 0)
{
GSL_ERROR_NULL ("failed to allocate space for ode struct", GSL_ENOMEM);
};
s->type = T;
s->dimension = dim;
s->state = s->type->alloc(dim);
if (s->state == 0)
{
free (s); /* exception in constructor, avoid memory leak */
GSL_ERROR_NULL ("failed to allocate space for ode state", GSL_ENOMEM);
};
return s;
}
const char *
gsl_odeiv_step_name(const gsl_odeiv_step * s)
{
return s->type->name;
}
unsigned int
gsl_odeiv_step_order(const gsl_odeiv_step * s)
{
return s->type->order(s->state);
}
int
gsl_odeiv_step_apply(
gsl_odeiv_step * s,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[],
const gsl_odeiv_system * dydt)
{
return s->type->apply(s->state, s->dimension, t, h, y, yerr, dydt_in, dydt_out, dydt);
}
int
gsl_odeiv_step_reset(gsl_odeiv_step * s)
{
return s->type->reset(s->state, s->dimension);
}
void
gsl_odeiv_step_free(gsl_odeiv_step * s)
{
s->type->free(s->state);
free(s);
}
| {
"alphanum_fraction": 0.6885401807,
"avg_line_length": 23.3666666667,
"ext": "c",
"hexsha": "96999e3acc83410549d6ef7833c06e15ecffc8e3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.c",
"max_line_length": 88,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/step.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": 632,
"size": 2103
} |
/*
* C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer
*
* Yan-Rong Li, liyanrong@mail.ihep.ac.cn
* Jun 30, 2016
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <gsl/gsl_rng.h>
#include "dnestvars.h"
/* output files */
FILE *fsample, *fsample_info;
/* random number generator */
const gsl_rng_type * dnest_gsl_T;
gsl_rng * dnest_gsl_r;
Options options;
char options_file[STR_MAX_LENGTH];
// sampler
bool save_to_disk;
double compression;
unsigned int regularisation;
void *particles;
int dnest_size_of_modeltype;
int particle_offset_size, particle_offset_double;
LikelihoodType *log_likelihoods;
unsigned int *level_assignments;
// number account of unaccepted times
unsigned int *account_unaccepts;
int size_levels;
Level *levels;
unsigned int count_saves, num_saves, num_saves_restart;
int dnest_which_particle_update; // which particle to be updated
int dnest_which_level_update; // which level to be updated;
unsigned long long int count_mcmc_steps;
LikelihoodType *above;
unsigned int size_above;
double post_logz;
int dnest_num_params;
char dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH];
double *limits, *copies_of_limits;
int *dnest_perturb_accept;
int dnest_root;
int dnest_flag_restart=0, dnest_flag_postprc=0, dnest_flag_sample_info=0, dnest_flag_limits=0;
double dnest_post_temp=1.0;
char file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH];
void *dnest_arg;
//***********************************************
/* functions */
double mod(double y, double x);
void dnest_wrap(double *x, double min, double max);
void wrap_limit(double *x, double min, double max);
int mod_int(int y, int x);
int dnest_cmp(const void *pa, const void *pb);
void options_load(int max_num_saves, double ptol);
void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, char *sample_dir, int max_num_saves, double ptol);
void finalise();
double dnest(int argc, char **argv, DNestFptrSet *fptrset, int num_params, char *sample_dir,
int max_num_saves, double pdff, const void *arg);
void dnest_run();
void dnest_mcmc_run();
void update_particle(unsigned int which);
void update_level_assignment(unsigned int which);
double log_push(unsigned int which_level);
bool enough_levels(Level *l, int size_l);
void do_bookkeeping();
void save_levels();
void save_particle();
void save_limits();
void kill_lagging_particles();
void renormalise_visits();
void recalculate_log_X();
double dnest_randh();
double dnest_rand();
double dnest_randn();
int dnest_rand_int(int size);
void dnest_postprocess(double temperature, int max_num_saves, double ptol);
void postprocess(double temperature);
void initialize_output_file();
void close_output_file();
void dnest_save_restart();
void dnest_restart();
void dnest_restart_action(int iflag);
void dnest_accept_action();
void dnest_kill_action(int i, int i_copy);
void dnest_print_particle(FILE *fp, const void *model, const void *arg);
void dnest_read_particle(FILE *fp, void *model);
int dnest_get_size_levels();
int dnest_get_which_level_update();
int dnest_get_which_particle_update();
void dnest_get_posterior_sample_file(char *fname);
int dnest_check_version(char *verion_str);
unsigned int dnest_get_which_num_saves();
unsigned int dnest_get_count_saves();
unsigned long long int dnest_get_count_mcmc_steps();
void dnest_check_fptrset(DNestFptrSet *fptrset);
DNestFptrSet * dnest_malloc_fptrset();
void dnest_free_fptrset(DNestFptrSet * fptrset);
/*=====================================================*/
// users responsible for following functions
void (*print_particle)(FILE *fp, const void *model, const void *arg);
void (*read_particle)(FILE *fp, void *model);
void (*from_prior)(void *model, const void *arg);
double (*log_likelihoods_cal)(const void *model, const void *arg);
double (*log_likelihoods_cal_initial)(const void *model, const void *arg);
double (*log_likelihoods_cal_restart)(const void *model, const void *arg);
double (*perturb)(void *model, const void *arg);
void (*restart_action)(int iflag);
void (*accept_action)();
void (*kill_action)(int i, int i_copy);
/*=====================================================*/ | {
"alphanum_fraction": 0.7494775946,
"avg_line_length": 32.6287878788,
"ext": "c",
"hexsha": "da00490281e3f33a8be90264350840f6a6ea685a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z",
"max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/pyCALI",
"max_forks_repo_path": "src/pycali/cdnest/dnestvars.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/pyCALI",
"max_issues_repo_path": "src/pycali/cdnest/dnestvars.c",
"max_line_length": 123,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/PyCALI",
"max_stars_repo_path": "src/pycali/cdnest/dnestvars.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z",
"num_tokens": 1075,
"size": 4307
} |
#ifndef BLAS_WRAPPER_H
#define BLAS_WRAPPER_H
#include <cassert>
#include <cmath>
#include <cstring>
#include <vector>
// Useful dense kernels from BLAS, with readable, overloaded, cross-platform names and some simplified calling
// dot (dot-product of vectors)
// nrm2 (2-norm of a vector)
// asum (1-norm of a vector)
// amax (index of maximum absolute value in a vector)
// swap (exchanging values in two vectors)
// copy (copying values from one vector to another)
// axpy (adding a scalar times a vector to another vector)
// scal (multiplying a vector by a scalar)
// gemv (multiplying a matrix times a vector, scaling, and adding result to another vector))
// gemm (multiplying two matrices, scaling, and adding result to another matrix)
// In addition:
// set_zero (zero out all entries in a vector)
// abs_max (return the infinity norm of a vector, i.e. the magnitude of its largest element)
// There are also version using std::vector for convenience.
// Matrices are always assumed to be in column-major format.
// You can #define one of:
// USE_FORTRAN_BLAS (if your BLAS calls should look like dgemm_ with FORTRAN calling conventions, as in GOTO BLAS)
// USE_AMD_BLAS (if using the AMD Math Library)
// USE_CBLAS (if instead you have calls like cblas_dgemm, and have a file "cblas.h" available)
// or, if you're on the Mac, it will default to the vecLib CBLAS if none of these are specified.
namespace BLAS{
template<class T>
inline void set_zero(int n, T *x)
{ std::memset(x, 0, n*sizeof(T)); }
}
//============================================================================
#ifdef USE_FORTRAN_BLAS
extern "C" {
double dsdot_(const int*, const float*, const int*, const float*, const int*);
double sdot_(const int*, const float*, const int*, const float*, const int*);
double ddot_(const int*, const double*, const int*, const double*, const int*);
float snrm2_(const int*, const float*, const int*);
double dnrm2_(const int*, const double*, const int*);
float sasum_(const int*, const float*, const int*);
double dasum_(const int*, const double*, const int*);
int isamax_(const int*, const float*, const int*);
int idamax_(const int*, const double*, const int*);
void sswap_(const int*, float*, const int*, float*, const int*);
void dswap_(const int*, double*, const int*, double*, const int*);
void scopy_(const int*, const float*, const int*, float*, const int*);
void dcopy_(const int*, const double*, const int*, double*, const int*);
void saxpy_(const int*, const float*, const float*, const int*, float*, const int*);
void daxpy_(const int*, const double*, const double*, const int*, double*, const int*);
void sscal_(const int*, const float*, float*, const int*);
void dscal_(const int*, const double*, double*, const int*);
void sgemv_(const char*, const int*, const int*, const float*, const float*, const int*, const float*, const int*, const float*, float*, 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 sgemm_(const char*, const char*, const int*, const int*, const int*, const float*, const float*, const int*, const float*, const int*, const float*, float*, 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*);
}
namespace BLAS{
enum Transpose {NoTrans='N', Trans='T'};
enum UpperLower {Upper='U', Lower='L'};
enum UnitDiag {NonUnit='N', Unit='U'};
enum Side {Left='L', Right='R'};
// dot products
inline double dot(int n, const float *x, int incx, const float *y, int incy=1)
{ return dsdot_(&n, x, &incx, y, &incy); }
inline double dot(int n, const float *x, const float *y, int incy=1)
{ const int one=1; return dsdot_(&n, x, &one, y, &incy); }
inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)
{ return (float)sdot_(&n, x, &incx, y, &incy); }
inline float dotf(int n, const float *x, const float *y, int incy=1)
{ const int one=1; return (float)sdot_(&n, x, &one, y, &incy); }
inline double dot(int n, const double *x, int incx, const double *y, int incy=1)
{ return ddot_(&n, x, &incx, y, &incy); }
inline double dot(int n, const double *x, const double *y, int incy=1)
{ const int one=1; return ddot_(&n, x, &one, y, &incy); }
// 2-norm
inline float norm2(int n, const float *x, int incx=1)
{ return snrm2_(&n, x, &incx); }
inline double norm2(int n, const double *x, int incx=1)
{ return dnrm2_(&n, x, &incx); }
// 1-norm (sum of absolute values)
inline float abs_sum(int n, const float *x, int incx=1)
{ return sasum_(&n, x, &incx); }
inline double abs_sum(int n, const double *x, int incx=1)
{ return dasum_(&n, x, &incx); }
// inf-norm (maximum absolute value: index of max returned)
inline int index_abs_max(int n, const float *x, int incx=1)
{ return isamax_(&n, x, &incx)-1; }
inline int index_abs_max(int n, const double *x, int incx=1)
{ return idamax_(&n, x, &incx)-1; }
inline float abs_max(int n, const float *x, int incx=1)
{ return std::fabs(x[isamax_(&n, x, &incx)-1]); }
inline double abs_max(int n, const double *x, int incx=1)
{ return std::fabs(x[idamax_(&n, x, &incx)-1]); }
// swap (actual data exchanged, not just pointers)
inline void swap(int n, float *x, int incx, float *y, int incy=1)
{ sswap_(&n, x, &incx, y, &incy); }
inline void swap(int n, float *x, float *y, int incy=1)
{ const int one=1; sswap_(&n, x, &one, y, &incy); }
inline void swap(int n, double *x, int incx, double *y, int incy=1)
{ dswap_(&n, x, &incx, y, &incy); }
inline void swap(int n, double *x, double *y, int incy=1)
{ const int one=1; dswap_(&n, x, &one, y, &incy); }
// copy (y=x)
inline void copy(int n, const float *x, int incx, float *y, int incy=1)
{ scopy_(&n, x, &incx, y, &incy); }
inline void copy(int n, const float *x, float *y, int incy=1)
{ const int one=1; scopy_(&n, x, &one, y, &incy); }
inline void copy(int n, const double *x, int incx, double *y, int incy=1)
{ dcopy_(&n, x, &incx, y, &incy); }
inline void copy(int n, const double *x, double *y, int incy=1)
{ const int one=1; dcopy_(&n, x, &one, y, &incy); }
// saxpy (y=alpha*x+y)
inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)
{ saxpy_(&n, &alpha, x, &incx, y, &incy); }
inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)
{ const int one=1; saxpy_(&n, &alpha, x, &one, y, &incy); }
inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)
{ daxpy_(&n, &alpha, x, &incx, y, &incy); }
inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)
{ const int one=1; daxpy_(&n, &alpha, x, &one, y, &incy); }
// scale (x=alpha*x)
inline void scale(int n, float alpha, float *x, int incx=1)
{ sscal_(&n, &alpha, x, &incx); }
inline void scale(int n, double alpha, double *x, int incx=1)
{ dscal_(&n, &alpha, x, &incx); }
// gemv (y=alpha*A*x+beta*y, or using A^T)
// The matrix is always m*n; the size of x and y depend on if A is transposed.
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, float alpha, const float *A, int lda,
const float *x, int incx, float beta, float *y, int incy=1)
{ sgemv_((const char*)&transpose, &m, &n, &alpha, A, &lda, x, &incx, &beta, y, &incy); }
inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x
{ const int onei=1; const float zero=0, onef=1; sgemv_("N", &m, &n, &onef, A, &m, x, &onei, &zero, y, &incy); }
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, double alpha, const double *A, int lda,
const double *x, int incx, double beta, double *y, int incy=1)
{ dgemv_((const char*)&transpose, &m, &n, &alpha, A, &lda, x, &incx, &beta, y, &incy); }
inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x
{ const int onei=1; const double zero=0, onef=1; dgemv_("N", &m, &n, &onef, A, &m, x, &onei, &zero, y, &incy); }
// gemm (C=alpha*A*B+beta*C)
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, float alpha, const float *A, int lda,
const float *B, int ldb, float beta, float *C, int ldc)
{ sgemm_((const char*)&transA, (const char*)&transB, &m, &n, &k, &alpha, A, &lda, B, &ldb, &beta, C, &ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C)
{ const float zero=0, one=1; sgemm_("N", "N", &m, &n, &k, &one, A, &m, B, &k, &zero, C, &m); } // C=A*B
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, double alpha, const double *A, int lda,
const double *B, int ldb, double beta, double *C, int ldc)
{ dgemm_((const char*)&transA, (const char*)&transB, &m, &n, &k, &alpha, A, &lda, B, &ldb, &beta, C, &ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C)
{ const double zero=0, one=1; dgemm_("N", "N", &m, &n, &k, &one, A, &m, B, &k, &zero, C, &m); } // C=A*B
};
//============================================================================
#elif defined USE_AMD_BLAS
#include <acml.h>
namespace BLAS{
enum Transpose {NoTrans='N', Trans='T'};
enum UpperLower {Upper='U', Lower='L'};
enum UnitDiag {NonUnit='N', Unit='U'};
enum Side {Left='L', Right='R'};
// dot products
inline double dot(int n, const float *x, int incx, const float *y, int incy=1)
{ return dsdot(n, (float*)x, incx, (float*)y, incy); }
inline double dot(int n, const float *x, const float *y, int incy=1)
{ return dsdot(n, (float*)x, 1, (float*)y, incy); }
inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)
{ return sdot(n, (float*)x, incx, (float*)y, incy); }
inline float dotf(int n, const float *x, const float *y, int incy=1)
{ return sdot(n, (float*)x, 1, (float*)y, incy); }
inline double dot(int n, const double *x, int incx, const double *y, int incy=1)
{ return ddot(n, (double *)x, incx, (double *)y, incy); }
inline double dot(int n, const double *x, const double *y, int incy=1)
{ return ddot(n, (double *)x, 1, (double *)y, incy); }
// 2-norm
inline float norm2(int n, const float *x, int incx=1)
{ return snrm2(n, (float*)x, incx); }
inline double norm2(int n, const double *x, int incx=1)
{ return dnrm2(n, (double*)x, incx); }
// 1-norm (sum of absolute values)
inline float abs_sum(int n, const float *x, int incx=1)
{ return sasum(n, (float*)x, incx); }
inline double abs_sum(int n, const double *x, int incx=1)
{ return dasum(n, (double*)x, incx); }
// inf-norm (maximum absolute value: index of max returned)
inline int index_abs_max(int n, const float *x, int incx=1)
{ return isamax(n, (float*)x, incx)-1; }
inline int index_abs_max(int n, const double *x, int incx=1)
{ return idamax(n, (double*)x, incx)-1; }
inline float abs_max(int n, const float *x, int incx=1)
{ return std::fabs(x[isamax(n, (float*)x, incx)]-1); }
inline double abs_max(int n, const double *x, int incx=1)
{ return std::fabs(x[idamax(n, (double*)x, incx)]-1); }
// swap (actual data exchanged, not just pointers)
inline void swap(int n, float *x, int incx, float *y, int incy=1)
{ sswap(n, x, incx, y, incy); }
inline void swap(int n, float *x, float *y, int incy=1)
{ sswap(n, x, 1, y, incy); }
inline void swap(int n, double *x, int incx, double *y, int incy=1)
{ dswap(n, x, incx, y, incy); }
inline void swap(int n, double *x, double *y, int incy=1)
{ dswap(n, x, 1, y, incy); }
// copy (y=x)
inline void copy(int n, const float *x, int incx, float *y, int incy=1)
{ scopy(n, (float*)x, incx, y, incy); }
inline void copy(int n, const float *x, float *y, int incy=1)
{ scopy(n, (float*)x, 1, y, incy); }
inline void copy(int n, const double *x, int incx, double *y, int incy=1)
{ dcopy(n, (double *)x, incx, y, incy); }
inline void copy(int n, const double *x, double *y, int incy=1)
{ dcopy(n, (double *)x, 1, y, incy); }
// saxpy (y=alpha*x+y)
inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)
{ saxpy(n, alpha, (float*)x, incx, y, incy); }
inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)
{ saxpy(n, alpha, (float*)x, 1, y, incy); }
inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)
{ daxpy(n, alpha, (double*)x, incx, y, incy); }
inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)
{ daxpy(n, alpha, (double*)x, 1, y, incy); }
// scale (x=alpha*x)
inline void scale(int n, float alpha, float *x, int incx=1)
{ sscal(n, alpha, x, incx); }
inline void scale(int n, double alpha, double *x, int incx=1)
{ dscal(n, alpha, x, incx); }
// gemv (y=alpha*A*x+beta*y, or using A^T)
// The matrix is always m*n; the size of x and y depend on if A is transposed.
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, float alpha, const float *A, int lda,
const float *x, int incx, float beta, float *y, int incy=1)
{ sgemv(transpose, m, n, alpha, (float*)A, lda, (float*)x, incx, beta, y, incy); }
inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x
{ sgemv(NoTrans, m, n, 1.f, (float*)A, m, (float*)x, 1, 0.f, y, incy); }
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, double alpha, const double *A, int lda,
const double *x, int incx, double beta, double *y, int incy=1)
{ dgemv(transpose, m, n, alpha, (double*)A, lda, (double*)x, incx, beta, y, incy); }
inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x
{ dgemv(NoTrans, m, n, 1., (double*)A, m, (double*)x, 1, 0., y, incy); }
// gemm (C=alpha*A*B+beta*C)
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, float alpha, const float *A, int lda,
const float *B, int ldb, float beta, float *C, int ldc)
{ sgemm(transA, transB, m, n, k, alpha, (float*)A, lda, (float*)B, ldb, beta, C, ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C)
{ sgemm(NoTrans, NoTrans, m, n, k, 1.f, (float*)A, m, (float*)B, k, 0.f, C, m); } // C=A*B
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, double alpha, const double *A, int lda,
const double *B, int ldb, double beta, double *C, int ldc)
{ dgemm(transA, transB, m, n, k, alpha, (double*)A, lda, (double*)B, ldb, beta, C, ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C)
{ dgemm(NoTrans, NoTrans, m, n, k, 1., (double*)A, m, (double*)B, k, 0., C, m); } // C=A*B
};
//============================================================================
#elif defined USE_CBLAS || defined __APPLE__
#ifdef USE_CBLAS
#include <cblas.h>
#elif defined __APPLE__
#include <Accelerate/Accelerate.h>
#endif
namespace BLAS{
enum Transpose {NoTrans=CblasNoTrans, Trans=CblasTrans};
enum UpperLower {Upper=CblasUpper, Lower=CblasLower};
enum UnitDiag {NonUnit=CblasNonUnit, Unit=CblasUnit};
enum Side {Left=CblasLeft, Right=CblasRight};
// dot products
inline float dotf(int n, const float *x, int incx, const float *y, int incy=1)
{ return cblas_sdot(n, x, incx, y, incy); }
inline float dotf(int n, const float *x, const float *y, int incy=1)
{ return cblas_sdot(n, x, 1, y, incy); }
inline double dot(int n, const float *x, int incx, const float *y, int incy=1)
{ return cblas_dsdot(n, x, incx, y, incy); }
inline double dot(int n, const float *x, const float *y, int incy=1)
{ return cblas_dsdot(n, x, 1, y, incy); }
inline double dot(int n, const double *x, int incx, const double *y, int incy=1)
{ return cblas_ddot(n, x, incx, y, incy); }
inline double dot(int n, const double *x, const double *y, int incy=1)
{ return cblas_ddot(n, x, 1, y, incy); }
// 2-norm
inline float norm2(int n, const float *x, int incx=1)
{ return cblas_snrm2(n, x, incx); }
inline double norm2(int n, const double *x, int incx=1)
{ return cblas_dnrm2(n, x, incx); }
// 1-norm (sum of absolute values)
inline float abs_sum(int n, const float *x, int incx=1)
{ return cblas_sasum(n, x, incx); }
inline double abs_sum(int n, const double *x, int incx=1)
{ return cblas_dasum(n, x, incx); }
// inf-norm (maximum absolute value)
inline int index_abs_max(int n, const float *x, int incx=1)
{ return cblas_isamax(n, x, incx); }
inline int index_abs_max(int n, const double *x, int incx=1)
{ return cblas_idamax(n, x, incx); }
inline float abs_max(int n, const float *x, int incx=1)
{ return std::fabs(x[cblas_isamax(n, x, incx)]); }
inline double abs_max(int n, const double *x, int incx=1)
{ return std::fabs(x[cblas_idamax(n, x, incx)]); }
// swap (actual data exchanged, not just pointers)
inline void swap(int n, float *x, int incx, float *y, int incy=1)
{ cblas_sswap(n, x, incx, y, incy); }
inline void swap(int n, float *x, float *y, int incy=1)
{ cblas_sswap(n, x, 1, y, incy); }
inline void swap(int n, double *x, int incx, double *y, int incy=1)
{ cblas_dswap(n, x, incx, y, incy); }
inline void swap(int n, double *x, double *y, int incy=1)
{ cblas_dswap(n, x, 1, y, incy); }
// copy (y=x)
inline void copy(int n, const float *x, int incx, float *y, int incy=1)
{ cblas_scopy(n, x, incx, y, incy); }
inline void copy(int n, const float *x, float *y, int incy=1)
{ cblas_scopy(n, x, 1, y, incy); }
inline void copy(int n, const double *x, int incx, double *y, int incy=1)
{ cblas_dcopy(n, x, incx, y, incy); }
inline void copy(int n, const double *x, double *y, int incy=1)
{ cblas_dcopy(n, x, 1, y, incy); }
// saxpy (y=alpha*x+y)
inline void add_scaled(int n, float alpha, const float *x, int incx, float *y, int incy=1)
{ cblas_saxpy(n, alpha, x, incx, y, incy); }
inline void add_scaled(int n, float alpha, const float *x, float *y, int incy=1)
{ cblas_saxpy(n, alpha, x, 1, y, incy); }
inline void add_scaled(int n, double alpha, const double *x, int incx, double *y, int incy=1)
{ cblas_daxpy(n, alpha, x, incx, y, incy); }
inline void add_scaled(int n, double alpha, const double *x, double *y, int incy=1)
{ cblas_daxpy(n, alpha, x, 1, y, incy); }
// scale (x=alpha*x)
inline void scale(int n, float alpha, float *x, int incx=1)
{ cblas_sscal(n, alpha, x, incx); }
inline void scale(int n, double alpha, double *x, int incx=1)
{ cblas_dscal(n, alpha, x, incx); }
// gemv (y=alpha*A*x+beta*y, or using A^T)
// The matrix is always m*n; the size of x and y depend on if A is transposed.
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, float alpha, const float *A, int lda,
const float *x, int incx,
float beta, float *y, int incy=1)
{ cblas_sgemv(CblasColMajor, (CBLAS_TRANSPOSE)transpose, m, n, alpha, A, lda, x, incx, beta, y, incy); }
inline void multiply_matrix_vector(int m, int n, const float *A, const float *x, float *y, int incy=1) // y=A*x
{ cblas_sgemv(CblasColMajor, CblasNoTrans, m, n, 1.f, A, m, x, 1, 0.f, y, incy); }
inline void multiply_matrix_vector(Transpose transpose,
int m, int n, double alpha, const double *A, int lda,
const double *x, int incx, double beta, double *y, int incy=1)
{ cblas_dgemv(CblasColMajor, (CBLAS_TRANSPOSE)transpose, m, n, alpha, A, lda, x, incx, beta, y, incy); }
inline void multiply_matrix_vector(int m, int n, const double *A, const double *x, double *y, int incy=1) // y=A*x
{ cblas_dgemv(CblasColMajor, CblasNoTrans, m, n, 1., A, m, x, 1, 0., y, incy); }
// gemm (C=alpha*A*B+beta*C)
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, float alpha, const float *A, int lda,
const float *B, int ldb, float beta, float *C, int ldc)
{ cblas_sgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const float *A, const float *B, float *C)
{ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.f, A, m, B, k, 0.f, C, m); } // C=A*B
inline void multiply_matrix_matrix(Transpose transA, Transpose transB,
int m, int n, int k, double alpha, const double *A, int lda,
const double *B, int ldb, double beta, double *C, int ldc)
{ cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); }
inline void multiply_matrix_matrix(int m, int n, int k, const double *A, const double *B, double *C)
{ cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1., A, m, B, k, 0., C, m); } // C=A*B
inline void rank_one_update( int m, int n, double alpha, const double* x, const double* y, double* A )
{
cblas_dger( CblasColMajor, m, n, alpha, x, 1, y, 1, A, m );
}
} // namespace BLAS
#endif
// std::vector calls =========================================================
namespace BLAS{
template<class T>
inline void set_zero(std::vector<T> &x)
{ set_zero((int)x.size(), &x[0]); }
inline float dotf(const std::vector<float> &x, const std::vector<float> &y)
{ assert(x.size()==y.size()); return dotf((int)x.size(), &x[0], &y[0]); }
inline double dot(const std::vector<float> &x, const std::vector<float> &y)
{ assert(x.size()==y.size()); return dot((int)x.size(), &x[0], &y[0]); }
inline double dot(const std::vector<double> &x, const std::vector<double> &y)
{ assert(x.size()==y.size()); return dot((int)x.size(), &x[0], &y[0]); }
inline float norm2(const std::vector<float> &x)
{ return norm2((int)x.size(), &x[0]); }
inline double norm2(const std::vector<double> &x)
{ return norm2((int)x.size(), &x[0]); }
inline float abs_sum(const std::vector<float> &x)
{ return abs_sum((int)x.size(), &x[0]); }
inline double abs_sum(const std::vector<double> &x)
{ return abs_sum((int)x.size(), &x[0]); }
inline int index_abs_max(const std::vector<float> &x)
{ return index_abs_max((int)x.size(), &x[0]); }
inline int index_abs_max(const std::vector<double> &x)
{ return index_abs_max((int)x.size(), &x[0]); }
inline float abs_max(const std::vector<float> &x)
{ return abs_max((int)x.size(), &x[0]); }
inline double abs_max(const std::vector<double> &x)
{ return abs_max((int)x.size(), &x[0]); }
inline void swap(std::vector<float> &x, std::vector<float> &y)
{ assert(x.size()==y.size()); swap((int)x.size(), &x[0], &y[0]); }
inline void swap(std::vector<double> &x, std::vector<double> &y)
{ assert(x.size()==y.size()); swap((int)x.size(), &x[0], &y[0]); }
inline void copy(const std::vector<float> &x, std::vector<float> &y)
{ assert(x.size()==y.size()); copy((int)x.size(), &x[0], &y[0]); }
inline void copy(const std::vector<double> &x, std::vector<double> &y)
{ assert(x.size()==y.size()); copy((int)x.size(), &x[0], &y[0]); }
inline void add_scaled(float alpha, const std::vector<float> &x, std::vector<float> &y)
{ assert(x.size()==y.size()); add_scaled((int)x.size(), alpha, &x[0], &y[0]); }
inline void add_scaled(double alpha, const std::vector<double> &x, std::vector<double> &y)
{ assert(x.size()==y.size()); add_scaled((int)x.size(), alpha, &x[0], &y[0]); }
inline void scale(float alpha, std::vector<float> &x)
{ scale((int)x.size(), alpha, &x[0]); }
inline void scale(float alpha, std::vector<double> &x)
{ scale((int)x.size(), alpha, &x[0]); }
// I'm not sure if it makes sense to include level 2 or level 3 std::vector versions,
// since there isn't an STL matrix type...
} // namespace BLAS
#endif
| {
"alphanum_fraction": 0.5823533846,
"avg_line_length": 44.2938230384,
"ext": "h",
"hexsha": "e6d13d7f1651d29a225cd21a3b700d126f1a4f57",
"lang": "C",
"max_forks_count": 28,
"max_forks_repo_forks_event_max_datetime": "2022-03-24T14:59:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-05T18:41:58.000Z",
"max_forks_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "q349wang/eltopo",
"max_forks_repo_path": "common/blas_wrapper.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564",
"max_issues_repo_issues_event_max_datetime": "2020-10-20T12:13:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-04T07:35:15.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "q349wang/eltopo",
"max_issues_repo_path": "common/blas_wrapper.h",
"max_line_length": 183,
"max_stars_count": 91,
"max_stars_repo_head_hexsha": "a63a43d2a890c53f8e0c51034c46ce01ead86564",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "q349wang/eltopo",
"max_stars_repo_path": "common/blas_wrapper.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T14:59:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-18T14:44:16.000Z",
"num_tokens": 8422,
"size": 26532
} |
/* -*- mode: C; c-basic-offset: 4 -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2013, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Neil T. Dantam <ntd@gatech.edu>
* Georgia Tech Humanoid Robotics Lab
* Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>
*
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 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 <amino.h>
#include <cblas.h>
#include "reflex.h"
void x_fopen( const char *prefix, const char *suffix, size_t n, FILE *f[] ) {
for( size_t i = 0; i < n; i ++ ) {
char buf[512];
sprintf(buf,"%s%lu%s", prefix, i, suffix);
f[i] = fopen(buf, "w");
}
}
void x_write( double t, size_t n, double e[], FILE *f[7] ) {
for( size_t i = 0; i < n; i ++ ) {
fprintf(f[i], "%f %f\n", t, e[i] );
//fprintf(stdout, "%f %f\n", t, e[i] );
}
}
void e_corrupt( double theta_max, double x_max, const double e0[7], double e1[7] )
{
// rotation
double aa[4];
aa_vrand( 4, aa );
aa_la_normalize(3,aa);
aa[3] *= theta_max;
// translation
double v[3];
aa_vrand( 3, v );
for( size_t i = 0; i < 3; i ++ ) {
v[i] *= x_max;
}
// convert
double ec[7];
aa_tf_axang2quat(aa, ec+AA_TF_QUTR_Q);
AA_MEM_CPY(ec+AA_TF_QUTR_V, v, 3 );
// mul
aa_tf_qutr_mul( e0, ec, e1 );
}
rfx_tf_dx XX_true;
rfx_tf_dx XX_est;
rfx_tf_dx ZZ;
rfx_tf_dx UU;
double P[16*16] = {0};
double V[16*16] = {0};
double W[8*8] = {0};
double Pa[13*13] = {0};
double Wa[13*13] = {0};
double Va[13*13] = {0};
double Pb[13*13] = {0};
double Wb[7*7] = {0};
double Vb[13*13] = {0};
int main(void)
{
double dt = .01;
FILE *fout_z[7];
FILE *fout_x_true[7];
FILE *fout_x_est[7];
FILE *fout_dx_true[6];
FILE *fout_dx_est[6];
// state
memset(&XX_true,0,sizeof(XX_true));
memset(&XX_est,0,sizeof(XX_est));
memset(&ZZ,0,sizeof(ZZ));
memset(&UU,0,sizeof(UU));
aa_la_diag( 16, P, 1.0 );
aa_la_diag( 8, W, 1.0 );
aa_la_diag( 16, V, 1.0e-2 );
for( size_t i = 0; i < 8; i ++ ) {
AA_MATREF(V,16, i, 8+i ) = 1e-2;
AA_MATREF(V,16, 8+i, i ) = 1e-2;
}
aa_la_diag( 13, Pb, 1 );
aa_la_diag( 7, Wb, dt*5e-1 );
aa_la_diag( 13, Pa, 1.0e-2 );
aa_la_diag( 13, Wa, 1.0 );
aa_la_diag( 13, Va, 1.0e2 );
// files
x_fopen("xtrue", ".dat", 7,fout_x_true);
x_fopen("z", ".dat", 7,fout_z);
x_fopen("xest", ".dat", 7,fout_x_est);
x_fopen("dx_true", ".dat", 6,fout_dx_true);
x_fopen("dx_est", ".dat", 6,fout_dx_est);
memcpy(XX_true.tf.r.data, aa_tf_quat_ident, 4*sizeof(XX_true.tf.r.data[0]));
memcpy(XX_est.tf.r.data, aa_tf_quat_ident, 4*sizeof(XX_true.tf.r.data[0]));
for( double t = 0.0; t < 10.0; t += dt ) {
fprintf(stderr, "t: %f, ", t );
// pristine velocity
double dx[6] = {cos(t*M_PI / 1), 0, 0,
0, 0, sin(t*M_PI / 1)};
AA_MEM_CPY(XX_true.dx.data, dx, 6);
// integrate true
{
double e_next[7];
aa_tf_qutr_svel(XX_true.tf.data, XX_true.dx.data, dt, e_next );
memcpy( XX_true.tf.data, e_next, sizeof(e_next) );
}
// corrupt measurement
e_corrupt( 10*M_PI/180, 7e-2, XX_true.tf.data, ZZ.tf.data );
// filter
aa_tick("filter time: ");
double S[8];
double Sz[8];
double dS_est[8];
double dS_true[8];
//double dE_est[7];
aa_tf_qutr2duqu( XX_est.tf.data, S);
aa_tf_qutr2duqu( ZZ.tf.data, Sz);
aa_tf_duqu_vel2diff( S, XX_est.dx.data, dS_est );
aa_tf_duqu_vel2diff( S, XX_true.dx.data, dS_true );
//aa_tf_qutr_vel2diff( XX_est.tf.data, XX_est.dx.data, dE_est );
/* rfx_lqg_duqu_predict( dt, S, dS_est, P, V ); */
/* rfx_lqg_duqu_correct( 1, */
/* S, dS_est, */
/* Sz, /\*ZZ.dx.data, *\/ */
/* P, W ); */
/* aa_tf_duqu_diff2vel( S, dS_est, XX_est.dx.data ); */
/* aa_tf_duqu2qutr( S, XX_est.tf.data); */
rfx_lqg_qutr_process_noise( dt, 1, 1, XX_est.tf.data, Vb );
rfx_lqg_qutr_predict( dt, XX_est.tf.data, XX_est.dx.data, Pb, Vb );
rfx_lqg_qutr_correct( 1,
XX_est.tf.data, XX_est.dx.data,
ZZ.tf.data,
Pb, Wb );
//aa_tf_qutr_diff2vel( XX_est.tf.data, dE_est, XX_est.dx.data );
//rfx_tf_filter_update_work( dt, XX_est.tf.data, UU.tf.data, ZZ.tf.data, Pa, Va, Wa );
aa_tock();
//printf("--\n");
//printf("dS_true: "); aa_dump_vec( stdout, dS_true, 8 );
//printf("dS_est: "); aa_dump_vec( stdout, dS_est, 8 );
//aa_dump_mat( stdout, P, 16, 16 );
//return 0;
// print
x_write( t, 7, XX_true.tf.data, fout_x_true );
x_write( t, 6, XX_true.dx.data, fout_dx_true );
x_write( t, 7, XX_est.tf.data, fout_x_est );
x_write( t, 6, XX_est.dx.data, fout_dx_est );
x_write( t, 7, ZZ.tf.data, fout_z );
}
}
| {
"alphanum_fraction": 0.5772283272,
"avg_line_length": 28.8634361233,
"ext": "c",
"hexsha": "8b7d350bee7de36b15bbc23b5951161784593002",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-05T12:58:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-23T18:09:25.000Z",
"max_forks_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "golems/reflex",
"max_forks_repo_path": "src/test/test-tf-filter.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"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": "golems/reflex",
"max_issues_repo_path": "src/test/test-tf-filter.c",
"max_line_length": 94,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "golems/reflex",
"max_stars_repo_path": "src/test/test-tf-filter.c",
"max_stars_repo_stars_event_max_datetime": "2021-03-29T10:12:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-29T02:12:02.000Z",
"num_tokens": 2089,
"size": 6552
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gsl/gsl_sf_trig.h>
#include <Accelerate/Accelerate.h>
#include "SE_trans.h"
#include "sigma.h"
#define ALPHA 0.99
#define DOMD 3.14
double* AllocVec(int dim)
{
double* vec;
vec = (double*)calloc(dim, sizeof(double));
/* Check memory */
if (vec == NULL) {
free(vec);
fprintf(stderr,"Vector was not allocated! \n");
exit(1);
}
return vec; /* Return the first address of the allocated memory */
}
void FreeVec(double* v)
{
free(v);
}
double f(double t)
{
return 0.25 * ((1+t) * log1p(t) + (1-t) * log1p(-t) - 2 * M_LN2) / M_LN2;
}
double G(double x)
{
return 0.25 * x * SE_trans_div(-1, 1, x) / M_LN2;
}
double Fapp(double* p, double t, int m)
{
double h = sqrt(M_PI*DOMD / (ALPHA*m));
int j;
double sum = 0;
for (j = -m; j <= m; j++) {
sum += p[j+m] * gsl_sf_sinc((SE_trans_inv(-1, 1, t) - j*h) / h);
}
return sum;
}
double eta(double x)
{
return 0.5*(1 + x);
}
int main()
{
int i, j;
int n, N;
double t, h;
double err, maxerr;
double Iast;
clock_t start, end;
double time;
double *J, *g, *c;
int STEP = 1000;
for (n = 3; n <= 180; n += 6) {
start = clock();
N = 2*n+1;
J = AllocVec(N*N);
g = AllocVec(N);
c = AllocVec(N);
h = sqrt(M_PI*DOMD / (ALPHA*n));
Iast = 0;
for (i = -n; i <= n; i++) {
Iast += G(i*h);
}
Iast *= h;
for (i = -n; i <= n; i++) {
for (j = -n; j <= n; j++) {
J[(i+n)*N + (j+n)] = 0.5 + (double)sigma_orig[1000 + (i - j)];
}
g[(i+n)] = G(i*h) - 0.5 * Iast * SE_trans_div(-1, 1, i*h);
}
/* c = h J g */
cblas_dgemv(CblasRowMajor, CblasNoTrans, N, N, h, J, N, g, 1, 0.0, c, 1);
maxerr = 0;
for (i = - STEP + 1; i <= STEP - 1; i++) {
t = (double)i / (double)(STEP);
err = fabs(f(t) - Fapp(c, t, n) - Iast*eta(t));
maxerr = fmax(err, maxerr);
}
end = clock();
time = (double)(end - start) / CLOCKS_PER_SEC;
printf("%d\t%e\t%e\n", n, err, time);
FreeVec(J);
FreeVec(g);
FreeVec(c);
}
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.512229539,
"avg_line_length": 17.7166666667,
"ext": "c",
"hexsha": "ec7e1b977266ba0a4d3d43d1442a197ea2d89298",
"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": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okayamat/sinc-indef",
"max_forks_repo_path": "Ex2SE2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9",
"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": "okayamat/sinc-indef",
"max_issues_repo_path": "Ex2SE2.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okayamat/sinc-indef",
"max_stars_repo_path": "Ex2SE2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 804,
"size": 2126
} |
#include "quac_p.h"
#include "quac.h"
#include "operators_p.h"
#include "operators.h"
#include <petsc.h>
int petsc_initialized = 0;
int nid;
int np;
/*
* QuaC_initialize initializes petsc, gets each core's nid, and lets the
* rest of the program know that it has been initialized.
* Inputs:
* int argc, char **args - command line input, for PETSc
*/
void QuaC_initialize(int argc,char **args){
/* Initialize Petsc */
PetscInitialize(&argc,&args,(char*)0,NULL);
#if !defined(PETSC_USE_COMPLEX)
SETERRQ(PETSC_COMM_WORLD,1,"This example requires complex numbers");
#endif
/* Get core's id */
MPI_Comm_rank(PETSC_COMM_WORLD,&nid);
/* Get number of processors */
MPI_Comm_size(PETSC_COMM_WORLD,&np);
petsc_initialized = 1;
PetscLogStageRegister("Pre-solve",&pre_solve_stage);
PetscLogStageRegister("Solve",&solve_stage);
PetscLogStageRegister("Post-solve",&post_solve_stage);
/* Register events */
PetscClassIdRegister("QuaC Class",&quac_class_id);
PetscLogEventRegister("add_lin",quac_class_id,&add_lin_event);
PetscLogEventRegister("add_to_ham",quac_class_id,&add_to_ham_event);
PetscLogEventRegister("add_lin_recovery",quac_class_id,&add_lin_recovery_event);
PetscLogEventRegister("_qc_event",quac_class_id,&_qc_event_function_event);
PetscLogEventRegister("_qc_postevent",quac_class_id,&_qc_postevent_function_event);
PetscLogEventRegister("_apply_gate",quac_class_id,&_apply_gate_event);
PetscLogStagePush(pre_solve_stage);
}
/*
* QuaC_clear clears the internal state of many of QuaC's
* variables so that multiple systems can be run in one file.
*/
void QuaC_clear(){
int i;
/* Destroy Matrix */
MatDestroy(&full_A);
MatDestroy(&ham_A);
MatDestroy(&full_stiff_A);
MatDestroy(&ham_stiff_A);
for (i=0;i<_num_time_dep;i++){
MatDestroy(&_time_dep_list[i].mat);
}
//stab_added = 0;
_print_dense_ham = 0;
_num_time_dep = 0;
op_initialized = 0;
}
/*
* QuaC_finalize finalizes petsc and destroys full_A.
* The user is responsible for freeing all of the objects
* using destroy_*
*/
void QuaC_finalize(){
int i;
/* Destroy Matrix */
MatDestroy(&full_A);
MatDestroy(&ham_A);
MatDestroy(&full_stiff_A);
MatDestroy(&ham_stiff_A);
for (i=0;i<_num_time_dep;i++){
MatDestroy(&_time_dep_list[i].mat);
}
/* Finalize Petsc */
PetscLogStagePop();
PetscFinalize();
return;
}
/*
* destroy_op frees the memory from op.
* Inputs:
* operator *op - pointer to operator to be freed
*/
void destroy_op(operator *op){
free((*op)->dag);
free((*op)->n);
free(*op);
}
/*
* destroy_vec frees the memory from a vec.
* Inputs:
* vec_op *op - pointer to vec_op to be freed
*/
void destroy_vec(vec_op *op){
int num_levels,i;
num_levels = (*op)[0]->my_levels;
/* Free each up in the array */
for (i=0;i<num_levels;i++){
free((*op)[i]);
}
free(*op);
}
| {
"alphanum_fraction": 0.7059026579,
"avg_line_length": 23.7459016393,
"ext": "c",
"hexsha": "517c66e775aaf7c3780dc9d57ba31c92f3b58f8c",
"lang": "C",
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-02-24T20:07:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-03-13T15:03:11.000Z",
"max_forks_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sgulania/QuaC",
"max_forks_repo_path": "src/quac.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337",
"max_issues_repo_issues_event_max_datetime": "2020-09-03T14:21:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-17T15:16:22.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sgulania/QuaC",
"max_issues_repo_path": "src/quac.c",
"max_line_length": 85,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "2b47b378c6b5b823a094e9af79f7cb8eb39dd337",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sgulania/QuaC",
"max_stars_repo_path": "src/quac.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-28T10:27:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-18T02:11:04.000Z",
"num_tokens": 806,
"size": 2897
} |
/******************************************************************************
*
* IMD -- The ITAP Molecular Dynamics Program
*
* Copyright 1996-2007 Institute for Theoretical and Applied Physics,
* University of Stuttgart, D-70550 Stuttgart
*
******************************************************************************/
/******************************************************************************
*
* imd.h -- Header file for all modules of IMD
*
******************************************************************************/
/******************************************************************************
* $Revision$
* $Date$
******************************************************************************/
/* C stuff */
#ifdef MEMALIGN
#define _XOPEN_SOURCE 600
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
//MYMOD
#include <stdbool.h>
#include "nn_interpol/nn.h"
#include "nn_interpol/delaunay.h"
//ENDOF MYMOD
//
//
#ifdef CBE
#define USE_WALLTIME
#endif
/* support for timers */
#ifndef MPI
#if defined(USE_RUSAGE) || defined(USE_WALLTIME)
#include <sys/time.h>
#include <sys/resource.h>
#else
#include <sys/times.h>
#include <sys/types.h>
#endif
#endif
/* Machine specific headers */
#if defined(MPI) || defined(NEB)
#include <mpi.h>
#ifdef MPE
#include <mpe.h>
#endif
#endif
#ifdef OMP
#include <omp.h>
#endif
/* FFT for diffraction patterns */
#ifdef DIFFPAT
#include <fftw3.h>
#endif
/* IMD version */
#include "version.h"
/* Configuration */
#include "config.h"
/* Data types */
#include "types.h"
/* Some constants */
#include "constants.h"
/* Some makros */
#include "makros.h"
/* Function Prototypes */
#include "prototypes.h"
/* Global Variables */
#include "globals.h"
/************
* MY MOD *
************/
#include <complex.h>
#ifdef COLRAD
// #include <gsl/gsl_sf_expint.h> //FUER EXPONENTIAL INTEGRAL
#include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */
#include <nvector/nvector_serial.h> /* serial N_Vector types, fcts., macros */
#include <sunmatrix/sunmatrix_dense.h>
//#include <sundials/sundials_types.h> /* definition of type realtype */
#include "sunnonlinsol/sunnonlinsol_newton.h"
#define LAPACK /* LAPACK SOLVER MULTO BENE*/
#ifdef LAPACK
#include <sunlinsol/sunlinsol_lapackdense.h>
#else
#include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver */
#endif
#endif //ifdef COLRAD
| {
"alphanum_fraction": 0.5596658711,
"avg_line_length": 22.0526315789,
"ext": "h",
"hexsha": "dccb87852489e06a4ebb83a027da20d65ca4d290",
"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": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fmqeisfeld/IMD",
"max_forks_repo_path": "imd.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"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": "fmqeisfeld/IMD",
"max_issues_repo_path": "imd.h",
"max_line_length": 81,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "fmqeisfeld/IMD",
"max_stars_repo_path": "imd.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z",
"num_tokens": 561,
"size": 2514
} |
/* block/gsl_block_uint.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_BLOCK_UINT_H__
#define __GSL_BLOCK_UINT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
struct gsl_block_uint_struct
{
size_t size;
unsigned int *data;
};
typedef struct gsl_block_uint_struct gsl_block_uint;
GSL_FUN gsl_block_uint *gsl_block_uint_alloc (const size_t n);
GSL_FUN gsl_block_uint *gsl_block_uint_calloc (const size_t n);
GSL_FUN void gsl_block_uint_free (gsl_block_uint * b);
GSL_FUN int gsl_block_uint_fread (FILE * stream, gsl_block_uint * b);
GSL_FUN int gsl_block_uint_fwrite (FILE * stream, const gsl_block_uint * b);
GSL_FUN int gsl_block_uint_fscanf (FILE * stream, gsl_block_uint * b);
GSL_FUN int gsl_block_uint_fprintf (FILE * stream, const gsl_block_uint * b, const char *format);
GSL_FUN int gsl_block_uint_raw_fread (FILE * stream, unsigned int * b, const size_t n, const size_t stride);
GSL_FUN int gsl_block_uint_raw_fwrite (FILE * stream, const unsigned int * b, const size_t n, const size_t stride);
GSL_FUN int gsl_block_uint_raw_fscanf (FILE * stream, unsigned int * b, const size_t n, const size_t stride);
GSL_FUN int gsl_block_uint_raw_fprintf (FILE * stream, const unsigned int * b, const size_t n, const size_t stride, const char *format);
GSL_FUN size_t gsl_block_uint_size (const gsl_block_uint * b);
GSL_FUN unsigned int * gsl_block_uint_data (const gsl_block_uint * b);
__END_DECLS
#endif /* __GSL_BLOCK_UINT_H__ */
| {
"alphanum_fraction": 0.7443636364,
"avg_line_length": 36.1842105263,
"ext": "h",
"hexsha": "4d1cec7eb619890bf5e098bf3eb136157e96ef4c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_block_uint.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_block_uint.h",
"max_line_length": 137,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_block_uint.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 708,
"size": 2750
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <gsl/gsl>
namespace onnxruntime {
// Inspired by Fekir's Blog https://fekir.info/post/span-the-missing-constructor/
// Used under MIT license
// Use AsSpan for less typing on any container including initializer list to create a span
// (unnamed, untyped initializer list does not automatically convert to gsl::span).
// {1, 2, 3} as such does not have a type
// (see https://scottmeyers.blogspot.com/2014/03/if-braced-initializers-have-no-type-why.html)
//
// Example: AsSpan({1, 2, 3}) results in gsl::span<const int>
//
// The above would deduce to std::initializer_list<int> and the result is gsl::span<const int>
//
// AsSpan<int64_t>({1, 2, 3}) produces gsl::span<const int64_t>
//
// We can also do std::array<int64_t, 3>{1, 2, 3} that can be automatically converted to span
// without memory allocation.
//
// If type conversion is not required, then for C++17 std::array template parameters are
// auto-deduced. Example: std::array{1, 2, 3}.
// We are aiming at not allocating memory dynamically.
namespace details {
template <class P>
constexpr auto AsSpanImpl(P* p, size_t s) {
return gsl::span<P>(p, s);
}
} // namespace details
template <class C>
constexpr auto AsSpan(C& c) {
return details::AsSpanImpl(c.data(), c.size());
}
template <class C>
constexpr auto AsSpan(const C& c) {
return details::AsSpanImpl(c.data(), c.size());
}
template <class C>
constexpr auto AsSpan(C&& c) {
return details::AsSpanImpl(c.data(), c.size());
}
template <class T>
constexpr auto AsSpan(std::initializer_list<T> c) {
return details::AsSpanImpl(c.begin(), c.size());
}
template <class T, size_t N>
constexpr auto AsSpan(T (&arr)[N]) {
return details::AsSpanImpl(arr, N);
}
template <class T, size_t N>
constexpr auto AsSpan(const T (&arr)[N]) {
return details::AsSpanImpl(arr, N);
}
} | {
"alphanum_fraction": 0.7030522504,
"avg_line_length": 28.8507462687,
"ext": "h",
"hexsha": "998fc6e71dcbb814ca642ab8f3177b93aad88297",
"lang": "C",
"max_forks_count": 140,
"max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z",
"max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SiriusKY/onnxruntime",
"max_forks_repo_path": "include/onnxruntime/core/common/span_utils.h",
"max_issues_count": 440,
"max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SiriusKY/onnxruntime",
"max_issues_repo_path": "include/onnxruntime/core/common/span_utils.h",
"max_line_length": 94,
"max_stars_count": 669,
"max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SiriusKY/onnxruntime",
"max_stars_repo_path": "include/onnxruntime/core/common/span_utils.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z",
"num_tokens": 533,
"size": 1933
} |
/* multilarge_nlinear/gsl_multilarge_nlinear.h
*
* Copyright (C) 2015, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MULTILARGE_NLINEAR_H__
#define __GSL_MULTILARGE_NLINEAR_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_blas.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 enum
{
GSL_MULTILARGE_NLINEAR_FWDIFF,
GSL_MULTILARGE_NLINEAR_CTRDIFF
} gsl_multilarge_nlinear_fdtype;
/* Definition of vector-valued functions and gradient with parameters
based on gsl_vector */
typedef struct
{
int (* f) (const gsl_vector * x, void * params, gsl_vector * f);
int (* df) (CBLAS_TRANSPOSE_t TransJ, const gsl_vector * x,
const gsl_vector * u, void * params, gsl_vector * v,
gsl_matrix * JTJ);
int (* fvv) (const gsl_vector * x, const gsl_vector * v, void * params,
gsl_vector * fvv);
size_t n; /* number of functions */
size_t p; /* number of independent variables */
void * params; /* user parameters */
size_t nevalf; /* number of function evaluations */
size_t nevaldfu; /* number of Jacobian matrix-vector evaluations */
size_t nevaldf2; /* number of Jacobian J^T J evaluations */
size_t nevalfvv; /* number of fvv evaluations */
} gsl_multilarge_nlinear_fdf;
/* trust region subproblem method */
typedef struct
{
const char *name;
void * (*alloc) (const void * params, const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*preloop) (const void * vtrust_state, void * vstate);
int (*step) (const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate);
int (*preduction) (const void * vtrust_state, const gsl_vector * dx,
double * pred, void * vstate);
void (*free) (void * vstate);
} gsl_multilarge_nlinear_trs;
/* scaling matrix specification */
typedef struct
{
const char *name;
int (*init) (const gsl_matrix * JTJ, gsl_vector * diag);
int (*update) (const gsl_matrix * JTJ, gsl_vector * diag);
} gsl_multilarge_nlinear_scale;
/*
* linear least squares solvers - there are three steps to
* solving a least squares problem using a direct method:
*
* 1. init: called once per iteration when a new Jacobian matrix
* is required; form normal equations matrix J^T J
* 2. presolve: called each time a new LM parameter value mu is available;
* used for cholesky method in order to factor
* the (J^T J + mu D^T D) matrix
* 3. solve: solve the least square system for a given rhs
*/
typedef struct
{
const char *name;
void * (*alloc) (const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*presolve) (const double mu, const void * vtrust_state, void * vstate);
int (*solve) (const gsl_vector * g, gsl_vector * x,
const void * vtrust_state, void * vstate);
int (*rcond) (double * rcond, const gsl_matrix * JTJ, void * vstate);
int (*covar) (const gsl_matrix * JTJ, gsl_matrix * covar, void * vstate);
void (*free) (void * vstate);
} gsl_multilarge_nlinear_solver;
/* tunable parameters */
typedef struct
{
const gsl_multilarge_nlinear_trs *trs; /* trust region subproblem method */
const gsl_multilarge_nlinear_scale *scale; /* scaling method */
const gsl_multilarge_nlinear_solver *solver; /* solver method */
gsl_multilarge_nlinear_fdtype fdtype; /* finite difference method */
double factor_up; /* factor for increasing trust radius */
double factor_down; /* factor for decreasing trust radius */
double avmax; /* max allowed |a|/|v| */
double h_df; /* step size for finite difference Jacobian */
double h_fvv; /* step size for finite difference fvv */
size_t max_iter; /* maximum iterations for trs method */
double tol; /* tolerance for solving trs */
} gsl_multilarge_nlinear_parameters;
typedef struct
{
const char *name;
void * (*alloc) (const gsl_multilarge_nlinear_parameters * params,
const size_t n, const size_t p);
int (*init) (void * state, const gsl_vector * wts,
gsl_multilarge_nlinear_fdf * fdf, const gsl_vector * x,
gsl_vector * f, gsl_vector * g, gsl_matrix * JTJ);
int (*iterate) (void * state, const gsl_vector * wts,
gsl_multilarge_nlinear_fdf * fdf, gsl_vector * x,
gsl_vector * f, gsl_vector * g, gsl_matrix * JTJ,
gsl_vector * dx);
int (*rcond) (double * rcond, const gsl_matrix * JTJ, void * state);
int (*covar) (const gsl_matrix * JTJ, gsl_matrix * covar, void * state);
double (*avratio) (void * state);
void (*free) (void * state);
} gsl_multilarge_nlinear_type;
/* current state passed to low-level trust region algorithms */
typedef struct
{
const gsl_vector * x; /* parameter values x */
const gsl_vector * f; /* residual vector f(x) */
const gsl_vector * g; /* gradient J^T f */
const gsl_matrix * JTJ; /* matrix J^T J */
const gsl_vector * diag; /* scaling matrix D */
const gsl_vector * sqrt_wts; /* sqrt(diag(W)) or NULL for unweighted */
const double *mu; /* LM parameter */
const gsl_multilarge_nlinear_parameters * params;
void *solver_state; /* workspace for direct least squares solver */
gsl_multilarge_nlinear_fdf * fdf;
double *avratio; /* |a| / |v| */
} gsl_multilarge_nlinear_trust_state;
typedef struct
{
const gsl_multilarge_nlinear_type * type;
gsl_multilarge_nlinear_fdf * fdf ;
gsl_vector * x; /* parameter values x */
gsl_vector * f; /* residual vector f(x) */
gsl_vector * dx; /* step dx */
gsl_vector * g; /* gradient J^T f */
gsl_matrix * JTJ; /* matrix J^T J */
gsl_vector * sqrt_wts_work; /* sqrt(W) */
gsl_vector * sqrt_wts; /* ptr to sqrt_wts_work, or NULL if not using weights */
size_t n; /* number of residuals */
size_t p; /* number of parameters */
size_t niter; /* number of iterations performed */
gsl_multilarge_nlinear_parameters params;
void *state;
} gsl_multilarge_nlinear_workspace;
GSL_FUN gsl_multilarge_nlinear_workspace *
gsl_multilarge_nlinear_alloc (const gsl_multilarge_nlinear_type * T,
const gsl_multilarge_nlinear_parameters * params,
size_t n, size_t p);
GSL_FUN void gsl_multilarge_nlinear_free (gsl_multilarge_nlinear_workspace * w);
GSL_FUN gsl_multilarge_nlinear_parameters gsl_multilarge_nlinear_default_parameters(void);
GSL_FUN int
gsl_multilarge_nlinear_init (const gsl_vector * x,
gsl_multilarge_nlinear_fdf * fdf,
gsl_multilarge_nlinear_workspace * w);
GSL_FUN int gsl_multilarge_nlinear_winit (const gsl_vector * x,
const gsl_vector * wts,
gsl_multilarge_nlinear_fdf * fdf,
gsl_multilarge_nlinear_workspace * w);
GSL_FUN int
gsl_multilarge_nlinear_iterate (gsl_multilarge_nlinear_workspace * w);
GSL_FUN double
gsl_multilarge_nlinear_avratio (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN int
gsl_multilarge_nlinear_rcond (double * rcond, const gsl_multilarge_nlinear_workspace * w);
GSL_FUN int
gsl_multilarge_nlinear_covar (gsl_matrix * covar, gsl_multilarge_nlinear_workspace * w);
GSL_FUN int
gsl_multilarge_nlinear_driver (const size_t maxiter,
const double xtol,
const double gtol,
const double ftol,
void (*callback)(const size_t iter, void *params,
const gsl_multilarge_nlinear_workspace *w),
void *callback_params,
int *info,
gsl_multilarge_nlinear_workspace * w);
GSL_FUN const char *
gsl_multilarge_nlinear_name (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN gsl_vector *
gsl_multilarge_nlinear_position (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN gsl_vector *
gsl_multilarge_nlinear_residual (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN gsl_vector *
gsl_multilarge_nlinear_step (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN size_t
gsl_multilarge_nlinear_niter (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN const char *
gsl_multilarge_nlinear_trs_name (const gsl_multilarge_nlinear_workspace * w);
GSL_FUN int gsl_multilarge_nlinear_eval_f(gsl_multilarge_nlinear_fdf *fdf,
const gsl_vector *x,
const gsl_vector *swts,
gsl_vector *y);
GSL_FUN int
gsl_multilarge_nlinear_eval_df(const CBLAS_TRANSPOSE_t TransJ,
const gsl_vector *x,
const gsl_vector *f,
const gsl_vector *u,
const gsl_vector *swts,
const double h,
const gsl_multilarge_nlinear_fdtype fdtype,
gsl_multilarge_nlinear_fdf *fdf,
gsl_vector *v,
gsl_matrix *JTJ,
gsl_vector *work);
GSL_FUN int
gsl_multilarge_nlinear_eval_fvv(const double h,
const gsl_vector *x,
const gsl_vector *v,
const gsl_vector *f,
const gsl_vector *swts,
gsl_multilarge_nlinear_fdf *fdf,
gsl_vector *yvv,
gsl_vector *work);
/* convergence.c */
GSL_FUN int
gsl_multilarge_nlinear_test (const double xtol, const double gtol,
const double ftol, int *info,
const gsl_multilarge_nlinear_workspace * w);
/* fdjac.c */
GSL_FUN int
gsl_multilarge_nlinear_df(const double h, const gsl_multilarge_nlinear_fdtype fdtype,
const gsl_vector *x, const gsl_vector *wts,
gsl_multilarge_nlinear_fdf *fdf,
const gsl_vector *f, gsl_matrix *J, gsl_vector *work);
/* fdfvv.c */
GSL_FUN int
gsl_multilarge_nlinear_fdfvv(const double h, const gsl_vector *x, const gsl_vector *v,
const gsl_vector *f, const gsl_matrix *J,
const gsl_vector *swts, gsl_multilarge_nlinear_fdf *fdf,
gsl_vector *fvv, gsl_vector *work);
/* top-level algorithms */
GSL_VAR const gsl_multilarge_nlinear_type * gsl_multilarge_nlinear_trust;
/* trust region subproblem methods */
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_lm;
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_lmaccel;
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_dogleg;
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_ddogleg;
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_subspace2D;
GSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_cgst;
/* scaling matrix strategies */
GSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_levenberg;
GSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_marquardt;
GSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_more;
/* linear solvers */
GSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_cholesky;
GSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_mcholesky;
GSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_none;
__END_DECLS
#endif /* __GSL_MULTILARGE_NLINEAR_H__ */
| {
"alphanum_fraction": 0.6509713777,
"avg_line_length": 41.4953846154,
"ext": "h",
"hexsha": "bdad1b23885bccd94352aff2f81263dc7cc4c85c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h",
"max_line_length": 93,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 3292,
"size": 13486
} |
/* multiroots/hybrid.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_linalg.h>
#include "dogleg.c"
typedef struct
{
size_t iter;
size_t ncfail;
size_t ncsuc;
size_t nslow1;
size_t nslow2;
double fnorm;
double delta;
gsl_matrix *J;
gsl_matrix *q;
gsl_matrix *r;
gsl_vector *tau;
gsl_vector *diag;
gsl_vector *qtf;
gsl_vector *newton;
gsl_vector *gradient;
gsl_vector *x_trial;
gsl_vector *f_trial;
gsl_vector *df;
gsl_vector *qtdf;
gsl_vector *rdx;
gsl_vector *w;
gsl_vector *v;
}
hybrid_state_t;
static int hybrid_alloc (void *vstate, size_t n);
static int hybrid_set (void *vstate, gsl_multiroot_function * func,
gsl_vector * x, gsl_vector * f, gsl_vector * dx);
static int hybrids_set (void *vstate, gsl_multiroot_function * func,
gsl_vector * x, gsl_vector * f, gsl_vector * dx);
static int hybrid_set_impl (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx, int scale);
static int hybrid_iterate (void *vstate, gsl_multiroot_function * func,
gsl_vector * x, gsl_vector * f, gsl_vector * dx);
static void hybrid_free (void *vstate);
static int hybrid_iterate_impl (void *vstate, gsl_multiroot_function * func,
gsl_vector * x, gsl_vector * f, gsl_vector * dx,
int scale);
static int
hybrid_alloc (void *vstate, size_t n)
{
hybrid_state_t *state = (hybrid_state_t *) vstate;
gsl_matrix *J, *q, *r;
gsl_vector *tau, *diag, *qtf, *newton, *gradient, *x_trial, *f_trial,
*df, *qtdf, *rdx, *w, *v;
J = gsl_matrix_calloc (n, n);
if (J == 0)
{
GSL_ERROR ("failed to allocate space for J", GSL_ENOMEM);
}
state->J = J;
q = gsl_matrix_calloc (n, n);
if (q == 0)
{
gsl_matrix_free (J);
GSL_ERROR ("failed to allocate space for q", GSL_ENOMEM);
}
state->q = q;
r = gsl_matrix_calloc (n, n);
if (r == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
GSL_ERROR ("failed to allocate space for r", GSL_ENOMEM);
}
state->r = r;
tau = gsl_vector_calloc (n);
if (tau == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
GSL_ERROR ("failed to allocate space for tau", GSL_ENOMEM);
}
state->tau = tau;
diag = gsl_vector_calloc (n);
if (diag == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
GSL_ERROR ("failed to allocate space for diag", GSL_ENOMEM);
}
state->diag = diag;
qtf = gsl_vector_calloc (n);
if (qtf == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
GSL_ERROR ("failed to allocate space for qtf", GSL_ENOMEM);
}
state->qtf = qtf;
newton = gsl_vector_calloc (n);
if (newton == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
GSL_ERROR ("failed to allocate space for newton", GSL_ENOMEM);
}
state->newton = newton;
gradient = gsl_vector_calloc (n);
if (gradient == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
GSL_ERROR ("failed to allocate space for gradient", GSL_ENOMEM);
}
state->gradient = gradient;
x_trial = gsl_vector_calloc (n);
if (x_trial == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
GSL_ERROR ("failed to allocate space for x_trial", GSL_ENOMEM);
}
state->x_trial = x_trial;
f_trial = gsl_vector_calloc (n);
if (f_trial == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
GSL_ERROR ("failed to allocate space for f_trial", GSL_ENOMEM);
}
state->f_trial = f_trial;
df = gsl_vector_calloc (n);
if (df == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
gsl_vector_free (f_trial);
GSL_ERROR ("failed to allocate space for df", GSL_ENOMEM);
}
state->df = df;
qtdf = gsl_vector_calloc (n);
if (qtdf == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
gsl_vector_free (f_trial);
gsl_vector_free (df);
GSL_ERROR ("failed to allocate space for qtdf", GSL_ENOMEM);
}
state->qtdf = qtdf;
rdx = gsl_vector_calloc (n);
if (rdx == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
gsl_vector_free (f_trial);
gsl_vector_free (df);
gsl_vector_free (qtdf);
GSL_ERROR ("failed to allocate space for rdx", GSL_ENOMEM);
}
state->rdx = rdx;
w = gsl_vector_calloc (n);
if (w == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
gsl_vector_free (f_trial);
gsl_vector_free (df);
gsl_vector_free (qtdf);
gsl_vector_free (rdx);
GSL_ERROR ("failed to allocate space for w", GSL_ENOMEM);
}
state->w = w;
v = gsl_vector_calloc (n);
if (v == 0)
{
gsl_matrix_free (J);
gsl_matrix_free (q);
gsl_matrix_free (r);
gsl_vector_free (tau);
gsl_vector_free (diag);
gsl_vector_free (qtf);
gsl_vector_free (newton);
gsl_vector_free (gradient);
gsl_vector_free (x_trial);
gsl_vector_free (f_trial);
gsl_vector_free (df);
gsl_vector_free (qtdf);
gsl_vector_free (rdx);
gsl_vector_free (w);
GSL_ERROR ("failed to allocate space for v", GSL_ENOMEM);
}
state->v = v;
return GSL_SUCCESS;
}
static int
hybrid_set (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx)
{
int status = hybrid_set_impl (vstate, func, x, f, dx, 0);
return status;
}
static int
hybrids_set (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx)
{
int status = hybrid_set_impl (vstate, func, x, f, dx, 1);
return status;
}
static int
hybrid_set_impl (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx, int scale)
{
hybrid_state_t *state = (hybrid_state_t *) vstate;
gsl_matrix *J = state->J;
gsl_matrix *q = state->q;
gsl_matrix *r = state->r;
gsl_vector *tau = state->tau;
gsl_vector *diag = state->diag;
int status;
status = GSL_MULTIROOT_FN_EVAL (func, x, f);
if (status)
{
return status;
}
status = gsl_multiroot_fdjacobian (func, x, f, GSL_SQRT_DBL_EPSILON, J);
if (status)
{
return status;
}
state->iter = 1;
state->fnorm = enorm (f);
state->ncfail = 0;
state->ncsuc = 0;
state->nslow1 = 0;
state->nslow2 = 0;
gsl_vector_set_all (dx, 0.0);
/* Store column norms in diag */
if (scale)
compute_diag (J, diag);
else
gsl_vector_set_all (diag, 1.0);
/* Set delta to factor |D x| or to factor if |D x| is zero */
state->delta = compute_delta (diag, x);
/* Factorize J into QR decomposition */
status = gsl_linalg_QR_decomp (J, tau);
if (status)
{
return status;
}
status = gsl_linalg_QR_unpack (J, tau, q, r);
return status;
}
static int
hybrid_iterate (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx)
{
int status = hybrid_iterate_impl (vstate, func, x, f, dx, 0);
return status;
}
static int
hybrids_iterate (void *vstate, gsl_multiroot_function * func, gsl_vector * x,
gsl_vector * f, gsl_vector * dx)
{
int status = hybrid_iterate_impl (vstate, func, x, f, dx, 1);
return status;
}
static int
hybrid_iterate_impl (void *vstate, gsl_multiroot_function * func,
gsl_vector * x,
gsl_vector * f, gsl_vector * dx, int scale)
{
hybrid_state_t *state = (hybrid_state_t *) vstate;
const double fnorm = state->fnorm;
gsl_matrix *J = state->J;
gsl_matrix *q = state->q;
gsl_matrix *r = state->r;
gsl_vector *tau = state->tau;
gsl_vector *diag = state->diag;
gsl_vector *qtf = state->qtf;
gsl_vector *x_trial = state->x_trial;
gsl_vector *f_trial = state->f_trial;
gsl_vector *df = state->df;
gsl_vector *qtdf = state->qtdf;
gsl_vector *rdx = state->rdx;
gsl_vector *w = state->w;
gsl_vector *v = state->v;
double prered, actred;
double pnorm, fnorm1, fnorm1p;
double ratio;
double p1 = 0.1, p5 = 0.5, p001 = 0.001, p0001 = 0.0001;
/* Compute qtf = Q^T f */
compute_qtf (q, f, qtf);
/* Compute dogleg step */
dogleg (r, qtf, diag, state->delta, state->newton, state->gradient, dx);
/* Take a trial step */
compute_trial_step (x, dx, state->x_trial);
pnorm = scaled_enorm (diag, dx);
if (state->iter == 1)
{
if (pnorm < state->delta)
{
state->delta = pnorm;
}
}
/* Evaluate function at x + p */
{
int status = GSL_MULTIROOT_FN_EVAL (func, x_trial, f_trial);
if (status != GSL_SUCCESS)
{
return GSL_EBADFUNC;
}
}
/* Set df = f_trial - f */
compute_df (f_trial, f, df);
/* Compute the scaled actual reduction */
fnorm1 = enorm (f_trial);
actred = compute_actual_reduction (fnorm, fnorm1);
/* Compute rdx = R dx */
compute_rdx (r, dx, rdx);
/* Compute the scaled predicted reduction phi1p = |Q^T f + R dx| */
fnorm1p = enorm_sum (qtf, rdx);
prered = compute_predicted_reduction (fnorm, fnorm1p);
/* Compute the ratio of the actual to predicted reduction */
if (prered > 0)
{
ratio = actred / prered;
}
else
{
ratio = 0;
}
/* Update the step bound */
if (ratio < p1)
{
state->ncsuc = 0;
state->ncfail++;
state->delta *= p5;
}
else
{
state->ncfail = 0;
state->ncsuc++;
if (ratio >= p5 || state->ncsuc > 1)
state->delta = GSL_MAX (state->delta, pnorm / p5);
if (fabs (ratio - 1) <= p1)
state->delta = pnorm / p5;
}
/* Test for successful iteration */
if (ratio >= p0001)
{
gsl_vector_memcpy (x, x_trial);
gsl_vector_memcpy (f, f_trial);
state->fnorm = fnorm1;
state->iter++;
}
/* Determine the progress of the iteration */
state->nslow1++;
if (actred >= p001)
state->nslow1 = 0;
if (actred >= p1)
state->nslow2 = 0;
if (state->ncfail == 2)
{
gsl_multiroot_fdjacobian (func, x, f, GSL_SQRT_DBL_EPSILON, J);
state->nslow2++;
if (state->iter == 1)
{
if (scale)
compute_diag (J, diag);
state->delta = compute_delta (diag, x);
}
else
{
if (scale)
update_diag (J, diag);
}
/* Factorize J into QR decomposition */
gsl_linalg_QR_decomp (J, tau);
gsl_linalg_QR_unpack (J, tau, q, r);
return GSL_SUCCESS;
}
/* Compute qtdf = Q^T df, w = (Q^T df - R dx)/|dx|, v = D^2 dx/|dx| */
compute_qtf (q, df, qtdf);
compute_wv (qtdf, rdx, dx, diag, pnorm, w, v);
/* Rank-1 update of the jacobian Q'R' = Q(R + w v^T) */
gsl_linalg_QR_update (q, r, w, v);
/* No progress as measured by jacobian evaluations */
if (state->nslow2 == 5)
{
return GSL_ENOPROGJ;
}
/* No progress as measured by function evaluations */
if (state->nslow1 == 10)
{
return GSL_ENOPROG;
}
return GSL_SUCCESS;
}
static void
hybrid_free (void *vstate)
{
hybrid_state_t *state = (hybrid_state_t *) vstate;
gsl_vector_free (state->v);
gsl_vector_free (state->w);
gsl_vector_free (state->rdx);
gsl_vector_free (state->qtdf);
gsl_vector_free (state->df);
gsl_vector_free (state->f_trial);
gsl_vector_free (state->x_trial);
gsl_vector_free (state->gradient);
gsl_vector_free (state->newton);
gsl_vector_free (state->qtf);
gsl_vector_free (state->diag);
gsl_vector_free (state->tau);
gsl_matrix_free (state->r);
gsl_matrix_free (state->q);
gsl_matrix_free (state->J);
}
static const gsl_multiroot_fsolver_type hybrid_type = {
"hybrid", /* name */
sizeof (hybrid_state_t),
&hybrid_alloc,
&hybrid_set,
&hybrid_iterate,
&hybrid_free
};
static const gsl_multiroot_fsolver_type hybrids_type = {
"hybrids", /* name */
sizeof (hybrid_state_t),
&hybrid_alloc,
&hybrids_set,
&hybrids_iterate,
&hybrid_free
};
const gsl_multiroot_fsolver_type *gsl_multiroot_fsolver_hybrid = &hybrid_type;
const gsl_multiroot_fsolver_type *gsl_multiroot_fsolver_hybrids =
&hybrids_type;
| {
"alphanum_fraction": 0.6215510313,
"avg_line_length": 22.5218702866,
"ext": "c",
"hexsha": "654938237a3f1eb5e68128c28a082058906e5ed7",
"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/multiroots/hybrid.c",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/multiroots/hybrid.c",
"max_line_length": 88,
"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/multiroots/hybrid.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 4360,
"size": 14932
} |
// Sammlung verwendeter Funktionen
#include "global.h"
#include "targets.h"
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
#include <math.h>
#include <stdio.h>
#include "utility.h"
#include <string.h>
#include <time.h>
#include <omp.h>
void VVerlet_Step(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
void (*derivmethod) (double *y, double *ans, double t,int N)) {
double temp_vec[N], abl[N];
int i,j;
for (j = 0; j < DIM; j++ ) // heavy particle outside parallel region
{
v[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;
x[j] = x[j] + v[j] * MAXSTEPSIZE;
temp_vec[j] = x[j]; //temp_vec zur abl- berechnung
temp_vec[DIM + j] = v[j] * mass;
}
#pragma omp parallel for //parallelisiere über Osszillatoren
for (i= 0 ; i < OSSZI; i++)
{
for (j = 0; j < DIM; j++ )
{
v[DIM + j + i*DIM] = v[DIM + j + i*DIM] + 0.5 * a[DIM + j + i*DIM] * MAXSTEPSIZE;
x[DIM + j + i*DIM] = x[DIM + j + i*DIM] + v[DIM + j + i*DIM] * MAXSTEPSIZE;
temp_vec[2*DIM + i * 2*DIM + j] = x[DIM + j + i*DIM]; //temp_vec zur abl- berechnung
temp_vec[3*DIM + i * 2*DIM + j] = v[DIM + j + i*DIM] ;
}
}
derivmethod(temp_vec, abl, *t, N); //bilde Ableitung zu t
// gehe wieder in x-v Form für a
for (j = 0; j < DIM; j++ )
{
a[j] = abl[DIM + j] / mass;
v[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;
}
#pragma omp parallel for
for (i= 0 ; i < OSSZI; i++)
{
for (j = 0; j < DIM; j++ )
{
a[DIM +j + i*DIM] = abl[3*DIM + j + i * 2*DIM]/massq[i];
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a[DIM +j + i*DIM] * MAXSTEPSIZE;
}
}
//#pragma omp parallel for
//for (i= 0 ; i < N/2; i++)
//{
// v[i] = v[i] + 0.5 * a[i] * MAXSTEPSIZE;
//}
Update_Lattice_Position(lattice_position, x, LATTICE_SPACING);
*t = *t + MAXSTEPSIZE;
}
void VVerlet_Step_deriv(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
void (*derivmethod) (double *y, double *ans, double t,int N)) {
int i,j;
SETNUMTHREADS
double sum[DIM];
#pragma omp parallel // Values for Bath particles parralized///////////////////
{
int ID = omp_get_thread_num();
int MAX_THREADS = omp_get_num_threads();
if (MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
sum[j] = 0.0f; // prepare sum for heavy particle
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
sum[ID] = 0.0f; // prepare sum for heavy particle
}
#pragma omp for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * MAXSTEPSIZE; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * MAXSTEPSIZE; //xnext = x + vnext *dt
}
#pragma omp for // Values for Bath particles parralized
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for(j = 0; j < DIM; j++)
{ // Ableitung /
double a_temp = a[DIM + j + i*DIM] = - om * om * x[DIM + j + i*DIM]\
+ coup * x[j]; // dp_q/dt = -w^2 * q+ gamma * x
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a_temp * MAXSTEPSIZE; // Zweites Halbupdate ////
}
}
double private_sum[DIM];
double private_c[DIM] = {0.0,0.0}; // Kahan correction
double private_t[DIM] = {0.0,0.0};
double private_y[DIM] = {0.0,0.0};
for(j = 0; j < DIM; j++) // Values for heavy particle
{
private_sum[j] = 0.0; // JEder thread berechnet Partialsumme
}
#pragma omp for // berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for (j=0; j<DIM; j++)
{ // Kahan summation scheme
private_y[j] = coup * x[DIM + j + i*DIM]\
- pow(coup,2.0)/pow(om,2.0) * x[j] - private_c[j];
private_t[j] = private_sum[j] + private_y[j];
private_c[j] = (private_t[j] - private_sum[j]) - private_y[j];
private_sum[j] = private_t[j];
}
}
for(j=0; j<DIM; j++)
{
#pragma omp atomic //addiere threadsummen auf
sum[j] =sum[j] + private_sum[j];
}
#pragma omp barrier
if ( MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
a[j] = sum[j] /mass ; //p-Ableitung
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
a[ID] = sum[ID] /mass ; //p-Ableitung
}
}
for(j = 0; j< DIM; j++)
{
v[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;
}
*t = *t + MAXSTEPSIZE;
}
void VVerlet_Step_hardsphere_reflect(const int N, double x[] , double v[], double a[], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
void (*derivmethod) (double *y, double *ans, double t,int N)) {
int i,j;
SETNUMTHREADS
double sum[DIM]; // variable stepsize maximum MAXSTEPSIZE
double target_vec[20];
int reflec_flag = 0; // set to 1of target if root found
int target_nr_hit = 0; // number of actual target hit
double contact_stepsize;
// upper search bound
int number_targets;
double lower_t_global[2*DIM]; // array containing contact times for all targets in cell
int reflec_flag_global[2*DIM]; // global array tro indicate reflection on target
for (i=0; i < 2*DIM; i++)
{
lower_t_global[i] = MAXSTEPSIZE; // all times a equal or smaller stepsize, so search for minimum later
reflec_flag_global[i] = 0;
}
// determine time to collsion --------------------------------------------------------------------------------------------
contact_stepsize = MAXSTEPSIZE;
Update_Lattice_Position(lattice_position, x, LATTICE_SPACING);
if ( (number_targets = TARGET_METHOD(lattice_position, target_vec, // Find Targets
LATTICE_SPACING, ESCAPE_CELLS)\
)>0
)
{
#pragma omp parallel for
for (int target_i = 0; target_i < number_targets; target_i++)
{
double lower_t; // lower search bound
double upper_t;
int signold; int signnew;
lower_t = 0.0; // lower search bound
upper_t = MAXSTEPSIZE; // upper search bound
double steps = 500.0;
int root_flag = 1; // set to one if root found and also one at fitst loop
int root_loop = 0; // number of current loop
int root_loop_max = 3;
while ((root_flag == 1) && (root_loop < root_loop_max))
{
root_flag = 0;
root_loop += 1;
// get sign lower bound before loop
double eval_value = 0.0;
for(i = 0; i< DIM; i++)
{
double v_temp = v[i] + 0.5 * a[i] * lower_t;
double x_temp = x[i] + v_temp * lower_t;
eval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0); // f = sum (x-R)^2
}
eval_value = eval_value - pow(TARGET_LENGTH , 2.0);
if (eval_value > 0)
{
signold = 1;
}else
{
signold = -1;
}
double dt = (upper_t - lower_t)/ steps;
// check all signs in intervall till first change
for (double t_check = lower_t; t_check < upper_t; t_check += dt)
{
eval_value = 0.0;
for(i = 0; i< DIM; i++)
{
double v_temp = v[i] + 0.5 * a[i] * t_check;
double x_temp = x[i] + v_temp * t_check;
eval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0); // f = sum (x-R)^2
}
eval_value = eval_value - pow(TARGET_LENGTH , 2.0);
//printf("%2.2e\n", eval_value);
if (eval_value > 0)
{
signnew = 1;
}else
{
signnew = -1;
}
if (signnew != signold) // at first sign change adjust intervall
{
lower_t = t_check - dt;
steps = 10000.0; // refine only 4 orders of magnitude per loop
upper_t = t_check;
root_flag = 1; // redo loop to refine root
lower_t_global[target_i] = lower_t;
break;
}
signold = signnew;
}
}
}
}// collision detection end--------------------------------------------------------------------------------------------------
double minimum_t = MAXSTEPSIZE;
for (i=0; i < number_targets; i++) //find smallest reflection time
{
if(lower_t_global[i] < minimum_t)
{
reflec_flag = 1;
target_nr_hit = i;
minimum_t = lower_t_global[i];
}
}
if (reflec_flag ==1 )
{
if (TARGET_FLAG) // check for first contact
{
time_first_contact += *t + minimum_t;
TARGET_FLAG = 0;// no need to test again after 1st contact
}
contact_stepsize = minimum_t; // pick lower boud so particle is JUST outside the boundary - Else zero search converges badly
}else
{
contact_stepsize = MAXSTEPSIZE;
}
#pragma omp parallel // Values for Bath particles parralized//
{
int ID = omp_get_thread_num();
int MAX_THREADS = omp_get_num_threads();
if (MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
sum[j] = 0.0f; // prepare sum for heavy particle
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
sum[ID] = 0.0f; // prepare sum for heavy particle
}
#pragma omp for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
#pragma omp for // Values for Bath particles parralized
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for(j = 0; j < DIM; j++)
{ // Ableitung /
double a_temp = a[DIM + j + i*DIM] = - om * om * x[DIM + j + i*DIM]\
+ coup * x[j]; // dp_q/dt = -w^2 * q+ gamma * x
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////
}
}
double private_sum[DIM];
double private_c[DIM] = {0.0,0.0}; // Kahan correction
double private_t[DIM] = {0.0,0.0};
double private_y[DIM] = {0.0,0.0};
for(j = 0; j < DIM; j++) // Values for heavy particle
{
private_sum[j] = 0.0; // ech thread calcs partial sum
}
#pragma omp for // calc sum gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for (j=0; j<DIM; j++)
{ // Kahan summation scheme
private_y[j] = coup * x[DIM + j + i*DIM]\
- pow(coup,2.0)/pow(om,2.0) * x[j] - private_c[j];
private_t[j] = private_sum[j] + private_y[j];
private_c[j] = (private_t[j] - private_sum[j]) - private_y[j];
private_sum[j] = private_t[j];
}
}
for(j=0; j<DIM; j++)
{
#pragma omp atomic //addiere threadsummen auf
sum[j] =sum[j] + private_sum[j];
}
#pragma omp barrier
if ( MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
a[j] = sum[j] /mass ; //p-Ableitung
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
a[ID] = sum[ID] /mass ; //p-Ableitung
}
}
for(j = 0; j< DIM; j++)
{
v[j] = v[j] + 0.5 * a[j] * contact_stepsize;
}
*t = *t + contact_stepsize;
double norm = 0.0;
for(j = 0; j< DIM; j++)
{
norm += pow(target_vec[j + DIM * target_nr_hit] - x[j],2.0);
}
norm = sqrt(norm);
if (number_targets)
{
if(norm < TARGET_LENGTH * 0.98) // catch case particle entered sphere, only nonempty cells
{
FLAG_DUMP_VALUE = 1;
printf("\nsphere entered at t=%2.2e, lattice point %d %d", *t, lattice_position[0], lattice_position[1]);
}
}
if ((reflec_flag)) // reflect on surface normal. Assume particle is on the surface
// prevent case of inner reflection in case particle still got in
{
double surface_normal[DIM];
double vec_norm = 0.0;
double scalar_prod = 0.0;
// find vector towards target
for(j = 0; j< DIM; j++)
{
surface_normal[j] = target_vec[j + DIM * target_nr_hit] - x[j];
}
for(j = 0; j< DIM; j++)
{
vec_norm += surface_normal[j] * surface_normal[j];
}
// point surface vector outwards and normalize
vec_norm = sqrt(vec_norm);
for(j = 0; j< DIM; j++)
{
surface_normal[j] = surface_normal[j]/vec_norm;
}
// find part of v in surface direction
for(j = 0; j< DIM; j++)
{
scalar_prod += surface_normal[j] * v[j];
}
// reflect that part
for(j = 0; j< DIM; j++)
{
v[j] = v[j] - 2.0 * scalar_prod * surface_normal[j];
}
}
}
void VVerlet_Step_hardsphere_reflect_all(const int N, double x[] , double v[], double a[], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
void (*derivmethod) (double *y, double *ans, double t,int N)) {
int i,j;
SETNUMTHREADS
double sum[DIM]; // variable stepsize maximum MAXSTEPSIZE
double target_vec[20];
int reflec_flag = 0; // set to 1of target if root found
int target_nr_hit = 0; // number of actual target hit
double contact_stepsize;
// upper search bound
int number_targets;
double lower_t_global[2*DIM]; // array containing contact times for all targets in cell
int reflec_flag_global[2*DIM]; // global array tro indicate reflection on target
for (i=0; i < 2*DIM; i++)
{
lower_t_global[i] = MAXSTEPSIZE; // all times a equal or smaller stepsize, so search for minimum later
reflec_flag_global[i] = 0;
}
// determine time to collsion --------------------------------------------------------------------------------------------
contact_stepsize = MAXSTEPSIZE;
Update_Lattice_Position(lattice_position, x, LATTICE_SPACING);
if ( (number_targets = TARGET_METHOD(lattice_position, target_vec, // Find Targets
LATTICE_SPACING, ESCAPE_CELLS)\
)>0
)
{
#pragma omp parallel for
for (int target_i = 0; target_i < number_targets; target_i++)
{
double lower_t; // lower search bound
double upper_t;
int signold; int signnew;
lower_t = 0.0; // lower search bound
upper_t = MAXSTEPSIZE; // upper search bound
double steps = 500.0;
int root_flag = 1; // set to one if root found and also one at fitst loop
int root_loop = 0; // number of current loop
int root_loop_max = 3;
while ((root_flag == 1) && (root_loop < root_loop_max))
{
root_flag = 0;
root_loop += 1;
// get sign lower bound before loop
double eval_value = 0.0;
for(i = 0; i< DIM; i++)
{
double v_temp = v[i] + 0.5 * a[i] * lower_t;
double x_temp = x[i] + v_temp * lower_t;
eval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0); // f = sum (x-R)^2
}
eval_value = eval_value - pow(TARGET_LENGTH , 2.0);
if (eval_value > 0)
{
signold = 1;
}else
{
signold = -1;
}
double dt = (upper_t - lower_t)/ steps;
// check all signs in intervall till first change
for (double t_check = lower_t; t_check < upper_t; t_check += dt)
{
eval_value = 0.0;
for(i = 0; i< DIM; i++)
{
double v_temp = v[i] + 0.5 * a[i] * t_check;
double x_temp = x[i] + v_temp * t_check;
eval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0); // f = sum (x-R)^2
}
eval_value = eval_value - pow(TARGET_LENGTH , 2.0);
//printf("%2.2e\n", eval_value);
if (eval_value > 0)
{
signnew = 1;
}else
{
signnew = -1;
}
if (signnew != signold) // at first sign change adjust intervall
{
lower_t = t_check - dt;
steps = 10000.0; // refine only 4 orders of magnitude per loop
upper_t = t_check;
root_flag = 1; // redo loop to refine root
lower_t_global[target_i] = lower_t;
break;
}
signold = signnew;
}
}
}
}// collision detection end--------------------------------------------------------------------------------------------------
double minimum_t = MAXSTEPSIZE;
for (i=0; i < number_targets; i++) //find smallest reflection time
{
if(lower_t_global[i] < minimum_t)
{
reflec_flag = 1;
target_nr_hit = i;
minimum_t = lower_t_global[i];
}
}
if (reflec_flag ==1 )
{
if (TARGET_FLAG) // check for first contact
{
time_first_contact += *t + minimum_t;
TARGET_FLAG = 0;// no need to test again after 1st contact
}
contact_stepsize = minimum_t; // pick lower boud so particle is JUST outside the boundary - Else zero search converges badly
}else
{
contact_stepsize = MAXSTEPSIZE;
}
#pragma omp parallel // Values for Bath particles parralized//
{
int ID = omp_get_thread_num();
int MAX_THREADS = omp_get_num_threads();
if (MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
sum[j] = 0.0f; // prepare sum for heavy particle
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
sum[ID] = 0.0f; // prepare sum for heavy particle
}
#pragma omp for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
#pragma omp for // Values for Bath particles parralized
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for(j = 0; j < DIM; j++)
{ // Ableitung /
double a_temp = a[DIM + j + i*DIM] = - om * om * x[DIM + j + i*DIM]\
+ coup * x[j]; // dp_q/dt = -w^2 * q+ gamma * x
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////
}
}
double private_sum[DIM];
double private_c[DIM] = {0.0,0.0}; // Kahan correction
double private_t[DIM] = {0.0,0.0};
double private_y[DIM] = {0.0,0.0};
for(j = 0; j < DIM; j++) // Values for heavy particle
{
private_sum[j] = 0.0; // ech thread calcs partial sum
}
#pragma omp for // calc sum gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for (j=0; j<DIM; j++)
{ // Kahan summation scheme
private_y[j] = coup * x[DIM + j + i*DIM]\
- pow(coup,2.0)/pow(om,2.0) * x[j] - private_c[j];
private_t[j] = private_sum[j] + private_y[j];
private_c[j] = (private_t[j] - private_sum[j]) - private_y[j];
private_sum[j] = private_t[j];
}
}
for(j=0; j<DIM; j++)
{
#pragma omp atomic //addiere threadsummen auf
sum[j] =sum[j] + private_sum[j];
}
#pragma omp barrier
if ( MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
a[j] = sum[j] /mass ; //p-Ableitung
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
a[ID] = sum[ID] /mass ; //p-Ableitung
}
}
for(j = 0; j< DIM; j++)
{
v[j] = v[j] + 0.5 * a[j] * contact_stepsize;
}
*t = *t + contact_stepsize;
double norm = 0.0;
for(j = 0; j< DIM; j++)
{
norm += pow(target_vec[j + DIM * target_nr_hit] - x[j],2.0);
}
norm = sqrt(norm);
if (number_targets)
{
if(norm < TARGET_LENGTH * 0.98) // catch case particle entered sphere, only nonempty cells
{
FLAG_DUMP_VALUE = 1;
printf("\nsphere entered at t=%2.2e, lattice point %d %d", *t, lattice_position[0], lattice_position[1]);
}
}
if ((reflec_flag)) // reflect on surface normal. Assume particle is on the surface
// prevent case of inner reflection in case particle still got in
{
double surface_normal[DIM];
double vec_norm = 0.0;
double scalar_prod = 0.0;
// find vector towards target
for(j = 0; j< DIM; j++)
{
surface_normal[j] = target_vec[j + DIM * target_nr_hit] - x[j];
}
for(j = 0; j< DIM; j++)
{
vec_norm += surface_normal[j] * surface_normal[j];
}
// point surface vector outwards and normalize
vec_norm = sqrt(vec_norm);
for(j = 0; j< DIM; j++)
{
surface_normal[j] = surface_normal[j]/vec_norm;
}
// find part of v in surface direction
for(j = 0; j< DIM; j++)
{
scalar_prod += surface_normal[j] * v[j];
}
// reflect that part for ALL
#pragma omp parallel for
for (i = 0; i < OSSZI; i++ )
{
for(j = 0; j< DIM; j++)
{
v[i*DIM + j] = v[i*DIM + j] - 2.0 * scalar_prod * surface_normal[j];
}
}
}
}
void VVerlet_Step_deriv_Kupf(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*derivmethod) (double *y, double *ans, double t,int N)) {
//mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
// use fully mobile Kupferman bath that is coupling U = sum gamma_i (q_i-X)^2
int i,j;
SETNUMTHREADS
double sum[DIM];
#pragma omp parallel // Values for Bath particles parralized///////////////////
{
int ID = omp_get_thread_num();
int MAX_THREADS = omp_get_num_threads();
if (MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
sum[j] = 0.0f; // prepare sum for heavy particle
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
sum[ID] = 0.0f; // prepare sum for heavy particle
}
#pragma omp for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * MAXSTEPSIZE; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * MAXSTEPSIZE; //xnext = x + vnext *dt
}
#pragma omp for // Values for Bath particles parralized
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for(j = 0; j < DIM; j++)
{ // Ableitung /
double a_temp = a[DIM + j + i*DIM] = -coup * (x[DIM + j + i*DIM] - x[j])/massq[i];
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a_temp * MAXSTEPSIZE; // Zweites Halbupdate ////
}
}
double private_sum[DIM];
double private_c[DIM] = {0.0,0.0}; // Kahan correction
double private_t[DIM] = {0.0,0.0};
double private_y[DIM] = {0.0,0.0};
for(j = 0; j < DIM; j++) // Values for heavy particle
{
private_sum[j] = 0.0; // JEder thread berechnet Partialsumme
}
#pragma omp for // berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for (j=0; j<DIM; j++)
{ // Kahan summation scheme
private_y[j] = coup * (x[DIM + j + i*DIM] - x[j]) - private_c[j];
private_t[j] = private_sum[j] + private_y[j];
private_c[j] = (private_t[j] - private_sum[j]) - private_y[j];
private_sum[j] = private_t[j];
}
}
for(j=0; j<DIM; j++)
{
#pragma omp atomic //addiere threadsummen auf
sum[j] =sum[j] + private_sum[j];
}
#pragma omp barrier
if ( MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
a[j] = sum[j] /mass ; //p-Ableitung
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
a[ID] = sum[ID] /mass ; //p-Ableitung
}
}
for(j = 0; j< DIM; j++)
{
v[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;
VIRTUAL_V[j] = v[j];
VIRTUAL_X[j] = x[j];
}
*t = *t + MAXSTEPSIZE;
}
void VVerlet_Step_hardsphere_reflect_Kupf(const int N, double x[] , double v[], double a[], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss
void (*derivmethod) (double *y, double *ans, double t,int N)) {
int i,j;
SETNUMTHREADS
double sum[DIM]; // variable stepsize maximum MAXSTEPSIZE
double target_vec[20];
int reflec_flag = 0; // set to 1of target if root found
int target_nr_hit = 0; // number of actual target hit
double contact_stepsize = LASTSTEPSIZE;
// upper search bound
int number_targets;
double lower_t_global[2*DIM]; // array containing contact times for all targets in cell
int reflec_flag_global[2*DIM]; // global array tro indicate reflection on target
for (i=0; i < 2*DIM; i++)
{
lower_t_global[i] = LASTSTEPSIZE; // all times a equal or smaller stepsize, so search for minimum later
reflec_flag_global[i] = 0;
}
// determine time to collsion --------------------------------------------------------------------------------------------
contact_stepsize = LASTSTEPSIZE;
if(VIRTUAL_FLAG)
{
Update_Lattice_Position(lattice_position, VIRTUAL_X, LATTICE_SPACING);
}else
{
Update_Lattice_Position(lattice_position, x, LATTICE_SPACING);
}
if ( (number_targets = TARGET_METHOD(lattice_position, target_vec, // Find Targets
LATTICE_SPACING, ESCAPE_CELLS)\
)>0
)
{
double N_CHECK = 1000.0;
#pragma omp parallel for
for (int target_i = 0; target_i < number_targets; target_i++) // check for all targets in increments of LASTSTEPSIZE/N_CHECK for contact
{
double dh = LASTSTEPSIZE / N_CHECK;
for (double h_check = 0.0; h_check < LASTSTEPSIZE; h_check += dh)
{
double r_check = 0.0;
for (int j = 0; j < DIM; j++)
{
double v_temp = v[j] + 0.5 * a[j] * h_check;
double x_temp = x[j] + v_temp * h_check;
if(VIRTUAL_FLAG)
{
v_temp = VIRTUAL_V[j] + 0.5 * a[j] * h_check;
x_temp = VIRTUAL_X[j] + v_temp * h_check;
}
r_check += pow( (x_temp - target_vec[j + target_i * DIM] ) ,2.0 );
}
r_check = sqrt(r_check);
if (r_check < TARGET_LENGTH)
{
reflec_flag = 1;
target_nr_hit = target_i;
contact_stepsize = h_check - dh;
if (TARGET_FLAG) // check for first contact
{
time_first_contact += *t + contact_stepsize;
TARGET_FLAG = 0;// no need to test again after 1st contact
}
break;
break;
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------
#pragma omp parallel // Values for Bath particles parralized//
{
int ID = omp_get_thread_num();
int MAX_THREADS = omp_get_num_threads();
if (MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
sum[j] = 0.0f; // prepare sum for heavy particle
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
sum[ID] = 0.0f; // prepare sum for heavy particle
}
#pragma omp for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
if(VIRTUAL_FLAG)
{
#pragma omp for
for (i= 0 ; i < DIM; i++) // Erstes Halbupdate ////
{
double v_temp = VIRTUAL_V[i] = VIRTUAL_V[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
VIRTUAL_X[i] = VIRTUAL_X[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
}
#pragma omp for // Values for Bath particles parralized
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for(j = 0; j < DIM; j++)
{ // Ableitung /
double a_temp = a[DIM + j + i*DIM] = -coup * (x[DIM + j + i*DIM] - x[j])/massq[i]; // dp_q/dt = -w^2 * q+ gamma * x
v[DIM +j + i*DIM] = v[DIM +j + i*DIM]\
+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////
}
}
double private_sum[DIM];
double private_c[DIM] = {0.0,0.0}; // Kahan correction
double private_t[DIM] = {0.0,0.0};
double private_y[DIM] = {0.0,0.0};
for(j = 0; j < DIM; j++) // Values for heavy particle
{
private_sum[j] = 0.0; // ech thread calcs partial sum
}
#pragma omp for // calc sum gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
for (j=0; j<DIM; j++)
{ // Kahan summation scheme
private_y[j] = coup * (x[DIM + j + i*DIM] - x[j]) - private_c[j];
private_t[j] = private_sum[j] + private_y[j];
private_c[j] = (private_t[j] - private_sum[j]) - private_y[j];
private_sum[j] = private_t[j];
}
}
for(j=0; j<DIM; j++)
{
#pragma omp atomic //addiere threadsummen auf
sum[j] =sum[j] + private_sum[j];
}
#pragma omp barrier
if ( MAX_THREADS < DIM) // Catch case : not enough threads
{ for (j= 0; j<DIM; j++)
{
a[j] = sum[j] /mass ; //p-Ableitung
}
}else if (ID < DIM) // heavy particle dimensions go to threads
{
a[ID] = sum[ID] /mass ; //p-Ableitung
}
}
for(j = 0; j< DIM; j++)
{
v[j] = v[j] + 0.5 * a[j] * contact_stepsize;
}
if(VIRTUAL_FLAG)
{
for(j = 0; j< DIM; j++)
{
VIRTUAL_V[j] = VIRTUAL_V[j] + 0.5 * a[j] * contact_stepsize;
}
}
*t = *t + contact_stepsize;
double norm = 0.0;
for(j = 0; j< DIM; j++)
{
if(VIRTUAL_FLAG)
{
norm += pow(target_vec[j + DIM * target_nr_hit] - VIRTUAL_X[j],2.0);
}else
{
norm += pow(target_vec[j + DIM * target_nr_hit] - x[j],2.0);
}
}
norm = sqrt(norm);
if (number_targets)
{
if(norm < TARGET_LENGTH * 0.98) // catch case particle entered sphere, only nonempty cells
{
FLAG_DUMP_VALUE = 1;
printf("\nsphere entered at t=%2.2e, lattice point %d %d", *t, lattice_position[0], lattice_position[1]);
}
}
if ((reflec_flag)) // reflect on surface normal. Assume particle is on the surface
// prevent case of inner reflection in case particle still got in
{
double surface_normal[DIM];
double vec_norm = 0.0;
double scalar_prod = 0.0;
// find vector towards target
for(j = 0; j< DIM; j++)
{
if(VIRTUAL_FLAG)
{
surface_normal[j] = target_vec[j + DIM * target_nr_hit] - VIRTUAL_X[j];
}else
{
surface_normal[j] = target_vec[j + DIM * target_nr_hit] - x[j];
}
}
for(j = 0; j< DIM; j++)
{
vec_norm += surface_normal[j] * surface_normal[j];
}
// point surface vector outwards and normalize
vec_norm = sqrt(vec_norm);
for(j = 0; j< DIM; j++)
{
surface_normal[j] = surface_normal[j]/vec_norm;
}
// find part of v in surface direction
for(j = 0; j< DIM; j++)
{
if(VIRTUAL_FLAG)
{
scalar_prod += surface_normal[j] * VIRTUAL_V[j];
}else
{
scalar_prod += surface_normal[j] * v[j];
}
}
// reflect that part
for(j = 0; j< DIM; j++)
{
if(VIRTUAL_FLAG)
{
VIRTUAL_V[j] = VIRTUAL_V[j] - 2.0 * scalar_prod * surface_normal[j];
}else
{
v[j] = v[j] - 2.0 * scalar_prod * surface_normal[j];
}
}
}
if ((reflec_flag))
{
LASTSTEPSIZE = LASTSTEPSIZE - contact_stepsize; // do remaining step time
}
else
{
LASTSTEPSIZE = MAXSTEPSIZE;
}
}
void VVerlet_Step_deriv_Box(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*derivmethod) (double *y, double *ans, double t,int N)) {
//macht einzelnen update schritt in Box der Länge Lattice_Spacting
// use fully mobile Kupferman bath that is coupling U = sum gamma_i (q_i-X)^2
int i,j;
SETNUMTHREADS
double sum = 0.0;
double contact_stepsize = LASTSTEPSIZE;
int reflec_flag = 0;
// find contact time ------------------------------------
double aa,b,c;
aa=b=c=0;
int REFLEC_WALL = 1;
if (REFLEC_WALL)
{ // debugging purposes, free evolution if false
for (int i_bound = -1; i_bound < 2; i_bound += 2)
{
double root1 = 0.0; double root2 = 0.0;
if(VIRTUAL_FLAG)
{
c = VIRTUAL_X[0] + i_bound * LATTICE_SPACING/2.0;
b = VIRTUAL_V[0];
aa = 0.5 * a[0];
}else
{
c = x[0] + i_bound * LATTICE_SPACING/2.0;
b = v[0];
aa = 0.5 * a[0];
}
if(b >= 0) // minimize rounoff err by case split
{
root1 = (-b - sqrt(b*b - 4.0 * aa * c)) / (2.0 * aa);
root2 = 2.0 * c /(-b - sqrt(b*b - 4.0 * aa * c) );
}else
{
root1 = 2.0 * c /(-b + sqrt(b*b - 4.0 * aa * c) );
root2 = (-b + sqrt(b*b - 4.0 * aa * c)) / (2.0 * aa);
}
if( (root1 > 0) && (root1 < contact_stepsize) )
{
contact_stepsize = 0.995 * root1;
reflec_flag = 1;
}
if( (root2 > 0) && (root2 < contact_stepsize) )
{
contact_stepsize = 0.995 * root2;
reflec_flag = 1;
}
}
}
// contact time end ||||||||||||||||||||||||||||||||||||<
#pragma omp parallel for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
if(VIRTUAL_FLAG)
{
double v_temp = VIRTUAL_V[0] = VIRTUAL_V[0] + 0.5 * a[0] * contact_stepsize; // virtual particle
VIRTUAL_X[0] = VIRTUAL_X[0] + v_temp * contact_stepsize;
}
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
double a_temp = a[1 + i] = -coup * (x[1 + i] - x[0])/massq[i];
v[1 + i] = v[1 + i]\
+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////
}
#pragma omp parallel for reduction(+:sum) // berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
sum += coup * (x[1 + i] - x[0]);
}
a[0] = sum /mass;
v[0] = v[0] + 0.5 * a[0] * contact_stepsize;
if(VIRTUAL_FLAG)
{
VIRTUAL_V[0] = VIRTUAL_V[0] + 0.5 * a[0] * contact_stepsize;
}
*t = *t + contact_stepsize;
if(reflec_flag)
{
LASTSTEPSIZE = LASTSTEPSIZE - contact_stepsize;
if(REFLECTALL_FLAG) // reflect whole bath if flag is set
{
for (i = 0 ; i < OSSZI; i++)
{
double v_rel = v[1 + i] - v[0];
v[1 + i] = - v[0] + v_rel; //keep relative velocity after reflection of heavy particle the same
}
}
if(VIRTUAL_FLAG)
{
VIRTUAL_V[0] = -VIRTUAL_V[0]; // reflect heavy
}else
{
v[0] = -v[0]; // reflect heavy
}
}
else
{
LASTSTEPSIZE = MAXSTEPSIZE;
}
}
void VVerlet_Step_deriv_Box_Ramp(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*derivmethod) (double *y, double *ans, double t,int N)) {
//macht einzelnen update schritt in Box der Länge Lattice_Spacting
// use fully mobile Kupferman bath that is coupling U = sum gamma_i (q_i-X)^2
int i,j;
SETNUMTHREADS
double sum = 0.0;
double contact_stepsize = LASTSTEPSIZE;
int reflec_flag = 0;
#pragma omp parallel for
for (i= 0 ; i < N/2; i++) // Erstes Halbupdate ////
{
double v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize; //vnext = v + a/2 *dt
x[i] = x[i] + v_temp * contact_stepsize; //xnext = x + vnext *dt
}
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
double om = ommega[i];
double a_temp = a[1 + i] = -coup * (x[1 + i] - x[0])/massq[i];
v[1 + i] = v[1 + i]\
+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////
}
#pragma omp parallel for reduction(+:sum) // berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x
for (i = 0 ; i < OSSZI; i++)
{
double coup = coupling[i];
sum += coup * (x[1 + i] - x[0]);
}
a[0] = sum /mass;
if(x[0] < -(LATTICE_SPACING/2.0 - L_BALL) ) //left wall;
{
double height_ramp = 2*KBOLTZ*TEMP;
a[0] += height_ramp/L_BALL/mass;
}
if(x[0] > (LATTICE_SPACING/2.0 - L_BALL) ) //right wall;
{
double height_ramp = 2*KBOLTZ*TEMP;
a[0] += -height_ramp/L_BALL/mass;
}
v[0] = v[0] + 0.5 * a[0] * contact_stepsize;
*t = *t + contact_stepsize;
}
| {
"alphanum_fraction": 0.5694096906,
"avg_line_length": 30.7681539808,
"ext": "c",
"hexsha": "9b3242e960051ec98789583267a3eea0985d6348",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_forks_repo_path": "steppmethods.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_issues_repo_path": "steppmethods.c",
"max_line_length": 173,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_stars_repo_path": "steppmethods.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12477,
"size": 35168
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <nlopt.h>
#include "mpi.h"
int numTasks, mpiRank;
#include "myFunc.h"
void writeParam(char *filename, int nParam, double *x)
{
FILE *fn=fopen(filename,"w");
if(!fn) {
fprintf(stderr,"Cannot open %s\n",filename);
exit(1);
}
uint32_t n=nParam; // ensure size is uint32_t
fwrite(&n,sizeof(uint32_t), 1, fn);
for(int i=0; i < nParam; i++) {
float tmp=x[i];
fwrite(&tmp,sizeof(float), 1, fn);
}
fclose(fn);
}
int masterOP=1;
void startClient(void * restrict my_func_data)
{
int op;
double xFromMPI[N_PARAM];
double partialError,sum;
for(;;) { // loop until the master says I am done - then exit
MPI_Bcast(&op, 1, MPI_INT, 0, MPI_COMM_WORLD); // receive the op code
if(op==0) { // we are done, normal exit
break;
}
MPI_Bcast(xFromMPI, N_PARAM, MPI_DOUBLE, 0, MPI_COMM_WORLD); // receive the parameters
partialError = objFunc(N_PARAM, xFromMPI, NULL, my_func_data);
MPI_Reduce(&partialError, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
}
}
double mpiObjFunc(unsigned n, const double * restrict x, double * restrict grad,
void * restrict my_func_data)
{
int op;
double partialError, totalError=0.;
MPI_Bcast(&masterOP, 1, MPI_INT, 0, MPI_COMM_WORLD); // Send the master op code
MPI_Bcast((void*) x, N_PARAM, MPI_DOUBLE, 0, MPI_COMM_WORLD); // Send the parameters
partialError = objFunc(N_PARAM, x, NULL, my_func_data);
MPI_Reduce(&partialError, &totalError, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); // get the totalError
return(totalError);
}
int main(int argc, char* argv[])
{
nlopt_opt opt;
userData_t uData = {0};
FILE *fout_mpi;
if(argc < 4) {
fprintf(stderr,"Use: datafile paramFile mpiTimingFile\n");
return -1;
}
int ret = MPI_Init(&argc,&argv);
if (ret != MPI_SUCCESS) {
printf ("Error in MPI_Init()!\n");
MPI_Abort(MPI_COMM_WORLD, ret);
}
MPI_Comm_size(MPI_COMM_WORLD,&numTasks);
MPI_Comm_rank(MPI_COMM_WORLD,&mpiRank);
#if defined(NO_IO_EXAMPLES)
#pragma message "TEST case: Clients use random memory values"
init_noIO(NO_IO_EXAMPLES,&uData);
#else
#pragma message "TEST case: all clients perform file reads"
{ // for simplicity, append the mpiRank to the data filename
char filename[256];
sprintf(filename,"%s.%d",argv[1],mpiRank);
//fprintf(stderr,"Loading %s into coprocessor %d\n", filename, MIC_DEV);
init(filename,&uData);
}
#endif
if(mpiRank > 0) {
startClient(&uData);
} else { // Master code
{ // open MPI results file for this size run
char buf[256];
sprintf(buf, "%s.%04d.txt",argv[3],numTasks);
fout_mpi = fopen(buf,"w");
if(!fout_mpi) {
fprintf(stderr,"Cannot open file %s\n",buf);
return -1;
}
}
printf ("Number of tasks= %d My rank= %d, number clients %d\n", numTasks,mpiRank,numTasks);
#ifdef MPI_NUM_COPROC_PER_NODE
printf ("Number of coprocessors per node= %d\n", MPI_NUM_COPROC_PER_NODE);
#endif
printf("myFunc %s\n", desc);
printf("nExamples %d\n", uData.nExamples);
printf("Number Parameters %d\n", N_PARAM);
opt = nlopt_create(NLOPT_LN_PRAXIS, N_PARAM); // algorithm and dimensionality
// NOTE: alternative optimization methods ...
//opt = nlopt_create(NLOPT_LN_NEWUOA, N_PARAM);
//opt = nlopt_create(NLOPT_LN_COBYLA, N_PARAM);
//opt = nlopt_create(NLOPT_LN_BOBYQA, N_PARAM);
//opt = nlopt_create(NLOPT_LN_AUGLAG, N_PARAM);
nlopt_set_min_objective(opt, mpiObjFunc, (void*) &uData);
/*
#if defined(MAX_RUNTIME)
fprintf(stderr,"Warning: performing a quick %d second test!\n", MAX_RUNTIME);
nlopt_set_maxtime(opt, MAX_RUNTIME); // Use for running quick tests
#else
fprintf(stderr,"MAX runtime %d seconds!\n", 120*60);
nlopt_set_maxtime(opt, (120. * 60.)); // maximum runtime in seconds
#endif
*/
double minf; /* the minimum objective value, upon return */
__declspec(align(64)) double x[N_PARAM];
for(int i=0; i < N_PARAM; i++) x[i] = 0.1*(random()/(double)RAND_MAX);
double startTime=getTime();
ret=nlopt_optimize(opt, x, &minf);
printf("Optimization Time %g\n",getTime()-startTime);
if (ret < 0) {
printf("nlopt failed! ret %d\n", ret);
} else {
printf("found minimum %0.10g ret %d\n", minf,ret);
}
writeParam(argv[2],N_PARAM, x);
nlopt_destroy(opt);
masterOP = 0; // signal completion
MPI_Bcast(&masterOP, 1, MPI_INT, 0, MPI_COMM_WORLD); // Send the master op code
printf("----------- performance times for the Master ----------\n");
fini(&uData);
}
int client_nExamples[numTasks];
double client_timeObjFunc[numTasks];
int client_countObjFunc[numTasks];
double client_timeDataLoad[numTasks];
double client_minTime[numTasks];
double client_maxTime[numTasks];
MPI_Gather(&uData.nExamples, 1, MPI_INT, client_nExamples, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&uData.countObjFunc, 1, MPI_INT, client_countObjFunc, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(&uData.timeDataLoad, 1, MPI_DOUBLE, client_timeDataLoad, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&uData.timeObjFunc, 1, MPI_DOUBLE, client_timeObjFunc, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&uData.minTime, 1, MPI_DOUBLE, client_minTime, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Gather(&uData.maxTime, 1, MPI_DOUBLE, client_maxTime, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if(mpiRank==0) {
printf("----------- performance times for the MPI run ----------\n");
printf("function: %s\n",desc);
uint64_t totalExamples=0;
for(int i=0; i < numTasks; i++) totalExamples += client_nExamples[i];
printf("totalExamples %g\n",(double) totalExamples);
printf("AveObjTime %g, countObjFunc %d, totalObjTime %g\n",
uData.timeObjFunc/uData.countObjFunc, uData.countObjFunc, uData.timeObjFunc);
#ifdef FLOP_ESTIMATE
printf("Estimated flops in myFunc %d, estimated average TFlop/s %g, nClients %d\n", FLOP_ESTIMATE,
(((double)totalExamples * (double)FLOP_ESTIMATE)/(uData.timeObjFunc/uData.countObjFunc)/1.e12),
numTasks);
printf("Estimated maximum TFlop/s %g, minimum TFLop/s %g\n",
(((double)totalExamples*(double)FLOP_ESTIMATE)/(uData.minTime)/1.e12),
(((double)totalExamples*(double)FLOP_ESTIMATE)/(uData.maxTime)/1.e12) );
#endif
fprintf(fout_mpi, "nExamples countObjFunc timeDataLoad timeObjFunc minObjFcnTime maxObjFcnTime\n");
for(int i=0; i < numTasks; i++) {
fprintf(fout_mpi, "%g %g %g %g %g %g\n",
(double) client_nExamples[i], (double) client_countObjFunc[i], client_timeDataLoad[i],
client_timeObjFunc[i], client_minTime[i], client_maxTime[i]);
}
}
MPI_Finalize();
return 0;
}
| {
"alphanum_fraction": 0.6763491595,
"avg_line_length": 33.5742574257,
"ext": "c",
"hexsha": "2fcadfa410feb4d70be932ef51c94129570a630c",
"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": "bf2fa1a4459d72f42cf39d772bf49d6965335b78",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "puckbee/PhiBench",
"max_forks_repo_path": "pca_exp/program/farbOpt/mpiTrain.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf2fa1a4459d72f42cf39d772bf49d6965335b78",
"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": "puckbee/PhiBench",
"max_issues_repo_path": "pca_exp/program/farbOpt/mpiTrain.c",
"max_line_length": 106,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "bf2fa1a4459d72f42cf39d772bf49d6965335b78",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "puckbee/PhiBench",
"max_stars_repo_path": "nlpca_exp/program/farbOpt/mpiTrain.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-17T17:51:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-14T12:32:15.000Z",
"num_tokens": 2037,
"size": 6782
} |
/*
Copyright [2020] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef MCAS_CCPM_LOG_H__
#define MCAS_CCPM_LOG_H__
#include <ccpm/interfaces.h>
#include <gsl/pointers>
#include <cstring>
#include <cstddef>
namespace ccpm
{
struct block_header;
struct log
: public ILog
{
using heap_type = gsl::not_null<IHeap_expandable *>;
using persister_type = gsl::not_null<ccpm::persister *>;
private:
/*
* The log needs to be stored persistently, and to use persistent storage.
* Use persister_type for the former and heap_type for the latter.
*/
persister_type _persister; // not owned
heap_type _mr; // not owned
/* The log needs a root */
block_header *_root; // owned
void clear_top();
static constexpr size_t min_log_extend = std::size_t(65536U);
void extend(std::size_t size);
public:
explicit log(persister_type, heap_type mr_);
log(const log &) = delete;
log &operator=(const log &) = delete;
/*
* Restoration of a log from persistent memory is done by moving the
* log to itself with a move constructor. The persisted log has a vft
* pointer, which is invalid when the log is rediscovered in persistent
* memory. The move constructor creates valid vft pointer and (we hope)
* preserves the rest of the log member data.
*/
log(log &&) = default;
log(log &&other, persister_type, heap_type);
~log();
/*
* Make a record of an old value
*/
void add(void *begin, std::size_t size) override;
/*
* Make a record of an allocate
*/
void allocated(void *&p, std::size_t size) override;
/*
* Make a record of a free
*/
void freed(void *&p, std::size_t size) override;
/*
* commit and discard all log entries
*/
void commit() override;
/*
* Restore all data areas added after initialization (or the most recent clear)
* to the values present at their last add command.
*/
void rollback() override;
bool includes(const void *addr) const { return _mr->includes(addr); }
};
struct bad_alloc_log
: public std::bad_alloc
{
bad_alloc_log()
{}
const char *what() const noexcept override
{
return "bad undo log allocate";
}
};
}
#endif
| {
"alphanum_fraction": 0.7052868391,
"avg_line_length": 26.9393939394,
"ext": "h",
"hexsha": "07578156a99aaaeef9858ae9c37006376707e5b6",
"lang": "C",
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z",
"max_forks_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "omriarad/mcas",
"max_forks_repo_path": "src/lib/libccpm/include/ccpm/log.h",
"max_issues_count": 66,
"max_issues_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "omriarad/mcas",
"max_issues_repo_path": "src/lib/libccpm/include/ccpm/log.h",
"max_line_length": 81,
"max_stars_count": 60,
"max_stars_repo_head_hexsha": "f47aab12754c91ebd75b0e1881c8a7cc7aa81278",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "omriarad/mcas",
"max_stars_repo_path": "src/lib/libccpm/include/ccpm/log.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z",
"num_tokens": 678,
"size": 2667
} |
// Authors: David Blei (blei@cs.princeton.edu)
// Sean Gerrish (sgerrish@cs.princeton.edu)
//
// Copyright 2011 Sean Gerrish and David Blei
// All Rights Reserved.
//
// See the README for this package for details about modifying or
// distributing this software.
#ifndef LDASEQ_H
#define LDASEQ_H
#include <sys/stat.h>
#include <sys/types.h>
#include "gsl-wrappers.h"
#include "lda.h"
#define LDA_SEQ_EM_THRESH 1e-4
#define SAVE_LAG 10
/*
* an lda sequence is a collection of simplex sequences for K topics
* and an alpha vector
*
*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <stdlib.h>
#include <assert.h>
#include "param.h"
#include "ss-lm.h"
#include "data.h"
#include "lda.h"
#define LDA_SEQ_EM_THRESHOLD 1e-5;
// lda sequence variational posterior distribution
// === allocation and initialization ===
inf_var* inf_var_alloc(int number_topics,
corpus_seq_t* corpus_seq);
void inf_var_free(inf_var* ptr);
// initialize lda sequence from lda model topics
void init_lda_seq_from_ss(lda_seq* model,
double topic_chain_variance,
double topic_obs_variance,
double alpha,
gsl_matrix* init_suffstats);
// === fitting ===
// infer a corpus with an lda-seq
double update_inf_var(lda_seq* seq,
const corpus_seq_t* data,
gsl_matrix** phi,
size_t t,
const char* root);
double update_inf_var_multiple(lda_seq* seq,
const corpus_seq_t* data,
gsl_matrix** phi,
size_t t,
const char* root);
void update_inf_reg(lda_seq* seq,
const corpus_seq_t* data,
gsl_matrix** phi,
size_t t,
const char* root);
double lda_seq_infer(lda_seq* model,
const corpus_seq_t* data,
gsl_matrix** suffstats,
gsl_matrix* gammas,
gsl_matrix* lhoods,
int iter,
const char* file_root);
// fit lda sequence from sufficient statistics
double fit_lda_seq(lda_seq* m,
const corpus_seq_t* data,
const corpus_seq_t* heldout,
const char* file_root);
void update_lda_seq_ss(int time,
const doc_t* doc,
const lda_post* post,
gsl_matrix** ss);
double fit_lda_seq_topics(lda_seq* model,
gsl_matrix** ss);
// === reading and writing ===
// read and write a lda sequence
void write_lda_seq(const lda_seq* m, const char* root);
lda_seq* read_lda_seq(const char* root, corpus_seq_t* data);
// write lda sequence sufficient statistics
void write_lda_seq_suffstats(lda_seq* m,
gsl_matrix** topic_ss,
const char* root);
// new lda sequence
lda_seq* new_lda_seq(corpus_seq_t* data,
int W,
int T,
int K);
void make_lda_from_seq_slice(lda* lda_m,
lda_seq* lda_seq_m,
int time);
#endif
| {
"alphanum_fraction": 0.6068541869,
"avg_line_length": 23.976744186,
"ext": "h",
"hexsha": "23df02e61b42540d91327b5afdd9ef2dae29fd43",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z",
"max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwangjian/topic-extractor",
"max_forks_repo_path": "scripts/lib/DTM/dtm/lda-seq.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "iwangjian/topic-extractor",
"max_issues_repo_path": "scripts/lib/DTM/dtm/lda-seq.h",
"max_line_length": 68,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwangjian/dtm-lab",
"max_stars_repo_path": "scripts/lib/DTM/dtm/lda-seq.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z",
"num_tokens": 704,
"size": 3093
} |
#if !defined(TESTUTIL_H_INCLUDED)
#define TESTUTIL_H_INCLUDED
#include "Exceptions.h"
#include <gsl/gsl>
#include <iosfwd>
// ===========================================================================
//
// Test case structs
//
// ===========================================================================
using ArgSpan = ::gsl::span<const char*const>;
struct CmdLineParseTestCase
{
template<::std::size_t N>
CmdLineParseTestCase(const char*const(&args)[N]) noexcept
: m_args(::gsl::make_span(args + 1, N - 1)) {}
ArgSpan m_args;
};
struct CmdLineParseFailTestCase : public CmdLineParseTestCase
{
template<::std::size_t N>
CmdLineParseFailTestCase(const char*const(&args)[N], char const* pExMsgPattern) noexcept :
CmdLineParseTestCase(args),
m_pExMsgPattern(pExMsgPattern)
{}
bool doesExMatch(CmdLineError const& ex) const;
char const* m_pExMsgPattern;
};
::std::ostream& operator<<(::std::ostream& ostrm, CmdLineParseTestCase const& tc);
#endif // TESTUTIL_H_INCLUDED
| {
"alphanum_fraction": 0.6218655968,
"avg_line_length": 23.7380952381,
"ext": "h",
"hexsha": "1f2518d2246bc760179ad20ec90f954137458ef7",
"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": "TestUtil.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": "TestUtil.h",
"max_line_length": 91,
"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": "TestUtil.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 244,
"size": 997
} |
#include <blas.h>
#include <inttypes.h>
#include "mex.h"
#include "mx_blas.h"
/* Level 1 BLAS */
void
mx_swap(mxArray *mxx, mxArray *mxy)
{
const ptrdiff_t incx = 1;
const ptrdiff_t incy = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
float *x = (float *)mxGetData(mxx);
float *y = (float *)mxGetData(mxy);
sswap(&n, x, &incx, y, &incy);
} else if (mxIsDouble(mxx)) {
double *x = (double *)mxGetData(mxx);
double *y = (double *)mxGetData(mxy);
dswap(&n, x, &incx, y, &incy);
} else {
mexErrMsgTxt("not implemented");
}
return;
} /* mx_swap() */
void
mx_scal(const double a, mxArray *mxx)
{
const ptrdiff_t incx = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
const float af = (const float)a;
float *x = (float *)mxGetData(mxx);
sscal(&n, &af, x, &incx);
} else if (mxIsDouble(mxx)) {
double *x = (double *)mxGetData(mxx);
dscal(&n, &a, x, &incx);
} else {
mexErrMsgTxt("not implemented");
}
return;
} /* mx_scal() */
void
mx_copy(const mxArray *mxx, mxArray *mxy)
{
const ptrdiff_t incx = 1;
const ptrdiff_t incy = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
float *y = (float *)mxGetData(mxy);
const float *x = (const float *)mxGetData(mxx);
scopy(&n, x, &incx, y, &incy);
} else if (mxIsDouble(mxx)) {
double *y = (double *)mxGetData(mxy);
const double *x = (const double *)mxGetData(mxx);
dcopy(&n, x, &incx, y, &incy);
} else {
mexErrMsgTxt("not implemented");
}
return;
} /* mx_copy() */
void
mx_axpy(const double a, const mxArray *mxx, mxArray *mxy)
{
const ptrdiff_t incx = 1;
const ptrdiff_t incy = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
float *y = (float *)mxGetData(mxy);
const float *x = (const float *)mxGetData(mxx);
const float af = (const float)a;
saxpy(&n, &af, x, &incx, y, &incy);
} else if (mxIsDouble(mxx)) {
double *y = (double *)mxGetData(mxy);
const double *x = (const double *)mxGetData(mxx);
daxpy(&n, &a, x, &incx, y, &incy);
} else {
mexErrMsgTxt("not implemented");
}
return;
} /* mx_axpy() */
double
mx_dot(const mxArray *mxx, const mxArray *mxy)
{
double p = -1.0;
const ptrdiff_t incx = 1;
const ptrdiff_t incy = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
const float *x = (const float *)mxGetData(mxx);
const float *y = (const float *)mxGetData(mxy);
p = (double)sdot(&n, x, &incx, y, &incy);
} else if (mxIsDouble(mxx)) {
const double *x = (const double *)mxGetData(mxx);
const double *y = (const double *)mxGetData(mxy);
p = ddot(&n, x, &incx, y, &incy);
} else {
mexErrMsgTxt("not implemented");
}
return p;
} /* mx_dot() */
double
mx_nrm2(const mxArray *mxx)
{
double p = -1.0;
const ptrdiff_t incx = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
const float *x = (const float *)mxGetData(mxx);
p = (double)snrm2(&n, x, &incx);
} else if (mxIsDouble(mxx)) {
const double *x = (const double *)mxGetData(mxx);
p = dnrm2(&n, x, &incx);
} else {
mexErrMsgTxt("not implemented");
}
return p;
} /* mx_nrm2() */
double
mx_asum(const mxArray *mxx)
{
double p = -1.0;
const ptrdiff_t incx = 1;
const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);
if (mxIsSingle(mxx)) {
const float *x = (const float *)mxGetData(mxx);
p = (double)sasum(&n, x, &incx);
} else if (mxIsDouble(mxx)) {
const double *x = (const double *)mxGetData(mxx);
p = dasum(&n, x, &incx);
} else {
mexErrMsgTxt("not implemented");
}
return p;
} /* mx_asum() */
| {
"alphanum_fraction": 0.5682144567,
"avg_line_length": 23.2111111111,
"ext": "c",
"hexsha": "f2d1d8a649b7f90d75db3dcbbc5716dbd4c67ee6",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-09-21T11:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-06T20:41:34.000Z",
"max_forks_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "n644t031/QSM.m",
"max_forks_repo_path": "src/utils/poisson_solver/mex/mx_blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813",
"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": "n644t031/QSM.m",
"max_issues_repo_path": "src/utils/poisson_solver/mex/mx_blas.c",
"max_line_length": 68,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "WeberLab/QSM.m",
"max_stars_repo_path": "src/utils/poisson_solver/mex/mx_blas.c",
"max_stars_repo_stars_event_max_datetime": "2021-08-18T09:12:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-18T20:04:39.000Z",
"num_tokens": 1324,
"size": 4178
} |
/*
Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
$Id$
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <dirent.h>
#include <sys/time.h>
#include <gsl/gsl_rng.h>
#include "string_f.h"
unsigned long int random_seed()
{
unsigned long int seed;
FILE *devrandom;
if ((devrandom = fopen("/dev/urandom","r")) == NULL) {
#ifdef HAVE_GETTIMEOFDAY
struct timeval tv;
gettimeofday(&tv, 0);
seed = tv.tv_sec + tv.tv_usec;
#else
seed = 0;
#endif
} else {
fread(&seed, sizeof(seed), 1, devrandom);
fclose(devrandom);
}
return seed;
}
void FC_FUNC_(oct_printrecipe, OCT_PRINTRECIPE)
(STR_F_TYPE _dir, STR_F_TYPE filename STR_ARG2)
{
#if HAVE_SCANDIR && HAVE_ALPHASORT
char *lang, *tmp, dir[512];
struct dirent **namelist;
int ii, nn;
gsl_rng *rng;
/* get language */
lang = getenv("LANG");
if(lang == NULL) lang = "en";
/* convert directory from Fortran to C string */
TO_C_STR1(_dir, tmp);
strcpy(dir, tmp);
free(tmp);
strcat(dir, "/recipes");
/* check out if lang dir exists */
nn = scandir(dir, &namelist, 0, alphasort);
if (nn < 0){
printf("Directory does not exist: %s", dir);
return;
}
for(ii=0; ii<nn; ii++)
if(strncmp(lang, namelist[ii]->d_name, 2) == 0){
strcat(dir, "/");
strcat(dir, namelist[ii]->d_name);
break;
}
if(ii == nn)
strcat(dir, "/en"); /* default */
/* clean up */
for(ii=0; ii<nn; ii++)
free(namelist[ii]);
free(namelist);
/* now we read the recipes */
nn = scandir(dir, &namelist, 0, alphasort);
/* initialize random numbers */
gsl_rng_env_setup();
rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng, random_seed());
ii = gsl_rng_uniform_int(rng, nn - 2);
gsl_rng_free(rng);
strcat(dir, "/");
strcat(dir, namelist[ii+2]->d_name); /* skip ./ and ../ */
/* clean up again */
for(ii=0; ii<nn; ii++)
free(namelist[ii]);
free(namelist);
TO_F_STR2(dir, filename);
#else
printf("Sorry, recipes cannot be printed unless scandir and alphasort are available with your C compiler.\n");
#endif
}
| {
"alphanum_fraction": 0.664305949,
"avg_line_length": 23.1475409836,
"ext": "c",
"hexsha": "0a34c02bc2594929f18330b7c87d1324999fda36",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "neelravi/octopus",
"max_forks_repo_path": "src/basic/recipes.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "neelravi/octopus",
"max_issues_repo_path": "src/basic/recipes.c",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "neelravi/octopus",
"max_stars_repo_path": "src/basic/recipes.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 791,
"size": 2824
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include "morn_tensor.h"
void ConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride);
void ConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_height,int knl_width,int y_stride,int x_stride);
struct TensorSampleConvPara
{
MLayer *prev;
int knl_num;
int knl_height;
int knl_width;
int x_stride;
int y_stride;
float sample_ratio;
int res_valid;
float rate;
float decay;
float momentum;
};
void *mTensorSampleConvPara(MSheet *ini,char *name)
{
struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)mMalloc(sizeof(struct TensorSampleConvPara));
char *value = mINIRead(ini,name,"prev");
para->prev = mNetworkLayer(ini,value);
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
value = mINIRead(ini,name,"knl_num");
if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1;
value = mINIRead(ini,name,"knl_height");
if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1;
value = mINIRead(ini,name,"knl_width");
if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1;
value = mINIRead(ini,name,"x_stride");
if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;
value = mINIRead(ini,name,"y_stride");
if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;
value = mINIRead(ini,name,"sample_ratio");
if(value != NULL) para->sample_ratio = atof(value);else para->sample_ratio = 0.5;
value = mINIRead(ini,name,"rate");
if(value != NULL) para->rate = atof(value);
else
{
value = mINIRead(ini,"para","rate");
if(value != NULL) para->rate = atof(value);
else para->rate = 0.001;
}
value = mINIRead(ini,name,"decay");
if(value != NULL) para->decay = atof(value);
else
{
value = mINIRead(ini,"para","decay");
if(value != NULL) para->decay = atof(value);
else para->decay = 0.01;
}
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
value = mINIRead(ini,name,"momentum");
if(value != NULL) para->momentum = atof(value);
else
{
value = mINIRead(ini,"para","momentum");
if(value != NULL) para->momentum = atof(value);
else para->momentum = 0.9;
}
return para;
}
struct HandleTensorSampleConv
{
float *mat;
float *data;
float *kernel;
float *update;
int *locate;
};
void endTensorSampleConv(void *info)
{
struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)info;
if(handle->mat != NULL) mFree(handle->mat );
if(handle->data != NULL) mFree(handle->data );
if(handle->kernel!= NULL) mFree(handle->kernel);
if(handle->update!= NULL) mFree(handle->update);
if(handle->locate!= NULL) mFree(handle->locate);
}
#define HASH_TensorSampleConv 0x8a31af2
void TensorSampleConvSet(MLayer *layer)
{
if(layer->state != DFLT) return;
struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out= layer->tns;
MHandle *hdl=mHandle(out,TensorSampleConv);
struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);
int out_height= in->height/para->y_stride;
int out_width = in->width /para->x_stride;
int mheight = (out_height*out_width);
int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;
int data_size = para->knl_num*(mwidth+1);
mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
if(handle->update != NULL) mFree(handle->update);
handle->update =(float *)mMalloc(data_size*sizeof(float));
memset(handle->update,0,data_size*sizeof(float));
}
if(handle->kernel !=NULL) mFree(handle->kernel);
handle->kernel = (float *)mMalloc(data_size*sizeof(float));
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/mwidth);
for(int i=0;i<data_size;i++)
handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;
}
else
{
mNetworkParaRead(layer,"kernel",handle->kernel,data_size*sizeof(float));
}
int matwidth = para->knl_height*para->knl_width*in->channel+1;
if(handle->mat!=NULL) mFree(handle->mat);
handle->mat = (float *)mMalloc(mheight*matwidth*sizeof(float));
if(handle->data!=NULL) mFree(handle->data);
handle->data= (float *)mMalloc(mheight*(mwidth+1)*sizeof(float));
if(handle->locate!=NULL) mFree(handle->locate);
handle->locate = (int *)mMalloc(mwidth*para->knl_num*sizeof(int));
if(morn_network_parafile==NULL)
{
char *flag = (char *)mMalloc(para->knl_height*para->knl_width*in->channel*sizeof(char));
for(int j=0;j<para->knl_num;j++)
{
memset(flag,1,para->knl_height*para->knl_width*in->channel*sizeof(char));
int *locate = handle->locate+j*mwidth;
for(int i=0;i<mwidth;)
{
locate[i]=mRand(0,para->knl_height*para->knl_width*in->channel);
if(flag[i]==0) continue;
flag[i]=0; i++;
}
mAscSortS32(locate,NULL,locate,NULL,mwidth);
}
mFree(flag);
}
else
{
mNetworkParaRead(layer,"locate",handle->locate,mwidth*para->knl_num*sizeof(int));
}
hdl->valid = 1;
}
void mTensorSampleConvForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("SampleConv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *out=layer->tns;
TensorSampleConvSet(layer);
MHandle *hdl=mHandle(out,TensorSampleConv);
struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);
int mheight = (out->height*out->width);
int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;
int matwidth = para->knl_height*para->knl_width*in->channel+1;
float *mat_data = handle->mat;
float *in_data = handle->data;
for(int b=0;b<in->batch;b++)
{
ConvTensorToMatData(in,b,mat_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
for(int k=0;k<para->knl_num;k++)
{
int *locate = handle->locate+k* mwidth;
float *kernel = handle->kernel+k*(mwidth+1);
float *out_data = out->data[b]+k* mheight;
for(int j=0;j<mheight;j++)
{
for(int i=0;i<mwidth;i++) in_data[j*mwidth+i]=mat_data[j*matwidth+locate[i]];
in_data[j*mwidth+mwidth]=1.0f;
}
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
1,mheight,mwidth+1,
1.0f,
kernel,mwidth+1,
in_data,mwidth+1,
0.0f,out_data,mheight);
}
}
layer->state = MORN_FORWARD;
}
void mTensorSampleConvBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("SampleConv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->res;
MHandle *hdl=mHandle(layer->tns,TensorSampleConv);
struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);
mException((hdl->valid == 0),EXIT,"no forward operate");
int mheight = (out->height*out->width);
int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;
int matwidth = para->knl_height*para->knl_width*in->channel+1;
float *mat_data = handle->mat;
float *in_data = handle->data;
float *res_data = handle->data;
mNetworkParaWrite(layer,"locate",handle->locate,mwidth*para->knl_num*sizeof(int));
mNetworkParaWrite(layer,"kernel",handle->kernel,para->knl_num*mwidth*sizeof(float));
for(int b=0;b<out->batch;b++)
{
ConvTensorToMatData(in,b,mat_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
for(int k=0;k<para->knl_num;k++)
{
int *locate = handle->locate+k* mwidth;
float *update = handle->update+k*(mwidth+1);
float *out_data = out->data[b]+k* mheight;
for(int j=0;j<mheight;j++)
{
for(int i=0;i<mwidth;i++) in_data[j*mwidth+i]=mat_data[j*matwidth+locate[i]];
in_data[j*mwidth+mwidth]=1.0f;
}
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,
1,mwidth,mheight,
1.0f/mheight,
out_data,mheight,
in_data,mwidth,
(b==0)?para->momentum:1.0f,
update,mwidth);
}
}
cblas_saxpby(para->knl_num*mwidth,
(0.0f-(para->rate/(float)(in->batch))),handle->update,1,
(1.0f-(para->decay*para->rate)) ,handle->kernel,1);
if(para->res_valid==0) return;
if(para->prev->state == MORN_FORWARD)
{
for(int b=0;b<res->batch;b++)
memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));
para->prev->state = MORN_BACKWARD;
}
for(int b=0;b<in->batch;b++)
{
memset(mat_data,0,matwidth*mheight*sizeof(float));
for(int k=0;k<para->knl_num;k++)
{
int *locate = handle->locate+k* mwidth;
float *kernel = handle->kernel+k*(mwidth+1);
float *out_data = out->data[b]+k* mheight;
cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,
mheight,mwidth,1,
1.0f,
out_data,mheight,
kernel,mwidth,
0.0,res_data,mwidth);
for(int j=0;j<mheight;j++)
{
for(int i=0;i<mwidth;i++) mat_data[j*matwidth+locate[i]]+=res_data[j*mwidth+i];
}
}
ConvMatDataToTensor(mat_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
}
}
void DirConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_r,int knl_dir,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height=height/y_stride;
int mwidth = (knl_r+knl_r+1)*channel+1;
int mheight= out_height*out_width;
int sx=0,sy=0;
if(knl_dir==0) {sx=0;sy= 1;}
else if(knl_dir==1) {sx=1;sy= 1;}
else if(knl_dir==2) {sx=1;sy= 0;}
else if(knl_dir==3) {sx=1;sy=-1;}
int x0=(width -(out_width -1)*x_stride)/2;
int y0=(height-(out_height-1)*y_stride)/2;
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int i,j,c;
for(j=out_width;j<mheight;j++)
{
int n=y0+j/out_width*y_stride-knl_r*sy;
int m=x0+j%out_width*x_stride-knl_r*sx;
for(i=0;i<mwidth-1;i+=channel)
{
int h=n;if(h<0)h=0;else if(h>=height)h=height-1;
int w=m;if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<channel;c++) mdata[(j*mwidth)+i+c]=tdata[c*tsize+h*width+w];
n=n+sy;m=m+sx;
}
mdata[(j*mwidth)+mwidth-1]=1.0f;
}
}
void DirConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_r,int knl_dir,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height=height/y_stride;
int mwidth = (knl_r+knl_r+1)*channel+1;
int mheight= out_height*out_width;
int sx=0,sy=0;
if(knl_dir==0) {sx=0;sy= 1;}
else if(knl_dir==1) {sx=1;sy= 1;}
else if(knl_dir==2) {sx=1;sy= 0;}
else if(knl_dir==3) {sx=1;sy=-1;}
int x0=(width -(out_width -1)*x_stride)/2;
int y0=(height-(out_height-1)*y_stride)/2;
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int i,j,c;
for(j=0;j<mheight;j++)
{
int n=y0+j/out_width*y_stride-knl_r*sy;
int m=x0+j%out_width*x_stride-knl_r*sx;
for(i=0;i<mwidth-1;i+=channel)
{
int h=n;if(h<0)h=0;else if(h>=height)h=height-1;
int w=m;if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<channel;c++) tdata[c*tsize+h*width+w]+=mdata[(j*mwidth)+i+c];
n=n+sy;m=m+sx;
}
}
}
struct TensorDirConvPara
{
MLayer *prev;
int knl_num;
int knl_r;
int dir;
int x_stride;
int y_stride;
int res_valid;
float rate;
float decay;
float momentum;
};
void *mTensorDirConvPara(MSheet *ini,char *name)
{
struct TensorDirConvPara *para = (struct TensorDirConvPara *)mMalloc(sizeof(struct TensorDirConvPara));
char *value = mINIRead(ini,name,"prev");
para->prev = mNetworkLayer(ini,value);
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
value = mINIRead(ini,name,"knl_num");
if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1;
value = mINIRead(ini,name,"knl_r");
if(value != NULL) para->knl_r= atoi(value);else para->knl_r= 1;
value = mINIRead(ini,name,"dir");
mException((value==NULL),EXIT,"invalid convolution direction");
if((strcmp(value, "u-d" )==0)||(strcmp(value, "d-u" )==0)) para->dir=0;
else if((strcmp(value,"lu-rd")==0)||(strcmp(value,"rd-lu")==0)) para->dir=1;
else if((strcmp(value, "l-r" )==0)||(strcmp(value, "r-l" )==0)) para->dir=2;
else if((strcmp(value,"ru-ld")==0)||(strcmp(value,"ld-ru")==0)) para->dir=3;
else mException(1,EXIT,"invalid convolution direction");
value = mINIRead(ini,name,"x_stride");
if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;
value = mINIRead(ini,name,"y_stride");
if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;
value = mINIRead(ini,name,"rate");
if(value != NULL) para->rate = atof(value);
else
{
value = mINIRead(ini,"para","rate");
if(value != NULL) para->rate = atof(value);
else para->rate = 0.001;
}
value = mINIRead(ini,name,"decay");
if(value != NULL) para->decay = atof(value);
else
{
value = mINIRead(ini,"para","decay");
if(value != NULL) para->decay = atof(value);
else para->decay = 0.01;
}
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
value = mINIRead(ini,name,"momentum");
if(value != NULL) para->momentum = atof(value);
else
{
value = mINIRead(ini,"para","momentum");
if(value != NULL) para->momentum = atof(value);
else para->momentum = 0.9;
}
return para;
}
struct HandleTensorDirConv
{
float *mat;
float *kernel;
float *update;
};
void endTensorDirConv(void *info)
{
struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)info;
if(handle->mat != NULL) mFree(handle->mat);
if(handle->kernel!= NULL) mFree(handle->kernel);
if(handle->update!= NULL) mFree(handle->update);
}
#define HASH_TensorDirConv 0x9e2674b3
void TensorDirConvSet(MLayer *layer)
{
if(layer->state != DFLT) return;
struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out= layer->tns;
MHandle *hdl=mHandle(out,TensorDirConv);
struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);
int out_height= in->height/para->y_stride;
int out_width = in->width /para->x_stride;
int mheight = (out_height*out_width);
int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;
int data_size = para->knl_num*mwidth;
mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
if(handle->update != NULL) mFree(handle->update);
handle->update =(float *)mMalloc(data_size*sizeof(float));
memset(handle->update,0,data_size*sizeof(float));
}
if(handle->kernel !=NULL) mFree(handle->kernel);
handle->kernel = (float *)mMalloc(data_size*sizeof(float));
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/mwidth);
for(int i=0;i<data_size;i++)
handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;
}
else
{
mNetworkParaRead(layer,"kernel",handle->kernel,data_size*sizeof(float));
}
if(handle->mat!=NULL) mFree(handle->mat);
handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));
hdl->valid = 1;
}
void mTensorDirConvForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("DirConv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *out=layer->tns;
TensorDirConvSet(layer);
MHandle *hdl=mHandle(out,TensorDirConv);
struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);
int mheight = (out->height*out->width);
int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;
float *kernel_data= handle->kernel;
float *in_data = handle->mat;
for(int b=0;b<in->batch;b++)
{
DirConvTensorToMatData(in,b,in_data,para->knl_r,para->dir,para->y_stride,para->x_stride);
float *out_data = out->data[b];
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
para->knl_num,mheight,mwidth,
1.0f,
kernel_data,mwidth,
in_data,mwidth,
0.0f, out_data,mheight);
}
layer->state = MORN_FORWARD;
}
void mTensorDirConvBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("DirConv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->res;
MHandle *hdl=mHandle(layer->tns,TensorDirConv);
struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);
mException((hdl->valid == 0),EXIT,"no forward operate");
int mheight = (out->height*out->width);
int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;
float *kernel_data= handle->kernel;
float *update_data= handle->update;
float * in_data= handle->mat;
float * res_data= handle->mat;
mNetworkParaWrite(layer,"kernel",kernel_data,para->knl_num*mwidth*sizeof(float));
for(int b=0;b<out->batch;b++)
{
DirConvTensorToMatData(in,b,in_data,para->knl_r,para->dir,para->y_stride,para->x_stride);
float *out_data = out->data[b];
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,
para->knl_num,mwidth,mheight,
1.0f/mheight,
out_data,mheight,
in_data,mwidth,
(b==0)?para->momentum:1.0f,
update_data,mwidth);
}
cblas_saxpby(para->knl_num*mwidth,
(0.0f-(para->rate/(float)(in->batch))),update_data,1,
(1.0f-(para->decay*para->rate)) ,kernel_data,1);
if(para->res_valid==0) return;
if(para->prev->state == MORN_FORWARD)
{
for(int b=0;b<res->batch;b++)
memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));
para->prev->state = MORN_BACKWARD;
}
for(int b=0;b<in->batch;b++)
{
float *out_data = out->data[b];
cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,
mheight,mwidth,para->knl_num,
1.0f,
out_data,mheight,
kernel_data,mwidth,
0.0, res_data,mwidth);
DirConvMatDataToTensor(res_data,res,b,para->knl_r,para->dir,para->y_stride,para->x_stride);
}
}
| {
"alphanum_fraction": 0.5957941834,
"avg_line_length": 34.3846153846,
"ext": "c",
"hexsha": "c25e6db038fdbd30cd4b8c148070eff996b40400",
"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": "d7617476daf4e7d965ac47b543c8886a6fafce24",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "dianjixz/Morn",
"max_forks_repo_path": "src/deep_learning/morn_tensor_conv2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d7617476daf4e7d965ac47b543c8886a6fafce24",
"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": "dianjixz/Morn",
"max_issues_repo_path": "src/deep_learning/morn_tensor_conv2.c",
"max_line_length": 501,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d7617476daf4e7d965ac47b543c8886a6fafce24",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "dianjixz/Morn",
"max_stars_repo_path": "src/deep_learning/morn_tensor_conv2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6384,
"size": 22350
} |
/*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
/**
* @file MKLHelper.h
* @brief Contains macros to help with various BLAS implementations.
*
* @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)
*/
#ifndef CONV_MKLHELPER_H
#define CONV_MKLHELPER_H
#ifdef BUILD_BLAS
/**
* Here we include our favorite BLAS library and define important functions
* so that they are independent of the type
*/
#ifdef BLAS_ACCELERATE
#include <Accelerate/Accelerate.h>
#define INNERGEMM cblas_sgemm
#define INNERGEMV cblas_sgemv
#endif
#ifdef BLAS_ATLAS
extern "C" {
#include <cblas.h>
}
#define INNERGEMM cblas_sgemm
#define INNERGEMV cblas_sgemv
#endif
#ifdef BLAS_ACML
extern "C" {
#include <cblas.h>
}
#define INNERGEMM cblas_sgemm
#define INNERGEMV cblas_sgemv
#endif
#ifdef BLAS_MKL
extern "C" {
#include <mkl_cblas.h>
}
#define INNERGEMM cblas_sgemm
#define INNERGEMV cblas_sgemv
#endif
#else
#include "Log.h"
#define INNERGEMM(...) { FATAL("GEMM function called without BLAS support!"); }
#define INNERGEMV(...) { FATAL("GEMV function called without BLAS support!"); }
#endif
#endif
| {
"alphanum_fraction": 0.7415384615,
"avg_line_length": 18.0555555556,
"ext": "h",
"hexsha": "e89022bd5250f63c42a3d7b4f4ea00b22db4dc3c",
"lang": "C",
"max_forks_count": 54,
"max_forks_repo_forks_event_max_datetime": "2022-01-06T09:33:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-23T00:22:53.000Z",
"max_forks_repo_head_hexsha": "69aaca014239f0b2aa1dd874e1651906f5a033e1",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "skn123/cn24",
"max_forks_repo_path": "include/private/MKLHelper.h",
"max_issues_count": 29,
"max_issues_repo_head_hexsha": "69aaca014239f0b2aa1dd874e1651906f5a033e1",
"max_issues_repo_issues_event_max_datetime": "2019-04-25T03:55:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-23T10:05:10.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "skn123/cn24",
"max_issues_repo_path": "include/private/MKLHelper.h",
"max_line_length": 79,
"max_stars_count": 141,
"max_stars_repo_head_hexsha": "69aaca014239f0b2aa1dd874e1651906f5a033e1",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "skn123/cn24",
"max_stars_repo_path": "include/private/MKLHelper.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-06T09:33:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-20T18:44:53.000Z",
"num_tokens": 372,
"size": 1300
} |
/*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
/**
Runs the verification procedure in stand-alone mode.
*/
#include "os-features.h"
#include "matchfile.h"
#include "matchobj.h"
#include "index.h"
#include "xylist.h"
#include "rdlist.h"
#include "log.h"
#include "errors.h"
#include "mathutil.h"
#include "verify.h"
#include "verify2.h"
#define SIGN(x) (((x) >= 0) ? (1) : (-1))
static const char* OPTIONS = "hvi:m:f:r:p";
static void print_help(const char* progname) {
printf("Usage: %s\n"
" -m <match-file>\n"
" -f <xylist-file>\n"
" ( -i <index-file>\n"
" OR -r <index-rdls>\n"
" )\n"
" [-v]: verbose\n"
"\n", progname);
}
int Npaths = 0;
static void explore_path(il** reflists, dl** problists, int i, int NT, int NR,
int* theta, double* logprobs,
anbool* refused, int mu,
double distractor, double logbg) {
int j;
double logprob;
FILE* f = stderr;
double logd = log(distractor + (1.0-distractor)*mu / (double)NR) + logbg;
if (i == NT) {
/*
fprintf(f, "allpaths.append(array([");
for (j=0; j<NT; j++)
fprintf(f, "%g,", logprobs[j]);
fprintf(f, "]))\n");
*/
fprintf(f, "alllogprobs.append(%g)\n", logprobs[i-1]);
Npaths++;
return;
}
if (i == 0)
logprob = 0.0;
else
logprob = logprobs[i-1];
for (j=0; reflists[i] && j<il_size(reflists[i]); j++) {
int refi;
refi = il_get(reflists[i], j);
if (refused[refi])
continue;
logprobs[i] = logprob + dl_get(problists[i], j) - logbg;
theta[i] = refi;
//fprintf(f, "plot([%i, %i], [%g, %g], 'r-')\n", i, i+1, logprob, logprobs[i]);
//fprintf(f, "pathsx.append(%i)\npathsy.append(%g)\n", i+1, logprobs[i]);
fprintf(f, "pathsx.append([%i, %i])\npathsy.append([%g, %g])\n", i, i+1, logprob, logprobs[i]);
fprintf(f, "pathst.append(%i)\n", refi);
refused[refi] = TRUE;
explore_path(reflists, problists, i+1, NT, NR, theta, logprobs,
refused, mu+1, distractor, logbg);
refused[refi] = FALSE;
}
logprobs[i] = logprob + logd - logbg;
theta[i] = -1;
//fprintf(f, "plot([%i, %i], [%g, %g], 'r-')\n", i, i+1, logprob, logprobs[i]);
//fprintf(f, "pathsx.append(%i)\npathsy.append(%g)\n", i+1, logprobs[i]);
fprintf(f, "pathsx.append([%i, %i])\npathsy.append([%g, %g])\n", i, i+1, logprob, logprobs[i]);
fprintf(f, "pathst.append(%i)\n", -1);
explore_path(reflists, problists, i+1, NT, NR, theta, logprobs,
refused, mu, distractor, logbg);
}
static void add_radial_and_tangential_correction(const double* in,
double r, double t,
const double* qc,
double* out,
int N) {
int i;
for (i=0; i<N; i++) {
double rdir[2];
// radial vector
rdir[0] = in[2*i+0] - qc[0];
rdir[1] = in[2*i+1] - qc[1];
out[2*i+0] = in[2*i+0] - r * rdir[0] + t * rdir[1];
out[2*i+1] = in[2*i+1] - r * rdir[1] - t * rdir[0];
}
}
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_vector_double.h>
#include "gslutils.h"
void find_cd_correction(const double* testxy, const double* sigma2s, int NT,
const int* theta, const double* refxy, int NR,
const double* crpix) {
gsl_matrix *A;
gsl_vector *B1, *B2, *X1, *X2;
int M, N;
int mu;
int i;
/*
solve min(|B - A*X|^2) for X
B: (refxy - crpix)_{x,y} / sigma
X: CD matrix elements (a,b) and (c,d)
A: (testxy - crpix)_{x,y} / sigma
*/
mu = 0;
for (i=0; i<NT; i++)
if (theta[i] >= 0)
mu++;
// number of samples
M = mu;
// number of coefficients
N = 2;
A = gsl_matrix_alloc(M, N);
B1 = gsl_vector_alloc(M);
B2 = gsl_vector_alloc(M);
mu = 0;
for (i=0; i<NT; i++) {
double w;
if (theta[i] < 0)
continue;
w = 1.0 / sqrt(sigma2s[i]);
gsl_matrix_set(A, mu, 0, w * (testxy[2*i] - crpix[0]));
gsl_matrix_set(A, mu, 1, w * (testxy[2*i+1] - crpix[1]));
gsl_vector_set(B1, mu, w * (refxy[2*theta[i]] - crpix[0]));
gsl_vector_set(B2, mu, w * (refxy[2*theta[i]+1] - crpix[1]));
mu++;
}
if (gslutils_solve_leastsquares_v(A, 2, B1, &X1, NULL, B2, &X2, NULL)) {
ERROR("Failed to solve CD matrix correction\n");
return;
}
logmsg("CD matrix:\n");
logmsg(" %g\n", gsl_vector_get(X1, 0));
logmsg(" %g\n", gsl_vector_get(X1, 1));
logmsg(" %g\n", gsl_vector_get(X2, 0));
logmsg(" %g\n", gsl_vector_get(X2, 1));
gsl_matrix_free(A);
gsl_vector_free(B1);
gsl_vector_free(B2);
gsl_vector_free(X1);
gsl_vector_free(X2);
}
int main(int argc, char** args) {
int argchar;
int loglvl = LOG_MSG;
char* indexfn = NULL;
char* matchfn = NULL;
char* xyfn = NULL;
char* rdfn = NULL;
index_t* index = NULL;
matchfile* mf;
MatchObj* mo;
verify_field_t* vf;
starxy_t* fieldxy;
xylist_t* xyls;
rdlist_t* rdls;
double pix2 = 1.0;
double distractors = 0.25;
double fieldW=0, fieldH=0;
double logbail = log(1e-100);
double logkeep = log(1e12);
double logaccept = LARGE_VAL;
anbool growvariance = TRUE;
anbool fake = FALSE;
double logodds;
anbool do_paths = FALSE;
while ((argchar = getopt(argc, args, OPTIONS)) != -1)
switch (argchar) {
case 'p':
do_paths = TRUE;
break;
case 'r':
rdfn = optarg;
break;
case 'f':
xyfn = optarg;
break;
case 'i':
indexfn = optarg;
break;
case 'm':
matchfn = optarg;
break;
case 'h':
print_help(args[0]);
exit(0);
case 'v':
loglvl++;
break;
}
log_init(loglvl);
if (!(indexfn || rdfn) || !matchfn || !xyfn) {
logerr("You must specify (index (-i) or index rdls (-r)) and matchfile (-m) and field xylist (-f).\n");
print_help(args[0]);
exit(-1);
}
mf = matchfile_open(matchfn);
if (!mf) {
ERROR("Failed to read match file %s", matchfn);
exit(-1);
}
xyls = xylist_open(xyfn);
if (!xyls) {
ERROR("Failed to open xylist %s", xyfn);
exit(-1);
}
// don't need these...
xylist_set_include_flux(xyls, FALSE);
xylist_set_include_background(xyls, FALSE);
fieldW = xylist_get_imagew(xyls);
fieldH = xylist_get_imageh(xyls);
logmsg("Field W,H = %g, %g\n", fieldW, fieldH);
mo = matchfile_read_match(mf);
if (!mo) {
ERROR("Failed to read object from match file.");
exit(-1);
}
mo->wcstan.imagew = fieldW;
mo->wcstan.imageh = fieldH;
fieldxy = xylist_read_field(xyls, NULL);
if (!fieldxy) {
ERROR("Failed to read a field from xylist %s", xyfn);
exit(-1);
}
if (indexfn) {
index = index_load(indexfn, 0);
if (!index) {
ERROR("Failed to open index %s", indexfn);
exit(-1);
}
pix2 += square(index->meta.index_jitter / mo->scale);
} else {
double indexjitter;
rdls = rdlist_open(rdfn);
if (!rdls) {
ERROR("Failed to open rdlist %s", rdfn);
exit(-1);
}
// HACK
indexjitter = 1.0; // arcsec.
pix2 += square(indexjitter / mo->scale);
}
logmsg("Pixel jitter: %g pix\n", sqrt(pix2));
vf = verify_field_preprocess(fieldxy);
if (index) {
mo->logodds = 0.0;
mo->dimquads = index_get_quad_dim(index);
verify_hit(index->starkd, index->meta.cutnside,
mo, NULL, vf,
pix2, distractors, fieldW, fieldH,
logbail, logkeep, logaccept, growvariance,
fake);
logodds = mo->logodds;
index_close(index);
} else {
int cutnside;
int cutnsweeps;
int indexid;
int uni_nw, uni_nh;
int* perm;
double* testxy;
double* refxy;
int i, j, NT, NR;
double* sigma2s = NULL;
rd_t* rd;
double effA;
double qc[2], Q2;
// -get reference stars
rd = rdlist_read_field(rdls, NULL);
if (!rd) {
ERROR("Failed to read rdls field");
exit(-1);
}
NR = rd_n(rd);
refxy = malloc(2 * NR * sizeof(double));
for (i=0; i<NR; i++) {
double ra, dec;
ra = rd_getra (rd, i);
dec = rd_getdec(rd, i);
if (!tan_radec2pixelxy(&(mo->wcstan), ra, dec, refxy + 2*i, refxy + 2*i + 1)) {
ERROR("rdls point projects to wrong side of sphere!");
exit(-1);
}
}
// -remove the ref star closest to each quad star.
for (i=0; i<mo->dimquads; i++) {
double qxy[2];
int besti = -1;
double bestd2 = LARGE_VAL;
if (!tan_xyzarr2pixelxy(&(mo->wcstan), mo->quadxyz + 3*i, qxy, qxy+1)) {
ERROR("quad star projects to wrong side of sphere!");
exit(-1);
}
logmsg("Ref quad star %i is at (%.1f, %.1f)\n", i, qxy[0], qxy[1]);
for (j=0; j<NR; j++) {
double d2 = distsq(qxy, refxy + 2*j, 2);
if (d2 < bestd2) {
bestd2 = d2;
besti = j;
}
}
logmsg("Ref star %i is closest: (%.1f, %.1f)\n", besti, refxy[2*besti+0], refxy[2*besti+1]);
// remove it!
memmove(refxy + 2*besti, refxy + 2*(besti + 1),
2*(NR - besti - 1) * sizeof(double));
NR--;
}
logmsg("Reference stars: %i\n", NR);
indexid = mo->indexid;
if (index_get_missing_cut_params(indexid, &cutnside, &cutnsweeps, NULL, NULL, NULL)) {
ERROR("Failed to get index cut parameters for index id %i", indexid);
exit(-1);
}
verify_get_quad_center(vf, mo, qc, &Q2);
verify_apply_ror(refxy, NULL, &NR, cutnside, mo,
vf, pix2, distractors, fieldW, fieldH,
growvariance, fake,
&testxy, &sigma2s, &NT, &perm, &effA, &uni_nw, &uni_nh);
/*{
double d = distractors;
// Predicted optimal number of reference stars:
int mmax = (int)round(exp(log(effA*(1-d)/(2*M_PI*pix2)) + d*log(d)/(1-d) + (M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA))));
logmsg("mmax = %i\n", mmax);
logmsg("first term: %g\n", effA*(1-d)/(2*M_PI*pix2));
logmsg("second term: %g\n", exp(d*log(d) / (1-d)));
logmsg("third term: %g\n", exp((M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA))));
// Predicted number of reference stars to allow the
// accept threshold to be reached.
double t1 = d*log(d) + (1-d)*(log(effA*(1-d)/(2*M_PI*pix2)) + (M_PI*Q2 + 1)/effA * log(M_PI*Q2 / (M_PI*Q2 + effA)));
for (i=1; i<1000000; i++) {
double logM = i*t1 - i*(1-d)*log(i);
if (logM > logkeep) {
logmsg("m = %i: M = %g\n", i, exp(logM));
break;
}
}
//NR = MIN(NR, 2 * i + 10);
//logmsg("Setting NR to %i\n", NR);
}*/
FILE* f = stderr;
fprintf(f, "distractor = %g\nNR=%i\nNT=%i\n", distractors, NR, NT);
fprintf(f, "W=%i\nH=%i\n", (int)fieldW, (int)fieldH);
fprintf(f, "effA=%g\n", effA);
fprintf(f, "sig2=%g\n", pix2);
fprintf(f, "quadxy = array([");
for (i=0; i<mo->dimquads; i++)
fprintf(f, "[%g,%g],", mo->quadpix[2*i+0], mo->quadpix[2*i+1]);
fprintf(f, "])\n");
fprintf(f, "testxy = array([");
for (i=0; i<NT; i++)
fprintf(f, "[%g,%g],", testxy[2*i+0], testxy[2*i+1]);
fprintf(f, "])\n");
fprintf(f, "sigmas = array([");
for (i=0; i<NT; i++)
fprintf(f, "%g,", sqrt(sigma2s[i]));
fprintf(f, "])\n");
double* rs2 = verify_compute_sigma2s_arr(refxy, NR, qc, Q2, pix2, !fake);
fprintf(f, "refsigmas = array([");
for (i=0; i<NR; i++)
fprintf(f, "%g,", sqrt(rs2[i]));
fprintf(f, "])\n");
free(rs2);
fprintf(f, "refxy = array([");
for (i=0; i<NR; i++)
fprintf(f, "[%g,%g],", refxy[2*i+0], refxy[2*i+1]);
fprintf(f, "])\n");
fprintf(f, "cutx = array([");
for (i=0; i<=uni_nw; i++)
fprintf(f, "%g,", i * fieldW / (float)uni_nw);
fprintf(f, "])\n");
fprintf(f, "cuty = array([");
for (i=0; i<=uni_nh; i++)
fprintf(f, "%g,", i * fieldH / (float)uni_nh);
fprintf(f, "])\n");
double* all_logodds;
int* theta;
int besti;
double worst;
logodds = verify_star_lists(refxy, NR, testxy, sigma2s, NT,
effA, distractors, logbail, logaccept,
&besti, &all_logodds, &theta, &worst);
fprintf(f, "besti = %i\n", besti);
fprintf(f, "worstlogodds = %g\n", worst);
fprintf(f, "logodds = array([");
for (i=0; i<NT; i++)
fprintf(f, "%g,", all_logodds[i]);
fprintf(f, "])\n");
fprintf(f, "theta = array([");
for (i=0; i<NT; i++)
fprintf(f, "%i,", theta[i]);
fprintf(f, "])\n");
// compare observed sigmas to expected...
fprintf(f, "obssigmas=array([");
for (i=0; i<NT; i++) {
double d2, r2;
if (theta[i] < 0)
continue;
d2 = distsq(testxy + 2*i, refxy + 2*theta[i], 2);
r2 = distsq(testxy + 2*i, qc, 2);
fprintf(f, "[%g,%g,%g],", sigma2s[i], d2, r2/Q2);
}
fprintf(f, "])\n");
find_cd_correction(testxy, sigma2s, NT, theta, refxy, NR, qc);
{
// introduce known radial and tangential terms and see if we can recover them...
//add_radial_and_tangential_correction(testxy, -0.01, -0.01, qc, testxy, NT);
// What is the ML correction to rotation and scaling?
// (shear, translation? distortion?)
// -> may need all matches, not just nearest neighbour, to
// do this correctly.
double racc = 0, tacc = 0;
int mu = 0;
for (i=0; i<NT; i++) {
double dxy[2];
double rdir[2];
double R2, ddotr;
double dr[2];
double dt[2];
double fr, ft;
if (theta[i] == -1)
continue;
mu++;
// jitter vector
dxy[0] = testxy[2*i+0] - refxy[2*theta[i]+0];
dxy[1] = testxy[2*i+1] - refxy[2*theta[i]+1];
// radial vector (this should perhaps be to the ref star, not test)
rdir[0] = testxy[2*i+0] - qc[0];
rdir[1] = testxy[2*i+1] - qc[1];
//
R2 = rdir[0]*rdir[0] + rdir[1]*rdir[1];
ddotr = (dxy[0]*rdir[0] + dxy[1]*rdir[1]);
// jitter vector projected onto radial vector.
dr[0] = ddotr * rdir[0] / R2;
dr[1] = ddotr * rdir[1] / R2;
// tangential
dt[0] = dxy[0] - dr[0];
dt[1] = dxy[1] - dr[1];
assert(fabs(dr[0] + dt[0] - dxy[0]) < 1e-10);
assert(fabs(dr[1] + dt[1] - dxy[1]) < 1e-10);
// fractional change in radial, tangential components.
fr = SIGN(ddotr) * sqrt((dr[0]*dr[0] + dr[1]*dr[1]) / R2);
ft = SIGN(rdir[0]*dt[1] - rdir[1]*dt[0]) * sqrt((dt[0]*dt[0] + dt[1]*dt[1]) / R2);
racc += fr;
tacc += ft;
}
racc /= (double)mu;
tacc /= (double)mu;
logmsg("Radial correction: %g\n", racc);
logmsg("Tangential correction: %g\n", tacc);
logmsg("Log-odds: %g\n", logodds);
// Rotate and scale the test stars...
double* t2xy = malloc(NT * 2 * sizeof(double));
add_radial_and_tangential_correction(testxy, racc, tacc, qc, t2xy, NT);
double logodds2 = verify_star_lists(refxy, NR, t2xy, sigma2s, NT,
effA, distractors, logbail, logaccept,
NULL, NULL, NULL, NULL);
logmsg("Log-odds 2: %g\n", logodds2);
fprintf(f, "t2xy = array([");
for (i=0; i<NT; i++)
fprintf(f, "[%g,%g],", t2xy[2*i+0], t2xy[2*i+1]);
fprintf(f, "])\n");
free(t2xy);
}
if (do_paths) {
il** reflist;
dl** problist;
NT = besti+1;
logmsg("Finding all matches...\n");
verify_get_all_matches(refxy, NR, testxy, sigma2s, NT,
effA, distractors, 5.0, 0.5,
&reflist, &problist);
/*
--reflist contains one list per test star, containing the
indices of reference stars within nsigma and within
limit of the distractor rate.
-a "regular" conflict occurs when one reference star
appears in more than one list.
-a "ref" conflict occurs when a list has more than one
element in it.
-each star has some "clique" of stars that it can
interact with (transitive connectivity of the 'nearby'
graph). These will usually be small, but might not
be... We can compute analytically the sums over small,
simple groups, but more complex ones will be very hairy.
*/
double np;
np = 1.0;
for (i=0; i<NT; i++) {
if (!reflist[i])
continue;
np *= (1.0 + il_size(reflist[i]));
}
logmsg("Number of paths: about %g\n", np);
fprintf(f, "allpaths=[]\n");
fprintf(f, "clf()\n");
fprintf(f, "alllogprobs = []\n");
fprintf(f, "pathsx = []\n");
fprintf(f, "pathsy = []\n");
fprintf(f, "pathst = []\n");
int theta[NT];
double logprobs[NT];
anbool refused[NR];
for (i=0; i<NR; i++)
refused[i] = FALSE;
Npaths = 0;
logmsg("Finding all paths...\n");
explore_path(reflist, problist, 0, NT, NR, theta, logprobs, refused, 0, distractors, log(1.0/effA));
logmsg("Number of paths: %i\n", Npaths);
fprintf(f, "pathsx = array(pathsx)\npathsy = array(pathsy)\n");
//fprintf(f, "axis([0, %i, -100, 100])\n", NT);
for (i=0; i<NT; i++) {
il_free(reflist[i]);
dl_free(problist[i]);
}
free(reflist);
free(problist);
}
free(theta);
free(all_logodds);
free(sigma2s);
free(testxy);
free(refxy);
rd_free(rd);
rdlist_close(rdls);
}
logmsg("Logodds: %g\n", logodds);
logmsg("Odds: %g\n", logodds);
verify_field_free(vf);
starxy_free(fieldxy);
xylist_close(xyls);
matchfile_close(mf);
return 0;
}
| {
"alphanum_fraction": 0.4725073132,
"avg_line_length": 30.8394495413,
"ext": "c",
"hexsha": "3725178582ab108b9f61d77878682fb1486b4ec0",
"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": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "solver/verify-paths.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "solver/verify-paths.c",
"max_line_length": 139,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "solver/verify-paths.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6070,
"size": 20169
} |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
// y' = 2y + x
// https://www.wolframalpha.com/input/?i=y%27+%3D+2y+%2B+x%2C+y%280%29+%3D+1%2C+y%281%29
// https://www.wolframalpha.com/input/?i=1%2F4+*+%285+*+e%5E2+-+3%29
// 미분 방정식을 푸는 방법
// 1. 미분 방정식의 표준형을 작성한다.
// y' <<<--- 미분항의 계수를 1로 만들어야 표준형이됨
// 2. 표준형의 y항 계수식을 통해 적분 인자를 구한다.
// 3. 적분 인자를 양변에 곱한다.
// 2y' + y = 3 -> y' + y / 2 = 3 / 2
// 여기서 적분 인자는 1 / 2가 됨
// 좀 더 정확하게는 exp^integral(1/2) 형태가 됨
// 4. 양변에 대한 계산(적분)을 진행한다.
// 5. 양변을 exp^적분인자 로 나누어 y에 대해 정리한다.
int odefunc (double x, const double y[], double f[], void *params)
{
// 계산하고자 하는 미분 방정식의 표준형식을 여기에 기록함
f[0] = x+2*y[0];
return GSL_SUCCESS;
}
int * jac;
int main(void)
{
// 1계 미분 방정식
// 만약 2계 미분 방정식이라면 dim = 2
int dim = 1;
// 미방을 풀기 위한 데이터 타입
gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};
// 드라이버는 미방을 쉽게 풀 수 있도록 시간에 따른 변화, 제어, 스텝에 대한 래퍼
// gsl_odeiv2_step_rkf45는 룬게쿠타 4-5차를 의미함
// Taylor(테일러) 혹은 Maculaurin(맥클로린) 급수
// 테일러 급수를 활용해서 미분을 4번이상 하여
// 오차를 최소화하는 방식을 룬게쿠타 4-5차라고 표현함
// 다음 인자는 미분방정식의 시작지점
// 절대적인 에러 바운드와 상대적인 에러 바운드
gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);
int i;
double x0 = 0.0, xf = 10.0; /* start and end of integration interval */
double x = x0;
double y[1] = { 1.0 }; /* initial value */
// 루프를 돌면서 각 케이스별 미분 방정식을 계산함
for (i = 1; i <= xf; i++)
{
// 0 ~ 10 - x input
double xi = x0 + i * (xf-x0) / xf;
// 결국 이 코드를 다시 재해석하자면
// x가 0일 경우, 1일 경우, ... , 10일 경우에 대해 각각을 해석한다고 보면 됩니다!
// 앞서서 룬게쿠타 4-5차 방식으로 미분 방정식을 계산하도록
// odefunc을 만들었고 이에 대한 설정값들로 xi를 넣고 이에 대한 y값을 계산한다.
int status = gsl_odeiv2_driver_apply (d, &x, xi, y);
if (status != GSL_SUCCESS)
{
printf ("error, return value=%d\n", status);
break;
}
printf ("%.8e %.8e\n", x, y[0]);
printf ("x = %lf, xi = %lf\n", x, xi);
}
// malloc 혹은 new 처럼 Heap에 메모리를 할당하기 때문에
// free를 사용해서 메모리 해제를 해주셔야 메모리 누수를 방지할 수 있음
gsl_odeiv2_driver_free (d);
return 0;
}
| {
"alphanum_fraction": 0.5767790262,
"avg_line_length": 28.1052631579,
"ext": "c",
"hexsha": "b0a39403bf75581305ea39b519b31463308ebebd",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_forks_repo_path": "ch4/src/main/ode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"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": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_issues_repo_path": "ch4/src/main/ode.c",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_stars_repo_path": "ch4/src/main/ode.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z",
"num_tokens": 1239,
"size": 2136
} |
#include <malloc.h>
#include <math.h>
#include <memory.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_matrix_double.h>
#include "tc_mat.h"
struct tc_mat *tc_mat_ctr(uint32_t nr_, uint32_t nc_)
{
struct tc_mat *A = (struct tc_mat *) malloc(sizeof(struct tc_mat));
memset(A, 0, sizeof(struct tc_mat));
tc_mat_resize(A, nr_, nc_);
return A;
}
void tc_mat_dtr(struct tc_mat *A)
{
if (!A)
return;
tc_mat_clear(A);
free(A);
}
void tc_mat_clear(struct tc_mat *A)
{
if (!A)
return;
if (A->a) {
for(uint32_t r=0; r < A->nr; r++)
if (A->a[r])
free(A->a[r]);
free(A->a);
}
A->a = NULL;
A->nr = 0;
A->nc = 0;
}
void tc_mat_print(const struct tc_mat *A)
{
if (!A)
return;
for(uint32_t i=0; i < A->nr; i++) {
for (uint32_t j=0; j < A->nc; j++)
printf(" %13.10f", A->a[i][j]);
printf("\n");
}
}
void tc_mat_resize(struct tc_mat *A, uint32_t nr_, uint32_t nc_)
{
if ((A->nr == nr_) && (A->nc == nc_))
return;
tc_mat_clear(A);
A->nr = nr_;
A->nc = nc_;
A->a = (double **) malloc(sizeof(double *) * nr_);
for(uint32_t r=0; r < nr_; r++)
A->a[r] = (double *) malloc(sizeof(double) * nc_);
}
void tc_mat_copy(struct tc_mat *B, const struct tc_mat *A)
{
if (A == B)
return;
if ((B->nr != A->nr) || (B->nc != A->nc))
tc_mat_resize(B, A->nr, A->nc);
for(uint32_t i=0; i < A->nr; i++)
for(uint32_t j=0; j < A->nc; j++)
B->a[i][j] = A->a[i][j];
}
void tc_mat_identity(struct tc_mat *A)
{
for(uint32_t i=0; i < A->nr; i++)
for(uint32_t j=0; j < A->nc; j++)
A->a[i][j] = (i==j)? 1.0: 0.0;
}
void tc_mat_transpose(struct tc_mat *B, const struct tc_mat *A)
{
if (A == B) {
struct tc_mat *b = tc_mat_ctr(A->nc, A->nr);
for(uint32_t i=0; i < A->nr; i++)
for(uint32_t j=0; j < A->nc; j++)
b->a[j][i] = A->a[i][j];
tc_mat_copy(B, b);
tc_mat_dtr(b);
return;
}
if ((B->nr != A->nc) || (B->nc != A->nr))
tc_mat_resize(B, A->nc, A->nr);
for(uint32_t i=0; i < A->nr; i++)
for(uint32_t j=0; j < A->nc; j++)
B->a[j][i] = A->a[i][j];
}
int tc_mat_add(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B)
{
if (!C || !A || !B || (A->nr != B->nr) || (A->nc != B->nc))
return -1;
if ((C->nr != A->nr) || (C->nc != A->nc))
tc_mat_resize(C, A->nr, B->nc);
for(uint32_t i=0; i < C->nr; i++)
for(uint32_t j=0; j < C->nc; j++)
C->a[i][j] = A->a[i][j] + B->a[i][j];
return 0;
}
int tc_mat_mult(struct tc_mat *C, const struct tc_mat *A, const struct tc_mat *B)
{
if (!C || !A || !B || (A->nc != B->nr))
return -1;
if ((C == A) || (C == B)) {
struct tc_mat *c = tc_mat_ctr(A->nr, B->nr);
tc_mat_mult(c, A, B);
tc_mat_copy(C, c);
tc_mat_dtr(c);
return 0;
}
if ((C->nc != B->nc) || (C->nr != A->nr))
tc_mat_resize(C, A->nr, B->nc);
for(uint32_t i=0; i < C->nr; i++) {
for(uint32_t j=0; j < C->nc; j++) {
C->a[i][j] = 0.0;
for(uint32_t k=0; k < A->nc; k++)
C->a[i][j] += A->a[i][k] * B->a[k][j];
}
}
return 0;
}
int tc_mat_mult_scalar(struct tc_mat *C, double a, const struct tc_mat *B)
{
if (!C || !B)
return -1;
if ((C->nr != B->nr) || (C->nc != B->nc))
tc_mat_resize(C, B->nr, B->nc);
for(uint32_t i=0; i < C->nr; i++)
for(uint32_t j=0; j < C->nc; j++)
C->a[i][j] = a * B->a[i][j];
return 0;
}
/* Householder Reduction to Bidiagonal Form
* Input m x n matrix A
* Output: m x n matrix U, products of Householder matrices
* m x n matrix B, bidiagonal
* m x n matrix V, products of Householder matrices
* such that A = U B V^T
*
* A Householder matrix P is a reflection transformation of the form
* I - tau u u^T where tau = 2 / (u^T u). P is orthonormal since
* P^T P = (I - tau u u^T)^T (I - tau u u^T)
* = (I - tau u u^T) (I - tau u u^T)
* = I - 2 tau u u^T + tau^2 u (u^T u) u^T
* = I - 2 tau u u^T + tau^2 u (2 / tau) u^T
* = I
* Products of orthonomal matrices are orthonormal so U and V will be
* orthonormal.
*
* B is constructed via the algorithm
* 1. B <-- A
* 2. U <-- I m x n
* 3. V <-- I n x n
* 4. For k = 1, ..., n
* a. construct a Householder matrix P such that
* i. P is the identity on the first k-1 components, and
* ii. the k-th column of P B is zero below the diagonal.
* b. B <--- P B
* c. U <--- U P
* d. If k < n - 2, increment k and repeat steps a-c for the
* operation from the right (the row of B P will be zero
* to the right of the superdiagonal).
*
* Step 4a(i) is equivalent to setting the first k-1 components of u
* to be zero. Let v be the k-th column of P B. Since
* P v = (I - tau u u^T) v
* = (I - tau u u^T) v
* = v - tau (u^T v) u (Eq. 1)
* we have that step 4a(ii) is equivalent to setting u to be an appropriate
* scalar multiple of v for all components above k. The previous steps
* would have zeroed out the first k-2 components of v. Let
* b^2 = Sum_{i>=k} (v_i)^2
* and choose the sign of b to ensure s = v_k - b is nonzero. Set u = v/s
* on all components larger than k and set u_k = 1. Then
* tau = 2 / (u^T u)
* = 2 / (1 + (b^2 - (v_k)^2) / s^2 )
* = (2 s) / (s + (b^2 - (v_k)^2) / s)
* = (2 s) / (s - (b + v_k))
* = (2 s) / ((v_k - b) - (b + v_k))
* = (2 s) / (- 2 b)
* = -s / b
* This leads to the zeroing out of the lower components of P v since
* u^T v = v_k + (b^2 - (v_k)^2) / s
* = v_k - (b + v_k)
* = b
* meaning that Eq 1 is simply
* P v = v - (-s/b) (b) u
* = v + s u
* and so P v is zero on all components larger than k.
*
* Side note on efficiency 1 (not implemented):
* Step c produces U and V as products of Housholder matrices. The actual
* computation of these products is not the most computationally efficient
* method. A Housholder matrix acts on a vector v as
* P v = (I - tau u u^T) v
* = v - tau u (v^T u)^T (Eq. 2)
* Thus if we've recorded all u's and tau's, we can find U, the product of
* all the P's, by sequentially applying Eq 2 to the components e1, e2, etc.
*
* Side note on efficiency 2 (not implemented):
* Since each iteration of B leads to known places where its terms have zeros,
* all matrix multiplications involving B can be restricted to the nonzero
* terms.
*
* Side note on efficiency 3 (not implemented):
* Since the u's have more zeros in each iteration, the collection of u's
* can be stored in the original matrix A (and hence B) so long as the
* Side note on efficiency #2 was implemented.
*/
int tc_mat_bidiag_decomp(
const struct tc_mat *A,
struct tc_mat *U,
struct tc_mat *B,
struct tc_mat *V)
{
if (!A || !U || !B || !V)
return -1;
if ((U->nr != A->nr) || (U->nc != A->nr))
tc_mat_resize(U, A->nr, A->nr);
if ((V->nr != A->nc) || (V->nc != A->nc))
tc_mat_resize(V, A->nc, A->nc);
if ((B->nr != A->nr) || (B->nc != A->nc))
tc_mat_resize(B, A->nr, A->nc);
tc_mat_copy(B, A);
tc_mat_identity(U);
tc_mat_identity(V);
struct tc_mat *Ic = tc_mat_ctr(A->nc, A->nc);
tc_mat_identity(Ic);
struct tc_mat *Ir = tc_mat_ctr(A->nr, A->nr);
tc_mat_identity(Ir);
struct tc_mat *u = tc_mat_ctr(0, 0);
struct tc_mat *uT = tc_mat_ctr(0, 0);
struct tc_mat *u_uT = tc_mat_ctr(0, 0);
struct tc_mat *P = tc_mat_ctr(0, 0);
for(uint32_t k=0; (k < A->nc) && (k+1 < A->nr); k++) {
/* from the left */
double b_k = B->a[k][k];
double b = 0.0;
for(uint32_t i=k; i < A->nr; i++)
b += B->a[i][k] * B->a[i][k];
if (b != 0.0) { /* if b = 0, there's nothing to do */
b = ((b_k > 0)? -1.0: 1.0) * sqrt(b);
double s = b_k - b;
double tau = - s / b;
tc_mat_resize(u, A->nr, 1);
for(uint32_t i=0; i < A->nr; i++)
u->a[i][0] = (i > k)? B->a[i][k]/s: ((i==k)? 1.0: 0.0);
/* P = I - tau u u^T */
tc_mat_transpose(uT, u);
tc_mat_mult(u_uT, u, uT);
tc_mat_mult_scalar(P, -tau, u_uT);
tc_mat_add(P, Ir, P);
/* U B = (U P) (P B) */
tc_mat_mult(B, P, B);
tc_mat_mult(U, U, P);
}
if (k + 2 < A->nc) {
/* from the right */
double b_k = B->a[k][k+1];
double b = 0.0;
for(uint32_t j=k+1; j < A->nc; j++)
b += B->a[k][j] * B->a[k][j];
b = ((b_k > 0)? -1.0: 1.0) * sqrt(b);
if (b != 0.0) { /* if b = 0, there's nothing to do */
double s = b_k - b;
double tau = - s / b;
tc_mat_resize(u, A->nc, 1);
for(uint32_t i=0; i < A->nc; i++)
u->a[i][0] = (i > k+1)? B->a[k][i]/s: ((i==k+1)? 1.0: 0.0);
/* P = I - tau u u^T */
tc_mat_transpose(uT, u);
tc_mat_mult(u_uT, u, uT);
tc_mat_mult_scalar(P, -tau, u_uT);
tc_mat_add(P, Ic, P);
/* B V = (B P) (P V) */
tc_mat_mult(B, B, P);
tc_mat_mult(V, P, V);
}
}
}
tc_mat_dtr(P);
tc_mat_dtr(u);
tc_mat_dtr(uT);
tc_mat_dtr(u_uT);
tc_mat_dtr(Ic);
tc_mat_dtr(Ir);
return 0;
}
/* tc_mat_eigenvalues
* only implmented for 2x2 matrices
* Input 2 x 2 matrix A
* Output: 2 x 1 matrix E of eigenvalues
*
* If we set A = [ a b ]
* [ c d ]
* Then
* 0 = det(A - x I)
* = (a - x)(d - x) - bc
* = x^2 - (a + d) x + (ad - bc)
*/
int tc_mat_eigenvalues(struct tc_mat *E, const struct tc_mat *A)
{
if (!A || !E)
return -1;
if ((A->nr != 2) || (A->nc != 2))
return -1;
if (E->nr != A->nr)
tc_mat_resize(E, A->nr, 1);
double a = A->a[0][0];
double b = A->a[1][0];
double c = A->a[0][1];
double d = A->a[1][1];
double ad2 = (a + d)/2.0;
double det = ad2*ad2 - (a*d - b*c);
double s = (det <= 0.0)? 0.0: sqrt(det);
E->a[0][0] = ad2 + s;
E->a[1][0] = ad2 - s;
return 0;
}
/* Wilkinson Shift
* Input: m x 2 matrix A
* Output: the Wilkinson shift
*
* ei= trailing 2x2 matrix of D^T D */
double tc_mat_wilkinson_shift(const struct tc_mat *A)
{
if (!A)
return 0.0;
if (A->nc != 2)
return 0.0;
struct tc_mat *AT = tc_mat_ctr(2, A->nr);
tc_mat_transpose(AT, A);
struct tc_mat *AT_A = tc_mat_ctr(2, 2);
tc_mat_mult(AT_A, AT, A);
struct tc_mat *E = tc_mat_ctr(2, 1);
tc_mat_eigenvalues(E, AT_A);
double l0 = E->a[0][0];
double l1 = E->a[1][0];
double t22 = AT_A->a[1][1];
tc_mat_dtr(AT);
tc_mat_dtr(AT_A);
tc_mat_dtr(E);
return (fabs(l0 - t22) < fabs(l1 - t22))? l0: l1;
}
int tc_mat_svd(
const struct tc_mat *A,
struct tc_mat *U,
struct tc_mat *D,
struct tc_mat *V)
{
if (!U || !D || !V || !A)
return -1;
if ((U->nr != A->nr) || (U->nc != A->nc))
tc_mat_resize(U, A->nr, A->nc);
if ((V->nr != A->nc) || (V->nc != A->nc))
tc_mat_resize(V, A->nc, A->nc);
if ((D->nr != A->nc) || (D->nc != A->nc))
tc_mat_resize(D, A->nc, A->nc);
if (A->nr < A->nc)
return -2;
/* case nc = 1 */
if (A->nc == 1) {
V->a[0][0] = 1.0;
double normsq = 0.0;
for(uint32_t i=0; i < A->nr; i++)
normsq += A->a[i][0] * A->a[i][0];
D->a[0][0] = sqrt(normsq);
if (D->a[0][0] == 0.0)
tc_mat_copy(U, A);
else {
double inv = 1.0 / D->a[0][0];
for(uint32_t i=0; i < A->nr; i++)
U->a[i][0] = A->a[i][0] * inv;
}
return 0;
}
/* Step1: A = U D V where D is bi-diagonal
* A is nr x nc
* U is nr x nr
* D is nr x nc
* V is nc x nc
*
* If A was not a square matrix, change U and D
* U nr x nc
* D nc x nc
*/
tc_mat_bidiag_decomp(A, U, D, V);
if (D->nr != D->nc) {
struct tc_mat *U0 = tc_mat_ctr(A->nr, A->nc);
for(uint32_t i=0; i < A->nr; i++)
for(uint32_t j=0; j < A->nc; j++)
U0->a[i][j] = U->a[i][j];
tc_mat_resize(U, A->nr, A->nc);
tc_mat_copy(U, U0);
tc_mat_dtr(U0);
struct tc_mat *D0 = tc_mat_ctr(A->nc, A->nc);
for(uint32_t i=0; i < A->nc; i++)
for(uint32_t j=0; j < A->nc; j++)
D0->a[i][j] = D->a[i][j];
tc_mat_resize(D, A->nc, A->nc);
tc_mat_copy(D, D0);
tc_mat_dtr(D0);
}
/* iterate until either max_iterations has been hit
* or the largest superdiagonal entry is below the
* threshold. Set threshold = 1-e8 * largest element.
* Any term less than 0.1 threshold will be considered
* to be zero.
*/
const uint32_t max_iterations = 100 * D->nc;
double threshold = D->a[0][0];
for(uint32_t i=0; i < D->nc; i++)
if (fabs(D->a[i][i]) > threshold)
threshold = fabs(D->a[i][i]);
for(uint32_t i=0; i+1 < D->nc; i++)
if (fabs(D->a[i][i+1]) > threshold)
threshold = fabs(D->a[i][i+1]);
threshold *= 1e-12;
const double zero_threshold = 0.1 * threshold;
/* Always reindex the components so that
* D so that has the form
* [D1, 0] where D1 is diagonal and
* [ 0,D2] D2 is bidiagonal
* Let i0 be the starting index of D2
*/
uint32_t i0 = 0;
for(uint32_t I=0; I < max_iterations; I++)
{
/* For any zeros on the diagonal, apply a series of
* Givens rotations to also zero out its off-diagonal
* term. Then move this component into D1.
*/
for(uint32_t i1=i0; i1 < D->nr; i1++) {
if (fabs(D->a[i1][i1]) > zero_threshold)
continue;
if ((i1+1 == D->nr) && fabs(D->a[i1-1][i1]) > zero_threshold)
continue;
if ((i1+1 < D->nr) && (fabs(D->a[i1][i1+1]) > zero_threshold)) {
for(uint32_t i=i1; i+1 < D->nr; i++) {
/* U D = (U G) (G^T D) */
double alpha = D->a[i1][i+1];
if (fabs(alpha) < zero_threshold)
break;
double beta = D->a[i+1][i+1];
double gamma = sqrt(alpha*alpha + beta*beta);
double c = beta / gamma;
double s = alpha / gamma;
for(uint32_t j=0; j < D->nr; j++) {
double a = D->a[i1][j];
double b = D->a[i+1][j];
D->a[i1][j] = a*c - b*s;
D->a[i+1][j] = a*s + b*c;
}
for(uint32_t j=0; j < U->nr; j++) {
double a = U->a[j][i1];
double b = U->a[j][i+1];
U->a[j][i1] = a*c - b*s;
U->a[j][i+1] = a*s + b*c;
}
}
i1++;
}
/* move (i0,i1-1) down, i1 -> i0 */
for(uint32_t j=0; j < D->nr; j++) {
double tmp = V->a[i1][j];
for(uint32_t k=i1; k > i0; k--)
V->a[k][j] = V->a[k-1][j];
V->a[i0][j] = tmp;
}
for(uint32_t j=0; j < D->nr; j++) {
double tmp = U->a[j][i1];
for(uint32_t k=i1; k > i0; k--)
U->a[j][k] = U->a[j][k-1];
U->a[j][i0] = tmp;
}
double tmp = D->a[i1][i1];
double tmp1 = D->a[i1][i1+1];
for(uint32_t k=i1; k > i0; k--) {
D->a[k][k] = D->a[k-1][k-1];
if (k+1 < D->nc)
D->a[k][k+1] = D->a[k-1][k];
}
D->a[i0][i0] = tmp;
D->a[i0][i0+1] = tmp1;
i0++;
}
/* For any zeros on the superdiagonal, move the
* component to D1.
*/
for(uint32_t i=i0; i+1 < D->nr; i++) {
if (fabs(D->a[i][i+1]) >= zero_threshold)
continue;
if (i == i0) {
i0++;
continue;
}
if (i+2 != D->nr)
continue;
/* move (i0,i) down, i+1 -> i0 */
for(uint32_t j=0; j < D->nr; j++) {
double tmp = V->a[i+1][j];
for(uint32_t k=i+1; k > i0; k--)
V->a[k][j] = V->a[k-1][j];
V->a[i0][j] = tmp;
}
for(uint32_t j=0; j < D->nr; j++) {
double tmp = U->a[j][i+1];
for(uint32_t k=i+1; k > i0; k--)
U->a[j][k] = U->a[j][k-1];
U->a[j][i0] = tmp;
}
double tmp = D->a[i+1][i+1];
double tmp1 = D->a[i][i+1];
for(uint32_t k=i+1; k > i0; k--) {
D->a[k][k] = D->a[k-1][k-1];
D->a[k-1][k] = (k-1==i0)? tmp1: D->a[k-2][k-1];
}
D->a[i0][i0] = tmp;
i0++;
if ((i+2 == D->nr) && (i0 != i))
i--; /* retry last term */
}
if (i0 >= D->nr - 1)
break;
/* Find largest element on super diagonal.*/
/* Break if less than threshold. */
double largest_off_diag = 0.0;
uint32_t n_zeros_on_off_diagonal = 0;
for(uint32_t i=i0; i+1 < D->nr; i++) {
if (fabs(D->a[i][i+1]) > largest_off_diag)
largest_off_diag = fabs(D->a[i][i+1]);
if (fabs(D->a[i][i+1]) < zero_threshold)
n_zeros_on_off_diagonal++;
}
if (largest_off_diag < threshold)
break;
/* Find the next zero on the uper diagonal*/
/* Treat [i0,i1] as a block. */
uint32_t i1 = i0;
for( ; i1+1 < D->nr; i1++)
if (fabs(D->a[i1][i1+1]) < zero_threshold)
break;
/* Find Wilkerson shift. */
struct tc_mat *t = tc_mat_ctr(3, 2);
for(uint32_t i=0; i < 3; i++)
for(uint32_t j=0; j < 2; j++)
t->a[i][j] = (i1+i>2)? D->a[i1+i-2][i1+j-1]: 0.0;
double mu = tc_mat_wilkinson_shift(t);
tc_mat_dtr(t);
double alpha = D->a[i0][i0] * D->a[i0][i0] - mu;
double beta = D->a[i0][i0] * D->a[i0][i0+1];
/* Apply Givens rotations G from i0 to the bottom,
* chasing the nonzero element until off the matrix
*/
for(uint32_t i=i0; i < i1; i++) {
/* D V = (D G) (G^T V) */
double gamma = sqrt(alpha*alpha + beta*beta);
double c = alpha / gamma;
double s = -beta / gamma;
for(uint32_t j=0; j < D->nr; j++) {
double a = D->a[j][i+0];
double b = D->a[j][i+1];
D->a[j][i+0] = a*c - b*s;
D->a[j][i+1] = a*s + b*c;
}
for(uint32_t j=0; j < D->nc; j++) {
double a = V->a[i+0][j];
double b = V->a[i+1][j];
V->a[i+0][j] = a*c - b*s;
V->a[i+1][j] = a*s + b*c;
}
/* U D = (U G) (G^T D) */
alpha = D->a[i+0][i];
beta = D->a[i+1][i];
gamma = sqrt(alpha*alpha + beta*beta);
if (fabs(gamma) > 0.0) {
c = alpha / gamma;
s = -beta / gamma;
for(uint32_t j=0; j < D->nc; j++) {
double a = D->a[i+0][j];
double b = D->a[i+1][j];
D->a[i+0][j] = a*c - b*s;
D->a[i+1][j] = a*s + b*c;
}
for(uint32_t j=0; j < U->nr; j++) {
double a = U->a[j][i+0];
double b = U->a[j][i+1];
U->a[j][i+0] = a*c - b*s;
U->a[j][i+1] = a*s + b*c;
}
}
if (i + 2 < D->nr) {
alpha = D->a[i][i+1];
beta = D->a[i][i+2];
}
}
}
/* now swap components to order the diagonal terms
* from largest to smallest
*/
for(uint32_t i=0; i+1 < D->nr; i++) {
double largest = fabs(D->a[i][i]);
uint32_t largest_i = i;
for(uint32_t j=i+1; j < D->nr; j++) {
if (fabs(D->a[j][j]) > largest) {
largest_i = j;
largest = fabs(D->a[j][j]);
}
}
if (largest_i != i) {
for(uint32_t j=0; j < D->nr; j++) {
double tmp = V->a[i][j];
V->a[i][j] = V->a[largest_i][j];
V->a[largest_i][j] = tmp;
tmp = U->a[j][i];
U->a[j][i] = U->a[j][largest_i];
U->a[j][largest_i] = tmp;
}
double tmp = D->a[i][i];
D->a[i][i] = D->a[largest_i][largest_i];
D->a[largest_i][largest_i] = tmp;
}
if (D->a[i][i] < 0) {
D->a[i][i] = -D->a[i][i];
for(uint32_t j=0; j < D->nr; j++)
V->a[i][j] = -V->a[i][j];
}
}
/* just to be sure, zero out all off-diagonal terms of D */
for(uint32_t i=0; i < D->nr; i++)
for(uint32_t j=0; j < D->nc; j++)
if (i != j)
D->a[i][j] = 0.0;
/* transpose V */
tc_mat_transpose(V, V);
return 0;
}
| {
"alphanum_fraction": 0.5112353568,
"avg_line_length": 28.4545454545,
"ext": "c",
"hexsha": "912336c4fa250c9bd27f002d354b6a2fcadf8be3",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z",
"max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "endolith/Truthcoin",
"max_forks_repo_path": "lib-other/cpplib/tc_mat.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237",
"max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "endolith/Truthcoin",
"max_issues_repo_path": "lib-other/cpplib/tc_mat.c",
"max_line_length": 81,
"max_stars_count": 161,
"max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "endolith/Truthcoin",
"max_stars_repo_path": "lib-other/cpplib/tc_mat.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z",
"num_tokens": 7516,
"size": 18780
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h
#define polygon_9cb4a5c6_8903_42fd_9232_eb81bfcd30a5_h
#include <gslib/std.h>
#include <gslib/math.h>
#include <ariel/config.h>
__ariel_begin__
class polygon
{
public:
typedef gs::vector<point3> vtstream;
typedef gs::vector<int> idstream;
typedef vtstream::iterator vtiter;
typedef vtstream::const_iterator const_vtiter;
typedef idstream::iterator iditer;
typedef idstream::const_iterator const_iditer;
public:
polygon();
int get_vertex_count() const { return (int)_vtstream.size(); }
int get_index_count() const { return (int)_idstream.size(); }
int get_face_count() const { return _faces; }
int query_face_count();
void write_vtstream(int start, int cnt, const point3* src);
void append_vtstream(int cnt, const point3* src) { write_vtstream(get_vertex_count(), cnt, src); }
void append_vtstream(const point3& src) { _vtstream.push_back(src); }
void write_idstream(int start, int cnt, const int* src);
void append_idstream(int cnt, const int* src) { write_idstream(get_index_count(), cnt, src); }
void append_idstream(int idx) { _idstream.push_back(idx); }
point3& get_vertex(int i) { return _vtstream.at(i); }
const point3& get_vertex(int i) const { return _vtstream.at(i); }
int& get_index(int i) { return _idstream.at(i); }
const int& get_index(int i) const { return _idstream.at(i); }
protected:
vtstream _vtstream;
idstream _idstream;
int _faces;
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.7155353394,
"avg_line_length": 39.1506849315,
"ext": "h",
"hexsha": "e8c89cc4c5187555153d8d32c6b0bc348d77d72f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/polygon.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/polygon.h",
"max_line_length": 103,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/polygon.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 716,
"size": 2858
} |
#pragma once
#include <gsl/gsl>
#include <DirectXMath.h>
#include <vector>
#include <memory>
#include <string>
#include <cstdint>
namespace Library
{
class Model;
class Bone;
class Keyframe;
class OutputStreamHelper;
class InputStreamHelper;
struct BoneAnimationData final
{
std::uint32_t BoneIndex{ 0 };
std::vector<std::shared_ptr<Keyframe>> Keyframes;
};
class BoneAnimation final
{
public:
BoneAnimation(Model& model, InputStreamHelper& streamHelper);
BoneAnimation(Model& model, const BoneAnimationData& boneAnimationData);
BoneAnimation(Model& model, BoneAnimationData&& boneAnimationData);
BoneAnimation(const BoneAnimation&) = default;
BoneAnimation(BoneAnimation&& rhs) = default;
BoneAnimation& operator=(const BoneAnimation& rhs) = default;
BoneAnimation& operator=(BoneAnimation&& rhs) = default;
~BoneAnimation() = default;
Bone& GetBone();
std::vector<std::shared_ptr<Keyframe>>& Keyframes();
std::uint32_t GetTransform(float time, DirectX::XMFLOAT4X4& transform) const;
void GetTransformAtKeyframe(std::uint32_t keyframeIndex, DirectX::XMFLOAT4X4& transform) const;
void GetInteropolatedTransform(float time, DirectX::XMFLOAT4X4& transform) const;
void Save(OutputStreamHelper& streamHelper);
private:
void Load(InputStreamHelper& streamHelper);
std::uint32_t FindKeyframeIndex(float time) const;
Model* mModel;
std::weak_ptr<Bone> mBone;
std::vector<std::shared_ptr<Keyframe>> mKeyframes;
};
}
| {
"alphanum_fraction": 0.7528542646,
"avg_line_length": 27.5740740741,
"ext": "h",
"hexsha": "1cf41c9e4d32a0d514a71befe1ec3af945b0d459",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/BoneAnimation.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/BoneAnimation.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/BoneAnimation.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 379,
"size": 1489
} |
#ifndef TOURNAMENTPIVOTING_H
#define TOURNAMENTPIVOTING_H
#include <stdio.h>
#include <stdlib.h>
#include "SuiteSparseQR_C.h"
#include <string.h>
#include <math.h>
#include <mpi.h>
#ifdef MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#define ASSERT(t_) if(!(t_)) printf("WARNING %s, line %d\n",__FILE__,__LINE__)
#ifndef MAX
#define MAX(a_,b_) ((a_)>(b_)?(a_):(b_))
#endif
#define DBL_EPSILON 1e-15
int preAlps_tournamentPivoting(MPI_Comm comm, int *colPtr, int *rowInd, double *a, int m, int n, int nnz, long col_offset, int k, long *Jc,
double *Sval, int printSVal, int ordering);
int preAlps_tournamentPivotingQR(MPI_Comm comm, int *colPtr, int *rowInd, double *a, int m, int n, int nnz,
long col_offset, int k, long *Jc, double *Sval, int printSVal, int checkFact, int printFact, int ordering);
int preAlps_tournamentPivotingCUR(MPI_Comm comm, int *colPtr, int *rowInd, double *a, int m, int n, int nnz,
long col_offset, int k, long *Jr, long *Jc, double *Sval, int printSVal, int checkFact, int printFact, int ordering);
#endif
| {
"alphanum_fraction": 0.7168224299,
"avg_line_length": 30.5714285714,
"ext": "h",
"hexsha": "d174f977a76852f54c53655ad7b1631d04431aaf",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-10-05T11:22:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-17T22:41:41.000Z",
"max_forks_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "W-Wuxian/preAlps",
"max_forks_repo_path": "utils/iterativeKernels/include/tournamentPivoting.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0",
"max_issues_repo_issues_event_max_datetime": "2019-03-14T16:11:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-14T16:11:37.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "W-Wuxian/preAlps",
"max_issues_repo_path": "utils/iterativeKernels/include/tournamentPivoting.h",
"max_line_length": 141,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "9718968d3474be821ceb676ceff8e1dee1dae2f0",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "W-Wuxian/preAlps",
"max_stars_repo_path": "utils/iterativeKernels/include/tournamentPivoting.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-25T17:42:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-28T12:30:06.000Z",
"num_tokens": 358,
"size": 1070
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: stdheader.h
* Author: lars
*
* Created on May 19, 2020, 2:40 PM
*/
#ifndef STDHEADER_H
#define STDHEADER_H
#include <string>
#include <vector>
#include <random>
#include <chrono>
#include <limits>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <cstddef>
#include <regex>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <tuple>
#include <map>
#include <utility>
#include <iomanip>
#include <type_traits>
#include <set>
#include <experimental/filesystem>
#include <filesystem>
#include <time.h>
#include <unordered_set>
#include <unordered_map>
//simple parallel
#include <parallel/algorithm>
//#include <experimental/algorithm>
#include <nlohmann/json.hpp>
#include <gsl/gsl_statistics_double.h>
#include "CLI11.hpp"
#include <essentia/algorithmfactory.h>
#include <essentia/streaming/algorithms/poolstorage.h>
#include <essentia/streaming/algorithms/fileoutput.h>
#include <essentia/pool.h>
#include <essentia/essentiamath.h>
#include "statInterface.h"
#include "utilities.h"
#include "featureSelektor.h"
#include "AudioFeature.h"
#include "GLCM.h"
#include "FACM.h"
#include "Haralick.h"
#include "AudioFile.h"
#include "distanceMetric.h"
#include "essentiaInterface.h"
#include "Json_Handler.h"
#include "printObjects.h"
#include "CLIHandler.h"
#include "src/hierarchCluster/fastcluster.h"
#include "simpleTests.h"
#endif /* STDHEADER_H */
| {
"alphanum_fraction": 0.7481155779,
"avg_line_length": 22.7428571429,
"ext": "h",
"hexsha": "5c753d3c4c42dae88f43ab2481649796799a2dc1",
"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": "deb2db22a3792a2d11035a60963c0522730b31ee",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Quodoso/SampleOrganiser",
"max_forks_repo_path": "stdheader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "deb2db22a3792a2d11035a60963c0522730b31ee",
"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": "Quodoso/SampleOrganiser",
"max_issues_repo_path": "stdheader.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "deb2db22a3792a2d11035a60963c0522730b31ee",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Quodoso/SampleOrganiser",
"max_stars_repo_path": "stdheader.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 392,
"size": 1592
} |
// Copyright (c) 2021 Stig Rune Sellevag
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef SCILIB_LINALG_EIGENVALUE_H
#define SCILIB_LINALG_EIGENVALUE_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <exception>
#include <cassert>
#include <complex>
#include <type_traits>
namespace Sci {
namespace Linalg {
// Compute eigenvalues and eigenvectors of a real symmetric matrix.
template <class Layout>
inline void eigs(Sci::Matrix_view<double, Layout> a,
Sci::Vector_view<double, Layout> w,
double abstol = -1.0 /* use default value */)
{
static_assert(a.is_contiguous());
static_assert(w.is_contiguous());
assert(a.extent(0) == a.extent(1));
assert(w.extent(0) == a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT nselect = n;
const BLAS_INT lda = n;
const BLAS_INT ldz = nselect;
BLAS_INT il = 1;
BLAS_INT iu = n;
BLAS_INT m;
BLAS_INT info;
double vl = 0.0;
double vu = 0.0;
Sci::Vector<BLAS_INT, Layout> isuppz(2 * n);
Sci::Matrix<double, Layout> z(ldz, n);
auto matrix_layout = LAPACK_ROW_MAJOR;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
}
info = LAPACKE_dsyevr(matrix_layout, 'V', 'A', 'U', n, a.data(), lda, vl,
vu, il, iu, abstol, &m, w.data(), z.data(), ldz,
isuppz.data());
if (info != 0) {
throw std::runtime_error("dsyevr failed");
}
Sci::copy(z.view(), a);
}
template <class Layout, class Allocator>
inline void eigs(Sci::Matrix<double, Layout, Allocator>& a,
Sci::Vector<double, Layout, Allocator>& w,
double abstol = -1.0 /* use default value */)
{
eigs(a.view(), w.view(), abstol);
}
// Compute eigenvalues and eigenvectors of a real non-symmetric matrix.
template <class Layout>
void eig(Sci::Matrix_view<double, Layout> a,
Sci::Matrix_view<std::complex<double>, Layout> evec,
Sci::Vector_view<std::complex<double>, Layout> eval)
{
using namespace Sci;
static_assert(a.is_contiguous());
static_assert(evec.is_contiguous());
static_assert(eval.is_contiguous());
assert(a.extent(0) == a.extent(1));
assert(a.extent(0) == eval.extent(0));
assert(a.extent(0) == evec.extent(0));
assert(a.extent(1) == evec.extent(1));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
Sci::Vector<double, Layout> wr(n);
Sci::Vector<double, Layout> wi(n);
Sci::Matrix<double, Layout> vr(n, n);
Sci::Matrix<double, Layout> vl(n, n);
auto matrix_layout = LAPACK_ROW_MAJOR;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
}
BLAS_INT info =
LAPACKE_dgeev(matrix_layout, 'N', 'V', n, a.data(), n, wr.data(),
wi.data(), vl.data(), n, vr.data(), n);
if (info != 0) {
throw std::runtime_error("dgeev failed");
}
for (BLAS_INT i = 0; i < n; ++i) {
std::complex<double> wii(wr(i), wi(i));
eval(i) = wii;
BLAS_INT j = 0;
while (j < n) {
if (wi(j) == 0.0) {
evec(i, j) = std::complex<double>{vr(i, j), 0.0};
++j;
}
else {
evec(i, j) = std::complex<double>{vr(i, j), vr(i, j + 1)};
evec(i, j + 1) = std::complex<double>{vr(i, j), -vr(i, j + 1)};
j += 2;
}
}
}
}
template <class Layout,
class Allocator_a,
class Allocator_evec,
class Allocator_eval>
void eig(Sci::Matrix<double, Layout, Allocator_a>& a,
Sci::Matrix<std::complex<double>, Layout, Allocator_evec>& evec,
Sci::Vector<std::complex<double>, Layout, Allocator_eval>& eval)
{
eig(a.view(), evec.view(), eval.view());
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_EIGENVALUE_H
| {
"alphanum_fraction": 0.5972583314,
"avg_line_length": 29.5874125874,
"ext": "h",
"hexsha": "95ed9a084f6c71093c78bf07e61303046a43f8ae",
"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": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stigrs/scilib",
"max_forks_repo_path": "include/scilib/linalg_impl/eigenvalue.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"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": "stigrs/scilib",
"max_issues_repo_path": "include/scilib/linalg_impl/eigenvalue.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stigrs/scilib",
"max_stars_repo_path": "include/scilib/linalg_impl/eigenvalue.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1181,
"size": 4231
} |
static char help[] =
"Solves a structured-grid Stokes problem with DMDA and SNES using finite elements: Q^2-P^-1.\n"
"FIXME: START OVER\n"
"\n\n";
#include <petsc.h>
typedef struct {
double u;
double v;
double p;
} Field;
typedef struct {
DM da;
Vec xexact;
double L, // length of domain in x direction
H, // length of domain in y direction
g1, // signed component of gravity in x-direction
g2, // signed component of gravity in y-direction
mu; // viscosity
} AppCtx;
extern PetscErrorCode FormExactSolution(AppCtx*);
extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*,Field**,Field**,AppCtx*);
//extern PetscErrorCode FormJacobianLocal(DMDALocalInfo*,Field**,Mat,Mat,AppCtx*);
int main(int argc,char **argv)
{
PetscErrorCode ierr;
AppCtx user; /* user-defined work context */
SNES snes; /* nonlinear solver */
Vec x; /* solution vector */
PetscInitialize(&argc,&argv,(char*)0,help);
const double rg = 1000.0 * 9.81, // = rho g; scale for body force;
// kg / (m^2 s^2); weight of water
theta = PETSC_PI / 9.0; // 20 degrees
user.L = 1.0;
user.H = 1.0;
user.g1 = rg * sin(theta);
user.g2 = - rg * cos(theta);
user.nu = 0.25; // Pa s; typical dynamic viscosity of motor oil
user.ppeps = 1.0;
// FIXME START OVER
PetscBool doerror = PETSC_FALSE, exactinit = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "stokes_", "options for stokes", ""); CHKERRQ(ierr);
FIXME
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate2d(PETSC_COMM_WORLD,
FIXME); CHKERRQ(ierr);
ierr = DMSetFromOptions(user.da); CHKERRQ(ierr);
ierr = DMSetUp(user.da); CHKERRQ(ierr);
ierr = DMDASetUniformCoordinates(user.da, 0.0, user.H, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr);
ierr = DMSetApplicationContext(user.da,&user); CHKERRQ(ierr);
ierr = DMCreateGlobalVector(user.da,&x); CHKERRQ(ierr);
ierr = DMDASetFieldName(user.da,0,"u"); CHKERRQ(ierr);
ierr = DMDASetFieldName(user.da,1,"v"); CHKERRQ(ierr);
ierr = DMDASetFieldName(user.da,2,"p"); CHKERRQ(ierr);
FIXME
SNESDestroy(&snes); DMDestroy(&user.da);
return PetscFinalize();
}
PetscErrorCode FormExactSolution(AppCtx* user) {
PetscErrorCode ierr;
DMDALocalInfo info;
int i,j;
double hy, y;
Field **ax;
ierr = DMDAGetLocalInfo(user->da,&info); CHKERRQ(ierr);
hy = user->H / (double)(info.my - 1);
ierr = DMDAVecGetArray(user->da,user->xexact,&ax); CHKERRQ(ierr);
for (j = info.ys; j < info.ys+info.ym; j++) {
y = hy * (double)j;
for (i = info.xs; i < info.xs+info.xm; i++) {
ax[j][i].u = (user->g1 / user->nu) * y * (user->H - y/2.0);
ax[j][i].v = 0.0;
ax[j][i].p = - user->g2 * (user->H - y);
}
}
ierr = DMDAVecRestoreArray(user->da,user->xexact,&ax); CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.5933528837,
"avg_line_length": 31.6391752577,
"ext": "c",
"hexsha": "5769e0997448186d48b2bab0d5c4c85480f773a5",
"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/junk/ch13/stokes.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/junk/ch13/stokes.c",
"max_line_length": 97,
"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/junk/ch13/stokes.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 923,
"size": 3069
} |
/* cdf/exponential.c
*
* Copyright (C) 2003, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
/* The exponential distribution has the form
p(x) dx = exp(-x/mu) dx/mu
for x = 0 ... +infty */
double
gsl_cdf_exponential_P (const double x, const double mu)
{
if (x < 0)
{
return 0;
}
else
{
double P = -expm1 (-x / mu);
return P;
}
}
double
gsl_cdf_exponential_Q (const double x, const double mu)
{
if (x < 0)
{
return 1;
}
else
{
double Q = exp (-x / mu);
return Q;
}
}
| {
"alphanum_fraction": 0.6579925651,
"avg_line_length": 22.4166666667,
"ext": "c",
"hexsha": "d6d822617c2adfbcf5ca3626c48266bcfc1169c9",
"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/cdf/exponential.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/cdf/exponential.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/cdf/exponential.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": 375,
"size": 1345
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#ifdef GSL_FOUND
#include <gsl/gsl_integration.h>
#endif
#include "core_allvars.h"
#include "core_init.h"
#include "core_mymalloc.h"
#include "core_cool_func.h"
//#include "core_metal_yield.h"
/* These functions do not need to be exposed externally */
double integrand_time_to_present(const double a, void *param);
void set_units(void);
void read_snap_list(const int ThisTask);
double time_to_present(const double z);
struct table{
double tbl[1000][17];
int nr;
};
struct table read_table(char *fname, int ncols);
void read_metal_yield();
#ifdef HDF5
#include "io/io_save_hdf5.h"
#endif
void init(const int ThisTask)
{
run_params.Age = mymalloc(ABSOLUTEMAXSNAPS*sizeof(*(run_params.Age)));
set_units();
read_snap_list(ThisTask);
//Hack to fix deltaT for snapshot 0
//This way, galsnapnum = -1 will not segfault.
run_params.Age[0] = time_to_present(1000.0);//lookback time from z=1000
run_params.Age++;
for(int i = 0; i < run_params.Snaplistlen; i++) {
run_params.ZZ[i] = 1 / run_params.AA[i] - 1;
run_params.Age[i] = time_to_present(run_params.ZZ[i]); //this is actually a lookback time
run_params.lbtime[i] = (run_params.Age[0] - run_params.Age[i]) * run_params.UnitTime_in_s / SEC_PER_MEGAYEAR; //age of universe since bigbang
}
run_params.a0 = 1.0 / (1.0 + run_params.Reionization_z0);
run_params.ar = 1.0 / (1.0 + run_params.Reionization_zr);
read_cooling_functions();
if(ThisTask == 0) {
printf("cooling functions read\n");
}
read_metal_yield();
if(ThisTask == 0){
printf("metal yields read\n\n");
}
#if 0
#ifdef HDF5
if(HDF5Output) {
calc_hdf5_props();
}
#endif
#endif
}
void set_units(void)
{
run_params.UnitTime_in_s = run_params.UnitLength_in_cm / run_params.UnitVelocity_in_cm_per_s;
run_params.UnitTime_in_Megayears = run_params.UnitTime_in_s / SEC_PER_MEGAYEAR;
run_params.G = GRAVITY / pow(run_params.UnitLength_in_cm, 3) * run_params.UnitMass_in_g * pow(run_params.UnitTime_in_s, 2);
run_params.UnitDensity_in_cgs = run_params.UnitMass_in_g / pow(run_params.UnitLength_in_cm, 3);
run_params.UnitPressure_in_cgs = run_params.UnitMass_in_g / run_params.UnitLength_in_cm / pow(run_params.UnitTime_in_s, 2);
run_params.UnitCoolingRate_in_cgs = run_params.UnitPressure_in_cgs / run_params.UnitTime_in_s;
run_params.UnitEnergy_in_cgs = run_params.UnitMass_in_g * pow(run_params.UnitLength_in_cm, 2) / pow(run_params.UnitTime_in_s, 2);
run_params.EnergySNcode = run_params.EnergySN / run_params.UnitEnergy_in_cgs * run_params.Hubble_h;
run_params.EtaSNcode = run_params.EtaSN * (run_params.UnitMass_in_g / SOLAR_MASS) / run_params.Hubble_h;
// convert some physical input parameters to internal units
run_params.Hubble = HUBBLE * run_params.UnitTime_in_s;
// compute a few quantitites
run_params.RhoCrit = 3.0 * run_params.Hubble * run_params.Hubble / (8 * M_PI * run_params.G);
}
void read_snap_list(const int ThisTask)
{
char fname[MAX_STRING_LEN+1];
snprintf(fname, MAX_STRING_LEN, "%s", run_params.FileWithSnapList);
FILE *fd = fopen(fname, "r");
if(fd == NULL) {
printf("can't read output list in file '%s'\n", fname);
ABORT(0);
}
run_params.Snaplistlen = 0;
do {
if(fscanf(fd, " %lg ", &(run_params.AA[run_params.Snaplistlen])) == 1) {
run_params.Snaplistlen++;
} else {
break;
}
} while(run_params.Snaplistlen < run_params.MAXSNAPS);
fclose(fd);
if(ThisTask == 0) {
printf("found %d defined times in snaplist\n", run_params.Snaplistlen);
}
}
double time_to_present(const double z)
{
const double end_limit = 1.0;
const double start_limit = 1.0/(1 + z);
double result=0.0;
#ifdef GSL_FOUND
#define WORKSIZE 1000
gsl_function F;
gsl_integration_workspace *workspace;
double abserr;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &integrand_time_to_present;
gsl_integration_qag(&F, start_limit, end_limit, 1.0 / run_params.Hubble,
1.0e-9, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);
gsl_integration_workspace_free(workspace);
#undef WORKSIZE
#else
/* Do not have GSL - let's integrate numerically ourselves */
const double step = 1e-7;
const int64_t nsteps = (end_limit - start_limit)/step;
result = 0.0;
const double y0 = integrand_time_to_present(start_limit + 0*step, NULL);
const double yn = integrand_time_to_present(start_limit + nsteps*step, NULL);
for(int64_t i=1; i<nsteps; i++) {
result += integrand_time_to_present(start_limit + i*step, NULL);
}
result = (step*0.5)*(y0 + yn + 2.0*result);
#endif
/* convert into Myrs/h (I think -> MS 23/6/2018) */
const double time = 1.0 / run_params.Hubble * result;
// return time to present as a function of redshift
return time;
}
double integrand_time_to_present(const double a, void *param)
{
(void) param;
return 1.0 / sqrt(run_params.Omega / a + (1.0 - run_params.Omega - run_params.OmegaLambda) + run_params.OmegaLambda * a * a);
}
void read_metal_yield(void)
{
char fname[MAX_STRING_LEN];
int cols=0;
int i, j, rows;
/* READ AGB YIELD */
if (run_params.AGBYields == 0)
{
double Z_std[7] = {0.0, 1e-4, 4e-4, 4e-3, 8e-3, 0.02, 0.05}; //metal grid from Karakas 10
strcpy(fname, "src/auxdata/yields/table2d.dat");
cols = 13; //number of columns in the file
struct table data;
data = read_table(fname, cols);
rows = data.nr;
double Z[rows];
//count how many rows necessary for each column based on Z
int count = 0;
for (i=0; i<rows; i++)
{
Z[i] = data.tbl[i][0];
if (Z[i] == Z_std[0]) {
count++;
}
}
//now assign
run_params.countagb = count;
for (j=0; j<7; j++){
int index = 0;
for (i=0; i<rows; i++){
if (Z[i] == Z_std[j])
{
run_params.magb[index] = data.tbl[i][1]; //1 is the column number
run_params.qCagb[index][j] = data.tbl[i][6] + data.tbl[i][7] + data.tbl[i][11];
run_params.qNagb[index][j] = data.tbl[i][8] + data.tbl[i][12];
run_params.qOagb[index][j] = data.tbl[i][9];
run_params.Qagb[index][j] = run_params.qCagb[index][j] + run_params.qNagb[index][j] + run_params.qOagb[index][j];
index++;
}
}
}
}
/* READ SN II YIELD */
if (run_params.SNIIYields == 0)
{
double Z_std[METALGRID] = {0.0, 1e-4, 4e-4, 4e-3, 8e-3, 0.02, 0.05}; //metal grid Woosley & Weaver 1995
strcpy(fname, "src/auxdata/yields/table4a.dat");
cols = 17; //number of columns in the file
struct table data;
data = read_table(fname, cols);
rows = data.nr;
double Z[rows];
//count how many rows necessary for each column based on Z
int count = 0;
for (i=0; i<rows; i++)
{
Z[i] = data.tbl[i][0];
if (Z[i] == Z_std[0]) {
count++;}
}
run_params.countsn = count;
for (j=0; j<7; j++){
int index = 0;
for (i=0; i<rows; i++){
if (Z[i] == Z_std[j])
{
run_params.msn[index] = data.tbl[i][1];
run_params.qCsn[index][j] = data.tbl[i][6] + data.tbl[i][15];
run_params.qOsn[index][j] = data.tbl[i][7];
run_params.qMgsn[index][j] = data.tbl[i][9];
run_params.qSisn[index][j] = data.tbl[i][10];
run_params.qSsn[index][j] = data.tbl[i][11];
run_params.qCasn[index][j] = data.tbl[i][12];
run_params.qFesn[index][j] = data.tbl[i][13];
run_params.Qsn[index][j] = run_params.qCsn[index][j] + run_params.qOsn[index][j] + run_params.qMgsn[index][j] + run_params.qSisn[index][j] + run_params.qSsn[index][j] + run_params.qCasn[index][j] + run_params.qFesn[index][j];
index++;
}
}
}
}
else if (run_params.SNIIYields == 1) //from Nomoto et al. 2006
{
double Z_std[METALGRID] = {0.0, 0.001, 0.004, 0.02};
strcpy(fname, "src/auxdata/yields/Nomoto.dat");
cols = 13; //number of columns in the file
struct table data;
data = read_table(fname, cols);
rows = data.nr;
double Z[rows];
//count how many rows necessary for each column based on Z
int count = 0;
for (i=0; i<rows; i++)
{
Z[i] = data.tbl[i][0];
if (Z[i] == Z_std[0]) {
count++;}
}
run_params.countsn = count;
for (j=0; j<4; j++){
int index = 0;
for (i=0; i<rows; i++){
if (Z[i] == Z_std[j])
{
run_params.msn[index] = data.tbl[i][1];
run_params.qCsn[index][j] = data.tbl[i][2] + data.tbl[i][11];
run_params.qOsn[index][j] = data.tbl[i][3];
run_params.qMgsn[index][j] = data.tbl[i][5];
run_params.qSisn[index][j] = data.tbl[i][6];
run_params.qSsn[index][j] = data.tbl[i][7];
run_params.qCasn[index][j] = data.tbl[i][8];
run_params.qFesn[index][j] = data.tbl[i][9];
run_params.Qsn[index][j] = run_params.qCsn[index][j] + run_params.qOsn[index][j] + run_params.qMgsn[index][j] + run_params.qSisn[index][j] + run_params.qSsn[index][j] + run_params.qCasn[index][j] + run_params.qFesn[index][j];
index++;
}
}
}
}
/* SNIa YIELD */
if (run_params.SNIaYields == 0)
{
run_params.qCrsnia = 0.0168; //yields from Iwamoto 1999
run_params.qFesnia = 0.587;
run_params.qNisnia = 0.0314;
}
else if (run_params.SNIaYields == 1) //yields from Seitenzahl et al. 2013
{
run_params.qCrsnia = 0.00857;
run_params.qFesnia = 0.622;
run_params.qNisnia = 0.069;
}
printf("ends reading yieldi \n");
}
struct table read_table(char *fname, int ncols)
{
int i, j;
struct table dt;
FILE *file;
file = fopen(fname,"r");
fscanf(file, "%*[^\n]"); //skips the first line
//start reading the file
i=0;
while (!feof(file)) //while it is not at the end of the file
{
for (j=0; j<ncols; j++)
{
fscanf(file, " %lf", &dt.tbl[i][j]); //notice the space char in front of %lf to handle any number of spaces as delimiter
}
fscanf(file,"%*[^\n]"); //ignore the rest of the line (if ncols is less than the file's column size), and go to the next line
i++;
}
fclose(file);
//store number of rows
dt.nr = i-1; //i is at the line AFTER the last line, so it's must be subtracted by 1
return dt;
}
| {
"alphanum_fraction": 0.5883233533,
"avg_line_length": 31.3701657459,
"ext": "c",
"hexsha": "730f16dbaa48a86d230d3bd673fdff29f7ac0ae2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-09T11:12:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-14T05:45:47.000Z",
"max_forks_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dptriani/sage",
"max_forks_repo_path": "src/core_init.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b",
"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": "dptriani/sage",
"max_issues_repo_path": "src/core_init.c",
"max_line_length": 258,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "0260b7026efd81d855bc1f187196da2b1839207b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dptriani/sage",
"max_stars_repo_path": "src/core_init.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-20T04:14:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-06T02:47:49.000Z",
"num_tokens": 3333,
"size": 11356
} |
#ifndef INTEGRATIONS_H
#define INTEGRATIONS_H
#include <armadillo>
#include <cmath>
#include <gsl/gsl_math.h>
#include <iostream>
template <typename F> class gsl_function_pp : public gsl_function {
public:
explicit gsl_function_pp(const F &func) : gsl_function_struct(), _func(func) {
function = &gsl_function_pp::invoke;
params = this;
}
private:
const F &_func;
static double invoke(double x, void *params) {
return static_cast<gsl_function_pp *>(params)->_func(x);
}
};
// wrapper functions for integration routines of the gsl
double cquad(const std::function<double(double)> &f, double a, double b,
double relerr, double epsabs);
double qags(const std::function<double(double)> &f, double a, double b,
double relerr, double epsabs);
double qagiu(const std::function<double(double)> &f, double a, double relerr,
double epsabs);
#endif // INTEGRATIONS_H
| {
"alphanum_fraction": 0.7076086957,
"avg_line_length": 29.6774193548,
"ext": "h",
"hexsha": "d6d6c529e828a058c555cc685ddb49726faeb810",
"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": "def47981b710a73f2fb3a7c14c354f8de91cf88f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "myoelmy/quaca",
"max_forks_repo_path": "src/Calculations/Integrations.h",
"max_issues_count": 31,
"max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f",
"max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "myoelmy/quaca",
"max_issues_repo_path": "src/Calculations/Integrations.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "QuaCaTeam/quaca",
"max_stars_repo_path": "src/Calculations/Integrations.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z",
"num_tokens": 226,
"size": 920
} |
#ifndef RADFIELD_H
#define RADFIELD_H
#include <cstdio>
#include <gsl/gsl_integration.h>
#include "types.h"
#include "sn3d.h"
namespace radfield
{
void zero_estimators(int modelgridindex);
void init(int my_rank, int ndo, int ndo_nonempty);
void initialise_prev_titer_photoionestimators(void);
void write_to_file(int modelgridindex, int timestep);
void close_file(void);
__host__ __device__ void update_estimators(int modelgridindex, double distance_e_cmf, double nu_cmf, const PKT *pkt_ptr, double t_current);
void increment_lineestimator(int modelgridindex, int lineindex, double increment);
__host__ __device__ double radfield(double nu, int modelgridindex);
__host__ __device__ double dbb_mgi(double nu, int modelgridindex);
void fit_parameters(int modelgridindex, int timestep);
__host__ __device__ void set_J_normfactor(int modelgridindex, double normfactor);
__host__ __device__ void normalise_J(int modelgridindex, double estimator_normfactor_over4pi);
__host__ __device__ void normalise_nuJ(int modelgridindex, double estimator_normfactor_over4pi);
__host__ __device__ double get_T_R_from_J(int modelgridindex);
__host__ __device__ int get_Jblueindex(int lineindex);
__host__ __device__ double get_Jb_lu(int modelgridindex, int jblueindex);
__host__ __device__ int get_Jb_lu_contribcount(int modelgridindex, int jblueindex);
void titer_J(int modelgridindex);
void titer_nuJ(int modelgridindex);
void reduce_estimators(void);
void do_MPI_Bcast(int modelgridindex, int root, int root_node_id);
void write_restart_data(FILE *gridsave_file);
void read_restart_data(FILE *gridsave_file);
__host__ __device__ void normalise_bf_estimators(int modelgridindex, double estimator_normfactor_over_H);
double get_bfrate_estimator(int element, int lowerion, int lower, int phixstargetindex, int modelgridindex);
void print_bfrate_contributions(int element, int lowerion, int lower, int phixstargetindex, int modelgridindex, double nnlowerlevel, double nnlowerion);
void reset_bfrate_contributions(const int modelgridindex);
int integrate(
const gsl_function *f, double nu_a, double nu_b, double epsabs, double epsrel,
size_t limit, int key, gsl_integration_workspace *workspace, double *result, double *abserr);
__host__ __device__ inline double dbb(double nu, float T, float W)
// returns J_nu for a dilute black body [ergs/s/sr/cm2/Hz]
{
return W * TWOHOVERCLIGHTSQUARED * pow(nu, 3) / expm1(HOVERKB * nu / T);
}
}
#endif //RADFIELD_H
| {
"alphanum_fraction": 0.8025477707,
"avg_line_length": 49.2549019608,
"ext": "h",
"hexsha": "e71af67934c6529b34d39f81f77e7aee93e0af6c",
"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": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "artis-mcrt/artis",
"max_forks_repo_path": "radfield.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "artis-mcrt/artis",
"max_issues_repo_path": "radfield.h",
"max_line_length": 154,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "artis-mcrt/artis",
"max_stars_repo_path": "radfield.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z",
"num_tokens": 670,
"size": 2512
} |
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <typeinfo>
#include <type_traits>
#include <gsl/gsl>
#include <upca/config.h>
#include "arch/arch.h"
namespace upca {
template <typename BACKEND> class resolver {
class description {
std::string name_;
unsigned size_;
unsigned offset_;
decltype(typename BACKEND::resolver_type().resolve({})) data_;
public:
description(std::string name, const unsigned size, const unsigned offset,
const typename BACKEND::resolver_type &resolver)
: name_(std::move(name)), size_(size), offset_(offset),
data_(resolver.resolve(name_)) {}
description(const char *name, const unsigned size, const unsigned offset,
const typename BACKEND::resolver_type &resolver)
: name_(name), size_(size), offset_(offset),
data_(resolver.resolve(name_)) {}
const std::string &name() const { return name_; }
unsigned size() const { return size_; }
unsigned offset() const { return offset_; }
decltype(auto) data() const { return data_; }
};
std::vector<description> counters_;
typename BACKEND::resolver_type resolver_;
public:
using value_type = description;
using iterator = typename std::vector<description>::iterator;
using const_iterator = typename std::vector<description>::const_iterator;
void add(const char *const name, const unsigned size = 8) {
counters_.emplace_back(name, size, counters_.size(), resolver_);
}
void add(std::string name, const unsigned size = 8) {
counters_.emplace_back(std::move(name), size, counters_.size(), resolver_);
}
size_t size() const { return counters_.size() + 1; }
unsigned bytesize() const {
unsigned sum = 0;
for (const auto &pmc : counters_) {
sum += pmc.size();
}
return sum;
}
const description &
at(const typename std::vector<description>::size_type pos) const {
return counters_.at(pos);
}
const_iterator begin() const { return counters_.cbegin(); }
const_iterator end() const { return counters_.cend(); }
const_iterator cbegin() const { return counters_.cbegin(); }
const_iterator cend() const { return counters_.cend(); }
/* Get PMU backend. Thread has to be pinned to a CPU before this is called */
std::unique_ptr<BACKEND> configure(const unsigned additional_counters = 0) const {
/* meh. add +1 for the "out-of-band" cycles counter :/ */
return std::make_unique<BACKEND>(counters_, additional_counters + 1);
}
};
/* sample pmcs */
} // namespace upca
| {
"alphanum_fraction": 0.6805772231,
"avg_line_length": 30.1647058824,
"ext": "h",
"hexsha": "b79f3db422de064eab9435d9fae2c254b6f0f534",
"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": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hannesweisbach/ucpa",
"max_forks_repo_path": "include/upca/upca.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd",
"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": "hannesweisbach/ucpa",
"max_issues_repo_path": "include/upca/upca.h",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e4062fd98d83f4cc57ee04f554540c09c1ca8ccd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hannesweisbach/ucpa",
"max_stars_repo_path": "include/upca/upca.h",
"max_stars_repo_stars_event_max_datetime": "2018-08-31T13:51:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-31T13:51:26.000Z",
"num_tokens": 606,
"size": 2564
} |
/* -*- linux-c -*- */
/* fewbody_utils.c
Copyright (C) 2002-2004 John M. Fregeau
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include "fewbody.h"
/* allocate a vector */
double *fb_malloc_vector(int n)
{
return((double *) malloc(n * sizeof(double)));
}
/* allocate a matrix */
double **fb_malloc_matrix(int nr, int nc)
{
int i;
double **m;
m = (double **) malloc(nr * sizeof(double *));
m[0] = (double *) malloc(nr * nc * sizeof(double));
for (i=1; i<nr; i++) {
m[i] = m[i-1] + nc;
}
return(m);
}
/* free a vector */
void fb_free_vector(double *v)
{
free(v);
}
/* free a matrix */
void fb_free_matrix(double **m)
{
free(m[0]);
free(m);
}
/* a fast square function */
double fb_sqr(double x)
{
return(x*x);
}
/* a fast cube function */
double fb_cub(double x)
{
return(x*x*x);
}
/* the dot product of two vectors */
double fb_dot(double x[3], double y[3])
{
return(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]);
}
/* the modulus of a vector */
double fb_mod(double x[3])
{
return(sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]));
}
/* the cross product of two vectors */
int fb_cross(double x[3], double y[3], double z[3])
{
z[0] = x[1] * y[2] - x[2] * y[1];
z[1] = x[2] * y[0] - x[0] * y[2];
z[2] = x[0] * y[1] - x[1] * y[0];
return(0);
}
/* something to calculate the angular momentum */
int fb_angmom(fb_obj_t *star, int nstar, double L[3])
{
int i, k;
double **l;
l = fb_malloc_matrix(nstar, 3);
for (k=0; k<3; k++) {
L[k] = 0.0;
}
for (i=0; i<nstar; i++) {
fb_cross(star[i].x, star[i].v, l[i]);
for (k=0; k<3; k++) {
L[k] += star[i].m * l[i][k];
}
}
fb_free_matrix(l);
return(0);
}
/* something to calculate the internal angular momentum */
void fb_angmomint(fb_obj_t *star, int nstar, double L[3])
{
int i, k;
for (k=0; k<3; k++) {
L[k] = 0.0;
}
for (i=0; i<nstar; i++) {
for (k=0; k<3; k++) {
L[k] += star[i].Lint[k];
}
}
}
/* something to calculate the internal energy */
double fb_einttot(fb_obj_t *star, int nstar)
{
int i;
double eint=0.0;
for (i=0; i<nstar; i++) {
eint += star[i].Eint;
}
return(eint);
}
/* calculates the total potential energy of the system */
double fb_petot(fb_obj_t *star, int nstar)
{
int i, j, k;
double pe=0.0, r[3];
for (i=0; i<nstar; i++) {
for (j=i+1; j<nstar; j++) {
for (k=0; k<3; k++) {
r[k] = star[j].x[k] - star[i].x[k];
}
pe += -star[i].m * star[j].m / fb_mod(r);
}
}
return(pe);
}
/* calculates the total kinetic energy of the system */
double fb_ketot(fb_obj_t *star, int nstar)
{
int i;
double ke=0.0;
for (i=0; i<nstar; i++) {
ke += 0.5 * star[i].m * fb_dot(star[i].v, star[i].v);
}
return(ke);
}
/* calculates the potential energy of the bound members of the system */
double fb_outerpetot(fb_obj_t **obj, int nobj)
{
int i, j, k;
double pe=0.0, r[3];
for (i=0; i<nobj; i++) {
for (j=i+1; j<nobj; j++) {
for (k=0; k<3; k++) {
r[k] = obj[j]->x[k] - obj[i]->x[k];
}
pe += -obj[i]->m * obj[j]->m / fb_mod(r);
}
}
return(pe);
}
/* calculates the kinetic energy of the bound members of the system */
double fb_outerketot(fb_obj_t **obj, int nobj)
{
int i;
double ke=0.0;
for (i=0; i<nobj; i++) {
ke += 0.5 * obj[i]->m * fb_dot(obj[i]->v, obj[i]->v);
}
return(ke);
}
/* solve the Kepler equation for the eccentric anomaly, given the mean anomaly and eccentricity */
double fb_kepler(double e, double mean_anom)
{
int status, iter;
double ecc_anom, params[2];
gsl_function F;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
/* set up the root solver */
F.function = &fb_keplerfunc;
F.params = ¶ms;
/* set the parameters */
params[0] = e;
params[1] = mean_anom;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &F, 0.0, 2.0*FB_CONST_PI);
/* get eccentric anomaly by root-finding */
iter = 0;
do {
iter++;
gsl_root_fsolver_iterate(s);
status = gsl_root_test_interval(gsl_root_fsolver_x_lower(s), gsl_root_fsolver_x_upper(s), \
FB_ROOTSOLVER_ABS_ACC, FB_ROOTSOLVER_REL_ACC);
} while (status == GSL_CONTINUE && iter < FB_ROOTSOLVER_MAX_ITER);
if (iter >= FB_ROOTSOLVER_MAX_ITER) {
fprintf(stderr, "Root finder failed to converge.\n");
exit(1);
}
/* we've got the root */
ecc_anom = gsl_root_fsolver_root(s);
/* free memory associated with root solver */
gsl_root_fsolver_free(s);
return(ecc_anom);
}
/* the Kepler function for the root finder */
double fb_keplerfunc(double ecc_anom, void *params)
{
double e, mean_anom;
e = ((double *)params)[0];
mean_anom = ((double *)params)[1];
return(ecc_anom - e * sin(ecc_anom) - mean_anom);
}
/* calculate the relative tidal acceleration */
double fb_reltide(fb_obj_t *bin, fb_obj_t *single, double r)
{
double arel, atid;
arel = bin->m / fb_sqr(bin->a * (1.0 + bin->e));
/* Factor in numerator is (single->m + bin->m) instead of single->m for the case of
small single->m, for which we want to at some point resolve "bin" to get the
motion of "single". This will eventually be fixed when we we use full collapsed
binary member positions in the integration, and not just the CM of the binary. */
atid = 2.0 * (single->m + bin->m) / fb_cub(r) * bin->a * (1.0 + bin->e);
return(atid/arel);
}
| {
"alphanum_fraction": 0.6254109139,
"avg_line_length": 21.4982332155,
"ext": "c",
"hexsha": "101a7464ee9b34fd7403ee4e845a4d8ff2366d58",
"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": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_utils.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_utils.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1986,
"size": 6084
} |
/*
* ParticleFilter.h
*
* Created on: Mar 21, 2012
* Author: nair
*/
#ifndef PARTICLEFILTER_H_
#define PARTICLEFILTER_H_
#include <QSettings>
#include <QFileInfo>
#include <opencv2/opencv.hpp>
#include <Eigen/Dense>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
namespace tracking
{
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_Z_STD;
/* autoregressive dynamics parameters for transition model */
float DYNAMICS_A1;
float DYNAMICS_A2;
float DYNAMICS_B0;
bool DYNAMIC_MODEL_CV;
float LAMBDA;
};
struct Particle
{
float x; /**< current x coordinate */
float y; /**< current y coordinate */
float z; /**< current z coordinate */
float xp; /**< previous x coordinate */
float yp; /**< previous y coordinate */
float zp; /**< previous z coordinate */
float x0; /**< original x coordinate */
float y0; /**< original y coordinate */
float z0; /**< original z coordinate */
float x_velocity; /**< current x_velocity coordinate */
float y_velocity; /**< current y_velocity coordinate */
float z_velocity; /**< current z_velocity coordinate */
float w; /**< weight */
};
class ParticleFilter
{
public:
ParticleFilter(uint& filter_id);
~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 setParticleWeightFromDistanceMeasure(int id, float dist);
void setParticleWeight(int id, float w);
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 getOutputVelocity(cv::Vec3d& vel);
uint getFilterId();
float getLikelihood();
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;
uint filterId;
float mMaxLikelihood;
};
}
#endif /* PARTICLEFILTER_H_ */
| {
"alphanum_fraction": 0.6322357019,
"avg_line_length": 19.4932432432,
"ext": "h",
"hexsha": "c89af59c413d804fe02e6e95a3855dbf71374605",
"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": "human-tracking/client/src/tracking/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": "human-tracking/client/src/tracking/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": "human-tracking/client/src/tracking/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": 697,
"size": 2885
} |
/**
*
* @file testing_cgebrd.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 Azzam Haidar
* @date 2010-11-15
* @generated c Tue Jan 7 11:45:17 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_cmain.h"
#undef REAL
#define COMPLEX
static int check_orthogonality(int, int, int, PLASMA_Complex32_t*, int, float);
static int check_reduction(int, int, float*, PLASMA_Complex32_t*, int, PLASMA_Complex32_t*, int, PLASMA_Complex32_t*, int, float);
static int check_solution(int, float*, float*, float);
int testing_cgebrd(int argc, char **argv)
{
int tree = 0;
if ( argc < 1 ){
goto usage;
} else {
tree = atoi(argv[0]);
}
/* Check for number of arguments*/
if ( ((tree == 0) && (argc != 4)) ||
((tree != 0) && (argc != 5)) ){
usage:
USAGE("GEBRD", "MODE M N LDA [RH]",
" - MODE : 0: flat, 1: tree (RH needed)\n"
" - M : number of rows of the matrix A\n"
" - N : number of columns of the matrix A\n"
" - LDA : leading dimension of the matrix A\n"
" - RH : Size of each subdomains\n");
return -1;
}
int M = atoi(argv[1]);
int N = atoi(argv[2]);
int LDA = atoi(argv[3]);
int rh;
if ( tree ) {
rh = atoi(argv[4]);
PLASMA_Set(PLASMA_HOUSEHOLDER_MODE, PLASMA_TREE_HOUSEHOLDER);
PLASMA_Set(PLASMA_HOUSEHOLDER_SIZE, rh);
}
if (LDA < M){
printf("LDA should be >= M !\n");
return -1;
}
float eps = LAPACKE_slamch_work('e');
float dmax = 1.0;
PLASMA_enum jobu = PlasmaVec;
PLASMA_enum jobvt = PlasmaVec;
int info_orthou = 0;
int info_orthovt = 0;
int info_solution = 0;
int info_reduction = 0;
int minMN = min(M, N);
int mode = 4;
float rcond = (float) minMN;
int INFO=-1;
PLASMA_Complex32_t *A1 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t));
float *S1 = (float *) malloc(minMN*sizeof(float));
float *S2 = (float *) malloc(minMN*sizeof(float));
float *E2 = (float *) malloc(minMN*sizeof(float));
PLASMA_Complex32_t *work = (PLASMA_Complex32_t *)malloc(3*max(M, N)* sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *A2 = NULL;
PLASMA_Complex32_t *U = NULL;
PLASMA_Complex32_t *VT = NULL;
PLASMA_desc *T;
/* Check if unable to allocate memory */
if ( (!A1) || (!S1) || (!S2) || (!work) ) {
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_cgebrd(M, N, &T);
/*----------------------------------------------------------
* TESTING CGEBRD
*/
/* Initialize A1 */
LAPACKE_clatms_work( LAPACK_COL_MAJOR, M, N,
lapack_const(PlasmaDistUniform), ISEED,
lapack_const(PlasmaNonsymPosv), S1, mode, rcond,
dmax, M, N,
lapack_const(PlasmaNoPacking), A1, LDA, work );
free(work);
/* Copy A1 for check */
if ( (jobu == PlasmaVec) && (jobvt == PlasmaVec) ) {
A2 = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t));
LAPACKE_clacpy_work(LAPACK_COL_MAJOR, 'A', M, N, A1, LDA, A2, LDA);
}
if ( jobu == PlasmaVec ) {
U = (PLASMA_Complex32_t *)malloc(M*M*sizeof(PLASMA_Complex32_t));
LAPACKE_claset_work(LAPACK_COL_MAJOR, 'A', M, M, 0., 1., U, M);
}
if ( jobvt == PlasmaVec ) {
VT = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));
LAPACKE_claset_work(LAPACK_COL_MAJOR, 'A', N, N, 0., 1., VT, N);
}
/* PLASMA CGEBRD */
INFO = PLASMA_cgebrd(jobu, jobvt, M, N, A1, LDA, S2, E2, T, U, M, VT, N);
if(INFO!=0){
printf(" ERROR OCCURED INFO %d\n",INFO);
goto fin;
}
printf("\n");
printf("------ TESTS FOR PLASMA CGEBRD ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", M, N);
printf("\n");
printf(" The matrix A is randomly generated for each test.\n");
printf("============\n");
printf(" The relative machine precision (eps) is to be %e \n",eps);
printf(" Computational tests pass if scaled residuals are less than 60.\n");
/* call SVD solver using lapack routine for our resulting bidiag [S E] */
int NCVT = 0;
int NRU = 0;
int NCC = 0;
if (jobu == PlasmaVec)
NRU = M;
if (jobvt == PlasmaVec)
NCVT = N;
PLASMA_enum uplo = M >=N ? PlasmaUpper : PlasmaLower;
INFO = LAPACKE_cbdsqr(LAPACK_COL_MAJOR, lapack_const(uplo),
minMN, NCVT, NRU, NCC,
S2, E2,
VT, N, U, M, NULL, 1 );
/* Check the orthogonality, reduction and the singular values */
if ( jobu == PlasmaVec )
info_orthou = check_orthogonality(PlasmaLeft, M, M, U, M, eps);
if ( jobvt == PlasmaVec )
info_orthovt = check_orthogonality(PlasmaRight, N, N, VT, N, eps);
/*
* WARNING: For now, Q is associated to Band tridiagonal reduction and
* not to the final tridiagonal reduction, so we can not call the check
* Need to accumulate the orthogonal transformations
* during the bulge chasing to be able to perform the next test!
*/
if ( (jobu == PlasmaVec) && (jobvt == PlasmaVec) )
info_reduction = check_reduction(M, N, S2, A2, LDA, U, M, VT, N, eps);
info_solution = check_solution(minMN, S1, S2, eps);
if ( (info_solution == 0) & (info_orthou == 0) &
(info_orthovt == 0) & (info_reduction == 0) ) {
if (M >= N) {
printf("***************************************************\n");
printf(" ---- TESTING CGEBRD .. M >= N ........... PASSED !\n");
printf("***************************************************\n");
}
else {
printf("***************************************************\n");
printf(" ---- TESTING CGEBRD .. M < N ............ PASSED !\n");
printf("***************************************************\n");
}
}
else {
if (M >= N) {
printf("************************************************\n");
printf(" - TESTING CGEBRD .. M >= N .. FAILED !\n");
printf("************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING CGEBRD .. M < N .. FAILED !\n");
printf("************************************************\n");
}
}
fin:
if ( A2 != NULL ) free(A2);
if ( U != NULL ) free(U);
if ( VT != NULL ) free(VT);
free(A1); free(S1); free(S2);free(E2);
PLASMA_Dealloc_Handle_Tile(&T);
return 0;
}
/*-------------------------------------------------------------------
* Check the orthogonality of U VT
*/
static int check_orthogonality(int side, int M, int N, PLASMA_Complex32_t *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 */
PLASMA_Complex32_t *Id = (PLASMA_Complex32_t *) malloc(minMN*minMN*sizeof(PLASMA_Complex32_t));
LAPACKE_claset_work(LAPACK_COL_MAJOR, 'A', minMN, minMN, 0., 1., Id, minMN);
/* Perform Id - Q'Q */
if (M >= N)
cblas_cherk(CblasColMajor, CblasUpper, CblasConjTrans, N, M, done, Q, LDQ, mdone, Id, N);
else
cblas_cherk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, done, Q, LDQ, mdone, Id, M);
normQ = LAPACKE_clansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'U', minMN, Id, minMN, work);
if (getenv("PLASMA_TESTING_VERBOSE"))
printf( "||Q||_oo=%f\n", normQ );
result = normQ / (M * eps);
if (side == PlasmaLeft)
{
printf(" ======================================================\n");
printf(" ||Id-U'*U||_oo / (M*eps) : %15.3E \n", result );
printf(" ======================================================\n");
}
else
{
printf(" ======================================================\n");
printf(" ||Id-VT'*VT||_oo / (M*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 bidiagonal reduction
*/
static int check_reduction(int M, int N, float *S, PLASMA_Complex32_t *A, int LDA,
PLASMA_Complex32_t *U, int LDU, PLASMA_Complex32_t *VT, int LDVT, float eps )
{
PLASMA_Complex32_t zone = 1.0;
PLASMA_Complex32_t mzone = -1.0;
float Anorm, Rnorm, result;
int info_reduction;
int i;
int maxMN = max(M, N);
int minMN = min(M, N);
PLASMA_Complex32_t *TEMP = (PLASMA_Complex32_t *)malloc(maxMN*maxMN*sizeof(PLASMA_Complex32_t));
PLASMA_Complex32_t *Residual = (PLASMA_Complex32_t *)malloc(maxMN*maxMN*sizeof(PLASMA_Complex32_t));
float *work = (float *)malloc(maxMN*sizeof(float));
memset((void*)TEMP, 0, maxMN*maxMN*sizeof(PLASMA_Complex32_t));
/* Compute TEMP = U * SIGMA */
/*
* U is of size (M,M),
* SIGMA is of size (M,N) but contains only MINMN singular values.
* Thus TEMP is of size (M,N)
*/
LAPACKE_clacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), M, M, U, LDU, TEMP, M);
for (i = 0; i < minMN; i++){
cblas_csscal(M, S[i], &(TEMP[i*M]),1);
}
/* Compute Residual = A - U * SIGMA * VT */
/*
* VT is of size (N,N)
*/
LAPACKE_clacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), M, N, A, LDA, Residual, M);
cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, CBLAS_SADDR(mzone), TEMP, M, VT, LDVT, CBLAS_SADDR(zone), Residual, M);
/* Compute the norms */
Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Residual, M, work);
Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A, LDA, work);
if (getenv("PLASMA_TESTING_VERBOSE"))
printf( "||A||_oo=%f\n||A - U*B*VT||_oo=%e\n", Anorm, Rnorm );
result = Rnorm / ( Anorm * maxMN * eps);
printf(" ======================================================\n");
printf(" ||A-U*SIGMA*VT'||_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(" | S - singularcomputed | / (|S| * N * eps) : %15.3E \n", maxel );
printf(" ======================================================\n");
if ( isnan(maxel) || isinf(maxel) || (maxel > 100) ) {
printf("-- The singular values are suspicious ! \n");
info_solution = 1;
}
else{
printf("-- The singular values are CORRECT ! \n");
info_solution = 0;
}
return info_solution;
}
| {
"alphanum_fraction": 0.5100031017,
"avg_line_length": 34.6666666667,
"ext": "c",
"hexsha": "cfc827b65d66e4cfd790236c6767005555a7100a",
"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_cgebrd.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_cgebrd.c",
"max_line_length": 144,
"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_cgebrd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3829,
"size": 12896
} |
/*
* Copyright (c) 2011-2020 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2013 Inria. All rights reserved.
*
* @precisions normal z -> c d s
*
*/
#include "dplasma.h"
#include "dplasma/types.h"
#include "dplasmaaux.h"
#include "parsec/data_dist/matrix/two_dim_rectangle_cyclic.h"
#include "parsec/data_dist/matrix/vector_two_dim_cyclic.h"
#include "cores/core_blas.h"
#include "zpltmg_chebvand.h"
#include "zpltmg_fiedler.h"
#include "zpltmg_hankel.h"
#include "zpltmg_toeppd.h"
#include <string.h>
#include <lapacke.h>
/**
*******************************************************************************
*
* Generic case
*
*******************************************************************************
*/
struct zpltmg_args_s {
dplasma_enum_t mtxtype;
unsigned long long int seed;
dplasma_complex64_t *W;
};
typedef struct zpltmg_args_s zpltmg_args_t;
static int
dplasma_zpltmg_generic_operator( parsec_execution_stream_t *es,
const parsec_tiled_matrix_t *descA,
void *_A,
dplasma_enum_t uplo, int m, int n,
void *op_data )
{
int tempmm, tempnn, ldam;
zpltmg_args_t *args = (zpltmg_args_t*)op_data;
dplasma_complex64_t *A = (dplasma_complex64_t*)_A;
(void)es;
(void)uplo;
tempmm = (m == (descA->mt-1)) ? (descA->m - m * descA->mb) : descA->mb;
tempnn = (n == (descA->nt-1)) ? (descA->n - n * descA->nb) : descA->nb;
ldam = BLKLDD( descA, m );
if ( args->mtxtype == dplasmaMatrixCircul ) {
return CORE_zpltmg_circul(
tempmm, tempnn, A, ldam,
descA->m, m*descA->mb, n*descA->nb, args->W );
} else {
return CORE_zpltmg(
args->mtxtype, tempmm, tempnn, A, ldam,
descA->m, descA->n, m*descA->mb, n*descA->nb, args->seed );
}
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zpltmg_generic - Generic wrapper for cases that are based on the map
* function. This is the default for many test matrices generation.
*
* See parsec_apply() for further information.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in] mtxtype
* Type of matrix to be generated.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
*
* @param[out] W
* Workspace required by some generators.
*
* @param[in] seed
* The seed used in the random generation.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg_genvect
* @sa dplasma_dpltmg_genvect
* @sa dplasma_spltmg_genvect
*
******************************************************************************/
static inline int
dplasma_zpltmg_generic( parsec_context_t *parsec,
dplasma_enum_t mtxtype,
parsec_tiled_matrix_t *A,
dplasma_complex64_t *W,
unsigned long long int seed)
{
parsec_taskpool_t *parsec_zpltmg = NULL;
zpltmg_args_t *params = (zpltmg_args_t*)malloc(sizeof(zpltmg_args_t));
params->mtxtype = mtxtype;
params->seed = seed;
params->W = W;
parsec_zpltmg = parsec_apply_New( dplasmaUpperLower, A, dplasma_zpltmg_generic_operator, params );
if ( parsec_zpltmg != NULL )
{
parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zpltmg);
dplasma_wait_until_completion(parsec);
parsec_apply_Destruct( parsec_zpltmg );
return 0;
}
return -101;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zpltmg_genvect - Generic wrapper for cases that are using two
* datatypes: the default one, and one describing a vector.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in] mtxtype
* Type of matrix to be generated.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
*
* @param[in] seed
* The seed used in the random generation.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg_genvect
* @sa dplasma_dpltmg_genvect
* @sa dplasma_spltmg_genvect
*
******************************************************************************/
static inline int
dplasma_zpltmg_genvect( parsec_context_t *parsec,
dplasma_enum_t mtxtype,
parsec_tiled_matrix_t *A,
unsigned long long int seed )
{
size_t vectorsize = 0;
parsec_taskpool_t* tp;
switch( mtxtype ) {
case dplasmaMatrixChebvand:
tp = (parsec_taskpool_t*)parsec_zpltmg_chebvand_new( seed,
A );
vectorsize = 2 * A->nb * sizeof(dplasma_complex64_t);
break;
case dplasmaMatrixFiedler:
tp = (parsec_taskpool_t*)parsec_zpltmg_fiedler_new( seed,
A );
vectorsize = A->mb * sizeof(dplasma_complex64_t);
break;
case dplasmaMatrixHankel:
tp = (parsec_taskpool_t*)parsec_zpltmg_hankel_new( seed,
A );
vectorsize = A->mb * sizeof(dplasma_complex64_t);
break;
case dplasmaMatrixToeppd:
tp = (parsec_taskpool_t*)parsec_zpltmg_toeppd_new( seed,
A );
vectorsize = 2 * A->mb * sizeof(dplasma_complex64_t);
break;
default:
return -2;
}
if (tp != NULL) {
parsec_zpltmg_hankel_taskpool_t *zpltmg_tp = (parsec_zpltmg_hankel_taskpool_t*)tp;
/* Default type */
dplasma_add2arena_tile( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_DEFAULT_ADT_IDX],
A->mb*A->nb*sizeof(dplasma_complex64_t),
PARSEC_ARENA_ALIGNMENT_SSE,
parsec_datatype_double_complex_t, A->mb );
/* Vector type */
dplasma_add2arena_tile( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_VECTOR_ADT_IDX],
vectorsize,
PARSEC_ARENA_ALIGNMENT_SSE,
parsec_datatype_double_complex_t, A->mb );
parsec_context_add_taskpool(parsec, tp);
dplasma_wait_until_completion(parsec);
dplasma_matrix_del2arena( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_DEFAULT_ADT_IDX] );
dplasma_matrix_del2arena( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_VECTOR_ADT_IDX ] );
parsec_taskpool_free(tp);
return 0;
}
return -101;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zpltmg_circul - Generates a Circulant test matrix by tiles.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
*
* @param[in] seed
* The seed used in the random generation.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg_circul
* @sa dplasma_dpltmg_circul
* @sa dplasma_spltmg_circul
*
******************************************************************************/
static inline int
dplasma_zpltmg_circul( parsec_context_t *parsec,
parsec_tiled_matrix_t *A,
unsigned long long int seed )
{
int info;
dplasma_complex64_t *V = (dplasma_complex64_t*) malloc( A->m * sizeof(dplasma_complex64_t) );
CORE_zplrnt( A->m, 1, V, A->m, A->m, 0, 0, seed );
info = dplasma_zpltmg_generic(parsec, dplasmaMatrixCircul, A, V, seed);
free(V);
return info;
}
/**
*******************************************************************************
*
* @ingroup dplasma_internal
*
* dplasma_zpltmg_condex - Generates a Condex test matrix by tiles.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg_condex
* @sa dplasma_dpltmg_condex
* @sa dplasma_spltmg_condex
*
******************************************************************************/
static inline int
dplasma_zpltmg_condex( parsec_context_t *parsec,
parsec_tiled_matrix_t *A )
{
/* gallery('condex', A->m, 4, 100.) */
dplasma_complex64_t theta = 100.;
parsec_matrix_block_cyclic_t *twodA = (parsec_matrix_block_cyclic_t *)A;
parsec_matrix_block_cyclic_t Q;
parsec_matrix_block_cyclic_init( &Q, PARSEC_MATRIX_COMPLEX_DOUBLE, PARSEC_MATRIX_TILE,
A->super.myrank,
A->mb, A->nb, A->mb*A->mt, 3, 0, 0, A->m, 3, 1, 1, twodA->grid.krows, twodA->grid.kcols, twodA->grid.ip, twodA->grid.jq );
Q.mat = parsec_data_allocate((size_t)Q.super.nb_local_tiles *
(size_t)Q.super.bsiz *
(size_t)parsec_datadist_getsizeoftype(Q.super.mtype));
parsec_data_collection_set_key((parsec_data_collection_t*)&Q, "Q");
if (A->super.myrank == 0) {
dplasma_complex64_t *Qmat;
Qmat = (dplasma_complex64_t*)(Q.mat);
/* Initialize the Q matrix */
CORE_zpltmg_condexq( A->m, A->n, Qmat, Q.super.lm );
/*
* Conversion to tile layout
*/
{
dplasma_complex64_t *W = (dplasma_complex64_t*) malloc (A->mb * sizeof(dplasma_complex64_t) );
int *leaders = NULL;
int i, nleaders;
/* Get all the cycles leaders and length
* They are the same for each independent problem (each panel) */
GKK_getLeaderNbr( Q.super.lmt, A->nb, &nleaders, &leaders );
/* shift cycles. */
for(i=0; i<nleaders; i++) {
/* cycle #i belongs to this thread, so shift it */
memcpy(W, Qmat + leaders[i*3] * A->mb, A->mb * sizeof(dplasma_complex64_t) );
CORE_zshiftw(leaders[i*3], leaders[i*3+1], A->mt, A->nb, A->mb, Qmat, W);
}
free(leaders); free(W);
}
}
dplasma_zlaset( parsec, dplasmaUpperLower, 0., 1. + theta, A );
dplasma_zgemm( parsec, dplasmaNoTrans, dplasmaConjTrans,
-theta, (parsec_tiled_matrix_t*)&Q,
(parsec_tiled_matrix_t*)&Q,
1., A );
parsec_data_free(Q.mat);
parsec_tiled_matrix_destroy((parsec_tiled_matrix_t*)&Q);
return 0;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zpltmg_house - Generates a Householder test matrix by tiles.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
*
* @param[in] seed
* The seed used in the random generation.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg_house
* @sa dplasma_dpltmg_house
* @sa dplasma_spltmg_house
*
******************************************************************************/
static inline int
dplasma_zpltmg_house( parsec_context_t *parsec,
parsec_tiled_matrix_t *A,
unsigned long long int seed )
{
/* gallery('house', random, 0 ) */
parsec_vector_two_dim_cyclic_t V;
dplasma_complex64_t *Vmat, tau;
parsec_vector_two_dim_cyclic_init( &V, PARSEC_MATRIX_COMPLEX_DOUBLE, PARSEC_VECTOR_DISTRIB_DIAG,
A->super.myrank,
A->mb, A->m, 0, A->m, 1, 1 );
V.mat = parsec_data_allocate((size_t)V.super.nb_local_tiles *
(size_t)V.super.bsiz *
(size_t)parsec_datadist_getsizeoftype(V.super.mtype));
parsec_data_collection_set_key((parsec_data_collection_t*)&V, "V");
Vmat = (dplasma_complex64_t*)(V.mat);
/* Initialize Householder vector */
if (A->super.myrank == 0) {
CORE_zplrnt( A->m, 1, Vmat, A->m, A->m, 0, 0, seed );
LAPACKE_zlarfg_work( A->m, Vmat, Vmat+1, 1, &tau );
Vmat[0] = 1.;
}
#if defined(PARSEC_HAVE_MPI)
/* If we don't need to broadcast, don't do it, this way we don't require MPI to be initialized */
if( A->super.nodes > 1 )
MPI_Bcast( &tau, 1, parsec_datatype_double_complex_t, 0, *(MPI_Comm*)dplasma_pcomm );
#endif
/* Compute the Householder matrix I - tau v * v' */
dplasma_zlaset( parsec, dplasmaUpperLower, 0., 1., A);
dplasma_zgerc( parsec, -tau,
(parsec_tiled_matrix_t*)&V,
(parsec_tiled_matrix_t*)&V,
A );
parsec_data_free(V.mat);
parsec_tiled_matrix_destroy((parsec_tiled_matrix_t*)&V);
return 0;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zpltmg - Generates a special test matrix by tiles.
*
*******************************************************************************
*
* @param[in,out] parsec
* The parsec context of the application that will run the operation.
*
* @param[in] mtxtype
* See PLASMA_zpltmg() for possible values and information on generated
* matrices.
*
* @param[in,out] A
* Descriptor of the distributed matrix A to generate. Any tiled matrix
* descriptor can be used.
* On exit, the matrix A generated.
*
* @param[in] seed
* The seed used in the random generation.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_cpltmg
* @sa dplasma_dpltmg
* @sa dplasma_spltmg
*
******************************************************************************/
int
dplasma_zpltmg( parsec_context_t *parsec,
dplasma_enum_t mtxtype,
parsec_tiled_matrix_t *A,
unsigned long long int seed)
{
switch( mtxtype ) {
case dplasmaMatrixCircul:
return dplasma_zpltmg_circul(parsec, A, seed);
break;
case dplasmaMatrixChebvand:
return dplasma_zpltmg_genvect(parsec, mtxtype,
A, seed);
break;
case dplasmaMatrixCondex:
return dplasma_zpltmg_condex(parsec, A);
break;
case dplasmaMatrixFiedler:
return dplasma_zpltmg_genvect(parsec, mtxtype,
A, seed);
break;
case dplasmaMatrixHankel:
return dplasma_zpltmg_genvect(parsec, mtxtype,
A, seed);
break;
case dplasmaMatrixHouse:
return dplasma_zpltmg_house(parsec, A, seed);
break;
case dplasmaMatrixToeppd:
return dplasma_zpltmg_genvect(parsec, mtxtype,
A, seed);
break;
case dplasmaMatrixCauchy:
case dplasmaMatrixCompan:
case dplasmaMatrixDemmel:
case dplasmaMatrixDorr:
case dplasmaMatrixFoster:
case dplasmaMatrixHadamard:
case dplasmaMatrixHilb:
case dplasmaMatrixInvhess:
case dplasmaMatrixKms:
case dplasmaMatrixLangou:
case dplasmaMatrixLehmer:
case dplasmaMatrixLotkin:
case dplasmaMatrixMinij:
case dplasmaMatrixMoler:
case dplasmaMatrixOrthog:
case dplasmaMatrixParter:
case dplasmaMatrixRandom:
case dplasmaMatrixRiemann:
case dplasmaMatrixRis:
case dplasmaMatrixWilkinson:
case dplasmaMatrixWright:
return dplasma_zpltmg_generic(parsec, mtxtype, A, NULL, seed);
break;
default:
return -2;
}
return 0;
}
| {
"alphanum_fraction": 0.5162555138,
"avg_line_length": 33.2061482821,
"ext": "c",
"hexsha": "3597dd2a08a6c18eaa5395718dc136e700a2f84c",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/zpltmg_wrapper.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/zpltmg_wrapper.c",
"max_line_length": 153,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/zpltmg_wrapper.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 4415,
"size": 18363
} |
/* eigen/gsl_eigen.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_EIGEN_H__
#define __GSL_EIGEN_H__
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct {
size_t size;
double * d;
double * sd;
} gsl_eigen_symm_workspace;
gsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n);
void gsl_eigen_symm_free (gsl_eigen_symm_workspace * w);
int gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * gc;
double * gs;
} gsl_eigen_symmv_workspace;
gsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n);
void gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w);
int gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w);
typedef struct {
size_t size; /* matrix size */
size_t max_iterations; /* max iterations since last eigenvalue found */
size_t n_iter; /* number of iterations since last eigenvalue found */
size_t n_evals; /* number of eigenvalues found so far */
gsl_vector *hv2; /* temporary 2-by-1 householder vector */
gsl_vector *hv3; /* temporary 3-by-1 householder vector */
int compute_t; /* compute Schur form T = Z^t A Z */
gsl_matrix *H; /* pointer to Hessenberg matrix */
gsl_matrix *Z; /* pointer to Schur vector matrix */
} gsl_eigen_francis_workspace;
gsl_eigen_francis_workspace * gsl_eigen_francis_alloc (void);
void gsl_eigen_francis_free (gsl_eigen_francis_workspace * w);
void gsl_eigen_francis_T (const int compute_t,
gsl_eigen_francis_workspace * w);
int gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval,
gsl_eigen_francis_workspace * w);
int gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval,
gsl_matrix * Z,
gsl_eigen_francis_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *diag; /* diagonal matrix elements from balancing */
gsl_vector *tau; /* Householder coefficients */
gsl_matrix *Z; /* pointer to Z matrix */
int do_balance; /* perform balancing transformation? */
size_t n_evals; /* number of eigenvalues found */
gsl_eigen_francis_workspace *francis_workspace_p;
} gsl_eigen_nonsymm_workspace;
gsl_eigen_nonsymm_workspace * gsl_eigen_nonsymm_alloc (const size_t n);
void gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w);
void gsl_eigen_nonsymm_params (const int compute_t, const int balance,
gsl_eigen_nonsymm_workspace *w);
int gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,
gsl_eigen_nonsymm_workspace * w);
int gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *work; /* scratch workspace */
gsl_vector *work2; /* scratch workspace */
gsl_vector *work3; /* scratch workspace */
gsl_matrix *Z; /* pointer to Schur vectors */
gsl_eigen_nonsymm_workspace *nonsymm_workspace_p;
} gsl_eigen_nonsymmv_workspace;
gsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc (const size_t n);
void gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w);
int gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_nonsymmv_workspace * w);
int gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec, gsl_matrix * Z,
gsl_eigen_nonsymmv_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * tau;
} gsl_eigen_herm_workspace;
gsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n);
void gsl_eigen_herm_free (gsl_eigen_herm_workspace * w);
int gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval,
gsl_eigen_herm_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * tau;
double * gc;
double * gs;
} gsl_eigen_hermv_workspace;
gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n);
void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w);
int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval,
gsl_matrix_complex * evec,
gsl_eigen_hermv_workspace * w);
typedef enum {
GSL_EIGEN_SORT_VAL_ASC,
GSL_EIGEN_SORT_VAL_DESC,
GSL_EIGEN_SORT_ABS_ASC,
GSL_EIGEN_SORT_ABS_DESC
}
gsl_eigen_sort_t;
/* Sort eigensystem results based on eigenvalues.
* Sorts in order of increasing value or increasing
* absolute value.
*
* exceptions: GSL_EBADLEN
*/
int gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec,
gsl_eigen_sort_t sort_type);
int gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
int gsl_eigen_nonsymmv_sort(gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
/* The following functions are obsolete: */
/* Eigensolve by Jacobi Method
*
* The data in the matrix input is destroyed.
*
* exceptions:
*/
int
gsl_eigen_jacobi(gsl_matrix * matrix,
gsl_vector * eval,
gsl_matrix * evec,
unsigned int max_rot,
unsigned int * nrot);
/* Invert by Jacobi Method
*
* exceptions:
*/
int
gsl_eigen_invert_jacobi(const gsl_matrix * matrix,
gsl_matrix * ainv,
unsigned int max_rot);
__END_DECLS
#endif /* __GSL_EIGEN_H__ */
| {
"alphanum_fraction": 0.6768484156,
"avg_line_length": 33.2037914692,
"ext": "h",
"hexsha": "25983dc1defbaace5a47ba8c5fec5b5c414a71f4",
"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/eigen/gsl_eigen.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/eigen/gsl_eigen.h",
"max_line_length": 106,
"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/eigen/gsl_eigen.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": 1784,
"size": 7006
} |
#include <stdio.h>
#include <string.h>
#include "erl_nif.h"
#include <cblas.h>
#define MAX(a,b) (((a)>(b))?(a):(b))
static ERL_NIF_TERM atom_ok;
static ERL_NIF_TERM atom_true;
static ERL_NIF_TERM atom_rowmaj;
static ERL_NIF_TERM atom_colmaj;
static ERL_NIF_TERM atom_notransp;
static ERL_NIF_TERM atom_transpose;
static ERL_NIF_TERM atom_conjugatet;
static ERL_NIF_TERM atom_upper;
static ERL_NIF_TERM atom_lower;
static ERL_NIF_TERM atom_left;
static ERL_NIF_TERM atom_right;
static ERL_NIF_TERM atom_nonunit;
static ERL_NIF_TERM atom_unit;
static ERL_NIF_TERM make_cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM from_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM to_values(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM to_idx_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM cont_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM cont_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM drotg(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM drot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM dcopy(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM l1d_1cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM l1d_2cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM dgemv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM dtrmv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM dgemm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);
static ErlNifFunc nif_funcs[] = {
{"make_cont", 2, make_cont},
{"from_list", 1, from_list},
{"to_tuple_list_impl", 4, to_values},
{"cont_size", 1, cont_size},
{"values", 2, to_idx_list},
{"update", 2, cont_update},
{"update", 3, cont_update},
{"rotg", 2, drotg},
{"rot", 9, drot},
{"copy", 4, dcopy},
{"copy", 7, dcopy},
{"one_vec", 6, l1d_1cont},
{"two_vec", 9, l1d_2cont},
{"gemv_impl", 15, dgemv},
{"trmv_impl", 11, dtrmv},
{"trmv_impl", 12, dtrmv},
{"gemm_impl", 15, dgemm},
{"trmm_impl", 15, dgemm},
};
static ErlNifResourceType *avec_r;
typedef struct {
double v[1];
} Avec;
static ERL_NIF_TERM mk_avec(ErlNifEnv *env, unsigned int n, Avec **avec) {
ERL_NIF_TERM term;
*avec = enif_alloc_resource(avec_r, n*sizeof(double));
term = enif_make_resource(env, *avec);
enif_release_resource(*avec);
return term;
}
#define AVEC_SIZE(AV) (enif_sizeof_resource(AV) / 8)
/* ---------------------------------------------------*/
static ERL_NIF_TERM make_cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int n;
ERL_NIF_TERM res;
Avec *avec = NULL;
double *data;
if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);
res = mk_avec(env, n, &avec);
if(enif_is_binary(env, argv[1])) {
ErlNifBinary bin;
enif_inspect_binary(env, argv[1], &bin);
if(n*sizeof(double) != bin.size)
return enif_make_badarg(env);
memcpy(avec->v, bin.data, sizeof(double)*n);
} else if(enif_is_identical(argv[1], atom_true)) {
data = avec->v;
memset(data, 0, sizeof(double)*n);
}
return res;
}
static ERL_NIF_TERM from_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int len;
int dim, i,j, tmp;
ERL_NIF_TERM hd, tail, res;
const ERL_NIF_TERM *current;
Avec *avec = NULL;
double *data;
if(!enif_get_list_length(env, argv[0], &len) || len == 0)
return enif_make_badarg(env);
enif_get_list_cell(env, argv[0], &hd, &tail);
if(!enif_get_tuple(env, hd, &dim, ¤t))
dim = 1;
res = mk_avec(env, len*dim, &avec);
enif_consume_timeslice(env, (len*dim)/1000);
data = avec->v;
if(dim == 1) {
for(i=0; i<len; i++) {
if(!enif_get_double(env, hd, data))
return enif_make_badarg(env);
data++;
enif_get_list_cell(env, tail, &hd, &tail);
}
} else {
for(i=0; i<len; i++) {
if(!enif_get_tuple(env, hd, &tmp, ¤t) || tmp != dim)
return enif_make_badarg(env);
for(j=0; j<dim; j++) {
if(!enif_get_double(env, current[j], data))
return enif_make_badarg(env);
data++;
}
enif_get_list_cell(env, tail, &hd, &tail);
}
}
return res;
}
static ERL_NIF_TERM to_values(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
ERL_NIF_TERM tail, *tmp;
Avec *avec = NULL;
double *arr;
unsigned int idx, n, dim, i, j, max;
if(!enif_get_uint(env, argv[0], &idx)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[1], &n)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[2], &dim)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[3], avec_r, (void **) &avec))
return enif_make_badarg(env);
max = AVEC_SIZE(avec);
enif_consume_timeslice(env, max/1000);
if(idx+n > max) return enif_make_badarg(env);
if(n == 1 && dim == 0) /* get_value() */
return enif_make_double(env, avec->v[idx]);
if(dim == 0) { /* to_list */
tail = enif_make_list(env, 0);
arr = avec->v + idx + n-1;
for(i=0; i < max; i++) {
tail = enif_make_list_cell(env, enif_make_double(env, *arr), tail);
arr -= 1;
}
return tail;
}
if(dim == n) { /* to_tuple */
tmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*n);
arr = avec->v;
for(i=0; i < n; i++) {
tmp[i] = enif_make_double(env, arr[idx+i]);
}
tail = enif_make_tuple_from_array(env, tmp, n);
free(tmp);
return tail;
}
/* list of tuples */
if(n % dim != 0)
return enif_make_badarg(env);
arr = avec->v + idx + n-dim;
tmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*dim);
tail = enif_make_list(env, 0);
for(i=0; i < max / dim; i++) {
for(j=0; j < dim; j++, arr++) {
tmp[j] = enif_make_double(env, *arr);
}
tail = enif_make_list_cell(env, enif_make_tuple_from_array(env, tmp, dim), tail);
arr -= 2*dim;
}
free(tmp);
return tail;
}
static ERL_NIF_TERM to_idx_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
ERL_NIF_TERM hd, tail, *tmp;
Avec *avec = NULL;
double *arr;
unsigned int idx, n, i;
if(!enif_get_list_length(env, argv[0], &n) || n == 0)
return enif_make_badarg(env);
if(!enif_get_resource(env, argv[1], avec_r, (void **) &avec))
return enif_make_badarg(env);
enif_consume_timeslice(env, n/1000);
tmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*n);
arr = avec->v;
tail = argv[0];
for(i=0; i < n; i++) {
enif_get_list_cell(env, tail, &hd, &tail);
if(!enif_get_uint(env, hd, &idx) || idx >= AVEC_SIZE(avec))
return enif_make_badarg(env);
tmp[i] = enif_make_tuple2(env, hd, enif_make_double(env, arr[idx]));
}
return enif_make_list_from_array(env, tmp, n);
}
static ERL_NIF_TERM cont_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
Avec *avec = NULL;
if(!enif_get_resource(env, argv[0], avec_r, (void **) &avec)) {
return enif_make_badarg(env);
}
return enif_make_uint(env, AVEC_SIZE(avec));
}
static ERL_NIF_TERM cont_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
ERL_NIF_TERM hd, tail;
const ERL_NIF_TERM *curr;
Avec *avec = NULL;
double *arr, temp;
int i=0, n=0;
unsigned int idx, max;
if(argc == 2) { /* tuple list of values */
if(!enif_is_list(env, argv[0]))
return enif_make_badarg(env);
if(!enif_get_resource(env, argv[1], avec_r, (void **) &avec))
return enif_make_badarg(env);
arr = avec->v;
max = AVEC_SIZE(avec);
tail = argv[0];
while(!enif_is_empty_list(env, tail)) {
if(!enif_get_list_cell(env, tail, &hd, &tail))
return enif_make_badarg(env);
if(!enif_get_tuple(env, hd, &i, &curr) || i != 2)
return enif_make_badarg(env);
if(!enif_get_uint(env, curr[0], &idx) || idx >= max)
return enif_make_badarg(env);
if(!enif_get_double(env, curr[1], &temp))
return enif_make_badarg(env);
arr[idx] = temp;
n++;
}
enif_consume_timeslice(env, n/1000);
return atom_ok;
}
/* update(Idx, V|[Vs], Vec) */
if(!enif_get_uint(env, argv[0], &idx))
return enif_make_badarg(env);
if(!enif_is_list(env, argv[1])) {
/* update(Idx, Double, Vec) */
if(!enif_get_double(env, argv[1], &temp))
return enif_make_badarg(env);
if(!enif_get_resource(env, argv[2], avec_r, (void **) &avec))
return enif_make_badarg(env);
max = AVEC_SIZE(avec);
if(idx >= max)
return enif_make_badarg(env);
arr = avec->v;
arr[idx] = temp;
return atom_ok;
}
/* update(Idx, [Values], Vec) */
tail = argv[1];
if(!enif_get_resource(env, argv[2], avec_r, (void **) &avec))
return enif_make_badarg(env);
max = AVEC_SIZE(avec);
arr = avec->v+idx;
while(!enif_is_empty_list(env, tail)) {
if(!enif_get_list_cell(env, tail, &hd, &tail))
return enif_make_badarg(env);
if(!enif_get_double(env, hd, &temp))
return enif_make_badarg(env);
*arr = temp;
arr++;
idx++;
n++;
if(idx > max)
return enif_make_badarg(env);
}
enif_consume_timeslice(env, n/1000);
return atom_ok;
}
/* ---------------------------------------------------*/
static ERL_NIF_TERM drotg(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{/* (a, b) */
double a,b,c,s;
if(!enif_get_double(env, argv[0], &a) || !enif_get_double(env, argv[1], &b)) {
return enif_make_badarg(env);
}
cblas_drotg(&a,&b,&c,&s);
return enif_make_tuple4(env,
enif_make_double(env, a), enif_make_double(env, b),
enif_make_double(env, c), enif_make_double(env, s));
}
static ERL_NIF_TERM drot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int n, xs, ys;
int xi, yi;
Avec *ax, *ay;
double *x, *y, c, s;
if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[1], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[2], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[3], &xi)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[4], avec_r, (void **) &ay)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[5], &ys)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[6], &yi)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[7], &c)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[8], &s)) return enif_make_badarg(env);
x = ax->v + xs;
y = ay->v + ys;
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
if((ys+n*abs(yi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
enif_consume_timeslice(env, n/1000);
cblas_drot(n, x, xi, y, xi, c, s);
return atom_ok;
}
static ERL_NIF_TERM l1d_1cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int op, n, xs;
int xi, tmp;
Avec *ax;
double *x, alpha;
ERL_NIF_TERM res = atom_ok;
if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[1], &alpha)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[2], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[3], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[4], &xi)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[5], &op)) return enif_make_badarg(env);
x = ax->v + xs;
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
switch(op) {
case 0:
cblas_dscal(n, alpha, x, xi);
break;
case 1:
res = enif_make_double(env, cblas_dnrm2(n, x, xi));
break;
case 2:
res = enif_make_double(env, cblas_dasum(n, x, xi));
break;
case 3:
tmp = cblas_idamax(n, x, xi);
res = enif_make_tuple2(env,
enif_make_uint(env, tmp),
enif_make_double(env, x[tmp]));
break;
}
enif_consume_timeslice(env, n/1000);
return res;
}
static ERL_NIF_TERM dcopy(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int n, xs, ys = 0;
int xi, yi=1;
Avec *ax, *ay;
double *x, *y;
ERL_NIF_TERM res;
if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[1], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[2], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[3], &xi)) return enif_make_badarg(env);
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
if(argc == 4) { /* copy to new vector */
res = mk_avec(env, n, &ay);
} else {
if(!enif_get_resource(env, argv[4], avec_r, (void **) &ay)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[5], &ys)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[6], &yi)) return enif_make_badarg(env);
if((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);
res = atom_ok;
}
x = ax->v + xs;
y = ay->v + ys;
cblas_dcopy(n, x, xi, y, yi);
enif_consume_timeslice(env, n/1000);
return res;
}
static ERL_NIF_TERM l1d_2cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int op, n, xs, ys;
int xi, yi;
Avec *ax, *ay;
double *x, *y, alpha, res;
if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[1], &alpha)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[2], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[3], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[4], &xi)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[5], avec_r, (void **) &ay)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[6], &ys)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[7], &yi)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[8], &op)) return enif_make_badarg(env);
x = ax->v + xs;
y = ay->v + ys;
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
if((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);
enif_consume_timeslice(env, n/1000);
switch(op) {
case 0:
cblas_daxpy(n, alpha, x, xi, y, yi);
break;
case 1:
cblas_dswap(n, x, xi, y, yi);
break;
case 2:
res = cblas_ddot(n, x, xi, y, yi);
return enif_make_double(env, res);
}
return atom_ok;
}
/* ---------------------------------------------------*/
static ERL_NIF_TERM dgemv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int m, n, lda, xs, ys, op;
int xi, yi;
Avec *aa, *ax, *ay;
double *a, *x, *y, alpha, beta;
enum CBLAS_ORDER order = 0;
enum CBLAS_TRANSPOSE trans = 0;
enum CBLAS_UPLO uplo = 0;
if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;
else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;
else return enif_make_badarg(env);
if(enif_is_identical(argv[1], atom_notransp)) trans = CblasNoTrans;
else if(enif_is_identical(argv[1], atom_transpose)) trans = CblasTrans;
else if(enif_is_identical(argv[1], atom_conjugatet)) trans = CblasConjTrans;
else if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(!enif_get_uint(env, argv[2], &m)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[3], &n)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[4], &alpha)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[5], avec_r, (void **) &aa)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[6], &lda)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[7], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[8], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[9], &xi)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[10], &beta)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[11], avec_r, (void **) &ay)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[12], &ys)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[13], &yi)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[14], &op)) return enif_make_badarg(env);
a = aa->v;
x = ax->v + xs;
y = ay->v + ys;
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
if((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);
switch(op) {
case 0:
cblas_dgemv(order, trans, m, n, alpha, a, lda, x, xi, beta, y, yi); break;
case 1:
cblas_dsymv(order, uplo, n, alpha, a, lda, x, xi, beta, y, yi); break;
case 2:
cblas_dspmv(order, uplo, n, alpha, a, x, xi, beta, y, yi); break;
case 3:
cblas_dger(order, m, n, alpha, x, xi, y, yi, a, lda); break;
case 4:
cblas_dsyr2(order, uplo, n, alpha, x, xi, y, yi, a, lda); break;
case 5:
cblas_dspr2(order, uplo, n, alpha, x, xi, y, yi, a); break;
}
enif_consume_timeslice(env, MAX(1,m)*n/1000);
return atom_ok;
}
static ERL_NIF_TERM dtrmv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int n, lda, xs, op;
int xi;
Avec *aa, *ax;
double *a, *x, alpha;
enum CBLAS_ORDER order = 0;
enum CBLAS_TRANSPOSE trans = 0;
enum CBLAS_UPLO uplo = 0;
enum CBLAS_DIAG diag = 0;
if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;
else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;
else return enif_make_badarg(env);
if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(!enif_get_uint(env, argv[10], &op)) return enif_make_badarg(env);
if(op < 4) {
if(enif_is_identical(argv[2], atom_notransp)) trans = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) trans = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) trans = CblasConjTrans;
else return enif_make_badarg(env);
if(enif_is_identical(argv[3], atom_nonunit)) diag = CblasNonUnit;
else if(enif_is_identical(argv[3], atom_unit)) diag = CblasUnit;
else return enif_make_badarg(env);
}
if(!enif_get_uint(env, argv[4], &n)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[5], avec_r, (void **) &aa)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[6], &lda)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[7], avec_r, (void **) &ax)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[8], &xs)) return enif_make_badarg(env);
if(!enif_get_int(env, argv[9], &xi)) return enif_make_badarg(env);
if(argc > 11)
if(!enif_get_double(env, argv[11], &alpha)) return enif_make_badarg(env);
a = aa->v;
x = ax->v + xs;
/* array limit checks */
if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);
switch(op) {
case 0:
cblas_dtrmv(order, uplo, trans, diag, n, a, lda, x, xi);break;
case 1:
cblas_dtpmv(order, uplo, trans, diag, n, a, x, xi); break;
case 2:
cblas_dtrsv(order, uplo, trans, diag, n, a, lda, x, xi);break;
case 3:
cblas_dtpsv(order, uplo, trans, diag, n, a, x, xi);break;
case 4:
cblas_dsyr(order, uplo, n, alpha, x, xi, a, lda); break;
case 5:
cblas_dspr(order, uplo, n, alpha, x, xi, a); break;
}
enif_consume_timeslice(env, n*n/1000);
return atom_ok;
}
/* ---------------------------------------------------*/
static ERL_NIF_TERM dgemm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned int m, n, k, lda, ldb, ldc, op;
Avec *aa, *ab, *ac;
double alpha, beta, *a, *b, *c = NULL;
enum CBLAS_ORDER order = 0;
enum CBLAS_TRANSPOSE ta = 0, tb = 0;
enum CBLAS_UPLO uplo = 0;
enum CBLAS_SIDE side = 0;
enum CBLAS_DIAG diag = 0;
if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;
else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;
else return enif_make_badarg(env);
if(!enif_get_uint(env, argv[3], &m)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[4], &n)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[5], &k)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[6], &alpha)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[7], avec_r, (void **) &aa)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[8], &lda)) return enif_make_badarg(env);
if(!enif_get_resource(env, argv[9], avec_r, (void **) &ab)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[10], &ldb)) return enif_make_badarg(env);
if(!enif_get_double(env, argv[11], &beta)) return enif_make_badarg(env);
if(!enif_get_uint(env, argv[12], &op)) return enif_make_badarg(env);
if(op < 3) {
if(!enif_get_resource(env, argv[13], avec_r, (void **) &ac))
return enif_make_badarg(env);
if(!enif_get_uint(env, argv[14], &ldc)) return enif_make_badarg(env);
c = ac->v;
}
a = aa->v;
b = ab->v;
switch(op) {
case 0: {
if(enif_is_identical(argv[1], atom_notransp)) ta = CblasNoTrans;
else if(enif_is_identical(argv[1], atom_transpose)) ta = CblasTrans;
else if(enif_is_identical(argv[1], atom_conjugatet)) ta = CblasConjTrans;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;
else return enif_make_badarg(env);
cblas_dgemm(order, ta,tb, m,n,k, alpha, a,lda, b,ldb, beta, c,ldc);
break;}
case 1: {
if(enif_is_identical(argv[1], atom_left)) side = CblasLeft;
else if(enif_is_identical(argv[1], atom_right)) side = CblasRight;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[2], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
cblas_dsymm(order, side, uplo, m,n, alpha, a,lda, b,ldb, beta, c,ldc);
break; }
case 2: {
if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;
// fprintf(stderr, "%d %d,%d,%d %.2f %.2f %d,%d,%d\r\n", __LINE__, m,n,k, alpha, beta, lda,ldb,ldc);
cblas_dsyr2k(order, uplo, tb, n, k, alpha, a,lda, b,ldb, beta, c,ldc);
break; }
case 3: {
if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;
if(enif_is_identical(argv[13], atom_left)) side = CblasLeft;
else if(enif_is_identical(argv[13], atom_right)) side = CblasRight;
else return enif_make_badarg(env);
if(enif_is_identical(argv[14], atom_nonunit)) diag = CblasNonUnit;
else if(enif_is_identical(argv[14], atom_unit)) diag = CblasUnit;
else return enif_make_badarg(env);
cblas_dtrmm(order,side,uplo,tb,diag, m,n, alpha, a,lda, b, ldb);
break; }
case 4: {
if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;
if(enif_is_identical(argv[13], atom_left)) side = CblasLeft;
else if(enif_is_identical(argv[13], atom_right)) side = CblasRight;
else return enif_make_badarg(env);
if(enif_is_identical(argv[14], atom_nonunit)) diag = CblasNonUnit;
else if(enif_is_identical(argv[14], atom_unit)) diag = CblasUnit;
else return enif_make_badarg(env);
cblas_dtrsm(order,side,uplo,tb,diag, m,n, alpha, a,lda, b, ldb);
break; }
case 5: {
if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;
else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;
else return enif_make_badarg(env);
if(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;
else if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;
else if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;
cblas_dsyrk(order,uplo,tb, n,k, alpha, a,lda, beta, b,ldb);
break; }
}
enif_consume_timeslice(env, MAX(m,k)*n/1000);
return atom_ok;
}
/* ---------------------------------------------------*/
static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
{
atom_ok = enif_make_atom(env,"ok");
atom_true = enif_make_atom(env,"true");
atom_notransp = enif_make_atom(env,"no_transp");
atom_transpose = enif_make_atom(env,"transp");
atom_conjugatet = enif_make_atom(env,"conj_transp");
atom_rowmaj = enif_make_atom(env,"row_maj");
atom_colmaj = enif_make_atom(env,"col_maj");
atom_upper = enif_make_atom(env,"upper");
atom_lower = enif_make_atom(env,"lower");
atom_left = enif_make_atom(env,"left");
atom_right = enif_make_atom(env,"right");
atom_nonunit = enif_make_atom(env,"non_unit");
atom_unit = enif_make_atom(env,"unit");
avec_r = enif_open_resource_type(env, "eblas", "avec", NULL, ERL_NIF_RT_CREATE, NULL);
return 0;
}
static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data,
ERL_NIF_TERM load_info)
{
return 0;
}
static void unload(ErlNifEnv* env, void* priv_data)
{
}
ERL_NIF_INIT(blasd_raw,nif_funcs,load,NULL,upgrade,unload)
| {
"alphanum_fraction": 0.6630401704,
"avg_line_length": 33.8762886598,
"ext": "c",
"hexsha": "c3df77ef3067f698126b98bcedc64d0dd167ec5e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-29T13:47:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-29T13:47:56.000Z",
"max_forks_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931",
"max_forks_repo_licenses": [
"TCL"
],
"max_forks_repo_name": "5HT/blas",
"max_forks_repo_path": "c_src/eblas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"TCL"
],
"max_issues_repo_name": "5HT/blas",
"max_issues_repo_path": "c_src/eblas.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931",
"max_stars_repo_licenses": [
"TCL"
],
"max_stars_repo_name": "5HT/blas",
"max_stars_repo_path": "c_src/eblas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8699,
"size": 26288
} |
/* cheb/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include "gsl_chebyshev.h"
double f_sin (double x, void * p) {
p = 0;
return sin(x);
}
int
main(void)
{
double tol = 100.0 * GSL_DBL_EPSILON;
double x;
gsl_cheb_series * cs = gsl_cheb_alloc(40);
gsl_cheb_series * csd = gsl_cheb_alloc(40);
gsl_cheb_series * csi = gsl_cheb_alloc(40);
gsl_function F_sin;
F_sin.function = f_sin;
F_sin.params = 0;
gsl_ieee_env_setup();
gsl_cheb_init(cs, &F_sin, -M_PI, M_PI);
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval(cs, x);
gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval, sin(%.3g)", x);
}
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_err(cs, x, &r, &e);
gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval_err, sin(%.3g)", x);
gsl_test_factor(fabs(r-sin(x)) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_err, error sin(%.3g)", x);
}
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval_n(cs, 25, x);
gsl_test_abs(r, sin(x), tol, "gsl_cheb_eval_n, sin(%.3g)", x);
}
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_n_err(cs, 25, x, &r, &e);
gsl_test_abs(r, sin(x), 100.0 * tol, "gsl_cheb_eval_n_err, deriv sin(%.3g)", x);
gsl_test_factor(fabs(r-sin(x)) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_n_err, error sin(%.3g)", x);
}
/* Test derivative */
gsl_cheb_calc_deriv(csd, cs);
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval(csd, x);
gsl_test_abs(r, cos(x), 1600 * tol, "gsl_cheb_eval, deriv sin(%.3g)", x);
}
#ifdef TEST_DERIVATIVE_ERR
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_err(csd, x, &r, &e);
gsl_test_abs(r, cos(x), tol, "gsl_cheb_eval_err, deriv sin(%.3g)", x);
gsl_test_factor(fabs(r-cos(x)) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_err, deriv error sin(%.3g)", x);
}
#endif
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval_n(csd, 25, x);
gsl_test_abs(r, cos(x), 1600 * tol, "gsl_cheb_eval_n, deriv sin(%.3g)", x);
}
#ifdef TEST_DERIVATIVE_ERR
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_n_err(csd, 25, x, &r, &e);
gsl_test_abs(r, cos(x), 100.0 * tol, "gsl_cheb_eval_n_err, deriv sin(%.3g)", x);
gsl_test_factor(fabs(r-cos(x)) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_n_err, deriv error sin(%.3g)", x);
}
#endif
/* Test integral */
gsl_cheb_calc_integ(csi, cs);
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval(csi, x);
gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval, integ sin(%.3g)", x);
}
#ifdef TEST_INTEGRAL_ERR
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_err(csi, x, &r, &e);
gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval_err, integ sin(%.3g)", x);
gsl_test_factor(fabs(r-(-1-cos(x))) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_err, integ error sin(%.3g)", x);
}
#endif
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r = gsl_cheb_eval_n(csi, 25, x);
gsl_test_abs(r, -(1+cos(x)), tol, "gsl_cheb_eval_n, integ sin(%.3g)", x);
}
#ifdef TEST_INTEGRAL_ERR
for(x=-M_PI; x<M_PI; x += M_PI/100.0) {
double r, e;
gsl_cheb_eval_n_err(csi, 25, x, &r, &e);
gsl_test_abs(r, -(1+cos(x)), 100.0 * tol, "gsl_cheb_eval_n_err, integ sin(%.3g)", x);
gsl_test_factor(fabs(r-(-1-cos(x))) + GSL_DBL_EPSILON, e, 10.0,
"gsl_cheb_eval_n_err, integ error sin(%.3g)", x);
}
#endif
gsl_cheb_free(csi);
gsl_cheb_free(csd);
gsl_cheb_free(cs);
exit (gsl_test_summary());
}
| {
"alphanum_fraction": 0.6242411101,
"avg_line_length": 30.3421052632,
"ext": "c",
"hexsha": "49d316c7fc9b8342119cfa71a40f048f5c0364a6",
"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/cheb/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cheb/test.c",
"max_line_length": 89,
"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/cheb/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 1653,
"size": 4612
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
double f (double x,void *params);
double f (double x,void *params)
{
double n=* (double *) params;
double f=exp (-x) * pow (x,n);
return f;
}
void integral_gen (int nmin, int nmax, double vals[]);
void integral_gen (int nmin, int nmax, double vals[])
{
double a=0.,b=1;
double abserr=1.e-9,relerr=1.e-9;
double result;
double error;
double n=10;
size_t np=1000;
gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);
gsl_function F;
F.function = &f;
for (int i=nmin;i<=nmax;i++)
{
F.params =&n;
gsl_integration_qag (&F, a, b, abserr, relerr,np,GSL_INTEG_GAUSS15, w, &result, &error);
vals[i]=result;
}
gsl_integration_workspace_free (w);
}
| {
"alphanum_fraction": 0.6021126761,
"avg_line_length": 25.0588235294,
"ext": "c",
"hexsha": "a8d8c1c7455e45db9b4a5c6d64725d7689dab90f",
"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": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlichtman13/hw07",
"max_forks_repo_path": "int_gsl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1",
"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": "jlichtman13/hw07",
"max_issues_repo_path": "int_gsl.c",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlichtman13/hw07",
"max_stars_repo_path": "int_gsl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 249,
"size": 852
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.