Search is not available for this dataset
text string | meta dict |
|---|---|
#pragma once
#include <vector>
#include <string>
#include <memory>
#include <functional>
#include <gsl>
struct Vec3 { float x,y,z; };
struct Vec2 { float x,y; };
#include "types.h"
#include "automaticId.h" | {
"alphanum_fraction": 0.6875,
"avg_line_length": 16,
"ext": "h",
"hexsha": "4fbcab844c51c1e92720775b42ffd4959cae0e29",
"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": "73659ce98b51eb8ebed297684f62b39fb728e37e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "racerxdl/bedhock",
"max_forks_repo_path": "include/fakemine/base.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73659ce98b51eb8ebed297684f62b39fb728e37e",
"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": "racerxdl/bedhock",
"max_issues_repo_path": "include/fakemine/base.h",
"max_line_length": 29,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "73659ce98b51eb8ebed297684f62b39fb728e37e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "racerxdl/bedhock",
"max_stars_repo_path": "include/fakemine/base.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T21:38:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-21T17:14:54.000Z",
"num_tokens": 54,
"size": 208
} |
#if !defined(REGEXMOVE_H_INCLUDED)
#define REGEXMOVE_H_INCLUDED
#include "Utils.h"
#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <regex>
#include <string>
class RegExMove
{
public:
static int usage(::std::ostream& strm, const ::std::string& progName,
const char* pMsg);
RegExMove(::gsl::span<const char*const> args);
int run() const;
RegExMove(const RegExMove&) = delete;
RegExMove& operator=(const RegExMove&) = delete;
RegExMove(RegExMove&&) = delete;
RegExMove& operator=(RegExMove&&) = delete;
PRIVATE_EXCEPT_IN_TEST:
using Path = ::std::filesystem::path;
using DirEntry = ::std::filesystem::directory_entry;
template <typename DirIter> void processDirectoryEntries() const;
void processDirectoryEntry(DirEntry const& dirEntry) const;
void renamePath(Path const& p) const;
bool m_caseSensitive;
bool m_renameDirectories;
bool m_renameFiles;
bool m_recursiveSearch;
bool m_verboseOutput;
bool m_allowOverwriteOnNameCollision;
Path m_rootDir;
::std::string m_patternStr;
::std::regex m_pattern;
::std::string m_replacement;
};
#endif // REGEXMOVE_H_INCLUDED
| {
"alphanum_fraction": 0.7405452946,
"avg_line_length": 23.6875,
"ext": "h",
"hexsha": "b566678d3d32a9458160a27aca1ecec0b61e2985",
"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": "RegExMove.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": "RegExMove.h",
"max_line_length": 70,
"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": "RegExMove.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 303,
"size": 1137
} |
/* multiset/gsl_multiset.h
* based on combination/gsl_combination.h by Szymon Jaroszewicz
* based on permutation/gsl_permutation.h by Brian Gough
*
* Copyright (C) 2009 Rhys Ulerich
*
* 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_MULTISET_H__
#define __GSL_MULTISET_H__
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.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_multiset_struct
{
size_t n;
size_t k;
size_t *data;
};
typedef struct gsl_multiset_struct gsl_multiset;
gsl_multiset *gsl_multiset_alloc (const size_t n, const size_t k);
gsl_multiset *gsl_multiset_calloc (const size_t n, const size_t k);
void gsl_multiset_init_first (gsl_multiset * c);
void gsl_multiset_init_last (gsl_multiset * c);
void gsl_multiset_free (gsl_multiset * c);
int gsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src);
int gsl_multiset_fread (FILE * stream, gsl_multiset * c);
int gsl_multiset_fwrite (FILE * stream, const gsl_multiset * c);
int gsl_multiset_fscanf (FILE * stream, gsl_multiset * c);
int gsl_multiset_fprintf (FILE * stream, const gsl_multiset * c, const char *format);
size_t gsl_multiset_n (const gsl_multiset * c);
size_t gsl_multiset_k (const gsl_multiset * c);
size_t * gsl_multiset_data (const gsl_multiset * c);
int gsl_multiset_valid (gsl_multiset * c);
int gsl_multiset_next (gsl_multiset * c);
int gsl_multiset_prev (gsl_multiset * c);
INLINE_DECL size_t gsl_multiset_get (const gsl_multiset * c, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
size_t
gsl_multiset_get (const gsl_multiset * c, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= c->k)) /* size_t is unsigned, can't be negative */
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return c->data[i];
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_MULTISET_H__ */
| {
"alphanum_fraction": 0.7564655172,
"avg_line_length": 29.6170212766,
"ext": "h",
"hexsha": "65e93f68e16d5ccee55426008ee6dd13b3949e59",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h",
"max_line_length": 85,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multiset.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 756,
"size": 2784
} |
static char help[] = "A structured-grid Poisson solver using DMDA+KSP.\n\n";
#include <petsc.h>
extern PetscErrorCode formMatrix(DM, Mat);
extern PetscErrorCode formExact(DM, Vec);
extern PetscErrorCode formRHS(DM, Vec);
//STARTMAIN
int main(int argc,char **args) {
PetscErrorCode ierr;
DM da;
Mat A;
Vec b,u,uexact;
KSP ksp;
PetscReal errnorm;
DMDALocalInfo info;
ierr = PetscInitialize(&argc,&args,NULL,help); if (ierr) return ierr;
// change default 9x9 size using -da_grid_x M -da_grid_y N
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,
9,9,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);
// create linear system matrix A
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMCreateMatrix(da,&A); CHKERRQ(ierr);
ierr = MatSetFromOptions(A); CHKERRQ(ierr);
// create RHS b, approx solution u, exact solution uexact
ierr = DMCreateGlobalVector(da,&b); CHKERRQ(ierr);
ierr = VecDuplicate(b,&u); CHKERRQ(ierr);
ierr = VecDuplicate(b,&uexact); CHKERRQ(ierr);
// fill vectors and assemble linear system
ierr = formExact(da,uexact); CHKERRQ(ierr);
ierr = formRHS(da,b); CHKERRQ(ierr);
ierr = formMatrix(da,A); CHKERRQ(ierr);
// create and solve the linear system
ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr);
ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr);
ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);
ierr = KSPSolve(ksp,b,u); CHKERRQ(ierr);
// report on grid and numerical error
ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uxact
ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"on %d x %d grid: error |u-uexact|_inf = %g\n",
info.mx,info.my,errnorm); CHKERRQ(ierr);
VecDestroy(&u); VecDestroy(&uexact); VecDestroy(&b);
MatDestroy(&A); KSPDestroy(&ksp); DMDestroy(&da);
return PetscFinalize();
}
//ENDMAIN
//STARTMATRIX
PetscErrorCode formMatrix(DM da, Mat A) {
PetscErrorCode ierr;
DMDALocalInfo info;
MatStencil row, col[5];
PetscReal hx, hy, v[5];
PetscInt i, j, ncols;
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);
for (j = info.ys; j < info.ys+info.ym; j++) {
for (i = info.xs; i < info.xs+info.xm; i++) {
row.j = j; // row of A corresponding to (x_i,y_j)
row.i = i;
col[0].j = j; // diagonal entry
col[0].i = i;
ncols = 1;
if (i==0 || i==info.mx-1 || j==0 || j==info.my-1) {
v[0] = 1.0; // on boundary: trivial equation
} else {
v[0] = 2*(hy/hx + hx/hy); // interior: build a row
if (i-1 > 0) {
col[ncols].j = j; col[ncols].i = i-1;
v[ncols++] = -hy/hx;
}
if (i+1 < info.mx-1) {
col[ncols].j = j; col[ncols].i = i+1;
v[ncols++] = -hy/hx;
}
if (j-1 > 0) {
col[ncols].j = j-1; col[ncols].i = i;
v[ncols++] = -hx/hy;
}
if (j+1 < info.my-1) {
col[ncols].j = j+1; col[ncols].i = i;
v[ncols++] = -hx/hy;
}
}
ierr = MatSetValuesStencil(A,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
return 0;
}
//ENDMATRIX
//STARTEXACT
PetscErrorCode formExact(DM da, Vec uexact) {
PetscErrorCode ierr;
PetscInt i, j;
PetscReal hx, hy, x, y, **auexact;
DMDALocalInfo info;
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);
ierr = DMDAVecGetArray(da, uexact, &auexact);CHKERRQ(ierr);
for (j = info.ys; j < info.ys+info.ym; j++) {
y = j * hy;
for (i = info.xs; i < info.xs+info.xm; i++) {
x = i * hx;
auexact[j][i] = x*x * (1.0 - x*x) * y*y * (y*y - 1.0);
}
}
ierr = DMDAVecRestoreArray(da, uexact, &auexact);CHKERRQ(ierr);
return 0;
}
PetscErrorCode formRHS(DM da, Vec b) {
PetscErrorCode ierr;
PetscInt i, j;
PetscReal hx, hy, x, y, f, **ab;
DMDALocalInfo info;
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);
ierr = DMDAVecGetArray(da, b, &ab);CHKERRQ(ierr);
for (j=info.ys; j<info.ys+info.ym; j++) {
y = j * hy;
for (i=info.xs; i<info.xs+info.xm; i++) {
x = i * hx;
if (i==0 || i==info.mx-1 || j==0 || j==info.my-1) {
ab[j][i] = 0.0; // on boundary: 1*u = 0
} else {
f = 2.0 * ( (1.0 - 6.0*x*x) * y*y * (1.0 - y*y)
+ (1.0 - 6.0*y*y) * x*x * (1.0 - x*x) );
ab[j][i] = hx * hy * f;
}
}
}
ierr = DMDAVecRestoreArray(da, b, &ab); CHKERRQ(ierr);
return 0;
}
//ENDEXACT
| {
"alphanum_fraction": 0.5240886609,
"avg_line_length": 34.7707006369,
"ext": "c",
"hexsha": "d52f399fd332e14d3998c1efc7397ed64ba86e48",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch3/poisson.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch3/poisson.c",
"max_line_length": 90,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch3/poisson.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 1756,
"size": 5459
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
int
main (void)
{
int N = 4;
double x[4] = {0.00, 0.10, 0.27, 0.30};
double y[4] = {0.15, 0.70, -0.10, 0.15};
/* Note: y[0] == y[3] for periodic data */
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
const gsl_interp_type *t = gsl_interp_cspline_periodic;
gsl_spline *spline = gsl_spline_alloc (t, N);
int i; double xi, yi;
printf ("#m=0,S=5\n");
for (i = 0; i < N; i++)
{
printf ("%g %g\n", x[i], y[i]);
}
printf ("#m=1,S=0\n");
gsl_spline_init (spline, x, y, N);
for (i = 0; i <= 100; i++)
{
xi = (1 - i / 100.0) * x[0] + (i / 100.0) * x[N-1];
yi = gsl_spline_eval (spline, xi, acc);
printf ("%g %g\n", xi, yi);
}
gsl_spline_free (spline);
gsl_interp_accel_free (acc);
return 0;
}
| {
"alphanum_fraction": 0.5401785714,
"avg_line_length": 21.8536585366,
"ext": "c",
"hexsha": "02488a1c878f96a751ab6c010d04f63536e05752",
"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/doc/examples/interpp.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/doc/examples/interpp.c",
"max_line_length": 58,
"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/doc/examples/interpp.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": 351,
"size": 896
} |
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_matrix_double.h>
int main() {
gsl_matrix* A;
gsl_matrix* U;
gsl_matrix* V;
gsl_vector* S;
gsl_vector* work;
int i, j;
int M, N;
M = N = 2;
work = gsl_vector_alloc(N);
S = gsl_vector_alloc(N);
A = gsl_matrix_alloc(M, N);
V = gsl_matrix_alloc(N, N);
gsl_matrix_set(A, 0, 0, -0.93);
gsl_matrix_set(A, 0, 1, 1.80);
gsl_matrix_set(A, 1, 0, 0);
gsl_matrix_set(A, 1, 1, 0);
gsl_linalg_SV_decomp(A, V, S, work);
U = A;
printf("S = [");
for (i=0; i<N; i++)
printf(" %g", gsl_vector_get(S, i));
printf(" ]\n");
printf("U = [");
for (j=0; j<M; j++) {
if (j)
printf(" [");
for (i=0; i<N; i++)
printf(" %g", gsl_matrix_get(U, j, i));
printf(" ]\n");
}
printf("V = [");
for (j=0; j<N; j++) {
if (j)
printf(" [");
for (i=0; i<N; i++)
printf(" %g", gsl_matrix_get(V, j, i));
printf(" ]\n");
}
gsl_matrix_set(A, 0, 0, -0.93);
gsl_matrix_set(A, 0, 1, 1.80);
gsl_matrix_set(A, 1, 0, 0);
gsl_matrix_set(A, 1, 1, 0);
gsl_linalg_SV_decomp_jacobi(A, V, S);
printf("S = [");
for (i=0; i<N; i++)
printf(" %g", gsl_vector_get(S, i));
printf(" ]\n");
printf("U = [");
for (j=0; j<M; j++) {
if (j)
printf(" [");
for (i=0; i<N; i++)
printf(" %g", gsl_matrix_get(U, j, i));
printf(" ]\n");
}
printf("V = [");
for (j=0; j<N; j++) {
if (j)
printf(" [");
for (i=0; i<N; i++)
printf(" %g", gsl_matrix_get(V, j, i));
printf(" ]\n");
}
return 0;
}
| {
"alphanum_fraction": 0.4449315068,
"avg_line_length": 20.9770114943,
"ext": "c",
"hexsha": "a2c7ca1a4f7cf1b1244c6f42c635efdbc64c02e5",
"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/svd-demo.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/svd-demo.c",
"max_line_length": 51,
"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/svd-demo.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": 652,
"size": 1825
} |
/* matrix/gsl_matrix_long_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_LONG_DOUBLE_H__
#define __GSL_MATRIX_LONG_DOUBLE_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_long_double.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
long double * data;
gsl_block_long_double * block;
int owner;
} gsl_matrix_long_double;
typedef struct
{
gsl_matrix_long_double matrix;
} _gsl_matrix_long_double_view;
typedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;
typedef struct
{
gsl_matrix_long_double matrix;
} _gsl_matrix_long_double_const_view;
typedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;
/* Allocation */
GSL_EXPORT
gsl_matrix_long_double *
gsl_matrix_long_double_alloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_long_double *
gsl_matrix_long_double_calloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_long_double *
gsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_EXPORT
gsl_matrix_long_double *
gsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_EXPORT
gsl_vector_long_double *
gsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,
const size_t i);
GSL_EXPORT
gsl_vector_long_double *
gsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,
const size_t j);
GSL_EXPORT void gsl_matrix_long_double_free (gsl_matrix_long_double * m);
/* Views */
GSL_EXPORT
_gsl_matrix_long_double_view
gsl_matrix_long_double_submatrix (gsl_matrix_long_double * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);
GSL_EXPORT
_gsl_matrix_long_double_view
gsl_matrix_long_double_view_array (long double * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_long_double_view
gsl_matrix_long_double_view_array_with_tda (long double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_long_double_view
gsl_matrix_long_double_view_vector (gsl_vector_long_double * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_long_double_view
gsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_matrix_long_double_const_row (const gsl_matrix_long_double * m,
const size_t i);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_matrix_long_double_const_column (const gsl_matrix_long_double * m,
const size_t j);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m,
const size_t k);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m,
const size_t k);
GSL_EXPORT
_gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_array (const long double * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_array_with_tda (const long double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_EXPORT long double gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);
GSL_EXPORT long double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT const long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);
GSL_EXPORT void gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);
GSL_EXPORT void gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);
GSL_EXPORT int gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;
GSL_EXPORT int gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;
GSL_EXPORT int gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);
GSL_EXPORT int gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);
GSL_EXPORT int gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_EXPORT int gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);
GSL_EXPORT int gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);
GSL_EXPORT int gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_EXPORT long double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);
GSL_EXPORT long double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);
GSL_EXPORT void gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);
GSL_EXPORT void gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);
GSL_EXPORT void gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);
GSL_EXPORT void gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_EXPORT int gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);
GSL_EXPORT int gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_EXPORT int gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_EXPORT int gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_EXPORT int gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_EXPORT int gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);
GSL_EXPORT int gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);
GSL_EXPORT int gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_EXPORT int gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);
GSL_EXPORT int gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);
GSL_EXPORT int gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);
GSL_EXPORT int gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
long double
gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
#endif
return m->data[i * m->tda + j] ;
}
extern inline
void
gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
m->data[i * m->tda + j] = x ;
}
extern inline
long double *
gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (long double *) (m->data + (i * m->tda + j)) ;
}
extern inline
const long double *
gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (const long double *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.7081639037,
"avg_line_length": 37.2827988338,
"ext": "h",
"hexsha": "f219ce76c61a8da15579df33d0e78297ece48cc7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h",
"max_line_length": 147,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_matrix_long_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2987,
"size": 12788
} |
/**
*
* @file qwrapper_dgemv_tile.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:59 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* Version of zgemv for tile storage, to avoid dependency problem when
* computations are done within the tile. alpha and beta are passed as
* pointers so they can depend on runtime values.
*
* @param[in] Alock
* Pointer to tile owning submatrix A.
*
* @param[in] xlock
* Pointer to tile owning subvector x.
*
* @param[in] ylock
* Pointer to tile owning subvector y.
*
**/
void QUARK_CORE_dgemv_tile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum trans,
int m, int n,
const double *alpha, const double *A, int lda,
const double *x, int incx,
const double *beta, double *y, int incy,
const double *Alock,
const double *xlock,
const double *ylock)
{
/* Quick return. Bad things happen if sizeof(...)*m*n is zero in QUARK_Insert_Task */
if ( m == 0 || n == 0 )
return;
DAG_SET_PROPERTIES("gemv", "lightslateblue");
QUARK_Insert_Task(quark, CORE_dgemv_tile_quark, task_flags,
sizeof(PLASMA_enum), &trans, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(double), alpha, INPUT,
sizeof(double)*m*n, A, NODEP, /* input; see Alock */
sizeof(int), &lda, VALUE,
sizeof(double)*n, x, NODEP, /* input; see xlock */
sizeof(int), &incx, VALUE,
sizeof(double), beta, INPUT,
sizeof(double)*m, y, NODEP, /* inout; see ylock */
sizeof(int), &incy, VALUE,
sizeof(double)*m*n, Alock, INPUT,
sizeof(double)*n, xlock, INPUT,
sizeof(double)*m, ylock, INOUT,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dgemv_tile_quark = PCORE_dgemv_tile_quark
#define CORE_dgemv_tile_quark PCORE_dgemv_tile_quark
#endif
void CORE_dgemv_tile_quark(Quark *quark)
{
PLASMA_enum trans;
int m, n, lda, incx, incy;
const double *alpha, *beta;
const double *A, *x;
double *y;
quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );
cblas_dgemv(
CblasColMajor,
(CBLAS_TRANSPOSE)trans,
m, n,
(*alpha), A, lda,
x, incx,
(*beta), y, incy );
}
| {
"alphanum_fraction": 0.4904776772,
"avg_line_length": 35.1978021978,
"ext": "c",
"hexsha": "c83ac5a31b119dd242def2d93028e7954f2c96e4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_dgemv_tile.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_dgemv_tile.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_dgemv_tile.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 791,
"size": 3203
} |
#ifndef DERIVATIVE_H
#define DERIVATIVE_H
#include <memory>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_deriv.h>
#include "constants.h"
void deriv_discrete(gsl_vector *df, gsl_vector *f, double step);
#endif // DERIVATIVE_H
| {
"alphanum_fraction": 0.7465277778,
"avg_line_length": 15.1578947368,
"ext": "h",
"hexsha": "51b8c2aa734e228866242aaae8599086584ed8a0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z",
"max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ichi-rika/glottal-inverse",
"max_forks_repo_path": "inc/derivative.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"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": "ichi-rika/glottal-inverse",
"max_issues_repo_path": "inc/derivative.h",
"max_line_length": 64,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ichi-rika/glottal-inverse",
"max_stars_repo_path": "inc/derivative.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z",
"num_tokens": 82,
"size": 288
} |
/* Siconos-Numerics, Copyright INRIA 2005-2011.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#ifndef SiconosBlas_H
#define SiconosBlas_H
#include "SiconosConfig.h"
#if defined(__cplusplus)
#include <algorithm>
using std::min;
using std::max;
#else
#define min(a,b) ((a)>(b)?(b):(a))
#define max(a,b) ((a) >= (b) ? (a) : (b))
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
#if defined(HAS_MKL_CBLAS)
#include <mkl_cblas.h>
#elif defined(HAS_ATLAS_CBLAS)
#include <cblas.h>
#elif defined(HAS_ACCELERATE)
#include <Accelerate.h>
#else
#include <cblas.h>
#endif
#ifdef __cplusplus
}
#endif
#include "matrix_la.h"
#endif // SiconosBlas_H
| {
"alphanum_fraction": 0.7335109927,
"avg_line_length": 25.4406779661,
"ext": "h",
"hexsha": "e7538814ec35fc21ea4a89f8f6deeadde4601684",
"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": "2739a23f23d797dbfecec79d409e914e13c45c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "siconos/siconos-deb",
"max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67",
"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": "siconos/siconos-deb",
"max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "siconos/siconos-deb",
"max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 407,
"size": 1501
} |
ο»Ώ/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Backwards elimination algorithm using Bidiag2.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
This is a MEX function which uses the Bidiag2 PLS algorithm to estimate the cross-validated root-
mean-squared-error, RMSEcv, of an initial design matrix X, regressed upon y, together with every
possible single inactivation of a column. The function returns a matrix with RMSEcv as a function
of variable selection and PLS component where the first row corresponds to the initial variable
selection and every following row corresponds to the inactivation of variable 1 to n.
The function takes 5 inputs:
* Input 1: a [m x n] design matrix with observations as rows and variables as columns.
* Input 2: a [m x 1] vector with response values (multiple responses is not supported).
* Input 3: a [1 x 1] scalar 'A' specifying the maximum number of PLS components to calculate.
* Input 4: a [1 x 1] scalar 'MaxIter' specifying how many MonteCarlo CV iterations should be done.
* Input 5: a [1 x 1] scalar 'NoValObs' specifying how many unique responses should be in one validation fold.
The function outputs 1 variable:
* Output 1: a [(n+1) x A] matrix with RMSEcv. Variable selection along rows and components
along columns.
Example on how to compile and run from Matlab:
% Compile .C to .mexw64
>> mex -largeArrayDims -lmwblas BackwardsSelectionBidag2.c
% Run from Matlab when compiled:
>> X = rand(10000, 256);
>> y = rand(10000, 1);
>> A = 10;
>> MaxIters = 10;
>> Valobs = round(length(unique(y))/4);
>> [ RMSEcv ] = BackwardsSelectionBidag2( X , y, A, MaxIters, Valobs );
Example of compatible C compilers:
* Microsoft Visual C++ 2013 Professional (C)
* Microsoft Visual C++ 2015 Professional (C)
* Intel Parallel Studio XE 2017
Written 2017-08-14 by
petter.stefansson@nmbu.no
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
#include <mex.h> // Needed to communicate with matlab
#include <blas.h> // Needed for blas functions
#include <string.h> // Needed to avoid compiler warning due to memcpy when using old compilers
#include <math.h> // Needed to take the square-root (sqrt)
#include <time.h> // Needed for counting CPU clock cycle which is used to set seed for rand()
/* βββββββββββββββββββββββββββββββββββ Function declarations βββββββββββββββββββββββββββββββββββ */
void PLS(const double *X, const double *y, int A, size_t m, size_t n, size_t p, double *beta,
double *B, double *w, double *wn, double *W, double *rho, double *rhoi, double *d, double *tty,
double *Xt, double *Ww, double *WWw, double *theta, double *thetai, double *Tt);
int randr(unsigned int min, unsigned int max);
void MarkAsVal(bool *IsVal, int NoValObs, size_t m, size_t *valm, size_t *trainm, const double *y);
void ExtractXandY(const double *X, const double *y, double *Xtrain, double *Xval, double *ytrain,
double *yval, size_t m, size_t n, bool *IsVal);
void Pred(double *Xval, double *beta, double *yval, size_t n, size_t valm, int A, double *yhat,
double *RMSEcv, int cvIter, int MaxIters, int ShavingIndex);
void SwapCols(double *Xtrain, double *Xval, size_t trainm, size_t valm, size_t n, int ColToShave);
/* βββββββββββββββββββββββββββββββββββ Matlab gateway start ββββββββββββββββββββββββββββββββββββ */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* ββββββββββββββββββββββββββ Variable type and name declaration βββββββββββββββββββββββββββ */
const double *X, *y;
double *Xtrain, *Xval, *ytrain, *yval, *beta, *yhat, *B, *w, *wn, *W, *rho, *rhoi, *d, *tty,
*Xt, *Ww, *WWw, *theta, *thetai, *Tt;
int cvIter, NoValObs, MaxIters, A, ColToShave;
bool *IsVal;
size_t m, n, p, trainm, valm;
/* ββββββββββββββββββββ Get pointers to the input variables from Matlab βββββββββββββββββββ */
X = mxGetPr(prhs[0]); // First input (X matrix).
y = mxGetPr(prhs[1]); // Second input (Y vector).
/* ββββββββββββββββββββ Get input scalar values containing PLS settings βββββββββββββββββββ */
A = (int)mxGetScalar(prhs[2]); // Third input (max number of components to calculate)
MaxIters = (int)mxGetScalar(prhs[3]); // Fourth input (Max cv-iters)
NoValObs = (int)mxGetScalar(prhs[4]); // Fifth input (Number of validation observations)
/* βββββββββββββββββββββββ Get the dimensions of the input variables βββββββββββββββββββββββ */
m = mxGetM(prhs[0]); // Number of rows in X.
n = mxGetN(prhs[0]); // Number of columns in X.
p = mxGetN(prhs[1]); // Number of columns in y.
/* βββββββββββββββββββββββββββ If input A is larger than n, let A = n ββββββββββββββββββββββ */
if ((A > n) || (A < 1)) { A = n; }
/* βββββββββββββββββββββββββββββββ Specify Matlab outputs ββββββββββββββββββββββββββββββββββ */
double *RMSEcv;
plhs[0] = mxCreateDoubleMatrix(n + 1, A, mxREAL);
RMSEcv = mxGetPr(plhs[0]);
/* ββββ Allocate space for variables that are used multiple times and can be overwritten βββ */
IsVal = (bool*)malloc(sizeof(bool) * m ); // [m-by-1]
Xtrain = (double*)malloc(sizeof(double) * m * n ); // [m-by-n] (overallocated)
Xval = (double*)malloc(sizeof(double) * m * n ); // [m-by-n] (overallocated)
ytrain = (double*)malloc(sizeof(double) * m ); // [m-by-1] (overallocated)
yval = (double*)malloc(sizeof(double) * m ); // [m-by-1] (overallocated)
beta = (double*)malloc(sizeof(double) * n * A ); // [n-by-A]
yhat = (double*)malloc(sizeof(double) * m * A ); // [m-by-A] (overallocated)
B = (double*)malloc(sizeof(double) * A * 2 ); // [A-by-2]
w = (double*)malloc(sizeof(double) * n ); // [n-by-1]
wn = (double*)malloc(sizeof(double) ); // [1-by-1]
W = (double*)malloc(sizeof(double) * n * A ); // [n-by-A]
rho = (double*)malloc(sizeof(double) ); // [1-by-1]
rhoi = (double*)malloc(sizeof(double) ); // [1-by-1]
d = (double*)malloc(sizeof(double) * n ); // [n-by-1]
tty = (double*)malloc(sizeof(double) ); // [1-by-1]
Xt = (double*)malloc(sizeof(double) * n ); // [n-by-1]
Ww = (double*)malloc(sizeof(double) * A ); // [A-by-1] (overallocated)
WWw = (double*)malloc(sizeof(double) * n ); // [n-by-1]
theta = (double*)malloc(sizeof(double) ); // [1-by-1]
thetai = (double*)malloc(sizeof(double) ); // [1-by-1]
Tt = (double*)malloc(sizeof(double) * A ); // [A-by-1] (overallocated)
/* Before starting set the seed of the RNG to the number of clock cycles since start. */
srand(clock());
/* CV-loop starts here */
for (cvIter = 0; cvIter < MaxIters; cvIter++) {
/* βββββββββββββ Mark rows of X as either validation rows or training rows βββββββββββββ */
MarkAsVal(IsVal, NoValObs, m, &valm, &trainm, y);
/* ββββββββββ Extract data from X and y and place in Xtrain/Xval/ytrain/yval βββββββββββ */
ExtractXandY(X, y, Xtrain, Xval, ytrain, yval, m, n, IsVal);
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Shaving step 1. Evaluate matrix with all variables included. */
/* βββββββββ Call PLS function to estimate Beta using Xtrain & ytrain ββββββββββββββββββ */
PLS( Xtrain, ytrain, A, trainm, n, p, beta, B, w, wn, W, rho, rhoi, d, tty, Xt, Ww, WWw, theta, thetai, Tt);
/* βββββββ Use beta to estimate error when predicting yval using Xval ββββββββββββββββββ */
Pred( Xval, beta, yval, n, valm, A, yhat, RMSEcv, cvIter, MaxIters, 0);
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Shaving step 2. Evaluate matrix with all except the last variable included. */
/* βββββββββ Call PLS function to estimate Beta using Xtrain & ytrain ββββββββββββββββββ */
PLS(Xtrain, ytrain, A, trainm, n - 1, p, beta, B, w, wn, W, rho, rhoi, d, tty, Xt, Ww, WWw, theta, thetai, Tt);
/* βββββββ Use beta to estimate error when predicting yval using Xval ββββββββββββββββββ */
Pred(Xval, beta, yval, n - 1, valm, A, yhat, RMSEcv, cvIter, MaxIters, n);
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Shaving step 3. Keep last column inactive and swap it one by one with cols 0 : n-1 */
for (ColToShave = 0; ColToShave < (n - 1); ColToShave++) {
/* Place ColToShave at the end, effectecly inactivating it. */
SwapCols(Xtrain, Xval, trainm, valm, n, ColToShave + 1);
/* ββββββββ Call PLS function to estimate Beta using Xtrain & ytrain βββββββββββββββ */
PLS(Xtrain, ytrain, A, trainm, n - 1, p, beta, B, w, wn, W, rho, rhoi, d, tty, Xt, Ww, WWw, theta, thetai, Tt);
/* ββββββ Use beta to estimate error when predicting yval using Xval βββββββββββββββ */
Pred(Xval, beta, yval, n - 1, valm, A, yhat, RMSEcv, cvIter, MaxIters, ColToShave + 1);
}
}
/* ββββββββββββββββββββββββββββββββββ Free allocated memory ββββββββββββββββββββββββββββββββ */
free(IsVal);
free(Xtrain);
free(Xval);
free(ytrain);
free(yval);
free(beta);
free(yhat);
free(B);
free(w);
free(wn);
free(W);
free(rho);
free(rhoi);
free(d);
free(tty);
free(Xt);
free(Ww);
free(WWw);
free(theta);
free(thetai);
free(Tt);
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for estimating Beta using the bidag2 algorithm */
void PLS(const double *X, const double *y, int A, size_t m, size_t n, size_t p, double *beta,
double *B, double *w, double *wn, double *W, double *rho, double *rhoi, double *d,
double *tty, double *Xt, double *Ww, double *WWw, double *theta, double *thetai, double *Tt){
/* ββββββββββββββββββββββββββ Variable type and name declaration ββββββββββββββββββββββββββ */
double *t;
double *T;
double *Xw;
double *TTt;
int a, row;
size_t st_a;
mwSignedIndex IntConstOne = 1;
double one = 1.0, zero = 0.0, none = -1.0;
/* βββββββββββββββββ Allocate memory for variables used in the calculation βββββββββββββββββ */
t = (double*)malloc(sizeof(double) * m ); // [m-by-1]
T = (double*)malloc(sizeof(double) * m * A ); // [m-by-A]
Xw = (double*)malloc(sizeof(double) * m ); // [m-by-1]
TTt = (double*)malloc(sizeof(double) * m ); // [m-by-1]
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββ Start of calculation part βββββββββββββββββββββββββββββββ */
/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 1: w = X'*y; */
/// X = [m-by-n]
/// y = [m-by-1]
/// w = [n-by-1]
// Matrix-Vector multiplication -> dgemv.
dgemv("T", &m, &n, &one, X, &m, y, &IntConstOne, &zero, w,&IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 2: w = w / norm(w); */
/// w = [n-by-1]
/// wn = [1-by-1]
// Vector norm -> dnrm2.
*wn = dnrm2(&n, w, &IntConstOne);
// Inverse resulting scalar to enable multiplication instead of division.
*wn = 1 / (*wn);
// Vector-scalar multiplication -> dscal.
dscal(&n, wn, w, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 3: W(:,CurrentComp) = w; */
/// W = [n-by-A]
/// w = [n-by-1]
// Copy n doubles from w to W.
memcpy(W, w, sizeof(double) * n);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 4: t = X*w; */
/// X = [m-by-n]
/// w = [n-by-1]
/// t = [m-by-1]
// Matrix-Vector multiplication -> dgemv.
dgemv("N", &m, &n, &one, X, &m, w, &IntConstOne, &zero, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 5: rho = norm(t); */
/// t = [m-by-1]
/// rho = [1-by-1]
// Vector norm->dnrm2.
*rho = dnrm2(&m, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 6: t = t / rho; */
/// t = [m-by-1]
/// rho = [1-by-1]
/// rhoi = [1-by-1]
// Create inverse rho (rhoi) scalar to enable multiplication instead of division.
*rhoi = 1 / (*rho);
// Vector-scalar multiplication ->dscal.
dscal(&m, rhoi, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 7: T(:,CurrentComp) = t; */
/// T = [m-by-A]
/// t = [m-by-p]
// Copy m doubles from t to T.
memcpy(T, t, sizeof(double) * m);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 8: B(1, 1) = rho; */
/// B = [A-by-2]
/// rho = [1-by-1]
B[0] = *rho;
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 9: d = w / rho; */
/// w = [n-by-1]
/// rho = [1-by-1]
/// rhoi = [1-by-1]
/// d = [n-by-1]
// Make d = w
memcpy(d, w, sizeof(double) * n);
// Then scale it with the inversed version of rho to make it w/rho.
dscal(&n, rhoi, d, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 9: beta(:, 1) = (t'*y)*d; */
/// t = [m-by-1]
/// d = [n-by-1]
/// y = [m-by-1]
/// tty = [1-by-1]
/// beta(:,1) = [n-by-1]
// (t'*y) vector-vector product -> ddot.
*tty = ddot(&m, t, &IntConstOne, y, &IntConstOne);
// (d*tty) vector-scalar product. (Here treated as matrix-matrix).
dgemm("N", "N", &n, &p, &p, &one, d, &n, tty, &p, &zero, beta, &n);
//* Start of component loop. */
for (a = 1; a < A; a++) {
/* size_t version of a (preferred by BLAS instead of int). */
st_a = (size_t)a;
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 10: w = X'*t - rho*w; */
/// w = [n-by-1]
/// rho = [1-by-1]
/// X = [m-by-n]
/// t = [m-by-1]
/// Xt = [n-by-1]
// Xt = X'*t matrix-vector multiplication -> dgemv.
dgemv("T", &m, &n, &one, X, &m, t, &IntConstOne, &zero, Xt, &IntConstOne);
// The value of rho wont be used again, overwrite with -1*rho.
*rho = -1 * (*rho);
// w = rho*w scalar-vector multiplication -> dscal.
dscal(&n, rho, w, &IntConstOne);
// w = 1*Xt + w vector times constant plus vector -> daxpy.
daxpy(&n, &one, Xt, &IntConstOne, w, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 11: w = w - W(:,1:a)*(W(:,1:a)'*w); */
/// W(:,1:a) = [n-by-a]
/// w = [n-by-1]
/// Ww = [a-by-1]
/// WWw = [n-by-1]
// Ww = (W(:,1:a)'*w) matrix-vector multiplication -> dgemm.
dgemv("T", &n, &st_a, &one, W, &n, w, &IntConstOne, &zero, Ww, &IntConstOne);
// WWw = W(:,1:a)*(W(:,1:a)'*w) matrix-vector multiplication -> dgemm.
dgemv("N", &n, &st_a, &one, W, &n, Ww, &IntConstOne, &zero, WWw, &IntConstOne);
// w β w + -1 * WWw constant times a vector plus a vector -> daxpy.
daxpy(&n, &none, WWw, &IntConstOne, w, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 12: theta = norm(w); */
/// w = [n-by-1]
/// theta = [1-by-1]
// Vector norm -> dnrm2.
*theta = dnrm2(&n, w, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 13: w = w / theta; */
/// w = [n-by-1]
/// theta = [1-by-1]
// w = w * (1/theta) scalar-vector multiplication -> dscal.
*thetai = 1 / (*theta);
dscal(&n, thetai, w, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 14: W(:,a) = w; */
/// w = [n-by-1]
/// W = [n-by-A]
// Copy n elemments from w into W at offset n * a.
memcpy(W + n * a, w, sizeof(double) * n);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 15: t = X*w - theta*t; */
/// X = [m-by-n]
/// w = [n-by-1]
/// theta = [1-by-1]
/// t = [m-by-1]
/// Xw = [m-by-1]
// Xw = X*w = matrix vector multiplication -> dgemv.
dgemv("N", &m, &n, &one, X, &m, w, &IntConstOne, &zero, Xw, &IntConstOne);
// t = Xw - theta*t Better to solve with daxpy?
//for (row = 0; row < m; row++){
// t[row] = Xw[row] - (*theta) * t[row];
//}
dscal(&m, theta, t, &IntConstOne);
dscal(&m, &none, t, &IntConstOne);
daxpy(&m, &one, Xw, &IntConstOne, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 16: t = t - T(:,1:a)*(T(:,1:a)'*t); */
/// t = [m-by-1]
/// T(:,1:a) = [m-by-a]
/// Tt = [a-by-1]
/// TTt = [m-by-1]
// Tt = (T(:,1:a)'*t) matrix-vector multiplication -> dgemv.
dgemv("T", &m, &st_a, &one, T, &m, t, &IntConstOne, &zero, Tt, &IntConstOne);
// TTt = T(:,1:a)*(T(:,1:a)'*t) matrix-vector multiplication -> dgemv.
dgemv("N", &m, &st_a, &one, T, &m, Tt, &IntConstOne, &zero, TTt, &IntConstOne);
// t β t + -1 * TTt constant times a vector plus a vector -> daxpy.
daxpy(&m, &none, TTt, &IntConstOne, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 17: rho = norm(t); */
/// t = [m-by-1]
/// rho = [1-by-1]
// Vector norm -> dnrm2.
*rho = dnrm2(&m, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 18: t = t/rho; */
/// t = [m-by-1]
/// rho = [1-by-1]
// Update inverse version of rho.
*rhoi = 1 / (*rho);
// t = t * (1/rho) scalar-vector multiplication -> dscal
dscal(&m, rhoi, t, &IntConstOne);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 19: T(:, a) = t; */
/// T = [m-by-A]
/// t = [m-by-1]
// Copy m elemments from t into T at offset m * a
memcpy(T + m * a, t, sizeof(double) * m);
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 20: B(a, 1) = rho; */
/// B = [A-by-2]
/// rho = [1-by-1]
B[a] = *rho;
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 21: B(a - 1, 2) = theta; */
/// B = [A-by-2]
/// theta = [1-by-1]
B[(a-1) + A] = *theta;
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 22: d = (w - theta*d) / rho; */
/// d = [n-by-1]
/// rho = [1-by-1]
/// theta = [1-by-1]
/// w = [n-by-1]
for (row = 0; row < n; row++){
d[row] = ( w[row] - (*theta) * d[row] ) / (*rho);
}
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Step 23: beta(:, a) = beta(:, a - 1) + (t'*y)*d; */
/// beta = [n-by-A]
/// t = [m-by-1]
/// y = [m-by-1]
/// d = [n-by-1]
// (t'*y) vector-vector product -> ddot
*tty = ddot(&m, t, &IntConstOne, y, &IntConstOne);
// (tty*d) = scalar-vector product. (Here treated as matrix-matrix).
dgemm("N", "N", &n, &p, &p, &one, d, &n, tty, &p, &zero, beta + n * a , &n);
// beta(:, a) β beta(:, a) + 1 * beta(:, a - 1) -> daxpy
daxpy(&n, &one, beta + n * (a-1), &IntConstOne, beta + n * a, &IntConstOne);
//for (row = 0; row < n; row++) {
//beta[row + n * a] = beta[row + n * a] + beta[row + n * (a - 1)];
//beta[row + n * a] = beta[row + n * (a - 1)];
//}
/* End of component loop. */
}
free(t);
free(T);
free(Xw);
free(TTt);
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for drawing a random integer that lies within range. */
int randr(unsigned int min, unsigned int max) {
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for marking rows in the data as validation or not during CV */
void MarkAsVal(bool *IsVal, int NoValObs, size_t m, size_t *valm, size_t *trainm, const double *y) {
int activeobs, row, index;
bool alreadyactive;
/* Initialize all IsVal elements to false */
for (row = 0; row < m; row++) {
IsVal[row] = false;
}
activeobs = 0;
while (activeobs < NoValObs) { // NOTE! this needs a check aginst input NoValObs larger than unique(y)!
/* Draw random rownumber between 0 and m */
index = randr(0, m);
alreadyactive = false;
/* Mark all the rows with the same response as validation to keep replicates together */
for (row = 0; row < m; row++) {
if (y[row] == y[index]) {
/* If IsVal was 0 it means this is a newly found observation. */
if (IsVal[row] == false & alreadyactive == false) {
activeobs += 1;
alreadyactive = true;
}
/* If IsVal is already 1 stop looping and pick a new observation to save time */
else if (IsVal[row] == true) {
break;
}
IsVal[row] = true;
}
}
}
/* Calculate the number of rows in Xval/yval and Xtrain/ytrain so they can be allocated */
*valm = 0;
for (row = 0; row < m; row++) {
if (IsVal[row] == true) {
*valm += 1;
}
}
*trainm = m - (*valm);
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for populating Xtrain Xval ytrain yval given known IsVal vector */
void ExtractXandY(const double *X, const double *y, double *Xtrain, double *Xval, double *ytrain,
double *yval, size_t m, size_t n, bool *IsVal) {
int col, row, xte, xve, yve, yte;
xte = xve = 0;
yte = yve = 0;
/* Outer loop over all columns of X */
for (col = 0; col < n; col++) {
/* Inner loop over all rows of X */
for (row = 0; row < m; row++) {
if (IsVal[row] == true) {
Xval[xve] = X[row + col * m];
xve += 1;
if (col == 0) {
yval[yve] = y[row];
yve += 1;
}
}
else {
Xtrain[xte] = X[row + col * m];
xte += 1;
if (col == 0) {
ytrain[yte] = y[row];
yte += 1;
}
}
}
}
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for calculating validation error using Xval and beta */
void Pred(double *Xval, double *beta, double *yval, size_t n, size_t valm, int A, double *yhat, double *RMSEcv, int cvIter, int MaxIters, int ShavingIndex) {
size_t st_A;
int col;
double one = 1.0, zero = 0.0, none = -1.0;
mwSignedIndex IntConstOne = 1;
st_A = (size_t)A;
/* yhat = Xval*beta */
dgemm("N", "N", &valm, &st_A, &n, &one, Xval, &valm, beta, &n, &zero, yhat, &valm);
/* Loop the columns of yhat and calulate the error for each component. */
for (col = 0; col < A; col++) {
/* yhat is here overwritten and becomes epsilon where epsilon = yhat + (-Yval). */
daxpy(&valm, &none, yval, &IntConstOne, yhat + col * valm, &IntConstOne);
/* Calculate the Mean Squared Error by taking the dot product of each error column with
itself and then dividing by the number of observations (valm). At the same time, add it
to the existing value of the RMSE vector, thereby performing a summation of the errors
of each cross-validation iteration at the same time (prevents the need of a 2D matrix). */
if (ShavingIndex == 0) {
RMSEcv[ShavingIndex + col*(n + 1)] += ddot(&valm, yhat + col * valm, &IntConstOne, yhat + col * valm, &IntConstOne) / valm;
}
else {
RMSEcv[ShavingIndex + col*(n + 2)] += ddot(&valm, yhat + col * valm, &IntConstOne, yhat + col * valm, &IntConstOne) / valm;
}
/* If its the last cross-validation iteration, finalize RMSEcv (which right now
represents sum(MSE,1) [folds-by-components] ) by dividing by the number of cv iterations
and taking the square-root of the currently squared errors. */
if (cvIter == MaxIters - 1) {
if (ShavingIndex == 0) {
RMSEcv[ShavingIndex + col*(n + 1)] = sqrt(RMSEcv[ShavingIndex + col*(n + 1)] / MaxIters);
}
else {
RMSEcv[ShavingIndex + col*(n + 2)] = sqrt(RMSEcv[ShavingIndex + col*(n + 2)] / MaxIters);
}
}
}
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* Function for placing a column at the and of a matrix (swapping it with the last column) */
void SwapCols(double *Xtrain, double *Xval, size_t trainm, size_t valm, size_t n, int ColToShave) {
mwSignedIndex IntConstOne = 1;
/* Use dswap to swap location of two column vectors in Xtrain. */
dswap(&trainm, Xtrain + (n - 1) * trainm, &IntConstOne, Xtrain + ColToShave * trainm, &IntConstOne);
/* Use dswap to swap location of two column vectors in Xval. */
dswap(&valm, Xval + (n - 1) * valm, &IntConstOne, Xval + ColToShave * valm, &IntConstOne);
}
/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */ | {
"alphanum_fraction": 0.4403349616,
"avg_line_length": 42.2779503106,
"ext": "c",
"hexsha": "8195e61e56b4bd008489e95544415dbc3533b431",
"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": "adcee85c172fdb1fe305f0bde7480f043566703b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Petter-s/RegressionFunctions",
"max_forks_repo_path": "PLS/VariableSelection/BackwardsSelectionBidag2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "adcee85c172fdb1fe305f0bde7480f043566703b",
"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": "Petter-s/RegressionFunctions",
"max_issues_repo_path": "PLS/VariableSelection/BackwardsSelectionBidag2.c",
"max_line_length": 157,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "adcee85c172fdb1fe305f0bde7480f043566703b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Petter-s/RegressionFunctions",
"max_stars_repo_path": "PLS/VariableSelection/BackwardsSelectionBidag2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8064,
"size": 27227
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "sum.h"
int main(int argc, char *argv[]) {
int num_bands = 2;
double t = 1.0;
double E0 = 6.0;
double deltaE = 14.0;
void Efn(double k[3], gsl_vector *energies) {
double cx = cos(2.0 * M_PI * k[0]);
double cy = cos(2.0 * M_PI * k[1]);
double cz = cos(2.0 * M_PI * k[2]);
double tk = -2.0 * t * (cx + cy + cz);
int i;
double E0_band;
for (i = 0; i < num_bands; i++) {
E0_band = E0 + ((double)i) * deltaE;
gsl_vector_set(energies, i, E0_band + tk);
}
}
int na = 8;
int nb = 8;
int nc = 8;
bool use_cache = true;
gsl_matrix *R = gsl_matrix_calloc(3, 3); // R -> all zeros
// Overall scale for R doesn't matter.
gsl_matrix_set(R, 0, 0, 1.0);
gsl_matrix_set(R, 1, 1, 1.0);
gsl_matrix_set(R, 2, 2, 1.0);
double num_electrons = 1.0;
double E_Fermi = 0.0;
double energy = SumEnergy(&E_Fermi, Efn, na, nb, nc, num_bands, num_electrons, R, use_cache);
printf("Got E_Fermi = %f\n", E_Fermi);
printf("Got energy = %f\n", energy);
double tol = 1e-8;
double expected = 6.0;
if (fabs(energy - expected) > tol) {
printf("Incorrect energy; got %f, expected %f\n", energy, expected);
return 1;
}
printf("Sum test passed.\n");
return 0;
}
| {
"alphanum_fraction": 0.5516769336,
"avg_line_length": 28.0961538462,
"ext": "c",
"hexsha": "52dddd8fd8b72b016de1516d04ae96c3b0be5202",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "sum_test.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "sum_test.c",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "sum_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 511,
"size": 1461
} |
/**
*
* @generated d Tue Jan 7 11:45:26 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#ifdef USE_MKL
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
#else
#include <cblas.h>
#include <lapacke.h>
#endif
#include "plasma.h"
#include <core_blas.h>
#include "auxiliary.h"
/*--------------------------------------------------------------
* Check the solution
*/
double d_check_solution(int M, int N, int NRHS, double *A, int LDA,
double *B, double *X, int LDB)
{
/* int info_solution; */
double Rnorm = -1.00;
double zone = 1.0;
double mzone = -1.0;
double *work = (double *)malloc(max(M, N)* sizeof(double));
LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work);
LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work);
LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB);
Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);
free(work);
return Rnorm;
}
| {
"alphanum_fraction": 0.5972101133,
"avg_line_length": 24.9347826087,
"ext": "c",
"hexsha": "32d31830408970a6f145a7bbb857c8628fe6269d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z",
"max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "tianyi93/hpxMP_mirror",
"max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/dauxiliary.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "tianyi93/hpxMP_mirror",
"max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/dauxiliary.c",
"max_line_length": 112,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "tianyi93/hpxMP_mirror",
"max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/dauxiliary.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z",
"num_tokens": 377,
"size": 1147
} |
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Developed by Minigraph
//
// Author: James Stanard
//
#pragma once
#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union
#pragma warning(disable:4238) // nonstandard extension used : class rvalue used as lvalue
#pragma warning(disable:4324) // structure was padded due to __declspec(align())
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <d3d12.h>
#pragma comment(lib, "d3d12.lib")
#pragma comment(lib, "dxgi.lib")
#define MY_IID_PPV_ARGS IID_PPV_ARGS
#define D3D12_GPU_VIRTUAL_ADDRESS_NULL ((D3D12_GPU_VIRTUAL_ADDRESS)0)
#define D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN ((D3D12_GPU_VIRTUAL_ADDRESS)-1)
#pragma region
#include <d3dx12.h>
#include <d3d12shader.h>
#include <d3dcompiler.h>
#pragma endregion
#pragma region
#pragma comment (lib, "d3dcompiler.lib")
#pragma endregion
#include <cstdint>
#include <cstdio>
#include <cstdarg>
#include <vector>
#include <memory>
#include <string>
#include <exception>
#include <numeric>
#include <wrl.h>
#include <ppltasks.h>
#include <gsl\gsl>
#include "Utility.h"
#include "VectorMath.h"
#include "EngineTuning.h"
#include "EngineProfiling.h"
template< typename T >
using NotNull = gsl::not_null< T >;
#define SHADER_ARGS(shader) (shader), \
sizeof(shader)
template<typename T, std::size_t N>
struct Array :public std::array<T, N>
{
static inline std::function<T(T, T)> multiply = [](T priview, T current) {
return priview * current;
};
public:
T product()
{
return std::accumulate(begin(), end(), 1, multiply);
}
};
using U32 = uint32_t;
using U32x1 = U32;
using U32x2 = Array<U32, 2>;
using U32x3 = Array<U32, 3>;
using F32 = float;
using F32x2 = Array<F32, 2>;
using F32x3 = Array<F32, 3>; | {
"alphanum_fraction": 0.6864142539,
"avg_line_length": 23.8829787234,
"ext": "h",
"hexsha": "aefc0ff0ef2aca0c5568b53b5f0b23b3546c4553",
"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": "2222a913905ba17c587dfedf04425fc8acfa06d3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sienaiwun/DirectX-Graphics-Samples",
"max_forks_repo_path": "MiniEngine/Core/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2222a913905ba17c587dfedf04425fc8acfa06d3",
"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": "sienaiwun/DirectX-Graphics-Samples",
"max_issues_repo_path": "MiniEngine/Core/pch.h",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2222a913905ba17c587dfedf04425fc8acfa06d3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sienaiwun/DirectX-Graphics-Samples",
"max_stars_repo_path": "MiniEngine/Core/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 584,
"size": 2245
} |
/* bcls.c
$Revision: 282 $ $Date: 2006-12-17 17:38:00 -0800 (Sun, 17 Dec 2006) $
---------------------------------------------------------------------
This file is part of BCLS (Bound-Constrained Least Squares).
Copyright (C) 2006 Michael P. Friedlander, Department of Computer
Science, University of British Columbia, Canada. All rights
reserved. E-mail: <mpf@cs.ubc.ca>.
BCLS is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
BCLS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with BCLS; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
---------------------------------------------------------------------
*/
/*!
\file
BCLS user-callable library routines.
*/
#include <cblas.h>
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
#include <math.h>
#include <assert.h>
#include <setjmp.h>
#include "bcls.h"
#include "bclib.h"
#include "bcsolver.h"
#include "bcversion.h"
/*!
\brief Malloc wrapper. Private to this file.
Pointer to the newly allocated memory,
or NULL if malloc returned an eror.
\param[in] len Number of elements needed
\param[in] size Memory needed for each element.
\param[in] who Short character description of the memory needed.
\return Pointer to the newly allocated memory.
*/
static void *
xmalloc (int len, size_t size, char * who)
{
register void *value = malloc(len * size);
if (value == NULL)
fprintf( stderr, "Not enough memory to allocate %s.\n", who );
return value;
}
/*!
\brief Create a BCLS problem instance.
This routine create a BCLS problem. It *must* be called before any
other BCLS routine. It will create and initialize a new BCLS
problem with enough space to accomodate the specified problem. The
problem is then initialized using bcls_init_prob.
In order to re-initialize the BCLS problem instance, but not
deallocate memory that's already sufficient for an equal or smaller
size problem, use bcls_init_prob.
\param[in] mmax Maximum number of rows in any A.
\param[in] nmax Maximum number of columns in any A.
\return Return a pointer to a new BCLS problem. If the return is
NULL, then the initialization failed.
*/
BCLS *
bcls_create_prob( int mmax, int nmax )
{
int mnmax = imax( nmax, mmax );
assert( mmax > 0 && nmax > 0 );
// Allocate the problem.
BCLS *ls = (BCLS *)xmalloc(1, sizeof(BCLS), "ls" );
// Check if the problem has been successfully allocated.
if (ls == NULL) {
fprintf( stderr, "XXX Could not allocate a BCLS problem.\n");
return ls;
}
// -----------------------------------------------------------------
// Allocate workspace vectors large enough to accomdate the problem.
// -----------------------------------------------------------------
// Record the maximum alloted workspace.
ls->mmax = mmax;
ls->nmax = nmax;
// Residual: r(m+n).
ls->r = (double *)xmalloc( mmax+nmax, sizeof(double), "r" );
if (ls->r == NULL) goto error;
// Gradient: g(n).
ls->g = (double *)xmalloc( nmax, sizeof(double), "g" );
if (ls->g == NULL) goto error;
// Search direction, full space: dx(n).
ls->dx = (double *)xmalloc( nmax, sizeof(double), "dx" );
if (ls->dx == NULL) goto error;
// Search direction, subspace: dxFree(n).
ls->dxFree = (double *)xmalloc( nmax, sizeof(double), "dxFree" );
if (ls->dxFree == NULL) goto error;
// Step to each breakpoint: aBreak(n).
ls->aBreak = (double *)xmalloc( nmax, sizeof(double), "aBreak" );
if (ls->aBreak == NULL) goto error;
// Indices of each breakpoint: iBreak(n).
ls->iBreak = (int *)xmalloc( nmax, sizeof(int), "iBreak" );
if (ls->iBreak == NULL) goto error;
// Variable indices: ix(n).
ls->ix = (int *)xmalloc( nmax, sizeof(int), "ix" );
if (ls->ix == NULL) goto error;
// Workspace: wrk_v( max(n, m) ).
ls->wrk_u = (double *)xmalloc( mnmax, sizeof(double), "wrk_u" );
if (ls->wrk_u == NULL) goto error;
// Workspace: wrk_v( max(n, m) ).
ls->wrk_v = (double *)xmalloc( mnmax, sizeof(double), "wrk_v" );
if (ls->wrk_v == NULL) goto error;
// Workspace: wrk_w( max(n, m) ).
ls->wrk_w = (double *)xmalloc( mnmax, sizeof(double), "wrk_w" );
if (ls->wrk_w == NULL) goto error;
// -----------------------------------------------------------------
// Initialize this new problem instance.
// -----------------------------------------------------------------
bcls_init_prob( ls );
// -----------------------------------------------------------------
// Exits.
// -----------------------------------------------------------------
// Successfull exit.
return ls;
error:
// Unsuccessful exit.
bcls_free_prob( ls );
return ls;
}
/*!
\brief Initialize a BCLS problem.
Initialize a BCLS problem. You can call this routine to "reset" a
BCLS problem, i.e., reset all parameter values. Note that it is
automatically called by bcls_create_prob.
\param[in,out] ls BCLS problem context.
*/
void
bcls_init_prob( BCLS *ls )
{
// Some quick error checking.
assert( ls->mmax > 0 && ls->nmax > 0 );
// Check if the problem has been successfully allocated.
if (ls == NULL) {
fprintf( stderr, "XXX The BCLS problem is NULL.\n");
return;
}
// Initialize the problem structure.
ls->print_info = NULL;
ls->print_hook = NULL;
ls->fault_info = NULL;
ls->fault_hook = NULL;
ls->Aprod = NULL;
ls->Usolve = NULL;
ls->CallBack = NULL;
ls->UsrWrk = NULL;
ls->anorm = NULL;
ls->print_level = 1;
ls->proj_search = BCLS_PROJ_SEARCH_EXACT;
ls->newton_step = BCLS_NEWTON_STEP_LSQR;
ls->minor_file = NULL;
ls->itnMaj = 0;
ls->itnMajLim = 5 * (ls->nmax);
ls->itnMin = 0;
ls->itnMinLim = 10 * (ls->nmax);
ls->nAprodT = 0;
ls->nAprodF = 0;
ls->nAprod1 = 0;
ls->nUsolve = 0;
ls->m = 0;
ls->n = 0;
ls->unconstrained = 0;
ls->damp = 0.0;
ls->damp_min = 1.0e-4;
ls->exit = BCLS_EXIT_UNDEF;
ls->soln_rNorm = -1.0;
ls->soln_dInf = 0.0;
ls->soln_jInf = -1;
ls->soln_stat = BCLS_SOLN_UNDEF;
ls->optTol = 1.0e-6;
ls->conlim = 1.0 / ( 10.0 * sqrt( DBL_EPSILON ) );
ls->mu = 1.0e-2;
ls->backtrack = 1.0e-1;
ls->backtrack_limit = 10;
// Initialize timers.
bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL] ), BCLS_TIMER_INIT );
ls->stopwatch[BCLS_TIMER_TOTAL].name = "Total time";
bcls_timer( &(ls->stopwatch[BCLS_TIMER_APROD] ), BCLS_TIMER_INIT );
ls->stopwatch[BCLS_TIMER_APROD].name = "Total time for Aprod";
bcls_timer( &(ls->stopwatch[BCLS_TIMER_USOLVE] ), BCLS_TIMER_INIT );
ls->stopwatch[BCLS_TIMER_USOLVE].name = "Total time for Usolve";
bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR] ), BCLS_TIMER_INIT );
ls->stopwatch[BCLS_TIMER_LSQR].name = "Total time for LSQR";
// Initialize constants.
ls->eps = DBL_EPSILON;
ls->eps2 = pow( DBL_EPSILON, 0.50 );
ls->eps3 = pow( DBL_EPSILON, 0.75 );
ls->epsx = ls->eps3;
ls->epsfixed = DBL_EPSILON;
ls->BigNum = BCLS_INFINITY;
return;
}
/*!
\brief Free and reinitialize all resources in an existing BCLS problem.
\return
- 0: no errors
- 1: the BCLS problem is NULL (ie, does not exist).
*/
int
bcls_free_prob( BCLS *ls )
{
// Report an error if it's already NULL.
if (ls == NULL) return 1;
// Deallocate the workspace.
assert( ls->r != NULL ); free( ls->r );
assert( ls->g != NULL ); free( ls->g );
assert( ls->dx != NULL ); free( ls->dx );
assert( ls->dxFree != NULL ); free( ls->dxFree );
assert( ls->aBreak != NULL ); free( ls->aBreak );
assert( ls->iBreak != NULL ); free( ls->iBreak );
assert( ls->ix != NULL ); free( ls->ix );
assert( ls->wrk_u != NULL ); free( ls->wrk_u );
assert( ls->wrk_v != NULL ); free( ls->wrk_v );
assert( ls->wrk_w != NULL ); free( ls->wrk_w );
// Deallocate the BCLS problem.
free( ls );
return 0;
}
/*!
\brief Install a print-hook routine.
This routine installs a user-defined print-hook routine.
The parameter info is a transit pointer passed to the hook routine.
The parameter hook is an entry point to the user-defined print-hook
routine. This routine is called by the routine "print" every time an
informative message should be output. The routine "print" passes to
the hook routine the transit pointer info and the character string
msg, which contains the message. If the hook routine returns zero,
the routine print prints the message in an usual way. Otherwise, if
the hook routine returns non-zero, the message is not printed.
In order to uninstall the hook routine the parameter hook should be
specified as NULL (in this case the parameter info is ignored).
\param[in,out] ls BCLS problem context.
\param[in] info Transit pointer passed to the hook routine.
\param[in] hook Pointer to the print-hook routine.
*/
void
bcls_set_print_hook( BCLS *ls,
void *info,
int (*hook)(void *info, char *msg))
{
ls->print_info = info;
ls->print_hook = hook;
return;
}
/*!
\brief Install a fault-hook routine.
This routine installs a user-defined fault-hook routine.
The parameter info is a transit pointer passed to the hook routine.
The parameter "hook" is an entry point to the user-defined
fault-hook routine. This routine is called by the routine
"bcls_fault" every time an error message should be output. The
routine "bcls_fault" passes to the hook routine the transit pointer
info and the character string msg, which contains the message. If
the hook routine returns zero, the routine print prints the message
in an usual way. Otherwise, if the hook routine returns non-zero,
the message is not printed.
In order to uninstall the hook routine the parameter hook should be
specified as NULL (in this case the parameter info is ignored).
\param[in,out] ls BCLS problem context.
\param[in] info Transit pointer passed to the hook routine.
\param[in] hook Pointer to the fault-hook routine.
*/
void
bcls_set_fault_hook( BCLS *ls,
void *info,
int (*hook)(void *info, char *msg))
{
ls->fault_info = info;
ls->fault_hook = hook;
return;
}
/*!
\brief Give BCLS access to set of column weights.
Define a set of column weights. BCLS will use these to scale the
steepest-descent steps.
\param[in,out] ls BCLS problem context.
\param[in] anorm Array of columns norms of A.
*/
void
bcls_set_anorm( BCLS *ls,
double anorm[] )
{
ls->anorm = anorm;
return;
}
/*!
\brief Install a user-defined preconditioning routine.
Replace each subproblem
\f[
\def\minimize{\displaystyle\mathop{\hbox{minimize}}}
\minimize_x \| Ax - b \|
\f]
with
\f[
\def\minimize{\displaystyle\mathop{\hbox{minimize}}}
\minimize_y \| AU^{-1}y - b \|
\quad\mbox{with}\quad
Ux = y.
\f]
\param[in,out] ls BCLS problem context.
\param[in] Usolve Pointer to the user's preconditioning routine.
*/
void
bcls_set_usolve( BCLS *ls,
int (*Usolve)( int mode, int m, int n, int nix,
int ix[], double v[], double w[],
void *UsrWrk ) )
{
assert( Usolve != NULL );
ls->Usolve = Usolve;
return;
}
/*!
\brief Compute the column norms of A.
Compute the columns norms of A. Each column of A is generated by
multiplying A by a unit vector. The two-norm squared of each
column is stored in aprod.
This routine must be called *after* bcls_create_prob. (As with any
other BCLS routine.)
\param[in] ls BCLS problem context.
\param[in] m Number of rows in A.
\param[in] n Number of columns in A.
\param[in] Aprod User's matrix-product routine.
\param[in,out] UsrWrk Pointer to user's workspace (could be NULL).
\param[out] anorm Vector of column norms of A.
\return Returns any error codes returned by the user's aprod
routine.
*/
int
bcls_compute_anorm( BCLS *ls, int n, int m,
int (*Aprod)
( int mode, int m, int n, int nix,
int ix[], double x[], double y[], void *UsrWrk ),
void *UsrWrk,
double anorm[] )
{
// Make sure that the problem instance has been created.
assert( ls != NULL );
assert( anorm != NULL );
int j;
int err;
const int mode = 1; // Always: aj = A*ej.
const int nix = 1; // Only one column is ever needed.
int *ix = ls->ix;
double *e = ls->wrk_u;
double *aj = ls->wrk_v;
bcls_dload( n, 1.0, e, 1 );
for (j = 0; j < n; j++) {
// Multiply A times the jth unit vector.
ix[0] = j;
// aj <- A * ej.
err = Aprod( mode, m, n, nix, ix, e, aj, UsrWrk );
// Exit if Aprod returned an error.
if (err) break;
// Compute the norm of aj and store it in anorm.
anorm[j] = cblas_dnrm2( m, aj, 1 );
// Make sure that the column norm is too small.
anorm[j] = fmax( BCLS_MIN_COLUMN_NORM, anorm[j] );
}
return err;
}
/*!
\brief Load the problem into the BCLS data structure.
The routiens loads the complete problem description into a BCLS
problem instance. No work is really being done: only the various
structure elements are being set to point to the right places.
\param[in,out] ls BCLS problem context.
\param[in] m Number of rows in A. Note: m <= mmax.
\param[in] n Number of columns in A. Note: n <= nmax.
\param[in] Aprod Hook to user's matrix-vector product routine.
\param[in,out] UsrWrk Transit pointer passed directly to Aprod/Usolve.
\param[in] damp Regularization parameter.
\param[in,out] x The starting point.
\param[in] b The RHS vector.
\param[in] c Defines a linear term (set to NULL if one doesn't exist).
\param[in] bl Lower bounds on x.
\param[in] bu Upper bounds on x.
*/
void
bcls_set_problem_data( BCLS *ls, int m, int n,
int (*Aprod)( int mode, int m, int n, int nix,
int ix[], double x[], double y[],
void *UsrWrk ),
void *UsrWrk, double damp,
double x[], double b[], double c[],
double bl[], double bu[] )
{
assert( m <= ls->mmax );
assert( n <= ls->nmax );
assert( Aprod != NULL ); ls->Aprod = Aprod;
assert( m >= 0 ); ls->m = m;
assert( n >= 0 ); ls->n = n;
ls->UsrWrk = UsrWrk;
assert( damp >= 0.0 ); ls->damp = damp;
assert( x != NULL ); ls->x = x;
assert( b != NULL ); ls->b = b;
ls->c = c;
assert( bl != NULL ); ls->bl = bl;
assert( bu != NULL ); ls->bu = bu;
return;
}
/*!
\brief Return an exit message.
\param[in] flag The code of the error.
\return Error messsage.
*/
char *
bcls_exit_msg( int flag )
{
char *msg;
if (flag==BCLS_EXIT_CNVGD) msg="Optimal solution found";
else if (flag==BCLS_EXIT_MAJOR) msg="Too many major iterations";
else if (flag==BCLS_EXIT_MINOR) msg="Too many minor iterations";
else if (flag==BCLS_EXIT_UNBND) msg="Found direction of infinite descent";
else if (flag==BCLS_EXIT_INFEA) msg="Bounds are inconsistent";
else if (flag==BCLS_EXIT_APROD) msg="Aprod requested immediate exit";
else if (flag==BCLS_EXIT_USOLVE) msg="Usolve requested immediate exit";
else if (flag==BCLS_EXIT_CALLBK) msg="CallBack requested immediate exit";
else msg="Undefined exit";
return msg;
}
/*!
\brief Solve the current problem instance.
\return
- #BCLS_EXIT_CNVGD (0) - Successful exit. Found an optimal solution.
- #BCLS_EXIT_MAJOR - Too many major iterations.
- #BCLS_EXIT_MINOR - Too many inner iterations.
- #BCLS_EXIT_UNBND - Found direction of infinite descent.
- #BCLS_EXIT_INFEA - Bounds are inconsistent.
- #BCLS_EXIT_APROD - Aprod requested immediate exit.
- #BCLS_EXIT_USOLVE - Usolve requested immediate exit.
*/
int
bcls_solve_prob( BCLS *ls )
{
int err;
int jpInf;
const int preconditioning = ls->Usolve != NULL;
double pInf, timeTot;
double bNorm; // Norm of the RHS (or 1.0, which ever is bigger).
BCLS_timer watch;
// Print the banner.
//PRINT1(" ----------------------------------------------------\n");
//PRINT1(" BCLS -- Bound-Constrained Least Squares, Version %s\n",
// bcls_version_info() );
//PRINT1(" Compiled on %s\n", bcls_compilation_info() );
//PRINT1(" ----------------------------------------------------\n");
// -----------------------------------------------------------------
// Print parameters and diagnostic information.
// -----------------------------------------------------------------
bcls_print_params( ls );
// Examine the bounds and print a summary about them.
// Also check if the problem is feasible!
err = bcls_examine_bnds( ls, ls->n, ls->bl, ls->bu );
if (err) {
ls->exit = err;
goto direct_exit;
}
// Set the return for longjmp. First call to setjmp returns 0.
err = setjmp(ls->jmp_env);
if (err) {
ls->exit = err;
goto direct_exit;
}
// Compute and print some statistics about the column scales.
bcls_examine_column_scales( ls, ls->anorm );
// Print a log header.
// PRINT1("\n %5s %5s %9s %9s %11s %9s %7s %7s %7s\n",
// "Major","Minor","Residual","xNorm","Optimal",
// ls->newton_step == BCLS_NEWTON_STEP_LSQR
// ? "LSQR" : "CGLS",
// "nSteps", "Free", "OptFac");
// -----------------------------------------------------------------
// Call the BCLS solver.
// -----------------------------------------------------------------
bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_START );
bcls_solver( ls, ls->m, ls->n, &bNorm,
ls->x, ls->b, ls->c, ls->bl, ls->bu, ls->r, ls->g,
ls->dx, ls->dxFree, ls->ix,
ls->aBreak, ls->iBreak, ls->anorm );
bcls_timer( &(ls->stopwatch[BCLS_TIMER_TOTAL]), BCLS_TIMER_STOP );
// =================================================================
// Exits.
// =================================================================
direct_exit:
// -----------------------------------------------------------------
// Check feasibility and print a solution summary (iterations, etc.)
// -----------------------------------------------------------------
bcls_primal_inf( ls->n, ls->x, ls->bl, ls->bu, &pInf, &jpInf );
//PRINT1("\n");
// PRINT1(" BCLS Exit %4d -- %s\n",ls->exit, bcls_exit_msg(ls->exit));
//PRINT1("\n");
//PRINT1(" No. of iterations %8d %7s", ls->itnMin, "");
//PRINT1(" Objective value %17.9e\n", ls->soln_obj );
//PRINT1(" No. of major iterations%8d %7s", ls->itnMaj, "");
//PRINT1(" Optimality (%7d) %8.1e\n",
// ls->soln_jInf,ls->soln_dInf);
//PRINT1(" No. of calls to Aprod %8d", ls->nAprodT);
//if (ls->proj_search == BCLS_PROJ_SEARCH_EXACT)
// PRINT1(" (%5d)", ls->nAprod1 );
//else
// PRINT1(" %5s ", "");
// PRINT1(" Norm of RHS %16.1e\n", bNorm);
// if (pInf > ls->eps)
// PRINT1(" Feasibility (%7d) %7.1e\n", jpInf, pInf);
//if (preconditioning)
// PRINT1(" No. of calls to Usolve %8d\n", ls->nUsolve);
//PRINT1("\n");
// -----------------------------------------------------------------
// Print timing statistics.
// -----------------------------------------------------------------
//timeTot = fmax(ls->eps,ls->stopwatch[BCLS_TIMER_TOTAL].total);
//watch = ls->stopwatch[BCLS_TIMER_TOTAL];
//timeTot = fmax(1e-6, watch.total); // Safeguard against timeTot = 0.
//PRINT1(" %-25s %5.1f (%4.2f) secs\n",
// watch.name, watch.total, 1.0 );
//watch = ls->stopwatch[BCLS_TIMER_LSQR];
//PRINT1(" %-25s %5.1f (%4.2f) secs\n",
// watch.name, watch.total, watch.total / timeTot );
// watch = ls->stopwatch[BCLS_TIMER_APROD];
//PRINT1(" %-25s %5.1f (%4.2f) secs\n",
// watch.name, watch.total, watch.total / timeTot );
// Only print time for Usolve is user provided this routine.
//if (preconditioning) {
// watch = ls->stopwatch[BCLS_TIMER_USOLVE];
//PRINT1(" %-25s %5.1f (%4.2f) secs\n",
// watch.name, watch.total, watch.total / timeTot );
//}
return (ls->exit + err);
}
| {
"alphanum_fraction": 0.564171,
"avg_line_length": 31.9104258443,
"ext": "c",
"hexsha": "6c5670b51069f1e2f0f17e9110bf58bf0f353ac1",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z",
"max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "echristakopoulou/glslim",
"max_forks_repo_path": "bcls-0.1/src/bcls.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "echristakopoulou/glslim",
"max_issues_repo_path": "bcls-0.1/src/bcls.c",
"max_line_length": 83,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "echristakopoulou/glslim",
"max_stars_repo_path": "bcls-0.1/src/bcls.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z",
"num_tokens": 6134,
"size": 21731
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "activation_info.h"
#include "attention_wrapper.h"
#include "core/providers/cpu/rnn/rnn_helpers.h"
#include "core/common/common.h"
#include "core/common/logging/logging.h"
#include "core/framework/allocator.h"
#include <gsl/span>
namespace onnxruntime {
namespace contrib {
namespace deepcpu = ::onnxruntime::rnn::detail::deepcpu;
namespace logging = ::onnxruntime::logging;
using ::onnxruntime::AllocatorPtr;
using ::onnxruntime::IAllocatorUniquePtr;
using ::onnxruntime::contrib::detail::ActivationInfo;
using ::onnxruntime::rnn::detail::ActivationFuncs;
using ::onnxruntime::rnn::detail::Direction;
namespace rnn {
namespace detail {
// copying the peephole values into UniDirectionalAttnLstm seems unnecessary. don't do that until proven necessary
#define LSTM_NO_PEEPHOLE_COPY
template <typename T>
class UniDirectionalAttnLstm {
public:
UniDirectionalAttnLstm(AllocatorPtr allocator,
const logging::Logger& logger,
const int seq_length,
const int batch_size,
const int input_size,
const int hidden_size,
Direction direction,
const bool input_forget,
AttentionWrapper<T>& attention_wrapper,
const gsl::span<const T>& bias,
const gsl::span<const T>& peephole_weights,
const gsl::span<const T>& initial_hidden_state,
const gsl::span<const T>& initial_cell_state,
const ActivationFuncs::Entry& activation_func_f,
const ActivationFuncs::Entry& activation_func_g,
const ActivationFuncs::Entry& activation_func_h,
const float clip,
onnxruntime::concurrency::ThreadPool* ttp);
void Compute(const gsl::span<const T>& inputs,
const gsl::span<const int>& sequence_lengths,
const int num_directions,
const gsl::span<const T>& input_weights,
const gsl::span<const T>& recurrent_weights,
gsl::span<T>& outputs,
gsl::span<T>& final_hidden_state,
gsl::span<T>& final_cell_state);
~UniDirectionalAttnLstm() = default;
AttentionWrapper<T>& GetAttentionWrapper() {
return attention_wrapper_;
}
private:
using span_T_const_iter = typename gsl::span<T>::const_iterator;
using span_T_iter = typename gsl::span<T>::iterator;
void SetNumThreads();
void GateComputations(span_T_iter& out, span_T_iter& out_end,
span_T_iter& C_prev, span_T_iter& C_prev_end, // Ct-1 value not 'ct'. using 'C' for clarity
span_T_iter& C_prev_clipped, span_T_iter& C_prev_clipped_end,
span_T_iter& batched_output, span_T_iter& batched_output_end,
const gsl::span<const int>& seq_lengths,
const int min_sequence_length,
const int step,
const int row,
const int local_fused_hidden_rows,
bool output_sequence);
void AllocateBuffers();
void InitializeBuffers(const gsl::span<const T>& initial_hidden_state,
const gsl::span<const T>& initial_cell_state);
void LoadPeepholeWeights(const gsl::span<const T>& peephole_weights);
void LoadBias(const gsl::span<const T>& WbRb_values);
AllocatorPtr allocator_;
const logging::Logger& logger_;
int seq_length_;
int batch_size_;
int input_size_;
int hidden_size_;
int attention_size_;
int attention_context_size_;
Direction direction_;
bool input_forget_;
float clip_;
bool batch_parallel_;
bool use_bias_;
bool use_peepholes_;
int hidden_num_threads_ = -1;
IAllocatorUniquePtr<T> output_iofc_ptr_;
IAllocatorUniquePtr<T> hidden0_ptr_, batched_hidden0_ptr_;
gsl::span<T> output_iofc_;
gsl::span<T> hidden0_, batched_hidden0_;
IAllocatorUniquePtr<T> internal_memory_prev_ptr_, batched_internal_memory_prev_ptr_;
IAllocatorUniquePtr<T> internal_memory_cur_ptr_, batched_internal_memory_cur_ptr_;
IAllocatorUniquePtr<T> batched_internal_memory_clipped_ptr_;
gsl::span<T> internal_memory_prev_, batched_internal_memory_prev_;
gsl::span<T> internal_memory_cur_, batched_internal_memory_cur_;
gsl::span<T> batched_internal_memory_clipped_;
IAllocatorUniquePtr<T> bias_WRi_ptr_, bias_WRf_ptr_, bias_WRo_ptr_, bias_WRc_ptr_;
IAllocatorUniquePtr<T> batched_bias_WRi_ptr_, batched_bias_WRf_ptr_, batched_bias_WRo_ptr_, batched_bias_WRc_ptr_;
IAllocatorUniquePtr<T> peephole_i_ptr_, peephole_f_ptr_, peephole_o_ptr_;
IAllocatorUniquePtr<T> inputs_reverse_ptr_, outputs_reverse_ptr_;
gsl::span<T> bias_WRi_, bias_WRf_, bias_WRo_, bias_WRc_;
gsl::span<T> batched_bias_WRi_, batched_bias_WRf_, batched_bias_WRo_, *batched_bias_WRc_;
gsl::span<T> inputs_reverse_, outputs_reverse_;
#if defined(LSTM_NO_PEEPHOLE_COPY)
gsl::span<const T> peephole_i_, peephole_f_, peephole_o_;
#else
gsl::span<T> peephole_i_, peephole_f_, peephole_o_;
#endif
IAllocatorUniquePtr<int> sequence_lengths_ptr_;
gsl::span<int> sequence_lengths_;
deepcpu::ClipWithBiasFuncPtr clip_with_bias_ptr_;
ActivationInfo<deepcpu::ActivationFuncPtr> activation_f_;
ActivationInfo<deepcpu::ActivationFuncPtr> activation_g_;
ActivationInfo<deepcpu::LstmMergeGatesFuncPtr> activation_h_;
AttentionWrapper<T>& attention_wrapper_;
onnxruntime::concurrency::ThreadPool* ttp_;
};
} // namespace detail
} // namespace rnn
} // namespace contrib
} // namespace onnxruntime
| {
"alphanum_fraction": 0.6900614754,
"avg_line_length": 36.3726708075,
"ext": "h",
"hexsha": "2d3a6f20fe1e90d75afeb6890eb52f8c7f877e8f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-11-30T13:58:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-05T19:52:22.000Z",
"max_forks_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hqucms/onnxruntime",
"max_forks_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/uni_dir_attn_lstm.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0",
"max_issues_repo_issues_event_max_datetime": "2019-12-24T00:27:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-24T00:27:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "hqucms/onnxruntime",
"max_issues_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/uni_dir_attn_lstm.h",
"max_line_length": 116,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "6e4e76414639f50836a64546603c8957227857b0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hqucms/onnxruntime",
"max_stars_repo_path": "onnxruntime/contrib_ops/cpu/attnlstm/uni_dir_attn_lstm.h",
"max_stars_repo_stars_event_max_datetime": "2019-12-04T12:49:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-18T14:04:42.000Z",
"num_tokens": 1329,
"size": 5856
} |
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl/gsl_vector.h>
#include <argtable2.h>
#include "qdm.h"
void
qdm_ispline_vector(
gsl_vector *result,
const double tau,
const size_t spline_df,
const gsl_vector *knots
)
{
size_t bin = qdm_vector_search(knots, tau);
gsl_vector_set(result, 0, 1);
for (size_t m = 0; m < result->size - 1; m++) {
double v;
if (bin < m) {
v = 0;
} else if (bin - spline_df + 1 > m) {
v = 1;
} else if (bin == m) {
double n = gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 3);
double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);
double d3 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m);
v = n / (d1 * d2 * d3);
} else if (bin == m + 1) {
double i1n = 3 * tau;
double i1d = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i1 = i1n / i1d;
double i2n = -gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 3);
double i2d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double i2d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);
double i2d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i2 = i2n / (i2d1 * i2d2 * i2d3);
double i3n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 3);
double i3d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);
double i3d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double i3d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i3 = i3n / (i3d1 * i3d2 * i3d3);
double i4an = -3 * gsl_vector_get(knots, m + 1);
double i4ad = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i4a = i4an / i4ad;
double i4bn = gsl_sf_pow_int(gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m), 3);
double i4bd1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double i4bd2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);
double i4bd3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i4b = i4bn / (i4bd1 * i4bd2 * i4bd3);
double i4cn = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1), 3);
double i4cd1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);
double i4cd2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double i4cd3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);
double i4c = i4cn / (i4cd1 * i4cd2 * i4cd3);
double i4 = i4a + i4b - i4c;
double i5 = 0;
if (m != 1) {
double i5n = gsl_sf_pow_int(gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m), 3);
double i5d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double i5d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);
double i5d3 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m);
i5 = i5n / (i5d1 * i5d2 * i5d3);
}
v = i1 + i2 + i3 + i4 + i5;
} else {
double n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 3);
double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);
double d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);
double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 2);
double d = d1 * d2 * d3;
v = 1 - n / d;
}
gsl_vector_set(result, m + 1, v);
}
}
void
qdm_ispline_matrix(
gsl_matrix *result,
const gsl_vector *taus,
const size_t spline_df,
const gsl_vector *knots
)
{
for (size_t i = 0; i < result->size1; i++) {
gsl_vector_view row = gsl_matrix_row(result, i);
qdm_ispline_vector(&row.vector, gsl_vector_get(taus, i), spline_df, knots);
}
}
| {
"alphanum_fraction": 0.6126194067,
"avg_line_length": 36.8333333333,
"ext": "c",
"hexsha": "795763e981977d894566799168dd0709f537e81f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/ispline.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/ispline.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/ispline.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1509,
"size": 3978
} |
#ifndef __RNG_H__
#define __RNG_H__
#include <gsl/gsl_rng.h>
#include <ctime>
#include<iostream>
#include <cstring>
#include <fstream>
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define min(a,b) ((a) <= (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))
#define OVERFLO 1e100
#define UNDERFLO 1e-100
namespace weakarg
{
extern gsl_rng * rng;
unsigned long makerng(bool fast=false);
unsigned long seedrng(unsigned long seed=0);
int saverng(std::string fname);
int loadrng(std::string fname);
double RandomReal(double low, double high);
int RandomInteger(int low, int high);
double rnd();
double RGamma(double n,double lambda);
void RDirichlet(const double * a, const int k, double * b);
long RPoisson(double mu);
double RExpon(double av);
double RNormal(double mu,double sd) ;
double fsign( double num, double sign );
double sexpo(void);
double snorm();
double genexp(double av);
long ignpoi(double mean);
long ignuin(int low, int high);
double genunf(double low, double high);
long Binomial(int n, double p);
long Binomial1(int n, double p);
double BinoProb(int n, double p,int i);
void LogRDirichlet (const double *a, const int k, double *b,double *c);
} // end namespace weakarg
#endif // __RNG_H__
| {
"alphanum_fraction": 0.6924939467,
"avg_line_length": 24.2941176471,
"ext": "h",
"hexsha": "4c5ad57d9ad33008719685555fab56d4337b0ebf",
"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": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "fmedina7/ClonOr_cpp",
"max_forks_repo_path": "ClonOr_cpp/rng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"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": "fmedina7/ClonOr_cpp",
"max_issues_repo_path": "ClonOr_cpp/rng.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d1c2e0e0f7d2315bad99de80a15458cb4015ae1e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "fmedina7/ClonOr_cpp",
"max_stars_repo_path": "ClonOr_cpp/rng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 354,
"size": 1239
} |
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c :
* Example of SPH Density Calculation using a
* naive implementation of the main density loop,
* no neighbours earch, and Array of Structs (AoS)
* data layout, OpenMP parallelization and SIMD
* directives on the kernel and density calculation.
* This incorporates strip mining and exchange to
* implement cache blocking and support performance
* for large number of particles that would otherwise
* be lost.
*
* (C) Copyright 2021 JosΓ© Hugo Elsas
* Author: JosΓ© Hugo Elsas <jhelsas@gmail.com>
*
* Command Line Options:
* -runs <int> : Set the number of repetitions (runs) for
* calculating the density. The value of
* the density is based on the last
* iteration.
* Default value: 1
* -run_seed <int>: Flag to set an alternative seed use for
* for the PRNG. Instead of feeding seed
* to the PRNG directly, it feeds
* seed + iteration, as to generate different
* configurations for each iteration.
* Default value: 0 - (possible 0/1)
* -seed <int>: Set the seed to use for the SPH particles
* uniform position generation in the box
* Default value: 123123123
*
* -N <int>: Set the number of SPH particles to be used
* Default value: 1e5 = 100,000
* -h <float>: Set the value of the smoothing kernel
* parameter h, which corresponds to half
* of the support of the kernel.
* Default value: 0.05
*
* -Nx <int>: Set the number of Cells in the X direction
* Default value: 10
* -Ny <int>: Set the number of Cells in the Y direction
* Default value: 10
* -Nz <int>: Set the number of Cells in the Z direction
* Default value: 10
*
* -Xmin <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 0.0
*
* -Xmax <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 1.0
* -Ymax <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 1.0
* -Zmax <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 1.0
*/
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_utils.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define COMPUTE_BLOCKS 1
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
linkedListBox *box, SPHparticle *lsph, double *times);
int compute_density_3d_naive_omp_simd_tiled(int N,double h,SPHparticle *lsph);
double w_bspline_3d_constant(double h);
#pragma omp declare simd
double w_bspline_3d_simd(double q);
int main(int argc, char **argv){
bool run_seed = false; // By default the behavior is is to use the same seed
int err, runs = 1; // By default the main loop only runs once
long int seed = 123123123; // The default seed is 123123123
int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000
double h=0.05; // The default kernel smoothing length is h = 0.05
linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method
SPHparticle *lsph; // Uninitialized array of SPH particles
box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain
// allow for command line customization of the run
arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options
// line arguments and override default values
lsph = (SPHparticle*)malloc(N*sizeof(SPHparticle)); // Create an array of N particles
double times[runs*COMPUTE_BLOCKS];
for(int run=0;run<runs;run+=1)
main_loop(run,run_seed,N,h,seed,box,lsph,times);
bool is_cll = false;
const char *prefix = "ex04,naive,AoS,omp,simd,tiled";
print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times);
print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box);
free(lsph);
safe_free_box(box);
return 0;
}
/*
* Function main_loop:
* Runs the main loop of the program, including the particle array generation,
* density calculation and the timings annotations.
*
* Arguments:
* run <int> : index (or value) or the present iteration
* run_seed <bool> : boolean defining whether to use run index for seed or not
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* seed <long int> : seed for GSL PRNG generator to generate particle positions
* box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* times <double> : Array to store the computation timings to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
* times <double> : Times is updated by reference
*/
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
linkedListBox *box, SPHparticle *lsph, double *times)
{
int err;
if(run_seed)
err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);
else
err = gen_unif_rdn_pos_box(N,seed,box,lsph);
if(err)
fprintf(stderr,"error in gen_unif_rdn_pos\n");
// ------------------------------------------------------ //
double t0,t1;
t0 = omp_get_wtime();
compute_density_3d_naive_omp_simd_tiled(N,h,lsph); // Compute the density for all particles
t1 = omp_get_wtime();
// ------------------------------------------------------ //
times[COMPUTE_BLOCKS*run+0] = t1-t0; // Only one component to measure time
return 0;
}
/*
* Function compute_density_3d_naive_omp_simd_tiled:
* Computes the SPH density from the particles implementing a strip mine and exchange
* strategy to re-use data in cache over the direct loop. It executes calculations
* in parallel for the outer-most loop using openMP and SIMD in inner-most loop,
* though SIMD only for limited success.
*
* Reference: https://en.wikipedia.org/wiki/Loop_nest_optimization
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
*/
int compute_density_3d_naive_omp_simd_tiled(int N,double h,SPHparticle *lsph){
const double inv_h = 1./h; // Pre-invert the smoothing distance
const double kernel_constant = w_bspline_3d_constant(h); // Pre-compute the 3d normalization constant
const int64_t STRIP = 500; // Setting the size of the strip or block
#pragma omp parallel for // Run the iteration in Parallel
for(int64_t ii=0;ii<N;ii+=1) // Iterate
lsph[ii].rho = 0.; // Pre-initialize the density to zero
#pragma omp parallel for // Run the iteration in i in parallel
for(int64_t i=0;i<N;i+=STRIP){ // Breaking up the i and j iterations in blocks
for(int64_t j=0;j<N;j+=STRIP){ // of size STRIP to do data re-use and cache blocking
for(int64_t ii=i;ii < ((i+STRIP<N)?(i+STRIP):N); ii+=1){ // Iterate a block over ii
double xii = lsph[ii].r.x; // Load the position in X for ii
double yii = lsph[ii].r.y; // Load the position in Y for ii
double zii = lsph[ii].r.z; // Load the position in Z for ii
double rhoii = 0.0; // Initialize partial density ii density to zero
#pragma omp simd // Hint at the compiler to vectorize this loop
for(int64_t jj=j;jj < ((j+STRIP<N)?(j+STRIP):N); jj+=1 ){ // and iterate over the jj part of the block
double q = 0.; // initialize the distance variable
double xij = xii-lsph[jj].r.x; // Load and subtract jj particle's X position component
double yij = yii-lsph[jj].r.y; // Load and subtract jj particle's Y position component
double zij = zii-lsph[jj].r.z; // Load and subtract jj particle's Z position component
q += xij*xij; // Add the jj contribution to the ii distance in X
q += yij*yij; // Add the jj contribution to the ii distance in Y
q += zij*zij; // Add the jj contribution to the ii distance in Z
q = sqrt(q)*inv_h; // Sqrt and normalizing the distance by the smoothing lengh
rhoii += lsph[jj].nu*w_bspline_3d_simd(q); // Add up the contribution from the jj particle
} // to the intermediary density and then
lsph[ii].rho += kernel_constant*rhoii; // add the intermediary density to the full density
}
}
}
return 0;
}
/*
* Function w_bspline_3d_constant:
* Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel
*
* Arguments:
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* Returns:
* 3d bspline normalization density <double>
*/
double w_bspline_3d_constant(double h){
return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel
}
/*
* Function w_bspline_3d_simd:
* Returns the un-normalized value of the cubic b-spline SPH smoothing kernel
*
* Arguments:
* q <double> : Distance between particles normalized by the smoothing length h
* Returns:
* wq <double> : Unnormalized value of the kernel
*
* Observation:
* Why not else if(q<2.)?
* Because if you use "else if", the compiler refuses to vectorize,
* This results in a large slowdown, as of 2.5x slower for example_04
*/
#pragma omp declare simd
double w_bspline_3d_simd(double q){ // Use as input the normalized distance
double wq = 0.0;
double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline
double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline
if(q<2.) // If the distance is below 2
wq = wq2; // Use the 2nd polynomial for the spline
if(q<1.) // If the distance is below 1
wq = wq1; // Use the 1nd polynomial for the spline
return wq; // return which ever value corresponds to the distance
} | {
"alphanum_fraction": 0.5627344408,
"avg_line_length": 45.6748251748,
"ext": "c",
"hexsha": "d3d0ab813325548102a67f495216220069ea5d40",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jhelsas/sphalerite",
"max_forks_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "jhelsas/sphalerite",
"max_issues_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jhelsas/sphalerite",
"max_stars_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3142,
"size": 13063
} |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2000 Brian Gerkey & Kasper Stoy
* gerkey@usc.edu kaspers@robotics.usc.edu
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/**************************************************************************
* Desc: Vector functions
* Author: Andrew Howard
* Date: 10 Dec 2002
* CVS: $Id: pf_vector.c 6345 2008-04-17 01:36:39Z gerkey $
*************************************************************************/
#include <math.h>
//#include <gsl/gsl_matrix.h>
//#include <gsl/gsl_eigen.h>
//#include <gsl/gsl_linalg.h>
#include "amcl/pf/pf_vector.h"
#include "amcl/pf/eig3.h"
// Return a zero vector
pf_vector_t pf_vector_zero()
{
pf_vector_t c;
c.v[0] = 0.0;
c.v[1] = 0.0;
c.v[2] = 0.0;
return c;
}
// Check for NAN or INF in any component
int pf_vector_finite(pf_vector_t a)
{
int i;
for (i = 0; i < 3; i++)
if (!isfinite(a.v[i]))
return 0;
return 1;
}
// Print a vector
void pf_vector_fprintf(pf_vector_t a, FILE *file, const char *fmt)
{
int i;
for (i = 0; i < 3; i++)
{
fprintf(file, fmt, a.v[i]);
fprintf(file, " ");
}
fprintf(file, "\n");
return;
}
// Simple vector addition
pf_vector_t pf_vector_add(pf_vector_t a, pf_vector_t b)
{
pf_vector_t c;
c.v[0] = a.v[0] + b.v[0];
c.v[1] = a.v[1] + b.v[1];
c.v[2] = a.v[2] + b.v[2];
return c;
}
// Simple vector subtraction
pf_vector_t pf_vector_sub(pf_vector_t a, pf_vector_t b)
{
pf_vector_t c;
c.v[0] = a.v[0] - b.v[0];
c.v[1] = a.v[1] - b.v[1];
c.v[2] = a.v[2] - b.v[2];
return c;
}
// Transform from local to global coords (a + b)
pf_vector_t pf_vector_coord_add(pf_vector_t a, pf_vector_t b)
{
pf_vector_t c;
c.v[0] = b.v[0] + a.v[0] * cos(b.v[2]) - a.v[1] * sin(b.v[2]);
c.v[1] = b.v[1] + a.v[0] * sin(b.v[2]) + a.v[1] * cos(b.v[2]);
c.v[2] = b.v[2] + a.v[2];
c.v[2] = atan2(sin(c.v[2]), cos(c.v[2]));
return c;
}
// Transform from global to local coords (a - b)
pf_vector_t pf_vector_coord_sub(pf_vector_t a, pf_vector_t b)
{
pf_vector_t c;
c.v[0] = +(a.v[0] - b.v[0]) * cos(b.v[2]) + (a.v[1] - b.v[1]) * sin(b.v[2]);
c.v[1] = -(a.v[0] - b.v[0]) * sin(b.v[2]) + (a.v[1] - b.v[1]) * cos(b.v[2]);
c.v[2] = a.v[2] - b.v[2];
c.v[2] = atan2(sin(c.v[2]), cos(c.v[2]));
return c;
}
// Return a zero matrix
pf_matrix_t pf_matrix_zero()
{
int i, j;
pf_matrix_t c;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
c.m[i][j] = 0.0;
return c;
}
// Check for NAN or INF in any component
int pf_matrix_finite(pf_matrix_t a)
{
int i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (!isfinite(a.m[i][j]))
return 0;
return 1;
}
// Print a matrix
void pf_matrix_fprintf(pf_matrix_t a, FILE *file, const char *fmt)
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
fprintf(file, fmt, a.m[i][j]);
fprintf(file, " ");
}
fprintf(file, "\n");
}
return;
}
/*
// Compute the matrix inverse
pf_matrix_t pf_matrix_inverse(pf_matrix_t a, double *det)
{
double lndet;
int signum;
gsl_permutation *p;
gsl_matrix_view A, Ai;
pf_matrix_t ai;
A = gsl_matrix_view_array((double*) a.m, 3, 3);
Ai = gsl_matrix_view_array((double*) ai.m, 3, 3);
// Do LU decomposition
p = gsl_permutation_alloc(3);
gsl_linalg_LU_decomp(&A.matrix, p, &signum);
// Check for underflow
lndet = gsl_linalg_LU_lndet(&A.matrix);
if (lndet < -1000)
{
//printf("underflow in matrix inverse lndet = %f", lndet);
gsl_matrix_set_zero(&Ai.matrix);
}
else
{
// Compute inverse
gsl_linalg_LU_invert(&A.matrix, p, &Ai.matrix);
}
gsl_permutation_free(p);
if (det)
*det = exp(lndet);
return ai;
}
*/
// Decompose a covariance matrix [a] into a rotation matrix [r] and a diagonal
// matrix [d] such that a = r d r^T.
void pf_matrix_unitary(pf_matrix_t *r, pf_matrix_t *d, pf_matrix_t a)
{
int i, j;
/*
gsl_matrix *aa;
gsl_vector *eval;
gsl_matrix *evec;
gsl_eigen_symmv_workspace *w;
aa = gsl_matrix_alloc(3, 3);
eval = gsl_vector_alloc(3);
evec = gsl_matrix_alloc(3, 3);
*/
double aa[3][3];
double eval[3];
double evec[3][3];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
//gsl_matrix_set(aa, i, j, a.m[i][j]);
aa[i][j] = a.m[i][j];
}
}
// Compute eigenvectors/values
/*
w = gsl_eigen_symmv_alloc(3);
gsl_eigen_symmv(aa, eval, evec, w);
gsl_eigen_symmv_free(w);
*/
eigen_decomposition(aa,evec,eval);
*d = pf_matrix_zero();
for (i = 0; i < 3; i++)
{
//d->m[i][i] = gsl_vector_get(eval, i);
d->m[i][i] = eval[i];
for (j = 0; j < 3; j++)
{
//r->m[i][j] = gsl_matrix_get(evec, i, j);
r->m[i][j] = evec[i][j];
}
}
//gsl_matrix_free(evec);
//gsl_vector_free(eval);
//gsl_matrix_free(aa);
return;
}
| {
"alphanum_fraction": 0.5712263316,
"avg_line_length": 20.4007220217,
"ext": "c",
"hexsha": "23d7ccb16c78d8d733a95e98132f5c8948f4ff20",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-05T15:04:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-24T17:19:13.000Z",
"max_forks_repo_head_hexsha": "3c5cb561d1aee11d80a7f3847e0334e93f345513",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Louis-AD-git/racecar_ws",
"max_forks_repo_path": "src/navigation-melodic-devel/amcl/src/amcl/pf/pf_vector.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3c5cb561d1aee11d80a7f3847e0334e93f345513",
"max_issues_repo_issues_event_max_datetime": "2020-11-12T09:53:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-12T09:53:16.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Louis-AD-git/racecar_ws",
"max_issues_repo_path": "src/navigation-melodic-devel/amcl/src/amcl/pf/pf_vector.c",
"max_line_length": 78,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "3c5cb561d1aee11d80a7f3847e0334e93f345513",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Louis-AD-git/racecar_ws",
"max_stars_repo_path": "src/navigation-melodic-devel/amcl/src/amcl/pf/pf_vector.c",
"max_stars_repo_stars_event_max_datetime": "2020-06-08T12:13:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-10T13:23:49.000Z",
"num_tokens": 1982,
"size": 5651
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_sf_zeta.h>
/* Calculate the Hurwitz zeta function by invoking the GNU scientific
library */
/* Only intended to be used with R; not the most elegant integration but it
may do for now */
/* Two arguments, the power used in the sum (s) and the baseline value (q) */
double s, q, zeta; /* arguments to zeta, value */
char *program_name; /* name program is invoked under, for errors */
int main(int argc, char* argv[]) {
void usage(void); /* Warn users about proper usage */
program_name = argv[0];
if (argc != 3) {
usage();
}
s = atof(&argv[1][0]);
if (s <= 1.0) {
usage();
}
q = atof(&argv[2][0]);
if (q <= 0.0) {
usage();
}
zeta = gsl_sf_hzeta(s,q);
printf("%.18e\n",zeta);
return(0);
}
void usage(void) {
(void) fprintf(stderr, "Usage is %s [floating-point exponent > 1] [floating-point additive constant > 0]\n", program_name);
exit(8);
}
| {
"alphanum_fraction": 0.6256572029,
"avg_line_length": 24.3846153846,
"ext": "c",
"hexsha": "0afe81f25966e9f2ece9cbd2a81df6d1cf4339e0",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T10:29:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-12T08:50:33.000Z",
"max_forks_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_forks_repo_licenses": [
"Unlicense",
"MIT"
],
"max_forks_repo_name": "jguerber/spatialwarnings",
"max_forks_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c",
"max_issues_count": 59,
"max_issues_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_issues_repo_issues_event_max_datetime": "2022-03-10T16:25:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-03-07T07:53:48.000Z",
"max_issues_repo_licenses": [
"Unlicense",
"MIT"
],
"max_issues_repo_name": "jguerber/spatialwarnings",
"max_issues_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c",
"max_line_length": 125,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709",
"max_stars_repo_licenses": [
"Unlicense",
"MIT"
],
"max_stars_repo_name": "jguerber/spatialwarnings",
"max_stars_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T11:21:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-06T14:32:17.000Z",
"num_tokens": 285,
"size": 951
} |
/*
* This file is part of MXE. See LICENSE.md for licensing information.
*/
/* taken from http://www.netlib.org/lapack/lapacke.html */
/* Calling CGEQRF and CUNGQR to compute Q with workspace querying */
#include <stdio.h>
#include <stdlib.h>
#include <lapacke_utils.h>
#include <cblas.h>
int main (int argc, const char * argv[])
{
(void)argc;
(void)argv;
lapack_complex_float *a,*tau,*r,*work,one,zero,query;
lapack_int info,m,n,lda,lwork;
int i,j;
float err;
m = 10; n = 5; lda = m;
one = lapack_make_complex_float(1.0,0.0);
zero= lapack_make_complex_float(0.0,0.0);
a = calloc(m*n,sizeof(lapack_complex_float));
r = calloc(n*n,sizeof(lapack_complex_float));
tau = calloc(m,sizeof(lapack_complex_float));
for(j=0;j<n;j++)
for(i=0;i<m;i++)
a[i+j*m] = lapack_make_complex_float(i+1,j+1);
info = LAPACKE_cgeqrf_work(LAPACK_COL_MAJOR,m,n,a,lda,tau,&query,-1);
lwork = (lapack_int)query;
info = LAPACKE_cungqr_work(LAPACK_COL_MAJOR,m,n,n,a,lda,tau,&query,-1);
lwork = MAX(lwork,(lapack_int)query);
work = calloc(lwork,sizeof(lapack_complex_float));
info = LAPACKE_cgeqrf_work(LAPACK_COL_MAJOR,m,n,a,lda,tau,work,lwork);
info = LAPACKE_cungqr_work(LAPACK_COL_MAJOR,m,n,n,a,lda,tau,work,lwork);
for(j=0;j<n;j++)
for(i=0;i<n;i++)
r[i+j*n]=(i==j)?-one:zero;
cblas_cgemm(CblasColMajor,CblasConjTrans,CblasNoTrans,
n,n,m,&one,a,lda,a,lda,&one,r,n);
err=0.0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
err=MAX(err,cabs(r[i+j*n]));
printf("error=%e\n",err);
free(work);
free(tau);
free(r);
free(a);
return(info);
}
| {
"alphanum_fraction": 0.6393244873,
"avg_line_length": 30.1454545455,
"ext": "c",
"hexsha": "6a63796da590c9e1287179e8c7ca62e969b63bb7",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2019-02-07T22:09:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-20T14:50:27.000Z",
"max_forks_repo_head_hexsha": "b86556f5332ba9a608154fe541c87c40313a128f",
"max_forks_repo_licenses": [
"RSA-MD"
],
"max_forks_repo_name": "Lord-Kamina/mxe",
"max_forks_repo_path": "src/lapack-test.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "b86556f5332ba9a608154fe541c87c40313a128f",
"max_issues_repo_issues_event_max_datetime": "2020-09-29T21:10:11.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-25T20:57:03.000Z",
"max_issues_repo_licenses": [
"RSA-MD"
],
"max_issues_repo_name": "Lord-Kamina/mxe",
"max_issues_repo_path": "src/lapack-test.c",
"max_line_length": 75,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "b86556f5332ba9a608154fe541c87c40313a128f",
"max_stars_repo_licenses": [
"RSA-MD"
],
"max_stars_repo_name": "Lord-Kamina/mxe",
"max_stars_repo_path": "src/lapack-test.c",
"max_stars_repo_stars_event_max_datetime": "2020-06-17T17:52:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-06T00:12:49.000Z",
"num_tokens": 558,
"size": 1658
} |
/* avl.c
*
* Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This code is originally from GNU libavl, with some modifications */
#include <config.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_bst.h>
#include <gsl/gsl_errno.h>
typedef struct gsl_bst_avl_node avl_node;
typedef gsl_bst_avl_table avl_table;
typedef gsl_bst_avl_traverser avl_traverser;
#ifndef AVL_MAX_HEIGHT
#define AVL_MAX_HEIGHT GSL_BST_AVL_MAX_HEIGHT
#endif
/* Function types. */
typedef void avl_item_func (void *avl_item, void *avl_param);
typedef void *avl_copy_func (void *avl_item, void *avl_param);
/* tree functions */
static int avl_init(const gsl_bst_allocator * allocator,
gsl_bst_cmp_function * compare, void * params, void * vtable);
static size_t avl_nodes (const void * vtable);
static int avl_empty (void * vtable);
static void ** avl_probe (void * item, avl_table * table);
static void * avl_insert (void * item, void * vtable);
static void * avl_find (const void *item, const void * vtable);
static void * avl_remove (const void *item, void * vtable);
/* traverser functions */
static int avl_t_init (void * vtrav, const void * vtable);
static void * avl_t_first (void * vtrav, const void * vtable);
static void * avl_t_last (void * vtrav, const void * vtable);
static void * avl_t_find (const void * item, void * vtrav, const void * vtable);
static void * avl_t_insert (void * item, void * vtrav, void * vtable);
static void * avl_t_copy (void * vtrav, const void * vsrc);
static void * avl_t_next (void * vtrav);
static void * avl_t_prev (void * vtrav);
static void * avl_t_cur (const void * vtrav);
static void * avl_t_replace (void * vtrav, void * new_item);
static void avl_trav_refresh (avl_traverser * trav);
#if 0
static avl_table * avl_copy (const avl_table *, avl_copy_func *,
avl_item_func *);
static void *avl_replace (avl_table *, void *);
#endif
static int
avl_init(const gsl_bst_allocator * allocator,
gsl_bst_cmp_function * compare, void * params, void * vtable)
{
avl_table * table = (avl_table *) vtable;
table->avl_alloc = allocator;
table->avl_compare = compare;
table->avl_param = params;
table->avl_root = NULL;
table->avl_count = 0;
table->avl_generation = 0;
return GSL_SUCCESS;
}
static size_t
avl_nodes (const void * vtable)
{
const avl_table * table = (const avl_table *) vtable;
return table->avl_count;
}
/* empty tree (delete all nodes) but do not free the tree itself */
static int
avl_empty (void * vtable)
{
avl_table * table = (avl_table *) vtable;
avl_node *p, *q;
for (p = table->avl_root; p != NULL; p = q)
{
if (p->avl_link[0] == NULL)
{
q = p->avl_link[1];
table->avl_alloc->free (p, table->avl_param);
}
else
{
q = p->avl_link[0];
p->avl_link[0] = q->avl_link[1];
q->avl_link[1] = p;
}
}
table->avl_root = NULL;
table->avl_count = 0;
table->avl_generation = 0;
return GSL_SUCCESS;
}
/*
avl_probe()
Inserts |item| into |tree| and returns a pointer to |item|'s address.
If a duplicate item is found in the tree, returns a pointer to the existing
item without inserting |item|.
Returns |NULL| in case of memory allocation failure.
*/
static void **
avl_probe (void * item, avl_table * table)
{
avl_node *y, *z; /* top node to update balance factor, and parent */
avl_node *p, *q; /* iterator, and parent */
avl_node *n; /* newly inserted node */
avl_node *w; /* new root of rebalanced subtree */
int dir; /* direction to descend */
unsigned char da[AVL_MAX_HEIGHT]; /* cached comparison results */
int k = 0; /* number of cached results */
z = (avl_node *) &table->avl_root;
y = table->avl_root;
dir = 0;
for (q = z, p = y; p != NULL; q = p, p = p->avl_link[dir])
{
int cmp = table->avl_compare (item, p->avl_data, table->avl_param);
if (cmp == 0)
return &p->avl_data;
if (p->avl_balance != 0)
z = q, y = p, k = 0;
da[k++] = dir = cmp > 0;
}
/* allocate a new node */
n = q->avl_link[dir] = table->avl_alloc->alloc (sizeof *n, table->avl_param);
if (n == NULL)
return NULL;
table->avl_count++;
n->avl_data = item;
n->avl_link[0] = n->avl_link[1] = NULL;
n->avl_balance = 0;
if (y == NULL)
return &n->avl_data;
for (p = y, k = 0; p != n; p = p->avl_link[da[k]], k++)
if (da[k] == 0)
p->avl_balance--;
else
p->avl_balance++;
if (y->avl_balance == -2)
{
avl_node *x = y->avl_link[0];
if (x->avl_balance == -1)
{
w = x;
y->avl_link[0] = x->avl_link[1];
x->avl_link[1] = y;
x->avl_balance = y->avl_balance = 0;
}
else
{
w = x->avl_link[1];
x->avl_link[1] = w->avl_link[0];
w->avl_link[0] = x;
y->avl_link[0] = w->avl_link[1];
w->avl_link[1] = y;
if (w->avl_balance == -1)
x->avl_balance = 0, y->avl_balance = +1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == +1| */
x->avl_balance = -1, y->avl_balance = 0;
w->avl_balance = 0;
}
}
else if (y->avl_balance == +2)
{
avl_node *x = y->avl_link[1];
if (x->avl_balance == +1)
{
w = x;
y->avl_link[1] = x->avl_link[0];
x->avl_link[0] = y;
x->avl_balance = y->avl_balance = 0;
}
else
{
w = x->avl_link[0];
x->avl_link[0] = w->avl_link[1];
w->avl_link[1] = x;
y->avl_link[1] = w->avl_link[0];
w->avl_link[0] = y;
if (w->avl_balance == +1)
x->avl_balance = 0, y->avl_balance = -1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == -1| */
x->avl_balance = +1, y->avl_balance = 0;
w->avl_balance = 0;
}
}
else
return &n->avl_data;
z->avl_link[y != z->avl_link[0]] = w;
table->avl_generation++;
return &n->avl_data;
}
/*
avl_insert()
Inserts |item| into |table|. Returns NULL if item successfully inserted,
or if a memory allocation error occurred. Otherwise, return duplicate
item.
*/
static void *
avl_insert (void * item, void * vtable)
{
void **p = avl_probe (item, vtable);
return p == NULL || *p == item ? NULL : *p;
}
/*
avl_find()
Search for |item| in |table| and return a pointer to item if found.
Return NULL if not found.
*/
static void *
avl_find (const void * item, const void * vtable)
{
const avl_table * table = (const avl_table *) vtable;
avl_node *p;
for (p = table->avl_root; p != NULL; )
{
int cmp = table->avl_compare (item, p->avl_data, table->avl_param);
if (cmp < 0)
p = p->avl_link[0];
else if (cmp > 0)
p = p->avl_link[1];
else /* |cmp == 0| */
return p->avl_data;
}
return NULL;
}
/*
avl_remove()
Deletes from |table| and returns an item matching |item|.
Returns a null pointer if no matching item found.
*/
static void *
avl_remove (const void * item, void * vtable)
{
avl_table * table = (avl_table *) vtable;
/* stack of nodes */
avl_node *pa[AVL_MAX_HEIGHT]; /* nodes */
unsigned char da[AVL_MAX_HEIGHT]; /* |link[]| indexes */
int k; /* stack pointer */
avl_node *p; /* traverses tree to find node to delete */
int cmp; /* result of comparison between |item| and |p| */
k = 0;
p = (avl_node *) &table->avl_root;
for (cmp = -1; cmp != 0;
cmp = table->avl_compare (item, p->avl_data, table->avl_param))
{
int dir = cmp > 0;
pa[k] = p;
da[k++] = dir;
p = p->avl_link[dir];
if (p == NULL)
return NULL;
}
item = p->avl_data;
if (p->avl_link[1] == NULL)
pa[k - 1]->avl_link[da[k - 1]] = p->avl_link[0];
else
{
avl_node *r = p->avl_link[1];
if (r->avl_link[0] == NULL)
{
r->avl_link[0] = p->avl_link[0];
r->avl_balance = p->avl_balance;
pa[k - 1]->avl_link[da[k - 1]] = r;
da[k] = 1;
pa[k++] = r;
}
else
{
avl_node *s;
int j = k++;
for (;;)
{
da[k] = 0;
pa[k++] = r;
s = r->avl_link[0];
if (s->avl_link[0] == NULL)
break;
r = s;
}
s->avl_link[0] = p->avl_link[0];
r->avl_link[0] = s->avl_link[1];
s->avl_link[1] = p->avl_link[1];
s->avl_balance = p->avl_balance;
pa[j - 1]->avl_link[da[j - 1]] = s;
da[j] = 1;
pa[j] = s;
}
}
table->avl_alloc->free (p, table->avl_param);
while (--k > 0)
{
avl_node *y = pa[k];
if (da[k] == 0)
{
y->avl_balance++;
if (y->avl_balance == +1)
break;
else if (y->avl_balance == +2)
{
avl_node *x = y->avl_link[1];
if (x->avl_balance == -1)
{
avl_node *w;
w = x->avl_link[0];
x->avl_link[0] = w->avl_link[1];
w->avl_link[1] = x;
y->avl_link[1] = w->avl_link[0];
w->avl_link[0] = y;
if (w->avl_balance == +1)
x->avl_balance = 0, y->avl_balance = -1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == -1| */
x->avl_balance = +1, y->avl_balance = 0;
w->avl_balance = 0;
pa[k - 1]->avl_link[da[k - 1]] = w;
}
else
{
y->avl_link[1] = x->avl_link[0];
x->avl_link[0] = y;
pa[k - 1]->avl_link[da[k - 1]] = x;
if (x->avl_balance == 0)
{
x->avl_balance = -1;
y->avl_balance = +1;
break;
}
else
x->avl_balance = y->avl_balance = 0;
}
}
}
else
{
y->avl_balance--;
if (y->avl_balance == -1)
break;
else if (y->avl_balance == -2)
{
avl_node *x = y->avl_link[0];
if (x->avl_balance == +1)
{
avl_node *w;
w = x->avl_link[1];
x->avl_link[1] = w->avl_link[0];
w->avl_link[0] = x;
y->avl_link[0] = w->avl_link[1];
w->avl_link[1] = y;
if (w->avl_balance == -1)
x->avl_balance = 0, y->avl_balance = +1;
else if (w->avl_balance == 0)
x->avl_balance = y->avl_balance = 0;
else /* |w->avl_balance == +1| */
x->avl_balance = -1, y->avl_balance = 0;
w->avl_balance = 0;
pa[k - 1]->avl_link[da[k - 1]] = w;
}
else
{
y->avl_link[0] = x->avl_link[1];
x->avl_link[1] = y;
pa[k - 1]->avl_link[da[k - 1]] = x;
if (x->avl_balance == 0)
{
x->avl_balance = +1;
y->avl_balance = -1;
break;
}
else
x->avl_balance = y->avl_balance = 0;
}
}
}
}
table->avl_count--;
table->avl_generation++;
return (void *) item;
}
#if 0
/* Inserts |item| into |table|, replacing any duplicate item.
Returns |NULL| if |item| was inserted without replacing a duplicate,
or if a memory allocation error occurred.
Otherwise, returns the item that was replaced. */
static void *
avl_replace (avl_table *table, void *item)
{
void **p = avl_probe (table, item);
if (p == NULL || *p == item)
return NULL;
else
{
void *r = *p;
*p = item;
return r;
}
}
/* Destroys |new| with |avl_destroy (new, destroy)|,
first setting right links of nodes in |stack| within |new|
to null pointers to avoid touching uninitialized data. */
static void
copy_error_recovery (avl_node **stack, int height,
avl_table *new, avl_item_func *destroy)
{
for (; height > 2; height -= 2)
stack[height - 1]->avl_link[1] = NULL;
avl_destroy (new, destroy);
}
/* Copies |org| to a newly created tree, which is returned.
If |copy != NULL|, each data item in |org| is first passed to |copy|,
and the return values are inserted into the tree,
with |NULL| return values taken as indications of failure.
On failure, destroys the partially created new tree,
applying |destroy|, if non-null, to each item in the new tree so far,
and returns |NULL|.
If |allocator != NULL|, it is used for allocation in the new tree.
Otherwise, the same allocator used for |org| is used. */
static avl_table *
avl_copy (const avl_table *org, avl_copy_func *copy,
avl_item_func *destroy, struct libavl_allocator *allocator)
{
avl_node *stack[2 * (AVL_MAX_HEIGHT + 1)];
int height = 0;
avl_table *new;
const avl_node *x;
avl_node *y;
new = avl_alloc (org->avl_compare, org->avl_param,
allocator != NULL ? allocator : org->avl_alloc);
if (new == NULL)
return NULL;
new->avl_count = org->avl_count;
if (new->avl_count == 0)
return new;
x = (const avl_node *) &org->avl_root;
y = (avl_node *) &new->avl_root;
for (;;)
{
while (x->avl_link[0] != NULL)
{
y->avl_link[0] =
new->allocator->alloc (sizeof *y->avl_link[0],
new->avl_param);
if (y->avl_link[0] == NULL)
{
if (y != (avl_node *) &new->avl_root)
{
y->avl_data = NULL;
y->avl_link[1] = NULL;
}
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
stack[height++] = (avl_node *) x;
stack[height++] = y;
x = x->avl_link[0];
y = y->avl_link[0];
}
y->avl_link[0] = NULL;
for (;;)
{
y->avl_balance = x->avl_balance;
if (copy == NULL)
y->avl_data = x->avl_data;
else
{
y->avl_data = copy (x->avl_data, org->avl_param);
if (y->avl_data == NULL)
{
y->avl_link[1] = NULL;
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
}
if (x->avl_link[1] != NULL)
{
y->avl_link[1] =
new->allocator->alloc (sizeof *y->avl_link[1],
new->avl_param);
if (y->avl_link[1] == NULL)
{
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
x = x->avl_link[1];
y = y->avl_link[1];
break;
}
else
y->avl_link[1] = NULL;
if (height <= 2)
return new;
y = stack[--height];
x = stack[--height];
}
}
}
#endif
/*
avl_t_init()
Initializes |trav| for use with |tree| and selects the null node.
*/
static int
avl_t_init (void * vtrav, const void * vtable)
{
avl_traverser * trav = (avl_traverser *) vtrav;
const avl_table * table = (const avl_table *) vtable;
trav->avl_table = table;
trav->avl_node = NULL;
trav->avl_height = 0;
trav->avl_generation = table->avl_generation;
return GSL_SUCCESS;
}
/*
avl_t_first()
Initializes |trav| for |tree| and selects and returns a pointer to its least-valued item.
Returns |NULL| if |tree| contains no nodes.
*/
static void *
avl_t_first (void * vtrav, const void * vtable)
{
const avl_table * table = (const avl_table *) vtable;
avl_traverser * trav = (avl_traverser *) vtrav;
avl_node *x;
trav->avl_table = table;
trav->avl_height = 0;
trav->avl_generation = table->avl_generation;
x = table->avl_root;
if (x != NULL)
{
while (x->avl_link[0] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
}
}
trav->avl_node = x;
return x != NULL ? x->avl_data : NULL;
}
/*
avl_t_last()
Initializes |trav| for |tree| and selects and returns a pointer to its greatest-valued item.
Returns |NULL| if |tree| contains no nodes.
*/
static void *
avl_t_last (void * vtrav, const void * vtable)
{
const avl_table * table = (const avl_table *) vtable;
avl_traverser * trav = (avl_traverser *) vtrav;
avl_node *x;
trav->avl_table = table;
trav->avl_height = 0;
trav->avl_generation = table->avl_generation;
x = table->avl_root;
if (x != NULL)
{
while (x->avl_link[1] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
}
}
trav->avl_node = x;
return x != NULL ? x->avl_data : NULL;
}
/*
avl_t_find()
Searches for |item| in |table|. If found, initializes |trav| to
the item found and returns the item as well. If there is no matching
item, initializes |trav| to the null item and returns |NULL|.
*/
static void *
avl_t_find (const void * item, void * vtrav, const void * vtable)
{
const avl_table * table = (const avl_table *) vtable;
avl_traverser * trav = (avl_traverser *) vtrav;
avl_node *p, *q;
trav->avl_table = table;
trav->avl_height = 0;
trav->avl_generation = table->avl_generation;
for (p = table->avl_root; p != NULL; p = q)
{
int cmp = table->avl_compare (item, p->avl_data, table->avl_param);
if (cmp < 0)
q = p->avl_link[0];
else if (cmp > 0)
q = p->avl_link[1];
else /* |cmp == 0| */
{
trav->avl_node = p;
return p->avl_data;
}
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = p;
}
trav->avl_height = 0;
trav->avl_node = NULL;
return NULL;
}
/*
avl_t_insert()
Attempts to insert |item| into |table|. If |item| is inserted
successfully, it is returned and |trav| is initialized to its location.
If a duplicate is found, it is returned and |trav| is initialized to
its location. No replacement of the item occurs.
If a memory allocation failure occurs, |NULL| is returned and |trav|
is initialized to the null item.
*/
static void *
avl_t_insert (void * item, void * vtrav, void * vtable)
{
avl_table * table = (avl_table *) vtable;
avl_traverser * trav = (avl_traverser *) vtrav;
void **p;
p = avl_probe (item, table);
if (p != NULL)
{
trav->avl_table = table;
trav->avl_node = ((avl_node *) ((char *) p - offsetof (avl_node, avl_data)));
trav->avl_generation = table->avl_generation - 1;
return *p;
}
else
{
avl_t_init (vtrav, vtable);
return NULL;
}
}
/*
avl_t_copy()
Initializes |trav| to have the same current node as |src|.
*/
static void *
avl_t_copy (void * vtrav, const void * vsrc)
{
const avl_traverser * src = (const avl_traverser *) vsrc;
avl_traverser * trav = (avl_traverser *) vtrav;
if (trav != src)
{
trav->avl_table = src->avl_table;
trav->avl_node = src->avl_node;
trav->avl_generation = src->avl_generation;
if (trav->avl_generation == trav->avl_table->avl_generation)
{
trav->avl_height = src->avl_height;
memcpy (trav->avl_stack, (const void *) src->avl_stack,
sizeof *trav->avl_stack * trav->avl_height);
}
}
return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;
}
/*
avl_t_next()
Returns the next data item in in-order within the tree
being traversed with |trav|, or if there are no more data items returns NULL.
*/
static void *
avl_t_next (void * vtrav)
{
avl_traverser * trav = (avl_traverser *) vtrav;
avl_node *x;
if (trav->avl_generation != trav->avl_table->avl_generation)
avl_trav_refresh (trav);
x = trav->avl_node;
if (x == NULL)
{
return avl_t_first (vtrav, trav->avl_table);
}
else if (x->avl_link[1] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
while (x->avl_link[0] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
}
}
else
{
avl_node *y;
do
{
if (trav->avl_height == 0)
{
trav->avl_node = NULL;
return NULL;
}
y = x;
x = trav->avl_stack[--trav->avl_height];
}
while (y == x->avl_link[1]);
}
trav->avl_node = x;
return x->avl_data;
}
/*
avl_t_prev()
Returns the previous data item in inorder within the tree being
traversed with |trav|, or if there are no more data items returns NULL.
*/
static void *
avl_t_prev (void * vtrav)
{
avl_traverser * trav = (avl_traverser *) vtrav;
avl_node *x;
if (trav->avl_generation != trav->avl_table->avl_generation)
avl_trav_refresh (trav);
x = trav->avl_node;
if (x == NULL)
{
return avl_t_last (vtrav, trav->avl_table);
}
else if (x->avl_link[0] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[0];
while (x->avl_link[1] != NULL)
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_NULL("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = x;
x = x->avl_link[1];
}
}
else
{
avl_node *y;
do
{
if (trav->avl_height == 0)
{
trav->avl_node = NULL;
return NULL;
}
y = x;
x = trav->avl_stack[--trav->avl_height];
}
while (y == x->avl_link[0]);
}
trav->avl_node = x;
return x->avl_data;
}
static void *
avl_t_cur (const void * vtrav)
{
const avl_traverser * trav = (const avl_traverser *) vtrav;
return trav->avl_node != NULL ? trav->avl_node->avl_data : NULL;
}
/*
avl_t_replace()
Replaces the current item in |trav| by |new| and returns the item replaced.
|trav| must not have the null item selected. The new item must not upset the
ordering of the tree.
*/
static void *
avl_t_replace (void * vtrav, void * new_item)
{
avl_traverser * trav = (avl_traverser *) vtrav;
void *old;
old = trav->avl_node->avl_data;
trav->avl_node->avl_data = new_item;
return old;
}
/*
avl_trav_refresh()
Refreshes the stack of parent pointers in |trav| and updates its generation number
*/
static void
avl_trav_refresh (avl_traverser * trav)
{
trav->avl_generation = trav->avl_table->avl_generation;
if (trav->avl_node != NULL)
{
gsl_bst_cmp_function *cmp = trav->avl_table->avl_compare;
void *param = trav->avl_table->avl_param;
avl_node *node = trav->avl_node;
avl_node *i;
trav->avl_height = 0;
for (i = trav->avl_table->avl_root; i != node; )
{
if (trav->avl_height >= AVL_MAX_HEIGHT)
{
GSL_ERROR_VOID("traverser height exceeds maximum", GSL_ETABLE);
}
trav->avl_stack[trav->avl_height++] = i;
i = i->avl_link[cmp (node->avl_data, i->avl_data, param) > 0];
}
}
}
static const gsl_bst_type avl_tree_type =
{
"AVL",
sizeof(avl_node),
avl_init,
avl_nodes,
avl_insert,
avl_find,
avl_remove,
avl_empty,
avl_t_init,
avl_t_first,
avl_t_last,
avl_t_find,
avl_t_insert,
avl_t_copy,
avl_t_next,
avl_t_prev,
avl_t_cur,
avl_t_replace
};
const gsl_bst_type * gsl_bst_avl = &avl_tree_type;
| {
"alphanum_fraction": 0.5442469382,
"avg_line_length": 26.1516064257,
"ext": "c",
"hexsha": "7423860b389b11f11245e61972df9cd15ce48ece",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/bst/avl.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/bst/avl.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/bst/avl.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": 7404,
"size": 26047
} |
/**
* @brief handle cosmological functions like power spectrum, growth, etc.
*
* @file core_power.h
* @author Michal Vrastil
* @date 2018-06-21
*/
#pragma once
#include "precision.hpp"
#include <gsl/gsl_spline.h>
/*******************//**
* FORWARD DECLARATIONS *
************************/
class Cosmo_Param; ///< declaration in params.hpp
class Sim_Param; ///< declaration in params.hpp
template <typename T, size_t N> class Data_Vec; ///< declaration in class_data_vec.hpp
/**
* @brief Initialize CCL power spectrum
*
* @param cosmo cosmological parameters
*/
void norm_pwr(Cosmo_Param& cosmo);
/**
* @brief when computing growth factor outside CCL range we need to normalize the growth factor; \f$D(a=1)\equiv1\f$
*
* @param cosmo cosmological parameters
* @return FTYPE_t unnormalized growth factor at 'a = 1'
*/
FTYPE_t norm_growth_factor(const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t growth_factor(FTYPE_t a, const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t growth_rate(FTYPE_t a, const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t growth_change(FTYPE_t a, const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t Omega_lambda(FTYPE_t a, const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param k
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t lin_pow_spec(FTYPE_t a, FTYPE_t k, const Cosmo_Param& cosmo);
/**
* @brief
*
* @param a
* @param k
* @param cosmo cosmological parameters
* @return FTYPE_t
*/
FTYPE_t non_lin_pow_spec(FTYPE_t a, FTYPE_t k, const Cosmo_Param& cosmo);
/**
* @class: Interp_obj
* @brief: linear interpolation (Steffen) of data [x, y]
*/
class Interp_obj
{
public:
Interp_obj(): is_init(false) {}
~Interp_obj();
double operator()(double x) const;
template <typename T, size_t N>
void init(const Data_Vec<T, N>& data);
double x_min, x_max;
private:
bool is_init;
gsl_spline* spline;
gsl_interp_accel* acc;
};
/**
* @class: Extrap_Pk
* @brief: linear interpolation of data [k, P(k)] within 'useful' range
* fit to primordial P_i(k) below the 'useful' range
* fit to PadΓ© approximant R [0/3] above the 'useful' range
*
* Steffen interpolation of data [k, P(k)] within range k_min, k_max
* fit to primordial P_i(k) below this range, fit A*k^ns above
*/
template <typename T, size_t N>
class Extrap_Pk : public Interp_obj
{
public:
Extrap_Pk(const Data_Vec<T, N>& data, const Sim_Param& sim);
Extrap_Pk(const Data_Vec<T, N>& data, const Sim_Param& sim, const size_t m_l, const size_t n_u);
Extrap_Pk(const Data_Vec<T, N>& data, const Sim_Param& sim, const size_t m_l, const size_t n_l,
const size_t m_u, const size_t n_u);
double operator()(double k) const;
void fit_lin(const Data_Vec<T, N>& data, const size_t m, const size_t n, double& A);
void fit_power_law(const Data_Vec<T, N>& data, const size_t m, const size_t n, double& A, double& n_s);
double A_low; ///< amplitude of linear power in lower range
const Cosmo_Param& cosmo;
double A_up, n_s; ///< scale-free power spectrum in upper range
T k_min, k_max; ///< interpolation range
};
/**
* @class: Extrap_Pk_Nl
* @brief: creates Extrapolate object (linear power spectrum) from data and store non-linear parameters
call 'operator()(k)' based on k_split (upper range of the linear)
*/
template <typename T, size_t N>
class Extrap_Pk_Nl : public Extrap_Pk<T, N>
{
public:
Extrap_Pk_Nl(const Data_Vec<T, N>& data, const Sim_Param &sim, T A_nl, T a_eff);
const T A_nl, a_eff, k_split;
double operator()(double k) const;
};
/**
* @brief compute correlation function and store results
*
* @tparam P callable object with 'operator()(double)'
* @param sim simulation parameters
* @param P_k power spectrum (callable)
* @param corr_func_binned object to store binned correlation function
*/
template<class P>
void gen_corr_func_binned_gsl_qawf(const Sim_Param &sim, const P& P_k, Data_Vec<FTYPE_t, 2>& corr_func_binned);
/**
* @brief compute linear correlation function and store results
*
* @param sim simulation parameters
* @param a scale factor
* @param corr_func_binned object to store binned correlation function
*/
void gen_corr_func_binned_gsl_qawf_lin(const Sim_Param &sim, FTYPE_t a, Data_Vec<FTYPE_t, 2>& corr_func_binned);
/**
* @brief compute non-linear correlation function and store results
*
* @param sim simulation parameters
* @param a scale factor
* @param corr_func_binned object to store binned correlation function
*/
void gen_corr_func_binned_gsl_qawf_nl(const Sim_Param &sim, FTYPE_t a, Data_Vec<FTYPE_t, 2>& corr_func_binned);
/**
* @brief compute amplitude of density fluctuation and store results
*
* @tparam P callable object with 'operator()(double)'
* @param sim simulation parameters
* @param P_k power spectrum (callable)
* @param sigma_binned object to store binned correlation function
*/
template<class P>
void gen_sigma_binned_gsl_qawf(const Sim_Param &sim, const P& P_k, Data_Vec<FTYPE_t, 2>& sigma_binned);
/**
* @brief compute linear amplitude of density fluctuation and store results
*
* @param sim simulation parameters
* @param a scale factor
* @param sigma_binned object to store binned correlation function
*/
void gen_sigma_func_binned_gsl_qawf_lin(const Sim_Param &sim, FTYPE_t a, Data_Vec<FTYPE_t, 2>& sigma_binned);
/**
* @brief compute non-linear amplitude of density fluctuation and store results
*
* @param sim simulation parameters
* @param a scale factor
* @param sigma_binned object to store binned correlation function
*/
void gen_sigma_func_binned_gsl_qawf_nl(const Sim_Param &sim, FTYPE_t a, Data_Vec<FTYPE_t, 2>& sigma_binned);
| {
"alphanum_fraction": 0.7069306931,
"avg_line_length": 28.7203791469,
"ext": "h",
"hexsha": "9fedcf1856254f1a52147a3f42b75edd151f54f0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-07-03T12:48:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-20T13:15:11.000Z",
"max_forks_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sjvs/FastSim",
"max_forks_repo_path": "src/core/include/core_power.h",
"max_issues_count": 22,
"max_issues_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55",
"max_issues_repo_issues_event_max_datetime": "2018-09-17T07:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-27T07:34:02.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sjvs/FastSim",
"max_issues_repo_path": "src/core/include/core_power.h",
"max_line_length": 116,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sjvs/FastSim",
"max_stars_repo_path": "src/core/include/core_power.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1696,
"size": 6060
} |
/* matrix/gsl_matrix_uint.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_MATRIX_UINT_H__
#define __GSL_MATRIX_UINT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_uint.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
unsigned int * data;
gsl_block_uint * block;
int owner;
} gsl_matrix_uint;
typedef struct
{
gsl_matrix_uint matrix;
} _gsl_matrix_uint_view;
typedef _gsl_matrix_uint_view gsl_matrix_uint_view;
typedef struct
{
gsl_matrix_uint matrix;
} _gsl_matrix_uint_const_view;
typedef const _gsl_matrix_uint_const_view gsl_matrix_uint_const_view;
/* Allocation */
gsl_matrix_uint *
gsl_matrix_uint_alloc (const size_t n1, const size_t n2);
gsl_matrix_uint *
gsl_matrix_uint_calloc (const size_t n1, const size_t n2);
gsl_matrix_uint *
gsl_matrix_uint_alloc_from_block (gsl_block_uint * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
gsl_matrix_uint *
gsl_matrix_uint_alloc_from_matrix (gsl_matrix_uint * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
gsl_vector_uint *
gsl_vector_uint_alloc_row_from_matrix (gsl_matrix_uint * m,
const size_t i);
gsl_vector_uint *
gsl_vector_uint_alloc_col_from_matrix (gsl_matrix_uint * m,
const size_t j);
void gsl_matrix_uint_free (gsl_matrix_uint * m);
/* Views */
_gsl_matrix_uint_view
gsl_matrix_uint_submatrix (gsl_matrix_uint * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_uint_view
gsl_matrix_uint_row (gsl_matrix_uint * m, const size_t i);
_gsl_vector_uint_view
gsl_matrix_uint_column (gsl_matrix_uint * m, const size_t j);
_gsl_vector_uint_view
gsl_matrix_uint_diagonal (gsl_matrix_uint * m);
_gsl_vector_uint_view
gsl_matrix_uint_subdiagonal (gsl_matrix_uint * m, const size_t k);
_gsl_vector_uint_view
gsl_matrix_uint_superdiagonal (gsl_matrix_uint * m, const size_t k);
_gsl_matrix_uint_view
gsl_matrix_uint_view_array (unsigned int * base,
const size_t n1,
const size_t n2);
_gsl_matrix_uint_view
gsl_matrix_uint_view_array_with_tda (unsigned int * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uint_view
gsl_matrix_uint_view_vector (gsl_vector_uint * v,
const size_t n1,
const size_t n2);
_gsl_matrix_uint_view
gsl_matrix_uint_view_vector_with_tda (gsl_vector_uint * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uint_const_view
gsl_matrix_uint_const_submatrix (const gsl_matrix_uint * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_uint_const_view
gsl_matrix_uint_const_row (const gsl_matrix_uint * m,
const size_t i);
_gsl_vector_uint_const_view
gsl_matrix_uint_const_column (const gsl_matrix_uint * m,
const size_t j);
_gsl_vector_uint_const_view
gsl_matrix_uint_const_diagonal (const gsl_matrix_uint * m);
_gsl_vector_uint_const_view
gsl_matrix_uint_const_subdiagonal (const gsl_matrix_uint * m,
const size_t k);
_gsl_vector_uint_const_view
gsl_matrix_uint_const_superdiagonal (const gsl_matrix_uint * m,
const size_t k);
_gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_array (const unsigned int * base,
const size_t n1,
const size_t n2);
_gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_array_with_tda (const unsigned int * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_vector (const gsl_vector_uint * v,
const size_t n1,
const size_t n2);
_gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_vector_with_tda (const gsl_vector_uint * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
unsigned int gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j);
void gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x);
unsigned int * gsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j);
const unsigned int * gsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j);
void gsl_matrix_uint_set_zero (gsl_matrix_uint * m);
void gsl_matrix_uint_set_identity (gsl_matrix_uint * m);
void gsl_matrix_uint_set_all (gsl_matrix_uint * m, unsigned int x);
int gsl_matrix_uint_fread (FILE * stream, gsl_matrix_uint * m) ;
int gsl_matrix_uint_fwrite (FILE * stream, const gsl_matrix_uint * m) ;
int gsl_matrix_uint_fscanf (FILE * stream, gsl_matrix_uint * m);
int gsl_matrix_uint_fprintf (FILE * stream, const gsl_matrix_uint * m, const char * format);
int gsl_matrix_uint_memcpy(gsl_matrix_uint * dest, const gsl_matrix_uint * src);
int gsl_matrix_uint_swap(gsl_matrix_uint * m1, gsl_matrix_uint * m2);
int gsl_matrix_uint_swap_rows(gsl_matrix_uint * m, const size_t i, const size_t j);
int gsl_matrix_uint_swap_columns(gsl_matrix_uint * m, const size_t i, const size_t j);
int gsl_matrix_uint_swap_rowcol(gsl_matrix_uint * m, const size_t i, const size_t j);
int gsl_matrix_uint_transpose (gsl_matrix_uint * m);
int gsl_matrix_uint_transpose_memcpy (gsl_matrix_uint * dest, const gsl_matrix_uint * src);
unsigned int gsl_matrix_uint_max (const gsl_matrix_uint * m);
unsigned int gsl_matrix_uint_min (const gsl_matrix_uint * m);
void gsl_matrix_uint_minmax (const gsl_matrix_uint * m, unsigned int * min_out, unsigned int * max_out);
void gsl_matrix_uint_max_index (const gsl_matrix_uint * m, size_t * imax, size_t *jmax);
void gsl_matrix_uint_min_index (const gsl_matrix_uint * m, size_t * imin, size_t *jmin);
void gsl_matrix_uint_minmax_index (const gsl_matrix_uint * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
int gsl_matrix_uint_isnull (const gsl_matrix_uint * m);
int gsl_matrix_uint_add (gsl_matrix_uint * a, const gsl_matrix_uint * b);
int gsl_matrix_uint_sub (gsl_matrix_uint * a, const gsl_matrix_uint * b);
int gsl_matrix_uint_mul_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);
int gsl_matrix_uint_div_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);
int gsl_matrix_uint_scale (gsl_matrix_uint * a, const double x);
int gsl_matrix_uint_add_constant (gsl_matrix_uint * a, const double x);
int gsl_matrix_uint_add_diagonal (gsl_matrix_uint * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_uint_get_row(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t i);
int gsl_matrix_uint_get_col(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t j);
int gsl_matrix_uint_set_row(gsl_matrix_uint * m, const size_t i, const gsl_vector_uint * v);
int gsl_matrix_uint_set_col(gsl_matrix_uint * m, const size_t j, const gsl_vector_uint * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
unsigned int
gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
#endif
return m->data[i * m->tda + j] ;
}
extern inline
void
gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
m->data[i * m->tda + j] = x ;
}
extern inline
unsigned int *
gsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (unsigned int *) (m->data + (i * m->tda + j)) ;
}
extern inline
const unsigned int *
gsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (const unsigned int *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_UINT_H__ */
| {
"alphanum_fraction": 0.6590242113,
"avg_line_length": 34.3974763407,
"ext": "h",
"hexsha": "a253657227e6e9a9e961681088c0c5d01d550c64",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/segSiteHMM",
"max_forks_repo_path": "extern/include/gsl/gsl_matrix_uint.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/segSiteHMM",
"max_issues_repo_path": "extern/include/gsl/gsl_matrix_uint.h",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/segSiteHMM",
"max_stars_repo_path": "extern/include/gsl/gsl_matrix_uint.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2626,
"size": 10904
} |
/* statistics/gsl_statistics_ushort.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, 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_STATISTICS_USHORT_H__
#define __GSL_STATISTICS_USHORT_H__
#include <stddef.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_EXPORT double gsl_stats_ushort_mean (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_variance (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_sd (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_variance_with_fixed_mean (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_sd_with_fixed_mean (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_absdev (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_skew (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_kurtosis (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_lag1_autocorrelation (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_covariance (const unsigned short data1[], const size_t stride1,const unsigned short data2[], const size_t stride2, const size_t n);
GSL_EXPORT double gsl_stats_ushort_variance_m (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_sd_m (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_absdev_m (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_skew_m_sd (const unsigned short data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_ushort_kurtosis_m_sd (const unsigned short data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_ushort_lag1_autocorrelation_m (const unsigned short data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_ushort_covariance_m (const unsigned short data1[], const size_t stride1,const unsigned short data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);
GSL_EXPORT double gsl_stats_ushort_pvariance (const unsigned short data1[], const size_t stride1, const size_t n1, const unsigned short data2[], const size_t stride2, const size_t n2);
GSL_EXPORT double gsl_stats_ushort_ttest (const unsigned short data1[], const size_t stride1, const size_t n1, const unsigned short data2[], const size_t stride2, const size_t n2);
GSL_EXPORT unsigned short gsl_stats_ushort_max (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT unsigned short gsl_stats_ushort_min (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_ushort_minmax (unsigned short * min, unsigned short * max, const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_ushort_max_index (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_ushort_min_index (const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_ushort_minmax_index (size_t * min_index, size_t * max_index, const unsigned short data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_ushort_median_from_sorted_data (const unsigned short sorted_data[], const size_t stride, const size_t n) ;
GSL_EXPORT double gsl_stats_ushort_quantile_from_sorted_data (const unsigned short sorted_data[], const size_t stride, const size_t n, const double f) ;
__END_DECLS
#endif /* __GSL_STATISTICS_USHORT_H__ */
| {
"alphanum_fraction": 0.8015390846,
"avg_line_length": 64.1298701299,
"ext": "h",
"hexsha": "49669cf7f655acf508519587530168672b6805ae",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ushort.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ushort.h",
"max_line_length": 208,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_ushort.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1192,
"size": 4938
} |
/**
* @file batchg_zgemv.c
*
* Part of API test for Batched BLAS routines.
*
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-06-01
*
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "bblas.h"
#define COMPLEX
void batchg_zgemv(
const enum BBLAS_TRANS *trans,
const int *m, const int *n,
const BBLAS_Complex64_t *alpha,
const BBLAS_Complex64_t **arrayA, const int *lda,
const BBLAS_Complex64_t **arrayx, const int *incx,
const BBLAS_Complex64_t *beta,
BBLAS_Complex64_t **arrayy, const int *incy,
const int group_count, const int *group_size,
int* info)
{
/* Local variables */
char func_name[15] = "batchg_zgemv";
int group_iter = 0;
int offset = 0; // How many subproblems solved so far
/* Check group_count */
if (group_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_GROUP_COUNT, -1);
return;
}
/* Check group_size and call fixed batch computation */
for (group_iter = 0; group_iter < group_count; group_iter++)
{
if (group_size[group_iter] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_GROUP_SIZE, group_iter);
info[group_iter] = BBLAS_ERR_GROUP_SIZE;
continue;
}
/* Call fixed batch computation on the group */
batchf_zgemv(
trans[group_iter],
m[group_iter], n[group_iter],
alpha[group_iter],
arrayA+offset, lda[group_iter],
arrayx+offset, incx[group_iter],
beta[group_iter],
arrayy+offset, incy[group_iter],
group_size[group_iter], info[group_iter]);
/* Update offset */
offset += group_size[group_iter];
} // End of group loop
}
#undef COMPLEX
| {
"alphanum_fraction": 0.6954346467,
"avg_line_length": 23.1739130435,
"ext": "c",
"hexsha": "4e542489de770b764e2187a2d9d470bef532afcf",
"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": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sdrelton/bblas_api_test",
"max_forks_repo_path": "src/batchg_zgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"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": "sdrelton/bblas_api_test",
"max_issues_repo_path": "src/batchg_zgemv.c",
"max_line_length": 61,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mawussi/BBLAS-group",
"max_stars_repo_path": "src/batchg_zgemv.c",
"max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z",
"num_tokens": 486,
"size": 1599
} |
#ifndef libceed_solids_examples_cl_options_h
#define libceed_solids_examples_cl_options_h
#include <petsc.h>
#include "../include/structs.h"
// Process general command line options
PetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx app_ctx);
#endif // libceed_solids_examples_cl_options_h
| {
"alphanum_fraction": 0.8421052632,
"avg_line_length": 27.6363636364,
"ext": "h",
"hexsha": "c4b3844a1b13b2eec5fdbca1591a43cd9d01594e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/solids/include/cl-options.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wence-/libCEED",
"max_issues_repo_path": "examples/solids/include/cl-options.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/solids/include/cl-options.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 67,
"size": 304
} |
/*
* 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 dirty_08c91b95_68e8_437c_b721_3ad67fdc25ac_h
#define dirty_08c91b95_68e8_437c_b721_3ad67fdc25ac_h
#include <gslib/std.h>
#include <ariel/type.h>
__ariel_begin__
class dirty_list
{
public:
typedef list<rect> rect_list;
typedef rect_list::iterator iterator;
typedef rect_list::const_iterator const_iterator;
protected:
int _width, _height;
int _cap;
bool _whole;
private:
rect_list _rclist;
public:
dirty_list();
dirty_list(int w, int h);
int size() const { return (int)_rclist.size(); }
void clear();
void set_dimension(int w, int h);
void add(rect rc);
void set_whole() { _whole = true;}
bool is_whole() const { return _whole; }
bool is_dirty(const rect& rc) const;
iterator begin() { return _rclist.begin(); }
const_iterator begin() const { return _rclist.begin(); }
iterator end() { return _rclist.end(); }
const_iterator end() const { return _rclist.end(); }
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6995244272,
"avg_line_length": 33.0428571429,
"ext": "h",
"hexsha": "de21f75df93f1f9c57b4b9e303c155672fafc698",
"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/dirty.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/dirty.h",
"max_line_length": 82,
"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/dirty.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": 556,
"size": 2313
} |
#ifndef QDM_PARAMETERS_H
#define QDM_PARAMETERS_H 1
#include <gsl/gsl_vector.h>
typedef struct {
unsigned long int rng_seed;
int acc_check;
int burn;
int iter;
int knot_try;
int spline_df;
int thin;
double month;
double knot;
double tau_high;
double tau_low;
double theta_min;
double theta_tune_sd;
double xi_high;
double xi_low;
double xi_prior_mean;
double xi_prior_var;
double xi_tune_sd;
double bound;
int debug;
int tau_table;
bool truncate;
} qdm_parameters;
void
qdm_parameters_fprint(
FILE *f,
const qdm_parameters *p
);
int
qdm_parameters_write(
hid_t id,
const qdm_parameters *p
);
int
qdm_parameters_read(
hid_t id,
qdm_parameters *p
);
#endif /* QDM_PARAMETERS_H */
| {
"alphanum_fraction": 0.7105263158,
"avg_line_length": 13.1034482759,
"ext": "h",
"hexsha": "a11d17c59c63173159d277e37a20473844146851",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/parameters.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/parameters.h",
"max_line_length": 29,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/parameters.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 211,
"size": 760
} |
#ifndef CTETRA_TETRA_H
#define CTETRA_TETRA_H
#include <stdlib.h>
#include <gsl/gsl_vector.h>
#include "ecache.h"
typedef double (*tetra_SumFn)(double E, double E1, double E2, double E3, double E4, double num_tetra);
double tetra_SumTetra(tetra_SumFn F, double E, EnergyCache *Ecache);
void sortEs(double Es[4]);
#endif // CTETRA_TETRA_H
| {
"alphanum_fraction": 0.7609329446,
"avg_line_length": 22.8666666667,
"ext": "h",
"hexsha": "00edd38cb29d92fe8ee96bcd5395eb9f68cd6363",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "tetra.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "tetra.h",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "tetra.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 115,
"size": 343
} |
// sammlung verwendeter Funktionen
#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 <string.h>
#include <time.h>
#include <omp.h>
#ifndef HEADER_FILE_UTIL
#define HEADER_FILE_UTIL
double Norm_Diff(double *vec1,double *vec2, int dim, int p); //berechnet norm von || vec1-vec2 ||_p
void Lattice_Setup(double **positions,int numbertoinf,int dim, double latticespacing); // Legt Koordianten auf mxn Gittermatrix der dimension numbertoinf**dim, dim
int ipow(int base, int exp);
int Kahan_Sum(int N, double input[], double *ans);
int Sign_Sum(int N, double input[], double *ans);
int Neumaier_Sum(int N, double input[N], double *ans);
void deleteSpaces(char src[], char dst[]);
void vec_zero(double *v,int N);
void vec_zero_i(int *v,int N);
int Update_Lattice_Position(int * pos, const double *vec, const double lattice_spacing);
// begin stepper with different external forces -------//
void VVerlet_Step(int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*deriv) (double *y, double *ans, double t,int N));
void VVerlet_Step_Target_Square(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*deriv) (double *y, double *ans, double t,int N));
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));
void VVerlet_Step_Yukawa(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));
void VVerlet_Step_Pore_Rectangle(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, // wie Verlet step, aber Teilchen reflektiert stehen falls in Target (Quadrat)
void (*derivmethod) (double *y, double *ans, double t,int N));
void VVerlet_Step_Pore_Yukawa(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));
// end stepper with different external forces -------//
void VVerlet(int N, double *y, double **ans, double *t,
void (*deriv) (double *y, double *ans, double t, int N));
void VVerlet_parallel(const int N, const double *y, double **ans, double *t,
void (*derivmethod) (double *y, double *ans, double t, int N));
void VVerlet_parallel_burn(const int N, const double *y, double **ans, double *t, // Velocity Verlet fΓΌr Start y, Ausgabe ans[LengthT][ORDER] zu Zeiten T
void (*derivmethod) (double *y, double *ans, double t, int N));
void Bath_Setup(double *y, char *label, gsl_rng * r);
void Ommega_Setup(gsl_rng * r);
void Gamma_Setup(double * gamma);
void deriv(double *y, double *ans, double t, int N);
void deriv_parallel(const double *yin, double *ans, double t, int N);
void deriv_Yukawa(const double *y, double *ans, double t, int N);
#endif | {
"alphanum_fraction": 0.7019322141,
"avg_line_length": 43.8472222222,
"ext": "h",
"hexsha": "0b41f7d5dd1eb1f26db38626696159dd658acd12",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_forks_repo_path": "utility.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_issues_repo_path": "utility.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_stars_repo_path": "utility.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 954,
"size": 3157
} |
#include <stdio.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_matrix_double.h>
// #include "covar.h"
void print_mat(gsl_matrix* C)
{
int i, j;
for (i = 0; i < C->size1; i++)
{
printf("\n");
for (j = 0; j < C->size2; j++)
{
printf("%f", C->data[C->size2*i+j]);
if(j < C->size2 - 1) printf(", ");
}
}
printf("\n");
}
int main()
{
int i, j;
/*
Okay, here's what we want to do
1) Collect *all* the data - 10 seconds at standstill should be sufficient, with
x, y, z, yaw, pitch, roll; for both pose and twist
2) twist gives us euler angles (yaw pitch roll), but pose gives us quaternions,
so we'll need to convert
2) This leads to a 6 by N matrix of values
3) We propose a cov_gen() function
input: 6 by N matrix of observation values
output: 6 by 6 matrix of covariance values
4) We can put a ROS wrapper around this function as a service routine,
i.e. the output of cov_gen() will serve as our estimate of
the covariance matrix for loam_velodyne's odometry topic
*/
// const int rsize = 5;
// const int csize = 3;
#define rsize 8
#define csize 6
double dataA[rsize][csize] =
{{9, 6, 9, 3, 2, 1},
{9, 9, 3, 4, 3, 5},
{6, 6, 6, 6, 7, 3},
{6, 6, 9, 4, 5, 1},
{9, 9, 3, 4, 3, 5},
{6, 6, 6, 6, 7, 3},
{6, 6, 9, 4, 5, 1},
{3, 3, 3, 6, 4, 1}};
// double dataA[rsize][csize] =
// {{90, 60, 90},
// {90, 90, 30},
// {60, 60, 60},
// {60, 60, 90},
// {30, 30, 30}};
// double dataA[5][3] = {{ 24, 0, 30},
// { 24, 30, -30},
// { -6, 0, 0},
// { -6, 0, 30},
// {-36, -30, -30}};
// double dataA[6][6] = {{1,1,1,1,1,1},
// {2,2,2,2,2,2},
// {3,3,3,3,3,3},
// {4,4,4,4,4,4},
// {5,5,5,5,5,5},
// {6,6,6,6,6,6}};
gsl_vector_view a, b;
gsl_matrix *A, *C;
A = gsl_matrix_alloc(rsize, csize);
C = gsl_matrix_alloc(csize, csize);
for ( i = 0; i < rsize; i++)
for ( j = 0; j < csize; j++)
gsl_matrix_set (A, i, j, dataA[i][j]);
print_mat(A);
for (i = 0; i < A->size2; i++) {
for (j = 0; j < A->size2; j++) {
a = gsl_matrix_column (A, i);
b = gsl_matrix_column (A, j);
double cov = gsl_stats_covariance(a.vector.data,
a.vector.stride,
b.vector.data,
b.vector.stride,
rsize);
gsl_matrix_set (C, i, j, cov);
}
}
print_mat(C);
return 0;
}
| {
"alphanum_fraction": 0.4144975288,
"avg_line_length": 28.3644859813,
"ext": "c",
"hexsha": "b23607fe109b9559f1e14a4a768517168f0d0530",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2022-02-22T10:10:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-04T04:32:54.000Z",
"max_forks_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joeyzhu00/FusionAD",
"max_forks_repo_path": "src/utility/covar/src/file.c",
"max_issues_count": 167,
"max_issues_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_issues_repo_issues_event_max_datetime": "2019-04-30T21:57:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-17T03:48:11.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joeyzhu00/FusionAD",
"max_issues_repo_path": "src/utility/covar/src/file.c",
"max_line_length": 84,
"max_stars_count": 33,
"max_stars_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joeyzhu00/FusionAD",
"max_stars_repo_path": "src/utility/covar/src/file.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-17T09:18:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-03T19:45:42.000Z",
"num_tokens": 1010,
"size": 3035
} |
#ifndef ANGLE_CONVERSION_H_1QTGVG9X
#define ANGLE_CONVERSION_H_1QTGVG9X
#include <gsl/gsl>
#include <sens_loc/math/constants.h>
#include <type_traits>
namespace sens_loc {
/// Implement necessary math functionality in this namespace, which is mostly
/// used by conversions.
namespace math {
/// This function converts degree into radians
/// \tparam T precision of the type (e.g. \c float or \c double)
/// \param degree angle in degree
/// \returns the same angle in radians
/// \sa rad_to_deg
/// \pre \f$0. <= degree <= 360.\f$
/// \post \f$0. <= result <= 2\pi\f$
/// \post \c rad_to_deg(result) == \p degree
template <typename T> // requires(Float(T))
constexpr inline T deg_to_rad(T degree) {
static_assert(std::is_floating_point_v<T>);
Expects(degree <= T(360.));
Expects(degree >= T(0.));
const T radians = degree / T(180.) * pi<T>;
Ensures(radians >= T(0.));
Ensures(radians <= T(2. * pi<T>));
return radians;
}
/// This function converts radians into degrees
/// \tparam T precision of the type (e.g. \c float or \c double)
/// \param radians angle in radians
/// \returns the same angle in degree
/// \sa deg_to_rad
/// \pre \f$0. <= radians <= 2\pi\f$
/// \post \f$0. <= result <= 360.\f$
/// \post \c deg_to_rad(result) == \p radians
template <typename T> // requires(Float(T))
constexpr inline T rad_to_deg(T radians) {
static_assert(std::is_floating_point_v<T>);
Expects(radians >= T(0.));
Expects(radians <= T(2. * pi<T>));
const T degree = radians * T(180.) / pi<T>;
Ensures(degree <= T(360.));
Ensures(degree >= T(0.));
return degree;
}
} // namespace math
} // namespace sens_loc
#endif /* end of include guard: ANGLE_CONVERSION_H_1QTGVG9X */
| {
"alphanum_fraction": 0.6549336411,
"avg_line_length": 29.3728813559,
"ext": "h",
"hexsha": "eefbc26431953bde5204f33dbd5480996bea9dbc",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/include/sens_loc/math/angle_conversion.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/include/sens_loc/math/angle_conversion.h",
"max_line_length": 77,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/include/sens_loc/math/angle_conversion.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 511,
"size": 1733
} |
/* vector/gsl_vector_char.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_CHAR_H__
#define __GSL_VECTOR_CHAR_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_char.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
char *data;
gsl_block_char *block;
int owner;
}
gsl_vector_char;
typedef struct
{
gsl_vector_char vector;
} _gsl_vector_char_view;
typedef _gsl_vector_char_view gsl_vector_char_view;
typedef struct
{
gsl_vector_char vector;
} _gsl_vector_char_const_view;
typedef const _gsl_vector_char_const_view gsl_vector_char_const_view;
/* Allocation */
GSL_FUN gsl_vector_char *gsl_vector_char_alloc (const size_t n);
GSL_FUN gsl_vector_char *gsl_vector_char_calloc (const size_t n);
GSL_FUN gsl_vector_char *gsl_vector_char_alloc_from_block (gsl_block_char * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_char *gsl_vector_char_alloc_from_vector (gsl_vector_char * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_char_free (gsl_vector_char * v);
/* Views */
GSL_FUN _gsl_vector_char_view
gsl_vector_char_view_array (char *v, size_t n);
GSL_FUN _gsl_vector_char_view
gsl_vector_char_view_array_with_stride (char *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_char_const_view
gsl_vector_char_const_view_array (const char *v, size_t n);
GSL_FUN _gsl_vector_char_const_view
gsl_vector_char_const_view_array_with_stride (const char *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_char_view
gsl_vector_char_subvector (gsl_vector_char *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_char_view
gsl_vector_char_subvector_with_stride (gsl_vector_char *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_char_const_view
gsl_vector_char_const_subvector (const gsl_vector_char *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_char_const_view
gsl_vector_char_const_subvector_with_stride (const gsl_vector_char *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_char_set_zero (gsl_vector_char * v);
GSL_FUN void gsl_vector_char_set_all (gsl_vector_char * v, char x);
GSL_FUN int gsl_vector_char_set_basis (gsl_vector_char * v, size_t i);
GSL_FUN int gsl_vector_char_fread (FILE * stream, gsl_vector_char * v);
GSL_FUN int gsl_vector_char_fwrite (FILE * stream, const gsl_vector_char * v);
GSL_FUN int gsl_vector_char_fscanf (FILE * stream, gsl_vector_char * v);
GSL_FUN int gsl_vector_char_fprintf (FILE * stream, const gsl_vector_char * v,
const char *format);
GSL_FUN int gsl_vector_char_memcpy (gsl_vector_char * dest, const gsl_vector_char * src);
GSL_FUN int gsl_vector_char_reverse (gsl_vector_char * v);
GSL_FUN int gsl_vector_char_swap (gsl_vector_char * v, gsl_vector_char * w);
GSL_FUN int gsl_vector_char_swap_elements (gsl_vector_char * v, const size_t i, const size_t j);
GSL_FUN char gsl_vector_char_max (const gsl_vector_char * v);
GSL_FUN char gsl_vector_char_min (const gsl_vector_char * v);
GSL_FUN void gsl_vector_char_minmax (const gsl_vector_char * v, char * min_out, char * max_out);
GSL_FUN size_t gsl_vector_char_max_index (const gsl_vector_char * v);
GSL_FUN size_t gsl_vector_char_min_index (const gsl_vector_char * v);
GSL_FUN void gsl_vector_char_minmax_index (const gsl_vector_char * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_char_add (gsl_vector_char * a, const gsl_vector_char * b);
GSL_FUN int gsl_vector_char_sub (gsl_vector_char * a, const gsl_vector_char * b);
GSL_FUN int gsl_vector_char_mul (gsl_vector_char * a, const gsl_vector_char * b);
GSL_FUN int gsl_vector_char_div (gsl_vector_char * a, const gsl_vector_char * b);
GSL_FUN int gsl_vector_char_scale (gsl_vector_char * a, const double x);
GSL_FUN int gsl_vector_char_add_constant (gsl_vector_char * a, const double x);
GSL_FUN int gsl_vector_char_isnull (const gsl_vector_char * v);
GSL_FUN int gsl_vector_char_ispos (const gsl_vector_char * v);
GSL_FUN int gsl_vector_char_isneg (const gsl_vector_char * v);
GSL_FUN int gsl_vector_char_isnonneg (const gsl_vector_char * v);
GSL_FUN INLINE_DECL char gsl_vector_char_get (const gsl_vector_char * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_char_set (gsl_vector_char * v, const size_t i, char x);
GSL_FUN INLINE_DECL char * gsl_vector_char_ptr (gsl_vector_char * v, const size_t i);
GSL_FUN INLINE_DECL const char * gsl_vector_char_const_ptr (const gsl_vector_char * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
char
gsl_vector_char_get (const gsl_vector_char * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_char_set (gsl_vector_char * v, const size_t i, char x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
char *
gsl_vector_char_ptr (gsl_vector_char * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (char *) (v->data + i * v->stride);
}
INLINE_FUN
const char *
gsl_vector_char_const_ptr (const gsl_vector_char * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const char *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_CHAR_H__ */
| {
"alphanum_fraction": 0.6631082423,
"avg_line_length": 33.8487394958,
"ext": "h",
"hexsha": "03e386734f03056206cfd0551e6d0eba618056f8",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_vector_char.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"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": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_vector_char.h",
"max_line_length": 104,
"max_stars_count": null,
"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_vector_char.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1931,
"size": 8056
} |
#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>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include "core_allvars_grid.h"
#include "core_proto_grid.h"
int32_t init(void)
{
int32_t i, status;
sum_photons = 0.0;
random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng_set(random_generator, 42); // start-up seed
set_units(); // Change units to code units where necessary.
srand((unsigned) time(NULL));
read_snap_list(); // Read the snapshots required.
for(i = 0; i < Snaplistlen; i++)
{
ZZ[i] = 1 / AA[i] - 1; // Redshift array.
Age[i] = time_to_present(ZZ[i]); // Age array.
}
if (fescPrescription == 0)
{
printf("\n\nUsing a constant escape fraction of %.4f\n", fesc);
}
else if (fescPrescription == 1)
{
fprintf(stderr, "\n\nDeprecated! Use a new one!\n");
return EXIT_FAILURE;
}
else if (fescPrescription == 2)
{
printf("\n\nUsing an fesc prescription that scales with halo mass.\n\n");
determine_fesc_constants();
}
else if (fescPrescription == 3)
{
printf("\n\nUsing an fesc prescription that scales with the fraction of ejected mass in the galaxy.\n");
printf("\nThis takes the form A*fej + B with A = %.4e and B = %.4e\n", alpha, beta);
}
else if (fescPrescription == 4)
{
printf("\n\nUsing an fesc prescription that depends upon quasar activity.\n");
printf("\nFor a galaxy that had a quasar event within %.2f dynamical times go the escape fraction will be %.2f. Otherwise it will have a constant value of %.2f\n", N_dyntime, quasar_boosted, quasar_baseline);
}
else if (fescPrescription == 5)
{
printf("\n\nUsing Anne's functional form for an escape fraction that decreases for increasing halo mass.\n");
XASSERT(fesc_low > fesc_high, "Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 5), we require fesc_low > fesc_high\n", fesc_low, fesc_high);
}
else if (fescPrescription == 6)
{
printf("\n\nUsing Anne's functional form for an escape fraction that increases for increasing halo mass.\n");
XASSERT(fesc_low < fesc_high, "Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 6), we require fesc_low < fesc_high\n", fesc_low, fesc_high);
}
else if (fescPrescription == 7)
{
printf("\n\nUsing an fesc prescription that scales as a power law with the fraction of ejected gas.\n");
determine_fesc_constants();
}
else
{
printf("\n\nOnly escape fraction prescriptions 0 to 6 (exlucding 1) are permitted.\n");
return EXIT_FAILURE;
}
Grid = malloc(sizeof(struct GRID_STRUCT));
if (Grid == NULL)
{
fprintf(stderr, "Could not allocate memory for the high level grid structure\n");
return EXIT_FAILURE;
}
status = init_grid(Grid);
if (status == EXIT_FAILURE)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
QuasarEventsAbovePartCut = 0;
QuasarEventsBelowPartCut = 0;
}
int32_t init_grid(struct GRID_STRUCT *grid)
{
#define ALLOCATE_GRID_MEMORY(name, length) \
{ \
name = calloc(length, sizeof(*(name))); \
if (name == NULL) \
{ \
fprintf(stderr, "Out of memory allocating %ld bytes, could not allocate"#name".\n", sizeof(*(name)* length)); \
return EXIT_FAILURE; \
} \
}
int32_t i;
uint64_t cell_idx;
if (grid == NULL)
{
fprintf(stderr, "init_grid was called with a GRID_STRUCT pointer that has not been initialized\n");
return EXIT_FAILURE;
}
grid->GridSize = GridSize;
grid->NumCellsTotal = CUBE(GridSize);
grid->NumGrids = NGrid;
grid->GridProperties = malloc(sizeof(struct GRID_PROPERTIES_STRUCT) * grid->NumGrids);
if (grid->GridProperties == NULL)
{
fprintf(stderr, "Could not allocate memory for the grid properties struct\n");
return EXIT_FAILURE;
}
for (i = 0; i < grid->NumGrids; ++i)
{
#ifdef MPI
printf("Allocating grid %d on Task %d.\n", i, ThisTask);
#endif
/* For now the self-consistent model only using the number of ionizing photons. */
/* Also use the number of galaxies for sanity check. */
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HI, grid->NumCellsTotal);
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].GalCount, grid->NumCellsTotal);
if (self_consistent == 0)
{
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].SFR, grid->NumCellsTotal);
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].StellarMass, grid->NumCellsTotal);
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HeI, grid->NumCellsTotal);
ALLOCATE_GRID_MEMORY(grid->GridProperties[i].Nion_HeII, grid->NumCellsTotal);
}
// All the memory has been allocated for the inner grid.
// Now let's initialize the values.
for (cell_idx = 0; cell_idx < Grid->NumCellsTotal; ++cell_idx)
{
grid->GridProperties[i].Nion_HI[cell_idx] = 0.0;
grid->GridProperties[i].GalCount[cell_idx] = 0;
if (self_consistent == 0)
{
grid->GridProperties[i].SFR[cell_idx] = 0.0;
grid->GridProperties[i].StellarMass[cell_idx] = 0.0;
grid->GridProperties[i].Nion_HeI[cell_idx] = 0.0;
grid->GridProperties[i].Nion_HeII[cell_idx] = 0.0;
}
}
}
printf("All grids have been initialized\n");
return EXIT_SUCCESS;
}
int32_t free_grid(void)
{
int32_t i;
for (i = 0; i < Grid->NumGrids; ++i)
{
free(Grid->GridProperties[i].Nion_HI);
free(Grid->GridProperties[i].GalCount);
if (self_consistent == 0)
{
free(Grid->GridProperties[i].Nion_HeII);
free(Grid->GridProperties[i].Nion_HeI);
free(Grid->GridProperties[i].StellarMass);
free(Grid->GridProperties[i].SFR);
}
}
free(Grid->GridProperties);
free(Grid);
return EXIT_SUCCESS;
}
void set_units(void)
{
UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR;
G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2);
UnitDensity_in_cgs = UnitMass_in_g / pow(UnitLength_in_cm, 3);
UnitPressure_in_cgs = UnitMass_in_g / UnitLength_in_cm / pow(UnitTime_in_s, 2);
UnitCoolingRate_in_cgs = UnitPressure_in_cgs / UnitTime_in_s;
UnitEnergy_in_cgs = UnitMass_in_g * pow(UnitLength_in_cm, 2) / pow(UnitTime_in_s, 2);
// convert some physical input parameters to internal units
Hubble = HUBBLE * UnitTime_in_s;
// compute a few quantitites
RhoCrit = 3 * Hubble * Hubble / (8 * M_PI * G);
}
void read_snap_list(void)
{
FILE *fd;
char fname[MAXLEN];
snprintf(fname, MAXLEN, "%s", FileWithSnapList);
if(!(fd = fopen(fname, "r")))
{
printf("can't read output list in file '%s'\n", fname);
ABORT(0);
}
Snaplistlen = 0;
do
{
if(fscanf(fd, " %lg ", &AA[Snaplistlen]) == 1)
Snaplistlen++;
else
break;
}
while(Snaplistlen < MAXSNAPS);
fclose(fd);
#ifdef MPI
if(ThisTask == 0)
#endif
printf("found %d defined times in snaplist\n", Snaplistlen);
}
double time_to_present(double z)
{
#define WORKSIZE 1000
gsl_function F;
gsl_integration_workspace *workspace;
double time, result, abserr;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &integrand_time_to_present;
gsl_integration_qag(&F, 1.0 / (z + 1), 1.0, 1.0 / Hubble,
1.0e-8, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);
time = 1 / Hubble * result;
gsl_integration_workspace_free(workspace);
// return time to present as a function of redshift
return time;
}
double integrand_time_to_present(double a, void *param)
{
return 1 / sqrt(Omega / a + (1 - Omega - OmegaLambda) + OmegaLambda * a * a);
}
void determine_fesc_constants(void)
{
double A, B, log_A;
log_A = (log10(fesc_high) - (log10(fesc_low)*log10(MH_high)/log10(MH_low))) * pow(1 - (log10(MH_high) / log10(MH_low)), -1);
B = (log10(fesc_low) - log_A) / log10(MH_low);
A = pow(10, log_A);
alpha = A;
beta = B;
printf("Fixing the points (%.4e, %.2f) and (%.4e, %.2f)\n", MH_low, fesc_low, MH_high, fesc_high);
printf("This gives a power law with constants A = %.4e, B = %.4e\n", alpha, beta);
}
/*
void estimate_grid_memory(void)
{
if (Verbose == 1)
{
printf("The size of the Grid Struct (that contains all the pointers) is %lu bytes\nEach grid cell has a struct, in addition to data that the pointers point to.\n", sizeof(struct GRID));
printf("The total memory taken up by the Grid will be the sizeof a grid cell (%lu bytes) times the number of grid cells (%d) times the number of output snapshots (%d) times 2 because we need memory for both the pointers for the grid and the actual numbers themselves.\n", sizeof(struct GRID), CUBE(GridSize), NGrid);
}
printf("Approximate total memory for the grid ===== %lu mb\n", sizeof(struct GRID)*CUBE(GridSize)*NGrid*2/1024/1024);
}
void estimate_gal_memory(int NtotGals)
{
if (Verbose == 1)
{
printf("The size of the Galaxy struct is %lu bytes and the size of the GalaxyGrid struct (that contains all the pointers for the SnapShot history) is %lu\n", sizeof(struct GALAXY_INPUT), sizeof(struct GALAXY_GRID));
printf("The total memory taken up by this file of galaxies will be the sizeof the galaxy input (%lu bytes) times the number of galaxies (%d) plus the sizeof the galaxygrid (%lu bytes) times the number of snapshots in the simulation (%d) times the number of galaxies (%d)\n", sizeof(struct GALAXY_INPUT), NtotGals, sizeof(struct GALAXY_GRID), LastSnapShotNr, NtotGals);
}
printf("Approximate memory occupied for this file of galaxies ===== %lu mb\n", (sizeof(struct GALAXY_INPUT)*NtotGals + sizeof(struct GALAXY_GRID)*NtotGals*LastSnapShotNr)/1024/1024);
}
*/
| {
"alphanum_fraction": 0.670810542,
"avg_line_length": 30.1047904192,
"ext": "c",
"hexsha": "476354e6515b61ea7a5267346aeaf1fcebdd16da",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jacobseiler/rsage",
"max_forks_repo_path": "gridding/core_init_grid.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jacobseiler/rsage",
"max_issues_repo_path": "gridding/core_init_grid.c",
"max_line_length": 373,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jacobseiler/rsage",
"max_stars_repo_path": "gridding/core_init_grid.c",
"max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z",
"num_tokens": 2874,
"size": 10055
} |
#pragma once
#include "halley/maths/vector3.h"
#include <gsl/span>
namespace Halley
{
class AudioListenerData;
class AudioChannelData
{
public:
float pan; // TODO, do this right
};
class AudioPosition
{
public:
static AudioPosition makeUI(float pan = 0.0f); // -1.0f = left, 1.0f = right
static AudioPosition makePositional(Vector2f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f);
static AudioPosition makePositional(Vector3f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f);
static AudioPosition makeFixed();
void setMix(size_t srcChannels, gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const;
AudioPosition();
private:
Vector3f pos;
float referenceDistance;
float maxDistance;
bool isUI;
bool isPannable;
};
}
| {
"alphanum_fraction": 0.7413394919,
"avg_line_length": 24.7428571429,
"ext": "h",
"hexsha": "47993c3b397b15332e18bdd608efe9e5189638fc",
"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": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Healthire/halley",
"max_forks_repo_path": "src/engine/audio/include/halley/audio/audio_position.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"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": "Healthire/halley",
"max_issues_repo_path": "src/engine/audio/include/halley/audio/audio_position.h",
"max_line_length": 160,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Healthire/halley",
"max_stars_repo_path": "src/engine/audio/include/halley/audio/audio_position.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 243,
"size": 866
} |
#include <math.h>
#include <gsl/gsl_linalg.h>
#include "getNextIterate.h"
void getNextIterate(const grid *grd, const bool eos_func,
const wksp *w
#if AA_M > 0
, const unsigned long itCount, const long nHist,
double *residMax
#endif
) {
long i;
#if AA_M > 0
long j, mk, colptr;
gsl_matrix *resid;
gsl_vector *tau, *llsresid, *aa_wgts, *constraint;
gsl_vector_view constraint_view;
#endif
#if AA_M == 0
/* No Anderson acceleration, so just move temporaries into next
guess */
for (i=0; i<grd->nr; i++) {
w->colNew[i] = w->colTmp[i];
w->presNew_g[i+1] = gsl_vector_get(w->presTmp_g, i+1);
if (eos_func==1)
w->eIntNew[i] = w->eIntTmp[i];
}
#else
/* Anderson acceleration code */
/* Set up pointers */
mk = itCount < AA_M+1 ? itCount : AA_M+1;
colptr = (itCount - 1) % (AA_M+1);
/* Store the current guesses in the history array */
for (i=0; i<grd->nr; i++) {
w->colHist[i + colptr*grd->nr] = w->colTmp[i];
w->presHist[i + colptr*grd->nr] = gsl_vector_get(w->presTmp_g, i+1);
if (eos_func)
w->eIntHist[i + colptr*grd->nr] = w->eIntTmp[i];
}
/* Compute residuals and store them in the residual matrix */
for (i=0; i<grd->nr; i++) {
w->colResid[i + colptr*grd->nr] =
(w->colHist[i+colptr*grd->nr]-w->colNew[i]) /
w->colHist[i+colptr*grd->nr];
if (fabs(w->colResid[i + colptr*grd->nr]) > *residMax) {
*residMax = fabs(w->colResid[i + colptr*grd->nr]);
}
w->presResid[i + colptr*grd->nr] =
(w->presHist[i+colptr*grd->nr]-w->presNew_g[i+1]) /
w->presHist[i+colptr*grd->nr];
if (fabs(w->presResid[i + colptr*grd->nr]) > *residMax) {
*residMax = fabs(w->presResid[i + colptr*grd->nr]);
}
if (eos_func) {
w->eIntResid[i + colptr*grd->nr] =
(w->eIntHist[i+colptr*grd->nr]-w->eIntNew[i]) /
w->eIntHist[i+colptr*grd->nr];
if (fabs(w->eIntResid[i + colptr*grd->nr]) > *residMax)
*residMax = fabs(w->eIntResid[i + colptr*grd->nr]);
}
}
/* If we're in the first iteration, set move temporaries to next
guess */
if (itCount == 1) {
for (i=0; i<grd->nr; i++) {
w->colNew[i] = w->colHist[i+colptr*grd->nr];
w->presNew_g[i+1] = w->presHist[i+colptr*grd->nr];
if (eos_func)
w->eIntNew[i] = w->eIntHist[i+colptr*grd->nr];
}
} else {
/* On subsequent iterations, solve the linear least squares
optimization problem to get a weighted sum of previous
guesses for the new guess */
/* Allocate workspace for this iteration */
resid = gsl_matrix_alloc(nHist+1, mk);
llsresid = gsl_vector_alloc(nHist+1);
aa_wgts = gsl_vector_alloc(mk);
if (nHist+1 < mk) {
tau = gsl_vector_alloc(nHist+1);
} else {
tau = gsl_vector_alloc(mk);
}
/* Build matrix of residuals */
for (i=0; i<grd->nr; i++) {
for (j=0; j<mk; j++) {
gsl_matrix_set(resid, i, j, w->colResid[i+j*grd->nr]);
gsl_matrix_set(resid, i+grd->nr, j, w->presResid[i+j*grd->nr]);
if (eos_func)
gsl_matrix_set(resid, i+2*grd->nr, j, w->eIntResid[i+j*grd->nr]);
}
}
/* Set up constraints on coefficients */
for (j=0; j<mk; j++) gsl_matrix_set(resid, nHist, j, 1.0e3*(*residMax));
constraint_view = gsl_vector_subvector(w->constraint, 0, nHist+1);
constraint = &(constraint_view.vector);
gsl_vector_set(constraint, nHist, 1e3*(*residMax));
/* Solve linear least squares system by QR decomposition */
gsl_linalg_QR_decomp(resid, tau);
gsl_linalg_QR_lssolve(resid, tau, constraint, aa_wgts, llsresid);
/* Build the new guess from the computed weights */
for (i=0; i<grd->nr; i++) {
w->colNew[i] =
gsl_vector_get(aa_wgts, 0)*w->colHist[i];
w->presNew_g[i+1] =
gsl_vector_get(aa_wgts, 0)*w->presHist[i];
if (eos_func)
w->eIntNew[i] =
gsl_vector_get(aa_wgts, 0)*w->eIntHist[i];
}
for (j=1; j<mk; j++) {
for (i=0; i<grd->nr; i++) {
w->colNew[i] += gsl_vector_get(aa_wgts, j) *
w->colHist[i+j*grd->nr];
w->presNew_g[i+1] += gsl_vector_get(aa_wgts, j) *
w->presHist[i+j*grd->nr];
if (eos_func)
w->eIntNew[i] += gsl_vector_get(aa_wgts, j) *
w->eIntHist[i+j*grd->nr];
}
}
/* Free memory for this iteration */
gsl_vector_free(llsresid);
gsl_vector_free(tau);
gsl_vector_free(aa_wgts);
gsl_matrix_free(resid);
}
#endif
/* End Anderson acceleration code */
}
| {
"alphanum_fraction": 0.6036626724,
"avg_line_length": 30.5034482759,
"ext": "c",
"hexsha": "552c81278645c48c94814020d4a952e0610d3187",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z",
"max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "franciscaconcha/amuse-vader",
"max_forks_repo_path": "src/amuse/community/vader/src/getNextIterate.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "franciscaconcha/amuse-vader",
"max_issues_repo_path": "src/amuse/community/vader/src/getNextIterate.c",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "franciscaconcha/amuse-vader",
"max_stars_repo_path": "src/amuse/community/vader/src/getNextIterate.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1594,
"size": 4423
} |
#include <petsc.h>
#include "poissonfunctions.h"
PetscErrorCode Poisson1DFunctionLocal(DMDALocalInfo *info, double *au,
double *aF, PoissonCtx *user) {
PetscErrorCode ierr;
int i;
double xmax[1], xmin[1], h, x, ue, uw;
ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);
h = (xmax[0] - xmin[0]) / (info->mx - 1);
for (i = info->xs; i < info->xs + info->xm; i++) {
x = xmin[0] + i * h;
if (i==0 || i==info->mx-1) {
aF[i] = au[i] - user->g_bdry(x,0.0,0.0,user);
aF[i] *= user->cx * (2.0 / h);
} else {
ue = (i+1 == info->mx-1) ? user->g_bdry(x+h,0.0,0.0,user)
: au[i+1];
uw = (i-1 == 0) ? user->g_bdry(x-h,0.0,0.0,user)
: au[i-1];
aF[i] = user->cx * (2.0 * au[i] - uw - ue) / h
- h * user->f_rhs(x,0.0,0.0,user);
}
}
ierr = PetscLogFlops(9.0*info->xm);CHKERRQ(ierr);
return 0;
}
//STARTFORM2DFUNCTION
PetscErrorCode Poisson2DFunctionLocal(DMDALocalInfo *info, double **au,
double **aF, PoissonCtx *user) {
PetscErrorCode ierr;
int i, j;
double xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, x, y,
ue, uw, un, us;
ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);
hx = (xymax[0] - xymin[0]) / (info->mx - 1);
hy = (xymax[1] - xymin[1]) / (info->my - 1);
darea = hx * hy;
scx = user->cx * hy / hx;
scy = user->cy * hx / hy;
scdiag = 2.0 * (scx + scy); // diagonal scaling
for (j = info->ys; j < info->ys + info->ym; j++) {
y = xymin[1] + j * hy;
for (i = info->xs; i < info->xs + info->xm; i++) {
x = xymin[0] + i * hx;
if (i==0 || i==info->mx-1 || j==0 || j==info->my-1) {
aF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,user);
aF[j][i] *= scdiag;
} else {
ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,0.0,user)
: au[j][i+1];
uw = (i-1 == 0) ? user->g_bdry(x-hx,y,0.0,user)
: au[j][i-1];
un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,0.0,user)
: au[j+1][i];
us = (j-1 == 0) ? user->g_bdry(x,y-hy,0.0,user)
: au[j-1][i];
aF[j][i] = scdiag * au[j][i]
- scx * (uw + ue) - scy * (us + un)
- darea * user->f_rhs(x,y,0.0,user);
}
}
}
ierr = PetscLogFlops(11.0*info->xm*info->ym);CHKERRQ(ierr);
return 0;
}
//ENDFORM2DFUNCTION
PetscErrorCode Poisson3DFunctionLocal(DMDALocalInfo *info, double ***au,
double ***aF, PoissonCtx *user) {
PetscErrorCode ierr;
int i, j, k;
double xyzmin[3], xyzmax[3], hx, hy, hz, dvol, scx, scy, scz, scdiag,
x, y, z, ue, uw, un, us, uu, ud;
ierr = DMDAGetBoundingBox(info->da,xyzmin,xyzmax); CHKERRQ(ierr);
hx = (xyzmax[0] - xyzmin[0]) / (info->mx - 1);
hy = (xyzmax[1] - xyzmin[1]) / (info->my - 1);
hz = (xyzmax[2] - xyzmin[2]) / (info->mz - 1);
dvol = hx * hy * hz;
scx = user->cx * dvol / (hx*hx);
scy = user->cy * dvol / (hy*hy);
scz = user->cz * dvol / (hz*hz);
scdiag = 2.0 * (scx + scy + scz);
for (k = info->zs; k < info->zs + info->zm; k++) {
z = xyzmin[2] + k * hz;
for (j = info->ys; j < info->ys + info->ym; j++) {
y = xyzmin[1] + j * hy;
for (i = info->xs; i < info->xs + info->xm; i++) {
x = xyzmin[0] + i * hx;
if ( i==0 || i==info->mx-1
|| j==0 || j==info->my-1
|| k==0 || k==info->mz-1) {
aF[k][j][i] = au[k][j][i] - user->g_bdry(x,y,z,user);
aF[k][j][i] *= scdiag;
} else {
ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,z,user)
: au[k][j][i+1];
uw = (i-1 == 0) ? user->g_bdry(x-hx,y,z,user)
: au[k][j][i-1];
un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,z,user)
: au[k][j+1][i];
us = (j-1 == 0) ? user->g_bdry(x,y-hy,z,user)
: au[k][j-1][i];
uu = (k+1 == info->mz-1) ? user->g_bdry(x,y,z+hz,user)
: au[k+1][j][i];
ud = (k-1 == 0) ? user->g_bdry(x,y,z-hz,user)
: au[k-1][j][i];
aF[k][j][i] = scdiag * au[k][j][i]
- scx * (uw + ue) - scy * (us + un) - scz * (uu + ud)
- dvol * user->f_rhs(x,y,z,user);
}
}
}
}
ierr = PetscLogFlops(14.0*info->xm*info->ym*info->zm);CHKERRQ(ierr);
return 0;
}
PetscErrorCode Poisson1DJacobianLocal(DMDALocalInfo *info, PetscScalar *au,
Mat J, Mat Jpre, PoissonCtx *user) {
PetscErrorCode ierr;
int i,ncols;
double xmin[1], xmax[1], h, v[3];
MatStencil col[3],row;
ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);
h = (xmax[0] - xmin[0]) / (info->mx - 1);
for (i = info->xs; i < info->xs+info->xm; i++) {
row.i = i;
col[0].i = i;
ncols = 1;
if (i==0 || i==info->mx-1) {
v[0] = user->cx * 2.0 / h;
} else {
v[0] = user->cx * 2.0 / h;
if (i-1 > 0) {
col[ncols].i = i-1; v[ncols++] = - user->cx / h;
}
if (i+1 < info->mx-1) {
col[ncols].i = i+1; v[ncols++] = - user->cx / h;
}
}
ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != Jpre) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode Poisson2DJacobianLocal(DMDALocalInfo *info, PetscScalar **au,
Mat J, Mat Jpre, PoissonCtx *user) {
PetscErrorCode ierr;
double xymin[2], xymax[2], hx, hy, scx, scy, scdiag, v[5];
int i,j,ncols;
MatStencil col[5],row;
ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);
hx = (xymax[0] - xymin[0]) / (info->mx - 1);
hy = (xymax[1] - xymin[1]) / (info->my - 1);
scx = user->cx * hy / hx;
scy = user->cy * hx / hy;
scdiag = 2.0 * (scx + scy);
for (j = info->ys; j < info->ys+info->ym; j++) {
row.j = j;
col[0].j = j;
for (i = info->xs; i < info->xs+info->xm; i++) {
row.i = i;
col[0].i = i;
ncols = 1;
v[0] = scdiag;
if (i>0 && i<info->mx-1 && j>0 && j<info->my-1) {
if (i-1 > 0) {
col[ncols].j = j; col[ncols].i = i-1; v[ncols++] = - scx; }
if (i+1 < info->mx-1) {
col[ncols].j = j; col[ncols].i = i+1; v[ncols++] = - scx; }
if (j-1 > 0) {
col[ncols].j = j-1; col[ncols].i = i; v[ncols++] = - scy; }
if (j+1 < info->my-1) {
col[ncols].j = j+1; col[ncols].i = i; v[ncols++] = - scy; }
}
ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != Jpre) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode Poisson3DJacobianLocal(DMDALocalInfo *info, PetscScalar ***au,
Mat J, Mat Jpre, PoissonCtx *user) {
PetscErrorCode ierr;
double xyzmin[3], xyzmax[3], hx, hy, hz, dvol, scx, scy, scz, scdiag, v[7];
int i,j,k,ncols;
MatStencil col[7],row;
ierr = DMDAGetBoundingBox(info->da,xyzmin,xyzmax); CHKERRQ(ierr);
hx = (xyzmax[0] - xyzmin[0]) / (info->mx - 1);
hy = (xyzmax[1] - xyzmin[1]) / (info->my - 1);
hz = (xyzmax[2] - xyzmin[2]) / (info->mz - 1);
dvol = hx * hy * hz;
scx = user->cx * dvol / (hx*hx);
scy = user->cy * dvol / (hy*hy);
scz = user->cz * dvol / (hz*hz);
scdiag = 2.0 * (scx + scy + scz);
for (k = info->zs; k < info->zs+info->zm; k++) {
row.k = k;
col[0].k = k;
for (j = info->ys; j < info->ys+info->ym; j++) {
row.j = j;
col[0].j = j;
for (i = info->xs; i < info->xs+info->xm; i++) {
row.i = i;
col[0].i = i;
ncols = 1;
v[0] = scdiag;
if (i>0 && i<info->mx-1 && j>0 && j<info->my-1 && k>0 && k<info->mz-1) {
if (i-1 > 0) {
col[ncols].k = k; col[ncols].j = j; col[ncols].i = i-1;
v[ncols++] = - scx;
}
if (i+1 < info->mx-1) {
col[ncols].k = k; col[ncols].j = j; col[ncols].i = i+1;
v[ncols++] = - scx;
}
if (j-1 > 0) {
col[ncols].k = k; col[ncols].j = j-1; col[ncols].i = i;
v[ncols++] = - scy;
}
if (j+1 < info->my-1) {
col[ncols].k = k; col[ncols].j = j+1; col[ncols].i = i;
v[ncols++] = - scy;
}
if (k-1 > 0) {
col[ncols].k = k-1; col[ncols].j = j; col[ncols].i = i;
v[ncols++] = - scz;
}
if (k+1 < info->mz-1) {
col[ncols].k = k+1; col[ncols].j = j; col[ncols].i = i;
v[ncols++] = - scz;
}
}
ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
}
ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != Jpre) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode InitialState(DM da, InitialType it, PetscBool gbdry,
Vec u, PoissonCtx *user) {
PetscErrorCode ierr;
DMDALocalInfo info;
PetscRandom rctx;
switch (it) {
case ZEROS:
ierr = VecSet(u,0.0); CHKERRQ(ierr);
break;
case RANDOM:
ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx); CHKERRQ(ierr);
ierr = VecSetRandom(u,rctx); CHKERRQ(ierr);
ierr = PetscRandomDestroy(&rctx); CHKERRQ(ierr);
break;
default:
SETERRQ(PETSC_COMM_WORLD,4,"invalid InitialType ... how did I get here?\n");
}
if (!gbdry) {
return 0;
}
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
switch (info.dim) {
case 1:
{
int i;
double xmax[1], xmin[1], h, x, *au;
ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);
ierr = DMDAGetBoundingBox(da,xmin,xmax); CHKERRQ(ierr);
h = (xmax[0] - xmin[0]) / (info.mx - 1);
for (i = info.xs; i < info.xs + info.xm; i++) {
if (i==0 || i==info.mx-1) {
x = xmin[0] + i * h;
au[i] = user->g_bdry(x,0.0,0.0,user);
}
}
ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);
break;
}
case 2:
{
int i, j;
double xymin[2], xymax[2], hx, hy, x, y, **au;
ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);
ierr = DMDAGetBoundingBox(da,xymin,xymax); CHKERRQ(ierr);
hx = (xymax[0] - xymin[0]) / (info.mx - 1);
hy = (xymax[1] - xymin[1]) / (info.my - 1);
for (j = info.ys; j < info.ys + info.ym; j++) {
y = xymin[1] + j * hy;
for (i = info.xs; i < info.xs + info.xm; i++) {
if (i==0 || i==info.mx-1 || j==0 || j==info.my-1) {
x = xymin[0] + i * hx;
au[j][i] = user->g_bdry(x,y,0.0,user);
}
}
}
ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);
break;
}
case 3:
{
int i, j, k;
double xyzmin[3], xyzmax[3], hx, hy, hz, x, y, z, ***au;
ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);
ierr = DMDAGetBoundingBox(da,xyzmin,xyzmax); CHKERRQ(ierr);
hx = (xyzmax[0] - xyzmin[0]) / (info.mx - 1);
hy = (xyzmax[1] - xyzmin[1]) / (info.my - 1);
hz = (xyzmax[2] - xyzmin[2]) / (info.mz - 1);
for (k = info.zs; k < info.zs+info.zm; k++) {
z = xyzmin[2] + k * hz;
for (j = info.ys; j < info.ys + info.ym; j++) {
y = xyzmin[1] + j * hy;
for (i = info.xs; i < info.xs + info.xm; i++) {
if (i==0 || i==info.mx-1 || j==0 || j==info.my-1
|| k==0 || k==info.mz-1) {
x = xyzmin[0] + i * hx;
au[k][j][i] = user->g_bdry(x,y,z,user);
}
}
}
}
ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);
break;
}
default:
SETERRQ(PETSC_COMM_WORLD,5,"invalid dim from DMDALocalInfo\n");
}
return 0;
}
| {
"alphanum_fraction": 0.4136988174,
"avg_line_length": 41.2084507042,
"ext": "c",
"hexsha": "e5bced073f16e701dffa5a42bbb10e9b938a4a3c",
"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/ch6/poissonfunctions.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/ch6/poissonfunctions.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/ch6/poissonfunctions.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4775,
"size": 14629
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <assert.h>
#include <nlopt.h>
// The "procedural" interface to Reduce/CSL.
#include "C_call_CSL.h"
// activate by setting to 1 or 2
int DEBUG = 0;
// The optimization "object":
static nlopt_opt opt = NULL;
// The result computed by NLOPT_optimize:
static double *result;
// The local optimization sub-algorithm/object, for algorithms that use it:
static nlopt_opt local_opt = NULL;
// Nlopt return codes, see nlopt_result in nlopt.h. Used only in few
// places. nlopt_main.red does error checking at the Reduce level.
char *nlopt_result_mess(nlopt_result r) {
char *s;
switch (r) {
case -1: s = "nlopt failure!"; break;
case -2: s = "invalid arguments or unsupported constraints (perhaps for this algorithm)!"; break;
case -3: s = "out of memory!"; break;
case -4: s = "progress limited by roundoff"; break;
case -5: s = "forced stop"; break;
case 1: s = "nlopt success"; break;
case 2: s = "stop value reached"; break;
case 3: s= "f-tolerance reached"; break;
case 4: s = "x-tolerance reached"; break;
case 5: s = "max evaluations reached"; break;
case 6: s = "max time reached"; break;
};
return s;
}
#define ERRORCHECK(who,r) if (r != NLOPT_SUCCESS) \
{fprintf(stderr, "*%s: %s\n", who, nlopt_result_mess(r));}
// =======================================================================
// Basics
// =======================================================================
void NLOPT_create(int32_t anum, int32_t n) {
opt = nlopt_create(anum, n);
if (opt == NULL)
fprintf(stderr, "Couldn't create '%s'!\n", nlopt_algorithm_name(anum));
// nlopt_algorithm_name is built-in to the NLopt library
}
void NLOPT_destroy() {
nlopt_destroy(opt);
}
int32_t NLOPT_get_algorithm() {
// The only reason for this 'NLOPT_' is to convert from nlopt_algorithm to 'int32_t'!
// Isn't there a better way?
int32_t a = nlopt_get_algorithm(opt);
return a;
}
int32_t NLOPT_get_dimension() {
// The only reason for this 'NLOPT_' is to convert from "unsigned" to 'int32_t'!
int32_t d = nlopt_get_dimension(opt);
return d;
}
// =======================================================================
// Setting upper and lower bounds (hyper-rectangle)
// =======================================================================
int32_t NLOPT_set_lower_bounds(const double *lb) {
int32_t r = nlopt_set_lower_bounds(opt, lb);
return r;
}
int32_t NLOPT_set_upper_bounds(const double *ub) {
int32_t r = nlopt_set_upper_bounds(opt, ub);
return r;
}
// acts like a Icon generator
double NLOPT_get_lower_bound(int32_t i, int32_t n) {
static double *slb = NULL;
if (i == 0) {
// Contortion 1:
slb = (double *) malloc(n*sizeof(double));
int32_t r = nlopt_get_lower_bounds(opt, slb);
ERRORCHECK("NLOPT_get_lower_bound",r);
}
// Contortion 2:
double lbi = slb[i];
if (i == n-1) free(slb);
return lbi;
}
// acts like a Icon generator
double NLOPT_get_upper_bound(int32_t i, int32_t n) {
static double *sub = NULL;
if (i == 0) {
// Contortion 1:
sub = (double *) malloc(n*sizeof(double));
int32_t r = nlopt_get_upper_bounds(opt, sub);
ERRORCHECK("NLOPT_get_upper_bound",r);
}
// Contortion 2:
double ubi = sub[i];
if (i == n-1) free(sub);
return ubi;
}
// =======================================================================
// Stopping criteria
// =======================================================================
int32_t NLOPT_set_xtol_rel(double t) {
return nlopt_set_xtol_rel(opt, t);
}
int32_t NLOPT_set_ftol_rel(double t) {
return nlopt_set_ftol_rel(opt, t);
}
int32_t NLOPT_set_ftol_abs(double t) {
return nlopt_set_ftol_abs(opt, t);
}
int32_t NLOPT_set_maxeval(int32_t m) {
return nlopt_set_maxeval(opt, m);
}
int32_t NLOPT_set_maxtime(double m) {
return nlopt_set_maxtime(opt, m);
}
int32_t NLOPT_set_stopval(double v) {
return nlopt_set_stopval(opt, v);
}
double NLOPT_get_xtol_rel() {
return nlopt_get_xtol_rel(opt);
}
double NLOPT_get_ftol_rel() {
return nlopt_get_ftol_rel(opt);
}
double NLOPT_get_ftol_abs() {
return nlopt_get_ftol_abs(opt);
}
int32_t NLOPT_get_maxeval() {
return nlopt_get_maxeval(opt);
}
double NLOPT_get_maxtime() {
return nlopt_get_maxtime(opt);
}
// ===========================================================================
// Functions *internal* to the interface for dealing with arrays of doubles
// To understand what's going on see the comments in nlopt_set_lower_bounds()
// in nlopt_main.red.
// ===========================================================================
double *newDoubleArray(int32_t len) {
double *a;
a = (double *) malloc(len*sizeof(double));
return a;
}
void setDoubleArray(double a[], int32_t i, double x) {
a[i] = x;
}
void freeDoubleArray(double a[]) {
free(a);
}
// This internal function turns a C array of doubles into a Lisp list and
// leaves it at the top of the stack. The "stack" is used by the "procedural"
// interface to Reduce, see file "C_call_CSL.h".
void C_darray_to_Lisp_list(int32_t n, const double x[]) {
// Push the x[i] on the stack.
for (int i = 0; i < n; i++) PROC_push_floating(x[i]);
// Make a list out of the x[i]; it is left at the top of the stack.
PROC_make_function_call("list", n);
// Now having put 'list on the front, get rid of it.
// (This perhaps shows that that ACN should really extend the procedural
// interface to make this slightly nicer. But with luck this will suffice
// for now.)
PROC_lisp_eval();
}
// ================================================================
// Setting the optimization objective
// ================================================================
// This is the most complex and difficult part of the interface so far.
// This function is internal to the interface (static), and is of type nlopt_func.
// It is modelled after f77_func_wrap in api/f77api.c. It is used as a wrapper
// for scalar functions, which can represent either the optimization objective,
// or a general equality or inequality constraint.
// The PROC_ code is borrowed from cuba_integrand in redcuba.c of the 'cuba' package.
static double red_func_wrap(unsigned n, const double *x, double *grad, void *f_data) {
double z;
char *fn = (char *) f_data;
if (DEBUG > 1) {
fprintf(stderr, "red_func_wrap: %s", fn);
if (grad) fprintf(stderr, " [G]");
fprintf(stderr, "\n");
}
// Convert the function name (string) to a symbol, push it on the stack, and
// wrap it in a quote:
PROC_push_symbol(fn);
PROC_make_function_call("quote", 1);
// Turn the array 'x' into a Lisp list and leave it at the top of the "stack".
C_darray_to_Lisp_list(n,x);
// Wrap it in a quote:
PROC_make_function_call("quote", 1);
// Evaluate a call to the Reduce algebraic function 'fn' that takes an n-list
// of reals 'x', and delivers either a single real, f(x), or, if 'grad' is not
// NULL, the flattened (n+1)-list of reals {f(x),grad(x)}.
int32_t r = PROC_make_function_call("call_alg_fn_list2list", 2);
PROC_lisp_eval();
if (DEBUG > 1) {
fprintf(stderr, " %s(", fn);
for (int i=0; i<n; i++) {
fprintf(stderr, "%.4g", x[i]);
if (i < n-1) fprintf(stderr, ",");
}
};
if (grad) {
// If 'grad' is not NULL, the Reduce function 'fn' is expected to return a
// flattened list {f(x),grad(x)}, where grad(x) is an n-list which should
// be assigned to 'grad'. (Also see the function red_mfunc_wrap.)
PROC_handle y = PROC_get_value();
z = PROC_floating_value(PROC_first(y));
if (DEBUG > 1) {
fprintf(stderr, ") = %.5g\n", z);
fprintf(stderr, " grad = {");
};
y = PROC_rest(y);
for (int i = 0; i < n; i++) {
grad[i] = PROC_floating_value(PROC_first(y));
y = PROC_rest(y);
if (DEBUG > 1) {
fprintf(stderr, "%.4g", grad[i]);
if (i < n-1) fprintf(stderr, ",");
}
}
if (DEBUG > 1) fprintf(stderr, "}\n");
}
else { // grad is NULL, result is just f(x)
z = PROC_floating_value(PROC_get_value());
if (DEBUG > 1) fprintf(stderr, ") = %.5g\n", z);
}
return z;
}
// Modelled after F77_nlo_set_min_objective in api/f77funcs_.h.
int32_t NLOPT_set_min_objective(char *fname) {
// In the call to nlopt_set_min_objective:
// 1. The wrapper red_func_wrap is the nlopt_func argument,
// 2. The name of the Reduce function defining the objective is the *f_data argument,
// 3. We can't just pass fname to to this argument, we need the string rfun on the heap!
char *rfun = malloc(strlen(fname)*sizeof(char)+1);
strcpy(rfun,fname);
return nlopt_set_min_objective(opt, red_func_wrap, rfun);
}
int32_t NLOPT_set_max_objective(char *fname) {
char *rfun = malloc(strlen(fname)*sizeof(char)+1);
strcpy(rfun,fname);
return nlopt_set_max_objective(opt, red_func_wrap, rfun);
}
int32_t NLOPT_optimize(double *x0, int32_t n) {
double *x, f;
x = (double *) malloc(n*sizeof(double));
for (int j=0; j<n; j++) x[j] = x0[j];
if (DEBUG) fprintf(stderr, "NLOPT_optimize:\n");
int32_t r = nlopt_optimize(opt, x, &f);
// assign results to the static 'result' array:
result = (double *) malloc((n+1)*sizeof(double));
result[0] = f;
for (int j=0; j<n; j++) result[j+1] = x[j];
free(x);
if (DEBUG) {
fprintf(stderr, " f = %f\n", result[0]);
fprintf(stderr, " result =");
for (int j=0; j<n; j++)
fprintf(stderr, " %.5g", result[j+1]);
fprintf(stderr, "\n");
}
return r;
}
double get_result(int32_t i) {
return result[i];
}
void free_result() {
free(result);
}
// ================================================================
// Setting the local optimization sub-algorithm
// ================================================================
int32_t NLOPT_set_local_optimizer(int32_t anum) {
local_opt = nlopt_create(anum, nlopt_get_dimension(opt));
return nlopt_set_local_optimizer(opt, local_opt);
}
// =============================================================================
// Defining scalar constraints
// =============================================================================
// Note: in the next two functions
// 1. The wrapper function red_func_wrap is the nlopt_func argument,
// 2. The name of the Reduce function defining the constraint is the *f_data argument,
// 3. We can't just pass c_fname to to this argument, we need the string cfun on the heap!
int32_t NLOPT_add_eq_constraint(char *c_fname, double tol) {
char *cfun = malloc(strlen(c_fname)*sizeof(char)+1);
assert(cfun != NULL);
strcpy(cfun,c_fname);
if (DEBUG) fprintf(stderr, "added '%s' equality constraint, %.3g\n", cfun, tol);
return nlopt_add_equality_constraint(opt, red_func_wrap, cfun, tol);
}
int32_t NLOPT_add_ineq_constraint(char *c_fname, double tol) {
char *cfun = malloc(strlen(c_fname)*sizeof(char)+1);
assert(cfun != NULL);
strcpy(cfun,c_fname);
if (DEBUG) fprintf(stderr, "added '%s' inequality constraint, %.3g\n", cfun, tol);
return nlopt_add_inequality_constraint(opt, red_func_wrap, cfun, tol);
}
// =============================================================================
// Defining vector-valued constraints
// =============================================================================
// This function is internal to the interface (static), and is of type nlopt_mfunc.
// It is modelled after f77_mfunc_wrap in api/f77api.c. It is used as a wrapper for
// functions that, given an n-vector 'x', return an m-vector in 'result'.
static void red_mfunc_wrap(unsigned m, double *result, unsigned n, const double *x,
double *grad, void *f_data) {
char *fn = (char *) f_data;
if (DEBUG > 1) {
fprintf(stderr, "red_mfunc_wrap: %s", fn);
if (grad) fprintf(stderr, " [G]");
fprintf(stderr, "\n");
}
// Convert the function name (string) to a symbol, push it on the stack, and
// wrap it in a quote:
PROC_push_symbol(fn);
PROC_make_function_call("quote", 1);
// Turn the array x into a Lisp list and leave it at the top of the "stack".
C_darray_to_Lisp_list(n,x);
// Wrap it in a quote:
PROC_make_function_call("quote", 1);
// Evaluate a call to the Reduce m-dimensional algebraic function fn: R^n -> R^m
int32_t r = PROC_make_function_call("call_alg_fn_list2list", 2);
PROC_lisp_eval();
if (DEBUG > 1) {
fprintf(stderr, " %s(", fn);
for (int i=0; i<n; i++) {
fprintf(stderr, "%.4g", x[i]);
if (i < n-1) fprintf(stderr, ",");
}
fprintf(stderr, ") = {");
}
// If 'grad' is NULL, the result is a an m-list, which we assign to the C
// array 'result' element-by-element. If 'grad' is non-NULL, then it points
// to an array of length m*n, and the result of 'fn' also contains a list of
// length m*n, the gradients of the constraint functions with respect to x,
// and 'grad' should be set to this list. It is assumed that βc_i/βx_j is
// stored in grad[i*n + j].
// Irrespective of 'grad', we first get the first m elements of the list and
// assign them to 'result'.
PROC_handle y = PROC_get_value();
for (int i = 0; i < m; i++) {
result[i] = PROC_floating_value(PROC_first(y));
y = PROC_rest(y);
if (DEBUG > 1) {
fprintf(stderr, "%.4g", result[i]);
if (i < m-1) fprintf(stderr, ",");
}
}
if (DEBUG > 1) fprintf(stderr, "}\n");
if (grad) {
// Now handle the last m*n elements of what 'fn' has returned
if (DEBUG > 1) fprintf(stderr, " grad = {");
for (int i = 0; i < m*n; i++) {
grad[i] = PROC_floating_value(PROC_first(y));
y = PROC_rest(y);
if (DEBUG > 1) {
fprintf(stderr, "%.4g", grad[i]);
if (i < m*n-1) fprintf(stderr, ",");
}
}
if (DEBUG > 1) fprintf(stderr, "}\n");
}
}
// Note: look at the notes for the functions for scalar constraints
int32_t NLOPT_add_eq_mconstraint(char *c_fname, int32_t m, double *tol) {
char *cfun = malloc(strlen(c_fname)*sizeof(char)+1);
assert(cfun != NULL);
strcpy(cfun,c_fname);
if (DEBUG) fprintf(stderr, "added '%s' equality m-constraint\n", cfun);
return nlopt_add_equality_mconstraint(opt, m, red_mfunc_wrap, cfun, tol);
}
int32_t NLOPT_add_ineq_mconstraint(char *c_fname, int32_t m, double *tol) {
char *cfun = malloc(strlen(c_fname)*sizeof(char)+1);
assert(cfun != NULL);
strcpy(cfun,c_fname);
if (DEBUG) fprintf(stderr, "added '%s' inequality m-constraint\n", cfun);
return nlopt_add_inequality_mconstraint(opt, m, red_mfunc_wrap, cfun, tol);
}
// =============================================================================
// Removing constraints
// =============================================================================
int32_t NLOPT_remove_eq_constraints() {
return nlopt_remove_equality_constraints(opt);
}
int32_t NLOPT_remove_ineq_constraints() {
return nlopt_remove_inequality_constraints(opt);
}
// =============================================================================
// Step size for algorithms without derivatives
// =============================================================================
int32_t NLOPT_set_initial_step(const double *dx) {
return nlopt_set_initial_step(opt, dx);
}
int32_t NLOPT_set_initial_step1(double dx) {
return nlopt_set_initial_step1(opt, dx);
}
// ============================================================================
// Stochastic search algorithms
// ============================================================================
int32_t NLOPT_set_population(int p) {
return nlopt_set_population(opt, (unsigned) p);
}
void NLOPT_srand(int64_t seed) {
nlopt_srand((unsigned long) seed);
}
| {
"alphanum_fraction": 0.6025624681,
"avg_line_length": 34.2532751092,
"ext": "c",
"hexsha": "cb8c616dbea8a952b8f1ca1122c4a6f806ec10a9",
"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": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "arthurcnorman/general",
"max_forks_repo_path": "packages/foreign/nlopt/rednlopt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b",
"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": "arthurcnorman/general",
"max_issues_repo_path": "packages/foreign/nlopt/rednlopt.c",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e8fef0cc7999fa8ab75d8fdf79ad5488047282b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "arthurcnorman/general",
"max_stars_repo_path": "packages/foreign/nlopt/rednlopt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4280,
"size": 15688
} |
#include "jfftw_complex_nd_Plan.h"
#include <fftw.h>
/*
* Class: jfftw_complex_nd_Plan
* Method: createPlan
* Signature: ([III)V
*/
JNIEXPORT void JNICALL Java_jfftw_complex_nd_Plan_createPlan( JNIEnv *env, jobject obj, jintArray dim, jint dir, jint flags )
{
jclass clazz;
jfieldID id;
jbyteArray arr;
unsigned char* carr;
int rank;
int *cdim;
if( sizeof( jdouble ) != sizeof( fftw_real ) )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/RuntimeException" ), "jdouble and fftw_real are incompatible" );
return;
}
clazz = (*env)->GetObjectClass( env, obj );
id = (*env)->GetFieldID( env, clazz, "plan", "[B" );
arr = (*env)->NewByteArray( env, sizeof( fftwnd_plan ) );
carr = (*env)->GetByteArrayElements( env, arr, 0 );
rank = (*env)->GetArrayLength( env, dim );
cdim = (*env)->GetIntArrayElements( env, dim, 0 );
(*env)->MonitorEnter( env, (*env)->FindClass( env, "jfftw/Plan" ) );
*(fftwnd_plan*)carr = fftwnd_create_plan( rank, cdim, dir, flags );
(*env)->MonitorExit( env, (*env)->FindClass( env, "jfftw/Plan" ) );
(*env)->ReleaseIntArrayElements( env, dim, cdim, 0 );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
(*env)->SetObjectField( env, obj, id, arr );
}
/*
* Class: jfftw_complex_nd_Plan
* Method: createPlanSpecific
* Signature: ([III[DI[DI)V
*/
JNIEXPORT void JNICALL Java_jfftw_complex_nd_Plan_createPlanSpecific( JNIEnv *env, jobject obj, jintArray dim, jint dir, jint flags, jdoubleArray in, jint idist, jdoubleArray out, jint odist )
{
jclass clazz;
jfieldID id;
jbyteArray arr;
unsigned char* carr;
int rank;
int *cdim;
double *cin, *cout;
if( sizeof( jdouble ) != sizeof( fftw_real ) )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/RuntimeException" ), "jdouble and fftw_real are incompatible" );
return;
}
clazz = (*env)->GetObjectClass( env, obj );
id = (*env)->GetFieldID( env, clazz, "plan", "[B" );
arr = (*env)->NewByteArray( env, sizeof( fftwnd_plan ) );
carr = (*env)->GetByteArrayElements( env, arr, 0 );
rank = (*env)->GetArrayLength( env, dim );
cdim = (*env)->GetIntArrayElements( env, dim, 0 );
cin = (*env)->GetDoubleArrayElements( env, in, 0 );
cout = (*env)->GetDoubleArrayElements( env, out, 0 );
(*env)->MonitorEnter( env, (*env)->FindClass( env, "jfftw/Plan" ) );
*(fftwnd_plan*)carr = fftwnd_create_plan_specific( rank, cdim, dir, flags, (fftw_complex*)cin, idist, (fftw_complex*)cout, odist );
(*env)->MonitorExit( env, (*env)->FindClass( env, "jfftw/Plan" ) );
(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );
(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
(*env)->SetObjectField( env, obj, id, arr );
}
/*
* Class: jfftw_complex_nd_Plan
* Method: destroyPlan
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_jfftw_complex_nd_Plan_destroyPlan( JNIEnv* env, jobject obj )
{
jclass clazz = (*env)->GetObjectClass( env, obj );
jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" );
jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );
unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );
fftwnd_destroy_plan( *(fftwnd_plan*)carr );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
(*env)->SetObjectField( env, obj, id, NULL );
}
/*
* Class: jfftw_complex_nd_Plan
* Method: transform
* Signature: ([D)[D
*/
JNIEXPORT jdoubleArray JNICALL Java_jfftw_complex_nd_Plan_transform___3D( JNIEnv* env, jobject obj, jdoubleArray in )
{
jdouble *cin, *cout;
jdoubleArray out;
int i;
jclass clazz = (*env)->GetObjectClass( env, obj );
jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" );
jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );
unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );
fftwnd_plan plan = *(fftwnd_plan*)carr;
int length = 1;
for( i = 0; i < plan->rank; ++i ) length *= plan->n[i];
if( length * 2 != (*env)->GetArrayLength( env, in ) )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length" );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
return NULL;
}
cin = (*env)->GetDoubleArrayElements( env, in, 0 );
if( plan->rank > 0 && ! plan->plans[0]->flags & FFTW_THREADSAFE )
{
// synchronization
(*env)->MonitorEnter( env, obj );
}
if( plan->is_in_place )
{
out = in;
fftwnd_one( plan, (fftw_complex*)cin, NULL );
}
else
{
out = (*env)->NewDoubleArray( env, length * 2 );
cout = (*env)->GetDoubleArrayElements( env, out, 0 );
fftwnd_one( plan, (fftw_complex*)cin, (fftw_complex*)cout );
(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );
}
if( plan->rank > 0 && ! plan->plans[0]->flags & FFTW_THREADSAFE )
{
// synchronization
(*env)->MonitorExit( env, obj );
}
(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
return out;
}
/*
* Class: jfftw_complex_nd_Plan
* Method: transform
* Signature: (I[DII[DII)V
*/
JNIEXPORT void JNICALL Java_jfftw_complex_nd_Plan_transform__I_3DII_3DII( JNIEnv *env, jobject obj, jint howmany, jdoubleArray in, jint istride, jint idist, jdoubleArray out, jint ostride, jint odist )
{
jdouble *cin, *cout;
int i;
jclass clazz = (*env)->GetObjectClass( env, obj );
jfieldID id = (*env)->GetFieldID( env, clazz, "plan", "[B" );
jbyteArray arr = (jbyteArray)(*env)->GetObjectField( env, obj, id );
unsigned char* carr = (*env)->GetByteArrayElements( env, arr, 0 );
fftwnd_plan plan = *(fftwnd_plan*)carr;
int length = 1;
for( i = 0; i < plan->rank; ++i ) length *= plan->plans[i]->n;
if( (howmany - 1) * idist * 2 + length * istride * 2 != (*env)->GetArrayLength( env, in ) )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length (in)" );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
return;
}
if( (howmany - 1) * odist * 2 + length * ostride * 2 != (*env)->GetArrayLength( env, out ) )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IndexOutOfBoundsException" ), "the Plan was created for a different length (out)" );
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
return;
}
cin = (*env)->GetDoubleArrayElements( env, in, 0 );
cout = (*env)->GetDoubleArrayElements( env, out, 0 );
if( plan->rank > 0 && ! plan->plans[0]->flags & FFTW_THREADSAFE )
{
// synchronization
(*env)->MonitorEnter( env, obj );
}
fftwnd( plan, howmany, (fftw_complex*)cin, istride, idist, (fftw_complex*)cout, ostride, odist );
if( plan->rank > 0 && ! plan->plans[0]->flags & FFTW_THREADSAFE )
{
// synchronization
(*env)->MonitorExit( env, obj );
}
(*env)->ReleaseByteArrayElements( env, arr, carr, 0 );
(*env)->ReleaseDoubleArrayElements( env, in, cin, 0 );
(*env)->ReleaseDoubleArrayElements( env, out, cout, 0 );
}
| {
"alphanum_fraction": 0.6543245175,
"avg_line_length": 32.9952830189,
"ext": "c",
"hexsha": "25e15e1f19c2bf9d4e9e7d5533edebe7bf413251",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-09T05:30:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-08T14:04:52.000Z",
"max_forks_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "CSCSI/Triana",
"max_forks_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_nd_Plan.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_issues_repo_issues_event_max_datetime": "2016-01-22T13:06:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-28T13:52:42.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "CSCSI/Triana",
"max_issues_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_nd_Plan.c",
"max_line_length": 201,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "CSCSI/Triana",
"max_stars_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_complex_nd_Plan.c",
"max_stars_repo_stars_event_max_datetime": "2019-01-15T21:45:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-02T10:12:13.000Z",
"num_tokens": 2222,
"size": 6995
} |
/*
* Gsl_vector_3: test gsl_vector
*
* Copyright (c) 2012 JΓ©rΓ©mie Decock
*
* Required: GSL library (libgsl0-dev)
* Usage: gcc gsl_vector_3.c -lgsl -lgslcblas -lm
* or: gcc gsl_vector_3.c $(pkg-config --libs gsl)
*/
#include <gsl/gsl_vector.h>
int main(int argc, char * argv[]) {
gsl_vector * v1 = gsl_vector_calloc(10);
gsl_vector * v2 = gsl_vector_calloc(10);
gsl_vector_set_all(v1, 2.0);
gsl_vector_set_all(v2, 6.0);
gsl_vector_mul(v1, v2);
gsl_vector_fprintf(stdout, v1, "%.2f");
gsl_vector_free(v1);
gsl_vector_free(v2);
return 0;
}
| {
"alphanum_fraction": 0.652613828,
"avg_line_length": 19.7666666667,
"ext": "c",
"hexsha": "eefddb4f339ba6e6e5e6d0cb3d9e811f49f40aba",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z",
"max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jeremiedecock/snippets",
"max_forks_repo_path": "c/gsl/gsl_vector_3.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jeremiedecock/snippets",
"max_issues_repo_path": "c/gsl/gsl_vector_3.c",
"max_line_length": 53,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jeremiedecock/snippets",
"max_stars_repo_path": "c/gsl/gsl_vector_3.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z",
"num_tokens": 197,
"size": 593
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_fft_complex.h>
#define REAL(z,i) ((z)[2*(i)])
#define IMAG(z,i) ((z)[2*(i)+1])
int
main (void)
{
int i;
const int n = 630;
double data[2*n];
gsl_fft_complex_wavetable * wavetable;
gsl_fft_complex_workspace * workspace;
for (i = 0; i < n; i++)
{
REAL(data,i) = 0.0;
IMAG(data,i) = 0.0;
}
data[0] = 1.0;
for (i = 1; i <= 10; i++)
{
REAL(data,i) = REAL(data,n-i) = 1.0;
}
for (i = 0; i < n; i++)
{
printf ("%d: %e %e\n", i, REAL(data,i),
IMAG(data,i));
}
printf ("\n");
wavetable = gsl_fft_complex_wavetable_alloc (n);
workspace = gsl_fft_complex_workspace_alloc (n);
for (i = 0; i < (int) wavetable->nf; i++)
{
printf ("# factor %d: %zu\n", i,
wavetable->factor[i]);
}
gsl_fft_complex_forward (data, 1, n,
wavetable, workspace);
for (i = 0; i < n; i++)
{
printf ("%d: %e %e\n", i, REAL(data,i),
IMAG(data,i));
}
gsl_fft_complex_wavetable_free (wavetable);
gsl_fft_complex_workspace_free (workspace);
return 0;
}
| {
"alphanum_fraction": 0.5093724531,
"avg_line_length": 20.1147540984,
"ext": "c",
"hexsha": "b12dc7669af4c0972aee4d206291946519f4be24",
"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/doc/examples/fftmr.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/doc/examples/fftmr.c",
"max_line_length": 50,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/fftmr.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": 396,
"size": 1227
} |
/* linalg/qr.c
*
* 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.
*/
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include "givens.c"
#include "apply_givens.c"
/* Factorise a general M x N matrix A into
*
* A = Q R
*
* where Q is orthogonal (M x M) and R is upper triangular (M x N).
*
* Q is stored as a packed set of Householder transformations in the
* strict lower triangular part of the input matrix.
*
* R is stored in the diagonal and upper triangle of the input matrix.
*
* The full matrix for Q can be obtained as the product
*
* Q = Q_k .. Q_2 Q_1
*
* where k = MIN(M,N) and
*
* Q_i = (I - tau_i * v_i * v_i')
*
* and where v_i is a Householder vector
*
* v_i = [1, m(i+1,i), m(i+2,i), ... , m(M,i)]
*
* This storage scheme is the same as in LAPACK. */
int
gsl_linalg_QR_decomp (gsl_matrix * A, gsl_vector * tau)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (tau->size != GSL_MIN (M, N))
{
GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN);
}
else
{
size_t i;
for (i = 0; i < GSL_MIN (M, N); i++)
{
/* Compute the Householder transformation to reduce the j-th
column of the matrix to a multiple of the j-th unit vector */
gsl_vector_view c_full = gsl_matrix_column (A, i);
gsl_vector_view c = gsl_vector_subvector (&(c_full.vector), i, M-i);
double tau_i = gsl_linalg_householder_transform (&(c.vector));
gsl_vector_set (tau, i, tau_i);
/* Apply the transformation to the remaining columns and
update the norms */
if (i + 1 < N)
{
gsl_matrix_view m = gsl_matrix_submatrix (A, i, i + 1, M - i, N - (i + 1));
gsl_linalg_householder_hm (tau_i, &(c.vector), &(m.matrix));
}
}
return GSL_SUCCESS;
}
}
/* Solves the system A x = b using the QR factorisation,
* R x = Q^T b
*
* to obtain x. Based on SLATEC code.
*/
int
gsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x)
{
if (QR->size1 != QR->size2)
{
GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR);
}
else if (QR->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (QR->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Copy x <- b */
gsl_vector_memcpy (x, b);
/* Solve for x */
gsl_linalg_QR_svx (QR, tau, x);
return GSL_SUCCESS;
}
}
/* Solves the system A x = b in place using the QR factorisation,
* R x = Q^T b
*
* to obtain x. Based on SLATEC code.
*/
int
gsl_linalg_QR_svx (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * x)
{
if (QR->size1 != QR->size2)
{
GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR);
}
else if (QR->size1 != x->size)
{
GSL_ERROR ("matrix size must match x/rhs size", GSL_EBADLEN);
}
else
{
/* compute rhs = Q^T b */
gsl_linalg_QR_QTvec (QR, tau, x);
/* Solve R x = rhs, storing x in-place */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);
return GSL_SUCCESS;
}
}
/* Find the least squares solution to the overdetermined system
*
* A x = b
*
* for M >= N using the QR factorization A = Q R.
*/
int
gsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x, gsl_vector * residual)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (M < N)
{
GSL_ERROR ("QR matrix must have M>=N", GSL_EBADLEN);
}
else if (M != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (N != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else if (M != residual->size)
{
GSL_ERROR ("matrix size must match residual size", GSL_EBADLEN);
}
else
{
gsl_matrix_const_view R = gsl_matrix_const_submatrix (QR, 0, 0, N, N);
gsl_vector_view c = gsl_vector_subvector(residual, 0, N);
gsl_vector_memcpy(residual, b);
/* compute rhs = Q^T b */
gsl_linalg_QR_QTvec (QR, tau, residual);
/* Solve R x = rhs */
gsl_vector_memcpy(x, &(c.vector));
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &(R.matrix), x);
/* Compute residual = b - A x = Q (Q^T b - R x) */
gsl_vector_set_zero(&(c.vector));
gsl_linalg_QR_Qvec(QR, tau, residual);
return GSL_SUCCESS;
}
}
int
gsl_linalg_QR_Rsolve (const gsl_matrix * QR, const gsl_vector * b, gsl_vector * x)
{
if (QR->size1 != QR->size2)
{
GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR);
}
else if (QR->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (QR->size2 != x->size)
{
GSL_ERROR ("matrix size must match x size", GSL_EBADLEN);
}
else
{
/* Copy x <- b */
gsl_vector_memcpy (x, b);
/* Solve R x = b, storing x in-place */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_QR_Rsvx (const gsl_matrix * QR, gsl_vector * x)
{
if (QR->size1 != QR->size2)
{
GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR);
}
else if (QR->size1 != x->size)
{
GSL_ERROR ("matrix size must match rhs size", GSL_EBADLEN);
}
else
{
/* Solve R x = b, storing x in-place */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_R_solve (const gsl_matrix * R, const gsl_vector * b, gsl_vector * x)
{
if (R->size1 != R->size2)
{
GSL_ERROR ("R matrix must be square", GSL_ENOTSQR);
}
else if (R->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (R->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Copy x <- b */
gsl_vector_memcpy (x, b);
/* Solve R x = b, storing x inplace in b */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_R_svx (const gsl_matrix * R, gsl_vector * x)
{
if (R->size1 != R->size2)
{
GSL_ERROR ("R matrix must be square", GSL_ENOTSQR);
}
else if (R->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Solve R x = b, storing x inplace in b */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);
return GSL_SUCCESS;
}
}
/* Form the product Q^T v from a QR factorized matrix
*/
int
gsl_linalg_QR_QTvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (tau->size != GSL_MIN (M, N))
{
GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN);
}
else if (v->size != M)
{
GSL_ERROR ("vector size must be N", GSL_EBADLEN);
}
else
{
size_t i;
/* compute Q^T v */
for (i = 0; i < GSL_MIN (M, N); i++)
{
gsl_vector_const_view c = gsl_matrix_const_column (QR, i);
gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector), i, M - i);
gsl_vector_view w = gsl_vector_subvector (v, i, M - i);
double ti = gsl_vector_get (tau, i);
gsl_linalg_householder_hv (ti, &(h.vector), &(w.vector));
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_QR_Qvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (tau->size != GSL_MIN (M, N))
{
GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN);
}
else if (v->size != M)
{
GSL_ERROR ("vector size must be N", GSL_EBADLEN);
}
else
{
size_t i;
/* compute Q^T v */
for (i = GSL_MIN (M, N); i-- > 0;)
{
gsl_vector_const_view c = gsl_matrix_const_column (QR, i);
gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector),
i, M - i);
gsl_vector_view w = gsl_vector_subvector (v, i, M - i);
double ti = gsl_vector_get (tau, i);
gsl_linalg_householder_hv (ti, &h.vector, &w.vector);
}
return GSL_SUCCESS;
}
}
/* Form the product Q^T A from a QR factorized matrix */
int
gsl_linalg_QR_QTmat (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (tau->size != GSL_MIN (M, N))
{
GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN);
}
else if (A->size1 != M)
{
GSL_ERROR ("matrix must have M rows", GSL_EBADLEN);
}
else
{
size_t i;
/* compute Q^T A */
for (i = 0; i < GSL_MIN (M, N); i++)
{
gsl_vector_const_view c = gsl_matrix_const_column (QR, i);
gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector), i, M - i);
gsl_matrix_view m = gsl_matrix_submatrix(A, i, 0, M - i, A->size2);
double ti = gsl_vector_get (tau, i);
gsl_linalg_householder_hm (ti, &(h.vector), &(m.matrix));
}
return GSL_SUCCESS;
}
}
/* Form the orthogonal matrix Q from the packed QR matrix */
int
gsl_linalg_QR_unpack (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * R)
{
const size_t M = QR->size1;
const size_t N = QR->size2;
if (Q->size1 != M || Q->size2 != M)
{
GSL_ERROR ("Q matrix must be M x M", GSL_ENOTSQR);
}
else if (R->size1 != M || R->size2 != N)
{
GSL_ERROR ("R matrix must be M x N", GSL_ENOTSQR);
}
else if (tau->size != GSL_MIN (M, N))
{
GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN);
}
else
{
size_t i, j;
/* Initialize Q to the identity */
gsl_matrix_set_identity (Q);
for (i = GSL_MIN (M, N); i-- > 0;)
{
gsl_vector_const_view c = gsl_matrix_const_column (QR, i);
gsl_vector_const_view h = gsl_vector_const_subvector (&c.vector,
i, M - i);
gsl_matrix_view m = gsl_matrix_submatrix (Q, i, i, M - i, M - i);
double ti = gsl_vector_get (tau, i);
gsl_linalg_householder_hm (ti, &h.vector, &m.matrix);
}
/* Form the right triangular matrix R from a packed QR matrix */
for (i = 0; i < M; i++)
{
for (j = 0; j < i && j < N; j++)
gsl_matrix_set (R, i, j, 0.0);
for (j = i; j < N; j++)
gsl_matrix_set (R, i, j, gsl_matrix_get (QR, i, j));
}
return GSL_SUCCESS;
}
}
/* Update a QR factorisation for A= Q R , A' = A + u v^T,
* Q' R' = QR + u v^T
* = Q (R + Q^T u v^T)
* = Q (R + w v^T)
*
* where w = Q^T u.
*
* Algorithm from Golub and Van Loan, "Matrix Computations", Section
* 12.5 (Updating Matrix Factorizations, Rank-One Changes)
*/
int
gsl_linalg_QR_update (gsl_matrix * Q, gsl_matrix * R,
gsl_vector * w, const gsl_vector * v)
{
const size_t M = R->size1;
const size_t N = R->size2;
if (Q->size1 != M || Q->size2 != M)
{
GSL_ERROR ("Q matrix must be M x M if R is M x N", GSL_ENOTSQR);
}
else if (w->size != M)
{
GSL_ERROR ("w must be length M if R is M x N", GSL_EBADLEN);
}
else if (v->size != N)
{
GSL_ERROR ("v must be length N if R is M x N", GSL_EBADLEN);
}
else
{
size_t j, k;
double w0;
/* Apply Given's rotations to reduce w to (|w|, 0, 0, ... , 0)
J_1^T .... J_(n-1)^T w = +/- |w| e_1
simultaneously applied to R, H = J_1^T ... J^T_(n-1) R
so that H is upper Hessenberg. (12.5.2) */
for (k = M - 1; k > 0; k--) /* loop from k = M-1 to 1 */
{
double c, s;
double wk = gsl_vector_get (w, k);
double wkm1 = gsl_vector_get (w, k - 1);
create_givens (wkm1, wk, &c, &s);
apply_givens_vec (w, k - 1, k, c, s);
apply_givens_qr (M, N, Q, R, k - 1, k, c, s);
}
w0 = gsl_vector_get (w, 0);
/* Add in w v^T (Equation 12.5.3) */
for (j = 0; j < N; j++)
{
double r0j = gsl_matrix_get (R, 0, j);
double vj = gsl_vector_get (v, j);
gsl_matrix_set (R, 0, j, r0j + w0 * vj);
}
/* Apply Givens transformations R' = G_(n-1)^T ... G_1^T H
Equation 12.5.4 */
for (k = 1; k < GSL_MIN(M,N+1); k++)
{
double c, s;
double diag = gsl_matrix_get (R, k - 1, k - 1);
double offdiag = gsl_matrix_get (R, k, k - 1);
create_givens (diag, offdiag, &c, &s);
apply_givens_qr (M, N, Q, R, k - 1, k, c, s);
gsl_matrix_set (R, k, k - 1, 0.0); /* exact zero of G^T */
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_QR_QRsolve (gsl_matrix * Q, gsl_matrix * R, const gsl_vector * b, gsl_vector * x)
{
const size_t M = R->size1;
const size_t N = R->size2;
if (M != N)
{
return GSL_ENOTSQR;
}
else if (Q->size1 != M || b->size != M || x->size != M)
{
return GSL_EBADLEN;
}
else
{
/* compute sol = Q^T b */
gsl_blas_dgemv (CblasTrans, 1.0, Q, b, 0.0, x);
/* Solve R x = sol, storing x in-place */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5669803019,
"avg_line_length": 24.6627712855,
"ext": "c",
"hexsha": "126a382305932a2d53827b9530e155121ad03d5d",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/qr.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/qr.c",
"max_line_length": 130,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/linalg/qr.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": 4550,
"size": 14773
} |
#define _XOPEN_SOURCE 600
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
#include <time.h>
void
setupInitialSeed(
int id,
gsl_rng *rgen)
{
struct timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
gsl_rng_set( rgen, (unsigned long int) ( round( spec.tv_nsec / 1.0e6 ) + 20 * id ) );
}
void createInitialSample(
double *x,
long N,
gsl_rng *rgen,
int state_dim )
{
for ( long i = 0; i < N; i++)
for ( int d = 0; d < state_dim; d++ )
x[ state_dim * i + d ] = gsl_ran_gaussian_ziggurat( rgen, 1.0 );
}
| {
"alphanum_fraction": 0.6,
"avg_line_length": 16.5277777778,
"ext": "c",
"hexsha": "c84073fbc63e0ecd3c94f6db8b002880430c111f",
"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": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "heinekmp/AIRPF",
"max_forks_repo_path": "src/randomisation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"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": "heinekmp/AIRPF",
"max_issues_repo_path": "src/randomisation.c",
"max_line_length": 87,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "heinekmp/AIRPF",
"max_stars_repo_path": "src/randomisation.c",
"max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z",
"num_tokens": 206,
"size": 595
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_drotmg (double *d1, double *d2, double *b1, const double b2, double *P)
{
#define BASE double
#include "source_rotmg.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7196261682,
"avg_line_length": 17.8333333333,
"ext": "c",
"hexsha": "d92358ff70295d6de5e42ead0e980dafb956eb1b",
"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/drotmg.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/drotmg.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/drotmg.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": 71,
"size": 214
} |
/*
* Copyright 2020 Makani Technologies LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SIM_PHYSICS_WIND_H_
#define SIM_PHYSICS_WIND_H_
#include <gsl/gsl_vector.h>
#include <string>
#include "common/c_math/mat3.h"
#include "common/c_math/vec3.h"
#include "common/macros.h"
// Functions related to wind shear and turbulence.
//
// Many of these functions define a "mean wind frame" denoted by
// the "mw" subscript. This should not be confused with the
// wind frame defined in sim/physics/aero_frame.h, which related to
// the apparent wind at a body.
//
// The origin of the mean wind frame lies at ground level directly
// below the ground station origin. The axes are defined by:
// x: Points along the predominate wind vector.
// y: Completes a right-handed frame.
// z: Points up.
// These are chosen to be consistent with NREL's TurbSim software
// and various IEC standards.
namespace sim {
namespace physics {
namespace wind {
double CalcWindShear(double height_agl, double ref_height_agl,
double ref_wind_speed, double wind_shear_exponent);
class FrozenTurbulenceWindDatabase {
friend class FrozenTurbulenceWindDatabaseTest;
public:
FrozenTurbulenceWindDatabase(double t0, double y0,
const std::string &filename);
~FrozenTurbulenceWindDatabase() {
gsl_vector_free(u_);
gsl_vector_free(v_);
gsl_vector_free(w_);
}
void CalcWind(double t, const Vec3 &pos_mw, Vec3 *wind_mw) const;
private:
// Time offset [s] to apply. At t = 0, positions whose x coordinate
// (in the mw frame) is zero will fetch the database entry given at
// time t0_.
double t0_;
// Y offset [m] to apply from the center of the wind database.
double y0_;
// Mean wind speed [m/s] that sets the rate at which the database
// is "advected" along the mean wind coordinate x axis.
double mean_wind_speed_;
// Number [#] of t, y, and z grid points.
int32_t num_t_, num_y_, num_z_;
// Duration [s], width [m], and height [m] of the grid defining
// the database.
double duration_, width_, height_;
// Vectors storing the components of the wind velocity [m/s]. Each
// vector has num_t * num_y * num_z elements. The u, v, and w
// components point along the x, y, and z axes of the mean wind
// coordinate system.
gsl_vector *u_;
gsl_vector *v_;
gsl_vector *w_;
DISALLOW_COPY_AND_ASSIGN(FrozenTurbulenceWindDatabase);
};
enum class IecTurbulenceCategory { kA, kB, kC };
enum class IecWindTurbineClass { kI, kII, kIII };
class IecWindModel {
public:
IecWindModel(double hub_height_agl__, double rotor_diameter,
double hub_wind_speed, IecTurbulenceCategory turbulence_category,
IecWindTurbineClass wind_turbine_class);
double hub_height_agl() const { return hub_height_agl_; }
double ntm_sigma_1() const { return ntm_sigma_1_; }
double ewm_sigma_1() const { return ewm_sigma_1_; }
double etm_sigma_1() const { return etm_sigma_1_; }
// IEC 61400-1 Design situations.
// IEC 61400-1 Sec. 6.3.1.2 -- Normal Wind Profile Model (NWP).
double CalcNormalWindProfile(double height_agl) const;
// IEC 61400-1 Sec. 6.3.2.1 -- Extreme wind speed model (EWM).
double CalcExtremeWindSpeed1YearRecurrence(double height_agl,
bool is_turbulent) const;
double CalcExtremeWindSpeed50YearRecurrence(double height_agl,
bool is_turbulent) const;
// IEC 61400-1 Sec. 6.3.2.2 -- Extreme Operating Gust (EOG).
double CalcExtremeOperatingGust(double t, double height_agl) const;
// IEC 61400-1 Sec. 6.3.2.4 -- Extreme direction change (EDC).
double CalcExtremeDirectionChange(double t) const;
// IEC 61400-1 Sec. 6.3.2.5 -- Extreme coherent gust with direction
// change (ECD).
double CalcExtremeCoherentGustWithDirectionChange(
double t, double height_agl, double *wind_direction) const;
// IEC 61400-1 Sec. 6.3.2.6 -- Extreme wind shear (EWS).
double CalcExtremeWindShearVertical(double t, double height_agl) const;
double CalcExtremeWindShearHorizontal(double t, double height_agl,
double y) const;
private:
// Hub height above ground level [m].
const double hub_height_agl_;
// Rotor diameter [m].
const double rotor_diameter_;
// Nominal wind speed [m/s] at hub height.
const double hub_wind_speed_;
// Reference wind speed [m/s], see IEC 61400-1 Sec. 6.2.
const double v_ref_;
// Expected value of the turbulence intensity [#] at 15 m/s.
const double I_ref_;
// Longitudinal turbulence scale parameter [#].
const double lambda_1_;
// Normal turbulence model (NTM) standard deviation [m/s].
const double ntm_sigma_1_;
// Extreme wind model (EWM) standard deviation [m/s].
const double ewm_sigma_1_;
// Extreme turbulence model (ETM) standard deviation [m/s].
const double etm_sigma_1_;
};
} // namespace wind
} // namespace physics
} // namespace sim
#endif // SIM_PHYSICS_WIND_H_
| {
"alphanum_fraction": 0.7059878093,
"avg_line_length": 33.0059171598,
"ext": "h",
"hexsha": "b015b6d5ec3c7d87477c35ed2c75107b00fe7539",
"lang": "C",
"max_forks_count": 107,
"max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z",
"max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "leozz37/makani",
"max_forks_repo_path": "sim/physics/wind.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "leozz37/makani",
"max_issues_repo_path": "sim/physics/wind.h",
"max_line_length": 80,
"max_stars_count": 1178,
"max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "leozz37/makani",
"max_stars_repo_path": "sim/physics/wind.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z",
"num_tokens": 1470,
"size": 5578
} |
#pragma once
#include <array>
#include <variant>
#include <gsl/gsl-lite.hpp>
#include <clrie/method_info.h>
#include <clrie/instruction_factory.h>
#include <corhdr.h>
#include "cil.h"
#include "signature.h"
namespace appmap {
template <typename T>
constexpr COR_SIGNATURE type_signature() {
if constexpr (std::is_same_v<T, void>) {
return ELEMENT_TYPE_VOID;
} else if constexpr (std::is_same_v<T, int32_t>) {
return ELEMENT_TYPE_I4;
} else if constexpr (std::is_same_v<T, int64_t>) {
return ELEMENT_TYPE_I8;
} else if constexpr (std::is_same_v<T, uint32_t>) {
return ELEMENT_TYPE_U4;
} else if constexpr (std::is_same_v<T, uint64_t>) {
return ELEMENT_TYPE_U8;
} else if constexpr (std::is_same_v<T, char *> || std::is_same_v<T, const char *>) {
return ELEMENT_TYPE_STRING;
} else if constexpr (std::is_pointer_v<T>) {
static_assert(sizeof(void *) == 8);
return ELEMENT_TYPE_I8;
} else if constexpr (std::is_same_v<T, bool>) {
return ELEMENT_TYPE_BOOLEAN;
} else {
static_assert(std::is_same_v<T, void>, "unhandled native type");
}
}
template <typename F>
struct func_traits;
template <typename Ret, typename... Args>
struct func_traits<Ret(*)(Args...)>
{
static constexpr std::size_t arity = sizeof...(Args);
static constexpr std::array<COR_SIGNATURE, 3 + arity> signature = {
IMAGE_CEE_UNMANAGED_CALLCONV_STDCALL,
arity,
type_signature<Ret>(),
type_signature<Args>()...
};
};
template <typename C, typename Ret, typename... Args>
struct func_traits<Ret(C::*)(Args...)>
{
using instance_type = C;
static constexpr std::size_t arity = sizeof...(Args);
static constexpr std::array<COR_SIGNATURE, 4 + arity> signature = {
IMAGE_CEE_UNMANAGED_CALLCONV_STDCALL,
arity + 1,
type_signature<Ret>,
type_signature<C*>,
type_signature<Args>...
};
};
struct instrumentation : public clrie::instruction_factory {
instrumentation(clrie::method_info method_info) :
clrie::instruction_factory(method_info.instruction_factory()),
method(method_info),
module(method.module_info()),
module_id(module.module_id()),
metadata(module.meta_data_emit()),
type_factory(module.create_type_factory()),
locals(method.get(&IMethodInfo::GetLocalVariables))
{}
clrie::method_info method;
clrie::module_info module;
const ModuleID module_id;
com::ptr<IMetaDataEmit> metadata;
com::ptr<ITypeCreator> type_factory;
com::ptr<ILocalVariableCollection> locals;
static com::ptr<ISignatureBuilder> signature_builder;
template <class F>
instruction_sequence make_call(F f) const {
return make_call_sig(reinterpret_cast<void *>(f), gsl::make_span(func_traits<F>::signature));
}
instruction_sequence create_call_to_string(const clrie::type &type) const noexcept;
// Note capture_value takes a reference; in case of a composite type, it dereferences
// it to a primitive that can be then passed onto the correct native function.
// The argument is updated to reflect the resulting simple type.
instruction_sequence capture_value(clrie::type &type) const noexcept;
template <typename T>
uint64_t add_local()
{
auto t = type_factory.get(&ITypeCreator::FromCorElement, static_cast<CorElementType>(type_signature<T>()));
return locals.get(&ILocalVariableCollection::AddLocal, t);
}
// emit metadata and return reference tokens
mdAssemblyRef assembly_reference(const char16_t *assembly);
mdTypeRef type_reference(mdAssemblyRef assembly, const char16_t *type);
mdTypeRef type_reference(const char16_t *assembly, const char16_t *type) {
return type_reference(assembly_reference(assembly), type);
}
mdMemberRef member_reference(mdTypeRef type, const char16_t *member,
gsl::span<const COR_SIGNATURE> signature);
mdMemberRef member_reference(mdAssemblyRef assembly, const char16_t *type,
const char16_t *member, gsl::span<const COR_SIGNATURE> signature) {
return member_reference(type_reference(assembly, type), member, signature);
}
mdMemberRef member_reference(const char16_t *assembly, const char16_t *type,
const char16_t *member, gsl::span<const COR_SIGNATURE> signature) {
return member_reference(type_reference(assembly, type), member, signature);
}
mdTypeDef define_type(const char16_t *name);
mdFieldDef define_field(mdTypeDef type, const char16_t *name, gsl::span<const COR_SIGNATURE> signature);
mdMethodDef define_method(
mdTypeDef type,
const char16_t *name,
gsl::span<const COR_SIGNATURE> signature,
std::initializer_list<appmap::signature::type> locals,
std::vector<cil::instruction> code
);
mdMethodDef define_method(mdTypeDef type, const char16_t *name, gsl::span<const COR_SIGNATURE> signature, std::vector<cil::instruction> code) {
return define_method(type, name, signature, {}, std::move(code));
}
template <class Ret, class... Args>
mdTypeSpec native_type(Ret (*)(Args...)) {
constexpr auto sig = func_traits<Ret(*)(Args...)>::signature;
return metadata.get(&IMetaDataEmit::GetTokenFromSig, sig.data(), sig.size());
}
mdTypeSpec type_token(gsl::span<const COR_SIGNATURE> sig) {
return metadata.get(&IMetaDataEmit::GetTokenFromTypeSpec, sig.data(), sig.size());
}
protected:
instruction_sequence make_call_sig(void *fn, gsl::span<const COR_SIGNATURE> signature) const;
};
}
| {
"alphanum_fraction": 0.6393549438,
"avg_line_length": 38.8544303797,
"ext": "h",
"hexsha": "e39ac320525788df14d3974f401af822a44a7f16",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-24T02:05:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-24T02:05:16.000Z",
"max_forks_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "applandinc/appmap-dotnet",
"max_forks_repo_path": "source/instrumentation.h",
"max_issues_count": 18,
"max_issues_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307",
"max_issues_repo_issues_event_max_datetime": "2021-08-22T16:45:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-28T22:32:05.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "applandinc/appmap-dotnet",
"max_issues_repo_path": "source/instrumentation.h",
"max_line_length": 151,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "applandinc/appmap-dotnet",
"max_stars_repo_path": "source/instrumentation.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-24T02:04:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-11T04:59:58.000Z",
"num_tokens": 1336,
"size": 6139
} |
/* BalSelSims.c
Simulation of balancing selection simulation with sampling (finite population effects)
Selection; reproduction; mutation based on deterministic recursions, then sampling
Repeats for 'Length' generations
Simulation uses routines found with the GNU Scientific Library (GSL)
(http://www.gnu.org/software/gsl/)
Since GSL is distributed under the GNU General Public License
(http://www.gnu.org/copyleft/gpl.html), you must download it
separately from this file.
This program can be compiled in e.g. GCC using a command like:
gcc BalSelSims -lm -lgsl -lgslcblas -I/usr/local/include -L/usr/local/lib BalSelSims.c
Then run by executing:
./BalSelSims N s rec sex self gc reps
Where:
- N is the population size
- s is the fitness disadvantage of homozygotes
- rec is recombination rate
- sex is rate of sex (a value between 0 = obligate asex, and 1 = obligate sex)
- self is selfing rate
- gc is gene conversion
- reps is how many times to introduce linked neutral allele
Note that haplotypes are defined as:
x1 = ab
x2 = Ab
x3 = aB
x4 = AB
Genotypes defined as:
g11 = g1 = ab/ab
g12 = g2 = Ab/ab
g13 = g3 = aB/ab
g14 = g4 = AB/ab
g22 = g5 = Ab/Ab
g23 = g6 = Ab/aB
g24 = g7 = Ab/AB
g33 = g8 = aB/aB
g34 = g9 = aB/AB
g44 = g10 = AB/AB
*/
/* Preprocessor statements */
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Function prototypes */
void geninit(double *geninit);
void selection(double *geninit);
void reproduction(double *geninit);
void gconv(double *geninit);
void neutinit(double *geninit,const gsl_rng *r);
double ncheck(double *geninit);
double pcheck(double *geninit);
/* Global variable declaration */
unsigned int N = 0; /* Pop size */
double s = 0; /* Fitness disadvantage of homozyogtes */
double rec = 0; /* Recombination rate */
double sex = 0; /* Rate of sexual reproduction */
double self = 0; /* Rate of self-fertilisation */
double gc = 0; /* Rate of gene conversion */
/* Main program */
int main(int argc, char *argv[]){
unsigned int g, i; /* Counters. Reps counter, geno counter */
unsigned int reps; /* Length of simulation (no. of introductions of neutral site) */
double Bcheck = 0; /* Frequency of B after each reproduction */
double Acheck = 0; /* Frequency of polymorphism */
double Hsum = 0; /* Summed heterozygosity over transit time of neutral allele */
/* GSL random number definitions */
const gsl_rng_type * T;
gsl_rng * r;
/* This reads in data from command line. */
if(argc != 8){
fprintf(stderr,"Invalid number of input values.\n");
exit(1);
}
N = strtod(argv[1],NULL);
s = strtod(argv[2],NULL);
rec = strtod(argv[3],NULL);
sex = strtod(argv[4],NULL);
self = strtod(argv[5],NULL);
gc = strtod(argv[6],NULL);
reps = strtod(argv[7],NULL);
/* Arrays definition and memory assignment */
double *genotype = calloc(10,sizeof(double)); /* Genotype frequencies */
unsigned int *gensamp = calloc(10,sizeof(unsigned int)); /* New population samples */
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
/* Initialising genotypes */
geninit(genotype);
/* Run simulation for 2000 generations to create a burn in */
for(g = 0; g < 2000; g++){
/* Selection routine */
selection(genotype);
/* Reproduction routine */
reproduction(genotype);
/* Gene conversion routine */
gconv(genotype);
/* Sampling based on new frequencies */
gsl_ran_multinomial(r,10,N,genotype,gensamp);
for(i = 0; i < 10; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
/* Printing out results (for testing) */
/*
for(i = 0; i < 10; i++){
printf("%.10lf ", *(genotype + i));
}
printf("\n");
*/
}
/* Reintroducing neutral genotype, resetting hap sum */
neutinit(genotype,r);
Bcheck = ncheck(genotype);
Hsum = Bcheck*(1-Bcheck);
/* printf("%.10lf %.10lf\n",Bcheck,Hsum); */
/* Introduce and track neutral mutations 'reps' times */
g = 0;
while(g < reps){
/* Selection routine */
selection(genotype);
/* Reproduction routine */
reproduction(genotype);
/* Gene conversion routine */
gconv(genotype);
/* Sampling based on new frequencies */
gsl_ran_multinomial(r,10,N,genotype,gensamp);
for(i = 0; i < 10; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
/* Checking state of haplotypes: if B fixed reset so can start fresh next time */
Bcheck = ncheck(genotype);
Hsum += Bcheck*(1-Bcheck);
/* printf("%.10lf %.10lf\n",Bcheck,Hsum); */
/* If polymorphism fixed then abandon simulation */
Acheck = pcheck(genotype);
if(Acheck == 0){
g = reps;
}
if(Bcheck == 0 || Bcheck == 1){
printf("%.10lf\n",Hsum);
g++;
/* printf("Rep Number %d\n",g); */
if(Bcheck == 1){
/* Reset genotypes so B becomes ancestral allele */
*(genotype + 0) = *(genotype + 7);
*(genotype + 1) = *(genotype + 8);
*(genotype + 4) = *(genotype + 9);
*(genotype + 7) = 0;
*(genotype + 8) = 0;
*(genotype + 9) = 0;
}
/* Reintroducing neutral genotype, resetting hap sum */
neutinit(genotype,r);
Bcheck = ncheck(genotype);
Hsum = Bcheck*(1-Bcheck);
}
} /* End of simulation */
/* Freeing memory and wrapping up */
gsl_rng_free(r);
free(gensamp);
free(genotype);
/* printf("The End!\n"); */
return 0;
}
/* Initialising genotypes */
void geninit(double *geninit){
/* Basic idea: before neutral mutation introduced, g0 = 1/4; g1 = 1/2; g4 = 1/4. Deterministic frequencies. */
*(geninit + 0) = 0.25;
*(geninit + 1) = 0.50;
*(geninit + 2) = 0;
*(geninit + 3) = 0;
*(geninit + 4) = 0.25;
*(geninit + 5) = 0;
*(geninit + 6) = 0;
*(geninit + 7) = 0;
*(geninit + 8) = 0;
*(geninit + 9) = 0;
} /* End of gen initiation routine */
/* Initialising NEUTRAL allele */
void neutinit(double *geninit, const gsl_rng *r){
double *probin = calloc(4,sizeof(double)); /* Probability inputs, determine location of neutral allele */
unsigned int *probout = calloc(4,sizeof(unsigned int)); /* Output from multinomial sampling */
/* Basic idea: g11 at freq p^2; g12 at freq 2pq; g22 at freq q^2.
So weighted sampling to determine which genotype the neutral allele arises on
*/
/* Prob definitions */
*(probin + 0) = *(geninit + 0);
*(probin + 1) = (*(geninit + 1))/2.0;
*(probin + 2) = (*(geninit + 1))/2.0;
*(probin + 3) = *(geninit + 4);
gsl_ran_multinomial(r,4,1,probin,probout);
/* Redefining genotypes depending on outcome */
if(*(probout + 0) == 1){
*(geninit + 0) = (*(geninit + 0)) - 1/(1.0*N);
*(geninit + 2) = (*(geninit + 2)) + 1/(1.0*N);
}
else if(*(probout + 1) == 1){
*(geninit + 1) = (*(geninit + 1)) - 1/(1.0*N);
*(geninit + 3) = (*(geninit + 3)) + 1/(1.0*N);
}
else if(*(probout + 2) == 1){
*(geninit + 1) = (*(geninit + 1)) - 1/(1.0*N);
*(geninit + 5) = (*(geninit + 5)) + 1/(1.0*N);
}
else if(*(probout + 3) == 1){
*(geninit + 4) = (*(geninit + 4)) - 1/(1.0*N);
*(geninit + 6) = (*(geninit + 6)) + 1/(1.0*N);
}
free(probout);
free(probin);
} /* End of gen initiation routine */
/* Selection routine */
void selection(double *geninit){
double Waa, WAa, WAA; /* Fitness of locus A (bal sel locus) */
double Wmean; /* Mean fitness */
Waa = 1-s;
WAa = 1;
WAA = 1-s;
/* Mean fitness calculation */
Wmean = ((*(geninit + 0))*Waa) + ((*(geninit + 1))*WAa) + ((*(geninit + 2))*Waa) + ((*(geninit + 3))*WAa) + ((*(geninit + 4))*WAA) + ((*(geninit + 5))*WAa) + ((*(geninit + 6))*WAA) + ((*(geninit + 7))*Waa) + ((*(geninit + 8))*WAa) + ((*(geninit + 9))*WAA);
/* Changing frequencies by selection */
*(geninit + 0) = ((*(geninit + 0))*Waa)/Wmean;
*(geninit + 1) = ((*(geninit + 1))*WAa)/Wmean;
*(geninit + 2) = ((*(geninit + 2))*Waa)/Wmean;
*(geninit + 3) = ((*(geninit + 3))*WAa)/Wmean;
*(geninit + 4) = ((*(geninit + 4))*WAA)/Wmean;
*(geninit + 5) = ((*(geninit + 5))*WAa)/Wmean;
*(geninit + 6) = ((*(geninit + 6))*WAA)/Wmean;
*(geninit + 7) = ((*(geninit + 7))*Waa)/Wmean;
*(geninit + 8) = ((*(geninit + 8))*WAa)/Wmean;
*(geninit + 9) = ((*(geninit + 9))*WAA)/Wmean;
} /* End of selection routine */
/* Reproduction routine */
void reproduction(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;
/* Genotype frequencies after sex (outcross and selfing) */
double g11SX, g12SX, g13SX, g14SX, g22SX, g23SX, g24SX, g33SX, g34SX, g44SX;
/* Genotype frequencies after ASEX */
double g11AS, g12AS, g13AS, g14AS, g22AS, g23AS, g24AS, g33AS, g34AS, g44AS;
/* Haplotypes */
double x1, x2, x3, x4;
/* Initial definition of genotypes */
g11s = *(geninit + 0);
g12s = *(geninit + 1);
g13s = *(geninit + 2);
g14s = *(geninit + 3);
g22s = *(geninit + 4);
g23s = *(geninit + 5);
g24s = *(geninit + 6);
g33s = *(geninit + 7);
g34s = *(geninit + 8);
g44s = *(geninit + 9);
/* Baseline change in haplotype frequencies */
x1 = g11s + (g12s + g13s + g14s)/2.0 - ((g14s - g23s)*rec)/2.0;
x2 = g22s + (g12s + g23s + g24s)/2.0 + ((g14s - g23s)*rec)/2.0;
x3 = g33s + (g13s + g23s + g34s)/2.0 + ((g14s - g23s)*rec)/2.0;
x4 = g44s + (g14s + g24s + g34s)/2.0 - ((g14s - g23s)*rec)/2.0;
/* Change in SEXUAL frequencies (both outcrossing and selfing) */
g11SX = (g11s + (g12s + g13s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self*sex + (1 - self)*pow(x1,2)*sex;
g22SX = (g22s + (g12s + g24s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self*sex + (1 - self)*pow(x2,2)*sex;
g33SX = (g33s + (g13s + g34s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self*sex + (1 - self)*pow(x3,2)*sex;
g44SX = (g44s + (g24s + g34s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self*sex + (1 - self)*pow(x4,2)*sex;
g12SX = ((g12s + (g14s + g23s)*(1 - rec)*rec)*self*sex)/2.0 + 2.0*(1 - self)*x1*x2*sex;
g13SX = ((g13s + (g14s + g23s)*(1 - rec)*rec)*self*sex)/2.0 + 2.0*(1 - self)*x1*x3*sex;
g14SX = ((g14s*pow((1 - rec),2) + g23s*pow(rec,2))*self*sex)/2.0 + 2.0*(1 - self)*x1*x4*sex;
g23SX = ((g23s*pow((1 - rec),2) + g14s*pow(rec,2))*self*sex)/2.0 + 2.0*(1 - self)*x2*x3*sex;
g24SX = ((g24s + (g14s + g23s)*(1 - rec)*rec)*self*sex)/2.0 + 2.0*(1 - self)*x2*x4*sex;
g34SX = ((g34s + (g14s + g23s)*(1 - rec)*rec)*self*sex)/2.0 + 2.0*(1 - self)*x3*x4*sex;
/* Change in ASEXUAL frequencies */
g11AS = g11s*(1 - sex);
g12AS = g12s*(1 - sex);
g13AS = g13s*(1 - sex);
g14AS = g14s*(1 - sex);
g22AS = g22s*(1 - sex);
g23AS = g23s*(1 - sex);
g24AS = g24s*(1 - sex);
g33AS = g33s*(1 - sex);
g34AS = g34s*(1 - sex);
g44AS = g44s*(1 - sex);
/* Combining to give overall frequency change following reproduction */
*(geninit + 0) = g11AS + g11SX;
*(geninit + 1) = g12AS + g12SX;
*(geninit + 2) = g13AS + g13SX;
*(geninit + 3) = g14AS + g14SX;
*(geninit + 4) = g22AS + g22SX;
*(geninit + 5) = g23AS + g23SX;
*(geninit + 6) = g24AS + g24SX;
*(geninit + 7) = g33AS + g33SX;
*(geninit + 8) = g34AS + g34SX;
*(geninit + 9) = g44AS + g44SX;
} /* End of reproduction routine */
/* Gene conversion routine */
void gconv(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double g11r, g12r, g13r, g14r, g22r, g23r, g24r, g33r, g34r, g44r;
/* Frequencies after gene conversion */
double g11gc, g12gc, g13gc, g14gc, g22gc, g23gc, g24gc, g33gc, g34gc, g44gc;
/* Initial definition of genotypes */
g11r = *(geninit + 0);
g12r = *(geninit + 1);
g13r = *(geninit + 2);
g14r = *(geninit + 3);
g22r = *(geninit + 4);
g23r = *(geninit + 5);
g24r = *(geninit + 6);
g33r = *(geninit + 7);
g34r = *(geninit + 8);
g44r = *(geninit + 9);
/* Gene conversion equations */
g11gc = g11r + (gc*g12r)/4.0 + (gc*g13r)/4.0;
g12gc = g12r*(1 - gc/2.0) + ((g14r + g23r)*gc)/4.0;
g13gc = g13r*(1 - gc/2.0) + ((g14r + g23r)*gc)/4.0;
g14gc = (1-gc)*g14r;
g22gc = g22r + (g12r*gc)/4.0 + (g24r*gc)/4.0;
g23gc = (1-gc)*g23r;
g24gc = g24r*(1 - gc/2.0) + ((g14r + g23r)*gc)/4.0;
g33gc = g33r + (g13r*gc)/4.0 + (g34r*gc)/4.0;
g34gc = g34r*(1 - gc/2.0) + ((g14r + g23r)*gc)/4.0;
g44gc = g44r + (g24r*gc)/4.0 + (g34r*gc)/4.0;
/* Output */
*(geninit + 0) = g11gc;
*(geninit + 1) = g12gc;
*(geninit + 2) = g13gc;
*(geninit + 3) = g14gc;
*(geninit + 4) = g22gc;
*(geninit + 5) = g23gc;
*(geninit + 6) = g24gc;
*(geninit + 7) = g33gc;
*(geninit + 8) = g34gc;
*(geninit + 9) = g44gc;
} /* End of gene conversion routine */
/* Has neutral allele fixed or not? Measuring freq of B */
double ncheck(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;
/* Haplotypes ONLY CONTAINING B */
double x3, x4;
double Btot = 0; /* Total frequency of B */
/* Initial definition of genotypes */
g11s = *(geninit + 0);
g12s = *(geninit + 1);
g13s = *(geninit + 2);
g14s = *(geninit + 3);
g22s = *(geninit + 4);
g23s = *(geninit + 5);
g24s = *(geninit + 6);
g33s = *(geninit + 7);
g34s = *(geninit + 8);
g44s = *(geninit + 9);
/* Calculation of haplotypes containing B */
x3 = g33s + (g13s + g23s + g34s)/2.0;
x4 = g44s + (g14s + g24s + g34s)/2.0;
/* Checking */
Btot = x3 + x4;
return Btot;
} /* End of B check routine */
/* Checking if balancing polymorphism lost or not */
double pcheck(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;
double x2, x4;
double Atot = 0; /* Total frequency of A */
/* Initial definition of genotypes */
g11s = *(geninit + 0);
g12s = *(geninit + 1);
g13s = *(geninit + 2);
g14s = *(geninit + 3);
g22s = *(geninit + 4);
g23s = *(geninit + 5);
g24s = *(geninit + 6);
g33s = *(geninit + 7);
g34s = *(geninit + 8);
g44s = *(geninit + 9);
/* Calculation of haplotypes containing B */
x2 = g22s + (g12s + g23s + g24s)/2.0;
x4 = g44s + (g14s + g24s + g34s)/2.0;
/* Checking */
Atot = x2 + x4;
return Atot;
} /* End of A check routine */
/* End of program */
| {
"alphanum_fraction": 0.5877048052,
"avg_line_length": 31.1716738197,
"ext": "c",
"hexsha": "6b728f8e74a4fd8093f06005a0f80bffc5791f0f",
"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": "9df64092397e1c043ecadde0f4bd86ada180fe60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/BalSelSims",
"max_forks_repo_path": "BalSelSims.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9df64092397e1c043ecadde0f4bd86ada180fe60",
"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": "MattHartfield/BalSelSims",
"max_issues_repo_path": "BalSelSims.c",
"max_line_length": 257,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9df64092397e1c043ecadde0f4bd86ada180fe60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/BalSelSims",
"max_stars_repo_path": "BalSelSims.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5464,
"size": 14526
} |
/*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @file LogEntry.h
* @author: yujiechen
* @date: 2021-03-18
*/
#pragma once
#include "../interfaces/crypto/CryptoSuite.h"
#include "../libutilities/Common.h"
#include "../libutilities/FixedBytes.h"
#include <gsl/span>
namespace bcos
{
namespace protocol
{
class LogEntry
{
public:
using Ptr = std::shared_ptr<LogEntry>;
LogEntry() = default;
LogEntry(bytes const& _address, h256s _topics, bytes _data)
: m_address(_address), m_topics(std::move(_topics)), m_data(std::move(_data))
{}
~LogEntry() {}
std::string_view address() const
{
return std::string_view((char*)m_address.data(), m_address.size());
}
gsl::span<const h256> topics() const { return gsl::span(m_topics.data(), m_topics.size()); }
bytesConstRef data() const { return ref(m_data); }
// Define the scale decode method, which cannot be modified at will
template <class Stream, typename = std::enable_if_t<Stream::is_decoder_stream>>
friend Stream& operator>>(Stream& _stream, LogEntry& _logEntry)
{
return _stream >> _logEntry.m_address >> _logEntry.m_topics >> _logEntry.m_data;
}
// Define the scale encode method, which cannot be modified at will
template <class Stream, typename = std::enable_if_t<Stream::is_encoder_stream>>
friend Stream& operator<<(Stream& _stream, LogEntry const& _logEntry)
{
return _stream << _logEntry.m_address << _logEntry.m_topics << _logEntry.m_data;
}
private:
bcos::bytes m_address;
bcos::h256s m_topics;
bytes m_data;
};
using LogEntries = std::vector<LogEntry>;
using LogEntriesPtr = std::shared_ptr<std::vector<LogEntry>>;
} // namespace protocol
} // namespace bcos | {
"alphanum_fraction": 0.697992311,
"avg_line_length": 33.4428571429,
"ext": "h",
"hexsha": "3da9d9469ac78449a1afc2be106b40097b3bc39e",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z",
"max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "xueying4402/FISCO-BCOS",
"max_forks_repo_path": "bcos-framework/libprotocol/LogEntry.h",
"max_issues_count": 267,
"max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "xueying4402/FISCO-BCOS",
"max_issues_repo_path": "bcos-framework/libprotocol/LogEntry.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "xueying4402/FISCO-BCOS",
"max_stars_repo_path": "bcos-framework/libprotocol/LogEntry.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 598,
"size": 2341
} |
// 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_INV_H
#define SCILIB_LINALG_INV_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <experimental/mdspan>
#include <exception>
#include <cassert>
#include <type_traits>
namespace Sci {
namespace Linalg {
// Matrix inversion.
template <class T_a, class T_res, class Layout>
requires(std::is_same_v<std::remove_cv_t<T_a>, double>)
inline void inv(Sci::Matrix_view<T_a, Layout> a,
Sci::Matrix_view<T_res, Layout> res)
{
namespace stdex = std::experimental;
static_assert(a.is_contiguous());
static_assert(res.is_contiguous());
assert(a.extent(0) == a.extent(1));
if (det(a) == 0.0) {
throw std::runtime_error("inv: matrix not invertible");
}
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(0));
auto matrix_layout = LAPACK_ROW_MAJOR;
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
}
Sci::copy(a, res);
Sci::Vector<BLAS_INT, Layout> ipiv(n);
Sci::Linalg::lu(res, ipiv.view()); // perform LU factorization
BLAS_INT info =
LAPACKE_dgetri(matrix_layout, n, res.data(), lda, ipiv.data());
if (info != 0) {
throw std::runtime_error("dgetri: matrix inversion failed");
}
}
template <class Layout, class Allocator>
inline Sci::Matrix<double, Layout, Allocator>
inv(const Sci::Matrix<double, Layout, Allocator>& a)
{
Sci::Matrix<double, Layout, Allocator> res(a.extent(0), a.extent(1));
inv(a.view(), res.view());
return res;
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_INV_H
| {
"alphanum_fraction": 0.6831530139,
"avg_line_length": 25.5394736842,
"ext": "h",
"hexsha": "32581d4f49a8b7c21c394a59a1d249174d868992",
"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/inv.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/inv.h",
"max_line_length": 78,
"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/inv.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 520,
"size": 1941
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <php.h>
#include <cblas.h>
#include <lapacke.h>
#include "kernel/operators.h"
/**
* Matrix-matrix multiplication i.e. linear transformation of matrices A and B.
*
* @param return_value
* @param a
* @param b
*/
void tensor_matmul(zval * return_value, zval * a, zval * b)
{
unsigned int i, j;
Bucket * row;
zval rowC, c;
zend_array * aa = Z_ARR_P(a);
zend_array * ab = Z_ARR_P(b);
Bucket * ba = aa->arData;
Bucket * bb = ab->arData;
unsigned int m = zend_array_count(aa);
unsigned int p = zend_array_count(ab);
unsigned int n = zend_array_count(Z_ARR(bb[0].val));
double * va = emalloc(m * p * sizeof(double));
double * vb = emalloc(n * p * sizeof(double));
double * vc = emalloc(m * n * sizeof(double));
for (i = 0; i < m; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < p; ++j) {
va[i * p + j] = zephir_get_doubleval(&row[j].val);
}
}
for (i = 0; i < p; ++i) {
row = Z_ARR(bb[i].val)->arData;
for (j = 0; j < n; ++j) {
vb[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, p, 1.0, va, p, vb, n, 0.0, vc, n);
array_init_size(&c, m);
for (i = 0; i < m; ++i) {
array_init_size(&rowC, n);
for (j = 0; j < n; ++j) {
add_next_index_double(&rowC, vc[i * n + j]);
}
add_next_index_zval(&c, &rowC);
}
RETVAL_ARR(Z_ARR(c));
efree(va);
efree(vb);
efree(vc);
}
/**
* Dot product between vectors A and B.
*
* @param return_value
* @param a
* @param b
*/
void tensor_dot(zval * return_value, zval * a, zval * b)
{
unsigned int i;
zend_array * aa = Z_ARR_P(a);
zend_array * ab = Z_ARR_P(b);
Bucket * ba = aa->arData;
Bucket * bb = ab->arData;
unsigned int n = zend_array_count(aa);
double sigma = 0.0;
for (i = 0; i < n; ++i) {
sigma += zephir_get_doubleval(&ba[i].val) * zephir_get_doubleval(&bb[i].val);
}
RETVAL_DOUBLE(sigma);
}
/**
* Return the multiplicative inverse of a square matrix A.
*
* @param return_value
* @param a
*/
void tensor_inverse(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval rowB, b;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int n = zend_array_count(aa);
double * va = emalloc(n * n * sizeof(double));
int * pivots = emalloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status;
status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots);
if (status != 0) {
RETURN_NULL();
}
status = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, va, n, pivots);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&b, n);
for (i = 0; i < n; ++i) {
array_init_size(&rowB, n);
for (j = 0; j < n; ++j) {
add_next_index_double(&rowB, va[i * n + j]);
}
add_next_index_zval(&b, &rowB);
}
RETVAL_ARR(Z_ARR(b));
efree(va);
efree(pivots);
}
/**
* Return the (Moore-Penrose) pseudoinverse of a general matrix A.
*
* @param return_value
* @param a
*/
void tensor_pseudoinverse(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval b, rowB;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int m = zend_array_count(aa);
unsigned int n = zend_array_count(Z_ARR(ba[0].val));
unsigned int k = MIN(m, n);
double * va = emalloc(m * n * sizeof(double));
double * vu = emalloc(m * m * sizeof(double));
double * vs = emalloc(k * sizeof(double));
double * vvt = emalloc(n * n * sizeof(double));
double * vb = emalloc(n * m * sizeof(double));
for (i = 0; i < m; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n);
if (status != 0) {
RETURN_NULL();
}
for (i = 0; i < k; ++i) {
cblas_dscal(m, 1.0 / vs[i], &vu[i], m);
}
cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, n, m, m, 1.0, vvt, n, vu, m, 0.0, vb, m);
array_init_size(&b, n);
for (i = 0; i < n; ++i) {
array_init_size(&rowB, m);
for (j = 0; j < m; ++j) {
add_next_index_double(&rowB, vb[i * m + j]);
}
add_next_index_zval(&b, &rowB);
}
RETVAL_ARR(Z_ARR(b));
efree(va);
efree(vu);
efree(vs);
efree(vvt);
efree(vb);
}
/**
* Return the row echelon form of matrix A.
*
* @param return_value
* @param a
*/
void tensor_ref(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval rowB, b;
zval tuple;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int m = zend_array_count(aa);
unsigned int n = zend_array_count(Z_ARR(ba[0].val));
double * va = emalloc(m * n * sizeof(double));
int * pivots = emalloc(MIN(m, n) * sizeof(int));
for (i = 0; i < m; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, n, va, n, pivots);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&b, m);
long swaps = 0;
for (i = 0; i < m; ++i) {
array_init_size(&rowB, n);
for (j = 0; j < i; ++j) {
add_next_index_double(&rowB, 0.0);
}
for (j = i; j < n; ++j) {
add_next_index_double(&rowB, va[i * n + j]);
}
add_next_index_zval(&b, &rowB);
if (i + 1 != pivots[i]) {
++swaps;
}
}
array_init_size(&tuple, 2);
add_next_index_zval(&tuple, &b);
add_next_index_long(&tuple, swaps);
RETVAL_ARR(Z_ARR(tuple));
efree(va);
efree(pivots);
}
/**
* Compute the Cholesky decomposition of matrix A and return the lower triangular matrix.
*
* @param return_value
* @param a
*/
void tensor_cholesky(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval rowB, b;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int n = zend_array_count(aa);
double * va = emalloc(n * n * sizeof(double));
for (i = 0; i < n; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'L', n, va, n);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&b, n);
for (i = 0; i < n; ++i) {
array_init_size(&rowB, n);
for (j = 0; j <= i; ++j) {
add_next_index_double(&rowB, va[i * n + j]);
}
for (j = i + 1; j < n; ++j) {
add_next_index_double(&rowB, 0.0);
}
add_next_index_zval(&b, &rowB);
}
RETVAL_ARR(Z_ARR(b));
efree(va);
}
/**
* Compute the LU factorization of matrix A and return a tuple with lower, upper, and permutation matrices.
*
* @param return_value
* @param a
*/
void tensor_lu(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval rowL, l, rowU, u, rowP, p;
zval tuple;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int n = zend_array_count(aa);
double * va = emalloc(n * n * sizeof(double));
int * pivots = emalloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&l, n);
array_init_size(&u, n);
array_init_size(&p, n);
for (i = 0; i < n; ++i) {
array_init_size(&rowL, n);
for (j = 0; j < i; ++j) {
add_next_index_double(&rowL, va[i * n + j]);
}
add_next_index_double(&rowL, 1.0);
for (j = i + 1; j < n; ++j) {
add_next_index_double(&rowL, 0.0);
}
add_next_index_zval(&l, &rowL);
}
for (i = 0; i < n; ++i) {
array_init_size(&rowU, n);
for (j = 0; j < i; ++j) {
add_next_index_double(&rowU, 0.0);
}
for (j = i; j < n; ++j) {
add_next_index_double(&rowU, va[i * n + j]);
}
add_next_index_zval(&u, &rowU);
}
for (i = 0; i < n; ++i) {
array_init_size(&rowP, n);
for (j = 0; j < n; ++j) {
if (j == pivots[i] - 1) {
add_next_index_long(&rowP, 1);
} else {
add_next_index_long(&rowP, 0);
}
}
add_next_index_zval(&p, &rowP);
}
array_init_size(&tuple, 3);
add_next_index_zval(&tuple, &l);
add_next_index_zval(&tuple, &u);
add_next_index_zval(&tuple, &p);
RETVAL_ARR(Z_ARR(tuple));
efree(va);
efree(pivots);
}
/**
* Compute the eigendecomposition of a general matrix A and return the eigenvalues and eigenvectors in a tuple.
*
* @param return_value
* @param a
*/
void tensor_eig(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval eigenvalues;
zval eigenvectors;
zval eigenvector;
zval tuple;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int n = zend_array_count(aa);
double * va = emalloc(n * n * sizeof(double));
double * wr = emalloc(n * sizeof(double));
double * wi = emalloc(n * sizeof(double));
double * vr = emalloc(n * n * sizeof(double));
for (i = 0; i < n; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dgeev(LAPACK_ROW_MAJOR, 'N', 'V', n, va, n, wr, wi, NULL, n, vr, n);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&eigenvalues, n);
array_init_size(&eigenvectors, n);
for (i = 0; i < n; ++i) {
add_next_index_double(&eigenvalues, wr[i]);
array_init_size(&eigenvector, n);
for (j = 0; j < n; ++j) {
add_next_index_double(&eigenvector, vr[i * n + j]);
}
add_next_index_zval(&eigenvectors, &eigenvector);
}
array_init_size(&tuple, 2);
add_next_index_zval(&tuple, &eigenvalues);
add_next_index_zval(&tuple, &eigenvectors);
RETVAL_ARR(Z_ARR(tuple));
efree(va);
efree(wr);
efree(wi);
efree(vr);
}
/**
* Compute the eigendecomposition of a symmetric matrix A and return the eigenvalues and eigenvectors in a tuple.
*
* @param return_value
* @param a
*/
void tensor_eig_symmetric(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval eigenvalues;
zval eigenvectors;
zval eigenvector;
zval tuple;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int n = zend_array_count(aa);
double * va = emalloc(n * n * sizeof(double));
double * wr = emalloc(n * sizeof(double));
for (i = 0; i < n; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', n, va, n, wr);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&eigenvalues, n);
array_init_size(&eigenvectors, n);
for (i = 0; i < n; ++i) {
add_next_index_double(&eigenvalues, wr[i]);
array_init_size(&eigenvector, n);
for (j = 0; j < n; ++j) {
add_next_index_double(&eigenvector, va[i * n + j]);
}
add_next_index_zval(&eigenvectors, &eigenvector);
}
array_init_size(&tuple, 2);
add_next_index_zval(&tuple, &eigenvalues);
add_next_index_zval(&tuple, &eigenvectors);
RETVAL_ARR(Z_ARR(tuple));
efree(va);
efree(wr);
}
/**
* Compute the singular value decomposition of a matrix A and return the singular values, and unitary matrices U and VT in a tuple.
*
* @param return_value
* @param a
*/
void tensor_svd(zval * return_value, zval * a)
{
unsigned int i, j;
Bucket * row;
zval u, rowU;
zval s;
zval vt, rowVt;
zval tuple;
zend_array * aa = Z_ARR_P(a);
Bucket * ba = aa->arData;
unsigned int m = zend_array_count(aa);
unsigned int n = zend_array_count(Z_ARR(ba[0].val));
unsigned int k = MIN(m, n);
double * va = emalloc(m * n * sizeof(double));
double * vu = emalloc(m * m * sizeof(double));
double * vs = emalloc(k * sizeof(double));
double * vvt = emalloc(n * n * sizeof(double));
for (i = 0; i < m; ++i) {
row = Z_ARR(ba[i].val)->arData;
for (j = 0; j < n; ++j) {
va[i * n + j] = zephir_get_doubleval(&row[j].val);
}
}
lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n);
if (status != 0) {
RETURN_NULL();
}
array_init_size(&u, m);
array_init_size(&s, k);
array_init_size(&vt, n);
for (i = 0; i < m; ++i) {
array_init_size(&rowU, m);
for (j = 0; j < m; ++j) {
add_next_index_double(&rowU, vu[i * m + j]);
}
add_next_index_zval(&u, &rowU);
}
for (i = 0; i < k; ++i) {
add_next_index_double(&s, vs[i]);
}
for (i = 0; i < n; ++i) {
array_init_size(&rowVt, n);
for (j = 0; j < n; ++j) {
add_next_index_double(&rowVt, vvt[i * n + j]);
}
add_next_index_zval(&vt, &rowVt);
}
array_init_size(&tuple, 3);
add_next_index_zval(&tuple, &u);
add_next_index_zval(&tuple, &s);
add_next_index_zval(&tuple, &vt);
RETVAL_ARR(Z_ARR(tuple));
efree(va);
efree(vu);
efree(vs);
efree(vvt);
}
| {
"alphanum_fraction": 0.5321689907,
"avg_line_length": 21.7507507508,
"ext": "c",
"hexsha": "a551923dcc5ad00a6fc78c69c1d1e0c86d7437f1",
"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": "cf6f57a4b88e2954c00c2598ea37e6246567d215",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "asdrenxhafa/mood_detection",
"max_forks_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cf6f57a4b88e2954c00c2598ea37e6246567d215",
"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": "asdrenxhafa/mood_detection",
"max_issues_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c",
"max_line_length": 131,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "cf6f57a4b88e2954c00c2598ea37e6246567d215",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "asdrenxhafa/mood_detection",
"max_stars_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c",
"max_stars_repo_stars_event_max_datetime": "2021-03-06T19:09:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-06T19:09:18.000Z",
"num_tokens": 4684,
"size": 14486
} |
/*
* 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 thdpool_3a298e4f_792c_44ff_bc62_c639d1eb697c_h
#define thdpool_3a298e4f_792c_44ff_bc62_c639d1eb697c_h
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <gslib/std.h>
__gslib_begin__
using std::thread;
using std::function;
class thread_pool
{
public:
thread_pool(int threads)
{
for(int i = 0; i < threads; i ++) {
_workers.emplace_back(
[this]() {
for(;;) {
function<void()> task;
{
std::unique_lock<std::mutex> lock(_mtx_worker);
_cv_worker.wait(lock, [this] { return _stop || !_tasks.empty(); });
if(_stop && _tasks.empty())
return;
task = std::move(_tasks.front());
_tasks.pop();
}
task();
{
std::unique_lock<std::mutex> lock(_mtx_main);
-- _undone;
}
_cv_main.notify_one();
}
}
);
}
}
~thread_pool()
{
{
std::unique_lock<std::mutex> lock(_mtx_worker);
_stop = true;
}
_cv_worker.notify_all();
for(thread& worker : _workers)
worker.join();
}
protected:
vector<thread> _workers;
queue<function<void()>> _tasks;
std::mutex _mtx_worker;
std::mutex _mtx_main;
std::condition_variable _cv_worker;
std::condition_variable _cv_main;
volatile bool _stop = false;
volatile int _undone = 0;
public:
template<class _func, class... _args>
auto add(_func&& f, _args&&... args) ->
std::future<typename std::result_of<_func(_args...)>::type>
{
using return_type = typename std::result_of<_func(_args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<_func>(f), std::forward<_args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(_mtx_worker);
if(_stop)
throw std::runtime_error("enqueue on stopped thread pool.");
_tasks.emplace([task]() { (*task)(); });
}
{
std::unique_lock<std::mutex> lock(_mtx_main);
++ _undone;
}
_cv_worker.notify_one();
return res;
}
void join()
{
std::unique_lock<std::mutex> lock(_mtx_main);
_cv_main.wait(lock, [this] { return !_undone; });
}
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.5682315738,
"avg_line_length": 32.3700787402,
"ext": "h",
"hexsha": "7bd8b8973277679ec76c44150f076f13a82697db",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/thdpool.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/thdpool.h",
"max_line_length": 95,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/thdpool.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": 912,
"size": 4111
} |
/* multifit_nlinear/test.c
*
* Copyright (C) 2007, 2013, 2015, 2016 Brian Gough, 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.
*/
/* These tests are based on the NIST Statistical Reference Datasets
See http://www.nist.gov/itl/div898/strd/index.html for more
information. */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_ieee_utils.h>
#include "test_fdf.c"
static void
test_proc(const gsl_multifit_nlinear_trs *trs,
const gsl_multifit_nlinear_scale *scale,
const gsl_multifit_nlinear_solver *solver,
const int fdtype)
{
gsl_multifit_nlinear_parameters fdf_params =
gsl_multifit_nlinear_default_parameters();
fdf_params.trs = trs;
fdf_params.scale = scale;
fdf_params.solver = solver;
fdf_params.fdtype = fdtype;
test_fdf_main(&fdf_params);
}
int
main (void)
{
const gsl_multifit_nlinear_trs **nlinear_trs[6];
const gsl_multifit_nlinear_solver **nlinear_solvers[5];
const gsl_multifit_nlinear_scale **nlinear_scales[3];
const gsl_multifit_nlinear_trs **trs;
const gsl_multifit_nlinear_solver **solver;
const gsl_multifit_nlinear_scale **scale;
size_t i = 0;
gsl_ieee_env_setup();
/* initialize arrays */
nlinear_trs[0] = &gsl_multifit_nlinear_trs_lm;
nlinear_trs[1] = &gsl_multifit_nlinear_trs_lmaccel;
nlinear_trs[2] = &gsl_multifit_nlinear_trs_dogleg;
nlinear_trs[3] = &gsl_multifit_nlinear_trs_ddogleg;
nlinear_trs[4] = &gsl_multifit_nlinear_trs_subspace2D;
nlinear_trs[5] = NULL;
nlinear_solvers[0] = &gsl_multifit_nlinear_solver_cholesky;
nlinear_solvers[1] = &gsl_multifit_nlinear_solver_mcholesky;
nlinear_solvers[2] = &gsl_multifit_nlinear_solver_qr;
nlinear_solvers[3] = &gsl_multifit_nlinear_solver_svd;
nlinear_solvers[4] = NULL;
/* skip Marquardt scaling since it won't pass */
nlinear_scales[0] = &gsl_multifit_nlinear_scale_levenberg;
nlinear_scales[1] = &gsl_multifit_nlinear_scale_more;
nlinear_scales[2] = NULL;
/* run testsuite over all parameter combinations */
for (trs = nlinear_trs[i]; trs != NULL; trs = nlinear_trs[++i])
{
size_t j = 0;
fprintf(stderr, "trs = %s\n", (*trs)->name);
for (solver = nlinear_solvers[j]; solver != NULL; solver = nlinear_solvers[++j])
{
size_t k = 0;
/* don't use Cholesky solver with dogleg methods */
if (i > 1 && *solver == gsl_multifit_nlinear_solver_cholesky)
continue;
fprintf(stderr, "solver = %s\n", (*solver)->name);
for (scale = nlinear_scales[k]; scale != NULL; scale = nlinear_scales[++k])
{
test_proc(*trs, *scale, *solver, GSL_MULTIFIT_NLINEAR_FWDIFF);
test_proc(*trs, *scale, *solver, GSL_MULTIFIT_NLINEAR_CTRDIFF);
}
}
}
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.7103239978,
"avg_line_length": 32.5178571429,
"ext": "c",
"hexsha": "0052ff2b8890f7afdffdbd838973cb9571fb94c1",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/multifit_nlinear/test.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/multifit_nlinear/test.c",
"max_line_length": 86,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit_nlinear/test.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": 1080,
"size": 3642
} |
#pragma once
#include <utility>
#include <array>
#include <vector>
#include <unordered_map>
#include <DirectXMathExtend.h>
#include <gsl.h>
#include <VertexTraits.h>
#include <minmax>
#include "bvh.h"
#include <hlslm\hlsl.hpp>
#include <iostream>
namespace Geometrics
{
template <typename IndexType>
struct Triangle
{
static constexpr size_t VertexCount = 3;
typedef std::array<IndexType, VertexCount> container_type;
container_type v;
typedef IndexType value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef IndexType *pointer;
typedef const IndexType *const_pointer;
typedef IndexType& reference;
typedef const IndexType& const_reference;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
Triangle() {}
Triangle(const IndexType &v0, const IndexType &v1, const IndexType &v2)
{
v[0] = v0; v[1] = v1; v[2] = v2;
}
Triangle(const IndexType *v_)
{
v[0] = v_[0]; v[1] = v_[1]; v[2] = v_[2];
}
template <class S> explicit Triangle(const S &x)
{
v[0] = x[0]; v[1] = x[1]; v[2] = x[2];
}
IndexType &operator[] (int i) { return v[i]; }
const IndexType &operator[] (int i) const { return v[i]; }
operator const IndexType * () const { return &(v[0]); }
operator IndexType * () { return &(v[0]); }
void rewind() {
std::swap(v[0], v[2]);
}
int indexof(IndexType v_) const
{
return (v[0] == v_) ? 0 :
(v[1] == v_) ? 1 :
(v[2] == v_) ? 2 : -1;
}
// contrainer access
auto begin() { return v.begin(); }
auto end() { return v.end(); }
auto begin() const { return v.begin(); }
auto end() const { return v.end(); }
auto rbegin() { return v.rbegin(); }
auto rend() { return v.rend(); }
auto rbegin() const { return v.rbegin(); }
auto rend() const { return v.rend(); }
size_t size() const { return VertexCount; }
};
struct submesh_data
{
uint32_t vertex_offset; // start vertices index of this geometry
uint32_t vertex_count;
uint32_t index_offset; // start index position of this geometry
uint32_t index_count;
};
// generate per vertex normal for given triangle mesh
template <typename VertexType, typename IndexType>
bool generate_normal(gsl::span<VertexType> vertices, gsl::span<const Triangle<IndexType>> facets)
{
using namespace DirectX::VertexTraits;
using namespace DirectX;
if (!has_normal<VertexType>::value)
return false;
//static_assert(has_normal<VertexType>::value, "The vertex type dose not contains normal field");
std::vector<XMVECTOR, XMAllocator> normals(vertices.size());
// set zero
std::memset(normals.data(), 0, normals.size() * sizeof(XMVECTOR));
XMVECTOR v0, v1, v2, n;
for (const auto& face : facets)
{
v0 = get_position(vertices[face[0]]);
v1 = get_position(vertices[face[1]]);
v2 = get_position(vertices[face[2]]);
v1 -= v0;
v2 -= v0;
v1 = XMVector3Normalize(v1);
v2 = XMVector3Normalize(v2);
n = XMVector3Cross(v1, v2); // weighted normal
normals[face[0]] += n;
normals[face[1]] += n;
normals[face[2]] += n;
}
for (size_t i = 0; i < vertices.size(); i++)
{
n = XMVector3Normalize(normals[i]);
set_normal(vertices[i], n);
}
return true;
}
// generate per vertex tangent for given triangle mesh
template <typename VertexType, typename IndexType>
bool generate_tangent(gsl::span<VertexType> vertices, gsl::span<const Triangle<IndexType>> facets)
{
using namespace DirectX::VertexTraits;
using namespace DirectX;
if (!has_tangent<VertexType>::value)
return false;
//static_assert(has_tangent<VertexType>::value, "The vertex type dose not contains tangent field");
std::vector<XMVECTOR, XMAllocator> tan1(vertices.size() * 2);
XMVECTOR* tan2 = &tan1[vertices.size()];
std::memset(tan1.data(), 0, tan1.size() * sizeof(XMVECTOR));
for (const auto& face : facets)
{
{
XMVECTOR v0, v1, v2, w0, w1, w2;
v0 = get_position(vertices[face[0]]);
w0 = get_uv(vertices[face[0]]);
v1 = get_position(vertices[face[1]]);
w1 = get_uv(vertices[face[1]]);
v2 = get_position(vertices[face[2]]);
w2 = get_uv(vertices[face[2]]);
}
XMFLOAT4A v_1, v_2, w_1, w_2;
XMStoreA(v_1, v1 - v0);
XMStoreA(v_2, v2 - v0);
XMStoreA(w_1, w1 - w0);
XMStoreA(w_2, w2 - w0);
float x1 = v_1.x; float x2 = v_2.x;
float y1 = v_1.y; float y2 = v_2.y;
float z1 = v_1.z; float z2 = v_2.z;
float s1 = w_1.x; float s2 = w_2.x;
float t1 = w_1.y; float t2 = w_2.y;
float r = 1.0F / (s1 * t2 - s2 * t1);
XMVECTOR sdir = XMVectorSet(
(t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r, .0f);
XMVECTOR tdir = XMVectorSet(
(s1 * x2 - s2 * x1) * r,
(s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r, .0f);
tan1[face[0]] += sdir;
tan1[face[1]] += sdir;
tan1[face[2]] += sdir;
tan2[face[0]] += tdir;
tan2[face[1]] += tdir;
tan2[face[2]] += tdir;
}
for (size_t i = 0; i < vertices.size(); i++)
{
XMVECTOR n = get_normal(vertices[i], n);
XMVECTOR t = tan1[i];
// Gram-Schmidt orthogonalize
XMVECTOR nt = XMVector3Normalize(t - n * XMVector3Dot(n, t));
XMVECTOR w = XMVectorLess(XMVector3Dot(XMVector3Cross(n, t), tan2[i]), XMVectorZero());
w = XMVectorSelect(g_XMNegativeOne.v, g_XMOne.v, w);
nt = _DXMEXT XMVectorSelect<0, 0, 0, 1>(nt, w);
set_tangent(vertices[i], nt);
}
return true;
}
namespace Detail
{
XM_HAS_MEMBER(vertices, has_vertices);
XM_HAS_MEMBER(indices, has_indices);
}
template <typename MeshType>
struct concept_mesh_type : public std::integral_constant<bool, Detail::has_vertices<MeshType>::value && Detail::has_indices<MeshType>::value> {};
template <typename _MeshType>
class SubMesh : public submesh_data
{
public:
typedef _MeshType MeshType; // Parent MeshTypw
typedef typename MeshType::VertexType VertexType;
typedef typename MeshType::IndexType IndexType;
typedef typename MeshType::FaceType FaceType;
static constexpr size_t PolygonVertex = FaceType::VertexCount;
SubMesh(MeshType& mesh, const submesh_data& metric)
: parent(mesh), submesh_data(metric)
{
vertices = gsl::span<VertexType>(&mesh.vertices[metric.vertex_offset], metric.vertex_count);
indices = gsl::span<IndexType>(&mesh.indices[metric.index_offset], metric.index_count);
}
MeshType& parent;
gsl::span<VertexType> vertices;
gsl::span<IndexType> indices;
gsl::span<Triangle<IndexType>> facets()
{
return gsl::span<const FaceType>(
reinterpret_cast<const FaceType*>(indices.data()),
indices.size() / FaceType::VertexCount);
}
bool empty() const {
return vertices.empty() || indices.empty();
}
};
template <typename _VertexType, typename _IndexType = uint16_t, typename _FaceType = Triangle<_IndexType>>
class PolygonSoup
{
public:
typedef _VertexType VertexType;
typedef _IndexType IndexType;
typedef _FaceType FaceType;
static constexpr size_t PolygonVertex = FaceType::VertexCount;
PolygonSoup() {}
bool empty() const {
return vertices.empty() || indices.empty();
}
void clear()
{
vertices.clear();
indices.clear();
}
inline const FaceType& facet(int idx) const
{
return reinterpret_cast<const FaceType&>(indices[idx * FaceType::VertexCount]);
}
inline FaceType& facet(int idx)
{
return reinterpret_cast<FaceType&>(indices[idx * FaceType::VertexCount]);
}
void add_facet(const FaceType& new_facet)
{
indices.insert(indices.end(), new_facet.begin(), new_facet.end());
}
template <class... _TIndecies>
std::enable_if_t<sizeof...(_TIndecies) == FaceType::VertexCount> add_facet(_TIndecies... _indices)
{
indices.insert(indices.end(), { static_cast<IndexType>(_indices)... });
}
gsl::span<FaceType> facets() {
return gsl::span<FaceType>(
reinterpret_cast<FaceType*>(indices.data()),
indices.size() / FaceType::VertexCount);
}
gsl::span<const FaceType> facets() const {
return gsl::span<const FaceType>(
reinterpret_cast<const FaceType*>(indices.data()),
indices.size() / FaceType::VertexCount);
}
const VertexType& vertex(int facet, int vidx) const
{
return this->vertices[this->indices[facet * FaceType::VertexCount + vidx]];
}
VertexType& vertex(int facet, int vidx)
{
return this->vertices[this->indices[facet * FaceType::VertexCount + vidx]];
}
// flip all the polygons' winding and vertices' normal
void flip()
{
using namespace DirectX::VertexTraits;
if (has_normal<VertexType>::value)
{
for (auto& v : vertices)
set_normal(v, -get_normal(v));
}
static constexpr int vc = FaceType::VertexCount;
for (int i = 0; i < indices.size() / vc; i++)
std::reverse(indices.begin() + i * vc, indices.begin() + (i + 1)* vc);
}
void generate_normal()
{
static_assert(PolygonVertex == 3, "This mesh is not trigle mesh, please trianglize it first");
generate_normal<VertexType, IndexType>(this->vertices, this->facets());
}
void generate_tangent()
{
static_assert(PolygonVertex == 3, "This mesh is not trigle mesh, please trianglize it first");
generate_tangent<VertexType, IndexType>(this->vertices, this->facets());
}
// applies an uniform transform to all vertices in the mesh
void XM_CALLCONV transform(DirectX::FXMMATRIX M)
{
using namespace DirectX::VertexTraits;
for (auto& v : vertices)
{
XMVECTOR p = get_position(v);
p = _DXMEXT XMVector3TransformCoord(p, M);
set_position(v, p);
if (has_normal<VertexType>::value)
{
p = get_normal(v);
p = _DXMEXT XMVector3TransformNormal(p, M);
set_normal(v, p);
if (has_tangent<VertexType>::value)
{
p = get_tangent(v);
p = _DXMEXT XMVector3TransformNormal(p, M);
set_tangent(v, p);
}
}
}
}
std::vector<VertexType, DirectX::AlignedAllocator<VertexType>> vertices;
std::vector<IndexType> indices;
};
template <class _VertexType, class _IndexType>
int XM_CALLCONV intersect(const PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>> &Mesh, DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector<float>* distances = nullptr)
{
using namespace DirectX;
using namespace DirectX::VertexTraits;
int count = 0;
XMVECTOR vDir = XMVector3Normalize(Direction);
for (const auto& tri : Mesh.facets())
{
float distance;
XMVECTOR v0 = get_position(&Mesh.vertices[tri[0]]);
XMVECTOR v1 = get_position(&Mesh.vertices[tri[1]]);
XMVECTOR v2 = get_position(&Mesh.vertices[tri[2]]);
bool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);
if (hr) {
++count;
if (distances) {
distances->push_back(distances);
}
}
}
return count;
}
template <typename _TVertex>
struct MeshRayIntersectedVertex : public _TVertex
{
using Vector3 = DirectX::Vector3;
float distance;
Vector3 barycentric;
int facet; // facet id
inline bool operator < (const MeshRayIntersectedVertex& rhs)
{
return this->distance < rhs.distance;
}
inline bool is_valiad() const {return facet >= 0; }
inline operator bool() const { return is_valiad(); }
};
template <size_t _Dim>
struct PolygonContainmentInfo
{
static constexpr size_t Dim = _Dim;
DirectX::ContainmentType containment; // overall polygon containment type
DirectX::ContainmentType vertex_containments[Dim];
operator DirectX::ContainmentType() const { return containment; }
};
struct XM_ALIGNATTR aabb_t {
::hlsl::xmvector3f min;
::hlsl::xmvector3f max;
mutable int intersected;
template <size_t dim>
static bool less(const aabb_t& lhs, const aabb_t & rhs)
{
using namespace hlsl;
return hlsl::less(lhs.min, rhs.min).get<dim>();
}
aabb_t operator+(const aabb_t& rhs) const
{
const aabb_t& lhs = *this;
using namespace ::hlsl;
aabb_t ret{ ::hlsl::min(lhs.min,rhs.min),::hlsl::max(lhs.max,rhs.max) };
return ret;
}
// Convert min-max representation of this box to center-extent representation
DirectX::BoundingBox get_dxbox() const
{
const float epsilon = 1e-3;
using namespace ::hlsl;
auto& aabb = *this;
DirectX::BoundingBox box;
xmvector3f extent = (aabb.max - aabb.min) * 0.5f;
extent = ::hlsl::max(extent, xmfloat(epsilon));
box.Center << (aabb.max + aabb.min) * 0.5f;
box.Extents << extent;
return box;
}
operator DirectX::BoundingBox() const { return get_dxbox(); }
};
// A struct stores fixed size polygon (position only)
template <size_t _Size>
struct PlainPolygon {
hlsl::xmvector3f v[_Size];
};
/// <summary>
/// Basic triangle mesh, each index represent an edge, which is the edge oppsite to the vertex in it's owner triangle
/// </summary>
template <typename _VertexType, typename _IndexType = uint16_t>
class TriangleMesh : public PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>
{
public:
static const size_t VertexCount = FaceType::VertexCount;
using triangle_handle = IndexType;
using PlainTriangle = PlainPolygon<3>;
using ContainmentType = DirectX::ContainmentType;
using BaseType = PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>;
using BaseType::PolygonVertex;
using typename BaseType::VertexType;
using typename BaseType::IndexType;
using IntersectionVertex = MeshRayIntersectedVertex<_VertexType>;
public:
// edge's reverse edge
// stores the adjacent edges of a edge in a triangle
std::vector<IndexType> revedges;
DirectX::BoundingBox aabb;
DirectX::BoundingOrientedBox obb;
PlainTriangle XM_CALLCONV get_triangle_position(IndexType fid) const
{
using namespace DirectX::VertexTraits;
using namespace hlsl;
auto f = this->indices.begin() + fid * 3;
PlainTriangle tri = {
xmvector3f(get_position(this->vertices[f[0]]))
,xmvector3f(get_position(this->vertices[f[1]]))
,xmvector3f(get_position(this->vertices[f[2]])) };
return tri;
}
#define _EXPANDTRI(tri) tri.v[0].v, tri.v[1].v, tri.v[2].v
aabb_t XM_CALLCONV get_triangle_aabb(triangle_handle t) const
{
using namespace hlsl;
PlainTriangle tri = get_triangle_position(t);
xmvector3f vmax = hlsl::max(tri.v[0], tri.v[1]);
vmax = hlsl::max(vmax, tri.v[2]);
xmvector3f vmin = hlsl::min(tri.v[0], tri.v[1]);
vmin = hlsl::min(vmin, tri.v[2]);
aabb_t ret;
ret.min = vmin;
ret.max = vmax;
ret.intersected = true;
return ret;
}
using triangle_bvh_t = kd_bvh<triangle_handle, float, 3, aabb_t>;
triangle_bvh_t triangle_bvh;
using vertex_bvh_t = kd_bvh<::hlsl::xmvector3f, float, 3, aabb_t>;
vertex_bvh_t vertex_bvh;
// An Lookup table to find the 'Ienditification' of a vertex
// Make sense when multiple vertex shares the same spatial location but have different index
std::vector<IndexType> vertex_id;
TriangleMesh() : triangle_bvh([this](const triangle_handle& t) {
return this->get_triangle_aabb(t);
}) {}
// vertex's first adjacant edge
// std::vector<IndexType> vedges;
union EdgeType
{
_IndexType v[2];
struct {
_IndexType v0, v1;
};
};
inline EdgeType edge(int facet, int edge) const
{
EdgeType e;
auto& tri = this->facet(facet);
switch (edge)
{
case 0:
e.v0 = tri[1];
e.v1 = tri[2];
break;
case 1:
e.v0 = tri[2];
e.v1 = tri[0];
break;
case 2:
e.v0 = tri[0];
e.v1 = tri[1];
break;
default:
e.v0 = -1;
e.v1 = -1;
break;
}
return e;
}
inline EdgeType edge(int eid) const
{
return edge(eid / VertexCount, eid % VertexCount);
}
inline int adjacentFacet(int facet, int edge) const
{
return revedges[facet * VertexCount + edge] / VertexCount;
}
inline int adjacentFacet(int eid) const
{
return revedges[eid] / VertexCount;
}
void build_reverse_edges()
{
// intialize all adjacant edges to -1
revedges.resize(this->indices.size(), -1);
_IndexType vsize = this->vertices.size();
int esize = this->indices.size();
int fsize = this->indices.size() / VertexCount;
using hash_type = uint64_t;
// make sure int for hash is enough
assert(vsize*vsize < std::numeric_limits<hash_type>::max());
std::unordered_map<hash_type, _IndexType> edges(esize * 2);
// max items inside this table should be less than (esize / 2)
for (_IndexType fid = 0; fid < fsize; fid++)
{
for (_IndexType i = 0; i < VertexCount; i++)
{
_IndexType eid = i + fid * VertexCount;
auto e = this->edge(fid, i);
e.v0 = vertex_id[e.v0];
e.v1 = vertex_id[e.v1];
hash_type ehash = e.v0 * vsize + e.v1;
hash_type revehash = e.v0 + e.v1 * vsize;
auto revItr = edges.find(revehash);
if (revItr == edges.end())
edges[ehash] = eid;
else // find reversed edge, remove from edges map
{
auto revEid = revItr->second;
revedges[eid] = revEid;
revedges[revEid] = eid;
auto reve = this->edge(revEid);
reve.v0 = vertex_id[reve.v0];
reve.v1 = vertex_id[reve.v1];
assert(reve.v0 == e.v1 && reve.v1 == e.v0);
edges.erase(revItr);
}
}
}
}
// build the adjacent map so we can access all the 1 rings
void build()
{
int vsize = this->vertices.size();
int esize = this->indices.size();
int fsize = this->indices.size() / VertexCount;
// rebuild the triangle-bvh
triangle_bvh.resize(fsize);
std::iota(triangle_bvh.begin(), triangle_bvh.end(), 0);
triangle_bvh.rebuild();
// build the vertex-bvh
const aabb_t& bb = this->triangle_bvh.get_volumn(this->triangle_bvh.root());
::hlsl::xmvector3f voxel_ext(1e-4f);
vertex_bvh.set_volumn_getter([voxel_ext](const ::hlsl::xmvector3f v) {
return aabb_t{ v - voxel_ext , v + voxel_ext, 0 };
});
vertex_bvh.resize(vsize);
for (int i = 0; i < vsize; i++)
vertex_bvh[i] = ::hlsl::xmvector3f(::DirectX::VertexTraits::get_position(this->vertices[i]));
vertex_bvh.rebuild();
vertex_id.resize(vsize);
std::iota(vertex_id.begin(), vertex_id.end(), 0);
std::unordered_map<uint64_t, IndexType> vids(vsize);
// Use 20-bits to hash a float component, plus 1 bit signbit
// Generate a total 63-bits
auto hash_position = [](const ::hlsl::xmvector3f vp) -> uint64_t{
auto vf = vp * 3e4f; // 30 * 3e4 = 9e5 < 1e6 = 2^20
auto vi = vf.cast<uint32_t>();
uint32_t signbits32 = ::hlsl::detail::move_mask(vi);
uint64_t signbits = signbits32;
vi &= ::hlsl::xmuint((1ULL << 20ULL) - 1ULL);
uint32_t vis32[3];
vis32 << vi;
uint64_t vis[3] = { vis32[0], vis32[1], vis32[2]};
uint64_t vhash = ((signbits&7) << 60ULL) | (vis[0] << 40ULL) | (vis[1] << 20ULL) | (vis[2]);
return vhash;
};
for (int i = 0; i < vsize; i++)
{
auto vp = *vertex_bvh.get_object(i);
std::pair<uint64_t, IndexType> p = { hash_position(vp), i };
auto rib = vids.insert(p);
IndexType vid = rib.first->second;
if (!rib.second && vid != i)
{
// query-merge-set merge algorithm
int root = vid;
// find the ultimate parent (root)
while (vertex_id[root] != root) root = vertex_id[root];
while (vid != root)
{
int cvid = vid;
vid = vertex_id[vid];
vertex_id[cvid] = root;
}
vertex_id[i] = root;
//if (vid != i)
// std::cout << "Glued vertex pair (" << i << ',' << vid << ')' << std::endl;
}
}
build_reverse_edges();
//for (int fid = 0; fid < this->indices.size() / 3; ++fid)
//{
// auto tri = this->facet(fid);
// using namespace DirectX::VertexTraits;
// DirectX::XMVECTOR v0 = get_position(this->vertices[tri[0]]);
// DirectX::XMVECTOR v1 = get_position(this->vertices[tri[1]]);
// DirectX::XMVECTOR v2 = get_position(this->vertices[tri[2]]);
// auto&& vol = triangle_bvh.get_volumn(fid);
// bool cond = true;
// assert(DirectX::XMVector3LessOrEqual(v0, vol.max.v));
// assert(DirectX::XMVector3LessOrEqual(v1, vol.max.v));
// assert(DirectX::XMVector3LessOrEqual(v2, vol.max.v));
// assert(DirectX::XMVector3LessOrEqual(vol.min.v, v0));
// assert(DirectX::XMVector3LessOrEqual(vol.min.v, v1));
// assert(DirectX::XMVector3LessOrEqual(vol.min.v, v2));
//}
}
// generate a persoude vertex from the interpolation of the trianlge
VertexType persudo_vertex(int fid, DirectX::FXMVECTOR baycentric) const
{
const auto& tri = this->facet(fid);
const VertexType& v0 = this->vertices[tri[0]];
const VertexType& v1 = this->vertices[tri[1]];
const VertexType& v2 = this->vertices[tri[2]];
using namespace DirectX::VertexTraits;
return interpolate_vertex(baycentric, v0, v1, v2);
}
protected:
IntersectionVertex XM_CALLCONV get_ray_intersected_vertex(DirectX::FXMVECTOR vOri, DirectX::FXMVECTOR vDir, IndexType fid) const
{
using DirectX::XMVECTOR;
IntersectionVertex info;
float distance = .0f;
info.facet = -1;
PlainTriangle tri = this->get_triangle_position(fid);
bool hr = DirectX::TriangleTests::Intersects(vOri, vDir, _EXPANDTRI(tri), distance);
if (!hr) return info; // No intersection, return with info.facet == -1
// Fill the persudo-vertex
XMVECTOR pos = distance * vDir + vOri;
XMVECTOR baryc = DirectX::TriangleTests::BarycentricCoordinate(pos, _EXPANDTRI(tri));
info.barycentric = baryc;
info.facet = fid;
info.distance = distance;
(VertexType&)info = this->persudo_vertex(fid, baryc);
return info;
}
template <typename _Ty>
inline static void push_back_output_itr(nullptr_t itr, _Ty&& element)
{
}
template <typename _OutItr, typename _Ty>
inline static std::enable_if_t<!std::is_same<_OutItr,nullptr_t>::value>
push_back_output_itr(_OutItr& itr, _Ty&& element)
{
static_assert(std::is_same<std::decay_t<decltype(*itr)>,std::decay_t<_Ty>>::value,"Output Iterator's Type is not expected");
*(itr++) = element;
}
public:
IntersectionVertex XM_CALLCONV first_intersect(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction) const
{
using namespace DirectX;
assert(this->triangle_bvh.valiad() && "This triangle mesh is modified but not rebuild");
XMVECTOR vOri = Origin;
XMVECTOR vDir = XMVector3Normalize(Direction);
auto ray_aabb_inter = [vOri, vDir](const aabb_t& aabb) -> float
{
float f;
auto box = aabb.get_dxbox();
bool succ = box.Intersects(vOri, vDir, f);
aabb.intersected = succ;
return succ ? f : -1.0f;
};
auto ray_triangle_inter = [this, vOri, vDir](const int fid) -> float
{
PlainTriangle tri = this->get_triangle_position(fid);
float f;
bool succ = DirectX::TriangleTests::Intersects(vOri, vDir, _EXPANDTRI(tri), f);
return succ ? f : -1.0f;
};
//std::cout << counter << std::endl;
auto pfid = find_first_of(this->triangle_bvh, ray_triangle_inter, ray_aabb_inter);
IntersectionVertex info;
info.facet = -1;
if (pfid)
info = get_ray_intersected_vertex(vOri, vDir, *pfid);
return info;
}
// Ray intersection test with advanced infomation
template <typename _TOutItr>
int XM_CALLCONV all_intersections(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, _TOutItr outItr) const
{
using namespace DirectX;
assert(this->triangle_bvh.valiad() && "This triangle mesh is modified but not rebuild");
size_t count = 0;
XMVECTOR vOri = Origin;
XMVECTOR vDir = XMVector3Normalize(Direction);
struct XM_ALIGNATTR ray_aabb_intersector {
DirectX::XMVECTOR origin;
DirectX::XMVECTOR direction;
bool XM_CALLCONV operator ()(const aabb_t& aabb) const
{
float f;
auto box = aabb.get_dxbox();
bool succ = box.Intersects(origin, direction, f);
aabb.intersected = succ;
return succ;
}
} intersector{ vOri , vDir };
for (auto triangles = find_all_of(triangle_bvh, intersector);
triangles;
++triangles)
{
int fid = *triangles;
IntersectionVertex info = get_ray_intersected_vertex(vOri, vDir, fid);
if (info.is_valiad()) {
++count;
push_back_output_itr(outItr, std::move(info));
}
}
return count;
}
template <typename _TPred, typename _TContainer>
void find_adjacant_facets_of(IndexType facet_id, _TPred&& pred, _TContainer& result_map) const
{
auto containment = pred(facet_id);
result_map.insert(std::make_pair(facet_id, containment));
if (!containment) return;
for (int e = 0; e < PolygonVertex; e++)
{
int eid = facet_id * PolygonVertex + e;
auto rev_edge = this->revedges[eid];
auto adj_face = rev_edge / PolygonVertex;
// if not visited yet
if (rev_edge != -1 && result_map.find(adj_face) == result_map.end())
this->find_adjacant_facets_of(adj_face, pred, result_map);
}
}
};
namespace Internal
{
#ifndef min
template <typename T>
inline T clamp(T value, T minV, T maxV)
{
return std::max(std::min(value, maxV), minV);
}
#else
template <typename T>
inline T clamp(T value, T minV, T maxV)
{
return max(min(value, maxV), minV);
}
#endif
}
/// <summary>
/// Compute the closest projection point from P0 to triangle(V0,V1,V2).
/// </summary>
/// <param name="P0">The p0.</param>
/// <param name="V0">The v0.</param>
/// <param name="V1">The v1.</param>
/// <param name="V2">The v2.</param>
/// <returns></returns>
inline DirectX::XMVECTOR XM_CALLCONV Projection(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)
{
using namespace DirectX;
using namespace Geometrics::Internal;
XMVECTOR edge0 = V1 - V0;
XMVECTOR edge1 = V2 - V0;
XMVECTOR p0 = V0 - P0;
//XMVectorBaryCentric();
float a = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge0));
float b = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, edge1));
float c = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge1));
float d = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, p0));
float e = XMVectorGetX(_DXMEXT XMVector3Dot(edge1, p0));
float det = a*c - b*b;
float s = b*e - c*d;
float t = b*d - a*e;
if (s + t < det)
{
if (s < 0.f)
{
if (t < 0.f)
{
if (d < 0.f)
{
s = clamp(-d / a, 0.f, 1.f);
t = 0.f;
}
else
{
s = 0.f;
t = clamp(-e / c, 0.f, 1.f);
}
}
else
{
s = 0.f;
t = clamp(-e / c, 0.f, 1.f);
}
}
else if (t < 0.f)
{
s = clamp(-d / a, 0.f, 1.f);
t = 0.f;
}
else
{
float invDet = 1.f / det;
s *= invDet;
t *= invDet;
}
}
else
{
if (s < 0.f)
{
float tmp0 = b + d;
float tmp1 = c + e;
if (tmp1 > tmp0)
{
float numer = tmp1 - tmp0;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1 - s;
}
else
{
t = clamp(-e / c, 0.f, 1.f);
s = 0.f;
}
}
else if (t < 0.f)
{
if (a + d > b + e)
{
float numer = c + e - b - d;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1 - s;
}
else
{
s = clamp(-e / c, 0.f, 1.f);
t = 0.f;
}
}
else
{
float numer = c + e - b - d;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1.f - s;
}
}
return V0 + s * edge0 + t * edge1;
}
inline float XM_CALLCONV Distance(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)
{
using namespace DirectX;
XMVECTOR vProj = Projection(P0, V0, V1, V2);
vProj -= P0;
return XMVectorGetX(_DXMEXT XMVector3Length(vProj));
}
template <typename _VertexType, typename _IndexType>
inline float XM_CALLCONV Distance(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)
{
using namespace DirectX;
float minDis = numeric_limits<float>::max();
for (const auto& tri : Mesh.facets())
{
float dis;
XMVECTOR v0 = XMLoadFloat3(&Mesh.vertices[tri[0]].position);
XMVECTOR v1 = XMLoadFloat3(&Mesh.vertices[tri[1]].position);
XMVECTOR v2 = XMLoadFloat3(&Mesh.vertices[tri[2]].position);
dis = Distance(Point, v0, v1, v2);
if (dis < minDis) minDis = dis;
//minDis = std::min(dis,minDis);
}
//XMVECTOR vDis = XMVectorReplicate(numeric_limits<float>::max());
//for (const auto& vertex : Mesh.vertices)
//{
// XMVECTOR vPos = XMLoadFloat3(&vertex.position);
// vPos -= Point;
// XMVECTOR dis = XMVector3Length(vPos);
// vDis = XMVectorMin(vDis,dis);
//}
//float minDisV = XMVectorGetX(vDis);
//assert(minDisV >= minDis);
return minDis;
//return XMVectorGetX(minDis);
}
template <typename _VertexType, typename _IndexType>
bool XM_CALLCONV Inside(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)
{
XMFLOAT3A Direction;
Direction.x = (float)std::rand() / (RAND_MAX + 1);
Direction.y = (float)std::rand() / (RAND_MAX + 1);
Direction.z = (float)std::rand() / (RAND_MAX + 1);
XMVECTOR vDir = XMLoadFloat3A(&Direction);
auto count = intersect(Mesh, Point, vDir, nullptr);
return count & 1; //count % 2
}
} | {
"alphanum_fraction": 0.6517373724,
"avg_line_length": 27.8188751192,
"ext": "h",
"hexsha": "d5444e3383ae3a2d48466c23320ad465ca048731",
"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": "63c540d1736e323a0f409914e413cb237f03c5c9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ArcEarth/SrInspection",
"max_forks_repo_path": "Geometrics/TriangleMesh.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9",
"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": "ArcEarth/SrInspection",
"max_issues_repo_path": "Geometrics/TriangleMesh.h",
"max_line_length": 196,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ArcEarth/SrInspection",
"max_stars_repo_path": "Geometrics/TriangleMesh.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9244,
"size": 29182
} |
#ifndef LDA_TOPIC_WORD_PROB_MULTI_SELECT_H
#define LDA_TOPIC_WORD_PROB_MULTI_SELECT_H
#include "Lambda.h"
#include "LambdaCreationFunctions.h"
#include "MultiSelectionComp.h"
#include "PDBVector.h"
#include "LDATopicWordProb.h"
#include "TopicAssignment.h"
#include "LDATopicWordProb.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <random>
#include <gsl/gsl_vector.h>
/* This class generates the entries for the topic probability for each word */
using namespace pdb;
class LDATopicWordProbMultiSelection
: public MultiSelectionComp<LDATopicWordProb, TopicAssignment> {
private:
Vector<double> prior;
Handle<Vector<char>> myMem;
int numTopics;
public:
ENABLE_DEEP_COPY
LDATopicWordProbMultiSelection() {}
LDATopicWordProbMultiSelection(Vector<double>& fromPrior, unsigned numTopics) {
this->prior = fromPrior;
this->numTopics = numTopics;
/* Set up the random number generator */
gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937);
std::random_device rd;
std::mt19937 gen(rd());
gsl_rng_set(src, gen());
int spaceNeeded = sizeof(gsl_rng) + src->type->size;
myMem = makeObject<Vector<char>>(spaceNeeded, spaceNeeded);
memcpy(myMem->c_ptr(), src, sizeof(gsl_rng));
memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size);
gsl_rng_free(src);
}
Lambda<bool> getSelection(Handle<TopicAssignment> checkMe) override {
return makeLambda(checkMe, [](Handle<TopicAssignment>& checkMe) { return true; });
}
Lambda<Vector<Handle<LDATopicWordProb>>> getProjection(
Handle<TopicAssignment> checkMe) override {
return makeLambda(checkMe, [&](Handle<TopicAssignment>& checkMe) {
gsl_rng* rng = getRng();
Vector<unsigned>& wordCount = checkMe->getVector();
unsigned wordNum = prior.size();
double* mySamples = new double[wordNum];
double* totalProb = new double[wordNum];
double* myPrior = prior.c_ptr();
for (int i = 0; i < wordNum; i++) {
totalProb[i] = myPrior[i] + wordCount[i];
}
/* Sample the word probability */
gsl_ran_dirichlet(rng, wordNum, totalProb, mySamples);
/* Create the topic probability for each word */
Vector<Handle<LDATopicWordProb>> result(wordNum);
for (int i = 0; i < wordNum; i++) {
Handle<LDATopicWordProb> myTWP =
makeObject<LDATopicWordProb>(numTopics, i, checkMe->getKey(), mySamples[i]);
result.push_back(myTWP);
}
delete[] mySamples;
delete[] totalProb;
return result;
});
}
gsl_rng* getRng() {
gsl_rng* dst = (gsl_rng*)myMem->c_ptr();
dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng));
dst->type = gsl_rng_mt19937;
return dst;
}
};
#endif
| {
"alphanum_fraction": 0.6307485733,
"avg_line_length": 29.79,
"ext": "h",
"hexsha": "172d5f746ace1aaddec60d8777974ab727a6a5c3",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-06T19:28:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-18T02:13:53.000Z",
"max_forks_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_forks_repo_path": "src/sharedLibraries/headers/LDA/LDATopicWordProbMultiSelection.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_issues_repo_issues_event_max_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_issues_repo_path": "src/sharedLibraries/headers/LDA/LDATopicWordProbMultiSelection.h",
"max_line_length": 96,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_stars_repo_path": "src/sharedLibraries/headers/LDA/LDATopicWordProbMultiSelection.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T02:06:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-17T16:14:26.000Z",
"num_tokens": 731,
"size": 2979
} |
/* movstat/test_median.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_statistics.h>
/* compute filtered data by explicitely constructing window, sorting it and finding median */
int
slow_movmedian(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y,
const int H, const int J)
{
const size_t n = x->size;
const int K = H + J + 1;
double *window = malloc(K * sizeof(double));
size_t i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window);
double yi = gsl_stats_median(window, 1, wsize);
gsl_vector_set(y, i, yi);
}
free(window);
return GSL_SUCCESS;
}
/* test root sequence */
static void
test_median_root(const double tol, const size_t n, const size_t K, const gsl_movstat_end_t etype)
{
gsl_movstat_workspace *w = gsl_movstat_alloc(K);
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *y = gsl_vector_alloc(n);
char buf[2048];
size_t i;
/* test a root sequence (square input): x = [zero one zero] */
gsl_vector_set_all(x, 0.0);
for (i = n / 3; i <= n / 2; ++i)
gsl_vector_set(x, i, 1.0);
/* compute y = median(x) and test y = x */
gsl_movstat_median(etype, x, y, w);
sprintf(buf, "n=%zu K=%zu endtype=%u SMF root sequence", n, K, etype);
compare_vectors(tol, y, x, buf);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_movstat_free(w);
}
static double
func_median(const size_t n, double x[], void * params)
{
(void) params;
return gsl_stats_median(x, 1, n);
}
static void
test_median_proc(const double tol, const size_t n, const size_t H, const size_t J,
const gsl_movstat_end_t etype, gsl_rng *rng_p)
{
gsl_movstat_workspace *w;
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *y = gsl_vector_alloc(n);
gsl_vector *z = gsl_vector_alloc(n);
gsl_movstat_function F;
char buf[2048];
F.function = func_median;
F.params = NULL;
if (H == J)
w = gsl_movstat_alloc(2*H + 1);
else
w = gsl_movstat_alloc2(H, J);
/* test moving median with random input */
random_vector(x, rng_p);
/* y = median(x) with slow brute force algorithm */
slow_movmedian(etype, x, y, H, J);
/* z = median(x) */
gsl_movstat_median(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u median random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = median(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_median(etype, z, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u median random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = median(x) with user-defined function */
gsl_movstat_apply(etype, &F, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u median user", n, H, J, etype);
compare_vectors(tol, z, y, buf);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
gsl_movstat_free(w);
}
static void
test_median(gsl_rng * rng_p)
{
test_median_root(GSL_DBL_EPSILON, 1000, 3, GSL_MOVSTAT_END_PADZERO);
test_median_root(GSL_DBL_EPSILON, 200, 15, GSL_MOVSTAT_END_PADVALUE);
test_median_root(GSL_DBL_EPSILON, 100, 5, GSL_MOVSTAT_END_TRUNCATE);
test_median_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 1, 1, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 150, 150, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 8, 8, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 0, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 5, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 15, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 10, 15, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 150, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 150, 100, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 100, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 1, 1, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 150, 150, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 8, 8, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 0, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 5, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 15, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 10, 15, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 150, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 150, 100, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 100, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 1, 1, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 150, 150, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 8, 8, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 0, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 5, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 15, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 10, 15, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 150, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 150, 100, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 100, 100, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.731544619,
"avg_line_length": 37.8988764045,
"ext": "c",
"hexsha": "9eaca2f5de8a02fd7201d9294c3ee3996e3a5e88",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/movstat/test_median.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/movstat/test_median.c",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/test_median.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": 2209,
"size": 6746
} |
/*
* Copyright (c) 2011-2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
*
* @precisions normal z -> s d c
*
*/
#ifndef _DPLASMA_CORES_H_
#define _DPLASMA_CORES_H_
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include "dplasma_complex.h"
#include "parsec/data_dist/matrix/matrix.h"
#include <core_blas.h>
#define PLASMA_BLKADDR(A, type, m, n) (type *)plasma_getaddr(A, m, n)
#define PLASMA_BLKLDD(A, k) ( ( (k) + (A).i/(A).mb) < (A).lm1 ? (A).mb : (A).lm%(A).mb )
#endif /* _DPLASMA_CORES_H_ */
| {
"alphanum_fraction": 0.626984127,
"avg_line_length": 27.3913043478,
"ext": "h",
"hexsha": "3dbe42be31fe335990e713f291725c90009a87b8",
"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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "NLAFET/ABFT",
"max_forks_repo_path": "dplasma/cores/dplasma_cores.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"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": "NLAFET/ABFT",
"max_issues_repo_path": "dplasma/cores/dplasma_cores.h",
"max_line_length": 88,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "NLAFET/ABFT",
"max_stars_repo_path": "dplasma/cores/dplasma_cores.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z",
"num_tokens": 201,
"size": 630
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_randist.h>
int
main (void)
{
double x;
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (x = 0.1; x < 2; x+= 0.1)
{
double y0 = exp (x);
double sigma = 0.1 * y0;
double dy = gsl_ran_gaussian (r, sigma);
printf ("%g %g %g\n", x, y0 + dy, sigma);
}
gsl_rng_free(r);
return 0;
}
| {
"alphanum_fraction": 0.5488888889,
"avg_line_length": 15,
"ext": "c",
"hexsha": "a3f1e32854bcbf0f0220513d3d25cb8b4d4d5e4c",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting3.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitting3.c",
"max_line_length": 47,
"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/fitting3.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": 161,
"size": 450
} |
/**
* @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST).
* All rights reserved.
**/
/**
* @file time_zpotrf_tile.c
*
* This file shows how to generate tile low-rank (TLR) matrix and factorize it using Cholesky factorization.
*
* HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST)
*
* @version 0.1.1
* @author Kadir Akbudak
* @date 2018-11-08
**/
/*
* @copyright (c) 2009-2014 The University of Tennessee and The University
* of Tennessee Research Foundation.
* All rights reserved.
* @copyright (c) 2012-2016 Inria. All rights reserved.
* @copyright (c) 2012-2014 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria, Univ. Bordeaux. All rights reserved.
*/
/**
* The meaning of the descriptors:
* - AUV: U and V, side by side
* - AD : U*V
* - A : the original, non-approximated problem
* - Ark: rank of U and V, each tile of the matrix is a single integer in fact a double.
*
**/
#include "morse.h"
#include "timing.h"
#include "hicma_constants.h"
#include "hicma_struct.h"
#include "hicma_z.h"
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
//#include <mpi.h> //MPI_Wtime()
#include "starpu.h"
#ifdef MKL
#include <mkl.h>
//#pragma message("MKL is used")
#else
#include <cblas.h>
#ifdef LAPACKE_UTILS
#include <lapacke_utils.h>
#endif
#include <lapacke.h>
//#pragma message("MKL is NOT used")
#endif
#include "starsh-spatial.h"
#include <assert.h>
#include "hicma_z.h"
#include "auxcompute_z.h"
#include "auxdescutil.h"
#include "hicma.h"
#include <math.h>
#include <time.h>
#undef CBLAS_SADDR
#define CBLAS_SADDR(_val) (_val)
// zgytlr uses starsh in MPI mode.
STARSH_blrf *mpiF;
int print_progress = 1; // Print progress about the execution
char datebuf[128];
time_t timer;
struct tm* tm_info;
#define PROGRESS(str) \
if(print_progress){ \
int myrank = MORSE_My_Mpi_Rank();\
time(&timer); \
tm_info = localtime(&timer); \
strftime(datebuf, 26, "%Y-%m-%d %H:%M:%S",tm_info); \
fprintf(stderr, "%d:%s\t%d\t%s\t%s\n", myrank, datebuf, __LINE__, __func__, str);\
fflush(stderr);\
}
//#undef PROGRESS
//#define PROGRESS(str)
int store_only_diagonal_tiles = 0;
int global_check = 0;
int global_always_fixed_rank = 0;
int global_fixed_rank = 0;
int global_omit_computation = 1;
int num_mpi_ranks;
int run_potrf = 1;
int diag_nrows = 0;
int main_print_index = 0;
int print_index = 0;
int print_index_end = 0;
int main_print_mat = 0;
int print_mat = 0;
int use_scratch = 1; // Use scratch memory provided by starpu
int calc_rank_stat = 1;
void fwrite_array(int m, int n, int ld, double* arr, char* file){
FILE* fp = fopen(file, "w");
if(fp == NULL){
fprintf(stderr, "File %s cannot be opened to write\n", file);
exit(1);
}
int i, j;
fprintf(fp, "%d %d\n", m, n);
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
fprintf(fp, "%d\t", (int)arr[ld*j+i] );
}
fprintf(fp, "\n" );
}
fclose(fp);
}
double timediff(struct timeval begin, struct timeval end){
double elapsed = (end.tv_sec - begin.tv_sec) +
((end.tv_usec - begin.tv_usec)/1000000.0);
return elapsed;
}
int
RunTest(int *iparam, double *dparam, morse_time_t *t_, char* rankfile)
{
// print progress info only on ROOT process
if(MORSE_My_Mpi_Rank() != 0)
print_progress = 0;
PROGRESS("RunTest started");
// this paramater enables storing only diagonal tiles in a tall and skinny matrix
store_only_diagonal_tiles = 1;
//chameleon/runtime/starpu/control/runtime_descriptor.c
//MORSE_user_tag_size(31,26);
//MORSE_user_tag_size(31,29);
MORSE_user_tag_size(31,27);// When I added tile_to_lapack for descArk, I got not enough number of desc error
// get parameters coming from command line
PASTE_CODE_IPARAM_LOCALS( iparam );
// set global variable so that p.. files can fill dense matrix
global_check = check;
// calculate total number of mpi processes (it is not used for now)
num_mpi_ranks = P*Q;
print_index = iparam[IPARAM_HICMA_PRINTINDEX];
print_index_end = iparam[IPARAM_HICMA_PRINTINDEXEND];
print_mat = iparam[IPARAM_HICMA_PRINTMAT];
int64_t _nb = iparam[IPARAM_NB];
LDA = chameleon_max(M, iparam[IPARAM_LDA]);
int hicma_maxrank = iparam[IPARAM_HICMA_MAXRANK];
global_always_fixed_rank = iparam[IPARAM_HICMA_ALWAYS_FIXED_RANK];
int saveNB = NB;
NB = MB;
size_t ncols_AD;
int saveP = P;
int saveQ = Q;
if (store_only_diagonal_tiles == 1) {
ncols_AD = MB;
} else {
ncols_AD = M;
}
int saveN = N;
N = ncols_AD;
PASTE_CODE_ALLOCATE_MATRIX_TILE( descAD, 1, double, MorseRealDouble, LDA, M, N );
N = saveN;
P = saveP;
Q = saveQ;
PROGRESS("descAD is allocated");
size_t ncols_Dense;
size_t ld_Dense;
int saveMB = MB;
if(check == 0) {
ncols_Dense = MT;
MB = NB = 1;
ld_Dense = MT;
} else {
ncols_Dense = M;
ld_Dense = M;
}
/*descDense is full matrix if numerical accuracy will be checked.
* Otherwise it is MB-by-MB matrix with 1-by-1 tiles */
PASTE_CODE_ALLOCATE_MATRIX_TILE( descDense, 1, double, MorseRealDouble, ld_Dense, ncols_Dense, ncols_Dense );
if(check == 0) {
MB = saveMB;
} else {
}
PROGRESS("descDense is allocated");
NB = saveNB;
int MTMB = MT * MB; // roundup number of rows/columns for AUV
int nrows_AUV = MTMB;
int ld_AUV = MTMB;
// allocate descUV
saveN = N;
N = N * 2;
saveNB = NB;
NB = NB * 2;
//printf("N:%d NB:%d\n", N, NB);
PASTE_CODE_ALLOCATE_MATRIX_TILE( descAUV, 1, double, MorseRealDouble, ld_AUV, nrows_AUV, N );
N = saveN;
NB = saveNB;
PROGRESS("descAUV is allocated");
/* tile dimension of rank descriptor must be 1 */
/* when LD for rk matrices is 1, program exits*/
int bigMB = MB;
int bigNB = NB;
MB = NB = 1;
PASTE_CODE_ALLOCATE_MATRIX_TILE( descArk, 1, double, MorseRealDouble, MT, MT, NT);
PROGRESS("descA's are allocated");
MB = bigMB;
NB = bigNB;
int diag_dense = 1;
int fixedrank = iparam[IPARAM_RK]; //genargs->k
double fixedacc = pow(10, -1.0*iparam[IPARAM_ACC]);
char sym;
if (run_potrf)
sym = 'S';
else
sym = 'N';
int probtype = iparam[IPARAM_HICMA_STARSH_PROB];
int maxrank = iparam[IPARAM_HICMA_STARSH_MAXRANK];
//double ddecay = pow(10, -1.0*iparam[IPARAM_HICMA_STARSH_DECAY]);
double ddecay = dparam[IPARAM_HICMA_STARSH_DECAY];
int initial_maxrank, final_maxrank;
double initial_avgrank, final_avgrank;
HICMA_problem_t hicma_problem;
hicma_problem.ndim = 2;
//BEGIN: rndtiled
if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_RND) {
hicma_problem.noise = 1.0; //value added to diagonal
}
//END: rndtiled
//BEGIN: geostat
//double theta[3] = {1, 0.1, 0.5}; //initially
double theta[3] = {
1.0, //sigma
0.01, //beta
10.0 //nu Aleks used 10.0 in his paper
};
if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_GEOSTAT) {
hicma_problem.theta = theta;
hicma_problem.noise = 0.0;
hicma_problem.noise = 1.e-2;
hicma_problem.kernel_type = STARSH_SPATIAL_MATERN2_SIMD;
}
//END: geostat
//BEGIN: ss
if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_SS) {
//sigma=1.0 default value line 193 of stars-h/src/applications/spatial.c
// Correlation length
hicma_problem.beta = 0.1;
//If fixed rank is required set beta=1 and a sample case will be like this nb=25 maxrank=10 m=2500 So ranks will decrease.
// Smoothing parameter for Matern kernel
hicma_problem.nu = 0.5;
// Shift added to diagonal elements
hicma_problem.noise = 1.e-4; //not enough for matrices larger than 600K
hicma_problem.noise = 5.e-4; //works for 640K but does not work for 10M
hicma_problem.noise = 1.e-2; //
}
//END: ss
//BEGIN: edsin
if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_EDSIN) {
// Wave number, >= 0
hicma_problem.wave_k = dparam[IPARAM_HICMA_STARSH_WAVE_K];
hicma_problem.diag = M;
//printf("%s %d: %g\n", __FILE__, __LINE__, hicma_problem.wave_k);
}
//END: edsin
PROGRESS("generating coordinates started");
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
HICMA_zgenerate_problem(probtype, sym, ddecay, M, MB, MT, NT, &hicma_problem);
gettimeofday (&tvalAfter, NULL);
if(MORSE_My_Mpi_Rank()==0){
printf("Tproblem:%g\n",
(tvalAfter.tv_sec - tvalBefore.tv_sec)
+(tvalAfter.tv_usec - tvalBefore.tv_usec)/1000000.0
);
fflush(stderr);
fflush(stdout);
}
PROGRESS("generating coordinates ended");
mpiF = hicma_problem.starsh_format; // This is assignment will be hidden from user in release
// DO NOT enforce compression of diagonal tiles
int compress_diag = 0;
PROGRESS("nompi zgytlr starting");
//descDense original problem
gettimeofday (&tvalBefore, NULL);
HICMA_zgytlr_Tile(MorseLower, descAUV, descAD, descArk, 0, maxrank, fixedacc, compress_diag, descDense);
gettimeofday (&tvalAfter, NULL);
if(MORSE_My_Mpi_Rank()==0){
printf("Tcompress:%g\n",
(tvalAfter.tv_sec - tvalBefore.tv_sec)
+(tvalAfter.tv_usec - tvalBefore.tv_usec)/1000000.0
);
fflush(stderr);
fflush(stdout);
}
PROGRESS("nompi zgytlr finished");
fflush(stderr);
fflush(stdout);
/*return 0; //TODO*/
if(calc_rank_stat == 1) {
PASTE_TILE_TO_LAPACK( descArk, Ark_initial, 1, double, MT, NT );
if(MORSE_My_Mpi_Rank()==0){
sprintf(rankfile, "%s-1", rankfile);
fwrite_array(descArk->m, descArk->n, descArk->m, Ark_initial, rankfile);
HICMA_stat_t hicma_statrk_initial;
zget_stat(MorseLower, Ark_initial, MT, NT, MT, &hicma_statrk_initial);
printf("initial_ranks:");
zprint_stat(hicma_statrk_initial);
fflush(stderr);
fflush(stdout);
}
}
if (global_always_fixed_rank == 1) {
fprintf(stderr, "%s %d Fixed rank: %d\n", __FILE__, __LINE__, global_fixed_rank);
}
if(0 && num_mpi_ranks == 1 && initial_maxrank > N){ //FIXME Enable for distributed mem
fprintf(stderr,"%s %d %d\t|N:%d is less than actual maxrank:%d\n", __FILE__, __LINE__, MORSE_My_Mpi_Rank(), N, initial_maxrank);
exit(1);
}
int set_diag = 0;
/* Save A for check */
PROGRESS("pasting original dense descAD into Adense and Adense2 started");
// Adense: original dense problem.
PASTE_TILE_TO_LAPACK( descDense, Adense, check, double, LDA, M );
double one = 1.0, zero = 0.0, minusone = -1.0, diagVal = M;
double* swork = NULL;
//double* cp_L_Adense = calloc(LDA*M, sizeof(double));
if(check){
swork = calloc(2*M, sizeof(double));
{size_t i, j;
double* orgAdense = calloc(LDA*M, sizeof(double));
for(j = 0; j < M; j++){
for(i = 0; i < M; i++){
orgAdense[j*LDA+i] = Adense[j*LDA+i];
}
}
int info = LAPACKE_dpotrf_work(
LAPACK_COL_MAJOR,
'L',
M, orgAdense, LDA);
if(0 && info != 0){ //FIXME
fprintf(stderr, "%s\t|%d\t|Error in LAPACK potrf. info:%d, This errors means "
"that the matrix generated is not positive definite\n", __FILE__, __LINE__, info);
}
for(j = 0; j < M; j++){
for(i = 0; i < j; i++){
orgAdense[j*LDA+i] = zero;
}
}
/*for(j = 0; j < M; j++) { */
/*for(i = 0; i < M; i++){*/
/*cp_L_Adense[j*LDA+i] = orgAdense[j*LDA+i];*/
/*}*/
/*}*/
if(main_print_mat ){printf("L of Adense\n");printmat(orgAdense,M,M,LDA,MB, MB);}
double normOrgAdense = 0.0;
/*HICMA_znormest(M, M, orgAdense, &normOrgAdense, swork);*/
/*printf("norm_L_OrgAdense:%e\n",normOrgAdense);*/
free(orgAdense);
}
}
PASTE_TILE_TO_LAPACK( descDense, Adense2, check, double, LDA, M );
PROGRESS("pasting original dense descAD into Adense and Adense2 finished");
PROGRESS("potrf started");
START_TIMING();
HICMA_zpotrf_Tile(MorseLower, descAUV, descAD, descArk, fixedrank, maxrank, fixedacc );
STOP_TIMING();
fflush(stderr);
fflush(stdout);
PROGRESS("potrf finished");
if(check){
HICMA_zuncompress(MorseLower, descAUV, descDense, descArk);
HICMA_zdiag_vec2mat(descAD, descDense);
PASTE_CODE_FREE_MATRIX( descAD ); //@KADIRLBL001
descAD = descDense; // descAD was only diagonals.
// After this line, descAD is dense matrix containing approximate L
// So no need to adapt below code for descAD containg only diagonals.
}
if(calc_rank_stat == 1) {
PASTE_TILE_TO_LAPACK( descArk, Ark_final, 1, double, MT, NT );
if(MORSE_My_Mpi_Rank()==0){
sprintf(rankfile, "%s-2", rankfile);
fwrite_array(descArk->m, descArk->n, descArk->m, Ark_final, rankfile);
HICMA_stat_t hicma_statrk_final;
zget_stat(MorseLower, Ark_final, MT, NT, MT, &hicma_statrk_final);
printf("final_ranks:");
zprint_stat(hicma_statrk_final);
fflush(stderr);
fflush(stdout);
}
}
int check_dense = 0;
int check_app = 1;
if(check == 0){
check_dense = check_app = 0;
}
if(check_app ) {
PROGRESS("checking accuracy");
if( MORSE_My_Mpi_Rank()==0){
#ifndef COMPLEX
if(main_print_mat){printf("Adense2\n");printmat(Adense2,M,M,LDA,MB, MB);}
double normA;
{size_t i, j;
for(j = 0; j < M; j++){
for(i = 0; i < j; i++){
Adense2[j*LDA+i] = zero;
}
}
}
PROGRESS("normaA started");
HICMA_znormest(M, M, Adense2, &normA, swork);
// Ahicma: result of TLR potrf
PASTE_TILE_TO_LAPACK( descAD, Ahicma, check, double, LDA, M );
/*if(0){size_t i,j;*/
/*for(j = 0; j < M; j++) { */
/*for(i = 0; i < M; i++){*/
/*Ahicma[j*LDA+i] = cp_L_Adense[j*LDA+i];*/
/*}*/
/*}*/
/*}*/
double normAhicma = 0.0;
{size_t i, j;
for(j = 0; j < M; j++){
for(i = 0; i < j; i++){
Ahicma[j*LDA+i] = zero;
}
}
double* orgAhicma = calloc(LDA*M, sizeof(double));
for(j = 0; j < M; j++){
for(i = 0; i < M; i++){
orgAhicma[j*LDA+i] = Ahicma[j*LDA+i];
}
}
HICMA_znormest(M, M, orgAhicma, &normAhicma, swork);
free(orgAhicma);
}
if(set_diag){size_t j; for(j = 0; j < M; j++){ Ahicma[j*LDA+j] = diagVal; } }
if(main_print_mat){printf("Ahicma\n");printmat(Ahicma,M,M,LDA, MB, MB);}
//LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', M, Ahicma, LDA);
// AhicmaT: transpose of Ahicma
PROGRESS("copy descAd into AhicmaT started");
PASTE_TILE_TO_LAPACK( descAD, AhicmaT, check, double, LDA, M );
{size_t i, j;
for(j = 0; j < M; j++){
for(i = 0; i < j; i++){
Adense[j*LDA+i] = zero;
}
}
}
if(main_print_mat){printf("Ahicma-upperzero\n");printmat(Ahicma,M,M,LDA, MB, MB);}
PROGRESS("Transpose A started");
LAPACKE_dge_trans(LAPACK_COL_MAJOR, M, M, Ahicma, LDA, AhicmaT, LDA);
if(main_print_mat){printf("AhicmaT\n");printmat(AhicmaT,M,M,LDA, MB, MB);}
PROGRESS("TRMM started");
cblas_dtrmm (CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, M, M, one, Ahicma, LDA, AhicmaT, LDA);
if(main_print_mat){printf("Ahicma*AhicmaT\n");printmat(AhicmaT,M,M,LDA, MB, MB);}
//double tmpnorm;normest(M, M, AhicmaT, &tmpnorm, swork);printf("tmpnorm:%e\n",tmpnorm);
{size_t i, j;
for(j = 0; j < M; j++){
for(i = 0; i < j; i++){
AhicmaT[j*LDA+i] = zero;
}
}
}
size_t nelm = M * M;
if(main_print_mat)printf("nelm:%zu M:%d N:%d\n", nelm, M, N);
PROGRESS("DAXPY started");
cblas_daxpy(nelm, minusone, AhicmaT, 1, Adense, 1);
if(main_print_mat){printf("Adense-(Ahicma*AhicmaT)\n");printmat(Adense,M,M,LDA, MB, MB);}
double normDenseAppDiff;
PROGRESS("Norm of difference started");
HICMA_znormest(M, M, Adense, &normDenseAppDiff, swork);
double accuracyDenseAppDiff = normDenseAppDiff/normA;
//printf("normA:%.2e normDenseAppdiff:%.2e Accuracy: %.2e\n", normA, normDenseAppDiff, accuracyDenseAppDiff);
dparam[IPARAM_RES] = normDenseAppDiff;
dparam[IPARAM_ANORM] = normA;
dparam[IPARAM_XNORM] = normA;
dparam[IPARAM_BNORM] = normAhicma;
#endif
} else {
PASTE_TILE_TO_LAPACK( descAD, Ahicma, check, double, LDA, M );
PASTE_TILE_TO_LAPACK( descAD, AhicmaT, check, double, LDA, M );
}
PROGRESS("checking accuracy is finished");
}
PASTE_CODE_FREE_MATRIX( descAUV );
PROGRESS("descAUV is freed");
if(check == 0) { // If there is no check, then descAD and descDense are different. Refer to @KADIRLBL001
PASTE_CODE_FREE_MATRIX( descAD );
PROGRESS("descAD is freed");
}
PASTE_CODE_FREE_MATRIX( descArk );
PROGRESS("descArk is freed");
PASTE_CODE_FREE_MATRIX( descDense );
PROGRESS("descDense is freed");
PROGRESS("freed descs");
return 0;
}
| {
"alphanum_fraction": 0.5805419245,
"avg_line_length": 34.9776119403,
"ext": "c",
"hexsha": "c59d8e055c23094fe639c75a8d8009b72c278acc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-08T11:05:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-08T11:05:38.000Z",
"max_forks_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "isabella232/hicma",
"max_forks_repo_path": "timing/time_zpotrf_tile.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534",
"max_issues_repo_issues_event_max_datetime": "2021-04-08T11:06:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-04-08T11:06:39.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Quansight/hicma",
"max_issues_repo_path": "timing/time_zpotrf_tile.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Quansight/hicma",
"max_stars_repo_path": "timing/time_zpotrf_tile.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5515,
"size": 18748
} |
#ifndef __GSL_VERSION_H__
#define __GSL_VERSION_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
#define GSL_VERSION "2.4"
#define GSL_MAJOR_VERSION 2
#define GSL_MINOR_VERSION 4
GSL_VAR const char * gsl_version;
__END_DECLS
#endif /* __GSL_VERSION_H__ */
| {
"alphanum_fraction": 0.7510853835,
"avg_line_length": 18.6756756757,
"ext": "h",
"hexsha": "ed7cb3275663921dcc3c0ee3b8723a89f0708a04",
"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": "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_version.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_version.h",
"max_line_length": 48,
"max_stars_count": null,
"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_version.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 186,
"size": 691
} |
#include <stdio.h>
#include <cblas.h>
int main(void)
{
float a[] = { 1, 2, 3, 4, 5, 6 };
float b[] = { 0, 0, 0, 0, 0, 0 };
const int n = sizeof a / sizeof a[0];
int i;
cblas_scopy(n/2, a, 2, b, 2); /* copy every other element */
for (i = 0; i < n; ++i)
printf("%f ", b[i]);
putchar('\n');
return 0;
}
| {
"alphanum_fraction": 0.5063694268,
"avg_line_length": 17.4444444444,
"ext": "c",
"hexsha": "bf1699535837b8197475c625fae6760fd0b4dbdf",
"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": "ddc7a3648845abe98d516287ba11ba591cda1150",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "ecashin/mmm-blog",
"max_forks_repo_path": "listings/incdemo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ddc7a3648845abe98d516287ba11ba591cda1150",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "ecashin/mmm-blog",
"max_issues_repo_path": "listings/incdemo.c",
"max_line_length": 61,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ddc7a3648845abe98d516287ba11ba591cda1150",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "ecashin/mmm-blog",
"max_stars_repo_path": "listings/incdemo.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 134,
"size": 314
} |
/**
* @license BSD 3-Clause
* @copyright Pawel Okas
* @version $Id$
* @brief
*
* @authors Pawel Okas
* created on: 30-03-2019
*
* @copyright Copyright (c) 2019, Pawel Okas
* 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.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _AT24MAC_H_
#define _AT24MAC_H_
#include <charconv>
#include <gsl/span>
#include <optional>
#include <string_view>
#include "I2CDevice/I2CDevice.h"
#include "microhal.h"
/**
* \addtogroup Devices
* @{
* @class AT24MAC
* @}
*/
class AT24MAC {
public:
using I2C = microhal::I2C;
enum class Error {
AcknowledgeFailure = static_cast<int>(I2C::Error::AcknowledgeFailure),
ArbitrationLost = static_cast<int>(I2C::Error::ArbitrationLost),
Bus = static_cast<int>(I2C::Error::Bus),
None = static_cast<int>(I2C::Error::None),
Overrun = static_cast<int>(I2C::Error::Overrun),
Timeout = static_cast<int>(I2C::Error::Timeout),
Unknown = static_cast<int>(I2C::Error::Unknown),
DataOverflow,
Addres
};
struct SerialNumber {
uint8_t serial[128 / 8];
bool operator!=(SerialNumber b) { return std::equal(std::begin(serial), std::begin(serial) + sizeof(serial), std::begin(b.serial)); }
std::string toString() const {
std::string str;
str.reserve(18);
for (uint_fast8_t i = 0; i < sizeof(serial); i++) {
std::array<char, 2> buff;
auto [p, ec] = std::to_chars(buff.data(), buff.data() + buff.size(), serial[i], 16);
str.append(std::string_view(buff.data(), p - str.data()));
if (i + 1 != sizeof(serial)) {
str.append(":");
}
}
return str;
}
};
static constexpr const size_t pageSize = 16;
static constexpr const size_t memorySizeInBytes = 256;
private:
using Endianness = microhal::Endianness;
using Access = microhal::Access;
using span = gsl::span<uint8_t>; // Todo change to std::span when it will be available in gcc
// create alias to microhal::Address, we just want to type less
template <typename T, T i>
using Address = microhal::Address<T, i>;
struct Register {
static constexpr auto SerialNumberReg =
microhal::makeRegister<SerialNumber, Access::ReadOnly, Endianness::Little>(Address<uint8_t, 0b1000'0000>{});
static constexpr auto EUIAddress = microhal::makeRegister<uint64_t, Access::ReadOnly, Endianness::Big>(Address<uint8_t, 0b1001'1000>{});
};
static constexpr uint8_t getMACi2cAddrFromMemoryI2cAddr(uint8_t memoryAddress) { return (memoryAddress & 0x0F) | 0xB0; }
public:
AT24MAC(I2C &i2c, uint8_t address) : memory(i2c, address), mac(i2c, getMACi2cAddrFromMemoryI2cAddr(address)) {}
static std::string_view toString(Error error);
Error readEUI(uint64_t &eui) { return static_cast<Error>(mac.readRegister(Register::EUIAddress, eui)); }
Error readSerialNumber(SerialNumber &serial) { return static_cast<Error>(mac.readRegister(Register::SerialNumberReg, serial)); }
// Memory access functions
Error readByte(uint8_t address, uint8_t &data) { return static_cast<Error>(memory.read(address, data)); }
Error read(uint8_t address, span data) { return static_cast<Error>(memory.read(address, data)); }
Error writeByte(uint8_t address, uint8_t data) { return static_cast<Error>(memory.write(address, data)); }
Error writePage(uint8_t pageAddress, span data) {
if (data.size_bytes() > 16) return Error::DataOverflow;
if ((pageAddress % 16) != 0) return Error::Addres;
return static_cast<Error>(memory.write(pageAddress, data));
}
Error write(uint8_t address, span data) {
if (data.size_bytes() > memorySizeInBytes) return Error::DataOverflow;
uint_fast8_t bytesInFirstPage = pageSize - (address % pageSize);
span firstPage(data.data(), bytesInFirstPage);
writePage(address, firstPage);
address += bytesInFirstPage;
uint_fast8_t bytesToWrite = (data.size_bytes() - bytesInFirstPage);
uint8_t *dataPtr = data.data() + bytesInFirstPage;
while (bytesToWrite / pageSize) {
span page(dataPtr, pageSize);
writePage(address, page);
address += pageSize;
dataPtr += pageSize;
bytesToWrite -= pageSize;
}
uint_fast8_t lastPageSize = bytesToWrite % pageSize;
if (lastPageSize) {
span page(dataPtr, lastPageSize);
writePage(address, page);
}
return Error::None;
}
void writeWait() { std::this_thread::sleep_for(std::chrono::milliseconds{5}); }
private:
microhal::I2CDevice memory;
microhal::I2CDevice mac;
};
#endif /* _AT24MAC_H_ */
| {
"alphanum_fraction": 0.6719122556,
"avg_line_length": 41.6622516556,
"ext": "h",
"hexsha": "0ceeeaac071404bfc8510dc5f19319464124766f",
"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": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "microHAL/microhal-drivers",
"max_forks_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b",
"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": "microHAL/microhal-drivers",
"max_issues_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h",
"max_line_length": 148,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "09925a9696e4794f9ca0b2e9b5e61908ac99b84b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "microHAL/microhal-drivers",
"max_stars_repo_path": "drivers/Atmel/AT24MAC/driver/at24mac.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1531,
"size": 6291
} |
/*
* PIController.h
*
* Created on: Mar 31, 2013
* Author: vgomez, Sep Thijssen
*/
#ifndef PICONTROLLER_H_
#define PICONTROLLER_H_
#define VERB_LEVEL 1
#include "global.h"
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <Eigen/Dense>
using namespace Eigen;
class PIController {
public:
static double dt; // time increment (required in Model)
static int units; // number of UAVs (required in PIController and Model)
static double R; // control (required in Model)
static double nu; // noise level
static double lambda; // PI scalar ratio = nu*R
static int dtperstep; // number of dt per control step
static int H; // number of steps in horizon
static double dS; // duration of a control step = dt*dtperstep
static double stdv; // local standard deviation = sqrt(nu/dS)
static int dimUAVx;
static int dimUAVu;
static int seed;
protected:
gsl_rng *r; // Random seed.
int dimX; // dimension state
int dimU; // dimension control
int N; // number of rollouts applied each step
double stdv_dt; // new time scale for noise
vvec u_exp; // [H][dimU] current best, used for exploring
std::string outfile_matlab; // name of the output .m file
std::string outfile_costs; // name of a log file with costs (comma separated values format)
boost::property_tree::ptree pt;
// needed for feedback
vector<MatrixXd> A,lhs,dlhs,rhs,drhs;
int dimF;
public :
// nested class Model used by the PIController to simulate dynamics
class Model {
protected:
vec state; // [dimX] running state
PIController *ctrl; // pointer to PIController object (outer class)
public:
Model() {};
virtual ~Model() {};
// apply control uuu on the current state
virtual void step(const vec&) = 0;
// replaces the current state
void setState(const vec& X0) { state = X0; }
// returns the current state
vec getState() const { return state; }
// replaces the current state
void setController(PIController *_ctrl) { ctrl = _ctrl; }
// sets the concrete model (implemented by subclass)
virtual void setProperties() = 0;
// Output is the immediate state reward
// writes in of the components of the reward to be logged
virtual double immediateStateReward(std::ofstream &of) = 0;
// Output is the immediate state reward
// sets different attributes of the subclass to be logged if necessary
virtual double immediateStateReward() = 0;
// Output is the end state reward. Input is a state.
double endStateReward() { return immediateStateReward(); };
};
private:
protected:
Model *model; // The dynamical model the PIController uses
public:
PIController() {};
virtual ~PIController() { unsetModel(); };
void Init(const boost::property_tree::ptree &pt);
void setSeed(const double &s) { seed = s; };
// sets the concrete model (implemented by subclass)
void setModel();
// unsets the concrete model (implemented by subclass)
void unsetModel();
// Returns state based reward of a rollout
double runningStateReward(const vec&, const vvec&);
// Returns the cost of a control sequence.
double runningControlCost(const vvec&) const;
vec predictState(const vec& X, const vec& A);
// Output is the immediate control cost. Input is a control action.
double immediateControlCost(const vec&) const;
// double immediateStateReward(const vec& X) { model->setState(X); return model->immediateStateReward(); }
void printTime() const;
void plotCurrent(const vec&, const vec&) const;
void plotSetup() const;
boost::property_tree::ptree getProperties() { return pt; }
// The PI-control algorithm, input is a state, output is control (VelHeight)
vec computeControl(const vec &);
// PI-Controller with feedback, input is a state, output is control (VelHeight)
// property A is updated
vec computeControlFeedback(const vec &);
};
#endif /* PICONTROLLER_H_ */
| {
"alphanum_fraction": 0.7108886108,
"avg_line_length": 27.1768707483,
"ext": "h",
"hexsha": "e63864a9e83f8951208ad33bd5bace574ff6a901",
"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": "711c9fafbdc775114345ab0ca389656db9d20df7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jiangchenzhu/crates_zhejiang",
"max_forks_repo_path": "thirdparty/cm_picontrol/pi/PIController.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7",
"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": "jiangchenzhu/crates_zhejiang",
"max_issues_repo_path": "thirdparty/cm_picontrol/pi/PIController.h",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jiangchenzhu/crates_zhejiang",
"max_stars_repo_path": "thirdparty/cm_picontrol/pi/PIController.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1019,
"size": 3995
} |
#pragma once
#include "Ds4Color.h"
#include <gsl/span>
/**
* \brief PoD for setting \c Ds4Device parameters like motor speed, light color, etc.
*/
struct Ds4Output
{
uint8_t rightMotor = 0;
uint8_t leftMotor = 0;
Ds4Color lightColor = {};
uint8_t flashOnDur = 0;
uint8_t flashOffDur = 0;
uint8_t volumeLeft = 50;
uint8_t volumeRight = 50;
uint8_t volumeMic = 50;
uint8_t volumeSpeaker = 50;
/**
* \brief Updates a buffer with the stored device parameters.
* \param buffer Buffer to update.
* \return \c true if changes have been made to \a buffer.
*/
bool update(const gsl::span<uint8_t>& buffer) const;
};
| {
"alphanum_fraction": 0.66918429,
"avg_line_length": 24.5185185185,
"ext": "h",
"hexsha": "6ff7fa24edf3b9874bfb275a1c9604a70907eb93",
"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": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SonicFreak94/ds4wizard",
"max_forks_repo_path": "ds4wizard-cpp/Ds4Output.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SonicFreak94/ds4wizard",
"max_issues_repo_path": "ds4wizard-cpp/Ds4Output.h",
"max_line_length": 85,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SonicFreak94/ds4wizard",
"max_stars_repo_path": "ds4wizard-cpp/Ds4Output.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z",
"num_tokens": 204,
"size": 662
} |
/* multimin/test_funcs.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 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_multimin.h>
#include "test_funcs.h"
gsl_multimin_function_fdf rosenbrock =
{&rosenbrock_f,
&rosenbrock_df,
&rosenbrock_fdf,
2, 0};
gsl_multimin_function rosenbrock_fmin =
{&rosenbrock_f,
2, 0};
void rosenbrock_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, -1.2);
gsl_vector_set (x, 1, 1.0);
}
double rosenbrock_f (const gsl_vector * x, void *params)
{
double u = gsl_vector_get(x,0);
double v = gsl_vector_get(x,1);
double a = u - 1;
double b = u * u - v;
fcount++;
return a * a + 10 * b * b;
}
void rosenbrock_df (const gsl_vector * x, void *params, gsl_vector * df)
{
double u = gsl_vector_get(x,0);
double v = gsl_vector_get(x,1);
double b = u * u - v;
gcount++;
gsl_vector_set(df,0,2 * (u - 1) + 40 * u * b);
gsl_vector_set(df,1,-20 * b);
}
void rosenbrock_fdf (const gsl_vector * x, void *params, double * f,
gsl_vector * df)
{
double u = gsl_vector_get(x,0);
double v = gsl_vector_get(x,1);
double a = u - 1;
double b = u * u - v;
gcount++;
*f = a * a + 10 * b * b;
gsl_vector_set(df,0,2 * (u - 1) + 40 * u * b);
gsl_vector_set(df,1,-20 * b);
}
gsl_multimin_function_fdf roth =
{&roth_f,
&roth_df,
&roth_fdf,
2, 0};
gsl_multimin_function roth_fmin =
{&roth_f,
2, 0};
void roth_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, 4.5);
gsl_vector_set (x, 1, 3.5);
}
double roth_f (const gsl_vector * x, void *params)
{
double u = gsl_vector_get(x,0);
double v = gsl_vector_get(x,1);
double a = -13.0 + u + ((5.0 - v)*v - 2.0)*v;
double b = -29.0 + u + ((v + 1.0)*v - 14.0)*v;
fcount++;
return a * a + b * b;
}
void roth_df (const gsl_vector * x, void *params, gsl_vector * df)
{
double u = gsl_vector_get(x,0);
double v = gsl_vector_get(x,1);
double a = -13.0 + u + ((5.0 - v)*v - 2.0)*v;
double b = -29.0 + u + ((v + 1.0)*v - 14.0)*v;
double c = -2 + v * (10 - 3 * v);
double d = -14 + v * (2 + 3 * v);
gcount++;
gsl_vector_set(df,0,2 * a + 2 * b);
gsl_vector_set(df,1,2 * a * c + 2 * b * d);
}
void roth_fdf (const gsl_vector * x, void *params, double * f,
gsl_vector * df)
{
*f = roth_f (x,params);
roth_df(x,params,df);
}
gsl_multimin_function_fdf wood =
{&wood_f,
&wood_df,
&wood_fdf,
4, 0};
gsl_multimin_function wood_fmin =
{&wood_f,
4, 0};
void
wood_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, -3.0);
gsl_vector_set (x, 1, -1.0);
gsl_vector_set (x, 2, -3.0);
gsl_vector_set (x, 3, -1.0);
}
double wood_f (const gsl_vector * x, void *params)
{
double u1 = gsl_vector_get(x,0);
double u2 = gsl_vector_get(x,1);
double u3 = gsl_vector_get(x,2);
double u4 = gsl_vector_get(x,3);
double t1 = u1 * u1 - u2;
double t2 = u3 * u3 - u4;
fcount++;
return 100 * t1 * t1 + (1 - u1) * (1 - u1)
+ 90 * t2 * t2 + (1 - u3) * (1 - u3)
+ 10.1 * ( (1 - u2) * (1 - u2) + (1 - u4) * (1 - u4) )
+ 19.8 * (1 - u2) * (1 - u4);
}
void wood_df (const gsl_vector * x, void *params, gsl_vector * df)
{
double u1 = gsl_vector_get(x,0);
double u2 = gsl_vector_get(x,1);
double u3 = gsl_vector_get(x,2);
double u4 = gsl_vector_get(x,3);
double t1 = u1 * u1 - u2;
double t2 = u3 * u3 - u4;
gcount++;
gsl_vector_set(df,0, 400 * u1 * t1 - 2 * (1 - u1) );
gsl_vector_set(df,1, -200 * t1 - 20.2 * (1 - u2) - 19.8 * (1 - u4) );
gsl_vector_set(df,2, 360 * u3 * t2 - 2 * (1 - u3) );
gsl_vector_set(df,3, -180 * t2 - 20.2 * (1 - u4) - 19.8 * (1 - u2) );
}
void wood_fdf (const gsl_vector * x, void *params, double * f, gsl_vector * df)
{
wood_df(x,params,df);
*f=wood_f(x,params);
}
gsl_multimin_function_fdf Nrosenbrock =
{&rosenbrock_f,
&Nrosenbrock_df,
&Nrosenbrock_fdf,
2, 0};
void Nrosenbrock_df (const gsl_vector * x, void *params, gsl_vector * df)
{
gsl_multimin_function F ;
F.f = rosenbrock_f;
F.params = params;
F.n = x->size;
gsl_multimin_diff (&F, x, df);
}
void Nrosenbrock_fdf (const gsl_vector * x, void *params, double * f,
gsl_vector * df)
{
*f = rosenbrock_f (x, params);
Nrosenbrock_df (x, params, df);
}
gsl_multimin_function_fdf Nroth =
{&roth_f,
&Nroth_df,
&Nroth_fdf,
2, 0};
void Nroth_df (const gsl_vector * x, void *params, gsl_vector * df)
{
gsl_multimin_function F ;
F.f = roth_f;
F.params = params;
F.n = x->size;
gsl_multimin_diff (&F, x, df);
}
void Nroth_fdf (const gsl_vector * x, void *params, double * f,
gsl_vector * df)
{
*f = roth_f (x, params);
Nroth_df (x, params, df);
}
gsl_multimin_function_fdf Nwood =
{&wood_f,
&Nwood_df,
&Nwood_fdf,
4, 0};
void Nwood_df (const gsl_vector * x, void *params, gsl_vector * df)
{
gsl_multimin_function F ;
F.f = wood_f;
F.params = params;
F.n = x->size;
gsl_multimin_diff (&F, x, df);
}
void Nwood_fdf (const gsl_vector * x, void *params, double * f,
gsl_vector * df)
{
*f = wood_f (x, params);
Nwood_df (x, params, df);
}
| {
"alphanum_fraction": 0.6161301488,
"avg_line_length": 23.5836734694,
"ext": "c",
"hexsha": "34081af1881d4d1a93378b347a0f7834ae8b97ca",
"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/multimin/test_funcs.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/multimin/test_funcs.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/multimin/test_funcs.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": 2140,
"size": 5778
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
/************************************************************************************************************************************************************************/
/***********\\Global variable\\******************************************************************************************************************************************/
size_t limit = 100; // Limit for the convergence of the integrale
size_t size = 100;
double kmin, // minimum k in the power spectrum file (define in main function)
kmax, // minimum k in the power spectrum file (define in main function)
lk, // lk = kmax-kmin lenth for the integral calculation (define in main function)
q_v[3], // unit vector q_i, q_j, q_k
sig8; // Value of sigma 8 (define in main function)
struct my_f_params {double a; double b; double c; double d;};
gsl_interp_accel *acc[25];
gsl_spline *spline[25]; //Use for interpolation
/************************************************************************************************************************************************************************/
/*******************\\ Gauss-Legendre integral quadrature\\***********************************************************************************************************/
static const double x[] = {
1.56289844215430828714e-02, 4.68716824215916316162e-02,
7.80685828134366366918e-02, 1.09189203580061115002e-01,
1.40203137236113973212e-01, 1.71080080538603274883e-01,
2.01789864095735997236e-01, 2.32302481844973969643e-01,
2.62588120371503479163e-01, 2.92617188038471964730e-01,
3.22360343900529151720e-01, 3.51788526372421720979e-01,
3.80872981624629956772e-01, 4.09585291678301542532e-01,
4.37897402172031513100e-01, 4.65781649773358042251e-01,
4.93210789208190933576e-01, 5.20158019881763056670e-01,
5.46597012065094167460e-01, 5.72501932621381191292e-01,
5.97847470247178721259e-01, 6.22608860203707771585e-01,
6.46761908514129279840e-01, 6.70283015603141015784e-01,
6.93149199355801965946e-01, 7.15338117573056446485e-01,
7.36828089802020705530e-01, 7.57598118519707176062e-01,
7.77627909649495475605e-01, 7.96897892390314476375e-01,
8.15389238339176254384e-01, 8.33083879888400823522e-01,
8.49964527879591284320e-01, 8.66014688497164623416e-01,
8.81218679385018415547e-01, 8.95561644970726986709e-01,
9.09029570982529690453e-01, 9.21609298145333952679e-01,
9.33288535043079545942e-01, 9.44055870136255977955e-01,
9.53900782925491742847e-01, 9.62813654255815527284e-01,
9.70785775763706331929e-01, 9.77809358486918288561e-01,
9.83877540706057015509e-01, 9.88984395242991747997e-01,
9.93124937037443459632e-01, 9.96295134733125149166e-01,
9.98491950639595818382e-01, 9.99713726773441233703e-01
};
static const double A[] = {
3.12554234538633569472e-02, 3.12248842548493577326e-02,
3.11638356962099067834e-02, 3.10723374275665165874e-02,
3.09504788504909882337e-02, 3.07983790311525904274e-02,
3.06161865839804484966e-02, 3.04040795264548200160e-02,
3.01622651051691449196e-02, 2.98909795933328309169e-02,
2.95904880599126425122e-02, 2.92610841106382766198e-02,
2.89030896011252031353e-02, 2.85168543223950979908e-02,
2.81027556591011733175e-02, 2.76611982207923882944e-02,
2.71926134465768801373e-02, 2.66974591835709626611e-02,
2.61762192395456763420e-02, 2.56294029102081160751e-02,
2.50575444815795897034e-02, 2.44612027079570527207e-02,
2.38409602659682059633e-02, 2.31974231852541216230e-02,
2.25312202563362727021e-02, 2.18430024162473863146e-02,
2.11334421125276415432e-02, 2.04032326462094327666e-02,
1.96530874944353058650e-02, 1.88837396133749045537e-02,
1.80959407221281166640e-02, 1.72904605683235824399e-02,
1.64680861761452126430e-02, 1.56296210775460027242e-02,
1.47758845274413017686e-02, 1.39077107037187726882e-02,
1.30259478929715422855e-02, 1.21314576629794974079e-02,
1.12251140231859771176e-02, 1.03078025748689695861e-02,
9.38041965369445795116e-03, 8.44387146966897140266e-03,
7.49907325546471157895e-03, 6.54694845084532276405e-03,
5.58842800386551515727e-03, 4.62445006342211935096e-03,
3.65596120132637518238e-03, 2.68392537155348241939e-03,
1.70939265351810523958e-03, 7.34634490505671730396e-04
};
#define NUM_OF_POSITIVE_ZEROS sizeof(x) / sizeof(double)
#define NUM_OF_ZEROS NUM_OF_POSITIVE_ZEROS+NUM_OF_POSITIVE_ZEROS
double
gl_int(double a, double b, double (*f)(double, void *), void *prms)
{
double integral = 0.0;
double c = 0.5 * (b - a);
double d = 0.5 * (b + a);
double dum;
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
for (; px >= x; pA--, px--) {
dum = c * *px;
integral += *pA * ( (*f)(d - dum,prms) + (*f)(d + dum,prms) );
}
return c * integral;
}
void
gl_int2(double a, double b, void (*f)(double, double, double*,double*), void *prms,double *int1,double *int2)
{
double integral1 = 0.0;
double integral2 = 0.0;
double c = 0.5 * (b - a);
double d = 0.5 * (b + a);
double dum;
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
double outi[2], outs[2];
double R=* (double *)prms;
for (; px >= x; pA--, px--) {
dum = c * *px;
(*f)(d - dum,R,&outi[0],&outi[1]);
(*f)(d + dum,R,&outs[0],&outs[1]);
integral1 += *pA * (outi[0] + outs[0]);
integral2 += *pA * (outi[1] + outs[1]);
}
*int1 = c * integral1;
*int2 = c * integral2;
}
void
gl_int5(double a, double b, void (*f)(double, double, double*,double*,double*,double*,double*), void *prms, double *int1,double *int2, double *int3, double *int4, double *int5)
{
double integral1 = 0.0;
double integral2 = 0.0;
double integral3 = 0.0;
double integral4 = 0.0;
double integral5 = 0.0;
double c = 0.5 * (b - a);
double d = 0.5 * (b + a);
double dum;
double outi[5],outs[5];
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
double R=* (double *)prms;
for (; px >= x; pA--, px--) {
dum = c * *px;
(*f)(d - dum,R,&outi[0],&outi[1],&outi[2],&outi[3],&outi[4]);
(*f)(d + dum,R,&outs[0],&outs[1],&outs[2],&outs[3],&outs[4]);
integral1 += *pA * (outi[0] + outs[0]);
integral2 += *pA * (outi[1] + outs[1]);
integral3 += *pA * (outi[2] + outs[2]);
integral4 += *pA * (outi[3] + outs[3]);
integral5 += *pA * (outi[4] + outs[4]);
}
*int1 = c * integral1;
*int2 = c * integral2;
*int3 = c * integral3;
*int4 = c * integral4;
*int5 = c * integral5;
}
void
gl_int6(double a, double b, void (*f)(double, double, double []), void *prms,double result[], int n)
{
int i;
double integral[n];
for (i=0; i<n; i++)
integral[i] = 0;
double c = 0.5 * (b - a);
double d = 0.5 * (b + a);
double dum;
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
double outi[n], outs[n];
double R=* (double *)prms;
for (; px >= x; pA--, px--) {
dum = c * *px;
(*f)(d - dum,R,outi);
(*f)(d + dum,R,outs);
for (i=0; i<n; i++)
integral[i] += *pA * (outi[i] + outs[i]);
}
for (i=0; i<n; i++)
result[i] = c*integral[i];
}
void Gauss_Legendre_Zeros_100pts( double zeros[] ) {
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
double *pz = &zeros[NUM_OF_ZEROS - 1];
for (; px >= x; px--) {
*(zeros++) = - *px;
*(pz--) = *px;
}
}
void Gauss_Legendre_Coefs_100pts( double coefs[] ) {
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
double *pc = &coefs[NUM_OF_ZEROS - 1];
for (; pA >= A; pA--) {
*(coefs++) = *pA;
*(pc--) = *pA;
}
}
/************************************************************************************************************************************************************************/
/****************************\\gsl_cquad integration \\*****************************************************************************************************************/
double int_cquad (double func(double, void*), double alpha)
{
double result, error;
gsl_function F;
F.function = func;
F.params = α
gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(size);
gsl_integration_cquad(&F, kmin, kmax, 0, 1e-9, w, &result, &error, NULL);
gsl_integration_cquad_workspace_free(w);
return result;
}
/************************************************************************************************************************************************************************/
/****************************\\Bessel function\\************************************************************************************************************************/
double func_bessel_0(double x)
{
return sin(x)/x;
}
double func_bessel_1(double x)
{
return sin(x)/(x*x)-cos(x)/x;
}
double func_bessel_2 (double x)
{
return (3./(x*x)-1)*sin(x)/x-3*cos(x)/(x*x);
}
double func_bessel_3 (double x)
{
return (15./pow(x,3)-6./(x))*sin(x)/x-(15./(x*x)-1)*cos(x)/x;
}
/************************************************************************************************************************************************************************/
/********************************\\ Interpolation Function \\***********************************************************************************************************/
double P_L (double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[1], k, acc[1]);
else return 0;
}
double R_1(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[2], k, acc[2]);
else return 0;
}
double R_2(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[3], k, acc[3]);
else return 0;
}
double Q_1(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[4], k, acc[4]);
else return 0;
}
double Q_2(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[5], k, acc[5]);
else return 0;
}
double Q_5(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[6], k, acc[6]);
else return 0;
}
double Q_8(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[7], k, acc[7]);
else return 0;
}
double iXi_L(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[8], q, acc[8]);
else return 0;
}
double iU_1(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[9], q, acc[9]);
else return 0;
}
double iU_3(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[10], q, acc[10]);
else return 0;
}
double iU_11(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[11], q, acc[11]);
else return 0;
}
double iU_20(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[12], q, acc[12]);
else return 0;
}
double iX_11(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[13], q, acc[13]);
else return 0;
}
double iX_13(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[14], q, acc[14]);
else return 0;
}
double iX_22(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[15], q, acc[15]);
else return 0;
}
double iX_10_12(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[16], q, acc[16]);
else return 0;
}
double iY_11(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[17], q, acc[17]);
else return 0;
}
double iY_13(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[18], q, acc[18]);
else return 0;
}
double iY_22(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[19], q, acc[19]);
else return 0;
}
double iY_10_12(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[20], q, acc[20]);
else return 0;
}
double iW_V1(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[21], q, acc[21]);
else return 0;
}
double iW_V3(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[22], q, acc[22]);
else return 0;
}
double iW_T(double q)
{
if (q>0 && q<=1999) return gsl_spline_eval (spline[23], q, acc[23]);
else return 0;
}
double iXi_R(double r)
{
if (r>0 && r<=129) return gsl_spline_eval (spline[24], r, acc[24]);
else return 0;
}
/************************************************************************************************************************************************************************/
/*****************\\delta kronecker\\***********************************************************************************************************************************/
int delta_K (int i, int j)
{
if (i == j) return 1;
else return 0;
}
/************************************************************************************************************************************************************************/
/***************************************************\\Sigma 8\\*********************************************************************************************************/
double fS8 (double k, void * params)
{
double x = k*8;
return P_L(k)*k*k*(sin(x)-x*cos(x))*(sin(x)-x*cos(x))/pow(x,6);
}
double S8 (void)
{
double result, error;
gsl_function F;
F.function = &fS8;
gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(size);
gsl_integration_cquad(&F, 0, 130, 0, 1e-12, w, &result, &error, NULL);
gsl_integration_cquad_workspace_free(w);
return 9./(2.*M_PI*M_PI)*result;
}
/*
double P_L (double k)
{
return Pm(k)/sig8;
}
*/
/************************************************************************************************************************************************************************/
/****************************************\\ R_n FUNCTIONS \\*********************************************************************************************************/
// R_1_tilde function
double fRt1 (double x, void *p)
{
double r = *(double *) p;
return (r*r*(1.-x*x)*(1.-x*x))/(1.+r*r-2.*x*r);
}
double Rt_1 (double r)
{
return gl_int(-1, 1, &fRt1, &r);
}
// R_2_tilde function
double fRt2 (double x, void *p)
{
double r = *(double *) p;
return ((1.-x*x)*r*x*(1.-x*r))/(1.+r*r-2.*r*x);
}
double Rt_2 (double r)
{
return gl_int(-1, 1, &fRt2, &r);
}
// R1 function
double fR_1 (double r, void *p)
{
double k = *(double *) p;
return P_L(k*r)*Rt_1(r);
}
double R1(double k)
{
double result, error;
gsl_function F;
F.function = &fR_1;
F.params = &k;
gsl_integration_workspace *w = gsl_integration_workspace_alloc(200);
gsl_integration_qag(&F, 0, kmax/k, 0, 1e-3, 200, 6, w, &result, &error); // Kmax/k car k*r<=! kmax sinon Pk = 0
gsl_integration_workspace_free(w);
return (k*k*k)/(4.*M_PI*M_PI)*P_L(k)*result;
}
// R2 function
double fR_2 (double r, void *p)
{
double k = *(double *) p;
return P_L(k*r)*Rt_2(r);
}
double R2(double k)
{
double result, error;
gsl_function F;
F.function = &fR_2;
F.params = &k;
gsl_integration_workspace *w = gsl_integration_workspace_alloc(200);
gsl_integration_qag(&F, 0, kmax/k, 0, 5e-3, 200, 6, w, &result, &error);
gsl_integration_workspace_free(w);
return (k*k*k)/(4.*M_PI*M_PI)*P_L(k)*result;//gl_int(0, 800, &fR_2, &k);
}
/*****************Compute R1 and R2 in text files for interpolation*************************************************************************************************/
void calc_R1 ()
{
printf("getting R function 1/2 ...\n");
FILE* f;
double k;
f = fopen("data/func_R1.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, R1(k));
fclose(f);
f = fopen("data/func_R1.dat","a+");
for (k=1; k<(kmax+9.9e-3); k+=0.01)
fprintf(f, "%le %le\n", k, R1(k));
fclose(f);
return;
}
void calc_R2 ()
{
printf("getting R function 2/2 ...\n");
FILE* f;
double k;
f = fopen("data/func_R2.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, R2(k));
fclose(f);
f = fopen("data/func_R2.dat","a+");
for (k=1; k<(kmax+9.9e-3); k+=0.01)
fprintf(f, "%le %le\n", k, R2(k));
fclose(f);
return;
}
/***********************************************************************************************************************************************************************/
/******************************\\FUNCTION Q\\***********************************************************************************************************************/
// Compute Qn(r,x)
double Qt_1 (double r, double x)
{
return (r*r*(1.-x*x)*(1.-x*x))/((1.+r*r-2.*x*r)*(1.+r*r-2.*x*r));
}
double Qt_2 (double r, double x)
{
return ((1.-x*x)*r*x*(1.-x*r))/((1.+r*r-2.*r*x)*(1.+r*r-2.*r*x));
}
double Qt_5 (double r, double x)
{
return (r*x*(1.-x*x))/(1.+r*r-2.*x*r);
}
double Qt_8 (double r, double x)
{
return (r*r*(1.-x*x)) /(1.+r*r-2.*x*r);
}
/***********\\Integration to compute the inner integral of Qn(k)\\**************************************************************************************************/
double lg_Q_n( double x, void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
double k = (params->a);
double r = (params->b);
double n = (params->c);
double y_p = 1.+r*r-2.*x*r;
if (y_p < 0) return 0;
else {
if (n == 1) return P_L(k*sqrt(y_p))*Qt_1(r,x);
if (n == 2) return P_L(k*sqrt(y_p))*Qt_2(r,x);
if (n == 5) return P_L(k*sqrt(y_p))*Qt_5(r,x);
if (n == 8) return P_L(k*sqrt(y_p))*Qt_8(r,x);
else return -1;
}
}
/***********\\Compute Qn(k)\\***************************************************************************************************************************************/
double fQ_n (double r, void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
double k = (params->a);
double n = (params->b);
struct my_f_params par = {k, r, n};
return P_L(k*r)*gl_int(-1, 1, &lg_Q_n, &par);
}
double Q_n (int n, double k)
{
struct my_f_params p = {k, n};
double result, error;
gsl_function F;
F.function = &fQ_n;
F.params = &p;
gsl_integration_workspace *w = gsl_integration_workspace_alloc(200);
gsl_integration_qag(&F, 0, kmax/k, 0, 1e-3, 200, 6, w, &result, &error);
gsl_integration_workspace_free(w);
return (k*k*k)/(4.*M_PI*M_PI)*result;
}
/*************Compute Qn in text file for interpolation*************************************************************************************************************/
void calc_Qn ()
{
FILE* f;
int n;
double k;
for (n=1; n<9; n++){
printf("getting Q function %d/8...\n",n);
switch (n){
case 1:
f = fopen("data/func_Q1.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, Q_n(1,k));
fclose(f);
f = fopen("data/func_Q1.dat","a+");
for (k=1; k<kmax+100; k+=0.1)
fprintf(f, "%le %le\n", k, Q_n(1,k));
fclose(f);
break;
case 2:
f = fopen("data/func_Q2.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, Q_n(2,k));
fclose(f);
f = fopen("data/func_Q2.dat","a+");
for (k=1; k<kmax+100; k+=0.1)
fprintf(f, "%le %le\n", k, Q_n(2,k));
fclose(f);
break;
case 5:
f = fopen("data/func_Q5.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, Q_n(5,k));
fclose(f);
f = fopen("data/func_Q5.dat","a+");
for (k=1; k<kmax+100; k+=0.1)
fprintf(f, "%le %le\n", k, Q_n(5,k));
fclose(f);
break;
case 8:
f = fopen("data/func_Q8.dat","w+");
for (k=kmin; k<1; k+=0.001)
fprintf(f, "%le %le\n", k, Q_n(8,k));
fclose(f);
f = fopen("data/func_Q8.dat","a+");
for (k=1; k<kmax+100; k+=0.1)
fprintf(f, "%le %le\n", k, Q_n(8,k));
fclose(f);
break;
default:
break;
}
}
return;
}
/*******************************************************************************************************************************************************************/
/************************\\Compute Xi linear\\********************************************************************************************************************/
double fXi_L (double k, void * p)
{
double q = *(double *) p;
return P_L(k)*k*k*func_bessel_0(k*q);
}
double Xi_L (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fXi_L, q);
}
/*******************************************************************************************************************************************************************/
/**************\\U function\\**************************************************************************************************************************************/
// U^1(q)
double fU_1 (double k, void *p)
{
double q = *(double *) p;
return -P_L(k)*k*func_bessel_1(k*q);
}
double U_1 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fU_1, q);
}
// U^3(q)
double fU_3 (double k, void *p)
{
double q = *(double *) p;
return -5./21.*R_1(k)*k*func_bessel_1(k*q);
}
double U_3 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fU_3, q);
}
// U_11(q)
double fU_11 (double k, void *p)
{
double q = *(double *) p;
return -6./7.*k*(R_1(k)+R_2(k))*func_bessel_1(k*q);
}
double U_11 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fU_11, q);
}
// U_20(q)
double fU_20 (double k, void *p)
{
double q = *(double *) p;
return -3./7.*k*Q_8(k)*func_bessel_1(k*q);
}
double U_20 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fU_20, q);
}
//Ui(q)
double get_U (double q)
{
return iU_1(q)+iU_3(q);
}
/*******************************************************************************************************************************************************************/
/*******************\\X FUNCTIONS\\*****************************************************************************************************************************/
// X^11(q)
double fX_11 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return P_L(k)*(2./3.-2.*func_bessel_1(x)/x);
}
double X_11 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fX_11, q);
}
// X^22(q)
double fX_22 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return 9./98.*Q_1(k)*(2./3.-2.*func_bessel_1(x)/(x));
}
double X_22 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fX_22, q);
}
// X^13(q)
double fX_13 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return 5./21.*R_1(k)*(2./3.-2.*func_bessel_1(x)/x);
}
double X_13 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fX_13, q);
}
// X_10^12(q)
double fX_10_12 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return 1./14.*(2.*(R_1(k)-R_2(k))+3.*R_1(k)*sin(k*q)/(k*q)-3.*(3.*R_1(k)+4.*R_2(k)+2.*Q_5(k))*func_bessel_1(x)/x);
}
double X_10_12 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fX_10_12, q);
}
/*******************************************************************************************************************************************************************/
/*******************Y FUNCTIONS*****************************************************************************************************************************/
// Y^11(q)
double fY_11 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return P_L(k)*(-2.*sin(k*q)/(k*q)+6.*func_bessel_1(x)/x);
}
double Y_11 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fY_11, q);
}
// Y^22(q)
double fY_22 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return 9./98.*Q_1(k)*(-2.*sin(k*q)/(k*q)+6.*func_bessel_1(x)/x);
}
double Y_22 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fY_22, q);
}
// Y^13(q)
double fY_13 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return 5./21.*R_1(k)*(-2.*sin(k*q)/(k*q)+6.*func_bessel_1(x)/x);
}
double Y_13 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fY_13, q);
}
// Y^10_12(q)
double fY_10_12 (double k, void *p)
{
double q = *(double *) p;
double x = q*k;
return -3./14.*(3.*R_1(k)+4.*R_2(k)+2.*Q_5(k))*(sin(k*q)/(k*q)-3.*func_bessel_1(x)/x);
}
double Y_10_12 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fY_10_12, q);
}
/************************************************************************************************************************************************************************/
/**************************\\V+S et T function\\************************************************************************************************************************/
// V^112_1(q) + S^112 (q)
double fV1_112 (double k, void*p)
{
double q = *(double *) p;
double x = k*q;
return -3./7.*R_1(k)*func_bessel_1(x)/k + 3./(7.*k)*(2.*R_1(k)+4.*R_2(k)+Q_1(k)+2.*Q_2(k))*func_bessel_2(x)/x;
} // V^112_1 + S^112
double V1_112 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fV1_112, q);
}
// V^112_3(q)+ S^112 (q)
double fV3_112 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return -3./7.*Q_1(k)*func_bessel_1(x)/k + 3./(7.*k)*(2.*R_1(k)+4.*R_2(k)+Q_1(k)+2.*Q_2(k))*func_bessel_2(x)/x;
} // V^112_3 + S^112
double V3_112 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fV3_112, q);
}
// T^112(q)
double fT_112 (double k, void *p)
{
double q = *(double *) p;
double x = k*q;
return -3./7.*(2.*R_1(k)+4.*R_2(k)+Q_1(k)+2.*Q_2(k))*func_bessel_3(x)/k;
}
double T_112 (double q)
{
return 1./(2.*M_PI*M_PI)*int_cquad(fT_112, q);
}
/************************************************************************************************************************************************************************/
/***************************\\Compute U, X, Y, V and T (q) in text file for interpolation\\******************************************************************************/
void q_function ()
{
FILE *fx, *fy, *fw, *fu, *fxi;
double q;
printf("getting Xi_L function...\n");
fxi = fopen("data/Xi_L_func.dat","w+");
for (q=0; q<10; q+=.01)
fprintf(fxi,"%lf %lf\n",q, Xi_L(q));
fclose(fxi);
fxi = fopen("data/Xi_L_func.dat","a+");
for (q=11; q<2000; q+=1)
fprintf(fxi,"%lf %lf\n",q, Xi_L(q));
fclose(fxi);
printf("getting U function...\n");
fu = fopen("data/U_func.dat","w+");
for (q=0; q<10; q+=.01)
fprintf(fu,"%lf %lf %lf %lf %lf\n",q, U_1(q), U_3(q), U_11(q), U_20(q));
fclose(fu);
fu = fopen("data/U_func.dat","a+");
for (q=11; q<2000; q+=1)
fprintf(fu,"%lf %lf %lf %lf %lf\n",q, U_1(q), U_3(q), U_11(q), U_20(q));
fclose(fu);
printf("getting X function...\n");
fx = fopen("data/X_func.dat","w+");
for (q=0; q<10; q+=.01)
fprintf(fx,"%lf %lf %lf %lf %lf\n",q, X_11(q), X_13(q), X_22(q), X_10_12(q));
fclose(fx);
fx = fopen("data/X_func.dat","a+");
for (q=11; q<2000; q+=1)
fprintf(fx,"%lf %lf %lf %lf %lf\n",q, X_11(q), X_13(q), X_22(q), X_10_12(q));
fclose(fx);
printf("getting Y function...\n");
fy = fopen("data/Y_func.dat","w+");
for (q=0; q<10; q+=.01)
fprintf(fy,"%lf %lf %lf %lf %lf\n",q, Y_11(q), Y_13(q), Y_22(q), Y_10_12(q));
fclose(fy);
fy = fopen("data/Y_func.dat","a+");
for (q=11; q<2000; q+=1)
fprintf(fy,"%lf %lf %lf %lf %lf\n",q, Y_11(q), Y_13(q), Y_22(q), Y_10_12(q));
fclose(fy);
printf("getting W function...\n");
fw = fopen("data/W_func.dat","w+");
for (q=0; q<10; q+=.01)
fprintf(fw,"%lf %lf %lf %lf\n",q, V1_112(q), V3_112(q), T_112(q));
fclose(fw);
fw = fopen("data/W_func.dat","a+");
for (q=11; q<2000; q+=1)
fprintf(fw,"%lf %lf %lf %lf\n",q, V1_112(q), V3_112(q), T_112(q));
fclose(fw);
return;
}
/************************************************************************************************************************************************************************/
/*********************\\Interpolation functions\\***********************************************************************************************************************/
void interpole(int n, char ficher[100],int val)
{
double T_x[val];
double T_y[val];
FILE* f;
int i = 0;
f = fopen(ficher, "r");
for(i=0; i < val; i++) fscanf(f, "%lf %lf\n", &T_x[i], &T_y[i]);
acc[n] = gsl_interp_accel_alloc ();
spline[n] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[n], T_x, T_y, val);
fclose(f);
}
void interp_qfunc()
{
FILE *fu, *fx, *fy, *fw;
int i;
const int val = 2990;
double X_q[val], X_x11[val], X_x13[val], X_x22[val], X_x1012[val], Y_q[val], Y_y11[val], Y_y13[val], Y_y22[val], Y_y1012[val], U_q[val], U_u1[val], U_u3[val], U_u11[val], U_u20[val], W_q[val], W_v1[val], W_v3[val], W_t[val];
fu = fopen("data/U_func.dat", "r");
for(i=0; i < val; i++) fscanf(fu, "%lf %lf %lf %lf %lf\n", &U_q[i], &U_u1[i], &U_u3[i], &U_u11[i], &U_u20[i]);
acc[9] = gsl_interp_accel_alloc ();
spline[9] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[9], U_q, U_u1, val);
acc[10] = gsl_interp_accel_alloc ();
spline[10] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[10], U_q, U_u3, val);
acc[11] = gsl_interp_accel_alloc ();
spline[11] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[11], U_q, U_u11, val);
acc[12] = gsl_interp_accel_alloc ();
spline[12] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[12], U_q, U_u20, val);
fclose(fu);
fx = fopen("data/X_func.dat", "r");
for(i=0; i < val; i++) fscanf(fx, "%lf %lf %lf %lf %lf\n", &X_q[i], &X_x11[i], &X_x13[i], &X_x22[i], &X_x1012[i]);
acc[13] = gsl_interp_accel_alloc ();
spline[13] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[13], X_q, X_x11, val);
acc[14] = gsl_interp_accel_alloc ();
spline[14] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[14], X_q, X_x13, val);
acc[15] = gsl_interp_accel_alloc ();
spline[15] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[15], X_q, X_x22, val);
acc[16] = gsl_interp_accel_alloc ();
spline[16] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[16], X_q, X_x1012, val);
fclose(fx);
fy = fopen("data/Y_func.dat", "r");
for(i=0; i < val; i++) fscanf(fy, "%lf %lf %lf %lf %lf\n", &Y_q[i], &Y_y11[i], &Y_y13[i], &Y_y22[i], &Y_y1012[i]);
acc[17] = gsl_interp_accel_alloc ();
spline[17] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[17], Y_q, Y_y11, val);
acc[18] = gsl_interp_accel_alloc ();
spline[18] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[18], Y_q, Y_y13, val);
acc[19] = gsl_interp_accel_alloc ();
spline[19] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[19], Y_q, Y_y22, val);
acc[20] = gsl_interp_accel_alloc ();
spline[20] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[20], Y_q, Y_y1012, val);
fclose(fy);
fw = fopen("data/W_func.dat", "r");
for(i=0; i < val; i++) fscanf(fw, "%lf %lf %lf %lf\n", &W_q[i], &W_v1[i], &W_v3[i], &W_t[i]);
acc[21] = gsl_interp_accel_alloc ();
spline[21] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[21], W_q, W_v1, val);
acc[22] = gsl_interp_accel_alloc ();
spline[22] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[22], W_q, W_v3, val);
acc[23] = gsl_interp_accel_alloc ();
spline[23] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[23], W_q, W_t, val);
fclose(fw);
}
/************************************************************************************************************************************************************************/
/*****************\\Matrix A \\ *****************************************************************************************************************************************/
/*A_ij(q) = X(q)*delta_k(i,j) + Y(q)*q_v[i]*q_v[j]*/
double Aij_13 (int i, int j, double q)
{
return iX_13(q)*delta_K(i,j)+iY_13(q)*q_v[i]*q_v[j]; // q_v[i] unit vector over i component
}
double Aij_22 (int i, int j, double q)
{
return iX_22(q)*delta_K(i,j)+iY_22(q)*q_v[i]*q_v[j];
}
double Aij_11 (int i, int j, double q)
{
return iX_11(q)*delta_K(i,j)+iY_11(q)*q_v[i]*q_v[j];
}
double Aij (int i, int j, double q) // Compute the ij component of matrix A
{
return Aij_11(i, j, q)+Aij_22(i, j, q)+2.*Aij_13(i, j, q);
}
double A10_ij (int i, int j, double q)
{
return 2.*(iX_10_12(q)*delta_K(i,j)+iY_10_12(q)*q_v[i]*q_v[j]);
}
// Initialize A matrix
gsl_matrix *get_M (double q)
{
int i, j;
gsl_matrix *M = gsl_matrix_calloc (3,3);
for (i=0; i<3; i++){
for (j=0; j<3;j++)
gsl_matrix_set(M, i, j, Aij(i,j,q));
}
return M;
}
/************************************************************************************************************************************************************************/
/******************\\ g_i, G_ij and Gamma_ijk functions\\**************************************************************************************************************/
double g_i (int i, int j, gsl_matrix *M_inv, double y[])
{
return gsl_matrix_get(M_inv, i, j)*y[j];
}
double G_ij (int i, int j, gsl_matrix *M_inv, double g[])
{
return gsl_matrix_get(M_inv, i, j)-g[i]*g[j];
}
double Gamma_ijk (int i, int j, int k, gsl_matrix *M_inv, double g[])
{
return gsl_matrix_get(M_inv, i, j)*g[k]+ gsl_matrix_get(M_inv, k, i)*g[j] + gsl_matrix_get(M_inv, j, k)*g[i] - g[i]*g[j]*g[k];
}
/************************************************************************************************************************************************************************/
/******************\\Compute W^112_ijk(q)\\**************************************************************************************************************************/
double W_112 (int i, int j, int k, double q)
{
return iW_V1(q)*delta_K(j,k)*q_v[i] +
iW_V1(q)*delta_K(k,i)*q_v[j] +
iW_V3(q)*delta_K(i,j)*q_v[k] +
iW_T(q)*q_v[i]*q_v[j]*q_v[k];
}
/************************************************************************************************************************************************************************/
/*************\\Dot functions\\*****************************************************************************************************************************************/
//Udot_n
double fU_dot (double q)
{
return iU_1(q) + 3.*iU_3(q);
}
//Adot_in
double fA_dot (int i, int n, double q)
{
return Aij_11(i,n,q)+4.*Aij_13(i,n,q)+2.*Aij_22(i,n,q);
}
//Adot^10_in
double fA10_dot (int i, int n, double q)
{
return 3.*(iX_10_12(q)*delta_K(i,n)+iY_10_12(q)*q_v[i]*q_v[n]);
}
//Wdot_ijn
double fW_dot (int i, int j, int n, double q)
{
return 2.*W_112(i,j,n,q)+W_112(n,i,j,q)+W_112(j,n,i,q);
}
/************************************************************************************************************************************************************************/
/*********\\Double dot functions\\*************************************************************************************************************************************/
//A2dot_nm
double fA_2dot (int n, int m, double q)
{
return Aij_11(n,m,q)+6.*Aij_13(n,m,q)+4.*Aij_22(n,m,q);
}
//A2dot^10_nm
double fA10_2dot (int n, int m, double q)
{
return 4.*(iX_10_12(q)*delta_K(n,m)+iY_10_12(q)*q_v[n]*q_v[m]); //A_nm = A_mn
}
// W2dot_inm
double fW_2dot (int i, int n, int m, double q)
{
return 2.*W_112(i,n,m,q)+2.*W_112(m,i,n,q)+W_112(n,m,i,q); //W^121_inm = W^112_min and W^211_inm = W^112_nmi
}
/************************************************************************************************************************************************************************/
/**************\\M_0 integral\\*****************************************************************************************************************************************/
void M_0(double y, double R, double M0_fin[])
{
int l, m,o;
double mu, q_n, det_A, y_t[3], q[3], U[3], G[3][3], U11[3], U20[3], g[3], Gamma[3][3][3], W[3][3][3], W_fin[3][3][3], A10[3][3], Xi, s, fac, F_b[6], M0_tab[6];
double dmu = 0.001;
int signum = 0;
for (l = 0; l<6; l++) // Inizialise at each step
M0_tab[l] = 0;
for (mu=-1; mu <= 1; mu +=dmu){ // Decomp integrale dtheta en somme de riemann int=somme f(x_i)*delta_x
gsl_matrix *A = gsl_matrix_calloc (3, 3);
gsl_matrix *A_inv = gsl_matrix_calloc (3, 3); // Declaration of matrix A (3x3)
// change variable y = q-r
y_t[0] = y*sqrt(1-mu*mu);
y_t[1] = 0;
y_t[2] = y*mu;
// Compute vector q = y+r with r= (0,0,1) along the LOS
q[0] = y_t[0];
q[1] = y_t[1];
q[2] = y_t[2]+R;
q_n = sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]); // norm of q
// unit vector
for (l=0; l<3; l++)
q_v[l] = q[l]/q_n;
/********Compute function ****************************************/
// Xi linear
Xi = iXi_L(q_n);
// U functions
for (l = 0; l<3 ; l++){
U[l] = get_U(q_n)*q_v[l];
U11[l] = iU_11(q_n)*q_v[l];
U20[l] = iU_20(q_n)*q_v[l];
}
// Matix A
gsl_permutation *p = gsl_permutation_alloc (3);
A = get_M(q_n); //Initialize matix A
gsl_linalg_LU_decomp(A, p, &signum);
det_A = gsl_linalg_LU_det(A, signum); // Determinant of A
gsl_linalg_LU_invert(A, p, A_inv); // Inverse of matrix A
// g_i components
for (l=0; l<3; l++){
g[l] = 0;
for (m=0; m<3; m++)
g[l] += g_i(l, m, A_inv, y_t);
}
// G_ij components
for (l=0; l<3; l++){
for (m=0; m<3; m++)
G[l][m] = G_ij(l, m, A_inv, g);
}
// Gamma_ijk
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
Gamma[l][m][o] = Gamma_ijk(l, m, o, A_inv, g);
}
}
// W_ijk
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W[l][m][o] = W_112(l, m, o, q_n);
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W_fin[l][m][o] = W[l][m][o]+ W[o][l][m]+ W[m][o][ l ];
}
}
// A^10_ij
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A10[l][m] = A10_ij(l, m, q_n);
}
// Sum over all the bias component
for(l=0; l<6; l++)
F_b[l] = 0;
// <F'>
s=0;
for (l=0; l<3; l++)
s += U[l]*g[l];
F_b[1] -= 2.*s;
F_b[4] -= 2.*Xi*s; // <F'F''>
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += A10[l][m]*G[l][m];
}
F_b[1] -= s;
// <F'>Β²
F_b[3] += Xi;
s=0;
for (l=0; l<3; l++)
s += U11[l]*g[l];
F_b[3] -= s;
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += U[l]*U[m]*G[l][m];
}
F_b[3] -= s;
// <F''>
s=0;
for (l=0; l<3; l++)
s += U20[l]*g[l];
F_b[2] -= s;
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += U[l]*U[m]*G[l][m];
}
F_b[2] -= s;
// <F''>Β²
F_b[5] = 0.5*Xi*Xi;
// F0
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
s += Gamma[l][m][o]*W_fin[l][m][o];
}
}
F_b[0] += s/6.;
F_b[0] += 1.;
// gaussian factor of M
s = 0;
for (l=0; l<3; l++)
s += g[l]*y_t[l];
fac = exp(-0.5*s)/(sqrt(2.*M_PI)*2.*M_PI*sqrt(det_A));
// Sum over all component
for (l=0; l<6; l++)
M0_tab[l] += F_b[l]*fac;
gsl_permutation_free (p);
gsl_matrix_free(A);
gsl_matrix_free(A_inv);
}
s = y*y*dmu;
for (l=0; l<6; l++)
M0_fin[l] = M0_tab[l]*s;
}
/********Generate correlation function in real space Xi_R(r) ************************************************************************************************************/
void get_Xi_R ()
{
printf("Calculating Xi_r...\n");
int i, n =6;
double r, M0[n];
FILE *fi;
fi = fopen("data/Xi_r_CLPT.dat","w+");
for (r=1; r<=160; r+=1){
for (i=0; i<n; i++)
M0[i] = 0;
gl_int6(0, 50, &M_0, &r, M0, n);
for (i=0; i<n; i++)
M0[i] *= 2.*M_PI;
M0[0] -= 1;
fprintf(fi,"%lf %lf %lf %lf %lf %lf %lf\n", r, M0[0], M0[1], M0[2], M0[3], M0[4], M0[5]);
}
fclose(fi);
return ;
}
/************************************************************************************************************************************************************************/
/**************\\M_1 integral\\*****************************************************************************************************************************************/
void M_1(double y, double R, double M1_fin[])
{
const double rn[ 3 ] = { 0, 0, 1 }; // unit vector to project over the LOS
int l, m,o;
double mu, q_n, det_A, y_t[3], q[3], U[3], U_dot[3], G[3][3], U11[3], U20[3], g[3], W[3][3][3], W_dot[3][3][3], A_dot[3][3], A10_dot[3][3], Xi, s, fac, F_b[5], M1_tab[5];
double dmu = 0.005;
int signum = 0; // Use for matrix inversion
for (l = 0; l<5 ; l++) // Initialize at each step
M1_tab[l] = 0;
for (mu=-1; mu <= 1; mu +=dmu){ // Decomp integrale dtheta en somme de riemann int=somme f(x_i)*delta_x
gsl_matrix *A = gsl_matrix_calloc (3, 3);
gsl_matrix *A_inv = gsl_matrix_calloc (3, 3); // Declaration of matrix A (3x3)
// change variable y = q-r
y_t[0] = y*sqrt(1-mu*mu);
y_t[1] = 0;
y_t[2] = y*mu;
// Compute vector q = y+r with r= (0,0,1) along the LOS
q[0] = y_t[0];
q[1] = y_t[1];
q[2] = y_t[2]+R;
q_n = sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]); // norm of q
// unit vector
for (l=0; l<3; l++)
q_v[l] = q[l]/q_n;
/********Compute function ****************************************/
// Xi linear
Xi = iXi_L(q_n);
// U functions
for (l = 0; l<3 ; l++){
U_dot[l] = fU_dot(q_n)*q_v[l];
U[l] = get_U(q_n)*q_v[l];
U11[l] = 2.*iU_11(q_n)*q_v[l]; // Pq 2 ?????
U20[l] = 2.*iU_20(q_n)*q_v[l];
}
// Matix A
gsl_permutation *p = gsl_permutation_alloc (3);
A = get_M(q_n); //Initialize matix A
gsl_linalg_LU_decomp(A, p, &signum);
det_A = gsl_linalg_LU_det(A, signum); // Determinant of A
gsl_linalg_LU_invert(A, p, A_inv); // Inverse of matrix A
// g_i components
for (l=0; l<3; l++){
g[l] = 0;
for (m=0; m<3; m++)
g[l] += g_i(l, m, A_inv, y_t);
}
// G_ij components
for (l=0; l<3; l++){
for (m=0; m<3; m++)
G[l][m] = G_ij(l, m, A_inv, g);
}
// Adot_in
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A_dot[l][m] = fA_dot(l, m, q_n);
}
// Adot^10_in
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A10_dot[l][m] = fA10_dot(l, m, q_n);
}
// W_ijn
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W[l][m][o] = W_112(l, m, o, q_n);
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W_dot[l][m][o] = 2.*W[l][m][o]+ W[o][l][m]+ W[m][o][ l ];
}
}
// Sum over all the bias component
for(l=0; l<5; l++)
F_b[l] = 0;
// <F'> F_b[1]
s = 0;
for (l=0; l<3; l++)
s += U_dot[l]*rn[l];
F_b[1] += 2.*s;
s = 0;
for (l=0; l<3; l++){
for (o=0; o<3; o++)
s += g[l]*A10_dot[l][o]*rn[o];
}
F_b[1] -= 2.*s;
s = 0;
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
s += G[l][m]*U[l]*A_dot[m][o]*rn[o];
}
}
F_b[1] -= 2.*s;
// <F''>
s = 0;
for (l=0; l<3; l++)
s += U20[l]*rn[l];
F_b[2] += s;
s = 0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += U[l]*g[l]*U_dot[m]*rn[m];
}
F_b[2] -= 2.*s;
// <F'>Β²
s=0;
for (l=0; l<3; l++)
s += U11[l]*rn[l];
F_b[3] += s;
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += U[l]*g[l]*U_dot[m]*rn[m];
}
F_b[3] -= 2.*s;
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += g[l]*A_dot[l][m]*rn[m];
}
F_b[3] -= Xi*s;
// <F'F''>
s=0;
for (l=0; l<3; l++)
s += U_dot[l]*rn[l];
F_b[4] += 2.*Xi*s;
// F0
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
s += G[l][m]*W_dot[l][m][o]*rn[o];
}
}
F_b[0] -= s/2.;
s=0;
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s += g[l]*A_dot[l][m]*rn[m];
}
F_b[0] -= s;
// gaussian factor of M
s = 0;
for (l=0; l<3; l++)
s += g[l]*y_t[l];
fac = exp(-0.5*s)/(sqrt(2.*M_PI)*2.*M_PI*sqrt(det_A));
// Sum over all component
for (l=0; l<5; l++)
M1_tab[l] += F_b[l]*fac;
gsl_matrix_free(A);
gsl_matrix_free(A_inv);
gsl_permutation_free (p);
}
s = y*y*dmu;
for (l=0; l<5; l++)
M1_fin[l] = M1_tab[l]*s;
}
/********Generate V_12(r) **********************************************************************************************************************************************/
/*To compare with Wang +13 we do not divise by 1+Xi_R*/
void get_V12 ()
{
printf("Calculating V12...\n");
int i, n=5;
double r, result [n];
FILE *fi;
fi = fopen("data/V_12_CLPT.dat","w+");
for (r=1; r<=160; r+=1){
gl_int6(0, 50, &M_1, &r, result, n);
for (i=0; i<n; i++)
result[i] *= 2.*M_PI;
fprintf(fi,"%lf %lf %lf %lf %lf %lf\n", r, result[0], result[1], result[2], result[3], result[4]);
}
fclose(fi);
return ;
}
/************************************************************************************************************************************************************************/
/************************************************************************************************************************************************************************/
//Calcul de M2
void M_2 (double y, double R, double M2_fin[])
{
const double rn[ 3 ] = { 0, 0, 1 }; // unit vector to project on n and m
int l, m,o, n;
double mu, q_n, det_A, y_t[3], q[3], U[3], U_dot[3], G[3][3], g[3], W[3][3][3], W_2dot[3][3][3], A_dot[3][3], A_2dot[3][3], A10_2dot[3][3], Xi, s[3][3], f, fac, M2_tab[8];;
double F_par[4], //Bias factor for sigma_parallel
F_per[4]; //Bias factor for sigma_perpendicular
double dmu = 0.005;
int signum = 0; // use for matrix inversion
for (l=0; l<8; l++) //Initialize at each step
M2_tab[l] = 0;
for (mu=-1; mu <= 1; mu +=dmu){ // Decomp integrale dtheta en somme de riemann int=somme f(x_i)*delta_x
gsl_matrix *A = gsl_matrix_calloc (3, 3);
gsl_matrix *A_inv = gsl_matrix_calloc (3, 3); // Declaration of matrix A (3x3)
// change variable y = q-r
y_t[0] = y*sqrt(1-mu*mu);
y_t[1] = 0;
y_t[2] = y*mu;
// Compute vector q = y+r with r= (0,0,1) along the LOS
q[0] = y_t[0];
q[1] = y_t[1];
q[2] = y_t[2]+R;
q_n = sqrt(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]); // norm of q
// unit vector
for (l=0; l<3; l++)
q_v[l] = q[l]/q_n;
/********Compute function ****************************************/
// Xi linear
Xi = iXi_L(q_n);
// U functions
for (l = 0; l<3 ; l++){
U[l] = get_U(q_n)*q_v[l];
U_dot[l] = fU_dot(q_n)*q_v[l];
}
// Matix A
gsl_permutation *p = gsl_permutation_alloc (3);
A = get_M(q_n); //Initialize matix A
gsl_linalg_LU_decomp(A, p, &signum);
det_A = gsl_linalg_LU_det(A, signum); // Determinant of A
gsl_linalg_LU_invert(A, p, A_inv); // Inverse of matrix A
// g_i components
for (l=0; l<3; l++){
g[l] = 0;
for (m=0; m<3; m++)
g[l] += g_i(l, m, A_inv, y_t);
}
// G_ij components
for (l=0; l<3; l++){
for (m=0; m<3; m++)
G[l][m] = G_ij(l, m, A_inv, g);
}
// Adot_nm
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A_dot[l][m] = fA_dot(l, m, q_n);
}
// A2dot_nm
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A_2dot[l][m] = fA_2dot(l, m, q_n);
}
// A2dot^10_nm
for (l=0; l<3; l++){
for (m=0; m<3; m++)
A10_2dot[l][m] = fA10_2dot(l, m, q_n);
}
// W_inm
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W[l][m][o] = W_112(l, m, o, q_n);
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
W_2dot[l][m][o] = 2.*W[l][m][o]+ W[o][l][m]+ 2.*W[m][o][ l ];
}
}
// Sum over all the bias component
for (l=0; l<4; l++){ // Initialize at each step
F_par[l]=0;
F_per[l]=0;
}
// <F'>
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s[l][m] = A10_2dot[l][m];
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++){
s[m][o] -= (A_dot[l][m]*g[l]*U_dot[o]+A_dot[l][o]*g[l]*U_dot[m]);
s[m][o] -= U[l]*g[l]*A_2dot[m][o];
}
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
F_par[1] += 2.*s[l][m]*rn[l]*rn[m];
F_per[1] += 2.*s[l][m]*delta_K(l,m);
}
}
// <F''>
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s[l][m] = U_dot[l]*U_dot[m];
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
F_par[2] += 2.*s[l][m]*rn[l]*rn[m];
F_per[2] += 2.*s[l][m]*delta_K(l,m);
}
}
// <F'>Β²
for (l=0; l<3; l++){
for (m=0; m<3; m++){
s[l][m] = Xi*A_2dot[l][m];
s[l][m] += 2.*U_dot[l]*U_dot[m];
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
F_par[3] += s[l][m]*rn[l]*rn[m];
F_per[3] += s[l][m]*delta_K(l,m);
}
}
// F0
for (l=0; l<3; l++){
for (m=0; m<3; m++)
s[l][m] = A_2dot[l][m];
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for(n=0; n<3; n++){
for (o=0; o<3; o++)
s[n][o] -= A_dot[l][n]*A_dot[m][o]*G[l][m];
}
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
for (o=0; o<3; o++)
s[m][o] -= W_2dot[l][m][o]*g[l];
}
}
for (l=0; l<3; l++){
for (m=0; m<3; m++){
F_per[0] += s[l][m]*delta_K(l,m);
F_par[0] += s[l][m]*rn[l]*rn[m];
}
}
// gaussian factor of M
f = 0;
for (l=0; l<3; l++)
f += g[l]*y_t[l];
fac = exp(-0.5*f)/(sqrt(2.*M_PI)*2.*M_PI*sqrt(fabs(det_A)));
// Sum over all component
for (l=0; l<4; l++){
M2_tab[l] += F_par[l]*fac;
M2_tab[l+4] += F_per[l]*fac;
}
gsl_permutation_free (p);
}
f = y*y*dmu;
for (l=0; l<4; l++){
M2_fin[l] = M2_tab[l]*f;
M2_fin[l+4] = 0.5*f*(M2_tab[l+4]-M2_tab[l]);
}
}
/********Generate Sigma_12(r) perp and par*******************************************************************************************************************************/
//To compare with Wang +13 we do not divise by 1+Xi_R
void get_Sigma ()
{
int i, n=8;
double r, result[n];
FILE *fi;
printf("Calculating Sigma...\n");
fi = fopen("data/Sigma_12_CLPT.dat","w+");
for (r=1; r<=160; r+=1){
gl_int6(0, 50, &M_2, &r, result, n);
for (i=0; i<n; i++)
result[i] *= 2.*M_PI;
fprintf(fi,"%lf %lf %lf %lf %lf %lf %lf %lf %lf\n", r, result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]);
}
fclose(fi);
return ;
}
/************************************************************************************************************************************************************************/
/************\\Count the number of ligne in a file\\********************************************************************************************************************/
int compte(FILE *fichier)
{
int c;
int nLignes = 0;
int c2 = '\0';
while((c=fgetc(fichier)) != EOF){ if(c=='\n') nLignes++; c2 = c;}
if(c2 != '\n') nLignes++;
return nLignes;
}
/************************************************************************************************************************************************************************/
/**********\\MAIN FUNCTION\\***************************************************************************************************************************************/
int
main (int argc, char *argv[])
{
int i;
double nLignes;
FILE *ps;
// Count number of lines
ps = fopen(argv[1], "r");
if (ps!=0){
nLignes = compte(ps);
}
else {
printf("Error openning power spectrum file.\n");
return 1;
}
// Read kmin and kmax
rewind(ps);
kmin=1e30;
kmax=0;
for(i=0; i < nLignes; i++) {
double val;
fscanf(ps, "%lf %*f\n", &val);
if (val<kmin) kmin=val;
if (val>kmax) kmax=val;
}
fclose(ps);
lk = kmax-kmin;
interpole(1,argv[1], nLignes);
calc_R1();
calc_R2();
calc_Qn();
interpole(2,"data/func_R1.dat", 10901);
interpole(3,"data/func_R2.dat", 10901);
interpole(4,"data/func_Q1.dat", 2991);
interpole(5,"data/func_Q2.dat", 2991);
interpole(6,"data/func_Q5.dat", 2991);
interpole(7,"data/func_Q8.dat", 2991);
q_function();
interpole(8,"data/Xi_L_func.dat", 2900);
interp_qfunc();
get_Xi_R();
get_V12();
get_Sigma();
for (i=0; i<25; i++){
gsl_spline_free (spline[i]);
gsl_interp_accel_free (acc[i]);}
return 0;
}
| {
"alphanum_fraction": 0.4556627314,
"avg_line_length": 29.5065934066,
"ext": "c",
"hexsha": "062784f12def76d28c24cbf8bfa0784002115300",
"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": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoine-rocher/Master-2-internship",
"max_forks_repo_path": "Code_RSD_CLPT.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"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": "antoine-rocher/Master-2-internship",
"max_issues_repo_path": "Code_RSD_CLPT.c",
"max_line_length": 225,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoine-rocher/Master-2-internship",
"max_stars_repo_path": "Code_RSD_CLPT.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-10T10:33:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-16T14:04:45.000Z",
"num_tokens": 18715,
"size": 53702
} |
#pragma once
#include "datastructures/PointBuffer.h"
#include "math/Vector3.h"
#include "proj_api.h"
#include <containers/Range.h>
#include <string>
#include <gsl/gsl>
class Point;
struct AABB;
/// <summary>
/// Spatial reference systems that the SRSTransformHelper can transform into
/// </summary>
enum class TargetSRS
{
/// <summary>
/// WGS84 specified with latitude, longitude (radians) and height over
/// ellipsoid (meters)
/// </summary>
WGS84,
/// <summary>
/// Cesium world coordinate system (WGS84 geocentric)
/// </summary>
CesiumWorld
};
/// <summary>
/// Utility class for transforming positions between spatial reference systems
/// </summary>
struct SRSTransformHelper
{
virtual ~SRSTransformHelper();
/// <summary>
/// Transforms a range of positions into the target SRS. Transformation
/// modifies the source points
/// </summary>
virtual void transformPositionsTo(TargetSRS targetSRS,
gsl::span<Vector3<double>> positions) const = 0;
/// <summary>
/// Transforms a range of position from the given SRS back into source
/// coordinate space
/// </summary>
virtual void transformPositionToSourceFrom(TargetSRS currentSRS,
gsl::span<Vector3<double>> positions) const = 0;
virtual void transformPointsTo(TargetSRS targetSRS,
gsl::span<PointBuffer::PointReference> points) const = 0;
virtual void transformPointsTo(TargetSRS targetSRS,
util::Range<PointBuffer::PointIterator> points) const = 0;
/// <summary>
/// Transforms a range of axis-aligned bounding boxes into the target SRS.
/// Transformation happens in-place. The axis-aligned property will be
/// preserved after the transformation, which can result in an increase in
/// volume of the AABBs
/// </summary>
virtual void transformAABBsTo(TargetSRS targetSRS, gsl::span<AABB> aabbs) const = 0;
};
/// <summary>
/// Identity transformation, i.e. a transformation that does nothing
/// </summary>
struct IdentityTransform : SRSTransformHelper
{
virtual ~IdentityTransform();
void transformPositionsTo(TargetSRS targetSRS,
gsl::span<Vector3<double>> positions) const override;
void transformPositionToSourceFrom(TargetSRS currentSRS,
gsl::span<Vector3<double>> positions) const override;
void transformPointsTo(TargetSRS targetSRS,
gsl::span<PointBuffer::PointReference> points) const override;
void transformPointsTo(TargetSRS targetSRS,
util::Range<PointBuffer::PointIterator> points) const override;
void transformAABBsTo(TargetSRS targetSRS, gsl::span<AABB> aabbs) const override;
};
/// <summary>
/// Transformation based on proj4 coordinate system conversion
/// </summary>
struct Proj4Transform : SRSTransformHelper
{
explicit Proj4Transform(const std::string& sourceTransformation);
virtual ~Proj4Transform();
void transformPositionsTo(TargetSRS targetSRS,
gsl::span<Vector3<double>> positions) const override;
void transformPositionToSourceFrom(TargetSRS currentSRS,
gsl::span<Vector3<double>> positions) const override;
void transformPointsTo(TargetSRS targetSRS,
gsl::span<PointBuffer::PointReference> points) const override;
void transformPointsTo(TargetSRS targetSRS,
util::Range<PointBuffer::PointIterator> points) const override;
void transformAABBsTo(TargetSRS targetSRS, gsl::span<AABB> aabbs) const override;
private:
projPJ getTargetTransformation(TargetSRS targetSRS) const;
projPJ _sourceTransformation;
projPJ _wgs84;
projPJ _cesiumWorld;
};
/// <summary>
/// Finds the smallest point of the given points and subtracts it from all
/// points. This sets the origin of the points to the smallest point. The
/// smallest point prior to subtraction is returned
/// </summary>
Vector3<double>
setOriginToSmallestPoint(std::vector<Vector3<double>>& points);
template<typename Iter>
Vector3<double>
setOriginToSmallestPoint(Iter points_begin, Iter points_end)
{
const auto dblMax = std::numeric_limits<double>::max();
const auto smallestPoint =
std::accumulate(points_begin,
points_end,
Vector3<double>{ dblMax, dblMax, dblMax },
[](const auto& accum, const auto& point) {
return Vector3<double>::minByAxis(accum, point.position());
});
std::for_each(
points_begin, points_end, [smallestPoint](auto& point) { point.position() -= smallestPoint; });
return smallestPoint;
} | {
"alphanum_fraction": 0.6796727502,
"avg_line_length": 34.795620438,
"ext": "h",
"hexsha": "b9bb9429a9a09f592d95bcde854adb701adb6ede",
"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/util/Transformation.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/util/Transformation.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/util/Transformation.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": 1067,
"size": 4767
} |
/*!
* Copyright (c) 2014 by Contributors
* \file base.h
* \brief definitions of base types, operators, macros functions
*
* \author Bing Xu, Tianqi Chen
*/
#ifndef MSHADOW_BASE_H_
#define MSHADOW_BASE_H_
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX
#endif
#include <cmath>
#include <cstdio>
#include <cfloat>
#include <climits>
#include <algorithm>
// macro defintiions
/*!
* \brief if this macro is define to be 1,
* mshadow should compile without any of other libs
*/
#ifndef MSHADOW_STAND_ALONE
#define MSHADOW_STAND_ALONE 0
#endif
/*! \brief whether do padding during allocation */
#ifndef MSHADOW_ALLOC_PAD
#define MSHADOW_ALLOC_PAD true
#endif
/*!
* \brief
* x dimension of data must be bigger pad_size * ratio to be alloced padded memory,
* otherwise use tide allocation
* for example, if pad_ratio=2, GPU memory alignement size is 32,
* then we will only allocate padded memory if x dimension > 64
* set it to 0 then we will always allocate padded memory
*/
#ifndef MSHADOW_MIN_PAD_RATIO
#define MSHADOW_MIN_PAD_RATIO 2
#endif
#if MSHADOW_STAND_ALONE
#define MSHADOW_USE_CBLAS 0
#define MSHADOW_USE_MKL 0
#define MSHADOW_USE_CUDA 0
#endif
/*!
* \brief force user to use GPU stream during computation
* error will be shot when default stream NULL is used
*/
#ifndef MSHADOW_FORCE_STREAM
#define MSHADOW_FORCE_STREAM 0
#endif
/*! \brief use CBLAS for CBLAS */
#ifndef MSHADOW_USE_CBLAS
#define MSHADOW_USE_CBLAS 0
#endif
/*! \brief use MKL for BLAS */
#ifndef MSHADOW_USE_MKL
#define MSHADOW_USE_MKL 1
#endif
/*!
* \brief use CUDA support, must ensure that the cuda include path is correct,
* or directly compile using nvcc
*/
#ifndef MSHADOW_USE_CUDA
#define MSHADOW_USE_CUDA 1
#endif
/*!
* \brief seems CUDAARCH is deprecated in future NVCC
* set this to 1 if you want to use CUDA version smaller than 2.0
*/
#ifndef MSHADOW_OLD_CUDA
#define MSHADOW_OLD_CUDA 0
#endif
/*! \brief whether use SSE */
#ifndef MSHADOW_USE_SSE
#define MSHADOW_USE_SSE 1
#endif
/*! \brief whether use NVML to get dynamic info */
#ifndef MSHADOW_USE_NVML
#define MSHADOW_USE_NVML 0
#endif
// SSE is conflict with cudacc
#ifdef __CUDACC__
#undef MSHADOW_USE_SSE
#define MSHADOW_USE_SSE 0
#endif
#if MSHADOW_USE_CBLAS
extern "C" {
#include <cblas.h>
}
#elif MSHADOW_USE_MKL
#include <mkl.h>
#include <mkl_cblas.h>
#include <mkl_vsl.h>
#include <mkl_vsl_functions.h>
#endif
#if MSHADOW_USE_CUDA
#include <cublas.h>
#include <curand.h>
#endif
#if MSHADOW_USE_NVML
#include <nvml.h>
#endif
// --------------------------------
// MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code
#ifdef MSHADOW_XINLINE
#error "MSHADOW_XINLINE must not be defined"
#endif
#ifdef _MSC_VER
#define MSHADOW_FORCE_INLINE __forceinline
#pragma warning( disable : 4068 )
#else
#define MSHADOW_FORCE_INLINE inline __attribute__((always_inline))
#endif
#ifdef __CUDACC__
#define MSHADOW_XINLINE MSHADOW_FORCE_INLINE __device__ __host__
#else
#define MSHADOW_XINLINE MSHADOW_FORCE_INLINE
#endif
/*! \brief cpu force inline */
#define MSHADOW_CINLINE MSHADOW_FORCE_INLINE
#if defined(__GXX_EXPERIMENTAL_CXX0X) ||\
defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#define MSHADOW_CONSTEXPR constexpr
#else
#define MSHADOW_CONSTEXPR const
#endif
/*!
* \brief default data type for tensor string
* in code release, change it to default_real_t
* during development, change it to empty string so that missing
* template arguments can be detected
*/
#ifndef MSHADOW_DEFAULT_DTYPE
#define MSHADOW_DEFAULT_DTYPE = default_real_t
//#define MSHADOW_DEFAULT_DTYPE
#endif
/*! \brief namespace for mshadow */
namespace mshadow {
/*! \brief buffer size for each random number generator */
const unsigned kRandBufferSize = 1000000;
/*! \brief pi */
const float kPi = 3.1415926f;
/*! \brief type that will be used for index */
typedef unsigned index_t;
/*! \brief float point type that will be used in default by mshadow */
typedef float default_real_t;
/*! \brief namespace for operators */
namespace op {
// binary operator
/*! \brief mul operator */
struct mul{
/*! \brief map a, b to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return a * b;
}
};
/*! \brief plus operator */
struct plus {
/*! \brief map a, b to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return a + b;
}
};
/*! \brief minus operator */
struct minus {
/*! \brief map a, b to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return a - b;
}
};
/*! \brief divide operator */
struct div {
/*! \brief map a, b to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return a / b;
}
};
/*! \brief get rhs */
struct right {
/*! \brief map a, b to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return b;
}
};
// unary operator/ function: example
// these operators can be defined by user,
// in the same style as binary and unary operator
// to use, simply write F<op::identity>( src )
/*! \brief identity function that maps a real number to it self */
struct identity{
/*! \brief map a to result using defined operation */
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a) {
return a;
}
};
} // namespace op
/*! \brief namespace for savers */
namespace sv {
/*! \brief save to saver: = */
struct saveto {
/*! \brief save b to a using save method */
template<typename DType>
MSHADOW_XINLINE static void Save(DType &a, DType b) {
a = b;
}
/*! \brief helper constant to use BLAS, alpha */
inline static default_real_t AlphaBLAS(void) { return 1.0f; }
/*! \brief helper constant to use BLAS, beta */
inline static default_real_t BetaBLAS(void) { return 0.0f; }
/*! \brief corresponding binary operator type */
typedef op::right OPType;
};
/*! \brief save to saver: += */
struct plusto {
/*! \brief save b to a using save method */
template<typename DType>
MSHADOW_XINLINE static void Save(DType &a, DType b) {
a += b;
}
/*! \brief helper constant to use BLAS, alpha */
inline static default_real_t AlphaBLAS(void) { return 1.0f; }
/*! \brief helper constant to use BLAS, beta */
inline static default_real_t BetaBLAS(void) { return 1.0f; }
/*! \brief corresponding binary operator type */
typedef op::plus OPType;
};
/*! \brief minus to saver: -= */
struct minusto {
/*! \brief save b to a using save method */
template<typename DType>
MSHADOW_XINLINE static void Save(DType &a, DType b) {
a -= b;
}
/*! \brief helper constant to use BLAS, alpha */
inline static default_real_t AlphaBLAS(void) { return -1.0f; }
/*! \brief helper constant to use BLAS, beta */
inline static default_real_t BetaBLAS(void) { return 1.0f; }
/*! \brief corresponding binary operator type */
typedef op::minus OPType;
};
/*! \brief multiply to saver: *= */
struct multo {
/*! \brief save b to a using save method */
template<typename DType>
MSHADOW_XINLINE static void Save(DType &a, DType b) {
a *= b;
}
/*! \brief corresponding binary operator type */
typedef op::mul OPType;
};
/*! \brief divide to saver: /= */
struct divto {
/*! \brief save b to a using save method */
template<typename DType>
MSHADOW_XINLINE static void Save(DType& a, DType b) {
a /= b;
}
/*! \brief corresponding binary operator type */
typedef op::div OPType;
};
} // namespace sv
/*! \brief namespace for potential reducer operations */
namespace red {
namespace limits {
/*!
* \brief minimum value of certain types
* \tparam DType data type
*/
template<typename DType>
MSHADOW_XINLINE DType MinValue(void);
/*! \brief minimum value of float */
template<>
MSHADOW_XINLINE float MinValue<float>(void) {
return -FLT_MAX;
}
/*! \brief minimum value of double */
template<>
MSHADOW_XINLINE double MinValue<double>(void) {
return -DBL_MAX;
}
/*! \brief minimum value of int */
template<>
MSHADOW_XINLINE int MinValue<int>(void) {
return INT_MIN;
}
} // namespace limits
/*! \brief sum reducer */
struct sum {
/*! \brief do reduction into dst */
template<typename DType>
MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) {
dst += src;
}
/*!
*\brief calculate gradient of redres with respect to redsrc,
* redres: reduced result, redsrc: one of reduction element
*/
template<typename DType>
MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {
return 1;
}
/*!
*\brief set the initial value during reduction
*/
template<typename DType>
MSHADOW_XINLINE static void SetInitValue(DType &initv) {
initv = 0;
}
};
/*! \brief maximum reducer */
struct maximum {
/*! \brief do reduction into dst */
template<typename DType>
MSHADOW_XINLINE static void Reduce(volatile DType& dst, volatile DType src) {
using namespace std;
dst = max(dst, src);
}
/*!
* \brief calculate gradient of redres with respect to redsrc,
* redres: reduced result, redsrc: one of reduction element
*/
template<typename DType>
MSHADOW_XINLINE static DType PartialGrad(DType redres, DType redsrc) {
return redres == redsrc ? 1: 0;
}
/*!
*\brief set the initial value during reduction
*/
template<typename DType>
MSHADOW_XINLINE static void SetInitValue(DType &initv) {
initv = limits::MinValue<DType>();
}
};
} // namespace red
} // namespace mshadow
#endif // MSHADOW_BASE_H_
| {
"alphanum_fraction": 0.707120237,
"avg_line_length": 27.1916666667,
"ext": "h",
"hexsha": "6336dfa023bcc15baed7ff45e0bf33ba6755d466",
"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": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Kingnus/mshadow",
"max_forks_repo_path": "mshadow/base.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575",
"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": "Kingnus/mshadow",
"max_issues_repo_path": "mshadow/base.h",
"max_line_length": 84,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5491dfbb8e491ff9315e7b8b03db2d97dcee5575",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Kingnus/mshadow",
"max_stars_repo_path": "mshadow/base.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-17T16:42:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-21T05:41:52.000Z",
"num_tokens": 2685,
"size": 9789
} |
///
/// @file
///
/// @author Mirko Myllykoski (mirkom@cs.umu.se), UmeΓ₯ University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, UmeΓ₯ Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_config.h>
#include <starneig/configuration.h>
#include "cpu.h"
#include "../common/common.h"
#include "../common/sanity.h"
#include "../common/tiles.h"
#include "../common/trace.h"
#include <starpu.h>
#include <starpu_scheduler.h>
#include <hwloc.h>
#include <cblas.h>
#include <omp.h>
void starneig_hessenberg_cpu_prepare_column(
void *buffers[], void *cl_args)
{
// LAPACK subroutine that generates a real elementary reflector H
extern void dlarfg_(int const *, double *, double *, int const *, double *);
int i; // the index of the currect column inside the panel
struct range_packing_info v_pi;
starpu_codelet_unpack_args(cl_args, &i, &v_pi);
int k = 0;
double *Y = NULL; int ldY = 0;
if (0 < i) {
Y = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
ldY = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
}
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
int m = STARPU_MATRIX_GET_NX(buffers[k]);
int nb = STARPU_MATRIX_GET_NY(buffers[k]);
k++;
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldT = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldP = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
// an intemediate vector interface for the trailing matrix operation
struct starpu_vector_interface **v_i =
(struct starpu_vector_interface **)buffers + k;
k += v_pi.handles;
// current column
double *p = P+i*ldP;
//
// update the current column
//
if (0 < i) {
// A <- A - Y * V' (update column from the right)
cblas_dgemv(CblasColMajor, CblasNoTrans, m, i,
-1.0, Y, ldY, V+i-1, ldV, 1.0, p, 1);
//
// update column from the left
//
// we use the last column of T as a work space
double *w = T+(nb-1)*ldT;
// w <- V1' * b1 (upper part)
cblas_dcopy(i, p, 1, w, 1);
cblas_dtrmv(
CblasColMajor, CblasLower, CblasTrans, CblasUnit, i, V, ldV, w, 1);
// w <- w + V2' * b2 (lower part)
cblas_dgemv(CblasColMajor, CblasTrans, m-i, i,
1.0, V+i, ldV, p+i, 1, 1.0, w, 1);
// w <- T' * w
cblas_dtrmv(
CblasColMajor, CblasUpper, CblasTrans, CblasNonUnit, i,
T, ldT, w, 1);
// b2 <- b2 - V2 * w
cblas_dgemv(CblasColMajor, CblasNoTrans, m-i, i,
-1.0, V+i, ldV, w, 1, 1.0, p+i, 1);
// b1 <- b1 - V1 * w
cblas_dtrmv(
CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, i,
V, ldV, w, 1);
cblas_daxpy(i, -1.0, w, 1, p, 1);
}
//
// compute the current unit vector
//
int height = m-i;
double tau, *v = V+i*ldV+i;
memcpy(v, p+i, height*sizeof(double));
dlarfg_(&height, p+i, v+1, (const int[]){1}, &tau);
v[0] = 1.0;
//
// copy the current unit vector to the intemediate vector interface
//
starneig_join_range(&v_pi, v_i, v, 1);
//
// set elements below the subdiagonal to zero
//
for (int j = i+1; j < m; j++)
p[j] = 0.0;
//
// store tau for future use
//
T[i*ldT+i] = tau;
}
void starneig_hessenberg_cpu_compute_column(
void *buffers[], void *cl_args)
{
struct packing_info A_pi;
struct range_packing_info v_pi, y_pi;
starpu_codelet_unpack_args(cl_args, &A_pi, &v_pi, &y_pi);
STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_red);
int k = 0;
// involved trailing matrix tiles
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += A_pi.handles;
// intemediate vector interface for the trailing matrix operation
struct starpu_vector_interface **v_i =
(struct starpu_vector_interface **)buffers + k;
k += v_pi.handles;
// intemediate vector interface from the trailing matrix operation
struct starpu_vector_interface **y_i =
(struct starpu_vector_interface **)buffers + k;
k += y_pi.handles;
int t_rows = (A_pi.rend-1) / A_pi.bm + 1 - (A_pi.rbegin-1) / A_pi.bm;
int t_cols = (A_pi.cend-1) / A_pi.bn + 1 - (A_pi.cbegin-1) / A_pi.bn;
//
// loop oper tile rows
//
for (int i = 0; i < t_rows; i++) {
double *y = (double *) STARPU_VECTOR_GET_PTR(y_i[i]);
int rbegin = MAX( 0, A_pi.rbegin - i * A_pi.bm);
int rend = MIN(A_pi.bm, A_pi.rend - i * A_pi.bm);
//
// loop over tile columns
//
for (int j = 0; j < t_cols; j++) {
double *A = (double *) STARPU_MATRIX_GET_PTR(A_i[j*t_rows+i]);
int ldA = STARPU_MATRIX_GET_LD(A_i[j*t_rows+i]);
double *v = (double *) STARPU_VECTOR_GET_PTR(v_i[j]);
int cbegin = MAX( 0, A_pi.cbegin - j * A_pi.bn);
int cend = MIN(A_pi.bn, A_pi.cend - j * A_pi.bn);
cblas_dgemv(
CblasColMajor, CblasNoTrans, rend-rbegin, cend-cbegin,
1.0, A+cbegin*ldA+rbegin, ldA, v+cbegin, 1, 1.0, y+rbegin, 1);
}
}
STARNEIG_EVENT_END();
}
void starneig_hessenberg_cpu_finish_column(
void *buffers[], void *cl_args)
{
struct range_packing_info y_pi;
int i;
starpu_codelet_unpack_args(cl_args, &i, &y_pi);
int k = 0;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int m = STARPU_MATRIX_GET_NX(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldT = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldY = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
// intemediate vector interface from the trailing matrix operation
struct starpu_vector_interface **y_i =
(struct starpu_vector_interface **)buffers + k;
k += y_pi.handles;
double tau = T[i*ldT+i];
double *v = V+i*ldV+i;
//
// finish Y update
//
starneig_join_range(&y_pi, y_i, Y+i*ldY, 0);
// w <- V' * v (shared result)
cblas_dgemv(CblasColMajor, CblasTrans, m-i, i,
1.0, V+i, ldV, v, 1, 0.0, T+i*ldT, 1);
// Y(:,i) <- Y(:,i) - Y * w
cblas_dgemv(CblasColMajor, CblasNoTrans, m, i,
-1.0, Y, ldY, T+i*ldT, 1, 1.0, Y+i*ldY, 1);
cblas_dscal(m, tau, Y+i*ldY, 1);
//
// update T
//
// w <- tau * w
cblas_dscal(i, -tau, T+i*ldT, 1);
// T(0:i,i) = T * w
cblas_dtrmv(
CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i,
T, ldT, T+i*ldT, 1);
T[i*ldT+i] = tau;
}
void starneig_hessenberg_cpu_update_trail_right(
void *buffers[], void *cl_args)
{
struct packing_info A_pi;
int nb, roffset, coffset;
starpu_codelet_unpack_args(cl_args, &A_pi, &nb, &roffset, &coffset);
STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_blue);
int m = A_pi.rend - A_pi.rbegin;
int n = A_pi.cend - A_pi.cbegin;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);
int ldV = STARPU_MATRIX_GET_LD(buffers[0]);
double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[1]);
int ldY = STARPU_MATRIX_GET_LD(buffers[1]);
double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);
int ldA = STARPU_MATRIX_GET_LD(buffers[2]);
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + 3;
// join tiles
starneig_join_window(&A_pi, ldA, A_i, A, 0);
// A <- Y V^T
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m, n, nb, -1.0, Y+roffset, ldY, V+coffset+nb-1, ldV, 1.0, A, ldA);
// split tiles
starneig_join_window(&A_pi, ldA, A_i, A, 1);
STARNEIG_EVENT_END();
}
void starneig_hessenberg_cpu_update_left_a(
void *buffers[], void *cl_args)
{
struct packing_info A_pi, W_pi;
int nb, offset;
starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);
STARNEIG_EVENT_BEGIN(&A_pi, starneig_event_green);
int m = A_pi.rend - A_pi.rbegin;
int n = A_pi.cend - A_pi.cbegin;
int k = 0;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldT = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldA = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldW = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldP = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += A_pi.handles;
struct starpu_matrix_interface **W_i =
(struct starpu_matrix_interface **)buffers + k;
k += W_pi.handles;
// join A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 0);
// join W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 0);
// P <- A^T * V
cblas_dgemm(
CblasColMajor, CblasTrans, CblasNoTrans, n, nb, m,
1.0, A, ldA, V+offset, ldV, 0.0, P, ldP);
// P <- P * T
cblas_dtrmm(
CblasColMajor, CblasRight, CblasUpper, CblasNoTrans,
CblasNonUnit, n, nb, 1.0, T, ldT, P, ldP);
// W <- W + P
for (int j = 0; j < nb; j++)
cblas_daxpy(n, 1.0, P+j*ldP, 1, W+j*ldW, 1);
// split W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 1);
STARNEIG_EVENT_END();
}
void starneig_hessenberg_cpu_update_left_b(
void *buffers[], void *cl_args)
{
struct packing_info A_pi, W_pi;
int nb, offset;
starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);
STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_green);
int m = A_pi.rend - A_pi.rbegin;
int n = A_pi.cend - A_pi.cbegin;
int k = 0;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldW = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldA = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
struct starpu_matrix_interface **W_i =
(struct starpu_matrix_interface **)buffers + k;
k += W_pi.handles;
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += A_pi.handles;
// join A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 0);
// join W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 0);
// A <- A - V * W^T
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasTrans, m, n,
nb, -1.0, V+offset, ldV, W, ldW, 1.0, A, ldA);
// split A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 1);
STARNEIG_EVENT_END();
}
void starneig_hessenberg_cpu_update_right_a(
void *buffers[], void *cl_args)
{
struct packing_info A_pi, W_pi;
int nb, offset;
starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);
STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_blue);
int m = A_pi.rend - A_pi.rbegin;
int n = A_pi.cend - A_pi.cbegin;
int k = 0;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldT = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldA = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldW = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *P = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldP = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += A_pi.handles;
struct starpu_matrix_interface **W_i =
(struct starpu_matrix_interface **)buffers + k;
k += W_pi.handles;
// join A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 0);
// join W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 0);
// P <- A * V
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, m, nb, n,
1.0, A, ldA, V+offset, ldV, 0.0, P, ldP);
// P <- P * T
cblas_dtrmm(
CblasColMajor, CblasRight, CblasUpper, CblasNoTrans,
CblasNonUnit, m, nb, 1.0, T, ldT, P, ldP);
// W <- W + P
for (int j = 0; j < nb; j++)
cblas_daxpy(m, 1.0, P+j*ldP, 1, W+j*ldW, 1);
// split W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 1);
STARNEIG_EVENT_END();
}
void starneig_hessenberg_cpu_update_right_b(
void *buffers[], void *cl_args)
{
struct packing_info A_pi, W_pi;
int nb, offset;
starpu_codelet_unpack_args(cl_args, &A_pi, &W_pi, &nb, &offset);
STARNEIG_EVENT_BEGIN(&packing_info, starneig_event_blue);
int m = A_pi.rend - A_pi.rbegin;
int n = A_pi.cend - A_pi.cbegin;
int k = 0;
double *V = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldV = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *W = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldW = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
double *A = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);
int ldA = STARPU_MATRIX_GET_LD(buffers[k]);
k++;
struct starpu_matrix_interface **W_i =
(struct starpu_matrix_interface **)buffers + k;
k += W_pi.handles;
struct starpu_matrix_interface **A_i =
(struct starpu_matrix_interface **)buffers + k;
k += A_pi.handles;
// join A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 0);
// join W tiles
starneig_join_window(&W_pi, ldW, W_i, W, 0);
// A <- A - W * V
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasTrans, m, n,
nb, -1.0, W, ldW, V+offset, ldV, 1.0, A, ldA);
// split A tiles
starneig_join_window(&A_pi, ldA, A_i, A, 1);
STARNEIG_EVENT_END();
}
| {
"alphanum_fraction": 0.6213452127,
"avg_line_length": 28.4099821747,
"ext": "c",
"hexsha": "0d7e9dee5e25ab3bc50d76a8583f333e667f510f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "src/hessenberg/cpu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "src/hessenberg/cpu.c",
"max_line_length": 80,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "src/hessenberg/cpu.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 4965,
"size": 15938
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ndlinear/gsl_multifit_ndlinear.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_laguerre.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_statistics.h>
/* dimension of fit */
#define N_DIM 3
/* number of basis functions for each variable */
#define N_SUM_R 10
#define N_SUM_THETA 10
#define N_SUM_PHI 9
#define R_MAX 3.0
double
psi_real_exact(int k, int l, int m, double r, double theta, double phi)
{
double R, T, P;
R = pow(r, (double) l) *
exp(-r*r) *
gsl_sf_laguerre_n(k, l + 0.5, 2 * r * r);
T = gsl_sf_legendre_sphPlm(l, m, cos(theta));
P = cos(m * phi);
return (R * T * P);
}
/* basis functions for each variable */
int
basis_r(double r, double y[], void *params)
{
gsl_bspline_workspace *bw = params;
gsl_vector_view v = gsl_vector_view_array(y, N_SUM_R);
int s;
/* use B-splines for r dependence */
s = gsl_bspline_eval(r, &v.vector, bw);
return s;
}
int
basis_theta(double theta, double y[], void *params)
{
size_t i;
/* use Legendre polynomials for theta dependence */
for (i = 0; i < N_SUM_THETA; ++i)
y[i] = gsl_sf_legendre_Pl(i, cos(theta));
return GSL_SUCCESS;
}
int
basis_phi(double phi, double y[], void *params)
{
size_t i;
/* use standard Fourier basis (sin/cos) for phi dependence */
for (i = 0; i < N_SUM_PHI; ++i)
{
if ((i % 2) == 0)
y[i] = cos((double)(i/2) * phi);
else
y[i] = sin((double)((i+1)/2) * phi);
}
return GSL_SUCCESS;
}
int
main(int argc, char *argv[])
{
const size_t ndim = N_DIM; /* dimension of fit */
const size_t ndata = 3000; /* number of data points to fit */
size_t N[N_DIM]; /* upper bounds on model sums */
int (*u[N_DIM])(double x, double y[], void *params);
size_t i; /* looping */
int k, l, m; /* quantum numbers */
gsl_rng *rng_p;
gsl_bspline_workspace *bspline_p;
gsl_multifit_linear_workspace *multifit_p;
gsl_multifit_ndlinear_workspace *ndlinear_p;
gsl_vector *data; /* psi data */
gsl_matrix *vars; /* parameters corresponding to psi data */
gsl_matrix *X; /* matrix for least squares fit */
gsl_vector *coeffs; /* fit coefficients */
gsl_matrix *cov; /* covariance matrix */
double chisq; /* chi^2 */
double Rsq; /* R^2 */
size_t ncoeffs; /* total number of fit coefficients */
gsl_rng_env_setup();
k = 5;
l = 4;
m = 2;
N[0] = N_SUM_R;
N[1] = N_SUM_THETA;
N[2] = N_SUM_PHI;
u[0] = &basis_r;
u[1] = &basis_theta;
u[2] = &basis_phi;
rng_p = gsl_rng_alloc(gsl_rng_default);
bspline_p = gsl_bspline_alloc(4, N_SUM_R - 2);
ndlinear_p = gsl_multifit_ndlinear_alloc(ndim, N, u, bspline_p);
ncoeffs = gsl_multifit_ndlinear_ncoeffs(ndlinear_p);
multifit_p = gsl_multifit_linear_alloc(ndata, ncoeffs);
data = gsl_vector_alloc(ndata);
vars = gsl_matrix_alloc(ndata, ndim);
X = gsl_matrix_alloc(ndata, ncoeffs);
coeffs = gsl_vector_alloc(ncoeffs);
cov = gsl_matrix_alloc(ncoeffs, ncoeffs);
gsl_bspline_knots_uniform(0.0, R_MAX, bspline_p);
/* this is the data to be fitted */
for (i = 0; i < ndata; ++i)
{
double r = gsl_rng_uniform(rng_p) * R_MAX;
double theta = gsl_rng_uniform(rng_p) * M_PI;
double phi = gsl_rng_uniform(rng_p) * 2.0 * M_PI;
double psi = psi_real_exact(k, l, m, r, theta, phi);
double dpsi = gsl_ran_gaussian(rng_p, 0.05 * psi);
/* keep track of (r, theta, phi) points */
gsl_matrix_set(vars, i, 0, r);
gsl_matrix_set(vars, i, 1, theta);
gsl_matrix_set(vars, i, 2, phi);
/* fill in RHS data vector */
gsl_vector_set(data, i, psi + dpsi);
}
/* construct the design matrix X */
gsl_multifit_ndlinear_design(vars, X, ndlinear_p);
/* now do the actual least squares fit */
gsl_multifit_linear(X, data, coeffs, cov, &chisq, multifit_p);
/* compute R^2 */
Rsq = 1.0 - chisq / gsl_stats_tss(data->data, 1, data->size);
fprintf(stderr, "chisq = %e, Rsq = %f\n", chisq, Rsq);
/* now print out the model and the exact solution and compute rms error */
{
double eps_rms = 0.0;
double volume = 0.0;
double r, theta, phi;
double dr = 0.05;
double dtheta = 5.0 * M_PI / 180.0;
double dphi = 5.0 * M_PI / 180.0;
double x[N_DIM];
gsl_vector_view xv = gsl_vector_view_array(x, N_DIM);
double psi;
double psi_model;
double err;
for (r = 0.01; r < R_MAX; r += dr)
{
for (theta = 0.0; theta < M_PI; theta += dtheta)
{
for (phi = 0.0; phi < 2.0 * M_PI; phi += dphi)
{
double dV = r * r * sin(theta) * dr * dtheta * dphi;
x[0] = r;
x[1] = theta;
x[2] = phi;
/* compute model value for this (r, theta, phi) */
psi_model = gsl_multifit_ndlinear_calc(&xv.vector,
coeffs,
ndlinear_p);
/* compute exact value for this (r, theta, phi) */
psi = psi_real_exact(k, l, m, r, theta, phi);
err = psi_model - psi;
eps_rms += err * err * dV;
volume += dV;
if (phi == 0.0)
printf("%e %e %e %e\n", r, theta, psi, psi_model);
}
}
printf("\n");
}
eps_rms /= volume;
eps_rms = sqrt(eps_rms);
fprintf(stderr, "rms error over all parameter space = %e\n", eps_rms);
}
gsl_rng_free(rng_p);
gsl_bspline_free(bspline_p);
gsl_multifit_ndlinear_free(ndlinear_p);
gsl_multifit_linear_free(multifit_p);
gsl_vector_free(data);
gsl_matrix_free(vars);
gsl_matrix_free(X);
gsl_vector_free(coeffs);
gsl_matrix_free(cov);
return 0;
} /* main() */
| {
"alphanum_fraction": 0.5850097339,
"avg_line_length": 26.9170305677,
"ext": "c",
"hexsha": "a4872bf1a77cf2a2be99b4c83307d434f54fb98d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rennhak/Keyposes",
"max_forks_repo_path": "src/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rennhak/Keyposes",
"max_issues_repo_path": "src/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c",
"max_line_length": 76,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rennhak/Keyposes",
"max_stars_repo_path": "src/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c",
"max_stars_repo_stars_event_max_datetime": "2018-05-05T12:45:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-26T07:28:56.000Z",
"num_tokens": 1866,
"size": 6164
} |
#include <petsc.h>
#include <bpetsc_impl.h>
#include <assert.h>
#define LEFT_SUBSPACE Full
#define RIGHT_SUBSPACE Full
#include <buildmat_template.h>
#undef RIGHT_SUBSPACE
#undef LEFT_SUBSPACE
int main(int argc, char const *argv[]) {
PetscErrorCode ierr;
PetscScalar* x_array;
PetscScalar* b_array;
shell_context ctx;
data_Full subspace_data;
/* test identity */
ctx.nmasks = 1;
ierr = PetscMalloc1(1, &(ctx.masks));CHKERRQ(ierr);
ierr = PetscMalloc1(2, &(ctx.mask_offsets));CHKERRQ(ierr);
ierr = PetscMalloc1(1, &(ctx.signs));CHKERRQ(ierr);
ierr = PetscMalloc1(1, &(ctx.real_coeffs));CHKERRQ(ierr);
ctx.masks[0] = 0;
ctx.mask_offsets[0] = 0;
ctx.mask_offsets[1] = 1;
ctx.signs[0] = 0;
ctx.real_coeffs[0] = 1.;
subspace_data.L = -1;
ctx.left_subspace_data = &subspace_data;
ctx.right_subspace_data = &subspace_data;
#define DIM 100
ierr = PetscMalloc1(DIM, &x_array);CHKERRQ(ierr);
ierr = PetscMalloc1(DIM, &b_array);CHKERRQ(ierr);
for (PetscInt i = 0; i < DIM; ++i) {
x_array[i] = i;
b_array[i] = 0;
}
MatMult_CPU_kernel_Full_Full(x_array, b_array, &ctx, 0, DIM, 0, DIM);
for (PetscInt i = 0; i < DIM; ++i) {
assert(b_array[i] == i);
}
ierr = PetscFree(x_array);CHKERRQ(ierr);
ierr = PetscFree(b_array);CHKERRQ(ierr);
#undef DIM
ierr = PetscFree(ctx.masks);CHKERRQ(ierr);
ierr = PetscFree(ctx.mask_offsets);CHKERRQ(ierr);
ierr = PetscFree(ctx.signs);CHKERRQ(ierr);
ierr = PetscFree(ctx.real_coeffs);CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.6738421396,
"avg_line_length": 23.5846153846,
"ext": "c",
"hexsha": "a7a7f42ea5a668be900138ffe697fa1a3134ba09",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T21:38:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-02-21T19:36:47.000Z",
"max_forks_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "GregDMeyer/dynamite",
"max_forks_repo_path": "dynamite/_backend/tests/test_shell_kernel.c",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_issues_repo_issues_event_max_datetime": "2021-02-03T20:35:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-11T22:57:09.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "GregDMeyer/dynamite",
"max_issues_repo_path": "dynamite/_backend/tests/test_shell_kernel.c",
"max_line_length": 71,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "440f0c3674bf12a835b8ad4b3c10c303c2d28265",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "GregDMeyer/dynamite",
"max_stars_repo_path": "dynamite/_backend/tests/test_shell_kernel.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-23T01:17:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-11T22:53:30.000Z",
"num_tokens": 482,
"size": 1533
} |
/* test.c
*
* Copyright (C) 2012-2014 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_spblas.h>
/*
create_random_sparse()
Create a random sparse matrix with approximately
M*N*density non-zero entries
Inputs: M - number of rows
N - number of columns
density - sparse density \in [0,1]
0 = no non-zero entries
1 = all m*n entries are filled
r - random number generator
Return: pointer to sparse matrix in triplet format (must be freed by caller)
Notes:
1) non-zero matrix entries are uniformly distributed in [0,1]
*/
static gsl_spmatrix *
create_random_sparse(const size_t M, const size_t N, const double density,
const gsl_rng *r)
{
size_t nnzwanted = (size_t) floor(M * N * GSL_MIN(density, 1.0));
gsl_spmatrix *m = gsl_spmatrix_alloc_nzmax(M, N,
nnzwanted,
GSL_SPMATRIX_TRIPLET);
while (gsl_spmatrix_nnz(m) < nnzwanted)
{
/* generate a random row and column */
size_t i = gsl_rng_uniform(r) * M;
size_t j = gsl_rng_uniform(r) * N;
/* generate random m_{ij} and add it */
double x = gsl_rng_uniform(r);
gsl_spmatrix_set(m, i, j, x);
}
return m;
} /* create_random_sparse() */
static void
create_random_vector(gsl_vector *v, const gsl_rng *r)
{
size_t i;
for (i = 0; i < v->size; ++i)
{
double x = gsl_rng_uniform(r);
gsl_vector_set(v, i, x);
}
} /* create_random_vector() */
static int
test_vectors(gsl_vector *observed, gsl_vector *expected, const double tol,
const char *str)
{
int s = 0;
size_t N = observed->size;
size_t i;
for (i = 0; i < N; ++i)
{
double x_obs = gsl_vector_get(observed, i);
double x_exp = gsl_vector_get(expected, i);
gsl_test_rel(x_obs, x_exp, tol, "N=%zu i=%zu %s", N, i, str);
}
return s;
} /* test_vectors() */
static void
test_dgemv(const size_t N, const size_t M, const double alpha,
const double beta, const CBLAS_TRANSPOSE_t TransA,
const gsl_rng *r)
{
gsl_spmatrix *A = create_random_sparse(M, N, 0.2, r);
gsl_spmatrix *B, *C;
gsl_matrix *A_dense = gsl_matrix_alloc(M, N);
gsl_vector *x, *y, *y_gsl, *y_sp;
size_t lenX, lenY;
if (TransA == CblasNoTrans)
{
lenX = N;
lenY = M;
}
else
{
lenX = M;
lenY = N;
}
x = gsl_vector_alloc(lenX);
y = gsl_vector_alloc(lenY);
y_gsl = gsl_vector_alloc(lenY);
y_sp = gsl_vector_alloc(lenY);
/* create random dense vectors */
create_random_vector(x, r);
create_random_vector(y, r);
/* copy A into A_dense */
gsl_spmatrix_sp2d(A_dense, A);
gsl_vector_memcpy(y_gsl, y);
gsl_vector_memcpy(y_sp, y);
/* compute y = alpha*op(A)*x + beta*y0 with gsl */
gsl_blas_dgemv(TransA, alpha, A_dense, x, beta, y_gsl);
/* compute y = alpha*op(A)*x + beta*y0 with spblas/triplet */
gsl_spblas_dgemv(TransA, alpha, A, x, beta, y_sp);
/* test y_sp = y_gsl */
test_vectors(y_sp, y_gsl, 1.0e-10, "test_dgemv: triplet format");
/* compute y = alpha*op(A)*x + beta*y0 with spblas/CCS */
B = gsl_spmatrix_ccs(A);
gsl_vector_memcpy(y_sp, y);
gsl_spblas_dgemv(TransA, alpha, B, x, beta, y_sp);
/* test y_sp = y_gsl */
test_vectors(y_sp, y_gsl, 1.0e-10, "test_dgemv: CCS format");
/* compute y = alpha*op(A)*x + beta*y0 with spblas/CRS */
C = gsl_spmatrix_crs(A);
gsl_vector_memcpy(y_sp, y);
gsl_spblas_dgemv(TransA, alpha, C, x, beta, y_sp);
/* test y_sp = y_gsl */
test_vectors(y_sp, y_gsl, 1.0e-10, "test_dgemv: CRS format");
gsl_spmatrix_free(A);
gsl_spmatrix_free(B);
gsl_spmatrix_free(C);
gsl_matrix_free(A_dense);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(y_gsl);
gsl_vector_free(y_sp);
} /* test_dgemv() */
static void
test_dgemm(const double alpha, const size_t M, const size_t N,
const gsl_rng *r)
{
const size_t max = GSL_MAX(M, N);
size_t i, j, k;
gsl_matrix *A_dense = gsl_matrix_alloc(M, max);
gsl_matrix *B_dense = gsl_matrix_alloc(max, N);
gsl_matrix *C_dense = gsl_matrix_alloc(M, N);
gsl_spmatrix *C = gsl_spmatrix_alloc_nzmax(M, N, 1, GSL_SPMATRIX_CCS);
for (k = 1; k <= max; ++k)
{
gsl_matrix_view Ad = gsl_matrix_submatrix(A_dense, 0, 0, M, k);
gsl_matrix_view Bd = gsl_matrix_submatrix(B_dense, 0, 0, k, N);
gsl_spmatrix *TA = create_random_sparse(M, k, 0.2, r);
gsl_spmatrix *TB = create_random_sparse(k, N, 0.2, r);
gsl_spmatrix *A = gsl_spmatrix_ccs(TA);
gsl_spmatrix *B = gsl_spmatrix_ccs(TB);
gsl_spmatrix_set_zero(C);
gsl_spblas_dgemm(alpha, A, B, C);
/* make dense matrices and use standard dgemm to multiply them */
gsl_spmatrix_sp2d(&Ad.matrix, TA);
gsl_spmatrix_sp2d(&Bd.matrix, TB);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, alpha, &Ad.matrix,
&Bd.matrix, 0.0, C_dense);
/* compare C and C_dense */
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double Cij = gsl_spmatrix_get(C, i, j);
double Dij = gsl_matrix_get(C_dense, i, j);
gsl_test_rel(Cij, Dij, 1.0e-12, "test_dgemm: _dgemm");
}
}
gsl_spmatrix_free(TA);
gsl_spmatrix_free(TB);
gsl_spmatrix_free(A);
gsl_spmatrix_free(B);
}
gsl_spmatrix_free(C);
gsl_matrix_free(A_dense);
gsl_matrix_free(B_dense);
gsl_matrix_free(C_dense);
} /* test_dgemm() */
int
main()
{
const size_t N_max = 40;
size_t m, n;
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
for (m = 1; m <= N_max; ++m)
{
for (n = 1; n <= N_max; ++n)
{
test_dgemv(m, n, 1.0, 0.0, CblasNoTrans, r);
test_dgemv(m, n, 1.0, 0.0, CblasTrans, r);
test_dgemv(m, n, 2.4, -0.5, CblasNoTrans, r);
test_dgemv(m, n, 2.4, -0.5, CblasTrans, r);
test_dgemv(m, n, 0.1, 10.0, CblasNoTrans, r);
test_dgemv(m, n, 0.1, 10.0, CblasTrans, r);
}
}
test_dgemm(1.0, 10, 10, r);
test_dgemm(2.3, 20, 15, r);
test_dgemm(1.8, 12, 30, r);
test_dgemm(0.4, 45, 35, r);
gsl_rng_free(r);
exit (gsl_test_summary());
} /* main() */
| {
"alphanum_fraction": 0.6256508633,
"avg_line_length": 27.7490494297,
"ext": "c",
"hexsha": "0c2637db4655e82cae4767b88353d056f9cd3495",
"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/spblas/test.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/spblas/test.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/spblas/test.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": 2330,
"size": 7298
} |
/** @file */
#ifndef __CCL_UTILS_H_INCLUDED__
#define __CCL_UTILS_H_INCLUDED__
#include <gsl/gsl_spline.h>
#define CCL_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define CCL_MAX(a, b) (((a) > (b)) ? (a) : (b))
CCL_BEGIN_DECLS
/**
* Compute bin edges of N-1 linearly spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_linear_spacing(double xmin, double xmax, int N);
/**
* Compute bin edges of N-1 logarithmically and then linearly spaced bins on the interval [xmin,xmax]
* @param xminlog minimum value of spacing
* @param xmin value when logarithmical ends and linear spacing begins
* @param xmax maximum value of spacing
* @param Nlin number of linear bins plus one (number of bin edges)
* @param Nlog number of logarithmic bins plus one (number of bin edges)
* @return x, bin edges in range [xminlog, xmax]
*/
double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlin, int Nlog);
/**
* Compute bin edges of N-1 logarithmically spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_log_spacing(double xmin, double xmax, int N);
//Returns array of N logarithmically-spaced values between xmin and xmax
double ccl_j_bessel(int l,double x);
//Spherical Bessel function of order l (adapted from CAMB)
/**
* Spline wrapper
* Used to take care of evaluations outside the supported range
*/
typedef struct {
gsl_interp_accel *intacc; //GSL spline
gsl_spline *spline;
double x0,xf; //Interpolation limits
double y0,yf; //Constant values to use beyond interpolation limit
} SplPar;
SplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf);
double ccl_spline_eval(double x,SplPar *spl);
void ccl_spline_free(SplPar *spl);
CCL_END_DECLS
#endif
| {
"alphanum_fraction": 0.7252641691,
"avg_line_length": 32.0307692308,
"ext": "h",
"hexsha": "7694e68b2328bf6064c23f26ed8078702722a4f3",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Russell-Jones-OxPhys/CCL",
"max_forks_repo_path": "include/ccl_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Russell-Jones-OxPhys/CCL",
"max_issues_repo_path": "include/ccl_utils.h",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Russell-Jones-OxPhys/CCL",
"max_stars_repo_path": "include/ccl_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 564,
"size": 2082
} |
// Petsc initialization
#pragma once
#include <hollow/petsc/config.h>
#include <geode/utility/debug.h>
#include <vector>
#include <string>
// Work around configuration issue in old PETSc versions
#define PETSC_RESTRICT PETSC_CXX_RESTRICT
#include <petsc.h>
namespace hollow {
using std::string;
using std::vector;
// Initialize petsc, and automatically finalize on application exit
HOLLOW_EXPORT void petsc_initialize(const string& help, const vector<string>& args);
// Check if petsc is initialized
HOLLOW_EXPORT bool petsc_initialized();
// Ensure that petsc is initialized. Can be called multiple times, but no help or args support.
HOLLOW_EXPORT void petsc_reinitialize();
// Explicitly finalize petsc. This happens automatically at program exit if petsc_initialize
// is called, but sometime it is useful to do it sooner.
HOLLOW_EXPORT void petsc_finalize();
// Reset petsc options to the given list. Any petsc objects already allocated will not change.
HOLLOW_EXPORT void petsc_set_options(const vector<string>& args);
// Add new petsc options without removing old options. Like argv[0], the first option is ignored.
HOLLOW_EXPORT void petsc_add_options(const vector<string>& args);
}
| {
"alphanum_fraction": 0.7873754153,
"avg_line_length": 33.4444444444,
"ext": "h",
"hexsha": "7984d8097eb19036cd60a40dbbbd308aeca378d2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-05-20T06:16:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-20T06:16:51.000Z",
"max_forks_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "otherlab/hollow",
"max_forks_repo_path": "hollow/petsc/init.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7",
"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": "otherlab/hollow",
"max_issues_repo_path": "hollow/petsc/init.h",
"max_line_length": 98,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "9f8209464969dfd449c791c93978292998d5c4e7",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "otherlab/hollow",
"max_stars_repo_path": "hollow/petsc/init.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-18T22:22:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-05-09T17:49:28.000Z",
"num_tokens": 266,
"size": 1204
} |
/*
** Implementation of LISA algorithm
** for statistical inference of fMRI images
**
** 2nd level inference using a GLM design matrix,
** e.g. for anova designs
**
** G.Lohmann, 2018
*/
#include <viaio/Vlib.h>
#include <viaio/file.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <viaio/os.h>
#include <viaio/VImage.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_histogram.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern void VIsolatedVoxels(VImage src,float threshold);
extern void VHistogram(gsl_histogram *histogram,VString filename);
extern void VCheckImage(VImage src);
extern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);
extern double ttest1(double *data1,int n);
extern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);
extern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);
extern double VImageVar(VImage src);
extern void VImageCount(VImage src);
extern void VGetHistRange(VImage src,double *hmin,double *hmax);
extern void VZScale(VImage src,float mode,float stddev);
extern float VGetMode(VImage src);
extern void XReadExchange(VString filename,int *exchange,int n);
extern void GLM2(VImage *src,gsl_matrix *X,gsl_vector *contrast,int *,int *permtable,int *signtable,int signswitch,VImage dest);
extern gsl_matrix *XRead2ndLevel(VString);
extern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);
extern int SignSwitch (gsl_matrix *X,gsl_vector *contrast,int *);
extern void genperm(long seed,int *exchange,int,int **,int **,int,int,gsl_vector *);
extern void HistoUpdate(VImage,gsl_histogram *);
extern gsl_matrix *VReadCovariates(VString,VBoolean);
int main (int argc, char *argv[])
{
static VArgVector in_files1;
static VString out_filename="";
static VString design_filename="";
static VString exchange_filename="";
static VString nuisance_filename="";
static VString mask_filename="";
static VArgVector cont;
static VFloat alpha = 0.05;
static VShort radius = 2;
static VFloat rvar = 2.0;
static VFloat svar = 2.0;
static VShort numiter = 2;
static VShort numperm = 5000;
static VLong seed = 99402622;
static VBoolean centering = FALSE;
static VBoolean demean = TRUE;
static VBoolean cleanup = TRUE;
static VShort nproc = 0;
static VOptionDescRec options[] = {
{"in", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,"Input files" },
{"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,"Output file" },
{"design",VStringRepn,1,(VPointer) &design_filename,VRequiredOpt,NULL,"Design file (2nd level)"},
{"grp", VStringRepn, 1, & exchange_filename, VOptionalOpt, NULL,"Group Ids needed for exchangeability" },
{"contrast", VFloatRepn, 0, (VPointer) &cont, VRequiredOpt, NULL, "contrast vector"},
{"nuisance", VStringRepn, 1, & nuisance_filename, VOptionalOpt, NULL,"Nuisance regressors" },
{"demean",VBooleanRepn,1,(VPointer) &demean,VOptionalOpt,NULL,"Whether to subtract mean in nuisance regressors"},
{"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"FDR significance level"},
{"perm",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"},
{"mask", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, "Mask"},
{"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generation"},
{"radius",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Bilateral parameter (radius in voxels)"},
{"rvar",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,"Bilateral parameter (radiometric)"},
{"svar",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,"Bilateral parameter (spatial)"},
{"filteriterations",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,"Bilateral parameter (number of iterations)"},
{"cleanup",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,"Whether to remove isolated voxels"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"},
};
FILE *fp=NULL;
VString in_filename;
VAttrList list1=NULL,out_list=NULL,geolist=NULL;
VImage *src1;
int i,j,nimages,npix=0;
double u=0;
char *prg_name=GetLipsiaName("vlisa_2ndlevel");
fprintf (stderr, "%s\n", prg_name);
/* parse command line */
if (! VParseCommand (VNumber (options), options, & argc, argv)) {
VReportUsage (argv[0], VNumber (options), options, NULL);
exit (EXIT_FAILURE);
}
if (argc > 1) {
VReportBadArgs (argc, argv);
exit (EXIT_FAILURE);
}
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
if (nproc > 0 && nproc < num_procs) num_procs = nproc;
fprintf(stderr," using %d cores\n",(int)num_procs);
omp_set_num_threads(num_procs);
#endif /* _OPENMP */
/* images */
VImage mask = VReadImageFile(mask_filename);
if (mask==NULL) VError("Error reading mask file %s",mask_filename);
nimages = in_files1.number;
src1 = (VImage *) VCalloc(nimages,sizeof(VImage));
for (i = 0; i < nimages; i++) {
in_filename = ((VString *) in_files1.vector)[i];
list1 = VReadAttrList(in_filename,0L,TRUE,FALSE);
VMaskMinval(list1,mask,0.0);
src1[i] = VReadImage(list1);
if (src1[i] == NULL) VError(" no input image found");
if (VPixelRepn(src1[i]) != VFloatRepn) VError(" input pixel repn must be float");
if (i == 0) npix = VImageNPixels(src1[i]);
else if (npix != VImageNPixels(src1[i])) VError(" inconsistent image dimensions");
fprintf(stderr," %3d: %s\n",i,in_filename);
/* use geometry info from 1st file */
if (geolist == NULL) geolist = VGetGeoInfo(list1);
}
/* get nuisance file */
gsl_matrix *XN = NULL;
if (strlen(nuisance_filename) > 1) {
XN = VReadCovariates(nuisance_filename,demean);
fprintf(stderr," nuisance covariates dimensions: %d x %d\n",(int)XN->size1,(int)XN->size2);
if (XN->size1 != nimages)
VError(" number of input images (%d) does not match number of rows in nuisance covariates file (%d)",nimages,(int)XN->size1);
}
/* get design file and its inverse */
gsl_matrix *X0 = XRead2ndLevel(design_filename);
fprintf(stderr," design file dimensions: %d x %d\n",(int)X0->size1,(int)X0->size2);
if (X0->size1 != nimages)
VError(" number of input images (%d) does not match number of rows in design file (%d)",nimages,(int)X0->size1);
/* read contrast vector */
if (cont.number != X0->size2)
VError(" Dimension of contrast vector (%d) does not match number of columns in design file (%d)",cont.number,X0->size2);
gsl_vector *contrast0 = gsl_vector_alloc(cont.number);
for (i=0; i < cont.number; i++) {
double u = ((VFloat *)cont.vector)[i];
gsl_vector_set(contrast0, i, u);
}
/* concatenate design matrix and nuisance covariates */
gsl_matrix *X = NULL;
gsl_vector *contrast = NULL;
int *permflag = NULL;
/* include nuisance covariates, if present */
if (XN != NULL) {
permflag = (int *) VCalloc(XN->size2 + X0->size2,sizeof(int));
for (j=0; j<XN->size2 + X0->size2; j++) permflag[j] = 0;
for (j=0; j<X0->size2; j++) permflag[j] = 1;
X = gsl_matrix_calloc(X0->size1, X0->size2 + XN->size2);
for (i=0; i<X->size1; i++) {
for (j=0; j<X0->size2; j++) {
u = gsl_matrix_get(X0,i,j);
gsl_matrix_set(X,i,j,u);
}
for (j=0; j<XN->size2; j++) {
u = gsl_matrix_get(XN,i,j);
gsl_matrix_set(X,i,j+X0->size2,u);
}
}
contrast = gsl_vector_calloc(cont.number + XN->size2);
gsl_vector_set_zero(contrast);
for (j=0; j<contrast0->size; j++) gsl_vector_set(contrast,j,contrast0->data[j]);
}
/* no nuisance covariates */
else {
if (X0->size2 == 1) VError(" Please use 'vlisa_onesample' for onesample tests");
permflag = (int *) VCalloc(X0->size2,sizeof(int));
for (j=0; j<X0->size2; j++) permflag[j] = 1;
X = gsl_matrix_calloc(X0->size1,X0->size2);
gsl_matrix_memcpy(X,X0);
contrast = gsl_vector_calloc(cont.number);
gsl_vector_memcpy(contrast,contrast0);
}
/* read exchangeability information */
int *exchange = (int *) VCalloc(X->size1,sizeof(int));
for (i=0; i<X->size1; i++) exchange[i] = 1; /* no restrictions w.r.t. exchangeability */
if (strlen(exchange_filename) > 1) {
XReadExchange(exchange_filename,exchange,(int)X->size1);
}
/* ini random permutations and sign switching */
int signswitch = SignSwitch(X,contrast,permflag);
int nperm=0;
int **permtable = (int **) VCalloc(numperm,sizeof(int *));
int **signtable = (int **) VCalloc(numperm,sizeof(int *));
genperm((long)seed,exchange,signswitch,permtable,signtable,(int)nimages,(int)numperm,contrast);
/* estimate null variance based on first 30 permutations */
double hmin=0,hmax=0;
float stddev=1.0;
if (numperm > 0) {
int tstperm = 30;
if (tstperm > numperm) tstperm = numperm;
double varsum=0,nx=0;
#pragma omp parallel for shared(src1,permtable) schedule(dynamic)
for (nperm = 0; nperm < tstperm; nperm++) {
VImage zmap = VCreateImageLike(src1[0]);
GLM2(src1,X,contrast,permflag,permtable[nperm],signtable[nperm],signswitch,zmap);
#pragma omp critical
{
varsum += VImageVar(zmap);
nx++;
}
VDestroyImage(zmap);
}
double meanvar = varsum/nx;
stddev = sqrt(meanvar);
}
/* no permutation */
int *nopermtable = (int *) VCalloc(nimages,sizeof(int));
int *nosigntable = (int *) VCalloc(nimages,sizeof(int));
for (i=0; i<nimages; i++) nopermtable[i] = i;
for (i=0; i<nimages; i++) nosigntable[i] = 1;
VImage dst1 = VCreateImageLike (src1[0]);
VImage zmap1 = VCreateImageLike(src1[0]);
GLM2(src1,X,contrast,permflag,nopermtable,nosigntable,signswitch,zmap1);
if (numperm == 0) {
double z = VImageVar(zmap1);
stddev = (float)(sqrt(z)); /* update stddev */
}
float mode=0;
if (centering) mode = VGetMode(zmap1);
if (numperm > 0) VZScale(zmap1,mode,stddev);
VBilateralFilter(zmap1,dst1,(int)radius,(double)(rvar),(double)svar,(int)numiter);
/* ini histograms */
VGetHistRange(dst1,&hmin,&hmax);
size_t nbins = 20000;
gsl_histogram *hist0 = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);
gsl_histogram *histz = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (histz,hmin,hmax);
HistoUpdate(dst1,histz);
/* random permutations */
#pragma omp parallel for shared(src1,permtable) schedule(dynamic)
for (nperm = 0; nperm < numperm; nperm++) {
if (nperm%20 == 0) fprintf(stderr," perm %4d of %d\r",nperm,(int)numperm);
VImage zmap = VCreateImageLike(src1[0]);
VImage dst = VCreateImageLike (zmap);
GLM2(src1,X,contrast,permflag,permtable[nperm],signtable[nperm],signswitch,zmap);
float mode=0;
if (centering) mode = VGetMode(zmap);
VZScale(zmap,mode,stddev);
VBilateralFilter(zmap,dst,(int)radius,(double)(rvar),(double)svar,(int)numiter);
#pragma omp critical
{
HistoUpdate(dst,hist0);
}
VDestroyImage(dst);
VDestroyImage(zmap);
}
/* apply fdr */
VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);
if (numperm > 0) {
FDR(dst1,fdrimage,hist0,histz,(double)alpha);
if (cleanup && alpha < 1.0) {
VIsolatedVoxels(fdrimage,(float)(1.0-alpha));
}
}
/* write output to disk */
out_list = VCreateAttrList ();
VHistory(VNumber(options),options,prg_name,&list1,&out_list);
VSetGeoInfo(geolist,out_list);
VAppendAttr (out_list,"image",NULL,VImageRepn,fdrimage);
fp = VOpenOutputFile (out_filename, TRUE);
if (! VWriteFile (fp, out_list)) exit (1);
fclose(fp);
fprintf (stderr, "\n%s: done.\n", argv[0]);
exit(0);
}
| {
"alphanum_fraction": 0.6801971102,
"avg_line_length": 35.4230769231,
"ext": "c",
"hexsha": "4f1a2e8e732ec257490f55d599ad1ca8f998968a",
"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_2ndlevel/vlisa_2ndlevel.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_2ndlevel/vlisa_2ndlevel.c",
"max_line_length": 131,
"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_2ndlevel/vlisa_2ndlevel.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": 3714,
"size": 11973
} |
#include <gsl/blas/cblas.h>
/**
All the methods below are obtained directly from the ATLAS implementation of BLAS, available at: http://www.netlib.org/clapack/cblas/
*/
#include "f2c.h"
doublereal ddot(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy){
/* System generated locals */
integer i__1;
doublereal ret_val;
/* Local variables */
static integer i, m;
static doublereal dtemp;
static integer ix, iy, mp1;
/* forms the dot product of two vectors.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
ret_val = 0.;
dtemp = 0.;
if (*n <= 0) {
return ret_val;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
dtemp += DX(ix) * DY(iy);
ix += *incx;
iy += *incy;
/* L10: */
}
ret_val = dtemp;
return ret_val;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 5;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
dtemp += DX(i) * DY(i);
/* L30: */
}
if (*n < 5) {
goto L60;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 5) {
dtemp = dtemp + DX(i) * DY(i) + DX(i + 1) * DY(i + 1) + DX(i + 2) *
DY(i + 2) + DX(i + 3) * DY(i + 3) + DX(i + 4) * DY(i + 4);
/* L50: */
}
L60:
ret_val = dtemp;
return ret_val;
} /* ddot_ */
doublereal dnrm2(integer *n, doublereal *x, integer *incx)
{
/* System generated locals */
integer i__1, i__2;
doublereal ret_val, d__1;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static doublereal norm, scale, absxi;
static integer ix;
static doublereal ssq;
/* DNRM2 returns the euclidean norm of a vector via the function
name, so that
DNRM2 := sqrt( x'*x )
-- This version written on 25-October-1982.
Modified on 14-October-1993 to inline the call to DLASSQ.
Sven Hammarling, Nag Ltd.
Parameter adjustments
Function Body */
#define X(I) x[(I)-1]
if (*n < 1 || *incx < 1) {
norm = 0.;
} else if (*n == 1) {
norm = abs(X(1));
} else {
scale = 0.;
ssq = 1.;
/* The following loop is equivalent to this call to the LAPACK
auxiliary routine:
CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */
i__1 = (*n - 1) * *incx + 1;
i__2 = *incx;
for (ix = 1; *incx < 0 ? ix >= (*n-1)**incx+1 : ix <= (*n-1)**incx+1; ix += *incx) {
if (X(ix) != 0.) {
absxi = (d__1 = X(ix), abs(d__1));
if (scale < absxi) {
/* Computing 2nd power */
d__1 = scale / absxi;
ssq = ssq * (d__1 * d__1) + 1.;
scale = absxi;
} else {
/* Computing 2nd power */
d__1 = absxi / scale;
ssq += d__1 * d__1;
}
}
/* L10: */
}
norm = scale * sqrt(ssq);
}
ret_val = norm;
return ret_val;
/* End of DNRM2. */
} /* dnrm2_ */
int dswap(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy)
{
/* System generated locals */
integer i__1;
/* Local variables */
static integer i, m;
static doublereal dtemp;
static integer ix, iy, mp1;
/* interchanges two vectors.
uses unrolled loops for increments equal one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
if (*n <= 0) {
return 0;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments not equal
to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
dtemp = DX(ix);
DX(ix) = DY(iy);
DY(iy) = dtemp;
ix += *incx;
iy += *incy;
/* L10: */
}
return 0;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 3;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
dtemp = DX(i);
DX(i) = DY(i);
DY(i) = dtemp;
/* L30: */
}
if (*n < 3) {
return 0;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 3) {
dtemp = DX(i);
DX(i) = DY(i);
DY(i) = dtemp;
dtemp = DX(i + 1);
DX(i + 1) = DY(i + 1);
DY(i + 1) = dtemp;
dtemp = DX(i + 2);
DX(i + 2) = DY(i + 2);
DY(i + 2) = dtemp;
/* L50: */
}
return 0;
} /* dswap_ */
int dcopy(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy)
{
/* System generated locals */
integer i__1;
/* Local variables */
static integer i, m, ix, iy, mp1;
/* copies a vector, x, to a vector, y.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
if (*n <= 0) {
return 0;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
DY(iy) = DX(ix);
ix += *incx;
iy += *incy;
/* L10: */
}
return 0;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 7;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
DY(i) = DX(i);
/* L30: */
}
if (*n < 7) {
return 0;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 7) {
DY(i) = DX(i);
DY(i + 1) = DX(i + 1);
DY(i + 2) = DX(i + 2);
DY(i + 3) = DX(i + 3);
DY(i + 4) = DX(i + 4);
DY(i + 5) = DX(i + 5);
DY(i + 6) = DX(i + 6);
/* L50: */
}
return 0;
} /* dcopy_ */
int dgemm(char *transa, char *transb, integer *m, integer * n, integer *k, doublereal *alpha, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal *beta, doublereal *c, integer *ldc)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2,
i__3;
/* Local variables */
static integer info;
static logical nota, notb;
static doublereal temp;
static integer i, j, l, ncola;
extern logical lsame_(char *, char *);
static integer nrowa, nrowb;
extern /* Subroutine */ int xerbla_(char *, integer *);
/* Purpose
=======
DGEMM performs one of the matrix-matrix operations
C := alpha*op( A )*op( B ) + beta*C,
where op( X ) is one of
op( X ) = X or op( X ) = X',
alpha and beta are scalars, and A, B and C are matrices, with op( A )
an m by k matrix, op( B ) a k by n matrix and C an m by n matrix.
Parameters
==========
TRANSA - CHARACTER*1.
On entry, TRANSA specifies the form of op( A ) to be used in
the matrix multiplication as follows:
TRANSA = 'N' or 'n', op( A ) = A.
TRANSA = 'T' or 't', op( A ) = A'.
TRANSA = 'C' or 'c', op( A ) = A'.
Unchanged on exit.
TRANSB - CHARACTER*1.
On entry, TRANSB specifies the form of op( B ) to be used in
the matrix multiplication as follows:
TRANSB = 'N' or 'n', op( B ) = B.
TRANSB = 'T' or 't', op( B ) = B'.
TRANSB = 'C' or 'c', op( B ) = B'.
Unchanged on exit.
M - INTEGER.
On entry, M specifies the number of rows of the matrix
op( A ) and of the matrix C. M must be at least zero.
Unchanged on exit.
N - INTEGER.
On entry, N specifies the number of columns of the matrix
op( B ) and the number of columns of the matrix C. N must be
at least zero.
Unchanged on exit.
K - INTEGER.
On entry, K specifies the number of columns of the matrix
op( A ) and the number of rows of the matrix op( B ). K must
be at least zero.
Unchanged on exit.
ALPHA - DOUBLE PRECISION.
On entry, ALPHA specifies the scalar alpha.
Unchanged on exit.
A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is
k when TRANSA = 'N' or 'n', and is m otherwise.
Before entry with TRANSA = 'N' or 'n', the leading m by k
part of the array A must contain the matrix A, otherwise
the leading k by m part of the array A must contain the
matrix A.
Unchanged on exit.
LDA - INTEGER.
On entry, LDA specifies the first dimension of A as declared
in the calling (sub) program. When TRANSA = 'N' or 'n' then
LDA must be at least max( 1, m ), otherwise LDA must be at
least max( 1, k ).
Unchanged on exit.
B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is
n when TRANSB = 'N' or 'n', and is k otherwise.
Before entry with TRANSB = 'N' or 'n', the leading k by n
part of the array B must contain the matrix B, otherwise
the leading n by k part of the array B must contain the
matrix B.
Unchanged on exit.
LDB - INTEGER.
On entry, LDB specifies the first dimension of B as declared
in the calling (sub) program. When TRANSB = 'N' or 'n' then
LDB must be at least max( 1, k ), otherwise LDB must be at
least max( 1, n ).
Unchanged on exit.
BETA - DOUBLE PRECISION.
On entry, BETA specifies the scalar beta. When BETA is
supplied as zero then C need not be set on input.
Unchanged on exit.
C - DOUBLE PRECISION array of DIMENSION ( LDC, n ).
Before entry, the leading m by n part of the array C must
contain the matrix C, except when beta is zero, in which
case C need not be set on entry.
On exit, the array C is overwritten by the m by n matrix
( alpha*op( A )*op( B ) + beta*C ).
LDC - INTEGER.
On entry, LDC specifies the first dimension of C as declared
in the calling (sub) program. LDC must be at least
max( 1, m ).
Unchanged on exit.
Level 3 Blas routine.
-- Written on 8-February-1989.
Jack Dongarra, Argonne National Laboratory.
Iain Duff, AERE Harwell.
Jeremy Du Croz, Numerical Algorithms Group Ltd.
Sven Hammarling, Numerical Algorithms Group Ltd.
Set NOTA and NOTB as true if A and B respectively are not
transposed and set NROWA, NCOLA and NROWB as the number of rows
and columns of A and the number of rows of B respectively.
Parameter adjustments
Function Body */
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
#define B(I,J) b[(I)-1 + ((J)-1)* ( *ldb)]
#define C(I,J) c[(I)-1 + ((J)-1)* ( *ldc)]
nota = lsame_(transa, "N");
notb = lsame_(transb, "N");
if (nota) {
nrowa = *m;
ncola = *k;
} else {
nrowa = *k;
ncola = *m;
}
if (notb) {
nrowb = *k;
} else {
nrowb = *n;
}
/* Test the input parameters. */
info = 0;
if (! nota && ! lsame_(transa, "C") && ! lsame_(transa, "T")) {
info = 1;
} else if (! notb && ! lsame_(transb, "C") && ! lsame_(transb,
"T")) {
info = 2;
} else if (*m < 0) {
info = 3;
} else if (*n < 0) {
info = 4;
} else if (*k < 0) {
info = 5;
} else if (*lda < max(1,nrowa)) {
info = 8;
} else if (*ldb < max(1,nrowb)) {
info = 10;
} else if (*ldc < max(1,*m)) {
info = 13;
}
if (info != 0) {
xerbla_("DGEMM ", &info);
return 0;
}
/* Quick return if possible. */
if (*m == 0 || *n == 0 || (*alpha == 0. || *k == 0) && *beta == 1.) {
return 0;
}
/* And if alpha.eq.zero. */
if (*alpha == 0.) {
if (*beta == 0.) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = 0.;
/* L10: */
}
/* L20: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = *beta * C(i,j);
/* L30: */
}
/* L40: */
}
}
return 0;
}
/* Start the operations. */
if (notb) {
if (nota) {
/* Form C := alpha*A*B + beta*C. */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (*beta == 0.) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = 0.;
/* L50: */
}
} else if (*beta != 1.) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = *beta * C(i,j);
/* L60: */
}
}
i__2 = *k;
for (l = 1; l <= *k; ++l) {
if (B(l,j) != 0.) {
temp = *alpha * B(l,j);
i__3 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) += temp * A(i,l);
/* L70: */
}
}
/* L80: */
}
/* L90: */
}
} else {
/* Form C := alpha*A'*B + beta*C */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = 0.;
i__3 = *k;
for (l = 1; l <= *k; ++l) {
temp += A(l,i) * B(l,j);
/* L100: */
}
if (*beta == 0.) {
C(i,j) = *alpha * temp;
} else {
C(i,j) = *alpha * temp + *beta * C(i,j);
}
/* L110: */
}
/* L120: */
}
}
} else {
if (nota) {
/* Form C := alpha*A*B' + beta*C */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (*beta == 0.) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = 0.;
/* L130: */
}
} else if (*beta != 1.) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) = *beta * C(i,j);
/* L140: */
}
}
i__2 = *k;
for (l = 1; l <= *k; ++l) {
if (B(j,l) != 0.) {
temp = *alpha * B(j,l);
i__3 = *m;
for (i = 1; i <= *m; ++i) {
C(i,j) += temp * A(i,l);
/* L150: */
}
}
/* L160: */
}
/* L170: */
}
} else {
/* Form C := alpha*A'*B' + beta*C */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = 0.;
i__3 = *k;
for (l = 1; l <= *k; ++l) {
temp += A(l,i) * B(j,l);
/* L180: */
}
if (*beta == 0.) {
C(i,j) = *alpha * temp;
} else {
C(i,j) = *alpha * temp + *beta * C(i,j);
}
/* L190: */
}
/* L200: */
}
}
}
return 0;
/* End of DGEMM . */
} /* dgemm_ */
int dgemv(char *trans, integer *m, integer *n, doublereal * alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2;
/* Local variables */
static integer info;
static doublereal temp;
static integer lenx, leny, i, j;
extern logical lsame_(char *, char *);
static integer ix, iy, jx, jy, kx, ky;
extern /* Subroutine */ int xerbla_(char *, integer *);
/* Purpose
=======
DGEMV performs one of the matrix-vector operations
y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y,
where alpha and beta are scalars, x and y are vectors and A is an
m by n matrix.
Parameters
==========
TRANS - CHARACTER*1.
On entry, TRANS specifies the operation to be performed as
follows:
TRANS = 'N' or 'n' y := alpha*A*x + beta*y.
TRANS = 'T' or 't' y := alpha*A'*x + beta*y.
TRANS = 'C' or 'c' y := alpha*A'*x + beta*y.
Unchanged on exit.
M - INTEGER.
On entry, M specifies the number of rows of the matrix A.
M must be at least zero.
Unchanged on exit.
N - INTEGER.
On entry, N specifies the number of columns of the matrix A.
N must be at least zero.
Unchanged on exit.
ALPHA - DOUBLE PRECISION.
On entry, ALPHA specifies the scalar alpha.
Unchanged on exit.
A - DOUBLE PRECISION array of DIMENSION ( LDA, n ).
Before entry, the leading m by n part of the array A must
contain the matrix of coefficients.
Unchanged on exit.
LDA - INTEGER.
On entry, LDA specifies the first dimension of A as declared
in the calling (sub) program. LDA must be at least
max( 1, m ).
Unchanged on exit.
X - DOUBLE PRECISION array of DIMENSION at least
( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n'
and at least
( 1 + ( m - 1 )*abs( INCX ) ) otherwise.
Before entry, the incremented array X must contain the
vector x.
Unchanged on exit.
INCX - INTEGER.
On entry, INCX specifies the increment for the elements of
X. INCX must not be zero.
Unchanged on exit.
BETA - DOUBLE PRECISION.
On entry, BETA specifies the scalar beta. When BETA is
supplied as zero then Y need not be set on input.
Unchanged on exit.
Y - DOUBLE PRECISION array of DIMENSION at least
( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'
and at least
( 1 + ( n - 1 )*abs( INCY ) ) otherwise.
Before entry with BETA non-zero, the incremented array Y
must contain the vector y. On exit, Y is overwritten by the
updated vector y.
INCY - INTEGER.
On entry, INCY specifies the increment for the elements of
Y. INCY must not be zero.
Unchanged on exit.
Level 2 Blas routine.
-- Written on 22-October-1986.
Jack Dongarra, Argonne National Lab.
Jeremy Du Croz, Nag Central Office.
Sven Hammarling, Nag Central Office.
Richard Hanson, Sandia National Labs.
Test the input parameters.
Parameter adjustments
Function Body */
#define X(I) x[(I)-1]
#define Y(I) y[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
info = 0;
if (! lsame_(trans, "N") && ! lsame_(trans, "T") && !
lsame_(trans, "C")) {
info = 1;
} else if (*m < 0) {
info = 2;
} else if (*n < 0) {
info = 3;
} else if (*lda < max(1,*m)) {
info = 6;
} else if (*incx == 0) {
info = 8;
} else if (*incy == 0) {
info = 11;
}
if (info != 0) {
xerbla_("DGEMV ", &info);
return 0;
}
/* Quick return if possible. */
if (*m == 0 || *n == 0 || *alpha == 0. && *beta == 1.) {
return 0;
}
/* Set LENX and LENY, the lengths of the vectors x and y, and set
up the start points in X and Y. */
if (lsame_(trans, "N")) {
lenx = *n;
leny = *m;
} else {
lenx = *m;
leny = *n;
}
if (*incx > 0) {
kx = 1;
} else {
kx = 1 - (lenx - 1) * *incx;
}
if (*incy > 0) {
ky = 1;
} else {
ky = 1 - (leny - 1) * *incy;
}
/* Start the operations. In this version the elements of A are
accessed sequentially with one pass through A.
First form y := beta*y. */
if (*beta != 1.) {
if (*incy == 1) {
if (*beta == 0.) {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(i) = 0.;
/* L10: */
}
} else {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(i) = *beta * Y(i);
/* L20: */
}
}
} else {
iy = ky;
if (*beta == 0.) {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(iy) = 0.;
iy += *incy;
/* L30: */
}
} else {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(iy) = *beta * Y(iy);
iy += *incy;
/* L40: */
}
}
}
}
if (*alpha == 0.) {
return 0;
}
if (lsame_(trans, "N")) {
/* Form y := alpha*A*x + y. */
jx = kx;
if (*incy == 1) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (X(jx) != 0.) {
temp = *alpha * X(jx);
i__2 = *m;
for (i = 1; i <= *m; ++i) {
Y(i) += temp * A(i,j);
/* L50: */
}
}
jx += *incx;
/* L60: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (X(jx) != 0.) {
temp = *alpha * X(jx);
iy = ky;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
Y(iy) += temp * A(i,j);
iy += *incy;
/* L70: */
}
}
jx += *incx;
/* L80: */
}
}
} else {
/* Form y := alpha*A'*x + y. */
jy = ky;
if (*incx == 1) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
temp = 0.;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp += A(i,j) * X(i);
/* L90: */
}
Y(jy) += *alpha * temp;
jy += *incy;
/* L100: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
temp = 0.;
ix = kx;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp += A(i,j) * X(ix);
ix += *incx;
/* L110: */
}
Y(jy) += *alpha * temp;
jy += *incy;
/* L120: */
}
}
}
return 0;
/* End of DGEMV . */
} /* dgemv_ */
logical lsame_(char *ca, char *cb)
{
/* System generated locals */
logical ret_val;
/* Local variables */
static integer inta, intb, zcode;
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
January 31, 1994
Purpose
=======
LSAME returns .TRUE. if CA is the same letter as CB regardless of
case.
Arguments
=========
CA (input) CHARACTER*1
CB (input) CHARACTER*1
CA and CB specify the single characters to be compared.
=====================================================================
Test if the characters are equal */
ret_val = *(unsigned char *)ca == *(unsigned char *)cb;
if (ret_val) {
return ret_val;
}
/* Now test for equivalence if both characters are alphabetic. */
zcode = 'Z';
/* Use 'Z' rather than 'A' so that ASCII can be detected on Prime
machines, on which ICHAR returns a value with bit 8 set.
ICHAR('A') on Prime machines returns 193 which is the same as
ICHAR('A') on an EBCDIC machine. */
inta = *(unsigned char *)ca;
intb = *(unsigned char *)cb;
if (zcode == 90 || zcode == 122) {
/* ASCII is assumed - ZCODE is the ASCII code of either lower o
r
upper case 'Z'. */
if (inta >= 97 && inta <= 122) {
inta += -32;
}
if (intb >= 97 && intb <= 122) {
intb += -32;
}
} else if (zcode == 233 || zcode == 169) {
/* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower
or
upper case 'Z'. */
if (inta >= 129 && inta <= 137 || inta >= 145 && inta <= 153 || inta
>= 162 && inta <= 169) {
inta += 64;
}
if (intb >= 129 && intb <= 137 || intb >= 145 && intb <= 153 || intb
>= 162 && intb <= 169) {
intb += 64;
}
} else if (zcode == 218 || zcode == 250) {
/* ASCII is assumed, on Prime machines - ZCODE is the ASCII cod
e
plus 128 of either lower or upper case 'Z'. */
if (inta >= 225 && inta <= 250) {
inta += -32;
}
if (intb >= 225 && intb <= 250) {
intb += -32;
}
}
ret_val = inta == intb;
/* RETURN
End of LSAME */
return ret_val;
} /* lsame_ */
int xerbla_(char *srname, integer *info)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
XERBLA is an error handler for the LAPACK routines.
It is called by an LAPACK routine if an input parameter has an
invalid value. A message is printed and execution stops.
Installers may consider modifying the STOP statement in order to
call system-specific exception-handling facilities.
Arguments
=========
SRNAME (input) CHARACTER*6
The name of the routine which called XERBLA.
INFO (input) INTEGER
The position of the invalid parameter in the parameter list
of the calling routine.
=====================================================================
*/
printf("** On entry to %6s, parameter number %2i had an illegal value\n",
srname, *info);
/* End of XERBLA */
return 0;
} /* xerbla_ */
| {
"alphanum_fraction": 0.4696168834,
"avg_line_length": 22.0963341858,
"ext": "c",
"hexsha": "822c008379b52d3daaf761dbf15833f329872df9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c",
"max_line_length": 198,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8572,
"size": 25919
} |
/*
* CircularDB implementation for time series data.
*
* Copyright (c) 2007-2009 Powerset, Inc
* Copyright (c) Dan Grillo, Manish Dubey, Dan Sully
*
* All rights reserved.
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
/* For the aggregation interface */
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics.h>
#include <circulardb_interface.h>
/* Future win32 support */
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* Save away errno so it doesn't get overwritten */
int cdb_error(void) {
int cdb_error = errno;
return cdb_error;
}
static void _print_record(FILE *fh, cdb_time_t time, double value, const char *date_format) {
if (date_format == NULL || strcmp(date_format, "") == 0) {
fprintf(fh, "%d %.8g\n", (int)(time), value);
} else {
char formatted[256];
time_t stime = (time_t)time;
strftime(formatted, sizeof(formatted), date_format, localtime(&stime));
fprintf(fh, "%d [%s] %.8g\n", (int)(time), formatted, value);
}
}
static uint64_t _physical_record_for_logical_record(cdb_header_t *header, int64_t logical_record) {
uint64_t physical_record = 0;
/* -ve indicates nth record from the end
+ve indicates nth record from the beginning (zero based counting for
this case)
-3 = seek to 3rd record from the end
5 = seek to 6th record from the beginning
0 = seek to first record (start) from the beginning
change the request for -nth record (nth record from the end)
to a request for mth record from the beginning, where:
m = N + n (n is -ve)
N : total num of records. */
if (logical_record < 0) {
int64_t rec_num_from_start = header->num_records + logical_record;
/* if asking for records more than there are in the db, just give as many as we can */
logical_record = rec_num_from_start >= 0 ? rec_num_from_start : 0;
}
if (logical_record >= header->num_records) {
#ifdef DEBUG
printf("Can't seek to record [%"PRIu64"] with only [%"PRIu64"] in db\n", logical_record, header->num_records);
#endif
return 0;
}
/* DRK unclear behavior here. Looks like if I specify -N where N >
num_records, I get pointed to #0, but if I specify +N where N >
num_records, it's an error */
/* Nth logical record (from the beginning) maps to Mth physical record
in the file, where:
m = (n+s) % N
s = physical record that is 0th logical record
N = total number of records in the db. */
physical_record = logical_record + header->start_record;
if (header->num_records > 0) {
physical_record = (physical_record % header->num_records);
}
return physical_record;
}
static int64_t _seek_to_logical_record(cdb_t *cdb, int64_t logical_record) {
uint64_t physical_record = _physical_record_for_logical_record(cdb->header, logical_record);
uint64_t offset = HEADER_SIZE + (physical_record * RECORD_SIZE);
if (lseek(cdb->fd, offset, SEEK_SET) != offset) {
return -1;
}
return physical_record;
}
static cdb_time_t _time_for_logical_record(cdb_t *cdb, int64_t logical_record) {
cdb_record_t record[RECORD_SIZE];
cdb_time_t time = 0;
/* skip over any record that has NULL time or bad time values
Such datapoints in cdb indicate a corrupted cdb. */
while (!time || time <= 0) {
if (_seek_to_logical_record(cdb, logical_record) < 0) {
time = 0;
break;
}
logical_record += 1;
if (read(cdb->fd, &record, RECORD_SIZE) < 0) {
time = 0;
break;
}
time = record->time;
}
return time;
}
/* note - if no exact match, will return a record with a time greater than the requested value */
static int64_t _logical_record_for_time(cdb_t *cdb, cdb_time_t req_time, int64_t start_logical_record, int64_t end_logical_record) {
bool first_time = false;
cdb_time_t start_time, next_time, center_time;
int64_t delta, center_logical_record, next_logical_record;
uint64_t num_recs = cdb->header->num_records;
/* for the very first time find start and end */
if (start_logical_record == 0 && end_logical_record == 0) {
start_logical_record = 0;
end_logical_record = num_recs - 1;
first_time = true;
}
/* if no particular time was requested, just return the first one. */
if (req_time == 0) {
return start_logical_record;
}
/* if there are only 2 or 1 records in the search space, return the last record */
if (end_logical_record - start_logical_record <= 1) {
return end_logical_record;
}
start_time = _time_for_logical_record(cdb, start_logical_record);
/* if requested time is less than start_time, start_time is the best we can do. */
if (req_time <= start_time) {
return start_logical_record;
}
/* don't go out of bounds */
if (start_logical_record + 1 >= num_recs) {
return start_logical_record;
}
next_logical_record = start_logical_record;
next_time = start_time;
/* if _seek_to_logical_record encounters bad data it fabricates and
returns next good value. Try to get the *real* next rec. */
while ((next_time - start_time) == 0) {
next_logical_record += 1;
next_time = _time_for_logical_record(cdb, next_logical_record);
if (next_logical_record >= num_recs) {
break;
}
}
delta = next_time - start_time;
/* delta = 0 means that _seek_to_logical_record fabricated data on the fly */
if (delta == 0) {
return start_logical_record;
/* if we have wrapped over, or if the requested time is in the range of start and next, return start */
} else if (delta < 0) {
return start_logical_record;
} else if (req_time <= next_time) {
return next_logical_record;
}
/* for the very first binary search pivot point, take an aggressive guess to make search converge faster */
if (first_time) {
center_logical_record = (req_time - start_time) / (next_time - start_time) - 1;
} else {
center_logical_record = start_logical_record + (end_logical_record - start_logical_record) / 2;
}
if (num_recs > 0) {
center_logical_record = (center_logical_record % num_recs);
}
center_time = _time_for_logical_record(cdb, center_logical_record);
if (req_time >= center_time) {
start_logical_record = center_logical_record;
} else {
end_logical_record = center_logical_record;
}
return _logical_record_for_time(cdb, req_time, start_logical_record, end_logical_record);
}
bool _cdb_is_writable(cdb_t *cdb) {
/* We can't check for the O_RDONLY bit being because its defined value is zero.
* i.e. there are no bits set to look for. We therefore assume
* O_RDONLY if neither O_WRONLY nor O_RDWR are set. */
if (cdb->flags & O_RDWR) {
return true;
}
return false;
}
int cdb_read_header(cdb_t *cdb) {
struct stat st;
/* If the header has already been read from backing store do not read again */
if (cdb->synced == true) {
return CDB_SUCCESS;
}
if (cdb_open(cdb) != 0) {
return cdb_error();
}
if (pread(cdb->fd, cdb->header, HEADER_SIZE, 0) != HEADER_SIZE) {
return cdb_error();
}
if (strncmp(cdb->header->token, CDB_TOKEN, sizeof(CDB_TOKEN)) != 0) {
return CDB_EBADTOK;
}
if (strncmp(cdb->header->version, CDB_VERSION, sizeof(CDB_VERSION)) != 0) {
return CDB_EBADVER;
}
cdb->synced = true;
/* Calculate the number of records */
if (fstat(cdb->fd, &st) == 0) {
cdb->header->num_records = (st.st_size - HEADER_SIZE) / RECORD_SIZE;
} else {
cdb->header->num_records = 0;
}
return CDB_SUCCESS;
}
int cdb_write_header(cdb_t *cdb) {
if (cdb->synced) {
return CDB_SUCCESS;
}
if (_cdb_is_writable(cdb) == false) {
return CDB_ERDONLY;
}
cdb->synced = false;
if (cdb_open(cdb) > 0) {
return cdb_error();
}
if (pwrite(cdb->fd, cdb->header, HEADER_SIZE, 0) != HEADER_SIZE) {
return cdb_error();
}
cdb->synced = true;
return CDB_SUCCESS;
}
void cdb_print_header(cdb_t * cdb) {
printf("version: [%s]\n", cdb->header->version);
printf("name: [%s]\n", cdb->header->name);
printf("desc: [%s]\n", cdb->header->desc);
printf("units: [%s]\n", cdb->header->units);
if (cdb->header->type == CDB_TYPE_COUNTER) {
printf("type: [COUNTER]\n");
}
if (cdb->header->type == CDB_TYPE_GAUGE) {
printf("type: [GAUGE]\n");
}
printf("min_value: [%g]\n", cdb->header->min_value);
printf("max_value: [%g]\n", cdb->header->max_value);
printf("max_records: [%"PRIu64"]\n", cdb->header->max_records);
printf("num_records: [%"PRIu64"]\n", cdb->header->num_records);
printf("start_record: [%"PRIu64"]\n", cdb->header->start_record);
}
int cdb_write_records(cdb_t *cdb, cdb_record_t *records, uint64_t len, uint64_t *num_recs) {
/* read old header if it exists.
write a header out, since the db may not have existed.
*/
uint64_t i = 0;
uint64_t j = 0;
off_t offset = 0;
*num_recs = 0;
if (cdb_read_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
if (_cdb_is_writable(cdb) == false) {
return CDB_ERDONLY;
}
if (cdb->header->max_records <= 0) {
return CDB_EINVMAX;
}
/* Logic for writes:
cdb is 5 records.
try to write 7 records
len = 7
len + 0 > 5
j = (7 + 0) - 5
j = 2
i = 7 - 2
i = 5
need to write j records at offset: HEADER_SIZE + (cdb->header->start_record * RECORD_SIZE)
index into records is i
need to write i records at offset: HEADER_SIZE + (cdb->header->num_records * RECORD_SIZE)
index into records is 0;
*/
/* Calculate our indicies into the records array. */
if (len + cdb->header->num_records >= cdb->header->max_records) {
j = (len + cdb->header->num_records) - cdb->header->max_records;
i = (len - j);
} else {
i = len;
}
/* If we need to wrap around */
if (j > 0) {
offset = HEADER_SIZE + (cdb->header->start_record * RECORD_SIZE);
cdb->header->start_record += j;
cdb->header->start_record %= cdb->header->max_records;
if (pwrite(cdb->fd, &records[i], (RECORD_SIZE * j), offset) != (RECORD_SIZE * j)) {
return cdb_error();
}
cdb->synced = false;
/* start_record is no longer 0, so update the header */
if (cdb_write_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
}
/* Normal case */
offset = HEADER_SIZE + (cdb->header->num_records * RECORD_SIZE);
cdb->header->num_records += i;
if (pwrite(cdb->fd, &records[0], (RECORD_SIZE * i), offset) != (RECORD_SIZE * i)) {
return cdb_error();
}
*num_recs += len;
#ifdef DEBUG
printf("write_records: wrote [%"PRIu64"] records\n", *num_recs);
#endif
return CDB_SUCCESS;
}
bool cdb_write_record(cdb_t *cdb, cdb_time_t time, double value) {
cdb_record_t record[RECORD_SIZE];
uint64_t num_recs = 0;
record->time = time;
record->value = value;
if (cdb_write_records(cdb, record, 1, &num_recs) != CDB_SUCCESS) {
return false;
}
return true;
}
int cdb_update_records(cdb_t *cdb, cdb_record_t *records, uint64_t len, uint64_t *num_recs) {
int ret = CDB_SUCCESS;
*num_recs = 0;
uint64_t i = 0;
if (cdb_read_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
if (_cdb_is_writable(cdb) == false) {
return CDB_ERDONLY;
}
#ifdef DEBUG
printf("in update_records with [%"PRIu64"] num_recs\n", cdb->header->num_records);
#endif
for (i = 0; i < len; i++) {
cdb_time_t time = records[i].time;
cdb_time_t rtime;
uint64_t lrec;
lrec = _logical_record_for_time(cdb, time, 0, 0);
if (lrec >= 1) {
lrec -= 1;
/* DRK things like this are extremely confusing. some logical
functions are zero based? some are one? or you're trying to back up? */
}
rtime = _time_for_logical_record(cdb, lrec);
while (rtime < time && lrec < cdb->header->num_records - 1) {
/* DRK is this true? or is the condition (lrec - start_lrec) <
num_recs -- seems you can't wrap here (i.e. what if the initial
lrec was num_recs - 1) */
lrec += 1;
rtime = _time_for_logical_record(cdb, lrec);
}
#ifdef DEBUG
printf("update_records: value: lrec [%"PRIu64"] time [%d] rtime [%d]\n", lrec, (int)time, (int)rtime);
#endif
while (time == rtime && lrec < cdb->header->num_records - 1) {
_seek_to_logical_record(cdb, lrec);
if (write(cdb->fd, &records[0], RECORD_SIZE) != RECORD_SIZE) {
ret = cdb_error();
break;
}
lrec += 1;
rtime = _time_for_logical_record(cdb, lrec);
}
}
if (ret == CDB_SUCCESS) {
if (i > 0) {
cdb->synced = false;
*num_recs = i;
}
if (cdb_write_header(cdb) != CDB_SUCCESS) {
ret = cdb_error();
}
}
return ret;
}
bool cdb_update_record(cdb_t *cdb, cdb_time_t time, double value) {
cdb_record_t record[RECORD_SIZE];
uint64_t num_recs = 0;
record->time = time;
record->value = value;
if (cdb_update_records(cdb, record, 1, &num_recs) != 0) {
return false;
}
return true;
}
int cdb_discard_records_in_time_range(cdb_t *cdb, cdb_request_t *request, uint64_t *num_recs) {
uint64_t i = 0;
int64_t lrec;
off_t offset = RECORD_SIZE;
*num_recs = 0;
if (cdb_read_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
if (_cdb_is_writable(cdb) == false) {
return CDB_ERDONLY;
}
lrec = _logical_record_for_time(cdb, request->start, 0, 0);
if (lrec >= 1) {
lrec -= 1;
}
for (i = lrec; i < cdb->header->num_records; i++) {
cdb_time_t rtime = _time_for_logical_record(cdb, i);
if (rtime >= request->start && rtime <= request->end) {
cdb_record_t record[RECORD_SIZE];
record->time = rtime;
record->value = CDB_NAN;
if (pwrite(cdb->fd, &record, RECORD_SIZE, offset) != RECORD_SIZE) {
return cdb_error();
}
*num_recs += 1;
}
}
if (*num_recs > 0) {
cdb->synced = false;
}
if (cdb_write_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
return CDB_SUCCESS;
}
static int _compute_scale_factor_and_num_records(cdb_t *cdb, int64_t *num_records, int32_t *factor) {
if (cdb->header->type == CDB_TYPE_COUNTER) {
if (*num_records != 0) {
if (*num_records > 0) {
*num_records += 1;
} else {
*num_records -= 1;
}
}
}
if (strlen(cdb->header->units) > 0) {
int32_t multiplier = 1;
char *frequency;
if ((frequency = calloc(strlen(cdb->header->units), sizeof(char))) == NULL) {
return CDB_ENOMEM;
}
if ((sscanf(cdb->header->units, "per %d %s", &multiplier, frequency) == 2) ||
(sscanf(cdb->header->units, "per %s", frequency) == 1) ||
(sscanf(cdb->header->units, "%*s per %s", frequency) == 1)) {
if (strcmp(frequency, "min") == 0) {
*factor = 60;
} else if (strcmp(frequency, "hour") == 0) {
*factor = 60 * 60;
} else if (strcmp(frequency, "sec") == 0 || strcmp(frequency, "second") == 0) {
*factor = 1;
} else if (strcmp(frequency, "day") == 0) {
*factor = 60 * 60 * 24;
} else if (strcmp(frequency, "week") == 0) {
*factor = 60 * 60 * 24 * 7;
} else if (strcmp(frequency, "month") == 0) {
*factor = 60 * 60 * 24 * 30;
} else if (strcmp(frequency, "quarter") == 0) {
*factor = 60 * 60 * 24 * 90;
} else if (strcmp(frequency, "year") == 0) {
*factor = 60 * 60 * 24 * 365;
}
if (*factor != 0) {
*factor *= multiplier;
}
}
free(frequency);
}
return CDB_SUCCESS;
}
/* Statistics code
* Make only one call to reading for a particular time range and compute all our stats
*/
void _compute_statistics(cdb_range_t *range, uint64_t *num_recs, cdb_record_t *records) {
uint64_t i = 0;
uint64_t valid = 0;
double sum = 0.0;
double *values = calloc(*num_recs, sizeof(double));
for (i = 0; i < *num_recs; i++) {
if (!isnan(records[i].value)) {
sum += values[valid] = records[i].value;
valid++;
}
}
range->num_recs = valid;
range->mean = gsl_stats_mean(values, 1, valid);
range->max = gsl_stats_max(values, 1, valid);
range->min = gsl_stats_min(values, 1, valid);
range->sum = sum;
range->stddev = gsl_stats_sd(values, 1, valid);
range->absdev = gsl_stats_absdev(values, 1, valid);
/* The rest need sorted data */
gsl_sort(values, 1, valid);
range->median = gsl_stats_median_from_sorted_data(values, 1, valid);
range->pct95th = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.95);
range->pct75th = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.75);
range->pct50th = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.50);
range->pct25th = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.25);
/* MAD must come last because it alters the values array
* http://en.wikipedia.org/wiki/Median_absolute_deviation */
for (i = 0; i < valid; i++) {
values[i] = fabs(values[i] - range->median);
if (values[i] < 0.0) {
values[i] *= -1.0;
}
}
/* Final sort is required MAD */
gsl_sort(values, 1, valid);
range->mad = gsl_stats_median_from_sorted_data(values, 1, valid);
free(values);
}
double cdb_get_statistic(cdb_range_t *range, cdb_statistics_enum_t type) {
switch (type) {
case CDB_MEDIAN:
return range->median;
case CDB_MAD:
return range->mad;
case CDB_95TH:
return range->pct95th;
case CDB_75TH:
return range->pct75th;
case CDB_50TH:
return range->pct50th;
case CDB_25TH:
return range->pct25th;
case CDB_MEAN:
return range->mean;
case CDB_SUM:
return range->sum;
case CDB_MAX:
return range->max;
case CDB_MIN:
return range->min;
case CDB_STDDEV:
return range->stddev;
case CDB_ABSDEV:
return range->absdev;
default:
fprintf(stderr, "aggregate_using_function_for_records() function: [%d] not supported\n", type);
return CDB_FAILURE;
}
}
static int _cdb_read_records(cdb_t *cdb, cdb_request_t *request, uint64_t *num_recs, cdb_record_t **records) {
int64_t first_requested_logical_record;
int64_t last_requested_logical_record;
uint64_t last_requested_physical_record;
int64_t seek_physical_record;
cdb_record_t *buffer = NULL;
if (cdb_read_header(cdb) != CDB_SUCCESS) {
return cdb_error();
}
if (request->start != 0 && request->end != 0 && request->end < request->start) {
return CDB_ETMRANGE;
}
if (cdb->header == NULL || cdb->synced == false) {
return CDB_ESANITY;
}
/* bail out if there are no records */
if (cdb->header->num_records <= 0) {
return CDB_ENORECS;
}
/*
get the number of requested records:
-ve indicates n records from the beginning
+ve indicates n records off of the end.
0 or undef means the whole thing.
switch the meaning of -ve/+ve to be more array like
*/
if (request->count != 0) {
request->count = -request->count;
}
#ifdef DEBUG
printf("read_records start: [%ld]\n", request->start);
printf("read_records end: [%ld]\n", request->end);
printf("read_records num_requested: [%"PRIu64"]\n", request->count);
#endif
if (request->count != 0 && request->count < 0 && request->start == 0) {
/* if reading only few records from the end, just set -ve offset to seek to */
first_requested_logical_record = request->count;
} else {
/* compute which record to start reading from the beginning, based on start time specified. */
first_requested_logical_record = _logical_record_for_time(cdb, request->start, 0, 0);
}
/* if end is not defined, read all the records or only read uptill the specified record. */
if (request->end == 0) {
last_requested_logical_record = cdb->header->num_records - 1;
} else {
last_requested_logical_record = _logical_record_for_time(cdb, request->end, 0, 0);
/* this can return something > end, check for that */
if (_time_for_logical_record(cdb, last_requested_logical_record) > request->end) {
last_requested_logical_record -= 1;
}
}
last_requested_physical_record = (last_requested_logical_record + cdb->header->start_record) % cdb->header->num_records;
/* After _seek_to_logical_record(), we're at the offset to read from. */
seek_physical_record = _seek_to_logical_record(cdb, first_requested_logical_record);
if (last_requested_physical_record >= seek_physical_record) {
uint64_t nrec = (last_requested_physical_record - seek_physical_record + 1);
uint64_t rlen = RECORD_SIZE * nrec;
if ((buffer = calloc(1, rlen)) == NULL) {
free(buffer);
return CDB_ENOMEM;
}
if (read(cdb->fd, buffer, rlen) != rlen) {
free(buffer);
return cdb_error();
}
*num_recs = nrec;
} else {
/* We've wrapped around the end of the file */
uint64_t nrec1 = (cdb->header->num_records - seek_physical_record);
uint64_t nrec2 = (last_requested_physical_record + 1);
uint64_t rlen1 = RECORD_SIZE * nrec1;
uint64_t rlen2 = RECORD_SIZE * nrec2;
if ((buffer = calloc(1, rlen1 + rlen2)) == NULL) {
free(buffer);
return CDB_ENOMEM;
}
/* Read at the offset set by _seek_to_logical_record() */
if (read(cdb->fd, buffer, rlen1) != rlen1) {
free(buffer);
return cdb_error();
}
/* And then the wrap around portion past the header. */
if (pread(cdb->fd, &buffer[nrec1], rlen2, HEADER_SIZE) != rlen2) {
free(buffer);
return cdb_error();
}
*num_recs = nrec1 + nrec2;
}
/* Deal with cooking the output */
if (request->cooked) {
bool check_min_max = true;
int32_t factor = 0;
uint64_t i = 0;
uint64_t cooked_recs = 0;
double prev_value = 0.0;
cdb_time_t prev_date = 0;
cdb_record_t *crecords;
if ((crecords = calloc(*num_recs, RECORD_SIZE)) == NULL) {
free(crecords);
free(buffer);
return CDB_ENOMEM;
}
if (_compute_scale_factor_and_num_records(cdb, &request->count, &factor)) {
free(crecords);
free(buffer);
return cdb_error();
}
if (cdb->header->min_value == 0 && cdb->header->max_value == 0) {
check_min_max = false;
}
for (i = 0; i < *num_recs; i++) {
cdb_time_t date = buffer[i].time;
double value = buffer[i].value;
if (cdb->header->type == CDB_TYPE_COUNTER) {
double new_value = value;
value = CDB_NAN;
if (!isnan(prev_value) && !isnan(new_value)) {
double val_delta = new_value - prev_value;
if (val_delta >= 0) {
value = val_delta;
}
}
prev_value = new_value;
}
if (factor != 0 && cdb->header->type == CDB_TYPE_COUNTER) {
/* Skip the first entry, since it's absolute and is needed
* to calculate the second */
if (prev_date == 0) {
prev_date = date;
continue;
}
cdb_time_t time_delta = date - prev_date;
if (time_delta > 0 && !isnan(value)) {
value = factor * (value / time_delta);
}
prev_date = date;
}
/* Check for min/max boundaries */
/* Should this be done on write instead of read? */
if (check_min_max && !isnan(value)) {
if (value > cdb->header->max_value || value < cdb->header->min_value) {
value = CDB_NAN;
}
}
/* Copy the munged data to our new array, since we might skip
* elements. Also keep in mind mmap for the future */
crecords[cooked_recs].time = date;
crecords[cooked_recs].value = value;
cooked_recs += 1;
}
/* Now swap our cooked records for the buffer, so we can slice it as needed. */
free(buffer);
buffer = crecords;
*num_recs = cooked_recs;
}
/* If we've been requested to average the records & timestamps */
if (request->step > 1) {
cdb_record_t *arecords;
uint32_t step = request->step;
uint64_t step_recs = 0;
uint64_t leftover = (*num_recs % step);
uint64_t walkend = (*num_recs - leftover);
uint64_t i = 0;
if ((arecords = calloc(((*num_recs / step) + leftover), RECORD_SIZE)) == NULL) {
free(arecords);
free(buffer);
return CDB_ENOMEM;
}
/* Walk our list of cooked records, jumping ahead by the given step.
For each set of records within that step, we want to get the average
for those records and place them into a new array.
*/
for (i = 0; i < walkend; i += step) {
uint64_t j = 0;
double xi[step];
double yi[step];
for (j = 0; j < step; j++) {
/* No NaNs on average - they cause bogus graphs. Is there a
* better value than 0 to use here? */
if (isnan(buffer[i+j].value)) {
buffer[i+j].value = 0;
}
xi[j] = (double)buffer[i+j].time;
yi[j] = buffer[i+j].value;
}
arecords[step_recs].time = (cdb_time_t)gsl_stats_mean(xi, 1, step);
arecords[step_recs].value = gsl_stats_mean(yi, 1, step);
step_recs += 1;
}
/* Now collect from the last step point to the end & average. */
if (leftover > 0) {
uint64_t leftover_start = *num_recs - leftover;
uint64_t j = 0;
double xi[leftover];
double yi[leftover];
for (i = leftover_start; i < *num_recs; i++) {
/* No NaNs on average - they cause bogus graphs. Is there a
* better value than 0 to use here? */
if (isnan(buffer[i].value)) {
buffer[i].value = 0;
}
xi[j] = (double)buffer[i].time;
yi[j] = buffer[i].value;
j++;
}
arecords[step_recs].time = (cdb_time_t)gsl_stats_mean(xi, 1, j);
arecords[step_recs].value = gsl_stats_mean(yi, 1, j);
step_recs += 1;
}
free(buffer);
buffer = arecords;
*num_recs = step_recs;
}
/* now pull out the number of requested records if asked */
if (request->count != 0 && *num_recs >= abs(request->count)) {
uint64_t start_index = 0;
if (request->count <= 0) {
start_index = *num_recs - abs(request->count);
}
*num_recs = abs(request->count);
if ((*records = calloc(*num_recs, RECORD_SIZE)) == NULL) {
free(buffer);
return CDB_ENOMEM;
}
memcpy(*records, &buffer[start_index], RECORD_SIZE * *num_recs);
free(buffer);
} else {
*records = buffer;
}
return CDB_SUCCESS;
}
int cdb_read_records(cdb_t *cdb, cdb_request_t *request,
uint64_t *num_recs, cdb_record_t **records, cdb_range_t *range) {
int ret = CDB_SUCCESS;
ret = _cdb_read_records(cdb, request, num_recs, records);
if (ret == CDB_SUCCESS) {
if (*num_recs > 0) {
range->start_time = request->start;
range->end_time = request->end;
_compute_statistics(range, num_recs, *records);
}
}
return ret;
}
void cdb_print_records(cdb_t *cdb, cdb_request_t *request, FILE *fh, const char *date_format) {
uint64_t i = 0;
uint64_t num_recs = 0;
cdb_record_t *records = NULL;
if (_cdb_read_records(cdb, request, &num_recs, &records) == CDB_SUCCESS) {
for (i = 0; i < num_recs; i++) {
_print_record(fh, records[i].time, records[i].value, date_format);
}
}
free(records);
}
void cdb_print(cdb_t *cdb) {
const char *date_format = "%Y-%m-%d %H:%M:%S";
cdb_request_t request;
request.start = 0;
request.end = 0;
request.count = 0;
request.step = 0;
request.cooked = false;
printf("============== Header ================\n");
if (cdb_read_header(cdb) == CDB_SUCCESS) {
cdb_print_header(cdb);
}
if (cdb->header->type == CDB_TYPE_COUNTER) {
printf("============= Raw Counter Records =============\n");
cdb_print_records(cdb, &request, stdout, date_format);
printf("============== End Raw Counter Records ==============\n");
printf("============== Cooked Records ================\n");
} else {
printf("============== Records ================\n");
}
request.cooked = true;
cdb_print_records(cdb, &request, stdout, date_format);
printf("============== End ================\n");
}
/* Take in an array of cdbs */
int cdb_read_aggregate_records(cdb_t **cdbs, int num_cdbs, cdb_request_t *request,
uint64_t *driver_num_recs, cdb_record_t **records, cdb_range_t *range) {
uint64_t i = 0;
int ret = CDB_SUCCESS;
cdb_record_t *driver_records = NULL;
*driver_num_recs = 0;
if (cdbs[0] == NULL) {
return CDB_ESANITY;
}
/* The first cdb is the driver */
ret = _cdb_read_records(cdbs[0], request, driver_num_recs, &driver_records);
if (ret != CDB_SUCCESS) {
fprintf(stderr, "Bailed on: %s\n", cdbs[0]->filename);
free(driver_records);
return ret;
}
if ((*records = calloc(*driver_num_recs, RECORD_SIZE)) == NULL) {
free(driver_records);
return CDB_ENOMEM;
}
if (*driver_num_recs <= 1) {
free(driver_records);
return CDB_EINTERPD;
}
double *driver_x_values = calloc(*driver_num_recs, sizeof(double));
double *driver_y_values = calloc(*driver_num_recs, sizeof(double));
double *follower_x_values = calloc(*driver_num_recs, sizeof(double));
double *follower_y_values = calloc(*driver_num_recs, sizeof(double));
for (i = 0; i < *driver_num_recs; i++) {
(*records)[i].time = driver_x_values[i] = driver_records[i].time;
(*records)[i].value = driver_y_values[i] = driver_records[i].value;
}
/* initialize and allocate the gsl objects */
gsl_interp_accel *accel = gsl_interp_accel_alloc();
gsl_interp *interp = gsl_interp_alloc(gsl_interp_linear, *driver_num_recs);
/* Allows 0.0 to be returned as a valid yi */
gsl_set_error_handler_off();
gsl_interp_init(interp, driver_x_values, driver_y_values, *driver_num_recs);
for (i = 1; i < num_cdbs; i++) {
uint64_t j = 0;
uint64_t follower_num_recs = 0;
cdb_record_t *follower_records = NULL;
ret = _cdb_read_records(cdbs[i], request, &follower_num_recs, &follower_records);
/* Just bail, free all allocations below and let the error bubble up */
if (ret == CDB_SUCCESS && follower_num_recs != 0) {
for (j = 0; j < *driver_num_recs; j++) {
/* Check for out of bounds */
if (j >= follower_num_recs) {
break;
}
follower_x_values[j] = follower_records[j].time;
follower_y_values[j] = follower_records[j].value;
}
for (j = 0; j < *driver_num_recs; j++) {
double yi = gsl_interp_eval(interp, follower_x_values, follower_y_values, driver_x_values[j], accel);
if (isnormal(yi)) {
(*records)[j].value += yi;
}
}
}
free(follower_records);
if (ret != CDB_SUCCESS) {
break;
}
}
if (ret == CDB_SUCCESS && *driver_num_recs > 0) {
/* Compute all the statistics for this range */
range->start_time = request->start;
range->end_time = request->end;
_compute_statistics(range, driver_num_recs, *records);
}
free(driver_x_values);
free(driver_y_values);
free(follower_x_values);
free(follower_y_values);
gsl_interp_free(interp);
gsl_interp_accel_free(accel);
free(driver_records);
return ret;
}
void cdb_print_aggregate_records(cdb_t **cdbs, int32_t num_cdbs, cdb_request_t *request, FILE *fh, const char *date_format) {
uint64_t i = 0;
uint64_t num_recs = 0;
cdb_record_t *records = NULL;
cdb_range_t *range = calloc(1, sizeof(cdb_range_t));
cdb_read_aggregate_records(cdbs, num_cdbs, request, &num_recs, &records, range);
for (i = 0; i < num_recs; i++) {
_print_record(fh, records[i].time, records[i].value, date_format);
}
free(range);
free(records);
}
void cdb_generate_header(cdb_t *cdb, char* name, char* desc, uint64_t max_records, int32_t type,
char* units, uint64_t min_value, uint64_t max_value) {
if (max_records == 0) {
max_records = CDB_DEFAULT_RECORDS;
}
if (type == 0) {
cdb->header->type = CDB_DEFAULT_DATA_TYPE;
}
if (units == NULL || (strcmp(units, "") == 0)) {
units = (char*)CDB_DEFAULT_DATA_UNIT;
}
if (desc == NULL) {
desc = (char*)"";
}
memset(cdb->header->name, 0, sizeof(cdb->header->name));
memset(cdb->header->desc, 0, sizeof(cdb->header->desc));
memset(cdb->header->units, 0, sizeof(cdb->header->units));
memset(cdb->header->version, 0, sizeof(cdb->header->version));
memset(cdb->header->token, 0, sizeof(cdb->header->token));
strncpy(cdb->header->name, name, sizeof(cdb->header->name));
strncpy(cdb->header->desc, desc, sizeof(cdb->header->desc));
strncpy(cdb->header->units, units, sizeof(cdb->header->units));
strncpy(cdb->header->version, CDB_VERSION, sizeof(cdb->header->version));
strncpy(cdb->header->token, CDB_TOKEN, sizeof(cdb->header->token));
cdb->header->type = type;
cdb->header->max_records = max_records;
cdb->header->min_value = min_value;
cdb->header->max_value = max_value;
cdb->header->num_records = 0;
cdb->header->start_record = 0;
}
cdb_t* cdb_new(void) {
cdb_t *cdb = calloc(1, sizeof(cdb_t));
cdb->header = calloc(1, HEADER_SIZE);
cdb->fd = -1;
cdb->synced = false;
cdb->flags = -1;
cdb->mode = -1;
return cdb;
}
cdb_request_t cdb_new_request(void) {
cdb_request_t request;
memset (&request, 0, sizeof (request));
request.start = 0;
request.end = 0;
request.count = 0;
request.cooked = true;
request.step = 0;
return request;
}
int cdb_open(cdb_t *cdb) {
if (cdb->fd >= 0) {
return CDB_SUCCESS;
}
/* Default flags if none were set */
if (cdb->flags == -1) {
cdb->flags = O_RDONLY|O_BINARY;
}
/* A cdb can't be write only - we need to read the header */
if (cdb->flags & O_WRONLY) {
cdb->flags = O_RDWR;
}
if (cdb->mode == -1) {
cdb->mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
}
cdb->fd = open(cdb->filename, cdb->flags, cdb->mode);
if (cdb->fd < 0) {
return cdb_error();
}
return CDB_SUCCESS;
}
int cdb_close(cdb_t *cdb) {
if (cdb != NULL) {
if (cdb->fd > 0) {
if (close(cdb->fd) != 0) {
return cdb_error();
}
cdb->fd = -1;
}
}
return CDB_SUCCESS;
}
int cdb_free(cdb_t *cdb) {
int ret = CDB_SUCCESS;
if (cdb != NULL) {
if (cdb->header != NULL) {
ret = cdb_close(cdb);
free(cdb->header);
cdb->header = NULL;
}
free(cdb);
cdb = NULL;
}
return ret;
}
/* -*- Mode: C; tab-width: 4 -*- */
/* vim: set tabstop=4 expandtab shiftwidth=4: */
| {
"alphanum_fraction": 0.5749651783,
"avg_line_length": 27.8761904762,
"ext": "c",
"hexsha": "fba1152dd4938c8f72aea83aea7fba0d1f84902e",
"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": "8191d65e18324e5c2e7481de8ed3281ab197d205",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dsully/circulardb",
"max_forks_repo_path": "src/circulardb.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "8191d65e18324e5c2e7481de8ed3281ab197d205",
"max_issues_repo_issues_event_max_datetime": "2020-05-09T08:28:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-09T08:28:27.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dsully/circulardb",
"max_issues_repo_path": "src/circulardb.c",
"max_line_length": 132,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "8191d65e18324e5c2e7481de8ed3281ab197d205",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dsully/circulardb",
"max_stars_repo_path": "src/circulardb.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-25T03:35:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-24T12:59:03.000Z",
"num_tokens": 10329,
"size": 38051
} |
/*
* Gsl_blas_dgemm_matrix_view: test gsl_blas_dgemm (matrix . matrix)
*
* Copyright (c) 2012 JΓ©rΓ©mie Decock
*
* Required: GSL library (libgsl0-dev)
* Usage: gcc gsl_blas_dgemm_matrix_view.c -lgsl -lgslcblas -lm
* or: gcc gsl_blas_dgemm_matrix_view.c $(pkg-config --libs gsl)
*/
#include <stdio.h>
#include <gsl/gsl_blas.h>
int main (void)
{
double a[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23 };
double b[] = { 1011, 1012,
1021, 1022,
1031, 1032 };
double c[] = { 0.00, 0.00,
0.00, 0.00 };
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 3);
gsl_matrix_view B = gsl_matrix_view_array(b, 3, 2);
gsl_matrix_view C = gsl_matrix_view_array(c, 2, 2);
/* Compute C = A B */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,
1.0, &A.matrix, &B.matrix,
0.0, &C.matrix);
printf("[ %g, %g\n", c[0], c[1]);
printf(" %g, %g ]\n", c[2], c[3]);
return 0;
}
| {
"alphanum_fraction": 0.5432220039,
"avg_line_length": 24.2380952381,
"ext": "c",
"hexsha": "119d4ec13710ec5ea0a836e5365e6dc7d59fce5d",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z",
"max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jeremiedecock/snippets",
"max_forks_repo_path": "c/gsl/blas/gsl_blas_dgemm_matrix_view.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jeremiedecock/snippets",
"max_issues_repo_path": "c/gsl/blas/gsl_blas_dgemm_matrix_view.c",
"max_line_length": 68,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jeremiedecock/snippets",
"max_stars_repo_path": "c/gsl/blas/gsl_blas_dgemm_matrix_view.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z",
"num_tokens": 366,
"size": 1018
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_chebyshev.h>
double f1(double x, void *p) {
(void) (p); /* avoid unused parameter warning */
return exp(pow(x, 2));
}
double f2(double x, void *p) {
(void) (p); /* avoid unused parameter warning */
return fabs(x + pow(x, 3));
}
double f3(double x, void *p) {
(void) (p); /* avoid unused parameter warning */
return x <= 0 ? -1 : 1;
}
double (*f[])(double, void *) = {f1, f2, f3};
char *a[] = {"pierwsze1.dat", "pierwsze2.dat", "pierwsze3.dat"};
int main(void) {
int i, n = 10000;
gsl_cheb_series *cs = gsl_cheb_alloc(40);
gsl_function F;
FILE *file;
for (int j = 0; j < 3; j++) {
file = fopen(a[j], "w");
F.function = f[j];
F.params = 0;
gsl_cheb_init(cs, &F, -1.0, 1.0);
for (i = -n; i < n; i++) {
double x = i / (double) n;
double r10 = gsl_cheb_eval_n(cs, 10, x);
double r40 = gsl_cheb_eval(cs, x);
fprintf(file, "%g %g %g %g\n",
x, GSL_FN_EVAL (&F, x), r10, r40);
}
fclose(file);
}
gsl_cheb_free(cs);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5204678363,
"avg_line_length": 25.4680851064,
"ext": "c",
"hexsha": "bb15481ccccb5625f0c419da41614bd0481e87ff",
"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/pierwsze.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/pierwsze.c",
"max_line_length": 64,
"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/pierwsze.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 397,
"size": 1197
} |
/*
* Copyright 2014 Marc Normandin
*
* 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.
*/
/*
* pso.h
*
* Created on: Jun 30, 2013
* Author: marc
*/
#ifndef PSO_H_
#define PSO_H_
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <cstdlib>
#include <gsl/gsl_rng.h>
#include <limits>
#include <fstream>
#include <cassert>
#include "rng.h"
#include "dim.h"
#include "particle.h"
template<class FitnessFunction>
class PSO
{
public:
// This routine is used by the PSO unit test
PSO(const unsigned int numParticles, const std::vector<Dim>& dim,
const gslseed_t seed, FitnessFunction& fitnessFunction, const unsigned int maxIterations)
: mNumParticles(numParticles), mGBest(dim), mDim(dim), mRng(seed), mFitnessFunction(fitnessFunction),
mMaxIterations(maxIterations)
{
mParticles.reserve(mNumParticles);
}
unsigned int getNumParticles() const
{
return mNumParticles;
}
const Particle& iterate()
{
createRandomParticles();
unsigned int numIterations = 0;
std::vector<double> particleFitnesses(mParticles.size());
do
{
// Evaluate the fitness/objective function
mFitnessFunction(mParticles, &particleFitnesses);
//For each particle
for (unsigned int i = 0; i < mParticles.size(); i++)
{
// Calculate fitness value
const prob_t fitness = particleFitnesses[i]; //
// If the fitness value is better than the best fitness value (pBest) in history
// set current value as the new pBest
mParticles[i].updateFitness( fitness );
}
// Choose the particle with the best fitness value of all the particles as the gBest
std::vector<Particle>::const_iterator best = std::max_element(mParticles.begin(), mParticles.end());
mGBest = Particle( best->getBestPosition(), best->getBestFitness() );
// Update the inertia weight
const double inertiaWeight = computeInertiaWeight(numIterations, mMaxIterations);
// For each particle
for (unsigned int i = 0; i < mParticles.size(); i++)
{
mParticles[i].updatePosition( mGBest, mDim, mCognitiveWeight, mSocialWeight, mRng, inertiaWeight );
}
numIterations++;
}
while(numIterations < mMaxIterations);
return mGBest;
}
protected:
PSO(const PSO&);
void operator=(const PSO&);
void createRandomParticles() {
mParticles.clear(); // Remove previous particles in the container
// For each particle
for (unsigned int i = 0; i < mNumParticles; i++)
{
std::vector<dim_t> pos;
// For each dimension
for (unsigned int d = 0; d < mDim.size(); d++)
{
dim_t posd = mRng.uniform( mDim[d].min(), mDim[d].max() );
pos.push_back(posd);
}
// Add the particle to the collection
mParticles.push_back( Particle(pos) );
}
}
// Compute inertia. This is based on equation 4.1 from:
// http://www.hindawi.com/journals/ddns/2010/462145/
double computeInertiaWeight(const unsigned int iteration, const unsigned int maxInterations) const
{
// Note. We add +1 because our iterations go from 0 to max-1.
double inertiaWeight = (mOmega1 - mOmega2) * ( (maxInterations - (iteration+1.0)) / (1.0 * (iteration+1.0) ) ) + mOmega2;
return inertiaWeight;
}
private:
unsigned int mNumParticles;
std::vector<Particle> mParticles; // Particle positions
Particle mGBest;
std::vector<Dim> mDim;
// These values control how random the particle velocities are
static const double mCognitiveWeight;
static const double mSocialWeight;
// These values control the rate of convergence
static const double mOmega1;
static const double mOmega2;
RandomNumberGenerator mRng;
FitnessFunction& mFitnessFunction;
unsigned int mMaxIterations;
};
#endif /* PSO_H_ */
| {
"alphanum_fraction": 0.6189099917,
"avg_line_length": 30.8535031847,
"ext": "h",
"hexsha": "056e4cb204794070a0df4db8c1743e873c50d4e0",
"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": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_forks_repo_path": "pso.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T20:48:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-27T05:48:44.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_issues_repo_path": "pso.h",
"max_line_length": 129,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_stars_repo_path": "pso.h",
"max_stars_repo_stars_event_max_datetime": "2018-04-09T21:25:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-28T05:27:28.000Z",
"num_tokens": 1106,
"size": 4844
} |
/***
* Copyright 2019 The Katla Authors
*
* 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 KATLA_PIPE_H
#define KATLA_PIPE_H
#include "katla/core/core.h"
#include <gsl/span>
#include <optional>
namespace outcome = OUTCOME_V2_NAMESPACE;
namespace katla {
class PosixPipe {
public:
PosixPipe();
~PosixPipe();
outcome::result<void> open();
outcome::result<ssize_t> read(gsl::span<std::byte>& buffer);
outcome::result<ssize_t> write(gsl::span<std::byte>& buffer);
outcome::result<void> redirectToRead(int fd_src);
outcome::result<void> redirectToWrite(int fd_src);
outcome::result<void> close();
outcome::result<void> closeRead();
outcome::result<void> closeWrite();
private:
int _fd[2];
};
}
#endif // KATLA_PIPE_H
| {
"alphanum_fraction": 0.7104037267,
"avg_line_length": 24.3018867925,
"ext": "h",
"hexsha": "b6f7d09419aa4d51b1b84da9febf33c60326312b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "plok/katla",
"max_forks_repo_path": "core/posix-pipe.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "plok/katla",
"max_issues_repo_path": "core/posix-pipe.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "plok/katla",
"max_stars_repo_path": "core/posix-pipe.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 313,
"size": 1288
} |
/**
* File: scaleback_utils.c
* Subroutine for the WFC3 background scaling
*
*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sort.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spc_FITScards.h"
#include "spce_sect.h"
#include "spce_fitting.h"
#include "spce_is_in.h"
#include "spc_back.h"
#include "spce_pathlength.h"
#include "trfit_utils.h"
#include "nicback_utils.h"
#include "scaleback_utils.h"
/**
* Function: fit_to_FITScards
* Fills the results of the fitting into a set of fits cards.
*
* Parameters:
* @param bck_vals - vector with the fit results
* @param npixels - dimension of all images
*
* Returns:
* @return cards - the list of fits header cards
*/
FITScards *fit_to_FITScards(const gsl_vector* bck_vals, const px_point npixels)
{
char templt[FLEN_CARD];
int i=0,keytype, f_status=0;
int npix_tot;
FITScards *cards;
// allocate the cards
cards = allocate_FITScards(7);
// compute the number of pixels
npix_tot = npixels.x * npixels.y;
i=0;
sprintf(templt,"SCALVAL = %e / computed scale value", gsl_vector_get(bck_vals, 0));
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"SCALERR = %e / error for scale value", gsl_vector_get(bck_vals, 1));
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"NPIXINI = %e / initial fill value", gsl_vector_get(bck_vals, 2));
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"NPIXFIN = %e / final fill value", gsl_vector_get(bck_vals, 3));
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"FRACINI = %e / initial fill value", gsl_vector_get(bck_vals, 2) / (float)npix_tot);
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"FRACFIN = %e / final fill value", gsl_vector_get(bck_vals, 3) / (float)npix_tot);
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
sprintf(templt,"NITER = %d / number of iterations", (int)gsl_vector_get(bck_vals, 4));
fits_parse_template (templt, cards->cards[i++], &keytype, &f_status);
// return the filled cards
return cards;
}
/**
* Function: make_scale_back
* Loads the various image data inputs and performs a fit using a kappa-sigma
* clipping iteration. Then a scaled version of one of the input images
* is produced and written to disk. Optionally, an ASCII list with the
* pixel values before the fitting is produced.
*
* Parameters:
* @param grism_image - full pathname to the grism image
* @param grism_mask - full pathname to the mask image
* @param conf_file - full pathname to the configuration file
* @param scale_image - full pathname to the scaling (=master sky) image
* @param bck_image - full pathname to the scaled (=background) image
* @param plist_name - full pathname to the pixel list
* @param scale_to_master - integer/boolean to specify what should be scaled as output
* @param make_plis - integer/boolean to request a pixel list as output
*
* Returns:
* @return -
*/
void
make_scale_back(char grism_image[], const char grism_mask[], char conf_file[],
const char scale_image[], char bck_image[], const char plist_name[],
const int scale_to_master, const int make_plis)
{
px_point npixels;
gsl_matrix *gr_img;
gsl_matrix *gr_dqval;
gsl_matrix *gr_mask;
gsl_matrix *sc_img;
gsl_matrix *bck_img;
gsl_vector *bck_vals;
fitbck_data *fbck_data;
//int f_status=0;
FITScards *cards;
aperture_conf *conf;
char ID[MAXCHAR];
// fix the extension name
sprintf (ID, "BCK");
// read the configuration file
// determine all extensions
conf = get_aperture_descriptor(conf_file);
get_extension_numbers(grism_image, conf, conf->optkey1, conf->optval1);
// load the scale image
fprintf(stdout,"Loading DATA from: %s...", scale_image);
sc_img = FITSimage_to_gsl(scale_image, 1, 1);
fprintf(stdout,". Done.\n");
// load the grism image
fprintf(stdout,"Loading DATA from: %s...", grism_image);
gr_img = FITSimage_to_gsl(grism_image, conf->science_numext, 1);
fprintf(stdout,". Done.\n");
if (conf->dq_numext < 0)
{
// allocate the space for the dq-image
// set all values to 0.0
gr_dqval = gsl_matrix_alloc(gr_img->size1, gr_img->size2);
gsl_matrix_set_all (gr_dqval, 0.0);
}
else
{
// load the scale dq values
fprintf(stdout,"Loading DQ from: %s...", grism_image);
gr_dqval = FITSimage_to_gsl(grism_image, conf->dq_numext, 1);
fprintf(stdout,". Done.\n");
}
// load the grism mask
fprintf(stdout,"Loading DATA from: %s...", grism_mask);
gr_mask = FITSimage_to_gsl(grism_mask, 2, 1);
fprintf(stdout,". Done.\n");
// get the number of pixels
npixels.x = sc_img->size1;
npixels.y = sc_img->size2;
// report the number of pixels
//fprintf(stdout,"Loading DATA from: %i pix\n", npixels.x * npixels.y);
// allocate memory for the fit data
fbck_data = alloc_fitbck_data(npixels.x * npixels.y);
// fill the data into the structure
if (scale_to_master)
fill_cont_data(gr_img, gr_dqval, gr_mask, sc_img, fbck_data, conf->dqmask);
else
fill_mask_data(gr_img, gr_dqval, gr_mask, sc_img, fbck_data, conf->dqmask);
// make a pixel list if desired
if (make_plis)
print_plis(fbck_data, plist_name);
// make the fit
bck_vals = make_ksig_scalefit(fbck_data);
// report the result of the fit onto the screen
fprintf(stdout, "\nScale result image %s : c0 = %f +- %f", grism_image, gsl_vector_get(bck_vals, 0), gsl_vector_get(bck_vals, 1));
fprintf(stdout, "\nInitial fill factor: %.1f%%, final: %.1f%%", 100.0 * gsl_vector_get(bck_vals, 2) / ((float)npixels.x * (float)npixels.y), 100.0 *gsl_vector_get(bck_vals, 3) / ((float)npixels.x * (float)npixels.y));
fprintf(stdout, "\nNumber of iterations: % 2i\n\n", (int)gsl_vector_get(bck_vals, 4));
if (scale_to_master)
bck_img = compute_scale_grism(gr_img, gr_dqval, gr_mask, conf->dqmask, bck_vals);
else
bck_img = compute_scale_master(sc_img, bck_vals);
// write the background image to a file
fprintf(stdout,"Writing data to: %s...", bck_image);
gsl_to_FITSimage (bck_img, bck_image, 1, ID);
cards = fit_to_FITScards(bck_vals, npixels);
put_FITS_cards(bck_image, 1, cards);
fprintf(stdout,". Done.\n");
// release memory
free_fitbck_data(fbck_data);
free_FITScards(cards);
gsl_matrix_free(sc_img);
gsl_matrix_free(gr_img);
gsl_matrix_free(gr_dqval);
gsl_matrix_free(gr_mask);
gsl_matrix_free(bck_img);
gsl_vector_free(bck_vals);
free_aperture_conf(conf);
}
/**
* Function: print_plis
* Prints the content of a pixel list structure
* to an ASCII file.
*
* Parameters:
* @param fbck_data - the list of pixel values
* @param plist_name - full pathname to the pixel list
*
* Returns:
* @return -
*/
void
print_plis(const fitbck_data *fbck_data, const char plist_name[])
{
int index=0;
char Buffer[10240];
FILE *fout;
// open the pixel list
fout = fopen(plist_name, "w");
// go over all data values
for (index=0; index < fbck_data->n_data; index++)
{
// put the values into the buffer
sprintf (Buffer, "%i %i %e %e\n",fbck_data->x_pos[index], fbck_data->y_pos[index],
fbck_data->x_values[index], fbck_data->y_values[index]);
// push the buffer to the file
fputs (Buffer, fout);
}
// close the pixel file
fclose(fout);
}
/**
* Function: compute_scale_grism
* Computes a scaled version of the input grism images, using the
* scale given as input. Pixels masked in other images are given
* a fixed value.
*
* Parameters:
* @param gr_img - the list of pixel values
* @param gr_dqval - full pathname to the pixel list
* @param gr_mask - full pathname to the pixel list
* @param bck_vals - full pathname to the pixel list
*
* Returns:
* @return bck_img - the scaled grism image
*/
gsl_matrix *
compute_scale_grism(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,
int dqmask, gsl_vector *bck_vals)
{
gsl_matrix *bck_img;
int ii, jj;
double scale=0.0;
// get the scale
scale = gsl_vector_get(bck_vals, 0);
// allocate the space for the background image
bck_img = gsl_matrix_alloc(gr_img->size1, gr_img->size2);
// go over each row
for (ii=0; ii < (int)gr_img->size1; ii++)
// go over each column
for (jj=0; jj < (int)gr_img->size2; jj++)
// compute and set the value in the background image
if (gsl_matrix_get(gr_mask, ii, jj) > 0.0 ||
(int)gsl_matrix_get(gr_dqval, ii, jj) & dqmask)
gsl_matrix_set(bck_img, ii, jj, MASK_VALUE);
else
// using the fit values only
gsl_matrix_set(bck_img, ii, jj, gsl_matrix_get(gr_img, ii, jj) * scale);
// return the background image
return bck_img;
}
/**
* Function: compute_scale_master
* Computes a scaled version of the scaling (=master sky) image,
* using the scale given as input.
*
* Parameters:
* @param sc_img - the list of pixel valuessc_img
* @param bck_vals - full pathname to the pixel list
*
* Returns:
* @return bck_img - the scaled grism image
*/
gsl_matrix *
compute_scale_master(const gsl_matrix *sc_img, const gsl_vector *bck_vals)
{
gsl_matrix *bck_img;
int ii, jj;
double scale=0.0;
// get the scale
scale = gsl_vector_get(bck_vals, 0);
// allocate the space for the background image
bck_img = gsl_matrix_alloc(sc_img->size1, sc_img->size2);
// go over each row
for (ii=0; ii < (int)sc_img->size1; ii++)
// go over each column
for (jj=0; jj < (int)sc_img->size2; jj++)
// scale the master sky
gsl_matrix_set(bck_img, ii, jj, gsl_matrix_get(sc_img, ii, jj) * scale);
// return the background image
return bck_img;
}
/**
* Function: fill_mask_data
* Fills the pixel value structure with the data for the x/y-positions,
* the grism image and the scaling image values and a weigth. dq-flagged
* pixels and masked pixel are neglected. The mask is supposed to be a background
* mask where pixel with a value < 900000 shall be neglected.
* The weights are initially all set to 1.
*
* Parameters:
* @param gr_img - the grism image array
* @param gr_dqval - the dq-value array
* @param gr_mask - the grism mask array
* @param sc_img - the scaling image array
* @param fbck_data - the pixel list structure
* @param dqmask - dq value from the configuration file
*
* Returns:
* @return -
*/
void
fill_mask_data(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,
gsl_matrix *sc_img, fitbck_data *fbck_data, int dqmask)
{
int ix=0;
int iy=0;
int index=0;
// intitialize the index for
// the fit_data structure
index = 0;
// go over all pixels
// in the grism image
for (ix=0; ix < (int)sc_img->size1; ix++)
{
for (iy=0; iy < (int)sc_img->size2; iy++)
{
// set the scale image pixel as independent variable
fbck_data->x_values[index] = gsl_matrix_get(gr_img, ix, iy);
// set the grism image pixel as dependent variable
fbck_data->y_values[index] = gsl_matrix_get(sc_img, ix, iy);;
// set the x- and y-positions
fbck_data->x_pos[index] = ix;
fbck_data->y_pos[index] = iy;
// check whether the pixel was masked out
// or is part of an object
if (gsl_matrix_get(sc_img, ix, iy) < 0.0 ||
gsl_matrix_get(gr_mask, ix, iy) < -900000.0 ||
((int)gsl_matrix_get(gr_dqval, ix, iy) & dqmask))
{
continue;
}
else
{
// give the pixel full weight
//x,y,value_back,value_grism_imag
fbck_data->e_values[index] = 1.0;
// enhance the counter
index++;
}
}
}
fbck_data->n_data = index;
fprintf(stdout, "\nNumber of pixels in structure: %i\n\n", fbck_data->n_data);
if (fbck_data->n_data < 1)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_SCALEBCK: no data left to determine the scale!\n");
}
/**
* Function: fill_cont_data
* Fills the pixel value structure with the data for the x/y-positions,
* the grism image and the scaling image values and a weigth. dq-flagged
* pixels and masked pixel are neglected. The mask is supposed to be a geometric
* contamination where pixel with a value > 0 shall be neglected.
* The weights are initially all set to 1.
*
* Parameters:
* @param gr_img - the grism image array
* @param gr_dqval - the dq-value array
* @param gr_mask - the grism mask array
* @param sc_img - the scaling image array
* @param fbck_data - the pixel list structure
*
* Returns:
* @return -
*/
void
fill_cont_data(gsl_matrix *gr_img, gsl_matrix *gr_dqval, gsl_matrix *gr_mask,
gsl_matrix *sc_img, fitbck_data *fbck_data, int dqmask)
{
int ix=0;
int iy=0;
int index=0;
// intitialize the index for
// the fit_data structure
index = 0;
// go over all pixels
// in the grism image
for (ix=0; ix < (int)sc_img->size1; ix++)
{
for (iy=0; iy < (int)sc_img->size2; iy++)
{
// set the scale image pixel as independent variable
fbck_data->x_values[index] = gsl_matrix_get(sc_img, ix, iy);
// set the grism image pixel as dependent variable
fbck_data->y_values[index] = gsl_matrix_get(gr_img, ix, iy);;
// set the x- and y-positions
fbck_data->x_pos[index] = ix;
fbck_data->y_pos[index] = iy;
// check whether the pixel was masked out
// or is part of an object
if (gsl_matrix_get(sc_img, ix, iy) < 0.0 ||
gsl_matrix_get(gr_mask, ix, iy) > 0.0 ||
((int)gsl_matrix_get(gr_dqval, ix, iy) & dqmask))
continue;
else
{
// give the pixel full weight
//x,y,value_back,value_grism_imag
fbck_data->e_values[index] = 1.0;
// enhance the counter
index++;
}
}
}
fbck_data->n_data = index;
fprintf(stdout, "\nNumber of pixels in structure: %i\n\n", fbck_data->n_data);
if (fbck_data->n_data < 1)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_SCALEBCK: no data left to determine the scale!\n");
}
/**
* Function: make_ksig_scalefit
* Determines the scale from the values in the pixel value structure.
* The results are determined iteratively while rejecting pixels via
* kappa-sigma clipping to get robust measurements. The results are
* the scale value, the standard deviation, the final number of
* not rejected points and the number of iterations.
*
* Parameters:
* @param fbck_data - the pixel value structure
*
* Returns:
* @return bck_vals - a vector with the fit results
*/
gsl_vector *
make_ksig_scalefit(fitbck_data *fbck_data)
{
gsl_vector *bck_vals=NULL;
float old_scale;
int index=0;
int clipped=1;
bck_vals = gsl_vector_alloc(6);
// check whether iterations still
// must be done and whether
// the data was changed from clipping
old_scale= 1.0e+06;
while (index < N_BCKSCALE_ITER && clipped)
{
// make a non-weighted linear fit
get_bck_scale(fbck_data->x_values, fbck_data->y_values, fbck_data->e_values,
fbck_data->n_data, bck_vals);
// make a clipping iteration
clipped = clipp_scale_data(fbck_data, bck_vals, N_BCKSCALE_KAPPA);
// break the iteration if the scale change is below a certain threshold
if (fabs((gsl_vector_get(bck_vals, 0)-old_scale)/gsl_vector_get(bck_vals, 0)) < N_BCKSCALE_ACCUR)
clipped = 0;
// store the new scale
old_scale = gsl_vector_get(bck_vals, 0);
// inhance the clipping counter
index++;
}
// set the number of iterations
gsl_vector_set(bck_vals, 4, (double)index);
// return the fit result
return bck_vals;
}
/**
* Function: get_bck_scale
* Computes the scale value from the pixel values in two arrays.
* The scale value is the median value of all input with weight.
* Also the standard deviation, the total number of input and
* the number of input with weight is returned.
*
* Parameters:
* @param xs - pixel values from one image
* @param ys - pixel values from second image
* @param ws - weight values
* @param n_elem - number of elements
* @param bck_vals - vector for the result
*
* Returns:
* @return -
*/
void
get_bck_scale(const double *xs, double *ys, double *ws,
const int n_elem, gsl_vector *bck_vals)
{
int i, m;
double *tmp;
double median;
double stdev;
// allocate space for temporary vectors
tmp = (double *) malloc (n_elem * sizeof (double));
// initialize the array
for (i = 0; i < n_elem; i++)
tmp[i] = 0.0;
// fill the temporary vectors
// with scale values and weights
m = 0;
for (i = 0; i < n_elem; i++)
{
if (ws[i] > 0.0 && ys[i] != 0.0)
{
tmp[m] = xs[i] / ys[i];
m++;
}
}
// sort the vector
gsl_sort( tmp, 1, m);
// just confirm the sorting
for (i = 1; i < m; i++)
if (tmp[i] < tmp[i-1])
fprintf(stdout, "Wrong: %f <--> %f\n", tmp[i],tmp[i-1]);
// take the home made median
median = tmp[(int)m/2];
// get the standard deviation
stdev = comp_stdev_from_array(tmp, m, median);
// put the results in the vector
gsl_vector_set(bck_vals, 0, median);
gsl_vector_set(bck_vals, 1, stdev);
gsl_vector_set(bck_vals, 2, (double)n_elem);
gsl_vector_set(bck_vals, 3, (double)m);
// release memory
free(tmp);
}
/**
* Function: clipp_scale_data
* Set the weight in the pixel value structure such as to clip
* point that deviate from the mean/characteristic value by
* more than the allowed amount.
*
* Parameters:
* @param fbck_data - pixel values from one image
* @param bck_vals - vector for the result
* @param kappa - vector for the result
*
* Returns:
* @return nclip - integer/boolean indicating new clipping
*/
int
clipp_scale_data(fitbck_data *fbck_data, const gsl_vector *bck_vals,
const float kappa)
{
int index;
int nclip=0;
int newclip=0;
double mean;
//double stdev;
double absdev;
// get the mean value
mean = gsl_vector_get(bck_vals, 0);
// compute the maximum allowed deviation
absdev = kappa * gsl_vector_get(bck_vals, 1);
// go over all data values
for (index=0; index < fbck_data->n_data; index++)
{
// avoid zero values
if (fbck_data->y_values[index] != 0.0)
{
// check whether the actual value is outside the allowed range
if (fabs(mean - (fbck_data->x_values[index]/fbck_data->y_values[index])) > absdev)
{
// check and mark clip changes
if (fbck_data->e_values[index])
newclip = 1;
// set the weight, change the counter
fbck_data->e_values[index] = 0.0;
nclip++;
}
else
{
// set the weight
fbck_data->e_values[index] = 1.0;
}
}
else
{
// set the weight, change the counter
fbck_data->e_values[index] = 0.0;
nclip++;
}
}
// return the newclip indicator
return newclip;
}
| {
"alphanum_fraction": 0.657238193,
"avg_line_length": 29.4259818731,
"ext": "c",
"hexsha": "8bc6910772a8cc2a638f2ec41b76b5da94c1f8e6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/scaleback_utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/scaleback_utils.c",
"max_line_length": 219,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/scaleback_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5576,
"size": 19480
} |
#ifndef ShapeBase_H
#define ShapeBase_H
#include <iostream>
#include <ostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include "Node.h"
#include "ReferenceShapeBase.h"
#include "GrowthFunctionBase.h"
#include "GrowthFunctionTypes.h"
class ShapeBase{
private:
void ParentErrorMessage(std::string functionName); ///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string inputs.
bool ParentErrorMessage(std::string functionName, bool returnValue); ///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and bool inputs, returning bool.
double ParentErrorMessage(std::string functionName, double returnValue); ///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and double inputs, returning double.
int ParentErrorMessage(std::string functionName, int returnValue); ///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and int inputs, returning int.
protected:
int ShapeType; ///< The integer defining the type of the shape, Prisms shape type = 1;
size_t nNodes; ///< The number of nodes of the element, it is based on ShapeBase#ShapeType
size_t nDim; ///< The number of dimensions for the positions of each of the nodes of the element
std::array<int,3> IdentifierColour; ///< The unique identifier colour of the element, this is used for "picking" in the visual interface.
std::array<double,3> GrowthRate; ///< Growth rate recording for display purposes only. The recorded growth rate in x, y, and z coordinates, does not record shear deformation induced in growth. Recorded in exponential form through time step, converted to rate per hour for display within the visual interface
gsl_matrix* growthIncrement; ///< The matrix (3,3) representing the incremental growth in current time step. Reset to identity at the beginning of each time step, updated in growth functions, and utilised to update Fg.
gsl_matrix* plasticDeformationIncrement; ///< The matrix (3,3) representing the incremental plastic deformation (treated as growth) in current time step. Set in plastic deformation calculation at each step, and utilised to update Fg.
gsl_matrix* shapeChangeIncrement; ///< The matrix (3,3) representing the incremental shape change in current time step. Reset to identity at the beginning of each time step, updated in shape change functions, and utilised to update Fg.
double zRemodellingSoFar; ///< The z remodelling that have been applied to elemetn up to the current time step. This parameter is used to limit extreme thinning or elongation of elements.
double columnarGrowthWeight; ///< The fraction defining how close to the columnar layer the element is. 1.0 for columnar layer, 0.0 for peripodial membrane elements, and scaled according to position in the elements surrounding the lumen.
double peripodialGrowthWeight; ///< The fraction defining how close to the peripodial membrane the element is. 0.0 for columnar layer, 1.0 for peripodial membrane elements, and scaled according to position in the elements surrounding the lumen.
std::array<double,6> ShapeChangeRate; ///< Shape change rate of the elements, only orthagonal shape changes are allowed (x, y, z). Shape changes will be scaled to conserve volume, thus three values will not be independent.
bool rotatedGrowth; ///< The boolean stating if the element has rotated from the growth axis, hence the calculated growth requires further rotation to follow tissue axes.
std::array<double,3> relativePosInBoundingBox; ///< The relative position on x-y plane, within the bounding box of the tissue(x,y).
std::array<double,3> initialRelativePosInBoundingBox;///< The relative position on x-y plane, within the bounding box of the tissue(x,y) at the beginning of simulation. This is used when growth rates are pinned to the initial structure of the tissue.
double initialRelativePositionInZ; ///< The relative position on z-height of tissue, taken not in z direction but in tissue layers, 0 being on the apical surface and 1 being on the basal surface.
size_t numberOfGaussPoints; ///< The number of Gauss points used in numerical deforamtion calculation.
std::array<std::array<double,3>,6> gaussPoints; ///< The array contianing all the Gauss points for element. Set up is for 6, can work for any number as loops are kept indexed up to numberOfGaussPoints.
std::array<double,6> gaussWeights; ///< The array for storing the weights of each Gauss point for element.
std::vector<gsl_matrix*> ShapeFuncDerivatives; ///< The array of matrices for shape function derivatives. The array stores a ShapeBase#nDim by ShapeBase#nNodes matrix for each gauss point (there are 3 Gauss points for prisms).
std::vector<gsl_matrix*> ShapeFuncDerStacks; ///< The array of matrices of shape function derivatives in stacked format for ease of matrix operations. The array stores a (ShapeBase#nDim * ShapeBase#nDim) by (ShapeBase#nDim * ShapeBase#nNodes) matrix for each gauss point (there are 3 Gauss points for prisms).
std::vector<gsl_matrix*> InvdXdes; ///< The array stores inverse of the matrix for derivatives of world coordinates with respect to barycentric coordinates (dX / de). The array stores an ShapeBase#nDim by ShapeBase#nDim matrix for each gauss point (there are 3 Gauss points for prisms).
std::array<double,6> detdXdes; ///< The array stores the determinants of the matrices for derivatives of world coordinates with respect to barycentric coordinates (dX / de). The array stores a double value for each gauss point (there are 3 Gauss points for prisms).
std::vector<gsl_matrix*> Bmatrices; ///< The array stores the B matrix for the calculation of stiffness matrix, see for ShapeBase#calculateBTforNodalForces calculation. The array stores an ShapeBase#nNodes by (ShapeBase#nDim*ShapeBase#nNodes) matrix for each Gauss point (there are 3 Gauss points for prisms).
std::vector<gsl_matrix*> FeMatrices; ///< The array stores the elastic part of the deformation matrix. The array stores an ShapeBase#nDim by ShapeBase#nDim matrix for each Gauss point (there are 6 Gauss points for prisms).
std::vector<gsl_matrix*> invJShapeFuncDerStack; ///< The array stores the shape function derivatives multiplied by the inverse Jacobian stack, for each Gauss point. See ShapeBase#calculateBTforNodalForces for calculation.
std::vector<gsl_matrix*> invJShapeFuncDerStackwithFe; ///< See ShapeBase#calculateInvJShFuncDerSWithFe for calculation.
std::vector<gsl_matrix*> elasticStress; ///< The array of matrices for elastic stress of the element. The array stores a 6 by 6 matrix for each Gauss point (there are 6 Gauss points for prisms).
std::vector<gsl_matrix*> viscousStress; ///< The array of matrices for internal viscous stress of the element. The array stores a 6 by 6 matrix for each Gauss point (there are 6 Gauss points for prisms).
gsl_matrix* TriPointF; ///< The deformation matrix of the element resulting from iteration over all Gauss points. The dimensions of the matrix is ShapeBase#nDim by ShapeBase#nDim.
gsl_matrix* ElementalElasticSystemForces; ///< The matrix stores the elemental elastic forces. The dimensions of the matrix is ShapeBase#nNodes by ShapeBase#nDim.
gsl_matrix* ElementalInternalViscousSystemForces; ///< The matrix stores the elemental internal viscous forces. The dimensions of the matrix is ShapeBase#nNodes by ShapeBase#nDim.
std::array<double,6> detFs; ///< The array stores the determinant of the deformation matrix for each Gauss point.
double ZProjectedBasalArea; ///< The z-projected area of the basal surface of the element.
double ZProjectedApicalArea; ///< The z-projected area of the apical surface of the element.
double BasalArea; ///< The area of the basal surface of the element.
double ApicalArea; ///< The area of the apical surface of the element.
double exposedLateralAreaApicalSide; ///< The area of the element on a linker position, and has lateral sides exposed to outside of the tissue, on the apical side, therefore should feel external viscosity.
double exposedLateralAreaBasalSide; ///< The area of the element on a linker position, and has lateral sides exposed to outside of the tissue, on the basal side, therefore should feel external viscosity.
bool elementHasExposedApicalSurface; ///< The boolean stating if the element has any apical surface exposed to the environment
bool elementHasExposedBasalSurface; ///< The boolean stating if the element has any basal surface exposed to the environment
int exposedApicalSurfaceNodeIds[3]; ///< The int array of size 3, listing the node IDs of element that form the exposed apical surface. The IDs are the node IDs on the element (0-5 for prism), not the actual Node#Id.
int exposedBasalSurfaceNodeIds[3]; ///< The int array of size 3, listing the node IDs of element that form the exposed basal surface. The IDs are the node IDs on the element (0-5 for prism), not the actual Node#Id.
int exposedLateralAreaApicalSideNodeIds[4]; ///< The int array of size 4, listing the node IDs of element that form the lateral surface exposed apically. The IDs are the node IDs on the element (0-5 for prism), not the actual Node::Id.
int exposedLateralAreaBasalSideNodeIds[4]; ///< The int array of size 4, listing the node IDs of element that form the lateral surface exposed basally. The IDs are the node IDs on the element (0-5 for prism), not the actual Node::Id.
size_t nLateralSurfaceAreaNodeNumber; ///< Number of nodes that form the lateral surfaces for the element.
size_t nSurfaceAreaNodeNumber; ///< Number of nodes that form the apical/basal surfaces for the element.
double stiffnessPerturbationRateInSec; ///< The rate at which the stiffness of the element will be perturbed, used with the model inputs from "Stiffness_Perturbation:" header in model input file
double minimumValueOfStiffnessMultiplier; ///< The lower bound of stiffness modification multiplier, exists to prevent elements reaching unintended zero or negative stiffness values.
double maximumValueOfStiffnessMultiplier; ///< The upper bound of stiffness modification multiplier, exists to prevent elements reaching unrealistic hard stiffness values.
double mutationGrowthRatePerSec; ///< The growth rate set by a mutant clone covering this element.
double mutationGrowthFold; ///< The rate of fold change in growth rate set by a mutant clone covering this element.
void setShapeType(std::string TypeName); ///< The function sets the type of the shape.
void readNodeIds(const std::vector<int>& inpNodeIds);///< The function sets the Node#Id array that constructs the shape.
void setPositionMatrix(const std::vector<std::unique_ptr<Node>>& Nodes); ///< The function sets the ShapeBase#Positions matrix to define the locations of each constructing node.
void setTissuePlacement(const std::vector<std::unique_ptr<Node>>& Nodes); ///< The function sets the placement of the element within the tissue
void setTissueType(const std::vector<std::unique_ptr<Node>>& Nodes); ///< The function sets the tissue type of the element
void setReferencePositionMatrix(); ///< The function sets the RefereneceShapeBase#Positions matrix to define the reference positions of the element.
void setIdentificationColour(); ///< The function sets the unique ShapeBase#IdentifierColour colour for the element, which is used in element picking from the user interface.
void rotateReferenceElementByRotationMatrix(std::array<double,9> rotMat); ///< The function rotates the reference of the element (ShapeBase#ReferenceShape) by input rotation matrix, provided as a double pointer of 9 doubles.
bool InvertMatrix(boost::numeric::ublas::matrix<double>& input, boost::numeric::ublas::matrix<double>& inverse); ///< The function takes the first input matrix, and writes the inverse on the second input. False is returned if the matrix is not inverted. Input format is ublas matrices (slow).
bool InvertMatrix(gsl_matrix* input, gsl_matrix* inverse); ///< The function takes the first input matrix, and writes the inverse on the second input. False is returned if the matrix is not inverted. Input format is gsl matrices (fast).
void updateNodeIdsFromSave(std::ifstream& file); ///< The function reads the ShapeBase#NodeIds of the current shape from save file provided as input.
void updateReferencePositionMatrixFromSave(std::ifstream& file); ///< The function reads and updates the ShapeBase#ReferenceShape positions (ReferenceShapeBase#Positions) of the current shape from save file provided as input.
virtual void calculateReferenceVolume(){ParentErrorMessage("calculateReferenceVolume");} ///<Virtual function of the ShapeBase class to calculate volume of the ShapeBase#ReferenceShape
bool calculateGrowthStrainsRotMat(double* v); ///< The function calculates the rotation matrix to apply on growth strains to align growth with the current x axis of the tissue.
void calculateForces3D(const std::vector<std::unique_ptr<Node>>& Nodes, gsl_matrix* displacementPerDt); ///< The function calculates the viscous and elastic forces generated by the element.
gsl_matrix* calculateEForNodalForcesKirshoff(gsl_matrix* C); ///< This function calculates the green strains for a Kirshoff material model.
gsl_matrix* calculateCauchyGreenDeformationTensor(gsl_matrix* Fe); ///< This function calculates the Caucy-Green deformation tensor, from the elastic part of the deformation gradient
gsl_matrix* calculateSForNodalForcesKirshoff(gsl_matrix* E); ///< This function calculates the Secons order Piola-Kirshoff stress tensor for Kirshoff material model.
gsl_matrix* calculateSForNodalForcesNeoHookean(gsl_matrix* invC, double lnJ); ///< This function calculates the Secons order Piola-Kirshoff stress tensor for Neo-Hookean material model.v
void updateLagrangianElasticityTensorNeoHookean(gsl_matrix* invC,double lnJ, int pointNo); ///< This function calcualtes the Lagrangian elasticity tensor for Neo-Hookean material model.
gsl_matrix* calculateCompactStressForNodalForces(double detFe,gsl_matrix* Fe, gsl_matrix* S, gsl_matrix *Stress); ///< This function calculates elemental stress in Voigt notation.
gsl_matrix* calculateInverseJacobianStackForNodalForces(gsl_matrix* Jacobian); ///< This function calculates the stack matrix of inverse Jacobians, used to calculate the nodal forces.
gsl_matrix* calculateBTforNodalForces(gsl_matrix* InvJacobianStack, gsl_matrix* ShapeFuncDerStack, gsl_matrix *B, gsl_matrix* invJShFuncDerS); ///< This function calculates the B matrix, to calculate the nodal force.
void calculateInvJShFuncDerSWithFe(gsl_matrix * currFe, gsl_matrix * InvDXde, gsl_matrix* ShapeFuncDerStack, gsl_matrix *invJShFuncDerSWithF); ///< This function calculates the collated matrix from inverse jaconians and shape function derivatives.
gsl_matrix* calculateVelocityGradientTensor(gsl_matrix* B, gsl_matrix* displacementPerDt); ///< This function calculates the velocity gradient tensor.
gsl_matrix* constructElementalDisplacementMatrix(gsl_matrix* displacement); ///< This function will assemble elemental node displacement matrix from the input displacement matrix for the whole system.
gsl_matrix* calculateRateOfDeformationTensor(gsl_matrix* l); ///< This function will calculate rate of deformation tensor from velocity gradient tensor
void calculateViscousStress(gsl_matrix* d, gsl_matrix* viscousStress); ///< This function will calculate internal viscous stress of the element from rate of deformation matrix.
void calculateViscousForces(gsl_matrix* gv, gsl_matrix* BTdetFdetdXde, gsl_matrix* viscousStress); ///< This function will calculate the elemental viscous forces from viscous stress.
void consturctBaTBb(gsl_matrix* B, gsl_matrix* BaT, gsl_matrix* Bb, int a, int b); ///< This function constructs nodal subrange of B matrix for node couple a & b.
void calculateElasticKIntegral1(gsl_matrix* currElementalK,int pointNo); ///< This function calcultes the first part of the integral for the stiffness matirx, the elastic part of the system Jacobian.
void calculateElasticKIntegral2(gsl_matrix* currElementalK,int pointNo); ///< This function calcultes the second part of the integral for the stiffness matirx, the elastic part of the system Jacobian.
void calculateViscousKIntegral1(gsl_matrix* currElementalK, gsl_matrix* paranthesisTermForKv1, int pointNo); ///< This function calcultes the first part of the integral for the internal viscous part of the system Jacobian.
void calculateViscousKIntegral2(gsl_matrix* currElementalK,int pointNo); ///< This function calcultes the second part of the integral for the viscous part of the system Jacobian.
void calculateVelocityGradient( gsl_matrix* velocityGradient, gsl_matrix* displacementPerDt, int pointNo); ///< This function calculates the velocity gradient.
void calculateOuterProduct(gsl_matrix* a, gsl_matrix* b, gsl_matrix* outerProduct); ///< Calculates the outer product, maths helper function.
gsl_matrix* calculateSymmetricisedTensorProduct(gsl_matrix* a, gsl_matrix* b); ///< Calculates the symetricised tensor product, maths helper function.
bool disassembleRotationMatrixForZ(gsl_matrix* rotMat); ///< This function extracts the z rotation from a rotation matrix.
bool calculate3DRotMatFromF(gsl_matrix* rotMat); ///< This function dissects the deformation gradient of the element into the rigid body rotation and deformation.
gsl_matrix* D; ///< elasticity tensor for Kirshoff material
gsl_matrix* CoeffMat; ///< The coefficient matrix relating the shape function derivative stack to the Voigt notation of elemental stress nad strain.
//need to construct double array of size: D81[nGaussPoints][3][3][3][3];
std::vector<std::array<std::array<std::array<std::array<double,3>,3>,3>,3>> D81; ///<Lagrangian elasticity tensor, vector for the number of Gauss points in simulaiton.
double E; ///< Young's modulus of the element.
double v; ///< Poisson's ratio of the element.
double internalViscosity; ///< Current internal viscosity of the element.
double originalInternalViscosity; ///< The internal viscosity of the element at the beginning of the simulation, prior to physical property perturbations.
double lambda; ///< Lame's second parameter, driven from Young's modulus and Poisson's ratio of the element
double mu; ///< Sheer modulus of the element.
gsl_matrix* InvFg; ///< Inverse of growth matrix
gsl_matrix* Fsc; ///< Shape change matrix
gsl_matrix* InvFsc; ///< Inverse of shape change matrix
gsl_matrix* TriPointKe; ///< Current elastic part of the Jacobian (stiffness matrix) of the system, averaged over all Gauss Points.
gsl_matrix* TriPointKv; ///< Current viscous part of the Jacobian of the system, averaged over all Gauss Points.
public:
double stiffnessMultiplier; ///< Current stiffness multiplier of the element, initially 1.0, modulated by stiffness perturbations ///< The double for the multiplier that will define Young's modulus stress stiffening.
gsl_matrix* remodellingPlaneRotationMatrix; ///< The rotation matrix converting the xyz coordinate system to the plane of remodelling for the lateral elements.
gsl_matrix* Fg; ///< Growth deformation gradient
int Id; ///< The unique ID of the element, without remodelling, equal to its indes on the Simulation#Elements vector.
int ShapeDim; ///< The dimension of the shape in workd coordiantes (2D vs 3D).
std::vector<int> NodeIds; ///< The vector storing the unique IDs (Node#Id) of nodes constructing this element. Their order is consistent for a given shape type.
virtual ~ShapeBase(){ /// The ShapeBase destructor. This destructor should not be called uner healthy conditions.
//while deleting a ShapeBase* that happens to point a child, this destructor will be called after the child destructor
}
std::vector<std::array<double,3>> Positions; ///< The vector storing the positions of the nodes constructing the element.
std::unique_ptr<ReferenceShapeBase> ReferenceShape; ///< The pointer to the reference shape object that defines th reference shape of this element.
gsl_matrix* Strain; ///< The gsl_matrix pointer, storing the address of the current strains on the element.
bool isFlipped; ///< Boolean stating if the element is flipped. The simulation will be stopped if there are flipped elements.
bool IsChangingShape;
//bool willBeRefined;
int tissuePlacement; ///< 1 -> apical, 0 -> basal, 2->middle, 3 -> lateral
int tissueType; ///< The tissue type is 000 for columnar layer, 1 for peripodial membrane, and 2 for linker zone
bool spansWholeTissue; ///< Boolean staing is the element spans the whole tissue. This is used to identify mid-layer tagged tissues (tissuePlacement = 2), that should still have apical abd basal responses
int compartmentType; ///< integer identifying the compartment of the tissue in DV axis, 0 pouch, 1 hinge, 2 notum
double compartmentIdentityFraction; ///< The weight defining the constibution of each compartment to the physical identity of this element.
bool isECMMimicing; ///< Boolean stating if the element is an ECM element.
bool isECMMimimcingAtCircumference; ///< Boolean stating if the element is an ECM element at the circumference of the tissue.
bool atBasalBorderOfECM; ///< Boolean stating if the element is at the basal border of the cellular layer, linking to ECM elements.
bool isActinMimicing; ///< Boolean stating if the element is forming the actin dense layer on the apical surface.
bool atApicalBorderOfActin; ///< Boolean stating if the element is at the apical border of the soft cellular layer, linking to actin dense layer.
bool IsAblated; ///< Boolean stating if the element is laser ablated, therefore dead.
bool atSymetricityBoundary; ///< Boolean stating if the element is at the symmetricity boundary.
//bool IsClippedInDisplay;
//bool IsXSymmetricClippedInDisplay;
//bool IsYSymmetricClippedInDisplay;
double CurrShapeChangeToAdd[3]; ///< The current shape change to be applied to the element, in form of 3D rates.
double GrownVolume; ///< Current volume of the element after growth.
double VolumePerNode; ///< Volume per node of the element.
bool capElement; ///< Boolean stating if the element is capped at its remodelling due to restrictions in z remodelling (avoiding too thin ot too thick layers due to numerical error).
std::vector<int> elementsIdsOnSameColumn; ///< The vector storing the unique element IDs of each element that is on the same columnar region of the tissue, i.e. the elements share apical/basal surfaces.
int basalNeigElementId; ///< This is recorded only for apical nodes of the columnar layer. If not recorded, id is -1.
bool insideEllipseBand; ///< Boolean stating if the element is marked by any identifier bands for physical perturbation.
int coveringEllipseBandId; ///< The unique ID of the covering perturbation band.
double emergentShapeLongAxis[2]; ///< The long axis of the emergent shape. This is necessary for analysis of emergent growth orientations.
double emergentShapeShortAxis[2]; ///< The short axis of the emergent shape. This is necessary for analysis of emergent growth orientations.
double plasticDeformationHalfLifeMultiplier; ///< The multiplier to modify the remodelling half-life upon physical property perturbation.
bool isMutated; ///< Boolean stating if the element is mutated.
bool thereIsGrowthRedistribution; ///< Boolean stating if there is redistribution of growth among mesh elements.
bool growthRedistributionShrinksElement; ///< Boolean stating if the growth distribution is taking material out of thes element to redistribute ot others.
double growthRedistributionScale; ///< The extent of the redistribution of volume.
bool RotatedElement; ///< The boolean stating if the elemetn has rigid body rotation.
gsl_matrix* GrowthStrainsRotMat; ///< The rotation matrix needed to correct for the rigid body rotations of the element.
std::array<double,3> apicalNormalCurrentShape; ///< The apical normal of the current shape.
int getId(); ///< The function returns the unique ID of the element.
std::string getName(); ///< The function returns the name of the element.
int getShapeType(); ///< The function returns the shape type of the element.
size_t getNodeNumber(); ///< The function returns the number of nodes o the element.
const std::vector<int>& getNodeIds(); ///< The function returns the vector of node IDs.
int getNodeId(int i); ///< The function returns the input i^{th} node's ID.
size_t getDim(); ///< The function returns the dimensions of the node, ShapeBase#Dim.
std::array<int,3> getIdentifierColour(); ///< The unique [r,g,b] identifier colour of the element, utilised in picking in the user interface.
std::array<double,3> getCentre(); ///< This function returns the centre of the element in world spave.
double getPeripodialness(); ///< This function returns the relative influence of the peripodial physical characteristics to this element.
double getColumnarness(); ///< This function returns the relative influence of the columnar physical characteristics ot this element.
void getRelativePositionInTissueInGridIndex(int nGridX, int nGridY, int& IndexX, int& IndexY, double& FracX, double& FracY); ///< Provides the relative position within the bounding box of the tissue, and calculates which point on the growth maps should be read.
void getInitialRelativePositionInTissueInGridIndex(int nGridX, int nGridY, int& IndexX, int& IndexY, double& FracX, double& FracY); ///< The relative positions of the iitial configuration of the element within the bounding box of the tissue.
double getStiffnessMultiplier(); ///< This function returns the current stiffness multiplier as a result of perturbations to physical properties.
double getCurrentVolume(); ///< This function returns the current volume of the element.
double getElementalElasticForce(int nodeIndex, int dimIndex); ///< This function returns the calculated elastic force for the node nodeIndex, in coordinate dimIndex.
void setElementalElasticForce(int nodeIndex, int dimIndex, double value); ///< This functions sets the calculated elastic force for the node nodeIndex, dimension dimIndex, to the input value.
gsl_matrix* getCurrentFe(); ///< This function returns the current elastic part of the deformation gradient.
double getApicalArea(); ///< This function returns the current apical area of the element.
void relaxElasticForces(); ///< This function relaxes all teh accumulated elastic forces in the system.
bool isGrowthRateApplicable(int sourceTissue, double& weight, double zmin, double zmax); ///< The function checks if the element if affected by the current growth functions.
void updateGrowthWillBeScaledDueToApikobasalRedistribution(bool thisFunctionShrinksApical, std::vector<int>& ellipseBandIdsForGrowthRedistribution); ///< This function decide if the growth will be redistirbuted in the height of the tissue.
void scaleGrowthForZRedistribution( double& x, double& y, double& z); ///< This function will modify the incremental growth deformation gradient of the element to reflect the volume redistribution in the height of the tissue.
void calculateFgFromRates(double dt, double x, double y, double z, gsl_matrix* rotMat, gsl_matrix* increment, int sourceTissue, double zMin, double zMax); ///< This fucntion will calculate the incremental growth deformation gradient change for the current time step, from input growth rates
void calculateFgFromGridCorners(int gridGrowthsInterpolationType, double dt, GrowthFunctionBase* currGF, gsl_matrix* increment, int sourceTissue, int IndexX, int IndexY, double FracX, double dFracY); ///< This fucntion will calculate the incremental growth deformation gradient change for the current time step by reading it from the grid, and interpolating on 4 corners.
gsl_matrix* getGrowthIncrement(); ///< This function will return the current growth deformation gradient increment
void updateGrowthIncrement(gsl_matrix* columnar, gsl_matrix* peripodial); ///< This function will update the elemental growth deformation gradient from the current growth deformation gradient increment.
void updateGrowthByMutation(double dt); ///< This function will update the growth growth deformaton gradient increment of the element due to a mutation.
void scaleGrowthIncrement(double multiuplier); ///< This function will scale the growth growth deformaton gradient increment by input double.
void calculateShapeChangeIncrementFromRates(double dt, double rx, double ry, double rz, gsl_matrix* increment); ///< This function will calculate the current shape change deformation gradient increment due to elemental active shape change, from input rates.
void updateShapeChangeIncrement(gsl_matrix* columnarShapeChangeIncrement); ///< This function updates the growth increment of the element with the current shape change increment
void calculateRelativePosInBoundingBox(double boundingBoxXMin, double boundingBoxYMin, double boundingBoxLength, double boundingBoxWidth); ///< This function will calculate the relative positions of the element in the xy-plane bounding box of the tissue.
void mutateElement(double growthFold, double growthRatePerHour); ///< This function will set the element as a mutant, the mutant growth rates will be set.
void updateReferencePositionMatrixFromInput(double** input); ///< This function will update the reference position matrix. Not used under healthy, continuous simulations, to preserve continuity of the mesh.
void displayRelativePosInBoundingBox(); ///< Helper function to display the relative position of the element in the bounding box of the tissue.
std::array<double,2> getRelativePosInBoundingBox(); ///< This function will return the relative position of the element in the xy bounding box of the tissue
void setRelativePosInBoundingBox(double x, double y); ///< This functoin will set the relative position of the element in the bounding box of the tissue to the input coordinates.
void setInitialRelativePosInBoundingBox(); ///< This function sets the initial relative position in bounding box of the tissue to current reference position.
void setInitialZPosition(double zMax, double TissueHeight); ///< This fucntion sets the initial relative z position of the tissue in tissue height.
std::array<double,2> getInitialRelativePosInBoundingBox(); ///< This function will return the initial relative position of the element in the xy bounding box of the tissue
void convertRelativePosToGridIndex(std::array<double,2> relpos, int& indexX, int &indexY, double &fracX, double &fracY, int nGridX, int nGridY); ///< This function will convert the relative position of the tissue in xy plane bounding box to growth map grid indices.
void getStrain(int type, float &StrainMag); ///< This function will return the selected strain component of the element.
void getNodeBasedPysProp(int type, int NodeNo, const std::vector<std::unique_ptr<Node>>& Nodes, float& PysPropMag); ///< This function will return the selected physical properties of the element on a nodal basis.
void getPysProp(int type, float &PysPropMag, double dt); ///< This function will return the selected physical properties of the element.
double getInternalViscosity(); ///< This function will return the internal viscosity of the element.
double getOriginalInternalViscosity(); ///< This function will return the internal viscosity of the element prior to any perturbations.
//void updateInternalViscosityTest();
double getYoungModulus(); ///< This function will return the Young's modulus of the element
double getPoissonRatio(); ///< This function will return the Poissons's ratio of the element
const std::array<double,3>& getGrowthRate(); ///< This function will return the current growth rate of the element.
const std::array<double,6>& getShapeChangeRate(); ///< This function will return the current shape change rate of the element.
const std::vector<std::array<double,3>>& getReferencePos(); ///< This function will return the reference positions of the element.
void getPos(gsl_matrix* Pos); ///< This function will write the position of the element into input matrix.
gsl_matrix* getFg(); ///< This function will return the growth component of the deformation gradient.
gsl_matrix* getInvFg(); ///< This function calculates the inverse of the growth deformation gradient matrix.
gsl_matrix* getFsc(); ///< This function will return the shape change component of the deformation gradient.
gsl_matrix* getInvFsc(); ///< This function calculates the inverse of the shape change deformation gradient matrix.
gsl_matrix* getFe(); ///< This function will return the elastic component of the deformation gradient.
double getZRemodellingSoFar(); ///< This function will return the z remodelling applied to the element so far, to cap the z remodelling.
void setZRemodellingSoFar(double zRemodellingSoFar); ///< This function will set the z remodelling applied to the element so far to input value. This is needed during saved input reading.
void displayName(); ///< Helper function, display the name of the element
void displayNodeIds(); ///< Helper function, display the Ids of the nodes of the element
void displayPositions(); ///< Helper function, display the nodal positions of the element
void displayReferencePositions(); ///< Helper function, display the nodal positions of the reference element
void displayIdentifierColour(); ///< Helper function, display the unique identifier colour, for picking in user interface.
void setFg(gsl_matrix* currFg); ///< This function sets the current grwoth deformation gradient matrix equal to input matrix
void setGrowthWeightsViaTissuePlacement (double periWeight); ///< This function sets the weight for growth rate scaling depending on tissue type
void setYoungsModulus(double E); ///< This function sets the Young's modulus of the shape to inout double.
virtual void setElasticProperties(double /*EApical*/,double /*EBasal*/, double /*EMid*/, double /*EECM*/, double /*v*/){ParentErrorMessage("setElasticProperties");} ///< This is the parent virtual function for setting up the elasticity properties of the shape depending on its tissue type placement.
virtual void checkEdgeLenghtsForBinding(std::vector<int>& /*masterIds*/, std::vector<int>& /*slaveIds*/){ParentErrorMessage("checkEdgeLenghtsForBinding");} ///< The virt
void setViscosity(double viscosityApical,double viscosityBasal, double viscosityMid);///< This function sets the viscosity of the element depending on its placement in the tissue.
void setViscosity(double viscosityApical,double viscosityBasal); ///< This function sets the viscosity of the element depending on its placement in the tissue.
void setViscosity(double viscosity); ///< This function sets the viscosity of the element depending on its placement in the tissue.
double calculateEmergentShapeOrientation(); ///< This fucntion calculates the orientation of the emergent shape of an element in the xy plane of the tissue.
bool isActinStiffnessChangeAppliedToElement(bool ThereIsWholeTissueStiffnessPerturbation, bool ThereIsApicalStiffnessPerturbation, bool ThereIsBasalStiffnessPerturbation, bool ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation, bool ThereIsBasolateralStiffnessPerturbation, std::vector <int> &stiffnessPerturbationEllipseBandIds, int numberOfStiffnessPerturbationAppliesEllipseBands ); ///< This function decides if the actin stiffness perturbation is applied to this element.
bool isECMChangeAppliedToElement(bool changeApicalECM, bool changeBasalECM, std::vector<int> &ECMChangeEllipseBandIds, int numberOfECMChangeEllipseBands); ///< This function decides if the ECM perturbation is applied to this element
bool isShapeChangeAppliedToElement(std::vector<int> &ellipseBandIds, bool applyBasalECM, bool applyToLateralECM, bool applyApically, bool applyBasally, bool applyMidLayer ); ///< This function decides if the shape change perturbation is applied to this element
void calculateStiffnessPerturbationRate(bool ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation, double stiffnessPerturbationBeginTimeInSec, double stiffnessPerturbationEndTimeInSec, double stiffnessChangedToFractionOfOriginal); ///< This function will calciulate the stiffness perturbation rate.
void updateStiffnessMultiplier(double dt); ///< The function will update the actin multiplier as a result of stiffness perturbations.
virtual std::array<double,3> calculateBasalNormal(){ParentErrorMessage("calculateBasalNormal"); std::array<double,3> dummy = {0.0, 0.0, 0.0}; return dummy;} ///< The virtual function of the parent for basal normal calculation. The value is dependent on node topology of the element and defined for eac individual child class.
virtual void calculateApicalNormalCurrentShape(){ParentErrorMessage("calculateApicalNormal");} ///< The virtual function of the parent for apical normal calculation. The value is dependent on node topology of the element and defined for eac individual child class.
void calculateCurrentGrowthIncrement(gsl_matrix* resultingGrowthIncrement, double dt, double growthx, double growthy, double growthz, gsl_matrix* ShearAngleRotationMatrix); ///< The function calculates the current growth increment from the input of growth rate and the orientation rotation matrix.
void updateShapeChangeRate(double x, double y, double z, double xy, double yz, double xz);
virtual void calculateElementShapeFunctionDerivatives(){ParentErrorMessage("calculateElementShapeFunctionDerivatives");} ///< The virtual function of the parent for calculation of shape function derivatives. This is topology dependent and implemented in each child shape type.
virtual void calculateCurrNodalForces(gsl_matrix */*gslcurrge*/, gsl_matrix */*gslcurrgv*/, gsl_matrix */*gslcurrF*/, gsl_matrix* /*displacementPerDt*/, int /*pointNo*/){ParentErrorMessage("calculateCurrNodalForces");} ///< The virtual function to calculate nodal force. This is topology dependent and implemented in each child shape type.
virtual void calculateCurrTriPointFForRotation(gsl_matrix */*currF*/,int /*pointNo*/){ParentErrorMessage("calculateCurrTriPointFForRotation");}
virtual void calculateApicalArea(){ParentErrorMessage("calculateApicalArea");} ///< The virtual function to calculate apical area of element. This is topology dependent and implemented in each child shape type.
virtual void calculateBasalArea(){ParentErrorMessage("calculateBasalArea");} ///< The virtual function to calculate basal area of element. This is topology dependent and implemented in each child shape type.
double calculateCurrentGrownAndEmergentVolumes(); ///< This is the function to calculate hte current ideal volume of the element and its current apparent volume.
virtual void updateElasticProperties(){ParentErrorMessage("updateElasticProperties");} ///< This functions updates elastic propertiesand their dependent tensors upon alteration of a physical property.
void writeInternalForcesTogeAndgv(gsl_matrix* ge, gsl_matrix* gvInternal, std::vector<std::array<double,3>>& SystemForces, const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function writes the elemental elastic and viscous forces to the system scale force vector.
void calculateForces(const std::vector<std::unique_ptr<Node>>& Nodes, gsl_matrix* displacementPerDt);
void updatePositions(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function updates the position array of the element from the updated nodal posiitons.
void setGrowthRate(double dt, double rx, double ry, double rz); ///< This function sets the growth of the element from the tome step and the input rates
void setGrowthRateViaInputTimeMultipliedMagnitude(double x, double y, double z); ///< This function sets the growht rate to pre-calculated rates given as input.
void updateGrowthIncrementFromRate(); ///< This function fills th egrowht increment matirx from the current growth rate matrix
double calculateVolumeForInputShapeStructure(std::vector<std::array<double,3>> shapePositions, size_t nTriangularFaces, std::vector<std::array<int,3>> triangularFaces, std::array<double,3> midPoint ); ///< This function calculates the volume of the shape, it is generalised such that the shape is defined as an array of triengles forming a convex hull.
void calculatePrincipalStrains3D(double& e1, double &e2, double &e3, gsl_matrix* eigenVec); ///< This function calculates the principal components of the strains through eigen values and eigen vectors in 3D.
void calculatePrincipalStrains2D(double& e1, double &e2, double &e3, gsl_matrix* eigenVec); ///< This function calculates the principal components of the strains through eigen values and eigen vectors in 2D.
//void calculatePrincipalStrainAxesOnXYPlane(double& e1, double &e2, double& tet); ///< This function princial
// bool checkIfXYPlaneStrainAboveThreshold(double thres);
// bool calculateIfInsideActiveStripe(double initialPoint,double endPoint, double stripeSize1, double stripeSize2);
void setShapeChangeRate(double x, double y, double z, double xy, double yz, double xz); ///< This function sets the shape change rate to pre-calculated rates given as input.
void setShapeChangeInrementToIdentity(); ///< This function sets the shape change deformation gradient increment to identity
void updateElementVolumesAndTissuePlacementsForSave(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function calculates the reference volume, tissue placement and tissue type from nodal information
bool readNodeIdData(std::ifstream& file); ///< This function reads in the node Ids for the element from save file
bool readReferencePositionData(std::ifstream& file); ///< This function reads the reference element positions from save file
bool areanyOfMyNodesAtCircumference(const std::vector<std::unique_ptr<Node> > &Nodes); ///< This function check if the element owns any node at tissue circumference
virtual void checkHealth(){ParentErrorMessage("checkHealth");} ///< The virtual function in parent to check if element is flipped, implemented for each child as it is node topology dependent.
void writeKelasticToMainKatrix(gsl_matrix* K); ///< This function writes the elemental elastic component of the Jacobian to system Jacobian.
void writeKviscousToMainKatrix(gsl_matrix* K); ///< This function writes the elemental viscous component of the Jacobian to system Jacobian.
void calculateImplicitKElastic(); ///< This function calculates the elemental elastic component of the Jacobian for implicit NR itaration.
void calculateImplicitKViscous(gsl_matrix* displacementPerDt, double dt); ///< This function calculates the elemental viscous component of the Jacobian for implicit NR itaration.
void calculateForceFromStress(int nodeId, gsl_matrix* Externalstress, gsl_matrix* ExternalNodalForces); ///< This function calculates the elemental nodal forces from an input external stress matrix
void updateShapeFromSave(std::ifstream& file); ///< This function updates the element geometric poroerties from save file.
void displayMatrix(boost::numeric::ublas::matrix<double>& mat, std::string matname); ///< Helper function, displays the input blas (double) matrix with the input name.
void displayMatrix(boost::numeric::ublas::matrix<int>& mat, std::string matname); ///< Helper function, displays the input blas (int) matrix with the input name.
void displayMatrix(boost::numeric::ublas::vector<double>& vec, std::string matname); ///< Helper function, displays the input blas (double) vector with the input name.
void displayMatrix(gsl_matrix* mat, std::string matname); ///< Helper function, displays the input gsl matrix with the input name.
void displayMatrix(gsl_vector* mat, std::string matname); ///< Helper function, displays the input gsl vector with the input name.
void createMatrixCopy(gsl_matrix *dest, gsl_matrix* src); ///< Helper function, creates a copy of the gsl matrix on new memory locaiton.
double calculateMagnitudeVector3D(std::array<double,3> v); ///< Helper algebraic function, calculates norm of the vector defined in the array<double,3>;
void normaliseVector3D(gsl_vector* v); ///< Helper algebraic function, normalises the input gsl vector (the input vector is modified)
double normaliseVector3D(std::array<double,3>& v); ///< Helper algebraic function, normalises the input array<double,3> (the input vector is modified)
double getNormVector3D(gsl_vector* v); ///< Helper algebraic function, calculates norm of the vector defined in the gsl vector, the vector is not modified.
//double determinant3by3Matrix(double* rotMat); ///< Helper algebraic function, calculates determinant of 3by3 matrix stored in the double array pointed by the input pointer
double determinant3by3Matrix(boost::numeric::ublas::matrix<double>& Mat); ///< Helper algebraic function, calculates determinant of 3by3 boost matrix
double determinant3by3Matrix(gsl_matrix* Mat); ///< Helper algebraic function, calculates determinant of 3by3 gsl matrix
double determinant2by2Matrix(boost::numeric::ublas::matrix<double>& Mat); ///< Helper algebraic function, calculates determinant of 2by2 boost matrix
void calculateRotationAngleSinCos(std::array<double,3>& u, std::array<double,3>& v, double& c, double& s); /// Helper algebraic function calculates the sine and cosine of the rotation angle needed to align vector u onto v.
void calculateRotationAxis(const std::array<double,3>& u, const std::array<double,3> &v, std::array<double,3>& rotAx, double c); /// Helper algebraic function calculates the rotation axis needed to align vector u onto v.
void constructRotationMatrix(double c, double s, double* rotAx, double* rotMat); ///< Helper algebraic functio calculates the rotation matrix from input sine, cosine of the rotation angle and the rotation axis. Writes the matrix into the input rotMat
void constructRotationMatrix(double c, double s, std::array<double,3>& rotAx, std::array<double,9>& rotMat); ///< Helper algebraic functio calculates the rotation matrix from input sine, cosine of the rotation angle and the rotation axis. Writes the matrix into the input rotMat
void rotateVectorByRotationMatrix(double* u,double* rotMat); ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat
void rotateVectorByRotationMatrix(double* u,gsl_matrix* rotMat); ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat
void rotateVectorByRotationMatrix(std::array<double,3>& u, std::array<double,9> rotMat); ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat
void CalculateGrowthRotationByF(); ///< This function calculates the rigid body rotation of the element around the z axis of the tissue from hte fecormation gradient.
void calculateTriPointFForRatation(); ///< This function calculates the current deformaiton gradient as averaged at all Gauss points, for rigid body rotation extraction
void setPlasticDeformationIncrement(double xx, double yy, double zz); ///< This function sets diagonal of the plastic deformation gradient increment from input values
void growShapeByFg(); ///< This function updates the current growth deformaiton gradient with the growt/shape change/plastic deformation increments and their respective rotations.
void changeShapeByFsc(double dt); ///< This function calculates the shape change increment from shape change rates
void checkIfInsideEllipseBands(int nMarkerEllipseRanges, std::vector<double> markerEllipseBandXCentres, std::vector<double> markerEllipseBandR1Ranges, std::vector<double> markerEllipseBandR2Ranges, const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function checks if the element is inside any marker bands for perturbatins.
bool checkZCappingInRemodelling(bool volumeConserved, double zRemodellingLowerThreshold, double zRemodellingUpperThreshold, gsl_matrix* increment, gsl_matrix* eigenVec); ///< This function checks if the remodelling of the element in z axis have reached the specified cap.
void assignSoftHinge(double lowHingeLimit, double highHingeLimit,double softnessLevel); ///< This function modulates the stiffness of the hinge domain of the tissue with the input level. The domain is defined in relative x position boundaries.
void calculatePlasticDeformation3D(bool volumeConserved, double dt, double plasticDeformationHalfLife, double zRemodellingLowerThreshold, double zRemodellingUpperThreshold); ///< This function calculates the plastic deformation (remodelling) from the current elastic deformation gradient.
//void addMigrationIncrementToGrowthIncrement(gsl_matrix* migrationIncrement);
void displayDebuggingMatrices(); ///< This function displays a selected set of matricex for debugging purposes.
virtual double getApicalSideLengthAverage(){return ParentErrorMessage("getApicalSideLengthAverage",0.0);} ///< The virtual function of the parent to calculate average apical side length, dependent on nodal topology, defined in each child.
virtual double getBasalSideLengthAverage(){return ParentErrorMessage("getBasalSideLengthAverage",0.0);} ///< The virtual function of the parent to calculate average basal side length, dependent on nodal topology, defined in each child.
virtual int getCorrecpondingApical(int /*currNodeId*/){return ParentErrorMessage("getCorrecpondingApical", -100);} ///< The virtual function of the parent to obtain the corresponding apical node of a basal node, dependent on nodal topology, defined in each child.
virtual bool IsThisNodeMyBasal(int /*currNodeId*/){return ParentErrorMessage("IsThisNodeMyBasal", false);} ///< The virtual function of the parent to check if the input node ID is a basal node of the element, dependent on nodal topology, defined in each child.
virtual bool IsThisNodeMyApical(int /*currNodeId*/){return ParentErrorMessage("IsThisNodeMyApical", false);} ///< The virtual function of the parent to check if the input node ID is an apical node of the element, dependent on nodal topology, defined in each child.
virtual double getElementHeight(){return ParentErrorMessage("getElementHeight", 0.0);} ///< //< The virtual function of the parent to calculate z height of the element, dependent on nodal topology, defined in each child.
virtual void constructElementStackList(const int /*discretisationLayers*/, const std::vector<std::unique_ptr<ShapeBase>>& /*elementsList*/){ParentErrorMessage("constructElementStackList");}
virtual void checkRotationConsistency3D(){ParentErrorMessage("checkRotationConsistency3D");} ///< The virtual function of the parent to check if the two input nodes of the element are directly connected on one of the elemental surfaces, dependent on nodal topology, defined in each child.
virtual bool areNodesDirectlyConnected(int /*node0*/, int /*node1*/){return ParentErrorMessage("areNodesDirectlyConnected",false);} ///< The virtual function of the parent to check if the rotation of the nodes of the element are consistent, dependent on nodal topology, defined in each child.
bool DoesPointBelogToMe(int IdNode); ///< This function checks if the input node belogs to the element.
void assignVolumesToNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function distributes element's total volume among its owner nodes.
void calculateZProjectedAreas(); ///< This function calculated the z-projected (to world xy plane) apical and basal areas of the element.
void assignZProjectedAreas(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function distributes element's z-projected areas among its owner nodes.
void assignElementToConnectedNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function assigns the element to the nodes it owns, necessary to construc the owner and connectivity list of nodes.
void setECMMimicing(bool IsECMMimicing); ///< This funciton sets the element as an ECM mimicking element (distinct domain in terms of physical characteristics).
void setActinMimicing(bool isActinMimicing); ///< This funciton sets the element as an actin mimicking element (distinct domain in terms of physical characteristics).
virtual void assignExposedSurfaceAreaIndices(const std::vector<std::unique_ptr<Node>>& /*Nodes*/){ParentErrorMessage("assignExposedSurfaceAreaIndices");} ///< The virtual function on parent assigns the nodes of the surfaces that are exposed to external world, dependent on topology, defined for each child.
void calculateViscositySurfaces(); ///< This function calls for the assignment of exposed surfaces if the element has viscosity
void assignViscositySurfaceAreaToNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function distributes elemenbt's exposed surfaces to nodes.
void calculateEmergentRotationAngles(); ///< This function calculates the emergent rotation of the element in xy plane for display purposes
void updateReferencePositionMatrixFromMeshInput(std::ifstream& file); ///< This function updates the reference position of the element from save file
void fillNodeNeighbourhood(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function fills in the node neightbourhood, needed for constrction of the connectivity of nodes
double dotProduct3D(std::array<double,3>& u, std::array<double,3>& v); ///< Helper algebraic function, calculates dot product of two arrays <double,3>
void crossProduct3D(gsl_vector* u, gsl_vector* v, gsl_vector* cross); ///< Helper algebraic function, calculates cross product of two gsl_vectors, writes into the third input gls vector.
std::array<double,3> crossProduct3D(std::array<double,3> u, std::array<double,3> v); ///< Helper algebraic function, calculates cross product of two arrays <double,3>
virtual void setBasalNeigElementId(const std::vector<std::unique_ptr<ShapeBase>>& /*elementsList*/){ParentErrorMessage("setBasalNeigElementId");}
bool isElementFlippedInPotentialNewShape(int nodeId, double newX, double newY, double newZ); ///< This function checks if the element will plip in the case that its node (nodeID) is moved to the new x,y,z coordintes specified in the input. Necessary in node collapsing.
void checkForCollapsedNodes(int TissueHeightDiscretisationLayers, const std::vector<std::unique_ptr<Node>>& Nodes, const std::vector<std::unique_ptr<ShapeBase>>& Elements); ///< This function checks if any of the edges of the element is shortened to the extent that it should be collapsed.
bool hasEnoughNodesOnCurve(const std::vector<std::unique_ptr<Node> > &Nodes); ///< This function checks if the majority of the nodes of teh element reside in a curved region, to assign it to specific curvature dependent perturbations.
void assignEllipseBandIdToWholeTissueColumn(size_t TissueHeightDiscretisationLayers, const std::vector<std::unique_ptr<Node>>& Nodes, const std::vector<std::unique_ptr<ShapeBase>>& Elements); ///< This function assigns the marker ID of the apical elemetn ot all its connected elements in the tissue hight (all column of the element).
void assignEllipseBandId(const std::vector<std::unique_ptr<Node>>& Nodes, int selectedEllipseBandId); ///< This function assigns the marking ellipse band ID of the element depending on the definition of nodes it is consturcted of.
void assignEllipseBandIdToNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function assigns the marker ID of the elemetn to all its nodes.
void addToElementalElasticSystemForces(int i,int j,double value); /// This function is to add the input value, to the (i,j)th element of the ElementalElasticSystemForces
void addToTriPointKe(int i,int j,double value); /// This function is to add the input value, to the (i,j)th element of the triPointKe
};
#endif
| {
"alphanum_fraction": 0.6982008668,
"avg_line_length": 163.6275510204,
"ext": "h",
"hexsha": "154d86d1b177f1683db627608bbb01521ce5592d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-07-28T12:26:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-06T11:38:53.000Z",
"max_forks_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_forks_repo_path": "TissueFolding/SourceCode/ShapeBase.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_issues_repo_path": "TissueFolding/SourceCode/ShapeBase.h",
"max_line_length": 492,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_stars_repo_path": "TissueFolding/SourceCode/ShapeBase.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-25T16:18:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-18T14:13:41.000Z",
"num_tokens": 13539,
"size": 64142
} |
/*
Excited States software: KGS
Contributors: See CONTRIBUTORS.txt
Contact: kgs-contact@simtk.org
Copyright (C) 2009-2017 Stanford University
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
This entire text, including the above copyright notice and this permission notice
shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef KGS_DIRECTION_H
#define KGS_DIRECTION_H
#include <gsl/gsl_vector.h>
#include "core/Configuration.h"
/**
* Implementing sub-classes specify different methods of computing gradients.
*/
class Direction {
public:
virtual ~Direction() = 0;
/**
* Compute a gradient for the configuration `conf` and store the result in `ret`.
* A target configuration can be specified if the implementing subclass performs directed
* gradients. If not the target will be ignored.
*
* Any values stored in the `ret` vector will be overwritten by this function so there is
* no need to reset it to zero before use.
*
* \pre { `conf` and `ret` are both non-nullptr }
* \post { All values in `ret` are guaranteed to be in the the range -Ο to Ο. }
*/
void gradient(Configuration* conf, Configuration* target, gsl_vector* ret);
protected:
virtual void computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret) = 0;
};
#endif //KGS_DIRECTION_H
| {
"alphanum_fraction": 0.7627885921,
"avg_line_length": 34.515625,
"ext": "h",
"hexsha": "ce9aa32dc18bf6aecfc84662966913094325c96e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/directions/Direction.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/directions/Direction.h",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/directions/Direction.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 488,
"size": 2209
} |
/*
** pseudoinverse
**
** G.Lohmann, July 2004
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "viaio/Vlib.h"
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
extern void printmat(gsl_matrix *R,char *str);
extern void printvec(gsl_vector *x,char *str);
/*
** B = A^-1 = A^+
*/
gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B)
{
int j,k,l,n,m;
double u,x;
gsl_matrix *U=NULL,*V=NULL;
gsl_vector *w=NULL;
m = A->size1;
n = A->size2;
if (B == NULL) {
B = gsl_matrix_calloc (n,m);
}
U = gsl_matrix_calloc (m, n);
V = gsl_matrix_calloc (n, n);
w = gsl_vector_calloc (n);
/* singular value decomposition */
gsl_matrix_memcpy (U,A);
gsl_linalg_SV_decomp_jacobi(U,V,w);
gsl_matrix_set_zero(B);
k=0;
for (j=0; j<n; j++) {
if (fabs(w->data[j]) > 1.0e-6) k++;
}
if (k < 1) VError(" Design matrix is singular\n");
for (k=0; k<n; k++) {
for (l=0; l<m; l++) {
for (j=0; j<n; j++) {
u = gsl_vector_get(w,j);
if (fabs(u) > 1.0e-6) {
x = gsl_matrix_get(B,k,l);
x += gsl_matrix_get(V,k,j)*gsl_matrix_get(U,l,j)/u;
gsl_matrix_set(B,k,l,x);
}
}
}
}
gsl_matrix_free(U);
gsl_matrix_free(V);
gsl_vector_free(w);
return B;
}
| {
"alphanum_fraction": 0.5811320755,
"avg_line_length": 18.4027777778,
"ext": "c",
"hexsha": "aafd1c8740551e30413dcef0a1192a233d9b596d",
"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_2ndlevel/pseudoinv.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_2ndlevel/pseudoinv.c",
"max_line_length": 54,
"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_2ndlevel/pseudoinv.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": 468,
"size": 1325
} |
/* robust_wfun.c
*
* Copyright (C) 2013 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit.h>
/* default tuning constants */
#define TUNING_BISQUARE (4.685)
#define TUNING_CAUCHY (2.385)
#define TUNING_FAIR (1.4)
#define TUNING_HUBER (1.345)
#define TUNING_OLS (1.0)
#define TUNING_WELSCH (2.985)
/*
* Note: for each of the weighting functions below, it
* is safe to call them with in-place parameters, so that
* input/output vectors are the same
*/
static int
bisquare(const gsl_vector *r, gsl_vector *w)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
if (fabs(ri) < 1.0)
gsl_vector_set(w, i, (1.0 - ri*ri)*(1.0 - ri*ri));
else
gsl_vector_set(w, i, 0.0);
}
return GSL_SUCCESS;
} /* bisquare() */
static int
bisquare_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
if (fabs(ri) < 1.0)
gsl_vector_set(dpsi, i, (1.0 - ri*ri)*(1.0 - 5.0*ri*ri));
else
gsl_vector_set(dpsi, i, 0.0);
}
return GSL_SUCCESS;
} /* bisquare_dpsi() */
static const gsl_multifit_robust_type bisquare_type = {
"bisquare",
&bisquare,
&bisquare_dpsi,
TUNING_BISQUARE
};
static int
cauchy(const gsl_vector *r, gsl_vector *w)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
gsl_vector_set(w, i, 1.0 / (1.0 + ri*ri));
}
return GSL_SUCCESS;
} /* cauchy() */
static int
cauchy_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
double rsq = ri * ri;
gsl_vector_set(dpsi, i, (1 - rsq) / (1.0 + rsq) / (1.0 + rsq));
}
return GSL_SUCCESS;
} /* cauchy_dpsi() */
static const gsl_multifit_robust_type cauchy_type = {
"cauchy",
&cauchy,
&cauchy_dpsi,
TUNING_CAUCHY
};
static int
fair(const gsl_vector *r, gsl_vector *w)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
gsl_vector_set(w, i, 1.0 / (1.0 + fabs(ri)));
}
return GSL_SUCCESS;
} /* fair() */
static int
fair_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
gsl_vector_set(dpsi, i, 1.0 / (1.0 + fabs(ri)) / (1.0 + fabs(ri)));
}
return GSL_SUCCESS;
} /* fair_dpsi() */
static const gsl_multifit_robust_type fair_type = {
"fair",
&fair,
&fair_dpsi,
TUNING_FAIR
};
static int
huber(const gsl_vector *r, gsl_vector *w)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double absri = fabs(gsl_vector_get(r, i));
if (absri <= 1.0)
gsl_vector_set(w, i, 1.0);
else
gsl_vector_set(w, i, 1.0 / absri);
}
return GSL_SUCCESS;
} /* huber() */
static int
huber_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
if (fabs(ri) <= 1.0)
gsl_vector_set(dpsi, i, 1.0);
else
gsl_vector_set(dpsi, i, 0.0);
}
return GSL_SUCCESS;
} /* huber_dpsi() */
static const gsl_multifit_robust_type huber_type = {
"huber",
&huber,
&huber_dpsi,
TUNING_HUBER
};
static int
ols(const gsl_vector *r, gsl_vector *w)
{
gsl_vector_set_all(w, 1.0);
return GSL_SUCCESS;
}
static int
ols_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
gsl_vector_set_all(dpsi, 1.0);
return GSL_SUCCESS;
}
static const gsl_multifit_robust_type ols_type = {
"ols",
&ols,
&ols_dpsi,
TUNING_OLS
};
static int
welsch(const gsl_vector *r, gsl_vector *w)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
gsl_vector_set(w, i, exp(-ri*ri));
}
return GSL_SUCCESS;
} /* welsch() */
static int
welsch_dpsi(const gsl_vector *r, gsl_vector *dpsi)
{
size_t i;
size_t n = r->size;
for (i = 0; i < n; ++i)
{
double ri = gsl_vector_get(r, i);
gsl_vector_set(dpsi, i, (1.0 - 2.0*ri*ri) * exp(-ri*ri));
}
return GSL_SUCCESS;
} /* welsch_dpsi() */
static const gsl_multifit_robust_type welsch_type = {
"welsch",
&welsch,
&welsch_dpsi,
TUNING_WELSCH
};
const gsl_multifit_robust_type *gsl_multifit_robust_default = &bisquare_type;
const gsl_multifit_robust_type *gsl_multifit_robust_bisquare = &bisquare_type;
const gsl_multifit_robust_type *gsl_multifit_robust_cauchy = &cauchy_type;
const gsl_multifit_robust_type *gsl_multifit_robust_fair = &fair_type;
const gsl_multifit_robust_type *gsl_multifit_robust_huber = &huber_type;
const gsl_multifit_robust_type *gsl_multifit_robust_ols = &ols_type;
const gsl_multifit_robust_type *gsl_multifit_robust_welsch = &welsch_type;
| {
"alphanum_fraction": 0.6365054602,
"avg_line_length": 20.8267148014,
"ext": "c",
"hexsha": "af8d2c3e97eeb52fd870f0159760994da34c7573",
"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/robust_wfun.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/robust_wfun.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit/robust_wfun.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": 1957,
"size": 5769
} |
#ifndef IMAGE_H_YQCE0AWR
#define IMAGE_H_YQCE0AWR
#include <gsl/gsl>
#include <opencv2/core/mat.hpp>
#include <sens_loc/math/coordinate.h>
#include <type_traits>
namespace sens_loc::math {
namespace detail {
template <typename Number> // requires Number<Number>
inline int get_opencv_type() {
static_assert(std::is_arithmetic_v<Number>);
if constexpr (std::is_same<Number, float>::value)
return CV_32F; // NOLINT(bugprone-branch-clone)
else if constexpr (std::is_same<Number, double>::value)
return CV_64F;
else if constexpr (std::is_same<Number, uchar>::value)
return CV_8U;
else if constexpr (std::is_same<Number, schar>::value)
return CV_8S;
else if constexpr (std::is_same<Number, ushort>::value)
return CV_16U;
else if constexpr (std::is_same<Number, short>::value)
return CV_16S;
else
return -1;
}
} // namespace detail
/// This function encapsulates an \c cv::Mat and ensures the common
/// preconditions for this code base are enforced.
///
/// \invariant the image has only 1 channel.
/// \invariant the underlying data types are consistent
/// \invariant access is only done in \p pixel_coord<int>
///
/// \tparam PixelType the underlying type of the \c cv::Mat
/// \sa math::pixel_coord
template <typename PixelType = ushort>
class image {
public:
static_assert(std::is_arithmetic_v<PixelType>);
image() = default;
/// Construct the image from a \c cv::Mat and uphold the class invariant.
explicit image(const cv::Mat& image) noexcept
: _data(image) {
Expects(image.type() == detail::get_opencv_type<PixelType>());
Expects(image.channels() == 1);
Expects(!image.empty());
}
image(const image<PixelType>& other) = default;
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
image(image<PixelType>&& other) = default;
explicit image(cv::Mat&& other) noexcept
: _data(std::move(other)) {
Expects(_data.type() == detail::get_opencv_type<PixelType>());
Expects(_data.channels() == 1);
Expects(!_data.empty());
}
image<PixelType>& operator=(const image<PixelType>& other) = default;
image<PixelType>& operator=(const cv::Mat& other) noexcept {
Expects(other.type() == detail::get_opencv_type<PixelType>());
Expects(other.channels() == 1);
Expects(!other.empty());
_data = other;
return *this;
}
// NOLINTNEXTLINE(performance-noexcept-move-constructor)
image<PixelType>& operator=(image<PixelType>&& other) = default;
image<PixelType>& operator=(cv::Mat&& other) noexcept {
Expects(other.type() == detail::get_opencv_type<PixelType>());
Expects(other.channels() == 1);
Expects(!other.empty());
_data = std::move(other);
return *this;
}
~image() = default;
/// Return the width of the image.
[[nodiscard]] int w() const noexcept { return _data.cols; }
/// Return the height of the image.
[[nodiscard]] int h() const noexcept { return _data.rows; }
/// Read-Access in the image for some pixel \p p.
template <typename Number = int>
[[nodiscard]] PixelType at(const pixel_coord<Number>& p) const noexcept {
static_assert(std::is_arithmetic_v<Number>);
return _data.at<PixelType>(gsl::narrow_cast<int>(p.v()),
gsl::narrow_cast<int>(p.u()));
}
/// Write-Access in the image for some pixel \p p.
template <typename Number = int>
[[nodiscard]] PixelType& at(const pixel_coord<Number>& p) noexcept {
static_assert(std::is_arithmetic_v<Number>);
return _data.at<PixelType>(gsl::narrow_cast<int>(p.v()),
gsl::narrow_cast<int>(p.u()));
}
/// Get access to the underlying data to use it for normal cv operations.
[[nodiscard]] const cv::Mat& data() const noexcept { return _data; }
private:
cv::Mat _data;
};
template <typename TargetType, typename PixelType>
image<TargetType> convert(const image<PixelType>& img) noexcept {
static_assert(std::is_arithmetic_v<TargetType>);
static_assert(std::is_arithmetic_v<PixelType>);
if constexpr (std::is_same_v<TargetType, PixelType>)
return img; // NOLINT(bugprone-suspicious-semicolon)
cv::Mat tmp(img.h(), img.w(), detail::get_opencv_type<TargetType>());
img.data().convertTo(tmp, detail::get_opencv_type<TargetType>());
return math::image<TargetType>(std::move(tmp));
}
} // namespace sens_loc::math
#endif /* end of include guard: IMAGE_H_YQCE0AWR */
| {
"alphanum_fraction": 0.6519576033,
"avg_line_length": 34.7593984962,
"ext": "h",
"hexsha": "ef785e79326bd221f604649b3eed30aac836d7dd",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/include/sens_loc/math/image.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/include/sens_loc/math/image.h",
"max_line_length": 77,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/include/sens_loc/math/image.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 1182,
"size": 4623
} |
/* #define _XOPEN_SOURCE 500 */
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <inttypes.h>
#include <limits.h>
#ifndef SIZE_MAX
#define SIZE_MAX (~(size_t)0)
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
/* for open/close and other file io*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/*for sendfile (in-kernel file to file copy, supposedly very fast) */
#ifdef USE_SENDFILE
#include <sys/sendfile.h>
#endif
#if defined(USE_MMAP)
#include <sys/mman.h>
#elif defined(USE_SENDFILE)
#include <sys/sendfile.h>
#else
#endif
#ifdef USE_WRITEV
#ifndef USE_MMAP
#error USE_MMAP must be enabled with USE_WRITEV
#endif
#include <sys/uio.h>
#endif
#include <gsl/gsl_rng.h>
#include "macros.h"
#include "utils.h"
#include "progressbar.h"
#include "gadget_utils.h"
/* Copied straight from https://fossies.org/dox/gsl-2.2.1/shuffle_8c_source.html*/
/* Adapted to generate array indices. The returned random indices are in increasing order */
int gsl_ran_arr_index (const gsl_rng * r, size_t * dest, const size_t k, const size_t n)
{
/* Choose k out of n items, return an array x[] of the k items.
These items will preserve the relative order of the original
input -- you can use shuffle() to randomize the output if you
wish */
if (k > n) {
fprintf(stderr,"k=%zu is greater than n=%zu. Cannot sample more than n items\n",
k, n);
return EXIT_FAILURE;
}
if(k == n) {
for(size_t i=0;i<n;i++) {
dest[i] = i;
}
} else {
size_t j=0;
for (size_t i = 0; i < n && j < k; i++) {
if ((n - i) * gsl_rng_uniform (r) < k - j) {
dest[j] = i;
j++ ;
}
}
}
return EXIT_SUCCESS;
}
int write_random_subsample_of_field(int in_fd, int out_fd, off_t in_offset, off_t out_offset, const int dest_npart, const size_t itemsize, size_t *random_indices
#ifdef USE_MMAP
,char *in_memblock
#endif
)
{
#ifdef USE_MMAP
in_memblock += in_offset;//These are here so that I don't lose the original pointer from mmap
#endif
#ifndef USE_MMAP
size_t buf[itemsize];
#endif
int interrupted=0;
#ifndef _OPENMP
init_my_progressbar(dest_npart,&interrupted);
#endif
#ifdef USE_WRITEV
//vector writes. Loop has to be re-written in units of IOV_MAX
for(int i=0;i<dest_npart;i+=IOV_MAX) {
#ifndef _OPENMP
my_progressbar(i,&interrupted);//progress-bar will be jumpy
#endif
const int nleft = ((dest_npart - i) > IOV_MAX) ? IOV_MAX:(dest_npart - i);
struct iovec iov[IOV_MAX];
for(int j=0;j<nleft;j++){
const size_t ind = random_indices[j];
const size_t offset_in_field = ind * itemsize;
iov[j].iov_base = in_memblock + offset_in_field;
iov[j].iov_len = itemsize;
}
random_indices += nleft;
ssize_t bytes_written = writev(out_fd, iov, nleft);
XRETURN(bytes_written == nleft*itemsize, EXIT_FAILURE, "Expected to write bytes = %zu but wrote %zd instead\n",nleft*itemsize, bytes_written);
}
#else //Not using WRITEV -> 3 options here i) MMAP + write ii) sendfile iii) pread + write
for(int i=0;i<dest_npart;i++) {
#ifndef _OPENMP
my_progressbar(i,&interrupted);
#endif
const size_t ind = random_indices[i];
size_t offset_in_field = ind * itemsize;
#if defined(USE_MMAP)
ssize_t bytes_written = write(out_fd, in_memblock + offset_in_field, itemsize);
#elif defined(USE_SENDFILE)
off_t input_offset = in_offset + offset_in_field;
ssize_t bytes_written = sendfile(out_fd, in_fd, &input_offset, itemsize);
#else
ssize_t bytes_read = pread(in_fd, &buf, itemsize, in_offset + offset_in_field);
XRETURN(bytes_read == itemsize, EXIT_FAILURE, "Expected to read bytes = %zu but read %zd instead\n",itemsize, bytes_read);
ssize_t bytes_written = write(out_fd, &buf, itemsize);
#endif//default case (pread + write)
XRETURN(bytes_written == itemsize, EXIT_FAILURE, "Expected to write bytes = %zu but wrote %zd instead\n",itemsize, bytes_written);
out_offset += itemsize;
}
#endif //end of WRITEV
#ifndef _OPENMP
finish_myprogressbar(&interrupted);
#endif
return EXIT_SUCCESS;
}
int subsample_single_gadgetfile(const int dest_npart, const char *inputfile, const char *outputfile, const size_t id_bytes, const gsl_rng *rng, const double fraction, const int64_t nparttotal)
{
if(dest_npart <= 0) {
fprintf(stderr,"Error: Desired number of particles =%d in the subsampled file must be > 0\n",dest_npart);
return EXIT_FAILURE;
}
struct timespec tstart, t0, t1;
current_utc_time(&tstart);
int in_fd=-1;
int out_fd=-1;
int status = EXIT_FAILURE;
in_fd = open(inputfile, O_RDONLY);
if(in_fd < 0) {
fprintf(stderr,"Error (in function %s, line # %d) while opening input file = `%s'\n",__FUNCTION__,__LINE__,inputfile);
perror(NULL);
return EXIT_FAILURE;
}
#ifdef USE_MMAP
struct stat sb;
if(fstat(in_fd, &sb) < 0) {
perror(NULL);
return EXIT_FAILURE;
}
char *in_memblock = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, in_fd, 0);
#endif
//Check that that the output file does not exist.
{
FILE *fp = fopen(outputfile,"r");
if(fp != NULL) {
fclose(fp);
fprintf(stderr,"Warning: Output file = `%s' should not exist. "
"Aborting so as to avoid accidentally over-writing regular fles\n",outputfile);
return EXIT_FAILURE;
}
}
out_fd = open(outputfile, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);//set the mode since the file is being created
if(out_fd < 0) {
fprintf(stderr,"Error (in function %s, line # %d) while opening output file = `%s'\n",__FUNCTION__,__LINE__, outputfile);
perror(NULL);
return EXIT_FAILURE;
}
/* Reserve disk-space for dest_npart particles, written as a fortran binary */
const size_t pos_vel_itemsize = sizeof(float)*3;
const off_t header_disk_size = 4 + sizeof(struct io_header) + 4; //header
const off_t pos_disk_size = 4 + pos_vel_itemsize*dest_npart + 4; //all 3 positions for each particle
const off_t vel_disk_size = 4 + pos_vel_itemsize*dest_npart + 4; //all 3 velocities for each particle
const off_t id_disk_size = 4 + id_bytes*dest_npart + 4;//all particle IDs
/* These are all of the fields to be written */
const off_t outputfile_size = header_disk_size + pos_disk_size + vel_disk_size + id_disk_size;
status = posix_fallocate(out_fd, 0, outputfile_size);
if(status < 0) {
fprintf(stderr,"Error: Could not reserve disk space for %d particles (output file: `%s', expected file-size on disk = %zu bytes)\n",
dest_npart, outputfile, (size_t) outputfile_size);
perror(NULL);
return status;
}
struct io_header hdr;
int dummy1=0,dummy2=0;
const off_t pos_start_offset = header_disk_size + 4;
const off_t vel_start_offset = header_disk_size + pos_disk_size + 4;
const off_t id_start_offset = header_disk_size + pos_disk_size + vel_disk_size + 4;
read(in_fd, &dummy1, 4);
read(in_fd, &hdr, sizeof(struct io_header));
read(in_fd, &dummy2, 4);
if(dummy1 != 256 || dummy2 != 256) {
fprintf(stderr,"Error: Padding bytes for header = %d (front) and %d (end) should be exactly 256\n",dummy1, dummy2);
return EXIT_FAILURE;
}
#ifdef USE_MMAP
if(fraction == 1.0) {
XRETURN(dest_npart == hdr.npart[1],EXIT_FAILURE,
"for fraction = 1.0, input npart = %d must equal subsampled npart = %d\n",hdr.npart[1], dest_npart);
/* XRETURN(sb.st_size == outputfile_size, EXIT_FAILURE, */
/* "for fraction = 1.0, input (=%zu bytes) and output file sizes (=%zu bytes) must be the same",sb.st_size, outputfile_size); */
}
#endif
for(int type=0;type<6;type++) {
if(type==1) {
continue;
}
/* There should only be dark-matter particles */
if(hdr.npart[type] > 0) {
fprintf(stderr,"Error: Input file `%s' contains %d particles of type=%d. This code only works for dark-matter only simulations\n",
inputfile, hdr.npart[type], type);
return EXIT_FAILURE;
}
}
/* The number of subsampled particles wanted can at most be the numbers present in the file*/
if(dest_npart > hdr.npart[1]) {
fprintf(stderr,"Error: Number of subsampled particles = %d exceeds the number of particles in the file = %d\n",
dest_npart, hdr.npart[1]);
return EXIT_FAILURE;
}
struct io_header out_hdr = hdr;
out_hdr.npart[1] = dest_npart;
out_hdr.npartTotal[1] = nparttotal;
out_hdr.npartTotalHighWord[1] = (nparttotal >> 32);
out_hdr.mass[1] /= fraction;
write(out_fd, &dummy1, sizeof(dummy1));
write(out_fd, &out_hdr, sizeof(struct io_header));
write(out_fd, &dummy2, sizeof(dummy2));
//create an array of random indices
size_t *random_indices = calloc(dest_npart, sizeof(*random_indices));
status = gsl_ran_arr_index(rng, random_indices, (size_t) dest_npart, (size_t) hdr.npart[1]);
//write positions
current_utc_time(&t0);
int posvel_disk_size=pos_vel_itemsize*dest_npart;
write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));
status = write_random_subsample_of_field(in_fd, out_fd, pos_start_offset, -1,dest_npart, pos_vel_itemsize, random_indices
#ifdef USE_MMAP
,in_memblock
#endif
);
if(status != EXIT_SUCCESS) {
return status;
}
write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));
current_utc_time(&t1);
double pos_time = REALTIME_ELAPSED_NS(t0,t1)*1e-9;
//write velocities
write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));
status = write_random_subsample_of_field(in_fd, out_fd, vel_start_offset, -1,dest_npart, pos_vel_itemsize, random_indices
#ifdef USE_MMAP
,in_memblock
#endif
);
if(status != EXIT_SUCCESS) {
return status;
}
write(out_fd, &posvel_disk_size, sizeof(posvel_disk_size));
current_utc_time(&t0);
double vel_time = REALTIME_ELAPSED_NS(t1, t0)*1e-9;
//write ids
int id_size = id_bytes * dest_npart;
write(out_fd, &id_size, sizeof(id_size));
status = write_random_subsample_of_field(in_fd, out_fd, vel_start_offset, -1,dest_npart, id_bytes, random_indices
#ifdef USE_MMAP
,in_memblock
#endif
);
if(status != EXIT_SUCCESS) {
return status;
}
write(out_fd, &id_size, sizeof(id_size));
current_utc_time(&t1);
double id_time = REALTIME_ELAPSED_NS(t0,t1)*1e-9;
free(random_indices);
//close the input file -> we are only reading, unlikely to be error
close(in_fd);
#ifdef USE_MMAP
munmap(in_memblock, sb.st_size);
#endif
//check for error code here since disk quota might be hit
status = close(out_fd);
if(status != EXIT_SUCCESS){
fprintf(stderr,"Error while closing output file = `%s'\n",outputfile);
perror(NULL);
return status;
}
current_utc_time(&t1);
/* fprintf(stderr,"Done with file. Total time taken = %8.4lf seconds (pos_time = %6.3e vel_time = %6.3e id_time = %6.3e seconds)\n",REALTIME_ELAPSED_NS(tstart,t1)*1e-9, */
/* pos_time,vel_time,id_time); */
return EXIT_SUCCESS;
}
int main(int argc,char **argv)
{
const char argnames[][100]={"fraction","input file","output file"};
int nargs=sizeof(argnames)/(sizeof(char)*100);
char input_filename[MAXLEN];
char output_filename[MAXLEN];
struct timespec tstart,t0,t1;
int64_t nparticles_written=0,nparticles_withmass=0;
const gsl_rng_type * rng_type = gsl_rng_ranlxd1;
gsl_rng * all_procs_rng = gsl_rng_alloc(rng_type);
unsigned long seed = 42;
int64_t TotNumPart;
current_utc_time(&tstart);
if (argc != 4 ) {
fprintf(stderr,"ERROR: %s usage - <fraction> <gadget snapshot name> <output filename>\n",argv[0]);
fprintf(stderr,"Each file will be subsampled to get (roughly) that fraction for each particle-type\n");
fprintf(stderr,"\nFound: %d parameters\n ",argc-1);
int i;
for(i=1;i<argc;i++) {
if(i <= nargs)
fprintf(stderr,"\t\t %s = `%s' \n",argnames[i-1],argv[i]);
else
fprintf(stderr,"\t\t <> = `%s' \n",argv[i]);
}
if(i <= nargs) {
fprintf(stderr,"\nMissing required parameters: \n");
for(i=argc;i<=nargs;i++)
fprintf(stderr,"\t\t %20s = `?'\n",argnames[i-1]);
}
fprintf(stderr,"\n\n");
exit(EXIT_FAILURE);
}
double fraction = atof(argv[1]);
XRETURN(fraction > 0 && fraction <= 1.0, EXIT_FAILURE, "Subsample fraction = %lf needs to be in (0,1]", fraction);
strncpy(input_filename,argv[2],MAXLEN);
strncpy(output_filename,argv[3],MAXLEN);
XRETURN(strncmp(input_filename,output_filename,MAXLEN) != 0, EXIT_FAILURE, "Input filename = `%s' and output filename = `%s' are the same",input_filename, output_filename);
const int nfiles = get_gadget_nfiles(input_filename);
struct io_header header = get_gadget_header(input_filename);
TotNumPart = get_Numpart(&header);
XRETURN(header.npartTotal[0] == 0 && header.npartTotalHighWord[0] == 0, EXIT_FAILURE, "Subsampling will not work with gas particles");
fprintf(stderr,"Running `%s' on %d files with the following parameters \n",argv[0],nfiles);
fprintf(stderr,"\n\t\t ---------------------------------------------\n");
for(int i=1;i<=nargs;i++) {
fprintf(stderr,"\t\t %-25s = %s \n",argnames[i-1],argv[i]);
}
#ifdef _OPENMP
#pragma omp parallel
{
int nthreads = omp_get_num_threads();
int tid = omp_get_thread_num();
if(tid == 0)
fprintf(stderr,"\t\t %-25s = %d \n","nthreads", nthreads);
}
#endif
fprintf(stderr,"\t\t ---------------------------------------------\n\n");
if(SIZE_MAX != 0xFFFFFFFFFFFFFFFF) {
fprintf(stderr,"Error: SIZE_MAX=%zu should be (2^64-1)\n", SIZE_MAX);
return EXIT_FAILURE;
}
size_t id_bytes;
int interrupted=0;
size_t seedtable[nfiles];
int64_t nparttotal=0;
fprintf(stderr,"Checking all input files ...\n");
init_my_progressbar(nfiles, &interrupted);
for(int ifile=0;ifile<nfiles;ifile++) {
seedtable[ifile] = SIZE_MAX * gsl_rng_uniform(all_procs_rng);
char inputfile[MAXLEN];
my_snprintf(inputfile,MAXLEN,"%s.%d",input_filename, ifile);
if(ifile == 0) {
id_bytes = get_gadget_id_bytes(inputfile);
fprintf(stderr,"Gadget ID bytes = %zu\n",id_bytes);
interrupted=1;
}
struct io_header hdr = get_gadget_header(inputfile);
const int dest_npart = fraction * hdr.npart[1];
XRETURN((int) (dest_npart*3*sizeof(float)) < INT_MAX, EXIT_FAILURE,
"Padding bytes will overflow, please reduce the value of fraction (currently, fraction = %lf)\n",fraction);
my_progressbar(ifile,&interrupted);
nparttotal += dest_npart;
}
finish_myprogressbar(&interrupted);
fprintf(stderr,"Checking all input files .....done\n\n");
int numdone=0, errorflag=0, savestatus=0;
init_my_progressbar(nfiles, &interrupted);
#ifdef _OPENMP
#pragma omp parallel shared(numdone, savestatus)
{
int nthreads = omp_get_num_threads();
int tid = omp_get_thread_num();
#pragma omp for schedule(dynamic)
#endif
for(int ifile=0;ifile<nfiles;ifile++) {
if(errorflag == 0) {
//Setup the rng
gsl_rng * rng = gsl_rng_alloc(rng_type);
gsl_rng_set(rng, seedtable[ifile]);
#ifdef _OPENMP
#pragma omp atomic
numdone++;
if(tid == 0)
#endif
my_progressbar(numdone,&interrupted);
char inputfile[MAXLEN],outputfile[MAXLEN];
my_snprintf(inputfile,MAXLEN,"%s.%d",input_filename,ifile);
my_snprintf(outputfile, MAXLEN,"%s.%d",output_filename,ifile);
struct io_header hdr = get_gadget_header(inputfile);
const int dest_npart = fraction * hdr.npart[1];
int status = subsample_single_gadgetfile(dest_npart, inputfile, outputfile, id_bytes, rng, fraction, nparttotal);
if(status != EXIT_SUCCESS) {
savestatus = status;
errorflag = 1;
}
gsl_rng_free(rng);
/* #ifdef _OPENMP */
/* #pragma omp critical(info) */
/* { */
/* #endif */
/* fprintf(stderr,"Wrote %d subsampled particles out of %d particles (%d/%d files).\n", */
/* dest_npart, hdr.npart[1], ifile+1,nfiles); */
/* interrupted=1; */
/* #ifdef _OPENMP */
/* }//critical region */
/* #endif */
}//errorflag == 0 condition
}//for loop over nfiles
#ifdef _OPENMP
}//omp parallel region
#endif
gsl_rng_free(all_procs_rng);
finish_myprogressbar(&interrupted);
if(errorflag != 0) {
return savestatus;
}
current_utc_time(&t1);
fprintf(stderr,"subsample_Gadget> Done. Wrote %"PRId64" particles to file `%s'. Time taken = %6.2lf mins\n",
nparttotal,output_filename,REALTIME_ELAPSED_NS(tstart, t1)*1e-9/60.0);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6632371098,
"avg_line_length": 33.220703125,
"ext": "c",
"hexsha": "c1970769ffb1e49c496bab2d42a0c5b165a423bc",
"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": "7255a48ba531110bdb55ad34d8749aca7fec3ced",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "manodeep/subsampleGadget",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7255a48ba531110bdb55ad34d8749aca7fec3ced",
"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": "manodeep/subsampleGadget",
"max_issues_repo_path": "main.c",
"max_line_length": 192,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7255a48ba531110bdb55ad34d8749aca7fec3ced",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "manodeep/subsampleGadget",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4673,
"size": 17009
} |
#pragma once
#include "bits_of_matcha/engine/memory/Buffer.h"
#include "bits_of_matcha/engine/iterations/MatrixwiseBinaryCtx.h"
#include <cblas.h>
namespace matcha::engine::cpu {
void mm(engine::Buffer* a, engine::Buffer* b, engine::Buffer* c, const MatrixwiseBinaryCtx& ctx) {
size_t sizeA = ctx.rowsA * ctx.colsA;
size_t sizeB = ctx.rowsB * ctx.colsB;
size_t sizeC = ctx.rowsA * ctx.colsB;
dynamic_cast<Buffer*>(a);
dynamic_cast<Buffer*>(b);
dynamic_cast<Buffer*>(c);
auto valsA = a->as<float*>();
auto valsB = b->as<float*>();
auto valsC = c->as<float*>();
int strides = (int) ctx.prefixStridesA.size();
std::vector<unsigned> beginA(strides, 0);
std::vector<unsigned> beginB(strides, 0);
std::vector<unsigned> beginC(strides, 0);
auto iterC = valsC;
int counter = 0;
int axis = 1;
while (true) {
// if (counter++ > 20) exit(69);
if (axis < strides - 1) {
print("==========");
print("axis ", axis, " beginC ", beginC[axis], " stridesC ", ctx.prefixStridesC[axis - 1]);
// print("axis: ", axis, " (strides ", strides, ")");
// print("strides: ", ctx.prefixStridesA[axis], " ", ctx.prefixStridesB[axis], " -> ", ctx.prefixStridesC[axis]);
// print("begins: ", beginA[axis], " ", beginB[axis], " -> ", beginC[axis]);
// print("BC: ", beginC[axis], " ", beginC[axis - 1] + ctx.prefixStridesC[axis - 1]);
// print("beginC ", beginC[axis]);
if (beginC[axis] == beginC[axis - 1] + ctx.prefixStridesC[axis - 1]) {
// print("-> dec axis");
if (axis == 1) break;
axis--;
} else {
beginA[axis + 1] = beginA[axis];
beginB[axis + 1] = beginB[axis];
beginC[axis + 1] = beginC[axis];
beginA[axis] += ctx.prefixStridesA[axis];
beginB[axis] += ctx.prefixStridesB[axis];
beginC[axis] += ctx.prefixStridesC[axis];
// print("-> inc axis");
axis++;
}
} else {
if (axis >= strides) {
axis = strides - 1;
}
// print(ctx.prefixStridesC[axis - 1]);
// print(beginA[axis]);
auto matA = valsA + beginA[axis] * sizeA;
auto matB = valsB + beginB[axis] * sizeB;
auto loops = axis - 1 >= 0 ? ctx.prefixStridesC[axis - 1] : 1;
for (auto itC = 0; itC != loops; itC++) {
auto matC = valsC + (beginC[axis] + itC) * sizeC;
// print(matA - valsA, " ", matB - valsB, " -> ", matC - valsC);
///*
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
(int) ctx.rowsA,
(int) ctx.colsB,
(int) ctx.colsA,
1,
matA,
(int) ctx.colsA,
matB,
(int) ctx.colsB,
0,
matC,
(int) ctx.colsB
);
// */
matA += sizeA * ctx.prefixStridesA[axis];
matB += sizeB * ctx.prefixStridesB[axis];
}
// print("blas");
if (axis <= 1) break;
axis--;
}
}
}
}
| {
"alphanum_fraction": 0.5368562773,
"avg_line_length": 28.0283018868,
"ext": "h",
"hexsha": "0bd45697f775aedb24de078374143e393df197e2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-17T12:14:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-17T12:14:27.000Z",
"max_forks_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "matcha-ai/matcha",
"max_forks_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408",
"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": "matcha-ai/matcha",
"max_issues_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "matcha-ai/matcha",
"max_stars_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 898,
"size": 2971
} |
/* Pre-requisites for the package regression */
#include "config.h"
#ifdef HAVE_GSL_HEADER
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_vector.h>
#include "R.h"
#if _CUDA_
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <cublas.h>
#include <cula_blas.h>
#include <cula.h>
#endif
#if _CUDA_
#define PREC float
#define PREC_EPS FLT_EPSILON
#define GSL_TYPE(type) gsl_ ## type ## _float
#define GSL_FUNCTION(type,name) gsl_ ## type ## _float_ ## name
#define GSL_STATS_FUNCTION(name) gsl_stats ## _float_ ## name
#define MATHS_FUNCTION(name) name ## f
#define SVD_FUNCTION svdAnyMatCuda
#define BLAS_FUNCTION(name) my_cula_s ## name
#define MY_FUNCTION(name) my_cula_ ## name
#define UGAUSSIAN_FUNCTION my_ugaussian_function
#define GSL_BLAS_FUNCTION(name) gsl_blas_s ## name
#define PREPARE_FUNCTION(name) prepare ## name ## ForCoordinateDescentCuda
#define PREC_DIFF -4
#else
#define PREC double
#define PREC_EPS DBL_EPSILON
#define GSL_TYPE(type) gsl_ ## type
#define GSL_FUNCTION(type,name) gsl_ ## type ## _ ## name
#define GSL_STATS_FUNCTION(name) gsl_stats ## _ ## name
#define MATHS_FUNCTION(name) name
#define SVD_FUNCTION svdAnyMat
#define BLAS_FUNCTION(name) gsl_blas_d ## name
#define MY_FUNCTION(name) my_gsl_ ## name
#define UGAUSSIAN_FUNCTION gsl_cdf_ugaussian_P
#define GSL_BLAS_FUNCTION(name) gsl_blas_d ## name
#define PREPARE_FUNCTION(name) prepare ## name ## ForCoordinateDescent
#define PREC_DIFF -6
#endif
#endif
| {
"alphanum_fraction": 0.7546106557,
"avg_line_length": 28.2898550725,
"ext": "h",
"hexsha": "bf047b41c7e52cc45ccb3a6b9f094ce26a5aea81",
"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": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_forks_repo_licenses": [
"OLDAP-2.4"
],
"max_forks_repo_name": "dfrankow/ridge-cran",
"max_forks_repo_path": "src/depends.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"OLDAP-2.4"
],
"max_issues_repo_name": "dfrankow/ridge-cran",
"max_issues_repo_path": "src/depends.h",
"max_line_length": 75,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "78183d367b6e43aa93b629248450d001b6bb58ef",
"max_stars_repo_licenses": [
"OLDAP-2.4"
],
"max_stars_repo_name": "dfrankow/ridge-cran",
"max_stars_repo_path": "src/depends.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-05T13:56:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-05T13:56:56.000Z",
"num_tokens": 576,
"size": 1952
} |
/*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @brief scale codec
* @file Scale.h
*/
#pragma once
#include "Common.h"
#include "ScaleDecoderStream.h"
#include "ScaleEncoderStream.h"
#include <boost/system/system_error.hpp>
#include <boost/throw_exception.hpp>
#include <gsl/span>
#include <vector>
namespace bcos
{
namespace codec
{
namespace scale
{
/**
* @brief convenience function for encoding primitives data to stream
* @tparam Args primitive types to be encoded
* @param args data to encode
* @return encoded data
*/
template <typename... Args>
void encode(std::shared_ptr<bytes> _encodeData, Args&&... _args)
{
ScaleEncoderStream s;
(s << ... << std::forward<Args>(_args));
*_encodeData = s.data();
}
template <typename... Args>
bytes encode(Args&&... _args)
{
ScaleEncoderStream s;
(s << ... << std::forward<Args>(_args));
return s.data();
}
/**
* @brief convenience function for decoding primitives data from stream
* @tparam T primitive type that is decoded from provided span
* @param span of bytes with encoded data
* @return decoded T
*/
template <class T>
void decode(T& _decodedObject, gsl::span<byte const> _span)
{
ScaleDecoderStream s(_span);
s >> _decodedObject;
}
template <class T>
T decode(gsl::span<byte const> _span)
{
T t;
decode(t, _span);
return t;
}
} // namespace scale
} // namespace codec
} // namespace bcos
| {
"alphanum_fraction": 0.6988011988,
"avg_line_length": 25.3417721519,
"ext": "h",
"hexsha": "7b320e3c7bb3f7e7b592cc393a420b50f24318e0",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2021-12-06T06:41:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-22T03:47:01.000Z",
"max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "xueying4402/FISCO-BCOS",
"max_forks_repo_path": "bcos-framework/libcodec/scale/Scale.h",
"max_issues_count": 267,
"max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_issues_repo_issues_event_max_datetime": "2021-09-17T08:18:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-01T02:12:17.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "xueying4402/FISCO-BCOS",
"max_issues_repo_path": "bcos-framework/libcodec/scale/Scale.h",
"max_line_length": 76,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "xueying4402/FISCO-BCOS",
"max_stars_repo_path": "bcos-framework/libcodec/scale/Scale.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z",
"num_tokens": 499,
"size": 2002
} |
/**
*
* @file core_dsetvar.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:49 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_double
*
* CORE_dsetvar sets a single variable, x := alpha.
*
*******************************************************************************
*
* @param[in] alpha
* Scalar to set x to, passed by pointer so it can depend on runtime value.
*
* @param[out] x
* On exit, x = alpha.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dsetvar = PCORE_dsetvar
#define CORE_dsetvar PCORE_dsetvar
#endif
void CORE_dsetvar(const double *alpha, double *x)
{
*x = *alpha;
}
| {
"alphanum_fraction": 0.5034414946,
"avg_line_length": 24.8048780488,
"ext": "c",
"hexsha": "23c0d85255e074a71fd5777c201097e780952ed6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_dsetvar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_dsetvar.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_dsetvar.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 246,
"size": 1017
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
int main()
{
//set up some data
int n=300;
float* x = malloc( n*sizeof(float) );
float* y = malloc( n*sizeof(float) );
for( int i=0; i<n; ++i )
{
x[i]=i+1;
y[i]=(i+1)*(i+1);
}
//calculate y = a*x + y
float a=7.0f;
int incx=1;
int incy=1;
cblas_saxpy( n, a, x, incx, y, incy );
//check it
int status = 0;
for( int i=0; i<n; ++i )
{
float expected = 7.0f*(i+1) + (i+1)*(i+1);
if( fabs( y[i]/expected - 1 )>1e-4 ){
printf("error matching element i=%d expected=%g received=%g\n",i+1,expected,y[i]);
status=-1;
break;
}
}
//free data
free(x);
free(y);
return status;
}
| {
"alphanum_fraction": 0.4708798017,
"avg_line_length": 18.3409090909,
"ext": "c",
"hexsha": "332dd426b29eb4769788ff7b848bb5a5a6ef44d7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-10-03T12:13:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-03T12:13:36.000Z",
"max_forks_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "murraypurves/BootsOnTheGround",
"max_forks_repo_path": "src/CBLAS/test/tstCBLAS.c",
"max_issues_count": 14,
"max_issues_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32",
"max_issues_repo_issues_event_max_datetime": "2017-08-27T21:52:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-19T17:56:04.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "murraypurves/BootsOnTheGround",
"max_issues_repo_path": "src/CBLAS/test/tstCBLAS.c",
"max_line_length": 94,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "15acc4ed064e368f6af5114408f1be8a62749f32",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "murraypurves/BootsOnTheGround",
"max_stars_repo_path": "src/CBLAS/test/tstCBLAS.c",
"max_stars_repo_stars_event_max_datetime": "2018-08-09T11:53:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-02-01T00:39:29.000Z",
"num_tokens": 280,
"size": 807
} |
#ifndef QDM_MCMC_H
#define QDM_MCMC_H 1
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <hdf5.h>
#include "ijk.h"
#include "tau.h"
typedef struct {
const gsl_rng *rng;
size_t burn;
size_t iter;
size_t thin;
size_t acc_check;
size_t spline_df;
const gsl_vector *xi;
const gsl_vector *ll;
const gsl_vector *tau;
const gsl_matrix *theta;
double xi_prior_mean;
double xi_prior_var;
double xi_tune_sd;
double theta_min;
double theta_tune_sd;
const gsl_vector *x;
const gsl_vector *y;
const qdm_tau *t;
const gsl_vector *m_knots;
bool truncate;
} qdm_mcmc_parameters;
typedef struct {
gsl_vector *xi;
gsl_vector *xi_acc;
gsl_vector *xi_p;
gsl_vector *xi_tune;
gsl_vector *ll;
gsl_vector *ll_p;
gsl_vector *tau;
gsl_vector *tau_p;
gsl_matrix *theta;
gsl_matrix *theta_acc;
gsl_matrix *theta_p;
gsl_matrix *theta_star;
gsl_matrix *theta_star_p;
gsl_matrix *theta_tune;
} qdm_mcmc_workspace;
typedef struct {
size_t s;
qdm_ijk *theta;
qdm_ijk *theta_star;
qdm_ijk *ll;
qdm_ijk *tau;
qdm_ijk *xi;
} qdm_mcmc_results;
typedef struct {
qdm_mcmc_parameters p;
qdm_mcmc_workspace w;
qdm_mcmc_results r;
} qdm_mcmc;
qdm_mcmc *
qdm_mcmc_alloc(
qdm_mcmc_parameters p
);
void
qdm_mcmc_free(
qdm_mcmc *mcmc
);
int
qdm_mcmc_run(
qdm_mcmc *mcmc
);
int
qdm_mcmc_next(
qdm_mcmc *mcmc
);
int
qdm_mcmc_update_theta(
qdm_mcmc *mcmc
);
int
qdm_mcmc_update_xi(
qdm_mcmc *mcmc
);
void
qdm_mcmc_update_tune(
qdm_mcmc *mcmc
);
int
qdm_mcmc_save(
qdm_mcmc *mcmc,
size_t k
);
int
qdm_mcmc_write(
hid_t id,
const qdm_mcmc *mcmc
);
int
qdm_mcmc_read(
hid_t id,
qdm_mcmc **mcmc
);
#endif /* QDM_MCMC_H */
| {
"alphanum_fraction": 0.7056179775,
"avg_line_length": 13.1851851852,
"ext": "h",
"hexsha": "e1c53634f6fc4e09aa52a94ec934c9e93dc09ee0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/mcmc.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/mcmc.h",
"max_line_length": 28,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/mcmc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 609,
"size": 1780
} |
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include "su3_matrix.c"
#ifndef gauge_config
#include "config.h"
#define gauge_config 1
#define sq(x) ((x)*(x))
#define cb(x) ((x)*(x)*(x))
#endif
int acc, tot; // acceptance rate
#define FORWARD 1 //true
#define BACKWARD 0 //false
// Access pattern methods --------------------------------------------------
// index of link site=(t,x,y,z) in direction dir
int index(const int* site, int dir){
return dir+site[0]*4+site[1]*N*4+site[2]*N*N*4+site[3]*N*N*N*4;
}
// shift site array by one to direction dir
void shift(int* site, int dir, int forward){
if(forward == 1){
site[dir] = (site[dir]+1)%N;
}else{
site[dir] = (site[dir]-1+N)%N;
}
}
// spatial rotation by 90deg of shape array
void rotate(int n, int* shape){
for(int i=0;i<n;i++){
if(shape[i]==1) shape[i]=2;
if(shape[i]==2) shape[i]=3;
if(shape[i]==3) shape[i]=1;
}
}
// end of access pattern methods -------------------------------------------
// Plaquette methods -------------------------------------------------------
// plaquette operator at site (t,x,y,z) in plane (mu,nu)
// normally mu>nu
double plaquette(const su3_matrix* links, int mu, int nu, int* site){
su3_matrix A,B,C,D;
A = links[index(site,mu)];
shift(site,mu,FORWARD);
B = links[index(site,nu)];
shift(site,mu,BACKWARD);
shift(site,nu,FORWARD);
C = su3_inv(links[index(site,mu)]);
shift(site,nu,BACKWARD); // restore site position
D = su3_inv(links[index(site,nu)]);
A = su3_mul(A,B);
A = su3_mul(A,C);
A = su3_mul(A,D);
return su3_trace(A)/3.0;
}
// plaquette spatial mean
double plaq_mean_s(int t, const su3_matrix* links){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
for(int mu=1;mu<4;mu++){
for(int nu=mu+1;nu<4;nu++){
mean += plaquette(links,mu,nu,site);
}
}
}
}
}
return mean/ (3*N*N*N); // 3 directions & N^3 sites
}
// end of plaquette methods ------------------------------------------------
// Metropolis update --------------------------------------------------------
void do_hb_update(su3_matrix* links, const gsl_rng* r, const su3_matrix* rands, int* site, int dir);
double action(su3_matrix* links, int* site, int dir);
// the big loop
void hb_update(su3_matrix* links, const gsl_rng* r, const su3_matrix* rands){
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
for(int dir=0;dir<4;dir++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
do_hb_update(links,r,rands,site,dir);
}
}
}
}
}
}
// update
void do_hb_update(su3_matrix* links, const gsl_rng* r, const su3_matrix* rands, int* site, int dir){
if(verbose) {printf("Updating {%d, %d, %d, %d} direction %d",site[0],site[1],site[2],site[3],dir);getchar();}
double dS,action_old;
su3_matrix link_old;
for(int times=0; times<Nk; times++){
action_old = action(links,site,dir);
link_old = links[index(site,dir)];
links[index(site,dir)]=su3_mul(links[index(site,dir)],rands[gsl_rng_uniform_int(r, 50)]);
dS = action(links,site,dir)-action_old;
if(verbose) {printf("Old action = %f, ",action_old); su3_print(link_old); getchar();}
if(verbose) {printf("New action = %f, ",action_old+dS); su3_print(links[index(site,dir)]); getchar();}
acc++;tot++;
if(dS>0){
if(exp(-dS)<gsl_rng_uniform(r)){
acc--;
links[index(site,dir)]=link_old; // revert update
if(verbose) {printf("Reverted"); getchar();}
}
}
}
}
// calculating the action
// for each direction we need to find plaquette at 2 sites in each of the 3 planes
// mu > nu
double action(su3_matrix* links, int* site, int dir){
int mu,nu;
double result=0;
for(int k=0; k<4; k++){
if(k==dir) continue; // loop over planes
if(k>dir){mu=k; nu=dir;} // mu=larger number
if(k<dir){mu=dir; nu=k;}
result += plaquette(links, mu,nu,site);
shift(site,k,BACKWARD); // shift to the perpendicular direction backwards
result += plaquette(links, mu,nu,site);
shift(site,k,FORWARD); // shift it back
}
return -beta*result;
}
// end of heat bath update -------------------------------------------------
// Loops -------------------------------------------------------------------
// Generic loop ------------------------------------------------------------
// TODO: not working
double gloop(int n, int* shape, const su3_matrix* links, int* site){
su3_matrix A[2*n];
// forward
for(int i=0;i<n;i++){
A[i]=links[index(site,shape[i])];
shift(site,shape[i],FORWARD);
}
// backward
for(int i=0;i<n;i++){
shift(site,shape[i],BACKWARD);
A[n+i]=su3_inv(links[index(site,shape[i])]);
}
// multiply
for(int i=1;i<2*n;i++){
A[0]=su3_mul(A[0],A[i]);
}
return su3_trace(A[0])/3.0;
}
double loop(int r, int t, int mu, int nu, const su3_matrix* links, int* site){
int shape[r+t];
for(int i=0;i<t;i++)shape[i]=nu;
for(int i=0;i<r;i++)shape[t+i]=mu;
return gloop(r+t,shape,links,site);
/*
su3_matrix A[(r+t)*2];
// bottom side
for(int i=0;i<t;i++){
A[i]=links[index(site,nu)];
shift(site,nu,FORWARD);
}
// right side
for(int i=0;i<r;i++){
A[t+i]=links[index(site,mu)];
shift(site,mu,FORWARD);
}
// top side
for(int i=0;i<t;i++){
shift(site,nu,BACKWARD);
A[t+r+i]=su3_inv(links[index(site,nu)]);
}
// left side
for(int i=0;i<r;i++){
shift(site,mu,BACKWARD);
A[t+r+t+i]=su3_inv(links[index(site,mu)]);
}
// multiply
for(int i=1;i<2*(r+t);i++){
A[0]=su3_mul(A[0],A[i]);
}
return su3_trace(A[0])/3.0;*/
}
// end of Loop -------------------------------------------------------------
// Wilson loop -------------------------------------------------------------
double wloop(int r, int t, int mu,const su3_matrix* links, int* site){
return loop(r, t, mu, 0, links, site);
}
double wloop_mean(int wR, int wT, const su3_matrix* links){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
for(int mu=1;mu<4;mu++){
mean += wloop(wR,wT,mu,links,site);
}
}
}
}
}
return mean/ (3*N*N*N*N); // 3 directions & N^3 sites
}
// end of Wilson loop ------------------------------------------------------
// Polyakov loop -----------------------------------------------------------
double polyakov(const su3_matrix* links, int* site){
su3_matrix A[N];
for(int i=0;i<N;i++){
A[i]=links[index(site,0)];
shift(site,0,FORWARD);
}
// multiply
for(int i=1;i<N;i++){
A[0]=su3_mul(A[0],A[i]);
}
return su3_trace(A[0])/3.0;
}
double polyakov_mean(const su3_matrix* links){
double mean = 0;
int site[4];
site[0]=0;
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
site[1]=x; site[2]=y; site[3]=z;
mean += polyakov(links,site);
}
}
}
return mean/ (N*N*N);
}
// end of Polyakov loop ----------------------------------------------------
// Twisted Wilson loop -----------------------------------------------------
// Ref: Lepage p.33
// r=sqrt(2)
double twloop2(int t, int mu, int nu ,const su3_matrix* links, int* site){
su3_matrix A[(2+t)*2];
// bottom side
for(int i=0;i<t;i++){
A[i]=links[index(site,0)];
shift(site,0,FORWARD);
}
// right side, twisted
A[t+0]=links[index(site,mu)];
shift(site,mu,FORWARD);
A[t+1]=links[index(site,nu)];
shift(site,nu,FORWARD);
// top side
for(int i=0;i<t;i++){
shift(site,0,BACKWARD);
A[t+2+i]=su3_inv(links[index(site,0)]);
}
// left side, twisted
shift(site,mu,BACKWARD);
A[t+2+t+0]=su3_inv(links[index(site,mu)]);
shift(site,nu,BACKWARD);
A[t+2+t+1]=su3_inv(links[index(site,nu)]);
// multiply
for(int i=1;i<2*(2+t);i++){
A[0]=su3_mul(A[0],A[i]);
}
return su3_trace(A[0])/3.0;
}
double twloop2_mean(int wT, const su3_matrix* links){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
for(int mu=1;mu<4;mu++){
for(int nu=1;nu<4;nu++){
if(mu!=nu){
mean += twloop2(wT,mu,nu,links,site);
}
}
}
}
}
}
}
return mean/ (6*N*N*N*N); // 3 x 2 directions & N^3 sites
}
// r=sqrt(3)
double twloop3(int t, const su3_matrix* links, int* site){
su3_matrix A[(3+t)*2];
// bottom side
for(int i=0;i<t;i++){
A[i]=links[index(site,0)];
shift(site,0,FORWARD);
}
// right side, twisted
A[t+0]=links[index(site,1)];
shift(site,1,FORWARD);
A[t+1]=links[index(site,2)];
shift(site,2,FORWARD);
A[t+2]=links[index(site,3)];
shift(site,3,FORWARD);
// top side
for(int i=0;i<t;i++){
shift(site,0,BACKWARD);
A[t+3+i]=su3_inv(links[index(site,0)]);
}
// left side, twisted
shift(site,1,BACKWARD);
A[t+3+t+0]=su3_inv(links[index(site,1)]);
shift(site,2,BACKWARD);
A[t+3+t+1]=su3_inv(links[index(site,2)]);
shift(site,3,BACKWARD);
A[t+3+t+2]=su3_inv(links[index(site,3)]);
// multiply
for(int i=1;i<2*(3+t);i++){
A[0]=su3_mul(A[0],A[i]);
}
return su3_trace(A[0])/3.0;
}
double twloop3_mean(int wT, const su3_matrix* links){
double mean = 0;
int site[4];
for(int z=0;z<N;z++){
for(int y=0;y<N;y++){
for(int x=0;x<N;x++){
for(int t=0;t<N;t++){
site[0]=t; site[1]=x; site[2]=y; site[3]=z;
mean += twloop3(wT,links,site);
}
}
}
}
return mean/ (N*N*N*N); // N^3 sites
}
// end of twisted Wilson loop --------------------------------------------
// Plaquette correlator
double plaq_corr(int T, const su3_matrix* links){
double mean=0;
for(int i=0;i<N;i++){
mean+=plaq_mean_s(i,links)*plaq_mean_s(i+T,links);
}
return mean/N;
}
// end of plaquette correlator
// TODO: vvvvvvvv
// Smeared Wilson loop ---------------------------------------------------
// end of smeared Wilson loop --------------------------------------------
| {
"alphanum_fraction": 0.5270143072,
"avg_line_length": 24.6496519722,
"ext": "c",
"hexsha": "ef00f148ab1da9ce3ebea1af0d82a8ea01ab3a89",
"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": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "uchuutamashi/lqcd",
"max_forks_repo_path": "su3/su3_utils.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "uchuutamashi/lqcd",
"max_issues_repo_path": "su3/su3_utils.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "uchuutamashi/lqcd",
"max_stars_repo_path": "su3/su3_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3333,
"size": 10624
} |
#include <pygsl/solver.h>
#include <pygsl/rng.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
const char * filename = __FILE__;
PyObject *module = NULL;
static const char monte_f_type_name[] = "F-monte";
static const char module_doc[] = "XXX Missing";
static const char PyGSL_monte_type[] = "monte";
enum PyGSL_gsl_monte_type{
PyGSL_MONTE_plain = 1,
PyGSL_MONTE_miser = 2,
PyGSL_MONTE_vegas = 3
};
struct _monte_csys{
enum PyGSL_gsl_monte_type type;
};
typedef struct _monte_csys monte_csys;
static double
PyGSL_g_test(double *k, size_t dim, void *params)
{
double A = 1.0 / (M_PI * M_PI * M_PI);
return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));
}
static double
PyGSL_monte_function_wrap(double *x, size_t dim, void *params)
{
double tmp, *dresult;
int dimension;
PyGSL_solver *s;
PyArrayObject *a_array = NULL;
PyObject *result = NULL, *arglist=NULL, *callback, *retval;
PyGSL_error_info info;
/* the line number to appear in the traceback */
int trb_lineno = -1, i;
struct pygsl_array_cache * cache_ptr;
gsl_vector_view view;
FUNC_MESS_BEGIN();
s = (PyGSL_solver *) params;
/*
flag = PyGSL_function_wrap_On_O(&view.vector, s->cbs[0], s->args,
&tmp, NULL, view.vector.size,
"monte_wrap");
*/
FUNC_MESS_BEGIN();
callback = s->cbs[0];
assert(s->args != NULL);
assert(callback != NULL);
/* Do I need to copy the array ??? */
for(i = 2; i < PyGSL_SOLVER_N_ARRAYS; ++i){
cache_ptr = &(s->cache[i]);
if(cache_ptr->ref == NULL)
/* no array found */
break;
if(x == cache_ptr->data){
a_array = cache_ptr->ref;
break;
}
}
if(i >= PyGSL_SOLVER_N_ARRAYS){
trb_lineno = __LINE__ -1;
pygsl_error("Not enough space to cache arrays...", filename, trb_lineno, GSL_ESANITY);
goto fail;
}
if(a_array == NULL){
dimension = dim;
a_array = (PyArrayObject *) PyArray_FromDimsAndData(1, &dimension, PyArray_DOUBLE, (char *)x);
cache_ptr->ref = a_array;
cache_ptr->data = x;
/*
* Required for deallocation.
* Tuples steal the references. But this array will be dereferenced by the
* normal procedure!
*/
Py_INCREF(a_array);
}
if (a_array == NULL){
trb_lineno = __LINE__ - 2;
goto fail;
}
/* arglist was already set up */
result = (PyObject *) s->cache[1].ref;
dresult = (double *) s->cache[1].data;
arglist = (PyObject *) s->cache[0].ref;
Py_INCREF(s->args);
PyTuple_SET_ITEM(arglist, 0, (PyObject *) a_array);
PyTuple_SET_ITEM(arglist, 1, s->args);
/*
arglist = Py_BuildValue("(OOO)", a_array, s->args, result);
if(DEBUG > 2){
fprintf(stderr, "callback = %p, arglist = %p\n", callback, arglist);
}
*/
FUNC_MESS(" Call Python Object BEGIN");
retval = PyEval_CallObject(callback, arglist);
FUNC_MESS(" Call Python Object END");
/*
info.callback = callback;
info.message = __FUNCTION__;
if(PyGSL_CHECK_PYTHON_RETURN(retval, 0, &info) != GSL_SUCCESS){
trb_lineno = __LINE__ - 1;
goto fail;
}
info.argnum = 1;
DEBUG_MESS(3, "result was %e", *dresult);
*/
FUNC_MESS_END();
return *dresult;
fail:
PyGSL_add_traceback(NULL, __FILE__, __FUNCTION__, trb_lineno);
FUNC_MESS("Failure");
if(s->isset == 1){
longjmp(s->buffer, GSL_EFAILED);
FUNC_MESS("\t\t Using jump buffer");
} else {
FUNC_MESS("\t\t Jump buffer was not defined!");
}
tmp = gsl_nan();
return tmp;
}
static PyObject *
PyGSL_monte_init(PyGSL_solver *self, PyObject *args)
{
int flag = GSL_EFAILED;
monte_csys * csys;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
csys = (monte_csys *)self->c_sys;
assert(csys);
switch(csys->type){
case PyGSL_MONTE_plain:
flag = gsl_monte_plain_init(self->solver);
break;
case PyGSL_MONTE_miser:
flag = gsl_monte_miser_init(self->solver);
break;
case PyGSL_MONTE_vegas:
flag = gsl_monte_vegas_init(self->solver);
break;
default:
DEBUG_MESS(2, "Monte type %d unknown",flag);
PyGSL_ERROR_NULL("Unknown monte type!", GSL_ESANITY);
}
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
return NULL;
}
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
}
typedef int (*pygsl_monte_fptr_t)(gsl_monte_function * F, double XL[], double XU[], size_t DIM,
size_t CALLS, gsl_rng * R, gsl_monte_plain_state * S,
double * RESULT, double * ABSERR);
static PyObject *
PyGSL_monte_integrate(PyGSL_solver *self, PyObject *args)
{
int flag = GSL_EFAILED, line, dim;
unsigned int ncalls;
monte_csys * csys;
gsl_rng * rng;
PyObject *func=NULL, *xlo=NULL, *xuo=NULL, *rng_obj=NULL, *ncallso=NULL, *argso=NULL;
PyArrayObject *xla=NULL;
PyArrayObject *xua=NULL;
double result, abserr;
gsl_monte_function mfunc;
pygsl_monte_fptr_t fptr;
FUNC_MESS_BEGIN();
assert(PyGSL_solver_check(self));
if(!PyArg_ParseTuple(args, "OOOOO|O", &func, &xlo, &xuo, &ncallso, &rng_obj, &argso)){
line = __LINE__ - 1;
goto fail;
}
if(!PyCallable_Check(func)){
line = __LINE__ - 1;
pygsl_error("The function argument must be callable!", filename, line, GSL_EINVAL);
goto fail;
}
if(PyGSL_PYLONG_TO_UINT(ncallso, &ncalls, NULL) != GSL_SUCCESS){
line = __LINE__ - 1;
goto fail;
}
if(!PyGSL_RNG_Check(rng_obj)){
line = __LINE__ - 1;
pygsl_error("The rng object must be a rng!", filename, line, GSL_EINVAL);
goto fail;
}
rng = ((PyGSL_rng *) rng_obj)->rng;
xla = PyGSL_vector_check(xlo, -1, PyGSL_DARRAY_CINPUT(2), NULL, NULL);
if(xla == NULL){
line = __LINE__ - 2;
goto fail;
}
dim = xla->dimensions[0];
xua = PyGSL_vector_check(xuo, dim, PyGSL_DARRAY_CINPUT(3), NULL, NULL);
if(xua == NULL){
line = __LINE__ - 2;
goto fail;
}
if(argso == NULL){
Py_INCREF(Py_None);
argso = Py_None;
}
Py_XDECREF(self->cbs[0]);
Py_INCREF(func);
self->cbs[0] = func;
self->args = argso;
csys = (monte_csys *)self->c_sys;
switch(csys->type){
case PyGSL_MONTE_plain: fptr = (pygsl_monte_fptr_t)&gsl_monte_plain_integrate; break;
case PyGSL_MONTE_miser: fptr = (pygsl_monte_fptr_t)&gsl_monte_miser_integrate; break;
case PyGSL_MONTE_vegas: fptr = (pygsl_monte_fptr_t)&gsl_monte_vegas_integrate; break;
default:
line = __LINE__ - 5;
DEBUG_MESS(2, "Monte type %d unknown",flag);
pygsl_error("Unknown monte type!", filename, line, GSL_ESANITY);
goto fail;
}
assert(fptr);
mfunc.f = &PyGSL_monte_function_wrap;
mfunc.f = &PyGSL_g_test;
mfunc.dim = dim;
mfunc.params = self;
if(setjmp(self->buffer) != 0){
self->isset = 0;
line = __LINE__ - 2;
goto fail;
}else{
self->isset = 1;
}
flag = fptr(&mfunc, (double *) xla->data, (double *)xua->data,
dim, ncalls, rng, self->solver, &result, &abserr);
self->isset = 0;
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
line = __LINE__ - 2;
return NULL;
}
Py_DECREF(xla); xla = NULL;
Py_DECREF(xua); xua = NULL;
Py_DECREF(self->cbs[0]);
Py_DECREF(self->args);
self->cbs[0] = NULL;
self->args = NULL;
FUNC_MESS_END();
return Py_BuildValue("dd", result, abserr);
fail:
FUNC_MESS("FAIL");
Py_XDECREF(xla);
Py_XDECREF(xua);
Py_XDECREF(self->cbs[0]);
Py_XDECREF(self->args);
self->cbs[0] = NULL;
self->args = NULL;
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
return NULL;
}
#define GET_SET(montetype, name, mode) \
static PyObject * GetSet_ ## montetype ## _ ## name(PyGSL_solver *self, PyObject *args) \
{ \
gsl_monte_## montetype ## _state *state = self->solver; \
return PyGSL_solver_GetSet((PyObject *)self, args, &(state->name), mode); \
}
#define GET_SET_DOUBLE(mintype, name) GET_SET(mintype, name, PyGSL_MODE_DOUBLE)
#define GET_SET_SIZE_T(mintype, name) GET_SET(mintype, name, PyGSL_MODE_SIZE_T)
#define GET_SET_INT(mintype, name) GET_SET(mintype, name, PyGSL_MODE_INT)
GET_SET_DOUBLE(miser, estimate_frac)
GET_SET_SIZE_T(miser, min_calls)
GET_SET_SIZE_T(miser, min_calls_per_bisection)
GET_SET_DOUBLE(miser, alpha)
GET_SET_DOUBLE(miser, dither)
GET_SET_DOUBLE(vegas, result)
GET_SET_DOUBLE(vegas, sigma)
GET_SET_DOUBLE(vegas, chisq)
GET_SET_DOUBLE(vegas, alpha)
GET_SET_SIZE_T(vegas, iterations)
GET_SET_INT(vegas, stage)
GET_SET_INT(vegas, mode)
GET_SET_INT(vegas, verbose)
#undef GET_SET_DOUBLE
#undef GET_SET_SIZE_T
#undef GET_SET_INT
#undef GET_SET
#define GETSET(montetype, name, mode) {#name, (PyCFunction) GetSet_ ## montetype ## _ ## name, METH_VARARGS, NULL},
#define GET_SET_DOUBLE(montetype, name) GETSET(montetype, name, 0)
#define GET_SET_INT(montetype, name) GETSET(montetype, name, 0)
#define GET_SET_SIZE_T(montetype, name) GETSET(montetype, name, 0)
#define MONTE_STANDARD_METHODS \
{"init", (PyCFunction)PyGSL_monte_init, METH_VARARGS, NULL}, \
{"integrate", (PyCFunction)PyGSL_monte_integrate, METH_VARARGS, NULL}, \
static PyMethodDef PyGSL_monte_plain_methods[] = {
MONTE_STANDARD_METHODS
{NULL, NULL, 0, NULL}
};
static PyMethodDef PyGSL_monte_miser_methods[] = {
MONTE_STANDARD_METHODS
GET_SET_DOUBLE(miser, estimate_frac)
GET_SET_SIZE_T(miser, min_calls)
GET_SET_SIZE_T(miser, min_calls_per_bisection)
GET_SET_DOUBLE(miser, alpha)
GET_SET_DOUBLE(miser, dither)
{NULL, NULL, 0, NULL}
};
static PyMethodDef PyGSL_monte_vegas_methods[] = {
MONTE_STANDARD_METHODS
GET_SET_DOUBLE(vegas, result)
GET_SET_DOUBLE(vegas, sigma)
GET_SET_DOUBLE(vegas, chisq)
GET_SET_DOUBLE(vegas, alpha)
GET_SET_SIZE_T(vegas, iterations)
GET_SET_INT(vegas, stage)
GET_SET_INT(vegas, mode)
GET_SET_INT(vegas, verbose)
{NULL, NULL, 0, NULL}
};
/* make the init look similar to the one */
static void *
PyGSL_gsl_monte_alloc(void * type, int n)
{
enum PyGSL_gsl_monte_type flag = (enum PyGSL_gsl_monte_type) type;
void * result = NULL;
FUNC_MESS_BEGIN();
switch(flag){
case PyGSL_MONTE_plain:
result = gsl_monte_plain_alloc(n);
break;
case PyGSL_MONTE_miser:
result = gsl_monte_miser_alloc(n);
break;
case PyGSL_MONTE_vegas:
result = gsl_monte_vegas_alloc(n);
break;
default:
DEBUG_MESS(2, "Monte type %d unknown",flag);
PyGSL_ERROR_NULL("Unknown monte type!", GSL_ESANITY);
}
FUNC_MESS_END();
return result;
}
const struct _SolverStatic
monte_plain_solver_f = {{(void_m_t) gsl_monte_plain_free,
(void_m_t) NULL,
NULL,
NULL},
1, PyGSL_monte_plain_methods, PyGSL_monte_type},
monte_miser_solver_f = {{(void_m_t) gsl_monte_miser_free,
(void_m_t) NULL,
NULL,
NULL},
1, PyGSL_monte_miser_methods, PyGSL_monte_type},
monte_vegas_solver_f = {{(void_m_t) gsl_monte_vegas_free,
(void_m_t) NULL,
NULL,
NULL},
1, PyGSL_monte_vegas_methods, PyGSL_monte_type};
static PyObject*
PyGSL_init_monte(PyObject *self, PyObject *args, int type, const struct _SolverStatic *sost)
{
PyGSL_solver *result = NULL;
struct pygsl_array_cache *tmp;
int line = -1, dims;
monte_csys * csys;
PyObject *mytuple;
FUNC_MESS_BEGIN();
const solver_alloc_struct alloc = {(const void *) type, (void *) PyGSL_gsl_monte_alloc, sost};
result = (PyGSL_solver *) PyGSL_solver_dn_init(self, args, &alloc, 1);
if(result == NULL){
line = __LINE__ - 2;
goto fail;
}
csys = (monte_csys *) calloc(1, sizeof(monte_csys));
if(csys == NULL){
PyErr_NoMemory();
line = __LINE__ - 1;
goto fail;
}
dims = 1;
tmp = result->cache;
tmp[1].ref = PyGSL_New_Array(1, &dims, PyArray_DOUBLE);
tmp[1].data = (double *) tmp[1].ref->data;
mytuple = PyTuple_New(3);
PyTuple_SetItem(mytuple, 2, (PyObject *) tmp[1].ref);
/*
* Required for deallocation.
* Tuples steal the references. But this array will be dereferenced by the
* normal procedure!
*/
Py_INCREF(tmp[1].ref);
Py_INCREF(tmp[1].ref);
/*
* Initalise the others
*/
Py_INCREF(Py_None);
Py_INCREF(Py_None);
Py_INCREF(Py_None);
Py_INCREF(Py_None);
PyTuple_SetItem(mytuple, 0, Py_None);
PyTuple_SetItem(mytuple, 1, Py_None);
tmp[0].ref = (PyArrayObject*) mytuple;
result->cache = tmp;
csys->type = type;
result->c_sys = csys;
FUNC_MESS_END();
return (PyObject *) result;
fail:
FUNC_MESS("Fail");
Py_XDECREF(result);
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__);
return NULL;
}
#define MONTE_INIT(name) \
static PyObject* PyGSL_init_ ## name(PyObject * self, PyObject *args) \
{ return PyGSL_init_monte(self, args, PyGSL_MONTE_ ##name, &monte_ ## name ## _solver_f); }
MONTE_INIT(plain)
MONTE_INIT(miser)
MONTE_INIT(vegas)
static PyMethodDef mMethods[] = {
{"plain", PyGSL_init_plain, METH_VARARGS, NULL},
{"miser", PyGSL_init_miser, METH_VARARGS, NULL},
{"vegas", PyGSL_init_vegas, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
void
initmonte(void)
{
PyObject* m, *dict, *item;
FUNC_MESS_BEGIN();
m=Py_InitModule("monte", mMethods);
module = m;
assert(m);
dict = PyModule_GetDict(m);
if(!dict)
goto fail;
init_pygsl()
import_pygsl_solver();
assert(PyGSL_API);
if (!(item = PyString_FromString((char*)module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
goto fail;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
goto fail;
}
PyModule_AddIntConstant(m, "GSL_VEGAS_MODE_IMPORTANCE", GSL_VEGAS_MODE_IMPORTANCE);
PyModule_AddIntConstant(m, "GSL_VEGAS_MODE_IMPORTANCE_ONLY", GSL_VEGAS_MODE_IMPORTANCE_ONLY);
PyModule_AddIntConstant(m, "GSL_VEGAS_MODE_STRATIFIED", GSL_VEGAS_MODE_STRATIFIED);
FUNC_MESS_END();
return;
fail:
FUNC_MESS("FAIL");
return;
}
| {
"alphanum_fraction": 0.646130831,
"avg_line_length": 27.7471698113,
"ext": "c",
"hexsha": "6ca5a06119e17608e0563d2644a925e0856f920b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/monte.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4447,
"size": 14706
} |
#if !defined(XFORMCVSSTATUS_H_INCLUDED)
#define XFORMCVSSTATUS_H_INCLUDED
#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <map>
#include <string>
class XformCvsStatus
{
public:
static int usage(::std::ostream& strm, const ::std::string& progName,
const char* pMsg);
XformCvsStatus(::gsl::span<const char*const> args);
int run();
XformCvsStatus(const XformCvsStatus&) = delete;
XformCvsStatus& operator=(const XformCvsStatus&) = delete;
XformCvsStatus(XformCvsStatus&&) = delete;
XformCvsStatus& operator=(XformCvsStatus&&) = delete;
private:
using Path = ::std::filesystem::path;
using FileToStatusMap = ::std::map<Path, ::std::string>;
void insertInMap(const ::std::string& file, const ::std::string& status);
Path buildPath(const ::std::string& file) const;
static ::std::string xlateStatus(const ::std::string& status);
static ::std::string pathStringToConsoleString(const Path::string_type& str);
bool m_suppressNew;
bool m_suppressUpToDate;
bool m_suppressLocal;
Path m_lastWorkingDir;
FileToStatusMap m_map;
};
#endif // XFORMCVSSTATUS_H_INCLUDED
| {
"alphanum_fraction": 0.7363717605,
"avg_line_length": 26.6428571429,
"ext": "h",
"hexsha": "0099e68f8e0f1b187e0020a0bc5508ee1131ec15",
"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": "XformCvsStatus.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": "XformCvsStatus.h",
"max_line_length": 78,
"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": "XformCvsStatus.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 312,
"size": 1119
} |
// A rectangular block of data of type float. A transparent block
// cache is used for each instance of this class if necessary, so the
// image can be much bigger than will fit in memory, and pixels can
// still be accessed and written efficiently, provided subsequent
// accesses are spatially correlated. A variety of useful methods are
// implemented (filtering, subsetting, interpolating, etc.)
//
// Don't try to access the same instance concurrently. Split your
// images up into separate instances if you must parallelize things.
//
// For many methods, arguments of type ssize_t are used, but are not
// allowed to be negative. This is to help prevent people from
// shooting themselves in the foor by accidently passing negative
// values which don't yield warnings and can't be caught with
// assertions.
#ifndef FLOAT_IMAGE_H
#define FLOAT_IMAGE_H
#ifndef solaris
# include <stdint.h>
#endif
#include "asf_meta.h"
#include <stdio.h>
#include <sys/types.h>
#include <glib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_histogram.h>
// sometimes we don't have this - choose a conservative value
#ifndef SSIZE_MAX
#define SSIZE_MAX 32767
#endif
// Instance structure. Everything here is private and need not be
// used or understood by client code, except for the size_x and size_y
// fields.
typedef struct {
size_t size_x, size_y; // Image dimensions.
size_t cache_space; // Memory cache space in bytes.
size_t cache_area; // Memory cache area in pixels.
size_t tile_size; // Tile size in pixels on a side.
size_t cache_size_in_tiles; // Number of tiles in cache.
size_t tile_count_x; // Number of tiles in image in x direction.
size_t tile_count_y; // Number of tiles in image in y direction.
size_t tile_count; // Total number of tiles in image.
size_t tile_area; // Area of a tile, in pixels.
float *cache; // Memory cache.
float **tile_addresses; // Addresss of individual tiles in the cache.
GQueue *tile_queue; // Queue of tile offsets kept in load order.
FILE *tile_file; // File with tiles stored contiguously.
GString *tile_file_name; // Name of the tile file
int reference_count; // For optional reference counting.
} FloatImage;
///////////////////////////////////////////////////////////////////////////////
//
// Creating New Instances
//
// Includeing methods which create new instances by copying existing
// ones.
//
///////////////////////////////////////////////////////////////////////////////
// Thaw out a previously frozen instance (produced with
// float_image_freeze) using data pointed to by file_pointer. Frozen
// instances aren't portable between platforms. After thawing
// file_pointer points to the data immediately following the data from
// the thawed instance (or to the end of the file).
FloatImage *
float_image_thaw (FILE *file_pointer);
// Create a new image filled with zero pixel values.
FloatImage *
float_image_new (ssize_t size_x, ssize_t size_y);
// Create a new image with pixels initialized to value.
FloatImage *
float_image_new_with_value (ssize_t size_x, ssize_t size_y, float value);
// Create a new image from memory. This pixels are assumed to be
// layed out in memory in the usual way, i.e. contiguous rows of
// pixels in the x direction are contiguous in memory.
FloatImage *
float_image_new_from_memory (ssize_t size_x, ssize_t size_y, float *buffer);
// Create a new independent copy of model.
FloatImage *
float_image_copy (FloatImage *model);
// Form reduced resolution version of the model. The scale_factor
// must be positive and odd. The new image will be round ((double)
// model->size_x / scale_factor) pixels by round ((double)
// model->size_y / scale_factor) pixels. Scaling is performed by
// averaging blocks of pixels together, using odd pixel reflection
// around the image edges (see the description of the apply_kernel
// method). The upper and leftmost blocks of pixels averaged together
// are always centered at the 0 index in the direction in question, so
// reflection is always used for these edges. Whether reflection is
// used for the right and lower edges depends on the relationship
// between the model dimensions and the scale factor.
FloatImage *
float_image_new_from_model_scaled (FloatImage *model, ssize_t scale_factor);
// Create a new image by copying the portion of model with upper left
// corner at model coordinates (x, y), width size_x, and height
// size_y.
FloatImage *
float_image_new_subimage (FloatImage *model, ssize_t x, ssize_t y,
ssize_t size_x, ssize_t size_y);
// Type used to specify whether disk files should be in big or little
// endian byte order.
typedef enum {
FLOAT_IMAGE_BYTE_ORDER_LITTLE_ENDIAN=1,
FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN
} float_image_byte_order_t;
// Create a new image from data at byte offset in file. The pixel
// layout in the file is assumed to be the same as for the
// float_image_new_from_memory method. The byte order of individual
// pixels in the file should be byte_order.
FloatImage *
float_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,
off_t offset, float_image_byte_order_t byte_order);
// The method is like new_from_file, but takes a file pointer instead
// of a file name, and the offset argument is with respect to the
// current position in the file_pointer stream.
FloatImage *
float_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,
FILE *file_pointer, off_t offset,
float_image_byte_order_t byte_order);
// Form a low quality reduced resolution version of the
// original_size_x by original_size_y image in file. The new image
// will be size_x by size_y pixels. This method is like new_from_file
// method, but gets its data by sampling in each dimension using
// bilinear interpolation. This is a decent way of forming quick
// thumbnails of images, or of scaling images down just slightly (by a
// factor of say 1.5 or less), but not much else.
FloatImage *
float_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,
ssize_t original_size_x,
ssize_t original_size_y,
const char *file, off_t offset,
float_image_byte_order_t byte_order);
// The function that does it all, generating an instance of FloatImage
// from a file and the metadata
FloatImage *
float_image_new_from_metadata(meta_parameters *meta, const char *file);
// For multi-band imagery the previous function needs to be more specific.
FloatImage *
float_image_band_new_from_metadata(meta_parameters *meta,
int band, const char *file);
// Sample type of an image that is to be used to create a float_image
// instance. For example, floating point image can be created from
// signed sixteen bit integer data.
typedef enum {
FLOAT_IMAGE_SAMPLE_TYPE_SIGNED_TWO_BYTE_INTEGER=1,
FLOAT_IMAGE_SAMPLE_TYPE_UNSIGNED_BYTE
} float_image_sample_type;
// Form a new image by reading a data file full of sample_type
// samples. The integer sample type are converted to floating point
// values by simple assignment (i.e. C assignment semantics apply,
// which for the smaller integer types should mean than an exact
// floating point representation is possible). The other arguments
// are like those of the new_from_file method.
FloatImage *
float_image_new_from_file_with_sample_type
(ssize_t size_x, ssize_t size_y, const char *file, off_t offset,
float_image_byte_order_t byte_order, float_image_sample_type sample_type);
// This method is to new_from_file_with_sample_type as
// new_from_file_pointer is to new_from_file.
FloatImage *
float_image_new_from_file_pointer_with_sample_type
(ssize_t size_x, ssize_t size_y, FILE *file_pointer, off_t offset,
float_image_byte_order_t byte_order, float_image_sample_type sample_type);
///////////////////////////////////////////////////////////////////////////////
//
// Getting and Setting Image Pixels and Regions
//
///////////////////////////////////////////////////////////////////////////////
// Get pixel at 0-indexed position x, y. A cache is used so pixel
// access does not usually involve the hard disk, provided subsequent
// pixel lookups are spatially close together. You can probably get
// away with trating this function just as if everything was in
// memory. For details, see the cache control methods below.
//
// The x and y arguments should always be positive, ssize_t is used
// only so people can't as easily shoot themselves in the foot by
// accidently supplying negative arguments which get promoted in some
// strange way.
float
float_image_get_pixel (FloatImage *self, ssize_t x, ssize_t y);
// Set pixel at 0-indexed position x, y to value. A cache is used to
// make this fast, as for the float_image_get_pixel method.
void
float_image_set_pixel (FloatImage *self, ssize_t x, ssize_t y, float value);
// Get rectangular image region of size_x, size_y having upper left
// corner at x, y and copy it into already allocated buffer. There is
// not necessarily any caching help for this method, i.e. it may
// always involve disk access and always be slow.
void
float_image_get_region (FloatImage *self, ssize_t x, ssize_t y,
ssize_t size_x, ssize_t size_y, float *buffer);
// This method is analogous to float_image_get_region.
void
float_image_set_region (FloatImage *self, size_t x, size_t y, size_t size_x,
size_t size_y, float *buffer);
// Get a full row of pixels, copying the data into already allocated
// buffer. This method will be fast on the average for calls with
// sequential row numbers.
void
float_image_get_row (FloatImage *self, size_t row, float *buffer);
// Get a pixel, performing odd reflection at image edges if the pixel
// indicies fall outside the image. See the description of the
// apply_kernel method for an explanation of reflection.
float
float_image_get_pixel_with_reflection (FloatImage *self, ssize_t x, ssize_t y);
///////////////////////////////////////////////////////////////////////////////
//
// Image Analysis and Statistics
//
///////////////////////////////////////////////////////////////////////////////
// Default mask value when figuring image stats
#define FLOAT_IMAGE_DEFAULT_MASK (0.0)
// Finds the minimum and maximum pixel values in the image, and the
// mean and standard deviation of all pixels. This function considers
// every pixel in the image when mask is NAN, otherwise it discounts
// all values within .00000000001 of the mask
void
float_image_statistics (FloatImage *self, float *min, float *max, float *mean,
float *standard_deviation, float mask);
// Does the same thing as float_image_statistics() but for only one selected
// band within a multi-band float image. Returns 1 on error, otherwise 0
int
float_image_band_statistics(FloatImage *self, meta_stats *stats,
int line_count, int band_no,
float mask);
// This method works like the statistics method, except values in the
// interval [interval_start, interval_end] are not considered at all
// for the purposes of determining any of the outputs.
void
float_image_statistics_with_mask_interval (FloatImage *self, float *min,
float *max, float *mean,
float *standard_deviation,
double interval_start,
double interval_end);
// Compute an efficient estimate of the mean and standard deviation of
// the pixels in the image, by sampling every stride th pixel in each
// dimension, beginning with pixel (0, 0). If the mask is a non-NAN
// value, this function will discount all values within .00000000001
// of the mask
void
float_image_approximate_statistics (FloatImage *self, size_t stride,
float *mean, float *standard_deviation,
float mask);
// This method is a logical combination of the
// statistics_with_mask_interval and approximate_statistics methods.
void
float_image_approximate_statistics_with_mask_interval
(FloatImage *self, size_t stride, float *mean, float *standard_deviation,
double interval_start, double interval_end);
// Creates a gsl_histogram with 'num_bins' bins evenly spaced between
// 'min' and 'max'. This function considers every pixel in the image.
gsl_histogram *
float_image_gsl_histogram (FloatImage *self, float min, float max,
size_t num_bins);
///////////////////////////////////////////////////////////////////////////////
//
// Kernels, Interpolation, and Sampling
//
///////////////////////////////////////////////////////////////////////////////
// Apply kernel centerd at pixel x, y and return the value. The
// kernel matrix must be have equal odd dimensions. The values in the
// kernel are multiplied by the pixels, and the sum of the products
// returned. When part of the kernel would fall outside the image
// extents, the values used for the out-of-image pixels are the mirror
// images of the corresponding in-image pixels, with the edge pixels
// not duplicated, i.e. reflection about the middle of the edge pixels
// is used.
float
float_image_apply_kernel (FloatImage *self, ssize_t x, ssize_t y,
gsl_matrix_float *kernel);
// Type used to specify whether disk files should be in big or little
// endian byte order.
// Sample method types. These dictate how nearby pixels are
// considered when we want to find the approximate value for a point
// which falls between pixel indicies.
typedef enum {
// Nearest pixel.
FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR,
// Linearly weited average of four nearest pixels
FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR,
// Bicubic spline interpolation (which consideres the nearest 16 pixels).
FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC
} float_image_sample_method_t;
float
float_image_sample (FloatImage *self, float x, float y,
float_image_sample_method_t sample_method);
///////////////////////////////////////////////////////////////////////////////
//
// Comparing Images
//
///////////////////////////////////////////////////////////////////////////////
// Return true iff self and other have identical sizes and pixels that
// are all approximately equal to relative accuracy epsilon, as
// understood by the GNU Scientific Library function gsl_fcmp.
gboolean
float_image_equals (FloatImage *self, FloatImage *other, float epsilon);
///////////////////////////////////////////////////////////////////////////////
//
// Manipulating Images
//
///////////////////////////////////////////////////////////////////////////////
// Flip an image about a horizontal line through the center of the image
void
float_image_flip_y(FloatImage *self);
// Flip an image about a vertical line through the center of the image
void
float_image_flip_x(FloatImage *self);
///////////////////////////////////////////////////////////////////////////////
//
// Storing Images in Files
//
///////////////////////////////////////////////////////////////////////////////
// Store instance self at position pointed to by file_pointer, for
// later retrieval using float_image_thaw. The serialized version of
// self is not portable between platforms.
void
float_image_freeze (FloatImage *self, FILE *file_pointer);
// Store image pixels in file. The image is stored in the usual
// order, i.e. contiguous rows of pixels in the x direction are stored
// contiguously in memory. Individual pixels are stored in byte order
// byte_order. Returns 0 on success, nonzero on error.
int
float_image_store (FloatImage *self, const char *file,
float_image_byte_order_t byte_order);
int
float_image_store_ext(FloatImage *self, const char *file,
float_image_byte_order_t byte_order, int append_flag);
int
float_image_band_store(FloatImage *self, const char *file,
meta_parameters *meta, int append_flag);
///////////////////////////////////////////////////////////////////////////////
//
// Exporting Images in Various Image File Formats
//
///////////////////////////////////////////////////////////////////////////////
// Export image to file as a gray scaled jpeg image, with largest
// dimension no larger than max_dimension. The max_dimension argument
// must be less than or equal to the largest dimension of the image.
// The image may be scaled st its largest dimension is considerably
// less than max_dimension. Scaling is performed by averaging blocks
// of pixels together, using odd pixel reflection around the image
// edges (see the description of the apply_kernel method). The JPEG
// format uses byte-valued gray scale samples, so the dynamic range of
// gray scale output pixels is limited to [0, 255]. Image pixel
// values inside two standard deviations of the mean pixel value are
// mapped linearly into this range; image pixel values outside two
// standard are clamped at the appropriate limit. In determining the
// image statistics (mean and standard deviation), values equal to mask
// are not considered, unless mask is NAN, in which case mask has no
// effect. If all image pixels have the same value, the output is
// made black if the pixels have value 0.0, and white otherwise. This
// routine slurps the whole image into memory, so beware. Returns 0
// on success, nonzero on error.
int
float_image_export_as_jpeg (FloatImage *self, const char *file,
size_t max_dimension, double mask);
// This method works like the export_as_jpeg method, but all values in
// the interval [interval_start, interval_end] are considered to be
// uninteresting low values which should be mapped to zero in the
// output image, and should not be included in the calculations which
// determine the image statistics used to map the other floating point
// values into bytes. For example, if one has an a bright island
// surrounded by very dark water in a radar image, setting the dark
// water covered areas to zero and not including them in the mean and
// standard deviation calculations will prevent the more interesting
// land areas from being driven into saturation in the generated
// image.
int
float_image_export_as_jpeg_with_mask_interval (FloatImage *self,
const char *file,
ssize_t max_dimension,
double interval_start,
double interval_end);
// Export image to file as a gray scaled tiff image, with largest
// dimension no larger than max_dimension. The max_dimension argument
// must be less than or equal to the largest dimension of the image.
// The image may be scaled st its largest dimension is considerably
// less than max_dimension. Scaling is performed by averaging blocks
// of pixels together, using odd pixel reflection around the image
// edges (see the description of the apply_kernel method). The TIFF
// format (here) uses byte-valued gray scale samples, so the dynamic range
// of gray scale output pixels is limited to [0, 255]. Image pixel
// values inside two standard deviations of the mean pixel value are
// mapped linearly into this range; image pixel values outside two
// standard are clamped at the appropriate limit. In determining the
// image statistics (mean and standard deviation), values equal to mask
// are not considered, unless mask is NAN, in which case mask has no
// effect. If all image pixels have the same value, the output is
// made black if the pixels have value 0.0, and white otherwise. This
// routine slurps the whole image into memory, so beware. Returns 0
// on success, nonzero on error.
int
float_image_export_as_tiff (FloatImage *self, const char *file,
size_t max_dimension, double mask);
// This method exports the float image data as an ascii CSV file.
// Don't use this method on large sections of data - it will give
// an assertion failure if either dimension is larger than 255.
int
float_image_export_as_csv (FloatImage *self, const char *file);
///////////////////////////////////////////////////////////////////////////////
//
// Controlling Image Data Caching
//
// It probably isn't necessary to use these methods. They are
// provided largely to make it clear how the cache works. The major
// tunable parameter is the size of the in-memory cache to use.
//
// When a new image is created, the following steps are performed:
//
// 1. The image is divided up into square tiles st two full rows
// or columns of tiles will fit in the memory cache.
//
// 2. A copy of the image is created on disk with the memory
// layout rearranged st individual tiles are contiguous in
// memory. This allows tiles to be quickly retrieved later.
//
// When a pixel is accessed (read or set), the following happens:
//
// 1. If the pixel is in a tile already loaded into the cache,
// it is simply fetched or set.
//
// 2. Otherwise, the tile containing the pixel is loaded,
// possibly displacing an already loaded tile, and then the
// pixel is fetched or set. The tile displaced is the one
// loaded longest ago (there is no most-recently-accessed
// heuristic, as this would make pixel access too slow).
//
// Thus, using a larger memory cache will result in larger tiles being
// used, and fewer tile loads being needed. In general, the default
// behavior is pretty good, but if you know will be performing lots of
// widely (but not too widely) scattered accesses, you might want to
// make it bigger.
//
///////////////////////////////////////////////////////////////////////////////
// Get the image memory cache size setting, in bytes. Note that this
// is the memory cache used per image, not the class-wide cache usage.
// If you will have a lot of objects instantiated simultaneously, you
// may find it necessary to use a smaller cache for each image.
size_t
float_image_get_cache_size (FloatImage *self);
// Set the image memory cache to size bytes. Changing the cache size
// requires the tiling to be recomputed, the on-disk tile cache to be
// regenerated, and the in memory cache to be flushed, so its slow.
void
float_image_set_cache_size (FloatImage *self, size_t size);
///////////////////////////////////////////////////////////////////////////////
//
// Reference Counting or Freeing Instances
//
///////////////////////////////////////////////////////////////////////////////
// Increment reference count. Return pointer to self for convenience.
FloatImage *
float_image_ref (FloatImage *self);
// Decrement reference count, freeing instance if count falls to 0.
void
float_image_unref (FloatImage *self);
// Destroy self, regardless of reference count.
void
float_image_free (FloatImage *self);
#endif // #ifndef FLOAT_IMAGE_H
| {
"alphanum_fraction": 0.691678273,
"avg_line_length": 43.7638095238,
"ext": "h",
"hexsha": "b08369e3ee844440f4c22d8ff8513f2d53b5bcb6",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_raster/float_image.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_raster/float_image.h",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_raster/float_image.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 4841,
"size": 22976
} |
/**
*
* @file core_sgemv.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @author Mathieu Faverge
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:49 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_sgemv performs one of the matrix-vector operations
*
* y := alpha*A*x + beta*y, or
* y := alpha*A**T*x + beta*y, or
* y := alpha*A**T*x + beta*y,
*
* where alpha and beta are scalars, x and y are vectors,
* and A is an m by n matrix.
*
*******************************************************************************
*
* @param[in] trans
* @arg PlasmaNoTrans: y := alpha*A*x + beta*y
* @arg PlasmaTrans: y := alpha*A**T*x + beta*y
* @arg PlasmaTrans: y := alpha*A**T*x + beta*y
*
* @param[in] m
* Number of rows of matrix A.
*
* @param[in] n
* Number of columns of matrix A.
*
* @param[in] alpha
* Scalar alpha.
*
* @param[in] A
* On entry, m by n matrix A. Dimension (lda,n).
*
* @param[in] lda
* Leading dimension of array A. lda >= max(1,m).
*
* @param[in] x
* On entry, vector x.
* If trans == PlasmaNoTrans, the n vector x has dimension 1 + (n-1)*abs(incx).
* Else, the m vector x has dimension 1 + (m-1)*abs(incx).
*
* @param[in] incx
* Increment between elements of x. incx must not be zero.
*
* @param[in] beta
* Scalar beta.
*
* @param[in,out] y
* On entry, vector y. On exit, y is overwritten by updated vector y.
* If trans == PlasmaNoTrans, the m vector y has dimension 1 + (m-1)*abs(incy).
* Else, the n vector y has dimension 1 + (n-1)*abs(incy).
*
* @param[in] incy
* Increment between elements of y. incy must not be zero.
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemv = PCORE_sgemv
#define CORE_sgemv PCORE_sgemv
#endif
void CORE_sgemv(PLASMA_enum trans,
int m, int n,
float alpha, const float *A, int lda,
const float *x, int incx,
float beta, float *y, int incy)
{
cblas_sgemv(
CblasColMajor,
(CBLAS_TRANSPOSE)trans,
m, n,
(alpha), A, lda,
x, incx,
(beta), y, incy );
}
| {
"alphanum_fraction": 0.5225755791,
"avg_line_length": 27.6847826087,
"ext": "c",
"hexsha": "6aca79493130697f30ba05a51929c4b225c2f41e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_sgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_sgemv.c",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_sgemv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 728,
"size": 2547
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.